blob: b3d370ab12ebb90677baba71c4a085fe4f975269 [file] [log] [blame]
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
13#include "Sema.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/StmtVisitor.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/Parse/DeclSpec.h"
20#include "llvm/Support/Compiler.h"
Douglas Gregor508f1c82009-06-26 23:10:12 +000021
22namespace clang {
23 /// \brief Various flags that control template argument deduction.
24 ///
25 /// These flags can be bitwise-OR'd together.
26 enum TemplateDeductionFlags {
27 /// \brief No template argument deduction flags, which indicates the
28 /// strictest results for template argument deduction (as used for, e.g.,
29 /// matching class template partial specializations).
30 TDF_None = 0,
31 /// \brief Within template argument deduction from a function call, we are
32 /// matching with a parameter type for which the original parameter was
33 /// a reference.
34 TDF_ParamWithReferenceType = 0x1,
35 /// \brief Within template argument deduction from a function call, we
36 /// are matching in a case where we ignore cv-qualifiers.
37 TDF_IgnoreQualifiers = 0x02,
38 /// \brief Within template argument deduction from a function call,
39 /// we are matching in a case where we can perform template argument
Douglas Gregor41128772009-06-26 23:27:24 +000040 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor508f1c82009-06-26 23:10:12 +000041 TDF_DerivedClass = 0x04
42 };
43}
44
Douglas Gregor0b9247f2009-06-04 00:03:07 +000045using namespace clang;
46
Douglas Gregorf67875d2009-06-12 18:26:56 +000047static Sema::TemplateDeductionResult
48DeduceTemplateArguments(ASTContext &Context,
49 TemplateParameterList *TemplateParams,
50 const TemplateArgument &Param,
Douglas Gregord708c722009-06-09 16:35:58 +000051 const TemplateArgument &Arg,
Douglas Gregorf67875d2009-06-12 18:26:56 +000052 Sema::TemplateDeductionInfo &Info,
Douglas Gregord708c722009-06-09 16:35:58 +000053 llvm::SmallVectorImpl<TemplateArgument> &Deduced);
54
Douglas Gregor199d9912009-06-05 00:53:49 +000055/// \brief If the given expression is of a form that permits the deduction
56/// of a non-type template parameter, return the declaration of that
57/// non-type template parameter.
58static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
59 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
60 E = IC->getSubExpr();
61
62 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
63 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
64
65 return 0;
66}
67
68/// \brief Deduce the value of the given non-type template parameter
69/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +000070static Sema::TemplateDeductionResult
71DeduceNonTypeTemplateArgument(ASTContext &Context,
72 NonTypeTemplateParmDecl *NTTP,
Anders Carlsson335e24a2009-06-16 22:44:31 +000073 llvm::APSInt Value,
Douglas Gregorf67875d2009-06-12 18:26:56 +000074 Sema::TemplateDeductionInfo &Info,
75 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
Douglas Gregor199d9912009-06-05 00:53:49 +000076 assert(NTTP->getDepth() == 0 &&
77 "Cannot deduce non-type template argument with depth > 0");
78
79 if (Deduced[NTTP->getIndex()].isNull()) {
Anders Carlsson25af1ed2009-06-16 23:08:29 +000080 QualType T = NTTP->getType();
81
82 // FIXME: Make sure we didn't overflow our data type!
83 unsigned AllowedBits = Context.getTypeSize(T);
84 if (Value.getBitWidth() != AllowedBits)
85 Value.extOrTrunc(AllowedBits);
86 Value.setIsSigned(T->isSignedIntegerType());
87
88 Deduced[NTTP->getIndex()] = TemplateArgument(SourceLocation(), Value, T);
Douglas Gregorf67875d2009-06-12 18:26:56 +000089 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +000090 }
91
Douglas Gregorf67875d2009-06-12 18:26:56 +000092 assert(Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Integral);
Douglas Gregor199d9912009-06-05 00:53:49 +000093
94 // If the template argument was previously deduced to a negative value,
95 // then our deduction fails.
96 const llvm::APSInt *PrevValuePtr = Deduced[NTTP->getIndex()].getAsIntegral();
Anders Carlsson335e24a2009-06-16 22:44:31 +000097 if (PrevValuePtr->isNegative()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +000098 Info.Param = NTTP;
99 Info.FirstArg = Deduced[NTTP->getIndex()];
Anders Carlsson335e24a2009-06-16 22:44:31 +0000100 Info.SecondArg = TemplateArgument(SourceLocation(), Value, NTTP->getType());
Douglas Gregorf67875d2009-06-12 18:26:56 +0000101 return Sema::TDK_Inconsistent;
102 }
103
Anders Carlsson335e24a2009-06-16 22:44:31 +0000104 llvm::APSInt PrevValue = *PrevValuePtr;
Douglas Gregor199d9912009-06-05 00:53:49 +0000105 if (Value.getBitWidth() > PrevValue.getBitWidth())
106 PrevValue.zext(Value.getBitWidth());
107 else if (Value.getBitWidth() < PrevValue.getBitWidth())
108 Value.zext(PrevValue.getBitWidth());
Douglas Gregorf67875d2009-06-12 18:26:56 +0000109
110 if (Value != PrevValue) {
111 Info.Param = NTTP;
112 Info.FirstArg = Deduced[NTTP->getIndex()];
Anders Carlsson335e24a2009-06-16 22:44:31 +0000113 Info.SecondArg = TemplateArgument(SourceLocation(), Value, NTTP->getType());
Douglas Gregorf67875d2009-06-12 18:26:56 +0000114 return Sema::TDK_Inconsistent;
115 }
116
117 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000118}
119
120/// \brief Deduce the value of the given non-type template parameter
121/// from the given type- or value-dependent expression.
122///
123/// \returns true if deduction succeeded, false otherwise.
124
Douglas Gregorf67875d2009-06-12 18:26:56 +0000125static Sema::TemplateDeductionResult
126DeduceNonTypeTemplateArgument(ASTContext &Context,
127 NonTypeTemplateParmDecl *NTTP,
128 Expr *Value,
129 Sema::TemplateDeductionInfo &Info,
130 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000131 assert(NTTP->getDepth() == 0 &&
132 "Cannot deduce non-type template argument with depth > 0");
133 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
134 "Expression template argument must be type- or value-dependent.");
135
136 if (Deduced[NTTP->getIndex()].isNull()) {
137 // FIXME: Clone the Value?
138 Deduced[NTTP->getIndex()] = TemplateArgument(Value);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000139 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000140 }
141
142 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Integral) {
143 // Okay, we deduced a constant in one case and a dependent expression
144 // in another case. FIXME: Later, we will check that instantiating the
145 // dependent expression gives us the constant value.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000146 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000147 }
148
149 // FIXME: Compare the expressions for equality!
Douglas Gregorf67875d2009-06-12 18:26:56 +0000150 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000151}
152
Douglas Gregorf67875d2009-06-12 18:26:56 +0000153static Sema::TemplateDeductionResult
154DeduceTemplateArguments(ASTContext &Context,
155 TemplateName Param,
156 TemplateName Arg,
157 Sema::TemplateDeductionInfo &Info,
158 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000159 // FIXME: Implement template argument deduction for template
160 // template parameters.
161
Douglas Gregorf67875d2009-06-12 18:26:56 +0000162 // FIXME: this routine does not have enough information to produce
163 // good diagnostics.
164
Douglas Gregord708c722009-06-09 16:35:58 +0000165 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
166 TemplateDecl *ArgDecl = Arg.getAsTemplateDecl();
167
Douglas Gregorf67875d2009-06-12 18:26:56 +0000168 if (!ParamDecl || !ArgDecl) {
169 // FIXME: fill in Info.Param/Info.FirstArg
170 return Sema::TDK_Inconsistent;
171 }
Douglas Gregord708c722009-06-09 16:35:58 +0000172
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000173 ParamDecl = cast<TemplateDecl>(ParamDecl->getCanonicalDecl());
174 ArgDecl = cast<TemplateDecl>(ArgDecl->getCanonicalDecl());
Douglas Gregorf67875d2009-06-12 18:26:56 +0000175 if (ParamDecl != ArgDecl) {
176 // FIXME: fill in Info.Param/Info.FirstArg
177 return Sema::TDK_Inconsistent;
178 }
179
180 return Sema::TDK_Success;
Douglas Gregord708c722009-06-09 16:35:58 +0000181}
182
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000183/// \brief Deduce the template arguments by comparing the template parameter
184/// type (which is a template-id) with the template argument type.
185///
186/// \param Context the AST context in which this deduction occurs.
187///
188/// \param TemplateParams the template parameters that we are deducing
189///
190/// \param Param the parameter type
191///
192/// \param Arg the argument type
193///
194/// \param Info information about the template argument deduction itself
195///
196/// \param Deduced the deduced template arguments
197///
198/// \returns the result of template argument deduction so far. Note that a
199/// "success" result means that template argument deduction has not yet failed,
200/// but it may still fail, later, for other reasons.
201static Sema::TemplateDeductionResult
202DeduceTemplateArguments(ASTContext &Context,
203 TemplateParameterList *TemplateParams,
204 const TemplateSpecializationType *Param,
205 QualType Arg,
206 Sema::TemplateDeductionInfo &Info,
207 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
208 assert(Arg->isCanonical() && "Argument type must be canonical");
209
210 // Check whether the template argument is a dependent template-id.
211 // FIXME: This is untested code; it can be tested when we implement
212 // partial ordering of class template partial specializations.
213 if (const TemplateSpecializationType *SpecArg
214 = dyn_cast<TemplateSpecializationType>(Arg)) {
215 // Perform template argument deduction for the template name.
216 if (Sema::TemplateDeductionResult Result
217 = DeduceTemplateArguments(Context,
218 Param->getTemplateName(),
219 SpecArg->getTemplateName(),
220 Info, Deduced))
221 return Result;
222
223 unsigned NumArgs = Param->getNumArgs();
224
225 // FIXME: When one of the template-names refers to a
226 // declaration with default template arguments, do we need to
227 // fill in those default template arguments here? Most likely,
228 // the answer is "yes", but I don't see any references. This
229 // issue may be resolved elsewhere, because we may want to
230 // instantiate default template arguments when we actually write
231 // the template-id.
232 if (SpecArg->getNumArgs() != NumArgs)
233 return Sema::TDK_NonDeducedMismatch;
234
235 // Perform template argument deduction on each template
236 // argument.
237 for (unsigned I = 0; I != NumArgs; ++I)
238 if (Sema::TemplateDeductionResult Result
239 = DeduceTemplateArguments(Context, TemplateParams,
240 Param->getArg(I),
241 SpecArg->getArg(I),
242 Info, Deduced))
243 return Result;
244
245 return Sema::TDK_Success;
246 }
247
248 // If the argument type is a class template specialization, we
249 // perform template argument deduction using its template
250 // arguments.
251 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
252 if (!RecordArg)
253 return Sema::TDK_NonDeducedMismatch;
254
255 ClassTemplateSpecializationDecl *SpecArg
256 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
257 if (!SpecArg)
258 return Sema::TDK_NonDeducedMismatch;
259
260 // Perform template argument deduction for the template name.
261 if (Sema::TemplateDeductionResult Result
262 = DeduceTemplateArguments(Context,
263 Param->getTemplateName(),
264 TemplateName(SpecArg->getSpecializedTemplate()),
265 Info, Deduced))
266 return Result;
267
268 // FIXME: Can the # of arguments in the parameter and the argument
269 // differ due to default arguments?
270 unsigned NumArgs = Param->getNumArgs();
271 const TemplateArgumentList &ArgArgs = SpecArg->getTemplateArgs();
272 if (NumArgs != ArgArgs.size())
273 return Sema::TDK_NonDeducedMismatch;
274
275 for (unsigned I = 0; I != NumArgs; ++I)
276 if (Sema::TemplateDeductionResult Result
277 = DeduceTemplateArguments(Context, TemplateParams,
278 Param->getArg(I),
279 ArgArgs.get(I),
280 Info, Deduced))
281 return Result;
282
283 return Sema::TDK_Success;
284}
285
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000286/// \brief Returns a completely-unqualified array type, capturing the
287/// qualifiers in CVRQuals.
288///
289/// \param Context the AST context in which the array type was built.
290///
291/// \param T a canonical type that may be an array type.
292///
293/// \param CVRQuals will receive the set of const/volatile/restrict qualifiers
294/// that were applied to the element type of the array.
295///
296/// \returns if \p T is an array type, the completely unqualified array type
297/// that corresponds to T. Otherwise, returns T.
298static QualType getUnqualifiedArrayType(ASTContext &Context, QualType T,
299 unsigned &CVRQuals) {
300 assert(T->isCanonical() && "Only operates on canonical types");
301 if (!isa<ArrayType>(T)) {
302 CVRQuals = T.getCVRQualifiers();
303 return T.getUnqualifiedType();
304 }
305
306 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
307 QualType Elt = getUnqualifiedArrayType(Context, CAT->getElementType(),
308 CVRQuals);
309 if (Elt == CAT->getElementType())
310 return T;
311
312 return Context.getConstantArrayType(Elt, CAT->getSize(),
313 CAT->getSizeModifier(), 0);
314 }
315
316 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
317 QualType Elt = getUnqualifiedArrayType(Context, IAT->getElementType(),
318 CVRQuals);
319 if (Elt == IAT->getElementType())
320 return T;
321
322 return Context.getIncompleteArrayType(Elt, IAT->getSizeModifier(), 0);
323 }
324
325 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
326 QualType Elt = getUnqualifiedArrayType(Context, DSAT->getElementType(),
327 CVRQuals);
328 if (Elt == DSAT->getElementType())
329 return T;
330
Anders Carlssond4972062009-08-08 02:50:17 +0000331 return Context.getDependentSizedArrayType(Elt, DSAT->getSizeExpr()->Retain(),
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000332 DSAT->getSizeModifier(), 0,
333 SourceRange());
334}
335
Douglas Gregor500d3312009-06-26 18:27:22 +0000336/// \brief Deduce the template arguments by comparing the parameter type and
337/// the argument type (C++ [temp.deduct.type]).
338///
339/// \param Context the AST context in which this deduction occurs.
340///
341/// \param TemplateParams the template parameters that we are deducing
342///
343/// \param ParamIn the parameter type
344///
345/// \param ArgIn the argument type
346///
347/// \param Info information about the template argument deduction itself
348///
349/// \param Deduced the deduced template arguments
350///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000351/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
352/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000353///
354/// \returns the result of template argument deduction so far. Note that a
355/// "success" result means that template argument deduction has not yet failed,
356/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000357static Sema::TemplateDeductionResult
358DeduceTemplateArguments(ASTContext &Context,
359 TemplateParameterList *TemplateParams,
360 QualType ParamIn, QualType ArgIn,
361 Sema::TemplateDeductionInfo &Info,
Douglas Gregor500d3312009-06-26 18:27:22 +0000362 llvm::SmallVectorImpl<TemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000363 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000364 // We only want to look at the canonical types, since typedefs and
365 // sugar are not part of template argument deduction.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000366 QualType Param = Context.getCanonicalType(ParamIn);
367 QualType Arg = Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000368
Douglas Gregor500d3312009-06-26 18:27:22 +0000369 // C++0x [temp.deduct.call]p4 bullet 1:
370 // - If the original P is a reference type, the deduced A (i.e., the type
371 // referred to by the reference) can be more cv-qualified than the
372 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000373 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor500d3312009-06-26 18:27:22 +0000374 unsigned ExtraQualsOnParam
375 = Param.getCVRQualifiers() & ~Arg.getCVRQualifiers();
376 Param.setCVRQualifiers(Param.getCVRQualifiers() & ~ExtraQualsOnParam);
377 }
378
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000379 // If the parameter type is not dependent, there is nothing to deduce.
380 if (!Param->isDependentType())
381 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000382
Douglas Gregor199d9912009-06-05 00:53:49 +0000383 // C++ [temp.deduct.type]p9:
Douglas Gregor199d9912009-06-05 00:53:49 +0000384 // A template type argument T, a template template argument TT or a
385 // template non-type argument i can be deduced if P and A have one of
386 // the following forms:
387 //
388 // T
389 // cv-list T
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000390 if (const TemplateTypeParmType *TemplateTypeParm
391 = Param->getAsTemplateTypeParmType()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000392 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000393 bool RecanonicalizeArg = false;
394
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000395 // If the argument type is an array type, move the qualifiers up to the
396 // top level, so they can be matched with the qualifiers on the parameter.
397 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000398 if (isa<ArrayType>(Arg)) {
399 unsigned CVRQuals = 0;
400 Arg = getUnqualifiedArrayType(Context, Arg, CVRQuals);
401 if (CVRQuals) {
402 Arg = Arg.getWithAdditionalQualifiers(CVRQuals);
403 RecanonicalizeArg = true;
404 }
405 }
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000406
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000407 // The argument type can not be less qualified than the parameter
408 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000409 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000410 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
411 Info.FirstArg = Deduced[Index];
412 Info.SecondArg = TemplateArgument(SourceLocation(), Arg);
413 return Sema::TDK_InconsistentQuals;
414 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000415
416 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
417
418 unsigned Quals = Arg.getCVRQualifiers() & ~Param.getCVRQualifiers();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000419 QualType DeducedType = Arg.getQualifiedType(Quals);
420 if (RecanonicalizeArg)
421 DeducedType = Context.getCanonicalType(DeducedType);
422
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000423 if (Deduced[Index].isNull())
424 Deduced[Index] = TemplateArgument(SourceLocation(), DeducedType);
425 else {
426 // C++ [temp.deduct.type]p2:
427 // [...] If type deduction cannot be done for any P/A pair, or if for
428 // any pair the deduction leads to more than one possible set of
429 // deduced values, or if different pairs yield different deduced
430 // values, or if any template argument remains neither deduced nor
431 // explicitly specified, template argument deduction fails.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000432 if (Deduced[Index].getAsType() != DeducedType) {
433 Info.Param
434 = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
435 Info.FirstArg = Deduced[Index];
436 Info.SecondArg = TemplateArgument(SourceLocation(), Arg);
437 return Sema::TDK_Inconsistent;
438 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000439 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000440 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000441 }
442
Douglas Gregorf67875d2009-06-12 18:26:56 +0000443 // Set up the template argument deduction information for a failure.
444 Info.FirstArg = TemplateArgument(SourceLocation(), ParamIn);
445 Info.SecondArg = TemplateArgument(SourceLocation(), ArgIn);
446
Douglas Gregor508f1c82009-06-26 23:10:12 +0000447 // Check the cv-qualifiers on the parameter and argument types.
448 if (!(TDF & TDF_IgnoreQualifiers)) {
449 if (TDF & TDF_ParamWithReferenceType) {
450 if (Param.isMoreQualifiedThan(Arg))
451 return Sema::TDK_NonDeducedMismatch;
452 } else {
453 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
454 return Sema::TDK_NonDeducedMismatch;
455 }
456 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000457
Douglas Gregord560d502009-06-04 00:21:18 +0000458 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000459 // No deduction possible for these types
460 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000461 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000462
463 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000464 case Type::Pointer: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000465 const PointerType *PointerArg = Arg->getAs<PointerType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000466 if (!PointerArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000467 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord560d502009-06-04 00:21:18 +0000468
Douglas Gregor41128772009-06-26 23:27:24 +0000469 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000470 return DeduceTemplateArguments(Context, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000471 cast<PointerType>(Param)->getPointeeType(),
472 PointerArg->getPointeeType(),
Douglas Gregor41128772009-06-26 23:27:24 +0000473 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000474 }
475
Douglas Gregor199d9912009-06-05 00:53:49 +0000476 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000477 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000478 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000479 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000480 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord560d502009-06-04 00:21:18 +0000481
Douglas Gregorf67875d2009-06-12 18:26:56 +0000482 return DeduceTemplateArguments(Context, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000483 cast<LValueReferenceType>(Param)->getPointeeType(),
484 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000485 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000486 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000487
Douglas Gregor199d9912009-06-05 00:53:49 +0000488 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000489 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000490 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000491 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000492 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord560d502009-06-04 00:21:18 +0000493
Douglas Gregorf67875d2009-06-12 18:26:56 +0000494 return DeduceTemplateArguments(Context, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000495 cast<RValueReferenceType>(Param)->getPointeeType(),
496 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000497 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000498 }
499
Douglas Gregor199d9912009-06-05 00:53:49 +0000500 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000501 case Type::IncompleteArray: {
502 const IncompleteArrayType *IncompleteArrayArg =
503 Context.getAsIncompleteArrayType(Arg);
504 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000505 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000506
Douglas Gregorf67875d2009-06-12 18:26:56 +0000507 return DeduceTemplateArguments(Context, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000508 Context.getAsIncompleteArrayType(Param)->getElementType(),
509 IncompleteArrayArg->getElementType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000510 Info, Deduced, 0);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000511 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000512
513 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000514 case Type::ConstantArray: {
515 const ConstantArrayType *ConstantArrayArg =
516 Context.getAsConstantArrayType(Arg);
517 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000518 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000519
520 const ConstantArrayType *ConstantArrayParm =
521 Context.getAsConstantArrayType(Param);
522 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000523 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000524
Douglas Gregorf67875d2009-06-12 18:26:56 +0000525 return DeduceTemplateArguments(Context, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000526 ConstantArrayParm->getElementType(),
527 ConstantArrayArg->getElementType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000528 Info, Deduced, 0);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000529 }
530
Douglas Gregor199d9912009-06-05 00:53:49 +0000531 // type [i]
532 case Type::DependentSizedArray: {
533 const ArrayType *ArrayArg = dyn_cast<ArrayType>(Arg);
534 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000535 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000536
537 // Check the element type of the arrays
538 const DependentSizedArrayType *DependentArrayParm
539 = cast<DependentSizedArrayType>(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000540 if (Sema::TemplateDeductionResult Result
541 = DeduceTemplateArguments(Context, TemplateParams,
542 DependentArrayParm->getElementType(),
543 ArrayArg->getElementType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000544 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000545 return Result;
Douglas Gregor199d9912009-06-05 00:53:49 +0000546
547 // Determine the array bound is something we can deduce.
548 NonTypeTemplateParmDecl *NTTP
549 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
550 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000551 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000552
553 // We can perform template argument deduction for the given non-type
554 // template parameter.
555 assert(NTTP->getDepth() == 0 &&
556 "Cannot deduce non-type template argument at depth > 0");
557 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000558 = dyn_cast<ConstantArrayType>(ArrayArg)) {
559 llvm::APSInt Size(ConstantArrayArg->getSize());
560 return DeduceNonTypeTemplateArgument(Context, NTTP, Size,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000561 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000562 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000563 if (const DependentSizedArrayType *DependentArrayArg
564 = dyn_cast<DependentSizedArrayType>(ArrayArg))
565 return DeduceNonTypeTemplateArgument(Context, NTTP,
566 DependentArrayArg->getSizeExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000567 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000568
569 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000570 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000571 }
572
Douglas Gregor0fce0ae2009-06-08 15:59:14 +0000573 // type(*)(T)
574 // T(*)()
575 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000576 case Type::FunctionProto: {
577 const FunctionProtoType *FunctionProtoArg =
578 dyn_cast<FunctionProtoType>(Arg);
579 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000580 return Sema::TDK_NonDeducedMismatch;
Anders Carlssona27fad52009-06-08 15:19:08 +0000581
582 const FunctionProtoType *FunctionProtoParam =
583 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000584
585 if (FunctionProtoParam->getTypeQuals() !=
586 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000587 return Sema::TDK_NonDeducedMismatch;
Anders Carlssona27fad52009-06-08 15:19:08 +0000588
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000589 if (FunctionProtoParam->getNumArgs() != FunctionProtoArg->getNumArgs())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000590 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000591
592 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000593 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000594
Anders Carlssona27fad52009-06-08 15:19:08 +0000595 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000596 if (Sema::TemplateDeductionResult Result
597 = DeduceTemplateArguments(Context, TemplateParams,
598 FunctionProtoParam->getResultType(),
599 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000600 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000601 return Result;
Anders Carlssona27fad52009-06-08 15:19:08 +0000602
Anders Carlssona27fad52009-06-08 15:19:08 +0000603 for (unsigned I = 0, N = FunctionProtoParam->getNumArgs(); I != N; ++I) {
604 // Check argument types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000605 if (Sema::TemplateDeductionResult Result
606 = DeduceTemplateArguments(Context, TemplateParams,
607 FunctionProtoParam->getArgType(I),
608 FunctionProtoArg->getArgType(I),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000609 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000610 return Result;
Anders Carlssona27fad52009-06-08 15:19:08 +0000611 }
612
Douglas Gregorf67875d2009-06-12 18:26:56 +0000613 return Sema::TDK_Success;
Anders Carlssona27fad52009-06-08 15:19:08 +0000614 }
Douglas Gregord708c722009-06-09 16:35:58 +0000615
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000616 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000617 // template-name<i>
618 // TT<T> (TODO)
619 // TT<i> (TODO)
620 // TT<> (TODO)
621 case Type::TemplateSpecialization: {
622 const TemplateSpecializationType *SpecParam
623 = cast<TemplateSpecializationType>(Param);
Anders Carlssona27fad52009-06-08 15:19:08 +0000624
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000625 // Try to deduce template arguments from the template-id.
626 Sema::TemplateDeductionResult Result
627 = DeduceTemplateArguments(Context, TemplateParams, SpecParam, Arg,
628 Info, Deduced);
629
630 if (Result && (TDF & TDF_DerivedClass) &&
631 Result != Sema::TDK_Inconsistent) {
632 // C++ [temp.deduct.call]p3b3:
633 // If P is a class, and P has the form template-id, then A can be a
634 // derived class of the deduced A. Likewise, if P is a pointer to a
635 // class of the form template-id, A can be a pointer to a derived
636 // class pointed to by the deduced A.
637 //
638 // More importantly:
639 // These alternatives are considered only if type deduction would
640 // otherwise fail.
641 if (const RecordType *RecordT = dyn_cast<RecordType>(Arg)) {
642 // Use data recursion to crawl through the list of base classes.
643 // Visited contains the set of nodes we have already visited, while
644 // ToVisit is our stack of records that we still need to visit.
645 llvm::SmallPtrSet<const RecordType *, 8> Visited;
646 llvm::SmallVector<const RecordType *, 8> ToVisit;
647 ToVisit.push_back(RecordT);
648 bool Successful = false;
649 while (!ToVisit.empty()) {
650 // Retrieve the next class in the inheritance hierarchy.
651 const RecordType *NextT = ToVisit.back();
652 ToVisit.pop_back();
653
654 // If we have already seen this type, skip it.
655 if (!Visited.insert(NextT))
656 continue;
657
658 // If this is a base class, try to perform template argument
659 // deduction from it.
660 if (NextT != RecordT) {
661 Sema::TemplateDeductionResult BaseResult
662 = DeduceTemplateArguments(Context, TemplateParams, SpecParam,
663 QualType(NextT, 0), Info, Deduced);
664
665 // If template argument deduction for this base was successful,
666 // note that we had some success.
667 if (BaseResult == Sema::TDK_Success)
668 Successful = true;
669 // If deduction against this base resulted in an inconsistent
670 // set of deduced template arguments, template argument
671 // deduction fails.
672 else if (BaseResult == Sema::TDK_Inconsistent)
673 return BaseResult;
674 }
675
676 // Visit base classes
677 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
678 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
679 BaseEnd = Next->bases_end();
680 Base != BaseEnd; ++Base) {
681 assert(Base->getType()->isRecordType() &&
682 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +0000683 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000684 }
685 }
686
687 if (Successful)
688 return Sema::TDK_Success;
689 }
690
691 }
692
693 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +0000694 }
695
Douglas Gregor637a4092009-06-10 23:47:09 +0000696 // T type::*
697 // T T::*
698 // T (type::*)()
699 // type (T::*)()
700 // type (type::*)(T)
701 // type (T::*)(T)
702 // T (type::*)(T)
703 // T (T::*)()
704 // T (T::*)(T)
705 case Type::MemberPointer: {
706 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
707 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
708 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000709 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +0000710
Douglas Gregorf67875d2009-06-12 18:26:56 +0000711 if (Sema::TemplateDeductionResult Result
712 = DeduceTemplateArguments(Context, TemplateParams,
713 MemPtrParam->getPointeeType(),
714 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000715 Info, Deduced,
716 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000717 return Result;
718
719 return DeduceTemplateArguments(Context, TemplateParams,
720 QualType(MemPtrParam->getClass(), 0),
721 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000722 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +0000723 }
724
Anders Carlsson9a917e42009-06-12 22:56:54 +0000725 // (clang extension)
726 //
Anders Carlsson859ba502009-06-12 16:23:10 +0000727 // type(^)(T)
728 // T(^)()
729 // T(^)(T)
730 case Type::BlockPointer: {
731 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
732 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
733
734 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000735 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson859ba502009-06-12 16:23:10 +0000736
Douglas Gregorf67875d2009-06-12 18:26:56 +0000737 return DeduceTemplateArguments(Context, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +0000738 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000739 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000740 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +0000741 }
742
Douglas Gregor637a4092009-06-10 23:47:09 +0000743 case Type::TypeOfExpr:
744 case Type::TypeOf:
745 case Type::Typename:
746 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +0000747 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +0000748
Douglas Gregord560d502009-06-04 00:21:18 +0000749 default:
750 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000751 }
752
753 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000754 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000755}
756
Douglas Gregorf67875d2009-06-12 18:26:56 +0000757static Sema::TemplateDeductionResult
758DeduceTemplateArguments(ASTContext &Context,
759 TemplateParameterList *TemplateParams,
760 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000761 const TemplateArgument &Arg,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000762 Sema::TemplateDeductionInfo &Info,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000763 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000764 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000765 case TemplateArgument::Null:
766 assert(false && "Null template argument in parameter list");
767 break;
768
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000769 case TemplateArgument::Type:
Douglas Gregor199d9912009-06-05 00:53:49 +0000770 assert(Arg.getKind() == TemplateArgument::Type && "Type/value mismatch");
Douglas Gregor508f1c82009-06-26 23:10:12 +0000771 return DeduceTemplateArguments(Context, TemplateParams, Param.getAsType(),
772 Arg.getAsType(), Info, Deduced, 0);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000773
Douglas Gregor199d9912009-06-05 00:53:49 +0000774 case TemplateArgument::Declaration:
775 // FIXME: Implement this check
776 assert(false && "Unimplemented template argument deduction case");
Douglas Gregorf67875d2009-06-12 18:26:56 +0000777 Info.FirstArg = Param;
778 Info.SecondArg = Arg;
779 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000780
781 case TemplateArgument::Integral:
782 if (Arg.getKind() == TemplateArgument::Integral) {
783 // FIXME: Zero extension + sign checking here?
Douglas Gregorf67875d2009-06-12 18:26:56 +0000784 if (*Param.getAsIntegral() == *Arg.getAsIntegral())
785 return Sema::TDK_Success;
786
787 Info.FirstArg = Param;
788 Info.SecondArg = Arg;
789 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000790 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000791
792 if (Arg.getKind() == TemplateArgument::Expression) {
793 Info.FirstArg = Param;
794 Info.SecondArg = Arg;
795 return Sema::TDK_NonDeducedMismatch;
796 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000797
798 assert(false && "Type/value mismatch");
Douglas Gregorf67875d2009-06-12 18:26:56 +0000799 Info.FirstArg = Param;
800 Info.SecondArg = Arg;
801 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000802
803 case TemplateArgument::Expression: {
804 if (NonTypeTemplateParmDecl *NTTP
805 = getDeducedParameterFromExpr(Param.getAsExpr())) {
806 if (Arg.getKind() == TemplateArgument::Integral)
807 // FIXME: Sign problems here
808 return DeduceNonTypeTemplateArgument(Context, NTTP,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000809 *Arg.getAsIntegral(),
810 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000811 if (Arg.getKind() == TemplateArgument::Expression)
812 return DeduceNonTypeTemplateArgument(Context, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000813 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000814
815 assert(false && "Type/value mismatch");
Douglas Gregorf67875d2009-06-12 18:26:56 +0000816 Info.FirstArg = Param;
817 Info.SecondArg = Arg;
818 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000819 }
820
821 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000822 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000823 }
Anders Carlssond01b1da2009-06-15 17:04:53 +0000824 case TemplateArgument::Pack:
825 assert(0 && "FIXME: Implement!");
826 break;
Douglas Gregor199d9912009-06-05 00:53:49 +0000827 }
828
Douglas Gregorf67875d2009-06-12 18:26:56 +0000829 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000830}
831
Douglas Gregorf67875d2009-06-12 18:26:56 +0000832static Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000833DeduceTemplateArguments(ASTContext &Context,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000834 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000835 const TemplateArgumentList &ParamList,
836 const TemplateArgumentList &ArgList,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000837 Sema::TemplateDeductionInfo &Info,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000838 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
839 assert(ParamList.size() == ArgList.size());
840 for (unsigned I = 0, N = ParamList.size(); I != N; ++I) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000841 if (Sema::TemplateDeductionResult Result
842 = DeduceTemplateArguments(Context, TemplateParams,
843 ParamList[I], ArgList[I],
844 Info, Deduced))
845 return Result;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000846 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000847 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000848}
849
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000850/// \brief Determine whether two template arguments are the same.
851static bool isSameTemplateArg(ASTContext &Context,
852 const TemplateArgument &X,
853 const TemplateArgument &Y) {
854 if (X.getKind() != Y.getKind())
855 return false;
856
857 switch (X.getKind()) {
858 case TemplateArgument::Null:
859 assert(false && "Comparing NULL template argument");
860 break;
861
862 case TemplateArgument::Type:
863 return Context.getCanonicalType(X.getAsType()) ==
864 Context.getCanonicalType(Y.getAsType());
865
866 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000867 return X.getAsDecl()->getCanonicalDecl() ==
868 Y.getAsDecl()->getCanonicalDecl();
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000869
870 case TemplateArgument::Integral:
871 return *X.getAsIntegral() == *Y.getAsIntegral();
872
873 case TemplateArgument::Expression:
874 // FIXME: We assume that all expressions are distinct, but we should
875 // really check their canonical forms.
876 return false;
877
878 case TemplateArgument::Pack:
879 if (X.pack_size() != Y.pack_size())
880 return false;
881
882 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
883 XPEnd = X.pack_end(),
884 YP = Y.pack_begin();
885 XP != XPEnd; ++XP, ++YP)
886 if (!isSameTemplateArg(Context, *XP, *YP))
887 return false;
888
889 return true;
890 }
891
892 return false;
893}
894
895/// \brief Helper function to build a TemplateParameter when we don't
896/// know its type statically.
897static TemplateParameter makeTemplateParameter(Decl *D) {
898 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
899 return TemplateParameter(TTP);
900 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
901 return TemplateParameter(NTTP);
902
903 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
904}
905
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000906/// \brief Perform template argument deduction to determine whether
907/// the given template arguments match the given class template
908/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +0000909Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000910Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000911 const TemplateArgumentList &TemplateArgs,
912 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000913 // C++ [temp.class.spec.match]p2:
914 // A partial specialization matches a given actual template
915 // argument list if the template arguments of the partial
916 // specialization can be deduced from the actual template argument
917 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +0000918 SFINAETrap Trap(*this);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000919 llvm::SmallVector<TemplateArgument, 4> Deduced;
920 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +0000921 if (TemplateDeductionResult Result
922 = ::DeduceTemplateArguments(Context,
923 Partial->getTemplateParameters(),
924 Partial->getTemplateArgs(),
925 TemplateArgs, Info, Deduced))
926 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +0000927
Douglas Gregor637a4092009-06-10 23:47:09 +0000928 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
929 Deduced.data(), Deduced.size());
930 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000931 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +0000932
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000933 // C++ [temp.deduct.type]p2:
934 // [...] or if any template argument remains neither deduced nor
935 // explicitly specified, template argument deduction fails.
Anders Carlssonfb250522009-06-23 01:26:57 +0000936 TemplateArgumentListBuilder Builder(Partial->getTemplateParameters(),
937 Deduced.size());
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000938 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000939 if (Deduced[I].isNull()) {
940 Decl *Param
941 = const_cast<Decl *>(Partial->getTemplateParameters()->getParam(I));
942 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
943 Info.Param = TTP;
944 else if (NonTypeTemplateParmDecl *NTTP
945 = dyn_cast<NonTypeTemplateParmDecl>(Param))
946 Info.Param = NTTP;
947 else
948 Info.Param = cast<TemplateTemplateParmDecl>(Param);
949 return TDK_Incomplete;
950 }
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000951
Anders Carlssonfb250522009-06-23 01:26:57 +0000952 Builder.Append(Deduced[I]);
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000953 }
954
955 // Form the template argument list from the deduced template arguments.
956 TemplateArgumentList *DeducedArgumentList
Anders Carlssonfb250522009-06-23 01:26:57 +0000957 = new (Context) TemplateArgumentList(Context, Builder, /*TakeArgs=*/true);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000958 Info.reset(DeducedArgumentList);
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000959
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000960 // Substitute the deduced template arguments into the template
961 // arguments of the class template partial specialization, and
962 // verify that the instantiated template arguments are both valid
963 // and are equivalent to the template arguments originally provided
Douglas Gregorc9e5d252009-06-13 00:59:32 +0000964 // to the class template.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000965 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
966 const TemplateArgumentList &PartialTemplateArgs = Partial->getTemplateArgs();
967 for (unsigned I = 0, N = PartialTemplateArgs.flat_size(); I != N; ++I) {
Douglas Gregorc9e5d252009-06-13 00:59:32 +0000968 Decl *Param = const_cast<Decl *>(
969 ClassTemplate->getTemplateParameters()->getParam(I));
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000970 TemplateArgument InstArg = Instantiate(PartialTemplateArgs[I],
971 *DeducedArgumentList);
972 if (InstArg.isNull()) {
973 Info.Param = makeTemplateParameter(Param);
974 Info.FirstArg = PartialTemplateArgs[I];
975 return TDK_SubstitutionFailure;
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000976 }
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000977
978 if (InstArg.getKind() == TemplateArgument::Expression) {
979 // When the argument is an expression, check the expression result
980 // against the actual template parameter to get down to the canonical
981 // template argument.
982 Expr *InstExpr = InstArg.getAsExpr();
983 if (NonTypeTemplateParmDecl *NTTP
984 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
985 if (CheckTemplateArgument(NTTP, NTTP->getType(), InstExpr, InstArg)) {
986 Info.Param = makeTemplateParameter(Param);
987 Info.FirstArg = PartialTemplateArgs[I];
988 return TDK_SubstitutionFailure;
989 }
990 } else if (TemplateTemplateParmDecl *TTP
991 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
992 // FIXME: template template arguments should really resolve to decls
993 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InstExpr);
994 if (!DRE || CheckTemplateArgument(TTP, DRE)) {
995 Info.Param = makeTemplateParameter(Param);
996 Info.FirstArg = PartialTemplateArgs[I];
997 return TDK_SubstitutionFailure;
998 }
999 }
1000 }
1001
1002 if (!isSameTemplateArg(Context, TemplateArgs[I], InstArg)) {
1003 Info.Param = makeTemplateParameter(Param);
1004 Info.FirstArg = TemplateArgs[I];
1005 Info.SecondArg = InstArg;
1006 return TDK_NonDeducedMismatch;
1007 }
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001008 }
1009
Douglas Gregorbb260412009-06-14 08:02:22 +00001010 if (Trap.hasErrorOccurred())
1011 return TDK_SubstitutionFailure;
1012
Douglas Gregorf67875d2009-06-12 18:26:56 +00001013 return TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001014}
Douglas Gregor031a5882009-06-13 00:26:55 +00001015
Douglas Gregor41128772009-06-26 23:27:24 +00001016/// \brief Determine whether the given type T is a simple-template-id type.
1017static bool isSimpleTemplateIdType(QualType T) {
1018 if (const TemplateSpecializationType *Spec
1019 = T->getAsTemplateSpecializationType())
1020 return Spec->getTemplateName().getAsTemplateDecl() != 0;
1021
1022 return false;
1023}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001024
1025/// \brief Substitute the explicitly-provided template arguments into the
1026/// given function template according to C++ [temp.arg.explicit].
1027///
1028/// \param FunctionTemplate the function template into which the explicit
1029/// template arguments will be substituted.
1030///
1031/// \param ExplicitTemplateArguments the explicitly-specified template
1032/// arguments.
1033///
1034/// \param NumExplicitTemplateArguments the number of explicitly-specified
1035/// template arguments in @p ExplicitTemplateArguments. This value may be zero.
1036///
1037/// \param Deduced the deduced template arguments, which will be populated
1038/// with the converted and checked explicit template arguments.
1039///
1040/// \param ParamTypes will be populated with the instantiated function
1041/// parameters.
1042///
1043/// \param FunctionType if non-NULL, the result type of the function template
1044/// will also be instantiated and the pointed-to value will be updated with
1045/// the instantiated function type.
1046///
1047/// \param Info if substitution fails for any reason, this object will be
1048/// populated with more information about the failure.
1049///
1050/// \returns TDK_Success if substitution was successful, or some failure
1051/// condition.
1052Sema::TemplateDeductionResult
1053Sema::SubstituteExplicitTemplateArguments(
1054 FunctionTemplateDecl *FunctionTemplate,
1055 const TemplateArgument *ExplicitTemplateArgs,
1056 unsigned NumExplicitTemplateArgs,
1057 llvm::SmallVectorImpl<TemplateArgument> &Deduced,
1058 llvm::SmallVectorImpl<QualType> &ParamTypes,
1059 QualType *FunctionType,
1060 TemplateDeductionInfo &Info) {
1061 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1062 TemplateParameterList *TemplateParams
1063 = FunctionTemplate->getTemplateParameters();
1064
1065 if (NumExplicitTemplateArgs == 0) {
1066 // No arguments to substitute; just copy over the parameter types and
1067 // fill in the function type.
1068 for (FunctionDecl::param_iterator P = Function->param_begin(),
1069 PEnd = Function->param_end();
1070 P != PEnd;
1071 ++P)
1072 ParamTypes.push_back((*P)->getType());
1073
1074 if (FunctionType)
1075 *FunctionType = Function->getType();
1076 return TDK_Success;
1077 }
1078
1079 // Substitution of the explicit template arguments into a function template
1080 /// is a SFINAE context. Trap any errors that might occur.
1081 SFINAETrap Trap(*this);
1082
1083 // C++ [temp.arg.explicit]p3:
1084 // Template arguments that are present shall be specified in the
1085 // declaration order of their corresponding template-parameters. The
1086 // template argument list shall not specify more template-arguments than
1087 // there are corresponding template-parameters.
1088 TemplateArgumentListBuilder Builder(TemplateParams,
1089 NumExplicitTemplateArgs);
1090
1091 // Enter a new template instantiation context where we check the
1092 // explicitly-specified template arguments against this function template,
1093 // and then substitute them into the function parameter types.
1094 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
1095 FunctionTemplate, Deduced.data(), Deduced.size(),
1096 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution);
1097 if (Inst)
1098 return TDK_InstantiationDepth;
1099
1100 if (CheckTemplateArgumentList(FunctionTemplate,
1101 SourceLocation(), SourceLocation(),
1102 ExplicitTemplateArgs,
1103 NumExplicitTemplateArgs,
1104 SourceLocation(),
1105 true,
1106 Builder) || Trap.hasErrorOccurred())
1107 return TDK_InvalidExplicitArguments;
1108
1109 // Form the template argument list from the explicitly-specified
1110 // template arguments.
1111 TemplateArgumentList *ExplicitArgumentList
1112 = new (Context) TemplateArgumentList(Context, Builder, /*TakeArgs=*/true);
1113 Info.reset(ExplicitArgumentList);
1114
1115 // Instantiate the types of each of the function parameters given the
1116 // explicitly-specified template arguments.
1117 for (FunctionDecl::param_iterator P = Function->param_begin(),
1118 PEnd = Function->param_end();
1119 P != PEnd;
1120 ++P) {
1121 QualType ParamType = InstantiateType((*P)->getType(),
1122 *ExplicitArgumentList,
1123 (*P)->getLocation(),
1124 (*P)->getDeclName());
1125 if (ParamType.isNull() || Trap.hasErrorOccurred())
1126 return TDK_SubstitutionFailure;
1127
1128 ParamTypes.push_back(ParamType);
1129 }
1130
1131 // If the caller wants a full function type back, instantiate the return
1132 // type and form that function type.
1133 if (FunctionType) {
1134 // FIXME: exception-specifications?
1135 const FunctionProtoType *Proto
1136 = Function->getType()->getAsFunctionProtoType();
1137 assert(Proto && "Function template does not have a prototype?");
1138
1139 QualType ResultType = InstantiateType(Proto->getResultType(),
1140 *ExplicitArgumentList,
1141 Function->getTypeSpecStartLoc(),
1142 Function->getDeclName());
1143 if (ResultType.isNull() || Trap.hasErrorOccurred())
1144 return TDK_SubstitutionFailure;
1145
1146 *FunctionType = BuildFunctionType(ResultType,
1147 ParamTypes.data(), ParamTypes.size(),
1148 Proto->isVariadic(),
1149 Proto->getTypeQuals(),
1150 Function->getLocation(),
1151 Function->getDeclName());
1152 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1153 return TDK_SubstitutionFailure;
1154 }
1155
1156 // C++ [temp.arg.explicit]p2:
1157 // Trailing template arguments that can be deduced (14.8.2) may be
1158 // omitted from the list of explicit template-arguments. If all of the
1159 // template arguments can be deduced, they may all be omitted; in this
1160 // case, the empty template argument list <> itself may also be omitted.
1161 //
1162 // Take all of the explicitly-specified arguments and put them into the
1163 // set of deduced template arguments.
1164 Deduced.reserve(TemplateParams->size());
1165 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
1166 Deduced.push_back(ExplicitArgumentList->get(I));
1167
1168 return TDK_Success;
1169}
1170
1171/// \brief Finish template argument deduction for a function template,
1172/// checking the deduced template arguments for completeness and forming
1173/// the function template specialization.
1174Sema::TemplateDeductionResult
1175Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
1176 llvm::SmallVectorImpl<TemplateArgument> &Deduced,
1177 FunctionDecl *&Specialization,
1178 TemplateDeductionInfo &Info) {
1179 TemplateParameterList *TemplateParams
1180 = FunctionTemplate->getTemplateParameters();
1181
1182 // C++ [temp.deduct.type]p2:
1183 // [...] or if any template argument remains neither deduced nor
1184 // explicitly specified, template argument deduction fails.
1185 TemplateArgumentListBuilder Builder(TemplateParams, Deduced.size());
1186 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
1187 if (Deduced[I].isNull()) {
1188 Info.Param = makeTemplateParameter(
1189 const_cast<Decl *>(TemplateParams->getParam(I)));
1190 return TDK_Incomplete;
1191 }
1192
1193 Builder.Append(Deduced[I]);
1194 }
1195
1196 // Form the template argument list from the deduced template arguments.
1197 TemplateArgumentList *DeducedArgumentList
1198 = new (Context) TemplateArgumentList(Context, Builder, /*TakeArgs=*/true);
1199 Info.reset(DeducedArgumentList);
1200
1201 // Template argument deduction for function templates in a SFINAE context.
1202 // Trap any errors that might occur.
1203 SFINAETrap Trap(*this);
1204
1205 // Enter a new template instantiation context while we instantiate the
1206 // actual function declaration.
1207 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
1208 FunctionTemplate, Deduced.data(), Deduced.size(),
1209 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution);
1210 if (Inst)
1211 return TDK_InstantiationDepth;
1212
1213 // Substitute the deduced template arguments into the function template
1214 // declaration to produce the function template specialization.
1215 Specialization = cast_or_null<FunctionDecl>(
1216 InstantiateDecl(FunctionTemplate->getTemplatedDecl(),
1217 FunctionTemplate->getDeclContext(),
1218 *DeducedArgumentList));
1219 if (!Specialization)
1220 return TDK_SubstitutionFailure;
1221
1222 // If the template argument list is owned by the function template
1223 // specialization, release it.
1224 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList)
1225 Info.take();
1226
1227 // There may have been an error that did not prevent us from constructing a
1228 // declaration. Mark the declaration invalid and return with a substitution
1229 // failure.
1230 if (Trap.hasErrorOccurred()) {
1231 Specialization->setInvalidDecl(true);
1232 return TDK_SubstitutionFailure;
1233 }
1234
1235 return TDK_Success;
1236}
1237
Douglas Gregore53060f2009-06-25 22:08:12 +00001238/// \brief Perform template argument deduction from a function call
1239/// (C++ [temp.deduct.call]).
1240///
1241/// \param FunctionTemplate the function template for which we are performing
1242/// template argument deduction.
1243///
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001244/// \param HasExplicitTemplateArgs whether any template arguments were
1245/// explicitly specified.
1246///
1247/// \param ExplicitTemplateArguments when @p HasExplicitTemplateArgs is true,
1248/// the explicitly-specified template arguments.
1249///
1250/// \param NumExplicitTemplateArguments when @p HasExplicitTemplateArgs is true,
1251/// the number of explicitly-specified template arguments in
1252/// @p ExplicitTemplateArguments. This value may be zero.
1253///
Douglas Gregore53060f2009-06-25 22:08:12 +00001254/// \param Args the function call arguments
1255///
1256/// \param NumArgs the number of arguments in Args
1257///
1258/// \param Specialization if template argument deduction was successful,
1259/// this will be set to the function template specialization produced by
1260/// template argument deduction.
1261///
1262/// \param Info the argument will be updated to provide additional information
1263/// about template argument deduction.
1264///
1265/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00001266Sema::TemplateDeductionResult
1267Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001268 bool HasExplicitTemplateArgs,
1269 const TemplateArgument *ExplicitTemplateArgs,
1270 unsigned NumExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00001271 Expr **Args, unsigned NumArgs,
1272 FunctionDecl *&Specialization,
1273 TemplateDeductionInfo &Info) {
1274 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001275
Douglas Gregore53060f2009-06-25 22:08:12 +00001276 // C++ [temp.deduct.call]p1:
1277 // Template argument deduction is done by comparing each function template
1278 // parameter type (call it P) with the type of the corresponding argument
1279 // of the call (call it A) as described below.
1280 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001281 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00001282 return TDK_TooFewArguments;
1283 else if (NumArgs > Function->getNumParams()) {
1284 const FunctionProtoType *Proto
1285 = Function->getType()->getAsFunctionProtoType();
1286 if (!Proto->isVariadic())
1287 return TDK_TooManyArguments;
1288
1289 CheckArgs = Function->getNumParams();
1290 }
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001291
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001292 // The types of the parameters from which we will perform template argument
1293 // deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00001294 TemplateParameterList *TemplateParams
1295 = FunctionTemplate->getTemplateParameters();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001296 llvm::SmallVector<TemplateArgument, 4> Deduced;
1297 llvm::SmallVector<QualType, 4> ParamTypes;
1298 if (NumExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001299 TemplateDeductionResult Result =
1300 SubstituteExplicitTemplateArguments(FunctionTemplate,
1301 ExplicitTemplateArgs,
1302 NumExplicitTemplateArgs,
1303 Deduced,
1304 ParamTypes,
1305 0,
1306 Info);
1307 if (Result)
1308 return Result;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001309 } else {
1310 // Just fill in the parameter types from the function declaration.
1311 for (unsigned I = 0; I != CheckArgs; ++I)
1312 ParamTypes.push_back(Function->getParamDecl(I)->getType());
1313 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00001314
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001315 // Deduce template arguments from the function parameters.
1316 Deduced.resize(TemplateParams->size());
Douglas Gregore53060f2009-06-25 22:08:12 +00001317 for (unsigned I = 0; I != CheckArgs; ++I) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001318 QualType ParamType = ParamTypes[I];
Douglas Gregore53060f2009-06-25 22:08:12 +00001319 QualType ArgType = Args[I]->getType();
Douglas Gregor500d3312009-06-26 18:27:22 +00001320
Douglas Gregore53060f2009-06-25 22:08:12 +00001321 // C++ [temp.deduct.call]p2:
1322 // If P is not a reference type:
1323 QualType CanonParamType = Context.getCanonicalType(ParamType);
Douglas Gregor500d3312009-06-26 18:27:22 +00001324 bool ParamWasReference = isa<ReferenceType>(CanonParamType);
1325 if (!ParamWasReference) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001326 // - If A is an array type, the pointer type produced by the
1327 // array-to-pointer standard conversion (4.2) is used in place of
1328 // A for type deduction; otherwise,
1329 if (ArgType->isArrayType())
1330 ArgType = Context.getArrayDecayedType(ArgType);
1331 // - If A is a function type, the pointer type produced by the
1332 // function-to-pointer standard conversion (4.3) is used in place
1333 // of A for type deduction; otherwise,
1334 else if (ArgType->isFunctionType())
1335 ArgType = Context.getPointerType(ArgType);
1336 else {
1337 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
1338 // type are ignored for type deduction.
1339 QualType CanonArgType = Context.getCanonicalType(ArgType);
1340 if (CanonArgType.getCVRQualifiers())
1341 ArgType = CanonArgType.getUnqualifiedType();
1342 }
1343 }
1344
1345 // C++0x [temp.deduct.call]p3:
1346 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
1347 // are ignored for type deduction.
1348 if (CanonParamType.getCVRQualifiers())
1349 ParamType = CanonParamType.getUnqualifiedType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001350 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001351 // [...] If P is a reference type, the type referred to by P is used
1352 // for type deduction.
1353 ParamType = ParamRefType->getPointeeType();
1354
1355 // [...] If P is of the form T&&, where T is a template parameter, and
1356 // the argument is an lvalue, the type A& is used in place of A for
1357 // type deduction.
1358 if (isa<RValueReferenceType>(ParamRefType) &&
1359 ParamRefType->getAsTemplateTypeParmType() &&
1360 Args[I]->isLvalue(Context) == Expr::LV_Valid)
1361 ArgType = Context.getLValueReferenceType(ArgType);
1362 }
1363
1364 // C++0x [temp.deduct.call]p4:
1365 // In general, the deduction process attempts to find template argument
1366 // values that will make the deduced A identical to A (after the type A
1367 // is transformed as described above). [...]
Douglas Gregor508f1c82009-06-26 23:10:12 +00001368 unsigned TDF = 0;
1369
1370 // - If the original P is a reference type, the deduced A (i.e., the
1371 // type referred to by the reference) can be more cv-qualified than
1372 // the transformed A.
1373 if (ParamWasReference)
1374 TDF |= TDF_ParamWithReferenceType;
1375 // - The transformed A can be another pointer or pointer to member
1376 // type that can be converted to the deduced A via a qualification
1377 // conversion (4.4).
1378 if (ArgType->isPointerType() || ArgType->isMemberPointerType())
1379 TDF |= TDF_IgnoreQualifiers;
Douglas Gregor41128772009-06-26 23:27:24 +00001380 // - If P is a class and P has the form simple-template-id, then the
1381 // transformed A can be a derived class of the deduced A. Likewise,
1382 // if P is a pointer to a class of the form simple-template-id, the
1383 // transformed A can be a pointer to a derived class pointed to by
1384 // the deduced A.
1385 if (isSimpleTemplateIdType(ParamType) ||
1386 (isa<PointerType>(ParamType) &&
1387 isSimpleTemplateIdType(
Ted Kremenek6217b802009-07-29 21:53:49 +00001388 ParamType->getAs<PointerType>()->getPointeeType())))
Douglas Gregor41128772009-06-26 23:27:24 +00001389 TDF |= TDF_DerivedClass;
1390
Douglas Gregore53060f2009-06-25 22:08:12 +00001391 if (TemplateDeductionResult Result
1392 = ::DeduceTemplateArguments(Context, TemplateParams,
Douglas Gregor500d3312009-06-26 18:27:22 +00001393 ParamType, ArgType, Info, Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001394 TDF))
Douglas Gregore53060f2009-06-25 22:08:12 +00001395 return Result;
1396
Douglas Gregor8fdc3c42009-07-07 23:12:18 +00001397 // FIXME: C++0x [temp.deduct.call] paragraphs 6-9 deal with function
Douglas Gregore53060f2009-06-25 22:08:12 +00001398 // pointer parameters.
1399 }
Douglas Gregore53060f2009-06-25 22:08:12 +00001400
Douglas Gregor83314aa2009-07-08 20:55:45 +00001401 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
1402 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00001403}
1404
Douglas Gregor83314aa2009-07-08 20:55:45 +00001405/// \brief Deduce template arguments when taking the address of a function
1406/// template (C++ [temp.deduct.funcaddr]).
1407///
1408/// \param FunctionTemplate the function template for which we are performing
1409/// template argument deduction.
1410///
1411/// \param HasExplicitTemplateArgs whether any template arguments were
1412/// explicitly specified.
1413///
1414/// \param ExplicitTemplateArguments when @p HasExplicitTemplateArgs is true,
1415/// the explicitly-specified template arguments.
1416///
1417/// \param NumExplicitTemplateArguments when @p HasExplicitTemplateArgs is true,
1418/// the number of explicitly-specified template arguments in
1419/// @p ExplicitTemplateArguments. This value may be zero.
1420///
1421/// \param ArgFunctionType the function type that will be used as the
1422/// "argument" type (A) when performing template argument deduction from the
1423/// function template's function type.
1424///
1425/// \param Specialization if template argument deduction was successful,
1426/// this will be set to the function template specialization produced by
1427/// template argument deduction.
1428///
1429/// \param Info the argument will be updated to provide additional information
1430/// about template argument deduction.
1431///
1432/// \returns the result of template argument deduction.
1433Sema::TemplateDeductionResult
1434Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
1435 bool HasExplicitTemplateArgs,
1436 const TemplateArgument *ExplicitTemplateArgs,
1437 unsigned NumExplicitTemplateArgs,
1438 QualType ArgFunctionType,
1439 FunctionDecl *&Specialization,
1440 TemplateDeductionInfo &Info) {
1441 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1442 TemplateParameterList *TemplateParams
1443 = FunctionTemplate->getTemplateParameters();
1444 QualType FunctionType = Function->getType();
1445
1446 // Substitute any explicit template arguments.
1447 llvm::SmallVector<TemplateArgument, 4> Deduced;
1448 llvm::SmallVector<QualType, 4> ParamTypes;
1449 if (HasExplicitTemplateArgs) {
1450 if (TemplateDeductionResult Result
1451 = SubstituteExplicitTemplateArguments(FunctionTemplate,
1452 ExplicitTemplateArgs,
1453 NumExplicitTemplateArgs,
1454 Deduced, ParamTypes,
1455 &FunctionType, Info))
1456 return Result;
1457 }
1458
1459 // Template argument deduction for function templates in a SFINAE context.
1460 // Trap any errors that might occur.
1461 SFINAETrap Trap(*this);
1462
1463 // Deduce template arguments from the function type.
1464 Deduced.resize(TemplateParams->size());
1465 if (TemplateDeductionResult Result
1466 = ::DeduceTemplateArguments(Context, TemplateParams,
1467 FunctionType, ArgFunctionType, Info,
1468 Deduced, 0))
1469 return Result;
1470
1471 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
1472 Specialization, Info);
1473}
1474
1475
Douglas Gregor031a5882009-06-13 00:26:55 +00001476static void
1477MarkDeducedTemplateParameters(Sema &SemaRef,
1478 const TemplateArgument &TemplateArg,
1479 llvm::SmallVectorImpl<bool> &Deduced);
1480
1481/// \brief Mark the template arguments that are deduced by the given
1482/// expression.
1483static void
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001484MarkDeducedTemplateParameters(const Expr *E,
1485 llvm::SmallVectorImpl<bool> &Deduced) {
1486 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor031a5882009-06-13 00:26:55 +00001487 if (!E)
1488 return;
1489
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001490 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00001491 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
1492 if (!NTTP)
1493 return;
1494
1495 Deduced[NTTP->getIndex()] = true;
1496}
1497
1498/// \brief Mark the template parameters that are deduced by the given
1499/// type.
1500static void
1501MarkDeducedTemplateParameters(Sema &SemaRef, QualType T,
1502 llvm::SmallVectorImpl<bool> &Deduced) {
1503 // Non-dependent types have nothing deducible
1504 if (!T->isDependentType())
1505 return;
1506
1507 T = SemaRef.Context.getCanonicalType(T);
1508 switch (T->getTypeClass()) {
1509 case Type::ExtQual:
1510 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001511 QualType(cast<ExtQualType>(T)->getBaseType(), 0),
Douglas Gregor031a5882009-06-13 00:26:55 +00001512 Deduced);
1513 break;
1514
1515 case Type::Pointer:
1516 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001517 cast<PointerType>(T)->getPointeeType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001518 Deduced);
1519 break;
1520
1521 case Type::BlockPointer:
1522 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001523 cast<BlockPointerType>(T)->getPointeeType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001524 Deduced);
1525 break;
1526
1527 case Type::LValueReference:
1528 case Type::RValueReference:
1529 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001530 cast<ReferenceType>(T)->getPointeeType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001531 Deduced);
1532 break;
1533
1534 case Type::MemberPointer: {
1535 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
1536 MarkDeducedTemplateParameters(SemaRef, MemPtr->getPointeeType(), Deduced);
1537 MarkDeducedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
1538 Deduced);
1539 break;
1540 }
1541
1542 case Type::DependentSizedArray:
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001543 MarkDeducedTemplateParameters(cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001544 Deduced);
1545 // Fall through to check the element type
1546
1547 case Type::ConstantArray:
1548 case Type::IncompleteArray:
1549 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001550 cast<ArrayType>(T)->getElementType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001551 Deduced);
1552 break;
1553
1554 case Type::Vector:
1555 case Type::ExtVector:
1556 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001557 cast<VectorType>(T)->getElementType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001558 Deduced);
1559 break;
1560
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001561 case Type::DependentSizedExtVector: {
1562 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001563 = cast<DependentSizedExtVectorType>(T);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001564 MarkDeducedTemplateParameters(SemaRef, VecType->getElementType(), Deduced);
1565 MarkDeducedTemplateParameters(VecType->getSizeExpr(), Deduced);
1566 break;
1567 }
1568
Douglas Gregor031a5882009-06-13 00:26:55 +00001569 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001570 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregor031a5882009-06-13 00:26:55 +00001571 MarkDeducedTemplateParameters(SemaRef, Proto->getResultType(), Deduced);
1572 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
1573 MarkDeducedTemplateParameters(SemaRef, Proto->getArgType(I), Deduced);
1574 break;
1575 }
1576
1577 case Type::TemplateTypeParm:
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001578 Deduced[cast<TemplateTypeParmType>(T)->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00001579 break;
1580
1581 case Type::TemplateSpecialization: {
1582 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001583 = cast<TemplateSpecializationType>(T);
Douglas Gregor031a5882009-06-13 00:26:55 +00001584 if (TemplateDecl *Template = Spec->getTemplateName().getAsTemplateDecl())
1585 if (TemplateTemplateParmDecl *TTP
1586 = dyn_cast<TemplateTemplateParmDecl>(Template))
1587 Deduced[TTP->getIndex()] = true;
1588
1589 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
1590 MarkDeducedTemplateParameters(SemaRef, Spec->getArg(I), Deduced);
1591
1592 break;
1593 }
1594
1595 // None of these types have any deducible parts.
1596 case Type::Builtin:
1597 case Type::FixedWidthInt:
1598 case Type::Complex:
1599 case Type::VariableArray:
1600 case Type::FunctionNoProto:
1601 case Type::Record:
1602 case Type::Enum:
1603 case Type::Typename:
1604 case Type::ObjCInterface:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001605 case Type::ObjCObjectPointer:
Douglas Gregor031a5882009-06-13 00:26:55 +00001606#define TYPE(Class, Base)
1607#define ABSTRACT_TYPE(Class, Base)
1608#define DEPENDENT_TYPE(Class, Base)
1609#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1610#include "clang/AST/TypeNodes.def"
1611 break;
1612 }
1613}
1614
1615/// \brief Mark the template parameters that are deduced by this
1616/// template argument.
1617static void
1618MarkDeducedTemplateParameters(Sema &SemaRef,
1619 const TemplateArgument &TemplateArg,
1620 llvm::SmallVectorImpl<bool> &Deduced) {
1621 switch (TemplateArg.getKind()) {
1622 case TemplateArgument::Null:
1623 case TemplateArgument::Integral:
1624 break;
1625
1626 case TemplateArgument::Type:
1627 MarkDeducedTemplateParameters(SemaRef, TemplateArg.getAsType(), Deduced);
1628 break;
1629
1630 case TemplateArgument::Declaration:
1631 if (TemplateTemplateParmDecl *TTP
1632 = dyn_cast<TemplateTemplateParmDecl>(TemplateArg.getAsDecl()))
1633 Deduced[TTP->getIndex()] = true;
1634 break;
1635
1636 case TemplateArgument::Expression:
1637 MarkDeducedTemplateParameters(TemplateArg.getAsExpr(), Deduced);
1638 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001639 case TemplateArgument::Pack:
1640 assert(0 && "FIXME: Implement!");
1641 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00001642 }
1643}
1644
1645/// \brief Mark the template parameters can be deduced by the given
1646/// template argument list.
1647///
1648/// \param TemplateArgs the template argument list from which template
1649/// parameters will be deduced.
1650///
1651/// \param Deduced a bit vector whose elements will be set to \c true
1652/// to indicate when the corresponding template parameter will be
1653/// deduced.
1654void
1655Sema::MarkDeducedTemplateParameters(const TemplateArgumentList &TemplateArgs,
1656 llvm::SmallVectorImpl<bool> &Deduced) {
1657 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1658 ::MarkDeducedTemplateParameters(*this, TemplateArgs[I], Deduced);
1659}