1 //===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
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 argument deduction.
11 //===----------------------------------------------------------------------===/
13 #include "clang/Sema/Sema.h"
14 #include "clang/Sema/DeclSpec.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/Sema/TemplateDeduction.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
28 /// \brief Various flags that control template argument deduction.
30 /// These flags can be bitwise-OR'd together.
31 enum TemplateDeductionFlags
{
32 /// \brief No template argument deduction flags, which indicates the
33 /// strictest results for template argument deduction (as used for, e.g.,
34 /// matching class template partial specializations).
36 /// \brief Within template argument deduction from a function call, we are
37 /// matching with a parameter type for which the original parameter was
39 TDF_ParamWithReferenceType
= 0x1,
40 /// \brief Within template argument deduction from a function call, we
41 /// are matching in a case where we ignore cv-qualifiers.
42 TDF_IgnoreQualifiers
= 0x02,
43 /// \brief Within template argument deduction from a function call,
44 /// we are matching in a case where we can perform template argument
45 /// deduction from a template-id of a derived class of the argument type.
46 TDF_DerivedClass
= 0x04,
47 /// \brief Allow non-dependent types to differ, e.g., when performing
48 /// template argument deduction from a function call where conversions
50 TDF_SkipNonDependent
= 0x08
54 using namespace clang
;
56 /// \brief Compare two APSInts, extending and switching the sign as
57 /// necessary to compare their values regardless of underlying type.
58 static bool hasSameExtendedValue(llvm::APSInt X
, llvm::APSInt Y
) {
59 if (Y
.getBitWidth() > X
.getBitWidth())
60 X
.extend(Y
.getBitWidth());
61 else if (Y
.getBitWidth() < X
.getBitWidth())
62 Y
.extend(X
.getBitWidth());
64 // If there is a signedness mismatch, correct it.
65 if (X
.isSigned() != Y
.isSigned()) {
66 // If the signed value is negative, then the values cannot be the same.
67 if ((Y
.isSigned() && Y
.isNegative()) || (X
.isSigned() && X
.isNegative()))
77 static Sema::TemplateDeductionResult
78 DeduceTemplateArguments(Sema
&S
,
79 TemplateParameterList
*TemplateParams
,
80 const TemplateArgument
&Param
,
81 const TemplateArgument
&Arg
,
82 TemplateDeductionInfo
&Info
,
83 llvm::SmallVectorImpl
<DeducedTemplateArgument
> &Deduced
);
85 /// \brief If the given expression is of a form that permits the deduction
86 /// of a non-type template parameter, return the declaration of that
87 /// non-type template parameter.
88 static NonTypeTemplateParmDecl
*getDeducedParameterFromExpr(Expr
*E
) {
89 if (ImplicitCastExpr
*IC
= dyn_cast
<ImplicitCastExpr
>(E
))
92 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
))
93 return dyn_cast
<NonTypeTemplateParmDecl
>(DRE
->getDecl());
98 /// \brief Deduce the value of the given non-type template parameter
99 /// from the given constant.
100 static Sema::TemplateDeductionResult
101 DeduceNonTypeTemplateArgument(Sema
&S
,
102 NonTypeTemplateParmDecl
*NTTP
,
103 llvm::APSInt Value
, QualType ValueType
,
104 bool DeducedFromArrayBound
,
105 TemplateDeductionInfo
&Info
,
106 llvm::SmallVectorImpl
<DeducedTemplateArgument
> &Deduced
) {
107 assert(NTTP
->getDepth() == 0 &&
108 "Cannot deduce non-type template argument with depth > 0");
110 if (Deduced
[NTTP
->getIndex()].isNull()) {
111 Deduced
[NTTP
->getIndex()] = DeducedTemplateArgument(Value
, ValueType
,
112 DeducedFromArrayBound
);
113 return Sema::TDK_Success
;
116 if (Deduced
[NTTP
->getIndex()].getKind() != TemplateArgument::Integral
) {
118 Info
.FirstArg
= Deduced
[NTTP
->getIndex()];
119 Info
.SecondArg
= TemplateArgument(Value
, ValueType
);
120 return Sema::TDK_Inconsistent
;
123 // Extent the smaller of the two values.
124 llvm::APSInt PrevValue
= *Deduced
[NTTP
->getIndex()].getAsIntegral();
125 if (!hasSameExtendedValue(PrevValue
, Value
)) {
127 Info
.FirstArg
= Deduced
[NTTP
->getIndex()];
128 Info
.SecondArg
= TemplateArgument(Value
, ValueType
);
129 return Sema::TDK_Inconsistent
;
132 if (!DeducedFromArrayBound
)
133 Deduced
[NTTP
->getIndex()].setDeducedFromArrayBound(false);
135 return Sema::TDK_Success
;
138 /// \brief Deduce the value of the given non-type template parameter
139 /// from the given type- or value-dependent expression.
141 /// \returns true if deduction succeeded, false otherwise.
142 static Sema::TemplateDeductionResult
143 DeduceNonTypeTemplateArgument(Sema
&S
,
144 NonTypeTemplateParmDecl
*NTTP
,
146 TemplateDeductionInfo
&Info
,
147 llvm::SmallVectorImpl
<DeducedTemplateArgument
> &Deduced
) {
148 assert(NTTP
->getDepth() == 0 &&
149 "Cannot deduce non-type template argument with depth > 0");
150 assert((Value
->isTypeDependent() || Value
->isValueDependent()) &&
151 "Expression template argument must be type- or value-dependent.");
153 if (Deduced
[NTTP
->getIndex()].isNull()) {
154 Deduced
[NTTP
->getIndex()] = TemplateArgument(Value
->Retain());
155 return Sema::TDK_Success
;
158 if (Deduced
[NTTP
->getIndex()].getKind() == TemplateArgument::Integral
) {
159 // Okay, we deduced a constant in one case and a dependent expression
160 // in another case. FIXME: Later, we will check that instantiating the
161 // dependent expression gives us the constant value.
162 return Sema::TDK_Success
;
165 if (Deduced
[NTTP
->getIndex()].getKind() == TemplateArgument::Expression
) {
166 // Compare the expressions for equality
167 llvm::FoldingSetNodeID ID1
, ID2
;
168 Deduced
[NTTP
->getIndex()].getAsExpr()->Profile(ID1
, S
.Context
, true);
169 Value
->Profile(ID2
, S
.Context
, true);
171 return Sema::TDK_Success
;
173 // FIXME: Fill in argument mismatch information
174 return Sema::TDK_NonDeducedMismatch
;
177 return Sema::TDK_Success
;
180 /// \brief Deduce the value of the given non-type template parameter
181 /// from the given declaration.
183 /// \returns true if deduction succeeded, false otherwise.
184 static Sema::TemplateDeductionResult
185 DeduceNonTypeTemplateArgument(Sema
&S
,
186 NonTypeTemplateParmDecl
*NTTP
,
188 TemplateDeductionInfo
&Info
,
189 llvm::SmallVectorImpl
<DeducedTemplateArgument
> &Deduced
) {
190 assert(NTTP
->getDepth() == 0 &&
191 "Cannot deduce non-type template argument with depth > 0");
193 if (Deduced
[NTTP
->getIndex()].isNull()) {
194 Deduced
[NTTP
->getIndex()] = TemplateArgument(D
->getCanonicalDecl());
195 return Sema::TDK_Success
;
198 if (Deduced
[NTTP
->getIndex()].getKind() == TemplateArgument::Expression
) {
199 // Okay, we deduced a declaration in one case and a dependent expression
201 return Sema::TDK_Success
;
204 if (Deduced
[NTTP
->getIndex()].getKind() == TemplateArgument::Declaration
) {
205 // Compare the declarations for equality
206 if (Deduced
[NTTP
->getIndex()].getAsDecl()->getCanonicalDecl() ==
207 D
->getCanonicalDecl())
208 return Sema::TDK_Success
;
210 // FIXME: Fill in argument mismatch information
211 return Sema::TDK_NonDeducedMismatch
;
214 return Sema::TDK_Success
;
217 static Sema::TemplateDeductionResult
218 DeduceTemplateArguments(Sema
&S
,
219 TemplateParameterList
*TemplateParams
,
222 TemplateDeductionInfo
&Info
,
223 llvm::SmallVectorImpl
<DeducedTemplateArgument
> &Deduced
) {
224 TemplateDecl
*ParamDecl
= Param
.getAsTemplateDecl();
226 // The parameter type is dependent and is not a template template parameter,
227 // so there is nothing that we can deduce.
228 return Sema::TDK_Success
;
231 if (TemplateTemplateParmDecl
*TempParam
232 = dyn_cast
<TemplateTemplateParmDecl
>(ParamDecl
)) {
233 // Bind the template template parameter to the given template name.
234 TemplateArgument
&ExistingArg
= Deduced
[TempParam
->getIndex()];
235 if (ExistingArg
.isNull()) {
236 // This is the first deduction for this template template parameter.
237 ExistingArg
= TemplateArgument(S
.Context
.getCanonicalTemplateName(Arg
));
238 return Sema::TDK_Success
;
241 // Verify that the previous binding matches this deduction.
242 assert(ExistingArg
.getKind() == TemplateArgument::Template
);
243 if (S
.Context
.hasSameTemplateName(ExistingArg
.getAsTemplate(), Arg
))
244 return Sema::TDK_Success
;
246 // Inconsistent deduction.
247 Info
.Param
= TempParam
;
248 Info
.FirstArg
= ExistingArg
;
249 Info
.SecondArg
= TemplateArgument(Arg
);
250 return Sema::TDK_Inconsistent
;
253 // Verify that the two template names are equivalent.
254 if (S
.Context
.hasSameTemplateName(Param
, Arg
))
255 return Sema::TDK_Success
;
257 // Mismatch of non-dependent template parameter to argument.
258 Info
.FirstArg
= TemplateArgument(Param
);
259 Info
.SecondArg
= TemplateArgument(Arg
);
260 return Sema::TDK_NonDeducedMismatch
;
263 /// \brief Deduce the template arguments by comparing the template parameter
264 /// type (which is a template-id) with the template argument type.
266 /// \param S the Sema
268 /// \param TemplateParams the template parameters that we are deducing
270 /// \param Param the parameter type
272 /// \param Arg the argument type
274 /// \param Info information about the template argument deduction itself
276 /// \param Deduced the deduced template arguments
278 /// \returns the result of template argument deduction so far. Note that a
279 /// "success" result means that template argument deduction has not yet failed,
280 /// but it may still fail, later, for other reasons.
281 static Sema::TemplateDeductionResult
282 DeduceTemplateArguments(Sema
&S
,
283 TemplateParameterList
*TemplateParams
,
284 const TemplateSpecializationType
*Param
,
286 TemplateDeductionInfo
&Info
,
287 llvm::SmallVectorImpl
<DeducedTemplateArgument
> &Deduced
) {
288 assert(Arg
.isCanonical() && "Argument type must be canonical");
290 // Check whether the template argument is a dependent template-id.
291 if (const TemplateSpecializationType
*SpecArg
292 = dyn_cast
<TemplateSpecializationType
>(Arg
)) {
293 // Perform template argument deduction for the template name.
294 if (Sema::TemplateDeductionResult Result
295 = DeduceTemplateArguments(S
, TemplateParams
,
296 Param
->getTemplateName(),
297 SpecArg
->getTemplateName(),
302 // Perform template argument deduction on each template
304 unsigned NumArgs
= std::min(SpecArg
->getNumArgs(), Param
->getNumArgs());
305 for (unsigned I
= 0; I
!= NumArgs
; ++I
)
306 if (Sema::TemplateDeductionResult Result
307 = DeduceTemplateArguments(S
, TemplateParams
,
313 return Sema::TDK_Success
;
316 // If the argument type is a class template specialization, we
317 // perform template argument deduction using its template
319 const RecordType
*RecordArg
= dyn_cast
<RecordType
>(Arg
);
321 return Sema::TDK_NonDeducedMismatch
;
323 ClassTemplateSpecializationDecl
*SpecArg
324 = dyn_cast
<ClassTemplateSpecializationDecl
>(RecordArg
->getDecl());
326 return Sema::TDK_NonDeducedMismatch
;
328 // Perform template argument deduction for the template name.
329 if (Sema::TemplateDeductionResult Result
330 = DeduceTemplateArguments(S
,
332 Param
->getTemplateName(),
333 TemplateName(SpecArg
->getSpecializedTemplate()),
337 unsigned NumArgs
= Param
->getNumArgs();
338 const TemplateArgumentList
&ArgArgs
= SpecArg
->getTemplateArgs();
339 if (NumArgs
!= ArgArgs
.size())
340 return Sema::TDK_NonDeducedMismatch
;
342 for (unsigned I
= 0; I
!= NumArgs
; ++I
)
343 if (Sema::TemplateDeductionResult Result
344 = DeduceTemplateArguments(S
, TemplateParams
,
350 return Sema::TDK_Success
;
353 /// \brief Deduce the template arguments by comparing the parameter type and
354 /// the argument type (C++ [temp.deduct.type]).
356 /// \param S the semantic analysis object within which we are deducing
358 /// \param TemplateParams the template parameters that we are deducing
360 /// \param ParamIn the parameter type
362 /// \param ArgIn the argument type
364 /// \param Info information about the template argument deduction itself
366 /// \param Deduced the deduced template arguments
368 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
369 /// how template argument deduction is performed.
371 /// \returns the result of template argument deduction so far. Note that a
372 /// "success" result means that template argument deduction has not yet failed,
373 /// but it may still fail, later, for other reasons.
374 static Sema::TemplateDeductionResult
375 DeduceTemplateArguments(Sema
&S
,
376 TemplateParameterList
*TemplateParams
,
377 QualType ParamIn
, QualType ArgIn
,
378 TemplateDeductionInfo
&Info
,
379 llvm::SmallVectorImpl
<DeducedTemplateArgument
> &Deduced
,
381 // We only want to look at the canonical types, since typedefs and
382 // sugar are not part of template argument deduction.
383 QualType Param
= S
.Context
.getCanonicalType(ParamIn
);
384 QualType Arg
= S
.Context
.getCanonicalType(ArgIn
);
386 // C++0x [temp.deduct.call]p4 bullet 1:
387 // - If the original P is a reference type, the deduced A (i.e., the type
388 // referred to by the reference) can be more cv-qualified than the
390 if (TDF
& TDF_ParamWithReferenceType
) {
392 QualType UnqualParam
= S
.Context
.getUnqualifiedArrayType(Param
, Quals
);
393 Quals
.setCVRQualifiers(Quals
.getCVRQualifiers() &
394 Arg
.getCVRQualifiersThroughArrayTypes());
395 Param
= S
.Context
.getQualifiedType(UnqualParam
, Quals
);
398 // If the parameter type is not dependent, there is nothing to deduce.
399 if (!Param
->isDependentType()) {
400 if (!(TDF
& TDF_SkipNonDependent
) && Param
!= Arg
) {
402 return Sema::TDK_NonDeducedMismatch
;
405 return Sema::TDK_Success
;
408 // C++ [temp.deduct.type]p9:
409 // A template type argument T, a template template argument TT or a
410 // template non-type argument i can be deduced if P and A have one of
411 // the following forms:
415 if (const TemplateTypeParmType
*TemplateTypeParm
416 = Param
->getAs
<TemplateTypeParmType
>()) {
417 unsigned Index
= TemplateTypeParm
->getIndex();
418 bool RecanonicalizeArg
= false;
420 // If the argument type is an array type, move the qualifiers up to the
421 // top level, so they can be matched with the qualifiers on the parameter.
422 // FIXME: address spaces, ObjC GC qualifiers
423 if (isa
<ArrayType
>(Arg
)) {
425 Arg
= S
.Context
.getUnqualifiedArrayType(Arg
, Quals
);
427 Arg
= S
.Context
.getQualifiedType(Arg
, Quals
);
428 RecanonicalizeArg
= true;
432 // The argument type can not be less qualified than the parameter
434 if (Param
.isMoreQualifiedThan(Arg
) && !(TDF
& TDF_IgnoreQualifiers
)) {
435 Info
.Param
= cast
<TemplateTypeParmDecl
>(TemplateParams
->getParam(Index
));
436 Info
.FirstArg
= TemplateArgument(Param
);
437 Info
.SecondArg
= TemplateArgument(Arg
);
438 return Sema::TDK_Underqualified
;
441 assert(TemplateTypeParm
->getDepth() == 0 && "Can't deduce with depth > 0");
442 assert(Arg
!= S
.Context
.OverloadTy
&& "Unresolved overloaded function");
443 QualType DeducedType
= Arg
;
444 DeducedType
.removeCVRQualifiers(Param
.getCVRQualifiers());
445 if (RecanonicalizeArg
)
446 DeducedType
= S
.Context
.getCanonicalType(DeducedType
);
448 if (Deduced
[Index
].isNull())
449 Deduced
[Index
] = TemplateArgument(DeducedType
);
451 // C++ [temp.deduct.type]p2:
452 // [...] If type deduction cannot be done for any P/A pair, or if for
453 // any pair the deduction leads to more than one possible set of
454 // deduced values, or if different pairs yield different deduced
455 // values, or if any template argument remains neither deduced nor
456 // explicitly specified, template argument deduction fails.
457 if (Deduced
[Index
].getAsType() != DeducedType
) {
459 = cast
<TemplateTypeParmDecl
>(TemplateParams
->getParam(Index
));
460 Info
.FirstArg
= Deduced
[Index
];
461 Info
.SecondArg
= TemplateArgument(Arg
);
462 return Sema::TDK_Inconsistent
;
465 return Sema::TDK_Success
;
468 // Set up the template argument deduction information for a failure.
469 Info
.FirstArg
= TemplateArgument(ParamIn
);
470 Info
.SecondArg
= TemplateArgument(ArgIn
);
472 // Check the cv-qualifiers on the parameter and argument types.
473 if (!(TDF
& TDF_IgnoreQualifiers
)) {
474 if (TDF
& TDF_ParamWithReferenceType
) {
475 if (Param
.isMoreQualifiedThan(Arg
))
476 return Sema::TDK_NonDeducedMismatch
;
478 if (Param
.getCVRQualifiers() != Arg
.getCVRQualifiers())
479 return Sema::TDK_NonDeducedMismatch
;
483 switch (Param
->getTypeClass()) {
484 // No deduction possible for these types
486 return Sema::TDK_NonDeducedMismatch
;
489 case Type::Pointer
: {
490 QualType PointeeType
;
491 if (const PointerType
*PointerArg
= Arg
->getAs
<PointerType
>()) {
492 PointeeType
= PointerArg
->getPointeeType();
493 } else if (const ObjCObjectPointerType
*PointerArg
494 = Arg
->getAs
<ObjCObjectPointerType
>()) {
495 PointeeType
= PointerArg
->getPointeeType();
497 return Sema::TDK_NonDeducedMismatch
;
500 unsigned SubTDF
= TDF
& (TDF_IgnoreQualifiers
| TDF_DerivedClass
);
501 return DeduceTemplateArguments(S
, TemplateParams
,
502 cast
<PointerType
>(Param
)->getPointeeType(),
504 Info
, Deduced
, SubTDF
);
508 case Type::LValueReference
: {
509 const LValueReferenceType
*ReferenceArg
= Arg
->getAs
<LValueReferenceType
>();
511 return Sema::TDK_NonDeducedMismatch
;
513 return DeduceTemplateArguments(S
, TemplateParams
,
514 cast
<LValueReferenceType
>(Param
)->getPointeeType(),
515 ReferenceArg
->getPointeeType(),
520 case Type::RValueReference
: {
521 const RValueReferenceType
*ReferenceArg
= Arg
->getAs
<RValueReferenceType
>();
523 return Sema::TDK_NonDeducedMismatch
;
525 return DeduceTemplateArguments(S
, TemplateParams
,
526 cast
<RValueReferenceType
>(Param
)->getPointeeType(),
527 ReferenceArg
->getPointeeType(),
531 // T [] (implied, but not stated explicitly)
532 case Type::IncompleteArray
: {
533 const IncompleteArrayType
*IncompleteArrayArg
=
534 S
.Context
.getAsIncompleteArrayType(Arg
);
535 if (!IncompleteArrayArg
)
536 return Sema::TDK_NonDeducedMismatch
;
538 unsigned SubTDF
= TDF
& TDF_IgnoreQualifiers
;
539 return DeduceTemplateArguments(S
, TemplateParams
,
540 S
.Context
.getAsIncompleteArrayType(Param
)->getElementType(),
541 IncompleteArrayArg
->getElementType(),
542 Info
, Deduced
, SubTDF
);
545 // T [integer-constant]
546 case Type::ConstantArray
: {
547 const ConstantArrayType
*ConstantArrayArg
=
548 S
.Context
.getAsConstantArrayType(Arg
);
549 if (!ConstantArrayArg
)
550 return Sema::TDK_NonDeducedMismatch
;
552 const ConstantArrayType
*ConstantArrayParm
=
553 S
.Context
.getAsConstantArrayType(Param
);
554 if (ConstantArrayArg
->getSize() != ConstantArrayParm
->getSize())
555 return Sema::TDK_NonDeducedMismatch
;
557 unsigned SubTDF
= TDF
& TDF_IgnoreQualifiers
;
558 return DeduceTemplateArguments(S
, TemplateParams
,
559 ConstantArrayParm
->getElementType(),
560 ConstantArrayArg
->getElementType(),
561 Info
, Deduced
, SubTDF
);
565 case Type::DependentSizedArray
: {
566 const ArrayType
*ArrayArg
= S
.Context
.getAsArrayType(Arg
);
568 return Sema::TDK_NonDeducedMismatch
;
570 unsigned SubTDF
= TDF
& TDF_IgnoreQualifiers
;
572 // Check the element type of the arrays
573 const DependentSizedArrayType
*DependentArrayParm
574 = S
.Context
.getAsDependentSizedArrayType(Param
);
575 if (Sema::TemplateDeductionResult Result
576 = DeduceTemplateArguments(S
, TemplateParams
,
577 DependentArrayParm
->getElementType(),
578 ArrayArg
->getElementType(),
579 Info
, Deduced
, SubTDF
))
582 // Determine the array bound is something we can deduce.
583 NonTypeTemplateParmDecl
*NTTP
584 = getDeducedParameterFromExpr(DependentArrayParm
->getSizeExpr());
586 return Sema::TDK_Success
;
588 // We can perform template argument deduction for the given non-type
589 // template parameter.
590 assert(NTTP
->getDepth() == 0 &&
591 "Cannot deduce non-type template argument at depth > 0");
592 if (const ConstantArrayType
*ConstantArrayArg
593 = dyn_cast
<ConstantArrayType
>(ArrayArg
)) {
594 llvm::APSInt
Size(ConstantArrayArg
->getSize());
595 return DeduceNonTypeTemplateArgument(S
, NTTP
, Size
,
596 S
.Context
.getSizeType(),
600 if (const DependentSizedArrayType
*DependentArrayArg
601 = dyn_cast
<DependentSizedArrayType
>(ArrayArg
))
602 return DeduceNonTypeTemplateArgument(S
, NTTP
,
603 DependentArrayArg
->getSizeExpr(),
606 // Incomplete type does not match a dependently-sized array type
607 return Sema::TDK_NonDeducedMismatch
;
613 case Type::FunctionProto
: {
614 const FunctionProtoType
*FunctionProtoArg
=
615 dyn_cast
<FunctionProtoType
>(Arg
);
616 if (!FunctionProtoArg
)
617 return Sema::TDK_NonDeducedMismatch
;
619 const FunctionProtoType
*FunctionProtoParam
=
620 cast
<FunctionProtoType
>(Param
);
622 if (FunctionProtoParam
->getTypeQuals() !=
623 FunctionProtoArg
->getTypeQuals())
624 return Sema::TDK_NonDeducedMismatch
;
626 if (FunctionProtoParam
->getNumArgs() != FunctionProtoArg
->getNumArgs())
627 return Sema::TDK_NonDeducedMismatch
;
629 if (FunctionProtoParam
->isVariadic() != FunctionProtoArg
->isVariadic())
630 return Sema::TDK_NonDeducedMismatch
;
632 // Check return types.
633 if (Sema::TemplateDeductionResult Result
634 = DeduceTemplateArguments(S
, TemplateParams
,
635 FunctionProtoParam
->getResultType(),
636 FunctionProtoArg
->getResultType(),
640 for (unsigned I
= 0, N
= FunctionProtoParam
->getNumArgs(); I
!= N
; ++I
) {
641 // Check argument types.
642 if (Sema::TemplateDeductionResult Result
643 = DeduceTemplateArguments(S
, TemplateParams
,
644 FunctionProtoParam
->getArgType(I
),
645 FunctionProtoArg
->getArgType(I
),
650 return Sema::TDK_Success
;
653 case Type::InjectedClassName
: {
654 // Treat a template's injected-class-name as if the template
655 // specialization type had been used.
656 Param
= cast
<InjectedClassNameType
>(Param
)
657 ->getInjectedSpecializationType();
658 assert(isa
<TemplateSpecializationType
>(Param
) &&
659 "injected class name is not a template specialization type");
663 // template-name<T> (where template-name refers to a class template)
668 case Type::TemplateSpecialization
: {
669 const TemplateSpecializationType
*SpecParam
670 = cast
<TemplateSpecializationType
>(Param
);
672 // Try to deduce template arguments from the template-id.
673 Sema::TemplateDeductionResult Result
674 = DeduceTemplateArguments(S
, TemplateParams
, SpecParam
, Arg
,
677 if (Result
&& (TDF
& TDF_DerivedClass
)) {
678 // C++ [temp.deduct.call]p3b3:
679 // If P is a class, and P has the form template-id, then A can be a
680 // derived class of the deduced A. Likewise, if P is a pointer to a
681 // class of the form template-id, A can be a pointer to a derived
682 // class pointed to by the deduced A.
685 // These alternatives are considered only if type deduction would
687 if (const RecordType
*RecordT
= Arg
->getAs
<RecordType
>()) {
688 // We cannot inspect base classes as part of deduction when the type
689 // is incomplete, so either instantiate any templates necessary to
690 // complete the type, or skip over it if it cannot be completed.
691 if (S
.RequireCompleteType(Info
.getLocation(), Arg
, 0))
694 // Use data recursion to crawl through the list of base classes.
695 // Visited contains the set of nodes we have already visited, while
696 // ToVisit is our stack of records that we still need to visit.
697 llvm::SmallPtrSet
<const RecordType
*, 8> Visited
;
698 llvm::SmallVector
<const RecordType
*, 8> ToVisit
;
699 ToVisit
.push_back(RecordT
);
700 bool Successful
= false;
701 while (!ToVisit
.empty()) {
702 // Retrieve the next class in the inheritance hierarchy.
703 const RecordType
*NextT
= ToVisit
.back();
706 // If we have already seen this type, skip it.
707 if (!Visited
.insert(NextT
))
710 // If this is a base class, try to perform template argument
711 // deduction from it.
712 if (NextT
!= RecordT
) {
713 Sema::TemplateDeductionResult BaseResult
714 = DeduceTemplateArguments(S
, TemplateParams
, SpecParam
,
715 QualType(NextT
, 0), Info
, Deduced
);
717 // If template argument deduction for this base was successful,
718 // note that we had some success.
719 if (BaseResult
== Sema::TDK_Success
)
723 // Visit base classes
724 CXXRecordDecl
*Next
= cast
<CXXRecordDecl
>(NextT
->getDecl());
725 for (CXXRecordDecl::base_class_iterator Base
= Next
->bases_begin(),
726 BaseEnd
= Next
->bases_end();
727 Base
!= BaseEnd
; ++Base
) {
728 assert(Base
->getType()->isRecordType() &&
729 "Base class that isn't a record?");
730 ToVisit
.push_back(Base
->getType()->getAs
<RecordType
>());
735 return Sema::TDK_Success
;
752 case Type::MemberPointer
: {
753 const MemberPointerType
*MemPtrParam
= cast
<MemberPointerType
>(Param
);
754 const MemberPointerType
*MemPtrArg
= dyn_cast
<MemberPointerType
>(Arg
);
756 return Sema::TDK_NonDeducedMismatch
;
758 if (Sema::TemplateDeductionResult Result
759 = DeduceTemplateArguments(S
, TemplateParams
,
760 MemPtrParam
->getPointeeType(),
761 MemPtrArg
->getPointeeType(),
763 TDF
& TDF_IgnoreQualifiers
))
766 return DeduceTemplateArguments(S
, TemplateParams
,
767 QualType(MemPtrParam
->getClass(), 0),
768 QualType(MemPtrArg
->getClass(), 0),
777 case Type::BlockPointer
: {
778 const BlockPointerType
*BlockPtrParam
= cast
<BlockPointerType
>(Param
);
779 const BlockPointerType
*BlockPtrArg
= dyn_cast
<BlockPointerType
>(Arg
);
782 return Sema::TDK_NonDeducedMismatch
;
784 return DeduceTemplateArguments(S
, TemplateParams
,
785 BlockPtrParam
->getPointeeType(),
786 BlockPtrArg
->getPointeeType(), Info
,
790 case Type::TypeOfExpr
:
792 case Type::DependentName
:
793 // No template argument deduction for these types
794 return Sema::TDK_Success
;
800 // FIXME: Many more cases to go (to go).
801 return Sema::TDK_Success
;
804 static Sema::TemplateDeductionResult
805 DeduceTemplateArguments(Sema
&S
,
806 TemplateParameterList
*TemplateParams
,
807 const TemplateArgument
&Param
,
808 const TemplateArgument
&Arg
,
809 TemplateDeductionInfo
&Info
,
810 llvm::SmallVectorImpl
<DeducedTemplateArgument
> &Deduced
) {
811 switch (Param
.getKind()) {
812 case TemplateArgument::Null
:
813 assert(false && "Null template argument in parameter list");
816 case TemplateArgument::Type
:
817 if (Arg
.getKind() == TemplateArgument::Type
)
818 return DeduceTemplateArguments(S
, TemplateParams
, Param
.getAsType(),
819 Arg
.getAsType(), Info
, Deduced
, 0);
820 Info
.FirstArg
= Param
;
821 Info
.SecondArg
= Arg
;
822 return Sema::TDK_NonDeducedMismatch
;
824 case TemplateArgument::Template
:
825 if (Arg
.getKind() == TemplateArgument::Template
)
826 return DeduceTemplateArguments(S
, TemplateParams
,
827 Param
.getAsTemplate(),
828 Arg
.getAsTemplate(), Info
, Deduced
);
829 Info
.FirstArg
= Param
;
830 Info
.SecondArg
= Arg
;
831 return Sema::TDK_NonDeducedMismatch
;
833 case TemplateArgument::Declaration
:
834 if (Arg
.getKind() == TemplateArgument::Declaration
&&
835 Param
.getAsDecl()->getCanonicalDecl() ==
836 Arg
.getAsDecl()->getCanonicalDecl())
837 return Sema::TDK_Success
;
839 Info
.FirstArg
= Param
;
840 Info
.SecondArg
= Arg
;
841 return Sema::TDK_NonDeducedMismatch
;
843 case TemplateArgument::Integral
:
844 if (Arg
.getKind() == TemplateArgument::Integral
) {
845 if (hasSameExtendedValue(*Param
.getAsIntegral(), *Arg
.getAsIntegral()))
846 return Sema::TDK_Success
;
848 Info
.FirstArg
= Param
;
849 Info
.SecondArg
= Arg
;
850 return Sema::TDK_NonDeducedMismatch
;
853 if (Arg
.getKind() == TemplateArgument::Expression
) {
854 Info
.FirstArg
= Param
;
855 Info
.SecondArg
= Arg
;
856 return Sema::TDK_NonDeducedMismatch
;
859 Info
.FirstArg
= Param
;
860 Info
.SecondArg
= Arg
;
861 return Sema::TDK_NonDeducedMismatch
;
863 case TemplateArgument::Expression
: {
864 if (NonTypeTemplateParmDecl
*NTTP
865 = getDeducedParameterFromExpr(Param
.getAsExpr())) {
866 if (Arg
.getKind() == TemplateArgument::Integral
)
867 return DeduceNonTypeTemplateArgument(S
, NTTP
,
868 *Arg
.getAsIntegral(),
869 Arg
.getIntegralType(),
870 /*ArrayBound=*/false,
872 if (Arg
.getKind() == TemplateArgument::Expression
)
873 return DeduceNonTypeTemplateArgument(S
, NTTP
, Arg
.getAsExpr(),
875 if (Arg
.getKind() == TemplateArgument::Declaration
)
876 return DeduceNonTypeTemplateArgument(S
, NTTP
, Arg
.getAsDecl(),
879 Info
.FirstArg
= Param
;
880 Info
.SecondArg
= Arg
;
881 return Sema::TDK_NonDeducedMismatch
;
884 // Can't deduce anything, but that's okay.
885 return Sema::TDK_Success
;
887 case TemplateArgument::Pack
:
888 assert(0 && "FIXME: Implement!");
892 return Sema::TDK_Success
;
895 static Sema::TemplateDeductionResult
896 DeduceTemplateArguments(Sema
&S
,
897 TemplateParameterList
*TemplateParams
,
898 const TemplateArgumentList
&ParamList
,
899 const TemplateArgumentList
&ArgList
,
900 TemplateDeductionInfo
&Info
,
901 llvm::SmallVectorImpl
<DeducedTemplateArgument
> &Deduced
) {
902 assert(ParamList
.size() == ArgList
.size());
903 for (unsigned I
= 0, N
= ParamList
.size(); I
!= N
; ++I
) {
904 if (Sema::TemplateDeductionResult Result
905 = DeduceTemplateArguments(S
, TemplateParams
,
906 ParamList
[I
], ArgList
[I
],
910 return Sema::TDK_Success
;
913 /// \brief Determine whether two template arguments are the same.
914 static bool isSameTemplateArg(ASTContext
&Context
,
915 const TemplateArgument
&X
,
916 const TemplateArgument
&Y
) {
917 if (X
.getKind() != Y
.getKind())
920 switch (X
.getKind()) {
921 case TemplateArgument::Null
:
922 assert(false && "Comparing NULL template argument");
925 case TemplateArgument::Type
:
926 return Context
.getCanonicalType(X
.getAsType()) ==
927 Context
.getCanonicalType(Y
.getAsType());
929 case TemplateArgument::Declaration
:
930 return X
.getAsDecl()->getCanonicalDecl() ==
931 Y
.getAsDecl()->getCanonicalDecl();
933 case TemplateArgument::Template
:
934 return Context
.getCanonicalTemplateName(X
.getAsTemplate())
935 .getAsVoidPointer() ==
936 Context
.getCanonicalTemplateName(Y
.getAsTemplate())
939 case TemplateArgument::Integral
:
940 return *X
.getAsIntegral() == *Y
.getAsIntegral();
942 case TemplateArgument::Expression
: {
943 llvm::FoldingSetNodeID XID
, YID
;
944 X
.getAsExpr()->Profile(XID
, Context
, true);
945 Y
.getAsExpr()->Profile(YID
, Context
, true);
949 case TemplateArgument::Pack
:
950 if (X
.pack_size() != Y
.pack_size())
953 for (TemplateArgument::pack_iterator XP
= X
.pack_begin(),
954 XPEnd
= X
.pack_end(),
956 XP
!= XPEnd
; ++XP
, ++YP
)
957 if (!isSameTemplateArg(Context
, *XP
, *YP
))
966 /// \brief Helper function to build a TemplateParameter when we don't
967 /// know its type statically.
968 static TemplateParameter
makeTemplateParameter(Decl
*D
) {
969 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(D
))
970 return TemplateParameter(TTP
);
971 else if (NonTypeTemplateParmDecl
*NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(D
))
972 return TemplateParameter(NTTP
);
974 return TemplateParameter(cast
<TemplateTemplateParmDecl
>(D
));
977 /// Complete template argument deduction for a class template partial
979 static Sema::TemplateDeductionResult
980 FinishTemplateArgumentDeduction(Sema
&S
,
981 ClassTemplatePartialSpecializationDecl
*Partial
,
982 const TemplateArgumentList
&TemplateArgs
,
983 llvm::SmallVectorImpl
<DeducedTemplateArgument
> &Deduced
,
984 TemplateDeductionInfo
&Info
) {
986 Sema::SFINAETrap
Trap(S
);
988 Sema::ContextRAII
SavedContext(S
, Partial
);
990 // C++ [temp.deduct.type]p2:
991 // [...] or if any template argument remains neither deduced nor
992 // explicitly specified, template argument deduction fails.
993 TemplateArgumentListBuilder
Builder(Partial
->getTemplateParameters(),
995 for (unsigned I
= 0, N
= Deduced
.size(); I
!= N
; ++I
) {
996 if (Deduced
[I
].isNull()) {
998 = const_cast<NamedDecl
*>(
999 Partial
->getTemplateParameters()->getParam(I
));
1000 Info
.Param
= makeTemplateParameter(Param
);
1001 return Sema::TDK_Incomplete
;
1004 Builder
.Append(Deduced
[I
]);
1007 // Form the template argument list from the deduced template arguments.
1008 TemplateArgumentList
*DeducedArgumentList
1009 = new (S
.Context
) TemplateArgumentList(S
.Context
, Builder
,
1011 Info
.reset(DeducedArgumentList
);
1013 // Substitute the deduced template arguments into the template
1014 // arguments of the class template partial specialization, and
1015 // verify that the instantiated template arguments are both valid
1016 // and are equivalent to the template arguments originally provided
1017 // to the class template.
1018 // FIXME: Do we have to correct the types of deduced non-type template
1019 // arguments (in particular, integral non-type template arguments?).
1020 LocalInstantiationScope
InstScope(S
);
1021 ClassTemplateDecl
*ClassTemplate
= Partial
->getSpecializedTemplate();
1022 const TemplateArgumentLoc
*PartialTemplateArgs
1023 = Partial
->getTemplateArgsAsWritten();
1024 unsigned N
= Partial
->getNumTemplateArgsAsWritten();
1026 // Note that we don't provide the langle and rangle locations.
1027 TemplateArgumentListInfo InstArgs
;
1029 for (unsigned I
= 0; I
!= N
; ++I
) {
1030 Decl
*Param
= const_cast<NamedDecl
*>(
1031 ClassTemplate
->getTemplateParameters()->getParam(I
));
1032 TemplateArgumentLoc InstArg
;
1033 if (S
.Subst(PartialTemplateArgs
[I
], InstArg
,
1034 MultiLevelTemplateArgumentList(*DeducedArgumentList
))) {
1035 Info
.Param
= makeTemplateParameter(Param
);
1036 Info
.FirstArg
= PartialTemplateArgs
[I
].getArgument();
1037 return Sema::TDK_SubstitutionFailure
;
1039 InstArgs
.addArgument(InstArg
);
1042 TemplateArgumentListBuilder
ConvertedInstArgs(
1043 ClassTemplate
->getTemplateParameters(), N
);
1045 if (S
.CheckTemplateArgumentList(ClassTemplate
, Partial
->getLocation(),
1046 InstArgs
, false, ConvertedInstArgs
))
1047 return Sema::TDK_SubstitutionFailure
;
1049 for (unsigned I
= 0, E
= ConvertedInstArgs
.flatSize(); I
!= E
; ++I
) {
1050 TemplateArgument InstArg
= ConvertedInstArgs
.getFlatArguments()[I
];
1052 Decl
*Param
= const_cast<NamedDecl
*>(
1053 ClassTemplate
->getTemplateParameters()->getParam(I
));
1055 if (InstArg
.getKind() == TemplateArgument::Expression
) {
1056 // When the argument is an expression, check the expression result
1057 // against the actual template parameter to get down to the canonical
1058 // template argument.
1059 Expr
*InstExpr
= InstArg
.getAsExpr();
1060 if (NonTypeTemplateParmDecl
*NTTP
1061 = dyn_cast
<NonTypeTemplateParmDecl
>(Param
)) {
1062 if (S
.CheckTemplateArgument(NTTP
, NTTP
->getType(), InstExpr
, InstArg
)) {
1063 Info
.Param
= makeTemplateParameter(Param
);
1064 Info
.FirstArg
= Partial
->getTemplateArgs()[I
];
1065 return Sema::TDK_SubstitutionFailure
;
1070 if (!isSameTemplateArg(S
.Context
, TemplateArgs
[I
], InstArg
)) {
1071 Info
.Param
= makeTemplateParameter(Param
);
1072 Info
.FirstArg
= TemplateArgs
[I
];
1073 Info
.SecondArg
= InstArg
;
1074 return Sema::TDK_NonDeducedMismatch
;
1078 if (Trap
.hasErrorOccurred())
1079 return Sema::TDK_SubstitutionFailure
;
1081 return Sema::TDK_Success
;
1084 /// \brief Perform template argument deduction to determine whether
1085 /// the given template arguments match the given class template
1086 /// partial specialization per C++ [temp.class.spec.match].
1087 Sema::TemplateDeductionResult
1088 Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl
*Partial
,
1089 const TemplateArgumentList
&TemplateArgs
,
1090 TemplateDeductionInfo
&Info
) {
1091 // C++ [temp.class.spec.match]p2:
1092 // A partial specialization matches a given actual template
1093 // argument list if the template arguments of the partial
1094 // specialization can be deduced from the actual template argument
1096 SFINAETrap
Trap(*this);
1097 llvm::SmallVector
<DeducedTemplateArgument
, 4> Deduced
;
1098 Deduced
.resize(Partial
->getTemplateParameters()->size());
1099 if (TemplateDeductionResult Result
1100 = ::DeduceTemplateArguments(*this,
1101 Partial
->getTemplateParameters(),
1102 Partial
->getTemplateArgs(),
1103 TemplateArgs
, Info
, Deduced
))
1106 InstantiatingTemplate
Inst(*this, Partial
->getLocation(), Partial
,
1107 Deduced
.data(), Deduced
.size());
1109 return TDK_InstantiationDepth
;
1111 if (Trap
.hasErrorOccurred())
1112 return Sema::TDK_SubstitutionFailure
;
1114 return ::FinishTemplateArgumentDeduction(*this, Partial
, TemplateArgs
,
1118 /// \brief Determine whether the given type T is a simple-template-id type.
1119 static bool isSimpleTemplateIdType(QualType T
) {
1120 if (const TemplateSpecializationType
*Spec
1121 = T
->getAs
<TemplateSpecializationType
>())
1122 return Spec
->getTemplateName().getAsTemplateDecl() != 0;
1127 /// \brief Substitute the explicitly-provided template arguments into the
1128 /// given function template according to C++ [temp.arg.explicit].
1130 /// \param FunctionTemplate the function template into which the explicit
1131 /// template arguments will be substituted.
1133 /// \param ExplicitTemplateArguments the explicitly-specified template
1136 /// \param Deduced the deduced template arguments, which will be populated
1137 /// with the converted and checked explicit template arguments.
1139 /// \param ParamTypes will be populated with the instantiated function
1142 /// \param FunctionType if non-NULL, the result type of the function template
1143 /// will also be instantiated and the pointed-to value will be updated with
1144 /// the instantiated function type.
1146 /// \param Info if substitution fails for any reason, this object will be
1147 /// populated with more information about the failure.
1149 /// \returns TDK_Success if substitution was successful, or some failure
1151 Sema::TemplateDeductionResult
1152 Sema::SubstituteExplicitTemplateArguments(
1153 FunctionTemplateDecl
*FunctionTemplate
,
1154 const TemplateArgumentListInfo
&ExplicitTemplateArgs
,
1155 llvm::SmallVectorImpl
<DeducedTemplateArgument
> &Deduced
,
1156 llvm::SmallVectorImpl
<QualType
> &ParamTypes
,
1157 QualType
*FunctionType
,
1158 TemplateDeductionInfo
&Info
) {
1159 FunctionDecl
*Function
= FunctionTemplate
->getTemplatedDecl();
1160 TemplateParameterList
*TemplateParams
1161 = FunctionTemplate
->getTemplateParameters();
1163 if (ExplicitTemplateArgs
.size() == 0) {
1164 // No arguments to substitute; just copy over the parameter types and
1165 // fill in the function type.
1166 for (FunctionDecl::param_iterator P
= Function
->param_begin(),
1167 PEnd
= Function
->param_end();
1170 ParamTypes
.push_back((*P
)->getType());
1173 *FunctionType
= Function
->getType();
1177 // Substitution of the explicit template arguments into a function template
1178 /// is a SFINAE context. Trap any errors that might occur.
1179 SFINAETrap
Trap(*this);
1181 // C++ [temp.arg.explicit]p3:
1182 // Template arguments that are present shall be specified in the
1183 // declaration order of their corresponding template-parameters. The
1184 // template argument list shall not specify more template-arguments than
1185 // there are corresponding template-parameters.
1186 TemplateArgumentListBuilder
Builder(TemplateParams
,
1187 ExplicitTemplateArgs
.size());
1189 // Enter a new template instantiation context where we check the
1190 // explicitly-specified template arguments against this function template,
1191 // and then substitute them into the function parameter types.
1192 InstantiatingTemplate
Inst(*this, FunctionTemplate
->getLocation(),
1193 FunctionTemplate
, Deduced
.data(), Deduced
.size(),
1194 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution
);
1196 return TDK_InstantiationDepth
;
1198 ContextRAII
SavedContext(*this, FunctionTemplate
->getTemplatedDecl());
1200 if (CheckTemplateArgumentList(FunctionTemplate
,
1202 ExplicitTemplateArgs
,
1204 Builder
) || Trap
.hasErrorOccurred()) {
1205 unsigned Index
= Builder
.structuredSize();
1206 if (Index
>= TemplateParams
->size())
1207 Index
= TemplateParams
->size() - 1;
1208 Info
.Param
= makeTemplateParameter(TemplateParams
->getParam(Index
));
1209 return TDK_InvalidExplicitArguments
;
1212 // Form the template argument list from the explicitly-specified
1213 // template arguments.
1214 TemplateArgumentList
*ExplicitArgumentList
1215 = new (Context
) TemplateArgumentList(Context
, Builder
, /*TakeArgs=*/true);
1216 Info
.reset(ExplicitArgumentList
);
1218 // Instantiate the types of each of the function parameters given the
1219 // explicitly-specified template arguments.
1220 for (FunctionDecl::param_iterator P
= Function
->param_begin(),
1221 PEnd
= Function
->param_end();
1225 = SubstType((*P
)->getType(),
1226 MultiLevelTemplateArgumentList(*ExplicitArgumentList
),
1227 (*P
)->getLocation(), (*P
)->getDeclName());
1228 if (ParamType
.isNull() || Trap
.hasErrorOccurred())
1229 return TDK_SubstitutionFailure
;
1231 ParamTypes
.push_back(ParamType
);
1234 // If the caller wants a full function type back, instantiate the return
1235 // type and form that function type.
1237 // FIXME: exception-specifications?
1238 const FunctionProtoType
*Proto
1239 = Function
->getType()->getAs
<FunctionProtoType
>();
1240 assert(Proto
&& "Function template does not have a prototype?");
1243 = SubstType(Proto
->getResultType(),
1244 MultiLevelTemplateArgumentList(*ExplicitArgumentList
),
1245 Function
->getTypeSpecStartLoc(),
1246 Function
->getDeclName());
1247 if (ResultType
.isNull() || Trap
.hasErrorOccurred())
1248 return TDK_SubstitutionFailure
;
1250 *FunctionType
= BuildFunctionType(ResultType
,
1251 ParamTypes
.data(), ParamTypes
.size(),
1252 Proto
->isVariadic(),
1253 Proto
->getTypeQuals(),
1254 Function
->getLocation(),
1255 Function
->getDeclName(),
1256 Proto
->getExtInfo());
1257 if (FunctionType
->isNull() || Trap
.hasErrorOccurred())
1258 return TDK_SubstitutionFailure
;
1261 // C++ [temp.arg.explicit]p2:
1262 // Trailing template arguments that can be deduced (14.8.2) may be
1263 // omitted from the list of explicit template-arguments. If all of the
1264 // template arguments can be deduced, they may all be omitted; in this
1265 // case, the empty template argument list <> itself may also be omitted.
1267 // Take all of the explicitly-specified arguments and put them into the
1268 // set of deduced template arguments.
1269 Deduced
.reserve(TemplateParams
->size());
1270 for (unsigned I
= 0, N
= ExplicitArgumentList
->size(); I
!= N
; ++I
)
1271 Deduced
.push_back(ExplicitArgumentList
->get(I
));
1276 /// \brief Allocate a TemplateArgumentLoc where all locations have
1277 /// been initialized to the given location.
1279 /// \param S The semantic analysis object.
1281 /// \param The template argument we are producing template argument
1282 /// location information for.
1284 /// \param NTTPType For a declaration template argument, the type of
1285 /// the non-type template parameter that corresponds to this template
1288 /// \param Loc The source location to use for the resulting template
1290 static TemplateArgumentLoc
1291 getTrivialTemplateArgumentLoc(Sema
&S
,
1292 const TemplateArgument
&Arg
,
1294 SourceLocation Loc
) {
1295 switch (Arg
.getKind()) {
1296 case TemplateArgument::Null
:
1297 llvm_unreachable("Can't get a NULL template argument here");
1300 case TemplateArgument::Type
:
1301 return TemplateArgumentLoc(Arg
,
1302 S
.Context
.getTrivialTypeSourceInfo(Arg
.getAsType(), Loc
));
1304 case TemplateArgument::Declaration
: {
1306 = S
.BuildExpressionFromDeclTemplateArgument(Arg
, NTTPType
, Loc
)
1308 return TemplateArgumentLoc(TemplateArgument(E
), E
);
1311 case TemplateArgument::Integral
: {
1313 = S
.BuildExpressionFromIntegralTemplateArgument(Arg
, Loc
).takeAs
<Expr
>();
1314 return TemplateArgumentLoc(TemplateArgument(E
), E
);
1317 case TemplateArgument::Template
:
1318 return TemplateArgumentLoc(Arg
, SourceRange(), Loc
);
1320 case TemplateArgument::Expression
:
1321 return TemplateArgumentLoc(Arg
, Arg
.getAsExpr());
1323 case TemplateArgument::Pack
:
1324 llvm_unreachable("Template parameter packs are not yet supported");
1327 return TemplateArgumentLoc();
1330 /// \brief Finish template argument deduction for a function template,
1331 /// checking the deduced template arguments for completeness and forming
1332 /// the function template specialization.
1333 Sema::TemplateDeductionResult
1334 Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl
*FunctionTemplate
,
1335 llvm::SmallVectorImpl
<DeducedTemplateArgument
> &Deduced
,
1336 unsigned NumExplicitlySpecified
,
1337 FunctionDecl
*&Specialization
,
1338 TemplateDeductionInfo
&Info
) {
1339 TemplateParameterList
*TemplateParams
1340 = FunctionTemplate
->getTemplateParameters();
1342 // Template argument deduction for function templates in a SFINAE context.
1343 // Trap any errors that might occur.
1344 SFINAETrap
Trap(*this);
1346 // Enter a new template instantiation context while we instantiate the
1347 // actual function declaration.
1348 InstantiatingTemplate
Inst(*this, FunctionTemplate
->getLocation(),
1349 FunctionTemplate
, Deduced
.data(), Deduced
.size(),
1350 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution
);
1352 return TDK_InstantiationDepth
;
1354 ContextRAII
SavedContext(*this, FunctionTemplate
->getTemplatedDecl());
1356 // C++ [temp.deduct.type]p2:
1357 // [...] or if any template argument remains neither deduced nor
1358 // explicitly specified, template argument deduction fails.
1359 TemplateArgumentListBuilder
Builder(TemplateParams
, Deduced
.size());
1360 for (unsigned I
= 0, N
= Deduced
.size(); I
!= N
; ++I
) {
1361 NamedDecl
*Param
= FunctionTemplate
->getTemplateParameters()->getParam(I
);
1362 if (!Deduced
[I
].isNull()) {
1363 if (I
< NumExplicitlySpecified
||
1364 Deduced
[I
].getKind() == TemplateArgument::Type
) {
1365 // We have already fully type-checked and converted this
1366 // argument (because it was explicitly-specified) or no
1367 // additional checking is necessary (because it's a template
1368 // type parameter). Just record the presence of this
1370 Builder
.Append(Deduced
[I
]);
1374 // We have deduced this argument, so it still needs to be
1375 // checked and converted.
1377 // First, for a non-type template parameter type that is
1378 // initialized by a declaration, we need the type of the
1379 // corresponding non-type template parameter.
1381 if (NonTypeTemplateParmDecl
*NTTP
1382 = dyn_cast
<NonTypeTemplateParmDecl
>(Param
)) {
1383 if (Deduced
[I
].getKind() == TemplateArgument::Declaration
) {
1384 NTTPType
= NTTP
->getType();
1385 if (NTTPType
->isDependentType()) {
1386 TemplateArgumentList
TemplateArgs(Context
, Builder
,
1387 /*TakeArgs=*/false);
1388 NTTPType
= SubstType(NTTPType
,
1389 MultiLevelTemplateArgumentList(TemplateArgs
),
1390 NTTP
->getLocation(),
1391 NTTP
->getDeclName());
1392 if (NTTPType
.isNull()) {
1393 Info
.Param
= makeTemplateParameter(Param
);
1394 Info
.reset(new (Context
) TemplateArgumentList(Context
, Builder
,
1395 /*TakeArgs=*/true));
1396 return TDK_SubstitutionFailure
;
1402 // Convert the deduced template argument into a template
1403 // argument that we can check, almost as if the user had written
1404 // the template argument explicitly.
1405 TemplateArgumentLoc Arg
= getTrivialTemplateArgumentLoc(*this,
1410 // Check the template argument, converting it as necessary.
1411 if (CheckTemplateArgument(Param
, Arg
,
1413 FunctionTemplate
->getLocation(),
1414 FunctionTemplate
->getSourceRange().getEnd(),
1416 Deduced
[I
].wasDeducedFromArrayBound()
1417 ? CTAK_DeducedFromArrayBound
1419 Info
.Param
= makeTemplateParameter(
1420 const_cast<NamedDecl
*>(TemplateParams
->getParam(I
)));
1421 Info
.reset(new (Context
) TemplateArgumentList(Context
, Builder
,
1422 /*TakeArgs=*/true));
1423 return TDK_SubstitutionFailure
;
1429 // Substitute into the default template argument, if available.
1430 TemplateArgumentLoc DefArg
1431 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate
,
1432 FunctionTemplate
->getLocation(),
1433 FunctionTemplate
->getSourceRange().getEnd(),
1437 // If there was no default argument, deduction is incomplete.
1438 if (DefArg
.getArgument().isNull()) {
1439 Info
.Param
= makeTemplateParameter(
1440 const_cast<NamedDecl
*>(TemplateParams
->getParam(I
)));
1441 return TDK_Incomplete
;
1444 // Check whether we can actually use the default argument.
1445 if (CheckTemplateArgument(Param
, DefArg
,
1447 FunctionTemplate
->getLocation(),
1448 FunctionTemplate
->getSourceRange().getEnd(),
1451 Info
.Param
= makeTemplateParameter(
1452 const_cast<NamedDecl
*>(TemplateParams
->getParam(I
)));
1453 Info
.reset(new (Context
) TemplateArgumentList(Context
, Builder
,
1454 /*TakeArgs=*/true));
1455 return TDK_SubstitutionFailure
;
1458 // If we get here, we successfully used the default template argument.
1461 // Form the template argument list from the deduced template arguments.
1462 TemplateArgumentList
*DeducedArgumentList
1463 = new (Context
) TemplateArgumentList(Context
, Builder
, /*TakeArgs=*/true);
1464 Info
.reset(DeducedArgumentList
);
1466 // Substitute the deduced template arguments into the function template
1467 // declaration to produce the function template specialization.
1468 DeclContext
*Owner
= FunctionTemplate
->getDeclContext();
1469 if (FunctionTemplate
->getFriendObjectKind())
1470 Owner
= FunctionTemplate
->getLexicalDeclContext();
1471 Specialization
= cast_or_null
<FunctionDecl
>(
1472 SubstDecl(FunctionTemplate
->getTemplatedDecl(), Owner
,
1473 MultiLevelTemplateArgumentList(*DeducedArgumentList
)));
1474 if (!Specialization
)
1475 return TDK_SubstitutionFailure
;
1477 assert(Specialization
->getPrimaryTemplate()->getCanonicalDecl() ==
1478 FunctionTemplate
->getCanonicalDecl());
1480 // If the template argument list is owned by the function template
1481 // specialization, release it.
1482 if (Specialization
->getTemplateSpecializationArgs() == DeducedArgumentList
&&
1483 !Trap
.hasErrorOccurred())
1486 // There may have been an error that did not prevent us from constructing a
1487 // declaration. Mark the declaration invalid and return with a substitution
1489 if (Trap
.hasErrorOccurred()) {
1490 Specialization
->setInvalidDecl(true);
1491 return TDK_SubstitutionFailure
;
1497 /// Gets the type of a function for template-argument-deducton
1498 /// purposes when it's considered as part of an overload set.
1499 static QualType
GetTypeOfFunction(ASTContext
&Context
,
1500 const OverloadExpr::FindResult
&R
,
1502 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Fn
))
1503 if (Method
->isInstance()) {
1504 // An instance method that's referenced in a form that doesn't
1505 // look like a member pointer is just invalid.
1506 if (!R
.HasFormOfMemberPointer
) return QualType();
1508 return Context
.getMemberPointerType(Fn
->getType(),
1509 Context
.getTypeDeclType(Method
->getParent()).getTypePtr());
1512 if (!R
.IsAddressOfOperand
) return Fn
->getType();
1513 return Context
.getPointerType(Fn
->getType());
1516 /// Apply the deduction rules for overload sets.
1518 /// \return the null type if this argument should be treated as an
1519 /// undeduced context
1521 ResolveOverloadForDeduction(Sema
&S
, TemplateParameterList
*TemplateParams
,
1522 Expr
*Arg
, QualType ParamType
) {
1524 OverloadExpr::FindResult R
= OverloadExpr::find(Arg
);
1526 OverloadExpr
*Ovl
= R
.Expression
;
1528 // If there were explicit template arguments, we can only find
1529 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
1530 // unambiguously name a full specialization.
1531 if (Ovl
->hasExplicitTemplateArgs()) {
1532 // But we can still look for an explicit specialization.
1533 if (FunctionDecl
*ExplicitSpec
1534 = S
.ResolveSingleFunctionTemplateSpecialization(Ovl
))
1535 return GetTypeOfFunction(S
.Context
, R
, ExplicitSpec
);
1539 // C++0x [temp.deduct.call]p6:
1540 // When P is a function type, pointer to function type, or pointer
1541 // to member function type:
1543 if (!ParamType
->isFunctionType() &&
1544 !ParamType
->isFunctionPointerType() &&
1545 !ParamType
->isMemberFunctionPointerType())
1549 for (UnresolvedSetIterator I
= Ovl
->decls_begin(),
1550 E
= Ovl
->decls_end(); I
!= E
; ++I
) {
1551 NamedDecl
*D
= (*I
)->getUnderlyingDecl();
1553 // - If the argument is an overload set containing one or more
1554 // function templates, the parameter is treated as a
1555 // non-deduced context.
1556 if (isa
<FunctionTemplateDecl
>(D
))
1559 FunctionDecl
*Fn
= cast
<FunctionDecl
>(D
);
1560 QualType ArgType
= GetTypeOfFunction(S
.Context
, R
, Fn
);
1561 if (ArgType
.isNull()) continue;
1563 // - If the argument is an overload set (not containing function
1564 // templates), trial argument deduction is attempted using each
1565 // of the members of the set. If deduction succeeds for only one
1566 // of the overload set members, that member is used as the
1567 // argument value for the deduction. If deduction succeeds for
1568 // more than one member of the overload set the parameter is
1569 // treated as a non-deduced context.
1571 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
1572 // Type deduction is done independently for each P/A pair, and
1573 // the deduced template argument values are then combined.
1574 // So we do not reject deductions which were made elsewhere.
1575 llvm::SmallVector
<DeducedTemplateArgument
, 8>
1576 Deduced(TemplateParams
->size());
1577 TemplateDeductionInfo
Info(S
.Context
, Ovl
->getNameLoc());
1580 Sema::TemplateDeductionResult Result
1581 = DeduceTemplateArguments(S
, TemplateParams
,
1583 Info
, Deduced
, TDF
);
1584 if (Result
) continue;
1585 if (!Match
.isNull()) return QualType();
1592 /// \brief Perform template argument deduction from a function call
1593 /// (C++ [temp.deduct.call]).
1595 /// \param FunctionTemplate the function template for which we are performing
1596 /// template argument deduction.
1598 /// \param ExplicitTemplateArguments the explicit template arguments provided
1601 /// \param Args the function call arguments
1603 /// \param NumArgs the number of arguments in Args
1605 /// \param Name the name of the function being called. This is only significant
1606 /// when the function template is a conversion function template, in which
1607 /// case this routine will also perform template argument deduction based on
1608 /// the function to which
1610 /// \param Specialization if template argument deduction was successful,
1611 /// this will be set to the function template specialization produced by
1612 /// template argument deduction.
1614 /// \param Info the argument will be updated to provide additional information
1615 /// about template argument deduction.
1617 /// \returns the result of template argument deduction.
1618 Sema::TemplateDeductionResult
1619 Sema::DeduceTemplateArguments(FunctionTemplateDecl
*FunctionTemplate
,
1620 const TemplateArgumentListInfo
*ExplicitTemplateArgs
,
1621 Expr
**Args
, unsigned NumArgs
,
1622 FunctionDecl
*&Specialization
,
1623 TemplateDeductionInfo
&Info
) {
1624 FunctionDecl
*Function
= FunctionTemplate
->getTemplatedDecl();
1626 // C++ [temp.deduct.call]p1:
1627 // Template argument deduction is done by comparing each function template
1628 // parameter type (call it P) with the type of the corresponding argument
1629 // of the call (call it A) as described below.
1630 unsigned CheckArgs
= NumArgs
;
1631 if (NumArgs
< Function
->getMinRequiredArguments())
1632 return TDK_TooFewArguments
;
1633 else if (NumArgs
> Function
->getNumParams()) {
1634 const FunctionProtoType
*Proto
1635 = Function
->getType()->getAs
<FunctionProtoType
>();
1636 if (!Proto
->isVariadic())
1637 return TDK_TooManyArguments
;
1639 CheckArgs
= Function
->getNumParams();
1642 // The types of the parameters from which we will perform template argument
1644 LocalInstantiationScope
InstScope(*this);
1645 TemplateParameterList
*TemplateParams
1646 = FunctionTemplate
->getTemplateParameters();
1647 llvm::SmallVector
<DeducedTemplateArgument
, 4> Deduced
;
1648 llvm::SmallVector
<QualType
, 4> ParamTypes
;
1649 unsigned NumExplicitlySpecified
= 0;
1650 if (ExplicitTemplateArgs
) {
1651 TemplateDeductionResult Result
=
1652 SubstituteExplicitTemplateArguments(FunctionTemplate
,
1653 *ExplicitTemplateArgs
,
1661 NumExplicitlySpecified
= Deduced
.size();
1663 // Just fill in the parameter types from the function declaration.
1664 for (unsigned I
= 0; I
!= CheckArgs
; ++I
)
1665 ParamTypes
.push_back(Function
->getParamDecl(I
)->getType());
1668 // Deduce template arguments from the function parameters.
1669 Deduced
.resize(TemplateParams
->size());
1670 for (unsigned I
= 0; I
!= CheckArgs
; ++I
) {
1671 QualType ParamType
= ParamTypes
[I
];
1672 QualType ArgType
= Args
[I
]->getType();
1674 // Overload sets usually make this parameter an undeduced
1675 // context, but there are sometimes special circumstances.
1676 if (ArgType
== Context
.OverloadTy
) {
1677 ArgType
= ResolveOverloadForDeduction(*this, TemplateParams
,
1678 Args
[I
], ParamType
);
1679 if (ArgType
.isNull())
1683 // C++ [temp.deduct.call]p2:
1684 // If P is not a reference type:
1685 QualType CanonParamType
= Context
.getCanonicalType(ParamType
);
1686 bool ParamWasReference
= isa
<ReferenceType
>(CanonParamType
);
1687 if (!ParamWasReference
) {
1688 // - If A is an array type, the pointer type produced by the
1689 // array-to-pointer standard conversion (4.2) is used in place of
1690 // A for type deduction; otherwise,
1691 if (ArgType
->isArrayType())
1692 ArgType
= Context
.getArrayDecayedType(ArgType
);
1693 // - If A is a function type, the pointer type produced by the
1694 // function-to-pointer standard conversion (4.3) is used in place
1695 // of A for type deduction; otherwise,
1696 else if (ArgType
->isFunctionType())
1697 ArgType
= Context
.getPointerType(ArgType
);
1699 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
1700 // type are ignored for type deduction.
1701 QualType CanonArgType
= Context
.getCanonicalType(ArgType
);
1702 if (CanonArgType
.getLocalCVRQualifiers())
1703 ArgType
= CanonArgType
.getLocalUnqualifiedType();
1707 // C++0x [temp.deduct.call]p3:
1708 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
1709 // are ignored for type deduction.
1710 if (CanonParamType
.getLocalCVRQualifiers())
1711 ParamType
= CanonParamType
.getLocalUnqualifiedType();
1712 if (const ReferenceType
*ParamRefType
= ParamType
->getAs
<ReferenceType
>()) {
1713 // [...] If P is a reference type, the type referred to by P is used
1714 // for type deduction.
1715 ParamType
= ParamRefType
->getPointeeType();
1717 // [...] If P is of the form T&&, where T is a template parameter, and
1718 // the argument is an lvalue, the type A& is used in place of A for
1720 if (isa
<RValueReferenceType
>(ParamRefType
) &&
1721 ParamRefType
->getAs
<TemplateTypeParmType
>() &&
1722 Args
[I
]->isLvalue(Context
) == Expr::LV_Valid
)
1723 ArgType
= Context
.getLValueReferenceType(ArgType
);
1726 // C++0x [temp.deduct.call]p4:
1727 // In general, the deduction process attempts to find template argument
1728 // values that will make the deduced A identical to A (after the type A
1729 // is transformed as described above). [...]
1730 unsigned TDF
= TDF_SkipNonDependent
;
1732 // - If the original P is a reference type, the deduced A (i.e., the
1733 // type referred to by the reference) can be more cv-qualified than
1734 // the transformed A.
1735 if (ParamWasReference
)
1736 TDF
|= TDF_ParamWithReferenceType
;
1737 // - The transformed A can be another pointer or pointer to member
1738 // type that can be converted to the deduced A via a qualification
1739 // conversion (4.4).
1740 if (ArgType
->isPointerType() || ArgType
->isMemberPointerType() ||
1741 ArgType
->isObjCObjectPointerType())
1742 TDF
|= TDF_IgnoreQualifiers
;
1743 // - If P is a class and P has the form simple-template-id, then the
1744 // transformed A can be a derived class of the deduced A. Likewise,
1745 // if P is a pointer to a class of the form simple-template-id, the
1746 // transformed A can be a pointer to a derived class pointed to by
1748 if (isSimpleTemplateIdType(ParamType
) ||
1749 (isa
<PointerType
>(ParamType
) &&
1750 isSimpleTemplateIdType(
1751 ParamType
->getAs
<PointerType
>()->getPointeeType())))
1752 TDF
|= TDF_DerivedClass
;
1754 if (TemplateDeductionResult Result
1755 = ::DeduceTemplateArguments(*this, TemplateParams
,
1756 ParamType
, ArgType
, Info
, Deduced
,
1760 // FIXME: we need to check that the deduced A is the same as A,
1761 // modulo the various allowed differences.
1764 return FinishTemplateArgumentDeduction(FunctionTemplate
, Deduced
,
1765 NumExplicitlySpecified
,
1766 Specialization
, Info
);
1769 /// \brief Deduce template arguments when taking the address of a function
1770 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
1773 /// \param FunctionTemplate the function template for which we are performing
1774 /// template argument deduction.
1776 /// \param ExplicitTemplateArguments the explicitly-specified template
1779 /// \param ArgFunctionType the function type that will be used as the
1780 /// "argument" type (A) when performing template argument deduction from the
1781 /// function template's function type. This type may be NULL, if there is no
1782 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
1784 /// \param Specialization if template argument deduction was successful,
1785 /// this will be set to the function template specialization produced by
1786 /// template argument deduction.
1788 /// \param Info the argument will be updated to provide additional information
1789 /// about template argument deduction.
1791 /// \returns the result of template argument deduction.
1792 Sema::TemplateDeductionResult
1793 Sema::DeduceTemplateArguments(FunctionTemplateDecl
*FunctionTemplate
,
1794 const TemplateArgumentListInfo
*ExplicitTemplateArgs
,
1795 QualType ArgFunctionType
,
1796 FunctionDecl
*&Specialization
,
1797 TemplateDeductionInfo
&Info
) {
1798 FunctionDecl
*Function
= FunctionTemplate
->getTemplatedDecl();
1799 TemplateParameterList
*TemplateParams
1800 = FunctionTemplate
->getTemplateParameters();
1801 QualType FunctionType
= Function
->getType();
1803 // Substitute any explicit template arguments.
1804 LocalInstantiationScope
InstScope(*this);
1805 llvm::SmallVector
<DeducedTemplateArgument
, 4> Deduced
;
1806 unsigned NumExplicitlySpecified
= 0;
1807 llvm::SmallVector
<QualType
, 4> ParamTypes
;
1808 if (ExplicitTemplateArgs
) {
1809 if (TemplateDeductionResult Result
1810 = SubstituteExplicitTemplateArguments(FunctionTemplate
,
1811 *ExplicitTemplateArgs
,
1812 Deduced
, ParamTypes
,
1813 &FunctionType
, Info
))
1816 NumExplicitlySpecified
= Deduced
.size();
1819 // Template argument deduction for function templates in a SFINAE context.
1820 // Trap any errors that might occur.
1821 SFINAETrap
Trap(*this);
1823 Deduced
.resize(TemplateParams
->size());
1825 if (!ArgFunctionType
.isNull()) {
1826 // Deduce template arguments from the function type.
1827 if (TemplateDeductionResult Result
1828 = ::DeduceTemplateArguments(*this, TemplateParams
,
1829 FunctionType
, ArgFunctionType
, Info
,
1834 return FinishTemplateArgumentDeduction(FunctionTemplate
, Deduced
,
1835 NumExplicitlySpecified
,
1836 Specialization
, Info
);
1839 /// \brief Deduce template arguments for a templated conversion
1840 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
1841 /// conversion function template specialization.
1842 Sema::TemplateDeductionResult
1843 Sema::DeduceTemplateArguments(FunctionTemplateDecl
*FunctionTemplate
,
1845 CXXConversionDecl
*&Specialization
,
1846 TemplateDeductionInfo
&Info
) {
1847 CXXConversionDecl
*Conv
1848 = cast
<CXXConversionDecl
>(FunctionTemplate
->getTemplatedDecl());
1849 QualType FromType
= Conv
->getConversionType();
1851 // Canonicalize the types for deduction.
1852 QualType P
= Context
.getCanonicalType(FromType
);
1853 QualType A
= Context
.getCanonicalType(ToType
);
1855 // C++0x [temp.deduct.conv]p3:
1856 // If P is a reference type, the type referred to by P is used for
1858 if (const ReferenceType
*PRef
= P
->getAs
<ReferenceType
>())
1859 P
= PRef
->getPointeeType();
1861 // C++0x [temp.deduct.conv]p3:
1862 // If A is a reference type, the type referred to by A is used
1863 // for type deduction.
1864 if (const ReferenceType
*ARef
= A
->getAs
<ReferenceType
>())
1865 A
= ARef
->getPointeeType();
1866 // C++ [temp.deduct.conv]p2:
1868 // If A is not a reference type:
1870 assert(!A
->isReferenceType() && "Reference types were handled above");
1872 // - If P is an array type, the pointer type produced by the
1873 // array-to-pointer standard conversion (4.2) is used in place
1874 // of P for type deduction; otherwise,
1875 if (P
->isArrayType())
1876 P
= Context
.getArrayDecayedType(P
);
1877 // - If P is a function type, the pointer type produced by the
1878 // function-to-pointer standard conversion (4.3) is used in
1879 // place of P for type deduction; otherwise,
1880 else if (P
->isFunctionType())
1881 P
= Context
.getPointerType(P
);
1882 // - If P is a cv-qualified type, the top level cv-qualifiers of
1883 // P’s type are ignored for type deduction.
1885 P
= P
.getUnqualifiedType();
1887 // C++0x [temp.deduct.conv]p3:
1888 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
1889 // type are ignored for type deduction.
1890 A
= A
.getUnqualifiedType();
1893 // Template argument deduction for function templates in a SFINAE context.
1894 // Trap any errors that might occur.
1895 SFINAETrap
Trap(*this);
1897 // C++ [temp.deduct.conv]p1:
1898 // Template argument deduction is done by comparing the return
1899 // type of the template conversion function (call it P) with the
1900 // type that is required as the result of the conversion (call it
1901 // A) as described in 14.8.2.4.
1902 TemplateParameterList
*TemplateParams
1903 = FunctionTemplate
->getTemplateParameters();
1904 llvm::SmallVector
<DeducedTemplateArgument
, 4> Deduced
;
1905 Deduced
.resize(TemplateParams
->size());
1907 // C++0x [temp.deduct.conv]p4:
1908 // In general, the deduction process attempts to find template
1909 // argument values that will make the deduced A identical to
1910 // A. However, there are two cases that allow a difference:
1912 // - If the original A is a reference type, A can be more
1913 // cv-qualified than the deduced A (i.e., the type referred to
1914 // by the reference)
1915 if (ToType
->isReferenceType())
1916 TDF
|= TDF_ParamWithReferenceType
;
1917 // - The deduced A can be another pointer or pointer to member
1918 // type that can be converted to A via a qualification
1921 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
1922 // both P and A are pointers or member pointers. In this case, we
1923 // just ignore cv-qualifiers completely).
1924 if ((P
->isPointerType() && A
->isPointerType()) ||
1925 (P
->isMemberPointerType() && P
->isMemberPointerType()))
1926 TDF
|= TDF_IgnoreQualifiers
;
1927 if (TemplateDeductionResult Result
1928 = ::DeduceTemplateArguments(*this, TemplateParams
,
1929 P
, A
, Info
, Deduced
, TDF
))
1932 // FIXME: we need to check that the deduced A is the same as A,
1933 // modulo the various allowed differences.
1935 // Finish template argument deduction.
1936 LocalInstantiationScope
InstScope(*this);
1937 FunctionDecl
*Spec
= 0;
1938 TemplateDeductionResult Result
1939 = FinishTemplateArgumentDeduction(FunctionTemplate
, Deduced
, 0, Spec
,
1941 Specialization
= cast_or_null
<CXXConversionDecl
>(Spec
);
1945 /// \brief Deduce template arguments for a function template when there is
1946 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
1948 /// \param FunctionTemplate the function template for which we are performing
1949 /// template argument deduction.
1951 /// \param ExplicitTemplateArguments the explicitly-specified template
1954 /// \param Specialization if template argument deduction was successful,
1955 /// this will be set to the function template specialization produced by
1956 /// template argument deduction.
1958 /// \param Info the argument will be updated to provide additional information
1959 /// about template argument deduction.
1961 /// \returns the result of template argument deduction.
1962 Sema::TemplateDeductionResult
1963 Sema::DeduceTemplateArguments(FunctionTemplateDecl
*FunctionTemplate
,
1964 const TemplateArgumentListInfo
*ExplicitTemplateArgs
,
1965 FunctionDecl
*&Specialization
,
1966 TemplateDeductionInfo
&Info
) {
1967 return DeduceTemplateArguments(FunctionTemplate
, ExplicitTemplateArgs
,
1968 QualType(), Specialization
, Info
);
1971 /// \brief Stores the result of comparing the qualifiers of two types.
1972 enum DeductionQualifierComparison
{
1973 NeitherMoreQualified
= 0,
1978 /// \brief Deduce the template arguments during partial ordering by comparing
1979 /// the parameter type and the argument type (C++0x [temp.deduct.partial]).
1981 /// \param S the semantic analysis object within which we are deducing
1983 /// \param TemplateParams the template parameters that we are deducing
1985 /// \param ParamIn the parameter type
1987 /// \param ArgIn the argument type
1989 /// \param Info information about the template argument deduction itself
1991 /// \param Deduced the deduced template arguments
1993 /// \returns the result of template argument deduction so far. Note that a
1994 /// "success" result means that template argument deduction has not yet failed,
1995 /// but it may still fail, later, for other reasons.
1996 static Sema::TemplateDeductionResult
1997 DeduceTemplateArgumentsDuringPartialOrdering(Sema
&S
,
1998 TemplateParameterList
*TemplateParams
,
1999 QualType ParamIn
, QualType ArgIn
,
2000 TemplateDeductionInfo
&Info
,
2001 llvm::SmallVectorImpl
<DeducedTemplateArgument
> &Deduced
,
2002 llvm::SmallVectorImpl
<DeductionQualifierComparison
> *QualifierComparisons
) {
2003 CanQualType Param
= S
.Context
.getCanonicalType(ParamIn
);
2004 CanQualType Arg
= S
.Context
.getCanonicalType(ArgIn
);
2006 // C++0x [temp.deduct.partial]p5:
2007 // Before the partial ordering is done, certain transformations are
2008 // performed on the types used for partial ordering:
2009 // - If P is a reference type, P is replaced by the type referred to.
2010 CanQual
<ReferenceType
> ParamRef
= Param
->getAs
<ReferenceType
>();
2011 if (!ParamRef
.isNull())
2012 Param
= ParamRef
->getPointeeType();
2014 // - If A is a reference type, A is replaced by the type referred to.
2015 CanQual
<ReferenceType
> ArgRef
= Arg
->getAs
<ReferenceType
>();
2016 if (!ArgRef
.isNull())
2017 Arg
= ArgRef
->getPointeeType();
2019 if (QualifierComparisons
&& !ParamRef
.isNull() && !ArgRef
.isNull()) {
2020 // C++0x [temp.deduct.partial]p6:
2021 // If both P and A were reference types (before being replaced with the
2022 // type referred to above), determine which of the two types (if any) is
2023 // more cv-qualified than the other; otherwise the types are considered to
2024 // be equally cv-qualified for partial ordering purposes. The result of this
2025 // determination will be used below.
2027 // We save this information for later, using it only when deduction
2028 // succeeds in both directions.
2029 DeductionQualifierComparison QualifierResult
= NeitherMoreQualified
;
2030 if (Param
.isMoreQualifiedThan(Arg
))
2031 QualifierResult
= ParamMoreQualified
;
2032 else if (Arg
.isMoreQualifiedThan(Param
))
2033 QualifierResult
= ArgMoreQualified
;
2034 QualifierComparisons
->push_back(QualifierResult
);
2037 // C++0x [temp.deduct.partial]p7:
2038 // Remove any top-level cv-qualifiers:
2039 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2041 Param
= Param
.getUnqualifiedType();
2042 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2044 Arg
= Arg
.getUnqualifiedType();
2046 // C++0x [temp.deduct.partial]p8:
2047 // Using the resulting types P and A the deduction is then done as
2048 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2049 // from the argument template is considered to be at least as specialized
2050 // as the type from the parameter template.
2051 return DeduceTemplateArguments(S
, TemplateParams
, Param
, Arg
, Info
,
2056 MarkUsedTemplateParameters(Sema
&SemaRef
, QualType T
,
2059 llvm::SmallVectorImpl
<bool> &Deduced
);
2061 /// \brief Determine whether the function template \p FT1 is at least as
2062 /// specialized as \p FT2.
2063 static bool isAtLeastAsSpecializedAs(Sema
&S
,
2065 FunctionTemplateDecl
*FT1
,
2066 FunctionTemplateDecl
*FT2
,
2067 TemplatePartialOrderingContext TPOC
,
2068 llvm::SmallVectorImpl
<DeductionQualifierComparison
> *QualifierComparisons
) {
2069 FunctionDecl
*FD1
= FT1
->getTemplatedDecl();
2070 FunctionDecl
*FD2
= FT2
->getTemplatedDecl();
2071 const FunctionProtoType
*Proto1
= FD1
->getType()->getAs
<FunctionProtoType
>();
2072 const FunctionProtoType
*Proto2
= FD2
->getType()->getAs
<FunctionProtoType
>();
2074 assert(Proto1
&& Proto2
&& "Function templates must have prototypes");
2075 TemplateParameterList
*TemplateParams
= FT2
->getTemplateParameters();
2076 llvm::SmallVector
<DeducedTemplateArgument
, 4> Deduced
;
2077 Deduced
.resize(TemplateParams
->size());
2079 // C++0x [temp.deduct.partial]p3:
2080 // The types used to determine the ordering depend on the context in which
2081 // the partial ordering is done:
2082 TemplateDeductionInfo
Info(S
.Context
, Loc
);
2085 // - In the context of a function call, the function parameter types are
2087 unsigned NumParams
= std::min(Proto1
->getNumArgs(), Proto2
->getNumArgs());
2088 for (unsigned I
= 0; I
!= NumParams
; ++I
)
2089 if (DeduceTemplateArgumentsDuringPartialOrdering(S
,
2091 Proto2
->getArgType(I
),
2092 Proto1
->getArgType(I
),
2095 QualifierComparisons
))
2101 case TPOC_Conversion
:
2102 // - In the context of a call to a conversion operator, the return types
2103 // of the conversion function templates are used.
2104 if (DeduceTemplateArgumentsDuringPartialOrdering(S
,
2106 Proto2
->getResultType(),
2107 Proto1
->getResultType(),
2110 QualifierComparisons
))
2115 // - In other contexts (14.6.6.2) the function template’s function type
2117 if (DeduceTemplateArgumentsDuringPartialOrdering(S
,
2123 QualifierComparisons
))
2128 // C++0x [temp.deduct.partial]p11:
2129 // In most cases, all template parameters must have values in order for
2130 // deduction to succeed, but for partial ordering purposes a template
2131 // parameter may remain without a value provided it is not used in the
2132 // types being used for partial ordering. [ Note: a template parameter used
2133 // in a non-deduced context is considered used. -end note]
2134 unsigned ArgIdx
= 0, NumArgs
= Deduced
.size();
2135 for (; ArgIdx
!= NumArgs
; ++ArgIdx
)
2136 if (Deduced
[ArgIdx
].isNull())
2139 if (ArgIdx
== NumArgs
) {
2140 // All template arguments were deduced. FT1 is at least as specialized
2145 // Figure out which template parameters were used.
2146 llvm::SmallVector
<bool, 4> UsedParameters
;
2147 UsedParameters
.resize(TemplateParams
->size());
2150 unsigned NumParams
= std::min(Proto1
->getNumArgs(), Proto2
->getNumArgs());
2151 for (unsigned I
= 0; I
!= NumParams
; ++I
)
2152 ::MarkUsedTemplateParameters(S
, Proto2
->getArgType(I
), false,
2153 TemplateParams
->getDepth(),
2158 case TPOC_Conversion
:
2159 ::MarkUsedTemplateParameters(S
, Proto2
->getResultType(), false,
2160 TemplateParams
->getDepth(),
2165 ::MarkUsedTemplateParameters(S
, FD2
->getType(), false,
2166 TemplateParams
->getDepth(),
2171 for (; ArgIdx
!= NumArgs
; ++ArgIdx
)
2172 // If this argument had no value deduced but was used in one of the types
2173 // used for partial ordering, then deduction fails.
2174 if (Deduced
[ArgIdx
].isNull() && UsedParameters
[ArgIdx
])
2181 /// \brief Returns the more specialized function template according
2182 /// to the rules of function template partial ordering (C++ [temp.func.order]).
2184 /// \param FT1 the first function template
2186 /// \param FT2 the second function template
2188 /// \param TPOC the context in which we are performing partial ordering of
2189 /// function templates.
2191 /// \returns the more specialized function template. If neither
2192 /// template is more specialized, returns NULL.
2193 FunctionTemplateDecl
*
2194 Sema::getMoreSpecializedTemplate(FunctionTemplateDecl
*FT1
,
2195 FunctionTemplateDecl
*FT2
,
2197 TemplatePartialOrderingContext TPOC
) {
2198 llvm::SmallVector
<DeductionQualifierComparison
, 4> QualifierComparisons
;
2199 bool Better1
= isAtLeastAsSpecializedAs(*this, Loc
, FT1
, FT2
, TPOC
, 0);
2200 bool Better2
= isAtLeastAsSpecializedAs(*this, Loc
, FT2
, FT1
, TPOC
,
2201 &QualifierComparisons
);
2203 if (Better1
!= Better2
) // We have a clear winner
2204 return Better1
? FT1
: FT2
;
2206 if (!Better1
&& !Better2
) // Neither is better than the other
2210 // C++0x [temp.deduct.partial]p10:
2211 // If for each type being considered a given template is at least as
2212 // specialized for all types and more specialized for some set of types and
2213 // the other template is not more specialized for any types or is not at
2214 // least as specialized for any types, then the given template is more
2215 // specialized than the other template. Otherwise, neither template is more
2216 // specialized than the other.
2219 for (unsigned I
= 0, N
= QualifierComparisons
.size(); I
!= N
; ++I
) {
2220 // C++0x [temp.deduct.partial]p9:
2221 // If, for a given type, deduction succeeds in both directions (i.e., the
2222 // types are identical after the transformations above) and if the type
2223 // from the argument template is more cv-qualified than the type from the
2224 // parameter template (as described above) that type is considered to be
2225 // more specialized than the other. If neither type is more cv-qualified
2226 // than the other then neither type is more specialized than the other.
2227 switch (QualifierComparisons
[I
]) {
2228 case NeitherMoreQualified
:
2231 case ParamMoreQualified
:
2237 case ArgMoreQualified
:
2245 assert(!(Better1
&& Better2
) && "Should have broken out in the loop above");
2254 /// \brief Determine if the two templates are equivalent.
2255 static bool isSameTemplate(TemplateDecl
*T1
, TemplateDecl
*T2
) {
2262 return T1
->getCanonicalDecl() == T2
->getCanonicalDecl();
2265 /// \brief Retrieve the most specialized of the given function template
2266 /// specializations.
2268 /// \param SpecBegin the start iterator of the function template
2269 /// specializations that we will be comparing.
2271 /// \param SpecEnd the end iterator of the function template
2272 /// specializations, paired with \p SpecBegin.
2274 /// \param TPOC the partial ordering context to use to compare the function
2275 /// template specializations.
2277 /// \param Loc the location where the ambiguity or no-specializations
2278 /// diagnostic should occur.
2280 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
2281 /// no matching candidates.
2283 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
2286 /// \param CandidateDiag partial diagnostic used for each function template
2287 /// specialization that is a candidate in the ambiguous ordering. One parameter
2288 /// in this diagnostic should be unbound, which will correspond to the string
2289 /// describing the template arguments for the function template specialization.
2291 /// \param Index if non-NULL and the result of this function is non-nULL,
2292 /// receives the index corresponding to the resulting function template
2295 /// \returns the most specialized function template specialization, if
2296 /// found. Otherwise, returns SpecEnd.
2298 /// \todo FIXME: Consider passing in the "also-ran" candidates that failed
2299 /// template argument deduction.
2300 UnresolvedSetIterator
2301 Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin
,
2302 UnresolvedSetIterator SpecEnd
,
2303 TemplatePartialOrderingContext TPOC
,
2305 const PartialDiagnostic
&NoneDiag
,
2306 const PartialDiagnostic
&AmbigDiag
,
2307 const PartialDiagnostic
&CandidateDiag
) {
2308 if (SpecBegin
== SpecEnd
) {
2309 Diag(Loc
, NoneDiag
);
2313 if (SpecBegin
+ 1 == SpecEnd
)
2316 // Find the function template that is better than all of the templates it
2317 // has been compared to.
2318 UnresolvedSetIterator Best
= SpecBegin
;
2319 FunctionTemplateDecl
*BestTemplate
2320 = cast
<FunctionDecl
>(*Best
)->getPrimaryTemplate();
2321 assert(BestTemplate
&& "Not a function template specialization?");
2322 for (UnresolvedSetIterator I
= SpecBegin
+ 1; I
!= SpecEnd
; ++I
) {
2323 FunctionTemplateDecl
*Challenger
2324 = cast
<FunctionDecl
>(*I
)->getPrimaryTemplate();
2325 assert(Challenger
&& "Not a function template specialization?");
2326 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate
, Challenger
,
2330 BestTemplate
= Challenger
;
2334 // Make sure that the "best" function template is more specialized than all
2336 bool Ambiguous
= false;
2337 for (UnresolvedSetIterator I
= SpecBegin
; I
!= SpecEnd
; ++I
) {
2338 FunctionTemplateDecl
*Challenger
2339 = cast
<FunctionDecl
>(*I
)->getPrimaryTemplate();
2341 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate
, Challenger
,
2350 // We found an answer. Return it.
2354 // Diagnose the ambiguity.
2355 Diag(Loc
, AmbigDiag
);
2357 // FIXME: Can we order the candidates in some sane way?
2358 for (UnresolvedSetIterator I
= SpecBegin
; I
!= SpecEnd
; ++I
)
2359 Diag((*I
)->getLocation(), CandidateDiag
)
2360 << getTemplateArgumentBindingsText(
2361 cast
<FunctionDecl
>(*I
)->getPrimaryTemplate()->getTemplateParameters(),
2362 *cast
<FunctionDecl
>(*I
)->getTemplateSpecializationArgs());
2367 /// \brief Returns the more specialized class template partial specialization
2368 /// according to the rules of partial ordering of class template partial
2369 /// specializations (C++ [temp.class.order]).
2371 /// \param PS1 the first class template partial specialization
2373 /// \param PS2 the second class template partial specialization
2375 /// \returns the more specialized class template partial specialization. If
2376 /// neither partial specialization is more specialized, returns NULL.
2377 ClassTemplatePartialSpecializationDecl
*
2378 Sema::getMoreSpecializedPartialSpecialization(
2379 ClassTemplatePartialSpecializationDecl
*PS1
,
2380 ClassTemplatePartialSpecializationDecl
*PS2
,
2381 SourceLocation Loc
) {
2382 // C++ [temp.class.order]p1:
2383 // For two class template partial specializations, the first is at least as
2384 // specialized as the second if, given the following rewrite to two
2385 // function templates, the first function template is at least as
2386 // specialized as the second according to the ordering rules for function
2387 // templates (14.6.6.2):
2388 // - the first function template has the same template parameters as the
2389 // first partial specialization and has a single function parameter
2390 // whose type is a class template specialization with the template
2391 // arguments of the first partial specialization, and
2392 // - the second function template has the same template parameters as the
2393 // second partial specialization and has a single function parameter
2394 // whose type is a class template specialization with the template
2395 // arguments of the second partial specialization.
2397 // Rather than synthesize function templates, we merely perform the
2398 // equivalent partial ordering by performing deduction directly on
2399 // the template arguments of the class template partial
2400 // specializations. This computation is slightly simpler than the
2401 // general problem of function template partial ordering, because
2402 // class template partial specializations are more constrained. We
2403 // know that every template parameter is deducible from the class
2404 // template partial specialization's template arguments, for
2406 llvm::SmallVector
<DeducedTemplateArgument
, 4> Deduced
;
2407 TemplateDeductionInfo
Info(Context
, Loc
);
2409 QualType PT1
= PS1
->getInjectedSpecializationType();
2410 QualType PT2
= PS2
->getInjectedSpecializationType();
2412 // Determine whether PS1 is at least as specialized as PS2
2413 Deduced
.resize(PS2
->getTemplateParameters()->size());
2414 bool Better1
= !DeduceTemplateArgumentsDuringPartialOrdering(*this,
2415 PS2
->getTemplateParameters(),
2422 Better1
= !::FinishTemplateArgumentDeduction(*this, PS2
,
2423 PS1
->getTemplateArgs(),
2426 // Determine whether PS2 is at least as specialized as PS1
2428 Deduced
.resize(PS1
->getTemplateParameters()->size());
2429 bool Better2
= !DeduceTemplateArgumentsDuringPartialOrdering(*this,
2430 PS1
->getTemplateParameters(),
2437 Better2
= !::FinishTemplateArgumentDeduction(*this, PS1
,
2438 PS2
->getTemplateArgs(),
2441 if (Better1
== Better2
)
2444 return Better1
? PS1
: PS2
;
2448 MarkUsedTemplateParameters(Sema
&SemaRef
,
2449 const TemplateArgument
&TemplateArg
,
2452 llvm::SmallVectorImpl
<bool> &Used
);
2454 /// \brief Mark the template parameters that are used by the given
2457 MarkUsedTemplateParameters(Sema
&SemaRef
,
2461 llvm::SmallVectorImpl
<bool> &Used
) {
2462 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
2463 // find other occurrences of template parameters.
2464 const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
);
2468 const NonTypeTemplateParmDecl
*NTTP
2469 = dyn_cast
<NonTypeTemplateParmDecl
>(DRE
->getDecl());
2473 if (NTTP
->getDepth() == Depth
)
2474 Used
[NTTP
->getIndex()] = true;
2477 /// \brief Mark the template parameters that are used by the given
2478 /// nested name specifier.
2480 MarkUsedTemplateParameters(Sema
&SemaRef
,
2481 NestedNameSpecifier
*NNS
,
2484 llvm::SmallVectorImpl
<bool> &Used
) {
2488 MarkUsedTemplateParameters(SemaRef
, NNS
->getPrefix(), OnlyDeduced
, Depth
,
2490 MarkUsedTemplateParameters(SemaRef
, QualType(NNS
->getAsType(), 0),
2491 OnlyDeduced
, Depth
, Used
);
2494 /// \brief Mark the template parameters that are used by the given
2497 MarkUsedTemplateParameters(Sema
&SemaRef
,
2501 llvm::SmallVectorImpl
<bool> &Used
) {
2502 if (TemplateDecl
*Template
= Name
.getAsTemplateDecl()) {
2503 if (TemplateTemplateParmDecl
*TTP
2504 = dyn_cast
<TemplateTemplateParmDecl
>(Template
)) {
2505 if (TTP
->getDepth() == Depth
)
2506 Used
[TTP
->getIndex()] = true;
2511 if (QualifiedTemplateName
*QTN
= Name
.getAsQualifiedTemplateName())
2512 MarkUsedTemplateParameters(SemaRef
, QTN
->getQualifier(), OnlyDeduced
,
2514 if (DependentTemplateName
*DTN
= Name
.getAsDependentTemplateName())
2515 MarkUsedTemplateParameters(SemaRef
, DTN
->getQualifier(), OnlyDeduced
,
2519 /// \brief Mark the template parameters that are used by the given
2522 MarkUsedTemplateParameters(Sema
&SemaRef
, QualType T
,
2525 llvm::SmallVectorImpl
<bool> &Used
) {
2529 // Non-dependent types have nothing deducible
2530 if (!T
->isDependentType())
2533 T
= SemaRef
.Context
.getCanonicalType(T
);
2534 switch (T
->getTypeClass()) {
2536 MarkUsedTemplateParameters(SemaRef
,
2537 cast
<PointerType
>(T
)->getPointeeType(),
2543 case Type::BlockPointer
:
2544 MarkUsedTemplateParameters(SemaRef
,
2545 cast
<BlockPointerType
>(T
)->getPointeeType(),
2551 case Type::LValueReference
:
2552 case Type::RValueReference
:
2553 MarkUsedTemplateParameters(SemaRef
,
2554 cast
<ReferenceType
>(T
)->getPointeeType(),
2560 case Type::MemberPointer
: {
2561 const MemberPointerType
*MemPtr
= cast
<MemberPointerType
>(T
.getTypePtr());
2562 MarkUsedTemplateParameters(SemaRef
, MemPtr
->getPointeeType(), OnlyDeduced
,
2564 MarkUsedTemplateParameters(SemaRef
, QualType(MemPtr
->getClass(), 0),
2565 OnlyDeduced
, Depth
, Used
);
2569 case Type::DependentSizedArray
:
2570 MarkUsedTemplateParameters(SemaRef
,
2571 cast
<DependentSizedArrayType
>(T
)->getSizeExpr(),
2572 OnlyDeduced
, Depth
, Used
);
2573 // Fall through to check the element type
2575 case Type::ConstantArray
:
2576 case Type::IncompleteArray
:
2577 MarkUsedTemplateParameters(SemaRef
,
2578 cast
<ArrayType
>(T
)->getElementType(),
2579 OnlyDeduced
, Depth
, Used
);
2583 case Type::ExtVector
:
2584 MarkUsedTemplateParameters(SemaRef
,
2585 cast
<VectorType
>(T
)->getElementType(),
2586 OnlyDeduced
, Depth
, Used
);
2589 case Type::DependentSizedExtVector
: {
2590 const DependentSizedExtVectorType
*VecType
2591 = cast
<DependentSizedExtVectorType
>(T
);
2592 MarkUsedTemplateParameters(SemaRef
, VecType
->getElementType(), OnlyDeduced
,
2594 MarkUsedTemplateParameters(SemaRef
, VecType
->getSizeExpr(), OnlyDeduced
,
2599 case Type::FunctionProto
: {
2600 const FunctionProtoType
*Proto
= cast
<FunctionProtoType
>(T
);
2601 MarkUsedTemplateParameters(SemaRef
, Proto
->getResultType(), OnlyDeduced
,
2603 for (unsigned I
= 0, N
= Proto
->getNumArgs(); I
!= N
; ++I
)
2604 MarkUsedTemplateParameters(SemaRef
, Proto
->getArgType(I
), OnlyDeduced
,
2609 case Type::TemplateTypeParm
: {
2610 const TemplateTypeParmType
*TTP
= cast
<TemplateTypeParmType
>(T
);
2611 if (TTP
->getDepth() == Depth
)
2612 Used
[TTP
->getIndex()] = true;
2616 case Type::InjectedClassName
:
2617 T
= cast
<InjectedClassNameType
>(T
)->getInjectedSpecializationType();
2620 case Type::TemplateSpecialization
: {
2621 const TemplateSpecializationType
*Spec
2622 = cast
<TemplateSpecializationType
>(T
);
2623 MarkUsedTemplateParameters(SemaRef
, Spec
->getTemplateName(), OnlyDeduced
,
2625 for (unsigned I
= 0, N
= Spec
->getNumArgs(); I
!= N
; ++I
)
2626 MarkUsedTemplateParameters(SemaRef
, Spec
->getArg(I
), OnlyDeduced
, Depth
,
2633 MarkUsedTemplateParameters(SemaRef
,
2634 cast
<ComplexType
>(T
)->getElementType(),
2635 OnlyDeduced
, Depth
, Used
);
2638 case Type::DependentName
:
2640 MarkUsedTemplateParameters(SemaRef
,
2641 cast
<DependentNameType
>(T
)->getQualifier(),
2642 OnlyDeduced
, Depth
, Used
);
2645 case Type::DependentTemplateSpecialization
: {
2646 const DependentTemplateSpecializationType
*Spec
2647 = cast
<DependentTemplateSpecializationType
>(T
);
2649 MarkUsedTemplateParameters(SemaRef
, Spec
->getQualifier(),
2650 OnlyDeduced
, Depth
, Used
);
2651 for (unsigned I
= 0, N
= Spec
->getNumArgs(); I
!= N
; ++I
)
2652 MarkUsedTemplateParameters(SemaRef
, Spec
->getArg(I
), OnlyDeduced
, Depth
,
2659 MarkUsedTemplateParameters(SemaRef
,
2660 cast
<TypeOfType
>(T
)->getUnderlyingType(),
2661 OnlyDeduced
, Depth
, Used
);
2664 case Type::TypeOfExpr
:
2666 MarkUsedTemplateParameters(SemaRef
,
2667 cast
<TypeOfExprType
>(T
)->getUnderlyingExpr(),
2668 OnlyDeduced
, Depth
, Used
);
2671 case Type::Decltype
:
2673 MarkUsedTemplateParameters(SemaRef
,
2674 cast
<DecltypeType
>(T
)->getUnderlyingExpr(),
2675 OnlyDeduced
, Depth
, Used
);
2678 // None of these types have any template parameters in them.
2680 case Type::VariableArray
:
2681 case Type::FunctionNoProto
:
2684 case Type::ObjCInterface
:
2685 case Type::ObjCObject
:
2686 case Type::ObjCObjectPointer
:
2687 case Type::UnresolvedUsing
:
2688 #define TYPE(Class, Base)
2689 #define ABSTRACT_TYPE(Class, Base)
2690 #define DEPENDENT_TYPE(Class, Base)
2691 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2692 #include "clang/AST/TypeNodes.def"
2697 /// \brief Mark the template parameters that are used by this
2698 /// template argument.
2700 MarkUsedTemplateParameters(Sema
&SemaRef
,
2701 const TemplateArgument
&TemplateArg
,
2704 llvm::SmallVectorImpl
<bool> &Used
) {
2705 switch (TemplateArg
.getKind()) {
2706 case TemplateArgument::Null
:
2707 case TemplateArgument::Integral
:
2708 case TemplateArgument::Declaration
:
2711 case TemplateArgument::Type
:
2712 MarkUsedTemplateParameters(SemaRef
, TemplateArg
.getAsType(), OnlyDeduced
,
2716 case TemplateArgument::Template
:
2717 MarkUsedTemplateParameters(SemaRef
, TemplateArg
.getAsTemplate(),
2718 OnlyDeduced
, Depth
, Used
);
2721 case TemplateArgument::Expression
:
2722 MarkUsedTemplateParameters(SemaRef
, TemplateArg
.getAsExpr(), OnlyDeduced
,
2726 case TemplateArgument::Pack
:
2727 for (TemplateArgument::pack_iterator P
= TemplateArg
.pack_begin(),
2728 PEnd
= TemplateArg
.pack_end();
2730 MarkUsedTemplateParameters(SemaRef
, *P
, OnlyDeduced
, Depth
, Used
);
2735 /// \brief Mark the template parameters can be deduced by the given
2736 /// template argument list.
2738 /// \param TemplateArgs the template argument list from which template
2739 /// parameters will be deduced.
2741 /// \param Deduced a bit vector whose elements will be set to \c true
2742 /// to indicate when the corresponding template parameter will be
2745 Sema::MarkUsedTemplateParameters(const TemplateArgumentList
&TemplateArgs
,
2746 bool OnlyDeduced
, unsigned Depth
,
2747 llvm::SmallVectorImpl
<bool> &Used
) {
2748 for (unsigned I
= 0, N
= TemplateArgs
.size(); I
!= N
; ++I
)
2749 ::MarkUsedTemplateParameters(*this, TemplateArgs
[I
], OnlyDeduced
,
2753 /// \brief Marks all of the template parameters that will be deduced by a
2754 /// call to the given function template.
2756 Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl
*FunctionTemplate
,
2757 llvm::SmallVectorImpl
<bool> &Deduced
) {
2758 TemplateParameterList
*TemplateParams
2759 = FunctionTemplate
->getTemplateParameters();
2761 Deduced
.resize(TemplateParams
->size());
2763 FunctionDecl
*Function
= FunctionTemplate
->getTemplatedDecl();
2764 for (unsigned I
= 0, N
= Function
->getNumParams(); I
!= N
; ++I
)
2765 ::MarkUsedTemplateParameters(*this, Function
->getParamDecl(I
)->getType(),
2766 true, TemplateParams
->getDepth(), Deduced
);