1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
9 // This file implements C++ template instantiation for declarations.
11 //===----------------------------------------------------------------------===/
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/DeclVisitor.h"
17 #include "clang/AST/Expr.h"
18 #include "llvm/Support/Compiler.h"
20 using namespace clang
;
23 class VISIBILITY_HIDDEN TemplateDeclInstantiator
24 : public DeclVisitor
<TemplateDeclInstantiator
, Decl
*> {
27 const TemplateArgumentList
&TemplateArgs
;
30 typedef Sema::OwningExprResult OwningExprResult
;
32 TemplateDeclInstantiator(Sema
&SemaRef
, DeclContext
*Owner
,
33 const TemplateArgumentList
&TemplateArgs
)
34 : SemaRef(SemaRef
), Owner(Owner
), TemplateArgs(TemplateArgs
) { }
36 // FIXME: Once we get closer to completion, replace these manually-written
37 // declarations with automatically-generated ones from
38 // clang/AST/DeclNodes.def.
39 Decl
*VisitTranslationUnitDecl(TranslationUnitDecl
*D
);
40 Decl
*VisitNamespaceDecl(NamespaceDecl
*D
);
41 Decl
*VisitTypedefDecl(TypedefDecl
*D
);
42 Decl
*VisitVarDecl(VarDecl
*D
);
43 Decl
*VisitFieldDecl(FieldDecl
*D
);
44 Decl
*VisitStaticAssertDecl(StaticAssertDecl
*D
);
45 Decl
*VisitEnumDecl(EnumDecl
*D
);
46 Decl
*VisitEnumConstantDecl(EnumConstantDecl
*D
);
47 Decl
*VisitFunctionDecl(FunctionDecl
*D
);
48 Decl
*VisitCXXRecordDecl(CXXRecordDecl
*D
);
49 Decl
*VisitCXXMethodDecl(CXXMethodDecl
*D
);
50 Decl
*VisitCXXConstructorDecl(CXXConstructorDecl
*D
);
51 Decl
*VisitCXXDestructorDecl(CXXDestructorDecl
*D
);
52 Decl
*VisitCXXConversionDecl(CXXConversionDecl
*D
);
53 ParmVarDecl
*VisitParmVarDecl(ParmVarDecl
*D
);
54 Decl
*VisitOriginalParmVarDecl(OriginalParmVarDecl
*D
);
56 // Base case. FIXME: Remove once we can instantiate everything.
57 Decl
*VisitDecl(Decl
*) {
58 assert(false && "Template instantiation of unknown declaration kind!");
62 // Helper functions for instantiating methods.
63 QualType
InstantiateFunctionType(FunctionDecl
*D
,
64 llvm::SmallVectorImpl
<ParmVarDecl
*> &Params
);
65 bool InitFunctionInstantiation(FunctionDecl
*New
, FunctionDecl
*Tmpl
);
66 bool InitMethodInstantiation(CXXMethodDecl
*New
, CXXMethodDecl
*Tmpl
);
71 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl
*D
) {
72 assert(false && "Translation units cannot be instantiated");
77 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl
*D
) {
78 assert(false && "Namespaces cannot be instantiated");
82 Decl
*TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl
*D
) {
84 QualType T
= D
->getUnderlyingType();
85 if (T
->isDependentType()) {
86 T
= SemaRef
.InstantiateType(T
, TemplateArgs
,
87 D
->getLocation(), D
->getDeclName());
90 T
= SemaRef
.Context
.IntTy
;
94 // Create the new typedef
96 = TypedefDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
97 D
->getIdentifier(), T
);
99 Typedef
->setInvalidDecl();
101 Owner
->addDecl(Typedef
);
106 Decl
*TemplateDeclInstantiator::VisitVarDecl(VarDecl
*D
) {
107 // Instantiate the type of the declaration
108 QualType T
= SemaRef
.InstantiateType(D
->getType(), TemplateArgs
,
109 D
->getTypeSpecStartLoc(),
114 // Build the instantiated declaration
115 VarDecl
*Var
= VarDecl::Create(SemaRef
.Context
, Owner
,
116 D
->getLocation(), D
->getIdentifier(),
117 T
, D
->getStorageClass(),
118 D
->getTypeSpecStartLoc());
119 Var
->setThreadSpecified(D
->isThreadSpecified());
120 Var
->setCXXDirectInitializer(D
->hasCXXDirectInitializer());
121 Var
->setDeclaredInCondition(D
->isDeclaredInCondition());
123 // FIXME: In theory, we could have a previous declaration for variables that
124 // are not static data members.
125 bool Redeclaration
= false;
126 SemaRef
.CheckVariableDeclaration(Var
, 0, Redeclaration
);
130 OwningExprResult Init
131 = SemaRef
.InstantiateExpr(D
->getInit(), TemplateArgs
);
132 if (Init
.isInvalid())
133 Var
->setInvalidDecl();
135 SemaRef
.AddInitializerToDecl(Sema::DeclPtrTy::make(Var
), move(Init
),
136 D
->hasCXXDirectInitializer());
138 // FIXME: Call ActOnUninitializedDecl? (Not always)
144 Decl
*TemplateDeclInstantiator::VisitFieldDecl(FieldDecl
*D
) {
145 bool Invalid
= false;
146 QualType T
= D
->getType();
147 if (T
->isDependentType()) {
148 T
= SemaRef
.InstantiateType(T
, TemplateArgs
,
149 D
->getLocation(), D
->getDeclName());
150 if (!T
.isNull() && T
->isFunctionType()) {
151 // C++ [temp.arg.type]p3:
152 // If a declaration acquires a function type through a type
153 // dependent on a template-parameter and this causes a
154 // declaration that does not use the syntactic form of a
155 // function declarator to have function type, the program is
157 SemaRef
.Diag(D
->getLocation(), diag::err_field_instantiates_to_function
)
164 Expr
*BitWidth
= D
->getBitWidth();
168 // The bit-width expression is not potentially evaluated.
169 EnterExpressionEvaluationContext
Unevaluated(SemaRef
, Action::Unevaluated
);
171 OwningExprResult InstantiatedBitWidth
172 = SemaRef
.InstantiateExpr(BitWidth
, TemplateArgs
);
173 if (InstantiatedBitWidth
.isInvalid()) {
177 BitWidth
= InstantiatedBitWidth
.takeAs
<Expr
>();
180 FieldDecl
*Field
= SemaRef
.CheckFieldDecl(D
->getDeclName(), T
,
181 cast
<RecordDecl
>(Owner
),
185 D
->getTypeSpecStartLoc(),
190 Field
->setInvalidDecl();
192 Owner
->addDecl(Field
);
198 Decl
*TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl
*D
) {
199 Expr
*AssertExpr
= D
->getAssertExpr();
201 // The expression in a static assertion is not potentially evaluated.
202 EnterExpressionEvaluationContext
Unevaluated(SemaRef
, Action::Unevaluated
);
204 OwningExprResult InstantiatedAssertExpr
205 = SemaRef
.InstantiateExpr(AssertExpr
, TemplateArgs
);
206 if (InstantiatedAssertExpr
.isInvalid())
209 OwningExprResult Message
= SemaRef
.Clone(D
->getMessage());
211 = SemaRef
.ActOnStaticAssertDeclaration(D
->getLocation(),
212 move(InstantiatedAssertExpr
),
213 move(Message
)).getAs
<Decl
>();
217 Decl
*TemplateDeclInstantiator::VisitEnumDecl(EnumDecl
*D
) {
218 EnumDecl
*Enum
= EnumDecl::Create(SemaRef
.Context
, Owner
,
219 D
->getLocation(), D
->getIdentifier(),
221 Enum
->setInstantiationOfMemberEnum(D
);
222 Enum
->setAccess(D
->getAccess());
223 Owner
->addDecl(Enum
);
224 Enum
->startDefinition();
226 llvm::SmallVector
<Sema::DeclPtrTy
, 4> Enumerators
;
228 EnumConstantDecl
*LastEnumConst
= 0;
229 for (EnumDecl::enumerator_iterator EC
= D
->enumerator_begin(),
230 ECEnd
= D
->enumerator_end();
232 // The specified value for the enumerator.
233 OwningExprResult Value
= SemaRef
.Owned((Expr
*)0);
234 if (Expr
*UninstValue
= EC
->getInitExpr()) {
235 // The enumerator's value expression is not potentially evaluated.
236 EnterExpressionEvaluationContext
Unevaluated(SemaRef
,
237 Action::Unevaluated
);
239 Value
= SemaRef
.InstantiateExpr(UninstValue
, TemplateArgs
);
242 // Drop the initial value and continue.
243 bool isInvalid
= false;
244 if (Value
.isInvalid()) {
245 Value
= SemaRef
.Owned((Expr
*)0);
249 EnumConstantDecl
*EnumConst
250 = SemaRef
.CheckEnumConstant(Enum
, LastEnumConst
,
251 EC
->getLocation(), EC
->getIdentifier(),
256 EnumConst
->setInvalidDecl();
257 Enum
->setInvalidDecl();
261 Enum
->addDecl(EnumConst
);
262 Enumerators
.push_back(Sema::DeclPtrTy::make(EnumConst
));
263 LastEnumConst
= EnumConst
;
267 // FIXME: Fixup LBraceLoc and RBraceLoc
268 SemaRef
.ActOnEnumBody(Enum
->getLocation(), SourceLocation(), SourceLocation(),
269 Sema::DeclPtrTy::make(Enum
),
270 &Enumerators
[0], Enumerators
.size());
275 Decl
*TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl
*D
) {
276 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
280 Decl
*TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl
*D
) {
281 CXXRecordDecl
*PrevDecl
= 0;
282 if (D
->isInjectedClassName())
283 PrevDecl
= cast
<CXXRecordDecl
>(Owner
);
285 CXXRecordDecl
*Record
286 = CXXRecordDecl::Create(SemaRef
.Context
, D
->getTagKind(), Owner
,
287 D
->getLocation(), D
->getIdentifier(), PrevDecl
);
288 Record
->setImplicit(D
->isImplicit());
289 Record
->setAccess(D
->getAccess());
290 if (!D
->isInjectedClassName())
291 Record
->setInstantiationOfMemberClass(D
);
293 Owner
->addDecl(Record
);
297 Decl
*TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl
*D
) {
298 // Check whether there is already a function template specialization for
300 FunctionTemplateDecl
*FunctionTemplate
= D
->getDescribedFunctionTemplate();
302 if (FunctionTemplate
) {
303 llvm::FoldingSetNodeID ID
;
304 FunctionTemplateSpecializationInfo::Profile(ID
,
305 TemplateArgs
.getFlatArgumentList(),
306 TemplateArgs
.flat_size());
308 FunctionTemplateSpecializationInfo
*Info
309 = FunctionTemplate
->getSpecializations().FindNodeOrInsertPos(ID
,
312 // If we already have a function template specialization, return it.
314 return Info
->Function
;
317 Sema::LocalInstantiationScope
Scope(SemaRef
);
319 llvm::SmallVector
<ParmVarDecl
*, 4> Params
;
320 QualType T
= InstantiateFunctionType(D
, Params
);
324 // Build the instantiated method declaration.
325 FunctionDecl
*Function
326 = FunctionDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
327 D
->getDeclName(), T
, D
->getStorageClass(),
328 D
->isInline(), D
->hasWrittenPrototype(),
329 D
->getTypeSpecStartLoc());
331 // FIXME: friend functions
333 // Attach the parameters
334 for (unsigned P
= 0; P
< Params
.size(); ++P
)
335 Params
[P
]->setOwningFunction(Function
);
336 Function
->setParams(SemaRef
.Context
, Params
.data(), Params
.size());
338 if (InitFunctionInstantiation(Function
, D
))
339 Function
->setInvalidDecl();
341 bool Redeclaration
= false;
342 bool OverloadableAttrRequired
= false;
343 NamedDecl
*PrevDecl
= 0;
344 SemaRef
.CheckFunctionDeclaration(Function
, PrevDecl
, Redeclaration
,
345 /*FIXME:*/OverloadableAttrRequired
);
347 if (FunctionTemplate
) {
348 // Record this function template specialization.
349 Function
->setFunctionTemplateSpecialization(SemaRef
.Context
,
358 Decl
*TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl
*D
) {
359 // FIXME: Look for existing, explicit specializations.
360 Sema::LocalInstantiationScope
Scope(SemaRef
);
362 llvm::SmallVector
<ParmVarDecl
*, 4> Params
;
363 QualType T
= InstantiateFunctionType(D
, Params
);
367 // Build the instantiated method declaration.
368 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(Owner
);
369 CXXMethodDecl
*Method
370 = CXXMethodDecl::Create(SemaRef
.Context
, Record
, D
->getLocation(),
371 D
->getDeclName(), T
, D
->isStatic(),
373 Method
->setInstantiationOfMemberFunction(D
);
375 // Attach the parameters
376 for (unsigned P
= 0; P
< Params
.size(); ++P
)
377 Params
[P
]->setOwningFunction(Method
);
378 Method
->setParams(SemaRef
.Context
, Params
.data(), Params
.size());
380 if (InitMethodInstantiation(Method
, D
))
381 Method
->setInvalidDecl();
384 = SemaRef
.LookupQualifiedName(Owner
, Method
->getDeclName(),
385 Sema::LookupOrdinaryName
, true);
386 // In C++, the previous declaration we find might be a tag type
387 // (class or enum). In this case, the new declaration will hide the
388 // tag type. Note that this does does not apply if we're declaring a
389 // typedef (C++ [dcl.typedef]p4).
390 if (PrevDecl
&& PrevDecl
->getIdentifierNamespace() == Decl::IDNS_Tag
)
392 bool Redeclaration
= false;
393 bool OverloadableAttrRequired
= false;
394 SemaRef
.CheckFunctionDeclaration(Method
, PrevDecl
, Redeclaration
,
395 /*FIXME:*/OverloadableAttrRequired
);
397 if (!Method
->isInvalidDecl() || !PrevDecl
)
398 Owner
->addDecl(Method
);
402 Decl
*TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl
*D
) {
403 // FIXME: Look for existing, explicit specializations.
404 Sema::LocalInstantiationScope
Scope(SemaRef
);
406 llvm::SmallVector
<ParmVarDecl
*, 4> Params
;
407 QualType T
= InstantiateFunctionType(D
, Params
);
411 // Build the instantiated method declaration.
412 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(Owner
);
413 QualType ClassTy
= SemaRef
.Context
.getTypeDeclType(Record
);
415 = SemaRef
.Context
.DeclarationNames
.getCXXConstructorName(
416 SemaRef
.Context
.getCanonicalType(ClassTy
));
417 CXXConstructorDecl
*Constructor
418 = CXXConstructorDecl::Create(SemaRef
.Context
, Record
, D
->getLocation(),
419 Name
, T
, D
->isExplicit(), D
->isInline(),
421 Constructor
->setInstantiationOfMemberFunction(D
);
423 // Attach the parameters
424 for (unsigned P
= 0; P
< Params
.size(); ++P
)
425 Params
[P
]->setOwningFunction(Constructor
);
426 Constructor
->setParams(SemaRef
.Context
, Params
.data(), Params
.size());
428 if (InitMethodInstantiation(Constructor
, D
))
429 Constructor
->setInvalidDecl();
432 = SemaRef
.LookupQualifiedName(Owner
, Name
, Sema::LookupOrdinaryName
, true);
434 // In C++, the previous declaration we find might be a tag type
435 // (class or enum). In this case, the new declaration will hide the
436 // tag type. Note that this does does not apply if we're declaring a
437 // typedef (C++ [dcl.typedef]p4).
438 if (PrevDecl
&& PrevDecl
->getIdentifierNamespace() == Decl::IDNS_Tag
)
440 bool Redeclaration
= false;
441 bool OverloadableAttrRequired
= false;
442 SemaRef
.CheckFunctionDeclaration(Constructor
, PrevDecl
, Redeclaration
,
443 /*FIXME:*/OverloadableAttrRequired
);
445 Record
->addedConstructor(SemaRef
.Context
, Constructor
);
446 Owner
->addDecl(Constructor
);
450 Decl
*TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl
*D
) {
451 // FIXME: Look for existing, explicit specializations.
452 Sema::LocalInstantiationScope
Scope(SemaRef
);
454 llvm::SmallVector
<ParmVarDecl
*, 4> Params
;
455 QualType T
= InstantiateFunctionType(D
, Params
);
458 assert(Params
.size() == 0 && "Destructor with parameters?");
460 // Build the instantiated destructor declaration.
461 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(Owner
);
463 SemaRef
.Context
.getCanonicalType(SemaRef
.Context
.getTypeDeclType(Record
));
464 CXXDestructorDecl
*Destructor
465 = CXXDestructorDecl::Create(SemaRef
.Context
, Record
,
467 SemaRef
.Context
.DeclarationNames
.getCXXDestructorName(ClassTy
),
468 T
, D
->isInline(), false);
469 Destructor
->setInstantiationOfMemberFunction(D
);
470 if (InitMethodInstantiation(Destructor
, D
))
471 Destructor
->setInvalidDecl();
473 bool Redeclaration
= false;
474 bool OverloadableAttrRequired
= false;
475 NamedDecl
*PrevDecl
= 0;
476 SemaRef
.CheckFunctionDeclaration(Destructor
, PrevDecl
, Redeclaration
,
477 /*FIXME:*/OverloadableAttrRequired
);
478 Owner
->addDecl(Destructor
);
482 Decl
*TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl
*D
) {
483 // FIXME: Look for existing, explicit specializations.
484 Sema::LocalInstantiationScope
Scope(SemaRef
);
486 llvm::SmallVector
<ParmVarDecl
*, 4> Params
;
487 QualType T
= InstantiateFunctionType(D
, Params
);
490 assert(Params
.size() == 0 && "Destructor with parameters?");
492 // Build the instantiated conversion declaration.
493 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(Owner
);
494 QualType ClassTy
= SemaRef
.Context
.getTypeDeclType(Record
);
496 = SemaRef
.Context
.getCanonicalType(T
->getAsFunctionType()->getResultType());
497 CXXConversionDecl
*Conversion
498 = CXXConversionDecl::Create(SemaRef
.Context
, Record
,
500 SemaRef
.Context
.DeclarationNames
.getCXXConversionFunctionName(ConvTy
),
501 T
, D
->isInline(), D
->isExplicit());
502 Conversion
->setInstantiationOfMemberFunction(D
);
503 if (InitMethodInstantiation(Conversion
, D
))
504 Conversion
->setInvalidDecl();
506 bool Redeclaration
= false;
507 bool OverloadableAttrRequired
= false;
508 NamedDecl
*PrevDecl
= 0;
509 SemaRef
.CheckFunctionDeclaration(Conversion
, PrevDecl
, Redeclaration
,
510 /*FIXME:*/OverloadableAttrRequired
);
511 Owner
->addDecl(Conversion
);
515 ParmVarDecl
*TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl
*D
) {
516 QualType OrigT
= SemaRef
.InstantiateType(D
->getOriginalType(), TemplateArgs
,
517 D
->getLocation(), D
->getDeclName());
521 QualType T
= SemaRef
.adjustParameterType(OrigT
);
523 if (D
->getDefaultArg()) {
524 // FIXME: Leave a marker for "uninstantiated" default
525 // arguments. They only get instantiated on demand at the call
527 unsigned DiagID
= SemaRef
.Diags
.getCustomDiagID(Diagnostic::Warning
,
528 "sorry, dropping default argument during template instantiation");
529 SemaRef
.Diag(D
->getDefaultArg()->getSourceRange().getBegin(), DiagID
)
530 << D
->getDefaultArg()->getSourceRange();
533 // Allocate the parameter
534 ParmVarDecl
*Param
= 0;
536 Param
= ParmVarDecl::Create(SemaRef
.Context
, Owner
, D
->getLocation(),
537 D
->getIdentifier(), T
, D
->getStorageClass(),
540 Param
= OriginalParmVarDecl::Create(SemaRef
.Context
, Owner
,
541 D
->getLocation(), D
->getIdentifier(),
542 T
, OrigT
, D
->getStorageClass(), 0);
544 // Note: we don't try to instantiate function parameters until after
545 // we've instantiated the function's type. Therefore, we don't have
546 // to check for 'void' parameter types here.
547 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(D
, Param
);
552 TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl
*D
) {
553 // Since parameter types can decay either before or after
554 // instantiation, we simply treat OriginalParmVarDecls as
555 // ParmVarDecls the same way, and create one or the other depending
556 // on what happens after template instantiation.
557 return VisitParmVarDecl(D
);
560 Decl
*Sema::InstantiateDecl(Decl
*D
, DeclContext
*Owner
,
561 const TemplateArgumentList
&TemplateArgs
) {
562 TemplateDeclInstantiator
Instantiator(*this, Owner
, TemplateArgs
);
563 return Instantiator
.Visit(D
);
566 /// \brief Instantiates the type of the given function, including
567 /// instantiating all of the function parameters.
569 /// \param D The function that we will be instantiated
571 /// \param Params the instantiated parameter declarations
573 /// \returns the instantiated function's type if successfull, a NULL
574 /// type if there was an error.
576 TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl
*D
,
577 llvm::SmallVectorImpl
<ParmVarDecl
*> &Params
) {
578 bool InvalidDecl
= false;
580 // Instantiate the function parameters
581 TemplateDeclInstantiator
ParamInstantiator(SemaRef
, 0, TemplateArgs
);
582 llvm::SmallVector
<QualType
, 4> ParamTys
;
583 for (FunctionDecl::param_iterator P
= D
->param_begin(),
584 PEnd
= D
->param_end();
586 if (ParmVarDecl
*PInst
= ParamInstantiator
.VisitParmVarDecl(*P
)) {
587 if (PInst
->getType()->isVoidType()) {
588 SemaRef
.Diag(PInst
->getLocation(), diag::err_param_with_void_type
);
589 PInst
->setInvalidDecl();
591 else if (SemaRef
.RequireNonAbstractType(PInst
->getLocation(),
593 diag::err_abstract_type_in_decl
,
594 Sema::AbstractParamType
))
595 PInst
->setInvalidDecl();
597 Params
.push_back(PInst
);
598 ParamTys
.push_back(PInst
->getType());
600 if (PInst
->isInvalidDecl())
606 // FIXME: Deallocate dead declarations.
610 const FunctionProtoType
*Proto
= D
->getType()->getAsFunctionProtoType();
611 assert(Proto
&& "Missing prototype?");
613 = SemaRef
.InstantiateType(Proto
->getResultType(), TemplateArgs
,
614 D
->getLocation(), D
->getDeclName());
615 if (ResultType
.isNull())
618 return SemaRef
.BuildFunctionType(ResultType
, ParamTys
.data(), ParamTys
.size(),
619 Proto
->isVariadic(), Proto
->getTypeQuals(),
620 D
->getLocation(), D
->getDeclName());
623 /// \brief Initializes the common fields of an instantiation function
624 /// declaration (New) from the corresponding fields of its template (Tmpl).
626 /// \returns true if there was an error
628 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl
*New
,
629 FunctionDecl
*Tmpl
) {
630 if (Tmpl
->isDeleted())
633 // If we are performing substituting explicitly-specified template arguments
634 // or deduced template arguments into a function template and we reach this
635 // point, we are now past the point where SFINAE applies and have committed
636 // to keeping the new function template specialization. We therefore
637 // convert the active template instantiation for the function template
638 // into a template instantiation for this specific function template
639 // specialization, which is not a SFINAE context, so that we diagnose any
640 // further errors in the declaration itself.
641 typedef Sema::ActiveTemplateInstantiation ActiveInstType
;
642 ActiveInstType
&ActiveInst
= SemaRef
.ActiveTemplateInstantiations
.back();
643 if (ActiveInst
.Kind
== ActiveInstType::ExplicitTemplateArgumentSubstitution
||
644 ActiveInst
.Kind
== ActiveInstType::DeducedTemplateArgumentSubstitution
) {
645 if (FunctionTemplateDecl
*FunTmpl
646 = dyn_cast
<FunctionTemplateDecl
>((Decl
*)ActiveInst
.Entity
)) {
647 assert(FunTmpl
->getTemplatedDecl() == Tmpl
&&
648 "Deduction from the wrong function template?");
650 ActiveInst
.Kind
= ActiveInstType::TemplateInstantiation
;
651 ActiveInst
.Entity
= reinterpret_cast<uintptr_t>(New
);
658 /// \brief Initializes common fields of an instantiated method
659 /// declaration (New) from the corresponding fields of its template
662 /// \returns true if there was an error
664 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl
*New
,
665 CXXMethodDecl
*Tmpl
) {
666 if (InitFunctionInstantiation(New
, Tmpl
))
669 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(Owner
);
670 New
->setAccess(Tmpl
->getAccess());
671 if (Tmpl
->isVirtualAsWritten()) {
672 New
->setVirtualAsWritten(true);
673 Record
->setAggregate(false);
674 Record
->setPOD(false);
675 Record
->setPolymorphic(true);
677 if (Tmpl
->isPure()) {
679 Record
->setAbstract(true);
683 // FIXME: New needs a pointer to Tmpl
687 /// \brief Instantiate the definition of the given function from its
690 /// \param PointOfInstantiation the point at which the instantiation was
691 /// required. Note that this is not precisely a "point of instantiation"
692 /// for the function, but it's close.
694 /// \param Function the already-instantiated declaration of a
695 /// function template specialization or member function of a class template
698 /// \param Recursive if true, recursively instantiates any functions that
699 /// are required by this instantiation.
700 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation
,
701 FunctionDecl
*Function
,
703 if (Function
->isInvalidDecl())
706 assert(!Function
->getBody() && "Already instantiated!");
708 // Find the function body that we'll be substituting.
709 const FunctionDecl
*PatternDecl
= 0;
710 if (FunctionTemplateDecl
*Primary
= Function
->getPrimaryTemplate())
711 PatternDecl
= Primary
->getTemplatedDecl();
713 PatternDecl
= Function
->getInstantiatedFromMemberFunction();
716 Pattern
= PatternDecl
->getBody(PatternDecl
);
721 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Function
);
725 // If we're performing recursive template instantiation, create our own
726 // queue of pending implicit instantiations that we will instantiate later,
727 // while we're still within our own instantiation context.
728 std::deque
<PendingImplicitInstantiation
> SavedPendingImplicitInstantiations
;
730 PendingImplicitInstantiations
.swap(SavedPendingImplicitInstantiations
);
732 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function
));
734 // Introduce a new scope where local variable instantiations will be
736 LocalInstantiationScope
Scope(*this);
738 // Introduce the instantiated function parameters into the local
739 // instantiation scope.
740 for (unsigned I
= 0, N
= PatternDecl
->getNumParams(); I
!= N
; ++I
)
741 Scope
.InstantiatedLocal(PatternDecl
->getParamDecl(I
),
742 Function
->getParamDecl(I
));
744 // Enter the scope of this instantiation. We don't use
745 // PushDeclContext because we don't have a scope.
746 DeclContext
*PreviousContext
= CurContext
;
747 CurContext
= Function
;
749 // Instantiate the function body.
750 OwningStmtResult Body
751 = InstantiateStmt(Pattern
, getTemplateInstantiationArgs(Function
));
753 ActOnFinishFunctionBody(DeclPtrTy::make(Function
), move(Body
),
754 /*IsInstantiation=*/true);
756 CurContext
= PreviousContext
;
758 DeclGroupRef
DG(Function
);
759 Consumer
.HandleTopLevelDecl(DG
);
762 // Instantiate any pending implicit instantiations found during the
763 // instantiation of this template.
764 PerformPendingImplicitInstantiations();
766 // Restore the set of pending implicit instantiations.
767 PendingImplicitInstantiations
.swap(SavedPendingImplicitInstantiations
);
771 /// \brief Instantiate the definition of the given variable from its
774 /// \param Var the already-instantiated declaration of a variable.
775 void Sema::InstantiateVariableDefinition(VarDecl
*Var
) {
776 // FIXME: Implement this!
779 static bool isInstantiationOf(ASTContext
&Ctx
, NamedDecl
*D
, Decl
*Other
) {
780 if (D
->getKind() != Other
->getKind())
783 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(Other
))
784 return Record
->getInstantiatedFromMemberClass()->getCanonicalDecl()
785 == D
->getCanonicalDecl();
787 if (FunctionDecl
*Function
= dyn_cast
<FunctionDecl
>(Other
))
788 return Function
->getInstantiatedFromMemberFunction()->getCanonicalDecl()
789 == D
->getCanonicalDecl();
791 if (EnumDecl
*Enum
= dyn_cast
<EnumDecl
>(Other
))
792 return Enum
->getInstantiatedFromMemberEnum()->getCanonicalDecl()
793 == D
->getCanonicalDecl();
795 // FIXME: How can we find instantiations of anonymous unions?
797 return D
->getDeclName() && isa
<NamedDecl
>(Other
) &&
798 D
->getDeclName() == cast
<NamedDecl
>(Other
)->getDeclName();
801 template<typename ForwardIterator
>
802 static NamedDecl
*findInstantiationOf(ASTContext
&Ctx
,
804 ForwardIterator first
,
805 ForwardIterator last
) {
806 for (; first
!= last
; ++first
)
807 if (isInstantiationOf(Ctx
, D
, *first
))
808 return cast
<NamedDecl
>(*first
);
813 /// \brief Find the instantiation of the given declaration within the
814 /// current instantiation.
816 /// This routine is intended to be used when \p D is a declaration
817 /// referenced from within a template, that needs to mapped into the
818 /// corresponding declaration within an instantiation. For example,
822 /// template<typename T>
825 /// KnownValue = sizeof(T)
828 /// bool getKind() const { return KnownValue; }
831 /// template struct X<int>;
834 /// In the instantiation of X<int>::getKind(), we need to map the
835 /// EnumConstantDecl for KnownValue (which refers to
836 /// X<T>::<Kind>::KnownValue) to its instantiation
837 /// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
838 /// this mapping from within the instantiation of X<int>.
839 NamedDecl
* Sema::InstantiateCurrentDeclRef(NamedDecl
*D
) {
840 DeclContext
*ParentDC
= D
->getDeclContext();
841 if (isa
<ParmVarDecl
>(D
) || ParentDC
->isFunctionOrMethod()) {
842 // D is a local of some kind. Look into the map of local
843 // declarations to their instantiations.
844 return cast
<NamedDecl
>(CurrentInstantiationScope
->getInstantiationOf(D
));
847 if (NamedDecl
*ParentDecl
= dyn_cast
<NamedDecl
>(ParentDC
)) {
848 ParentDecl
= InstantiateCurrentDeclRef(ParentDecl
);
852 ParentDC
= cast
<DeclContext
>(ParentDecl
);
855 if (ParentDC
!= D
->getDeclContext()) {
856 // We performed some kind of instantiation in the parent context,
857 // so now we need to look into the instantiated parent context to
858 // find the instantiation of the declaration D.
859 NamedDecl
*Result
= 0;
860 if (D
->getDeclName()) {
861 DeclContext::lookup_result Found
= ParentDC
->lookup(D
->getDeclName());
862 Result
= findInstantiationOf(Context
, D
, Found
.first
, Found
.second
);
864 // Since we don't have a name for the entity we're looking for,
865 // our only option is to walk through all of the declarations to
866 // find that name. This will occur in a few cases:
868 // - anonymous struct/union within a template
869 // - unnamed class/struct/union/enum within a template
871 // FIXME: Find a better way to find these instantiations!
872 Result
= findInstantiationOf(Context
, D
,
873 ParentDC
->decls_begin(),
874 ParentDC
->decls_end());
876 assert(Result
&& "Unable to find instantiation of declaration!");
880 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(D
))
881 if (ClassTemplateDecl
*ClassTemplate
882 = Record
->getDescribedClassTemplate()) {
883 // When the declaration D was parsed, it referred to the current
884 // instantiation. Therefore, look through the current context,
885 // which contains actual instantiations, to find the
886 // instantiation of the "current instantiation" that D refers
887 // to. Alternatively, we could just instantiate the
888 // injected-class-name with the current template arguments, but
889 // such an instantiation is far more expensive.
890 for (DeclContext
*DC
= CurContext
; !DC
->isFileContext();
891 DC
= DC
->getParent()) {
892 if (ClassTemplateSpecializationDecl
*Spec
893 = dyn_cast
<ClassTemplateSpecializationDecl
>(DC
))
894 if (Spec
->getSpecializedTemplate()->getCanonicalDecl()
895 == ClassTemplate
->getCanonicalDecl())
900 "Unable to find declaration for the current instantiation");
906 /// \brief Performs template instantiation for all implicit template
907 /// instantiations we have seen until this point.
908 void Sema::PerformPendingImplicitInstantiations() {
909 while (!PendingImplicitInstantiations
.empty()) {
910 PendingImplicitInstantiation Inst
= PendingImplicitInstantiations
.front();
911 PendingImplicitInstantiations
.pop_front();
913 if (FunctionDecl
*Function
= dyn_cast
<FunctionDecl
>(Inst
.first
))
914 if (!Function
->getBody())
915 InstantiateFunctionDefinition(/*FIXME:*/Inst
.second
, Function
, true);
917 // FIXME: instantiate static member variables