blob: aea03cc580d85d8d86e71567398ddc6c5728100b [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"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/DeclTemplate.h"
Douglas Gregor313a81d2009-03-12 18:36:18 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000019#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 Gregor26dce442009-03-10 00:06:19 +000029Sema::InstantiatingTemplate::
30InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
31 ClassTemplateSpecializationDecl *Entity,
32 SourceRange InstantiationRange)
33 : SemaRef(SemaRef) {
Douglas Gregordf667e72009-03-10 20:44:00 +000034
35 Invalid = CheckInstantiationDepth(PointOfInstantiation,
36 InstantiationRange);
37 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +000038 ActiveTemplateInstantiation Inst;
Douglas Gregordf667e72009-03-10 20:44:00 +000039 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor26dce442009-03-10 00:06:19 +000040 Inst.PointOfInstantiation = PointOfInstantiation;
Douglas Gregordf667e72009-03-10 20:44:00 +000041 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
Douglas Gregor313a81d2009-03-12 18:36:18 +000042 Inst.TemplateArgs = 0;
43 Inst.NumTemplateArgs = 0;
Douglas Gregordf667e72009-03-10 20:44:00 +000044 Inst.InstantiationRange = InstantiationRange;
45 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
46 Invalid = false;
47 }
48}
49
50Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
51 SourceLocation PointOfInstantiation,
52 TemplateDecl *Template,
53 const TemplateArgument *TemplateArgs,
54 unsigned NumTemplateArgs,
55 SourceRange InstantiationRange)
56 : SemaRef(SemaRef) {
57
58 Invalid = CheckInstantiationDepth(PointOfInstantiation,
59 InstantiationRange);
60 if (!Invalid) {
61 ActiveTemplateInstantiation Inst;
62 Inst.Kind
63 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
64 Inst.PointOfInstantiation = PointOfInstantiation;
65 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
66 Inst.TemplateArgs = TemplateArgs;
67 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor26dce442009-03-10 00:06:19 +000068 Inst.InstantiationRange = InstantiationRange;
69 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
70 Invalid = false;
71 }
72}
73
74Sema::InstantiatingTemplate::~InstantiatingTemplate() {
75 if (!Invalid)
76 SemaRef.ActiveTemplateInstantiations.pop_back();
77}
78
Douglas Gregordf667e72009-03-10 20:44:00 +000079bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
80 SourceLocation PointOfInstantiation,
81 SourceRange InstantiationRange) {
82 if (SemaRef.ActiveTemplateInstantiations.size()
83 <= SemaRef.getLangOptions().InstantiationDepth)
84 return false;
85
86 SemaRef.Diag(PointOfInstantiation,
87 diag::err_template_recursion_depth_exceeded)
88 << SemaRef.getLangOptions().InstantiationDepth
89 << InstantiationRange;
90 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
91 << SemaRef.getLangOptions().InstantiationDepth;
92 return true;
93}
94
Douglas Gregoree1828a2009-03-10 18:03:33 +000095/// \brief Post-diagnostic hook for printing the instantiation stack.
96void Sema::PrintInstantiationStackHook(unsigned, void *Cookie) {
Douglas Gregor27b152f2009-03-10 18:52:44 +000097 Sema &SemaRef = *static_cast<Sema*>(Cookie);
98 SemaRef.PrintInstantiationStack();
99 SemaRef.LastTemplateInstantiationErrorContext
Douglas Gregordf667e72009-03-10 20:44:00 +0000100 = SemaRef.ActiveTemplateInstantiations.back();
Douglas Gregoree1828a2009-03-10 18:03:33 +0000101}
102
103/// \brief Prints the current instantiation stack through a series of
104/// notes.
105void Sema::PrintInstantiationStack() {
106 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
107 Active = ActiveTemplateInstantiations.rbegin(),
108 ActiveEnd = ActiveTemplateInstantiations.rend();
109 Active != ActiveEnd;
110 ++Active) {
Douglas Gregordf667e72009-03-10 20:44:00 +0000111 switch (Active->Kind) {
112 case ActiveTemplateInstantiation::TemplateInstantiation: {
113 ClassTemplateSpecializationDecl *Spec
114 = cast<ClassTemplateSpecializationDecl>((Decl*)Active->Entity);
115 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
116 diag::note_template_class_instantiation_here)
117 << Context.getTypeDeclType(Spec)
118 << Active->InstantiationRange;
119 break;
120 }
121
122 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
123 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
124 std::string TemplateArgsStr
125 = ClassTemplateSpecializationType::PrintTemplateArgumentList(
126 Active->TemplateArgs,
127 Active->NumTemplateArgs);
128 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
129 diag::note_default_arg_instantiation_here)
130 << (Template->getNameAsString() + TemplateArgsStr)
131 << Active->InstantiationRange;
132 break;
133 }
134 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000135 }
136}
137
Douglas Gregor99ebf652009-02-27 19:31:52 +0000138//===----------------------------------------------------------------------===/
139// Template Instantiation for Types
140//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000141namespace {
142 class VISIBILITY_HIDDEN TemplateTypeInstantiator {
143 Sema &SemaRef;
144 const TemplateArgument *TemplateArgs;
145 unsigned NumTemplateArgs;
146 SourceLocation Loc;
147 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000148
Douglas Gregorcd281c32009-02-28 00:25:32 +0000149 public:
150 TemplateTypeInstantiator(Sema &SemaRef,
151 const TemplateArgument *TemplateArgs,
152 unsigned NumTemplateArgs,
153 SourceLocation Loc,
154 DeclarationName Entity)
155 : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
156 NumTemplateArgs(NumTemplateArgs), Loc(Loc), Entity(Entity) { }
157
158 QualType operator()(QualType T) const { return Instantiate(T); }
159
160 QualType Instantiate(QualType T) const;
161
162 // Declare instantiate functions for each type.
163#define TYPE(Class, Base) \
164 QualType Instantiate##Class##Type(const Class##Type *T, \
165 unsigned Quals) const;
166#define ABSTRACT_TYPE(Class, Base)
167#include "clang/AST/TypeNodes.def"
168 };
169}
170
171QualType
172TemplateTypeInstantiator::InstantiateExtQualType(const ExtQualType *T,
173 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000174 // FIXME: Implement this
175 assert(false && "Cannot instantiate ExtQualType yet");
176 return QualType();
177}
178
Douglas Gregorcd281c32009-02-28 00:25:32 +0000179QualType
180TemplateTypeInstantiator::InstantiateBuiltinType(const BuiltinType *T,
181 unsigned Quals) const {
Douglas Gregor724651c2009-02-28 01:04:19 +0000182 assert(false && "Builtin types are not dependent and cannot be instantiated");
Douglas Gregorcd281c32009-02-28 00:25:32 +0000183 return QualType(T, Quals);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000184}
185
Douglas Gregorcd281c32009-02-28 00:25:32 +0000186QualType
187TemplateTypeInstantiator::
188InstantiateFixedWidthIntType(const FixedWidthIntType *T, unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000189 // FIXME: Implement this
190 assert(false && "Cannot instantiate FixedWidthIntType yet");
191 return QualType();
192}
193
Douglas Gregorcd281c32009-02-28 00:25:32 +0000194QualType
195TemplateTypeInstantiator::InstantiateComplexType(const ComplexType *T,
196 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000197 // FIXME: Implement this
198 assert(false && "Cannot instantiate ComplexType yet");
199 return QualType();
200}
201
Douglas Gregorcd281c32009-02-28 00:25:32 +0000202QualType
203TemplateTypeInstantiator::InstantiatePointerType(const PointerType *T,
204 unsigned Quals) const {
205 QualType PointeeType = Instantiate(T->getPointeeType());
206 if (PointeeType.isNull())
207 return QualType();
208
209 return SemaRef.BuildPointerType(PointeeType, Quals, Loc, Entity);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000210}
211
Douglas Gregorcd281c32009-02-28 00:25:32 +0000212QualType
213TemplateTypeInstantiator::InstantiateBlockPointerType(const BlockPointerType *T,
214 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000215 // FIXME: Implement this
216 assert(false && "Cannot instantiate BlockPointerType yet");
217 return QualType();
218}
219
Douglas Gregorcd281c32009-02-28 00:25:32 +0000220QualType
221TemplateTypeInstantiator::InstantiateReferenceType(const ReferenceType *T,
222 unsigned Quals) const {
223 QualType ReferentType = Instantiate(T->getPointeeType());
224 if (ReferentType.isNull())
225 return QualType();
226
227 return SemaRef.BuildReferenceType(ReferentType, Quals, Loc, Entity);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000228}
229
Douglas Gregorcd281c32009-02-28 00:25:32 +0000230QualType
231TemplateTypeInstantiator::
232InstantiateMemberPointerType(const MemberPointerType *T,
233 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000234 // FIXME: Implement this
235 assert(false && "Cannot instantiate MemberPointerType yet");
236 return QualType();
237}
238
Douglas Gregorcd281c32009-02-28 00:25:32 +0000239QualType
240TemplateTypeInstantiator::
241InstantiateConstantArrayType(const ConstantArrayType *T,
242 unsigned Quals) const {
243 QualType ElementType = Instantiate(T->getElementType());
244 if (ElementType.isNull())
245 return ElementType;
246
247 // Build a temporary integer literal to specify the size for
248 // BuildArrayType. Since we have already checked the size as part of
249 // creating the dependent array type in the first place, we know
250 // there aren't any errors.
Douglas Gregor8d217212009-03-09 20:07:22 +0000251 // FIXME: Is IntTy big enough? Maybe not, but LongLongTy causes
252 // problems that I have yet to investigate.
253 IntegerLiteral ArraySize(T->getSize(), SemaRef.Context.IntTy, Loc);
Douglas Gregorcd281c32009-02-28 00:25:32 +0000254 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
255 &ArraySize, T->getIndexTypeQualifier(),
256 Loc, Entity);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000257}
258
Douglas Gregorcd281c32009-02-28 00:25:32 +0000259QualType
260TemplateTypeInstantiator::
261InstantiateIncompleteArrayType(const IncompleteArrayType *T,
262 unsigned Quals) const {
263 QualType ElementType = Instantiate(T->getElementType());
264 if (ElementType.isNull())
265 return ElementType;
266
267 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
268 0, T->getIndexTypeQualifier(),
269 Loc, Entity);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000270}
271
Douglas Gregorcd281c32009-02-28 00:25:32 +0000272QualType
273TemplateTypeInstantiator::
274InstantiateVariableArrayType(const VariableArrayType *T,
275 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000276 // FIXME: Implement this
277 assert(false && "Cannot instantiate VariableArrayType yet");
278 return QualType();
279}
280
Douglas Gregorcd281c32009-02-28 00:25:32 +0000281QualType
282TemplateTypeInstantiator::
283InstantiateDependentSizedArrayType(const DependentSizedArrayType *T,
284 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000285 // FIXME: Implement this
286 assert(false && "Cannot instantiate DependentSizedArrayType yet");
287 return QualType();
288}
289
Douglas Gregorcd281c32009-02-28 00:25:32 +0000290QualType
291TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T,
292 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000293 // FIXME: Implement this
294 assert(false && "Cannot instantiate VectorType yet");
295 return QualType();
296}
297
Douglas Gregorcd281c32009-02-28 00:25:32 +0000298QualType
299TemplateTypeInstantiator::InstantiateExtVectorType(const ExtVectorType *T,
300 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000301 // FIXME: Implement this
302 assert(false && "Cannot instantiate ExtVectorType yet");
303 return QualType();
304}
305
Douglas Gregorcd281c32009-02-28 00:25:32 +0000306QualType
307TemplateTypeInstantiator::
308InstantiateFunctionProtoType(const FunctionProtoType *T,
309 unsigned Quals) const {
Douglas Gregor724651c2009-02-28 01:04:19 +0000310 QualType ResultType = Instantiate(T->getResultType());
311 if (ResultType.isNull())
312 return ResultType;
313
314 llvm::SmallVector<QualType, 16> ParamTypes;
315 for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(),
316 ParamEnd = T->arg_type_end();
317 Param != ParamEnd; ++Param) {
318 QualType P = Instantiate(*Param);
319 if (P.isNull())
320 return P;
321
322 ParamTypes.push_back(P);
323 }
324
325 return SemaRef.BuildFunctionType(ResultType, &ParamTypes[0],
326 ParamTypes.size(),
327 T->isVariadic(), T->getTypeQuals(),
328 Loc, Entity);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000329}
330
Douglas Gregorcd281c32009-02-28 00:25:32 +0000331QualType
332TemplateTypeInstantiator::
333InstantiateFunctionNoProtoType(const FunctionNoProtoType *T,
334 unsigned Quals) const {
Douglas Gregor724651c2009-02-28 01:04:19 +0000335 assert(false && "Functions without prototypes cannot be dependent.");
Douglas Gregor99ebf652009-02-27 19:31:52 +0000336 return QualType();
337}
338
Douglas Gregorcd281c32009-02-28 00:25:32 +0000339QualType
340TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T,
341 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000342 // FIXME: Implement this
343 assert(false && "Cannot instantiate TypedefType yet");
344 return QualType();
345}
346
Douglas Gregorcd281c32009-02-28 00:25:32 +0000347QualType
348TemplateTypeInstantiator::InstantiateTypeOfExprType(const TypeOfExprType *T,
349 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000350 // FIXME: Implement this
351 assert(false && "Cannot instantiate TypeOfExprType yet");
352 return QualType();
353}
354
Douglas Gregorcd281c32009-02-28 00:25:32 +0000355QualType
356TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T,
357 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000358 // FIXME: Implement this
359 assert(false && "Cannot instantiate TypeOfType yet");
360 return QualType();
361}
362
Douglas Gregorcd281c32009-02-28 00:25:32 +0000363QualType
364TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T,
365 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000366 // FIXME: Implement this
367 assert(false && "Cannot instantiate RecordType yet");
368 return QualType();
369}
370
Douglas Gregorcd281c32009-02-28 00:25:32 +0000371QualType
Douglas Gregorcd281c32009-02-28 00:25:32 +0000372TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T,
373 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000374 // FIXME: Implement this
375 assert(false && "Cannot instantiate EnumType yet");
376 return QualType();
377}
378
Douglas Gregorcd281c32009-02-28 00:25:32 +0000379QualType
380TemplateTypeInstantiator::
381InstantiateTemplateTypeParmType(const TemplateTypeParmType *T,
382 unsigned Quals) const {
Douglas Gregor99ebf652009-02-27 19:31:52 +0000383 if (T->getDepth() == 0) {
384 // Replace the template type parameter with its corresponding
385 // template argument.
386 assert(T->getIndex() < NumTemplateArgs && "Wrong # of template args");
387 assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
388 "Template argument kind mismatch");
389 QualType Result = TemplateArgs[T->getIndex()].getAsType();
Douglas Gregorcd281c32009-02-28 00:25:32 +0000390 if (Result.isNull() || !Quals)
Douglas Gregor99ebf652009-02-27 19:31:52 +0000391 return Result;
392
393 // C++ [dcl.ref]p1:
394 // [...] Cv-qualified references are ill-formed except when
395 // the cv-qualifiers are introduced through the use of a
396 // typedef (7.1.3) or of a template type argument (14.3), in
397 // which case the cv-qualifiers are ignored.
Douglas Gregorcd281c32009-02-28 00:25:32 +0000398 if (Quals && Result->isReferenceType())
399 Quals = 0;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000400
Douglas Gregorcd281c32009-02-28 00:25:32 +0000401 return QualType(Result.getTypePtr(), Quals | Result.getCVRQualifiers());
Douglas Gregor99ebf652009-02-27 19:31:52 +0000402 }
403
404 // The template type parameter comes from an inner template (e.g.,
405 // the template parameter list of a member template inside the
406 // template we are instantiating). Create a new template type
407 // parameter with the template "level" reduced by one.
408 return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1,
409 T->getIndex(),
Douglas Gregorcd281c32009-02-28 00:25:32 +0000410 T->getName())
411 .getQualifiedType(Quals);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000412}
413
Douglas Gregorcd281c32009-02-28 00:25:32 +0000414QualType
415TemplateTypeInstantiator::
416InstantiateClassTemplateSpecializationType(
417 const ClassTemplateSpecializationType *T,
418 unsigned Quals) const {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000419 llvm::SmallVector<TemplateArgument, 16> InstantiatedTemplateArgs;
420 InstantiatedTemplateArgs.reserve(T->getNumArgs());
421 for (ClassTemplateSpecializationType::iterator Arg = T->begin(),
422 ArgEnd = T->end();
423 Arg != ArgEnd; ++Arg) {
424 switch (Arg->getKind()) {
425 case TemplateArgument::Type: {
426 QualType T = SemaRef.InstantiateType(Arg->getAsType(),
427 TemplateArgs, NumTemplateArgs,
428 Arg->getLocation(),
429 DeclarationName());
430 if (T.isNull())
431 return QualType();
432
433 InstantiatedTemplateArgs.push_back(
434 TemplateArgument(Arg->getLocation(), T));
435 break;
436 }
437
438 case TemplateArgument::Declaration:
439 case TemplateArgument::Integral:
440 InstantiatedTemplateArgs.push_back(*Arg);
441 break;
442
443 case TemplateArgument::Expression:
444 assert(false && "Cannot instantiate expressions yet");
445 break;
446 }
447 }
448
449 // FIXME: We're missing the locations of the template name, '<', and
450 // '>'.
451 return SemaRef.CheckClassTemplateId(cast<ClassTemplateDecl>(T->getTemplate()),
452 Loc,
453 SourceLocation(),
454 &InstantiatedTemplateArgs[0],
455 InstantiatedTemplateArgs.size(),
456 SourceLocation());
Douglas Gregor99ebf652009-02-27 19:31:52 +0000457}
458
Douglas Gregorcd281c32009-02-28 00:25:32 +0000459QualType
460TemplateTypeInstantiator::
461InstantiateObjCInterfaceType(const ObjCInterfaceType *T,
462 unsigned Quals) const {
463 assert(false && "Objective-C types cannot be dependent");
Douglas Gregor99ebf652009-02-27 19:31:52 +0000464 return QualType();
465}
466
Douglas Gregorcd281c32009-02-28 00:25:32 +0000467QualType
468TemplateTypeInstantiator::
469InstantiateObjCQualifiedInterfaceType(const ObjCQualifiedInterfaceType *T,
470 unsigned Quals) const {
471 assert(false && "Objective-C types cannot be dependent");
Douglas Gregor99ebf652009-02-27 19:31:52 +0000472 return QualType();
473}
474
Douglas Gregorcd281c32009-02-28 00:25:32 +0000475QualType
476TemplateTypeInstantiator::
477InstantiateObjCQualifiedIdType(const ObjCQualifiedIdType *T,
478 unsigned Quals) const {
479 assert(false && "Objective-C types cannot be dependent");
Douglas Gregor99ebf652009-02-27 19:31:52 +0000480 return QualType();
481}
482
Douglas Gregorcd281c32009-02-28 00:25:32 +0000483QualType
484TemplateTypeInstantiator::
485InstantiateObjCQualifiedClassType(const ObjCQualifiedClassType *T,
486 unsigned Quals) const {
487 assert(false && "Objective-C types cannot be dependent");
Douglas Gregor99ebf652009-02-27 19:31:52 +0000488 return QualType();
489}
490
Douglas Gregorcd281c32009-02-28 00:25:32 +0000491/// \brief The actual implementation of Sema::InstantiateType().
492QualType TemplateTypeInstantiator::Instantiate(QualType T) const {
493 // If T is not a dependent type, there is nothing to do.
494 if (!T->isDependentType())
495 return T;
496
497 switch (T->getTypeClass()) {
498#define TYPE(Class, Base) \
499 case Type::Class: \
500 return Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr()), \
501 T.getCVRQualifiers());
502#define ABSTRACT_TYPE(Class, Base)
503#include "clang/AST/TypeNodes.def"
504 }
505
506 assert(false && "Not all types have been decoded for instantiation");
507 return QualType();
508}
Douglas Gregor99ebf652009-02-27 19:31:52 +0000509
510/// \brief Instantiate the type T with a given set of template arguments.
511///
512/// This routine substitutes the given template arguments into the
513/// type T and produces the instantiated type.
514///
515/// \param T the type into which the template arguments will be
516/// substituted. If this type is not dependent, it will be returned
517/// immediately.
518///
519/// \param TemplateArgs the template arguments that will be
520/// substituted for the top-level template parameters within T.
521///
522/// \param NumTemplateArgs the number of template arguments provided
523/// by TemplateArgs.
524///
525/// \param Loc the location in the source code where this substitution
526/// is being performed. It will typically be the location of the
527/// declarator (if we're instantiating the type of some declaration)
528/// or the location of the type in the source code (if, e.g., we're
529/// instantiating the type of a cast expression).
530///
531/// \param Entity the name of the entity associated with a declaration
532/// being instantiated (if any). May be empty to indicate that there
533/// is no such entity (if, e.g., this is a type that occurs as part of
534/// a cast expression) or that the entity has no name (e.g., an
535/// unnamed function parameter).
536///
537/// \returns If the instantiation succeeds, the instantiated
538/// type. Otherwise, produces diagnostics and returns a NULL type.
539QualType Sema::InstantiateType(QualType T,
540 const TemplateArgument *TemplateArgs,
541 unsigned NumTemplateArgs,
542 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +0000543 assert(!ActiveTemplateInstantiations.empty() &&
544 "Cannot perform an instantiation without some context on the "
545 "instantiation stack");
546
Douglas Gregor99ebf652009-02-27 19:31:52 +0000547 // If T is not a dependent type, there is nothing to do.
548 if (!T->isDependentType())
549 return T;
550
Douglas Gregorcd281c32009-02-28 00:25:32 +0000551 TemplateTypeInstantiator Instantiator(*this, TemplateArgs, NumTemplateArgs,
552 Loc, Entity);
553 return Instantiator(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +0000554}
Douglas Gregor2943aed2009-03-03 04:44:36 +0000555
Douglas Gregora0e500d2009-03-12 16:53:44 +0000556//===----------------------------------------------------------------------===/
557// Template Instantiation for Expressions
558//===----------------------------------------------------------------------===/
Douglas Gregor313a81d2009-03-12 18:36:18 +0000559namespace {
560 class VISIBILITY_HIDDEN TemplateExprInstantiator
561 : public StmtVisitor<TemplateExprInstantiator, Sema::OwningExprResult> {
562 Sema &SemaRef;
563 const TemplateArgument *TemplateArgs;
564 unsigned NumTemplateArgs;
565
566 public:
567 TemplateExprInstantiator(Sema &SemaRef,
568 const TemplateArgument *TemplateArgs,
569 unsigned NumTemplateArgs)
570 : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
571 NumTemplateArgs(NumTemplateArgs) { }
572
573 // FIXME: Once we get closer to completion, replace these
574 // manually-written declarations with automatically-generated ones
575 // from clang/AST/StmtNodes.def.
576 Sema::OwningExprResult VisitIntegerLiteral(IntegerLiteral *E);
577 Sema::OwningExprResult VisitDeclRefExpr(DeclRefExpr *E);
578 Sema::OwningExprResult VisitParenExpr(ParenExpr *E);
Douglas Gregordf032512009-03-12 22:46:12 +0000579 Sema::OwningExprResult VisitBinaryOperator(BinaryOperator *E);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +0000580 Sema::OwningExprResult VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Douglas Gregor313a81d2009-03-12 18:36:18 +0000581
582 // Base case. I'm supposed to ignore this.
Douglas Gregordf032512009-03-12 22:46:12 +0000583 Sema::OwningExprResult VisitStmt(Stmt *) {
584 assert(false && "Cannot instantiate this kind of expression");
585 return SemaRef.ExprError();
586 }
Douglas Gregor313a81d2009-03-12 18:36:18 +0000587 };
588}
589
590Sema::OwningExprResult
591TemplateExprInstantiator::VisitIntegerLiteral(IntegerLiteral *E) {
592 // FIXME: Can't we just re-use the expression node?
593 return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral(E->getValue(),
594 E->getType(),
595 E->getLocation()));
596}
597
598Sema::OwningExprResult
599TemplateExprInstantiator::VisitDeclRefExpr(DeclRefExpr *E) {
600 Decl *D = E->getDecl();
601 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
602 assert(NTTP->getDepth() == 0 && "No nested templates yet");
Douglas Gregorc971f862009-03-12 22:20:26 +0000603 const TemplateArgument &Arg = TemplateArgs[NTTP->getPosition()];
Douglas Gregor313a81d2009-03-12 18:36:18 +0000604 return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral(
Douglas Gregorc971f862009-03-12 22:20:26 +0000605 *Arg.getAsIntegral(),
606 Arg.getIntegralType(),
607 E->getSourceRange().getBegin()));
Douglas Gregor313a81d2009-03-12 18:36:18 +0000608 } else
609 assert(false && "Can't handle arbitrary declaration references");
610
611 return SemaRef.ExprError();
612}
613
614Sema::OwningExprResult
615TemplateExprInstantiator::VisitParenExpr(ParenExpr *E) {
616 Sema::OwningExprResult SubExpr
617 = SemaRef.InstantiateExpr(E->getSubExpr(), TemplateArgs, NumTemplateArgs);
618 if (SubExpr.isInvalid())
619 return SemaRef.ExprError();
620
621 return SemaRef.Owned(new (SemaRef.Context) ParenExpr(
622 E->getLParen(), E->getRParen(),
623 (Expr *)SubExpr.release()));
624}
625
Douglas Gregora0e500d2009-03-12 16:53:44 +0000626Sema::OwningExprResult
Douglas Gregordf032512009-03-12 22:46:12 +0000627TemplateExprInstantiator::VisitBinaryOperator(BinaryOperator *E) {
628 Sema::OwningExprResult LHS = Visit(E->getLHS());
629 if (LHS.isInvalid())
630 return SemaRef.ExprError();
631
632 Sema::OwningExprResult RHS = Visit(E->getRHS());
633 if (RHS.isInvalid())
634 return SemaRef.ExprError();
635
636 Sema::OwningExprResult Result
637 = SemaRef.CreateBuiltinBinOp(E->getOperatorLoc(),
638 E->getOpcode(),
639 (Expr *)LHS.get(),
640 (Expr *)RHS.get());
641 if (Result.isInvalid())
642 return SemaRef.ExprError();
643
644 LHS.release();
645 RHS.release();
646 return move(Result);
647}
648
649Sema::OwningExprResult
Douglas Gregor3fd95ce2009-03-13 00:33:25 +0000650TemplateExprInstantiator::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
Douglas Gregor063daf62009-03-13 18:40:31 +0000651 // FIXME: Only handles binary operators at the moment.
652
653 // FIXME: Can we optimize this further if neither the left- nor the
654 // right-hand sides are type-dependent? It depends on whether we
655 // need to perform ADL again
Douglas Gregor3fd95ce2009-03-13 00:33:25 +0000656 Sema::OwningExprResult LHS = Visit(E->getArg(0));
657 if (LHS.isInvalid())
658 return SemaRef.ExprError();
659
660 Sema::OwningExprResult RHS = Visit(E->getArg(1));
661 if (RHS.isInvalid())
662 return SemaRef.ExprError();
663
Douglas Gregor063daf62009-03-13 18:40:31 +0000664 Expr *lhs = (Expr *)LHS.get(), *rhs = (Expr *)RHS.get();
665 Expr *Args[2] = { lhs, rhs };
666
667 if (!E->isTypeDependent()) {
668 // Since our original expression was not type-dependent, we do not
669 // perform lookup again at instantiation time (C++ [temp.dep]p1).
670 // Instead, we just build the new overloaded operator call
671 // expression.
672 LHS.release();
673 RHS.release();
674 return SemaRef.Owned(new (SemaRef.Context) CXXOperatorCallExpr(
675 SemaRef.Context,
676 E->getOperator(),
677 E->getCallee(),
678 Args, 2, E->getType(),
679 E->getOperatorLoc()));
680 }
681
682 BinaryOperator::Opcode Opc =
683 BinaryOperator::getOverloadedOpcode(E->getOperator());
684 Sema::OwningExprResult Result(SemaRef);
685 if (!lhs->getType()->isOverloadableType() &&
686 !rhs->getType()->isOverloadableType()) {
687 // Neither LHS nor RHS is an overloadable type, so try create a
688 // built-in binary operation.
689 Result = SemaRef.CreateBuiltinBinOp(E->getOperatorLoc(), Opc,
690 lhs, rhs);
691 } else {
692 // Compute the set of functions that were found at template
693 // definition time.
694 Sema::FunctionSet Functions;
695 DeclRefExpr *DRE = cast<DeclRefExpr>(E->getCallee());
696 OverloadedFunctionDecl *Overloads
697 = cast<OverloadedFunctionDecl>(DRE->getDecl());
698 for (OverloadedFunctionDecl::function_iterator
699 F = Overloads->function_begin(),
700 FEnd = Overloads->function_end();
701 F != FEnd; ++F)
702 Functions.insert(*F);
703
704 // Add any functions found via argument-dependent lookup.
705 DeclarationName OpName
706 = SemaRef.Context.DeclarationNames.getCXXOperatorName(E->getOperator());
707 SemaRef.ArgumentDependentLookup(OpName, Args, 2, Functions);
708
709 // Create the overloaded operator.
710 Result = SemaRef.CreateOverloadedBinOp(E->getOperatorLoc(), Opc,
711 Functions, lhs, rhs);
712 }
713
Douglas Gregor3fd95ce2009-03-13 00:33:25 +0000714 if (Result.isInvalid())
715 return SemaRef.ExprError();
716
717 LHS.release();
718 RHS.release();
719 return move(Result);
720}
721
722Sema::OwningExprResult
Douglas Gregora0e500d2009-03-12 16:53:44 +0000723Sema::InstantiateExpr(Expr *E, const TemplateArgument *TemplateArgs,
724 unsigned NumTemplateArgs) {
Douglas Gregor313a81d2009-03-12 18:36:18 +0000725 TemplateExprInstantiator Instantiator(*this, TemplateArgs, NumTemplateArgs);
726 return Instantiator.Visit(E);
Douglas Gregora0e500d2009-03-12 16:53:44 +0000727}
728
Douglas Gregor2943aed2009-03-03 04:44:36 +0000729/// \brief Instantiate the base class specifiers of the given class
730/// template specialization.
731///
732/// Produces a diagnostic and returns true on error, returns false and
733/// attaches the instantiated base classes to the class template
734/// specialization if successful.
735bool
736Sema::InstantiateBaseSpecifiers(
737 ClassTemplateSpecializationDecl *ClassTemplateSpec,
738 ClassTemplateDecl *ClassTemplate) {
739 bool Invalid = false;
740 llvm::SmallVector<CXXBaseSpecifier*, 8> InstantiatedBases;
741 for (ClassTemplateSpecializationDecl::base_class_iterator
742 Base = ClassTemplate->getTemplatedDecl()->bases_begin(),
743 BaseEnd = ClassTemplate->getTemplatedDecl()->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +0000744 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000745 if (!Base->getType()->isDependentType()) {
746 // FIXME: Allocate via ASTContext
747 InstantiatedBases.push_back(new CXXBaseSpecifier(*Base));
748 continue;
749 }
750
751 QualType BaseType = InstantiateType(Base->getType(),
752 ClassTemplateSpec->getTemplateArgs(),
753 ClassTemplateSpec->getNumTemplateArgs(),
754 Base->getSourceRange().getBegin(),
755 DeclarationName());
756 if (BaseType.isNull()) {
757 Invalid = true;
758 continue;
759 }
760
761 if (CXXBaseSpecifier *InstantiatedBase
762 = CheckBaseSpecifier(ClassTemplateSpec,
763 Base->getSourceRange(),
764 Base->isVirtual(),
765 Base->getAccessSpecifierAsWritten(),
766 BaseType,
767 /*FIXME: Not totally accurate */
768 Base->getSourceRange().getBegin()))
769 InstantiatedBases.push_back(InstantiatedBase);
770 else
771 Invalid = true;
772 }
773
Douglas Gregor27b152f2009-03-10 18:52:44 +0000774 if (!Invalid &&
775 AttachBaseSpecifiers(ClassTemplateSpec, &InstantiatedBases[0],
Douglas Gregor2943aed2009-03-03 04:44:36 +0000776 InstantiatedBases.size()))
777 Invalid = true;
778
779 return Invalid;
780}
781
782bool
783Sema::InstantiateClassTemplateSpecialization(
784 ClassTemplateSpecializationDecl *ClassTemplateSpec,
785 bool ExplicitInstantiation) {
786 // Perform the actual instantiation on the canonical declaration.
787 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
788 Context.getCanonicalDecl(ClassTemplateSpec));
789
790 // We can only instantiate something that hasn't already been
791 // instantiated or specialized. Fail without any diagnostics: our
792 // caller will provide an error message.
793 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
794 return true;
795
796 // FIXME: Push this class template instantiation onto the
797 // instantiation stack, checking for recursion that exceeds a
798 // certain depth.
799
800 // FIXME: Perform class template partial specialization to select
801 // the best template.
802 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
803
804 if (!Template->getTemplatedDecl()->getDefinition(Context)) {
805 Diag(ClassTemplateSpec->getLocation(),
806 diag::err_template_implicit_instantiate_undefined)
807 << Context.getTypeDeclType(ClassTemplateSpec);
808 Diag(Template->getTemplatedDecl()->getLocation(),
809 diag::note_template_decl_here);
810 return true;
811 }
812
813 // Note that this is an instantiation.
814 ClassTemplateSpec->setSpecializationKind(
815 ExplicitInstantiation? TSK_ExplicitInstantiation
816 : TSK_ImplicitInstantiation);
817
818
819 bool Invalid = false;
820
Douglas Gregor26dce442009-03-10 00:06:19 +0000821 InstantiatingTemplate Inst(*this, ClassTemplateSpec->getLocation(),
822 ClassTemplateSpec);
823 if (Inst)
824 return true;
825
Douglas Gregor2943aed2009-03-03 04:44:36 +0000826 // Enter the scope of this instantiation. We don't use
827 // PushDeclContext because we don't have a scope.
828 DeclContext *PreviousContext = CurContext;
829 CurContext = ClassTemplateSpec;
830
831 // Start the definition of this instantiation.
832 ClassTemplateSpec->startDefinition();
833
Douglas Gregor2943aed2009-03-03 04:44:36 +0000834
835 // Instantiate the base class specifiers.
836 if (InstantiateBaseSpecifiers(ClassTemplateSpec, Template))
837 Invalid = true;
838
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000839 // FIXME: Create the injected-class-name for the
840 // instantiation. Should this be a typedef or something like it?
841
842 RecordDecl *Pattern = Template->getTemplatedDecl();
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000843 llvm::SmallVector<DeclTy *, 32> Fields;
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000844 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
845 MemberEnd = Pattern->decls_end();
846 Member != MemberEnd; ++Member) {
847 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(*Member)) {
848 // FIXME: Simplified instantiation of typedefs needs to be made
849 // "real".
850 QualType T = Typedef->getUnderlyingType();
851 if (T->isDependentType()) {
852 T = InstantiateType(T, ClassTemplateSpec->getTemplateArgs(),
853 ClassTemplateSpec->getNumTemplateArgs(),
854 Typedef->getLocation(),
855 Typedef->getDeclName());
856 if (T.isNull()) {
857 Invalid = true;
858 T = Context.IntTy;
859 }
860 }
861
862 // Create the new typedef
863 TypedefDecl *New
864 = TypedefDecl::Create(Context, ClassTemplateSpec,
865 Typedef->getLocation(),
866 Typedef->getIdentifier(),
867 T);
868 ClassTemplateSpec->addDecl(New);
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000869 }
870 else if (FieldDecl *Field = dyn_cast<FieldDecl>(*Member)) {
871 // FIXME: Simplified instantiation of fields needs to be made
872 // "real".
Douglas Gregora0e500d2009-03-12 16:53:44 +0000873 bool InvalidDecl = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000874 QualType T = Field->getType();
875 if (T->isDependentType()) {
876 T = InstantiateType(T, ClassTemplateSpec->getTemplateArgs(),
877 ClassTemplateSpec->getNumTemplateArgs(),
878 Field->getLocation(),
879 Field->getDeclName());
880 if (!T.isNull() && T->isFunctionType()) {
881 // C++ [temp.arg.type]p3:
882 // If a declaration acquires a function type through a type
883 // dependent on a template-parameter and this causes a
884 // declaration that does not use the syntactic form of a
885 // function declarator to have function type, the program is
886 // ill-formed.
887 Diag(Field->getLocation(), diag::err_field_instantiates_to_function)
888 << T;
889 T = QualType();
Douglas Gregora0e500d2009-03-12 16:53:44 +0000890 InvalidDecl = true;
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000891 }
892 }
893
Douglas Gregora0e500d2009-03-12 16:53:44 +0000894 Expr *BitWidth = Field->getBitWidth();
895 if (InvalidDecl)
896 BitWidth = 0;
897 if (BitWidth &&
898 (BitWidth->isTypeDependent() || BitWidth->isValueDependent())) {
899 OwningExprResult InstantiatedBitWidth
900 = InstantiateExpr(BitWidth,
901 ClassTemplateSpec->getTemplateArgs(),
902 ClassTemplateSpec->getNumTemplateArgs());
903 if (InstantiatedBitWidth.isInvalid()) {
904 Invalid = InvalidDecl = true;
905 BitWidth = 0;
906 } else
907 BitWidth = (Expr *)InstantiatedBitWidth.release();
908 }
909
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000910 FieldDecl *New = CheckFieldDecl(Field->getDeclName(), T,
911 ClassTemplateSpec,
912 Field->getLocation(),
913 Field->isMutable(),
Douglas Gregora0e500d2009-03-12 16:53:44 +0000914 BitWidth,
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000915 Field->getAccess(),
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000916 0);
917 if (New) {
918 ClassTemplateSpec->addDecl(New);
919 Fields.push_back(New);
920
Douglas Gregora0e500d2009-03-12 16:53:44 +0000921 if (InvalidDecl)
922 New->setInvalidDecl();
923
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000924 if (New->isInvalidDecl())
925 Invalid = true;
926 }
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000927 }
928 }
929
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000930 // Finish checking fields.
931 ActOnFields(0, ClassTemplateSpec->getLocation(), ClassTemplateSpec,
932 &Fields[0], Fields.size(), SourceLocation(), SourceLocation(),
933 0);
934
Douglas Gregor2943aed2009-03-03 04:44:36 +0000935 // Add any implicitly-declared members that we might need.
936 AddImplicitlyDeclaredMembersToClass(ClassTemplateSpec);
937
Douglas Gregor2943aed2009-03-03 04:44:36 +0000938 // Exit the scope of this instantiation.
939 CurContext = PreviousContext;
940
941 return Invalid;
942}