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 
27 namespace 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 
59 using namespace clang;
60 
61 /// \brief Compare two APSInts, extending and switching the sign as
62 /// necessary to compare their values regardless of underlying type.
63 static 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 
82 static Sema::TemplateDeductionResult
83 DeduceTemplateArguments(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.
93 enum 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.
102 struct 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 
114 static Sema::TemplateDeductionResult
115 DeduceTemplateArguments(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 
126 static Sema::TemplateDeductionResult
127 DeduceTemplateArguments(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.
138 static 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.
150 static 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.
166 static DeducedTemplateArgument
167 checkDeducedTemplateArguments(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.
285 static Sema::TemplateDeductionResult
286 DeduceNonTypeTemplateArgument(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.
314 static Sema::TemplateDeductionResult
315 DeduceNonTypeTemplateArgument(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.
345 static Sema::TemplateDeductionResult
346 DeduceNonTypeTemplateArgument(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 
369 static Sema::TemplateDeductionResult
370 DeduceTemplateArguments(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.
428 static Sema::TemplateDeductionResult
429 DeduceTemplateArguments(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.
490 static 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.
513 static std::pair<unsigned, unsigned>
514 getDepthAndIndex(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.
526 static std::pair<unsigned, unsigned>
527 getDepthAndIndex(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.
537 static 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.
548 static 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.
580 static Sema::TemplateDeductionResult
581 FinishArgumentPackDeduction(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.
665 static Sema::TemplateDeductionResult
666 DeduceTemplateArguments(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.
804 static 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.
860 static Sema::TemplateDeductionResult
861 DeduceTemplateArguments(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     //     T *
1121     case Type::Pointer: {
1122       QualType PointeeType;
1123       if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1124         PointeeType = PointerArg->getPointeeType();
1125       } else if (const ObjCObjectPointerType *PointerArg
1126                    = Arg->getAs<ObjCObjectPointerType>()) {
1127         PointeeType = PointerArg->getPointeeType();
1128       } else {
1129         return Sema::TDK_NonDeducedMismatch;
1130       }
1131 
1132       unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
1133       return DeduceTemplateArguments(S, TemplateParams,
1134                                    cast<PointerType>(Param)->getPointeeType(),
1135                                      PointeeType,
1136                                      Info, Deduced, SubTDF);
1137     }
1138 
1139     //     T &
1140     case Type::LValueReference: {
1141       const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
1142       if (!ReferenceArg)
1143         return Sema::TDK_NonDeducedMismatch;
1144 
1145       return DeduceTemplateArguments(S, TemplateParams,
1146                            cast<LValueReferenceType>(Param)->getPointeeType(),
1147                                      ReferenceArg->getPointeeType(),
1148                                      Info, Deduced, 0);
1149     }
1150 
1151     //     T && [C++0x]
1152     case Type::RValueReference: {
1153       const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
1154       if (!ReferenceArg)
1155         return Sema::TDK_NonDeducedMismatch;
1156 
1157       return DeduceTemplateArguments(S, TemplateParams,
1158                            cast<RValueReferenceType>(Param)->getPointeeType(),
1159                                      ReferenceArg->getPointeeType(),
1160                                      Info, Deduced, 0);
1161     }
1162 
1163     //     T [] (implied, but not stated explicitly)
1164     case Type::IncompleteArray: {
1165       const IncompleteArrayType *IncompleteArrayArg =
1166         S.Context.getAsIncompleteArrayType(Arg);
1167       if (!IncompleteArrayArg)
1168         return Sema::TDK_NonDeducedMismatch;
1169 
1170       unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1171       return DeduceTemplateArguments(S, TemplateParams,
1172                      S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1173                                      IncompleteArrayArg->getElementType(),
1174                                      Info, Deduced, SubTDF);
1175     }
1176 
1177     //     T [integer-constant]
1178     case Type::ConstantArray: {
1179       const ConstantArrayType *ConstantArrayArg =
1180         S.Context.getAsConstantArrayType(Arg);
1181       if (!ConstantArrayArg)
1182         return Sema::TDK_NonDeducedMismatch;
1183 
1184       const ConstantArrayType *ConstantArrayParm =
1185         S.Context.getAsConstantArrayType(Param);
1186       if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
1187         return Sema::TDK_NonDeducedMismatch;
1188 
1189       unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1190       return DeduceTemplateArguments(S, TemplateParams,
1191                                      ConstantArrayParm->getElementType(),
1192                                      ConstantArrayArg->getElementType(),
1193                                      Info, Deduced, SubTDF);
1194     }
1195 
1196     //     type [i]
1197     case Type::DependentSizedArray: {
1198       const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
1199       if (!ArrayArg)
1200         return Sema::TDK_NonDeducedMismatch;
1201 
1202       unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1203 
1204       // Check the element type of the arrays
1205       const DependentSizedArrayType *DependentArrayParm
1206         = S.Context.getAsDependentSizedArrayType(Param);
1207       if (Sema::TemplateDeductionResult Result
1208             = DeduceTemplateArguments(S, TemplateParams,
1209                                       DependentArrayParm->getElementType(),
1210                                       ArrayArg->getElementType(),
1211                                       Info, Deduced, SubTDF))
1212         return Result;
1213 
1214       // Determine the array bound is something we can deduce.
1215       NonTypeTemplateParmDecl *NTTP
1216         = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1217       if (!NTTP)
1218         return Sema::TDK_Success;
1219 
1220       // We can perform template argument deduction for the given non-type
1221       // template parameter.
1222       assert(NTTP->getDepth() == 0 &&
1223              "Cannot deduce non-type template argument at depth > 0");
1224       if (const ConstantArrayType *ConstantArrayArg
1225             = dyn_cast<ConstantArrayType>(ArrayArg)) {
1226         llvm::APSInt Size(ConstantArrayArg->getSize());
1227         return DeduceNonTypeTemplateArgument(S, NTTP, Size,
1228                                              S.Context.getSizeType(),
1229                                              /*ArrayBound=*/true,
1230                                              Info, Deduced);
1231       }
1232       if (const DependentSizedArrayType *DependentArrayArg
1233             = dyn_cast<DependentSizedArrayType>(ArrayArg))
1234         if (DependentArrayArg->getSizeExpr())
1235           return DeduceNonTypeTemplateArgument(S, NTTP,
1236                                                DependentArrayArg->getSizeExpr(),
1237                                                Info, Deduced);
1238 
1239       // Incomplete type does not match a dependently-sized array type
1240       return Sema::TDK_NonDeducedMismatch;
1241     }
1242 
1243     //     type(*)(T)
1244     //     T(*)()
1245     //     T(*)(T)
1246     case Type::FunctionProto: {
1247       unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
1248       const FunctionProtoType *FunctionProtoArg =
1249         dyn_cast<FunctionProtoType>(Arg);
1250       if (!FunctionProtoArg)
1251         return Sema::TDK_NonDeducedMismatch;
1252 
1253       const FunctionProtoType *FunctionProtoParam =
1254         cast<FunctionProtoType>(Param);
1255 
1256       if (FunctionProtoParam->getTypeQuals()
1257             != FunctionProtoArg->getTypeQuals() ||
1258           FunctionProtoParam->getRefQualifier()
1259             != FunctionProtoArg->getRefQualifier() ||
1260           FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
1261         return Sema::TDK_NonDeducedMismatch;
1262 
1263       // Check return types.
1264       if (Sema::TemplateDeductionResult Result
1265             = DeduceTemplateArguments(S, TemplateParams,
1266                                       FunctionProtoParam->getResultType(),
1267                                       FunctionProtoArg->getResultType(),
1268                                       Info, Deduced, 0))
1269         return Result;
1270 
1271       return DeduceTemplateArguments(S, TemplateParams,
1272                                      FunctionProtoParam->arg_type_begin(),
1273                                      FunctionProtoParam->getNumArgs(),
1274                                      FunctionProtoArg->arg_type_begin(),
1275                                      FunctionProtoArg->getNumArgs(),
1276                                      Info, Deduced, SubTDF);
1277     }
1278 
1279     case Type::InjectedClassName: {
1280       // Treat a template's injected-class-name as if the template
1281       // specialization type had been used.
1282       Param = cast<InjectedClassNameType>(Param)
1283         ->getInjectedSpecializationType();
1284       assert(isa<TemplateSpecializationType>(Param) &&
1285              "injected class name is not a template specialization type");
1286       // fall through
1287     }
1288 
1289     //     template-name<T> (where template-name refers to a class template)
1290     //     template-name<i>
1291     //     TT<T>
1292     //     TT<i>
1293     //     TT<>
1294     case Type::TemplateSpecialization: {
1295       const TemplateSpecializationType *SpecParam
1296         = cast<TemplateSpecializationType>(Param);
1297 
1298       // Try to deduce template arguments from the template-id.
1299       Sema::TemplateDeductionResult Result
1300         = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
1301                                   Info, Deduced);
1302 
1303       if (Result && (TDF & TDF_DerivedClass)) {
1304         // C++ [temp.deduct.call]p3b3:
1305         //   If P is a class, and P has the form template-id, then A can be a
1306         //   derived class of the deduced A. Likewise, if P is a pointer to a
1307         //   class of the form template-id, A can be a pointer to a derived
1308         //   class pointed to by the deduced A.
1309         //
1310         // More importantly:
1311         //   These alternatives are considered only if type deduction would
1312         //   otherwise fail.
1313         if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1314           // We cannot inspect base classes as part of deduction when the type
1315           // is incomplete, so either instantiate any templates necessary to
1316           // complete the type, or skip over it if it cannot be completed.
1317           if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
1318             return Result;
1319 
1320           // Use data recursion to crawl through the list of base classes.
1321           // Visited contains the set of nodes we have already visited, while
1322           // ToVisit is our stack of records that we still need to visit.
1323           llvm::SmallPtrSet<const RecordType *, 8> Visited;
1324           SmallVector<const RecordType *, 8> ToVisit;
1325           ToVisit.push_back(RecordT);
1326           bool Successful = false;
1327           SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1328           DeducedOrig = Deduced;
1329           while (!ToVisit.empty()) {
1330             // Retrieve the next class in the inheritance hierarchy.
1331             const RecordType *NextT = ToVisit.back();
1332             ToVisit.pop_back();
1333 
1334             // If we have already seen this type, skip it.
1335             if (!Visited.insert(NextT))
1336               continue;
1337 
1338             // If this is a base class, try to perform template argument
1339             // deduction from it.
1340             if (NextT != RecordT) {
1341               Sema::TemplateDeductionResult BaseResult
1342                 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
1343                                           QualType(NextT, 0), Info, Deduced);
1344 
1345               // If template argument deduction for this base was successful,
1346               // note that we had some success. Otherwise, ignore any deductions
1347               // from this base class.
1348               if (BaseResult == Sema::TDK_Success) {
1349                 Successful = true;
1350                 DeducedOrig = Deduced;
1351               }
1352               else
1353                 Deduced = DeducedOrig;
1354             }
1355 
1356             // Visit base classes
1357             CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1358             for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1359                                                  BaseEnd = Next->bases_end();
1360                  Base != BaseEnd; ++Base) {
1361               assert(Base->getType()->isRecordType() &&
1362                      "Base class that isn't a record?");
1363               ToVisit.push_back(Base->getType()->getAs<RecordType>());
1364             }
1365           }
1366 
1367           if (Successful)
1368             return Sema::TDK_Success;
1369         }
1370 
1371       }
1372 
1373       return Result;
1374     }
1375 
1376     //     T type::*
1377     //     T T::*
1378     //     T (type::*)()
1379     //     type (T::*)()
1380     //     type (type::*)(T)
1381     //     type (T::*)(T)
1382     //     T (type::*)(T)
1383     //     T (T::*)()
1384     //     T (T::*)(T)
1385     case Type::MemberPointer: {
1386       const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1387       const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1388       if (!MemPtrArg)
1389         return Sema::TDK_NonDeducedMismatch;
1390 
1391       if (Sema::TemplateDeductionResult Result
1392             = DeduceTemplateArguments(S, TemplateParams,
1393                                       MemPtrParam->getPointeeType(),
1394                                       MemPtrArg->getPointeeType(),
1395                                       Info, Deduced,
1396                                       TDF & TDF_IgnoreQualifiers))
1397         return Result;
1398 
1399       return DeduceTemplateArguments(S, TemplateParams,
1400                                      QualType(MemPtrParam->getClass(), 0),
1401                                      QualType(MemPtrArg->getClass(), 0),
1402                                      Info, Deduced, 0);
1403     }
1404 
1405     //     (clang extension)
1406     //
1407     //     type(^)(T)
1408     //     T(^)()
1409     //     T(^)(T)
1410     case Type::BlockPointer: {
1411       const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1412       const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
1413 
1414       if (!BlockPtrArg)
1415         return Sema::TDK_NonDeducedMismatch;
1416 
1417       return DeduceTemplateArguments(S, TemplateParams,
1418                                      BlockPtrParam->getPointeeType(),
1419                                      BlockPtrArg->getPointeeType(), Info,
1420                                      Deduced, 0);
1421     }
1422 
1423     //     (clang extension)
1424     //
1425     //     T __attribute__(((ext_vector_type(<integral constant>))))
1426     case Type::ExtVector: {
1427       const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1428       if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1429         // Make sure that the vectors have the same number of elements.
1430         if (VectorParam->getNumElements() != VectorArg->getNumElements())
1431           return Sema::TDK_NonDeducedMismatch;
1432 
1433         // Perform deduction on the element types.
1434         return DeduceTemplateArguments(S, TemplateParams,
1435                                        VectorParam->getElementType(),
1436                                        VectorArg->getElementType(),
1437                                        Info, Deduced,
1438                                        TDF);
1439       }
1440 
1441       if (const DependentSizedExtVectorType *VectorArg
1442                                 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1443         // We can't check the number of elements, since the argument has a
1444         // dependent number of elements. This can only occur during partial
1445         // ordering.
1446 
1447         // Perform deduction on the element types.
1448         return DeduceTemplateArguments(S, TemplateParams,
1449                                        VectorParam->getElementType(),
1450                                        VectorArg->getElementType(),
1451                                        Info, Deduced,
1452                                        TDF);
1453       }
1454 
1455       return Sema::TDK_NonDeducedMismatch;
1456     }
1457 
1458     //     (clang extension)
1459     //
1460     //     T __attribute__(((ext_vector_type(N))))
1461     case Type::DependentSizedExtVector: {
1462       const DependentSizedExtVectorType *VectorParam
1463         = cast<DependentSizedExtVectorType>(Param);
1464 
1465       if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1466         // Perform deduction on the element types.
1467         if (Sema::TemplateDeductionResult Result
1468               = DeduceTemplateArguments(S, TemplateParams,
1469                                         VectorParam->getElementType(),
1470                                         VectorArg->getElementType(),
1471                                         Info, Deduced,
1472                                         TDF))
1473           return Result;
1474 
1475         // Perform deduction on the vector size, if we can.
1476         NonTypeTemplateParmDecl *NTTP
1477           = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1478         if (!NTTP)
1479           return Sema::TDK_Success;
1480 
1481         llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1482         ArgSize = VectorArg->getNumElements();
1483         return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1484                                              false, Info, Deduced);
1485       }
1486 
1487       if (const DependentSizedExtVectorType *VectorArg
1488                                 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1489         // Perform deduction on the element types.
1490         if (Sema::TemplateDeductionResult Result
1491             = DeduceTemplateArguments(S, TemplateParams,
1492                                       VectorParam->getElementType(),
1493                                       VectorArg->getElementType(),
1494                                       Info, Deduced,
1495                                       TDF))
1496           return Result;
1497 
1498         // Perform deduction on the vector size, if we can.
1499         NonTypeTemplateParmDecl *NTTP
1500           = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1501         if (!NTTP)
1502           return Sema::TDK_Success;
1503 
1504         return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1505                                              Info, Deduced);
1506       }
1507 
1508       return Sema::TDK_NonDeducedMismatch;
1509     }
1510 
1511     case Type::TypeOfExpr:
1512     case Type::TypeOf:
1513     case Type::DependentName:
1514     case Type::UnresolvedUsing:
1515     case Type::Decltype:
1516     case Type::UnaryTransform:
1517     case Type::Auto:
1518     case Type::DependentTemplateSpecialization:
1519     case Type::PackExpansion:
1520       // No template argument deduction for these types
1521       return Sema::TDK_Success;
1522   }
1523 
1524   return Sema::TDK_Success;
1525 }
1526 
1527 static Sema::TemplateDeductionResult
1528 DeduceTemplateArguments(Sema &S,
1529                         TemplateParameterList *TemplateParams,
1530                         const TemplateArgument &Param,
1531                         TemplateArgument Arg,
1532                         TemplateDeductionInfo &Info,
1533                     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1534   // If the template argument is a pack expansion, perform template argument
1535   // deduction against the pattern of that expansion. This only occurs during
1536   // partial ordering.
1537   if (Arg.isPackExpansion())
1538     Arg = Arg.getPackExpansionPattern();
1539 
1540   switch (Param.getKind()) {
1541   case TemplateArgument::Null:
1542     llvm_unreachable("Null template argument in parameter list");
1543 
1544   case TemplateArgument::Type:
1545     if (Arg.getKind() == TemplateArgument::Type)
1546       return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
1547                                      Arg.getAsType(), Info, Deduced, 0);
1548     Info.FirstArg = Param;
1549     Info.SecondArg = Arg;
1550     return Sema::TDK_NonDeducedMismatch;
1551 
1552   case TemplateArgument::Template:
1553     if (Arg.getKind() == TemplateArgument::Template)
1554       return DeduceTemplateArguments(S, TemplateParams,
1555                                      Param.getAsTemplate(),
1556                                      Arg.getAsTemplate(), Info, Deduced);
1557     Info.FirstArg = Param;
1558     Info.SecondArg = Arg;
1559     return Sema::TDK_NonDeducedMismatch;
1560 
1561   case TemplateArgument::TemplateExpansion:
1562     llvm_unreachable("caller should handle pack expansions");
1563     break;
1564 
1565   case TemplateArgument::Declaration:
1566     if (Arg.getKind() == TemplateArgument::Declaration &&
1567         Param.getAsDecl()->getCanonicalDecl() ==
1568           Arg.getAsDecl()->getCanonicalDecl())
1569       return Sema::TDK_Success;
1570 
1571     Info.FirstArg = Param;
1572     Info.SecondArg = Arg;
1573     return Sema::TDK_NonDeducedMismatch;
1574 
1575   case TemplateArgument::Integral:
1576     if (Arg.getKind() == TemplateArgument::Integral) {
1577       if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
1578         return Sema::TDK_Success;
1579 
1580       Info.FirstArg = Param;
1581       Info.SecondArg = Arg;
1582       return Sema::TDK_NonDeducedMismatch;
1583     }
1584 
1585     if (Arg.getKind() == TemplateArgument::Expression) {
1586       Info.FirstArg = Param;
1587       Info.SecondArg = Arg;
1588       return Sema::TDK_NonDeducedMismatch;
1589     }
1590 
1591     Info.FirstArg = Param;
1592     Info.SecondArg = Arg;
1593     return Sema::TDK_NonDeducedMismatch;
1594 
1595   case TemplateArgument::Expression: {
1596     if (NonTypeTemplateParmDecl *NTTP
1597           = getDeducedParameterFromExpr(Param.getAsExpr())) {
1598       if (Arg.getKind() == TemplateArgument::Integral)
1599         return DeduceNonTypeTemplateArgument(S, NTTP,
1600                                              *Arg.getAsIntegral(),
1601                                              Arg.getIntegralType(),
1602                                              /*ArrayBound=*/false,
1603                                              Info, Deduced);
1604       if (Arg.getKind() == TemplateArgument::Expression)
1605         return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
1606                                              Info, Deduced);
1607       if (Arg.getKind() == TemplateArgument::Declaration)
1608         return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
1609                                              Info, Deduced);
1610 
1611       Info.FirstArg = Param;
1612       Info.SecondArg = Arg;
1613       return Sema::TDK_NonDeducedMismatch;
1614     }
1615 
1616     // Can't deduce anything, but that's okay.
1617     return Sema::TDK_Success;
1618   }
1619   case TemplateArgument::Pack:
1620     llvm_unreachable("Argument packs should be expanded by the caller!");
1621   }
1622 
1623   return Sema::TDK_Success;
1624 }
1625 
1626 /// \brief Determine whether there is a template argument to be used for
1627 /// deduction.
1628 ///
1629 /// This routine "expands" argument packs in-place, overriding its input
1630 /// parameters so that \c Args[ArgIdx] will be the available template argument.
1631 ///
1632 /// \returns true if there is another template argument (which will be at
1633 /// \c Args[ArgIdx]), false otherwise.
1634 static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1635                                             unsigned &ArgIdx,
1636                                             unsigned &NumArgs) {
1637   if (ArgIdx == NumArgs)
1638     return false;
1639 
1640   const TemplateArgument &Arg = Args[ArgIdx];
1641   if (Arg.getKind() != TemplateArgument::Pack)
1642     return true;
1643 
1644   assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1645   Args = Arg.pack_begin();
1646   NumArgs = Arg.pack_size();
1647   ArgIdx = 0;
1648   return ArgIdx < NumArgs;
1649 }
1650 
1651 /// \brief Determine whether the given set of template arguments has a pack
1652 /// expansion that is not the last template argument.
1653 static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1654                                       unsigned NumArgs) {
1655   unsigned ArgIdx = 0;
1656   while (ArgIdx < NumArgs) {
1657     const TemplateArgument &Arg = Args[ArgIdx];
1658 
1659     // Unwrap argument packs.
1660     if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1661       Args = Arg.pack_begin();
1662       NumArgs = Arg.pack_size();
1663       ArgIdx = 0;
1664       continue;
1665     }
1666 
1667     ++ArgIdx;
1668     if (ArgIdx == NumArgs)
1669       return false;
1670 
1671     if (Arg.isPackExpansion())
1672       return true;
1673   }
1674 
1675   return false;
1676 }
1677 
1678 static Sema::TemplateDeductionResult
1679 DeduceTemplateArguments(Sema &S,
1680                         TemplateParameterList *TemplateParams,
1681                         const TemplateArgument *Params, unsigned NumParams,
1682                         const TemplateArgument *Args, unsigned NumArgs,
1683                         TemplateDeductionInfo &Info,
1684                     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1685                         bool NumberOfArgumentsMustMatch) {
1686   // C++0x [temp.deduct.type]p9:
1687   //   If the template argument list of P contains a pack expansion that is not
1688   //   the last template argument, the entire template argument list is a
1689   //   non-deduced context.
1690   if (hasPackExpansionBeforeEnd(Params, NumParams))
1691     return Sema::TDK_Success;
1692 
1693   // C++0x [temp.deduct.type]p9:
1694   //   If P has a form that contains <T> or <i>, then each argument Pi of the
1695   //   respective template argument list P is compared with the corresponding
1696   //   argument Ai of the corresponding template argument list of A.
1697   unsigned ArgIdx = 0, ParamIdx = 0;
1698   for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1699        ++ParamIdx) {
1700     if (!Params[ParamIdx].isPackExpansion()) {
1701       // The simple case: deduce template arguments by matching Pi and Ai.
1702 
1703       // Check whether we have enough arguments.
1704       if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
1705         return NumberOfArgumentsMustMatch? Sema::TDK_NonDeducedMismatch
1706                                          : Sema::TDK_Success;
1707 
1708       if (Args[ArgIdx].isPackExpansion()) {
1709         // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1710         // but applied to pack expansions that are template arguments.
1711         return Sema::TDK_NonDeducedMismatch;
1712       }
1713 
1714       // Perform deduction for this Pi/Ai pair.
1715       if (Sema::TemplateDeductionResult Result
1716             = DeduceTemplateArguments(S, TemplateParams,
1717                                       Params[ParamIdx], Args[ArgIdx],
1718                                       Info, Deduced))
1719         return Result;
1720 
1721       // Move to the next argument.
1722       ++ArgIdx;
1723       continue;
1724     }
1725 
1726     // The parameter is a pack expansion.
1727 
1728     // C++0x [temp.deduct.type]p9:
1729     //   If Pi is a pack expansion, then the pattern of Pi is compared with
1730     //   each remaining argument in the template argument list of A. Each
1731     //   comparison deduces template arguments for subsequent positions in the
1732     //   template parameter packs expanded by Pi.
1733     TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1734 
1735     // Compute the set of template parameter indices that correspond to
1736     // parameter packs expanded by the pack expansion.
1737     SmallVector<unsigned, 2> PackIndices;
1738     {
1739       llvm::BitVector SawIndices(TemplateParams->size());
1740       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1741       S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1742       for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1743         unsigned Depth, Index;
1744         llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1745         if (Depth == 0 && !SawIndices[Index]) {
1746           SawIndices[Index] = true;
1747           PackIndices.push_back(Index);
1748         }
1749       }
1750     }
1751     assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1752 
1753     // FIXME: If there are no remaining arguments, we can bail out early
1754     // and set any deduced parameter packs to an empty argument pack.
1755     // The latter part of this is a (minor) correctness issue.
1756 
1757     // Save the deduced template arguments for each parameter pack expanded
1758     // by this pack expansion, then clear out the deduction.
1759     SmallVector<DeducedTemplateArgument, 2>
1760       SavedPacks(PackIndices.size());
1761     SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2>
1762       NewlyDeducedPacks(PackIndices.size());
1763     PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
1764                                  NewlyDeducedPacks);
1765 
1766     // Keep track of the deduced template arguments for each parameter pack
1767     // expanded by this pack expansion (the outer index) and for each
1768     // template argument (the inner SmallVectors).
1769     bool HasAnyArguments = false;
1770     while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1771       HasAnyArguments = true;
1772 
1773       // Deduce template arguments from the pattern.
1774       if (Sema::TemplateDeductionResult Result
1775             = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1776                                       Info, Deduced))
1777         return Result;
1778 
1779       // Capture the deduced template arguments for each parameter pack expanded
1780       // by this pack expansion, add them to the list of arguments we've deduced
1781       // for that pack, then clear out the deduced argument.
1782       for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1783         DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1784         if (!DeducedArg.isNull()) {
1785           NewlyDeducedPacks[I].push_back(DeducedArg);
1786           DeducedArg = DeducedTemplateArgument();
1787         }
1788       }
1789 
1790       ++ArgIdx;
1791     }
1792 
1793     // Build argument packs for each of the parameter packs expanded by this
1794     // pack expansion.
1795     if (Sema::TemplateDeductionResult Result
1796           = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
1797                                         Deduced, PackIndices, SavedPacks,
1798                                         NewlyDeducedPacks, Info))
1799       return Result;
1800   }
1801 
1802   // If there is an argument remaining, then we had too many arguments.
1803   if (NumberOfArgumentsMustMatch &&
1804       hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
1805     return Sema::TDK_NonDeducedMismatch;
1806 
1807   return Sema::TDK_Success;
1808 }
1809 
1810 static Sema::TemplateDeductionResult
1811 DeduceTemplateArguments(Sema &S,
1812                         TemplateParameterList *TemplateParams,
1813                         const TemplateArgumentList &ParamList,
1814                         const TemplateArgumentList &ArgList,
1815                         TemplateDeductionInfo &Info,
1816                     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1817   return DeduceTemplateArguments(S, TemplateParams,
1818                                  ParamList.data(), ParamList.size(),
1819                                  ArgList.data(), ArgList.size(),
1820                                  Info, Deduced);
1821 }
1822 
1823 /// \brief Determine whether two template arguments are the same.
1824 static bool isSameTemplateArg(ASTContext &Context,
1825                               const TemplateArgument &X,
1826                               const TemplateArgument &Y) {
1827   if (X.getKind() != Y.getKind())
1828     return false;
1829 
1830   switch (X.getKind()) {
1831     case TemplateArgument::Null:
1832       llvm_unreachable("Comparing NULL template argument");
1833 
1834     case TemplateArgument::Type:
1835       return Context.getCanonicalType(X.getAsType()) ==
1836              Context.getCanonicalType(Y.getAsType());
1837 
1838     case TemplateArgument::Declaration:
1839       return X.getAsDecl()->getCanonicalDecl() ==
1840              Y.getAsDecl()->getCanonicalDecl();
1841 
1842     case TemplateArgument::Template:
1843     case TemplateArgument::TemplateExpansion:
1844       return Context.getCanonicalTemplateName(
1845                     X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1846              Context.getCanonicalTemplateName(
1847                     Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
1848 
1849     case TemplateArgument::Integral:
1850       return *X.getAsIntegral() == *Y.getAsIntegral();
1851 
1852     case TemplateArgument::Expression: {
1853       llvm::FoldingSetNodeID XID, YID;
1854       X.getAsExpr()->Profile(XID, Context, true);
1855       Y.getAsExpr()->Profile(YID, Context, true);
1856       return XID == YID;
1857     }
1858 
1859     case TemplateArgument::Pack:
1860       if (X.pack_size() != Y.pack_size())
1861         return false;
1862 
1863       for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1864                                         XPEnd = X.pack_end(),
1865                                            YP = Y.pack_begin();
1866            XP != XPEnd; ++XP, ++YP)
1867         if (!isSameTemplateArg(Context, *XP, *YP))
1868           return false;
1869 
1870       return true;
1871   }
1872 
1873   return false;
1874 }
1875 
1876 /// \brief Allocate a TemplateArgumentLoc where all locations have
1877 /// been initialized to the given location.
1878 ///
1879 /// \param S The semantic analysis object.
1880 ///
1881 /// \param The template argument we are producing template argument
1882 /// location information for.
1883 ///
1884 /// \param NTTPType For a declaration template argument, the type of
1885 /// the non-type template parameter that corresponds to this template
1886 /// argument.
1887 ///
1888 /// \param Loc The source location to use for the resulting template
1889 /// argument.
1890 static TemplateArgumentLoc
1891 getTrivialTemplateArgumentLoc(Sema &S,
1892                               const TemplateArgument &Arg,
1893                               QualType NTTPType,
1894                               SourceLocation Loc) {
1895   switch (Arg.getKind()) {
1896   case TemplateArgument::Null:
1897     llvm_unreachable("Can't get a NULL template argument here");
1898     break;
1899 
1900   case TemplateArgument::Type:
1901     return TemplateArgumentLoc(Arg,
1902                      S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1903 
1904   case TemplateArgument::Declaration: {
1905     Expr *E
1906       = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
1907     .takeAs<Expr>();
1908     return TemplateArgumentLoc(TemplateArgument(E), E);
1909   }
1910 
1911   case TemplateArgument::Integral: {
1912     Expr *E
1913       = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
1914     return TemplateArgumentLoc(TemplateArgument(E), E);
1915   }
1916 
1917     case TemplateArgument::Template:
1918     case TemplateArgument::TemplateExpansion: {
1919       NestedNameSpecifierLocBuilder Builder;
1920       TemplateName Template = Arg.getAsTemplate();
1921       if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
1922         Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
1923       else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1924         Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
1925 
1926       if (Arg.getKind() == TemplateArgument::Template)
1927         return TemplateArgumentLoc(Arg,
1928                                    Builder.getWithLocInContext(S.Context),
1929                                    Loc);
1930 
1931 
1932       return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
1933                                  Loc, Loc);
1934     }
1935 
1936   case TemplateArgument::Expression:
1937     return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1938 
1939   case TemplateArgument::Pack:
1940     return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1941   }
1942 
1943   return TemplateArgumentLoc();
1944 }
1945 
1946 
1947 /// \brief Convert the given deduced template argument and add it to the set of
1948 /// fully-converted template arguments.
1949 static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1950                                            DeducedTemplateArgument Arg,
1951                                            NamedDecl *Template,
1952                                            QualType NTTPType,
1953                                            unsigned ArgumentPackIndex,
1954                                            TemplateDeductionInfo &Info,
1955                                            bool InFunctionTemplate,
1956                              SmallVectorImpl<TemplateArgument> &Output) {
1957   if (Arg.getKind() == TemplateArgument::Pack) {
1958     // This is a template argument pack, so check each of its arguments against
1959     // the template parameter.
1960     SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1961     for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
1962                                       PAEnd = Arg.pack_end();
1963          PA != PAEnd; ++PA) {
1964       // When converting the deduced template argument, append it to the
1965       // general output list. We need to do this so that the template argument
1966       // checking logic has all of the prior template arguments available.
1967       DeducedTemplateArgument InnerArg(*PA);
1968       InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1969       if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1970                                          NTTPType, PackedArgsBuilder.size(),
1971                                          Info, InFunctionTemplate, Output))
1972         return true;
1973 
1974       // Move the converted template argument into our argument pack.
1975       PackedArgsBuilder.push_back(Output.back());
1976       Output.pop_back();
1977     }
1978 
1979     // Create the resulting argument pack.
1980     Output.push_back(TemplateArgument::CreatePackCopy(S.Context,
1981                                                       PackedArgsBuilder.data(),
1982                                                      PackedArgsBuilder.size()));
1983     return false;
1984   }
1985 
1986   // Convert the deduced template argument into a template
1987   // argument that we can check, almost as if the user had written
1988   // the template argument explicitly.
1989   TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1990                                                              Info.getLocation());
1991 
1992   // Check the template argument, converting it as necessary.
1993   return S.CheckTemplateArgument(Param, ArgLoc,
1994                                  Template,
1995                                  Template->getLocation(),
1996                                  Template->getSourceRange().getEnd(),
1997                                  ArgumentPackIndex,
1998                                  Output,
1999                                  InFunctionTemplate
2000                                   ? (Arg.wasDeducedFromArrayBound()
2001                                        ? Sema::CTAK_DeducedFromArrayBound
2002                                        : Sema::CTAK_Deduced)
2003                                  : Sema::CTAK_Specified);
2004 }
2005 
2006 /// Complete template argument deduction for a class template partial
2007 /// specialization.
2008 static Sema::TemplateDeductionResult
2009 FinishTemplateArgumentDeduction(Sema &S,
2010                                 ClassTemplatePartialSpecializationDecl *Partial,
2011                                 const TemplateArgumentList &TemplateArgs,
2012                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2013                                 TemplateDeductionInfo &Info) {
2014   // Trap errors.
2015   Sema::SFINAETrap Trap(S);
2016 
2017   Sema::ContextRAII SavedContext(S, Partial);
2018 
2019   // C++ [temp.deduct.type]p2:
2020   //   [...] or if any template argument remains neither deduced nor
2021   //   explicitly specified, template argument deduction fails.
2022   SmallVector<TemplateArgument, 4> Builder;
2023   TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2024   for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2025     NamedDecl *Param = PartialParams->getParam(I);
2026     if (Deduced[I].isNull()) {
2027       Info.Param = makeTemplateParameter(Param);
2028       return Sema::TDK_Incomplete;
2029     }
2030 
2031     // We have deduced this argument, so it still needs to be
2032     // checked and converted.
2033 
2034     // First, for a non-type template parameter type that is
2035     // initialized by a declaration, we need the type of the
2036     // corresponding non-type template parameter.
2037     QualType NTTPType;
2038     if (NonTypeTemplateParmDecl *NTTP
2039                                   = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2040       NTTPType = NTTP->getType();
2041       if (NTTPType->isDependentType()) {
2042         TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2043                                           Builder.data(), Builder.size());
2044         NTTPType = S.SubstType(NTTPType,
2045                                MultiLevelTemplateArgumentList(TemplateArgs),
2046                                NTTP->getLocation(),
2047                                NTTP->getDeclName());
2048         if (NTTPType.isNull()) {
2049           Info.Param = makeTemplateParameter(Param);
2050           // FIXME: These template arguments are temporary. Free them!
2051           Info.reset(TemplateArgumentList::CreateCopy(S.Context,
2052                                                       Builder.data(),
2053                                                       Builder.size()));
2054           return Sema::TDK_SubstitutionFailure;
2055         }
2056       }
2057     }
2058 
2059     if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
2060                                        Partial, NTTPType, 0, Info, false,
2061                                        Builder)) {
2062       Info.Param = makeTemplateParameter(Param);
2063       // FIXME: These template arguments are temporary. Free them!
2064       Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2065                                                   Builder.size()));
2066       return Sema::TDK_SubstitutionFailure;
2067     }
2068   }
2069 
2070   // Form the template argument list from the deduced template arguments.
2071   TemplateArgumentList *DeducedArgumentList
2072     = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2073                                        Builder.size());
2074 
2075   Info.reset(DeducedArgumentList);
2076 
2077   // Substitute the deduced template arguments into the template
2078   // arguments of the class template partial specialization, and
2079   // verify that the instantiated template arguments are both valid
2080   // and are equivalent to the template arguments originally provided
2081   // to the class template.
2082   LocalInstantiationScope InstScope(S);
2083   ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
2084   const TemplateArgumentLoc *PartialTemplateArgs
2085     = Partial->getTemplateArgsAsWritten();
2086 
2087   // Note that we don't provide the langle and rangle locations.
2088   TemplateArgumentListInfo InstArgs;
2089 
2090   if (S.Subst(PartialTemplateArgs,
2091               Partial->getNumTemplateArgsAsWritten(),
2092               InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2093     unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2094     if (ParamIdx >= Partial->getTemplateParameters()->size())
2095       ParamIdx = Partial->getTemplateParameters()->size() - 1;
2096 
2097     Decl *Param
2098       = const_cast<NamedDecl *>(
2099                           Partial->getTemplateParameters()->getParam(ParamIdx));
2100     Info.Param = makeTemplateParameter(Param);
2101     Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2102     return Sema::TDK_SubstitutionFailure;
2103   }
2104 
2105   SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2106   if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
2107                                   InstArgs, false, ConvertedInstArgs))
2108     return Sema::TDK_SubstitutionFailure;
2109 
2110   TemplateParameterList *TemplateParams
2111     = ClassTemplate->getTemplateParameters();
2112   for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2113     TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2114     if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2115       Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2116       Info.FirstArg = TemplateArgs[I];
2117       Info.SecondArg = InstArg;
2118       return Sema::TDK_NonDeducedMismatch;
2119     }
2120   }
2121 
2122   if (Trap.hasErrorOccurred())
2123     return Sema::TDK_SubstitutionFailure;
2124 
2125   return Sema::TDK_Success;
2126 }
2127 
2128 /// \brief Perform template argument deduction to determine whether
2129 /// the given template arguments match the given class template
2130 /// partial specialization per C++ [temp.class.spec.match].
2131 Sema::TemplateDeductionResult
2132 Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
2133                               const TemplateArgumentList &TemplateArgs,
2134                               TemplateDeductionInfo &Info) {
2135   // C++ [temp.class.spec.match]p2:
2136   //   A partial specialization matches a given actual template
2137   //   argument list if the template arguments of the partial
2138   //   specialization can be deduced from the actual template argument
2139   //   list (14.8.2).
2140   SFINAETrap Trap(*this);
2141   SmallVector<DeducedTemplateArgument, 4> Deduced;
2142   Deduced.resize(Partial->getTemplateParameters()->size());
2143   if (TemplateDeductionResult Result
2144         = ::DeduceTemplateArguments(*this,
2145                                     Partial->getTemplateParameters(),
2146                                     Partial->getTemplateArgs(),
2147                                     TemplateArgs, Info, Deduced))
2148     return Result;
2149 
2150   InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
2151                              Deduced.data(), Deduced.size(), Info);
2152   if (Inst)
2153     return TDK_InstantiationDepth;
2154 
2155   if (Trap.hasErrorOccurred())
2156     return Sema::TDK_SubstitutionFailure;
2157 
2158   return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2159                                            Deduced, Info);
2160 }
2161 
2162 /// \brief Determine whether the given type T is a simple-template-id type.
2163 static bool isSimpleTemplateIdType(QualType T) {
2164   if (const TemplateSpecializationType *Spec
2165         = T->getAs<TemplateSpecializationType>())
2166     return Spec->getTemplateName().getAsTemplateDecl() != 0;
2167 
2168   return false;
2169 }
2170 
2171 /// \brief Substitute the explicitly-provided template arguments into the
2172 /// given function template according to C++ [temp.arg.explicit].
2173 ///
2174 /// \param FunctionTemplate the function template into which the explicit
2175 /// template arguments will be substituted.
2176 ///
2177 /// \param ExplicitTemplateArguments the explicitly-specified template
2178 /// arguments.
2179 ///
2180 /// \param Deduced the deduced template arguments, which will be populated
2181 /// with the converted and checked explicit template arguments.
2182 ///
2183 /// \param ParamTypes will be populated with the instantiated function
2184 /// parameters.
2185 ///
2186 /// \param FunctionType if non-NULL, the result type of the function template
2187 /// will also be instantiated and the pointed-to value will be updated with
2188 /// the instantiated function type.
2189 ///
2190 /// \param Info if substitution fails for any reason, this object will be
2191 /// populated with more information about the failure.
2192 ///
2193 /// \returns TDK_Success if substitution was successful, or some failure
2194 /// condition.
2195 Sema::TemplateDeductionResult
2196 Sema::SubstituteExplicitTemplateArguments(
2197                                       FunctionTemplateDecl *FunctionTemplate,
2198                                TemplateArgumentListInfo &ExplicitTemplateArgs,
2199                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2200                                  SmallVectorImpl<QualType> &ParamTypes,
2201                                           QualType *FunctionType,
2202                                           TemplateDeductionInfo &Info) {
2203   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2204   TemplateParameterList *TemplateParams
2205     = FunctionTemplate->getTemplateParameters();
2206 
2207   if (ExplicitTemplateArgs.size() == 0) {
2208     // No arguments to substitute; just copy over the parameter types and
2209     // fill in the function type.
2210     for (FunctionDecl::param_iterator P = Function->param_begin(),
2211                                    PEnd = Function->param_end();
2212          P != PEnd;
2213          ++P)
2214       ParamTypes.push_back((*P)->getType());
2215 
2216     if (FunctionType)
2217       *FunctionType = Function->getType();
2218     return TDK_Success;
2219   }
2220 
2221   // Substitution of the explicit template arguments into a function template
2222   /// is a SFINAE context. Trap any errors that might occur.
2223   SFINAETrap Trap(*this);
2224 
2225   // C++ [temp.arg.explicit]p3:
2226   //   Template arguments that are present shall be specified in the
2227   //   declaration order of their corresponding template-parameters. The
2228   //   template argument list shall not specify more template-arguments than
2229   //   there are corresponding template-parameters.
2230   SmallVector<TemplateArgument, 4> Builder;
2231 
2232   // Enter a new template instantiation context where we check the
2233   // explicitly-specified template arguments against this function template,
2234   // and then substitute them into the function parameter types.
2235   InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
2236                              FunctionTemplate, Deduced.data(), Deduced.size(),
2237            ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2238                              Info);
2239   if (Inst)
2240     return TDK_InstantiationDepth;
2241 
2242   if (CheckTemplateArgumentList(FunctionTemplate,
2243                                 SourceLocation(),
2244                                 ExplicitTemplateArgs,
2245                                 true,
2246                                 Builder) || Trap.hasErrorOccurred()) {
2247     unsigned Index = Builder.size();
2248     if (Index >= TemplateParams->size())
2249       Index = TemplateParams->size() - 1;
2250     Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
2251     return TDK_InvalidExplicitArguments;
2252   }
2253 
2254   // Form the template argument list from the explicitly-specified
2255   // template arguments.
2256   TemplateArgumentList *ExplicitArgumentList
2257     = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
2258   Info.reset(ExplicitArgumentList);
2259 
2260   // Template argument deduction and the final substitution should be
2261   // done in the context of the templated declaration.  Explicit
2262   // argument substitution, on the other hand, needs to happen in the
2263   // calling context.
2264   ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2265 
2266   // If we deduced template arguments for a template parameter pack,
2267   // note that the template argument pack is partially substituted and record
2268   // the explicit template arguments. They'll be used as part of deduction
2269   // for this template parameter pack.
2270   for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2271     const TemplateArgument &Arg = Builder[I];
2272     if (Arg.getKind() == TemplateArgument::Pack) {
2273       CurrentInstantiationScope->SetPartiallySubstitutedPack(
2274                                                  TemplateParams->getParam(I),
2275                                                              Arg.pack_begin(),
2276                                                              Arg.pack_size());
2277       break;
2278     }
2279   }
2280 
2281   // Instantiate the types of each of the function parameters given the
2282   // explicitly-specified template arguments.
2283   if (SubstParmTypes(Function->getLocation(),
2284                      Function->param_begin(), Function->getNumParams(),
2285                      MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2286                      ParamTypes))
2287     return TDK_SubstitutionFailure;
2288 
2289   // If the caller wants a full function type back, instantiate the return
2290   // type and form that function type.
2291   if (FunctionType) {
2292     // FIXME: exception-specifications?
2293     const FunctionProtoType *Proto
2294       = Function->getType()->getAs<FunctionProtoType>();
2295     assert(Proto && "Function template does not have a prototype?");
2296 
2297     QualType ResultType
2298       = SubstType(Proto->getResultType(),
2299                   MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2300                   Function->getTypeSpecStartLoc(),
2301                   Function->getDeclName());
2302     if (ResultType.isNull() || Trap.hasErrorOccurred())
2303       return TDK_SubstitutionFailure;
2304 
2305     *FunctionType = BuildFunctionType(ResultType,
2306                                       ParamTypes.data(), ParamTypes.size(),
2307                                       Proto->isVariadic(),
2308                                       Proto->getTypeQuals(),
2309                                       Proto->getRefQualifier(),
2310                                       Function->getLocation(),
2311                                       Function->getDeclName(),
2312                                       Proto->getExtInfo());
2313     if (FunctionType->isNull() || Trap.hasErrorOccurred())
2314       return TDK_SubstitutionFailure;
2315   }
2316 
2317   // C++ [temp.arg.explicit]p2:
2318   //   Trailing template arguments that can be deduced (14.8.2) may be
2319   //   omitted from the list of explicit template-arguments. If all of the
2320   //   template arguments can be deduced, they may all be omitted; in this
2321   //   case, the empty template argument list <> itself may also be omitted.
2322   //
2323   // Take all of the explicitly-specified arguments and put them into
2324   // the set of deduced template arguments. Explicitly-specified
2325   // parameter packs, however, will be set to NULL since the deduction
2326   // mechanisms handle explicitly-specified argument packs directly.
2327   Deduced.reserve(TemplateParams->size());
2328   for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2329     const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2330     if (Arg.getKind() == TemplateArgument::Pack)
2331       Deduced.push_back(DeducedTemplateArgument());
2332     else
2333       Deduced.push_back(Arg);
2334   }
2335 
2336   return TDK_Success;
2337 }
2338 
2339 /// \brief Check whether the deduced argument type for a call to a function
2340 /// template matches the actual argument type per C++ [temp.deduct.call]p4.
2341 static bool
2342 CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2343                               QualType DeducedA) {
2344   ASTContext &Context = S.Context;
2345 
2346   QualType A = OriginalArg.OriginalArgType;
2347   QualType OriginalParamType = OriginalArg.OriginalParamType;
2348 
2349   // Check for type equality (top-level cv-qualifiers are ignored).
2350   if (Context.hasSameUnqualifiedType(A, DeducedA))
2351     return false;
2352 
2353   // Strip off references on the argument types; they aren't needed for
2354   // the following checks.
2355   if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2356     DeducedA = DeducedARef->getPointeeType();
2357   if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2358     A = ARef->getPointeeType();
2359 
2360   // C++ [temp.deduct.call]p4:
2361   //   [...] However, there are three cases that allow a difference:
2362   //     - If the original P is a reference type, the deduced A (i.e., the
2363   //       type referred to by the reference) can be more cv-qualified than
2364   //       the transformed A.
2365   if (const ReferenceType *OriginalParamRef
2366       = OriginalParamType->getAs<ReferenceType>()) {
2367     // We don't want to keep the reference around any more.
2368     OriginalParamType = OriginalParamRef->getPointeeType();
2369 
2370     Qualifiers AQuals = A.getQualifiers();
2371     Qualifiers DeducedAQuals = DeducedA.getQualifiers();
2372     if (AQuals == DeducedAQuals) {
2373       // Qualifiers match; there's nothing to do.
2374     } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
2375       return true;
2376     } else {
2377       // Qualifiers are compatible, so have the argument type adopt the
2378       // deduced argument type's qualifiers as if we had performed the
2379       // qualification conversion.
2380       A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2381     }
2382   }
2383 
2384   //    - The transformed A can be another pointer or pointer to member
2385   //      type that can be converted to the deduced A via a qualification
2386   //      conversion.
2387   //
2388   // Also allow conversions which merely strip [[noreturn]] from function types
2389   // (recursively) as an extension.
2390   // FIXME: Currently, this doesn't place nicely with qualfication conversions.
2391   bool ObjCLifetimeConversion = false;
2392   QualType ResultTy;
2393   if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
2394       (S.IsQualificationConversion(A, DeducedA, false,
2395                                    ObjCLifetimeConversion) ||
2396        S.IsNoReturnConversion(A, DeducedA, ResultTy)))
2397     return false;
2398 
2399 
2400   //    - If P is a class and P has the form simple-template-id, then the
2401   //      transformed A can be a derived class of the deduced A. [...]
2402   //     [...] Likewise, if P is a pointer to a class of the form
2403   //      simple-template-id, the transformed A can be a pointer to a
2404   //      derived class pointed to by the deduced A.
2405   if (const PointerType *OriginalParamPtr
2406       = OriginalParamType->getAs<PointerType>()) {
2407     if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2408       if (const PointerType *APtr = A->getAs<PointerType>()) {
2409         if (A->getPointeeType()->isRecordType()) {
2410           OriginalParamType = OriginalParamPtr->getPointeeType();
2411           DeducedA = DeducedAPtr->getPointeeType();
2412           A = APtr->getPointeeType();
2413         }
2414       }
2415     }
2416   }
2417 
2418   if (Context.hasSameUnqualifiedType(A, DeducedA))
2419     return false;
2420 
2421   if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2422       S.IsDerivedFrom(A, DeducedA))
2423     return false;
2424 
2425   return true;
2426 }
2427 
2428 /// \brief Finish template argument deduction for a function template,
2429 /// checking the deduced template arguments for completeness and forming
2430 /// the function template specialization.
2431 ///
2432 /// \param OriginalCallArgs If non-NULL, the original call arguments against
2433 /// which the deduced argument types should be compared.
2434 Sema::TemplateDeductionResult
2435 Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
2436                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2437                                       unsigned NumExplicitlySpecified,
2438                                       FunctionDecl *&Specialization,
2439                                       TemplateDeductionInfo &Info,
2440         SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs) {
2441   TemplateParameterList *TemplateParams
2442     = FunctionTemplate->getTemplateParameters();
2443 
2444   // Template argument deduction for function templates in a SFINAE context.
2445   // Trap any errors that might occur.
2446   SFINAETrap Trap(*this);
2447 
2448   // Enter a new template instantiation context while we instantiate the
2449   // actual function declaration.
2450   InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
2451                              FunctionTemplate, Deduced.data(), Deduced.size(),
2452               ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2453                              Info);
2454   if (Inst)
2455     return TDK_InstantiationDepth;
2456 
2457   ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2458 
2459   // C++ [temp.deduct.type]p2:
2460   //   [...] or if any template argument remains neither deduced nor
2461   //   explicitly specified, template argument deduction fails.
2462   SmallVector<TemplateArgument, 4> Builder;
2463   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2464     NamedDecl *Param = TemplateParams->getParam(I);
2465 
2466     if (!Deduced[I].isNull()) {
2467       if (I < NumExplicitlySpecified) {
2468         // We have already fully type-checked and converted this
2469         // argument, because it was explicitly-specified. Just record the
2470         // presence of this argument.
2471         Builder.push_back(Deduced[I]);
2472         continue;
2473       }
2474 
2475       // We have deduced this argument, so it still needs to be
2476       // checked and converted.
2477 
2478       // First, for a non-type template parameter type that is
2479       // initialized by a declaration, we need the type of the
2480       // corresponding non-type template parameter.
2481       QualType NTTPType;
2482       if (NonTypeTemplateParmDecl *NTTP
2483                                 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2484         NTTPType = NTTP->getType();
2485         if (NTTPType->isDependentType()) {
2486           TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2487                                             Builder.data(), Builder.size());
2488           NTTPType = SubstType(NTTPType,
2489                                MultiLevelTemplateArgumentList(TemplateArgs),
2490                                NTTP->getLocation(),
2491                                NTTP->getDeclName());
2492           if (NTTPType.isNull()) {
2493             Info.Param = makeTemplateParameter(Param);
2494             // FIXME: These template arguments are temporary. Free them!
2495             Info.reset(TemplateArgumentList::CreateCopy(Context,
2496                                                         Builder.data(),
2497                                                         Builder.size()));
2498             return TDK_SubstitutionFailure;
2499           }
2500         }
2501       }
2502 
2503       if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2504                                          FunctionTemplate, NTTPType, 0, Info,
2505                                          true, Builder)) {
2506         Info.Param = makeTemplateParameter(Param);
2507         // FIXME: These template arguments are temporary. Free them!
2508         Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2509                                                     Builder.size()));
2510         return TDK_SubstitutionFailure;
2511       }
2512 
2513       continue;
2514     }
2515 
2516     // C++0x [temp.arg.explicit]p3:
2517     //    A trailing template parameter pack (14.5.3) not otherwise deduced will
2518     //    be deduced to an empty sequence of template arguments.
2519     // FIXME: Where did the word "trailing" come from?
2520     if (Param->isTemplateParameterPack()) {
2521       // We may have had explicitly-specified template arguments for this
2522       // template parameter pack. If so, our empty deduction extends the
2523       // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2524       const TemplateArgument *ExplicitArgs;
2525       unsigned NumExplicitArgs;
2526       if (CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
2527                                                              &NumExplicitArgs)
2528           == Param)
2529         Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
2530       else
2531         Builder.push_back(TemplateArgument(0, 0));
2532 
2533       continue;
2534     }
2535 
2536     // Substitute into the default template argument, if available.
2537     TemplateArgumentLoc DefArg
2538       = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2539                                               FunctionTemplate->getLocation(),
2540                                   FunctionTemplate->getSourceRange().getEnd(),
2541                                                 Param,
2542                                                 Builder);
2543 
2544     // If there was no default argument, deduction is incomplete.
2545     if (DefArg.getArgument().isNull()) {
2546       Info.Param = makeTemplateParameter(
2547                          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2548       return TDK_Incomplete;
2549     }
2550 
2551     // Check whether we can actually use the default argument.
2552     if (CheckTemplateArgument(Param, DefArg,
2553                               FunctionTemplate,
2554                               FunctionTemplate->getLocation(),
2555                               FunctionTemplate->getSourceRange().getEnd(),
2556                               0, Builder,
2557                               CTAK_Specified)) {
2558       Info.Param = makeTemplateParameter(
2559                          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2560       // FIXME: These template arguments are temporary. Free them!
2561       Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2562                                                   Builder.size()));
2563       return TDK_SubstitutionFailure;
2564     }
2565 
2566     // If we get here, we successfully used the default template argument.
2567   }
2568 
2569   // Form the template argument list from the deduced template arguments.
2570   TemplateArgumentList *DeducedArgumentList
2571     = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
2572   Info.reset(DeducedArgumentList);
2573 
2574   // Substitute the deduced template arguments into the function template
2575   // declaration to produce the function template specialization.
2576   DeclContext *Owner = FunctionTemplate->getDeclContext();
2577   if (FunctionTemplate->getFriendObjectKind())
2578     Owner = FunctionTemplate->getLexicalDeclContext();
2579   Specialization = cast_or_null<FunctionDecl>(
2580                       SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
2581                          MultiLevelTemplateArgumentList(*DeducedArgumentList)));
2582   if (!Specialization)
2583     return TDK_SubstitutionFailure;
2584 
2585   assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2586          FunctionTemplate->getCanonicalDecl());
2587 
2588   // If the template argument list is owned by the function template
2589   // specialization, release it.
2590   if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2591       !Trap.hasErrorOccurred())
2592     Info.take();
2593 
2594   if (OriginalCallArgs) {
2595     // C++ [temp.deduct.call]p4:
2596     //   In general, the deduction process attempts to find template argument
2597     //   values that will make the deduced A identical to A (after the type A
2598     //   is transformed as described above). [...]
2599     for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2600       OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
2601       unsigned ParamIdx = OriginalArg.ArgIdx;
2602 
2603       if (ParamIdx >= Specialization->getNumParams())
2604         continue;
2605 
2606       QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
2607       if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA))
2608         return Sema::TDK_SubstitutionFailure;
2609     }
2610   }
2611 
2612   // There may have been an error that did not prevent us from constructing a
2613   // declaration. Mark the declaration invalid and return with a substitution
2614   // failure.
2615   if (Trap.hasErrorOccurred()) {
2616     Specialization->setInvalidDecl(true);
2617     return TDK_SubstitutionFailure;
2618   }
2619 
2620   // If we suppressed any diagnostics while performing template argument
2621   // deduction, and if we haven't already instantiated this declaration,
2622   // keep track of these diagnostics. They'll be emitted if this specialization
2623   // is actually used.
2624   if (Info.diag_begin() != Info.diag_end()) {
2625     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
2626       Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2627     if (Pos == SuppressedDiagnostics.end())
2628         SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2629           .append(Info.diag_begin(), Info.diag_end());
2630   }
2631 
2632   return TDK_Success;
2633 }
2634 
2635 /// Gets the type of a function for template-argument-deducton
2636 /// purposes when it's considered as part of an overload set.
2637 static QualType GetTypeOfFunction(ASTContext &Context,
2638                                   const OverloadExpr::FindResult &R,
2639                                   FunctionDecl *Fn) {
2640   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
2641     if (Method->isInstance()) {
2642       // An instance method that's referenced in a form that doesn't
2643       // look like a member pointer is just invalid.
2644       if (!R.HasFormOfMemberPointer) return QualType();
2645 
2646       return Context.getMemberPointerType(Fn->getType(),
2647                Context.getTypeDeclType(Method->getParent()).getTypePtr());
2648     }
2649 
2650   if (!R.IsAddressOfOperand) return Fn->getType();
2651   return Context.getPointerType(Fn->getType());
2652 }
2653 
2654 /// Apply the deduction rules for overload sets.
2655 ///
2656 /// \return the null type if this argument should be treated as an
2657 /// undeduced context
2658 static QualType
2659 ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
2660                             Expr *Arg, QualType ParamType,
2661                             bool ParamWasReference) {
2662 
2663   OverloadExpr::FindResult R = OverloadExpr::find(Arg);
2664 
2665   OverloadExpr *Ovl = R.Expression;
2666 
2667   // C++0x [temp.deduct.call]p4
2668   unsigned TDF = 0;
2669   if (ParamWasReference)
2670     TDF |= TDF_ParamWithReferenceType;
2671   if (R.IsAddressOfOperand)
2672     TDF |= TDF_IgnoreQualifiers;
2673 
2674   // If there were explicit template arguments, we can only find
2675   // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2676   // unambiguously name a full specialization.
2677   if (Ovl->hasExplicitTemplateArgs()) {
2678     // But we can still look for an explicit specialization.
2679     if (FunctionDecl *ExplicitSpec
2680           = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
2681       return GetTypeOfFunction(S.Context, R, ExplicitSpec);
2682     return QualType();
2683   }
2684 
2685   // C++0x [temp.deduct.call]p6:
2686   //   When P is a function type, pointer to function type, or pointer
2687   //   to member function type:
2688 
2689   if (!ParamType->isFunctionType() &&
2690       !ParamType->isFunctionPointerType() &&
2691       !ParamType->isMemberFunctionPointerType())
2692     return QualType();
2693 
2694   QualType Match;
2695   for (UnresolvedSetIterator I = Ovl->decls_begin(),
2696          E = Ovl->decls_end(); I != E; ++I) {
2697     NamedDecl *D = (*I)->getUnderlyingDecl();
2698 
2699     //   - If the argument is an overload set containing one or more
2700     //     function templates, the parameter is treated as a
2701     //     non-deduced context.
2702     if (isa<FunctionTemplateDecl>(D))
2703       return QualType();
2704 
2705     FunctionDecl *Fn = cast<FunctionDecl>(D);
2706     QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2707     if (ArgType.isNull()) continue;
2708 
2709     // Function-to-pointer conversion.
2710     if (!ParamWasReference && ParamType->isPointerType() &&
2711         ArgType->isFunctionType())
2712       ArgType = S.Context.getPointerType(ArgType);
2713 
2714     //   - If the argument is an overload set (not containing function
2715     //     templates), trial argument deduction is attempted using each
2716     //     of the members of the set. If deduction succeeds for only one
2717     //     of the overload set members, that member is used as the
2718     //     argument value for the deduction. If deduction succeeds for
2719     //     more than one member of the overload set the parameter is
2720     //     treated as a non-deduced context.
2721 
2722     // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2723     //   Type deduction is done independently for each P/A pair, and
2724     //   the deduced template argument values are then combined.
2725     // So we do not reject deductions which were made elsewhere.
2726     SmallVector<DeducedTemplateArgument, 8>
2727       Deduced(TemplateParams->size());
2728     TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
2729     Sema::TemplateDeductionResult Result
2730       = DeduceTemplateArguments(S, TemplateParams,
2731                                 ParamType, ArgType,
2732                                 Info, Deduced, TDF);
2733     if (Result) continue;
2734     if (!Match.isNull()) return QualType();
2735     Match = ArgType;
2736   }
2737 
2738   return Match;
2739 }
2740 
2741 /// \brief Perform the adjustments to the parameter and argument types
2742 /// described in C++ [temp.deduct.call].
2743 ///
2744 /// \returns true if the caller should not attempt to perform any template
2745 /// argument deduction based on this P/A pair.
2746 static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2747                                           TemplateParameterList *TemplateParams,
2748                                                       QualType &ParamType,
2749                                                       QualType &ArgType,
2750                                                       Expr *Arg,
2751                                                       unsigned &TDF) {
2752   // C++0x [temp.deduct.call]p3:
2753   //   If P is a cv-qualified type, the top level cv-qualifiers of P's type
2754   //   are ignored for type deduction.
2755   if (ParamType.hasQualifiers())
2756     ParamType = ParamType.getUnqualifiedType();
2757   const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2758   if (ParamRefType) {
2759     QualType PointeeType = ParamRefType->getPointeeType();
2760 
2761     // If the argument has incomplete array type, try to complete it's type.
2762     if (ArgType->isIncompleteArrayType() &&
2763         !S.RequireCompleteExprType(Arg, S.PDiag(),
2764                                    std::make_pair(SourceLocation(), S.PDiag())))
2765       ArgType = Arg->getType();
2766 
2767     //   [C++0x] If P is an rvalue reference to a cv-unqualified
2768     //   template parameter and the argument is an lvalue, the type
2769     //   "lvalue reference to A" is used in place of A for type
2770     //   deduction.
2771     if (isa<RValueReferenceType>(ParamType)) {
2772       if (!PointeeType.getQualifiers() &&
2773           isa<TemplateTypeParmType>(PointeeType) &&
2774           Arg->Classify(S.Context).isLValue() &&
2775           Arg->getType() != S.Context.OverloadTy &&
2776           Arg->getType() != S.Context.BoundMemberTy)
2777         ArgType = S.Context.getLValueReferenceType(ArgType);
2778     }
2779 
2780     //   [...] If P is a reference type, the type referred to by P is used
2781     //   for type deduction.
2782     ParamType = PointeeType;
2783   }
2784 
2785   // Overload sets usually make this parameter an undeduced
2786   // context, but there are sometimes special circumstances.
2787   if (ArgType == S.Context.OverloadTy) {
2788     ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2789                                           Arg, ParamType,
2790                                           ParamRefType != 0);
2791     if (ArgType.isNull())
2792       return true;
2793   }
2794 
2795   if (ParamRefType) {
2796     // C++0x [temp.deduct.call]p3:
2797     //   [...] If P is of the form T&&, where T is a template parameter, and
2798     //   the argument is an lvalue, the type A& is used in place of A for
2799     //   type deduction.
2800     if (ParamRefType->isRValueReferenceType() &&
2801         ParamRefType->getAs<TemplateTypeParmType>() &&
2802         Arg->isLValue())
2803       ArgType = S.Context.getLValueReferenceType(ArgType);
2804   } else {
2805     // C++ [temp.deduct.call]p2:
2806     //   If P is not a reference type:
2807     //   - If A is an array type, the pointer type produced by the
2808     //     array-to-pointer standard conversion (4.2) is used in place of
2809     //     A for type deduction; otherwise,
2810     if (ArgType->isArrayType())
2811       ArgType = S.Context.getArrayDecayedType(ArgType);
2812     //   - If A is a function type, the pointer type produced by the
2813     //     function-to-pointer standard conversion (4.3) is used in place
2814     //     of A for type deduction; otherwise,
2815     else if (ArgType->isFunctionType())
2816       ArgType = S.Context.getPointerType(ArgType);
2817     else {
2818       // - If A is a cv-qualified type, the top level cv-qualifiers of A's
2819       //   type are ignored for type deduction.
2820       ArgType = ArgType.getUnqualifiedType();
2821     }
2822   }
2823 
2824   // C++0x [temp.deduct.call]p4:
2825   //   In general, the deduction process attempts to find template argument
2826   //   values that will make the deduced A identical to A (after the type A
2827   //   is transformed as described above). [...]
2828   TDF = TDF_SkipNonDependent;
2829 
2830   //     - If the original P is a reference type, the deduced A (i.e., the
2831   //       type referred to by the reference) can be more cv-qualified than
2832   //       the transformed A.
2833   if (ParamRefType)
2834     TDF |= TDF_ParamWithReferenceType;
2835   //     - The transformed A can be another pointer or pointer to member
2836   //       type that can be converted to the deduced A via a qualification
2837   //       conversion (4.4).
2838   if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2839       ArgType->isObjCObjectPointerType())
2840     TDF |= TDF_IgnoreQualifiers;
2841   //     - If P is a class and P has the form simple-template-id, then the
2842   //       transformed A can be a derived class of the deduced A. Likewise,
2843   //       if P is a pointer to a class of the form simple-template-id, the
2844   //       transformed A can be a pointer to a derived class pointed to by
2845   //       the deduced A.
2846   if (isSimpleTemplateIdType(ParamType) ||
2847       (isa<PointerType>(ParamType) &&
2848        isSimpleTemplateIdType(
2849                               ParamType->getAs<PointerType>()->getPointeeType())))
2850     TDF |= TDF_DerivedClass;
2851 
2852   return false;
2853 }
2854 
2855 static bool hasDeducibleTemplateParameters(Sema &S,
2856                                            FunctionTemplateDecl *FunctionTemplate,
2857                                            QualType T);
2858 
2859 /// \brief Perform template argument deduction from a function call
2860 /// (C++ [temp.deduct.call]).
2861 ///
2862 /// \param FunctionTemplate the function template for which we are performing
2863 /// template argument deduction.
2864 ///
2865 /// \param ExplicitTemplateArguments the explicit template arguments provided
2866 /// for this call.
2867 ///
2868 /// \param Args the function call arguments
2869 ///
2870 /// \param NumArgs the number of arguments in Args
2871 ///
2872 /// \param Name the name of the function being called. This is only significant
2873 /// when the function template is a conversion function template, in which
2874 /// case this routine will also perform template argument deduction based on
2875 /// the function to which
2876 ///
2877 /// \param Specialization if template argument deduction was successful,
2878 /// this will be set to the function template specialization produced by
2879 /// template argument deduction.
2880 ///
2881 /// \param Info the argument will be updated to provide additional information
2882 /// about template argument deduction.
2883 ///
2884 /// \returns the result of template argument deduction.
2885 Sema::TemplateDeductionResult
2886 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2887                               TemplateArgumentListInfo *ExplicitTemplateArgs,
2888                               Expr **Args, unsigned NumArgs,
2889                               FunctionDecl *&Specialization,
2890                               TemplateDeductionInfo &Info) {
2891   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2892 
2893   // C++ [temp.deduct.call]p1:
2894   //   Template argument deduction is done by comparing each function template
2895   //   parameter type (call it P) with the type of the corresponding argument
2896   //   of the call (call it A) as described below.
2897   unsigned CheckArgs = NumArgs;
2898   if (NumArgs < Function->getMinRequiredArguments())
2899     return TDK_TooFewArguments;
2900   else if (NumArgs > Function->getNumParams()) {
2901     const FunctionProtoType *Proto
2902       = Function->getType()->getAs<FunctionProtoType>();
2903     if (Proto->isTemplateVariadic())
2904       /* Do nothing */;
2905     else if (Proto->isVariadic())
2906       CheckArgs = Function->getNumParams();
2907     else
2908       return TDK_TooManyArguments;
2909   }
2910 
2911   // The types of the parameters from which we will perform template argument
2912   // deduction.
2913   LocalInstantiationScope InstScope(*this);
2914   TemplateParameterList *TemplateParams
2915     = FunctionTemplate->getTemplateParameters();
2916   SmallVector<DeducedTemplateArgument, 4> Deduced;
2917   SmallVector<QualType, 4> ParamTypes;
2918   unsigned NumExplicitlySpecified = 0;
2919   if (ExplicitTemplateArgs) {
2920     TemplateDeductionResult Result =
2921       SubstituteExplicitTemplateArguments(FunctionTemplate,
2922                                           *ExplicitTemplateArgs,
2923                                           Deduced,
2924                                           ParamTypes,
2925                                           0,
2926                                           Info);
2927     if (Result)
2928       return Result;
2929 
2930     NumExplicitlySpecified = Deduced.size();
2931   } else {
2932     // Just fill in the parameter types from the function declaration.
2933     for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
2934       ParamTypes.push_back(Function->getParamDecl(I)->getType());
2935   }
2936 
2937   // Deduce template arguments from the function parameters.
2938   Deduced.resize(TemplateParams->size());
2939   unsigned ArgIdx = 0;
2940   SmallVector<OriginalCallArg, 4> OriginalCallArgs;
2941   for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2942        ParamIdx != NumParams; ++ParamIdx) {
2943     QualType OrigParamType = ParamTypes[ParamIdx];
2944     QualType ParamType = OrigParamType;
2945 
2946     const PackExpansionType *ParamExpansion
2947       = dyn_cast<PackExpansionType>(ParamType);
2948     if (!ParamExpansion) {
2949       // Simple case: matching a function parameter to a function argument.
2950       if (ArgIdx >= CheckArgs)
2951         break;
2952 
2953       Expr *Arg = Args[ArgIdx++];
2954       QualType ArgType = Arg->getType();
2955 
2956       unsigned TDF = 0;
2957       if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2958                                                     ParamType, ArgType, Arg,
2959                                                     TDF))
2960         continue;
2961 
2962       // Keep track of the argument type and corresponding parameter index,
2963       // so we can check for compatibility between the deduced A and A.
2964       if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
2965         OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
2966                                                    ArgType));
2967 
2968       if (TemplateDeductionResult Result
2969           = ::DeduceTemplateArguments(*this, TemplateParams,
2970                                       ParamType, ArgType, Info, Deduced,
2971                                       TDF))
2972         return Result;
2973 
2974       continue;
2975     }
2976 
2977     // C++0x [temp.deduct.call]p1:
2978     //   For a function parameter pack that occurs at the end of the
2979     //   parameter-declaration-list, the type A of each remaining argument of
2980     //   the call is compared with the type P of the declarator-id of the
2981     //   function parameter pack. Each comparison deduces template arguments
2982     //   for subsequent positions in the template parameter packs expanded by
2983     //   the function parameter pack. For a function parameter pack that does
2984     //   not occur at the end of the parameter-declaration-list, the type of
2985     //   the parameter pack is a non-deduced context.
2986     if (ParamIdx + 1 < NumParams)
2987       break;
2988 
2989     QualType ParamPattern = ParamExpansion->getPattern();
2990     SmallVector<unsigned, 2> PackIndices;
2991     {
2992       llvm::BitVector SawIndices(TemplateParams->size());
2993       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2994       collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
2995       for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
2996         unsigned Depth, Index;
2997         llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
2998         if (Depth == 0 && !SawIndices[Index]) {
2999           SawIndices[Index] = true;
3000           PackIndices.push_back(Index);
3001         }
3002       }
3003     }
3004     assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
3005 
3006     // Keep track of the deduced template arguments for each parameter pack
3007     // expanded by this pack expansion (the outer index) and for each
3008     // template argument (the inner SmallVectors).
3009     SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2>
3010       NewlyDeducedPacks(PackIndices.size());
3011     SmallVector<DeducedTemplateArgument, 2>
3012       SavedPacks(PackIndices.size());
3013     PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks,
3014                                  NewlyDeducedPacks);
3015     bool HasAnyArguments = false;
3016     for (; ArgIdx < NumArgs; ++ArgIdx) {
3017       HasAnyArguments = true;
3018 
3019       QualType OrigParamType = ParamPattern;
3020       ParamType = OrigParamType;
3021       Expr *Arg = Args[ArgIdx];
3022       QualType ArgType = Arg->getType();
3023 
3024       unsigned TDF = 0;
3025       if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3026                                                     ParamType, ArgType, Arg,
3027                                                     TDF)) {
3028         // We can't actually perform any deduction for this argument, so stop
3029         // deduction at this point.
3030         ++ArgIdx;
3031         break;
3032       }
3033 
3034       // Keep track of the argument type and corresponding argument index,
3035       // so we can check for compatibility between the deduced A and A.
3036       if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3037         OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3038                                                    ArgType));
3039 
3040       if (TemplateDeductionResult Result
3041           = ::DeduceTemplateArguments(*this, TemplateParams,
3042                                       ParamType, ArgType, Info, Deduced,
3043                                       TDF))
3044         return Result;
3045 
3046       // Capture the deduced template arguments for each parameter pack expanded
3047       // by this pack expansion, add them to the list of arguments we've deduced
3048       // for that pack, then clear out the deduced argument.
3049       for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
3050         DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
3051         if (!DeducedArg.isNull()) {
3052           NewlyDeducedPacks[I].push_back(DeducedArg);
3053           DeducedArg = DeducedTemplateArgument();
3054         }
3055       }
3056     }
3057 
3058     // Build argument packs for each of the parameter packs expanded by this
3059     // pack expansion.
3060     if (Sema::TemplateDeductionResult Result
3061           = FinishArgumentPackDeduction(*this, TemplateParams, HasAnyArguments,
3062                                         Deduced, PackIndices, SavedPacks,
3063                                         NewlyDeducedPacks, Info))
3064       return Result;
3065 
3066     // After we've matching against a parameter pack, we're done.
3067     break;
3068   }
3069 
3070   return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3071                                          NumExplicitlySpecified,
3072                                          Specialization, Info, &OriginalCallArgs);
3073 }
3074 
3075 /// \brief Deduce template arguments when taking the address of a function
3076 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3077 /// a template.
3078 ///
3079 /// \param FunctionTemplate the function template for which we are performing
3080 /// template argument deduction.
3081 ///
3082 /// \param ExplicitTemplateArguments the explicitly-specified template
3083 /// arguments.
3084 ///
3085 /// \param ArgFunctionType the function type that will be used as the
3086 /// "argument" type (A) when performing template argument deduction from the
3087 /// function template's function type. This type may be NULL, if there is no
3088 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
3089 ///
3090 /// \param Specialization if template argument deduction was successful,
3091 /// this will be set to the function template specialization produced by
3092 /// template argument deduction.
3093 ///
3094 /// \param Info the argument will be updated to provide additional information
3095 /// about template argument deduction.
3096 ///
3097 /// \returns the result of template argument deduction.
3098 Sema::TemplateDeductionResult
3099 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3100                               TemplateArgumentListInfo *ExplicitTemplateArgs,
3101                               QualType ArgFunctionType,
3102                               FunctionDecl *&Specialization,
3103                               TemplateDeductionInfo &Info) {
3104   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3105   TemplateParameterList *TemplateParams
3106     = FunctionTemplate->getTemplateParameters();
3107   QualType FunctionType = Function->getType();
3108 
3109   // Substitute any explicit template arguments.
3110   LocalInstantiationScope InstScope(*this);
3111   SmallVector<DeducedTemplateArgument, 4> Deduced;
3112   unsigned NumExplicitlySpecified = 0;
3113   SmallVector<QualType, 4> ParamTypes;
3114   if (ExplicitTemplateArgs) {
3115     if (TemplateDeductionResult Result
3116           = SubstituteExplicitTemplateArguments(FunctionTemplate,
3117                                                 *ExplicitTemplateArgs,
3118                                                 Deduced, ParamTypes,
3119                                                 &FunctionType, Info))
3120       return Result;
3121 
3122     NumExplicitlySpecified = Deduced.size();
3123   }
3124 
3125   // Template argument deduction for function templates in a SFINAE context.
3126   // Trap any errors that might occur.
3127   SFINAETrap Trap(*this);
3128 
3129   Deduced.resize(TemplateParams->size());
3130 
3131   if (!ArgFunctionType.isNull()) {
3132     // Deduce template arguments from the function type.
3133     if (TemplateDeductionResult Result
3134           = ::DeduceTemplateArguments(*this, TemplateParams,
3135                                       FunctionType, ArgFunctionType, Info,
3136                                       Deduced, TDF_TopLevelParameterTypeList))
3137       return Result;
3138   }
3139 
3140   if (TemplateDeductionResult Result
3141         = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3142                                           NumExplicitlySpecified,
3143                                           Specialization, Info))
3144     return Result;
3145 
3146   // If the requested function type does not match the actual type of the
3147   // specialization, template argument deduction fails.
3148   if (!ArgFunctionType.isNull() &&
3149       !Context.hasSameType(ArgFunctionType, Specialization->getType()))
3150     return TDK_NonDeducedMismatch;
3151 
3152   return TDK_Success;
3153 }
3154 
3155 /// \brief Deduce template arguments for a templated conversion
3156 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
3157 /// conversion function template specialization.
3158 Sema::TemplateDeductionResult
3159 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3160                               QualType ToType,
3161                               CXXConversionDecl *&Specialization,
3162                               TemplateDeductionInfo &Info) {
3163   CXXConversionDecl *Conv
3164     = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
3165   QualType FromType = Conv->getConversionType();
3166 
3167   // Canonicalize the types for deduction.
3168   QualType P = Context.getCanonicalType(FromType);
3169   QualType A = Context.getCanonicalType(ToType);
3170 
3171   // C++0x [temp.deduct.conv]p2:
3172   //   If P is a reference type, the type referred to by P is used for
3173   //   type deduction.
3174   if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3175     P = PRef->getPointeeType();
3176 
3177   // C++0x [temp.deduct.conv]p4:
3178   //   [...] If A is a reference type, the type referred to by A is used
3179   //   for type deduction.
3180   if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3181     A = ARef->getPointeeType().getUnqualifiedType();
3182   // C++ [temp.deduct.conv]p3:
3183   //
3184   //   If A is not a reference type:
3185   else {
3186     assert(!A->isReferenceType() && "Reference types were handled above");
3187 
3188     //   - If P is an array type, the pointer type produced by the
3189     //     array-to-pointer standard conversion (4.2) is used in place
3190     //     of P for type deduction; otherwise,
3191     if (P->isArrayType())
3192       P = Context.getArrayDecayedType(P);
3193     //   - If P is a function type, the pointer type produced by the
3194     //     function-to-pointer standard conversion (4.3) is used in
3195     //     place of P for type deduction; otherwise,
3196     else if (P->isFunctionType())
3197       P = Context.getPointerType(P);
3198     //   - If P is a cv-qualified type, the top level cv-qualifiers of
3199     //     P's type are ignored for type deduction.
3200     else
3201       P = P.getUnqualifiedType();
3202 
3203     // C++0x [temp.deduct.conv]p4:
3204     //   If A is a cv-qualified type, the top level cv-qualifiers of A's
3205     //   type are ignored for type deduction. If A is a reference type, the type
3206     //   referred to by A is used for type deduction.
3207     A = A.getUnqualifiedType();
3208   }
3209 
3210   // Template argument deduction for function templates in a SFINAE context.
3211   // Trap any errors that might occur.
3212   SFINAETrap Trap(*this);
3213 
3214   // C++ [temp.deduct.conv]p1:
3215   //   Template argument deduction is done by comparing the return
3216   //   type of the template conversion function (call it P) with the
3217   //   type that is required as the result of the conversion (call it
3218   //   A) as described in 14.8.2.4.
3219   TemplateParameterList *TemplateParams
3220     = FunctionTemplate->getTemplateParameters();
3221   SmallVector<DeducedTemplateArgument, 4> Deduced;
3222   Deduced.resize(TemplateParams->size());
3223 
3224   // C++0x [temp.deduct.conv]p4:
3225   //   In general, the deduction process attempts to find template
3226   //   argument values that will make the deduced A identical to
3227   //   A. However, there are two cases that allow a difference:
3228   unsigned TDF = 0;
3229   //     - If the original A is a reference type, A can be more
3230   //       cv-qualified than the deduced A (i.e., the type referred to
3231   //       by the reference)
3232   if (ToType->isReferenceType())
3233     TDF |= TDF_ParamWithReferenceType;
3234   //     - The deduced A can be another pointer or pointer to member
3235   //       type that can be converted to A via a qualification
3236   //       conversion.
3237   //
3238   // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3239   // both P and A are pointers or member pointers. In this case, we
3240   // just ignore cv-qualifiers completely).
3241   if ((P->isPointerType() && A->isPointerType()) ||
3242       (P->isMemberPointerType() && A->isMemberPointerType()))
3243     TDF |= TDF_IgnoreQualifiers;
3244   if (TemplateDeductionResult Result
3245         = ::DeduceTemplateArguments(*this, TemplateParams,
3246                                     P, A, Info, Deduced, TDF))
3247     return Result;
3248 
3249   // Finish template argument deduction.
3250   LocalInstantiationScope InstScope(*this);
3251   FunctionDecl *Spec = 0;
3252   TemplateDeductionResult Result
3253     = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
3254                                       Info);
3255   Specialization = cast_or_null<CXXConversionDecl>(Spec);
3256   return Result;
3257 }
3258 
3259 /// \brief Deduce template arguments for a function template when there is
3260 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3261 ///
3262 /// \param FunctionTemplate the function template for which we are performing
3263 /// template argument deduction.
3264 ///
3265 /// \param ExplicitTemplateArguments the explicitly-specified template
3266 /// arguments.
3267 ///
3268 /// \param Specialization if template argument deduction was successful,
3269 /// this will be set to the function template specialization produced by
3270 /// template argument deduction.
3271 ///
3272 /// \param Info the argument will be updated to provide additional information
3273 /// about template argument deduction.
3274 ///
3275 /// \returns the result of template argument deduction.
3276 Sema::TemplateDeductionResult
3277 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3278                               TemplateArgumentListInfo *ExplicitTemplateArgs,
3279                               FunctionDecl *&Specialization,
3280                               TemplateDeductionInfo &Info) {
3281   return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
3282                                  QualType(), Specialization, Info);
3283 }
3284 
3285 namespace {
3286   /// Substitute the 'auto' type specifier within a type for a given replacement
3287   /// type.
3288   class SubstituteAutoTransform :
3289     public TreeTransform<SubstituteAutoTransform> {
3290     QualType Replacement;
3291   public:
3292     SubstituteAutoTransform(Sema &SemaRef, QualType Replacement) :
3293       TreeTransform<SubstituteAutoTransform>(SemaRef), Replacement(Replacement) {
3294     }
3295     QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3296       // If we're building the type pattern to deduce against, don't wrap the
3297       // substituted type in an AutoType. Certain template deduction rules
3298       // apply only when a template type parameter appears directly (and not if
3299       // the parameter is found through desugaring). For instance:
3300       //   auto &&lref = lvalue;
3301       // must transform into "rvalue reference to T" not "rvalue reference to
3302       // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
3303       if (isa<TemplateTypeParmType>(Replacement)) {
3304         QualType Result = Replacement;
3305         TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
3306         NewTL.setNameLoc(TL.getNameLoc());
3307         return Result;
3308       } else {
3309         QualType Result = RebuildAutoType(Replacement);
3310         AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3311         NewTL.setNameLoc(TL.getNameLoc());
3312         return Result;
3313       }
3314     }
3315   };
3316 }
3317 
3318 /// \brief Deduce the type for an auto type-specifier (C++0x [dcl.spec.auto]p6)
3319 ///
3320 /// \param Type the type pattern using the auto type-specifier.
3321 ///
3322 /// \param Init the initializer for the variable whose type is to be deduced.
3323 ///
3324 /// \param Result if type deduction was successful, this will be set to the
3325 /// deduced type. This may still contain undeduced autos if the type is
3326 /// dependent. This will be set to null if deduction succeeded, but auto
3327 /// substitution failed; the appropriate diagnostic will already have been
3328 /// produced in that case.
3329 ///
3330 /// \returns true if deduction succeeded, false if it failed.
3331 bool
3332 Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *Init,
3333                      TypeSourceInfo *&Result) {
3334   if (Init->isTypeDependent()) {
3335     Result = Type;
3336     return true;
3337   }
3338 
3339   SourceLocation Loc = Init->getExprLoc();
3340 
3341   LocalInstantiationScope InstScope(*this);
3342 
3343   // Build template<class TemplParam> void Func(FuncParam);
3344   TemplateTypeParmDecl *TemplParam =
3345     TemplateTypeParmDecl::Create(Context, 0, SourceLocation(), Loc, 0, 0, 0,
3346                                  false, false);
3347   QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
3348   NamedDecl *TemplParamPtr = TemplParam;
3349   FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr,
3350                                                    Loc);
3351 
3352   TypeSourceInfo *FuncParamInfo =
3353     SubstituteAutoTransform(*this, TemplArg).TransformType(Type);
3354   assert(FuncParamInfo && "substituting template parameter for 'auto' failed");
3355   QualType FuncParam = FuncParamInfo->getType();
3356 
3357   // Deduce type of TemplParam in Func(Init)
3358   SmallVector<DeducedTemplateArgument, 1> Deduced;
3359   Deduced.resize(1);
3360   QualType InitType = Init->getType();
3361   unsigned TDF = 0;
3362   if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
3363                                                 FuncParam, InitType, Init,
3364                                                 TDF))
3365     return false;
3366 
3367   TemplateDeductionInfo Info(Context, Loc);
3368   if (::DeduceTemplateArguments(*this, &TemplateParams,
3369                                 FuncParam, InitType, Info, Deduced,
3370                                 TDF))
3371     return false;
3372 
3373   QualType DeducedType = Deduced[0].getAsType();
3374   if (DeducedType.isNull())
3375     return false;
3376 
3377   Result = SubstituteAutoTransform(*this, DeducedType).TransformType(Type);
3378 
3379   // Check that the deduced argument type is compatible with the original
3380   // argument type per C++ [temp.deduct.call]p4.
3381   if (Result &&
3382       CheckOriginalCallArgDeduction(*this,
3383                                     Sema::OriginalCallArg(FuncParam,0,InitType),
3384                                     Result->getType())) {
3385     Result = 0;
3386     return false;
3387   }
3388 
3389   return true;
3390 }
3391 
3392 static void
3393 MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3394                            bool OnlyDeduced,
3395                            unsigned Level,
3396                            SmallVectorImpl<bool> &Deduced);
3397 
3398 /// \brief If this is a non-static member function,
3399 static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
3400                                                 CXXMethodDecl *Method,
3401                                  SmallVectorImpl<QualType> &ArgTypes) {
3402   if (Method->isStatic())
3403     return;
3404 
3405   // C++ [over.match.funcs]p4:
3406   //
3407   //   For non-static member functions, the type of the implicit
3408   //   object parameter is
3409   //     - "lvalue reference to cv X" for functions declared without a
3410   //       ref-qualifier or with the & ref-qualifier
3411   //     - "rvalue reference to cv X" for functions declared with the
3412   //       && ref-qualifier
3413   //
3414   // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
3415   QualType ArgTy = Context.getTypeDeclType(Method->getParent());
3416   ArgTy = Context.getQualifiedType(ArgTy,
3417                         Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
3418   ArgTy = Context.getLValueReferenceType(ArgTy);
3419   ArgTypes.push_back(ArgTy);
3420 }
3421 
3422 /// \brief Determine whether the function template \p FT1 is at least as
3423 /// specialized as \p FT2.
3424 static bool isAtLeastAsSpecializedAs(Sema &S,
3425                                      SourceLocation Loc,
3426                                      FunctionTemplateDecl *FT1,
3427                                      FunctionTemplateDecl *FT2,
3428                                      TemplatePartialOrderingContext TPOC,
3429                                      unsigned NumCallArguments,
3430     SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
3431   FunctionDecl *FD1 = FT1->getTemplatedDecl();
3432   FunctionDecl *FD2 = FT2->getTemplatedDecl();
3433   const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
3434   const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
3435 
3436   assert(Proto1 && Proto2 && "Function templates must have prototypes");
3437   TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
3438   SmallVector<DeducedTemplateArgument, 4> Deduced;
3439   Deduced.resize(TemplateParams->size());
3440 
3441   // C++0x [temp.deduct.partial]p3:
3442   //   The types used to determine the ordering depend on the context in which
3443   //   the partial ordering is done:
3444   TemplateDeductionInfo Info(S.Context, Loc);
3445   CXXMethodDecl *Method1 = 0;
3446   CXXMethodDecl *Method2 = 0;
3447   bool IsNonStatic2 = false;
3448   bool IsNonStatic1 = false;
3449   unsigned Skip2 = 0;
3450   switch (TPOC) {
3451   case TPOC_Call: {
3452     //   - In the context of a function call, the function parameter types are
3453     //     used.
3454     Method1 = dyn_cast<CXXMethodDecl>(FD1);
3455     Method2 = dyn_cast<CXXMethodDecl>(FD2);
3456     IsNonStatic1 = Method1 && !Method1->isStatic();
3457     IsNonStatic2 = Method2 && !Method2->isStatic();
3458 
3459     // C++0x [temp.func.order]p3:
3460     //   [...] If only one of the function templates is a non-static
3461     //   member, that function template is considered to have a new
3462     //   first parameter inserted in its function parameter list. The
3463     //   new parameter is of type "reference to cv A," where cv are
3464     //   the cv-qualifiers of the function template (if any) and A is
3465     //   the class of which the function template is a member.
3466     //
3467     // C++98/03 doesn't have this provision, so instead we drop the
3468     // first argument of the free function or static member, which
3469     // seems to match existing practice.
3470     SmallVector<QualType, 4> Args1;
3471     unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
3472       IsNonStatic2 && !IsNonStatic1;
3473     if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
3474       MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
3475     Args1.insert(Args1.end(),
3476                  Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
3477 
3478     SmallVector<QualType, 4> Args2;
3479     Skip2 = !S.getLangOptions().CPlusPlus0x &&
3480       IsNonStatic1 && !IsNonStatic2;
3481     if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3482       MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
3483     Args2.insert(Args2.end(),
3484                  Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
3485 
3486     // C++ [temp.func.order]p5:
3487     //   The presence of unused ellipsis and default arguments has no effect on
3488     //   the partial ordering of function templates.
3489     if (Args1.size() > NumCallArguments)
3490       Args1.resize(NumCallArguments);
3491     if (Args2.size() > NumCallArguments)
3492       Args2.resize(NumCallArguments);
3493     if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
3494                                 Args1.data(), Args1.size(), Info, Deduced,
3495                                 TDF_None, /*PartialOrdering=*/true,
3496                                 RefParamComparisons))
3497         return false;
3498 
3499     break;
3500   }
3501 
3502   case TPOC_Conversion:
3503     //   - In the context of a call to a conversion operator, the return types
3504     //     of the conversion function templates are used.
3505     if (DeduceTemplateArguments(S, TemplateParams, Proto2->getResultType(),
3506                                 Proto1->getResultType(), Info, Deduced,
3507                                 TDF_None, /*PartialOrdering=*/true,
3508                                 RefParamComparisons))
3509       return false;
3510     break;
3511 
3512   case TPOC_Other:
3513     //   - In other contexts (14.6.6.2) the function template's function type
3514     //     is used.
3515     if (DeduceTemplateArguments(S, TemplateParams, FD2->getType(),
3516                                 FD1->getType(), Info, Deduced, TDF_None,
3517                                 /*PartialOrdering=*/true, RefParamComparisons))
3518       return false;
3519     break;
3520   }
3521 
3522   // C++0x [temp.deduct.partial]p11:
3523   //   In most cases, all template parameters must have values in order for
3524   //   deduction to succeed, but for partial ordering purposes a template
3525   //   parameter may remain without a value provided it is not used in the
3526   //   types being used for partial ordering. [ Note: a template parameter used
3527   //   in a non-deduced context is considered used. -end note]
3528   unsigned ArgIdx = 0, NumArgs = Deduced.size();
3529   for (; ArgIdx != NumArgs; ++ArgIdx)
3530     if (Deduced[ArgIdx].isNull())
3531       break;
3532 
3533   if (ArgIdx == NumArgs) {
3534     // All template arguments were deduced. FT1 is at least as specialized
3535     // as FT2.
3536     return true;
3537   }
3538 
3539   // Figure out which template parameters were used.
3540   SmallVector<bool, 4> UsedParameters;
3541   UsedParameters.resize(TemplateParams->size());
3542   switch (TPOC) {
3543   case TPOC_Call: {
3544     unsigned NumParams = std::min(NumCallArguments,
3545                                   std::min(Proto1->getNumArgs(),
3546                                            Proto2->getNumArgs()));
3547     if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3548       ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3549                                    TemplateParams->getDepth(), UsedParameters);
3550     for (unsigned I = Skip2; I < NumParams; ++I)
3551       ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3552                                    TemplateParams->getDepth(),
3553                                    UsedParameters);
3554     break;
3555   }
3556 
3557   case TPOC_Conversion:
3558     ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3559                                  TemplateParams->getDepth(),
3560                                  UsedParameters);
3561     break;
3562 
3563   case TPOC_Other:
3564     ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3565                                  TemplateParams->getDepth(),
3566                                  UsedParameters);
3567     break;
3568   }
3569 
3570   for (; ArgIdx != NumArgs; ++ArgIdx)
3571     // If this argument had no value deduced but was used in one of the types
3572     // used for partial ordering, then deduction fails.
3573     if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3574       return false;
3575 
3576   return true;
3577 }
3578 
3579 /// \brief Determine whether this a function template whose parameter-type-list
3580 /// ends with a function parameter pack.
3581 static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
3582   FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3583   unsigned NumParams = Function->getNumParams();
3584   if (NumParams == 0)
3585     return false;
3586 
3587   ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
3588   if (!Last->isParameterPack())
3589     return false;
3590 
3591   // Make sure that no previous parameter is a parameter pack.
3592   while (--NumParams > 0) {
3593     if (Function->getParamDecl(NumParams - 1)->isParameterPack())
3594       return false;
3595   }
3596 
3597   return true;
3598 }
3599 
3600 /// \brief Returns the more specialized function template according
3601 /// to the rules of function template partial ordering (C++ [temp.func.order]).
3602 ///
3603 /// \param FT1 the first function template
3604 ///
3605 /// \param FT2 the second function template
3606 ///
3607 /// \param TPOC the context in which we are performing partial ordering of
3608 /// function templates.
3609 ///
3610 /// \param NumCallArguments The number of arguments in a call, used only
3611 /// when \c TPOC is \c TPOC_Call.
3612 ///
3613 /// \returns the more specialized function template. If neither
3614 /// template is more specialized, returns NULL.
3615 FunctionTemplateDecl *
3616 Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3617                                  FunctionTemplateDecl *FT2,
3618                                  SourceLocation Loc,
3619                                  TemplatePartialOrderingContext TPOC,
3620                                  unsigned NumCallArguments) {
3621   SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons;
3622   bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
3623                                           NumCallArguments, 0);
3624   bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
3625                                           NumCallArguments,
3626                                           &RefParamComparisons);
3627 
3628   if (Better1 != Better2) // We have a clear winner
3629     return Better1? FT1 : FT2;
3630 
3631   if (!Better1 && !Better2) // Neither is better than the other
3632     return 0;
3633 
3634   // C++0x [temp.deduct.partial]p10:
3635   //   If for each type being considered a given template is at least as
3636   //   specialized for all types and more specialized for some set of types and
3637   //   the other template is not more specialized for any types or is not at
3638   //   least as specialized for any types, then the given template is more
3639   //   specialized than the other template. Otherwise, neither template is more
3640   //   specialized than the other.
3641   Better1 = false;
3642   Better2 = false;
3643   for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) {
3644     // C++0x [temp.deduct.partial]p9:
3645     //   If, for a given type, deduction succeeds in both directions (i.e., the
3646     //   types are identical after the transformations above) and both P and A
3647     //   were reference types (before being replaced with the type referred to
3648     //   above):
3649 
3650     //     -- if the type from the argument template was an lvalue reference
3651     //        and the type from the parameter template was not, the argument
3652     //        type is considered to be more specialized than the other;
3653     //        otherwise,
3654     if (!RefParamComparisons[I].ArgIsRvalueRef &&
3655         RefParamComparisons[I].ParamIsRvalueRef) {
3656       Better2 = true;
3657       if (Better1)
3658         return 0;
3659       continue;
3660     } else if (!RefParamComparisons[I].ParamIsRvalueRef &&
3661                RefParamComparisons[I].ArgIsRvalueRef) {
3662       Better1 = true;
3663       if (Better2)
3664         return 0;
3665       continue;
3666     }
3667 
3668     //     -- if the type from the argument template is more cv-qualified than
3669     //        the type from the parameter template (as described above), the
3670     //        argument type is considered to be more specialized than the
3671     //        other; otherwise,
3672     switch (RefParamComparisons[I].Qualifiers) {
3673     case NeitherMoreQualified:
3674       break;
3675 
3676     case ParamMoreQualified:
3677       Better1 = true;
3678       if (Better2)
3679         return 0;
3680       continue;
3681 
3682     case ArgMoreQualified:
3683       Better2 = true;
3684       if (Better1)
3685         return 0;
3686       continue;
3687     }
3688 
3689     //     -- neither type is more specialized than the other.
3690   }
3691 
3692   assert(!(Better1 && Better2) && "Should have broken out in the loop above");
3693   if (Better1)
3694     return FT1;
3695   else if (Better2)
3696     return FT2;
3697 
3698   // FIXME: This mimics what GCC implements, but doesn't match up with the
3699   // proposed resolution for core issue 692. This area needs to be sorted out,
3700   // but for now we attempt to maintain compatibility.
3701   bool Variadic1 = isVariadicFunctionTemplate(FT1);
3702   bool Variadic2 = isVariadicFunctionTemplate(FT2);
3703   if (Variadic1 != Variadic2)
3704     return Variadic1? FT2 : FT1;
3705 
3706   return 0;
3707 }
3708 
3709 /// \brief Determine if the two templates are equivalent.
3710 static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3711   if (T1 == T2)
3712     return true;
3713 
3714   if (!T1 || !T2)
3715     return false;
3716 
3717   return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3718 }
3719 
3720 /// \brief Retrieve the most specialized of the given function template
3721 /// specializations.
3722 ///
3723 /// \param SpecBegin the start iterator of the function template
3724 /// specializations that we will be comparing.
3725 ///
3726 /// \param SpecEnd the end iterator of the function template
3727 /// specializations, paired with \p SpecBegin.
3728 ///
3729 /// \param TPOC the partial ordering context to use to compare the function
3730 /// template specializations.
3731 ///
3732 /// \param NumCallArguments The number of arguments in a call, used only
3733 /// when \c TPOC is \c TPOC_Call.
3734 ///
3735 /// \param Loc the location where the ambiguity or no-specializations
3736 /// diagnostic should occur.
3737 ///
3738 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
3739 /// no matching candidates.
3740 ///
3741 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3742 /// occurs.
3743 ///
3744 /// \param CandidateDiag partial diagnostic used for each function template
3745 /// specialization that is a candidate in the ambiguous ordering. One parameter
3746 /// in this diagnostic should be unbound, which will correspond to the string
3747 /// describing the template arguments for the function template specialization.
3748 ///
3749 /// \param Index if non-NULL and the result of this function is non-nULL,
3750 /// receives the index corresponding to the resulting function template
3751 /// specialization.
3752 ///
3753 /// \returns the most specialized function template specialization, if
3754 /// found. Otherwise, returns SpecEnd.
3755 ///
3756 /// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3757 /// template argument deduction.
3758 UnresolvedSetIterator
3759 Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
3760                         UnresolvedSetIterator SpecEnd,
3761                          TemplatePartialOrderingContext TPOC,
3762                          unsigned NumCallArguments,
3763                          SourceLocation Loc,
3764                          const PartialDiagnostic &NoneDiag,
3765                          const PartialDiagnostic &AmbigDiag,
3766                          const PartialDiagnostic &CandidateDiag,
3767                          bool Complain) {
3768   if (SpecBegin == SpecEnd) {
3769     if (Complain)
3770       Diag(Loc, NoneDiag);
3771     return SpecEnd;
3772   }
3773 
3774   if (SpecBegin + 1 == SpecEnd)
3775     return SpecBegin;
3776 
3777   // Find the function template that is better than all of the templates it
3778   // has been compared to.
3779   UnresolvedSetIterator Best = SpecBegin;
3780   FunctionTemplateDecl *BestTemplate
3781     = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
3782   assert(BestTemplate && "Not a function template specialization?");
3783   for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3784     FunctionTemplateDecl *Challenger
3785       = cast<FunctionDecl>(*I)->getPrimaryTemplate();
3786     assert(Challenger && "Not a function template specialization?");
3787     if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
3788                                                   Loc, TPOC, NumCallArguments),
3789                        Challenger)) {
3790       Best = I;
3791       BestTemplate = Challenger;
3792     }
3793   }
3794 
3795   // Make sure that the "best" function template is more specialized than all
3796   // of the others.
3797   bool Ambiguous = false;
3798   for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3799     FunctionTemplateDecl *Challenger
3800       = cast<FunctionDecl>(*I)->getPrimaryTemplate();
3801     if (I != Best &&
3802         !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
3803                                                    Loc, TPOC, NumCallArguments),
3804                         BestTemplate)) {
3805       Ambiguous = true;
3806       break;
3807     }
3808   }
3809 
3810   if (!Ambiguous) {
3811     // We found an answer. Return it.
3812     return Best;
3813   }
3814 
3815   // Diagnose the ambiguity.
3816   if (Complain)
3817     Diag(Loc, AmbigDiag);
3818 
3819   if (Complain)
3820   // FIXME: Can we order the candidates in some sane way?
3821     for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3822       Diag((*I)->getLocation(), CandidateDiag)
3823         << getTemplateArgumentBindingsText(
3824           cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3825                     *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
3826 
3827   return SpecEnd;
3828 }
3829 
3830 /// \brief Returns the more specialized class template partial specialization
3831 /// according to the rules of partial ordering of class template partial
3832 /// specializations (C++ [temp.class.order]).
3833 ///
3834 /// \param PS1 the first class template partial specialization
3835 ///
3836 /// \param PS2 the second class template partial specialization
3837 ///
3838 /// \returns the more specialized class template partial specialization. If
3839 /// neither partial specialization is more specialized, returns NULL.
3840 ClassTemplatePartialSpecializationDecl *
3841 Sema::getMoreSpecializedPartialSpecialization(
3842                                   ClassTemplatePartialSpecializationDecl *PS1,
3843                                   ClassTemplatePartialSpecializationDecl *PS2,
3844                                               SourceLocation Loc) {
3845   // C++ [temp.class.order]p1:
3846   //   For two class template partial specializations, the first is at least as
3847   //   specialized as the second if, given the following rewrite to two
3848   //   function templates, the first function template is at least as
3849   //   specialized as the second according to the ordering rules for function
3850   //   templates (14.6.6.2):
3851   //     - the first function template has the same template parameters as the
3852   //       first partial specialization and has a single function parameter
3853   //       whose type is a class template specialization with the template
3854   //       arguments of the first partial specialization, and
3855   //     - the second function template has the same template parameters as the
3856   //       second partial specialization and has a single function parameter
3857   //       whose type is a class template specialization with the template
3858   //       arguments of the second partial specialization.
3859   //
3860   // Rather than synthesize function templates, we merely perform the
3861   // equivalent partial ordering by performing deduction directly on
3862   // the template arguments of the class template partial
3863   // specializations. This computation is slightly simpler than the
3864   // general problem of function template partial ordering, because
3865   // class template partial specializations are more constrained. We
3866   // know that every template parameter is deducible from the class
3867   // template partial specialization's template arguments, for
3868   // example.
3869   SmallVector<DeducedTemplateArgument, 4> Deduced;
3870   TemplateDeductionInfo Info(Context, Loc);
3871 
3872   QualType PT1 = PS1->getInjectedSpecializationType();
3873   QualType PT2 = PS2->getInjectedSpecializationType();
3874 
3875   // Determine whether PS1 is at least as specialized as PS2
3876   Deduced.resize(PS2->getTemplateParameters()->size());
3877   bool Better1 = !::DeduceTemplateArguments(*this, PS2->getTemplateParameters(),
3878                                             PT2, PT1, Info, Deduced, TDF_None,
3879                                             /*PartialOrdering=*/true,
3880                                             /*RefParamComparisons=*/0);
3881   if (Better1) {
3882     InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3883                                Deduced.data(), Deduced.size(), Info);
3884     Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3885                                                  PS1->getTemplateArgs(),
3886                                                  Deduced, Info);
3887   }
3888 
3889   // Determine whether PS2 is at least as specialized as PS1
3890   Deduced.clear();
3891   Deduced.resize(PS1->getTemplateParameters()->size());
3892   bool Better2 = !::DeduceTemplateArguments(*this, PS1->getTemplateParameters(),
3893                                             PT1, PT2, Info, Deduced, TDF_None,
3894                                             /*PartialOrdering=*/true,
3895                                             /*RefParamComparisons=*/0);
3896   if (Better2) {
3897     InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3898                                Deduced.data(), Deduced.size(), Info);
3899     Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3900                                                  PS2->getTemplateArgs(),
3901                                                  Deduced, Info);
3902   }
3903 
3904   if (Better1 == Better2)
3905     return 0;
3906 
3907   return Better1? PS1 : PS2;
3908 }
3909 
3910 static void
3911 MarkUsedTemplateParameters(Sema &SemaRef,
3912                            const TemplateArgument &TemplateArg,
3913                            bool OnlyDeduced,
3914                            unsigned Depth,
3915                            SmallVectorImpl<bool> &Used);
3916 
3917 /// \brief Mark the template parameters that are used by the given
3918 /// expression.
3919 static void
3920 MarkUsedTemplateParameters(Sema &SemaRef,
3921                            const Expr *E,
3922                            bool OnlyDeduced,
3923                            unsigned Depth,
3924                            SmallVectorImpl<bool> &Used) {
3925   // We can deduce from a pack expansion.
3926   if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3927     E = Expansion->getPattern();
3928 
3929   // Skip through any implicit casts we added while type-checking.
3930   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3931     E = ICE->getSubExpr();
3932 
3933   // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3934   // find other occurrences of template parameters.
3935   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3936   if (!DRE)
3937     return;
3938 
3939   const NonTypeTemplateParmDecl *NTTP
3940     = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3941   if (!NTTP)
3942     return;
3943 
3944   if (NTTP->getDepth() == Depth)
3945     Used[NTTP->getIndex()] = true;
3946 }
3947 
3948 /// \brief Mark the template parameters that are used by the given
3949 /// nested name specifier.
3950 static void
3951 MarkUsedTemplateParameters(Sema &SemaRef,
3952                            NestedNameSpecifier *NNS,
3953                            bool OnlyDeduced,
3954                            unsigned Depth,
3955                            SmallVectorImpl<bool> &Used) {
3956   if (!NNS)
3957     return;
3958 
3959   MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3960                              Used);
3961   MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
3962                              OnlyDeduced, Depth, Used);
3963 }
3964 
3965 /// \brief Mark the template parameters that are used by the given
3966 /// template name.
3967 static void
3968 MarkUsedTemplateParameters(Sema &SemaRef,
3969                            TemplateName Name,
3970                            bool OnlyDeduced,
3971                            unsigned Depth,
3972                            SmallVectorImpl<bool> &Used) {
3973   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3974     if (TemplateTemplateParmDecl *TTP
3975           = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3976       if (TTP->getDepth() == Depth)
3977         Used[TTP->getIndex()] = true;
3978     }
3979     return;
3980   }
3981 
3982   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3983     MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3984                                Depth, Used);
3985   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
3986     MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3987                                Depth, Used);
3988 }
3989 
3990 /// \brief Mark the template parameters that are used by the given
3991 /// type.
3992 static void
3993 MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3994                            bool OnlyDeduced,
3995                            unsigned Depth,
3996                            SmallVectorImpl<bool> &Used) {
3997   if (T.isNull())
3998     return;
3999 
4000   // Non-dependent types have nothing deducible
4001   if (!T->isDependentType())
4002     return;
4003 
4004   T = SemaRef.Context.getCanonicalType(T);
4005   switch (T->getTypeClass()) {
4006   case Type::Pointer:
4007     MarkUsedTemplateParameters(SemaRef,
4008                                cast<PointerType>(T)->getPointeeType(),
4009                                OnlyDeduced,
4010                                Depth,
4011                                Used);
4012     break;
4013 
4014   case Type::BlockPointer:
4015     MarkUsedTemplateParameters(SemaRef,
4016                                cast<BlockPointerType>(T)->getPointeeType(),
4017                                OnlyDeduced,
4018                                Depth,
4019                                Used);
4020     break;
4021 
4022   case Type::LValueReference:
4023   case Type::RValueReference:
4024     MarkUsedTemplateParameters(SemaRef,
4025                                cast<ReferenceType>(T)->getPointeeType(),
4026                                OnlyDeduced,
4027                                Depth,
4028                                Used);
4029     break;
4030 
4031   case Type::MemberPointer: {
4032     const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
4033     MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
4034                                Depth, Used);
4035     MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
4036                                OnlyDeduced, Depth, Used);
4037     break;
4038   }
4039 
4040   case Type::DependentSizedArray:
4041     MarkUsedTemplateParameters(SemaRef,
4042                                cast<DependentSizedArrayType>(T)->getSizeExpr(),
4043                                OnlyDeduced, Depth, Used);
4044     // Fall through to check the element type
4045 
4046   case Type::ConstantArray:
4047   case Type::IncompleteArray:
4048     MarkUsedTemplateParameters(SemaRef,
4049                                cast<ArrayType>(T)->getElementType(),
4050                                OnlyDeduced, Depth, Used);
4051     break;
4052 
4053   case Type::Vector:
4054   case Type::ExtVector:
4055     MarkUsedTemplateParameters(SemaRef,
4056                                cast<VectorType>(T)->getElementType(),
4057                                OnlyDeduced, Depth, Used);
4058     break;
4059 
4060   case Type::DependentSizedExtVector: {
4061     const DependentSizedExtVectorType *VecType
4062       = cast<DependentSizedExtVectorType>(T);
4063     MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
4064                                Depth, Used);
4065     MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
4066                                Depth, Used);
4067     break;
4068   }
4069 
4070   case Type::FunctionProto: {
4071     const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
4072     MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
4073                                Depth, Used);
4074     for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
4075       MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
4076                                  Depth, Used);
4077     break;
4078   }
4079 
4080   case Type::TemplateTypeParm: {
4081     const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4082     if (TTP->getDepth() == Depth)
4083       Used[TTP->getIndex()] = true;
4084     break;
4085   }
4086 
4087   case Type::SubstTemplateTypeParmPack: {
4088     const SubstTemplateTypeParmPackType *Subst
4089       = cast<SubstTemplateTypeParmPackType>(T);
4090     MarkUsedTemplateParameters(SemaRef,
4091                                QualType(Subst->getReplacedParameter(), 0),
4092                                OnlyDeduced, Depth, Used);
4093     MarkUsedTemplateParameters(SemaRef, Subst->getArgumentPack(),
4094                                OnlyDeduced, Depth, Used);
4095     break;
4096   }
4097 
4098   case Type::InjectedClassName:
4099     T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4100     // fall through
4101 
4102   case Type::TemplateSpecialization: {
4103     const TemplateSpecializationType *Spec
4104       = cast<TemplateSpecializationType>(T);
4105     MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
4106                                Depth, Used);
4107 
4108     // C++0x [temp.deduct.type]p9:
4109     //   If the template argument list of P contains a pack expansion that is not
4110     //   the last template argument, the entire template argument list is a
4111     //   non-deduced context.
4112     if (OnlyDeduced &&
4113         hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4114       break;
4115 
4116     for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
4117       MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
4118                                  Used);
4119     break;
4120   }
4121 
4122   case Type::Complex:
4123     if (!OnlyDeduced)
4124       MarkUsedTemplateParameters(SemaRef,
4125                                  cast<ComplexType>(T)->getElementType(),
4126                                  OnlyDeduced, Depth, Used);
4127     break;
4128 
4129   case Type::DependentName:
4130     if (!OnlyDeduced)
4131       MarkUsedTemplateParameters(SemaRef,
4132                                  cast<DependentNameType>(T)->getQualifier(),
4133                                  OnlyDeduced, Depth, Used);
4134     break;
4135 
4136   case Type::DependentTemplateSpecialization: {
4137     const DependentTemplateSpecializationType *Spec
4138       = cast<DependentTemplateSpecializationType>(T);
4139     if (!OnlyDeduced)
4140       MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
4141                                  OnlyDeduced, Depth, Used);
4142 
4143     // C++0x [temp.deduct.type]p9:
4144     //   If the template argument list of P contains a pack expansion that is not
4145     //   the last template argument, the entire template argument list is a
4146     //   non-deduced context.
4147     if (OnlyDeduced &&
4148         hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4149       break;
4150 
4151     for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
4152       MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
4153                                  Used);
4154     break;
4155   }
4156 
4157   case Type::TypeOf:
4158     if (!OnlyDeduced)
4159       MarkUsedTemplateParameters(SemaRef,
4160                                  cast<TypeOfType>(T)->getUnderlyingType(),
4161                                  OnlyDeduced, Depth, Used);
4162     break;
4163 
4164   case Type::TypeOfExpr:
4165     if (!OnlyDeduced)
4166       MarkUsedTemplateParameters(SemaRef,
4167                                  cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4168                                  OnlyDeduced, Depth, Used);
4169     break;
4170 
4171   case Type::Decltype:
4172     if (!OnlyDeduced)
4173       MarkUsedTemplateParameters(SemaRef,
4174                                  cast<DecltypeType>(T)->getUnderlyingExpr(),
4175                                  OnlyDeduced, Depth, Used);
4176     break;
4177 
4178   case Type::UnaryTransform:
4179     if (!OnlyDeduced)
4180       MarkUsedTemplateParameters(SemaRef,
4181                                cast<UnaryTransformType>(T)->getUnderlyingType(),
4182                                  OnlyDeduced, Depth, Used);
4183     break;
4184 
4185   case Type::PackExpansion:
4186     MarkUsedTemplateParameters(SemaRef,
4187                                cast<PackExpansionType>(T)->getPattern(),
4188                                OnlyDeduced, Depth, Used);
4189     break;
4190 
4191   case Type::Auto:
4192     MarkUsedTemplateParameters(SemaRef,
4193                                cast<AutoType>(T)->getDeducedType(),
4194                                OnlyDeduced, Depth, Used);
4195 
4196   // None of these types have any template parameters in them.
4197   case Type::Builtin:
4198   case Type::VariableArray:
4199   case Type::FunctionNoProto:
4200   case Type::Record:
4201   case Type::Enum:
4202   case Type::ObjCInterface:
4203   case Type::ObjCObject:
4204   case Type::ObjCObjectPointer:
4205   case Type::UnresolvedUsing:
4206 #define TYPE(Class, Base)
4207 #define ABSTRACT_TYPE(Class, Base)
4208 #define DEPENDENT_TYPE(Class, Base)
4209 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4210 #include "clang/AST/TypeNodes.def"
4211     break;
4212   }
4213 }
4214 
4215 /// \brief Mark the template parameters that are used by this
4216 /// template argument.
4217 static void
4218 MarkUsedTemplateParameters(Sema &SemaRef,
4219                            const TemplateArgument &TemplateArg,
4220                            bool OnlyDeduced,
4221                            unsigned Depth,
4222                            SmallVectorImpl<bool> &Used) {
4223   switch (TemplateArg.getKind()) {
4224   case TemplateArgument::Null:
4225   case TemplateArgument::Integral:
4226     case TemplateArgument::Declaration:
4227     break;
4228 
4229   case TemplateArgument::Type:
4230     MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
4231                                Depth, Used);
4232     break;
4233 
4234   case TemplateArgument::Template:
4235   case TemplateArgument::TemplateExpansion:
4236     MarkUsedTemplateParameters(SemaRef,
4237                                TemplateArg.getAsTemplateOrTemplatePattern(),
4238                                OnlyDeduced, Depth, Used);
4239     break;
4240 
4241   case TemplateArgument::Expression:
4242     MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
4243                                Depth, Used);
4244     break;
4245 
4246   case TemplateArgument::Pack:
4247     for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
4248                                       PEnd = TemplateArg.pack_end();
4249          P != PEnd; ++P)
4250       MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
4251     break;
4252   }
4253 }
4254 
4255 /// \brief Mark the template parameters can be deduced by the given
4256 /// template argument list.
4257 ///
4258 /// \param TemplateArgs the template argument list from which template
4259 /// parameters will be deduced.
4260 ///
4261 /// \param Deduced a bit vector whose elements will be set to \c true
4262 /// to indicate when the corresponding template parameter will be
4263 /// deduced.
4264 void
4265 Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
4266                                  bool OnlyDeduced, unsigned Depth,
4267                                  SmallVectorImpl<bool> &Used) {
4268   // C++0x [temp.deduct.type]p9:
4269   //   If the template argument list of P contains a pack expansion that is not
4270   //   the last template argument, the entire template argument list is a
4271   //   non-deduced context.
4272   if (OnlyDeduced &&
4273       hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
4274     return;
4275 
4276   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4277     ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
4278                                  Depth, Used);
4279 }
4280 
4281 /// \brief Marks all of the template parameters that will be deduced by a
4282 /// call to the given function template.
4283 void
4284 Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
4285                                     SmallVectorImpl<bool> &Deduced) {
4286   TemplateParameterList *TemplateParams
4287     = FunctionTemplate->getTemplateParameters();
4288   Deduced.clear();
4289   Deduced.resize(TemplateParams->size());
4290 
4291   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4292   for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
4293     ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
4294                                  true, TemplateParams->getDepth(), Deduced);
4295 }
4296 
4297 bool hasDeducibleTemplateParameters(Sema &S,
4298                                     FunctionTemplateDecl *FunctionTemplate,
4299                                     QualType T) {
4300   if (!T->isDependentType())
4301     return false;
4302 
4303   TemplateParameterList *TemplateParams
4304     = FunctionTemplate->getTemplateParameters();
4305   SmallVector<bool, 4> Deduced;
4306   Deduced.resize(TemplateParams->size());
4307   ::MarkUsedTemplateParameters(S, T, true, TemplateParams->getDepth(),
4308                                Deduced);
4309 
4310   for (unsigned I = 0, N = Deduced.size(); I != N; ++I)
4311     if (Deduced[I])
4312       return true;
4313 
4314   return false;
4315 }
4316