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