blob: 0ae88044818f4d225d48b81463d7e15bd0b935d3 [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"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Lookup.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor28ad4b52009-05-26 20:50:29 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000020#include "clang/AST/ASTContext.h"
21#include "clang/AST/Expr.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000023#include "clang/Basic/LangOptions.h"
24
25using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000026using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000027
Douglas Gregor4ea568f2009-03-10 18:03:33 +000028//===----------------------------------------------------------------------===/
29// Template Instantiation Support
30//===----------------------------------------------------------------------===/
31
Douglas Gregor01afeef2009-08-28 20:31:08 +000032/// \brief Retrieve the template argument list(s) that should be used to
33/// instantiate the definition of the given declaration.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000034///
35/// \param D the declaration for which we are computing template instantiation
36/// arguments.
37///
38/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor8c702532010-02-05 07:33:43 +000039///
40/// \param RelativeToPrimary true if we should get the template
41/// arguments relative to the primary template, even when we're
42/// dealing with a specialization. This is only relevant for function
43/// template specializations.
Douglas Gregor1bd7a942010-05-03 23:29:10 +000044///
45/// \param Pattern If non-NULL, indicates the pattern from which we will be
46/// instantiating the definition of the given declaration, \p D. This is
47/// used to determine the proper set of template instantiation arguments for
48/// friend function template specializations.
Douglas Gregora654dd82009-08-28 17:37:35 +000049MultiLevelTemplateArgumentList
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000050Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000051 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000052 bool RelativeToPrimary,
53 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000054 // Accumulate the set of template argument lists in this structure.
55 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000056
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000057 if (Innermost)
58 Result.addOuterTemplateArguments(Innermost);
59
Douglas Gregora654dd82009-08-28 17:37:35 +000060 DeclContext *Ctx = dyn_cast<DeclContext>(D);
61 if (!Ctx)
62 Ctx = D->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +000063
John McCall970d5302009-08-29 03:16:09 +000064 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +000065 // Add template arguments from a class template instantiation.
Mike Stump11289f42009-09-09 15:08:12 +000066 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregora654dd82009-08-28 17:37:35 +000067 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
68 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +000069 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
70 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +000071 break;
Mike Stump11289f42009-09-09 15:08:12 +000072
Douglas Gregora654dd82009-08-28 17:37:35 +000073 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +000074
75 // If this class template specialization was instantiated from a
76 // specialized member that is a class template, we're done.
77 assert(Spec->getSpecializedTemplate() && "No class template?");
78 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
79 break;
Mike Stump11289f42009-09-09 15:08:12 +000080 }
Douglas Gregora654dd82009-08-28 17:37:35 +000081 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +000082 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +000083 if (!RelativeToPrimary &&
84 Function->getTemplateSpecializationKind()
85 == TSK_ExplicitSpecialization)
Douglas Gregorcf915552009-10-13 16:30:37 +000086 break;
87
Douglas Gregora654dd82009-08-28 17:37:35 +000088 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +000089 = Function->getTemplateSpecializationArgs()) {
90 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +000091 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +000092
Douglas Gregorcf915552009-10-13 16:30:37 +000093 // If this function was instantiated from a specialized member that is
94 // a function template, we're done.
95 assert(Function->getPrimaryTemplate() && "No function template?");
96 if (Function->getPrimaryTemplate()->isMemberSpecialization())
97 break;
98 }
99
John McCall970d5302009-08-29 03:16:09 +0000100 // If this is a friend declaration and it declares an entity at
101 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000102 // instead of its semantic parent, unless of course the pattern we're
103 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000104 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000105 Function->getDeclContext()->isFileContext() &&
106 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000107 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000108 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000109 continue;
110 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000111 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
112 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
113 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
114 const TemplateSpecializationType *TST
115 = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
116 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
117 if (ClassTemplate->isMemberSpecialization())
118 break;
119 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000120 }
John McCall970d5302009-08-29 03:16:09 +0000121
122 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000123 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000124 }
Mike Stump11289f42009-09-09 15:08:12 +0000125
Douglas Gregora654dd82009-08-28 17:37:35 +0000126 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000127}
128
Douglas Gregor84d49a22009-11-11 21:54:23 +0000129bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
130 switch (Kind) {
131 case TemplateInstantiation:
132 case DefaultTemplateArgumentInstantiation:
133 case DefaultFunctionArgumentInstantiation:
134 return true;
135
136 case ExplicitTemplateArgumentSubstitution:
137 case DeducedTemplateArgumentSubstitution:
138 case PriorTemplateArgumentSubstitution:
139 case DefaultTemplateArgumentChecking:
140 return false;
141 }
142
143 return true;
144}
145
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000146Sema::InstantiatingTemplate::
147InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregor85673582009-05-18 17:01:57 +0000148 Decl *Entity,
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000149 SourceRange InstantiationRange)
150 : SemaRef(SemaRef) {
Douglas Gregor79cf6032009-03-10 20:44:00 +0000151 Invalid = CheckInstantiationDepth(PointOfInstantiation,
152 InstantiationRange);
153 if (!Invalid) {
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000154 ActiveTemplateInstantiation Inst;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000155 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000156 Inst.PointOfInstantiation = PointOfInstantiation;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000157 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
Douglas Gregorc9220832009-03-12 18:36:18 +0000158 Inst.TemplateArgs = 0;
159 Inst.NumTemplateArgs = 0;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000160 Inst.InstantiationRange = InstantiationRange;
161 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor79cf6032009-03-10 20:44:00 +0000162 }
163}
164
Mike Stump11289f42009-09-09 15:08:12 +0000165Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000166 SourceLocation PointOfInstantiation,
167 TemplateDecl *Template,
168 const TemplateArgument *TemplateArgs,
169 unsigned NumTemplateArgs,
170 SourceRange InstantiationRange)
171 : SemaRef(SemaRef) {
172
173 Invalid = CheckInstantiationDepth(PointOfInstantiation,
174 InstantiationRange);
175 if (!Invalid) {
176 ActiveTemplateInstantiation Inst;
Mike Stump11289f42009-09-09 15:08:12 +0000177 Inst.Kind
Douglas Gregor79cf6032009-03-10 20:44:00 +0000178 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
179 Inst.PointOfInstantiation = PointOfInstantiation;
180 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
181 Inst.TemplateArgs = TemplateArgs;
182 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000183 Inst.InstantiationRange = InstantiationRange;
184 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000185 }
186}
187
Mike Stump11289f42009-09-09 15:08:12 +0000188Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor637d9982009-06-10 23:47:09 +0000189 SourceLocation PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000190 FunctionTemplateDecl *FunctionTemplate,
191 const TemplateArgument *TemplateArgs,
192 unsigned NumTemplateArgs,
193 ActiveTemplateInstantiation::InstantiationKind Kind,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000194 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000195 SourceRange InstantiationRange)
Nick Lewycky9331ed82010-11-20 01:29:55 +0000196 : SemaRef(SemaRef) {
Mike Stump11289f42009-09-09 15:08:12 +0000197
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000198 Invalid = CheckInstantiationDepth(PointOfInstantiation,
199 InstantiationRange);
200 if (!Invalid) {
201 ActiveTemplateInstantiation Inst;
202 Inst.Kind = Kind;
203 Inst.PointOfInstantiation = PointOfInstantiation;
204 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
205 Inst.TemplateArgs = TemplateArgs;
206 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000207 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000208 Inst.InstantiationRange = InstantiationRange;
209 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor84d49a22009-11-11 21:54:23 +0000210
211 if (!Inst.isInstantiationRecord())
212 ++SemaRef.NonInstantiationEntries;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000213 }
214}
215
Mike Stump11289f42009-09-09 15:08:12 +0000216Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000217 SourceLocation PointOfInstantiation,
Douglas Gregor637d9982009-06-10 23:47:09 +0000218 ClassTemplatePartialSpecializationDecl *PartialSpec,
219 const TemplateArgument *TemplateArgs,
220 unsigned NumTemplateArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000221 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregor637d9982009-06-10 23:47:09 +0000222 SourceRange InstantiationRange)
223 : SemaRef(SemaRef) {
224
Douglas Gregor84d49a22009-11-11 21:54:23 +0000225 Invalid = false;
226
227 ActiveTemplateInstantiation Inst;
228 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
229 Inst.PointOfInstantiation = PointOfInstantiation;
230 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
231 Inst.TemplateArgs = TemplateArgs;
232 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000233 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000234 Inst.InstantiationRange = InstantiationRange;
235 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
236
237 assert(!Inst.isInstantiationRecord());
238 ++SemaRef.NonInstantiationEntries;
Douglas Gregor637d9982009-06-10 23:47:09 +0000239}
240
Mike Stump11289f42009-09-09 15:08:12 +0000241Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000242 SourceLocation PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000243 ParmVarDecl *Param,
244 const TemplateArgument *TemplateArgs,
245 unsigned NumTemplateArgs,
246 SourceRange InstantiationRange)
247 : SemaRef(SemaRef) {
Mike Stump11289f42009-09-09 15:08:12 +0000248
Douglas Gregore62e6a02009-11-11 19:13:48 +0000249 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson657bad42009-09-05 05:14:19 +0000250
251 if (!Invalid) {
252 ActiveTemplateInstantiation Inst;
253 Inst.Kind
254 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregore62e6a02009-11-11 19:13:48 +0000255 Inst.PointOfInstantiation = PointOfInstantiation;
Anders Carlsson657bad42009-09-05 05:14:19 +0000256 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
257 Inst.TemplateArgs = TemplateArgs;
258 Inst.NumTemplateArgs = NumTemplateArgs;
259 Inst.InstantiationRange = InstantiationRange;
260 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000261 }
262}
263
264Sema::InstantiatingTemplate::
265InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorca4686d2011-01-04 23:35:54 +0000266 NamedDecl *Template,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000267 NonTypeTemplateParmDecl *Param,
268 const TemplateArgument *TemplateArgs,
269 unsigned NumTemplateArgs,
270 SourceRange InstantiationRange) : SemaRef(SemaRef) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000271 Invalid = false;
Douglas Gregore62e6a02009-11-11 19:13:48 +0000272
Douglas Gregor84d49a22009-11-11 21:54:23 +0000273 ActiveTemplateInstantiation Inst;
274 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
275 Inst.PointOfInstantiation = PointOfInstantiation;
276 Inst.Template = Template;
277 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
278 Inst.TemplateArgs = TemplateArgs;
279 Inst.NumTemplateArgs = NumTemplateArgs;
280 Inst.InstantiationRange = InstantiationRange;
281 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
282
283 assert(!Inst.isInstantiationRecord());
284 ++SemaRef.NonInstantiationEntries;
Douglas Gregore62e6a02009-11-11 19:13:48 +0000285}
286
287Sema::InstantiatingTemplate::
288InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorca4686d2011-01-04 23:35:54 +0000289 NamedDecl *Template,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000290 TemplateTemplateParmDecl *Param,
291 const TemplateArgument *TemplateArgs,
292 unsigned NumTemplateArgs,
293 SourceRange InstantiationRange) : SemaRef(SemaRef) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000294 Invalid = false;
295 ActiveTemplateInstantiation Inst;
296 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
297 Inst.PointOfInstantiation = PointOfInstantiation;
298 Inst.Template = Template;
299 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
300 Inst.TemplateArgs = TemplateArgs;
301 Inst.NumTemplateArgs = NumTemplateArgs;
302 Inst.InstantiationRange = InstantiationRange;
303 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000304
Douglas Gregor84d49a22009-11-11 21:54:23 +0000305 assert(!Inst.isInstantiationRecord());
306 ++SemaRef.NonInstantiationEntries;
307}
308
309Sema::InstantiatingTemplate::
310InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
311 TemplateDecl *Template,
312 NamedDecl *Param,
313 const TemplateArgument *TemplateArgs,
314 unsigned NumTemplateArgs,
315 SourceRange InstantiationRange) : SemaRef(SemaRef) {
316 Invalid = false;
317
318 ActiveTemplateInstantiation Inst;
319 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
320 Inst.PointOfInstantiation = PointOfInstantiation;
321 Inst.Template = Template;
322 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
323 Inst.TemplateArgs = TemplateArgs;
324 Inst.NumTemplateArgs = NumTemplateArgs;
325 Inst.InstantiationRange = InstantiationRange;
326 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
327
328 assert(!Inst.isInstantiationRecord());
329 ++SemaRef.NonInstantiationEntries;
Anders Carlsson657bad42009-09-05 05:14:19 +0000330}
331
Douglas Gregor85673582009-05-18 17:01:57 +0000332void Sema::InstantiatingTemplate::Clear() {
333 if (!Invalid) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000334 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
335 assert(SemaRef.NonInstantiationEntries > 0);
336 --SemaRef.NonInstantiationEntries;
337 }
338
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000339 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregor85673582009-05-18 17:01:57 +0000340 Invalid = true;
341 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000342}
343
Douglas Gregor79cf6032009-03-10 20:44:00 +0000344bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
345 SourceLocation PointOfInstantiation,
346 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000347 assert(SemaRef.NonInstantiationEntries <=
348 SemaRef.ActiveTemplateInstantiations.size());
349 if ((SemaRef.ActiveTemplateInstantiations.size() -
350 SemaRef.NonInstantiationEntries)
351 <= SemaRef.getLangOptions().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000352 return false;
353
Mike Stump11289f42009-09-09 15:08:12 +0000354 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000355 diag::err_template_recursion_depth_exceeded)
356 << SemaRef.getLangOptions().InstantiationDepth
357 << InstantiationRange;
358 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
359 << SemaRef.getLangOptions().InstantiationDepth;
360 return true;
361}
362
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000363/// \brief Prints the current instantiation stack through a series of
364/// notes.
365void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000366 // Determine which template instantiations to skip, if any.
367 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
368 unsigned Limit = Diags.getTemplateBacktraceLimit();
369 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
370 SkipStart = Limit / 2 + Limit % 2;
371 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
372 }
373
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000374 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000375 unsigned InstantiationIdx = 0;
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000376 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
377 Active = ActiveTemplateInstantiations.rbegin(),
378 ActiveEnd = ActiveTemplateInstantiations.rend();
379 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000380 ++Active, ++InstantiationIdx) {
381 // Skip this instantiation?
382 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
383 if (InstantiationIdx == SkipStart) {
384 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000385 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000386 diag::note_instantiation_contexts_suppressed)
387 << unsigned(ActiveTemplateInstantiations.size() - Limit);
388 }
389 continue;
390 }
391
Douglas Gregor79cf6032009-03-10 20:44:00 +0000392 switch (Active->Kind) {
393 case ActiveTemplateInstantiation::TemplateInstantiation: {
Douglas Gregor85673582009-05-18 17:01:57 +0000394 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
395 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
396 unsigned DiagID = diag::note_template_member_class_here;
397 if (isa<ClassTemplateSpecializationDecl>(Record))
398 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000399 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000400 << Context.getTypeDeclType(Record)
401 << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000402 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000403 unsigned DiagID;
404 if (Function->getPrimaryTemplate())
405 DiagID = diag::note_function_template_spec_here;
406 else
407 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000408 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000409 << Function
410 << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000411 } else {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000412 Diags.Report(Active->PointOfInstantiation,
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000413 diag::note_template_static_data_member_def_here)
414 << cast<VarDecl>(D)
415 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000416 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000417 break;
418 }
419
420 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
421 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
422 std::string TemplateArgsStr
Douglas Gregordc572a32009-03-30 22:58:21 +0000423 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump11289f42009-09-09 15:08:12 +0000424 Active->TemplateArgs,
Douglas Gregor7de59662009-05-29 20:38:28 +0000425 Active->NumTemplateArgs,
426 Context.PrintingPolicy);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000427 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000428 diag::note_default_arg_instantiation_here)
429 << (Template->getNameAsString() + TemplateArgsStr)
430 << Active->InstantiationRange;
431 break;
432 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000433
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000434 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Mike Stump11289f42009-09-09 15:08:12 +0000435 FunctionTemplateDecl *FnTmpl
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000436 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000437 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000438 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000439 << FnTmpl
440 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
441 Active->TemplateArgs,
442 Active->NumTemplateArgs)
443 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000444 break;
445 }
Mike Stump11289f42009-09-09 15:08:12 +0000446
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000447 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
448 if (ClassTemplatePartialSpecializationDecl *PartialSpec
449 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
450 (Decl *)Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000451 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000452 diag::note_partial_spec_deduct_instantiation_here)
453 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor607f1412010-03-30 20:35:20 +0000454 << getTemplateArgumentBindingsText(
455 PartialSpec->getTemplateParameters(),
456 Active->TemplateArgs,
457 Active->NumTemplateArgs)
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000458 << Active->InstantiationRange;
459 } else {
460 FunctionTemplateDecl *FnTmpl
461 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000462 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000463 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000464 << FnTmpl
465 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
466 Active->TemplateArgs,
467 Active->NumTemplateArgs)
468 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000469 }
470 break;
Douglas Gregor637d9982009-06-10 23:47:09 +0000471
Anders Carlsson657bad42009-09-05 05:14:19 +0000472 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
473 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
474 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000475
Anders Carlsson657bad42009-09-05 05:14:19 +0000476 std::string TemplateArgsStr
477 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump11289f42009-09-09 15:08:12 +0000478 Active->TemplateArgs,
Anders Carlsson657bad42009-09-05 05:14:19 +0000479 Active->NumTemplateArgs,
480 Context.PrintingPolicy);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000481 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000482 diag::note_default_function_arg_instantiation_here)
Anders Carlssondc6d2c32009-09-05 05:38:54 +0000483 << (FD->getNameAsString() + TemplateArgsStr)
Anders Carlsson657bad42009-09-05 05:14:19 +0000484 << Active->InstantiationRange;
485 break;
486 }
Mike Stump11289f42009-09-09 15:08:12 +0000487
Douglas Gregore62e6a02009-11-11 19:13:48 +0000488 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
489 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
490 std::string Name;
491 if (!Parm->getName().empty())
492 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregorca4686d2011-01-04 23:35:54 +0000493
494 TemplateParameterList *TemplateParams = 0;
495 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
496 TemplateParams = Template->getTemplateParameters();
497 else
498 TemplateParams =
499 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
500 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000501 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000502 diag::note_prior_template_arg_substitution)
503 << isa<TemplateTemplateParmDecl>(Parm)
504 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000505 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000506 Active->TemplateArgs,
507 Active->NumTemplateArgs)
508 << Active->InstantiationRange;
509 break;
510 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000511
512 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregorca4686d2011-01-04 23:35:54 +0000513 TemplateParameterList *TemplateParams = 0;
514 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
515 TemplateParams = Template->getTemplateParameters();
516 else
517 TemplateParams =
518 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
519 ->getTemplateParameters();
520
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000521 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000522 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000523 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000524 Active->TemplateArgs,
525 Active->NumTemplateArgs)
526 << Active->InstantiationRange;
527 break;
528 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000529 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000530 }
531}
532
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000533TemplateDeductionInfo *Sema::isSFINAEContext() const {
Douglas Gregor33834512009-06-14 07:33:30 +0000534 using llvm::SmallVector;
535 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
536 Active = ActiveTemplateInstantiations.rbegin(),
537 ActiveEnd = ActiveTemplateInstantiations.rend();
538 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000539 ++Active)
540 {
Douglas Gregor33834512009-06-14 07:33:30 +0000541 switch(Active->Kind) {
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000542 case ActiveTemplateInstantiation::TemplateInstantiation:
Anders Carlsson657bad42009-09-05 05:14:19 +0000543 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000544 // This is a template instantiation, so there is no SFINAE.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000545 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000546
Douglas Gregor33834512009-06-14 07:33:30 +0000547 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000548 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000549 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000550 // A default template argument instantiation and substitution into
551 // template parameters with arguments for prior parameters may or may
552 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000553 break;
Mike Stump11289f42009-09-09 15:08:12 +0000554
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000555 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
556 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
557 // We're either substitution explicitly-specified template arguments
558 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000559 assert(Active->DeductionInfo && "Missing deduction info pointer");
560 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000561 }
562 }
563
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000564 return 0;
Douglas Gregor33834512009-06-14 07:33:30 +0000565}
566
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000567/// \brief Retrieve the depth and index of a parameter pack.
568static std::pair<unsigned, unsigned>
569getDepthAndIndex(NamedDecl *ND) {
570 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
571 return std::make_pair(TTP->getDepth(), TTP->getIndex());
572
573 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
574 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
575
576 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
577 return std::make_pair(TTP->getDepth(), TTP->getIndex());
578}
579
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000580//===----------------------------------------------------------------------===/
581// Template Instantiation for Types
582//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000583namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000584 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000585 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000586 SourceLocation Loc;
587 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000588
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000589 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000590 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000591
592 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000593 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000594 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000595 DeclarationName Entity)
596 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000597 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000598
Mike Stump11289f42009-09-09 15:08:12 +0000599 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000600 /// transformed.
601 ///
602 /// For the purposes of template instantiation, a type has already been
603 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000604 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000605
Douglas Gregord6ff3322009-08-04 16:50:30 +0000606 /// \brief Returns the location of the entity being instantiated, if known.
607 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000608
Douglas Gregord6ff3322009-08-04 16:50:30 +0000609 /// \brief Returns the name of the entity being instantiated, if any.
610 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000611
Douglas Gregoref6ab412009-10-27 06:26:26 +0000612 /// \brief Sets the "base" location and entity when that
613 /// information is known based on another transformation.
614 void setBase(SourceLocation Loc, DeclarationName Entity) {
615 this->Loc = Loc;
616 this->Entity = Entity;
617 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000618
619 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
620 SourceRange PatternRange,
621 const UnexpandedParameterPack *Unexpanded,
622 unsigned NumUnexpanded,
623 bool &ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000624 bool &RetainExpansion,
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000625 llvm::Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000626 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
627 PatternRange, Unexpanded,
628 NumUnexpanded,
629 TemplateArgs,
630 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000631 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000632 NumExpansions);
633 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000634
Douglas Gregorf3010112011-01-07 16:43:16 +0000635 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
636 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
637 }
638
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000639 TemplateArgument ForgetPartiallySubstitutedPack() {
640 TemplateArgument Result;
641 if (NamedDecl *PartialPack
642 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
643 MultiLevelTemplateArgumentList &TemplateArgs
644 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
645 unsigned Depth, Index;
646 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
647 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
648 Result = TemplateArgs(Depth, Index);
649 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
650 }
651 }
652
653 return Result;
654 }
655
656 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
657 if (Arg.isNull())
658 return;
659
660 if (NamedDecl *PartialPack
661 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
662 MultiLevelTemplateArgumentList &TemplateArgs
663 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
664 unsigned Depth, Index;
665 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
666 TemplateArgs.setArgument(Depth, Index, Arg);
667 }
668 }
669
Douglas Gregord6ff3322009-08-04 16:50:30 +0000670 /// \brief Transform the given declaration by instantiating a reference to
671 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000672 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000673
Mike Stump11289f42009-09-09 15:08:12 +0000674 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000675 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000676 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000677
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000678 /// \bried Transform the first qualifier within a scope by instantiating the
679 /// declaration.
680 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
681
Douglas Gregorebe10102009-08-20 07:17:43 +0000682 /// \brief Rebuild the exception declaration and register the declaration
683 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000684 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000685 TypeSourceInfo *Declarator,
Douglas Gregorebe10102009-08-20 07:17:43 +0000686 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000687 SourceLocation Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000688
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000689 /// \brief Rebuild the Objective-C exception declaration and register the
690 /// declaration as an instantiated local.
691 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
692 TypeSourceInfo *TSInfo, QualType T);
693
John McCall7f41d982009-09-11 04:59:25 +0000694 /// \brief Check for tag mismatches when instantiating an
695 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000696 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
697 ElaboratedTypeKeyword Keyword,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000698 NestedNameSpecifier *NNS, QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000699
Douglas Gregor5590be02011-01-15 06:45:20 +0000700 TemplateName TransformTemplateName(TemplateName Name,
701 QualType ObjectType = QualType(),
702 NamedDecl *FirstQualifierInScope = 0);
703
John McCalldadc5752010-08-24 06:29:42 +0000704 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
705 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
706 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
707 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000708 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000709 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
710 SubstNonTypeTemplateParmPackExpr *E);
711
Douglas Gregor14cf7522010-04-30 18:55:50 +0000712 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000713 FunctionProtoTypeLoc TL);
Douglas Gregor715e4612011-01-14 22:40:04 +0000714 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
715 llvm::Optional<unsigned> NumExpansions);
John McCall58f10c32010-03-11 09:03:00 +0000716
Mike Stump11289f42009-09-09 15:08:12 +0000717 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000718 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000719 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000720 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000721
Douglas Gregorada4b792011-01-14 02:55:32 +0000722 /// \brief Transforms an already-substituted template type parameter pack
723 /// into either itself (if we aren't substituting into its pack expansion)
724 /// or the appropriate substituted argument.
725 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
726 SubstTemplateTypeParmPackTypeLoc TL);
727
John McCalldadc5752010-08-24 06:29:42 +0000728 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000729 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCalldadc5752010-08-24 06:29:42 +0000730 ExprResult Result =
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000731 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
732 getSema().CallsUndergoingInstantiation.pop_back();
733 return move(Result);
734 }
Douglas Gregord6ff3322009-08-04 16:50:30 +0000735 };
Douglas Gregor04318252009-07-06 15:59:29 +0000736}
737
Douglas Gregor5597ab42010-05-07 23:12:07 +0000738bool TemplateInstantiator::AlreadyTransformed(QualType T) {
739 if (T.isNull())
740 return true;
741
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000742 if (T->isDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000743 return false;
744
745 getSema().MarkDeclarationsReferencedInType(Loc, T);
746 return true;
747}
748
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000749Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000750 if (!D)
751 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000752
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000753 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000754 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000755 // If the corresponding template argument is NULL or non-existent, it's
756 // because we are performing instantiation from explicitly-specified
757 // template arguments in a function template, but there were some
758 // arguments left unspecified.
759 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
760 TTP->getPosition()))
761 return D;
762
Douglas Gregorf5500772011-01-05 15:48:55 +0000763 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
764
765 if (TTP->isParameterPack()) {
766 assert(Arg.getKind() == TemplateArgument::Pack &&
767 "Missing argument pack");
768
Douglas Gregor5590be02011-01-15 06:45:20 +0000769 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000770 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregorf5500772011-01-05 15:48:55 +0000771 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
772 }
773
774 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000775 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000776 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000777 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000778 }
Mike Stump11289f42009-09-09 15:08:12 +0000779
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000780 // Fall through to find the instantiated declaration for this template
781 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000782 }
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000784 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000785}
786
Douglas Gregor25289362010-03-01 17:25:41 +0000787Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000788 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000789 if (!Inst)
790 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000791
Douglas Gregorebe10102009-08-20 07:17:43 +0000792 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
793 return Inst;
794}
795
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000796NamedDecl *
797TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
798 SourceLocation Loc) {
799 // If the first part of the nested-name-specifier was a template type
800 // parameter, instantiate that type parameter down to a tag type.
801 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
802 const TemplateTypeParmType *TTP
803 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000804
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000805 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000806 // FIXME: This needs testing w/ member access expressions.
807 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
808
809 if (TTP->isParameterPack()) {
810 assert(Arg.getKind() == TemplateArgument::Pack &&
811 "Missing argument pack");
812
Douglas Gregore1d60df2011-01-14 23:41:42 +0000813 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000814 return 0;
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000815
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000816 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000817 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
818 }
819
820 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000821 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000822 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000823
824 if (const TagType *Tag = T->getAs<TagType>())
825 return Tag->getDecl();
826
827 // The resulting type is not a tag; complain.
828 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
829 return 0;
830 }
831 }
832
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000833 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000834}
835
Douglas Gregorebe10102009-08-20 07:17:43 +0000836VarDecl *
837TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000838 TypeSourceInfo *Declarator,
Douglas Gregorebe10102009-08-20 07:17:43 +0000839 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000840 SourceLocation Loc) {
841 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
842 Name, Loc);
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000843 if (Var)
844 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
845 return Var;
846}
847
848VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
849 TypeSourceInfo *TSInfo,
850 QualType T) {
851 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
852 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +0000853 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
854 return Var;
855}
856
John McCall7f41d982009-09-11 04:59:25 +0000857QualType
John McCall954b5de2010-11-04 19:04:38 +0000858TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
859 ElaboratedTypeKeyword Keyword,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000860 NestedNameSpecifier *NNS,
861 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +0000862 if (const TagType *TT = T->getAs<TagType>()) {
863 TagDecl* TD = TT->getDecl();
864
John McCall954b5de2010-11-04 19:04:38 +0000865 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +0000866
867 // FIXME: type might be anonymous.
868 IdentifierInfo *Id = TD->getIdentifier();
869
870 // TODO: should we even warn on struct/class mismatches for this? Seems
871 // like it's likely to produce a lot of spurious errors.
Abramo Bagnara6150c882010-05-11 21:36:43 +0000872 if (Keyword != ETK_None && Keyword != ETK_Typename) {
873 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
874 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, TagLocation, *Id)) {
875 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
876 << Id
877 << FixItHint::CreateReplacement(SourceRange(TagLocation),
878 TD->getKindName());
879 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
880 }
John McCall7f41d982009-09-11 04:59:25 +0000881 }
882 }
883
John McCall954b5de2010-11-04 19:04:38 +0000884 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
885 Keyword,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000886 NNS, T);
John McCall7f41d982009-09-11 04:59:25 +0000887}
888
Douglas Gregor5590be02011-01-15 06:45:20 +0000889TemplateName TemplateInstantiator::TransformTemplateName(TemplateName Name,
890 QualType ObjectType,
891 NamedDecl *FirstQualifierInScope) {
892 if (TemplateTemplateParmDecl *TTP
893 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
894 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
895 // If the corresponding template argument is NULL or non-existent, it's
896 // because we are performing instantiation from explicitly-specified
897 // template arguments in a function template, but there were some
898 // arguments left unspecified.
899 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
900 TTP->getPosition()))
901 return Name;
902
903 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
904
905 if (TTP->isParameterPack()) {
906 assert(Arg.getKind() == TemplateArgument::Pack &&
907 "Missing argument pack");
908
909 if (getSema().ArgumentPackSubstitutionIndex == -1) {
910 // We have the template argument pack to substitute, but we're not
911 // actually expanding the enclosing pack expansion yet. So, just
912 // keep the entire argument pack.
913 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
914 }
915
916 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
917 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
918 }
919
920 TemplateName Template = Arg.getAsTemplate();
921 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
922 "Wrong kind of template template argument");
923 return Template;
924 }
925 }
926
927 if (SubstTemplateTemplateParmPackStorage *SubstPack
928 = Name.getAsSubstTemplateTemplateParmPack()) {
929 if (getSema().ArgumentPackSubstitutionIndex == -1)
930 return Name;
931
932 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
933 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
934 "Pack substitution index out-of-range");
935 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
936 .getAsTemplate();
937 }
938
939 return inherited::TransformTemplateName(Name, ObjectType,
940 FirstQualifierInScope);
941}
942
John McCalldadc5752010-08-24 06:29:42 +0000943ExprResult
John McCall47f29ea2009-12-08 09:21:05 +0000944TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +0000945 if (!E->isTypeDependent())
John McCallc3007a22010-10-26 07:05:15 +0000946 return SemaRef.Owned(E);
Anders Carlsson0b209a82009-09-11 01:22:35 +0000947
948 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
949 assert(currentDecl && "Must have current function declaration when "
950 "instantiating.");
951
952 PredefinedExpr::IdentType IT = E->getIdentType();
953
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000954 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Anders Carlsson0b209a82009-09-11 01:22:35 +0000955
956 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +0000957 QualType ResTy = getSema().Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +0000958 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
959 ArrayType::Normal, 0);
960 PredefinedExpr *PE =
961 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
962 return getSema().Owned(PE);
963}
964
John McCalldadc5752010-08-24 06:29:42 +0000965ExprResult
John McCall13481c52010-02-06 08:42:39 +0000966TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +0000967 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +0000968 // 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(NTTP->getDepth(),
973 NTTP->getPosition()))
John McCallc3007a22010-10-26 07:05:15 +0000974 return SemaRef.Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +0000975
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000976 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
977 if (NTTP->isParameterPack()) {
978 assert(Arg.getKind() == TemplateArgument::Pack &&
979 "Missing argument pack");
980
981 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000982 // We have an argument pack, but we can't select a particular argument
983 // out of it yet. Therefore, we'll build an expression to hold on to that
984 // argument pack.
985 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
986 E->getLocation(),
987 NTTP->getDeclName());
988 if (TargetType.isNull())
989 return ExprError();
990
991 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
992 NTTP,
993 E->getLocation(),
994 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000995 }
996
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000997 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000998 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
999 }
Mike Stump11289f42009-09-09 15:08:12 +00001000
John McCall13481c52010-02-06 08:42:39 +00001001 // The template argument itself might be an expression, in which
1002 // case we just return that expression.
1003 if (Arg.getKind() == TemplateArgument::Expression)
John McCallc3007a22010-10-26 07:05:15 +00001004 return SemaRef.Owned(Arg.getAsExpr());
Mike Stump11289f42009-09-09 15:08:12 +00001005
John McCall13481c52010-02-06 08:42:39 +00001006 if (Arg.getKind() == TemplateArgument::Declaration) {
1007 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001008
John McCall15dda372010-02-06 10:23:53 +00001009 // Find the instantiation of the template argument. This is
1010 // required for nested templates.
John McCall13481c52010-02-06 08:42:39 +00001011 VD = cast_or_null<ValueDecl>(
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001012 getSema().FindInstantiatedDecl(E->getLocation(),
1013 VD, TemplateArgs));
John McCall13481c52010-02-06 08:42:39 +00001014 if (!VD)
John McCallfaf5fb42010-08-26 23:41:50 +00001015 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001016
John McCall15dda372010-02-06 10:23:53 +00001017 // Derive the type we want the substituted decl to have. This had
1018 // better be non-dependent, or these checks will have serious problems.
1019 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001020 E->getLocation(),
1021 DeclarationName());
John McCall15dda372010-02-06 10:23:53 +00001022 assert(!TargetType.isNull() && "type substitution failed for param type");
1023 assert(!TargetType->isDependentType() && "param type still dependent");
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001024 return SemaRef.BuildExpressionFromDeclTemplateArgument(Arg,
1025 TargetType,
1026 E->getLocation());
John McCall13481c52010-02-06 08:42:39 +00001027 }
1028
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001029 return SemaRef.BuildExpressionFromIntegralTemplateArgument(Arg,
1030 E->getSourceRange().getBegin());
John McCall13481c52010-02-06 08:42:39 +00001031}
1032
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001033ExprResult
1034TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1035 SubstNonTypeTemplateParmPackExpr *E) {
1036 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1037 // We aren't expanding the parameter pack, so just return ourselves.
1038 return getSema().Owned(E);
1039 }
1040
1041 // FIXME: Variadic templates select Nth from type?
1042 const TemplateArgument &ArgPack = E->getArgumentPack();
1043 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1044 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1045
1046 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
1047 if (Arg.getKind() == TemplateArgument::Expression)
1048 return SemaRef.Owned(Arg.getAsExpr());
1049
1050 if (Arg.getKind() == TemplateArgument::Declaration) {
1051 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
1052
1053 // Find the instantiation of the template argument. This is
1054 // required for nested templates.
1055 VD = cast_or_null<ValueDecl>(
1056 getSema().FindInstantiatedDecl(E->getParameterPackLocation(),
1057 VD, TemplateArgs));
1058 if (!VD)
1059 return ExprError();
1060
1061 return SemaRef.BuildExpressionFromDeclTemplateArgument(Arg,
1062 E->getType(),
1063 E->getParameterPackLocation());
1064 }
1065
1066 return SemaRef.BuildExpressionFromIntegralTemplateArgument(Arg,
1067 E->getParameterPackLocation());
1068}
John McCall13481c52010-02-06 08:42:39 +00001069
John McCalldadc5752010-08-24 06:29:42 +00001070ExprResult
John McCall13481c52010-02-06 08:42:39 +00001071TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1072 NamedDecl *D = E->getDecl();
1073 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1074 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1075 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001076
1077 // We have a non-type template parameter that isn't fully substituted;
1078 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001079 }
Mike Stump11289f42009-09-09 15:08:12 +00001080
John McCall47f29ea2009-12-08 09:21:05 +00001081 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001082}
1083
John McCalldadc5752010-08-24 06:29:42 +00001084ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001085 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001086 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1087 getDescribedFunctionTemplate() &&
1088 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001089 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1090 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1091 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001092}
1093
Douglas Gregor14cf7522010-04-30 18:55:50 +00001094QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001095 FunctionProtoTypeLoc TL) {
Douglas Gregor14cf7522010-04-30 18:55:50 +00001096 // We need a local instantiation scope for this function prototype.
John McCall19c1bfd2010-08-25 05:32:35 +00001097 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall31f82722010-11-12 08:19:04 +00001098 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall58f10c32010-03-11 09:03:00 +00001099}
1100
1101ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001102TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1103 llvm::Optional<unsigned> NumExpansions) {
1104 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs,
1105 NumExpansions);
John McCall58f10c32010-03-11 09:03:00 +00001106}
1107
Mike Stump11289f42009-09-09 15:08:12 +00001108QualType
John McCall550e0c22009-10-21 00:40:46 +00001109TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001110 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001111 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001112 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001113 // Replace the template type parameter with its corresponding
1114 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001115
1116 // If the corresponding template argument is NULL or doesn't exist, it's
1117 // because we are performing instantiation from explicitly-specified
1118 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001119 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001120 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1121 TemplateTypeParmTypeLoc NewTL
1122 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1123 NewTL.setNameLoc(TL.getNameLoc());
1124 return TL.getType();
1125 }
Mike Stump11289f42009-09-09 15:08:12 +00001126
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001127 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1128
1129 if (T->isParameterPack()) {
1130 assert(Arg.getKind() == TemplateArgument::Pack &&
1131 "Missing argument pack");
1132
1133 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001134 // We have the template argument pack, but we're not expanding the
1135 // enclosing pack expansion yet. Just save the template argument
1136 // pack for later substitution.
1137 QualType Result
1138 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1139 SubstTemplateTypeParmPackTypeLoc NewTL
1140 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1141 NewTL.setNameLoc(TL.getNameLoc());
1142 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001143 }
1144
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001145 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001146 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1147 }
1148
1149 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001150 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001151
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001152 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001153
1154 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001155 QualType Result
1156 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1157 SubstTemplateTypeParmTypeLoc NewTL
1158 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1159 NewTL.setNameLoc(TL.getNameLoc());
1160 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001161 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001162
1163 // The template type parameter comes from an inner template (e.g.,
1164 // the template parameter list of a member template inside the
1165 // template we are instantiating). Create a new template type
1166 // parameter with the template "level" reduced by one.
John McCall550e0c22009-10-21 00:40:46 +00001167 QualType Result
1168 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1169 - TemplateArgs.getNumLevels(),
1170 T->getIndex(),
1171 T->isParameterPack(),
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001172 T->getName());
John McCall550e0c22009-10-21 00:40:46 +00001173 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1174 NewTL.setNameLoc(TL.getNameLoc());
1175 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001176}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001177
Douglas Gregorada4b792011-01-14 02:55:32 +00001178QualType
1179TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1180 TypeLocBuilder &TLB,
1181 SubstTemplateTypeParmPackTypeLoc TL) {
1182 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1183 // We aren't expanding the parameter pack, so just return ourselves.
1184 SubstTemplateTypeParmPackTypeLoc NewTL
1185 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1186 NewTL.setNameLoc(TL.getNameLoc());
1187 return TL.getType();
1188 }
1189
1190 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1191 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1192 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1193
1194 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1195 Result = getSema().Context.getSubstTemplateTypeParmType(
1196 TL.getTypePtr()->getReplacedParameter(),
1197 Result);
1198 SubstTemplateTypeParmTypeLoc NewTL
1199 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1200 NewTL.setNameLoc(TL.getNameLoc());
1201 return Result;
1202}
1203
John McCall76d824f2009-08-25 22:02:44 +00001204/// \brief Perform substitution on the type T with a given set of template
1205/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001206///
1207/// This routine substitutes the given template arguments into the
1208/// type T and produces the instantiated type.
1209///
1210/// \param T the type into which the template arguments will be
1211/// substituted. If this type is not dependent, it will be returned
1212/// immediately.
1213///
1214/// \param TemplateArgs the template arguments that will be
1215/// substituted for the top-level template parameters within T.
1216///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001217/// \param Loc the location in the source code where this substitution
1218/// is being performed. It will typically be the location of the
1219/// declarator (if we're instantiating the type of some declaration)
1220/// or the location of the type in the source code (if, e.g., we're
1221/// instantiating the type of a cast expression).
1222///
1223/// \param Entity the name of the entity associated with a declaration
1224/// being instantiated (if any). May be empty to indicate that there
1225/// is no such entity (if, e.g., this is a type that occurs as part of
1226/// a cast expression) or that the entity has no name (e.g., an
1227/// unnamed function parameter).
1228///
1229/// \returns If the instantiation succeeds, the instantiated
1230/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001231TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001232 const MultiLevelTemplateArgumentList &Args,
1233 SourceLocation Loc,
1234 DeclarationName Entity) {
1235 assert(!ActiveTemplateInstantiations.empty() &&
1236 "Cannot perform an instantiation without some context on the "
1237 "instantiation stack");
1238
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001239 if (!T->getType()->isDependentType() &&
1240 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001241 return T;
1242
1243 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1244 return Instantiator.TransformType(T);
1245}
1246
Douglas Gregor5499af42011-01-05 23:12:31 +00001247TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1248 const MultiLevelTemplateArgumentList &Args,
1249 SourceLocation Loc,
1250 DeclarationName Entity) {
1251 assert(!ActiveTemplateInstantiations.empty() &&
1252 "Cannot perform an instantiation without some context on the "
1253 "instantiation stack");
1254
1255 if (TL.getType().isNull())
1256 return 0;
1257
1258 if (!TL.getType()->isDependentType() &&
1259 !TL.getType()->isVariablyModifiedType()) {
1260 // FIXME: Make a copy of the TypeLoc data here, so that we can
1261 // return a new TypeSourceInfo. Inefficient!
1262 TypeLocBuilder TLB;
1263 TLB.pushFullCopy(TL);
1264 return TLB.getTypeSourceInfo(Context, TL.getType());
1265 }
1266
1267 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1268 TypeLocBuilder TLB;
1269 TLB.reserve(TL.getFullDataSize());
1270 QualType Result = Instantiator.TransformType(TLB, TL);
1271 if (Result.isNull())
1272 return 0;
1273
1274 return TLB.getTypeSourceInfo(Context, Result);
1275}
1276
John McCall609459e2009-10-21 00:58:09 +00001277/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001278QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001279 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001280 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor79cf6032009-03-10 20:44:00 +00001281 assert(!ActiveTemplateInstantiations.empty() &&
1282 "Cannot perform an instantiation without some context on the "
1283 "instantiation stack");
1284
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001285 // If T is not a dependent type or a variably-modified type, there
1286 // is nothing to do.
1287 if (!T->isDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001288 return T;
1289
Douglas Gregord6ff3322009-08-04 16:50:30 +00001290 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1291 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001292}
Douglas Gregor463421d2009-03-03 04:44:36 +00001293
John McCallb29f78f2010-04-09 17:38:44 +00001294static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001295 if (T->getType()->isDependentType() || T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001296 return true;
1297
Abramo Bagnara6d810632010-12-14 22:11:44 +00001298 TypeLoc TL = T->getTypeLoc().IgnoreParens();
John McCallb29f78f2010-04-09 17:38:44 +00001299 if (!isa<FunctionProtoTypeLoc>(TL))
1300 return false;
1301
1302 FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL);
1303 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1304 ParmVarDecl *P = FP.getArg(I);
1305
1306 // TODO: currently we always rebuild expressions. When we
1307 // properly get lazier about this, we should use the same
1308 // logic to avoid rebuilding prototypes here.
Douglas Gregor9cc278222011-01-05 21:14:17 +00001309 if (P->hasDefaultArg())
John McCallb29f78f2010-04-09 17:38:44 +00001310 return true;
1311 }
1312
1313 return false;
1314}
1315
1316/// A form of SubstType intended specifically for instantiating the
1317/// type of a FunctionDecl. Its purpose is solely to force the
1318/// instantiation of default-argument expressions.
1319TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1320 const MultiLevelTemplateArgumentList &Args,
1321 SourceLocation Loc,
1322 DeclarationName Entity) {
1323 assert(!ActiveTemplateInstantiations.empty() &&
1324 "Cannot perform an instantiation without some context on the "
1325 "instantiation stack");
1326
1327 if (!NeedsInstantiationAsFunctionType(T))
1328 return T;
1329
1330 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1331
1332 TypeLocBuilder TLB;
1333
1334 TypeLoc TL = T->getTypeLoc();
1335 TLB.reserve(TL.getFullDataSize());
1336
John McCall31f82722010-11-12 08:19:04 +00001337 QualType Result = Instantiator.TransformType(TLB, TL);
John McCallb29f78f2010-04-09 17:38:44 +00001338 if (Result.isNull())
1339 return 0;
1340
1341 return TLB.getTypeSourceInfo(Context, Result);
1342}
1343
Douglas Gregor940bca72010-04-12 07:48:19 +00001344ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001345 const MultiLevelTemplateArgumentList &TemplateArgs,
1346 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001347 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor5499af42011-01-05 23:12:31 +00001348 TypeSourceInfo *NewDI = 0;
1349
Douglas Gregor5499af42011-01-05 23:12:31 +00001350 TypeLoc OldTL = OldDI->getTypeLoc();
1351 if (isa<PackExpansionTypeLoc>(OldTL)) {
1352 PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
Douglas Gregor5499af42011-01-05 23:12:31 +00001353
1354 // We have a function parameter pack. Substitute into the pattern of the
1355 // expansion.
1356 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1357 OldParm->getLocation(), OldParm->getDeclName());
1358 if (!NewDI)
1359 return 0;
1360
1361 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1362 // We still have unexpanded parameter packs, which means that
1363 // our function parameter is still a function parameter pack.
1364 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001365 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001366 NumExpansions);
Douglas Gregor5499af42011-01-05 23:12:31 +00001367 }
1368 } else {
1369 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1370 OldParm->getDeclName());
1371 }
1372
Douglas Gregor940bca72010-04-12 07:48:19 +00001373 if (!NewDI)
1374 return 0;
1375
1376 if (NewDI->getType()->isVoidType()) {
1377 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1378 return 0;
1379 }
1380
1381 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1382 NewDI, NewDI->getType(),
1383 OldParm->getIdentifier(),
1384 OldParm->getLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001385 OldParm->getStorageClass(),
1386 OldParm->getStorageClassAsWritten());
Douglas Gregor940bca72010-04-12 07:48:19 +00001387 if (!NewParm)
1388 return 0;
Douglas Gregor6044d692010-05-19 17:02:24 +00001389
Douglas Gregor940bca72010-04-12 07:48:19 +00001390 // Mark the (new) default argument as uninstantiated (if any).
1391 if (OldParm->hasUninstantiatedDefaultArg()) {
1392 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1393 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001394 } else if (OldParm->hasUnparsedDefaultArg()) {
1395 NewParm->setUnparsedDefaultArg();
1396 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Douglas Gregor940bca72010-04-12 07:48:19 +00001397 } else if (Expr *Arg = OldParm->getDefaultArg())
1398 NewParm->setUninstantiatedDefaultArg(Arg);
1399
1400 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1401
Douglas Gregor5499af42011-01-05 23:12:31 +00001402 // FIXME: When OldParm is a parameter pack and NewParm is not a parameter
1403 // pack, we actually have a set of instantiated locations. Maintain this set!
Douglas Gregorf3010112011-01-07 16:43:16 +00001404 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1405 // Add the new parameter to
1406 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1407 } else {
1408 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001409 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001410 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001411
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001412 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1413 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001414 NewParm->setDeclContext(CurContext);
Fariborz Jahaniana6c7efe2010-07-13 20:05:58 +00001415
Douglas Gregor940bca72010-04-12 07:48:19 +00001416 return NewParm;
1417}
1418
Douglas Gregordd472162011-01-07 00:20:55 +00001419/// \brief Substitute the given template arguments into the given set of
1420/// parameters, producing the set of parameter types that would be generated
1421/// from such a substitution.
1422bool Sema::SubstParmTypes(SourceLocation Loc,
1423 ParmVarDecl **Params, unsigned NumParams,
1424 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregorf3010112011-01-07 16:43:16 +00001425 llvm::SmallVectorImpl<QualType> &ParamTypes,
1426 llvm::SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregordd472162011-01-07 00:20:55 +00001427 assert(!ActiveTemplateInstantiations.empty() &&
1428 "Cannot perform an instantiation without some context on the "
1429 "instantiation stack");
1430
1431 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1432 DeclarationName());
1433 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregorf3010112011-01-07 16:43:16 +00001434 ParamTypes, OutParams);
Douglas Gregordd472162011-01-07 00:20:55 +00001435}
1436
John McCall76d824f2009-08-25 22:02:44 +00001437/// \brief Perform substitution on the base class specifiers of the
1438/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001439///
1440/// Produces a diagnostic and returns true on error, returns false and
1441/// attaches the instantiated base classes to the class template
1442/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001443bool
John McCall76d824f2009-08-25 22:02:44 +00001444Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1445 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001446 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001447 bool Invalid = false;
Douglas Gregor6181ded2009-05-29 18:27:38 +00001448 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump11289f42009-09-09 15:08:12 +00001449 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001450 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor2a72edd2009-03-10 18:52:44 +00001451 Base != BaseEnd; ++Base) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001452 if (!Base->getType()->isDependentType()) {
Fariborz Jahanian5c14ec32009-07-22 17:41:53 +00001453 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001454 continue;
1455 }
1456
Douglas Gregor752a5952011-01-03 22:36:02 +00001457 SourceLocation EllipsisLoc;
1458 if (Base->isPackExpansion()) {
1459 // This is a pack expansion. See whether we should expand it now, or
1460 // wait until later.
1461 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1462 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1463 Unexpanded);
1464 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001465 bool RetainExpansion = false;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001466 llvm::Optional<unsigned> NumExpansions;
Douglas Gregor752a5952011-01-03 22:36:02 +00001467 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1468 Base->getSourceRange(),
1469 Unexpanded.data(), Unexpanded.size(),
1470 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001471 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001472 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001473 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001474 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001475 }
1476
1477 // If we should expand this pack expansion now, do so.
1478 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001479 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001480 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1481
1482 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1483 TemplateArgs,
1484 Base->getSourceRange().getBegin(),
1485 DeclarationName());
1486 if (!BaseTypeLoc) {
1487 Invalid = true;
1488 continue;
1489 }
1490
1491 if (CXXBaseSpecifier *InstantiatedBase
1492 = CheckBaseSpecifier(Instantiation,
1493 Base->getSourceRange(),
1494 Base->isVirtual(),
1495 Base->getAccessSpecifierAsWritten(),
1496 BaseTypeLoc,
1497 SourceLocation()))
1498 InstantiatedBases.push_back(InstantiatedBase);
1499 else
1500 Invalid = true;
1501 }
1502
1503 continue;
1504 }
1505
1506 // The resulting base specifier will (still) be a pack expansion.
1507 EllipsisLoc = Base->getEllipsisLoc();
1508 }
1509
1510 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001511 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1512 TemplateArgs,
1513 Base->getSourceRange().getBegin(),
1514 DeclarationName());
1515 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001516 Invalid = true;
1517 continue;
1518 }
1519
1520 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001521 = CheckBaseSpecifier(Instantiation,
Douglas Gregor463421d2009-03-03 04:44:36 +00001522 Base->getSourceRange(),
1523 Base->isVirtual(),
1524 Base->getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001525 BaseTypeLoc,
1526 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001527 InstantiatedBases.push_back(InstantiatedBase);
1528 else
1529 Invalid = true;
1530 }
1531
Douglas Gregor2a72edd2009-03-10 18:52:44 +00001532 if (!Invalid &&
Jay Foad7d0479f2009-05-21 09:52:38 +00001533 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor463421d2009-03-03 04:44:36 +00001534 InstantiatedBases.size()))
1535 Invalid = true;
1536
1537 return Invalid;
1538}
1539
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001540/// \brief Instantiate the definition of a class from a given pattern.
1541///
1542/// \param PointOfInstantiation The point of instantiation within the
1543/// source code.
1544///
1545/// \param Instantiation is the declaration whose definition is being
1546/// instantiated. This will be either a class template specialization
1547/// or a member class of a class template specialization.
1548///
1549/// \param Pattern is the pattern from which the instantiation
1550/// occurs. This will be either the declaration of a class template or
1551/// the declaration of a member class of a class template.
1552///
1553/// \param TemplateArgs The template arguments to be substituted into
1554/// the pattern.
1555///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001556/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001557///
1558/// \param Complain whether to complain if the class cannot be instantiated due
1559/// to the lack of a definition.
1560///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001561/// \returns true if an error occurred, false otherwise.
1562bool
1563Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1564 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001565 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001566 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001567 bool Complain) {
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001568 bool Invalid = false;
John McCall87a44eb2009-08-20 01:44:21 +00001569
Mike Stump11289f42009-09-09 15:08:12 +00001570 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001571 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001572 if (!PatternDef) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001573 if (!Complain) {
1574 // Say nothing
1575 } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001576 Diag(PointOfInstantiation,
1577 diag::err_implicit_instantiate_member_undefined)
1578 << Context.getTypeDeclType(Instantiation);
1579 Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1580 } else {
Douglas Gregora1f49972009-05-13 00:25:59 +00001581 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001582 << (TSK != TSK_ImplicitInstantiation)
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001583 << Context.getTypeDeclType(Instantiation);
1584 Diag(Pattern->getLocation(), diag::note_template_decl_here);
1585 }
1586 return true;
1587 }
1588 Pattern = PatternDef;
1589
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001590 // \brief Record the point of instantiation.
1591 if (MemberSpecializationInfo *MSInfo
1592 = Instantiation->getMemberSpecializationInfo()) {
1593 MSInfo->setTemplateSpecializationKind(TSK);
1594 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00001595 } else if (ClassTemplateSpecializationDecl *Spec
1596 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1597 Spec->setTemplateSpecializationKind(TSK);
1598 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001599 }
1600
Douglas Gregorf3430ae2009-03-25 21:23:52 +00001601 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001602 if (Inst)
1603 return true;
1604
1605 // Enter the scope of this instantiation. We don't use
1606 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00001607 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00001608 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00001609 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001610
Douglas Gregor51121572010-03-24 01:33:17 +00001611 // If this is an instantiation of a local class, merge this local
1612 // instantiation scope with the enclosing scope. Otherwise, every
1613 // instantiation of a class has its own local instantiation scope.
1614 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00001615 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00001616
John McCall6602bb12010-08-01 02:01:53 +00001617 // Pull attributes from the pattern onto the instantiation.
1618 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1619
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001620 // Start the definition of this instantiation.
1621 Instantiation->startDefinition();
Douglas Gregore9029562010-05-06 00:28:52 +00001622
1623 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001624
John McCall76d824f2009-08-25 22:02:44 +00001625 // Do substitution on the base class specifiers.
1626 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001627 Invalid = true;
1628
Douglas Gregor869853e2010-11-10 19:44:59 +00001629 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
John McCall48871652010-08-21 09:40:31 +00001630 llvm::SmallVector<Decl*, 4> Fields;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001631 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001632 MemberEnd = Pattern->decls_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001633 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00001634 // Don't instantiate members not belonging in this semantic context.
1635 // e.g. for:
1636 // @code
1637 // template <int i> class A {
1638 // class B *g;
1639 // };
1640 // @endcode
1641 // 'class B' has the template as lexical context but semantically it is
1642 // introduced in namespace scope.
1643 if ((*Member)->getDeclContext() != Pattern)
1644 continue;
1645
Douglas Gregor869853e2010-11-10 19:44:59 +00001646 if ((*Member)->isInvalidDecl()) {
1647 Invalid = true;
1648 continue;
1649 }
1650
1651 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001652 if (NewMember) {
Eli Friedmand0e8de22009-12-07 00:22:08 +00001653 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
John McCall48871652010-08-21 09:40:31 +00001654 Fields.push_back(Field);
Eli Friedmand0e8de22009-12-07 00:22:08 +00001655 else if (NewMember->isInvalidDecl())
1656 Invalid = true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001657 } else {
1658 // FIXME: Eventually, a NULL return will mean that one of the
Mike Stump87c57ac2009-05-16 07:39:55 +00001659 // instantiations was a semantic disaster, and we'll want to set Invalid =
1660 // true. For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001661 }
1662 }
1663
1664 // Finish checking fields.
John McCall48871652010-08-21 09:40:31 +00001665 ActOnFields(0, Instantiation->getLocation(), Instantiation,
Jay Foad7d0479f2009-05-21 09:52:38 +00001666 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001667 0);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001668 CheckCompletedCXXClass(Instantiation);
Douglas Gregor3c74d412009-10-14 20:14:33 +00001669 if (Instantiation->isInvalidDecl())
1670 Invalid = true;
Douglas Gregor869853e2010-11-10 19:44:59 +00001671 else {
1672 // Instantiate any out-of-line class template partial
1673 // specializations now.
1674 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
1675 P = Instantiator.delayed_partial_spec_begin(),
1676 PEnd = Instantiator.delayed_partial_spec_end();
1677 P != PEnd; ++P) {
1678 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
1679 P->first,
1680 P->second)) {
1681 Invalid = true;
1682 break;
1683 }
1684 }
1685 }
1686
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001687 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00001688 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001689
Douglas Gregor88d292c2010-05-13 16:44:06 +00001690 if (!Invalid) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00001691 Consumer.HandleTagDeclDefinition(Instantiation);
1692
Douglas Gregor88d292c2010-05-13 16:44:06 +00001693 // Always emit the vtable for an explicit instantiation definition
1694 // of a polymorphic class template specialization.
1695 if (TSK == TSK_ExplicitInstantiationDefinition)
1696 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
1697 }
1698
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001699 return Invalid;
1700}
1701
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001702namespace {
1703 /// \brief A partial specialization whose template arguments have matched
1704 /// a given template-id.
1705 struct PartialSpecMatchResult {
1706 ClassTemplatePartialSpecializationDecl *Partial;
1707 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001708 };
1709}
1710
Mike Stump11289f42009-09-09 15:08:12 +00001711bool
Douglas Gregor463421d2009-03-03 04:44:36 +00001712Sema::InstantiateClassTemplateSpecialization(
Douglas Gregoref6ab412009-10-27 06:26:26 +00001713 SourceLocation PointOfInstantiation,
Douglas Gregor463421d2009-03-03 04:44:36 +00001714 ClassTemplateSpecializationDecl *ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001715 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001716 bool Complain) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001717 // Perform the actual instantiation on the canonical declaration.
1718 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00001719 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor463421d2009-03-03 04:44:36 +00001720
Douglas Gregor4aa04b12009-09-11 21:19:12 +00001721 // Check whether we have already instantiated or specialized this class
1722 // template specialization.
1723 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
1724 if (ClassTemplateSpec->getSpecializationKind() ==
1725 TSK_ExplicitInstantiationDeclaration &&
1726 TSK == TSK_ExplicitInstantiationDefinition) {
1727 // An explicit instantiation definition follows an explicit instantiation
1728 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
1729 // explicit instantiation.
1730 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor88d292c2010-05-13 16:44:06 +00001731
1732 // If this is an explicit instantiation definition, mark the
1733 // vtable as used.
1734 if (TSK == TSK_ExplicitInstantiationDefinition)
1735 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
1736
Douglas Gregor4aa04b12009-09-11 21:19:12 +00001737 return false;
1738 }
1739
1740 // We can only instantiate something that hasn't already been
1741 // instantiated or specialized. Fail without any diagnostics: our
1742 // caller will provide an error message.
Douglas Gregor463421d2009-03-03 04:44:36 +00001743 return true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00001744 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001745
Douglas Gregor00a511f2009-09-15 16:51:42 +00001746 if (ClassTemplateSpec->isInvalidDecl())
1747 return true;
1748
Douglas Gregor463421d2009-03-03 04:44:36 +00001749 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001750 CXXRecordDecl *Pattern = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00001751
Douglas Gregor170bc422009-06-12 22:31:52 +00001752 // C++ [temp.class.spec.match]p1:
1753 // When a class template is used in a context that requires an
1754 // instantiation of the class, it is necessary to determine
1755 // whether the instantiation is to be generated using the primary
1756 // template or one of the partial specializations. This is done by
1757 // matching the template arguments of the class template
1758 // specialization with the template argument lists of the partial
1759 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001760 typedef PartialSpecMatchResult MatchResult;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001761 llvm::SmallVector<MatchResult, 4> Matched;
Douglas Gregor407e9612010-04-30 05:56:50 +00001762 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1763 Template->getPartialSpecializations(PartialSpecs);
1764 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
1765 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
John McCallbc077cf2010-02-08 23:07:23 +00001766 TemplateDeductionInfo Info(Context, PointOfInstantiation);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001767 if (TemplateDeductionResult Result
Douglas Gregor407e9612010-04-30 05:56:50 +00001768 = DeduceTemplateArguments(Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001769 ClassTemplateSpec->getTemplateArgs(),
1770 Info)) {
1771 // FIXME: Store the failed-deduction information for use in
1772 // diagnostics, later.
1773 (void)Result;
1774 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001775 Matched.push_back(PartialSpecMatchResult());
1776 Matched.back().Partial = Partial;
1777 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001778 }
Douglas Gregor2373c592009-05-31 09:31:02 +00001779 }
1780
Douglas Gregor21610382009-10-29 00:04:11 +00001781 if (Matched.size() >= 1) {
Douglas Gregorbe999392009-09-15 16:23:51 +00001782 llvm::SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00001783 if (Matched.size() == 1) {
1784 // -- If exactly one matching specialization is found, the
1785 // instantiation is generated from that specialization.
1786 // We don't need to do anything for this.
1787 } else {
1788 // -- If more than one matching specialization is found, the
1789 // partial order rules (14.5.4.2) are used to determine
1790 // whether one of the specializations is more specialized
1791 // than the others. If none of the specializations is more
1792 // specialized than all of the other matching
1793 // specializations, then the use of the class template is
1794 // ambiguous and the program is ill-formed.
1795 for (llvm::SmallVector<MatchResult, 4>::iterator P = Best + 1,
1796 PEnd = Matched.end();
1797 P != PEnd; ++P) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001798 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00001799 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001800 == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00001801 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00001802 }
Douglas Gregorbe999392009-09-15 16:23:51 +00001803
Douglas Gregor21610382009-10-29 00:04:11 +00001804 // Determine if the best partial specialization is more specialized than
1805 // the others.
1806 bool Ambiguous = false;
Douglas Gregorbe999392009-09-15 16:23:51 +00001807 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1808 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00001809 P != PEnd; ++P) {
1810 if (P != Best &&
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001811 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00001812 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001813 != Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00001814 Ambiguous = true;
1815 break;
1816 }
1817 }
1818
1819 if (Ambiguous) {
1820 // Partial ordering did not produce a clear winner. Complain.
1821 ClassTemplateSpec->setInvalidDecl();
1822 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
1823 << ClassTemplateSpec;
1824
1825 // Print the matching partial specializations.
1826 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1827 PEnd = Matched.end();
1828 P != PEnd; ++P)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001829 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
1830 << getTemplateArgumentBindingsText(
1831 P->Partial->getTemplateParameters(),
1832 *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00001833
Douglas Gregor21610382009-10-29 00:04:11 +00001834 return true;
1835 }
Douglas Gregorbe999392009-09-15 16:23:51 +00001836 }
1837
1838 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001839 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00001840 while (OrigPartialSpec->getInstantiatedFromMember()) {
1841 // If we've found an explicit specialization of this class template,
1842 // stop here and use that as the pattern.
1843 if (OrigPartialSpec->isMemberSpecialization())
1844 break;
1845
1846 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
1847 }
1848
1849 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001850 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00001851 } else {
1852 // -- If no matches are found, the instantiation is generated
1853 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00001854 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00001855 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
1856 // If we've found an explicit specialization of this class template,
1857 // stop here and use that as the pattern.
1858 if (OrigTemplate->isMemberSpecialization())
1859 break;
1860
Douglas Gregor01afeef2009-08-28 20:31:08 +00001861 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00001862 }
1863
Douglas Gregor01afeef2009-08-28 20:31:08 +00001864 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00001865 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001866
Douglas Gregoref6ab412009-10-27 06:26:26 +00001867 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
1868 Pattern,
1869 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001870 TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001871 Complain);
Mike Stump11289f42009-09-09 15:08:12 +00001872
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001873 return Result;
Douglas Gregor463421d2009-03-03 04:44:36 +00001874}
Douglas Gregor90a1a652009-03-19 17:26:29 +00001875
John McCall76d824f2009-08-25 22:02:44 +00001876/// \brief Instantiates the definitions of all of the member
1877/// of the given class, which is an instantiation of a class template
1878/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00001879void
1880Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001881 CXXRecordDecl *Instantiation,
1882 const MultiLevelTemplateArgumentList &TemplateArgs,
1883 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001884 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
1885 DEnd = Instantiation->decls_end();
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00001886 D != DEnd; ++D) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00001887 bool SuppressNew = false;
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00001888 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00001889 if (FunctionDecl *Pattern
1890 = Function->getInstantiatedFromMemberFunction()) {
1891 MemberSpecializationInfo *MSInfo
1892 = Function->getMemberSpecializationInfo();
1893 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00001894 if (MSInfo->getTemplateSpecializationKind()
1895 == TSK_ExplicitSpecialization)
1896 continue;
1897
Douglas Gregor1d957a32009-10-27 18:42:08 +00001898 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
1899 Function,
1900 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00001901 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00001902 SuppressNew) ||
1903 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001904 continue;
1905
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001906 if (Function->hasBody())
Douglas Gregor1d957a32009-10-27 18:42:08 +00001907 continue;
1908
1909 if (TSK == TSK_ExplicitInstantiationDefinition) {
1910 // C++0x [temp.explicit]p8:
1911 // An explicit instantiation definition that names a class template
1912 // specialization explicitly instantiates the class template
1913 // specialization and is only an explicit instantiation definition
1914 // of members whose definition is visible at the point of
1915 // instantiation.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001916 if (!Pattern->hasBody())
Douglas Gregor1d957a32009-10-27 18:42:08 +00001917 continue;
1918
1919 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1920
1921 InstantiateFunctionDefinition(PointOfInstantiation, Function);
1922 } else {
1923 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1924 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001925 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00001926 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00001927 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00001928 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
1929 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00001930 if (MSInfo->getTemplateSpecializationKind()
1931 == TSK_ExplicitSpecialization)
1932 continue;
1933
Douglas Gregor1d957a32009-10-27 18:42:08 +00001934 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
1935 Var,
1936 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00001937 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00001938 SuppressNew) ||
1939 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001940 continue;
1941
Douglas Gregor1d957a32009-10-27 18:42:08 +00001942 if (TSK == TSK_ExplicitInstantiationDefinition) {
1943 // C++0x [temp.explicit]p8:
1944 // An explicit instantiation definition that names a class template
1945 // specialization explicitly instantiates the class template
1946 // specialization and is only an explicit instantiation definition
1947 // of members whose definition is visible at the point of
1948 // instantiation.
1949 if (!Var->getInstantiatedFromStaticDataMember()
1950 ->getOutOfLineDefinition())
1951 continue;
1952
1953 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00001954 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00001955 } else {
1956 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1957 }
1958 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00001959 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00001960 // Always skip the injected-class-name, along with any
1961 // redeclarations of nested classes, since both would cause us
1962 // to try to instantiate the members of a class twice.
1963 if (Record->isInjectedClassName() || Record->getPreviousDeclaration())
Douglas Gregord801b062009-10-07 23:56:10 +00001964 continue;
1965
Douglas Gregor1d957a32009-10-27 18:42:08 +00001966 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
1967 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00001968
1969 if (MSInfo->getTemplateSpecializationKind()
1970 == TSK_ExplicitSpecialization)
1971 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00001972
Douglas Gregor1d957a32009-10-27 18:42:08 +00001973 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
1974 Record,
1975 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00001976 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00001977 SuppressNew) ||
1978 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001979 continue;
1980
Douglas Gregor1d957a32009-10-27 18:42:08 +00001981 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
1982 assert(Pattern && "Missing instantiated-from-template information");
1983
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001984 if (!Record->getDefinition()) {
1985 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00001986 // C++0x [temp.explicit]p8:
1987 // An explicit instantiation definition that names a class template
1988 // specialization explicitly instantiates the class template
1989 // specialization and is only an explicit instantiation definition
1990 // of members whose definition is visible at the point of
1991 // instantiation.
1992 if (TSK == TSK_ExplicitInstantiationDeclaration) {
1993 MSInfo->setTemplateSpecializationKind(TSK);
1994 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1995 }
1996
1997 continue;
1998 }
1999
2000 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002001 TemplateArgs,
2002 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002003 } else {
2004 if (TSK == TSK_ExplicitInstantiationDefinition &&
2005 Record->getTemplateSpecializationKind() ==
2006 TSK_ExplicitInstantiationDeclaration) {
2007 Record->setTemplateSpecializationKind(TSK);
2008 MarkVTableUsed(PointOfInstantiation, Record, true);
2009 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002010 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002011
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002012 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002013 if (Pattern)
2014 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2015 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002016 }
2017 }
2018}
2019
2020/// \brief Instantiate the definitions of all of the members of the
2021/// given class template specialization, which was named as part of an
2022/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002023void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002024Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002025 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002026 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2027 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002028 // C++0x [temp.explicit]p7:
2029 // An explicit instantiation that names a class template
2030 // specialization is an explicit instantion of the same kind
2031 // (declaration or definition) of each of its members (not
2032 // including members inherited from base classes) that has not
2033 // been previously explicitly specialized in the translation unit
2034 // containing the explicit instantiation, except as described
2035 // below.
2036 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002037 getTemplateInstantiationArgs(ClassTemplateSpec),
2038 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002039}
2040
John McCalldadc5752010-08-24 06:29:42 +00002041StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002042Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002043 if (!S)
2044 return Owned(S);
2045
2046 TemplateInstantiator Instantiator(*this, TemplateArgs,
2047 SourceLocation(),
2048 DeclarationName());
2049 return Instantiator.TransformStmt(S);
2050}
2051
John McCalldadc5752010-08-24 06:29:42 +00002052ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002053Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002054 if (!E)
2055 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002056
Douglas Gregora16548e2009-08-11 05:31:07 +00002057 TemplateInstantiator Instantiator(*this, TemplateArgs,
2058 SourceLocation(),
2059 DeclarationName());
2060 return Instantiator.TransformExpr(E);
2061}
2062
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002063bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2064 const MultiLevelTemplateArgumentList &TemplateArgs,
2065 llvm::SmallVectorImpl<Expr *> &Outputs) {
2066 if (NumExprs == 0)
2067 return false;
2068
2069 TemplateInstantiator Instantiator(*this, TemplateArgs,
2070 SourceLocation(),
2071 DeclarationName());
2072 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2073}
2074
John McCall76d824f2009-08-25 22:02:44 +00002075/// \brief Do template substitution on a nested-name-specifier.
Douglas Gregorf21eb492009-03-26 23:50:42 +00002076NestedNameSpecifier *
John McCall76d824f2009-08-25 22:02:44 +00002077Sema::SubstNestedNameSpecifier(NestedNameSpecifier *NNS,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002078 SourceRange Range,
2079 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor1135c352009-08-06 05:28:30 +00002080 TemplateInstantiator Instantiator(*this, TemplateArgs, Range.getBegin(),
2081 DeclarationName());
Douglas Gregorcd3f49f2010-02-25 04:46:04 +00002082 return Instantiator.TransformNestedNameSpecifier(NNS, Range);
Douglas Gregor90a1a652009-03-19 17:26:29 +00002083}
Douglas Gregoraa594892009-03-31 18:38:02 +00002084
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002085/// \brief Do template substitution on declaration name info.
2086DeclarationNameInfo
2087Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2088 const MultiLevelTemplateArgumentList &TemplateArgs) {
2089 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2090 NameInfo.getName());
2091 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2092}
2093
Douglas Gregoraa594892009-03-31 18:38:02 +00002094TemplateName
John McCall76d824f2009-08-25 22:02:44 +00002095Sema::SubstTemplateName(TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002096 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002097 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2098 DeclarationName());
2099 return Instantiator.TransformTemplateName(Name);
Douglas Gregoraa594892009-03-31 18:38:02 +00002100}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002101
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002102bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2103 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002104 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002105 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2106 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002107
2108 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002109}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002110
John McCall19c1bfd2010-08-25 05:32:35 +00002111Decl *LocalInstantiationScope::getInstantiationOf(const Decl *D) {
Douglas Gregorf3010112011-01-07 16:43:16 +00002112 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found= findInstantiationOf(D);
2113 if (!Found)
2114 return 0;
2115
2116 if (Found->is<Decl *>())
2117 return Found->get<Decl *>();
2118
2119 return (*Found->get<DeclArgumentPack *>())[
2120 SemaRef.ArgumentPackSubstitutionIndex];
2121}
2122
2123llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2124LocalInstantiationScope::findInstantiationOf(const Decl *D) {
Douglas Gregor14cf7522010-04-30 18:55:50 +00002125 for (LocalInstantiationScope *Current = this; Current;
2126 Current = Current->Outer) {
2127 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002128 const Decl *CheckD = D;
2129 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002130 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002131 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002132 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002133
2134 // If this is a tag declaration, it's possible that we need to look for
2135 // a previous declaration.
2136 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2137 CheckD = Tag->getPreviousDeclaration();
2138 else
2139 CheckD = 0;
2140 } while (CheckD);
2141
Douglas Gregor14cf7522010-04-30 18:55:50 +00002142 // If we aren't combined with our outer scope, we're done.
2143 if (!Current->CombineWithOuterScope)
2144 break;
2145 }
2146
2147 assert(D->isInvalidDecl() &&
2148 "declaration was not instantiated in this scope!");
2149 return 0;
2150}
2151
John McCall19c1bfd2010-08-25 05:32:35 +00002152void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
Douglas Gregorf3010112011-01-07 16:43:16 +00002153 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002154 if (Stored.isNull())
2155 Stored = Inst;
2156 else if (Stored.is<Decl *>()) {
2157 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2158 Stored = Inst;
2159 } else
2160 LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
Douglas Gregor14cf7522010-04-30 18:55:50 +00002161}
Douglas Gregorf3010112011-01-07 16:43:16 +00002162
2163void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2164 Decl *Inst) {
2165 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2166 Pack->push_back(Inst);
2167}
2168
2169void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2170 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2171 assert(Stored.isNull() && "Already instantiated this local");
2172 DeclArgumentPack *Pack = new DeclArgumentPack;
2173 Stored = Pack;
2174 ArgumentPacks.push_back(Pack);
2175}
2176
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002177void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2178 const TemplateArgument *ExplicitArgs,
2179 unsigned NumExplicitArgs) {
2180 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2181 "Already have a partially-substituted pack");
2182 assert((!PartiallySubstitutedPack
2183 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2184 "Wrong number of arguments in partially-substituted pack");
2185 PartiallySubstitutedPack = Pack;
2186 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2187 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2188}
2189
2190NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2191 const TemplateArgument **ExplicitArgs,
2192 unsigned *NumExplicitArgs) const {
2193 if (ExplicitArgs)
2194 *ExplicitArgs = 0;
2195 if (NumExplicitArgs)
2196 *NumExplicitArgs = 0;
2197
2198 for (const LocalInstantiationScope *Current = this; Current;
2199 Current = Current->Outer) {
2200 if (Current->PartiallySubstitutedPack) {
2201 if (ExplicitArgs)
2202 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2203 if (NumExplicitArgs)
2204 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2205
2206 return Current->PartiallySubstitutedPack;
2207 }
2208
2209 if (!Current->CombineWithOuterScope)
2210 break;
2211 }
2212
2213 return 0;
2214}