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