SemaTemplateDeduction.cpp revision ecdc4c315cc0f0d45c3c14e8d076db06d59ff6ad
1//===------- 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 <algorithm>
21
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
40    /// deduction from a template-id of a derived class of the argument type.
41    TDF_DerivedClass = 0x04,
42    /// \brief Allow non-dependent types to differ, e.g., when performing
43    /// template argument deduction from a function call where conversions
44    /// may apply.
45    TDF_SkipNonDependent = 0x08
46  };
47}
48
49using namespace clang;
50
51static Sema::TemplateDeductionResult
52DeduceTemplateArguments(ASTContext &Context,
53                        TemplateParameterList *TemplateParams,
54                        const TemplateArgument &Param,
55                        const TemplateArgument &Arg,
56                        Sema::TemplateDeductionInfo &Info,
57                        llvm::SmallVectorImpl<TemplateArgument> &Deduced);
58
59/// \brief If the given expression is of a form that permits the deduction
60/// of a non-type template parameter, return the declaration of that
61/// non-type template parameter.
62static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
63  if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
64    E = IC->getSubExpr();
65
66  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
67    return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
68
69  return 0;
70}
71
72/// \brief Deduce the value of the given non-type template parameter
73/// from the given constant.
74static Sema::TemplateDeductionResult
75DeduceNonTypeTemplateArgument(ASTContext &Context,
76                              NonTypeTemplateParmDecl *NTTP,
77                              llvm::APSInt Value,
78                              Sema::TemplateDeductionInfo &Info,
79                              llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
80  assert(NTTP->getDepth() == 0 &&
81         "Cannot deduce non-type template argument with depth > 0");
82
83  if (Deduced[NTTP->getIndex()].isNull()) {
84    QualType T = NTTP->getType();
85
86    // FIXME: Make sure we didn't overflow our data type!
87    unsigned AllowedBits = Context.getTypeSize(T);
88    if (Value.getBitWidth() != AllowedBits)
89      Value.extOrTrunc(AllowedBits);
90    Value.setIsSigned(T->isSignedIntegerType());
91
92    Deduced[NTTP->getIndex()] = TemplateArgument(Value, T);
93    return Sema::TDK_Success;
94  }
95
96  assert(Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Integral);
97
98  // If the template argument was previously deduced to a negative value,
99  // then our deduction fails.
100  const llvm::APSInt *PrevValuePtr = Deduced[NTTP->getIndex()].getAsIntegral();
101  if (PrevValuePtr->isNegative()) {
102    Info.Param = NTTP;
103    Info.FirstArg = Deduced[NTTP->getIndex()];
104    Info.SecondArg = TemplateArgument(Value, NTTP->getType());
105    return Sema::TDK_Inconsistent;
106  }
107
108  llvm::APSInt PrevValue = *PrevValuePtr;
109  if (Value.getBitWidth() > PrevValue.getBitWidth())
110    PrevValue.zext(Value.getBitWidth());
111  else if (Value.getBitWidth() < PrevValue.getBitWidth())
112    Value.zext(PrevValue.getBitWidth());
113
114  if (Value != PrevValue) {
115    Info.Param = NTTP;
116    Info.FirstArg = Deduced[NTTP->getIndex()];
117    Info.SecondArg = TemplateArgument(Value, NTTP->getType());
118    return Sema::TDK_Inconsistent;
119  }
120
121  return Sema::TDK_Success;
122}
123
124/// \brief Deduce the value of the given non-type template parameter
125/// from the given type- or value-dependent expression.
126///
127/// \returns true if deduction succeeded, false otherwise.
128static Sema::TemplateDeductionResult
129DeduceNonTypeTemplateArgument(ASTContext &Context,
130                              NonTypeTemplateParmDecl *NTTP,
131                              Expr *Value,
132                              Sema::TemplateDeductionInfo &Info,
133                           llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
134  assert(NTTP->getDepth() == 0 &&
135         "Cannot deduce non-type template argument with depth > 0");
136  assert((Value->isTypeDependent() || Value->isValueDependent()) &&
137         "Expression template argument must be type- or value-dependent.");
138
139  if (Deduced[NTTP->getIndex()].isNull()) {
140    // FIXME: Clone the Value?
141    Deduced[NTTP->getIndex()] = TemplateArgument(Value);
142    return Sema::TDK_Success;
143  }
144
145  if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Integral) {
146    // Okay, we deduced a constant in one case and a dependent expression
147    // in another case. FIXME: Later, we will check that instantiating the
148    // dependent expression gives us the constant value.
149    return Sema::TDK_Success;
150  }
151
152  if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Expression) {
153    // Compare the expressions for equality
154    llvm::FoldingSetNodeID ID1, ID2;
155    Deduced[NTTP->getIndex()].getAsExpr()->Profile(ID1, Context, true);
156    Value->Profile(ID2, Context, true);
157    if (ID1 == ID2)
158      return Sema::TDK_Success;
159
160    // FIXME: Fill in argument mismatch information
161    return Sema::TDK_NonDeducedMismatch;
162  }
163
164  return Sema::TDK_Success;
165}
166
167/// \brief Deduce the value of the given non-type template parameter
168/// from the given declaration.
169///
170/// \returns true if deduction succeeded, false otherwise.
171static Sema::TemplateDeductionResult
172DeduceNonTypeTemplateArgument(ASTContext &Context,
173                              NonTypeTemplateParmDecl *NTTP,
174                              Decl *D,
175                              Sema::TemplateDeductionInfo &Info,
176                              llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
177  assert(NTTP->getDepth() == 0 &&
178         "Cannot deduce non-type template argument with depth > 0");
179
180  if (Deduced[NTTP->getIndex()].isNull()) {
181    Deduced[NTTP->getIndex()] = TemplateArgument(D->getCanonicalDecl());
182    return Sema::TDK_Success;
183  }
184
185  if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Expression) {
186    // Okay, we deduced a declaration in one case and a dependent expression
187    // in another case.
188    return Sema::TDK_Success;
189  }
190
191  if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Declaration) {
192    // Compare the declarations for equality
193    if (Deduced[NTTP->getIndex()].getAsDecl()->getCanonicalDecl() ==
194          D->getCanonicalDecl())
195      return Sema::TDK_Success;
196
197    // FIXME: Fill in argument mismatch information
198    return Sema::TDK_NonDeducedMismatch;
199  }
200
201  return Sema::TDK_Success;
202}
203
204static Sema::TemplateDeductionResult
205DeduceTemplateArguments(ASTContext &Context,
206                        TemplateParameterList *TemplateParams,
207                        TemplateName Param,
208                        TemplateName Arg,
209                        Sema::TemplateDeductionInfo &Info,
210                        llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
211  TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
212  if (!ParamDecl) {
213    // The parameter type is dependent and is not a template template parameter,
214    // so there is nothing that we can deduce.
215    return Sema::TDK_Success;
216  }
217
218  if (TemplateTemplateParmDecl *TempParam
219        = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
220    // Bind the template template parameter to the given template name.
221    TemplateArgument &ExistingArg = Deduced[TempParam->getIndex()];
222    if (ExistingArg.isNull()) {
223      // This is the first deduction for this template template parameter.
224      ExistingArg = TemplateArgument(Context.getCanonicalTemplateName(Arg));
225      return Sema::TDK_Success;
226    }
227
228    // Verify that the previous binding matches this deduction.
229    assert(ExistingArg.getKind() == TemplateArgument::Template);
230    if (Context.hasSameTemplateName(ExistingArg.getAsTemplate(), Arg))
231      return Sema::TDK_Success;
232
233    // Inconsistent deduction.
234    Info.Param = TempParam;
235    Info.FirstArg = ExistingArg;
236    Info.SecondArg = TemplateArgument(Arg);
237    return Sema::TDK_Inconsistent;
238  }
239
240  // Verify that the two template names are equivalent.
241  if (Context.hasSameTemplateName(Param, Arg))
242    return Sema::TDK_Success;
243
244  // Mismatch of non-dependent template parameter to argument.
245  Info.FirstArg = TemplateArgument(Param);
246  Info.SecondArg = TemplateArgument(Arg);
247  return Sema::TDK_NonDeducedMismatch;
248}
249
250/// \brief Deduce the template arguments by comparing the template parameter
251/// type (which is a template-id) with the template argument type.
252///
253/// \param Context the AST context in which this deduction occurs.
254///
255/// \param TemplateParams the template parameters that we are deducing
256///
257/// \param Param the parameter type
258///
259/// \param Arg the argument type
260///
261/// \param Info information about the template argument deduction itself
262///
263/// \param Deduced the deduced template arguments
264///
265/// \returns the result of template argument deduction so far. Note that a
266/// "success" result means that template argument deduction has not yet failed,
267/// but it may still fail, later, for other reasons.
268static Sema::TemplateDeductionResult
269DeduceTemplateArguments(ASTContext &Context,
270                        TemplateParameterList *TemplateParams,
271                        const TemplateSpecializationType *Param,
272                        QualType Arg,
273                        Sema::TemplateDeductionInfo &Info,
274                        llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
275  assert(Arg.isCanonical() && "Argument type must be canonical");
276
277  // Check whether the template argument is a dependent template-id.
278  if (const TemplateSpecializationType *SpecArg
279        = dyn_cast<TemplateSpecializationType>(Arg)) {
280    // Perform template argument deduction for the template name.
281    if (Sema::TemplateDeductionResult Result
282          = DeduceTemplateArguments(Context, TemplateParams,
283                                    Param->getTemplateName(),
284                                    SpecArg->getTemplateName(),
285                                    Info, Deduced))
286      return Result;
287
288
289    // Perform template argument deduction on each template
290    // argument.
291    unsigned NumArgs = std::min(SpecArg->getNumArgs(), Param->getNumArgs());
292    for (unsigned I = 0; I != NumArgs; ++I)
293      if (Sema::TemplateDeductionResult Result
294            = DeduceTemplateArguments(Context, TemplateParams,
295                                      Param->getArg(I),
296                                      SpecArg->getArg(I),
297                                      Info, Deduced))
298        return Result;
299
300    return Sema::TDK_Success;
301  }
302
303  // If the argument type is a class template specialization, we
304  // perform template argument deduction using its template
305  // arguments.
306  const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
307  if (!RecordArg)
308    return Sema::TDK_NonDeducedMismatch;
309
310  ClassTemplateSpecializationDecl *SpecArg
311    = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
312  if (!SpecArg)
313    return Sema::TDK_NonDeducedMismatch;
314
315  // Perform template argument deduction for the template name.
316  if (Sema::TemplateDeductionResult Result
317        = DeduceTemplateArguments(Context,
318                                  TemplateParams,
319                                  Param->getTemplateName(),
320                               TemplateName(SpecArg->getSpecializedTemplate()),
321                                  Info, Deduced))
322    return Result;
323
324  unsigned NumArgs = Param->getNumArgs();
325  const TemplateArgumentList &ArgArgs = SpecArg->getTemplateArgs();
326  if (NumArgs != ArgArgs.size())
327    return Sema::TDK_NonDeducedMismatch;
328
329  for (unsigned I = 0; I != NumArgs; ++I)
330    if (Sema::TemplateDeductionResult Result
331          = DeduceTemplateArguments(Context, TemplateParams,
332                                    Param->getArg(I),
333                                    ArgArgs.get(I),
334                                    Info, Deduced))
335      return Result;
336
337  return Sema::TDK_Success;
338}
339
340/// \brief Deduce the template arguments by comparing the parameter type and
341/// the argument type (C++ [temp.deduct.type]).
342///
343/// \param Context the AST context in which this deduction occurs.
344///
345/// \param TemplateParams the template parameters that we are deducing
346///
347/// \param ParamIn the parameter type
348///
349/// \param ArgIn the argument type
350///
351/// \param Info information about the template argument deduction itself
352///
353/// \param Deduced the deduced template arguments
354///
355/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
356/// how template argument deduction is performed.
357///
358/// \returns the result of template argument deduction so far. Note that a
359/// "success" result means that template argument deduction has not yet failed,
360/// but it may still fail, later, for other reasons.
361static Sema::TemplateDeductionResult
362DeduceTemplateArguments(ASTContext &Context,
363                        TemplateParameterList *TemplateParams,
364                        QualType ParamIn, QualType ArgIn,
365                        Sema::TemplateDeductionInfo &Info,
366                        llvm::SmallVectorImpl<TemplateArgument> &Deduced,
367                        unsigned TDF) {
368  // We only want to look at the canonical types, since typedefs and
369  // sugar are not part of template argument deduction.
370  QualType Param = Context.getCanonicalType(ParamIn);
371  QualType Arg = Context.getCanonicalType(ArgIn);
372
373  // C++0x [temp.deduct.call]p4 bullet 1:
374  //   - If the original P is a reference type, the deduced A (i.e., the type
375  //     referred to by the reference) can be more cv-qualified than the
376  //     transformed A.
377  if (TDF & TDF_ParamWithReferenceType) {
378    Qualifiers Quals;
379    QualType UnqualParam = Context.getUnqualifiedArrayType(Param, Quals);
380    Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
381                           Arg.getCVRQualifiersThroughArrayTypes());
382    Param = Context.getQualifiedType(UnqualParam, Quals);
383  }
384
385  // If the parameter type is not dependent, there is nothing to deduce.
386  if (!Param->isDependentType()) {
387    if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
388
389      return Sema::TDK_NonDeducedMismatch;
390    }
391
392    return Sema::TDK_Success;
393  }
394
395  // C++ [temp.deduct.type]p9:
396  //   A template type argument T, a template template argument TT or a
397  //   template non-type argument i can be deduced if P and A have one of
398  //   the following forms:
399  //
400  //     T
401  //     cv-list T
402  if (const TemplateTypeParmType *TemplateTypeParm
403        = Param->getAs<TemplateTypeParmType>()) {
404    unsigned Index = TemplateTypeParm->getIndex();
405    bool RecanonicalizeArg = false;
406
407    // If the argument type is an array type, move the qualifiers up to the
408    // top level, so they can be matched with the qualifiers on the parameter.
409    // FIXME: address spaces, ObjC GC qualifiers
410    if (isa<ArrayType>(Arg)) {
411      Qualifiers Quals;
412      Arg = Context.getUnqualifiedArrayType(Arg, Quals);
413      if (Quals) {
414        Arg = Context.getQualifiedType(Arg, Quals);
415        RecanonicalizeArg = true;
416      }
417    }
418
419    // The argument type can not be less qualified than the parameter
420    // type.
421    if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
422      Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
423      Info.FirstArg = Deduced[Index];
424      Info.SecondArg = TemplateArgument(Arg);
425      return Sema::TDK_InconsistentQuals;
426    }
427
428    assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
429    assert(Arg != Context.OverloadTy && "Unresolved overloaded function");
430    QualType DeducedType = Arg;
431    DeducedType.removeCVRQualifiers(Param.getCVRQualifiers());
432    if (RecanonicalizeArg)
433      DeducedType = Context.getCanonicalType(DeducedType);
434
435    if (Deduced[Index].isNull())
436      Deduced[Index] = TemplateArgument(DeducedType);
437    else {
438      // C++ [temp.deduct.type]p2:
439      //   [...] If type deduction cannot be done for any P/A pair, or if for
440      //   any pair the deduction leads to more than one possible set of
441      //   deduced values, or if different pairs yield different deduced
442      //   values, or if any template argument remains neither deduced nor
443      //   explicitly specified, template argument deduction fails.
444      if (Deduced[Index].getAsType() != DeducedType) {
445        Info.Param
446          = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
447        Info.FirstArg = Deduced[Index];
448        Info.SecondArg = TemplateArgument(Arg);
449        return Sema::TDK_Inconsistent;
450      }
451    }
452    return Sema::TDK_Success;
453  }
454
455  // Set up the template argument deduction information for a failure.
456  Info.FirstArg = TemplateArgument(ParamIn);
457  Info.SecondArg = TemplateArgument(ArgIn);
458
459  // Check the cv-qualifiers on the parameter and argument types.
460  if (!(TDF & TDF_IgnoreQualifiers)) {
461    if (TDF & TDF_ParamWithReferenceType) {
462      if (Param.isMoreQualifiedThan(Arg))
463        return Sema::TDK_NonDeducedMismatch;
464    } else {
465      if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
466        return Sema::TDK_NonDeducedMismatch;
467    }
468  }
469
470  switch (Param->getTypeClass()) {
471    // No deduction possible for these types
472    case Type::Builtin:
473      return Sema::TDK_NonDeducedMismatch;
474
475    //     T *
476    case Type::Pointer: {
477      const PointerType *PointerArg = Arg->getAs<PointerType>();
478      if (!PointerArg)
479        return Sema::TDK_NonDeducedMismatch;
480
481      unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
482      return DeduceTemplateArguments(Context, TemplateParams,
483                                   cast<PointerType>(Param)->getPointeeType(),
484                                     PointerArg->getPointeeType(),
485                                     Info, Deduced, SubTDF);
486    }
487
488    //     T &
489    case Type::LValueReference: {
490      const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
491      if (!ReferenceArg)
492        return Sema::TDK_NonDeducedMismatch;
493
494      return DeduceTemplateArguments(Context, TemplateParams,
495                           cast<LValueReferenceType>(Param)->getPointeeType(),
496                                     ReferenceArg->getPointeeType(),
497                                     Info, Deduced, 0);
498    }
499
500    //     T && [C++0x]
501    case Type::RValueReference: {
502      const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
503      if (!ReferenceArg)
504        return Sema::TDK_NonDeducedMismatch;
505
506      return DeduceTemplateArguments(Context, TemplateParams,
507                           cast<RValueReferenceType>(Param)->getPointeeType(),
508                                     ReferenceArg->getPointeeType(),
509                                     Info, Deduced, 0);
510    }
511
512    //     T [] (implied, but not stated explicitly)
513    case Type::IncompleteArray: {
514      const IncompleteArrayType *IncompleteArrayArg =
515        Context.getAsIncompleteArrayType(Arg);
516      if (!IncompleteArrayArg)
517        return Sema::TDK_NonDeducedMismatch;
518
519      return DeduceTemplateArguments(Context, TemplateParams,
520                     Context.getAsIncompleteArrayType(Param)->getElementType(),
521                                     IncompleteArrayArg->getElementType(),
522                                     Info, Deduced, 0);
523    }
524
525    //     T [integer-constant]
526    case Type::ConstantArray: {
527      const ConstantArrayType *ConstantArrayArg =
528        Context.getAsConstantArrayType(Arg);
529      if (!ConstantArrayArg)
530        return Sema::TDK_NonDeducedMismatch;
531
532      const ConstantArrayType *ConstantArrayParm =
533        Context.getAsConstantArrayType(Param);
534      if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
535        return Sema::TDK_NonDeducedMismatch;
536
537      return DeduceTemplateArguments(Context, TemplateParams,
538                                     ConstantArrayParm->getElementType(),
539                                     ConstantArrayArg->getElementType(),
540                                     Info, Deduced, 0);
541    }
542
543    //     type [i]
544    case Type::DependentSizedArray: {
545      const ArrayType *ArrayArg = Context.getAsArrayType(Arg);
546      if (!ArrayArg)
547        return Sema::TDK_NonDeducedMismatch;
548
549      // Check the element type of the arrays
550      const DependentSizedArrayType *DependentArrayParm
551        = Context.getAsDependentSizedArrayType(Param);
552      if (Sema::TemplateDeductionResult Result
553            = DeduceTemplateArguments(Context, TemplateParams,
554                                      DependentArrayParm->getElementType(),
555                                      ArrayArg->getElementType(),
556                                      Info, Deduced, 0))
557        return Result;
558
559      // Determine the array bound is something we can deduce.
560      NonTypeTemplateParmDecl *NTTP
561        = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
562      if (!NTTP)
563        return Sema::TDK_Success;
564
565      // We can perform template argument deduction for the given non-type
566      // template parameter.
567      assert(NTTP->getDepth() == 0 &&
568             "Cannot deduce non-type template argument at depth > 0");
569      if (const ConstantArrayType *ConstantArrayArg
570            = dyn_cast<ConstantArrayType>(ArrayArg)) {
571        llvm::APSInt Size(ConstantArrayArg->getSize());
572        return DeduceNonTypeTemplateArgument(Context, NTTP, Size,
573                                             Info, Deduced);
574      }
575      if (const DependentSizedArrayType *DependentArrayArg
576            = dyn_cast<DependentSizedArrayType>(ArrayArg))
577        return DeduceNonTypeTemplateArgument(Context, NTTP,
578                                             DependentArrayArg->getSizeExpr(),
579                                             Info, Deduced);
580
581      // Incomplete type does not match a dependently-sized array type
582      return Sema::TDK_NonDeducedMismatch;
583    }
584
585    //     type(*)(T)
586    //     T(*)()
587    //     T(*)(T)
588    case Type::FunctionProto: {
589      const FunctionProtoType *FunctionProtoArg =
590        dyn_cast<FunctionProtoType>(Arg);
591      if (!FunctionProtoArg)
592        return Sema::TDK_NonDeducedMismatch;
593
594      const FunctionProtoType *FunctionProtoParam =
595        cast<FunctionProtoType>(Param);
596
597      if (FunctionProtoParam->getTypeQuals() !=
598          FunctionProtoArg->getTypeQuals())
599        return Sema::TDK_NonDeducedMismatch;
600
601      if (FunctionProtoParam->getNumArgs() != FunctionProtoArg->getNumArgs())
602        return Sema::TDK_NonDeducedMismatch;
603
604      if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
605        return Sema::TDK_NonDeducedMismatch;
606
607      // Check return types.
608      if (Sema::TemplateDeductionResult Result
609            = DeduceTemplateArguments(Context, TemplateParams,
610                                      FunctionProtoParam->getResultType(),
611                                      FunctionProtoArg->getResultType(),
612                                      Info, Deduced, 0))
613        return Result;
614
615      for (unsigned I = 0, N = FunctionProtoParam->getNumArgs(); I != N; ++I) {
616        // Check argument types.
617        if (Sema::TemplateDeductionResult Result
618              = DeduceTemplateArguments(Context, TemplateParams,
619                                        FunctionProtoParam->getArgType(I),
620                                        FunctionProtoArg->getArgType(I),
621                                        Info, Deduced, 0))
622          return Result;
623      }
624
625      return Sema::TDK_Success;
626    }
627
628    //     template-name<T> (where template-name refers to a class template)
629    //     template-name<i>
630    //     TT<T>
631    //     TT<i>
632    //     TT<>
633    case Type::TemplateSpecialization: {
634      const TemplateSpecializationType *SpecParam
635        = cast<TemplateSpecializationType>(Param);
636
637      // Try to deduce template arguments from the template-id.
638      Sema::TemplateDeductionResult Result
639        = DeduceTemplateArguments(Context, TemplateParams, SpecParam, Arg,
640                                  Info, Deduced);
641
642      if (Result && (TDF & TDF_DerivedClass)) {
643        // C++ [temp.deduct.call]p3b3:
644        //   If P is a class, and P has the form template-id, then A can be a
645        //   derived class of the deduced A. Likewise, if P is a pointer to a
646        //   class of the form template-id, A can be a pointer to a derived
647        //   class pointed to by the deduced A.
648        //
649        // More importantly:
650        //   These alternatives are considered only if type deduction would
651        //   otherwise fail.
652        if (const RecordType *RecordT = dyn_cast<RecordType>(Arg)) {
653          // Use data recursion to crawl through the list of base classes.
654          // Visited contains the set of nodes we have already visited, while
655          // ToVisit is our stack of records that we still need to visit.
656          llvm::SmallPtrSet<const RecordType *, 8> Visited;
657          llvm::SmallVector<const RecordType *, 8> ToVisit;
658          ToVisit.push_back(RecordT);
659          bool Successful = false;
660          while (!ToVisit.empty()) {
661            // Retrieve the next class in the inheritance hierarchy.
662            const RecordType *NextT = ToVisit.back();
663            ToVisit.pop_back();
664
665            // If we have already seen this type, skip it.
666            if (!Visited.insert(NextT))
667              continue;
668
669            // If this is a base class, try to perform template argument
670            // deduction from it.
671            if (NextT != RecordT) {
672              Sema::TemplateDeductionResult BaseResult
673                = DeduceTemplateArguments(Context, TemplateParams, SpecParam,
674                                          QualType(NextT, 0), Info, Deduced);
675
676              // If template argument deduction for this base was successful,
677              // note that we had some success.
678              if (BaseResult == Sema::TDK_Success)
679                Successful = true;
680            }
681
682            // Visit base classes
683            CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
684            for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
685                                                 BaseEnd = Next->bases_end();
686                 Base != BaseEnd; ++Base) {
687              assert(Base->getType()->isRecordType() &&
688                     "Base class that isn't a record?");
689              ToVisit.push_back(Base->getType()->getAs<RecordType>());
690            }
691          }
692
693          if (Successful)
694            return Sema::TDK_Success;
695        }
696
697      }
698
699      return Result;
700    }
701
702    //     T type::*
703    //     T T::*
704    //     T (type::*)()
705    //     type (T::*)()
706    //     type (type::*)(T)
707    //     type (T::*)(T)
708    //     T (type::*)(T)
709    //     T (T::*)()
710    //     T (T::*)(T)
711    case Type::MemberPointer: {
712      const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
713      const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
714      if (!MemPtrArg)
715        return Sema::TDK_NonDeducedMismatch;
716
717      if (Sema::TemplateDeductionResult Result
718            = DeduceTemplateArguments(Context, TemplateParams,
719                                      MemPtrParam->getPointeeType(),
720                                      MemPtrArg->getPointeeType(),
721                                      Info, Deduced,
722                                      TDF & TDF_IgnoreQualifiers))
723        return Result;
724
725      return DeduceTemplateArguments(Context, TemplateParams,
726                                     QualType(MemPtrParam->getClass(), 0),
727                                     QualType(MemPtrArg->getClass(), 0),
728                                     Info, Deduced, 0);
729    }
730
731    //     (clang extension)
732    //
733    //     type(^)(T)
734    //     T(^)()
735    //     T(^)(T)
736    case Type::BlockPointer: {
737      const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
738      const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
739
740      if (!BlockPtrArg)
741        return Sema::TDK_NonDeducedMismatch;
742
743      return DeduceTemplateArguments(Context, TemplateParams,
744                                     BlockPtrParam->getPointeeType(),
745                                     BlockPtrArg->getPointeeType(), Info,
746                                     Deduced, 0);
747    }
748
749    case Type::TypeOfExpr:
750    case Type::TypeOf:
751    case Type::Typename:
752      // No template argument deduction for these types
753      return Sema::TDK_Success;
754
755    default:
756      break;
757  }
758
759  // FIXME: Many more cases to go (to go).
760  return Sema::TDK_Success;
761}
762
763static Sema::TemplateDeductionResult
764DeduceTemplateArguments(ASTContext &Context,
765                        TemplateParameterList *TemplateParams,
766                        const TemplateArgument &Param,
767                        const TemplateArgument &Arg,
768                        Sema::TemplateDeductionInfo &Info,
769                        llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
770  switch (Param.getKind()) {
771  case TemplateArgument::Null:
772    assert(false && "Null template argument in parameter list");
773    break;
774
775  case TemplateArgument::Type:
776    if (Arg.getKind() == TemplateArgument::Type)
777      return DeduceTemplateArguments(Context, TemplateParams, Param.getAsType(),
778                                     Arg.getAsType(), Info, Deduced, 0);
779    Info.FirstArg = Param;
780    Info.SecondArg = Arg;
781    return Sema::TDK_NonDeducedMismatch;
782
783  case TemplateArgument::Template:
784    if (Arg.getKind() == TemplateArgument::Template)
785      return DeduceTemplateArguments(Context, TemplateParams,
786                                     Param.getAsTemplate(),
787                                     Arg.getAsTemplate(), Info, Deduced);
788    Info.FirstArg = Param;
789    Info.SecondArg = Arg;
790    return Sema::TDK_NonDeducedMismatch;
791
792  case TemplateArgument::Declaration:
793    if (Arg.getKind() == TemplateArgument::Declaration &&
794        Param.getAsDecl()->getCanonicalDecl() ==
795          Arg.getAsDecl()->getCanonicalDecl())
796      return Sema::TDK_Success;
797
798    Info.FirstArg = Param;
799    Info.SecondArg = Arg;
800    return Sema::TDK_NonDeducedMismatch;
801
802  case TemplateArgument::Integral:
803    if (Arg.getKind() == TemplateArgument::Integral) {
804      // FIXME: Zero extension + sign checking here?
805      if (*Param.getAsIntegral() == *Arg.getAsIntegral())
806        return Sema::TDK_Success;
807
808      Info.FirstArg = Param;
809      Info.SecondArg = Arg;
810      return Sema::TDK_NonDeducedMismatch;
811    }
812
813    if (Arg.getKind() == TemplateArgument::Expression) {
814      Info.FirstArg = Param;
815      Info.SecondArg = Arg;
816      return Sema::TDK_NonDeducedMismatch;
817    }
818
819    assert(false && "Type/value mismatch");
820    Info.FirstArg = Param;
821    Info.SecondArg = Arg;
822    return Sema::TDK_NonDeducedMismatch;
823
824  case TemplateArgument::Expression: {
825    if (NonTypeTemplateParmDecl *NTTP
826          = getDeducedParameterFromExpr(Param.getAsExpr())) {
827      if (Arg.getKind() == TemplateArgument::Integral)
828        // FIXME: Sign problems here
829        return DeduceNonTypeTemplateArgument(Context, NTTP,
830                                             *Arg.getAsIntegral(),
831                                             Info, Deduced);
832      if (Arg.getKind() == TemplateArgument::Expression)
833        return DeduceNonTypeTemplateArgument(Context, NTTP, Arg.getAsExpr(),
834                                             Info, Deduced);
835      if (Arg.getKind() == TemplateArgument::Declaration)
836        return DeduceNonTypeTemplateArgument(Context, NTTP, Arg.getAsDecl(),
837                                             Info, Deduced);
838
839      assert(false && "Type/value mismatch");
840      Info.FirstArg = Param;
841      Info.SecondArg = Arg;
842      return Sema::TDK_NonDeducedMismatch;
843    }
844
845    // Can't deduce anything, but that's okay.
846    return Sema::TDK_Success;
847  }
848  case TemplateArgument::Pack:
849    assert(0 && "FIXME: Implement!");
850    break;
851  }
852
853  return Sema::TDK_Success;
854}
855
856static Sema::TemplateDeductionResult
857DeduceTemplateArguments(ASTContext &Context,
858                        TemplateParameterList *TemplateParams,
859                        const TemplateArgumentList &ParamList,
860                        const TemplateArgumentList &ArgList,
861                        Sema::TemplateDeductionInfo &Info,
862                        llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
863  assert(ParamList.size() == ArgList.size());
864  for (unsigned I = 0, N = ParamList.size(); I != N; ++I) {
865    if (Sema::TemplateDeductionResult Result
866          = DeduceTemplateArguments(Context, TemplateParams,
867                                    ParamList[I], ArgList[I],
868                                    Info, Deduced))
869      return Result;
870  }
871  return Sema::TDK_Success;
872}
873
874/// \brief Determine whether two template arguments are the same.
875static bool isSameTemplateArg(ASTContext &Context,
876                              const TemplateArgument &X,
877                              const TemplateArgument &Y) {
878  if (X.getKind() != Y.getKind())
879    return false;
880
881  switch (X.getKind()) {
882    case TemplateArgument::Null:
883      assert(false && "Comparing NULL template argument");
884      break;
885
886    case TemplateArgument::Type:
887      return Context.getCanonicalType(X.getAsType()) ==
888             Context.getCanonicalType(Y.getAsType());
889
890    case TemplateArgument::Declaration:
891      return X.getAsDecl()->getCanonicalDecl() ==
892             Y.getAsDecl()->getCanonicalDecl();
893
894    case TemplateArgument::Template:
895      return Context.getCanonicalTemplateName(X.getAsTemplate())
896               .getAsVoidPointer() ==
897             Context.getCanonicalTemplateName(Y.getAsTemplate())
898               .getAsVoidPointer();
899
900    case TemplateArgument::Integral:
901      return *X.getAsIntegral() == *Y.getAsIntegral();
902
903    case TemplateArgument::Expression: {
904      llvm::FoldingSetNodeID XID, YID;
905      X.getAsExpr()->Profile(XID, Context, true);
906      Y.getAsExpr()->Profile(YID, Context, true);
907      return XID == YID;
908    }
909
910    case TemplateArgument::Pack:
911      if (X.pack_size() != Y.pack_size())
912        return false;
913
914      for (TemplateArgument::pack_iterator XP = X.pack_begin(),
915                                        XPEnd = X.pack_end(),
916                                           YP = Y.pack_begin();
917           XP != XPEnd; ++XP, ++YP)
918        if (!isSameTemplateArg(Context, *XP, *YP))
919          return false;
920
921      return true;
922  }
923
924  return false;
925}
926
927/// \brief Helper function to build a TemplateParameter when we don't
928/// know its type statically.
929static TemplateParameter makeTemplateParameter(Decl *D) {
930  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
931    return TemplateParameter(TTP);
932  else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
933    return TemplateParameter(NTTP);
934
935  return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
936}
937
938/// \brief Perform template argument deduction to determine whether
939/// the given template arguments match the given class template
940/// partial specialization per C++ [temp.class.spec.match].
941Sema::TemplateDeductionResult
942Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
943                              const TemplateArgumentList &TemplateArgs,
944                              TemplateDeductionInfo &Info) {
945  // C++ [temp.class.spec.match]p2:
946  //   A partial specialization matches a given actual template
947  //   argument list if the template arguments of the partial
948  //   specialization can be deduced from the actual template argument
949  //   list (14.8.2).
950  SFINAETrap Trap(*this);
951  llvm::SmallVector<TemplateArgument, 4> Deduced;
952  Deduced.resize(Partial->getTemplateParameters()->size());
953  if (TemplateDeductionResult Result
954        = ::DeduceTemplateArguments(Context,
955                                    Partial->getTemplateParameters(),
956                                    Partial->getTemplateArgs(),
957                                    TemplateArgs, Info, Deduced))
958    return Result;
959
960  InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
961                             Deduced.data(), Deduced.size());
962  if (Inst)
963    return TDK_InstantiationDepth;
964
965  // C++ [temp.deduct.type]p2:
966  //   [...] or if any template argument remains neither deduced nor
967  //   explicitly specified, template argument deduction fails.
968  TemplateArgumentListBuilder Builder(Partial->getTemplateParameters(),
969                                      Deduced.size());
970  for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
971    if (Deduced[I].isNull()) {
972      Decl *Param
973        = const_cast<NamedDecl *>(
974                                Partial->getTemplateParameters()->getParam(I));
975      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
976        Info.Param = TTP;
977      else if (NonTypeTemplateParmDecl *NTTP
978                 = dyn_cast<NonTypeTemplateParmDecl>(Param))
979        Info.Param = NTTP;
980      else
981        Info.Param = cast<TemplateTemplateParmDecl>(Param);
982      return TDK_Incomplete;
983    }
984
985    Builder.Append(Deduced[I]);
986  }
987
988  // Form the template argument list from the deduced template arguments.
989  TemplateArgumentList *DeducedArgumentList
990    = new (Context) TemplateArgumentList(Context, Builder, /*TakeArgs=*/true);
991  Info.reset(DeducedArgumentList);
992
993  // Substitute the deduced template arguments into the template
994  // arguments of the class template partial specialization, and
995  // verify that the instantiated template arguments are both valid
996  // and are equivalent to the template arguments originally provided
997  // to the class template.
998  ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
999  const TemplateArgumentLoc *PartialTemplateArgs
1000    = Partial->getTemplateArgsAsWritten();
1001  unsigned N = Partial->getNumTemplateArgsAsWritten();
1002
1003  // Note that we don't provide the langle and rangle locations.
1004  TemplateArgumentListInfo InstArgs;
1005
1006  for (unsigned I = 0; I != N; ++I) {
1007    Decl *Param = const_cast<NamedDecl *>(
1008                    ClassTemplate->getTemplateParameters()->getParam(I));
1009    TemplateArgumentLoc InstArg;
1010    if (Subst(PartialTemplateArgs[I], InstArg,
1011              MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1012      Info.Param = makeTemplateParameter(Param);
1013      Info.FirstArg = PartialTemplateArgs[I].getArgument();
1014      return TDK_SubstitutionFailure;
1015    }
1016    InstArgs.addArgument(InstArg);
1017  }
1018
1019  TemplateArgumentListBuilder ConvertedInstArgs(
1020                                  ClassTemplate->getTemplateParameters(), N);
1021
1022  if (CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
1023                                InstArgs, false, ConvertedInstArgs)) {
1024    // FIXME: fail with more useful information?
1025    return TDK_SubstitutionFailure;
1026  }
1027
1028  for (unsigned I = 0, E = ConvertedInstArgs.flatSize(); I != E; ++I) {
1029    TemplateArgument InstArg = ConvertedInstArgs.getFlatArguments()[I];
1030
1031    Decl *Param = const_cast<NamedDecl *>(
1032                    ClassTemplate->getTemplateParameters()->getParam(I));
1033
1034    if (InstArg.getKind() == TemplateArgument::Expression) {
1035      // When the argument is an expression, check the expression result
1036      // against the actual template parameter to get down to the canonical
1037      // template argument.
1038      Expr *InstExpr = InstArg.getAsExpr();
1039      if (NonTypeTemplateParmDecl *NTTP
1040            = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1041        if (CheckTemplateArgument(NTTP, NTTP->getType(), InstExpr, InstArg)) {
1042          Info.Param = makeTemplateParameter(Param);
1043          Info.FirstArg = Partial->getTemplateArgs()[I];
1044          return TDK_SubstitutionFailure;
1045        }
1046      }
1047    }
1048
1049    if (!isSameTemplateArg(Context, TemplateArgs[I], InstArg)) {
1050      Info.Param = makeTemplateParameter(Param);
1051      Info.FirstArg = TemplateArgs[I];
1052      Info.SecondArg = InstArg;
1053      return TDK_NonDeducedMismatch;
1054    }
1055  }
1056
1057  if (Trap.hasErrorOccurred())
1058    return TDK_SubstitutionFailure;
1059
1060  return TDK_Success;
1061}
1062
1063/// \brief Determine whether the given type T is a simple-template-id type.
1064static bool isSimpleTemplateIdType(QualType T) {
1065  if (const TemplateSpecializationType *Spec
1066        = T->getAs<TemplateSpecializationType>())
1067    return Spec->getTemplateName().getAsTemplateDecl() != 0;
1068
1069  return false;
1070}
1071
1072/// \brief Substitute the explicitly-provided template arguments into the
1073/// given function template according to C++ [temp.arg.explicit].
1074///
1075/// \param FunctionTemplate the function template into which the explicit
1076/// template arguments will be substituted.
1077///
1078/// \param ExplicitTemplateArguments the explicitly-specified template
1079/// arguments.
1080///
1081/// \param Deduced the deduced template arguments, which will be populated
1082/// with the converted and checked explicit template arguments.
1083///
1084/// \param ParamTypes will be populated with the instantiated function
1085/// parameters.
1086///
1087/// \param FunctionType if non-NULL, the result type of the function template
1088/// will also be instantiated and the pointed-to value will be updated with
1089/// the instantiated function type.
1090///
1091/// \param Info if substitution fails for any reason, this object will be
1092/// populated with more information about the failure.
1093///
1094/// \returns TDK_Success if substitution was successful, or some failure
1095/// condition.
1096Sema::TemplateDeductionResult
1097Sema::SubstituteExplicitTemplateArguments(
1098                                      FunctionTemplateDecl *FunctionTemplate,
1099                        const TemplateArgumentListInfo &ExplicitTemplateArgs,
1100                            llvm::SmallVectorImpl<TemplateArgument> &Deduced,
1101                                 llvm::SmallVectorImpl<QualType> &ParamTypes,
1102                                          QualType *FunctionType,
1103                                          TemplateDeductionInfo &Info) {
1104  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1105  TemplateParameterList *TemplateParams
1106    = FunctionTemplate->getTemplateParameters();
1107
1108  if (ExplicitTemplateArgs.size() == 0) {
1109    // No arguments to substitute; just copy over the parameter types and
1110    // fill in the function type.
1111    for (FunctionDecl::param_iterator P = Function->param_begin(),
1112                                   PEnd = Function->param_end();
1113         P != PEnd;
1114         ++P)
1115      ParamTypes.push_back((*P)->getType());
1116
1117    if (FunctionType)
1118      *FunctionType = Function->getType();
1119    return TDK_Success;
1120  }
1121
1122  // Substitution of the explicit template arguments into a function template
1123  /// is a SFINAE context. Trap any errors that might occur.
1124  SFINAETrap Trap(*this);
1125
1126  // C++ [temp.arg.explicit]p3:
1127  //   Template arguments that are present shall be specified in the
1128  //   declaration order of their corresponding template-parameters. The
1129  //   template argument list shall not specify more template-arguments than
1130  //   there are corresponding template-parameters.
1131  TemplateArgumentListBuilder Builder(TemplateParams,
1132                                      ExplicitTemplateArgs.size());
1133
1134  // Enter a new template instantiation context where we check the
1135  // explicitly-specified template arguments against this function template,
1136  // and then substitute them into the function parameter types.
1137  InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
1138                             FunctionTemplate, Deduced.data(), Deduced.size(),
1139           ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution);
1140  if (Inst)
1141    return TDK_InstantiationDepth;
1142
1143  if (CheckTemplateArgumentList(FunctionTemplate,
1144                                SourceLocation(),
1145                                ExplicitTemplateArgs,
1146                                true,
1147                                Builder) || Trap.hasErrorOccurred())
1148    return TDK_InvalidExplicitArguments;
1149
1150  // Form the template argument list from the explicitly-specified
1151  // template arguments.
1152  TemplateArgumentList *ExplicitArgumentList
1153    = new (Context) TemplateArgumentList(Context, Builder, /*TakeArgs=*/true);
1154  Info.reset(ExplicitArgumentList);
1155
1156  // Instantiate the types of each of the function parameters given the
1157  // explicitly-specified template arguments.
1158  for (FunctionDecl::param_iterator P = Function->param_begin(),
1159                                PEnd = Function->param_end();
1160       P != PEnd;
1161       ++P) {
1162    QualType ParamType
1163      = SubstType((*P)->getType(),
1164                  MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1165                  (*P)->getLocation(), (*P)->getDeclName());
1166    if (ParamType.isNull() || Trap.hasErrorOccurred())
1167      return TDK_SubstitutionFailure;
1168
1169    ParamTypes.push_back(ParamType);
1170  }
1171
1172  // If the caller wants a full function type back, instantiate the return
1173  // type and form that function type.
1174  if (FunctionType) {
1175    // FIXME: exception-specifications?
1176    const FunctionProtoType *Proto
1177      = Function->getType()->getAs<FunctionProtoType>();
1178    assert(Proto && "Function template does not have a prototype?");
1179
1180    QualType ResultType
1181      = SubstType(Proto->getResultType(),
1182                  MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1183                  Function->getTypeSpecStartLoc(),
1184                  Function->getDeclName());
1185    if (ResultType.isNull() || Trap.hasErrorOccurred())
1186      return TDK_SubstitutionFailure;
1187
1188    *FunctionType = BuildFunctionType(ResultType,
1189                                      ParamTypes.data(), ParamTypes.size(),
1190                                      Proto->isVariadic(),
1191                                      Proto->getTypeQuals(),
1192                                      Function->getLocation(),
1193                                      Function->getDeclName());
1194    if (FunctionType->isNull() || Trap.hasErrorOccurred())
1195      return TDK_SubstitutionFailure;
1196  }
1197
1198  // C++ [temp.arg.explicit]p2:
1199  //   Trailing template arguments that can be deduced (14.8.2) may be
1200  //   omitted from the list of explicit template-arguments. If all of the
1201  //   template arguments can be deduced, they may all be omitted; in this
1202  //   case, the empty template argument list <> itself may also be omitted.
1203  //
1204  // Take all of the explicitly-specified arguments and put them into the
1205  // set of deduced template arguments.
1206  Deduced.reserve(TemplateParams->size());
1207  for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
1208    Deduced.push_back(ExplicitArgumentList->get(I));
1209
1210  return TDK_Success;
1211}
1212
1213/// \brief Finish template argument deduction for a function template,
1214/// checking the deduced template arguments for completeness and forming
1215/// the function template specialization.
1216Sema::TemplateDeductionResult
1217Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
1218                            llvm::SmallVectorImpl<TemplateArgument> &Deduced,
1219                                      FunctionDecl *&Specialization,
1220                                      TemplateDeductionInfo &Info) {
1221  TemplateParameterList *TemplateParams
1222    = FunctionTemplate->getTemplateParameters();
1223
1224  // Template argument deduction for function templates in a SFINAE context.
1225  // Trap any errors that might occur.
1226  SFINAETrap Trap(*this);
1227
1228  // Enter a new template instantiation context while we instantiate the
1229  // actual function declaration.
1230  InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
1231                             FunctionTemplate, Deduced.data(), Deduced.size(),
1232              ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution);
1233  if (Inst)
1234    return TDK_InstantiationDepth;
1235
1236  // C++ [temp.deduct.type]p2:
1237  //   [...] or if any template argument remains neither deduced nor
1238  //   explicitly specified, template argument deduction fails.
1239  TemplateArgumentListBuilder Builder(TemplateParams, Deduced.size());
1240  for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
1241    if (!Deduced[I].isNull()) {
1242      Builder.Append(Deduced[I]);
1243      continue;
1244    }
1245
1246    // Substitute into the default template argument, if available.
1247    NamedDecl *Param = FunctionTemplate->getTemplateParameters()->getParam(I);
1248    TemplateArgumentLoc DefArg
1249      = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
1250                                              FunctionTemplate->getLocation(),
1251                                  FunctionTemplate->getSourceRange().getEnd(),
1252                                                Param,
1253                                                Builder);
1254
1255    // If there was no default argument, deduction is incomplete.
1256    if (DefArg.getArgument().isNull()) {
1257      Info.Param = makeTemplateParameter(
1258                         const_cast<NamedDecl *>(TemplateParams->getParam(I)));
1259      return TDK_Incomplete;
1260    }
1261
1262    // Check whether we can actually use the default argument.
1263    if (CheckTemplateArgument(Param, DefArg,
1264                              FunctionTemplate,
1265                              FunctionTemplate->getLocation(),
1266                              FunctionTemplate->getSourceRange().getEnd(),
1267                              Builder)) {
1268      Info.Param = makeTemplateParameter(
1269                         const_cast<NamedDecl *>(TemplateParams->getParam(I)));
1270      return TDK_SubstitutionFailure;
1271    }
1272
1273    // If we get here, we successfully used the default template argument.
1274  }
1275
1276  // Form the template argument list from the deduced template arguments.
1277  TemplateArgumentList *DeducedArgumentList
1278    = new (Context) TemplateArgumentList(Context, Builder, /*TakeArgs=*/true);
1279  Info.reset(DeducedArgumentList);
1280
1281  // Substitute the deduced template arguments into the function template
1282  // declaration to produce the function template specialization.
1283  Specialization = cast_or_null<FunctionDecl>(
1284                      SubstDecl(FunctionTemplate->getTemplatedDecl(),
1285                                FunctionTemplate->getDeclContext(),
1286                         MultiLevelTemplateArgumentList(*DeducedArgumentList)));
1287  if (!Specialization)
1288    return TDK_SubstitutionFailure;
1289
1290  assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
1291         FunctionTemplate->getCanonicalDecl());
1292
1293  // If the template argument list is owned by the function template
1294  // specialization, release it.
1295  if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList)
1296    Info.take();
1297
1298  // There may have been an error that did not prevent us from constructing a
1299  // declaration. Mark the declaration invalid and return with a substitution
1300  // failure.
1301  if (Trap.hasErrorOccurred()) {
1302    Specialization->setInvalidDecl(true);
1303    return TDK_SubstitutionFailure;
1304  }
1305
1306  return TDK_Success;
1307}
1308
1309/// \brief Perform template argument deduction from a function call
1310/// (C++ [temp.deduct.call]).
1311///
1312/// \param FunctionTemplate the function template for which we are performing
1313/// template argument deduction.
1314///
1315/// \param ExplicitTemplateArguments the explicit template arguments provided
1316/// for this call.
1317///
1318/// \param Args the function call arguments
1319///
1320/// \param NumArgs the number of arguments in Args
1321///
1322/// \param Name the name of the function being called. This is only significant
1323/// when the function template is a conversion function template, in which
1324/// case this routine will also perform template argument deduction based on
1325/// the function to which
1326///
1327/// \param Specialization if template argument deduction was successful,
1328/// this will be set to the function template specialization produced by
1329/// template argument deduction.
1330///
1331/// \param Info the argument will be updated to provide additional information
1332/// about template argument deduction.
1333///
1334/// \returns the result of template argument deduction.
1335Sema::TemplateDeductionResult
1336Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
1337                          const TemplateArgumentListInfo *ExplicitTemplateArgs,
1338                              Expr **Args, unsigned NumArgs,
1339                              FunctionDecl *&Specialization,
1340                              TemplateDeductionInfo &Info) {
1341  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1342
1343  // C++ [temp.deduct.call]p1:
1344  //   Template argument deduction is done by comparing each function template
1345  //   parameter type (call it P) with the type of the corresponding argument
1346  //   of the call (call it A) as described below.
1347  unsigned CheckArgs = NumArgs;
1348  if (NumArgs < Function->getMinRequiredArguments())
1349    return TDK_TooFewArguments;
1350  else if (NumArgs > Function->getNumParams()) {
1351    const FunctionProtoType *Proto
1352      = Function->getType()->getAs<FunctionProtoType>();
1353    if (!Proto->isVariadic())
1354      return TDK_TooManyArguments;
1355
1356    CheckArgs = Function->getNumParams();
1357  }
1358
1359  // The types of the parameters from which we will perform template argument
1360  // deduction.
1361  TemplateParameterList *TemplateParams
1362    = FunctionTemplate->getTemplateParameters();
1363  llvm::SmallVector<TemplateArgument, 4> Deduced;
1364  llvm::SmallVector<QualType, 4> ParamTypes;
1365  if (ExplicitTemplateArgs) {
1366    TemplateDeductionResult Result =
1367      SubstituteExplicitTemplateArguments(FunctionTemplate,
1368                                          *ExplicitTemplateArgs,
1369                                          Deduced,
1370                                          ParamTypes,
1371                                          0,
1372                                          Info);
1373    if (Result)
1374      return Result;
1375  } else {
1376    // Just fill in the parameter types from the function declaration.
1377    for (unsigned I = 0; I != CheckArgs; ++I)
1378      ParamTypes.push_back(Function->getParamDecl(I)->getType());
1379  }
1380
1381  // Deduce template arguments from the function parameters.
1382  Deduced.resize(TemplateParams->size());
1383  for (unsigned I = 0; I != CheckArgs; ++I) {
1384    QualType ParamType = ParamTypes[I];
1385    QualType ArgType = Args[I]->getType();
1386
1387    // C++ [temp.deduct.call]p2:
1388    //   If P is not a reference type:
1389    QualType CanonParamType = Context.getCanonicalType(ParamType);
1390    bool ParamWasReference = isa<ReferenceType>(CanonParamType);
1391    if (!ParamWasReference) {
1392      //   - If A is an array type, the pointer type produced by the
1393      //     array-to-pointer standard conversion (4.2) is used in place of
1394      //     A for type deduction; otherwise,
1395      if (ArgType->isArrayType())
1396        ArgType = Context.getArrayDecayedType(ArgType);
1397      //   - If A is a function type, the pointer type produced by the
1398      //     function-to-pointer standard conversion (4.3) is used in place
1399      //     of A for type deduction; otherwise,
1400      else if (ArgType->isFunctionType())
1401        ArgType = Context.getPointerType(ArgType);
1402      else {
1403        // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
1404        //   type are ignored for type deduction.
1405        QualType CanonArgType = Context.getCanonicalType(ArgType);
1406        if (CanonArgType.getLocalCVRQualifiers())
1407          ArgType = CanonArgType.getLocalUnqualifiedType();
1408      }
1409    }
1410
1411    // C++0x [temp.deduct.call]p3:
1412    //   If P is a cv-qualified type, the top level cv-qualifiers of P’s type
1413    //   are ignored for type deduction.
1414    if (CanonParamType.getLocalCVRQualifiers())
1415      ParamType = CanonParamType.getLocalUnqualifiedType();
1416    if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
1417      //   [...] If P is a reference type, the type referred to by P is used
1418      //   for type deduction.
1419      ParamType = ParamRefType->getPointeeType();
1420
1421      //   [...] If P is of the form T&&, where T is a template parameter, and
1422      //   the argument is an lvalue, the type A& is used in place of A for
1423      //   type deduction.
1424      if (isa<RValueReferenceType>(ParamRefType) &&
1425          ParamRefType->getAs<TemplateTypeParmType>() &&
1426          Args[I]->isLvalue(Context) == Expr::LV_Valid)
1427        ArgType = Context.getLValueReferenceType(ArgType);
1428    }
1429
1430    // C++0x [temp.deduct.call]p4:
1431    //   In general, the deduction process attempts to find template argument
1432    //   values that will make the deduced A identical to A (after the type A
1433    //   is transformed as described above). [...]
1434    unsigned TDF = TDF_SkipNonDependent;
1435
1436    //     - If the original P is a reference type, the deduced A (i.e., the
1437    //       type referred to by the reference) can be more cv-qualified than
1438    //       the transformed A.
1439    if (ParamWasReference)
1440      TDF |= TDF_ParamWithReferenceType;
1441    //     - The transformed A can be another pointer or pointer to member
1442    //       type that can be converted to the deduced A via a qualification
1443    //       conversion (4.4).
1444    if (ArgType->isPointerType() || ArgType->isMemberPointerType())
1445      TDF |= TDF_IgnoreQualifiers;
1446    //     - If P is a class and P has the form simple-template-id, then the
1447    //       transformed A can be a derived class of the deduced A. Likewise,
1448    //       if P is a pointer to a class of the form simple-template-id, the
1449    //       transformed A can be a pointer to a derived class pointed to by
1450    //       the deduced A.
1451    if (isSimpleTemplateIdType(ParamType) ||
1452        (isa<PointerType>(ParamType) &&
1453         isSimpleTemplateIdType(
1454                              ParamType->getAs<PointerType>()->getPointeeType())))
1455      TDF |= TDF_DerivedClass;
1456
1457    // FIXME: C++0x [temp.deduct.call] paragraphs 6-9 deal with function
1458    // pointer parameters.
1459
1460    if (Context.hasSameUnqualifiedType(ArgType, Context.OverloadTy)) {
1461      // We know that template argument deduction will fail if the argument is
1462      // still an overloaded function. Check whether we can resolve this
1463      // argument as a single function template specialization per
1464      // C++ [temp.arg.explicit]p3.
1465      FunctionDecl *ExplicitSpec
1466        = ResolveSingleFunctionTemplateSpecialization(Args[I]);
1467      Expr *ResolvedArg = 0;
1468      if (ExplicitSpec)
1469        ResolvedArg = FixOverloadedFunctionReference(Args[I], ExplicitSpec);
1470      if (!ExplicitSpec || !ResolvedArg) {
1471        // Template argument deduction fails if we can't resolve the overloaded
1472        // function.
1473        return TDK_FailedOverloadResolution;
1474      }
1475
1476      // Get the type of the resolved argument, and adjust it per
1477      // C++0x [temp.deduct.call]p3.
1478      ArgType = ResolvedArg->getType();
1479      if (!ParamWasReference && ArgType->isFunctionType())
1480        ArgType = Context.getPointerType(ArgType);
1481      if (ArgType->isPointerType() || ArgType->isMemberPointerType())
1482        TDF |= TDF_IgnoreQualifiers;
1483
1484      ResolvedArg->Destroy(Context);
1485    }
1486
1487    if (TemplateDeductionResult Result
1488        = ::DeduceTemplateArguments(Context, TemplateParams,
1489                                    ParamType, ArgType, Info, Deduced,
1490                                    TDF))
1491      return Result;
1492
1493    // FIXME: we need to check that the deduced A is the same as A,
1494    // modulo the various allowed differences.
1495  }
1496
1497  return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
1498                                         Specialization, Info);
1499}
1500
1501/// \brief Deduce template arguments when taking the address of a function
1502/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
1503/// a template.
1504///
1505/// \param FunctionTemplate the function template for which we are performing
1506/// template argument deduction.
1507///
1508/// \param ExplicitTemplateArguments the explicitly-specified template
1509/// arguments.
1510///
1511/// \param ArgFunctionType the function type that will be used as the
1512/// "argument" type (A) when performing template argument deduction from the
1513/// function template's function type. This type may be NULL, if there is no
1514/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
1515///
1516/// \param Specialization if template argument deduction was successful,
1517/// this will be set to the function template specialization produced by
1518/// template argument deduction.
1519///
1520/// \param Info the argument will be updated to provide additional information
1521/// about template argument deduction.
1522///
1523/// \returns the result of template argument deduction.
1524Sema::TemplateDeductionResult
1525Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
1526                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
1527                              QualType ArgFunctionType,
1528                              FunctionDecl *&Specialization,
1529                              TemplateDeductionInfo &Info) {
1530  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1531  TemplateParameterList *TemplateParams
1532    = FunctionTemplate->getTemplateParameters();
1533  QualType FunctionType = Function->getType();
1534
1535  // Substitute any explicit template arguments.
1536  llvm::SmallVector<TemplateArgument, 4> Deduced;
1537  llvm::SmallVector<QualType, 4> ParamTypes;
1538  if (ExplicitTemplateArgs) {
1539    if (TemplateDeductionResult Result
1540          = SubstituteExplicitTemplateArguments(FunctionTemplate,
1541                                                *ExplicitTemplateArgs,
1542                                                Deduced, ParamTypes,
1543                                                &FunctionType, Info))
1544      return Result;
1545  }
1546
1547  // Template argument deduction for function templates in a SFINAE context.
1548  // Trap any errors that might occur.
1549  SFINAETrap Trap(*this);
1550
1551  if (!ArgFunctionType.isNull()) {
1552    // Deduce template arguments from the function type.
1553    Deduced.resize(TemplateParams->size());
1554    if (TemplateDeductionResult Result
1555          = ::DeduceTemplateArguments(Context, TemplateParams,
1556                                      FunctionType, ArgFunctionType, Info,
1557                                      Deduced, 0))
1558      return Result;
1559  }
1560
1561  return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
1562                                         Specialization, Info);
1563}
1564
1565/// \brief Deduce template arguments for a templated conversion
1566/// function (C++ [temp.deduct.conv]) and, if successful, produce a
1567/// conversion function template specialization.
1568Sema::TemplateDeductionResult
1569Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
1570                              QualType ToType,
1571                              CXXConversionDecl *&Specialization,
1572                              TemplateDeductionInfo &Info) {
1573  CXXConversionDecl *Conv
1574    = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
1575  QualType FromType = Conv->getConversionType();
1576
1577  // Canonicalize the types for deduction.
1578  QualType P = Context.getCanonicalType(FromType);
1579  QualType A = Context.getCanonicalType(ToType);
1580
1581  // C++0x [temp.deduct.conv]p3:
1582  //   If P is a reference type, the type referred to by P is used for
1583  //   type deduction.
1584  if (const ReferenceType *PRef = P->getAs<ReferenceType>())
1585    P = PRef->getPointeeType();
1586
1587  // C++0x [temp.deduct.conv]p3:
1588  //   If A is a reference type, the type referred to by A is used
1589  //   for type deduction.
1590  if (const ReferenceType *ARef = A->getAs<ReferenceType>())
1591    A = ARef->getPointeeType();
1592  // C++ [temp.deduct.conv]p2:
1593  //
1594  //   If A is not a reference type:
1595  else {
1596    assert(!A->isReferenceType() && "Reference types were handled above");
1597
1598    //   - If P is an array type, the pointer type produced by the
1599    //     array-to-pointer standard conversion (4.2) is used in place
1600    //     of P for type deduction; otherwise,
1601    if (P->isArrayType())
1602      P = Context.getArrayDecayedType(P);
1603    //   - If P is a function type, the pointer type produced by the
1604    //     function-to-pointer standard conversion (4.3) is used in
1605    //     place of P for type deduction; otherwise,
1606    else if (P->isFunctionType())
1607      P = Context.getPointerType(P);
1608    //   - If P is a cv-qualified type, the top level cv-qualifiers of
1609    //     P’s type are ignored for type deduction.
1610    else
1611      P = P.getUnqualifiedType();
1612
1613    // C++0x [temp.deduct.conv]p3:
1614    //   If A is a cv-qualified type, the top level cv-qualifiers of A’s
1615    //   type are ignored for type deduction.
1616    A = A.getUnqualifiedType();
1617  }
1618
1619  // Template argument deduction for function templates in a SFINAE context.
1620  // Trap any errors that might occur.
1621  SFINAETrap Trap(*this);
1622
1623  // C++ [temp.deduct.conv]p1:
1624  //   Template argument deduction is done by comparing the return
1625  //   type of the template conversion function (call it P) with the
1626  //   type that is required as the result of the conversion (call it
1627  //   A) as described in 14.8.2.4.
1628  TemplateParameterList *TemplateParams
1629    = FunctionTemplate->getTemplateParameters();
1630  llvm::SmallVector<TemplateArgument, 4> Deduced;
1631  Deduced.resize(TemplateParams->size());
1632
1633  // C++0x [temp.deduct.conv]p4:
1634  //   In general, the deduction process attempts to find template
1635  //   argument values that will make the deduced A identical to
1636  //   A. However, there are two cases that allow a difference:
1637  unsigned TDF = 0;
1638  //     - If the original A is a reference type, A can be more
1639  //       cv-qualified than the deduced A (i.e., the type referred to
1640  //       by the reference)
1641  if (ToType->isReferenceType())
1642    TDF |= TDF_ParamWithReferenceType;
1643  //     - The deduced A can be another pointer or pointer to member
1644  //       type that can be converted to A via a qualification
1645  //       conversion.
1646  //
1647  // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
1648  // both P and A are pointers or member pointers. In this case, we
1649  // just ignore cv-qualifiers completely).
1650  if ((P->isPointerType() && A->isPointerType()) ||
1651      (P->isMemberPointerType() && P->isMemberPointerType()))
1652    TDF |= TDF_IgnoreQualifiers;
1653  if (TemplateDeductionResult Result
1654        = ::DeduceTemplateArguments(Context, TemplateParams,
1655                                    P, A, Info, Deduced, TDF))
1656    return Result;
1657
1658  // FIXME: we need to check that the deduced A is the same as A,
1659  // modulo the various allowed differences.
1660
1661  // Finish template argument deduction.
1662  FunctionDecl *Spec = 0;
1663  TemplateDeductionResult Result
1664    = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, Spec, Info);
1665  Specialization = cast_or_null<CXXConversionDecl>(Spec);
1666  return Result;
1667}
1668
1669/// \brief Deduce template arguments for a function template when there is
1670/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
1671///
1672/// \param FunctionTemplate the function template for which we are performing
1673/// template argument deduction.
1674///
1675/// \param ExplicitTemplateArguments the explicitly-specified template
1676/// arguments.
1677///
1678/// \param Specialization if template argument deduction was successful,
1679/// this will be set to the function template specialization produced by
1680/// template argument deduction.
1681///
1682/// \param Info the argument will be updated to provide additional information
1683/// about template argument deduction.
1684///
1685/// \returns the result of template argument deduction.
1686Sema::TemplateDeductionResult
1687Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
1688                           const TemplateArgumentListInfo *ExplicitTemplateArgs,
1689                              FunctionDecl *&Specialization,
1690                              TemplateDeductionInfo &Info) {
1691  return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
1692                                 QualType(), Specialization, Info);
1693}
1694
1695/// \brief Stores the result of comparing the qualifiers of two types.
1696enum DeductionQualifierComparison {
1697  NeitherMoreQualified = 0,
1698  ParamMoreQualified,
1699  ArgMoreQualified
1700};
1701
1702/// \brief Deduce the template arguments during partial ordering by comparing
1703/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
1704///
1705/// \param Context the AST context in which this deduction occurs.
1706///
1707/// \param TemplateParams the template parameters that we are deducing
1708///
1709/// \param ParamIn the parameter type
1710///
1711/// \param ArgIn the argument type
1712///
1713/// \param Info information about the template argument deduction itself
1714///
1715/// \param Deduced the deduced template arguments
1716///
1717/// \returns the result of template argument deduction so far. Note that a
1718/// "success" result means that template argument deduction has not yet failed,
1719/// but it may still fail, later, for other reasons.
1720static Sema::TemplateDeductionResult
1721DeduceTemplateArgumentsDuringPartialOrdering(ASTContext &Context,
1722                                          TemplateParameterList *TemplateParams,
1723                                             QualType ParamIn, QualType ArgIn,
1724                                             Sema::TemplateDeductionInfo &Info,
1725                             llvm::SmallVectorImpl<TemplateArgument> &Deduced,
1726    llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
1727  CanQualType Param = Context.getCanonicalType(ParamIn);
1728  CanQualType Arg = Context.getCanonicalType(ArgIn);
1729
1730  // C++0x [temp.deduct.partial]p5:
1731  //   Before the partial ordering is done, certain transformations are
1732  //   performed on the types used for partial ordering:
1733  //     - If P is a reference type, P is replaced by the type referred to.
1734  CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
1735  if (!ParamRef.isNull())
1736    Param = ParamRef->getPointeeType();
1737
1738  //     - If A is a reference type, A is replaced by the type referred to.
1739  CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
1740  if (!ArgRef.isNull())
1741    Arg = ArgRef->getPointeeType();
1742
1743  if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
1744    // C++0x [temp.deduct.partial]p6:
1745    //   If both P and A were reference types (before being replaced with the
1746    //   type referred to above), determine which of the two types (if any) is
1747    //   more cv-qualified than the other; otherwise the types are considered to
1748    //   be equally cv-qualified for partial ordering purposes. The result of this
1749    //   determination will be used below.
1750    //
1751    // We save this information for later, using it only when deduction
1752    // succeeds in both directions.
1753    DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
1754    if (Param.isMoreQualifiedThan(Arg))
1755      QualifierResult = ParamMoreQualified;
1756    else if (Arg.isMoreQualifiedThan(Param))
1757      QualifierResult = ArgMoreQualified;
1758    QualifierComparisons->push_back(QualifierResult);
1759  }
1760
1761  // C++0x [temp.deduct.partial]p7:
1762  //   Remove any top-level cv-qualifiers:
1763  //     - If P is a cv-qualified type, P is replaced by the cv-unqualified
1764  //       version of P.
1765  Param = Param.getUnqualifiedType();
1766  //     - If A is a cv-qualified type, A is replaced by the cv-unqualified
1767  //       version of A.
1768  Arg = Arg.getUnqualifiedType();
1769
1770  // C++0x [temp.deduct.partial]p8:
1771  //   Using the resulting types P and A the deduction is then done as
1772  //   described in 14.9.2.5. If deduction succeeds for a given type, the type
1773  //   from the argument template is considered to be at least as specialized
1774  //   as the type from the parameter template.
1775  return DeduceTemplateArguments(Context, TemplateParams, Param, Arg, Info,
1776                                 Deduced, TDF_None);
1777}
1778
1779static void
1780MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
1781                           bool OnlyDeduced,
1782                           unsigned Level,
1783                           llvm::SmallVectorImpl<bool> &Deduced);
1784
1785/// \brief Determine whether the function template \p FT1 is at least as
1786/// specialized as \p FT2.
1787static bool isAtLeastAsSpecializedAs(Sema &S,
1788                                     FunctionTemplateDecl *FT1,
1789                                     FunctionTemplateDecl *FT2,
1790                                     TemplatePartialOrderingContext TPOC,
1791    llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
1792  FunctionDecl *FD1 = FT1->getTemplatedDecl();
1793  FunctionDecl *FD2 = FT2->getTemplatedDecl();
1794  const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
1795  const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
1796
1797  assert(Proto1 && Proto2 && "Function templates must have prototypes");
1798  TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
1799  llvm::SmallVector<TemplateArgument, 4> Deduced;
1800  Deduced.resize(TemplateParams->size());
1801
1802  // C++0x [temp.deduct.partial]p3:
1803  //   The types used to determine the ordering depend on the context in which
1804  //   the partial ordering is done:
1805  Sema::TemplateDeductionInfo Info(S.Context);
1806  switch (TPOC) {
1807  case TPOC_Call: {
1808    //   - In the context of a function call, the function parameter types are
1809    //     used.
1810    unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
1811    for (unsigned I = 0; I != NumParams; ++I)
1812      if (DeduceTemplateArgumentsDuringPartialOrdering(S.Context,
1813                                                       TemplateParams,
1814                                                       Proto2->getArgType(I),
1815                                                       Proto1->getArgType(I),
1816                                                       Info,
1817                                                       Deduced,
1818                                                       QualifierComparisons))
1819        return false;
1820
1821    break;
1822  }
1823
1824  case TPOC_Conversion:
1825    //   - In the context of a call to a conversion operator, the return types
1826    //     of the conversion function templates are used.
1827    if (DeduceTemplateArgumentsDuringPartialOrdering(S.Context,
1828                                                     TemplateParams,
1829                                                     Proto2->getResultType(),
1830                                                     Proto1->getResultType(),
1831                                                     Info,
1832                                                     Deduced,
1833                                                     QualifierComparisons))
1834      return false;
1835    break;
1836
1837  case TPOC_Other:
1838    //   - In other contexts (14.6.6.2) the function template’s function type
1839    //     is used.
1840    if (DeduceTemplateArgumentsDuringPartialOrdering(S.Context,
1841                                                     TemplateParams,
1842                                                     FD2->getType(),
1843                                                     FD1->getType(),
1844                                                     Info,
1845                                                     Deduced,
1846                                                     QualifierComparisons))
1847      return false;
1848    break;
1849  }
1850
1851  // C++0x [temp.deduct.partial]p11:
1852  //   In most cases, all template parameters must have values in order for
1853  //   deduction to succeed, but for partial ordering purposes a template
1854  //   parameter may remain without a value provided it is not used in the
1855  //   types being used for partial ordering. [ Note: a template parameter used
1856  //   in a non-deduced context is considered used. -end note]
1857  unsigned ArgIdx = 0, NumArgs = Deduced.size();
1858  for (; ArgIdx != NumArgs; ++ArgIdx)
1859    if (Deduced[ArgIdx].isNull())
1860      break;
1861
1862  if (ArgIdx == NumArgs) {
1863    // All template arguments were deduced. FT1 is at least as specialized
1864    // as FT2.
1865    return true;
1866  }
1867
1868  // Figure out which template parameters were used.
1869  llvm::SmallVector<bool, 4> UsedParameters;
1870  UsedParameters.resize(TemplateParams->size());
1871  switch (TPOC) {
1872  case TPOC_Call: {
1873    unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
1874    for (unsigned I = 0; I != NumParams; ++I)
1875      ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
1876                                   TemplateParams->getDepth(),
1877                                   UsedParameters);
1878    break;
1879  }
1880
1881  case TPOC_Conversion:
1882    ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
1883                                 TemplateParams->getDepth(),
1884                                 UsedParameters);
1885    break;
1886
1887  case TPOC_Other:
1888    ::MarkUsedTemplateParameters(S, FD2->getType(), false,
1889                                 TemplateParams->getDepth(),
1890                                 UsedParameters);
1891    break;
1892  }
1893
1894  for (; ArgIdx != NumArgs; ++ArgIdx)
1895    // If this argument had no value deduced but was used in one of the types
1896    // used for partial ordering, then deduction fails.
1897    if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
1898      return false;
1899
1900  return true;
1901}
1902
1903
1904/// \brief Returns the more specialized function template according
1905/// to the rules of function template partial ordering (C++ [temp.func.order]).
1906///
1907/// \param FT1 the first function template
1908///
1909/// \param FT2 the second function template
1910///
1911/// \param TPOC the context in which we are performing partial ordering of
1912/// function templates.
1913///
1914/// \returns the more specialized function template. If neither
1915/// template is more specialized, returns NULL.
1916FunctionTemplateDecl *
1917Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
1918                                 FunctionTemplateDecl *FT2,
1919                                 TemplatePartialOrderingContext TPOC) {
1920  llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
1921  bool Better1 = isAtLeastAsSpecializedAs(*this, FT1, FT2, TPOC, 0);
1922  bool Better2 = isAtLeastAsSpecializedAs(*this, FT2, FT1, TPOC,
1923                                          &QualifierComparisons);
1924
1925  if (Better1 != Better2) // We have a clear winner
1926    return Better1? FT1 : FT2;
1927
1928  if (!Better1 && !Better2) // Neither is better than the other
1929    return 0;
1930
1931
1932  // C++0x [temp.deduct.partial]p10:
1933  //   If for each type being considered a given template is at least as
1934  //   specialized for all types and more specialized for some set of types and
1935  //   the other template is not more specialized for any types or is not at
1936  //   least as specialized for any types, then the given template is more
1937  //   specialized than the other template. Otherwise, neither template is more
1938  //   specialized than the other.
1939  Better1 = false;
1940  Better2 = false;
1941  for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
1942    // C++0x [temp.deduct.partial]p9:
1943    //   If, for a given type, deduction succeeds in both directions (i.e., the
1944    //   types are identical after the transformations above) and if the type
1945    //   from the argument template is more cv-qualified than the type from the
1946    //   parameter template (as described above) that type is considered to be
1947    //   more specialized than the other. If neither type is more cv-qualified
1948    //   than the other then neither type is more specialized than the other.
1949    switch (QualifierComparisons[I]) {
1950      case NeitherMoreQualified:
1951        break;
1952
1953      case ParamMoreQualified:
1954        Better1 = true;
1955        if (Better2)
1956          return 0;
1957        break;
1958
1959      case ArgMoreQualified:
1960        Better2 = true;
1961        if (Better1)
1962          return 0;
1963        break;
1964    }
1965  }
1966
1967  assert(!(Better1 && Better2) && "Should have broken out in the loop above");
1968  if (Better1)
1969    return FT1;
1970  else if (Better2)
1971    return FT2;
1972  else
1973    return 0;
1974}
1975
1976/// \brief Determine if the two templates are equivalent.
1977static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
1978  if (T1 == T2)
1979    return true;
1980
1981  if (!T1 || !T2)
1982    return false;
1983
1984  return T1->getCanonicalDecl() == T2->getCanonicalDecl();
1985}
1986
1987/// \brief Retrieve the most specialized of the given function template
1988/// specializations.
1989///
1990/// \param Specializations the set of function template specializations that
1991/// we will be comparing.
1992///
1993/// \param NumSpecializations the number of function template specializations in
1994/// \p Specializations
1995///
1996/// \param TPOC the partial ordering context to use to compare the function
1997/// template specializations.
1998///
1999/// \param Loc the location where the ambiguity or no-specializations
2000/// diagnostic should occur.
2001///
2002/// \param NoneDiag partial diagnostic used to diagnose cases where there are
2003/// no matching candidates.
2004///
2005/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
2006/// occurs.
2007///
2008/// \param CandidateDiag partial diagnostic used for each function template
2009/// specialization that is a candidate in the ambiguous ordering. One parameter
2010/// in this diagnostic should be unbound, which will correspond to the string
2011/// describing the template arguments for the function template specialization.
2012///
2013/// \param Index if non-NULL and the result of this function is non-nULL,
2014/// receives the index corresponding to the resulting function template
2015/// specialization.
2016///
2017/// \returns the most specialized function template specialization, if
2018/// found. Otherwise, returns NULL.
2019///
2020/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
2021/// template argument deduction.
2022FunctionDecl *Sema::getMostSpecialized(FunctionDecl **Specializations,
2023                                       unsigned NumSpecializations,
2024                                       TemplatePartialOrderingContext TPOC,
2025                                       SourceLocation Loc,
2026                                       const PartialDiagnostic &NoneDiag,
2027                                       const PartialDiagnostic &AmbigDiag,
2028                                       const PartialDiagnostic &CandidateDiag,
2029                                       unsigned *Index) {
2030  if (NumSpecializations == 0) {
2031    Diag(Loc, NoneDiag);
2032    return 0;
2033  }
2034
2035  if (NumSpecializations == 1) {
2036    if (Index)
2037      *Index = 0;
2038
2039    return Specializations[0];
2040  }
2041
2042
2043  // Find the function template that is better than all of the templates it
2044  // has been compared to.
2045  unsigned Best = 0;
2046  FunctionTemplateDecl *BestTemplate
2047    = Specializations[Best]->getPrimaryTemplate();
2048  assert(BestTemplate && "Not a function template specialization?");
2049  for (unsigned I = 1; I != NumSpecializations; ++I) {
2050    FunctionTemplateDecl *Challenger = Specializations[I]->getPrimaryTemplate();
2051    assert(Challenger && "Not a function template specialization?");
2052    if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
2053                                                  TPOC),
2054                       Challenger)) {
2055      Best = I;
2056      BestTemplate = Challenger;
2057    }
2058  }
2059
2060  // Make sure that the "best" function template is more specialized than all
2061  // of the others.
2062  bool Ambiguous = false;
2063  for (unsigned I = 0; I != NumSpecializations; ++I) {
2064    FunctionTemplateDecl *Challenger = Specializations[I]->getPrimaryTemplate();
2065    if (I != Best &&
2066        !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
2067                                                  TPOC),
2068                        BestTemplate)) {
2069      Ambiguous = true;
2070      break;
2071    }
2072  }
2073
2074  if (!Ambiguous) {
2075    // We found an answer. Return it.
2076    if (Index)
2077      *Index = Best;
2078    return Specializations[Best];
2079  }
2080
2081  // Diagnose the ambiguity.
2082  Diag(Loc, AmbigDiag);
2083
2084  // FIXME: Can we order the candidates in some sane way?
2085  for (unsigned I = 0; I != NumSpecializations; ++I)
2086    Diag(Specializations[I]->getLocation(), CandidateDiag)
2087      << getTemplateArgumentBindingsText(
2088            Specializations[I]->getPrimaryTemplate()->getTemplateParameters(),
2089                         *Specializations[I]->getTemplateSpecializationArgs());
2090
2091  return 0;
2092}
2093
2094/// \brief Returns the more specialized class template partial specialization
2095/// according to the rules of partial ordering of class template partial
2096/// specializations (C++ [temp.class.order]).
2097///
2098/// \param PS1 the first class template partial specialization
2099///
2100/// \param PS2 the second class template partial specialization
2101///
2102/// \returns the more specialized class template partial specialization. If
2103/// neither partial specialization is more specialized, returns NULL.
2104ClassTemplatePartialSpecializationDecl *
2105Sema::getMoreSpecializedPartialSpecialization(
2106                                  ClassTemplatePartialSpecializationDecl *PS1,
2107                                  ClassTemplatePartialSpecializationDecl *PS2) {
2108  // C++ [temp.class.order]p1:
2109  //   For two class template partial specializations, the first is at least as
2110  //   specialized as the second if, given the following rewrite to two
2111  //   function templates, the first function template is at least as
2112  //   specialized as the second according to the ordering rules for function
2113  //   templates (14.6.6.2):
2114  //     - the first function template has the same template parameters as the
2115  //       first partial specialization and has a single function parameter
2116  //       whose type is a class template specialization with the template
2117  //       arguments of the first partial specialization, and
2118  //     - the second function template has the same template parameters as the
2119  //       second partial specialization and has a single function parameter
2120  //       whose type is a class template specialization with the template
2121  //       arguments of the second partial specialization.
2122  //
2123  // Rather than synthesize function templates, we merely perform the
2124  // equivalent partial ordering by performing deduction directly on the
2125  // template arguments of the class template partial specializations. This
2126  // computation is slightly simpler than the general problem of function
2127  // template partial ordering, because class template partial specializations
2128  // are more constrained. We know that every template parameter is deduc
2129  llvm::SmallVector<TemplateArgument, 4> Deduced;
2130  Sema::TemplateDeductionInfo Info(Context);
2131
2132  // Determine whether PS1 is at least as specialized as PS2
2133  Deduced.resize(PS2->getTemplateParameters()->size());
2134  bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(Context,
2135                                                  PS2->getTemplateParameters(),
2136                                                  Context.getTypeDeclType(PS2),
2137                                                  Context.getTypeDeclType(PS1),
2138                                                               Info,
2139                                                               Deduced,
2140                                                               0);
2141
2142  // Determine whether PS2 is at least as specialized as PS1
2143  Deduced.clear();
2144  Deduced.resize(PS1->getTemplateParameters()->size());
2145  bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(Context,
2146                                                  PS1->getTemplateParameters(),
2147                                                  Context.getTypeDeclType(PS1),
2148                                                  Context.getTypeDeclType(PS2),
2149                                                               Info,
2150                                                               Deduced,
2151                                                               0);
2152
2153  if (Better1 == Better2)
2154    return 0;
2155
2156  return Better1? PS1 : PS2;
2157}
2158
2159static void
2160MarkUsedTemplateParameters(Sema &SemaRef,
2161                           const TemplateArgument &TemplateArg,
2162                           bool OnlyDeduced,
2163                           unsigned Depth,
2164                           llvm::SmallVectorImpl<bool> &Used);
2165
2166/// \brief Mark the template parameters that are used by the given
2167/// expression.
2168static void
2169MarkUsedTemplateParameters(Sema &SemaRef,
2170                           const Expr *E,
2171                           bool OnlyDeduced,
2172                           unsigned Depth,
2173                           llvm::SmallVectorImpl<bool> &Used) {
2174  // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
2175  // find other occurrences of template parameters.
2176  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
2177  if (!DRE)
2178    return;
2179
2180  const NonTypeTemplateParmDecl *NTTP
2181    = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2182  if (!NTTP)
2183    return;
2184
2185  if (NTTP->getDepth() == Depth)
2186    Used[NTTP->getIndex()] = true;
2187}
2188
2189/// \brief Mark the template parameters that are used by the given
2190/// nested name specifier.
2191static void
2192MarkUsedTemplateParameters(Sema &SemaRef,
2193                           NestedNameSpecifier *NNS,
2194                           bool OnlyDeduced,
2195                           unsigned Depth,
2196                           llvm::SmallVectorImpl<bool> &Used) {
2197  if (!NNS)
2198    return;
2199
2200  MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
2201                             Used);
2202  MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
2203                             OnlyDeduced, Depth, Used);
2204}
2205
2206/// \brief Mark the template parameters that are used by the given
2207/// template name.
2208static void
2209MarkUsedTemplateParameters(Sema &SemaRef,
2210                           TemplateName Name,
2211                           bool OnlyDeduced,
2212                           unsigned Depth,
2213                           llvm::SmallVectorImpl<bool> &Used) {
2214  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2215    if (TemplateTemplateParmDecl *TTP
2216          = dyn_cast<TemplateTemplateParmDecl>(Template)) {
2217      if (TTP->getDepth() == Depth)
2218        Used[TTP->getIndex()] = true;
2219    }
2220    return;
2221  }
2222
2223  if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
2224    MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
2225                               Depth, Used);
2226  if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
2227    MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
2228                               Depth, Used);
2229}
2230
2231/// \brief Mark the template parameters that are used by the given
2232/// type.
2233static void
2234MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2235                           bool OnlyDeduced,
2236                           unsigned Depth,
2237                           llvm::SmallVectorImpl<bool> &Used) {
2238  if (T.isNull())
2239    return;
2240
2241  // Non-dependent types have nothing deducible
2242  if (!T->isDependentType())
2243    return;
2244
2245  T = SemaRef.Context.getCanonicalType(T);
2246  switch (T->getTypeClass()) {
2247  case Type::Pointer:
2248    MarkUsedTemplateParameters(SemaRef,
2249                               cast<PointerType>(T)->getPointeeType(),
2250                               OnlyDeduced,
2251                               Depth,
2252                               Used);
2253    break;
2254
2255  case Type::BlockPointer:
2256    MarkUsedTemplateParameters(SemaRef,
2257                               cast<BlockPointerType>(T)->getPointeeType(),
2258                               OnlyDeduced,
2259                               Depth,
2260                               Used);
2261    break;
2262
2263  case Type::LValueReference:
2264  case Type::RValueReference:
2265    MarkUsedTemplateParameters(SemaRef,
2266                               cast<ReferenceType>(T)->getPointeeType(),
2267                               OnlyDeduced,
2268                               Depth,
2269                               Used);
2270    break;
2271
2272  case Type::MemberPointer: {
2273    const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
2274    MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
2275                               Depth, Used);
2276    MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
2277                               OnlyDeduced, Depth, Used);
2278    break;
2279  }
2280
2281  case Type::DependentSizedArray:
2282    MarkUsedTemplateParameters(SemaRef,
2283                               cast<DependentSizedArrayType>(T)->getSizeExpr(),
2284                               OnlyDeduced, Depth, Used);
2285    // Fall through to check the element type
2286
2287  case Type::ConstantArray:
2288  case Type::IncompleteArray:
2289    MarkUsedTemplateParameters(SemaRef,
2290                               cast<ArrayType>(T)->getElementType(),
2291                               OnlyDeduced, Depth, Used);
2292    break;
2293
2294  case Type::Vector:
2295  case Type::ExtVector:
2296    MarkUsedTemplateParameters(SemaRef,
2297                               cast<VectorType>(T)->getElementType(),
2298                               OnlyDeduced, Depth, Used);
2299    break;
2300
2301  case Type::DependentSizedExtVector: {
2302    const DependentSizedExtVectorType *VecType
2303      = cast<DependentSizedExtVectorType>(T);
2304    MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
2305                               Depth, Used);
2306    MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
2307                               Depth, Used);
2308    break;
2309  }
2310
2311  case Type::FunctionProto: {
2312    const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2313    MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
2314                               Depth, Used);
2315    for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
2316      MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
2317                                 Depth, Used);
2318    break;
2319  }
2320
2321  case Type::TemplateTypeParm: {
2322    const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
2323    if (TTP->getDepth() == Depth)
2324      Used[TTP->getIndex()] = true;
2325    break;
2326  }
2327
2328  case Type::TemplateSpecialization: {
2329    const TemplateSpecializationType *Spec
2330      = cast<TemplateSpecializationType>(T);
2331    MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
2332                               Depth, Used);
2333    for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
2334      MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
2335                                 Used);
2336    break;
2337  }
2338
2339  case Type::Complex:
2340    if (!OnlyDeduced)
2341      MarkUsedTemplateParameters(SemaRef,
2342                                 cast<ComplexType>(T)->getElementType(),
2343                                 OnlyDeduced, Depth, Used);
2344    break;
2345
2346  case Type::Typename:
2347    if (!OnlyDeduced)
2348      MarkUsedTemplateParameters(SemaRef,
2349                                 cast<TypenameType>(T)->getQualifier(),
2350                                 OnlyDeduced, Depth, Used);
2351    break;
2352
2353  // None of these types have any template parameters in them.
2354  case Type::Builtin:
2355  case Type::VariableArray:
2356  case Type::FunctionNoProto:
2357  case Type::Record:
2358  case Type::Enum:
2359  case Type::ObjCInterface:
2360  case Type::ObjCObjectPointer:
2361  case Type::UnresolvedUsing:
2362#define TYPE(Class, Base)
2363#define ABSTRACT_TYPE(Class, Base)
2364#define DEPENDENT_TYPE(Class, Base)
2365#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2366#include "clang/AST/TypeNodes.def"
2367    break;
2368  }
2369}
2370
2371/// \brief Mark the template parameters that are used by this
2372/// template argument.
2373static void
2374MarkUsedTemplateParameters(Sema &SemaRef,
2375                           const TemplateArgument &TemplateArg,
2376                           bool OnlyDeduced,
2377                           unsigned Depth,
2378                           llvm::SmallVectorImpl<bool> &Used) {
2379  switch (TemplateArg.getKind()) {
2380  case TemplateArgument::Null:
2381  case TemplateArgument::Integral:
2382    case TemplateArgument::Declaration:
2383    break;
2384
2385  case TemplateArgument::Type:
2386    MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
2387                               Depth, Used);
2388    break;
2389
2390  case TemplateArgument::Template:
2391    MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsTemplate(),
2392                               OnlyDeduced, Depth, Used);
2393    break;
2394
2395  case TemplateArgument::Expression:
2396    MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
2397                               Depth, Used);
2398    break;
2399
2400  case TemplateArgument::Pack:
2401    for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
2402                                      PEnd = TemplateArg.pack_end();
2403         P != PEnd; ++P)
2404      MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
2405    break;
2406  }
2407}
2408
2409/// \brief Mark the template parameters can be deduced by the given
2410/// template argument list.
2411///
2412/// \param TemplateArgs the template argument list from which template
2413/// parameters will be deduced.
2414///
2415/// \param Deduced a bit vector whose elements will be set to \c true
2416/// to indicate when the corresponding template parameter will be
2417/// deduced.
2418void
2419Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
2420                                 bool OnlyDeduced, unsigned Depth,
2421                                 llvm::SmallVectorImpl<bool> &Used) {
2422  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2423    ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
2424                                 Depth, Used);
2425}
2426
2427/// \brief Marks all of the template parameters that will be deduced by a
2428/// call to the given function template.
2429void Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
2430                                         llvm::SmallVectorImpl<bool> &Deduced) {
2431  TemplateParameterList *TemplateParams
2432    = FunctionTemplate->getTemplateParameters();
2433  Deduced.clear();
2434  Deduced.resize(TemplateParams->size());
2435
2436  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2437  for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
2438    ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
2439                                 true, TemplateParams->getDepth(), Deduced);
2440}
2441