SemaTemplateDeduction.cpp revision b001de7458d17c17e6d8b8034c7cfcefd3b70c00
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 "clang/Sema/Sema.h"
14#include "clang/Sema/DeclSpec.h"
15#include "clang/Sema/Template.h"
16#include "clang/Sema/TemplateDeduction.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/StmtVisitor.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "llvm/ADT/BitVector.h"
24#include "TreeTransform.h"
25#include <algorithm>
26
27namespace clang {
28  using namespace sema;
29
30  /// \brief Various flags that control template argument deduction.
31  ///
32  /// These flags can be bitwise-OR'd together.
33  enum TemplateDeductionFlags {
34    /// \brief No template argument deduction flags, which indicates the
35    /// strictest results for template argument deduction (as used for, e.g.,
36    /// matching class template partial specializations).
37    TDF_None = 0,
38    /// \brief Within template argument deduction from a function call, we are
39    /// matching with a parameter type for which the original parameter was
40    /// a reference.
41    TDF_ParamWithReferenceType = 0x1,
42    /// \brief Within template argument deduction from a function call, we
43    /// are matching in a case where we ignore cv-qualifiers.
44    TDF_IgnoreQualifiers = 0x02,
45    /// \brief Within template argument deduction from a function call,
46    /// we are matching in a case where we can perform template argument
47    /// deduction from a template-id of a derived class of the argument type.
48    TDF_DerivedClass = 0x04,
49    /// \brief Allow non-dependent types to differ, e.g., when performing
50    /// template argument deduction from a function call where conversions
51    /// may apply.
52    TDF_SkipNonDependent = 0x08,
53    /// \brief Whether we are performing template argument deduction for
54    /// parameters and arguments in a top-level template argument
55    TDF_TopLevelParameterTypeList = 0x10
56  };
57}
58
59using namespace clang;
60
61/// \brief Compare two APSInts, extending and switching the sign as
62/// necessary to compare their values regardless of underlying type.
63static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
64  if (Y.getBitWidth() > X.getBitWidth())
65    X = X.extend(Y.getBitWidth());
66  else if (Y.getBitWidth() < X.getBitWidth())
67    Y = Y.extend(X.getBitWidth());
68
69  // If there is a signedness mismatch, correct it.
70  if (X.isSigned() != Y.isSigned()) {
71    // If the signed value is negative, then the values cannot be the same.
72    if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
73      return false;
74
75    Y.setIsSigned(true);
76    X.setIsSigned(true);
77  }
78
79  return X == Y;
80}
81
82static Sema::TemplateDeductionResult
83DeduceTemplateArguments(Sema &S,
84                        TemplateParameterList *TemplateParams,
85                        const TemplateArgument &Param,
86                        TemplateArgument Arg,
87                        TemplateDeductionInfo &Info,
88                      SmallVectorImpl<DeducedTemplateArgument> &Deduced);
89
90/// \brief Whether template argument deduction for two reference parameters
91/// resulted in the argument type, parameter type, or neither type being more
92/// qualified than the other.
93enum DeductionQualifierComparison {
94  NeitherMoreQualified = 0,
95  ParamMoreQualified,
96  ArgMoreQualified
97};
98
99/// \brief Stores the result of comparing two reference parameters while
100/// performing template argument deduction for partial ordering of function
101/// templates.
102struct RefParamPartialOrderingComparison {
103  /// \brief Whether the parameter type is an rvalue reference type.
104  bool ParamIsRvalueRef;
105  /// \brief Whether the argument type is an rvalue reference type.
106  bool ArgIsRvalueRef;
107
108  /// \brief Whether the parameter or argument (or neither) is more qualified.
109  DeductionQualifierComparison Qualifiers;
110};
111
112
113
114static Sema::TemplateDeductionResult
115DeduceTemplateArguments(Sema &S,
116                        TemplateParameterList *TemplateParams,
117                        QualType Param,
118                        QualType Arg,
119                        TemplateDeductionInfo &Info,
120                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
121                        unsigned TDF,
122                        bool PartialOrdering = false,
123                      SmallVectorImpl<RefParamPartialOrderingComparison> *
124                                                      RefParamComparisons = 0);
125
126static Sema::TemplateDeductionResult
127DeduceTemplateArguments(Sema &S,
128                        TemplateParameterList *TemplateParams,
129                        const TemplateArgument *Params, unsigned NumParams,
130                        const TemplateArgument *Args, unsigned NumArgs,
131                        TemplateDeductionInfo &Info,
132                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
133                        bool NumberOfArgumentsMustMatch = true);
134
135/// \brief If the given expression is of a form that permits the deduction
136/// of a non-type template parameter, return the declaration of that
137/// non-type template parameter.
138static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
139  if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
140    E = IC->getSubExpr();
141
142  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
143    return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
144
145  return 0;
146}
147
148/// \brief Determine whether two declaration pointers refer to the same
149/// declaration.
150static bool isSameDeclaration(Decl *X, Decl *Y) {
151  if (!X || !Y)
152    return !X && !Y;
153
154  if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
155    X = NX->getUnderlyingDecl();
156  if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
157    Y = NY->getUnderlyingDecl();
158
159  return X->getCanonicalDecl() == Y->getCanonicalDecl();
160}
161
162/// \brief Verify that the given, deduced template arguments are compatible.
163///
164/// \returns The deduced template argument, or a NULL template argument if
165/// the deduced template arguments were incompatible.
166static DeducedTemplateArgument
167checkDeducedTemplateArguments(ASTContext &Context,
168                              const DeducedTemplateArgument &X,
169                              const DeducedTemplateArgument &Y) {
170  // We have no deduction for one or both of the arguments; they're compatible.
171  if (X.isNull())
172    return Y;
173  if (Y.isNull())
174    return X;
175
176  switch (X.getKind()) {
177  case TemplateArgument::Null:
178    llvm_unreachable("Non-deduced template arguments handled above");
179
180  case TemplateArgument::Type:
181    // If two template type arguments have the same type, they're compatible.
182    if (Y.getKind() == TemplateArgument::Type &&
183        Context.hasSameType(X.getAsType(), Y.getAsType()))
184      return X;
185
186    return DeducedTemplateArgument();
187
188  case TemplateArgument::Integral:
189    // If we deduced a constant in one case and either a dependent expression or
190    // declaration in another case, keep the integral constant.
191    // If both are integral constants with the same value, keep that value.
192    if (Y.getKind() == TemplateArgument::Expression ||
193        Y.getKind() == TemplateArgument::Declaration ||
194        (Y.getKind() == TemplateArgument::Integral &&
195         hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
196      return DeducedTemplateArgument(X,
197                                     X.wasDeducedFromArrayBound() &&
198                                     Y.wasDeducedFromArrayBound());
199
200    // All other combinations are incompatible.
201    return DeducedTemplateArgument();
202
203  case TemplateArgument::Template:
204    if (Y.getKind() == TemplateArgument::Template &&
205        Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
206      return X;
207
208    // All other combinations are incompatible.
209    return DeducedTemplateArgument();
210
211  case TemplateArgument::TemplateExpansion:
212    if (Y.getKind() == TemplateArgument::TemplateExpansion &&
213        Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
214                                    Y.getAsTemplateOrTemplatePattern()))
215      return X;
216
217    // All other combinations are incompatible.
218    return DeducedTemplateArgument();
219
220  case TemplateArgument::Expression:
221    // If we deduced a dependent expression in one case and either an integral
222    // constant or a declaration in another case, keep the integral constant
223    // or declaration.
224    if (Y.getKind() == TemplateArgument::Integral ||
225        Y.getKind() == TemplateArgument::Declaration)
226      return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
227                                     Y.wasDeducedFromArrayBound());
228
229    if (Y.getKind() == TemplateArgument::Expression) {
230      // Compare the expressions for equality
231      llvm::FoldingSetNodeID ID1, ID2;
232      X.getAsExpr()->Profile(ID1, Context, true);
233      Y.getAsExpr()->Profile(ID2, Context, true);
234      if (ID1 == ID2)
235        return X;
236    }
237
238    // All other combinations are incompatible.
239    return DeducedTemplateArgument();
240
241  case TemplateArgument::Declaration:
242    // If we deduced a declaration and a dependent expression, keep the
243    // declaration.
244    if (Y.getKind() == TemplateArgument::Expression)
245      return X;
246
247    // If we deduced a declaration and an integral constant, keep the
248    // integral constant.
249    if (Y.getKind() == TemplateArgument::Integral)
250      return Y;
251
252    // If we deduced two declarations, make sure they they refer to the
253    // same declaration.
254    if (Y.getKind() == TemplateArgument::Declaration &&
255        isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
256      return X;
257
258    // All other combinations are incompatible.
259    return DeducedTemplateArgument();
260
261  case TemplateArgument::Pack:
262    if (Y.getKind() != TemplateArgument::Pack ||
263        X.pack_size() != Y.pack_size())
264      return DeducedTemplateArgument();
265
266    for (TemplateArgument::pack_iterator XA = X.pack_begin(),
267                                      XAEnd = X.pack_end(),
268                                         YA = Y.pack_begin();
269         XA != XAEnd; ++XA, ++YA) {
270      if (checkDeducedTemplateArguments(Context,
271                    DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
272                    DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
273            .isNull())
274        return DeducedTemplateArgument();
275    }
276
277    return X;
278  }
279
280  return DeducedTemplateArgument();
281}
282
283/// \brief Deduce the value of the given non-type template parameter
284/// from the given constant.
285static Sema::TemplateDeductionResult
286DeduceNonTypeTemplateArgument(Sema &S,
287                              NonTypeTemplateParmDecl *NTTP,
288                              llvm::APSInt Value, QualType ValueType,
289                              bool DeducedFromArrayBound,
290                              TemplateDeductionInfo &Info,
291                    SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
292  assert(NTTP->getDepth() == 0 &&
293         "Cannot deduce non-type template argument with depth > 0");
294
295  DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
296  DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
297                                                     Deduced[NTTP->getIndex()],
298                                                                 NewDeduced);
299  if (Result.isNull()) {
300    Info.Param = NTTP;
301    Info.FirstArg = Deduced[NTTP->getIndex()];
302    Info.SecondArg = NewDeduced;
303    return Sema::TDK_Inconsistent;
304  }
305
306  Deduced[NTTP->getIndex()] = Result;
307  return Sema::TDK_Success;
308}
309
310/// \brief Deduce the value of the given non-type template parameter
311/// from the given type- or value-dependent expression.
312///
313/// \returns true if deduction succeeded, false otherwise.
314static Sema::TemplateDeductionResult
315DeduceNonTypeTemplateArgument(Sema &S,
316                              NonTypeTemplateParmDecl *NTTP,
317                              Expr *Value,
318                              TemplateDeductionInfo &Info,
319                    SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
320  assert(NTTP->getDepth() == 0 &&
321         "Cannot deduce non-type template argument with depth > 0");
322  assert((Value->isTypeDependent() || Value->isValueDependent()) &&
323         "Expression template argument must be type- or value-dependent.");
324
325  DeducedTemplateArgument NewDeduced(Value);
326  DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
327                                                     Deduced[NTTP->getIndex()],
328                                                                 NewDeduced);
329
330  if (Result.isNull()) {
331    Info.Param = NTTP;
332    Info.FirstArg = Deduced[NTTP->getIndex()];
333    Info.SecondArg = NewDeduced;
334    return Sema::TDK_Inconsistent;
335  }
336
337  Deduced[NTTP->getIndex()] = Result;
338  return Sema::TDK_Success;
339}
340
341/// \brief Deduce the value of the given non-type template parameter
342/// from the given declaration.
343///
344/// \returns true if deduction succeeded, false otherwise.
345static Sema::TemplateDeductionResult
346DeduceNonTypeTemplateArgument(Sema &S,
347                              NonTypeTemplateParmDecl *NTTP,
348                              Decl *D,
349                              TemplateDeductionInfo &Info,
350                    SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
351  assert(NTTP->getDepth() == 0 &&
352         "Cannot deduce non-type template argument with depth > 0");
353
354  DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
355  DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
356                                                     Deduced[NTTP->getIndex()],
357                                                                 NewDeduced);
358  if (Result.isNull()) {
359    Info.Param = NTTP;
360    Info.FirstArg = Deduced[NTTP->getIndex()];
361    Info.SecondArg = NewDeduced;
362    return Sema::TDK_Inconsistent;
363  }
364
365  Deduced[NTTP->getIndex()] = Result;
366  return Sema::TDK_Success;
367}
368
369static Sema::TemplateDeductionResult
370DeduceTemplateArguments(Sema &S,
371                        TemplateParameterList *TemplateParams,
372                        TemplateName Param,
373                        TemplateName Arg,
374                        TemplateDeductionInfo &Info,
375                    SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
376  TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
377  if (!ParamDecl) {
378    // The parameter type is dependent and is not a template template parameter,
379    // so there is nothing that we can deduce.
380    return Sema::TDK_Success;
381  }
382
383  if (TemplateTemplateParmDecl *TempParam
384        = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
385    DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
386    DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
387                                                 Deduced[TempParam->getIndex()],
388                                                                   NewDeduced);
389    if (Result.isNull()) {
390      Info.Param = TempParam;
391      Info.FirstArg = Deduced[TempParam->getIndex()];
392      Info.SecondArg = NewDeduced;
393      return Sema::TDK_Inconsistent;
394    }
395
396    Deduced[TempParam->getIndex()] = Result;
397    return Sema::TDK_Success;
398  }
399
400  // Verify that the two template names are equivalent.
401  if (S.Context.hasSameTemplateName(Param, Arg))
402    return Sema::TDK_Success;
403
404  // Mismatch of non-dependent template parameter to argument.
405  Info.FirstArg = TemplateArgument(Param);
406  Info.SecondArg = TemplateArgument(Arg);
407  return Sema::TDK_NonDeducedMismatch;
408}
409
410/// \brief Deduce the template arguments by comparing the template parameter
411/// type (which is a template-id) with the template argument type.
412///
413/// \param S the Sema
414///
415/// \param TemplateParams the template parameters that we are deducing
416///
417/// \param Param the parameter type
418///
419/// \param Arg the argument type
420///
421/// \param Info information about the template argument deduction itself
422///
423/// \param Deduced the deduced template arguments
424///
425/// \returns the result of template argument deduction so far. Note that a
426/// "success" result means that template argument deduction has not yet failed,
427/// but it may still fail, later, for other reasons.
428static Sema::TemplateDeductionResult
429DeduceTemplateArguments(Sema &S,
430                        TemplateParameterList *TemplateParams,
431                        const TemplateSpecializationType *Param,
432                        QualType Arg,
433                        TemplateDeductionInfo &Info,
434                    SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
435  assert(Arg.isCanonical() && "Argument type must be canonical");
436
437  // Check whether the template argument is a dependent template-id.
438  if (const TemplateSpecializationType *SpecArg
439        = dyn_cast<TemplateSpecializationType>(Arg)) {
440    // Perform template argument deduction for the template name.
441    if (Sema::TemplateDeductionResult Result
442          = DeduceTemplateArguments(S, TemplateParams,
443                                    Param->getTemplateName(),
444                                    SpecArg->getTemplateName(),
445                                    Info, Deduced))
446      return Result;
447
448
449    // Perform template argument deduction on each template
450    // argument. Ignore any missing/extra arguments, since they could be
451    // filled in by default arguments.
452    return DeduceTemplateArguments(S, TemplateParams,
453                                   Param->getArgs(), Param->getNumArgs(),
454                                   SpecArg->getArgs(), SpecArg->getNumArgs(),
455                                   Info, Deduced,
456                                   /*NumberOfArgumentsMustMatch=*/false);
457  }
458
459  // If the argument type is a class template specialization, we
460  // perform template argument deduction using its template
461  // arguments.
462  const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
463  if (!RecordArg)
464    return Sema::TDK_NonDeducedMismatch;
465
466  ClassTemplateSpecializationDecl *SpecArg
467    = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
468  if (!SpecArg)
469    return Sema::TDK_NonDeducedMismatch;
470
471  // Perform template argument deduction for the template name.
472  if (Sema::TemplateDeductionResult Result
473        = DeduceTemplateArguments(S,
474                                  TemplateParams,
475                                  Param->getTemplateName(),
476                               TemplateName(SpecArg->getSpecializedTemplate()),
477                                  Info, Deduced))
478    return Result;
479
480  // Perform template argument deduction for the template arguments.
481  return DeduceTemplateArguments(S, TemplateParams,
482                                 Param->getArgs(), Param->getNumArgs(),
483                                 SpecArg->getTemplateArgs().data(),
484                                 SpecArg->getTemplateArgs().size(),
485                                 Info, Deduced);
486}
487
488/// \brief Determines whether the given type is an opaque type that
489/// might be more qualified when instantiated.
490static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
491  switch (T->getTypeClass()) {
492  case Type::TypeOfExpr:
493  case Type::TypeOf:
494  case Type::DependentName:
495  case Type::Decltype:
496  case Type::UnresolvedUsing:
497  case Type::TemplateTypeParm:
498    return true;
499
500  case Type::ConstantArray:
501  case Type::IncompleteArray:
502  case Type::VariableArray:
503  case Type::DependentSizedArray:
504    return IsPossiblyOpaquelyQualifiedType(
505                                      cast<ArrayType>(T)->getElementType());
506
507  default:
508    return false;
509  }
510}
511
512/// \brief Retrieve the depth and index of a template parameter.
513static std::pair<unsigned, unsigned>
514getDepthAndIndex(NamedDecl *ND) {
515  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
516    return std::make_pair(TTP->getDepth(), TTP->getIndex());
517
518  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
519    return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
520
521  TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
522  return std::make_pair(TTP->getDepth(), TTP->getIndex());
523}
524
525/// \brief Retrieve the depth and index of an unexpanded parameter pack.
526static std::pair<unsigned, unsigned>
527getDepthAndIndex(UnexpandedParameterPack UPP) {
528  if (const TemplateTypeParmType *TTP
529                          = UPP.first.dyn_cast<const TemplateTypeParmType *>())
530    return std::make_pair(TTP->getDepth(), TTP->getIndex());
531
532  return getDepthAndIndex(UPP.first.get<NamedDecl *>());
533}
534
535/// \brief Helper function to build a TemplateParameter when we don't
536/// know its type statically.
537static TemplateParameter makeTemplateParameter(Decl *D) {
538  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
539    return TemplateParameter(TTP);
540  else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
541    return TemplateParameter(NTTP);
542
543  return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
544}
545
546/// \brief Prepare to perform template argument deduction for all of the
547/// arguments in a set of argument packs.
548static void PrepareArgumentPackDeduction(Sema &S,
549                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
550                             const SmallVectorImpl<unsigned> &PackIndices,
551                     SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
552         SmallVectorImpl<
553           SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks) {
554  // Save the deduced template arguments for each parameter pack expanded
555  // by this pack expansion, then clear out the deduction.
556  for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
557    // Save the previously-deduced argument pack, then clear it out so that we
558    // can deduce a new argument pack.
559    SavedPacks[I] = Deduced[PackIndices[I]];
560    Deduced[PackIndices[I]] = TemplateArgument();
561
562    // If the template arugment pack was explicitly specified, add that to
563    // the set of deduced arguments.
564    const TemplateArgument *ExplicitArgs;
565    unsigned NumExplicitArgs;
566    if (NamedDecl *PartiallySubstitutedPack
567        = S.CurrentInstantiationScope->getPartiallySubstitutedPack(
568                                                           &ExplicitArgs,
569                                                           &NumExplicitArgs)) {
570      if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I])
571        NewlyDeducedPacks[I].append(ExplicitArgs,
572                                    ExplicitArgs + NumExplicitArgs);
573    }
574  }
575}
576
577/// \brief Finish template argument deduction for a set of argument packs,
578/// producing the argument packs and checking for consistency with prior
579/// deductions.
580static Sema::TemplateDeductionResult
581FinishArgumentPackDeduction(Sema &S,
582                            TemplateParameterList *TemplateParams,
583                            bool HasAnyArguments,
584                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
585                            const SmallVectorImpl<unsigned> &PackIndices,
586                    SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
587        SmallVectorImpl<
588          SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks,
589                            TemplateDeductionInfo &Info) {
590  // Build argument packs for each of the parameter packs expanded by this
591  // pack expansion.
592  for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
593    if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
594      // We were not able to deduce anything for this parameter pack,
595      // so just restore the saved argument pack.
596      Deduced[PackIndices[I]] = SavedPacks[I];
597      continue;
598    }
599
600    DeducedTemplateArgument NewPack;
601
602    if (NewlyDeducedPacks[I].empty()) {
603      // If we deduced an empty argument pack, create it now.
604      NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
605    } else {
606      TemplateArgument *ArgumentPack
607        = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
608      std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
609                ArgumentPack);
610      NewPack
611        = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
612                                                   NewlyDeducedPacks[I].size()),
613                            NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
614    }
615
616    DeducedTemplateArgument Result
617      = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
618    if (Result.isNull()) {
619      Info.Param
620        = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
621      Info.FirstArg = SavedPacks[I];
622      Info.SecondArg = NewPack;
623      return Sema::TDK_Inconsistent;
624    }
625
626    Deduced[PackIndices[I]] = Result;
627  }
628
629  return Sema::TDK_Success;
630}
631
632/// \brief Deduce the template arguments by comparing the list of parameter
633/// types to the list of argument types, as in the parameter-type-lists of
634/// function types (C++ [temp.deduct.type]p10).
635///
636/// \param S The semantic analysis object within which we are deducing
637///
638/// \param TemplateParams The template parameters that we are deducing
639///
640/// \param Params The list of parameter types
641///
642/// \param NumParams The number of types in \c Params
643///
644/// \param Args The list of argument types
645///
646/// \param NumArgs The number of types in \c Args
647///
648/// \param Info information about the template argument deduction itself
649///
650/// \param Deduced the deduced template arguments
651///
652/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
653/// how template argument deduction is performed.
654///
655/// \param PartialOrdering If true, we are performing template argument
656/// deduction for during partial ordering for a call
657/// (C++0x [temp.deduct.partial]).
658///
659/// \param RefParamComparisons If we're performing template argument deduction
660/// in the context of partial ordering, the set of qualifier comparisons.
661///
662/// \returns the result of template argument deduction so far. Note that a
663/// "success" result means that template argument deduction has not yet failed,
664/// but it may still fail, later, for other reasons.
665static Sema::TemplateDeductionResult
666DeduceTemplateArguments(Sema &S,
667                        TemplateParameterList *TemplateParams,
668                        const QualType *Params, unsigned NumParams,
669                        const QualType *Args, unsigned NumArgs,
670                        TemplateDeductionInfo &Info,
671                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
672                        unsigned TDF,
673                        bool PartialOrdering = false,
674                        SmallVectorImpl<RefParamPartialOrderingComparison> *
675                                                     RefParamComparisons = 0) {
676  // Fast-path check to see if we have too many/too few arguments.
677  if (NumParams != NumArgs &&
678      !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
679      !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
680    return Sema::TDK_NonDeducedMismatch;
681
682  // C++0x [temp.deduct.type]p10:
683  //   Similarly, if P has a form that contains (T), then each parameter type
684  //   Pi of the respective parameter-type- list of P is compared with the
685  //   corresponding parameter type Ai of the corresponding parameter-type-list
686  //   of A. [...]
687  unsigned ArgIdx = 0, ParamIdx = 0;
688  for (; ParamIdx != NumParams; ++ParamIdx) {
689    // Check argument types.
690    const PackExpansionType *Expansion
691                                = dyn_cast<PackExpansionType>(Params[ParamIdx]);
692    if (!Expansion) {
693      // Simple case: compare the parameter and argument types at this point.
694
695      // Make sure we have an argument.
696      if (ArgIdx >= NumArgs)
697        return Sema::TDK_NonDeducedMismatch;
698
699      if (isa<PackExpansionType>(Args[ArgIdx])) {
700        // C++0x [temp.deduct.type]p22:
701        //   If the original function parameter associated with A is a function
702        //   parameter pack and the function parameter associated with P is not
703        //   a function parameter pack, then template argument deduction fails.
704        return Sema::TDK_NonDeducedMismatch;
705      }
706
707      if (Sema::TemplateDeductionResult Result
708            = DeduceTemplateArguments(S, TemplateParams,
709                                      Params[ParamIdx],
710                                      Args[ArgIdx],
711                                      Info, Deduced, TDF,
712                                      PartialOrdering,
713                                      RefParamComparisons))
714        return Result;
715
716      ++ArgIdx;
717      continue;
718    }
719
720    // C++0x [temp.deduct.type]p5:
721    //   The non-deduced contexts are:
722    //     - A function parameter pack that does not occur at the end of the
723    //       parameter-declaration-clause.
724    if (ParamIdx + 1 < NumParams)
725      return Sema::TDK_Success;
726
727    // C++0x [temp.deduct.type]p10:
728    //   If the parameter-declaration corresponding to Pi is a function
729    //   parameter pack, then the type of its declarator- id is compared with
730    //   each remaining parameter type in the parameter-type-list of A. Each
731    //   comparison deduces template arguments for subsequent positions in the
732    //   template parameter packs expanded by the function parameter pack.
733
734    // Compute the set of template parameter indices that correspond to
735    // parameter packs expanded by the pack expansion.
736    SmallVector<unsigned, 2> PackIndices;
737    QualType Pattern = Expansion->getPattern();
738    {
739      llvm::BitVector SawIndices(TemplateParams->size());
740      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
741      S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
742      for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
743        unsigned Depth, Index;
744        llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
745        if (Depth == 0 && !SawIndices[Index]) {
746          SawIndices[Index] = true;
747          PackIndices.push_back(Index);
748        }
749      }
750    }
751    assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
752
753    // Keep track of the deduced template arguments for each parameter pack
754    // expanded by this pack expansion (the outer index) and for each
755    // template argument (the inner SmallVectors).
756    SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2>
757      NewlyDeducedPacks(PackIndices.size());
758    SmallVector<DeducedTemplateArgument, 2>
759      SavedPacks(PackIndices.size());
760    PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
761                                 NewlyDeducedPacks);
762
763    bool HasAnyArguments = false;
764    for (; ArgIdx < NumArgs; ++ArgIdx) {
765      HasAnyArguments = true;
766
767      // Deduce template arguments from the pattern.
768      if (Sema::TemplateDeductionResult Result
769            = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
770                                      Info, Deduced, TDF, PartialOrdering,
771                                      RefParamComparisons))
772        return Result;
773
774      // Capture the deduced template arguments for each parameter pack expanded
775      // by this pack expansion, add them to the list of arguments we've deduced
776      // for that pack, then clear out the deduced argument.
777      for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
778        DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
779        if (!DeducedArg.isNull()) {
780          NewlyDeducedPacks[I].push_back(DeducedArg);
781          DeducedArg = DeducedTemplateArgument();
782        }
783      }
784    }
785
786    // Build argument packs for each of the parameter packs expanded by this
787    // pack expansion.
788    if (Sema::TemplateDeductionResult Result
789          = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
790                                        Deduced, PackIndices, SavedPacks,
791                                        NewlyDeducedPacks, Info))
792      return Result;
793  }
794
795  // Make sure we don't have any extra arguments.
796  if (ArgIdx < NumArgs)
797    return Sema::TDK_NonDeducedMismatch;
798
799  return Sema::TDK_Success;
800}
801
802/// \brief Determine whether the parameter has qualifiers that are either
803/// inconsistent with or a superset of the argument's qualifiers.
804static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
805                                                  QualType ArgType) {
806  Qualifiers ParamQs = ParamType.getQualifiers();
807  Qualifiers ArgQs = ArgType.getQualifiers();
808
809  if (ParamQs == ArgQs)
810    return false;
811
812  // Mismatched (but not missing) Objective-C GC attributes.
813  if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
814      ParamQs.hasObjCGCAttr())
815    return true;
816
817  // Mismatched (but not missing) address spaces.
818  if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
819      ParamQs.hasAddressSpace())
820    return true;
821
822  // Mismatched (but not missing) Objective-C lifetime qualifiers.
823  if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
824      ParamQs.hasObjCLifetime())
825    return true;
826
827  // CVR qualifier superset.
828  return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
829      ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
830                                                == ParamQs.getCVRQualifiers());
831}
832
833/// \brief Deduce the template arguments by comparing the parameter type and
834/// the argument type (C++ [temp.deduct.type]).
835///
836/// \param S the semantic analysis object within which we are deducing
837///
838/// \param TemplateParams the template parameters that we are deducing
839///
840/// \param ParamIn the parameter type
841///
842/// \param ArgIn the argument type
843///
844/// \param Info information about the template argument deduction itself
845///
846/// \param Deduced the deduced template arguments
847///
848/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
849/// how template argument deduction is performed.
850///
851/// \param PartialOrdering Whether we're performing template argument deduction
852/// in the context of partial ordering (C++0x [temp.deduct.partial]).
853///
854/// \param RefParamComparisons If we're performing template argument deduction
855/// in the context of partial ordering, the set of qualifier comparisons.
856///
857/// \returns the result of template argument deduction so far. Note that a
858/// "success" result means that template argument deduction has not yet failed,
859/// but it may still fail, later, for other reasons.
860static Sema::TemplateDeductionResult
861DeduceTemplateArguments(Sema &S,
862                        TemplateParameterList *TemplateParams,
863                        QualType ParamIn, QualType ArgIn,
864                        TemplateDeductionInfo &Info,
865                     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
866                        unsigned TDF,
867                        bool PartialOrdering,
868    SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
869  // We only want to look at the canonical types, since typedefs and
870  // sugar are not part of template argument deduction.
871  QualType Param = S.Context.getCanonicalType(ParamIn);
872  QualType Arg = S.Context.getCanonicalType(ArgIn);
873
874  // If the argument type is a pack expansion, look at its pattern.
875  // This isn't explicitly called out
876  if (const PackExpansionType *ArgExpansion
877                                            = dyn_cast<PackExpansionType>(Arg))
878    Arg = ArgExpansion->getPattern();
879
880  if (PartialOrdering) {
881    // C++0x [temp.deduct.partial]p5:
882    //   Before the partial ordering is done, certain transformations are
883    //   performed on the types used for partial ordering:
884    //     - If P is a reference type, P is replaced by the type referred to.
885    const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
886    if (ParamRef)
887      Param = ParamRef->getPointeeType();
888
889    //     - If A is a reference type, A is replaced by the type referred to.
890    const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
891    if (ArgRef)
892      Arg = ArgRef->getPointeeType();
893
894    if (RefParamComparisons && ParamRef && ArgRef) {
895      // C++0x [temp.deduct.partial]p6:
896      //   If both P and A were reference types (before being replaced with the
897      //   type referred to above), determine which of the two types (if any) is
898      //   more cv-qualified than the other; otherwise the types are considered
899      //   to be equally cv-qualified for partial ordering purposes. The result
900      //   of this determination will be used below.
901      //
902      // We save this information for later, using it only when deduction
903      // succeeds in both directions.
904      RefParamPartialOrderingComparison Comparison;
905      Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>();
906      Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>();
907      Comparison.Qualifiers = NeitherMoreQualified;
908
909      Qualifiers ParamQuals = Param.getQualifiers();
910      Qualifiers ArgQuals = Arg.getQualifiers();
911      if (ParamQuals.isStrictSupersetOf(ArgQuals))
912        Comparison.Qualifiers = ParamMoreQualified;
913      else if (ArgQuals.isStrictSupersetOf(ParamQuals))
914        Comparison.Qualifiers = ArgMoreQualified;
915      RefParamComparisons->push_back(Comparison);
916    }
917
918    // C++0x [temp.deduct.partial]p7:
919    //   Remove any top-level cv-qualifiers:
920    //     - If P is a cv-qualified type, P is replaced by the cv-unqualified
921    //       version of P.
922    Param = Param.getUnqualifiedType();
923    //     - If A is a cv-qualified type, A is replaced by the cv-unqualified
924    //       version of A.
925    Arg = Arg.getUnqualifiedType();
926  } else {
927    // C++0x [temp.deduct.call]p4 bullet 1:
928    //   - If the original P is a reference type, the deduced A (i.e., the type
929    //     referred to by the reference) can be more cv-qualified than the
930    //     transformed A.
931    if (TDF & TDF_ParamWithReferenceType) {
932      Qualifiers Quals;
933      QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
934      Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
935                             Arg.getCVRQualifiers());
936      Param = S.Context.getQualifiedType(UnqualParam, Quals);
937    }
938
939    if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
940      // C++0x [temp.deduct.type]p10:
941      //   If P and A are function types that originated from deduction when
942      //   taking the address of a function template (14.8.2.2) or when deducing
943      //   template arguments from a function declaration (14.8.2.6) and Pi and
944      //   Ai are parameters of the top-level parameter-type-list of P and A,
945      //   respectively, Pi is adjusted if it is an rvalue reference to a
946      //   cv-unqualified template parameter and Ai is an lvalue reference, in
947      //   which case the type of Pi is changed to be the template parameter
948      //   type (i.e., T&& is changed to simply T). [ Note: As a result, when
949      //   Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
950      //   deduced as X&. - end note ]
951      TDF &= ~TDF_TopLevelParameterTypeList;
952
953      if (const RValueReferenceType *ParamRef
954                                        = Param->getAs<RValueReferenceType>()) {
955        if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
956            !ParamRef->getPointeeType().getQualifiers())
957          if (Arg->isLValueReferenceType())
958            Param = ParamRef->getPointeeType();
959      }
960    }
961  }
962
963  // If the parameter type is not dependent, there is nothing to deduce.
964  if (!Param->isDependentType()) {
965    if (!(TDF & TDF_SkipNonDependent) && Param != Arg)
966      return Sema::TDK_NonDeducedMismatch;
967
968    return Sema::TDK_Success;
969  }
970
971  // C++ [temp.deduct.type]p9:
972  //   A template type argument T, a template template argument TT or a
973  //   template non-type argument i can be deduced if P and A have one of
974  //   the following forms:
975  //
976  //     T
977  //     cv-list T
978  if (const TemplateTypeParmType *TemplateTypeParm
979        = Param->getAs<TemplateTypeParmType>()) {
980    // Just skip any attempts to deduce from a placeholder type.
981    if (Arg->isPlaceholderType())
982      return Sema::TDK_Success;
983
984    unsigned Index = TemplateTypeParm->getIndex();
985    bool RecanonicalizeArg = false;
986
987    // If the argument type is an array type, move the qualifiers up to the
988    // top level, so they can be matched with the qualifiers on the parameter.
989    if (isa<ArrayType>(Arg)) {
990      Qualifiers Quals;
991      Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
992      if (Quals) {
993        Arg = S.Context.getQualifiedType(Arg, Quals);
994        RecanonicalizeArg = true;
995      }
996    }
997
998    // The argument type can not be less qualified than the parameter
999    // type.
1000    if (!(TDF & TDF_IgnoreQualifiers) &&
1001        hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
1002      Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1003      Info.FirstArg = TemplateArgument(Param);
1004      Info.SecondArg = TemplateArgument(Arg);
1005      return Sema::TDK_Underqualified;
1006    }
1007
1008    assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
1009    assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
1010    QualType DeducedType = Arg;
1011
1012    // Remove any qualifiers on the parameter from the deduced type.
1013    // We checked the qualifiers for consistency above.
1014    Qualifiers DeducedQs = DeducedType.getQualifiers();
1015    Qualifiers ParamQs = Param.getQualifiers();
1016    DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1017    if (ParamQs.hasObjCGCAttr())
1018      DeducedQs.removeObjCGCAttr();
1019    if (ParamQs.hasAddressSpace())
1020      DeducedQs.removeAddressSpace();
1021    if (ParamQs.hasObjCLifetime())
1022      DeducedQs.removeObjCLifetime();
1023
1024    // Objective-C ARC:
1025    //   If template deduction would produce a lifetime qualifier on a type
1026    //   that is not a lifetime type, template argument deduction fails.
1027    if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1028        !DeducedType->isDependentType()) {
1029      Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1030      Info.FirstArg = TemplateArgument(Param);
1031      Info.SecondArg = TemplateArgument(Arg);
1032      return Sema::TDK_Underqualified;
1033    }
1034
1035    // Objective-C ARC:
1036    //   If template deduction would produce an argument type with lifetime type
1037    //   but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1038    if (S.getLangOptions().ObjCAutoRefCount &&
1039        DeducedType->isObjCLifetimeType() &&
1040        !DeducedQs.hasObjCLifetime())
1041      DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1042
1043    DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1044                                             DeducedQs);
1045
1046    if (RecanonicalizeArg)
1047      DeducedType = S.Context.getCanonicalType(DeducedType);
1048
1049    DeducedTemplateArgument NewDeduced(DeducedType);
1050    DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
1051                                                                 Deduced[Index],
1052                                                                   NewDeduced);
1053    if (Result.isNull()) {
1054      Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1055      Info.FirstArg = Deduced[Index];
1056      Info.SecondArg = NewDeduced;
1057      return Sema::TDK_Inconsistent;
1058    }
1059
1060    Deduced[Index] = Result;
1061    return Sema::TDK_Success;
1062  }
1063
1064  // Set up the template argument deduction information for a failure.
1065  Info.FirstArg = TemplateArgument(ParamIn);
1066  Info.SecondArg = TemplateArgument(ArgIn);
1067
1068  // If the parameter is an already-substituted template parameter
1069  // pack, do nothing: we don't know which of its arguments to look
1070  // at, so we have to wait until all of the parameter packs in this
1071  // expansion have arguments.
1072  if (isa<SubstTemplateTypeParmPackType>(Param))
1073    return Sema::TDK_Success;
1074
1075  // Check the cv-qualifiers on the parameter and argument types.
1076  if (!(TDF & TDF_IgnoreQualifiers)) {
1077    if (TDF & TDF_ParamWithReferenceType) {
1078      if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
1079        return Sema::TDK_NonDeducedMismatch;
1080    } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
1081      if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
1082        return Sema::TDK_NonDeducedMismatch;
1083    }
1084  }
1085
1086  switch (Param->getTypeClass()) {
1087    // Non-canonical types cannot appear here.
1088#define NON_CANONICAL_TYPE(Class, Base) \
1089  case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1090#define TYPE(Class, Base)
1091#include "clang/AST/TypeNodes.def"
1092
1093    case Type::TemplateTypeParm:
1094    case Type::SubstTemplateTypeParmPack:
1095      llvm_unreachable("Type nodes handled above");
1096
1097    // These types cannot be used in templates or cannot be dependent, so
1098    // deduction always fails.
1099    case Type::Builtin:
1100    case Type::VariableArray:
1101    case Type::Vector:
1102    case Type::FunctionNoProto:
1103    case Type::Record:
1104    case Type::Enum:
1105    case Type::ObjCObject:
1106    case Type::ObjCInterface:
1107    case Type::ObjCObjectPointer:
1108      return Sema::TDK_NonDeducedMismatch;
1109
1110    //     _Complex T   [placeholder extension]
1111    case Type::Complex:
1112      if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
1113        return DeduceTemplateArguments(S, TemplateParams,
1114                                    cast<ComplexType>(Param)->getElementType(),
1115                                       ComplexArg->getElementType(),
1116                                       Info, Deduced, TDF);
1117
1118      return Sema::TDK_NonDeducedMismatch;
1119
1120    //     _Atomic T   [extension]
1121    case Type::Atomic:
1122      if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
1123        return DeduceTemplateArguments(S, TemplateParams,
1124                                       cast<AtomicType>(Param)->getValueType(),
1125                                       AtomicArg->getValueType(),
1126                                       Info, Deduced, TDF);
1127
1128      return Sema::TDK_NonDeducedMismatch;
1129
1130    //     T *
1131    case Type::Pointer: {
1132      QualType PointeeType;
1133      if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1134        PointeeType = PointerArg->getPointeeType();
1135      } else if (const ObjCObjectPointerType *PointerArg
1136                   = Arg->getAs<ObjCObjectPointerType>()) {
1137        PointeeType = PointerArg->getPointeeType();
1138      } else {
1139        return Sema::TDK_NonDeducedMismatch;
1140      }
1141
1142      unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
1143      return DeduceTemplateArguments(S, TemplateParams,
1144                                   cast<PointerType>(Param)->getPointeeType(),
1145                                     PointeeType,
1146                                     Info, Deduced, SubTDF);
1147    }
1148
1149    //     T &
1150    case Type::LValueReference: {
1151      const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
1152      if (!ReferenceArg)
1153        return Sema::TDK_NonDeducedMismatch;
1154
1155      return DeduceTemplateArguments(S, TemplateParams,
1156                           cast<LValueReferenceType>(Param)->getPointeeType(),
1157                                     ReferenceArg->getPointeeType(),
1158                                     Info, Deduced, 0);
1159    }
1160
1161    //     T && [C++0x]
1162    case Type::RValueReference: {
1163      const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
1164      if (!ReferenceArg)
1165        return Sema::TDK_NonDeducedMismatch;
1166
1167      return DeduceTemplateArguments(S, TemplateParams,
1168                           cast<RValueReferenceType>(Param)->getPointeeType(),
1169                                     ReferenceArg->getPointeeType(),
1170                                     Info, Deduced, 0);
1171    }
1172
1173    //     T [] (implied, but not stated explicitly)
1174    case Type::IncompleteArray: {
1175      const IncompleteArrayType *IncompleteArrayArg =
1176        S.Context.getAsIncompleteArrayType(Arg);
1177      if (!IncompleteArrayArg)
1178        return Sema::TDK_NonDeducedMismatch;
1179
1180      unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1181      return DeduceTemplateArguments(S, TemplateParams,
1182                     S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1183                                     IncompleteArrayArg->getElementType(),
1184                                     Info, Deduced, SubTDF);
1185    }
1186
1187    //     T [integer-constant]
1188    case Type::ConstantArray: {
1189      const ConstantArrayType *ConstantArrayArg =
1190        S.Context.getAsConstantArrayType(Arg);
1191      if (!ConstantArrayArg)
1192        return Sema::TDK_NonDeducedMismatch;
1193
1194      const ConstantArrayType *ConstantArrayParm =
1195        S.Context.getAsConstantArrayType(Param);
1196      if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
1197        return Sema::TDK_NonDeducedMismatch;
1198
1199      unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1200      return DeduceTemplateArguments(S, TemplateParams,
1201                                     ConstantArrayParm->getElementType(),
1202                                     ConstantArrayArg->getElementType(),
1203                                     Info, Deduced, SubTDF);
1204    }
1205
1206    //     type [i]
1207    case Type::DependentSizedArray: {
1208      const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
1209      if (!ArrayArg)
1210        return Sema::TDK_NonDeducedMismatch;
1211
1212      unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1213
1214      // Check the element type of the arrays
1215      const DependentSizedArrayType *DependentArrayParm
1216        = S.Context.getAsDependentSizedArrayType(Param);
1217      if (Sema::TemplateDeductionResult Result
1218            = DeduceTemplateArguments(S, TemplateParams,
1219                                      DependentArrayParm->getElementType(),
1220                                      ArrayArg->getElementType(),
1221                                      Info, Deduced, SubTDF))
1222        return Result;
1223
1224      // Determine the array bound is something we can deduce.
1225      NonTypeTemplateParmDecl *NTTP
1226        = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1227      if (!NTTP)
1228        return Sema::TDK_Success;
1229
1230      // We can perform template argument deduction for the given non-type
1231      // template parameter.
1232      assert(NTTP->getDepth() == 0 &&
1233             "Cannot deduce non-type template argument at depth > 0");
1234      if (const ConstantArrayType *ConstantArrayArg
1235            = dyn_cast<ConstantArrayType>(ArrayArg)) {
1236        llvm::APSInt Size(ConstantArrayArg->getSize());
1237        return DeduceNonTypeTemplateArgument(S, NTTP, Size,
1238                                             S.Context.getSizeType(),
1239                                             /*ArrayBound=*/true,
1240                                             Info, Deduced);
1241      }
1242      if (const DependentSizedArrayType *DependentArrayArg
1243            = dyn_cast<DependentSizedArrayType>(ArrayArg))
1244        if (DependentArrayArg->getSizeExpr())
1245          return DeduceNonTypeTemplateArgument(S, NTTP,
1246                                               DependentArrayArg->getSizeExpr(),
1247                                               Info, Deduced);
1248
1249      // Incomplete type does not match a dependently-sized array type
1250      return Sema::TDK_NonDeducedMismatch;
1251    }
1252
1253    //     type(*)(T)
1254    //     T(*)()
1255    //     T(*)(T)
1256    case Type::FunctionProto: {
1257      unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
1258      const FunctionProtoType *FunctionProtoArg =
1259        dyn_cast<FunctionProtoType>(Arg);
1260      if (!FunctionProtoArg)
1261        return Sema::TDK_NonDeducedMismatch;
1262
1263      const FunctionProtoType *FunctionProtoParam =
1264        cast<FunctionProtoType>(Param);
1265
1266      if (FunctionProtoParam->getTypeQuals()
1267            != FunctionProtoArg->getTypeQuals() ||
1268          FunctionProtoParam->getRefQualifier()
1269            != FunctionProtoArg->getRefQualifier() ||
1270          FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
1271        return Sema::TDK_NonDeducedMismatch;
1272
1273      // Check return types.
1274      if (Sema::TemplateDeductionResult Result
1275            = DeduceTemplateArguments(S, TemplateParams,
1276                                      FunctionProtoParam->getResultType(),
1277                                      FunctionProtoArg->getResultType(),
1278                                      Info, Deduced, 0))
1279        return Result;
1280
1281      return DeduceTemplateArguments(S, TemplateParams,
1282                                     FunctionProtoParam->arg_type_begin(),
1283                                     FunctionProtoParam->getNumArgs(),
1284                                     FunctionProtoArg->arg_type_begin(),
1285                                     FunctionProtoArg->getNumArgs(),
1286                                     Info, Deduced, SubTDF);
1287    }
1288
1289    case Type::InjectedClassName: {
1290      // Treat a template's injected-class-name as if the template
1291      // specialization type had been used.
1292      Param = cast<InjectedClassNameType>(Param)
1293        ->getInjectedSpecializationType();
1294      assert(isa<TemplateSpecializationType>(Param) &&
1295             "injected class name is not a template specialization type");
1296      // fall through
1297    }
1298
1299    //     template-name<T> (where template-name refers to a class template)
1300    //     template-name<i>
1301    //     TT<T>
1302    //     TT<i>
1303    //     TT<>
1304    case Type::TemplateSpecialization: {
1305      const TemplateSpecializationType *SpecParam
1306        = cast<TemplateSpecializationType>(Param);
1307
1308      // Try to deduce template arguments from the template-id.
1309      Sema::TemplateDeductionResult Result
1310        = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
1311                                  Info, Deduced);
1312
1313      if (Result && (TDF & TDF_DerivedClass)) {
1314        // C++ [temp.deduct.call]p3b3:
1315        //   If P is a class, and P has the form template-id, then A can be a
1316        //   derived class of the deduced A. Likewise, if P is a pointer to a
1317        //   class of the form template-id, A can be a pointer to a derived
1318        //   class pointed to by the deduced A.
1319        //
1320        // More importantly:
1321        //   These alternatives are considered only if type deduction would
1322        //   otherwise fail.
1323        if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1324          // We cannot inspect base classes as part of deduction when the type
1325          // is incomplete, so either instantiate any templates necessary to
1326          // complete the type, or skip over it if it cannot be completed.
1327          if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
1328            return Result;
1329
1330          // Use data recursion to crawl through the list of base classes.
1331          // Visited contains the set of nodes we have already visited, while
1332          // ToVisit is our stack of records that we still need to visit.
1333          llvm::SmallPtrSet<const RecordType *, 8> Visited;
1334          SmallVector<const RecordType *, 8> ToVisit;
1335          ToVisit.push_back(RecordT);
1336          bool Successful = false;
1337          SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1338          DeducedOrig = Deduced;
1339          while (!ToVisit.empty()) {
1340            // Retrieve the next class in the inheritance hierarchy.
1341            const RecordType *NextT = ToVisit.back();
1342            ToVisit.pop_back();
1343
1344            // If we have already seen this type, skip it.
1345            if (!Visited.insert(NextT))
1346              continue;
1347
1348            // If this is a base class, try to perform template argument
1349            // deduction from it.
1350            if (NextT != RecordT) {
1351              Sema::TemplateDeductionResult BaseResult
1352                = DeduceTemplateArguments(S, TemplateParams, SpecParam,
1353                                          QualType(NextT, 0), Info, Deduced);
1354
1355              // If template argument deduction for this base was successful,
1356              // note that we had some success. Otherwise, ignore any deductions
1357              // from this base class.
1358              if (BaseResult == Sema::TDK_Success) {
1359                Successful = true;
1360                DeducedOrig = Deduced;
1361              }
1362              else
1363                Deduced = DeducedOrig;
1364            }
1365
1366            // Visit base classes
1367            CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1368            for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1369                                                 BaseEnd = Next->bases_end();
1370                 Base != BaseEnd; ++Base) {
1371              assert(Base->getType()->isRecordType() &&
1372                     "Base class that isn't a record?");
1373              ToVisit.push_back(Base->getType()->getAs<RecordType>());
1374            }
1375          }
1376
1377          if (Successful)
1378            return Sema::TDK_Success;
1379        }
1380
1381      }
1382
1383      return Result;
1384    }
1385
1386    //     T type::*
1387    //     T T::*
1388    //     T (type::*)()
1389    //     type (T::*)()
1390    //     type (type::*)(T)
1391    //     type (T::*)(T)
1392    //     T (type::*)(T)
1393    //     T (T::*)()
1394    //     T (T::*)(T)
1395    case Type::MemberPointer: {
1396      const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1397      const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1398      if (!MemPtrArg)
1399        return Sema::TDK_NonDeducedMismatch;
1400
1401      if (Sema::TemplateDeductionResult Result
1402            = DeduceTemplateArguments(S, TemplateParams,
1403                                      MemPtrParam->getPointeeType(),
1404                                      MemPtrArg->getPointeeType(),
1405                                      Info, Deduced,
1406                                      TDF & TDF_IgnoreQualifiers))
1407        return Result;
1408
1409      return DeduceTemplateArguments(S, TemplateParams,
1410                                     QualType(MemPtrParam->getClass(), 0),
1411                                     QualType(MemPtrArg->getClass(), 0),
1412                                     Info, Deduced, 0);
1413    }
1414
1415    //     (clang extension)
1416    //
1417    //     type(^)(T)
1418    //     T(^)()
1419    //     T(^)(T)
1420    case Type::BlockPointer: {
1421      const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1422      const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
1423
1424      if (!BlockPtrArg)
1425        return Sema::TDK_NonDeducedMismatch;
1426
1427      return DeduceTemplateArguments(S, TemplateParams,
1428                                     BlockPtrParam->getPointeeType(),
1429                                     BlockPtrArg->getPointeeType(), Info,
1430                                     Deduced, 0);
1431    }
1432
1433    //     (clang extension)
1434    //
1435    //     T __attribute__(((ext_vector_type(<integral constant>))))
1436    case Type::ExtVector: {
1437      const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1438      if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1439        // Make sure that the vectors have the same number of elements.
1440        if (VectorParam->getNumElements() != VectorArg->getNumElements())
1441          return Sema::TDK_NonDeducedMismatch;
1442
1443        // Perform deduction on the element types.
1444        return DeduceTemplateArguments(S, TemplateParams,
1445                                       VectorParam->getElementType(),
1446                                       VectorArg->getElementType(),
1447                                       Info, Deduced,
1448                                       TDF);
1449      }
1450
1451      if (const DependentSizedExtVectorType *VectorArg
1452                                = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1453        // We can't check the number of elements, since the argument has a
1454        // dependent number of elements. This can only occur during partial
1455        // ordering.
1456
1457        // Perform deduction on the element types.
1458        return DeduceTemplateArguments(S, TemplateParams,
1459                                       VectorParam->getElementType(),
1460                                       VectorArg->getElementType(),
1461                                       Info, Deduced,
1462                                       TDF);
1463      }
1464
1465      return Sema::TDK_NonDeducedMismatch;
1466    }
1467
1468    //     (clang extension)
1469    //
1470    //     T __attribute__(((ext_vector_type(N))))
1471    case Type::DependentSizedExtVector: {
1472      const DependentSizedExtVectorType *VectorParam
1473        = cast<DependentSizedExtVectorType>(Param);
1474
1475      if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1476        // Perform deduction on the element types.
1477        if (Sema::TemplateDeductionResult Result
1478              = DeduceTemplateArguments(S, TemplateParams,
1479                                        VectorParam->getElementType(),
1480                                        VectorArg->getElementType(),
1481                                        Info, Deduced,
1482                                        TDF))
1483          return Result;
1484
1485        // Perform deduction on the vector size, if we can.
1486        NonTypeTemplateParmDecl *NTTP
1487          = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1488        if (!NTTP)
1489          return Sema::TDK_Success;
1490
1491        llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1492        ArgSize = VectorArg->getNumElements();
1493        return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1494                                             false, Info, Deduced);
1495      }
1496
1497      if (const DependentSizedExtVectorType *VectorArg
1498                                = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1499        // Perform deduction on the element types.
1500        if (Sema::TemplateDeductionResult Result
1501            = DeduceTemplateArguments(S, TemplateParams,
1502                                      VectorParam->getElementType(),
1503                                      VectorArg->getElementType(),
1504                                      Info, Deduced,
1505                                      TDF))
1506          return Result;
1507
1508        // Perform deduction on the vector size, if we can.
1509        NonTypeTemplateParmDecl *NTTP
1510          = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1511        if (!NTTP)
1512          return Sema::TDK_Success;
1513
1514        return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1515                                             Info, Deduced);
1516      }
1517
1518      return Sema::TDK_NonDeducedMismatch;
1519    }
1520
1521    case Type::TypeOfExpr:
1522    case Type::TypeOf:
1523    case Type::DependentName:
1524    case Type::UnresolvedUsing:
1525    case Type::Decltype:
1526    case Type::UnaryTransform:
1527    case Type::Auto:
1528    case Type::DependentTemplateSpecialization:
1529    case Type::PackExpansion:
1530      // No template argument deduction for these types
1531      return Sema::TDK_Success;
1532  }
1533
1534  return Sema::TDK_Success;
1535}
1536
1537static Sema::TemplateDeductionResult
1538DeduceTemplateArguments(Sema &S,
1539                        TemplateParameterList *TemplateParams,
1540                        const TemplateArgument &Param,
1541                        TemplateArgument Arg,
1542                        TemplateDeductionInfo &Info,
1543                    SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1544  // If the template argument is a pack expansion, perform template argument
1545  // deduction against the pattern of that expansion. This only occurs during
1546  // partial ordering.
1547  if (Arg.isPackExpansion())
1548    Arg = Arg.getPackExpansionPattern();
1549
1550  switch (Param.getKind()) {
1551  case TemplateArgument::Null:
1552    llvm_unreachable("Null template argument in parameter list");
1553
1554  case TemplateArgument::Type:
1555    if (Arg.getKind() == TemplateArgument::Type)
1556      return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
1557                                     Arg.getAsType(), Info, Deduced, 0);
1558    Info.FirstArg = Param;
1559    Info.SecondArg = Arg;
1560    return Sema::TDK_NonDeducedMismatch;
1561
1562  case TemplateArgument::Template:
1563    if (Arg.getKind() == TemplateArgument::Template)
1564      return DeduceTemplateArguments(S, TemplateParams,
1565                                     Param.getAsTemplate(),
1566                                     Arg.getAsTemplate(), Info, Deduced);
1567    Info.FirstArg = Param;
1568    Info.SecondArg = Arg;
1569    return Sema::TDK_NonDeducedMismatch;
1570
1571  case TemplateArgument::TemplateExpansion:
1572    llvm_unreachable("caller should handle pack expansions");
1573    break;
1574
1575  case TemplateArgument::Declaration:
1576    if (Arg.getKind() == TemplateArgument::Declaration &&
1577        Param.getAsDecl()->getCanonicalDecl() ==
1578          Arg.getAsDecl()->getCanonicalDecl())
1579      return Sema::TDK_Success;
1580
1581    Info.FirstArg = Param;
1582    Info.SecondArg = Arg;
1583    return Sema::TDK_NonDeducedMismatch;
1584
1585  case TemplateArgument::Integral:
1586    if (Arg.getKind() == TemplateArgument::Integral) {
1587      if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
1588        return Sema::TDK_Success;
1589
1590      Info.FirstArg = Param;
1591      Info.SecondArg = Arg;
1592      return Sema::TDK_NonDeducedMismatch;
1593    }
1594
1595    if (Arg.getKind() == TemplateArgument::Expression) {
1596      Info.FirstArg = Param;
1597      Info.SecondArg = Arg;
1598      return Sema::TDK_NonDeducedMismatch;
1599    }
1600
1601    Info.FirstArg = Param;
1602    Info.SecondArg = Arg;
1603    return Sema::TDK_NonDeducedMismatch;
1604
1605  case TemplateArgument::Expression: {
1606    if (NonTypeTemplateParmDecl *NTTP
1607          = getDeducedParameterFromExpr(Param.getAsExpr())) {
1608      if (Arg.getKind() == TemplateArgument::Integral)
1609        return DeduceNonTypeTemplateArgument(S, NTTP,
1610                                             *Arg.getAsIntegral(),
1611                                             Arg.getIntegralType(),
1612                                             /*ArrayBound=*/false,
1613                                             Info, Deduced);
1614      if (Arg.getKind() == TemplateArgument::Expression)
1615        return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
1616                                             Info, Deduced);
1617      if (Arg.getKind() == TemplateArgument::Declaration)
1618        return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
1619                                             Info, Deduced);
1620
1621      Info.FirstArg = Param;
1622      Info.SecondArg = Arg;
1623      return Sema::TDK_NonDeducedMismatch;
1624    }
1625
1626    // Can't deduce anything, but that's okay.
1627    return Sema::TDK_Success;
1628  }
1629  case TemplateArgument::Pack:
1630    llvm_unreachable("Argument packs should be expanded by the caller!");
1631  }
1632
1633  return Sema::TDK_Success;
1634}
1635
1636/// \brief Determine whether there is a template argument to be used for
1637/// deduction.
1638///
1639/// This routine "expands" argument packs in-place, overriding its input
1640/// parameters so that \c Args[ArgIdx] will be the available template argument.
1641///
1642/// \returns true if there is another template argument (which will be at
1643/// \c Args[ArgIdx]), false otherwise.
1644static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1645                                            unsigned &ArgIdx,
1646                                            unsigned &NumArgs) {
1647  if (ArgIdx == NumArgs)
1648    return false;
1649
1650  const TemplateArgument &Arg = Args[ArgIdx];
1651  if (Arg.getKind() != TemplateArgument::Pack)
1652    return true;
1653
1654  assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1655  Args = Arg.pack_begin();
1656  NumArgs = Arg.pack_size();
1657  ArgIdx = 0;
1658  return ArgIdx < NumArgs;
1659}
1660
1661/// \brief Determine whether the given set of template arguments has a pack
1662/// expansion that is not the last template argument.
1663static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1664                                      unsigned NumArgs) {
1665  unsigned ArgIdx = 0;
1666  while (ArgIdx < NumArgs) {
1667    const TemplateArgument &Arg = Args[ArgIdx];
1668
1669    // Unwrap argument packs.
1670    if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1671      Args = Arg.pack_begin();
1672      NumArgs = Arg.pack_size();
1673      ArgIdx = 0;
1674      continue;
1675    }
1676
1677    ++ArgIdx;
1678    if (ArgIdx == NumArgs)
1679      return false;
1680
1681    if (Arg.isPackExpansion())
1682      return true;
1683  }
1684
1685  return false;
1686}
1687
1688static Sema::TemplateDeductionResult
1689DeduceTemplateArguments(Sema &S,
1690                        TemplateParameterList *TemplateParams,
1691                        const TemplateArgument *Params, unsigned NumParams,
1692                        const TemplateArgument *Args, unsigned NumArgs,
1693                        TemplateDeductionInfo &Info,
1694                    SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1695                        bool NumberOfArgumentsMustMatch) {
1696  // C++0x [temp.deduct.type]p9:
1697  //   If the template argument list of P contains a pack expansion that is not
1698  //   the last template argument, the entire template argument list is a
1699  //   non-deduced context.
1700  if (hasPackExpansionBeforeEnd(Params, NumParams))
1701    return Sema::TDK_Success;
1702
1703  // C++0x [temp.deduct.type]p9:
1704  //   If P has a form that contains <T> or <i>, then each argument Pi of the
1705  //   respective template argument list P is compared with the corresponding
1706  //   argument Ai of the corresponding template argument list of A.
1707  unsigned ArgIdx = 0, ParamIdx = 0;
1708  for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1709       ++ParamIdx) {
1710    if (!Params[ParamIdx].isPackExpansion()) {
1711      // The simple case: deduce template arguments by matching Pi and Ai.
1712
1713      // Check whether we have enough arguments.
1714      if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
1715        return NumberOfArgumentsMustMatch? Sema::TDK_NonDeducedMismatch
1716                                         : Sema::TDK_Success;
1717
1718      if (Args[ArgIdx].isPackExpansion()) {
1719        // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1720        // but applied to pack expansions that are template arguments.
1721        return Sema::TDK_NonDeducedMismatch;
1722      }
1723
1724      // Perform deduction for this Pi/Ai pair.
1725      if (Sema::TemplateDeductionResult Result
1726            = DeduceTemplateArguments(S, TemplateParams,
1727                                      Params[ParamIdx], Args[ArgIdx],
1728                                      Info, Deduced))
1729        return Result;
1730
1731      // Move to the next argument.
1732      ++ArgIdx;
1733      continue;
1734    }
1735
1736    // The parameter is a pack expansion.
1737
1738    // C++0x [temp.deduct.type]p9:
1739    //   If Pi is a pack expansion, then the pattern of Pi is compared with
1740    //   each remaining argument in the template argument list of A. Each
1741    //   comparison deduces template arguments for subsequent positions in the
1742    //   template parameter packs expanded by Pi.
1743    TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1744
1745    // Compute the set of template parameter indices that correspond to
1746    // parameter packs expanded by the pack expansion.
1747    SmallVector<unsigned, 2> PackIndices;
1748    {
1749      llvm::BitVector SawIndices(TemplateParams->size());
1750      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1751      S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1752      for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1753        unsigned Depth, Index;
1754        llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1755        if (Depth == 0 && !SawIndices[Index]) {
1756          SawIndices[Index] = true;
1757          PackIndices.push_back(Index);
1758        }
1759      }
1760    }
1761    assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1762
1763    // FIXME: If there are no remaining arguments, we can bail out early
1764    // and set any deduced parameter packs to an empty argument pack.
1765    // The latter part of this is a (minor) correctness issue.
1766
1767    // Save the deduced template arguments for each parameter pack expanded
1768    // by this pack expansion, then clear out the deduction.
1769    SmallVector<DeducedTemplateArgument, 2>
1770      SavedPacks(PackIndices.size());
1771    SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2>
1772      NewlyDeducedPacks(PackIndices.size());
1773    PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
1774                                 NewlyDeducedPacks);
1775
1776    // Keep track of the deduced template arguments for each parameter pack
1777    // expanded by this pack expansion (the outer index) and for each
1778    // template argument (the inner SmallVectors).
1779    bool HasAnyArguments = false;
1780    while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1781      HasAnyArguments = true;
1782
1783      // Deduce template arguments from the pattern.
1784      if (Sema::TemplateDeductionResult Result
1785            = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1786                                      Info, Deduced))
1787        return Result;
1788
1789      // Capture the deduced template arguments for each parameter pack expanded
1790      // by this pack expansion, add them to the list of arguments we've deduced
1791      // for that pack, then clear out the deduced argument.
1792      for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1793        DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1794        if (!DeducedArg.isNull()) {
1795          NewlyDeducedPacks[I].push_back(DeducedArg);
1796          DeducedArg = DeducedTemplateArgument();
1797        }
1798      }
1799
1800      ++ArgIdx;
1801    }
1802
1803    // Build argument packs for each of the parameter packs expanded by this
1804    // pack expansion.
1805    if (Sema::TemplateDeductionResult Result
1806          = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
1807                                        Deduced, PackIndices, SavedPacks,
1808                                        NewlyDeducedPacks, Info))
1809      return Result;
1810  }
1811
1812  // If there is an argument remaining, then we had too many arguments.
1813  if (NumberOfArgumentsMustMatch &&
1814      hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
1815    return Sema::TDK_NonDeducedMismatch;
1816
1817  return Sema::TDK_Success;
1818}
1819
1820static Sema::TemplateDeductionResult
1821DeduceTemplateArguments(Sema &S,
1822                        TemplateParameterList *TemplateParams,
1823                        const TemplateArgumentList &ParamList,
1824                        const TemplateArgumentList &ArgList,
1825                        TemplateDeductionInfo &Info,
1826                    SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1827  return DeduceTemplateArguments(S, TemplateParams,
1828                                 ParamList.data(), ParamList.size(),
1829                                 ArgList.data(), ArgList.size(),
1830                                 Info, Deduced);
1831}
1832
1833/// \brief Determine whether two template arguments are the same.
1834static bool isSameTemplateArg(ASTContext &Context,
1835                              const TemplateArgument &X,
1836                              const TemplateArgument &Y) {
1837  if (X.getKind() != Y.getKind())
1838    return false;
1839
1840  switch (X.getKind()) {
1841    case TemplateArgument::Null:
1842      llvm_unreachable("Comparing NULL template argument");
1843
1844    case TemplateArgument::Type:
1845      return Context.getCanonicalType(X.getAsType()) ==
1846             Context.getCanonicalType(Y.getAsType());
1847
1848    case TemplateArgument::Declaration:
1849      return X.getAsDecl()->getCanonicalDecl() ==
1850             Y.getAsDecl()->getCanonicalDecl();
1851
1852    case TemplateArgument::Template:
1853    case TemplateArgument::TemplateExpansion:
1854      return Context.getCanonicalTemplateName(
1855                    X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1856             Context.getCanonicalTemplateName(
1857                    Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
1858
1859    case TemplateArgument::Integral:
1860      return *X.getAsIntegral() == *Y.getAsIntegral();
1861
1862    case TemplateArgument::Expression: {
1863      llvm::FoldingSetNodeID XID, YID;
1864      X.getAsExpr()->Profile(XID, Context, true);
1865      Y.getAsExpr()->Profile(YID, Context, true);
1866      return XID == YID;
1867    }
1868
1869    case TemplateArgument::Pack:
1870      if (X.pack_size() != Y.pack_size())
1871        return false;
1872
1873      for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1874                                        XPEnd = X.pack_end(),
1875                                           YP = Y.pack_begin();
1876           XP != XPEnd; ++XP, ++YP)
1877        if (!isSameTemplateArg(Context, *XP, *YP))
1878          return false;
1879
1880      return true;
1881  }
1882
1883  return false;
1884}
1885
1886/// \brief Allocate a TemplateArgumentLoc where all locations have
1887/// been initialized to the given location.
1888///
1889/// \param S The semantic analysis object.
1890///
1891/// \param The template argument we are producing template argument
1892/// location information for.
1893///
1894/// \param NTTPType For a declaration template argument, the type of
1895/// the non-type template parameter that corresponds to this template
1896/// argument.
1897///
1898/// \param Loc The source location to use for the resulting template
1899/// argument.
1900static TemplateArgumentLoc
1901getTrivialTemplateArgumentLoc(Sema &S,
1902                              const TemplateArgument &Arg,
1903                              QualType NTTPType,
1904                              SourceLocation Loc) {
1905  switch (Arg.getKind()) {
1906  case TemplateArgument::Null:
1907    llvm_unreachable("Can't get a NULL template argument here");
1908    break;
1909
1910  case TemplateArgument::Type:
1911    return TemplateArgumentLoc(Arg,
1912                     S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1913
1914  case TemplateArgument::Declaration: {
1915    Expr *E
1916      = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
1917    .takeAs<Expr>();
1918    return TemplateArgumentLoc(TemplateArgument(E), E);
1919  }
1920
1921  case TemplateArgument::Integral: {
1922    Expr *E
1923      = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
1924    return TemplateArgumentLoc(TemplateArgument(E), E);
1925  }
1926
1927    case TemplateArgument::Template:
1928    case TemplateArgument::TemplateExpansion: {
1929      NestedNameSpecifierLocBuilder Builder;
1930      TemplateName Template = Arg.getAsTemplate();
1931      if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
1932        Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
1933      else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1934        Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
1935
1936      if (Arg.getKind() == TemplateArgument::Template)
1937        return TemplateArgumentLoc(Arg,
1938                                   Builder.getWithLocInContext(S.Context),
1939                                   Loc);
1940
1941
1942      return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
1943                                 Loc, Loc);
1944    }
1945
1946  case TemplateArgument::Expression:
1947    return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1948
1949  case TemplateArgument::Pack:
1950    return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1951  }
1952
1953  return TemplateArgumentLoc();
1954}
1955
1956
1957/// \brief Convert the given deduced template argument and add it to the set of
1958/// fully-converted template arguments.
1959static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1960                                           DeducedTemplateArgument Arg,
1961                                           NamedDecl *Template,
1962                                           QualType NTTPType,
1963                                           unsigned ArgumentPackIndex,
1964                                           TemplateDeductionInfo &Info,
1965                                           bool InFunctionTemplate,
1966                             SmallVectorImpl<TemplateArgument> &Output) {
1967  if (Arg.getKind() == TemplateArgument::Pack) {
1968    // This is a template argument pack, so check each of its arguments against
1969    // the template parameter.
1970    SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1971    for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
1972                                      PAEnd = Arg.pack_end();
1973         PA != PAEnd; ++PA) {
1974      // When converting the deduced template argument, append it to the
1975      // general output list. We need to do this so that the template argument
1976      // checking logic has all of the prior template arguments available.
1977      DeducedTemplateArgument InnerArg(*PA);
1978      InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1979      if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1980                                         NTTPType, PackedArgsBuilder.size(),
1981                                         Info, InFunctionTemplate, Output))
1982        return true;
1983
1984      // Move the converted template argument into our argument pack.
1985      PackedArgsBuilder.push_back(Output.back());
1986      Output.pop_back();
1987    }
1988
1989    // Create the resulting argument pack.
1990    Output.push_back(TemplateArgument::CreatePackCopy(S.Context,
1991                                                      PackedArgsBuilder.data(),
1992                                                     PackedArgsBuilder.size()));
1993    return false;
1994  }
1995
1996  // Convert the deduced template argument into a template
1997  // argument that we can check, almost as if the user had written
1998  // the template argument explicitly.
1999  TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
2000                                                             Info.getLocation());
2001
2002  // Check the template argument, converting it as necessary.
2003  return S.CheckTemplateArgument(Param, ArgLoc,
2004                                 Template,
2005                                 Template->getLocation(),
2006                                 Template->getSourceRange().getEnd(),
2007                                 ArgumentPackIndex,
2008                                 Output,
2009                                 InFunctionTemplate
2010                                  ? (Arg.wasDeducedFromArrayBound()
2011                                       ? Sema::CTAK_DeducedFromArrayBound
2012                                       : Sema::CTAK_Deduced)
2013                                 : Sema::CTAK_Specified);
2014}
2015
2016/// Complete template argument deduction for a class template partial
2017/// specialization.
2018static Sema::TemplateDeductionResult
2019FinishTemplateArgumentDeduction(Sema &S,
2020                                ClassTemplatePartialSpecializationDecl *Partial,
2021                                const TemplateArgumentList &TemplateArgs,
2022                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2023                                TemplateDeductionInfo &Info) {
2024  // Trap errors.
2025  Sema::SFINAETrap Trap(S);
2026
2027  Sema::ContextRAII SavedContext(S, Partial);
2028
2029  // C++ [temp.deduct.type]p2:
2030  //   [...] or if any template argument remains neither deduced nor
2031  //   explicitly specified, template argument deduction fails.
2032  SmallVector<TemplateArgument, 4> Builder;
2033  TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2034  for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2035    NamedDecl *Param = PartialParams->getParam(I);
2036    if (Deduced[I].isNull()) {
2037      Info.Param = makeTemplateParameter(Param);
2038      return Sema::TDK_Incomplete;
2039    }
2040
2041    // We have deduced this argument, so it still needs to be
2042    // checked and converted.
2043
2044    // First, for a non-type template parameter type that is
2045    // initialized by a declaration, we need the type of the
2046    // corresponding non-type template parameter.
2047    QualType NTTPType;
2048    if (NonTypeTemplateParmDecl *NTTP
2049                                  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2050      NTTPType = NTTP->getType();
2051      if (NTTPType->isDependentType()) {
2052        TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2053                                          Builder.data(), Builder.size());
2054        NTTPType = S.SubstType(NTTPType,
2055                               MultiLevelTemplateArgumentList(TemplateArgs),
2056                               NTTP->getLocation(),
2057                               NTTP->getDeclName());
2058        if (NTTPType.isNull()) {
2059          Info.Param = makeTemplateParameter(Param);
2060          // FIXME: These template arguments are temporary. Free them!
2061          Info.reset(TemplateArgumentList::CreateCopy(S.Context,
2062                                                      Builder.data(),
2063                                                      Builder.size()));
2064          return Sema::TDK_SubstitutionFailure;
2065        }
2066      }
2067    }
2068
2069    if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
2070                                       Partial, NTTPType, 0, Info, false,
2071                                       Builder)) {
2072      Info.Param = makeTemplateParameter(Param);
2073      // FIXME: These template arguments are temporary. Free them!
2074      Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2075                                                  Builder.size()));
2076      return Sema::TDK_SubstitutionFailure;
2077    }
2078  }
2079
2080  // Form the template argument list from the deduced template arguments.
2081  TemplateArgumentList *DeducedArgumentList
2082    = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2083                                       Builder.size());
2084
2085  Info.reset(DeducedArgumentList);
2086
2087  // Substitute the deduced template arguments into the template
2088  // arguments of the class template partial specialization, and
2089  // verify that the instantiated template arguments are both valid
2090  // and are equivalent to the template arguments originally provided
2091  // to the class template.
2092  LocalInstantiationScope InstScope(S);
2093  ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
2094  const TemplateArgumentLoc *PartialTemplateArgs
2095    = Partial->getTemplateArgsAsWritten();
2096
2097  // Note that we don't provide the langle and rangle locations.
2098  TemplateArgumentListInfo InstArgs;
2099
2100  if (S.Subst(PartialTemplateArgs,
2101              Partial->getNumTemplateArgsAsWritten(),
2102              InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2103    unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2104    if (ParamIdx >= Partial->getTemplateParameters()->size())
2105      ParamIdx = Partial->getTemplateParameters()->size() - 1;
2106
2107    Decl *Param
2108      = const_cast<NamedDecl *>(
2109                          Partial->getTemplateParameters()->getParam(ParamIdx));
2110    Info.Param = makeTemplateParameter(Param);
2111    Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2112    return Sema::TDK_SubstitutionFailure;
2113  }
2114
2115  SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2116  if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
2117                                  InstArgs, false, ConvertedInstArgs))
2118    return Sema::TDK_SubstitutionFailure;
2119
2120  TemplateParameterList *TemplateParams
2121    = ClassTemplate->getTemplateParameters();
2122  for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2123    TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2124    if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2125      Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2126      Info.FirstArg = TemplateArgs[I];
2127      Info.SecondArg = InstArg;
2128      return Sema::TDK_NonDeducedMismatch;
2129    }
2130  }
2131
2132  if (Trap.hasErrorOccurred())
2133    return Sema::TDK_SubstitutionFailure;
2134
2135  return Sema::TDK_Success;
2136}
2137
2138/// \brief Perform template argument deduction to determine whether
2139/// the given template arguments match the given class template
2140/// partial specialization per C++ [temp.class.spec.match].
2141Sema::TemplateDeductionResult
2142Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
2143                              const TemplateArgumentList &TemplateArgs,
2144                              TemplateDeductionInfo &Info) {
2145  // C++ [temp.class.spec.match]p2:
2146  //   A partial specialization matches a given actual template
2147  //   argument list if the template arguments of the partial
2148  //   specialization can be deduced from the actual template argument
2149  //   list (14.8.2).
2150  SFINAETrap Trap(*this);
2151  SmallVector<DeducedTemplateArgument, 4> Deduced;
2152  Deduced.resize(Partial->getTemplateParameters()->size());
2153  if (TemplateDeductionResult Result
2154        = ::DeduceTemplateArguments(*this,
2155                                    Partial->getTemplateParameters(),
2156                                    Partial->getTemplateArgs(),
2157                                    TemplateArgs, Info, Deduced))
2158    return Result;
2159
2160  InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
2161                             Deduced.data(), Deduced.size(), Info);
2162  if (Inst)
2163    return TDK_InstantiationDepth;
2164
2165  if (Trap.hasErrorOccurred())
2166    return Sema::TDK_SubstitutionFailure;
2167
2168  return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2169                                           Deduced, Info);
2170}
2171
2172/// \brief Determine whether the given type T is a simple-template-id type.
2173static bool isSimpleTemplateIdType(QualType T) {
2174  if (const TemplateSpecializationType *Spec
2175        = T->getAs<TemplateSpecializationType>())
2176    return Spec->getTemplateName().getAsTemplateDecl() != 0;
2177
2178  return false;
2179}
2180
2181/// \brief Substitute the explicitly-provided template arguments into the
2182/// given function template according to C++ [temp.arg.explicit].
2183///
2184/// \param FunctionTemplate the function template into which the explicit
2185/// template arguments will be substituted.
2186///
2187/// \param ExplicitTemplateArguments the explicitly-specified template
2188/// arguments.
2189///
2190/// \param Deduced the deduced template arguments, which will be populated
2191/// with the converted and checked explicit template arguments.
2192///
2193/// \param ParamTypes will be populated with the instantiated function
2194/// parameters.
2195///
2196/// \param FunctionType if non-NULL, the result type of the function template
2197/// will also be instantiated and the pointed-to value will be updated with
2198/// the instantiated function type.
2199///
2200/// \param Info if substitution fails for any reason, this object will be
2201/// populated with more information about the failure.
2202///
2203/// \returns TDK_Success if substitution was successful, or some failure
2204/// condition.
2205Sema::TemplateDeductionResult
2206Sema::SubstituteExplicitTemplateArguments(
2207                                      FunctionTemplateDecl *FunctionTemplate,
2208                               TemplateArgumentListInfo &ExplicitTemplateArgs,
2209                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2210                                 SmallVectorImpl<QualType> &ParamTypes,
2211                                          QualType *FunctionType,
2212                                          TemplateDeductionInfo &Info) {
2213  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2214  TemplateParameterList *TemplateParams
2215    = FunctionTemplate->getTemplateParameters();
2216
2217  if (ExplicitTemplateArgs.size() == 0) {
2218    // No arguments to substitute; just copy over the parameter types and
2219    // fill in the function type.
2220    for (FunctionDecl::param_iterator P = Function->param_begin(),
2221                                   PEnd = Function->param_end();
2222         P != PEnd;
2223         ++P)
2224      ParamTypes.push_back((*P)->getType());
2225
2226    if (FunctionType)
2227      *FunctionType = Function->getType();
2228    return TDK_Success;
2229  }
2230
2231  // Substitution of the explicit template arguments into a function template
2232  /// is a SFINAE context. Trap any errors that might occur.
2233  SFINAETrap Trap(*this);
2234
2235  // C++ [temp.arg.explicit]p3:
2236  //   Template arguments that are present shall be specified in the
2237  //   declaration order of their corresponding template-parameters. The
2238  //   template argument list shall not specify more template-arguments than
2239  //   there are corresponding template-parameters.
2240  SmallVector<TemplateArgument, 4> Builder;
2241
2242  // Enter a new template instantiation context where we check the
2243  // explicitly-specified template arguments against this function template,
2244  // and then substitute them into the function parameter types.
2245  InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
2246                             FunctionTemplate, Deduced.data(), Deduced.size(),
2247           ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2248                             Info);
2249  if (Inst)
2250    return TDK_InstantiationDepth;
2251
2252  if (CheckTemplateArgumentList(FunctionTemplate,
2253                                SourceLocation(),
2254                                ExplicitTemplateArgs,
2255                                true,
2256                                Builder) || Trap.hasErrorOccurred()) {
2257    unsigned Index = Builder.size();
2258    if (Index >= TemplateParams->size())
2259      Index = TemplateParams->size() - 1;
2260    Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
2261    return TDK_InvalidExplicitArguments;
2262  }
2263
2264  // Form the template argument list from the explicitly-specified
2265  // template arguments.
2266  TemplateArgumentList *ExplicitArgumentList
2267    = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
2268  Info.reset(ExplicitArgumentList);
2269
2270  // Template argument deduction and the final substitution should be
2271  // done in the context of the templated declaration.  Explicit
2272  // argument substitution, on the other hand, needs to happen in the
2273  // calling context.
2274  ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2275
2276  // If we deduced template arguments for a template parameter pack,
2277  // note that the template argument pack is partially substituted and record
2278  // the explicit template arguments. They'll be used as part of deduction
2279  // for this template parameter pack.
2280  for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2281    const TemplateArgument &Arg = Builder[I];
2282    if (Arg.getKind() == TemplateArgument::Pack) {
2283      CurrentInstantiationScope->SetPartiallySubstitutedPack(
2284                                                 TemplateParams->getParam(I),
2285                                                             Arg.pack_begin(),
2286                                                             Arg.pack_size());
2287      break;
2288    }
2289  }
2290
2291  // Instantiate the types of each of the function parameters given the
2292  // explicitly-specified template arguments.
2293  if (SubstParmTypes(Function->getLocation(),
2294                     Function->param_begin(), Function->getNumParams(),
2295                     MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2296                     ParamTypes))
2297    return TDK_SubstitutionFailure;
2298
2299  // If the caller wants a full function type back, instantiate the return
2300  // type and form that function type.
2301  if (FunctionType) {
2302    // FIXME: exception-specifications?
2303    const FunctionProtoType *Proto
2304      = Function->getType()->getAs<FunctionProtoType>();
2305    assert(Proto && "Function template does not have a prototype?");
2306
2307    QualType ResultType
2308      = SubstType(Proto->getResultType(),
2309                  MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2310                  Function->getTypeSpecStartLoc(),
2311                  Function->getDeclName());
2312    if (ResultType.isNull() || Trap.hasErrorOccurred())
2313      return TDK_SubstitutionFailure;
2314
2315    *FunctionType = BuildFunctionType(ResultType,
2316                                      ParamTypes.data(), ParamTypes.size(),
2317                                      Proto->isVariadic(),
2318                                      Proto->getTypeQuals(),
2319                                      Proto->getRefQualifier(),
2320                                      Function->getLocation(),
2321                                      Function->getDeclName(),
2322                                      Proto->getExtInfo());
2323    if (FunctionType->isNull() || Trap.hasErrorOccurred())
2324      return TDK_SubstitutionFailure;
2325  }
2326
2327  // C++ [temp.arg.explicit]p2:
2328  //   Trailing template arguments that can be deduced (14.8.2) may be
2329  //   omitted from the list of explicit template-arguments. If all of the
2330  //   template arguments can be deduced, they may all be omitted; in this
2331  //   case, the empty template argument list <> itself may also be omitted.
2332  //
2333  // Take all of the explicitly-specified arguments and put them into
2334  // the set of deduced template arguments. Explicitly-specified
2335  // parameter packs, however, will be set to NULL since the deduction
2336  // mechanisms handle explicitly-specified argument packs directly.
2337  Deduced.reserve(TemplateParams->size());
2338  for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2339    const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2340    if (Arg.getKind() == TemplateArgument::Pack)
2341      Deduced.push_back(DeducedTemplateArgument());
2342    else
2343      Deduced.push_back(Arg);
2344  }
2345
2346  return TDK_Success;
2347}
2348
2349/// \brief Check whether the deduced argument type for a call to a function
2350/// template matches the actual argument type per C++ [temp.deduct.call]p4.
2351static bool
2352CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2353                              QualType DeducedA) {
2354  ASTContext &Context = S.Context;
2355
2356  QualType A = OriginalArg.OriginalArgType;
2357  QualType OriginalParamType = OriginalArg.OriginalParamType;
2358
2359  // Check for type equality (top-level cv-qualifiers are ignored).
2360  if (Context.hasSameUnqualifiedType(A, DeducedA))
2361    return false;
2362
2363  // Strip off references on the argument types; they aren't needed for
2364  // the following checks.
2365  if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2366    DeducedA = DeducedARef->getPointeeType();
2367  if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2368    A = ARef->getPointeeType();
2369
2370  // C++ [temp.deduct.call]p4:
2371  //   [...] However, there are three cases that allow a difference:
2372  //     - If the original P is a reference type, the deduced A (i.e., the
2373  //       type referred to by the reference) can be more cv-qualified than
2374  //       the transformed A.
2375  if (const ReferenceType *OriginalParamRef
2376      = OriginalParamType->getAs<ReferenceType>()) {
2377    // We don't want to keep the reference around any more.
2378    OriginalParamType = OriginalParamRef->getPointeeType();
2379
2380    Qualifiers AQuals = A.getQualifiers();
2381    Qualifiers DeducedAQuals = DeducedA.getQualifiers();
2382    if (AQuals == DeducedAQuals) {
2383      // Qualifiers match; there's nothing to do.
2384    } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
2385      return true;
2386    } else {
2387      // Qualifiers are compatible, so have the argument type adopt the
2388      // deduced argument type's qualifiers as if we had performed the
2389      // qualification conversion.
2390      A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2391    }
2392  }
2393
2394  //    - The transformed A can be another pointer or pointer to member
2395  //      type that can be converted to the deduced A via a qualification
2396  //      conversion.
2397  //
2398  // Also allow conversions which merely strip [[noreturn]] from function types
2399  // (recursively) as an extension.
2400  // FIXME: Currently, this doesn't place nicely with qualfication conversions.
2401  bool ObjCLifetimeConversion = false;
2402  QualType ResultTy;
2403  if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
2404      (S.IsQualificationConversion(A, DeducedA, false,
2405                                   ObjCLifetimeConversion) ||
2406       S.IsNoReturnConversion(A, DeducedA, ResultTy)))
2407    return false;
2408
2409
2410  //    - If P is a class and P has the form simple-template-id, then the
2411  //      transformed A can be a derived class of the deduced A. [...]
2412  //     [...] Likewise, if P is a pointer to a class of the form
2413  //      simple-template-id, the transformed A can be a pointer to a
2414  //      derived class pointed to by the deduced A.
2415  if (const PointerType *OriginalParamPtr
2416      = OriginalParamType->getAs<PointerType>()) {
2417    if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2418      if (const PointerType *APtr = A->getAs<PointerType>()) {
2419        if (A->getPointeeType()->isRecordType()) {
2420          OriginalParamType = OriginalParamPtr->getPointeeType();
2421          DeducedA = DeducedAPtr->getPointeeType();
2422          A = APtr->getPointeeType();
2423        }
2424      }
2425    }
2426  }
2427
2428  if (Context.hasSameUnqualifiedType(A, DeducedA))
2429    return false;
2430
2431  if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2432      S.IsDerivedFrom(A, DeducedA))
2433    return false;
2434
2435  return true;
2436}
2437
2438/// \brief Finish template argument deduction for a function template,
2439/// checking the deduced template arguments for completeness and forming
2440/// the function template specialization.
2441///
2442/// \param OriginalCallArgs If non-NULL, the original call arguments against
2443/// which the deduced argument types should be compared.
2444Sema::TemplateDeductionResult
2445Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
2446                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2447                                      unsigned NumExplicitlySpecified,
2448                                      FunctionDecl *&Specialization,
2449                                      TemplateDeductionInfo &Info,
2450        SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs) {
2451  TemplateParameterList *TemplateParams
2452    = FunctionTemplate->getTemplateParameters();
2453
2454  // Template argument deduction for function templates in a SFINAE context.
2455  // Trap any errors that might occur.
2456  SFINAETrap Trap(*this);
2457
2458  // Enter a new template instantiation context while we instantiate the
2459  // actual function declaration.
2460  InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
2461                             FunctionTemplate, Deduced.data(), Deduced.size(),
2462              ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2463                             Info);
2464  if (Inst)
2465    return TDK_InstantiationDepth;
2466
2467  ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2468
2469  // C++ [temp.deduct.type]p2:
2470  //   [...] or if any template argument remains neither deduced nor
2471  //   explicitly specified, template argument deduction fails.
2472  SmallVector<TemplateArgument, 4> Builder;
2473  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2474    NamedDecl *Param = TemplateParams->getParam(I);
2475
2476    if (!Deduced[I].isNull()) {
2477      if (I < NumExplicitlySpecified) {
2478        // We have already fully type-checked and converted this
2479        // argument, because it was explicitly-specified. Just record the
2480        // presence of this argument.
2481        Builder.push_back(Deduced[I]);
2482        continue;
2483      }
2484
2485      // We have deduced this argument, so it still needs to be
2486      // checked and converted.
2487
2488      // First, for a non-type template parameter type that is
2489      // initialized by a declaration, we need the type of the
2490      // corresponding non-type template parameter.
2491      QualType NTTPType;
2492      if (NonTypeTemplateParmDecl *NTTP
2493                                = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2494        NTTPType = NTTP->getType();
2495        if (NTTPType->isDependentType()) {
2496          TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2497                                            Builder.data(), Builder.size());
2498          NTTPType = SubstType(NTTPType,
2499                               MultiLevelTemplateArgumentList(TemplateArgs),
2500                               NTTP->getLocation(),
2501                               NTTP->getDeclName());
2502          if (NTTPType.isNull()) {
2503            Info.Param = makeTemplateParameter(Param);
2504            // FIXME: These template arguments are temporary. Free them!
2505            Info.reset(TemplateArgumentList::CreateCopy(Context,
2506                                                        Builder.data(),
2507                                                        Builder.size()));
2508            return TDK_SubstitutionFailure;
2509          }
2510        }
2511      }
2512
2513      if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2514                                         FunctionTemplate, NTTPType, 0, Info,
2515                                         true, Builder)) {
2516        Info.Param = makeTemplateParameter(Param);
2517        // FIXME: These template arguments are temporary. Free them!
2518        Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2519                                                    Builder.size()));
2520        return TDK_SubstitutionFailure;
2521      }
2522
2523      continue;
2524    }
2525
2526    // C++0x [temp.arg.explicit]p3:
2527    //    A trailing template parameter pack (14.5.3) not otherwise deduced will
2528    //    be deduced to an empty sequence of template arguments.
2529    // FIXME: Where did the word "trailing" come from?
2530    if (Param->isTemplateParameterPack()) {
2531      // We may have had explicitly-specified template arguments for this
2532      // template parameter pack. If so, our empty deduction extends the
2533      // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2534      const TemplateArgument *ExplicitArgs;
2535      unsigned NumExplicitArgs;
2536      if (CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
2537                                                             &NumExplicitArgs)
2538          == Param)
2539        Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
2540      else
2541        Builder.push_back(TemplateArgument(0, 0));
2542
2543      continue;
2544    }
2545
2546    // Substitute into the default template argument, if available.
2547    TemplateArgumentLoc DefArg
2548      = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2549                                              FunctionTemplate->getLocation(),
2550                                  FunctionTemplate->getSourceRange().getEnd(),
2551                                                Param,
2552                                                Builder);
2553
2554    // If there was no default argument, deduction is incomplete.
2555    if (DefArg.getArgument().isNull()) {
2556      Info.Param = makeTemplateParameter(
2557                         const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2558      return TDK_Incomplete;
2559    }
2560
2561    // Check whether we can actually use the default argument.
2562    if (CheckTemplateArgument(Param, DefArg,
2563                              FunctionTemplate,
2564                              FunctionTemplate->getLocation(),
2565                              FunctionTemplate->getSourceRange().getEnd(),
2566                              0, Builder,
2567                              CTAK_Specified)) {
2568      Info.Param = makeTemplateParameter(
2569                         const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2570      // FIXME: These template arguments are temporary. Free them!
2571      Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2572                                                  Builder.size()));
2573      return TDK_SubstitutionFailure;
2574    }
2575
2576    // If we get here, we successfully used the default template argument.
2577  }
2578
2579  // Form the template argument list from the deduced template arguments.
2580  TemplateArgumentList *DeducedArgumentList
2581    = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
2582  Info.reset(DeducedArgumentList);
2583
2584  // Substitute the deduced template arguments into the function template
2585  // declaration to produce the function template specialization.
2586  DeclContext *Owner = FunctionTemplate->getDeclContext();
2587  if (FunctionTemplate->getFriendObjectKind())
2588    Owner = FunctionTemplate->getLexicalDeclContext();
2589  Specialization = cast_or_null<FunctionDecl>(
2590                      SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
2591                         MultiLevelTemplateArgumentList(*DeducedArgumentList)));
2592  if (!Specialization)
2593    return TDK_SubstitutionFailure;
2594
2595  assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2596         FunctionTemplate->getCanonicalDecl());
2597
2598  // If the template argument list is owned by the function template
2599  // specialization, release it.
2600  if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2601      !Trap.hasErrorOccurred())
2602    Info.take();
2603
2604  if (OriginalCallArgs) {
2605    // C++ [temp.deduct.call]p4:
2606    //   In general, the deduction process attempts to find template argument
2607    //   values that will make the deduced A identical to A (after the type A
2608    //   is transformed as described above). [...]
2609    for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2610      OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
2611      unsigned ParamIdx = OriginalArg.ArgIdx;
2612
2613      if (ParamIdx >= Specialization->getNumParams())
2614        continue;
2615
2616      QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
2617      if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA))
2618        return Sema::TDK_SubstitutionFailure;
2619    }
2620  }
2621
2622  // There may have been an error that did not prevent us from constructing a
2623  // declaration. Mark the declaration invalid and return with a substitution
2624  // failure.
2625  if (Trap.hasErrorOccurred()) {
2626    Specialization->setInvalidDecl(true);
2627    return TDK_SubstitutionFailure;
2628  }
2629
2630  // If we suppressed any diagnostics while performing template argument
2631  // deduction, and if we haven't already instantiated this declaration,
2632  // keep track of these diagnostics. They'll be emitted if this specialization
2633  // is actually used.
2634  if (Info.diag_begin() != Info.diag_end()) {
2635    llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
2636      Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2637    if (Pos == SuppressedDiagnostics.end())
2638        SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2639          .append(Info.diag_begin(), Info.diag_end());
2640  }
2641
2642  return TDK_Success;
2643}
2644
2645/// Gets the type of a function for template-argument-deducton
2646/// purposes when it's considered as part of an overload set.
2647static QualType GetTypeOfFunction(ASTContext &Context,
2648                                  const OverloadExpr::FindResult &R,
2649                                  FunctionDecl *Fn) {
2650  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
2651    if (Method->isInstance()) {
2652      // An instance method that's referenced in a form that doesn't
2653      // look like a member pointer is just invalid.
2654      if (!R.HasFormOfMemberPointer) return QualType();
2655
2656      return Context.getMemberPointerType(Fn->getType(),
2657               Context.getTypeDeclType(Method->getParent()).getTypePtr());
2658    }
2659
2660  if (!R.IsAddressOfOperand) return Fn->getType();
2661  return Context.getPointerType(Fn->getType());
2662}
2663
2664/// Apply the deduction rules for overload sets.
2665///
2666/// \return the null type if this argument should be treated as an
2667/// undeduced context
2668static QualType
2669ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
2670                            Expr *Arg, QualType ParamType,
2671                            bool ParamWasReference) {
2672
2673  OverloadExpr::FindResult R = OverloadExpr::find(Arg);
2674
2675  OverloadExpr *Ovl = R.Expression;
2676
2677  // C++0x [temp.deduct.call]p4
2678  unsigned TDF = 0;
2679  if (ParamWasReference)
2680    TDF |= TDF_ParamWithReferenceType;
2681  if (R.IsAddressOfOperand)
2682    TDF |= TDF_IgnoreQualifiers;
2683
2684  // If there were explicit template arguments, we can only find
2685  // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2686  // unambiguously name a full specialization.
2687  if (Ovl->hasExplicitTemplateArgs()) {
2688    // But we can still look for an explicit specialization.
2689    if (FunctionDecl *ExplicitSpec
2690          = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
2691      return GetTypeOfFunction(S.Context, R, ExplicitSpec);
2692    return QualType();
2693  }
2694
2695  // C++0x [temp.deduct.call]p6:
2696  //   When P is a function type, pointer to function type, or pointer
2697  //   to member function type:
2698
2699  if (!ParamType->isFunctionType() &&
2700      !ParamType->isFunctionPointerType() &&
2701      !ParamType->isMemberFunctionPointerType())
2702    return QualType();
2703
2704  QualType Match;
2705  for (UnresolvedSetIterator I = Ovl->decls_begin(),
2706         E = Ovl->decls_end(); I != E; ++I) {
2707    NamedDecl *D = (*I)->getUnderlyingDecl();
2708
2709    //   - If the argument is an overload set containing one or more
2710    //     function templates, the parameter is treated as a
2711    //     non-deduced context.
2712    if (isa<FunctionTemplateDecl>(D))
2713      return QualType();
2714
2715    FunctionDecl *Fn = cast<FunctionDecl>(D);
2716    QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2717    if (ArgType.isNull()) continue;
2718
2719    // Function-to-pointer conversion.
2720    if (!ParamWasReference && ParamType->isPointerType() &&
2721        ArgType->isFunctionType())
2722      ArgType = S.Context.getPointerType(ArgType);
2723
2724    //   - If the argument is an overload set (not containing function
2725    //     templates), trial argument deduction is attempted using each
2726    //     of the members of the set. If deduction succeeds for only one
2727    //     of the overload set members, that member is used as the
2728    //     argument value for the deduction. If deduction succeeds for
2729    //     more than one member of the overload set the parameter is
2730    //     treated as a non-deduced context.
2731
2732    // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2733    //   Type deduction is done independently for each P/A pair, and
2734    //   the deduced template argument values are then combined.
2735    // So we do not reject deductions which were made elsewhere.
2736    SmallVector<DeducedTemplateArgument, 8>
2737      Deduced(TemplateParams->size());
2738    TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
2739    Sema::TemplateDeductionResult Result
2740      = DeduceTemplateArguments(S, TemplateParams,
2741                                ParamType, ArgType,
2742                                Info, Deduced, TDF);
2743    if (Result) continue;
2744    if (!Match.isNull()) return QualType();
2745    Match = ArgType;
2746  }
2747
2748  return Match;
2749}
2750
2751/// \brief Perform the adjustments to the parameter and argument types
2752/// described in C++ [temp.deduct.call].
2753///
2754/// \returns true if the caller should not attempt to perform any template
2755/// argument deduction based on this P/A pair.
2756static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2757                                          TemplateParameterList *TemplateParams,
2758                                                      QualType &ParamType,
2759                                                      QualType &ArgType,
2760                                                      Expr *Arg,
2761                                                      unsigned &TDF) {
2762  // C++0x [temp.deduct.call]p3:
2763  //   If P is a cv-qualified type, the top level cv-qualifiers of P's type
2764  //   are ignored for type deduction.
2765  if (ParamType.hasQualifiers())
2766    ParamType = ParamType.getUnqualifiedType();
2767  const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2768  if (ParamRefType) {
2769    QualType PointeeType = ParamRefType->getPointeeType();
2770
2771    // If the argument has incomplete array type, try to complete it's type.
2772    if (ArgType->isIncompleteArrayType() &&
2773        !S.RequireCompleteExprType(Arg, S.PDiag(),
2774                                   std::make_pair(SourceLocation(), S.PDiag())))
2775      ArgType = Arg->getType();
2776
2777    //   [C++0x] If P is an rvalue reference to a cv-unqualified
2778    //   template parameter and the argument is an lvalue, the type
2779    //   "lvalue reference to A" is used in place of A for type
2780    //   deduction.
2781    if (isa<RValueReferenceType>(ParamType)) {
2782      if (!PointeeType.getQualifiers() &&
2783          isa<TemplateTypeParmType>(PointeeType) &&
2784          Arg->Classify(S.Context).isLValue() &&
2785          Arg->getType() != S.Context.OverloadTy &&
2786          Arg->getType() != S.Context.BoundMemberTy)
2787        ArgType = S.Context.getLValueReferenceType(ArgType);
2788    }
2789
2790    //   [...] If P is a reference type, the type referred to by P is used
2791    //   for type deduction.
2792    ParamType = PointeeType;
2793  }
2794
2795  // Overload sets usually make this parameter an undeduced
2796  // context, but there are sometimes special circumstances.
2797  if (ArgType == S.Context.OverloadTy) {
2798    ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2799                                          Arg, ParamType,
2800                                          ParamRefType != 0);
2801    if (ArgType.isNull())
2802      return true;
2803  }
2804
2805  if (ParamRefType) {
2806    // C++0x [temp.deduct.call]p3:
2807    //   [...] If P is of the form T&&, where T is a template parameter, and
2808    //   the argument is an lvalue, the type A& is used in place of A for
2809    //   type deduction.
2810    if (ParamRefType->isRValueReferenceType() &&
2811        ParamRefType->getAs<TemplateTypeParmType>() &&
2812        Arg->isLValue())
2813      ArgType = S.Context.getLValueReferenceType(ArgType);
2814  } else {
2815    // C++ [temp.deduct.call]p2:
2816    //   If P is not a reference type:
2817    //   - If A is an array type, the pointer type produced by the
2818    //     array-to-pointer standard conversion (4.2) is used in place of
2819    //     A for type deduction; otherwise,
2820    if (ArgType->isArrayType())
2821      ArgType = S.Context.getArrayDecayedType(ArgType);
2822    //   - If A is a function type, the pointer type produced by the
2823    //     function-to-pointer standard conversion (4.3) is used in place
2824    //     of A for type deduction; otherwise,
2825    else if (ArgType->isFunctionType())
2826      ArgType = S.Context.getPointerType(ArgType);
2827    else {
2828      // - If A is a cv-qualified type, the top level cv-qualifiers of A's
2829      //   type are ignored for type deduction.
2830      ArgType = ArgType.getUnqualifiedType();
2831    }
2832  }
2833
2834  // C++0x [temp.deduct.call]p4:
2835  //   In general, the deduction process attempts to find template argument
2836  //   values that will make the deduced A identical to A (after the type A
2837  //   is transformed as described above). [...]
2838  TDF = TDF_SkipNonDependent;
2839
2840  //     - If the original P is a reference type, the deduced A (i.e., the
2841  //       type referred to by the reference) can be more cv-qualified than
2842  //       the transformed A.
2843  if (ParamRefType)
2844    TDF |= TDF_ParamWithReferenceType;
2845  //     - The transformed A can be another pointer or pointer to member
2846  //       type that can be converted to the deduced A via a qualification
2847  //       conversion (4.4).
2848  if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2849      ArgType->isObjCObjectPointerType())
2850    TDF |= TDF_IgnoreQualifiers;
2851  //     - If P is a class and P has the form simple-template-id, then the
2852  //       transformed A can be a derived class of the deduced A. Likewise,
2853  //       if P is a pointer to a class of the form simple-template-id, the
2854  //       transformed A can be a pointer to a derived class pointed to by
2855  //       the deduced A.
2856  if (isSimpleTemplateIdType(ParamType) ||
2857      (isa<PointerType>(ParamType) &&
2858       isSimpleTemplateIdType(
2859                              ParamType->getAs<PointerType>()->getPointeeType())))
2860    TDF |= TDF_DerivedClass;
2861
2862  return false;
2863}
2864
2865static bool hasDeducibleTemplateParameters(Sema &S,
2866                                           FunctionTemplateDecl *FunctionTemplate,
2867                                           QualType T);
2868
2869/// \brief Perform template argument deduction from a function call
2870/// (C++ [temp.deduct.call]).
2871///
2872/// \param FunctionTemplate the function template for which we are performing
2873/// template argument deduction.
2874///
2875/// \param ExplicitTemplateArguments the explicit template arguments provided
2876/// for this call.
2877///
2878/// \param Args the function call arguments
2879///
2880/// \param NumArgs the number of arguments in Args
2881///
2882/// \param Name the name of the function being called. This is only significant
2883/// when the function template is a conversion function template, in which
2884/// case this routine will also perform template argument deduction based on
2885/// the function to which
2886///
2887/// \param Specialization if template argument deduction was successful,
2888/// this will be set to the function template specialization produced by
2889/// template argument deduction.
2890///
2891/// \param Info the argument will be updated to provide additional information
2892/// about template argument deduction.
2893///
2894/// \returns the result of template argument deduction.
2895Sema::TemplateDeductionResult
2896Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2897                              TemplateArgumentListInfo *ExplicitTemplateArgs,
2898                              Expr **Args, unsigned NumArgs,
2899                              FunctionDecl *&Specialization,
2900                              TemplateDeductionInfo &Info) {
2901  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2902
2903  // C++ [temp.deduct.call]p1:
2904  //   Template argument deduction is done by comparing each function template
2905  //   parameter type (call it P) with the type of the corresponding argument
2906  //   of the call (call it A) as described below.
2907  unsigned CheckArgs = NumArgs;
2908  if (NumArgs < Function->getMinRequiredArguments())
2909    return TDK_TooFewArguments;
2910  else if (NumArgs > Function->getNumParams()) {
2911    const FunctionProtoType *Proto
2912      = Function->getType()->getAs<FunctionProtoType>();
2913    if (Proto->isTemplateVariadic())
2914      /* Do nothing */;
2915    else if (Proto->isVariadic())
2916      CheckArgs = Function->getNumParams();
2917    else
2918      return TDK_TooManyArguments;
2919  }
2920
2921  // The types of the parameters from which we will perform template argument
2922  // deduction.
2923  LocalInstantiationScope InstScope(*this);
2924  TemplateParameterList *TemplateParams
2925    = FunctionTemplate->getTemplateParameters();
2926  SmallVector<DeducedTemplateArgument, 4> Deduced;
2927  SmallVector<QualType, 4> ParamTypes;
2928  unsigned NumExplicitlySpecified = 0;
2929  if (ExplicitTemplateArgs) {
2930    TemplateDeductionResult Result =
2931      SubstituteExplicitTemplateArguments(FunctionTemplate,
2932                                          *ExplicitTemplateArgs,
2933                                          Deduced,
2934                                          ParamTypes,
2935                                          0,
2936                                          Info);
2937    if (Result)
2938      return Result;
2939
2940    NumExplicitlySpecified = Deduced.size();
2941  } else {
2942    // Just fill in the parameter types from the function declaration.
2943    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
2944      ParamTypes.push_back(Function->getParamDecl(I)->getType());
2945  }
2946
2947  // Deduce template arguments from the function parameters.
2948  Deduced.resize(TemplateParams->size());
2949  unsigned ArgIdx = 0;
2950  SmallVector<OriginalCallArg, 4> OriginalCallArgs;
2951  for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2952       ParamIdx != NumParams; ++ParamIdx) {
2953    QualType OrigParamType = ParamTypes[ParamIdx];
2954    QualType ParamType = OrigParamType;
2955
2956    const PackExpansionType *ParamExpansion
2957      = dyn_cast<PackExpansionType>(ParamType);
2958    if (!ParamExpansion) {
2959      // Simple case: matching a function parameter to a function argument.
2960      if (ArgIdx >= CheckArgs)
2961        break;
2962
2963      Expr *Arg = Args[ArgIdx++];
2964      QualType ArgType = Arg->getType();
2965
2966      unsigned TDF = 0;
2967      if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2968                                                    ParamType, ArgType, Arg,
2969                                                    TDF))
2970        continue;
2971
2972      // Keep track of the argument type and corresponding parameter index,
2973      // so we can check for compatibility between the deduced A and A.
2974      if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
2975        OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
2976                                                   ArgType));
2977
2978      if (TemplateDeductionResult Result
2979          = ::DeduceTemplateArguments(*this, TemplateParams,
2980                                      ParamType, ArgType, Info, Deduced,
2981                                      TDF))
2982        return Result;
2983
2984      continue;
2985    }
2986
2987    // C++0x [temp.deduct.call]p1:
2988    //   For a function parameter pack that occurs at the end of the
2989    //   parameter-declaration-list, the type A of each remaining argument of
2990    //   the call is compared with the type P of the declarator-id of the
2991    //   function parameter pack. Each comparison deduces template arguments
2992    //   for subsequent positions in the template parameter packs expanded by
2993    //   the function parameter pack. For a function parameter pack that does
2994    //   not occur at the end of the parameter-declaration-list, the type of
2995    //   the parameter pack is a non-deduced context.
2996    if (ParamIdx + 1 < NumParams)
2997      break;
2998
2999    QualType ParamPattern = ParamExpansion->getPattern();
3000    SmallVector<unsigned, 2> PackIndices;
3001    {
3002      llvm::BitVector SawIndices(TemplateParams->size());
3003      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3004      collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
3005      for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
3006        unsigned Depth, Index;
3007        llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
3008        if (Depth == 0 && !SawIndices[Index]) {
3009          SawIndices[Index] = true;
3010          PackIndices.push_back(Index);
3011        }
3012      }
3013    }
3014    assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
3015
3016    // Keep track of the deduced template arguments for each parameter pack
3017    // expanded by this pack expansion (the outer index) and for each
3018    // template argument (the inner SmallVectors).
3019    SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2>
3020      NewlyDeducedPacks(PackIndices.size());
3021    SmallVector<DeducedTemplateArgument, 2>
3022      SavedPacks(PackIndices.size());
3023    PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks,
3024                                 NewlyDeducedPacks);
3025    bool HasAnyArguments = false;
3026    for (; ArgIdx < NumArgs; ++ArgIdx) {
3027      HasAnyArguments = true;
3028
3029      QualType OrigParamType = ParamPattern;
3030      ParamType = OrigParamType;
3031      Expr *Arg = Args[ArgIdx];
3032      QualType ArgType = Arg->getType();
3033
3034      unsigned TDF = 0;
3035      if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3036                                                    ParamType, ArgType, Arg,
3037                                                    TDF)) {
3038        // We can't actually perform any deduction for this argument, so stop
3039        // deduction at this point.
3040        ++ArgIdx;
3041        break;
3042      }
3043
3044      // Keep track of the argument type and corresponding argument index,
3045      // so we can check for compatibility between the deduced A and A.
3046      if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3047        OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3048                                                   ArgType));
3049
3050      if (TemplateDeductionResult Result
3051          = ::DeduceTemplateArguments(*this, TemplateParams,
3052                                      ParamType, ArgType, Info, Deduced,
3053                                      TDF))
3054        return Result;
3055
3056      // Capture the deduced template arguments for each parameter pack expanded
3057      // by this pack expansion, add them to the list of arguments we've deduced
3058      // for that pack, then clear out the deduced argument.
3059      for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
3060        DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
3061        if (!DeducedArg.isNull()) {
3062          NewlyDeducedPacks[I].push_back(DeducedArg);
3063          DeducedArg = DeducedTemplateArgument();
3064        }
3065      }
3066    }
3067
3068    // Build argument packs for each of the parameter packs expanded by this
3069    // pack expansion.
3070    if (Sema::TemplateDeductionResult Result
3071          = FinishArgumentPackDeduction(*this, TemplateParams, HasAnyArguments,
3072                                        Deduced, PackIndices, SavedPacks,
3073                                        NewlyDeducedPacks, Info))
3074      return Result;
3075
3076    // After we've matching against a parameter pack, we're done.
3077    break;
3078  }
3079
3080  return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3081                                         NumExplicitlySpecified,
3082                                         Specialization, Info, &OriginalCallArgs);
3083}
3084
3085/// \brief Deduce template arguments when taking the address of a function
3086/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3087/// a template.
3088///
3089/// \param FunctionTemplate the function template for which we are performing
3090/// template argument deduction.
3091///
3092/// \param ExplicitTemplateArguments the explicitly-specified template
3093/// arguments.
3094///
3095/// \param ArgFunctionType the function type that will be used as the
3096/// "argument" type (A) when performing template argument deduction from the
3097/// function template's function type. This type may be NULL, if there is no
3098/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
3099///
3100/// \param Specialization if template argument deduction was successful,
3101/// this will be set to the function template specialization produced by
3102/// template argument deduction.
3103///
3104/// \param Info the argument will be updated to provide additional information
3105/// about template argument deduction.
3106///
3107/// \returns the result of template argument deduction.
3108Sema::TemplateDeductionResult
3109Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3110                              TemplateArgumentListInfo *ExplicitTemplateArgs,
3111                              QualType ArgFunctionType,
3112                              FunctionDecl *&Specialization,
3113                              TemplateDeductionInfo &Info) {
3114  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3115  TemplateParameterList *TemplateParams
3116    = FunctionTemplate->getTemplateParameters();
3117  QualType FunctionType = Function->getType();
3118
3119  // Substitute any explicit template arguments.
3120  LocalInstantiationScope InstScope(*this);
3121  SmallVector<DeducedTemplateArgument, 4> Deduced;
3122  unsigned NumExplicitlySpecified = 0;
3123  SmallVector<QualType, 4> ParamTypes;
3124  if (ExplicitTemplateArgs) {
3125    if (TemplateDeductionResult Result
3126          = SubstituteExplicitTemplateArguments(FunctionTemplate,
3127                                                *ExplicitTemplateArgs,
3128                                                Deduced, ParamTypes,
3129                                                &FunctionType, Info))
3130      return Result;
3131
3132    NumExplicitlySpecified = Deduced.size();
3133  }
3134
3135  // Template argument deduction for function templates in a SFINAE context.
3136  // Trap any errors that might occur.
3137  SFINAETrap Trap(*this);
3138
3139  Deduced.resize(TemplateParams->size());
3140
3141  if (!ArgFunctionType.isNull()) {
3142    // Deduce template arguments from the function type.
3143    if (TemplateDeductionResult Result
3144          = ::DeduceTemplateArguments(*this, TemplateParams,
3145                                      FunctionType, ArgFunctionType, Info,
3146                                      Deduced, TDF_TopLevelParameterTypeList))
3147      return Result;
3148  }
3149
3150  if (TemplateDeductionResult Result
3151        = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3152                                          NumExplicitlySpecified,
3153                                          Specialization, Info))
3154    return Result;
3155
3156  // If the requested function type does not match the actual type of the
3157  // specialization, template argument deduction fails.
3158  if (!ArgFunctionType.isNull() &&
3159      !Context.hasSameType(ArgFunctionType, Specialization->getType()))
3160    return TDK_NonDeducedMismatch;
3161
3162  return TDK_Success;
3163}
3164
3165/// \brief Deduce template arguments for a templated conversion
3166/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3167/// conversion function template specialization.
3168Sema::TemplateDeductionResult
3169Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3170                              QualType ToType,
3171                              CXXConversionDecl *&Specialization,
3172                              TemplateDeductionInfo &Info) {
3173  CXXConversionDecl *Conv
3174    = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
3175  QualType FromType = Conv->getConversionType();
3176
3177  // Canonicalize the types for deduction.
3178  QualType P = Context.getCanonicalType(FromType);
3179  QualType A = Context.getCanonicalType(ToType);
3180
3181  // C++0x [temp.deduct.conv]p2:
3182  //   If P is a reference type, the type referred to by P is used for
3183  //   type deduction.
3184  if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3185    P = PRef->getPointeeType();
3186
3187  // C++0x [temp.deduct.conv]p4:
3188  //   [...] If A is a reference type, the type referred to by A is used
3189  //   for type deduction.
3190  if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3191    A = ARef->getPointeeType().getUnqualifiedType();
3192  // C++ [temp.deduct.conv]p3:
3193  //
3194  //   If A is not a reference type:
3195  else {
3196    assert(!A->isReferenceType() && "Reference types were handled above");
3197
3198    //   - If P is an array type, the pointer type produced by the
3199    //     array-to-pointer standard conversion (4.2) is used in place
3200    //     of P for type deduction; otherwise,
3201    if (P->isArrayType())
3202      P = Context.getArrayDecayedType(P);
3203    //   - If P is a function type, the pointer type produced by the
3204    //     function-to-pointer standard conversion (4.3) is used in
3205    //     place of P for type deduction; otherwise,
3206    else if (P->isFunctionType())
3207      P = Context.getPointerType(P);
3208    //   - If P is a cv-qualified type, the top level cv-qualifiers of
3209    //     P's type are ignored for type deduction.
3210    else
3211      P = P.getUnqualifiedType();
3212
3213    // C++0x [temp.deduct.conv]p4:
3214    //   If A is a cv-qualified type, the top level cv-qualifiers of A's
3215    //   type are ignored for type deduction. If A is a reference type, the type
3216    //   referred to by A is used for type deduction.
3217    A = A.getUnqualifiedType();
3218  }
3219
3220  // Template argument deduction for function templates in a SFINAE context.
3221  // Trap any errors that might occur.
3222  SFINAETrap Trap(*this);
3223
3224  // C++ [temp.deduct.conv]p1:
3225  //   Template argument deduction is done by comparing the return
3226  //   type of the template conversion function (call it P) with the
3227  //   type that is required as the result of the conversion (call it
3228  //   A) as described in 14.8.2.4.
3229  TemplateParameterList *TemplateParams
3230    = FunctionTemplate->getTemplateParameters();
3231  SmallVector<DeducedTemplateArgument, 4> Deduced;
3232  Deduced.resize(TemplateParams->size());
3233
3234  // C++0x [temp.deduct.conv]p4:
3235  //   In general, the deduction process attempts to find template
3236  //   argument values that will make the deduced A identical to
3237  //   A. However, there are two cases that allow a difference:
3238  unsigned TDF = 0;
3239  //     - If the original A is a reference type, A can be more
3240  //       cv-qualified than the deduced A (i.e., the type referred to
3241  //       by the reference)
3242  if (ToType->isReferenceType())
3243    TDF |= TDF_ParamWithReferenceType;
3244  //     - The deduced A can be another pointer or pointer to member
3245  //       type that can be converted to A via a qualification
3246  //       conversion.
3247  //
3248  // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3249  // both P and A are pointers or member pointers. In this case, we
3250  // just ignore cv-qualifiers completely).
3251  if ((P->isPointerType() && A->isPointerType()) ||
3252      (P->isMemberPointerType() && A->isMemberPointerType()))
3253    TDF |= TDF_IgnoreQualifiers;
3254  if (TemplateDeductionResult Result
3255        = ::DeduceTemplateArguments(*this, TemplateParams,
3256                                    P, A, Info, Deduced, TDF))
3257    return Result;
3258
3259  // Finish template argument deduction.
3260  LocalInstantiationScope InstScope(*this);
3261  FunctionDecl *Spec = 0;
3262  TemplateDeductionResult Result
3263    = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
3264                                      Info);
3265  Specialization = cast_or_null<CXXConversionDecl>(Spec);
3266  return Result;
3267}
3268
3269/// \brief Deduce template arguments for a function template when there is
3270/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3271///
3272/// \param FunctionTemplate the function template for which we are performing
3273/// template argument deduction.
3274///
3275/// \param ExplicitTemplateArguments the explicitly-specified template
3276/// arguments.
3277///
3278/// \param Specialization if template argument deduction was successful,
3279/// this will be set to the function template specialization produced by
3280/// template argument deduction.
3281///
3282/// \param Info the argument will be updated to provide additional information
3283/// about template argument deduction.
3284///
3285/// \returns the result of template argument deduction.
3286Sema::TemplateDeductionResult
3287Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3288                              TemplateArgumentListInfo *ExplicitTemplateArgs,
3289                              FunctionDecl *&Specialization,
3290                              TemplateDeductionInfo &Info) {
3291  return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
3292                                 QualType(), Specialization, Info);
3293}
3294
3295namespace {
3296  /// Substitute the 'auto' type specifier within a type for a given replacement
3297  /// type.
3298  class SubstituteAutoTransform :
3299    public TreeTransform<SubstituteAutoTransform> {
3300    QualType Replacement;
3301  public:
3302    SubstituteAutoTransform(Sema &SemaRef, QualType Replacement) :
3303      TreeTransform<SubstituteAutoTransform>(SemaRef), Replacement(Replacement) {
3304    }
3305    QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3306      // If we're building the type pattern to deduce against, don't wrap the
3307      // substituted type in an AutoType. Certain template deduction rules
3308      // apply only when a template type parameter appears directly (and not if
3309      // the parameter is found through desugaring). For instance:
3310      //   auto &&lref = lvalue;
3311      // must transform into "rvalue reference to T" not "rvalue reference to
3312      // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
3313      if (isa<TemplateTypeParmType>(Replacement)) {
3314        QualType Result = Replacement;
3315        TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
3316        NewTL.setNameLoc(TL.getNameLoc());
3317        return Result;
3318      } else {
3319        QualType Result = RebuildAutoType(Replacement);
3320        AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3321        NewTL.setNameLoc(TL.getNameLoc());
3322        return Result;
3323      }
3324    }
3325  };
3326}
3327
3328/// \brief Deduce the type for an auto type-specifier (C++0x [dcl.spec.auto]p6)
3329///
3330/// \param Type the type pattern using the auto type-specifier.
3331///
3332/// \param Init the initializer for the variable whose type is to be deduced.
3333///
3334/// \param Result if type deduction was successful, this will be set to the
3335/// deduced type. This may still contain undeduced autos if the type is
3336/// dependent. This will be set to null if deduction succeeded, but auto
3337/// substitution failed; the appropriate diagnostic will already have been
3338/// produced in that case.
3339///
3340/// \returns true if deduction succeeded, false if it failed.
3341bool
3342Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *Init,
3343                     TypeSourceInfo *&Result) {
3344  if (Init->isTypeDependent()) {
3345    Result = Type;
3346    return true;
3347  }
3348
3349  SourceLocation Loc = Init->getExprLoc();
3350
3351  LocalInstantiationScope InstScope(*this);
3352
3353  // Build template<class TemplParam> void Func(FuncParam);
3354  TemplateTypeParmDecl *TemplParam =
3355    TemplateTypeParmDecl::Create(Context, 0, SourceLocation(), Loc, 0, 0, 0,
3356                                 false, false);
3357  QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
3358  NamedDecl *TemplParamPtr = TemplParam;
3359  FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr,
3360                                                   Loc);
3361
3362  TypeSourceInfo *FuncParamInfo =
3363    SubstituteAutoTransform(*this, TemplArg).TransformType(Type);
3364  assert(FuncParamInfo && "substituting template parameter for 'auto' failed");
3365  QualType FuncParam = FuncParamInfo->getType();
3366
3367  // Deduce type of TemplParam in Func(Init)
3368  SmallVector<DeducedTemplateArgument, 1> Deduced;
3369  Deduced.resize(1);
3370  QualType InitType = Init->getType();
3371  unsigned TDF = 0;
3372  if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
3373                                                FuncParam, InitType, Init,
3374                                                TDF))
3375    return false;
3376
3377  TemplateDeductionInfo Info(Context, Loc);
3378  if (::DeduceTemplateArguments(*this, &TemplateParams,
3379                                FuncParam, InitType, Info, Deduced,
3380                                TDF))
3381    return false;
3382
3383  QualType DeducedType = Deduced[0].getAsType();
3384  if (DeducedType.isNull())
3385    return false;
3386
3387  Result = SubstituteAutoTransform(*this, DeducedType).TransformType(Type);
3388
3389  // Check that the deduced argument type is compatible with the original
3390  // argument type per C++ [temp.deduct.call]p4.
3391  if (Result &&
3392      CheckOriginalCallArgDeduction(*this,
3393                                    Sema::OriginalCallArg(FuncParam,0,InitType),
3394                                    Result->getType())) {
3395    Result = 0;
3396    return false;
3397  }
3398
3399  return true;
3400}
3401
3402static void
3403MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3404                           bool OnlyDeduced,
3405                           unsigned Level,
3406                           SmallVectorImpl<bool> &Deduced);
3407
3408/// \brief If this is a non-static member function,
3409static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
3410                                                CXXMethodDecl *Method,
3411                                 SmallVectorImpl<QualType> &ArgTypes) {
3412  if (Method->isStatic())
3413    return;
3414
3415  // C++ [over.match.funcs]p4:
3416  //
3417  //   For non-static member functions, the type of the implicit
3418  //   object parameter is
3419  //     - "lvalue reference to cv X" for functions declared without a
3420  //       ref-qualifier or with the & ref-qualifier
3421  //     - "rvalue reference to cv X" for functions declared with the
3422  //       && ref-qualifier
3423  //
3424  // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
3425  QualType ArgTy = Context.getTypeDeclType(Method->getParent());
3426  ArgTy = Context.getQualifiedType(ArgTy,
3427                        Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
3428  ArgTy = Context.getLValueReferenceType(ArgTy);
3429  ArgTypes.push_back(ArgTy);
3430}
3431
3432/// \brief Determine whether the function template \p FT1 is at least as
3433/// specialized as \p FT2.
3434static bool isAtLeastAsSpecializedAs(Sema &S,
3435                                     SourceLocation Loc,
3436                                     FunctionTemplateDecl *FT1,
3437                                     FunctionTemplateDecl *FT2,
3438                                     TemplatePartialOrderingContext TPOC,
3439                                     unsigned NumCallArguments,
3440    SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
3441  FunctionDecl *FD1 = FT1->getTemplatedDecl();
3442  FunctionDecl *FD2 = FT2->getTemplatedDecl();
3443  const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
3444  const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
3445
3446  assert(Proto1 && Proto2 && "Function templates must have prototypes");
3447  TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
3448  SmallVector<DeducedTemplateArgument, 4> Deduced;
3449  Deduced.resize(TemplateParams->size());
3450
3451  // C++0x [temp.deduct.partial]p3:
3452  //   The types used to determine the ordering depend on the context in which
3453  //   the partial ordering is done:
3454  TemplateDeductionInfo Info(S.Context, Loc);
3455  CXXMethodDecl *Method1 = 0;
3456  CXXMethodDecl *Method2 = 0;
3457  bool IsNonStatic2 = false;
3458  bool IsNonStatic1 = false;
3459  unsigned Skip2 = 0;
3460  switch (TPOC) {
3461  case TPOC_Call: {
3462    //   - In the context of a function call, the function parameter types are
3463    //     used.
3464    Method1 = dyn_cast<CXXMethodDecl>(FD1);
3465    Method2 = dyn_cast<CXXMethodDecl>(FD2);
3466    IsNonStatic1 = Method1 && !Method1->isStatic();
3467    IsNonStatic2 = Method2 && !Method2->isStatic();
3468
3469    // C++0x [temp.func.order]p3:
3470    //   [...] If only one of the function templates is a non-static
3471    //   member, that function template is considered to have a new
3472    //   first parameter inserted in its function parameter list. The
3473    //   new parameter is of type "reference to cv A," where cv are
3474    //   the cv-qualifiers of the function template (if any) and A is
3475    //   the class of which the function template is a member.
3476    //
3477    // C++98/03 doesn't have this provision, so instead we drop the
3478    // first argument of the free function or static member, which
3479    // seems to match existing practice.
3480    SmallVector<QualType, 4> Args1;
3481    unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
3482      IsNonStatic2 && !IsNonStatic1;
3483    if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
3484      MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
3485    Args1.insert(Args1.end(),
3486                 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
3487
3488    SmallVector<QualType, 4> Args2;
3489    Skip2 = !S.getLangOptions().CPlusPlus0x &&
3490      IsNonStatic1 && !IsNonStatic2;
3491    if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3492      MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
3493    Args2.insert(Args2.end(),
3494                 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
3495
3496    // C++ [temp.func.order]p5:
3497    //   The presence of unused ellipsis and default arguments has no effect on
3498    //   the partial ordering of function templates.
3499    if (Args1.size() > NumCallArguments)
3500      Args1.resize(NumCallArguments);
3501    if (Args2.size() > NumCallArguments)
3502      Args2.resize(NumCallArguments);
3503    if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
3504                                Args1.data(), Args1.size(), Info, Deduced,
3505                                TDF_None, /*PartialOrdering=*/true,
3506                                RefParamComparisons))
3507        return false;
3508
3509    break;
3510  }
3511
3512  case TPOC_Conversion:
3513    //   - In the context of a call to a conversion operator, the return types
3514    //     of the conversion function templates are used.
3515    if (DeduceTemplateArguments(S, TemplateParams, Proto2->getResultType(),
3516                                Proto1->getResultType(), Info, Deduced,
3517                                TDF_None, /*PartialOrdering=*/true,
3518                                RefParamComparisons))
3519      return false;
3520    break;
3521
3522  case TPOC_Other:
3523    //   - In other contexts (14.6.6.2) the function template's function type
3524    //     is used.
3525    if (DeduceTemplateArguments(S, TemplateParams, FD2->getType(),
3526                                FD1->getType(), Info, Deduced, TDF_None,
3527                                /*PartialOrdering=*/true, RefParamComparisons))
3528      return false;
3529    break;
3530  }
3531
3532  // C++0x [temp.deduct.partial]p11:
3533  //   In most cases, all template parameters must have values in order for
3534  //   deduction to succeed, but for partial ordering purposes a template
3535  //   parameter may remain without a value provided it is not used in the
3536  //   types being used for partial ordering. [ Note: a template parameter used
3537  //   in a non-deduced context is considered used. -end note]
3538  unsigned ArgIdx = 0, NumArgs = Deduced.size();
3539  for (; ArgIdx != NumArgs; ++ArgIdx)
3540    if (Deduced[ArgIdx].isNull())
3541      break;
3542
3543  if (ArgIdx == NumArgs) {
3544    // All template arguments were deduced. FT1 is at least as specialized
3545    // as FT2.
3546    return true;
3547  }
3548
3549  // Figure out which template parameters were used.
3550  SmallVector<bool, 4> UsedParameters;
3551  UsedParameters.resize(TemplateParams->size());
3552  switch (TPOC) {
3553  case TPOC_Call: {
3554    unsigned NumParams = std::min(NumCallArguments,
3555                                  std::min(Proto1->getNumArgs(),
3556                                           Proto2->getNumArgs()));
3557    if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3558      ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3559                                   TemplateParams->getDepth(), UsedParameters);
3560    for (unsigned I = Skip2; I < NumParams; ++I)
3561      ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3562                                   TemplateParams->getDepth(),
3563                                   UsedParameters);
3564    break;
3565  }
3566
3567  case TPOC_Conversion:
3568    ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3569                                 TemplateParams->getDepth(),
3570                                 UsedParameters);
3571    break;
3572
3573  case TPOC_Other:
3574    ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3575                                 TemplateParams->getDepth(),
3576                                 UsedParameters);
3577    break;
3578  }
3579
3580  for (; ArgIdx != NumArgs; ++ArgIdx)
3581    // If this argument had no value deduced but was used in one of the types
3582    // used for partial ordering, then deduction fails.
3583    if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3584      return false;
3585
3586  return true;
3587}
3588
3589/// \brief Determine whether this a function template whose parameter-type-list
3590/// ends with a function parameter pack.
3591static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
3592  FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3593  unsigned NumParams = Function->getNumParams();
3594  if (NumParams == 0)
3595    return false;
3596
3597  ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
3598  if (!Last->isParameterPack())
3599    return false;
3600
3601  // Make sure that no previous parameter is a parameter pack.
3602  while (--NumParams > 0) {
3603    if (Function->getParamDecl(NumParams - 1)->isParameterPack())
3604      return false;
3605  }
3606
3607  return true;
3608}
3609
3610/// \brief Returns the more specialized function template according
3611/// to the rules of function template partial ordering (C++ [temp.func.order]).
3612///
3613/// \param FT1 the first function template
3614///
3615/// \param FT2 the second function template
3616///
3617/// \param TPOC the context in which we are performing partial ordering of
3618/// function templates.
3619///
3620/// \param NumCallArguments The number of arguments in a call, used only
3621/// when \c TPOC is \c TPOC_Call.
3622///
3623/// \returns the more specialized function template. If neither
3624/// template is more specialized, returns NULL.
3625FunctionTemplateDecl *
3626Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3627                                 FunctionTemplateDecl *FT2,
3628                                 SourceLocation Loc,
3629                                 TemplatePartialOrderingContext TPOC,
3630                                 unsigned NumCallArguments) {
3631  SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons;
3632  bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
3633                                          NumCallArguments, 0);
3634  bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
3635                                          NumCallArguments,
3636                                          &RefParamComparisons);
3637
3638  if (Better1 != Better2) // We have a clear winner
3639    return Better1? FT1 : FT2;
3640
3641  if (!Better1 && !Better2) // Neither is better than the other
3642    return 0;
3643
3644  // C++0x [temp.deduct.partial]p10:
3645  //   If for each type being considered a given template is at least as
3646  //   specialized for all types and more specialized for some set of types and
3647  //   the other template is not more specialized for any types or is not at
3648  //   least as specialized for any types, then the given template is more
3649  //   specialized than the other template. Otherwise, neither template is more
3650  //   specialized than the other.
3651  Better1 = false;
3652  Better2 = false;
3653  for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) {
3654    // C++0x [temp.deduct.partial]p9:
3655    //   If, for a given type, deduction succeeds in both directions (i.e., the
3656    //   types are identical after the transformations above) and both P and A
3657    //   were reference types (before being replaced with the type referred to
3658    //   above):
3659
3660    //     -- if the type from the argument template was an lvalue reference
3661    //        and the type from the parameter template was not, the argument
3662    //        type is considered to be more specialized than the other;
3663    //        otherwise,
3664    if (!RefParamComparisons[I].ArgIsRvalueRef &&
3665        RefParamComparisons[I].ParamIsRvalueRef) {
3666      Better2 = true;
3667      if (Better1)
3668        return 0;
3669      continue;
3670    } else if (!RefParamComparisons[I].ParamIsRvalueRef &&
3671               RefParamComparisons[I].ArgIsRvalueRef) {
3672      Better1 = true;
3673      if (Better2)
3674        return 0;
3675      continue;
3676    }
3677
3678    //     -- if the type from the argument template is more cv-qualified than
3679    //        the type from the parameter template (as described above), the
3680    //        argument type is considered to be more specialized than the
3681    //        other; otherwise,
3682    switch (RefParamComparisons[I].Qualifiers) {
3683    case NeitherMoreQualified:
3684      break;
3685
3686    case ParamMoreQualified:
3687      Better1 = true;
3688      if (Better2)
3689        return 0;
3690      continue;
3691
3692    case ArgMoreQualified:
3693      Better2 = true;
3694      if (Better1)
3695        return 0;
3696      continue;
3697    }
3698
3699    //     -- neither type is more specialized than the other.
3700  }
3701
3702  assert(!(Better1 && Better2) && "Should have broken out in the loop above");
3703  if (Better1)
3704    return FT1;
3705  else if (Better2)
3706    return FT2;
3707
3708  // FIXME: This mimics what GCC implements, but doesn't match up with the
3709  // proposed resolution for core issue 692. This area needs to be sorted out,
3710  // but for now we attempt to maintain compatibility.
3711  bool Variadic1 = isVariadicFunctionTemplate(FT1);
3712  bool Variadic2 = isVariadicFunctionTemplate(FT2);
3713  if (Variadic1 != Variadic2)
3714    return Variadic1? FT2 : FT1;
3715
3716  return 0;
3717}
3718
3719/// \brief Determine if the two templates are equivalent.
3720static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3721  if (T1 == T2)
3722    return true;
3723
3724  if (!T1 || !T2)
3725    return false;
3726
3727  return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3728}
3729
3730/// \brief Retrieve the most specialized of the given function template
3731/// specializations.
3732///
3733/// \param SpecBegin the start iterator of the function template
3734/// specializations that we will be comparing.
3735///
3736/// \param SpecEnd the end iterator of the function template
3737/// specializations, paired with \p SpecBegin.
3738///
3739/// \param TPOC the partial ordering context to use to compare the function
3740/// template specializations.
3741///
3742/// \param NumCallArguments The number of arguments in a call, used only
3743/// when \c TPOC is \c TPOC_Call.
3744///
3745/// \param Loc the location where the ambiguity or no-specializations
3746/// diagnostic should occur.
3747///
3748/// \param NoneDiag partial diagnostic used to diagnose cases where there are
3749/// no matching candidates.
3750///
3751/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3752/// occurs.
3753///
3754/// \param CandidateDiag partial diagnostic used for each function template
3755/// specialization that is a candidate in the ambiguous ordering. One parameter
3756/// in this diagnostic should be unbound, which will correspond to the string
3757/// describing the template arguments for the function template specialization.
3758///
3759/// \param Index if non-NULL and the result of this function is non-nULL,
3760/// receives the index corresponding to the resulting function template
3761/// specialization.
3762///
3763/// \returns the most specialized function template specialization, if
3764/// found. Otherwise, returns SpecEnd.
3765///
3766/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3767/// template argument deduction.
3768UnresolvedSetIterator
3769Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
3770                        UnresolvedSetIterator SpecEnd,
3771                         TemplatePartialOrderingContext TPOC,
3772                         unsigned NumCallArguments,
3773                         SourceLocation Loc,
3774                         const PartialDiagnostic &NoneDiag,
3775                         const PartialDiagnostic &AmbigDiag,
3776                         const PartialDiagnostic &CandidateDiag,
3777                         bool Complain) {
3778  if (SpecBegin == SpecEnd) {
3779    if (Complain)
3780      Diag(Loc, NoneDiag);
3781    return SpecEnd;
3782  }
3783
3784  if (SpecBegin + 1 == SpecEnd)
3785    return SpecBegin;
3786
3787  // Find the function template that is better than all of the templates it
3788  // has been compared to.
3789  UnresolvedSetIterator Best = SpecBegin;
3790  FunctionTemplateDecl *BestTemplate
3791    = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
3792  assert(BestTemplate && "Not a function template specialization?");
3793  for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3794    FunctionTemplateDecl *Challenger
3795      = cast<FunctionDecl>(*I)->getPrimaryTemplate();
3796    assert(Challenger && "Not a function template specialization?");
3797    if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
3798                                                  Loc, TPOC, NumCallArguments),
3799                       Challenger)) {
3800      Best = I;
3801      BestTemplate = Challenger;
3802    }
3803  }
3804
3805  // Make sure that the "best" function template is more specialized than all
3806  // of the others.
3807  bool Ambiguous = false;
3808  for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3809    FunctionTemplateDecl *Challenger
3810      = cast<FunctionDecl>(*I)->getPrimaryTemplate();
3811    if (I != Best &&
3812        !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
3813                                                   Loc, TPOC, NumCallArguments),
3814                        BestTemplate)) {
3815      Ambiguous = true;
3816      break;
3817    }
3818  }
3819
3820  if (!Ambiguous) {
3821    // We found an answer. Return it.
3822    return Best;
3823  }
3824
3825  // Diagnose the ambiguity.
3826  if (Complain)
3827    Diag(Loc, AmbigDiag);
3828
3829  if (Complain)
3830  // FIXME: Can we order the candidates in some sane way?
3831    for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3832      Diag((*I)->getLocation(), CandidateDiag)
3833        << getTemplateArgumentBindingsText(
3834          cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3835                    *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
3836
3837  return SpecEnd;
3838}
3839
3840/// \brief Returns the more specialized class template partial specialization
3841/// according to the rules of partial ordering of class template partial
3842/// specializations (C++ [temp.class.order]).
3843///
3844/// \param PS1 the first class template partial specialization
3845///
3846/// \param PS2 the second class template partial specialization
3847///
3848/// \returns the more specialized class template partial specialization. If
3849/// neither partial specialization is more specialized, returns NULL.
3850ClassTemplatePartialSpecializationDecl *
3851Sema::getMoreSpecializedPartialSpecialization(
3852                                  ClassTemplatePartialSpecializationDecl *PS1,
3853                                  ClassTemplatePartialSpecializationDecl *PS2,
3854                                              SourceLocation Loc) {
3855  // C++ [temp.class.order]p1:
3856  //   For two class template partial specializations, the first is at least as
3857  //   specialized as the second if, given the following rewrite to two
3858  //   function templates, the first function template is at least as
3859  //   specialized as the second according to the ordering rules for function
3860  //   templates (14.6.6.2):
3861  //     - the first function template has the same template parameters as the
3862  //       first partial specialization and has a single function parameter
3863  //       whose type is a class template specialization with the template
3864  //       arguments of the first partial specialization, and
3865  //     - the second function template has the same template parameters as the
3866  //       second partial specialization and has a single function parameter
3867  //       whose type is a class template specialization with the template
3868  //       arguments of the second partial specialization.
3869  //
3870  // Rather than synthesize function templates, we merely perform the
3871  // equivalent partial ordering by performing deduction directly on
3872  // the template arguments of the class template partial
3873  // specializations. This computation is slightly simpler than the
3874  // general problem of function template partial ordering, because
3875  // class template partial specializations are more constrained. We
3876  // know that every template parameter is deducible from the class
3877  // template partial specialization's template arguments, for
3878  // example.
3879  SmallVector<DeducedTemplateArgument, 4> Deduced;
3880  TemplateDeductionInfo Info(Context, Loc);
3881
3882  QualType PT1 = PS1->getInjectedSpecializationType();
3883  QualType PT2 = PS2->getInjectedSpecializationType();
3884
3885  // Determine whether PS1 is at least as specialized as PS2
3886  Deduced.resize(PS2->getTemplateParameters()->size());
3887  bool Better1 = !::DeduceTemplateArguments(*this, PS2->getTemplateParameters(),
3888                                            PT2, PT1, Info, Deduced, TDF_None,
3889                                            /*PartialOrdering=*/true,
3890                                            /*RefParamComparisons=*/0);
3891  if (Better1) {
3892    InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3893                               Deduced.data(), Deduced.size(), Info);
3894    Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3895                                                 PS1->getTemplateArgs(),
3896                                                 Deduced, Info);
3897  }
3898
3899  // Determine whether PS2 is at least as specialized as PS1
3900  Deduced.clear();
3901  Deduced.resize(PS1->getTemplateParameters()->size());
3902  bool Better2 = !::DeduceTemplateArguments(*this, PS1->getTemplateParameters(),
3903                                            PT1, PT2, Info, Deduced, TDF_None,
3904                                            /*PartialOrdering=*/true,
3905                                            /*RefParamComparisons=*/0);
3906  if (Better2) {
3907    InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3908                               Deduced.data(), Deduced.size(), Info);
3909    Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3910                                                 PS2->getTemplateArgs(),
3911                                                 Deduced, Info);
3912  }
3913
3914  if (Better1 == Better2)
3915    return 0;
3916
3917  return Better1? PS1 : PS2;
3918}
3919
3920static void
3921MarkUsedTemplateParameters(Sema &SemaRef,
3922                           const TemplateArgument &TemplateArg,
3923                           bool OnlyDeduced,
3924                           unsigned Depth,
3925                           SmallVectorImpl<bool> &Used);
3926
3927/// \brief Mark the template parameters that are used by the given
3928/// expression.
3929static void
3930MarkUsedTemplateParameters(Sema &SemaRef,
3931                           const Expr *E,
3932                           bool OnlyDeduced,
3933                           unsigned Depth,
3934                           SmallVectorImpl<bool> &Used) {
3935  // We can deduce from a pack expansion.
3936  if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3937    E = Expansion->getPattern();
3938
3939  // Skip through any implicit casts we added while type-checking.
3940  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3941    E = ICE->getSubExpr();
3942
3943  // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3944  // find other occurrences of template parameters.
3945  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3946  if (!DRE)
3947    return;
3948
3949  const NonTypeTemplateParmDecl *NTTP
3950    = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3951  if (!NTTP)
3952    return;
3953
3954  if (NTTP->getDepth() == Depth)
3955    Used[NTTP->getIndex()] = true;
3956}
3957
3958/// \brief Mark the template parameters that are used by the given
3959/// nested name specifier.
3960static void
3961MarkUsedTemplateParameters(Sema &SemaRef,
3962                           NestedNameSpecifier *NNS,
3963                           bool OnlyDeduced,
3964                           unsigned Depth,
3965                           SmallVectorImpl<bool> &Used) {
3966  if (!NNS)
3967    return;
3968
3969  MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3970                             Used);
3971  MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
3972                             OnlyDeduced, Depth, Used);
3973}
3974
3975/// \brief Mark the template parameters that are used by the given
3976/// template name.
3977static void
3978MarkUsedTemplateParameters(Sema &SemaRef,
3979                           TemplateName Name,
3980                           bool OnlyDeduced,
3981                           unsigned Depth,
3982                           SmallVectorImpl<bool> &Used) {
3983  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3984    if (TemplateTemplateParmDecl *TTP
3985          = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3986      if (TTP->getDepth() == Depth)
3987        Used[TTP->getIndex()] = true;
3988    }
3989    return;
3990  }
3991
3992  if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3993    MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3994                               Depth, Used);
3995  if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
3996    MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3997                               Depth, Used);
3998}
3999
4000/// \brief Mark the template parameters that are used by the given
4001/// type.
4002static void
4003MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
4004                           bool OnlyDeduced,
4005                           unsigned Depth,
4006                           SmallVectorImpl<bool> &Used) {
4007  if (T.isNull())
4008    return;
4009
4010  // Non-dependent types have nothing deducible
4011  if (!T->isDependentType())
4012    return;
4013
4014  T = SemaRef.Context.getCanonicalType(T);
4015  switch (T->getTypeClass()) {
4016  case Type::Pointer:
4017    MarkUsedTemplateParameters(SemaRef,
4018                               cast<PointerType>(T)->getPointeeType(),
4019                               OnlyDeduced,
4020                               Depth,
4021                               Used);
4022    break;
4023
4024  case Type::BlockPointer:
4025    MarkUsedTemplateParameters(SemaRef,
4026                               cast<BlockPointerType>(T)->getPointeeType(),
4027                               OnlyDeduced,
4028                               Depth,
4029                               Used);
4030    break;
4031
4032  case Type::LValueReference:
4033  case Type::RValueReference:
4034    MarkUsedTemplateParameters(SemaRef,
4035                               cast<ReferenceType>(T)->getPointeeType(),
4036                               OnlyDeduced,
4037                               Depth,
4038                               Used);
4039    break;
4040
4041  case Type::MemberPointer: {
4042    const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
4043    MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
4044                               Depth, Used);
4045    MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
4046                               OnlyDeduced, Depth, Used);
4047    break;
4048  }
4049
4050  case Type::DependentSizedArray:
4051    MarkUsedTemplateParameters(SemaRef,
4052                               cast<DependentSizedArrayType>(T)->getSizeExpr(),
4053                               OnlyDeduced, Depth, Used);
4054    // Fall through to check the element type
4055
4056  case Type::ConstantArray:
4057  case Type::IncompleteArray:
4058    MarkUsedTemplateParameters(SemaRef,
4059                               cast<ArrayType>(T)->getElementType(),
4060                               OnlyDeduced, Depth, Used);
4061    break;
4062
4063  case Type::Vector:
4064  case Type::ExtVector:
4065    MarkUsedTemplateParameters(SemaRef,
4066                               cast<VectorType>(T)->getElementType(),
4067                               OnlyDeduced, Depth, Used);
4068    break;
4069
4070  case Type::DependentSizedExtVector: {
4071    const DependentSizedExtVectorType *VecType
4072      = cast<DependentSizedExtVectorType>(T);
4073    MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
4074                               Depth, Used);
4075    MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
4076                               Depth, Used);
4077    break;
4078  }
4079
4080  case Type::FunctionProto: {
4081    const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
4082    MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
4083                               Depth, Used);
4084    for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
4085      MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
4086                                 Depth, Used);
4087    break;
4088  }
4089
4090  case Type::TemplateTypeParm: {
4091    const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4092    if (TTP->getDepth() == Depth)
4093      Used[TTP->getIndex()] = true;
4094    break;
4095  }
4096
4097  case Type::SubstTemplateTypeParmPack: {
4098    const SubstTemplateTypeParmPackType *Subst
4099      = cast<SubstTemplateTypeParmPackType>(T);
4100    MarkUsedTemplateParameters(SemaRef,
4101                               QualType(Subst->getReplacedParameter(), 0),
4102                               OnlyDeduced, Depth, Used);
4103    MarkUsedTemplateParameters(SemaRef, Subst->getArgumentPack(),
4104                               OnlyDeduced, Depth, Used);
4105    break;
4106  }
4107
4108  case Type::InjectedClassName:
4109    T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4110    // fall through
4111
4112  case Type::TemplateSpecialization: {
4113    const TemplateSpecializationType *Spec
4114      = cast<TemplateSpecializationType>(T);
4115    MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
4116                               Depth, Used);
4117
4118    // C++0x [temp.deduct.type]p9:
4119    //   If the template argument list of P contains a pack expansion that is not
4120    //   the last template argument, the entire template argument list is a
4121    //   non-deduced context.
4122    if (OnlyDeduced &&
4123        hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4124      break;
4125
4126    for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
4127      MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
4128                                 Used);
4129    break;
4130  }
4131
4132  case Type::Complex:
4133    if (!OnlyDeduced)
4134      MarkUsedTemplateParameters(SemaRef,
4135                                 cast<ComplexType>(T)->getElementType(),
4136                                 OnlyDeduced, Depth, Used);
4137    break;
4138
4139  case Type::Atomic:
4140    if (!OnlyDeduced)
4141      MarkUsedTemplateParameters(SemaRef,
4142                                 cast<AtomicType>(T)->getValueType(),
4143                                 OnlyDeduced, Depth, Used);
4144    break;
4145
4146  case Type::DependentName:
4147    if (!OnlyDeduced)
4148      MarkUsedTemplateParameters(SemaRef,
4149                                 cast<DependentNameType>(T)->getQualifier(),
4150                                 OnlyDeduced, Depth, Used);
4151    break;
4152
4153  case Type::DependentTemplateSpecialization: {
4154    const DependentTemplateSpecializationType *Spec
4155      = cast<DependentTemplateSpecializationType>(T);
4156    if (!OnlyDeduced)
4157      MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
4158                                 OnlyDeduced, Depth, Used);
4159
4160    // C++0x [temp.deduct.type]p9:
4161    //   If the template argument list of P contains a pack expansion that is not
4162    //   the last template argument, the entire template argument list is a
4163    //   non-deduced context.
4164    if (OnlyDeduced &&
4165        hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4166      break;
4167
4168    for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
4169      MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
4170                                 Used);
4171    break;
4172  }
4173
4174  case Type::TypeOf:
4175    if (!OnlyDeduced)
4176      MarkUsedTemplateParameters(SemaRef,
4177                                 cast<TypeOfType>(T)->getUnderlyingType(),
4178                                 OnlyDeduced, Depth, Used);
4179    break;
4180
4181  case Type::TypeOfExpr:
4182    if (!OnlyDeduced)
4183      MarkUsedTemplateParameters(SemaRef,
4184                                 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4185                                 OnlyDeduced, Depth, Used);
4186    break;
4187
4188  case Type::Decltype:
4189    if (!OnlyDeduced)
4190      MarkUsedTemplateParameters(SemaRef,
4191                                 cast<DecltypeType>(T)->getUnderlyingExpr(),
4192                                 OnlyDeduced, Depth, Used);
4193    break;
4194
4195  case Type::UnaryTransform:
4196    if (!OnlyDeduced)
4197      MarkUsedTemplateParameters(SemaRef,
4198                               cast<UnaryTransformType>(T)->getUnderlyingType(),
4199                                 OnlyDeduced, Depth, Used);
4200    break;
4201
4202  case Type::PackExpansion:
4203    MarkUsedTemplateParameters(SemaRef,
4204                               cast<PackExpansionType>(T)->getPattern(),
4205                               OnlyDeduced, Depth, Used);
4206    break;
4207
4208  case Type::Auto:
4209    MarkUsedTemplateParameters(SemaRef,
4210                               cast<AutoType>(T)->getDeducedType(),
4211                               OnlyDeduced, Depth, Used);
4212
4213  // None of these types have any template parameters in them.
4214  case Type::Builtin:
4215  case Type::VariableArray:
4216  case Type::FunctionNoProto:
4217  case Type::Record:
4218  case Type::Enum:
4219  case Type::ObjCInterface:
4220  case Type::ObjCObject:
4221  case Type::ObjCObjectPointer:
4222  case Type::UnresolvedUsing:
4223#define TYPE(Class, Base)
4224#define ABSTRACT_TYPE(Class, Base)
4225#define DEPENDENT_TYPE(Class, Base)
4226#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4227#include "clang/AST/TypeNodes.def"
4228    break;
4229  }
4230}
4231
4232/// \brief Mark the template parameters that are used by this
4233/// template argument.
4234static void
4235MarkUsedTemplateParameters(Sema &SemaRef,
4236                           const TemplateArgument &TemplateArg,
4237                           bool OnlyDeduced,
4238                           unsigned Depth,
4239                           SmallVectorImpl<bool> &Used) {
4240  switch (TemplateArg.getKind()) {
4241  case TemplateArgument::Null:
4242  case TemplateArgument::Integral:
4243    case TemplateArgument::Declaration:
4244    break;
4245
4246  case TemplateArgument::Type:
4247    MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
4248                               Depth, Used);
4249    break;
4250
4251  case TemplateArgument::Template:
4252  case TemplateArgument::TemplateExpansion:
4253    MarkUsedTemplateParameters(SemaRef,
4254                               TemplateArg.getAsTemplateOrTemplatePattern(),
4255                               OnlyDeduced, Depth, Used);
4256    break;
4257
4258  case TemplateArgument::Expression:
4259    MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
4260                               Depth, Used);
4261    break;
4262
4263  case TemplateArgument::Pack:
4264    for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
4265                                      PEnd = TemplateArg.pack_end();
4266         P != PEnd; ++P)
4267      MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
4268    break;
4269  }
4270}
4271
4272/// \brief Mark the template parameters can be deduced by the given
4273/// template argument list.
4274///
4275/// \param TemplateArgs the template argument list from which template
4276/// parameters will be deduced.
4277///
4278/// \param Deduced a bit vector whose elements will be set to \c true
4279/// to indicate when the corresponding template parameter will be
4280/// deduced.
4281void
4282Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
4283                                 bool OnlyDeduced, unsigned Depth,
4284                                 SmallVectorImpl<bool> &Used) {
4285  // C++0x [temp.deduct.type]p9:
4286  //   If the template argument list of P contains a pack expansion that is not
4287  //   the last template argument, the entire template argument list is a
4288  //   non-deduced context.
4289  if (OnlyDeduced &&
4290      hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
4291    return;
4292
4293  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4294    ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
4295                                 Depth, Used);
4296}
4297
4298/// \brief Marks all of the template parameters that will be deduced by a
4299/// call to the given function template.
4300void
4301Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
4302                                    SmallVectorImpl<bool> &Deduced) {
4303  TemplateParameterList *TemplateParams
4304    = FunctionTemplate->getTemplateParameters();
4305  Deduced.clear();
4306  Deduced.resize(TemplateParams->size());
4307
4308  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4309  for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
4310    ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
4311                                 true, TemplateParams->getDepth(), Deduced);
4312}
4313
4314bool hasDeducibleTemplateParameters(Sema &S,
4315                                    FunctionTemplateDecl *FunctionTemplate,
4316                                    QualType T) {
4317  if (!T->isDependentType())
4318    return false;
4319
4320  TemplateParameterList *TemplateParams
4321    = FunctionTemplate->getTemplateParameters();
4322  SmallVector<bool, 4> Deduced;
4323  Deduced.resize(TemplateParams->size());
4324  ::MarkUsedTemplateParameters(S, T, true, TemplateParams->getDepth(),
4325                               Deduced);
4326
4327  for (unsigned I = 0, N = Deduced.size(); I != N; ++I)
4328    if (Deduced[I])
4329      return true;
4330
4331  return false;
4332}
4333