blob: 4d164ea12ea7ed2655a9f09d5baa358e3fc2bf11 [file] [log] [blame]
Douglas Gregor74296542009-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
13#include "Sema.h"
Douglas Gregor841324a2009-08-04 16:50:30 +000014#include "TreeTransform.h"
Douglas Gregordc18e892009-05-26 20:50:29 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor74296542009-02-27 19:31:52 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
Douglas Gregor74296542009-02-27 19:31:52 +000018#include "clang/AST/DeclTemplate.h"
19#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
Douglas Gregorf57dcd02009-02-28 00:25:32 +000021#include "llvm/Support/Compiler.h"
Douglas Gregor74296542009-02-27 19:31:52 +000022
23using namespace clang;
24
Douglas Gregorfee85d62009-03-10 18:03:33 +000025//===----------------------------------------------------------------------===/
26// Template Instantiation Support
27//===----------------------------------------------------------------------===/
28
Douglas Gregor5f62c5e2009-05-14 23:26:13 +000029/// \brief Retrieve the template argument list that should be used to
30/// instantiate the given declaration.
31const TemplateArgumentList &
32Sema::getTemplateInstantiationArgs(NamedDecl *D) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +000033 // Template arguments for a class template specialization.
Douglas Gregor5f62c5e2009-05-14 23:26:13 +000034 if (ClassTemplateSpecializationDecl *Spec
35 = dyn_cast<ClassTemplateSpecializationDecl>(D))
Douglas Gregor7b0b83f2009-08-02 23:24:31 +000036 return Spec->getTemplateInstantiationArgs();
Douglas Gregor5f62c5e2009-05-14 23:26:13 +000037
Douglas Gregor6f5e0542009-06-26 00:10:03 +000038 // Template arguments for a function template specialization.
39 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
40 if (const TemplateArgumentList *TemplateArgs
41 = Function->getTemplateSpecializationArgs())
42 return *TemplateArgs;
43
44 // Template arguments for a member of a class template specialization.
Douglas Gregor5f62c5e2009-05-14 23:26:13 +000045 DeclContext *EnclosingTemplateCtx = D->getDeclContext();
46 while (!isa<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx)) {
47 assert(!EnclosingTemplateCtx->isFileContext() &&
48 "Tried to get the instantiation arguments of a non-template");
49 EnclosingTemplateCtx = EnclosingTemplateCtx->getParent();
50 }
51
52 ClassTemplateSpecializationDecl *EnclosingTemplate
53 = cast<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx);
Douglas Gregor7b0b83f2009-08-02 23:24:31 +000054 return EnclosingTemplate->getTemplateInstantiationArgs();
Douglas Gregor5f62c5e2009-05-14 23:26:13 +000055}
56
Douglas Gregor375733c2009-03-10 00:06:19 +000057Sema::InstantiatingTemplate::
58InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorb12249d2009-05-18 17:01:57 +000059 Decl *Entity,
Douglas Gregor375733c2009-03-10 00:06:19 +000060 SourceRange InstantiationRange)
61 : SemaRef(SemaRef) {
Douglas Gregor56d25a72009-03-10 20:44:00 +000062
63 Invalid = CheckInstantiationDepth(PointOfInstantiation,
64 InstantiationRange);
65 if (!Invalid) {
Douglas Gregor375733c2009-03-10 00:06:19 +000066 ActiveTemplateInstantiation Inst;
Douglas Gregor56d25a72009-03-10 20:44:00 +000067 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor375733c2009-03-10 00:06:19 +000068 Inst.PointOfInstantiation = PointOfInstantiation;
Douglas Gregor56d25a72009-03-10 20:44:00 +000069 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
Douglas Gregor95ba1282009-03-12 18:36:18 +000070 Inst.TemplateArgs = 0;
71 Inst.NumTemplateArgs = 0;
Douglas Gregor56d25a72009-03-10 20:44:00 +000072 Inst.InstantiationRange = InstantiationRange;
73 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
74 Invalid = false;
75 }
76}
77
78Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
79 SourceLocation PointOfInstantiation,
80 TemplateDecl *Template,
81 const TemplateArgument *TemplateArgs,
82 unsigned NumTemplateArgs,
83 SourceRange InstantiationRange)
84 : SemaRef(SemaRef) {
85
86 Invalid = CheckInstantiationDepth(PointOfInstantiation,
87 InstantiationRange);
88 if (!Invalid) {
89 ActiveTemplateInstantiation Inst;
90 Inst.Kind
91 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
92 Inst.PointOfInstantiation = PointOfInstantiation;
93 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
94 Inst.TemplateArgs = TemplateArgs;
95 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor375733c2009-03-10 00:06:19 +000096 Inst.InstantiationRange = InstantiationRange;
97 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
98 Invalid = false;
99 }
100}
101
Douglas Gregorc5e01af2009-06-10 23:47:09 +0000102Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
103 SourceLocation PointOfInstantiation,
Douglas Gregor4c8b2b32009-07-01 22:01:06 +0000104 FunctionTemplateDecl *FunctionTemplate,
105 const TemplateArgument *TemplateArgs,
106 unsigned NumTemplateArgs,
107 ActiveTemplateInstantiation::InstantiationKind Kind,
108 SourceRange InstantiationRange)
109: SemaRef(SemaRef) {
110
111 Invalid = CheckInstantiationDepth(PointOfInstantiation,
112 InstantiationRange);
113 if (!Invalid) {
114 ActiveTemplateInstantiation Inst;
115 Inst.Kind = Kind;
116 Inst.PointOfInstantiation = PointOfInstantiation;
117 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
118 Inst.TemplateArgs = TemplateArgs;
119 Inst.NumTemplateArgs = NumTemplateArgs;
120 Inst.InstantiationRange = InstantiationRange;
121 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
122 Invalid = false;
123 }
124}
125
126Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
127 SourceLocation PointOfInstantiation,
Douglas Gregorc5e01af2009-06-10 23:47:09 +0000128 ClassTemplatePartialSpecializationDecl *PartialSpec,
129 const TemplateArgument *TemplateArgs,
130 unsigned NumTemplateArgs,
131 SourceRange InstantiationRange)
132 : SemaRef(SemaRef) {
133
134 Invalid = CheckInstantiationDepth(PointOfInstantiation,
135 InstantiationRange);
136 if (!Invalid) {
137 ActiveTemplateInstantiation Inst;
138 Inst.Kind
Douglas Gregor4c8b2b32009-07-01 22:01:06 +0000139 = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
Douglas Gregorc5e01af2009-06-10 23:47:09 +0000140 Inst.PointOfInstantiation = PointOfInstantiation;
141 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
142 Inst.TemplateArgs = TemplateArgs;
143 Inst.NumTemplateArgs = NumTemplateArgs;
144 Inst.InstantiationRange = InstantiationRange;
145 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
146 Invalid = false;
147 }
148}
149
Douglas Gregorb12249d2009-05-18 17:01:57 +0000150void Sema::InstantiatingTemplate::Clear() {
151 if (!Invalid) {
Douglas Gregor375733c2009-03-10 00:06:19 +0000152 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorb12249d2009-05-18 17:01:57 +0000153 Invalid = true;
154 }
Douglas Gregor375733c2009-03-10 00:06:19 +0000155}
156
Douglas Gregor56d25a72009-03-10 20:44:00 +0000157bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
158 SourceLocation PointOfInstantiation,
159 SourceRange InstantiationRange) {
160 if (SemaRef.ActiveTemplateInstantiations.size()
161 <= SemaRef.getLangOptions().InstantiationDepth)
162 return false;
163
164 SemaRef.Diag(PointOfInstantiation,
165 diag::err_template_recursion_depth_exceeded)
166 << SemaRef.getLangOptions().InstantiationDepth
167 << InstantiationRange;
168 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
169 << SemaRef.getLangOptions().InstantiationDepth;
170 return true;
171}
172
Douglas Gregorfee85d62009-03-10 18:03:33 +0000173/// \brief Prints the current instantiation stack through a series of
174/// notes.
175void Sema::PrintInstantiationStack() {
Douglas Gregor4c8b2b32009-07-01 22:01:06 +0000176 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorfee85d62009-03-10 18:03:33 +0000177 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
178 Active = ActiveTemplateInstantiations.rbegin(),
179 ActiveEnd = ActiveTemplateInstantiations.rend();
180 Active != ActiveEnd;
181 ++Active) {
Douglas Gregor56d25a72009-03-10 20:44:00 +0000182 switch (Active->Kind) {
183 case ActiveTemplateInstantiation::TemplateInstantiation: {
Douglas Gregorb12249d2009-05-18 17:01:57 +0000184 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
185 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
186 unsigned DiagID = diag::note_template_member_class_here;
187 if (isa<ClassTemplateSpecializationDecl>(Record))
188 DiagID = diag::note_template_class_instantiation_here;
189 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
190 DiagID)
191 << Context.getTypeDeclType(Record)
192 << Active->InstantiationRange;
Douglas Gregor181fe792009-07-24 20:34:43 +0000193 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +0000194 unsigned DiagID;
195 if (Function->getPrimaryTemplate())
196 DiagID = diag::note_function_template_spec_here;
197 else
198 DiagID = diag::note_template_member_function_here;
Douglas Gregorb12249d2009-05-18 17:01:57 +0000199 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
200 DiagID)
201 << Function
202 << Active->InstantiationRange;
Douglas Gregor181fe792009-07-24 20:34:43 +0000203 } else {
204 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
205 diag::note_template_static_data_member_def_here)
206 << cast<VarDecl>(D)
207 << Active->InstantiationRange;
Douglas Gregorb12249d2009-05-18 17:01:57 +0000208 }
Douglas Gregor56d25a72009-03-10 20:44:00 +0000209 break;
210 }
211
212 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
213 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
214 std::string TemplateArgsStr
Douglas Gregordd13e842009-03-30 22:58:21 +0000215 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor4c8b2b32009-07-01 22:01:06 +0000216 Active->TemplateArgs,
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +0000217 Active->NumTemplateArgs,
218 Context.PrintingPolicy);
Douglas Gregor56d25a72009-03-10 20:44:00 +0000219 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
220 diag::note_default_arg_instantiation_here)
221 << (Template->getNameAsString() + TemplateArgsStr)
222 << Active->InstantiationRange;
223 break;
224 }
Douglas Gregorc5e01af2009-06-10 23:47:09 +0000225
Douglas Gregor4c8b2b32009-07-01 22:01:06 +0000226 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
227 FunctionTemplateDecl *FnTmpl
228 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Douglas Gregorc5e01af2009-06-10 23:47:09 +0000229 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
Douglas Gregor4c8b2b32009-07-01 22:01:06 +0000230 diag::note_explicit_template_arg_substitution_here)
231 << FnTmpl << Active->InstantiationRange;
Douglas Gregorc5e01af2009-06-10 23:47:09 +0000232 break;
233 }
Douglas Gregor4c8b2b32009-07-01 22:01:06 +0000234
235 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
236 if (ClassTemplatePartialSpecializationDecl *PartialSpec
237 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
238 (Decl *)Active->Entity)) {
239 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
240 diag::note_partial_spec_deduct_instantiation_here)
241 << Context.getTypeDeclType(PartialSpec)
242 << Active->InstantiationRange;
243 } else {
244 FunctionTemplateDecl *FnTmpl
245 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
246 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
247 diag::note_function_template_deduction_instantiation_here)
248 << FnTmpl << Active->InstantiationRange;
249 }
250 break;
Douglas Gregorc5e01af2009-06-10 23:47:09 +0000251
Douglas Gregor56d25a72009-03-10 20:44:00 +0000252 }
Douglas Gregorfee85d62009-03-10 18:03:33 +0000253 }
254}
255
Douglas Gregor95d6c952009-06-14 07:33:30 +0000256bool Sema::isSFINAEContext() const {
257 using llvm::SmallVector;
258 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
259 Active = ActiveTemplateInstantiations.rbegin(),
260 ActiveEnd = ActiveTemplateInstantiations.rend();
261 Active != ActiveEnd;
262 ++Active) {
263
264 switch(Active->Kind) {
Douglas Gregor4c8b2b32009-07-01 22:01:06 +0000265 case ActiveTemplateInstantiation::TemplateInstantiation:
266 // This is a template instantiation, so there is no SFINAE.
267 return false;
268
Douglas Gregor95d6c952009-06-14 07:33:30 +0000269 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
270 // A default template argument instantiation may or may not be a
271 // SFINAE context; look further up the stack.
272 break;
Douglas Gregor4c8b2b32009-07-01 22:01:06 +0000273
274 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
275 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
276 // We're either substitution explicitly-specified template arguments
277 // or deduced template arguments, so SFINAE applies.
278 return true;
Douglas Gregor95d6c952009-06-14 07:33:30 +0000279 }
280 }
281
282 return false;
283}
284
Douglas Gregor74296542009-02-27 19:31:52 +0000285//===----------------------------------------------------------------------===/
286// Template Instantiation for Types
287//===----------------------------------------------------------------------===/
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000288namespace {
Douglas Gregor841324a2009-08-04 16:50:30 +0000289 class VISIBILITY_HIDDEN TemplateInstantiator
290 : public TreeTransform<TemplateInstantiator>
291 {
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +0000292 const TemplateArgumentList &TemplateArgs;
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000293 SourceLocation Loc;
294 DeclarationName Entity;
Douglas Gregor74296542009-02-27 19:31:52 +0000295
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000296 public:
Douglas Gregor841324a2009-08-04 16:50:30 +0000297 TemplateInstantiator(Sema &SemaRef,
298 const TemplateArgumentList &TemplateArgs,
299 SourceLocation Loc,
300 DeclarationName Entity)
301 : TreeTransform<TemplateInstantiator>(SemaRef), TemplateArgs(TemplateArgs),
302 Loc(Loc), Entity(Entity) { }
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000303
Douglas Gregor841324a2009-08-04 16:50:30 +0000304 /// \brief Determine whether the given type \p T has already been
305 /// transformed.
306 ///
307 /// For the purposes of template instantiation, a type has already been
308 /// transformed if it is NULL or if it is not dependent.
309 bool AlreadyTransformed(QualType T) {
310 return T.isNull() || !T->isDependentType();
Douglas Gregor90177912009-05-13 18:28:20 +0000311 }
Douglas Gregor841324a2009-08-04 16:50:30 +0000312
313 /// \brief Returns the location of the entity being instantiated, if known.
314 SourceLocation getBaseLocation() { return Loc; }
315
316 /// \brief Returns the name of the entity being instantiated, if any.
317 DeclarationName getBaseEntity() { return Entity; }
318
Douglas Gregor841324a2009-08-04 16:50:30 +0000319 /// \brief Transform the given declaration by instantiating a reference to
320 /// this declaration.
321 Decl *TransformDecl(Decl *D);
322
Douglas Gregor9d879762009-08-11 05:31:07 +0000323 Sema::OwningStmtResult TransformStmt(Stmt *S) {
324 return SemaRef.InstantiateStmt(S, TemplateArgs);
325 }
326
327 Sema::OwningStmtResult TransformCompoundStmt(CompoundStmt *S,
328 bool IsStmtExpr) {
329 return SemaRef.InstantiateCompoundStmt(S, TemplateArgs, IsStmtExpr);
330 }
331
332 Sema::OwningExprResult TransformDeclRefExpr(DeclRefExpr *E);
333
334 Sema::OwningExprResult
335 TransformCXXConditionDeclExpr(CXXConditionDeclExpr *E);
336
Douglas Gregor841324a2009-08-04 16:50:30 +0000337 /// \brief Transforms a template type parameter type by performing
338 /// substitution of the corresponding template type argument.
339 QualType TransformTemplateTypeParmType(const TemplateTypeParmType *T);
340 };
Douglas Gregor1d381132009-07-06 15:59:29 +0000341}
342
Douglas Gregor841324a2009-08-04 16:50:30 +0000343Decl *TemplateInstantiator::TransformDecl(Decl *D) {
Douglas Gregor214d0462009-08-06 06:41:21 +0000344 if (TemplateTemplateParmDecl *TTP
345 = dyn_cast_or_null<TemplateTemplateParmDecl>(D)) {
346 // FIXME: Depth reduction
347 assert(TTP->getDepth() == 0 &&
348 "Cannot reduce depth of a template template parameter");
349 assert(TemplateArgs[TTP->getPosition()].getAsDecl() &&
350 "Wrong kind of template template argument");
351 TemplateDecl *Template
352 = dyn_cast<TemplateDecl>(TemplateArgs[TTP->getPosition()].getAsDecl());
353 assert(Template && "Expected a template");
354 return Template;
355 }
356
Douglas Gregor841324a2009-08-04 16:50:30 +0000357 return SemaRef.InstantiateCurrentDeclRef(cast_or_null<NamedDecl>(D));
358}
359
Douglas Gregor9d879762009-08-11 05:31:07 +0000360Sema::OwningExprResult
361TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
362 // FIXME: Clean this up a bit
363 NamedDecl *D = E->getDecl();
364 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
365 assert(NTTP->getDepth() == 0 && "No nested templates yet");
366
367 // If the corresponding template argument is NULL or non-existent, it's
368 // because we are performing instantiation from explicitly-specified
369 // template arguments in a function template, but there were some
370 // arguments left unspecified.
371 if (NTTP->getPosition() >= TemplateArgs.size() ||
372 TemplateArgs[NTTP->getPosition()].isNull())
373 return SemaRef.Owned(E); // FIXME: Clone the expression!
374
375 const TemplateArgument &Arg = TemplateArgs[NTTP->getPosition()];
376
377 // The template argument itself might be an expression, in which
378 // case we just return that expression.
379 if (Arg.getKind() == TemplateArgument::Expression)
380 // FIXME: Clone the expression!
381 return SemaRef.Owned(Arg.getAsExpr());
382
383 if (Arg.getKind() == TemplateArgument::Declaration) {
384 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
385
386 // FIXME: Can VD ever have a dependent type?
387 return SemaRef.BuildDeclRefExpr(VD, VD->getType(), E->getLocation(),
388 false, false);
389 }
390
391 assert(Arg.getKind() == TemplateArgument::Integral);
392 QualType T = Arg.getIntegralType();
393 if (T->isCharType() || T->isWideCharType())
394 return SemaRef.Owned(new (SemaRef.Context) CharacterLiteral(
395 Arg.getAsIntegral()->getZExtValue(),
396 T->isWideCharType(),
397 T,
398 E->getSourceRange().getBegin()));
399 if (T->isBooleanType())
400 return SemaRef.Owned(new (SemaRef.Context) CXXBoolLiteralExpr(
401 Arg.getAsIntegral()->getBoolValue(),
402 T,
403 E->getSourceRange().getBegin()));
404
405 assert(Arg.getAsIntegral()->getBitWidth() == SemaRef.Context.getIntWidth(T));
406 return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral(
407 *Arg.getAsIntegral(),
408 T,
409 E->getSourceRange().getBegin()));
410 }
411
412 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
413 // FIXME: instantiate each decl in the overload set
414 return SemaRef.Owned(new (SemaRef.Context) DeclRefExpr(Ovl,
415 SemaRef.Context.OverloadTy,
416 E->getLocation(),
417 false, false));
418 }
419
420 NamedDecl *InstD = SemaRef.InstantiateCurrentDeclRef(D);
421 if (!InstD)
422 return SemaRef.ExprError();
423
424 // FIXME: nested-name-specifier for QualifiedDeclRefExpr
425 return SemaRef.BuildDeclarationNameExpr(E->getLocation(), InstD,
426 /*FIXME:*/false,
427 /*FIXME:*/0,
428 /*FIXME:*/false);
429}
430
431Sema::OwningExprResult
432TemplateInstantiator::TransformCXXConditionDeclExpr(CXXConditionDeclExpr *E) {
433 VarDecl *Var
434 = cast_or_null<VarDecl>(SemaRef.InstantiateDecl(E->getVarDecl(),
435 SemaRef.CurContext,
436 TemplateArgs));
437 if (!Var)
438 return SemaRef.ExprError();
439
440 SemaRef.CurrentInstantiationScope->InstantiatedLocal(E->getVarDecl(), Var);
441 return SemaRef.Owned(new (SemaRef.Context) CXXConditionDeclExpr(
442 E->getStartLoc(),
443 SourceLocation(),
444 Var));
445}
446
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000447QualType
Douglas Gregor841324a2009-08-04 16:50:30 +0000448TemplateInstantiator::TransformTemplateTypeParmType(
449 const TemplateTypeParmType *T) {
Douglas Gregor74296542009-02-27 19:31:52 +0000450 if (T->getDepth() == 0) {
451 // Replace the template type parameter with its corresponding
452 // template argument.
Douglas Gregorecd63b82009-07-01 00:28:38 +0000453
Douglas Gregor841324a2009-08-04 16:50:30 +0000454 // FIXME: When dealing with member templates, we might end up with multiple
455 /// levels of template arguments that we're substituting into concurrently.
456
Douglas Gregorecd63b82009-07-01 00:28:38 +0000457 // If the corresponding template argument is NULL or doesn't exist, it's
458 // because we are performing instantiation from explicitly-specified
459 // template arguments in a function template class, but there were some
460 // arguments left unspecified.
461 if (T->getIndex() >= TemplateArgs.size() ||
462 TemplateArgs[T->getIndex()].isNull())
463 return QualType(T, 0); // Would be nice to keep the original type here
464
Douglas Gregor74296542009-02-27 19:31:52 +0000465 assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
466 "Template argument kind mismatch");
Douglas Gregor072ac382009-06-26 21:40:05 +0000467 return TemplateArgs[T->getIndex()].getAsType();
Douglas Gregor74296542009-02-27 19:31:52 +0000468 }
469
470 // The template type parameter comes from an inner template (e.g.,
471 // the template parameter list of a member template inside the
472 // template we are instantiating). Create a new template type
473 // parameter with the template "level" reduced by one.
Douglas Gregor841324a2009-08-04 16:50:30 +0000474 return getSema().Context.getTemplateTypeParmType(T->getDepth() - 1,
475 T->getIndex(),
476 T->isParameterPack(),
477 T->getName());
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000478}
Douglas Gregor74296542009-02-27 19:31:52 +0000479
480/// \brief Instantiate the type T with a given set of template arguments.
481///
482/// This routine substitutes the given template arguments into the
483/// type T and produces the instantiated type.
484///
485/// \param T the type into which the template arguments will be
486/// substituted. If this type is not dependent, it will be returned
487/// immediately.
488///
489/// \param TemplateArgs the template arguments that will be
490/// substituted for the top-level template parameters within T.
491///
Douglas Gregor74296542009-02-27 19:31:52 +0000492/// \param Loc the location in the source code where this substitution
493/// is being performed. It will typically be the location of the
494/// declarator (if we're instantiating the type of some declaration)
495/// or the location of the type in the source code (if, e.g., we're
496/// instantiating the type of a cast expression).
497///
498/// \param Entity the name of the entity associated with a declaration
499/// being instantiated (if any). May be empty to indicate that there
500/// is no such entity (if, e.g., this is a type that occurs as part of
501/// a cast expression) or that the entity has no name (e.g., an
502/// unnamed function parameter).
503///
504/// \returns If the instantiation succeeds, the instantiated
505/// type. Otherwise, produces diagnostics and returns a NULL type.
506QualType Sema::InstantiateType(QualType T,
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +0000507 const TemplateArgumentList &TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +0000508 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor56d25a72009-03-10 20:44:00 +0000509 assert(!ActiveTemplateInstantiations.empty() &&
510 "Cannot perform an instantiation without some context on the "
511 "instantiation stack");
512
Douglas Gregor74296542009-02-27 19:31:52 +0000513 // If T is not a dependent type, there is nothing to do.
514 if (!T->isDependentType())
515 return T;
516
Douglas Gregor841324a2009-08-04 16:50:30 +0000517 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
518 return Instantiator.TransformType(T);
Douglas Gregor74296542009-02-27 19:31:52 +0000519}
Douglas Gregored3a3982009-03-03 04:44:36 +0000520
521/// \brief Instantiate the base class specifiers of the given class
522/// template specialization.
523///
524/// Produces a diagnostic and returns true on error, returns false and
525/// attaches the instantiated base classes to the class template
526/// specialization if successful.
527bool
Douglas Gregorcc887972009-03-25 21:17:03 +0000528Sema::InstantiateBaseSpecifiers(CXXRecordDecl *Instantiation,
529 CXXRecordDecl *Pattern,
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +0000530 const TemplateArgumentList &TemplateArgs) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000531 bool Invalid = false;
Douglas Gregor4ac20ef2009-05-29 18:27:38 +0000532 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Douglas Gregorcc887972009-03-25 21:17:03 +0000533 for (ClassTemplateSpecializationDecl::base_class_iterator
534 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregord9572a12009-03-10 18:52:44 +0000535 Base != BaseEnd; ++Base) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000536 if (!Base->getType()->isDependentType()) {
Fariborz Jahanian1373b6f2009-07-22 17:41:53 +0000537 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregored3a3982009-03-03 04:44:36 +0000538 continue;
539 }
540
541 QualType BaseType = InstantiateType(Base->getType(),
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +0000542 TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +0000543 Base->getSourceRange().getBegin(),
544 DeclarationName());
545 if (BaseType.isNull()) {
546 Invalid = true;
547 continue;
548 }
549
550 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregorcc887972009-03-25 21:17:03 +0000551 = CheckBaseSpecifier(Instantiation,
Douglas Gregored3a3982009-03-03 04:44:36 +0000552 Base->getSourceRange(),
553 Base->isVirtual(),
554 Base->getAccessSpecifierAsWritten(),
555 BaseType,
556 /*FIXME: Not totally accurate */
557 Base->getSourceRange().getBegin()))
558 InstantiatedBases.push_back(InstantiatedBase);
559 else
560 Invalid = true;
561 }
562
Douglas Gregord9572a12009-03-10 18:52:44 +0000563 if (!Invalid &&
Jay Foad9e6bef42009-05-21 09:52:38 +0000564 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregored3a3982009-03-03 04:44:36 +0000565 InstantiatedBases.size()))
566 Invalid = true;
567
568 return Invalid;
569}
570
Douglas Gregorcc887972009-03-25 21:17:03 +0000571/// \brief Instantiate the definition of a class from a given pattern.
572///
573/// \param PointOfInstantiation The point of instantiation within the
574/// source code.
575///
576/// \param Instantiation is the declaration whose definition is being
577/// instantiated. This will be either a class template specialization
578/// or a member class of a class template specialization.
579///
580/// \param Pattern is the pattern from which the instantiation
581/// occurs. This will be either the declaration of a class template or
582/// the declaration of a member class of a class template.
583///
584/// \param TemplateArgs The template arguments to be substituted into
585/// the pattern.
586///
Douglas Gregorcc887972009-03-25 21:17:03 +0000587/// \returns true if an error occurred, false otherwise.
588bool
589Sema::InstantiateClass(SourceLocation PointOfInstantiation,
590 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregorfd79ac62009-05-13 00:25:59 +0000591 const TemplateArgumentList &TemplateArgs,
592 bool ExplicitInstantiation) {
Douglas Gregorcc887972009-03-25 21:17:03 +0000593 bool Invalid = false;
594
595 CXXRecordDecl *PatternDef
596 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
597 if (!PatternDef) {
598 if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
599 Diag(PointOfInstantiation,
600 diag::err_implicit_instantiate_member_undefined)
601 << Context.getTypeDeclType(Instantiation);
602 Diag(Pattern->getLocation(), diag::note_member_of_template_here);
603 } else {
Douglas Gregorfd79ac62009-05-13 00:25:59 +0000604 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
605 << ExplicitInstantiation
Douglas Gregorcc887972009-03-25 21:17:03 +0000606 << Context.getTypeDeclType(Instantiation);
607 Diag(Pattern->getLocation(), diag::note_template_decl_here);
608 }
609 return true;
610 }
611 Pattern = PatternDef;
612
Douglas Gregor42c48522009-03-25 21:23:52 +0000613 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregorcc887972009-03-25 21:17:03 +0000614 if (Inst)
615 return true;
616
617 // Enter the scope of this instantiation. We don't use
618 // PushDeclContext because we don't have a scope.
619 DeclContext *PreviousContext = CurContext;
620 CurContext = Instantiation;
621
622 // Start the definition of this instantiation.
623 Instantiation->startDefinition();
624
625 // Instantiate the base class specifiers.
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +0000626 if (InstantiateBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorcc887972009-03-25 21:17:03 +0000627 Invalid = true;
628
Douglas Gregor4ac20ef2009-05-29 18:27:38 +0000629 llvm::SmallVector<DeclPtrTy, 4> Fields;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000630 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
631 MemberEnd = Pattern->decls_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000632 Member != MemberEnd; ++Member) {
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +0000633 Decl *NewMember = InstantiateDecl(*Member, Instantiation, TemplateArgs);
Douglas Gregorcc887972009-03-25 21:17:03 +0000634 if (NewMember) {
635 if (NewMember->isInvalidDecl())
636 Invalid = true;
637 else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
Chris Lattner5261d0c2009-03-28 19:18:32 +0000638 Fields.push_back(DeclPtrTy::make(Field));
Douglas Gregorcc887972009-03-25 21:17:03 +0000639 } else {
640 // FIXME: Eventually, a NULL return will mean that one of the
Mike Stumpe127ae32009-05-16 07:39:55 +0000641 // instantiations was a semantic disaster, and we'll want to set Invalid =
642 // true. For now, we expect to skip some members that we can't yet handle.
Douglas Gregorcc887972009-03-25 21:17:03 +0000643 }
644 }
645
646 // Finish checking fields.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000647 ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
Jay Foad9e6bef42009-05-21 09:52:38 +0000648 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
Douglas Gregorcc887972009-03-25 21:17:03 +0000649 0);
650
651 // Add any implicitly-declared members that we might need.
652 AddImplicitlyDeclaredMembersToClass(Instantiation);
653
654 // Exit the scope of this instantiation.
655 CurContext = PreviousContext;
656
Douglas Gregordc18e892009-05-26 20:50:29 +0000657 if (!Invalid)
658 Consumer.HandleTagDeclDefinition(Instantiation);
659
Douglas Gregordf9f5d12009-05-13 20:28:22 +0000660 // If this is an explicit instantiation, instantiate our members, too.
Douglas Gregorb12249d2009-05-18 17:01:57 +0000661 if (!Invalid && ExplicitInstantiation) {
662 Inst.Clear();
Douglas Gregordf9f5d12009-05-13 20:28:22 +0000663 InstantiateClassMembers(PointOfInstantiation, Instantiation, TemplateArgs);
Douglas Gregorb12249d2009-05-18 17:01:57 +0000664 }
Douglas Gregordf9f5d12009-05-13 20:28:22 +0000665
Douglas Gregorcc887972009-03-25 21:17:03 +0000666 return Invalid;
667}
668
Douglas Gregored3a3982009-03-03 04:44:36 +0000669bool
670Sema::InstantiateClassTemplateSpecialization(
671 ClassTemplateSpecializationDecl *ClassTemplateSpec,
672 bool ExplicitInstantiation) {
673 // Perform the actual instantiation on the canonical declaration.
674 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +0000675 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregored3a3982009-03-03 04:44:36 +0000676
677 // We can only instantiate something that hasn't already been
678 // instantiated or specialized. Fail without any diagnostics: our
679 // caller will provide an error message.
680 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
681 return true;
682
Douglas Gregored3a3982009-03-03 04:44:36 +0000683 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregorcc887972009-03-25 21:17:03 +0000684 CXXRecordDecl *Pattern = Template->getTemplatedDecl();
Douglas Gregor58944ac2009-05-31 09:31:02 +0000685 const TemplateArgumentList *TemplateArgs
686 = &ClassTemplateSpec->getTemplateArgs();
687
Douglas Gregor21530c52009-06-12 22:31:52 +0000688 // C++ [temp.class.spec.match]p1:
689 // When a class template is used in a context that requires an
690 // instantiation of the class, it is necessary to determine
691 // whether the instantiation is to be generated using the primary
692 // template or one of the partial specializations. This is done by
693 // matching the template arguments of the class template
694 // specialization with the template argument lists of the partial
695 // specializations.
Douglas Gregorab9f71a2009-06-05 00:53:49 +0000696 typedef std::pair<ClassTemplatePartialSpecializationDecl *,
697 TemplateArgumentList *> MatchResult;
698 llvm::SmallVector<MatchResult, 4> Matched;
Douglas Gregor58944ac2009-05-31 09:31:02 +0000699 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
700 Partial = Template->getPartialSpecializations().begin(),
701 PartialEnd = Template->getPartialSpecializations().end();
702 Partial != PartialEnd;
703 ++Partial) {
Douglas Gregor623e2e02009-06-12 18:26:56 +0000704 TemplateDeductionInfo Info(Context);
705 if (TemplateDeductionResult Result
Douglas Gregorab9f71a2009-06-05 00:53:49 +0000706 = DeduceTemplateArguments(&*Partial,
Douglas Gregor623e2e02009-06-12 18:26:56 +0000707 ClassTemplateSpec->getTemplateArgs(),
708 Info)) {
709 // FIXME: Store the failed-deduction information for use in
710 // diagnostics, later.
711 (void)Result;
712 } else {
713 Matched.push_back(std::make_pair(&*Partial, Info.take()));
714 }
Douglas Gregor58944ac2009-05-31 09:31:02 +0000715 }
716
717 if (Matched.size() == 1) {
Douglas Gregor21530c52009-06-12 22:31:52 +0000718 // -- If exactly one matching specialization is found, the
719 // instantiation is generated from that specialization.
Douglas Gregorab9f71a2009-06-05 00:53:49 +0000720 Pattern = Matched[0].first;
721 TemplateArgs = Matched[0].second;
Douglas Gregor7b0b83f2009-08-02 23:24:31 +0000722 ClassTemplateSpec->setInstantiationOf(Matched[0].first, Matched[0].second);
Douglas Gregor58944ac2009-05-31 09:31:02 +0000723 } else if (Matched.size() > 1) {
Douglas Gregor21530c52009-06-12 22:31:52 +0000724 // -- If more than one matching specialization is found, the
725 // partial order rules (14.5.4.2) are used to determine
726 // whether one of the specializations is more specialized
727 // than the others. If none of the specializations is more
728 // specialized than all of the other matching
729 // specializations, then the use of the class template is
730 // ambiguous and the program is ill-formed.
Douglas Gregor58944ac2009-05-31 09:31:02 +0000731 // FIXME: Implement partial ordering of class template partial
732 // specializations.
733 Diag(ClassTemplateSpec->getLocation(),
734 diag::unsup_template_partial_spec_ordering);
Douglas Gregor21530c52009-06-12 22:31:52 +0000735 } else {
736 // -- If no matches are found, the instantiation is generated
737 // from the primary template.
738
739 // Since we initialized the pattern and template arguments from
740 // the primary template, there is nothing more we need to do here.
Douglas Gregor58944ac2009-05-31 09:31:02 +0000741 }
Douglas Gregored3a3982009-03-03 04:44:36 +0000742
743 // Note that this is an instantiation.
744 ClassTemplateSpec->setSpecializationKind(
745 ExplicitInstantiation? TSK_ExplicitInstantiation
746 : TSK_ImplicitInstantiation);
747
Douglas Gregorab9f71a2009-06-05 00:53:49 +0000748 bool Result = InstantiateClass(ClassTemplateSpec->getLocation(),
749 ClassTemplateSpec, Pattern, *TemplateArgs,
750 ExplicitInstantiation);
751
752 for (unsigned I = 0, N = Matched.size(); I != N; ++I) {
753 // FIXME: Implement TemplateArgumentList::Destroy!
754 // if (Matched[I].first != Pattern)
755 // Matched[I].second->Destroy(Context);
756 }
757
758 return Result;
Douglas Gregored3a3982009-03-03 04:44:36 +0000759}
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000760
Douglas Gregordf9f5d12009-05-13 20:28:22 +0000761/// \brief Instantiate the definitions of all of the member of the
762/// given class, which is an instantiation of a class template or a
763/// member class of a template.
764void
765Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
766 CXXRecordDecl *Instantiation,
767 const TemplateArgumentList &TemplateArgs) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000768 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
769 DEnd = Instantiation->decls_end();
Douglas Gregordf9f5d12009-05-13 20:28:22 +0000770 D != DEnd; ++D) {
771 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +0000772 if (!Function->getBody())
Douglas Gregorb12249d2009-05-18 17:01:57 +0000773 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Douglas Gregordf9f5d12009-05-13 20:28:22 +0000774 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +0000775 if (Var->isStaticDataMember())
776 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregordf9f5d12009-05-13 20:28:22 +0000777 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
778 if (!Record->isInjectedClassName() && !Record->getDefinition(Context)) {
779 assert(Record->getInstantiatedFromMemberClass() &&
780 "Missing instantiated-from-template information");
Douglas Gregorb12249d2009-05-18 17:01:57 +0000781 InstantiateClass(PointOfInstantiation, Record,
Douglas Gregordf9f5d12009-05-13 20:28:22 +0000782 Record->getInstantiatedFromMemberClass(),
783 TemplateArgs, true);
784 }
785 }
786 }
787}
788
789/// \brief Instantiate the definitions of all of the members of the
790/// given class template specialization, which was named as part of an
791/// explicit instantiation.
792void Sema::InstantiateClassTemplateSpecializationMembers(
793 SourceLocation PointOfInstantiation,
794 ClassTemplateSpecializationDecl *ClassTemplateSpec) {
795 // C++0x [temp.explicit]p7:
796 // An explicit instantiation that names a class template
797 // specialization is an explicit instantion of the same kind
798 // (declaration or definition) of each of its members (not
799 // including members inherited from base classes) that has not
800 // been previously explicitly specialized in the translation unit
801 // containing the explicit instantiation, except as described
802 // below.
803 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
804 ClassTemplateSpec->getTemplateArgs());
805}
806
Douglas Gregor9d879762009-08-11 05:31:07 +0000807Sema::OwningExprResult
808Sema::InstantiateExpr(Expr *E, const TemplateArgumentList &TemplateArgs) {
809 if (!E)
810 return Owned(E);
811
812 TemplateInstantiator Instantiator(*this, TemplateArgs,
813 SourceLocation(),
814 DeclarationName());
815 return Instantiator.TransformExpr(E);
816}
817
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000818/// \brief Instantiate a nested-name-specifier.
819NestedNameSpecifier *
820Sema::InstantiateNestedNameSpecifier(NestedNameSpecifier *NNS,
821 SourceRange Range,
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +0000822 const TemplateArgumentList &TemplateArgs) {
Douglas Gregor12431cb2009-08-06 05:28:30 +0000823 TemplateInstantiator Instantiator(*this, TemplateArgs, Range.getBegin(),
824 DeclarationName());
825 return Instantiator.TransformNestedNameSpecifier(NNS, Range);
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000826}
Douglas Gregor15a92852009-03-31 18:38:02 +0000827
828TemplateName
829Sema::InstantiateTemplateName(TemplateName Name, SourceLocation Loc,
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +0000830 const TemplateArgumentList &TemplateArgs) {
Douglas Gregor214d0462009-08-06 06:41:21 +0000831 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
832 DeclarationName());
833 return Instantiator.TransformTemplateName(Name);
Douglas Gregor15a92852009-03-31 18:38:02 +0000834}
Douglas Gregorb320b9e2009-06-11 00:06:24 +0000835
836TemplateArgument Sema::Instantiate(TemplateArgument Arg,
837 const TemplateArgumentList &TemplateArgs) {
Douglas Gregor2999faa2009-08-04 22:27:00 +0000838 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
839 DeclarationName());
840 return Instantiator.TransformTemplateArgument(Arg);
Douglas Gregorb320b9e2009-06-11 00:06:24 +0000841}