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