blob: 5fd38f71ed20b86122f9b086735f2a0c52906dbd [file] [log] [blame]
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl 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 for declarations.
10//
11//===----------------------------------------------------------------------===/
12#include "Sema.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/DeclTemplate.h"
15#include "clang/AST/DeclVisitor.h"
16#include "clang/AST/Expr.h"
17#include "llvm/Support/Compiler.h"
18
19using namespace clang;
20
21namespace {
22 class VISIBILITY_HIDDEN TemplateDeclInstantiator
23 : public DeclVisitor<TemplateDeclInstantiator, Decl *>
24 {
25 Sema &SemaRef;
26 DeclContext *Owner;
27 const TemplateArgument *TemplateArgs;
28 unsigned NumTemplateArgs;
29
30 public:
31 typedef Sema::OwningExprResult OwningExprResult;
32
33 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
34 const TemplateArgument *TemplateArgs,
35 unsigned NumTemplateArgs)
36 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs),
37 NumTemplateArgs(NumTemplateArgs) { }
38
39 // FIXME: Once we get closer to completion, replace these
40 // manually-written declarations with automatically-generated ones
41 // from clang/AST/DeclNodes.def.
42 Decl *VisitTypedefDecl(TypedefDecl *D);
43 Decl *VisitFieldDecl(FieldDecl *D);
44 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
45 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000046 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000047 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
Douglas Gregor615c5d42009-03-24 16:43:20 +000048 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000049 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000050 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000051 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000052 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
Douglas Gregor5545e162009-03-24 00:38:23 +000053
Douglas Gregor8dbc2692009-03-17 21:15:40 +000054 // Base case. FIXME: Remove once we can instantiate everything.
55 Decl *VisitDecl(Decl *) {
56 return 0;
57 }
Douglas Gregor5545e162009-03-24 00:38:23 +000058
59 // Helper functions for instantiating methods.
60 QualType InstantiateFunctionType(FunctionDecl *D,
61 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
62 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000063 };
64}
65
66Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
67 bool Invalid = false;
68 QualType T = D->getUnderlyingType();
69 if (T->isDependentType()) {
70 T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs,
71 D->getLocation(),
72 D->getDeclName());
73 if (T.isNull()) {
74 Invalid = true;
75 T = SemaRef.Context.IntTy;
76 }
77 }
78
79 // Create the new typedef
80 TypedefDecl *Typedef
81 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
82 D->getIdentifier(), T);
83 if (Invalid)
84 Typedef->setInvalidDecl();
85
86 Owner->addDecl(Typedef);
87 return Typedef;
88}
89
90Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
91 bool Invalid = false;
92 QualType T = D->getType();
93 if (T->isDependentType()) {
94 T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs,
95 D->getLocation(),
96 D->getDeclName());
97 if (!T.isNull() && T->isFunctionType()) {
98 // C++ [temp.arg.type]p3:
99 // If a declaration acquires a function type through a type
100 // dependent on a template-parameter and this causes a
101 // declaration that does not use the syntactic form of a
102 // function declarator to have function type, the program is
103 // ill-formed.
104 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
105 << T;
106 T = QualType();
107 Invalid = true;
108 }
109 }
110
111 Expr *BitWidth = D->getBitWidth();
112 if (Invalid)
113 BitWidth = 0;
114 else if (BitWidth) {
115 OwningExprResult InstantiatedBitWidth
116 = SemaRef.InstantiateExpr(BitWidth, TemplateArgs, NumTemplateArgs);
117 if (InstantiatedBitWidth.isInvalid()) {
118 Invalid = true;
119 BitWidth = 0;
120 } else
121 BitWidth = (Expr *)InstantiatedBitWidth.release();
122 }
123
124 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
125 cast<RecordDecl>(Owner),
126 D->getLocation(),
127 D->isMutable(),
128 BitWidth,
129 D->getAccess(),
130 0);
131 if (Field) {
132 if (Invalid)
133 Field->setInvalidDecl();
134
135 Owner->addDecl(Field);
136 }
137
138 return Field;
139}
140
141Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
142 Expr *AssertExpr = D->getAssertExpr();
143
144 OwningExprResult InstantiatedAssertExpr
145 = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs, NumTemplateArgs);
146 if (InstantiatedAssertExpr.isInvalid())
147 return 0;
148
149 OwningExprResult Message = SemaRef.Clone(D->getMessage());
150 Decl *StaticAssert
151 = (Decl *)SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
152 move(InstantiatedAssertExpr),
153 move(Message));
154 return StaticAssert;
155}
156
157Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
158 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
159 D->getLocation(), D->getIdentifier(),
160 /*PrevDecl=*/0);
161 Owner->addDecl(Enum);
162 Enum->startDefinition();
163
164 llvm::SmallVector<Sema::DeclTy *, 16> Enumerators;
165
166 EnumConstantDecl *LastEnumConst = 0;
167 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
168 ECEnd = D->enumerator_end();
169 EC != ECEnd; ++EC) {
170 // The specified value for the enumerator.
171 OwningExprResult Value = SemaRef.Owned((Expr *)0);
172 if (Expr *UninstValue = EC->getInitExpr())
173 Value = SemaRef.InstantiateExpr(UninstValue,
174 TemplateArgs, NumTemplateArgs);
175
176 // Drop the initial value and continue.
177 bool isInvalid = false;
178 if (Value.isInvalid()) {
179 Value = SemaRef.Owned((Expr *)0);
180 isInvalid = true;
181 }
182
183 EnumConstantDecl *EnumConst
184 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
185 EC->getLocation(), EC->getIdentifier(),
186 move(Value));
187
188 if (isInvalid) {
189 if (EnumConst)
190 EnumConst->setInvalidDecl();
191 Enum->setInvalidDecl();
192 }
193
194 if (EnumConst) {
195 Enum->addDecl(EnumConst);
196 Enumerators.push_back(EnumConst);
197 LastEnumConst = EnumConst;
198 }
199 }
200
201 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum,
202 &Enumerators[0], Enumerators.size());
203
204 return Enum;
205}
206
Douglas Gregor6477b692009-03-25 15:04:13 +0000207Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
208 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
209 return 0;
210}
211
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000212Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
213 // Only handle actual methods; we'll deal with constructors,
214 // destructors, etc. separately.
215 if (D->getKind() != Decl::CXXMethod)
216 return 0;
217
Douglas Gregor5545e162009-03-24 00:38:23 +0000218 llvm::SmallVector<ParmVarDecl *, 16> Params;
219 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000220 if (T.isNull())
221 return 0;
222
223 // Build the instantiated method declaration.
224 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
225 CXXMethodDecl *Method
226 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
227 D->getDeclName(), T, D->isStatic(),
228 D->isInline());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000229
Douglas Gregor5545e162009-03-24 00:38:23 +0000230 // Attach the parameters
231 for (unsigned P = 0; P < Params.size(); ++P)
232 Params[P]->setOwningFunction(Method);
233 Method->setParams(SemaRef.Context, &Params[0], Params.size());
234
235 if (InitMethodInstantiation(Method, D))
236 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000237
238 NamedDecl *PrevDecl
239 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
240 Sema::LookupOrdinaryName, true);
241 // In C++, the previous declaration we find might be a tag type
242 // (class or enum). In this case, the new declaration will hide the
243 // tag type. Note that this does does not apply if we're declaring a
244 // typedef (C++ [dcl.typedef]p4).
245 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
246 PrevDecl = 0;
247 bool Redeclaration = false;
248 bool OverloadableAttrRequired = false;
249 if (SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
250 /*FIXME:*/OverloadableAttrRequired))
251 Method->setInvalidDecl();
252
253 if (!Method->isInvalidDecl() || !PrevDecl)
254 Owner->addDecl(Method);
255 return Method;
256}
257
Douglas Gregor615c5d42009-03-24 16:43:20 +0000258Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
259 llvm::SmallVector<ParmVarDecl *, 16> Params;
260 QualType T = InstantiateFunctionType(D, Params);
261 if (T.isNull())
262 return 0;
263
264 // Build the instantiated method declaration.
265 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
266 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
267 DeclarationName Name
268 = SemaRef.Context.DeclarationNames.getCXXConstructorName(ClassTy);
269 CXXConstructorDecl *Constructor
270 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
271 Name, T, D->isExplicit(), D->isInline(),
272 false);
273
274 // Attach the parameters
275 for (unsigned P = 0; P < Params.size(); ++P)
276 Params[P]->setOwningFunction(Constructor);
277 Constructor->setParams(SemaRef.Context, &Params[0], Params.size());
278
279 if (InitMethodInstantiation(Constructor, D))
280 Constructor->setInvalidDecl();
281
282 NamedDecl *PrevDecl
283 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
284
285 // In C++, the previous declaration we find might be a tag type
286 // (class or enum). In this case, the new declaration will hide the
287 // tag type. Note that this does does not apply if we're declaring a
288 // typedef (C++ [dcl.typedef]p4).
289 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
290 PrevDecl = 0;
291 bool Redeclaration = false;
292 bool OverloadableAttrRequired = false;
293 if (SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
294 /*FIXME:*/OverloadableAttrRequired))
295 Constructor->setInvalidDecl();
296
297 if (!Constructor->isInvalidDecl())
298 Owner->addDecl(Constructor);
299 return Constructor;
300}
301
Douglas Gregor03b2b072009-03-24 00:15:49 +0000302Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000303 llvm::SmallVector<ParmVarDecl *, 16> Params;
304 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000305 if (T.isNull())
306 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +0000307 assert(Params.size() == 0 && "Destructor with parameters?");
308
Douglas Gregor03b2b072009-03-24 00:15:49 +0000309 // Build the instantiated destructor declaration.
310 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
311 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
312 CXXDestructorDecl *Destructor
313 = CXXDestructorDecl::Create(SemaRef.Context, Record,
314 D->getLocation(),
315 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
316 T, D->isInline(), false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000317 if (InitMethodInstantiation(Destructor, D))
318 Destructor->setInvalidDecl();
Douglas Gregor03b2b072009-03-24 00:15:49 +0000319
320 bool Redeclaration = false;
321 bool OverloadableAttrRequired = false;
322 NamedDecl *PrevDecl = 0;
323 if (SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
324 /*FIXME:*/OverloadableAttrRequired))
325 Destructor->setInvalidDecl();
326 Owner->addDecl(Destructor);
327 return Destructor;
328}
329
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000330Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
331 llvm::SmallVector<ParmVarDecl *, 16> Params;
332 QualType T = InstantiateFunctionType(D, Params);
333 if (T.isNull())
334 return 0;
335 assert(Params.size() == 0 && "Destructor with parameters?");
336
337 // Build the instantiated conversion declaration.
338 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
339 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
340 QualType ConvTy
341 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
342 CXXConversionDecl *Conversion
343 = CXXConversionDecl::Create(SemaRef.Context, Record,
344 D->getLocation(),
345 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
346 T, D->isInline(), D->isExplicit());
347 if (InitMethodInstantiation(Conversion, D))
348 Conversion->setInvalidDecl();
349
350 bool Redeclaration = false;
351 bool OverloadableAttrRequired = false;
352 NamedDecl *PrevDecl = 0;
353 if (SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
354 /*FIXME:*/OverloadableAttrRequired))
355 Conversion->setInvalidDecl();
356 Owner->addDecl(Conversion);
357 return Conversion;
358}
359
Douglas Gregor6477b692009-03-25 15:04:13 +0000360ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000361 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
362 NumTemplateArgs, D->getLocation(),
363 D->getDeclName());
364 if (OrigT.isNull())
365 return 0;
366
367 QualType T = SemaRef.adjustParameterType(OrigT);
368
369 if (D->getDefaultArg()) {
370 // FIXME: Leave a marker for "uninstantiated" default
371 // arguments. They only get instantiated on demand at the call
372 // site.
373 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
374 "sorry, dropping default argument during template instantiation");
375 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
376 << D->getDefaultArg()->getSourceRange();
377 }
378
379 // Allocate the parameter
380 ParmVarDecl *Param = 0;
381 if (T == OrigT)
382 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
383 D->getIdentifier(), T, D->getStorageClass(),
384 0);
385 else
386 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
387 D->getLocation(), D->getIdentifier(),
388 T, OrigT, D->getStorageClass(), 0);
389
390 // Note: we don't try to instantiate function parameters until after
391 // we've instantiated the function's type. Therefore, we don't have
392 // to check for 'void' parameter types here.
393 return Param;
394}
395
396Decl *
397TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
398 // Since parameter types can decay either before or after
399 // instantiation, we simply treat OriginalParmVarDecls as
400 // ParmVarDecls the same way, and create one or the other depending
401 // on what happens after template instantiation.
402 return VisitParmVarDecl(D);
403}
404
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000405Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
406 const TemplateArgument *TemplateArgs,
407 unsigned NumTemplateArgs) {
408 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs,
409 NumTemplateArgs);
410 return Instantiator.Visit(D);
411}
412
Douglas Gregor5545e162009-03-24 00:38:23 +0000413/// \brief Instantiates the type of the given function, including
414/// instantiating all of the function parameters.
415///
416/// \param D The function that we will be instantiated
417///
418/// \param Params the instantiated parameter declarations
419
420/// \returns the instantiated function's type if successfull, a NULL
421/// type if there was an error.
422QualType
423TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
424 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
425 bool InvalidDecl = false;
426
427 // Instantiate the function parameters
428 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0,
429 TemplateArgs, NumTemplateArgs);
430 llvm::SmallVector<QualType, 16> ParamTys;
431 for (FunctionDecl::param_iterator P = D->param_begin(),
432 PEnd = D->param_end();
433 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000434 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000435 if (PInst->getType()->isVoidType()) {
436 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
437 PInst->setInvalidDecl();
438 }
439 else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
440 PInst->getType(),
441 diag::err_abstract_type_in_decl,
Anders Carlsson8211eff2009-03-24 01:19:16 +0000442 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000443 PInst->setInvalidDecl();
444
445 Params.push_back(PInst);
446 ParamTys.push_back(PInst->getType());
447
448 if (PInst->isInvalidDecl())
449 InvalidDecl = true;
450 } else
451 InvalidDecl = true;
452 }
453
454 // FIXME: Deallocate dead declarations.
455 if (InvalidDecl)
456 return QualType();
457
458 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
459 assert(Proto && "Missing prototype?");
460 QualType ResultType
461 = SemaRef.InstantiateType(Proto->getResultType(),
462 TemplateArgs, NumTemplateArgs,
463 D->getLocation(), D->getDeclName());
464 if (ResultType.isNull())
465 return QualType();
466
467 return SemaRef.BuildFunctionType(ResultType, &ParamTys[0], ParamTys.size(),
468 Proto->isVariadic(), Proto->getTypeQuals(),
469 D->getLocation(), D->getDeclName());
470}
471
472/// \brief Initializes common fields of an instantiated method
473/// declaration (New) from the corresponding fields of its template
474/// (Tmpl).
475///
476/// \returns true if there was an error
477bool
478TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
479 CXXMethodDecl *Tmpl) {
480 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
481 New->setAccess(Tmpl->getAccess());
482 if (Tmpl->isVirtual()) {
483 New->setVirtual();
484 Record->setAggregate(false);
485 Record->setPOD(false);
486 Record->setPolymorphic(true);
487 }
488 if (Tmpl->isDeleted())
489 New->setDeleted();
490 if (Tmpl->isPure()) {
491 New->setPure();
492 Record->setAbstract(true);
493 }
494
495 // FIXME: attributes
496 // FIXME: New needs a pointer to Tmpl
497 return false;
498}