blob: 3bc1cf9504b8ccbc3f5f0f8915fe66e247303155 [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 Gregoraba43bb2009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/Expr.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000017#include "clang/AST/DeclTemplate.h"
18#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregorcd281c32009-02-28 00:25:32 +000020#include "llvm/Support/Compiler.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000021
22using namespace clang;
23
Douglas Gregoree1828a2009-03-10 18:03:33 +000024//===----------------------------------------------------------------------===/
25// Template Instantiation Support
26//===----------------------------------------------------------------------===/
27
Douglas Gregor54dabfc2009-05-14 23:26:13 +000028/// \brief Retrieve the template argument list that should be used to
29/// instantiate the given declaration.
30const TemplateArgumentList &
31Sema::getTemplateInstantiationArgs(NamedDecl *D) {
Douglas Gregor1637be72009-06-26 00:10:03 +000032 // Template arguments for a class template specialization.
Douglas Gregor54dabfc2009-05-14 23:26:13 +000033 if (ClassTemplateSpecializationDecl *Spec
34 = dyn_cast<ClassTemplateSpecializationDecl>(D))
35 return Spec->getTemplateArgs();
36
Douglas Gregor1637be72009-06-26 00:10:03 +000037 // Template arguments for a function template specialization.
38 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
39 if (const TemplateArgumentList *TemplateArgs
40 = Function->getTemplateSpecializationArgs())
41 return *TemplateArgs;
42
43 // Template arguments for a member of a class template specialization.
Douglas Gregor54dabfc2009-05-14 23:26:13 +000044 DeclContext *EnclosingTemplateCtx = D->getDeclContext();
45 while (!isa<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx)) {
46 assert(!EnclosingTemplateCtx->isFileContext() &&
47 "Tried to get the instantiation arguments of a non-template");
48 EnclosingTemplateCtx = EnclosingTemplateCtx->getParent();
49 }
50
51 ClassTemplateSpecializationDecl *EnclosingTemplate
52 = cast<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx);
53 return EnclosingTemplate->getTemplateArgs();
54}
55
Douglas Gregor26dce442009-03-10 00:06:19 +000056Sema::InstantiatingTemplate::
57InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +000058 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +000059 SourceRange InstantiationRange)
60 : SemaRef(SemaRef) {
Douglas Gregordf667e72009-03-10 20:44:00 +000061
62 Invalid = CheckInstantiationDepth(PointOfInstantiation,
63 InstantiationRange);
64 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +000065 ActiveTemplateInstantiation Inst;
Douglas Gregordf667e72009-03-10 20:44:00 +000066 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor26dce442009-03-10 00:06:19 +000067 Inst.PointOfInstantiation = PointOfInstantiation;
Douglas Gregordf667e72009-03-10 20:44:00 +000068 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
Douglas Gregor313a81d2009-03-12 18:36:18 +000069 Inst.TemplateArgs = 0;
70 Inst.NumTemplateArgs = 0;
Douglas Gregordf667e72009-03-10 20:44:00 +000071 Inst.InstantiationRange = InstantiationRange;
72 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
73 Invalid = false;
74 }
75}
76
77Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
78 SourceLocation PointOfInstantiation,
79 TemplateDecl *Template,
80 const TemplateArgument *TemplateArgs,
81 unsigned NumTemplateArgs,
82 SourceRange InstantiationRange)
83 : SemaRef(SemaRef) {
84
85 Invalid = CheckInstantiationDepth(PointOfInstantiation,
86 InstantiationRange);
87 if (!Invalid) {
88 ActiveTemplateInstantiation Inst;
89 Inst.Kind
90 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
91 Inst.PointOfInstantiation = PointOfInstantiation;
92 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
93 Inst.TemplateArgs = TemplateArgs;
94 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor26dce442009-03-10 00:06:19 +000095 Inst.InstantiationRange = InstantiationRange;
96 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
97 Invalid = false;
98 }
99}
100
Douglas Gregor637a4092009-06-10 23:47:09 +0000101Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
102 SourceLocation PointOfInstantiation,
103 ClassTemplatePartialSpecializationDecl *PartialSpec,
104 const TemplateArgument *TemplateArgs,
105 unsigned NumTemplateArgs,
106 SourceRange InstantiationRange)
107 : SemaRef(SemaRef) {
108
109 Invalid = CheckInstantiationDepth(PointOfInstantiation,
110 InstantiationRange);
111 if (!Invalid) {
112 ActiveTemplateInstantiation Inst;
113 Inst.Kind
114 = ActiveTemplateInstantiation::PartialSpecDeductionInstantiation;
115 Inst.PointOfInstantiation = PointOfInstantiation;
116 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
117 Inst.TemplateArgs = TemplateArgs;
118 Inst.NumTemplateArgs = NumTemplateArgs;
119 Inst.InstantiationRange = InstantiationRange;
120 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
121 Invalid = false;
122 }
123}
124
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000125void Sema::InstantiatingTemplate::Clear() {
126 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +0000127 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000128 Invalid = true;
129 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000130}
131
Douglas Gregordf667e72009-03-10 20:44:00 +0000132bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
133 SourceLocation PointOfInstantiation,
134 SourceRange InstantiationRange) {
135 if (SemaRef.ActiveTemplateInstantiations.size()
136 <= SemaRef.getLangOptions().InstantiationDepth)
137 return false;
138
139 SemaRef.Diag(PointOfInstantiation,
140 diag::err_template_recursion_depth_exceeded)
141 << SemaRef.getLangOptions().InstantiationDepth
142 << InstantiationRange;
143 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
144 << SemaRef.getLangOptions().InstantiationDepth;
145 return true;
146}
147
Douglas Gregoree1828a2009-03-10 18:03:33 +0000148/// \brief Prints the current instantiation stack through a series of
149/// notes.
150void Sema::PrintInstantiationStack() {
151 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
152 Active = ActiveTemplateInstantiations.rbegin(),
153 ActiveEnd = ActiveTemplateInstantiations.rend();
154 Active != ActiveEnd;
155 ++Active) {
Douglas Gregordf667e72009-03-10 20:44:00 +0000156 switch (Active->Kind) {
157 case ActiveTemplateInstantiation::TemplateInstantiation: {
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000158 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
159 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
160 unsigned DiagID = diag::note_template_member_class_here;
161 if (isa<ClassTemplateSpecializationDecl>(Record))
162 DiagID = diag::note_template_class_instantiation_here;
163 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
164 DiagID)
165 << Context.getTypeDeclType(Record)
166 << Active->InstantiationRange;
167 } else {
168 FunctionDecl *Function = cast<FunctionDecl>(D);
Douglas Gregor1637be72009-06-26 00:10:03 +0000169 unsigned DiagID;
170 if (Function->getPrimaryTemplate())
171 DiagID = diag::note_function_template_spec_here;
172 else
173 DiagID = diag::note_template_member_function_here;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000174 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
175 DiagID)
176 << Function
177 << Active->InstantiationRange;
178 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000179 break;
180 }
181
182 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
183 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
184 std::string TemplateArgsStr
Douglas Gregor7532dc62009-03-30 22:58:21 +0000185 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregordf667e72009-03-10 20:44:00 +0000186 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000187 Active->NumTemplateArgs,
188 Context.PrintingPolicy);
Douglas Gregordf667e72009-03-10 20:44:00 +0000189 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
190 diag::note_default_arg_instantiation_here)
191 << (Template->getNameAsString() + TemplateArgsStr)
192 << Active->InstantiationRange;
193 break;
194 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000195
196 case ActiveTemplateInstantiation::PartialSpecDeductionInstantiation: {
197 ClassTemplatePartialSpecializationDecl *PartialSpec
198 = cast<ClassTemplatePartialSpecializationDecl>((Decl *)Active->Entity);
Douglas Gregor637a4092009-06-10 23:47:09 +0000199 // FIXME: The active template instantiation's template arguments
200 // are interesting, too. We should add something like [with T =
201 // foo, U = bar, etc.] to the string.
202 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
203 diag::note_partial_spec_deduct_instantiation_here)
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000204 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor637a4092009-06-10 23:47:09 +0000205 << Active->InstantiationRange;
206 break;
207 }
208
Douglas Gregordf667e72009-03-10 20:44:00 +0000209 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000210 }
211}
212
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000213bool Sema::isSFINAEContext() const {
214 using llvm::SmallVector;
215 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
216 Active = ActiveTemplateInstantiations.rbegin(),
217 ActiveEnd = ActiveTemplateInstantiations.rend();
218 Active != ActiveEnd;
219 ++Active) {
220
221 switch(Active->Kind) {
222 case ActiveTemplateInstantiation::PartialSpecDeductionInstantiation:
223 // We're in a template argument deduction context, so SFINAE
224 // applies.
225 return true;
226
227 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
228 // A default template argument instantiation may or may not be a
229 // SFINAE context; look further up the stack.
230 break;
231
232 case ActiveTemplateInstantiation::TemplateInstantiation:
233 // This is a template instantiation, so there is no SFINAE.
234 return false;
235 }
236 }
237
238 return false;
239}
240
Douglas Gregor99ebf652009-02-27 19:31:52 +0000241//===----------------------------------------------------------------------===/
242// Template Instantiation for Types
243//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000244namespace {
245 class VISIBILITY_HIDDEN TemplateTypeInstantiator {
246 Sema &SemaRef;
Douglas Gregor7e063902009-05-11 23:53:27 +0000247 const TemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000248 SourceLocation Loc;
249 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000250
Douglas Gregorcd281c32009-02-28 00:25:32 +0000251 public:
252 TemplateTypeInstantiator(Sema &SemaRef,
Douglas Gregor7e063902009-05-11 23:53:27 +0000253 const TemplateArgumentList &TemplateArgs,
Douglas Gregorcd281c32009-02-28 00:25:32 +0000254 SourceLocation Loc,
255 DeclarationName Entity)
256 : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
Douglas Gregor7e063902009-05-11 23:53:27 +0000257 Loc(Loc), Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000258
259 QualType operator()(QualType T) const { return Instantiate(T); }
260
261 QualType Instantiate(QualType T) const;
262
263 // Declare instantiate functions for each type.
264#define TYPE(Class, Base) \
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000265 QualType Instantiate##Class##Type(const Class##Type *T) const;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000266#define ABSTRACT_TYPE(Class, Base)
267#include "clang/AST/TypeNodes.def"
268 };
269}
270
271QualType
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000272TemplateTypeInstantiator::InstantiateExtQualType(const ExtQualType *T) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000273 // FIXME: Implement this
274 assert(false && "Cannot instantiate ExtQualType yet");
275 return QualType();
276}
277
Douglas Gregorcd281c32009-02-28 00:25:32 +0000278QualType
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000279TemplateTypeInstantiator::InstantiateBuiltinType(const BuiltinType *T) const {
Douglas Gregor724651c2009-02-28 01:04:19 +0000280 assert(false && "Builtin types are not dependent and cannot be instantiated");
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000281 return QualType(T, 0);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000282}
283
Douglas Gregorcd281c32009-02-28 00:25:32 +0000284QualType
285TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000286InstantiateFixedWidthIntType(const FixedWidthIntType *T) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000287 // FIXME: Implement this
288 assert(false && "Cannot instantiate FixedWidthIntType yet");
289 return QualType();
290}
291
Douglas Gregorcd281c32009-02-28 00:25:32 +0000292QualType
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000293TemplateTypeInstantiator::InstantiateComplexType(const ComplexType *T) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000294 // FIXME: Implement this
295 assert(false && "Cannot instantiate ComplexType yet");
296 return QualType();
297}
298
Douglas Gregorcd281c32009-02-28 00:25:32 +0000299QualType
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000300TemplateTypeInstantiator::InstantiatePointerType(const PointerType *T) const {
Douglas Gregorcd281c32009-02-28 00:25:32 +0000301 QualType PointeeType = Instantiate(T->getPointeeType());
302 if (PointeeType.isNull())
303 return QualType();
304
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000305 return SemaRef.BuildPointerType(PointeeType, 0, Loc, Entity);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000306}
307
Douglas Gregorcd281c32009-02-28 00:25:32 +0000308QualType
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000309TemplateTypeInstantiator::InstantiateBlockPointerType(
310 const BlockPointerType *T) const {
Anders Carlsson859ba502009-06-12 16:23:10 +0000311 QualType PointeeType = Instantiate(T->getPointeeType());
312 if (PointeeType.isNull())
313 return QualType();
314
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000315 return SemaRef.BuildBlockPointerType(PointeeType, 0, Loc, Entity);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000316}
317
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000318QualType
319TemplateTypeInstantiator::InstantiateLValueReferenceType(
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000320 const LValueReferenceType *T) const {
Douglas Gregorcd281c32009-02-28 00:25:32 +0000321 QualType ReferentType = Instantiate(T->getPointeeType());
322 if (ReferentType.isNull())
323 return QualType();
324
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000325 return SemaRef.BuildReferenceType(ReferentType, true, 0, Loc, Entity);
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000326}
327
328QualType
329TemplateTypeInstantiator::InstantiateRValueReferenceType(
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000330 const RValueReferenceType *T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000331 QualType ReferentType = Instantiate(T->getPointeeType());
332 if (ReferentType.isNull())
333 return QualType();
334
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000335 return SemaRef.BuildReferenceType(ReferentType, false, 0, Loc, Entity);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000336}
337
Douglas Gregorcd281c32009-02-28 00:25:32 +0000338QualType
339TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000340InstantiateMemberPointerType(const MemberPointerType *T) const {
Douglas Gregor949bf692009-06-09 22:17:39 +0000341 QualType PointeeType = Instantiate(T->getPointeeType());
342 if (PointeeType.isNull())
343 return QualType();
344
345 QualType ClassType = Instantiate(QualType(T->getClass(), 0));
346 if (ClassType.isNull())
347 return QualType();
348
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000349 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, 0, Loc,
Douglas Gregor949bf692009-06-09 22:17:39 +0000350 Entity);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000351}
352
Douglas Gregorcd281c32009-02-28 00:25:32 +0000353QualType
354TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000355InstantiateConstantArrayType(const ConstantArrayType *T) const {
Douglas Gregorcd281c32009-02-28 00:25:32 +0000356 QualType ElementType = Instantiate(T->getElementType());
357 if (ElementType.isNull())
358 return ElementType;
359
360 // Build a temporary integer literal to specify the size for
361 // BuildArrayType. Since we have already checked the size as part of
362 // creating the dependent array type in the first place, we know
Douglas Gregorff668032009-05-13 18:28:20 +0000363 // there aren't any errors. However, we do need to determine what
364 // C++ type to give the size expression.
365 llvm::APInt Size = T->getSize();
366 QualType Types[] = {
367 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
368 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
369 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
370 };
371 const unsigned NumTypes = sizeof(Types) / sizeof(QualType);
372 QualType SizeType;
373 for (unsigned I = 0; I != NumTypes; ++I)
374 if (Size.getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
375 SizeType = Types[I];
376 break;
377 }
378
379 if (SizeType.isNull())
380 SizeType = SemaRef.Context.getFixedWidthIntType(Size.getBitWidth(), false);
381
382 IntegerLiteral ArraySize(Size, SizeType, Loc);
Douglas Gregorcd281c32009-02-28 00:25:32 +0000383 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
384 &ArraySize, T->getIndexTypeQualifier(),
385 Loc, Entity);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000386}
387
Douglas Gregorcd281c32009-02-28 00:25:32 +0000388QualType
389TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000390InstantiateIncompleteArrayType(const IncompleteArrayType *T) const {
Douglas Gregorcd281c32009-02-28 00:25:32 +0000391 QualType ElementType = Instantiate(T->getElementType());
392 if (ElementType.isNull())
393 return ElementType;
394
395 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
396 0, T->getIndexTypeQualifier(),
397 Loc, Entity);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000398}
399
Douglas Gregorcd281c32009-02-28 00:25:32 +0000400QualType
401TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000402InstantiateVariableArrayType(const VariableArrayType *T) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000403 // FIXME: Implement this
404 assert(false && "Cannot instantiate VariableArrayType yet");
405 return QualType();
406}
407
Douglas Gregorcd281c32009-02-28 00:25:32 +0000408QualType
409TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000410InstantiateDependentSizedArrayType(const DependentSizedArrayType *T) const {
Anders Carlsson76b1c842009-03-15 20:12:13 +0000411 Expr *ArraySize = T->getSizeExpr();
412 assert(ArraySize->isValueDependent() &&
413 "dependent sized array types must have value dependent size expr");
414
415 // Instantiate the element type if needed
416 QualType ElementType = T->getElementType();
417 if (ElementType->isDependentType()) {
418 ElementType = Instantiate(ElementType);
419 if (ElementType.isNull())
420 return QualType();
421 }
422
423 // Instantiate the size expression
Douglas Gregorac7610d2009-06-22 20:57:11 +0000424 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Anders Carlsson76b1c842009-03-15 20:12:13 +0000425 Sema::OwningExprResult InstantiatedArraySize =
Douglas Gregor7e063902009-05-11 23:53:27 +0000426 SemaRef.InstantiateExpr(ArraySize, TemplateArgs);
Anders Carlsson76b1c842009-03-15 20:12:13 +0000427 if (InstantiatedArraySize.isInvalid())
428 return QualType();
429
430 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
Anders Carlssone9146f22009-05-01 19:49:17 +0000431 InstantiatedArraySize.takeAs<Expr>(),
Anders Carlsson76b1c842009-03-15 20:12:13 +0000432 T->getIndexTypeQualifier(), Loc, Entity);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000433}
434
Douglas Gregorcd281c32009-02-28 00:25:32 +0000435QualType
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000436TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000437InstantiateDependentSizedExtVectorType(
438 const DependentSizedExtVectorType *T) const {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000439
Douglas Gregorf6ddb732009-06-18 18:45:36 +0000440 // Instantiate the element type if needed.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000441 QualType ElementType = T->getElementType();
442 if (ElementType->isDependentType()) {
443 ElementType = Instantiate(ElementType);
444 if (ElementType.isNull())
445 return QualType();
446 }
447
Douglas Gregorac7610d2009-06-22 20:57:11 +0000448 // The expression in a dependent-sized extended vector type is not
449 // potentially evaluated.
450 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
451
Douglas Gregorf6ddb732009-06-18 18:45:36 +0000452 // Instantiate the size expression.
453 const Expr *SizeExpr = T->getSizeExpr();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000454 Sema::OwningExprResult InstantiatedArraySize =
Douglas Gregorf6ddb732009-06-18 18:45:36 +0000455 SemaRef.InstantiateExpr(const_cast<Expr *>(SizeExpr), TemplateArgs);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000456 if (InstantiatedArraySize.isInvalid())
457 return QualType();
458
459 return SemaRef.BuildExtVectorType(ElementType,
460 SemaRef.Owned(
461 InstantiatedArraySize.takeAs<Expr>()),
462 T->getAttributeLoc());
463}
464
465QualType
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000466TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000467 // FIXME: Implement this
468 assert(false && "Cannot instantiate VectorType yet");
469 return QualType();
470}
471
Douglas Gregorcd281c32009-02-28 00:25:32 +0000472QualType
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000473TemplateTypeInstantiator::InstantiateExtVectorType(
474 const ExtVectorType *T) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000475 // FIXME: Implement this
476 assert(false && "Cannot instantiate ExtVectorType yet");
477 return QualType();
478}
479
Douglas Gregorcd281c32009-02-28 00:25:32 +0000480QualType
481TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000482InstantiateFunctionProtoType(const FunctionProtoType *T) const {
Douglas Gregor724651c2009-02-28 01:04:19 +0000483 QualType ResultType = Instantiate(T->getResultType());
484 if (ResultType.isNull())
485 return ResultType;
486
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000487 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor724651c2009-02-28 01:04:19 +0000488 for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(),
489 ParamEnd = T->arg_type_end();
490 Param != ParamEnd; ++Param) {
491 QualType P = Instantiate(*Param);
492 if (P.isNull())
493 return P;
494
495 ParamTypes.push_back(P);
496 }
497
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000498 return SemaRef.BuildFunctionType(ResultType, ParamTypes.data(),
Douglas Gregor724651c2009-02-28 01:04:19 +0000499 ParamTypes.size(),
500 T->isVariadic(), T->getTypeQuals(),
501 Loc, Entity);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000502}
503
Douglas Gregorcd281c32009-02-28 00:25:32 +0000504QualType
505TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000506InstantiateFunctionNoProtoType(const FunctionNoProtoType *T) const {
Douglas Gregor724651c2009-02-28 01:04:19 +0000507 assert(false && "Functions without prototypes cannot be dependent.");
Douglas Gregor99ebf652009-02-27 19:31:52 +0000508 return QualType();
509}
510
Douglas Gregorcd281c32009-02-28 00:25:32 +0000511QualType
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000512TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T) const {
Douglas Gregor815215d2009-05-27 05:35:12 +0000513 TypedefDecl *Typedef
Douglas Gregored961e72009-05-27 17:54:46 +0000514 = cast_or_null<TypedefDecl>(
515 SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
Douglas Gregor815215d2009-05-27 05:35:12 +0000516 if (!Typedef)
517 return QualType();
518
519 return SemaRef.Context.getTypeDeclType(Typedef);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000520}
521
Douglas Gregorcd281c32009-02-28 00:25:32 +0000522QualType
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000523TemplateTypeInstantiator::InstantiateTypeOfExprType(
524 const TypeOfExprType *T) const {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000525 // The expression in a typeof is not potentially evaluated.
526 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
527
Douglas Gregor5f8bd592009-05-26 22:09:24 +0000528 Sema::OwningExprResult E
529 = SemaRef.InstantiateExpr(T->getUnderlyingExpr(), TemplateArgs);
530 if (E.isInvalid())
531 return QualType();
532
Anders Carlssonaf017e62009-06-29 22:58:55 +0000533 return SemaRef.BuildTypeofExprType(E.takeAs<Expr>());
Douglas Gregor99ebf652009-02-27 19:31:52 +0000534}
535
Douglas Gregorcd281c32009-02-28 00:25:32 +0000536QualType
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000537TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T) const {
Douglas Gregor5f8bd592009-05-26 22:09:24 +0000538 QualType Underlying = Instantiate(T->getUnderlyingType());
539 if (Underlying.isNull())
540 return QualType();
541
542 return SemaRef.Context.getTypeOfType(Underlying);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000543}
544
Anders Carlsson395b4752009-06-24 19:06:50 +0000545QualType
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000546TemplateTypeInstantiator::InstantiateDecltypeType(const DecltypeType *T) const {
Anders Carlsson87471f52009-06-26 03:02:18 +0000547 // C++0x [dcl.type.simple]p4:
548 // The operand of the decltype specifier is an unevaluated operand.
549 EnterExpressionEvaluationContext Unevaluated(SemaRef,
550 Action::Unevaluated);
551
Anders Carlsson395b4752009-06-24 19:06:50 +0000552 Sema::OwningExprResult E
553 = SemaRef.InstantiateExpr(T->getUnderlyingExpr(), TemplateArgs);
554
555 if (E.isInvalid())
556 return QualType();
557
Anders Carlssonaf017e62009-06-29 22:58:55 +0000558 return SemaRef.BuildDecltypeType(E.takeAs<Expr>());
Anders Carlsson395b4752009-06-24 19:06:50 +0000559}
560
Douglas Gregorcd281c32009-02-28 00:25:32 +0000561QualType
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000562TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T) const {
Douglas Gregor815215d2009-05-27 05:35:12 +0000563 RecordDecl *Record
Douglas Gregored961e72009-05-27 17:54:46 +0000564 = cast_or_null<RecordDecl>(SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
Douglas Gregor815215d2009-05-27 05:35:12 +0000565 if (!Record)
566 return QualType();
567
568 return SemaRef.Context.getTypeDeclType(Record);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000569}
570
Douglas Gregorcd281c32009-02-28 00:25:32 +0000571QualType
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000572TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T) const {
Douglas Gregor815215d2009-05-27 05:35:12 +0000573 EnumDecl *Enum
Douglas Gregored961e72009-05-27 17:54:46 +0000574 = cast_or_null<EnumDecl>(SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
Douglas Gregor815215d2009-05-27 05:35:12 +0000575 if (!Enum)
576 return QualType();
577
578 return SemaRef.Context.getTypeDeclType(Enum);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000579}
580
Douglas Gregorcd281c32009-02-28 00:25:32 +0000581QualType
582TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000583InstantiateTemplateTypeParmType(const TemplateTypeParmType *T) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000584 if (T->getDepth() == 0) {
585 // Replace the template type parameter with its corresponding
586 // template argument.
Douglas Gregor16134c62009-07-01 00:28:38 +0000587
588 // If the corresponding template argument is NULL or doesn't exist, it's
589 // because we are performing instantiation from explicitly-specified
590 // template arguments in a function template class, but there were some
591 // arguments left unspecified.
592 if (T->getIndex() >= TemplateArgs.size() ||
593 TemplateArgs[T->getIndex()].isNull())
594 return QualType(T, 0); // Would be nice to keep the original type here
595
Douglas Gregor99ebf652009-02-27 19:31:52 +0000596 assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
597 "Template argument kind mismatch");
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000598 return TemplateArgs[T->getIndex()].getAsType();
Douglas Gregor99ebf652009-02-27 19:31:52 +0000599 }
600
601 // The template type parameter comes from an inner template (e.g.,
602 // the template parameter list of a member template inside the
603 // template we are instantiating). Create a new template type
604 // parameter with the template "level" reduced by one.
605 return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1,
606 T->getIndex(),
Anders Carlsson76e4ce42009-06-16 00:30:48 +0000607 T->isParameterPack(),
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000608 T->getName());
Douglas Gregor99ebf652009-02-27 19:31:52 +0000609}
610
Douglas Gregorcd281c32009-02-28 00:25:32 +0000611QualType
612TemplateTypeInstantiator::
Douglas Gregor7532dc62009-03-30 22:58:21 +0000613InstantiateTemplateSpecializationType(
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000614 const TemplateSpecializationType *T) const {
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000615 llvm::SmallVector<TemplateArgument, 4> InstantiatedTemplateArgs;
Douglas Gregor40808ce2009-03-09 23:48:35 +0000616 InstantiatedTemplateArgs.reserve(T->getNumArgs());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000617 for (TemplateSpecializationType::iterator Arg = T->begin(), ArgEnd = T->end();
Douglas Gregor40808ce2009-03-09 23:48:35 +0000618 Arg != ArgEnd; ++Arg) {
Douglas Gregor91333002009-06-11 00:06:24 +0000619 TemplateArgument InstArg = SemaRef.Instantiate(*Arg, TemplateArgs);
620 if (InstArg.isNull())
621 return QualType();
Douglas Gregor40808ce2009-03-09 23:48:35 +0000622
Douglas Gregor91333002009-06-11 00:06:24 +0000623 InstantiatedTemplateArgs.push_back(InstArg);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000624 }
625
Mike Stump390b4cc2009-05-16 07:39:55 +0000626 // FIXME: We're missing the locations of the template name, '<', and '>'.
Douglas Gregorde650ae2009-03-31 18:38:02 +0000627
628 TemplateName Name = SemaRef.InstantiateTemplateName(T->getTemplateName(),
629 Loc,
Douglas Gregor7e063902009-05-11 23:53:27 +0000630 TemplateArgs);
Douglas Gregorde650ae2009-03-31 18:38:02 +0000631
632 return SemaRef.CheckTemplateIdType(Name, Loc, SourceLocation(),
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000633 InstantiatedTemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +0000634 InstantiatedTemplateArgs.size(),
635 SourceLocation());
Douglas Gregor99ebf652009-02-27 19:31:52 +0000636}
637
Douglas Gregorcd281c32009-02-28 00:25:32 +0000638QualType
639TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000640InstantiateQualifiedNameType(const QualifiedNameType *T) const {
Douglas Gregord57959a2009-03-27 23:10:48 +0000641 // When we instantiated a qualified name type, there's no point in
642 // keeping the qualification around in the instantiated result. So,
643 // just instantiate the named type.
644 return (*this)(T->getNamedType());
645}
646
647QualType
648TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000649InstantiateTypenameType(const TypenameType *T) const {
Douglas Gregor17343172009-04-01 00:28:59 +0000650 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
651 // When the typename type refers to a template-id, the template-id
652 // is dependent and has enough information to instantiate the
653 // result of the typename type. Since we don't care about keeping
654 // the spelling of the typename type in template instantiations,
655 // we just instantiate the template-id.
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000656 return InstantiateTemplateSpecializationType(TemplateId);
Douglas Gregor17343172009-04-01 00:28:59 +0000657 }
658
Douglas Gregord57959a2009-03-27 23:10:48 +0000659 NestedNameSpecifier *NNS
660 = SemaRef.InstantiateNestedNameSpecifier(T->getQualifier(),
661 SourceRange(Loc),
Douglas Gregor7e063902009-05-11 23:53:27 +0000662 TemplateArgs);
Douglas Gregord57959a2009-03-27 23:10:48 +0000663 if (!NNS)
664 return QualType();
665
Douglas Gregor17343172009-04-01 00:28:59 +0000666 return SemaRef.CheckTypenameType(NNS, *T->getIdentifier(), SourceRange(Loc));
Douglas Gregore4e5b052009-03-19 00:18:19 +0000667}
668
669QualType
670TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000671InstantiateObjCObjectPointerType(const ObjCObjectPointerType *T) const {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000672 assert(false && "Objective-C types cannot be dependent");
673 return QualType();
674}
675
676QualType
677TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000678InstantiateObjCInterfaceType(const ObjCInterfaceType *T) const {
Douglas Gregorcd281c32009-02-28 00:25:32 +0000679 assert(false && "Objective-C types cannot be dependent");
Douglas Gregor99ebf652009-02-27 19:31:52 +0000680 return QualType();
681}
682
Douglas Gregorcd281c32009-02-28 00:25:32 +0000683QualType
684TemplateTypeInstantiator::
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000685InstantiateObjCQualifiedInterfaceType(
686 const ObjCQualifiedInterfaceType *T) const {
Douglas Gregorcd281c32009-02-28 00:25:32 +0000687 assert(false && "Objective-C types cannot be dependent");
Douglas Gregor99ebf652009-02-27 19:31:52 +0000688 return QualType();
689}
690
Douglas Gregorcd281c32009-02-28 00:25:32 +0000691/// \brief The actual implementation of Sema::InstantiateType().
692QualType TemplateTypeInstantiator::Instantiate(QualType T) const {
693 // If T is not a dependent type, there is nothing to do.
694 if (!T->isDependentType())
695 return T;
696
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000697 QualType Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000698 switch (T->getTypeClass()) {
699#define TYPE(Class, Base) \
700 case Type::Class: \
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000701 Result = Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr())); \
702 break;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000703#define ABSTRACT_TYPE(Class, Base)
704#include "clang/AST/TypeNodes.def"
705 }
Douglas Gregor8a5cb112009-06-26 21:40:05 +0000706
707 // C++ [dcl.ref]p1:
708 // [...] Cv-qualified references are ill-formed except when
709 // the cv-qualifiers are introduced through the use of a
710 // typedef (7.1.3) or of a template type argument (14.3), in
711 // which case the cv-qualifiers are ignored.
712 //
713 // The same rule applies to function types.
714 if (!Result.isNull() && T.getCVRQualifiers() &&
715 !Result->isFunctionType() && !Result->isReferenceType())
716 Result = Result.getWithAdditionalQualifiers(T.getCVRQualifiers());
717 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000718}
Douglas Gregor99ebf652009-02-27 19:31:52 +0000719
720/// \brief Instantiate the type T with a given set of template arguments.
721///
722/// This routine substitutes the given template arguments into the
723/// type T and produces the instantiated type.
724///
725/// \param T the type into which the template arguments will be
726/// substituted. If this type is not dependent, it will be returned
727/// immediately.
728///
729/// \param TemplateArgs the template arguments that will be
730/// substituted for the top-level template parameters within T.
731///
Douglas Gregor99ebf652009-02-27 19:31:52 +0000732/// \param Loc the location in the source code where this substitution
733/// is being performed. It will typically be the location of the
734/// declarator (if we're instantiating the type of some declaration)
735/// or the location of the type in the source code (if, e.g., we're
736/// instantiating the type of a cast expression).
737///
738/// \param Entity the name of the entity associated with a declaration
739/// being instantiated (if any). May be empty to indicate that there
740/// is no such entity (if, e.g., this is a type that occurs as part of
741/// a cast expression) or that the entity has no name (e.g., an
742/// unnamed function parameter).
743///
744/// \returns If the instantiation succeeds, the instantiated
745/// type. Otherwise, produces diagnostics and returns a NULL type.
746QualType Sema::InstantiateType(QualType T,
Douglas Gregor7e063902009-05-11 23:53:27 +0000747 const TemplateArgumentList &TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +0000748 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +0000749 assert(!ActiveTemplateInstantiations.empty() &&
750 "Cannot perform an instantiation without some context on the "
751 "instantiation stack");
752
Douglas Gregor99ebf652009-02-27 19:31:52 +0000753 // If T is not a dependent type, there is nothing to do.
754 if (!T->isDependentType())
755 return T;
756
Douglas Gregor7e063902009-05-11 23:53:27 +0000757 TemplateTypeInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
Douglas Gregorcd281c32009-02-28 00:25:32 +0000758 return Instantiator(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000759}
Douglas Gregor2943aed2009-03-03 04:44:36 +0000760
761/// \brief Instantiate the base class specifiers of the given class
762/// template specialization.
763///
764/// Produces a diagnostic and returns true on error, returns false and
765/// attaches the instantiated base classes to the class template
766/// specialization if successful.
767bool
Douglas Gregord475b8d2009-03-25 21:17:03 +0000768Sema::InstantiateBaseSpecifiers(CXXRecordDecl *Instantiation,
769 CXXRecordDecl *Pattern,
Douglas Gregor7e063902009-05-11 23:53:27 +0000770 const TemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000771 bool Invalid = false;
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000772 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Douglas Gregord475b8d2009-03-25 21:17:03 +0000773 for (ClassTemplateSpecializationDecl::base_class_iterator
774 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +0000775 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000776 if (!Base->getType()->isDependentType()) {
777 // FIXME: Allocate via ASTContext
778 InstantiatedBases.push_back(new CXXBaseSpecifier(*Base));
779 continue;
780 }
781
782 QualType BaseType = InstantiateType(Base->getType(),
Douglas Gregor7e063902009-05-11 23:53:27 +0000783 TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000784 Base->getSourceRange().getBegin(),
785 DeclarationName());
786 if (BaseType.isNull()) {
787 Invalid = true;
788 continue;
789 }
790
791 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +0000792 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000793 Base->getSourceRange(),
794 Base->isVirtual(),
795 Base->getAccessSpecifierAsWritten(),
796 BaseType,
797 /*FIXME: Not totally accurate */
798 Base->getSourceRange().getBegin()))
799 InstantiatedBases.push_back(InstantiatedBase);
800 else
801 Invalid = true;
802 }
803
Douglas Gregor27b152f2009-03-10 18:52:44 +0000804 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +0000805 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000806 InstantiatedBases.size()))
807 Invalid = true;
808
809 return Invalid;
810}
811
Douglas Gregord475b8d2009-03-25 21:17:03 +0000812/// \brief Instantiate the definition of a class from a given pattern.
813///
814/// \param PointOfInstantiation The point of instantiation within the
815/// source code.
816///
817/// \param Instantiation is the declaration whose definition is being
818/// instantiated. This will be either a class template specialization
819/// or a member class of a class template specialization.
820///
821/// \param Pattern is the pattern from which the instantiation
822/// occurs. This will be either the declaration of a class template or
823/// the declaration of a member class of a class template.
824///
825/// \param TemplateArgs The template arguments to be substituted into
826/// the pattern.
827///
Douglas Gregord475b8d2009-03-25 21:17:03 +0000828/// \returns true if an error occurred, false otherwise.
829bool
830Sema::InstantiateClass(SourceLocation PointOfInstantiation,
831 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor93dfdb12009-05-13 00:25:59 +0000832 const TemplateArgumentList &TemplateArgs,
833 bool ExplicitInstantiation) {
Douglas Gregord475b8d2009-03-25 21:17:03 +0000834 bool Invalid = false;
835
836 CXXRecordDecl *PatternDef
837 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
838 if (!PatternDef) {
839 if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
840 Diag(PointOfInstantiation,
841 diag::err_implicit_instantiate_member_undefined)
842 << Context.getTypeDeclType(Instantiation);
843 Diag(Pattern->getLocation(), diag::note_member_of_template_here);
844 } else {
Douglas Gregor93dfdb12009-05-13 00:25:59 +0000845 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
846 << ExplicitInstantiation
Douglas Gregord475b8d2009-03-25 21:17:03 +0000847 << Context.getTypeDeclType(Instantiation);
848 Diag(Pattern->getLocation(), diag::note_template_decl_here);
849 }
850 return true;
851 }
852 Pattern = PatternDef;
853
Douglas Gregord048bb72009-03-25 21:23:52 +0000854 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000855 if (Inst)
856 return true;
857
858 // Enter the scope of this instantiation. We don't use
859 // PushDeclContext because we don't have a scope.
860 DeclContext *PreviousContext = CurContext;
861 CurContext = Instantiation;
862
863 // Start the definition of this instantiation.
864 Instantiation->startDefinition();
865
866 // Instantiate the base class specifiers.
Douglas Gregor7e063902009-05-11 23:53:27 +0000867 if (InstantiateBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregord475b8d2009-03-25 21:17:03 +0000868 Invalid = true;
869
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000870 llvm::SmallVector<DeclPtrTy, 4> Fields;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000871 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
872 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000873 Member != MemberEnd; ++Member) {
Douglas Gregor7e063902009-05-11 23:53:27 +0000874 Decl *NewMember = InstantiateDecl(*Member, Instantiation, TemplateArgs);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000875 if (NewMember) {
876 if (NewMember->isInvalidDecl())
877 Invalid = true;
878 else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
Chris Lattnerb28317a2009-03-28 19:18:32 +0000879 Fields.push_back(DeclPtrTy::make(Field));
Douglas Gregord475b8d2009-03-25 21:17:03 +0000880 } else {
881 // FIXME: Eventually, a NULL return will mean that one of the
Mike Stump390b4cc2009-05-16 07:39:55 +0000882 // instantiations was a semantic disaster, and we'll want to set Invalid =
883 // true. For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +0000884 }
885 }
886
887 // Finish checking fields.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000888 ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
Jay Foadbeaaccd2009-05-21 09:52:38 +0000889 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
Douglas Gregord475b8d2009-03-25 21:17:03 +0000890 0);
891
892 // Add any implicitly-declared members that we might need.
893 AddImplicitlyDeclaredMembersToClass(Instantiation);
894
895 // Exit the scope of this instantiation.
896 CurContext = PreviousContext;
897
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000898 if (!Invalid)
899 Consumer.HandleTagDeclDefinition(Instantiation);
900
Douglas Gregora58861f2009-05-13 20:28:22 +0000901 // If this is an explicit instantiation, instantiate our members, too.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000902 if (!Invalid && ExplicitInstantiation) {
903 Inst.Clear();
Douglas Gregora58861f2009-05-13 20:28:22 +0000904 InstantiateClassMembers(PointOfInstantiation, Instantiation, TemplateArgs);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000905 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000906
Douglas Gregord475b8d2009-03-25 21:17:03 +0000907 return Invalid;
908}
909
Douglas Gregor2943aed2009-03-03 04:44:36 +0000910bool
911Sema::InstantiateClassTemplateSpecialization(
912 ClassTemplateSpecializationDecl *ClassTemplateSpec,
913 bool ExplicitInstantiation) {
914 // Perform the actual instantiation on the canonical declaration.
915 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
916 Context.getCanonicalDecl(ClassTemplateSpec));
917
918 // We can only instantiate something that hasn't already been
919 // instantiated or specialized. Fail without any diagnostics: our
920 // caller will provide an error message.
921 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
922 return true;
923
Douglas Gregor2943aed2009-03-03 04:44:36 +0000924 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord475b8d2009-03-25 21:17:03 +0000925 CXXRecordDecl *Pattern = Template->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000926 const TemplateArgumentList *TemplateArgs
927 = &ClassTemplateSpec->getTemplateArgs();
928
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000929 // C++ [temp.class.spec.match]p1:
930 // When a class template is used in a context that requires an
931 // instantiation of the class, it is necessary to determine
932 // whether the instantiation is to be generated using the primary
933 // template or one of the partial specializations. This is done by
934 // matching the template arguments of the class template
935 // specialization with the template argument lists of the partial
936 // specializations.
Douglas Gregor199d9912009-06-05 00:53:49 +0000937 typedef std::pair<ClassTemplatePartialSpecializationDecl *,
938 TemplateArgumentList *> MatchResult;
939 llvm::SmallVector<MatchResult, 4> Matched;
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000940 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
941 Partial = Template->getPartialSpecializations().begin(),
942 PartialEnd = Template->getPartialSpecializations().end();
943 Partial != PartialEnd;
944 ++Partial) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000945 TemplateDeductionInfo Info(Context);
946 if (TemplateDeductionResult Result
Douglas Gregor199d9912009-06-05 00:53:49 +0000947 = DeduceTemplateArguments(&*Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000948 ClassTemplateSpec->getTemplateArgs(),
949 Info)) {
950 // FIXME: Store the failed-deduction information for use in
951 // diagnostics, later.
952 (void)Result;
953 } else {
954 Matched.push_back(std::make_pair(&*Partial, Info.take()));
955 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000956 }
957
958 if (Matched.size() == 1) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000959 // -- If exactly one matching specialization is found, the
960 // instantiation is generated from that specialization.
Douglas Gregor199d9912009-06-05 00:53:49 +0000961 Pattern = Matched[0].first;
962 TemplateArgs = Matched[0].second;
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000963 } else if (Matched.size() > 1) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000964 // -- If more than one matching specialization is found, the
965 // partial order rules (14.5.4.2) are used to determine
966 // whether one of the specializations is more specialized
967 // than the others. If none of the specializations is more
968 // specialized than all of the other matching
969 // specializations, then the use of the class template is
970 // ambiguous and the program is ill-formed.
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000971 // FIXME: Implement partial ordering of class template partial
972 // specializations.
973 Diag(ClassTemplateSpec->getLocation(),
974 diag::unsup_template_partial_spec_ordering);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000975 } else {
976 // -- If no matches are found, the instantiation is generated
977 // from the primary template.
978
979 // Since we initialized the pattern and template arguments from
980 // the primary template, there is nothing more we need to do here.
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000981 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000982
983 // Note that this is an instantiation.
984 ClassTemplateSpec->setSpecializationKind(
985 ExplicitInstantiation? TSK_ExplicitInstantiation
986 : TSK_ImplicitInstantiation);
987
Douglas Gregor199d9912009-06-05 00:53:49 +0000988 bool Result = InstantiateClass(ClassTemplateSpec->getLocation(),
989 ClassTemplateSpec, Pattern, *TemplateArgs,
990 ExplicitInstantiation);
991
992 for (unsigned I = 0, N = Matched.size(); I != N; ++I) {
993 // FIXME: Implement TemplateArgumentList::Destroy!
994 // if (Matched[I].first != Pattern)
995 // Matched[I].second->Destroy(Context);
996 }
997
998 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000999}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001000
Douglas Gregora58861f2009-05-13 20:28:22 +00001001/// \brief Instantiate the definitions of all of the member of the
1002/// given class, which is an instantiation of a class template or a
1003/// member class of a template.
1004void
1005Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
1006 CXXRecordDecl *Instantiation,
1007 const TemplateArgumentList &TemplateArgs) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001008 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
1009 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +00001010 D != DEnd; ++D) {
1011 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001012 if (!Function->getBody())
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001013 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Douglas Gregora58861f2009-05-13 20:28:22 +00001014 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
1015 const VarDecl *Def = 0;
1016 if (!Var->getDefinition(Def))
1017 InstantiateVariableDefinition(Var);
1018 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
1019 if (!Record->isInjectedClassName() && !Record->getDefinition(Context)) {
1020 assert(Record->getInstantiatedFromMemberClass() &&
1021 "Missing instantiated-from-template information");
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001022 InstantiateClass(PointOfInstantiation, Record,
Douglas Gregora58861f2009-05-13 20:28:22 +00001023 Record->getInstantiatedFromMemberClass(),
1024 TemplateArgs, true);
1025 }
1026 }
1027 }
1028}
1029
1030/// \brief Instantiate the definitions of all of the members of the
1031/// given class template specialization, which was named as part of an
1032/// explicit instantiation.
1033void Sema::InstantiateClassTemplateSpecializationMembers(
1034 SourceLocation PointOfInstantiation,
1035 ClassTemplateSpecializationDecl *ClassTemplateSpec) {
1036 // C++0x [temp.explicit]p7:
1037 // An explicit instantiation that names a class template
1038 // specialization is an explicit instantion of the same kind
1039 // (declaration or definition) of each of its members (not
1040 // including members inherited from base classes) that has not
1041 // been previously explicitly specialized in the translation unit
1042 // containing the explicit instantiation, except as described
1043 // below.
1044 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
1045 ClassTemplateSpec->getTemplateArgs());
1046}
1047
Douglas Gregorab452ba2009-03-26 23:50:42 +00001048/// \brief Instantiate a nested-name-specifier.
1049NestedNameSpecifier *
1050Sema::InstantiateNestedNameSpecifier(NestedNameSpecifier *NNS,
1051 SourceRange Range,
Douglas Gregor7e063902009-05-11 23:53:27 +00001052 const TemplateArgumentList &TemplateArgs) {
Douglas Gregorab452ba2009-03-26 23:50:42 +00001053 // Instantiate the prefix of this nested name specifier.
1054 NestedNameSpecifier *Prefix = NNS->getPrefix();
1055 if (Prefix) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001056 Prefix = InstantiateNestedNameSpecifier(Prefix, Range, TemplateArgs);
Douglas Gregorab452ba2009-03-26 23:50:42 +00001057 if (!Prefix)
1058 return 0;
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001059 }
1060
Douglas Gregorab452ba2009-03-26 23:50:42 +00001061 switch (NNS->getKind()) {
Douglas Gregor17343172009-04-01 00:28:59 +00001062 case NestedNameSpecifier::Identifier: {
1063 assert(Prefix &&
1064 "Can't have an identifier nested-name-specifier with no prefix");
1065 CXXScopeSpec SS;
1066 // FIXME: The source location information is all wrong.
1067 SS.setRange(Range);
1068 SS.setScopeRep(Prefix);
1069 return static_cast<NestedNameSpecifier *>(
1070 ActOnCXXNestedNameSpecifier(0, SS,
1071 Range.getEnd(),
1072 Range.getEnd(),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00001073 *NNS->getAsIdentifier()));
Douglas Gregorab452ba2009-03-26 23:50:42 +00001074 break;
Douglas Gregor17343172009-04-01 00:28:59 +00001075 }
Douglas Gregorab452ba2009-03-26 23:50:42 +00001076
1077 case NestedNameSpecifier::Namespace:
1078 case NestedNameSpecifier::Global:
1079 return NNS;
1080
1081 case NestedNameSpecifier::TypeSpecWithTemplate:
1082 case NestedNameSpecifier::TypeSpec: {
1083 QualType T = QualType(NNS->getAsType(), 0);
1084 if (!T->isDependentType())
1085 return NNS;
1086
Douglas Gregor7e063902009-05-11 23:53:27 +00001087 T = InstantiateType(T, TemplateArgs, Range.getBegin(), DeclarationName());
Douglas Gregorab452ba2009-03-26 23:50:42 +00001088 if (T.isNull())
1089 return 0;
1090
Eli Friedman923f7532009-06-13 04:51:30 +00001091 if (T->isDependentType() || T->isRecordType() ||
Douglas Gregord57959a2009-03-27 23:10:48 +00001092 (getLangOptions().CPlusPlus0x && T->isEnumeralType())) {
Douglas Gregor17343172009-04-01 00:28:59 +00001093 assert(T.getCVRQualifiers() == 0 && "Can't get cv-qualifiers here");
Douglas Gregord57959a2009-03-27 23:10:48 +00001094 return NestedNameSpecifier::Create(Context, Prefix,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001095 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00001096 T.getTypePtr());
1097 }
1098
1099 Diag(Range.getBegin(), diag::err_nested_name_spec_non_tag) << T;
1100 return 0;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001101 }
1102 }
1103
Douglas Gregord57959a2009-03-27 23:10:48 +00001104 // Required to silence a GCC warning
Douglas Gregorab452ba2009-03-26 23:50:42 +00001105 return 0;
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001106}
Douglas Gregorde650ae2009-03-31 18:38:02 +00001107
1108TemplateName
1109Sema::InstantiateTemplateName(TemplateName Name, SourceLocation Loc,
Douglas Gregor7e063902009-05-11 23:53:27 +00001110 const TemplateArgumentList &TemplateArgs) {
Douglas Gregorde650ae2009-03-31 18:38:02 +00001111 if (TemplateTemplateParmDecl *TTP
1112 = dyn_cast_or_null<TemplateTemplateParmDecl>(
1113 Name.getAsTemplateDecl())) {
1114 assert(TTP->getDepth() == 0 &&
1115 "Cannot reduce depth of a template template parameter");
Douglas Gregor9bde7732009-03-31 20:22:05 +00001116 assert(TemplateArgs[TTP->getPosition()].getAsDecl() &&
Douglas Gregorde650ae2009-03-31 18:38:02 +00001117 "Wrong kind of template template argument");
1118 ClassTemplateDecl *ClassTemplate
1119 = dyn_cast<ClassTemplateDecl>(
1120 TemplateArgs[TTP->getPosition()].getAsDecl());
Douglas Gregor9bde7732009-03-31 20:22:05 +00001121 assert(ClassTemplate && "Expected a class template");
Douglas Gregorde650ae2009-03-31 18:38:02 +00001122 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
1123 NestedNameSpecifier *NNS
1124 = InstantiateNestedNameSpecifier(QTN->getQualifier(),
1125 /*FIXME=*/SourceRange(Loc),
Douglas Gregor7e063902009-05-11 23:53:27 +00001126 TemplateArgs);
Douglas Gregorde650ae2009-03-31 18:38:02 +00001127 if (NNS)
1128 return Context.getQualifiedTemplateName(NNS,
1129 QTN->hasTemplateKeyword(),
1130 ClassTemplate);
1131 }
1132
1133 return TemplateName(ClassTemplate);
1134 } else if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
1135 NestedNameSpecifier *NNS
1136 = InstantiateNestedNameSpecifier(DTN->getQualifier(),
1137 /*FIXME=*/SourceRange(Loc),
Douglas Gregor7e063902009-05-11 23:53:27 +00001138 TemplateArgs);
Douglas Gregorde650ae2009-03-31 18:38:02 +00001139
1140 if (!NNS) // FIXME: Not the best recovery strategy.
1141 return Name;
1142
1143 if (NNS->isDependent())
1144 return Context.getDependentTemplateName(NNS, DTN->getName());
1145
1146 // Somewhat redundant with ActOnDependentTemplateName.
1147 CXXScopeSpec SS;
1148 SS.setRange(SourceRange(Loc));
1149 SS.setScopeRep(NNS);
1150 TemplateTy Template;
1151 TemplateNameKind TNK = isTemplateName(*DTN->getName(), 0, Template, &SS);
1152 if (TNK == TNK_Non_template) {
1153 Diag(Loc, diag::err_template_kw_refers_to_non_template)
1154 << DTN->getName();
1155 return Name;
1156 } else if (TNK == TNK_Function_template) {
1157 Diag(Loc, diag::err_template_kw_refers_to_non_template)
1158 << DTN->getName();
1159 return Name;
1160 }
1161
1162 return Template.getAsVal<TemplateName>();
1163 }
1164
1165
1166
Mike Stump390b4cc2009-05-16 07:39:55 +00001167 // FIXME: Even if we're referring to a Decl that isn't a template template
1168 // parameter, we may need to instantiate the outer contexts of that
1169 // Decl. However, this won't be needed until we implement member templates.
Douglas Gregorde650ae2009-03-31 18:38:02 +00001170 return Name;
1171}
Douglas Gregor91333002009-06-11 00:06:24 +00001172
1173TemplateArgument Sema::Instantiate(TemplateArgument Arg,
1174 const TemplateArgumentList &TemplateArgs) {
1175 switch (Arg.getKind()) {
1176 case TemplateArgument::Null:
1177 assert(false && "Should never have a NULL template argument");
1178 break;
1179
1180 case TemplateArgument::Type: {
1181 QualType T = InstantiateType(Arg.getAsType(), TemplateArgs,
1182 Arg.getLocation(), DeclarationName());
1183 if (T.isNull())
1184 return TemplateArgument();
1185
1186 return TemplateArgument(Arg.getLocation(), T);
1187 }
1188
1189 case TemplateArgument::Declaration:
1190 // FIXME: Template instantiation for template template parameters.
1191 return Arg;
1192
1193 case TemplateArgument::Integral:
1194 return Arg;
1195
1196 case TemplateArgument::Expression: {
Douglas Gregorac7610d2009-06-22 20:57:11 +00001197 // Template argument expressions are not potentially evaluated.
1198 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
1199
Douglas Gregor91333002009-06-11 00:06:24 +00001200 Sema::OwningExprResult E = InstantiateExpr(Arg.getAsExpr(), TemplateArgs);
1201 if (E.isInvalid())
1202 return TemplateArgument();
1203 return TemplateArgument(E.takeAs<Expr>());
1204 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001205
1206 case TemplateArgument::Pack:
1207 assert(0 && "FIXME: Implement!");
1208 break;
Douglas Gregor91333002009-06-11 00:06:24 +00001209 }
1210
1211 assert(false && "Unhandled template argument kind");
1212 return TemplateArgument();
1213}