blob: 5f378993a254f01d11adb8447d64b228b8fda990 [file] [log] [blame]
Douglas Gregor99ebf652009-02-27 19:31:52 +00001//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation.
10//
11//===----------------------------------------------------------------------===/
12
13#include "Sema.h"
Douglas Gregor577f75a2009-08-04 16:50:30 +000014#include "TreeTransform.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000018#include "clang/AST/DeclTemplate.h"
19#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
Douglas Gregorcd281c32009-02-28 00:25:32 +000021#include "llvm/Support/Compiler.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000022
23using namespace clang;
24
Douglas Gregoree1828a2009-03-10 18:03:33 +000025//===----------------------------------------------------------------------===/
26// Template Instantiation Support
27//===----------------------------------------------------------------------===/
28
Douglas Gregor54dabfc2009-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 Gregor1637be72009-06-26 00:10:03 +000033 // Template arguments for a class template specialization.
Douglas Gregor54dabfc2009-05-14 23:26:13 +000034 if (ClassTemplateSpecializationDecl *Spec
35 = dyn_cast<ClassTemplateSpecializationDecl>(D))
Douglas Gregor37d93e92009-08-02 23:24:31 +000036 return Spec->getTemplateInstantiationArgs();
Douglas Gregor54dabfc2009-05-14 23:26:13 +000037
Douglas Gregor1637be72009-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 Gregor54dabfc2009-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 Gregor37d93e92009-08-02 23:24:31 +000054 return EnclosingTemplate->getTemplateInstantiationArgs();
Douglas Gregor54dabfc2009-05-14 23:26:13 +000055}
56
Douglas Gregor26dce442009-03-10 00:06:19 +000057Sema::InstantiatingTemplate::
58InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +000059 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +000060 SourceRange InstantiationRange)
61 : SemaRef(SemaRef) {
Douglas Gregordf667e72009-03-10 20:44:00 +000062
63 Invalid = CheckInstantiationDepth(PointOfInstantiation,
64 InstantiationRange);
65 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +000066 ActiveTemplateInstantiation Inst;
Douglas Gregordf667e72009-03-10 20:44:00 +000067 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor26dce442009-03-10 00:06:19 +000068 Inst.PointOfInstantiation = PointOfInstantiation;
Douglas Gregordf667e72009-03-10 20:44:00 +000069 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
Douglas Gregor313a81d2009-03-12 18:36:18 +000070 Inst.TemplateArgs = 0;
71 Inst.NumTemplateArgs = 0;
Douglas Gregordf667e72009-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 Gregor26dce442009-03-10 00:06:19 +000096 Inst.InstantiationRange = InstantiationRange;
97 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
98 Invalid = false;
99 }
100}
101
Douglas Gregor637a4092009-06-10 23:47:09 +0000102Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
103 SourceLocation PointOfInstantiation,
Douglas Gregorcca9e962009-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 Gregor637a4092009-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 Gregorcca9e962009-07-01 22:01:06 +0000139 = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
Douglas Gregor637a4092009-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 Gregorf3e7ce42009-05-18 17:01:57 +0000150void Sema::InstantiatingTemplate::Clear() {
151 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +0000152 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000153 Invalid = true;
154 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000155}
156
Douglas Gregordf667e72009-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 Gregoree1828a2009-03-10 18:03:33 +0000173/// \brief Prints the current instantiation stack through a series of
174/// notes.
175void Sema::PrintInstantiationStack() {
Douglas Gregorcca9e962009-07-01 22:01:06 +0000176 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregoree1828a2009-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 Gregordf667e72009-03-10 20:44:00 +0000182 switch (Active->Kind) {
183 case ActiveTemplateInstantiation::TemplateInstantiation: {
Douglas Gregorf3e7ce42009-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 Gregor7caa6822009-07-24 20:34:43 +0000193 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-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 Gregorf3e7ce42009-05-18 17:01:57 +0000199 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
200 DiagID)
201 << Function
202 << Active->InstantiationRange;
Douglas Gregor7caa6822009-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 Gregorf3e7ce42009-05-18 17:01:57 +0000208 }
Douglas Gregordf667e72009-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 Gregor7532dc62009-03-30 22:58:21 +0000215 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregorcca9e962009-07-01 22:01:06 +0000216 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000217 Active->NumTemplateArgs,
218 Context.PrintingPolicy);
Douglas Gregordf667e72009-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 Gregor637a4092009-06-10 23:47:09 +0000225
Douglas Gregorcca9e962009-07-01 22:01:06 +0000226 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
227 FunctionTemplateDecl *FnTmpl
228 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Douglas Gregor637a4092009-06-10 23:47:09 +0000229 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
Douglas Gregorcca9e962009-07-01 22:01:06 +0000230 diag::note_explicit_template_arg_substitution_here)
231 << FnTmpl << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000232 break;
233 }
Douglas Gregorcca9e962009-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 Gregor637a4092009-06-10 23:47:09 +0000251
Douglas Gregordf667e72009-03-10 20:44:00 +0000252 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000253 }
254}
255
Douglas Gregor5e9f35c2009-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 Gregorcca9e962009-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 Gregor5e9f35c2009-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 Gregorcca9e962009-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 Gregor5e9f35c2009-06-14 07:33:30 +0000279 }
280 }
281
282 return false;
283}
284
Douglas Gregor99ebf652009-02-27 19:31:52 +0000285//===----------------------------------------------------------------------===/
286// Template Instantiation for Types
287//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000288namespace {
Douglas Gregor577f75a2009-08-04 16:50:30 +0000289 class VISIBILITY_HIDDEN TemplateInstantiator
290 : public TreeTransform<TemplateInstantiator>
291 {
Douglas Gregor7e063902009-05-11 23:53:27 +0000292 const TemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000293 SourceLocation Loc;
294 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000295
Douglas Gregorcd281c32009-02-28 00:25:32 +0000296 public:
Douglas Gregor577f75a2009-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 Gregorcd281c32009-02-28 00:25:32 +0000303
Douglas Gregor577f75a2009-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 Gregorff668032009-05-13 18:28:20 +0000311 }
Douglas Gregor577f75a2009-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
319 /// \brief Transforms an expression by instantiating it with the given
320 /// template arguments.
321 Sema::OwningExprResult TransformExpr(Expr *E);
Douglas Gregorff668032009-05-13 18:28:20 +0000322
Douglas Gregor577f75a2009-08-04 16:50:30 +0000323 /// \brief Transform the given declaration by instantiating a reference to
324 /// this declaration.
325 Decl *TransformDecl(Decl *D);
326
Douglas Gregor577f75a2009-08-04 16:50:30 +0000327 /// \brief Transform the given template name by instantiating it.
328 TemplateName TransformTemplateName(TemplateName Template);
329
Douglas Gregor577f75a2009-08-04 16:50:30 +0000330 /// \brief Transforms a template type parameter type by performing
331 /// substitution of the corresponding template type argument.
332 QualType TransformTemplateTypeParmType(const TemplateTypeParmType *T);
333 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000334}
335
Douglas Gregor577f75a2009-08-04 16:50:30 +0000336Sema::OwningExprResult TemplateInstantiator::TransformExpr(Expr *E) {
337 return getSema().InstantiateExpr(E, TemplateArgs);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000338}
339
Douglas Gregor577f75a2009-08-04 16:50:30 +0000340Decl *TemplateInstantiator::TransformDecl(Decl *D) {
341 return SemaRef.InstantiateCurrentDeclRef(cast_or_null<NamedDecl>(D));
342}
343
Douglas Gregor577f75a2009-08-04 16:50:30 +0000344TemplateName
345TemplateInstantiator::TransformTemplateName(TemplateName Template) {
346 return getSema().InstantiateTemplateName(Template, /*FIXME*/Loc,
347 TemplateArgs);
348}
349
Douglas Gregorcd281c32009-02-28 00:25:32 +0000350QualType
Douglas Gregor577f75a2009-08-04 16:50:30 +0000351TemplateInstantiator::TransformTemplateTypeParmType(
352 const TemplateTypeParmType *T) {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000353 if (T->getDepth() == 0) {
354 // Replace the template type parameter with its corresponding
355 // template argument.
Douglas Gregor16134c62009-07-01 00:28:38 +0000356
Douglas Gregor577f75a2009-08-04 16:50:30 +0000357 // FIXME: When dealing with member templates, we might end up with multiple
358 /// levels of template arguments that we're substituting into concurrently.
359
Douglas Gregor16134c62009-07-01 00:28:38 +0000360 // If the corresponding template argument is NULL or doesn't exist, it's
361 // because we are performing instantiation from explicitly-specified
362 // template arguments in a function template class, but there were some
363 // arguments left unspecified.
364 if (T->getIndex() >= TemplateArgs.size() ||
365 TemplateArgs[T->getIndex()].isNull())
366 return QualType(T, 0); // Would be nice to keep the original type here
367
Douglas Gregor99ebf652009-02-27 19:31:52 +0000368 assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
369 "Template argument kind mismatch");
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000370 return TemplateArgs[T->getIndex()].getAsType();
Douglas Gregor99ebf652009-02-27 19:31:52 +0000371 }
372
373 // The template type parameter comes from an inner template (e.g.,
374 // the template parameter list of a member template inside the
375 // template we are instantiating). Create a new template type
376 // parameter with the template "level" reduced by one.
Douglas Gregor577f75a2009-08-04 16:50:30 +0000377 return getSema().Context.getTemplateTypeParmType(T->getDepth() - 1,
378 T->getIndex(),
379 T->isParameterPack(),
380 T->getName());
Douglas Gregorcd281c32009-02-28 00:25:32 +0000381}
Douglas Gregor99ebf652009-02-27 19:31:52 +0000382
383/// \brief Instantiate the type T with a given set of template arguments.
384///
385/// This routine substitutes the given template arguments into the
386/// type T and produces the instantiated type.
387///
388/// \param T the type into which the template arguments will be
389/// substituted. If this type is not dependent, it will be returned
390/// immediately.
391///
392/// \param TemplateArgs the template arguments that will be
393/// substituted for the top-level template parameters within T.
394///
Douglas Gregor99ebf652009-02-27 19:31:52 +0000395/// \param Loc the location in the source code where this substitution
396/// is being performed. It will typically be the location of the
397/// declarator (if we're instantiating the type of some declaration)
398/// or the location of the type in the source code (if, e.g., we're
399/// instantiating the type of a cast expression).
400///
401/// \param Entity the name of the entity associated with a declaration
402/// being instantiated (if any). May be empty to indicate that there
403/// is no such entity (if, e.g., this is a type that occurs as part of
404/// a cast expression) or that the entity has no name (e.g., an
405/// unnamed function parameter).
406///
407/// \returns If the instantiation succeeds, the instantiated
408/// type. Otherwise, produces diagnostics and returns a NULL type.
409QualType Sema::InstantiateType(QualType T,
Douglas Gregor7e063902009-05-11 23:53:27 +0000410 const TemplateArgumentList &TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +0000411 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +0000412 assert(!ActiveTemplateInstantiations.empty() &&
413 "Cannot perform an instantiation without some context on the "
414 "instantiation stack");
415
Douglas Gregor99ebf652009-02-27 19:31:52 +0000416 // If T is not a dependent type, there is nothing to do.
417 if (!T->isDependentType())
418 return T;
419
Douglas Gregor577f75a2009-08-04 16:50:30 +0000420 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
421 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000422}
Douglas Gregor2943aed2009-03-03 04:44:36 +0000423
424/// \brief Instantiate the base class specifiers of the given class
425/// template specialization.
426///
427/// Produces a diagnostic and returns true on error, returns false and
428/// attaches the instantiated base classes to the class template
429/// specialization if successful.
430bool
Douglas Gregord475b8d2009-03-25 21:17:03 +0000431Sema::InstantiateBaseSpecifiers(CXXRecordDecl *Instantiation,
432 CXXRecordDecl *Pattern,
Douglas Gregor7e063902009-05-11 23:53:27 +0000433 const TemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000434 bool Invalid = false;
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000435 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Douglas Gregord475b8d2009-03-25 21:17:03 +0000436 for (ClassTemplateSpecializationDecl::base_class_iterator
437 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +0000438 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000439 if (!Base->getType()->isDependentType()) {
Fariborz Jahanian71c6e712009-07-22 17:41:53 +0000440 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +0000441 continue;
442 }
443
444 QualType BaseType = InstantiateType(Base->getType(),
Douglas Gregor7e063902009-05-11 23:53:27 +0000445 TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000446 Base->getSourceRange().getBegin(),
447 DeclarationName());
448 if (BaseType.isNull()) {
449 Invalid = true;
450 continue;
451 }
452
453 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +0000454 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000455 Base->getSourceRange(),
456 Base->isVirtual(),
457 Base->getAccessSpecifierAsWritten(),
458 BaseType,
459 /*FIXME: Not totally accurate */
460 Base->getSourceRange().getBegin()))
461 InstantiatedBases.push_back(InstantiatedBase);
462 else
463 Invalid = true;
464 }
465
Douglas Gregor27b152f2009-03-10 18:52:44 +0000466 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +0000467 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000468 InstantiatedBases.size()))
469 Invalid = true;
470
471 return Invalid;
472}
473
Douglas Gregord475b8d2009-03-25 21:17:03 +0000474/// \brief Instantiate the definition of a class from a given pattern.
475///
476/// \param PointOfInstantiation The point of instantiation within the
477/// source code.
478///
479/// \param Instantiation is the declaration whose definition is being
480/// instantiated. This will be either a class template specialization
481/// or a member class of a class template specialization.
482///
483/// \param Pattern is the pattern from which the instantiation
484/// occurs. This will be either the declaration of a class template or
485/// the declaration of a member class of a class template.
486///
487/// \param TemplateArgs The template arguments to be substituted into
488/// the pattern.
489///
Douglas Gregord475b8d2009-03-25 21:17:03 +0000490/// \returns true if an error occurred, false otherwise.
491bool
492Sema::InstantiateClass(SourceLocation PointOfInstantiation,
493 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor93dfdb12009-05-13 00:25:59 +0000494 const TemplateArgumentList &TemplateArgs,
495 bool ExplicitInstantiation) {
Douglas Gregord475b8d2009-03-25 21:17:03 +0000496 bool Invalid = false;
497
498 CXXRecordDecl *PatternDef
499 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
500 if (!PatternDef) {
501 if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
502 Diag(PointOfInstantiation,
503 diag::err_implicit_instantiate_member_undefined)
504 << Context.getTypeDeclType(Instantiation);
505 Diag(Pattern->getLocation(), diag::note_member_of_template_here);
506 } else {
Douglas Gregor93dfdb12009-05-13 00:25:59 +0000507 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
508 << ExplicitInstantiation
Douglas Gregord475b8d2009-03-25 21:17:03 +0000509 << Context.getTypeDeclType(Instantiation);
510 Diag(Pattern->getLocation(), diag::note_template_decl_here);
511 }
512 return true;
513 }
514 Pattern = PatternDef;
515
Douglas Gregord048bb72009-03-25 21:23:52 +0000516 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000517 if (Inst)
518 return true;
519
520 // Enter the scope of this instantiation. We don't use
521 // PushDeclContext because we don't have a scope.
522 DeclContext *PreviousContext = CurContext;
523 CurContext = Instantiation;
524
525 // Start the definition of this instantiation.
526 Instantiation->startDefinition();
527
528 // Instantiate the base class specifiers.
Douglas Gregor7e063902009-05-11 23:53:27 +0000529 if (InstantiateBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregord475b8d2009-03-25 21:17:03 +0000530 Invalid = true;
531
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000532 llvm::SmallVector<DeclPtrTy, 4> Fields;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000533 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
534 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000535 Member != MemberEnd; ++Member) {
Douglas Gregor7e063902009-05-11 23:53:27 +0000536 Decl *NewMember = InstantiateDecl(*Member, Instantiation, TemplateArgs);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000537 if (NewMember) {
538 if (NewMember->isInvalidDecl())
539 Invalid = true;
540 else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
Chris Lattnerb28317a2009-03-28 19:18:32 +0000541 Fields.push_back(DeclPtrTy::make(Field));
Douglas Gregord475b8d2009-03-25 21:17:03 +0000542 } else {
543 // FIXME: Eventually, a NULL return will mean that one of the
Mike Stump390b4cc2009-05-16 07:39:55 +0000544 // instantiations was a semantic disaster, and we'll want to set Invalid =
545 // true. For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +0000546 }
547 }
548
549 // Finish checking fields.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000550 ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
Jay Foadbeaaccd2009-05-21 09:52:38 +0000551 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
Douglas Gregord475b8d2009-03-25 21:17:03 +0000552 0);
553
554 // Add any implicitly-declared members that we might need.
555 AddImplicitlyDeclaredMembersToClass(Instantiation);
556
557 // Exit the scope of this instantiation.
558 CurContext = PreviousContext;
559
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000560 if (!Invalid)
561 Consumer.HandleTagDeclDefinition(Instantiation);
562
Douglas Gregora58861f2009-05-13 20:28:22 +0000563 // If this is an explicit instantiation, instantiate our members, too.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000564 if (!Invalid && ExplicitInstantiation) {
565 Inst.Clear();
Douglas Gregora58861f2009-05-13 20:28:22 +0000566 InstantiateClassMembers(PointOfInstantiation, Instantiation, TemplateArgs);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000567 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000568
Douglas Gregord475b8d2009-03-25 21:17:03 +0000569 return Invalid;
570}
571
Douglas Gregor2943aed2009-03-03 04:44:36 +0000572bool
573Sema::InstantiateClassTemplateSpecialization(
574 ClassTemplateSpecializationDecl *ClassTemplateSpec,
575 bool ExplicitInstantiation) {
576 // Perform the actual instantiation on the canonical declaration.
577 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000578 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +0000579
580 // We can only instantiate something that hasn't already been
581 // instantiated or specialized. Fail without any diagnostics: our
582 // caller will provide an error message.
583 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
584 return true;
585
Douglas Gregor2943aed2009-03-03 04:44:36 +0000586 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord475b8d2009-03-25 21:17:03 +0000587 CXXRecordDecl *Pattern = Template->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000588 const TemplateArgumentList *TemplateArgs
589 = &ClassTemplateSpec->getTemplateArgs();
590
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000591 // C++ [temp.class.spec.match]p1:
592 // When a class template is used in a context that requires an
593 // instantiation of the class, it is necessary to determine
594 // whether the instantiation is to be generated using the primary
595 // template or one of the partial specializations. This is done by
596 // matching the template arguments of the class template
597 // specialization with the template argument lists of the partial
598 // specializations.
Douglas Gregor199d9912009-06-05 00:53:49 +0000599 typedef std::pair<ClassTemplatePartialSpecializationDecl *,
600 TemplateArgumentList *> MatchResult;
601 llvm::SmallVector<MatchResult, 4> Matched;
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000602 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
603 Partial = Template->getPartialSpecializations().begin(),
604 PartialEnd = Template->getPartialSpecializations().end();
605 Partial != PartialEnd;
606 ++Partial) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000607 TemplateDeductionInfo Info(Context);
608 if (TemplateDeductionResult Result
Douglas Gregor199d9912009-06-05 00:53:49 +0000609 = DeduceTemplateArguments(&*Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000610 ClassTemplateSpec->getTemplateArgs(),
611 Info)) {
612 // FIXME: Store the failed-deduction information for use in
613 // diagnostics, later.
614 (void)Result;
615 } else {
616 Matched.push_back(std::make_pair(&*Partial, Info.take()));
617 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000618 }
619
620 if (Matched.size() == 1) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000621 // -- If exactly one matching specialization is found, the
622 // instantiation is generated from that specialization.
Douglas Gregor199d9912009-06-05 00:53:49 +0000623 Pattern = Matched[0].first;
624 TemplateArgs = Matched[0].second;
Douglas Gregor37d93e92009-08-02 23:24:31 +0000625 ClassTemplateSpec->setInstantiationOf(Matched[0].first, Matched[0].second);
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000626 } else if (Matched.size() > 1) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000627 // -- If more than one matching specialization is found, the
628 // partial order rules (14.5.4.2) are used to determine
629 // whether one of the specializations is more specialized
630 // than the others. If none of the specializations is more
631 // specialized than all of the other matching
632 // specializations, then the use of the class template is
633 // ambiguous and the program is ill-formed.
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000634 // FIXME: Implement partial ordering of class template partial
635 // specializations.
636 Diag(ClassTemplateSpec->getLocation(),
637 diag::unsup_template_partial_spec_ordering);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000638 } else {
639 // -- If no matches are found, the instantiation is generated
640 // from the primary template.
641
642 // Since we initialized the pattern and template arguments from
643 // the primary template, there is nothing more we need to do here.
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000644 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000645
646 // Note that this is an instantiation.
647 ClassTemplateSpec->setSpecializationKind(
648 ExplicitInstantiation? TSK_ExplicitInstantiation
649 : TSK_ImplicitInstantiation);
650
Douglas Gregor199d9912009-06-05 00:53:49 +0000651 bool Result = InstantiateClass(ClassTemplateSpec->getLocation(),
652 ClassTemplateSpec, Pattern, *TemplateArgs,
653 ExplicitInstantiation);
654
655 for (unsigned I = 0, N = Matched.size(); I != N; ++I) {
656 // FIXME: Implement TemplateArgumentList::Destroy!
657 // if (Matched[I].first != Pattern)
658 // Matched[I].second->Destroy(Context);
659 }
660
661 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000662}
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000663
Douglas Gregora58861f2009-05-13 20:28:22 +0000664/// \brief Instantiate the definitions of all of the member of the
665/// given class, which is an instantiation of a class template or a
666/// member class of a template.
667void
668Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
669 CXXRecordDecl *Instantiation,
670 const TemplateArgumentList &TemplateArgs) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000671 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
672 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +0000673 D != DEnd; ++D) {
674 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000675 if (!Function->getBody())
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000676 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Douglas Gregora58861f2009-05-13 20:28:22 +0000677 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000678 if (Var->isStaticDataMember())
679 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregora58861f2009-05-13 20:28:22 +0000680 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
681 if (!Record->isInjectedClassName() && !Record->getDefinition(Context)) {
682 assert(Record->getInstantiatedFromMemberClass() &&
683 "Missing instantiated-from-template information");
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000684 InstantiateClass(PointOfInstantiation, Record,
Douglas Gregora58861f2009-05-13 20:28:22 +0000685 Record->getInstantiatedFromMemberClass(),
686 TemplateArgs, true);
687 }
688 }
689 }
690}
691
692/// \brief Instantiate the definitions of all of the members of the
693/// given class template specialization, which was named as part of an
694/// explicit instantiation.
695void Sema::InstantiateClassTemplateSpecializationMembers(
696 SourceLocation PointOfInstantiation,
697 ClassTemplateSpecializationDecl *ClassTemplateSpec) {
698 // C++0x [temp.explicit]p7:
699 // An explicit instantiation that names a class template
700 // specialization is an explicit instantion of the same kind
701 // (declaration or definition) of each of its members (not
702 // including members inherited from base classes) that has not
703 // been previously explicitly specialized in the translation unit
704 // containing the explicit instantiation, except as described
705 // below.
706 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
707 ClassTemplateSpec->getTemplateArgs());
708}
709
Douglas Gregorab452ba2009-03-26 23:50:42 +0000710/// \brief Instantiate a nested-name-specifier.
711NestedNameSpecifier *
712Sema::InstantiateNestedNameSpecifier(NestedNameSpecifier *NNS,
713 SourceRange Range,
Douglas Gregor7e063902009-05-11 23:53:27 +0000714 const TemplateArgumentList &TemplateArgs) {
Douglas Gregordcee1a12009-08-06 05:28:30 +0000715 TemplateInstantiator Instantiator(*this, TemplateArgs, Range.getBegin(),
716 DeclarationName());
717 return Instantiator.TransformNestedNameSpecifier(NNS, Range);
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000718}
Douglas Gregorde650ae2009-03-31 18:38:02 +0000719
720TemplateName
721Sema::InstantiateTemplateName(TemplateName Name, SourceLocation Loc,
Douglas Gregor7e063902009-05-11 23:53:27 +0000722 const TemplateArgumentList &TemplateArgs) {
Douglas Gregorde650ae2009-03-31 18:38:02 +0000723 if (TemplateTemplateParmDecl *TTP
724 = dyn_cast_or_null<TemplateTemplateParmDecl>(
725 Name.getAsTemplateDecl())) {
726 assert(TTP->getDepth() == 0 &&
727 "Cannot reduce depth of a template template parameter");
Douglas Gregor9bde7732009-03-31 20:22:05 +0000728 assert(TemplateArgs[TTP->getPosition()].getAsDecl() &&
Douglas Gregorde650ae2009-03-31 18:38:02 +0000729 "Wrong kind of template template argument");
730 ClassTemplateDecl *ClassTemplate
731 = dyn_cast<ClassTemplateDecl>(
732 TemplateArgs[TTP->getPosition()].getAsDecl());
Douglas Gregor9bde7732009-03-31 20:22:05 +0000733 assert(ClassTemplate && "Expected a class template");
Douglas Gregorde650ae2009-03-31 18:38:02 +0000734 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
735 NestedNameSpecifier *NNS
736 = InstantiateNestedNameSpecifier(QTN->getQualifier(),
737 /*FIXME=*/SourceRange(Loc),
Douglas Gregor7e063902009-05-11 23:53:27 +0000738 TemplateArgs);
Douglas Gregorde650ae2009-03-31 18:38:02 +0000739 if (NNS)
740 return Context.getQualifiedTemplateName(NNS,
741 QTN->hasTemplateKeyword(),
742 ClassTemplate);
743 }
744
745 return TemplateName(ClassTemplate);
746 } else if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
747 NestedNameSpecifier *NNS
748 = InstantiateNestedNameSpecifier(DTN->getQualifier(),
749 /*FIXME=*/SourceRange(Loc),
Douglas Gregor7e063902009-05-11 23:53:27 +0000750 TemplateArgs);
Douglas Gregorde650ae2009-03-31 18:38:02 +0000751
752 if (!NNS) // FIXME: Not the best recovery strategy.
753 return Name;
754
755 if (NNS->isDependent())
756 return Context.getDependentTemplateName(NNS, DTN->getName());
757
758 // Somewhat redundant with ActOnDependentTemplateName.
759 CXXScopeSpec SS;
760 SS.setRange(SourceRange(Loc));
761 SS.setScopeRep(NNS);
762 TemplateTy Template;
763 TemplateNameKind TNK = isTemplateName(*DTN->getName(), 0, Template, &SS);
764 if (TNK == TNK_Non_template) {
765 Diag(Loc, diag::err_template_kw_refers_to_non_template)
766 << DTN->getName();
767 return Name;
768 } else if (TNK == TNK_Function_template) {
769 Diag(Loc, diag::err_template_kw_refers_to_non_template)
770 << DTN->getName();
771 return Name;
772 }
773
774 return Template.getAsVal<TemplateName>();
775 }
776
777
778
Mike Stump390b4cc2009-05-16 07:39:55 +0000779 // FIXME: Even if we're referring to a Decl that isn't a template template
780 // parameter, we may need to instantiate the outer contexts of that
781 // Decl. However, this won't be needed until we implement member templates.
Douglas Gregorde650ae2009-03-31 18:38:02 +0000782 return Name;
783}
Douglas Gregor91333002009-06-11 00:06:24 +0000784
785TemplateArgument Sema::Instantiate(TemplateArgument Arg,
786 const TemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +0000787 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
788 DeclarationName());
789 return Instantiator.TransformTemplateArgument(Arg);
Douglas Gregor91333002009-06-11 00:06:24 +0000790}