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