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