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       // Try to deduce template arguments from the template-id.
1425       Sema::TemplateDeductionResult Result
1426         = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
1427                                   Info, Deduced);
1428 
1429       if (Result && (TDF & TDF_DerivedClass)) {
1430         // C++ [temp.deduct.call]p3b3:
1431         //   If P is a class, and P has the form template-id, then A can be a
1432         //   derived class of the deduced A. Likewise, if P is a pointer to a
1433         //   class of the form template-id, A can be a pointer to a derived
1434         //   class pointed to by the deduced A.
1435         //
1436         // More importantly:
1437         //   These alternatives are considered only if type deduction would
1438         //   otherwise fail.
1439         if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
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           // Use data recursion to crawl through the list of base classes.
1447           // Visited contains the set of nodes we have already visited, while
1448           // ToVisit is our stack of records that we still need to visit.
1449           llvm::SmallPtrSet<const RecordType *, 8> Visited;
1450           SmallVector<const RecordType *, 8> ToVisit;
1451           ToVisit.push_back(RecordT);
1452           bool Successful = false;
1453           SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1454                                                               Deduced.end());
1455           while (!ToVisit.empty()) {
1456             // Retrieve the next class in the inheritance hierarchy.
1457             const RecordType *NextT = ToVisit.pop_back_val();
1458 
1459             // If we have already seen this type, skip it.
1460             if (!Visited.insert(NextT).second)
1461               continue;
1462 
1463             // If this is a base class, try to perform template argument
1464             // deduction from it.
1465             if (NextT != RecordT) {
1466               TemplateDeductionInfo BaseInfo(Info.getLocation());
1467               Sema::TemplateDeductionResult BaseResult
1468                 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
1469                                           QualType(NextT, 0), BaseInfo,
1470                                           Deduced);
1471 
1472               // If template argument deduction for this base was successful,
1473               // note that we had some success. Otherwise, ignore any deductions
1474               // from this base class.
1475               if (BaseResult == Sema::TDK_Success) {
1476                 Successful = true;
1477                 DeducedOrig.clear();
1478                 DeducedOrig.append(Deduced.begin(), Deduced.end());
1479                 Info.Param = BaseInfo.Param;
1480                 Info.FirstArg = BaseInfo.FirstArg;
1481                 Info.SecondArg = BaseInfo.SecondArg;
1482               }
1483               else
1484                 Deduced = DeducedOrig;
1485             }
1486 
1487             // Visit base classes
1488             CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1489             for (const auto &Base : Next->bases()) {
1490               assert(Base.getType()->isRecordType() &&
1491                      "Base class that isn't a record?");
1492               ToVisit.push_back(Base.getType()->getAs<RecordType>());
1493             }
1494           }
1495 
1496           if (Successful)
1497             return Sema::TDK_Success;
1498         }
1499 
1500       }
1501 
1502       return Result;
1503     }
1504 
1505     //     T type::*
1506     //     T T::*
1507     //     T (type::*)()
1508     //     type (T::*)()
1509     //     type (type::*)(T)
1510     //     type (T::*)(T)
1511     //     T (type::*)(T)
1512     //     T (T::*)()
1513     //     T (T::*)(T)
1514     case Type::MemberPointer: {
1515       const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1516       const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1517       if (!MemPtrArg)
1518         return Sema::TDK_NonDeducedMismatch;
1519 
1520       QualType ParamPointeeType = MemPtrParam->getPointeeType();
1521       if (ParamPointeeType->isFunctionType())
1522         S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1523                                  /*IsCtorOrDtor=*/false, Info.getLocation());
1524       QualType ArgPointeeType = MemPtrArg->getPointeeType();
1525       if (ArgPointeeType->isFunctionType())
1526         S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1527                                  /*IsCtorOrDtor=*/false, Info.getLocation());
1528 
1529       if (Sema::TemplateDeductionResult Result
1530             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1531                                                  ParamPointeeType,
1532                                                  ArgPointeeType,
1533                                                  Info, Deduced,
1534                                                  TDF & TDF_IgnoreQualifiers))
1535         return Result;
1536 
1537       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1538                                            QualType(MemPtrParam->getClass(), 0),
1539                                            QualType(MemPtrArg->getClass(), 0),
1540                                            Info, Deduced,
1541                                            TDF & TDF_IgnoreQualifiers);
1542     }
1543 
1544     //     (clang extension)
1545     //
1546     //     type(^)(T)
1547     //     T(^)()
1548     //     T(^)(T)
1549     case Type::BlockPointer: {
1550       const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1551       const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
1552 
1553       if (!BlockPtrArg)
1554         return Sema::TDK_NonDeducedMismatch;
1555 
1556       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1557                                                 BlockPtrParam->getPointeeType(),
1558                                                 BlockPtrArg->getPointeeType(),
1559                                                 Info, Deduced, 0);
1560     }
1561 
1562     //     (clang extension)
1563     //
1564     //     T __attribute__(((ext_vector_type(<integral constant>))))
1565     case Type::ExtVector: {
1566       const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1567       if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1568         // Make sure that the vectors have the same number of elements.
1569         if (VectorParam->getNumElements() != VectorArg->getNumElements())
1570           return Sema::TDK_NonDeducedMismatch;
1571 
1572         // Perform deduction on the element types.
1573         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1574                                                   VectorParam->getElementType(),
1575                                                   VectorArg->getElementType(),
1576                                                   Info, Deduced, TDF);
1577       }
1578 
1579       if (const DependentSizedExtVectorType *VectorArg
1580                                 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1581         // We can't check the number of elements, since the argument has a
1582         // dependent number of elements. This can only occur during partial
1583         // ordering.
1584 
1585         // Perform deduction on the element types.
1586         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1587                                                   VectorParam->getElementType(),
1588                                                   VectorArg->getElementType(),
1589                                                   Info, Deduced, TDF);
1590       }
1591 
1592       return Sema::TDK_NonDeducedMismatch;
1593     }
1594 
1595     //     (clang extension)
1596     //
1597     //     T __attribute__(((ext_vector_type(N))))
1598     case Type::DependentSizedExtVector: {
1599       const DependentSizedExtVectorType *VectorParam
1600         = cast<DependentSizedExtVectorType>(Param);
1601 
1602       if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1603         // Perform deduction on the element types.
1604         if (Sema::TemplateDeductionResult Result
1605               = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1606                                                   VectorParam->getElementType(),
1607                                                    VectorArg->getElementType(),
1608                                                    Info, Deduced, TDF))
1609           return Result;
1610 
1611         // Perform deduction on the vector size, if we can.
1612         NonTypeTemplateParmDecl *NTTP
1613           = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1614         if (!NTTP)
1615           return Sema::TDK_Success;
1616 
1617         llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1618         ArgSize = VectorArg->getNumElements();
1619         return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1620                                              false, Info, Deduced);
1621       }
1622 
1623       if (const DependentSizedExtVectorType *VectorArg
1624                                 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1625         // Perform deduction on the element types.
1626         if (Sema::TemplateDeductionResult Result
1627             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1628                                                  VectorParam->getElementType(),
1629                                                  VectorArg->getElementType(),
1630                                                  Info, Deduced, TDF))
1631           return Result;
1632 
1633         // Perform deduction on the vector size, if we can.
1634         NonTypeTemplateParmDecl *NTTP
1635           = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1636         if (!NTTP)
1637           return Sema::TDK_Success;
1638 
1639         return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1640                                              Info, Deduced);
1641       }
1642 
1643       return Sema::TDK_NonDeducedMismatch;
1644     }
1645 
1646     case Type::TypeOfExpr:
1647     case Type::TypeOf:
1648     case Type::DependentName:
1649     case Type::UnresolvedUsing:
1650     case Type::Decltype:
1651     case Type::UnaryTransform:
1652     case Type::Auto:
1653     case Type::DependentTemplateSpecialization:
1654     case Type::PackExpansion:
1655     case Type::Pipe:
1656       // No template argument deduction for these types
1657       return Sema::TDK_Success;
1658   }
1659 
1660   llvm_unreachable("Invalid Type Class!");
1661 }
1662 
1663 static Sema::TemplateDeductionResult
1664 DeduceTemplateArguments(Sema &S,
1665                         TemplateParameterList *TemplateParams,
1666                         const TemplateArgument &Param,
1667                         TemplateArgument Arg,
1668                         TemplateDeductionInfo &Info,
1669                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1670   // If the template argument is a pack expansion, perform template argument
1671   // deduction against the pattern of that expansion. This only occurs during
1672   // partial ordering.
1673   if (Arg.isPackExpansion())
1674     Arg = Arg.getPackExpansionPattern();
1675 
1676   switch (Param.getKind()) {
1677   case TemplateArgument::Null:
1678     llvm_unreachable("Null template argument in parameter list");
1679 
1680   case TemplateArgument::Type:
1681     if (Arg.getKind() == TemplateArgument::Type)
1682       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1683                                                 Param.getAsType(),
1684                                                 Arg.getAsType(),
1685                                                 Info, Deduced, 0);
1686     Info.FirstArg = Param;
1687     Info.SecondArg = Arg;
1688     return Sema::TDK_NonDeducedMismatch;
1689 
1690   case TemplateArgument::Template:
1691     if (Arg.getKind() == TemplateArgument::Template)
1692       return DeduceTemplateArguments(S, TemplateParams,
1693                                      Param.getAsTemplate(),
1694                                      Arg.getAsTemplate(), Info, Deduced);
1695     Info.FirstArg = Param;
1696     Info.SecondArg = Arg;
1697     return Sema::TDK_NonDeducedMismatch;
1698 
1699   case TemplateArgument::TemplateExpansion:
1700     llvm_unreachable("caller should handle pack expansions");
1701 
1702   case TemplateArgument::Declaration:
1703     if (Arg.getKind() == TemplateArgument::Declaration &&
1704         isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
1705       return Sema::TDK_Success;
1706 
1707     Info.FirstArg = Param;
1708     Info.SecondArg = Arg;
1709     return Sema::TDK_NonDeducedMismatch;
1710 
1711   case TemplateArgument::NullPtr:
1712     if (Arg.getKind() == TemplateArgument::NullPtr &&
1713         S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
1714       return Sema::TDK_Success;
1715 
1716     Info.FirstArg = Param;
1717     Info.SecondArg = Arg;
1718     return Sema::TDK_NonDeducedMismatch;
1719 
1720   case TemplateArgument::Integral:
1721     if (Arg.getKind() == TemplateArgument::Integral) {
1722       if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
1723         return Sema::TDK_Success;
1724 
1725       Info.FirstArg = Param;
1726       Info.SecondArg = Arg;
1727       return Sema::TDK_NonDeducedMismatch;
1728     }
1729 
1730     if (Arg.getKind() == TemplateArgument::Expression) {
1731       Info.FirstArg = Param;
1732       Info.SecondArg = Arg;
1733       return Sema::TDK_NonDeducedMismatch;
1734     }
1735 
1736     Info.FirstArg = Param;
1737     Info.SecondArg = Arg;
1738     return Sema::TDK_NonDeducedMismatch;
1739 
1740   case TemplateArgument::Expression: {
1741     if (NonTypeTemplateParmDecl *NTTP
1742           = getDeducedParameterFromExpr(Param.getAsExpr())) {
1743       if (Arg.getKind() == TemplateArgument::Integral)
1744         return DeduceNonTypeTemplateArgument(S, NTTP,
1745                                              Arg.getAsIntegral(),
1746                                              Arg.getIntegralType(),
1747                                              /*ArrayBound=*/false,
1748                                              Info, Deduced);
1749       if (Arg.getKind() == TemplateArgument::Expression)
1750         return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
1751                                              Info, Deduced);
1752       if (Arg.getKind() == TemplateArgument::Declaration)
1753         return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
1754                                              Info, Deduced);
1755 
1756       Info.FirstArg = Param;
1757       Info.SecondArg = Arg;
1758       return Sema::TDK_NonDeducedMismatch;
1759     }
1760 
1761     // Can't deduce anything, but that's okay.
1762     return Sema::TDK_Success;
1763   }
1764   case TemplateArgument::Pack:
1765     llvm_unreachable("Argument packs should be expanded by the caller!");
1766   }
1767 
1768   llvm_unreachable("Invalid TemplateArgument Kind!");
1769 }
1770 
1771 /// \brief Determine whether there is a template argument to be used for
1772 /// deduction.
1773 ///
1774 /// This routine "expands" argument packs in-place, overriding its input
1775 /// parameters so that \c Args[ArgIdx] will be the available template argument.
1776 ///
1777 /// \returns true if there is another template argument (which will be at
1778 /// \c Args[ArgIdx]), false otherwise.
1779 static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1780                                             unsigned &ArgIdx,
1781                                             unsigned &NumArgs) {
1782   if (ArgIdx == NumArgs)
1783     return false;
1784 
1785   const TemplateArgument &Arg = Args[ArgIdx];
1786   if (Arg.getKind() != TemplateArgument::Pack)
1787     return true;
1788 
1789   assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1790   Args = Arg.pack_begin();
1791   NumArgs = Arg.pack_size();
1792   ArgIdx = 0;
1793   return ArgIdx < NumArgs;
1794 }
1795 
1796 /// \brief Determine whether the given set of template arguments has a pack
1797 /// expansion that is not the last template argument.
1798 static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1799                                       unsigned NumArgs) {
1800   unsigned ArgIdx = 0;
1801   while (ArgIdx < NumArgs) {
1802     const TemplateArgument &Arg = Args[ArgIdx];
1803 
1804     // Unwrap argument packs.
1805     if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1806       Args = Arg.pack_begin();
1807       NumArgs = Arg.pack_size();
1808       ArgIdx = 0;
1809       continue;
1810     }
1811 
1812     ++ArgIdx;
1813     if (ArgIdx == NumArgs)
1814       return false;
1815 
1816     if (Arg.isPackExpansion())
1817       return true;
1818   }
1819 
1820   return false;
1821 }
1822 
1823 static Sema::TemplateDeductionResult
1824 DeduceTemplateArguments(Sema &S,
1825                         TemplateParameterList *TemplateParams,
1826                         const TemplateArgument *Params, unsigned NumParams,
1827                         const TemplateArgument *Args, unsigned NumArgs,
1828                         TemplateDeductionInfo &Info,
1829                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1830   // C++0x [temp.deduct.type]p9:
1831   //   If the template argument list of P contains a pack expansion that is not
1832   //   the last template argument, the entire template argument list is a
1833   //   non-deduced context.
1834   if (hasPackExpansionBeforeEnd(Params, NumParams))
1835     return Sema::TDK_Success;
1836 
1837   // C++0x [temp.deduct.type]p9:
1838   //   If P has a form that contains <T> or <i>, then each argument Pi of the
1839   //   respective template argument list P is compared with the corresponding
1840   //   argument Ai of the corresponding template argument list of A.
1841   unsigned ArgIdx = 0, ParamIdx = 0;
1842   for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1843        ++ParamIdx) {
1844     if (!Params[ParamIdx].isPackExpansion()) {
1845       // The simple case: deduce template arguments by matching Pi and Ai.
1846 
1847       // Check whether we have enough arguments.
1848       if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
1849         return Sema::TDK_Success;
1850 
1851       if (Args[ArgIdx].isPackExpansion()) {
1852         // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1853         // but applied to pack expansions that are template arguments.
1854         return Sema::TDK_MiscellaneousDeductionFailure;
1855       }
1856 
1857       // Perform deduction for this Pi/Ai pair.
1858       if (Sema::TemplateDeductionResult Result
1859             = DeduceTemplateArguments(S, TemplateParams,
1860                                       Params[ParamIdx], Args[ArgIdx],
1861                                       Info, Deduced))
1862         return Result;
1863 
1864       // Move to the next argument.
1865       ++ArgIdx;
1866       continue;
1867     }
1868 
1869     // The parameter is a pack expansion.
1870 
1871     // C++0x [temp.deduct.type]p9:
1872     //   If Pi is a pack expansion, then the pattern of Pi is compared with
1873     //   each remaining argument in the template argument list of A. Each
1874     //   comparison deduces template arguments for subsequent positions in the
1875     //   template parameter packs expanded by Pi.
1876     TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1877 
1878     // FIXME: If there are no remaining arguments, we can bail out early
1879     // and set any deduced parameter packs to an empty argument pack.
1880     // The latter part of this is a (minor) correctness issue.
1881 
1882     // Prepare to deduce the packs within the pattern.
1883     PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1884 
1885     // Keep track of the deduced template arguments for each parameter pack
1886     // expanded by this pack expansion (the outer index) and for each
1887     // template argument (the inner SmallVectors).
1888     bool HasAnyArguments = false;
1889     for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
1890       HasAnyArguments = true;
1891 
1892       // Deduce template arguments from the pattern.
1893       if (Sema::TemplateDeductionResult Result
1894             = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1895                                       Info, Deduced))
1896         return Result;
1897 
1898       PackScope.nextPackElement();
1899     }
1900 
1901     // Build argument packs for each of the parameter packs expanded by this
1902     // pack expansion.
1903     if (auto Result = PackScope.finish(HasAnyArguments))
1904       return Result;
1905   }
1906 
1907   return Sema::TDK_Success;
1908 }
1909 
1910 static Sema::TemplateDeductionResult
1911 DeduceTemplateArguments(Sema &S,
1912                         TemplateParameterList *TemplateParams,
1913                         const TemplateArgumentList &ParamList,
1914                         const TemplateArgumentList &ArgList,
1915                         TemplateDeductionInfo &Info,
1916                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1917   return DeduceTemplateArguments(S, TemplateParams,
1918                                  ParamList.data(), ParamList.size(),
1919                                  ArgList.data(), ArgList.size(),
1920                                  Info, Deduced);
1921 }
1922 
1923 /// \brief Determine whether two template arguments are the same.
1924 static bool isSameTemplateArg(ASTContext &Context,
1925                               const TemplateArgument &X,
1926                               const TemplateArgument &Y) {
1927   if (X.getKind() != Y.getKind())
1928     return false;
1929 
1930   switch (X.getKind()) {
1931     case TemplateArgument::Null:
1932       llvm_unreachable("Comparing NULL template argument");
1933 
1934     case TemplateArgument::Type:
1935       return Context.getCanonicalType(X.getAsType()) ==
1936              Context.getCanonicalType(Y.getAsType());
1937 
1938     case TemplateArgument::Declaration:
1939       return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
1940 
1941     case TemplateArgument::NullPtr:
1942       return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
1943 
1944     case TemplateArgument::Template:
1945     case TemplateArgument::TemplateExpansion:
1946       return Context.getCanonicalTemplateName(
1947                     X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1948              Context.getCanonicalTemplateName(
1949                     Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
1950 
1951     case TemplateArgument::Integral:
1952       return X.getAsIntegral() == Y.getAsIntegral();
1953 
1954     case TemplateArgument::Expression: {
1955       llvm::FoldingSetNodeID XID, YID;
1956       X.getAsExpr()->Profile(XID, Context, true);
1957       Y.getAsExpr()->Profile(YID, Context, true);
1958       return XID == YID;
1959     }
1960 
1961     case TemplateArgument::Pack:
1962       if (X.pack_size() != Y.pack_size())
1963         return false;
1964 
1965       for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1966                                         XPEnd = X.pack_end(),
1967                                            YP = Y.pack_begin();
1968            XP != XPEnd; ++XP, ++YP)
1969         if (!isSameTemplateArg(Context, *XP, *YP))
1970           return false;
1971 
1972       return true;
1973   }
1974 
1975   llvm_unreachable("Invalid TemplateArgument Kind!");
1976 }
1977 
1978 /// \brief Allocate a TemplateArgumentLoc where all locations have
1979 /// been initialized to the given location.
1980 ///
1981 /// \param S The semantic analysis object.
1982 ///
1983 /// \param Arg The template argument we are producing template argument
1984 /// location information for.
1985 ///
1986 /// \param NTTPType For a declaration template argument, the type of
1987 /// the non-type template parameter that corresponds to this template
1988 /// argument.
1989 ///
1990 /// \param Loc The source location to use for the resulting template
1991 /// argument.
1992 static TemplateArgumentLoc
1993 getTrivialTemplateArgumentLoc(Sema &S,
1994                               const TemplateArgument &Arg,
1995                               QualType NTTPType,
1996                               SourceLocation Loc) {
1997   switch (Arg.getKind()) {
1998   case TemplateArgument::Null:
1999     llvm_unreachable("Can't get a NULL template argument here");
2000 
2001   case TemplateArgument::Type:
2002     return TemplateArgumentLoc(Arg,
2003                      S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2004 
2005   case TemplateArgument::Declaration: {
2006     Expr *E
2007       = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2008           .getAs<Expr>();
2009     return TemplateArgumentLoc(TemplateArgument(E), E);
2010   }
2011 
2012   case TemplateArgument::NullPtr: {
2013     Expr *E
2014       = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2015           .getAs<Expr>();
2016     return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2017                                E);
2018   }
2019 
2020   case TemplateArgument::Integral: {
2021     Expr *E
2022       = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
2023     return TemplateArgumentLoc(TemplateArgument(E), E);
2024   }
2025 
2026     case TemplateArgument::Template:
2027     case TemplateArgument::TemplateExpansion: {
2028       NestedNameSpecifierLocBuilder Builder;
2029       TemplateName Template = Arg.getAsTemplate();
2030       if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2031         Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
2032       else if (QualifiedTemplateName *QTN =
2033                    Template.getAsQualifiedTemplateName())
2034         Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
2035 
2036       if (Arg.getKind() == TemplateArgument::Template)
2037         return TemplateArgumentLoc(Arg,
2038                                    Builder.getWithLocInContext(S.Context),
2039                                    Loc);
2040 
2041 
2042       return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
2043                                  Loc, Loc);
2044     }
2045 
2046   case TemplateArgument::Expression:
2047     return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2048 
2049   case TemplateArgument::Pack:
2050     return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2051   }
2052 
2053   llvm_unreachable("Invalid TemplateArgument Kind!");
2054 }
2055 
2056 
2057 /// \brief Convert the given deduced template argument and add it to the set of
2058 /// fully-converted template arguments.
2059 static bool
2060 ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2061                                DeducedTemplateArgument Arg,
2062                                NamedDecl *Template,
2063                                TemplateDeductionInfo &Info,
2064                                bool InFunctionTemplate,
2065                                SmallVectorImpl<TemplateArgument> &Output) {
2066   // First, for a non-type template parameter type that is
2067   // initialized by a declaration, we need the type of the
2068   // corresponding non-type template parameter.
2069   QualType NTTPType;
2070   if (NonTypeTemplateParmDecl *NTTP =
2071           dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2072     NTTPType = NTTP->getType();
2073     if (NTTPType->isDependentType()) {
2074       TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2075                                         Output.data(), Output.size());
2076       NTTPType = S.SubstType(NTTPType,
2077                              MultiLevelTemplateArgumentList(TemplateArgs),
2078                              NTTP->getLocation(),
2079                              NTTP->getDeclName());
2080       if (NTTPType.isNull())
2081         return true;
2082     }
2083   }
2084 
2085   auto ConvertArg = [&](DeducedTemplateArgument Arg,
2086                         unsigned ArgumentPackIndex) {
2087     // Convert the deduced template argument into a template
2088     // argument that we can check, almost as if the user had written
2089     // the template argument explicitly.
2090     TemplateArgumentLoc ArgLoc =
2091         getTrivialTemplateArgumentLoc(S, Arg, NTTPType, Info.getLocation());
2092 
2093     // Check the template argument, converting it as necessary.
2094     return S.CheckTemplateArgument(
2095         Param, ArgLoc, Template, Template->getLocation(),
2096         Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2097         InFunctionTemplate
2098             ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2099                                               : Sema::CTAK_Deduced)
2100             : Sema::CTAK_Specified);
2101   };
2102 
2103   if (Arg.getKind() == TemplateArgument::Pack) {
2104     // This is a template argument pack, so check each of its arguments against
2105     // the template parameter.
2106     SmallVector<TemplateArgument, 2> PackedArgsBuilder;
2107     for (const auto &P : Arg.pack_elements()) {
2108       // When converting the deduced template argument, append it to the
2109       // general output list. We need to do this so that the template argument
2110       // checking logic has all of the prior template arguments available.
2111       DeducedTemplateArgument InnerArg(P);
2112       InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
2113       assert(InnerArg.getKind() != TemplateArgument::Pack &&
2114              "deduced nested pack");
2115       if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
2116         return true;
2117 
2118       // Move the converted template argument into our argument pack.
2119       PackedArgsBuilder.push_back(Output.pop_back_val());
2120     }
2121 
2122     // If the pack is empty, we still need to substitute into the parameter
2123     // itself, in case that substitution fails. For non-type parameters, we did
2124     // this above. For type parameters, no substitution is ever required.
2125     auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param);
2126     if (TTP && PackedArgsBuilder.empty()) {
2127       // Set up a template instantiation context.
2128       LocalInstantiationScope Scope(S);
2129       Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2130                                        TTP, Output,
2131                                        Template->getSourceRange());
2132       if (Inst.isInvalid())
2133         return true;
2134 
2135       TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2136                                         Output.data(), Output.size());
2137       if (!S.SubstDecl(TTP, S.CurContext,
2138                        MultiLevelTemplateArgumentList(TemplateArgs)))
2139         return true;
2140     }
2141 
2142     // Create the resulting argument pack.
2143     Output.push_back(
2144         TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
2145     return false;
2146   }
2147 
2148   return ConvertArg(Arg, 0);
2149 }
2150 
2151 /// Complete template argument deduction for a class template partial
2152 /// specialization.
2153 static Sema::TemplateDeductionResult
2154 FinishTemplateArgumentDeduction(Sema &S,
2155                                 ClassTemplatePartialSpecializationDecl *Partial,
2156                                 const TemplateArgumentList &TemplateArgs,
2157                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2158                                 TemplateDeductionInfo &Info) {
2159   // Unevaluated SFINAE context.
2160   EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2161   Sema::SFINAETrap Trap(S);
2162 
2163   Sema::ContextRAII SavedContext(S, Partial);
2164 
2165   // C++ [temp.deduct.type]p2:
2166   //   [...] or if any template argument remains neither deduced nor
2167   //   explicitly specified, template argument deduction fails.
2168   SmallVector<TemplateArgument, 4> Builder;
2169   TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2170   for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2171     NamedDecl *Param = PartialParams->getParam(I);
2172     if (Deduced[I].isNull()) {
2173       Info.Param = makeTemplateParameter(Param);
2174       return Sema::TDK_Incomplete;
2175     }
2176 
2177     // We have deduced this argument, so it still needs to be
2178     // checked and converted.
2179     if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
2180                                        Partial, Info, false,
2181                                        Builder)) {
2182       Info.Param = makeTemplateParameter(Param);
2183       // FIXME: These template arguments are temporary. Free them!
2184       Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2185                                                   Builder.size()));
2186       return Sema::TDK_SubstitutionFailure;
2187     }
2188   }
2189 
2190   // Form the template argument list from the deduced template arguments.
2191   TemplateArgumentList *DeducedArgumentList
2192     = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2193                                        Builder.size());
2194 
2195   Info.reset(DeducedArgumentList);
2196 
2197   // Substitute the deduced template arguments into the template
2198   // arguments of the class template partial specialization, and
2199   // verify that the instantiated template arguments are both valid
2200   // and are equivalent to the template arguments originally provided
2201   // to the class template.
2202   LocalInstantiationScope InstScope(S);
2203   ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
2204   const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2205     = Partial->getTemplateArgsAsWritten();
2206   const TemplateArgumentLoc *PartialTemplateArgs
2207     = PartialTemplArgInfo->getTemplateArgs();
2208 
2209   TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2210                                     PartialTemplArgInfo->RAngleLoc);
2211 
2212   if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2213               InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2214     unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2215     if (ParamIdx >= Partial->getTemplateParameters()->size())
2216       ParamIdx = Partial->getTemplateParameters()->size() - 1;
2217 
2218     Decl *Param
2219       = const_cast<NamedDecl *>(
2220                           Partial->getTemplateParameters()->getParam(ParamIdx));
2221     Info.Param = makeTemplateParameter(Param);
2222     Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2223     return Sema::TDK_SubstitutionFailure;
2224   }
2225 
2226   SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2227   if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
2228                                   InstArgs, false, ConvertedInstArgs))
2229     return Sema::TDK_SubstitutionFailure;
2230 
2231   TemplateParameterList *TemplateParams
2232     = ClassTemplate->getTemplateParameters();
2233   for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2234     TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2235     if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2236       Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2237       Info.FirstArg = TemplateArgs[I];
2238       Info.SecondArg = InstArg;
2239       return Sema::TDK_NonDeducedMismatch;
2240     }
2241   }
2242 
2243   if (Trap.hasErrorOccurred())
2244     return Sema::TDK_SubstitutionFailure;
2245 
2246   return Sema::TDK_Success;
2247 }
2248 
2249 /// \brief Perform template argument deduction to determine whether
2250 /// the given template arguments match the given class template
2251 /// partial specialization per C++ [temp.class.spec.match].
2252 Sema::TemplateDeductionResult
2253 Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
2254                               const TemplateArgumentList &TemplateArgs,
2255                               TemplateDeductionInfo &Info) {
2256   if (Partial->isInvalidDecl())
2257     return TDK_Invalid;
2258 
2259   // C++ [temp.class.spec.match]p2:
2260   //   A partial specialization matches a given actual template
2261   //   argument list if the template arguments of the partial
2262   //   specialization can be deduced from the actual template argument
2263   //   list (14.8.2).
2264 
2265   // Unevaluated SFINAE context.
2266   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2267   SFINAETrap Trap(*this);
2268 
2269   SmallVector<DeducedTemplateArgument, 4> Deduced;
2270   Deduced.resize(Partial->getTemplateParameters()->size());
2271   if (TemplateDeductionResult Result
2272         = ::DeduceTemplateArguments(*this,
2273                                     Partial->getTemplateParameters(),
2274                                     Partial->getTemplateArgs(),
2275                                     TemplateArgs, Info, Deduced))
2276     return Result;
2277 
2278   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2279   InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2280                              Info);
2281   if (Inst.isInvalid())
2282     return TDK_InstantiationDepth;
2283 
2284   if (Trap.hasErrorOccurred())
2285     return Sema::TDK_SubstitutionFailure;
2286 
2287   return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2288                                            Deduced, Info);
2289 }
2290 
2291 /// Complete template argument deduction for a variable template partial
2292 /// specialization.
2293 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2294 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
2295 ///        VarTemplate(Partial)SpecializationDecl with a new data
2296 ///        structure Template(Partial)SpecializationDecl, and
2297 ///        using Template(Partial)SpecializationDecl as input type.
2298 static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2299     Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2300     const TemplateArgumentList &TemplateArgs,
2301     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2302     TemplateDeductionInfo &Info) {
2303   // Unevaluated SFINAE context.
2304   EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2305   Sema::SFINAETrap Trap(S);
2306 
2307   // C++ [temp.deduct.type]p2:
2308   //   [...] or if any template argument remains neither deduced nor
2309   //   explicitly specified, template argument deduction fails.
2310   SmallVector<TemplateArgument, 4> Builder;
2311   TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2312   for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2313     NamedDecl *Param = PartialParams->getParam(I);
2314     if (Deduced[I].isNull()) {
2315       Info.Param = makeTemplateParameter(Param);
2316       return Sema::TDK_Incomplete;
2317     }
2318 
2319     // We have deduced this argument, so it still needs to be
2320     // checked and converted.
2321     if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial,
2322                                        Info, false, Builder)) {
2323       Info.Param = makeTemplateParameter(Param);
2324       // FIXME: These template arguments are temporary. Free them!
2325       Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2326                                                   Builder.size()));
2327       return Sema::TDK_SubstitutionFailure;
2328     }
2329   }
2330 
2331   // Form the template argument list from the deduced template arguments.
2332   TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
2333       S.Context, Builder.data(), Builder.size());
2334 
2335   Info.reset(DeducedArgumentList);
2336 
2337   // Substitute the deduced template arguments into the template
2338   // arguments of the class template partial specialization, and
2339   // verify that the instantiated template arguments are both valid
2340   // and are equivalent to the template arguments originally provided
2341   // to the class template.
2342   LocalInstantiationScope InstScope(S);
2343   VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
2344   const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2345     = Partial->getTemplateArgsAsWritten();
2346   const TemplateArgumentLoc *PartialTemplateArgs
2347     = PartialTemplArgInfo->getTemplateArgs();
2348 
2349   TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2350                                     PartialTemplArgInfo->RAngleLoc);
2351 
2352   if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2353               InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2354     unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2355     if (ParamIdx >= Partial->getTemplateParameters()->size())
2356       ParamIdx = Partial->getTemplateParameters()->size() - 1;
2357 
2358     Decl *Param = const_cast<NamedDecl *>(
2359         Partial->getTemplateParameters()->getParam(ParamIdx));
2360     Info.Param = makeTemplateParameter(Param);
2361     Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2362     return Sema::TDK_SubstitutionFailure;
2363   }
2364   SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2365   if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2366                                   false, ConvertedInstArgs))
2367     return Sema::TDK_SubstitutionFailure;
2368 
2369   TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2370   for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2371     TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2372     if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2373       Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2374       Info.FirstArg = TemplateArgs[I];
2375       Info.SecondArg = InstArg;
2376       return Sema::TDK_NonDeducedMismatch;
2377     }
2378   }
2379 
2380   if (Trap.hasErrorOccurred())
2381     return Sema::TDK_SubstitutionFailure;
2382 
2383   return Sema::TDK_Success;
2384 }
2385 
2386 /// \brief Perform template argument deduction to determine whether
2387 /// the given template arguments match the given variable template
2388 /// partial specialization per C++ [temp.class.spec.match].
2389 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2390 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
2391 ///        VarTemplate(Partial)SpecializationDecl with a new data
2392 ///        structure Template(Partial)SpecializationDecl, and
2393 ///        using Template(Partial)SpecializationDecl as input type.
2394 Sema::TemplateDeductionResult
2395 Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2396                               const TemplateArgumentList &TemplateArgs,
2397                               TemplateDeductionInfo &Info) {
2398   if (Partial->isInvalidDecl())
2399     return TDK_Invalid;
2400 
2401   // C++ [temp.class.spec.match]p2:
2402   //   A partial specialization matches a given actual template
2403   //   argument list if the template arguments of the partial
2404   //   specialization can be deduced from the actual template argument
2405   //   list (14.8.2).
2406 
2407   // Unevaluated SFINAE context.
2408   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2409   SFINAETrap Trap(*this);
2410 
2411   SmallVector<DeducedTemplateArgument, 4> Deduced;
2412   Deduced.resize(Partial->getTemplateParameters()->size());
2413   if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2414           *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2415           TemplateArgs, Info, Deduced))
2416     return Result;
2417 
2418   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2419   InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2420                              Info);
2421   if (Inst.isInvalid())
2422     return TDK_InstantiationDepth;
2423 
2424   if (Trap.hasErrorOccurred())
2425     return Sema::TDK_SubstitutionFailure;
2426 
2427   return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2428                                            Deduced, Info);
2429 }
2430 
2431 /// \brief Determine whether the given type T is a simple-template-id type.
2432 static bool isSimpleTemplateIdType(QualType T) {
2433   if (const TemplateSpecializationType *Spec
2434         = T->getAs<TemplateSpecializationType>())
2435     return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
2436 
2437   return false;
2438 }
2439 
2440 /// \brief Substitute the explicitly-provided template arguments into the
2441 /// given function template according to C++ [temp.arg.explicit].
2442 ///
2443 /// \param FunctionTemplate the function template into which the explicit
2444 /// template arguments will be substituted.
2445 ///
2446 /// \param ExplicitTemplateArgs the explicitly-specified template
2447 /// arguments.
2448 ///
2449 /// \param Deduced the deduced template arguments, which will be populated
2450 /// with the converted and checked explicit template arguments.
2451 ///
2452 /// \param ParamTypes will be populated with the instantiated function
2453 /// parameters.
2454 ///
2455 /// \param FunctionType if non-NULL, the result type of the function template
2456 /// will also be instantiated and the pointed-to value will be updated with
2457 /// the instantiated function type.
2458 ///
2459 /// \param Info if substitution fails for any reason, this object will be
2460 /// populated with more information about the failure.
2461 ///
2462 /// \returns TDK_Success if substitution was successful, or some failure
2463 /// condition.
2464 Sema::TemplateDeductionResult
2465 Sema::SubstituteExplicitTemplateArguments(
2466                                       FunctionTemplateDecl *FunctionTemplate,
2467                                TemplateArgumentListInfo &ExplicitTemplateArgs,
2468                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2469                                  SmallVectorImpl<QualType> &ParamTypes,
2470                                           QualType *FunctionType,
2471                                           TemplateDeductionInfo &Info) {
2472   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2473   TemplateParameterList *TemplateParams
2474     = FunctionTemplate->getTemplateParameters();
2475 
2476   if (ExplicitTemplateArgs.size() == 0) {
2477     // No arguments to substitute; just copy over the parameter types and
2478     // fill in the function type.
2479     for (auto P : Function->params())
2480       ParamTypes.push_back(P->getType());
2481 
2482     if (FunctionType)
2483       *FunctionType = Function->getType();
2484     return TDK_Success;
2485   }
2486 
2487   // Unevaluated SFINAE context.
2488   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2489   SFINAETrap Trap(*this);
2490 
2491   // C++ [temp.arg.explicit]p3:
2492   //   Template arguments that are present shall be specified in the
2493   //   declaration order of their corresponding template-parameters. The
2494   //   template argument list shall not specify more template-arguments than
2495   //   there are corresponding template-parameters.
2496   SmallVector<TemplateArgument, 4> Builder;
2497 
2498   // Enter a new template instantiation context where we check the
2499   // explicitly-specified template arguments against this function template,
2500   // and then substitute them into the function parameter types.
2501   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2502   InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2503                              DeducedArgs,
2504            ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2505                              Info);
2506   if (Inst.isInvalid())
2507     return TDK_InstantiationDepth;
2508 
2509   if (CheckTemplateArgumentList(FunctionTemplate,
2510                                 SourceLocation(),
2511                                 ExplicitTemplateArgs,
2512                                 true,
2513                                 Builder) || Trap.hasErrorOccurred()) {
2514     unsigned Index = Builder.size();
2515     if (Index >= TemplateParams->size())
2516       Index = TemplateParams->size() - 1;
2517     Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
2518     return TDK_InvalidExplicitArguments;
2519   }
2520 
2521   // Form the template argument list from the explicitly-specified
2522   // template arguments.
2523   TemplateArgumentList *ExplicitArgumentList
2524     = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
2525   Info.reset(ExplicitArgumentList);
2526 
2527   // Template argument deduction and the final substitution should be
2528   // done in the context of the templated declaration.  Explicit
2529   // argument substitution, on the other hand, needs to happen in the
2530   // calling context.
2531   ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2532 
2533   // If we deduced template arguments for a template parameter pack,
2534   // note that the template argument pack is partially substituted and record
2535   // the explicit template arguments. They'll be used as part of deduction
2536   // for this template parameter pack.
2537   for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2538     const TemplateArgument &Arg = Builder[I];
2539     if (Arg.getKind() == TemplateArgument::Pack) {
2540       CurrentInstantiationScope->SetPartiallySubstitutedPack(
2541                                                  TemplateParams->getParam(I),
2542                                                              Arg.pack_begin(),
2543                                                              Arg.pack_size());
2544       break;
2545     }
2546   }
2547 
2548   const FunctionProtoType *Proto
2549     = Function->getType()->getAs<FunctionProtoType>();
2550   assert(Proto && "Function template does not have a prototype?");
2551 
2552   // Isolate our substituted parameters from our caller.
2553   LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2554 
2555   ExtParameterInfoBuilder ExtParamInfos;
2556 
2557   // Instantiate the types of each of the function parameters given the
2558   // explicitly-specified template arguments. If the function has a trailing
2559   // return type, substitute it after the arguments to ensure we substitute
2560   // in lexical order.
2561   if (Proto->hasTrailingReturn()) {
2562     if (SubstParmTypes(Function->getLocation(),
2563                        Function->param_begin(), Function->getNumParams(),
2564                        Proto->getExtParameterInfosOrNull(),
2565                        MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2566                        ParamTypes, /*params*/ nullptr, ExtParamInfos))
2567       return TDK_SubstitutionFailure;
2568   }
2569 
2570   // Instantiate the return type.
2571   QualType ResultType;
2572   {
2573     // C++11 [expr.prim.general]p3:
2574     //   If a declaration declares a member function or member function
2575     //   template of a class X, the expression this is a prvalue of type
2576     //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2577     //   and the end of the function-definition, member-declarator, or
2578     //   declarator.
2579     unsigned ThisTypeQuals = 0;
2580     CXXRecordDecl *ThisContext = nullptr;
2581     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2582       ThisContext = Method->getParent();
2583       ThisTypeQuals = Method->getTypeQualifiers();
2584     }
2585 
2586     CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
2587                                getLangOpts().CPlusPlus11);
2588 
2589     ResultType =
2590         SubstType(Proto->getReturnType(),
2591                   MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2592                   Function->getTypeSpecStartLoc(), Function->getDeclName());
2593     if (ResultType.isNull() || Trap.hasErrorOccurred())
2594       return TDK_SubstitutionFailure;
2595   }
2596 
2597   // Instantiate the types of each of the function parameters given the
2598   // explicitly-specified template arguments if we didn't do so earlier.
2599   if (!Proto->hasTrailingReturn() &&
2600       SubstParmTypes(Function->getLocation(),
2601                      Function->param_begin(), Function->getNumParams(),
2602                      Proto->getExtParameterInfosOrNull(),
2603                      MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2604                      ParamTypes, /*params*/ nullptr, ExtParamInfos))
2605     return TDK_SubstitutionFailure;
2606 
2607   if (FunctionType) {
2608     auto EPI = Proto->getExtProtoInfo();
2609     EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
2610     *FunctionType = BuildFunctionType(ResultType, ParamTypes,
2611                                       Function->getLocation(),
2612                                       Function->getDeclName(),
2613                                       EPI);
2614     if (FunctionType->isNull() || Trap.hasErrorOccurred())
2615       return TDK_SubstitutionFailure;
2616   }
2617 
2618   // C++ [temp.arg.explicit]p2:
2619   //   Trailing template arguments that can be deduced (14.8.2) may be
2620   //   omitted from the list of explicit template-arguments. If all of the
2621   //   template arguments can be deduced, they may all be omitted; in this
2622   //   case, the empty template argument list <> itself may also be omitted.
2623   //
2624   // Take all of the explicitly-specified arguments and put them into
2625   // the set of deduced template arguments. Explicitly-specified
2626   // parameter packs, however, will be set to NULL since the deduction
2627   // mechanisms handle explicitly-specified argument packs directly.
2628   Deduced.reserve(TemplateParams->size());
2629   for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2630     const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2631     if (Arg.getKind() == TemplateArgument::Pack)
2632       Deduced.push_back(DeducedTemplateArgument());
2633     else
2634       Deduced.push_back(Arg);
2635   }
2636 
2637   return TDK_Success;
2638 }
2639 
2640 /// \brief Check whether the deduced argument type for a call to a function
2641 /// template matches the actual argument type per C++ [temp.deduct.call]p4.
2642 static bool
2643 CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2644                               QualType DeducedA) {
2645   ASTContext &Context = S.Context;
2646 
2647   QualType A = OriginalArg.OriginalArgType;
2648   QualType OriginalParamType = OriginalArg.OriginalParamType;
2649 
2650   // Check for type equality (top-level cv-qualifiers are ignored).
2651   if (Context.hasSameUnqualifiedType(A, DeducedA))
2652     return false;
2653 
2654   // Strip off references on the argument types; they aren't needed for
2655   // the following checks.
2656   if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2657     DeducedA = DeducedARef->getPointeeType();
2658   if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2659     A = ARef->getPointeeType();
2660 
2661   // C++ [temp.deduct.call]p4:
2662   //   [...] However, there are three cases that allow a difference:
2663   //     - If the original P is a reference type, the deduced A (i.e., the
2664   //       type referred to by the reference) can be more cv-qualified than
2665   //       the transformed A.
2666   if (const ReferenceType *OriginalParamRef
2667       = OriginalParamType->getAs<ReferenceType>()) {
2668     // We don't want to keep the reference around any more.
2669     OriginalParamType = OriginalParamRef->getPointeeType();
2670 
2671     Qualifiers AQuals = A.getQualifiers();
2672     Qualifiers DeducedAQuals = DeducedA.getQualifiers();
2673 
2674     // Under Objective-C++ ARC, the deduced type may have implicitly
2675     // been given strong or (when dealing with a const reference)
2676     // unsafe_unretained lifetime. If so, update the original
2677     // qualifiers to include this lifetime.
2678     if (S.getLangOpts().ObjCAutoRefCount &&
2679         ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2680           AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2681          (DeducedAQuals.hasConst() &&
2682           DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2683       AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
2684     }
2685 
2686     if (AQuals == DeducedAQuals) {
2687       // Qualifiers match; there's nothing to do.
2688     } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
2689       return true;
2690     } else {
2691       // Qualifiers are compatible, so have the argument type adopt the
2692       // deduced argument type's qualifiers as if we had performed the
2693       // qualification conversion.
2694       A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2695     }
2696   }
2697 
2698   //    - The transformed A can be another pointer or pointer to member
2699   //      type that can be converted to the deduced A via a qualification
2700   //      conversion.
2701   //
2702   // Also allow conversions which merely strip [[noreturn]] from function types
2703   // (recursively) as an extension.
2704   // FIXME: Currently, this doesn't play nicely with qualification conversions.
2705   bool ObjCLifetimeConversion = false;
2706   QualType ResultTy;
2707   if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
2708       (S.IsQualificationConversion(A, DeducedA, false,
2709                                    ObjCLifetimeConversion) ||
2710        S.IsNoReturnConversion(A, DeducedA, ResultTy)))
2711     return false;
2712 
2713 
2714   //    - If P is a class and P has the form simple-template-id, then the
2715   //      transformed A can be a derived class of the deduced A. [...]
2716   //     [...] Likewise, if P is a pointer to a class of the form
2717   //      simple-template-id, the transformed A can be a pointer to a
2718   //      derived class pointed to by the deduced A.
2719   if (const PointerType *OriginalParamPtr
2720       = OriginalParamType->getAs<PointerType>()) {
2721     if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2722       if (const PointerType *APtr = A->getAs<PointerType>()) {
2723         if (A->getPointeeType()->isRecordType()) {
2724           OriginalParamType = OriginalParamPtr->getPointeeType();
2725           DeducedA = DeducedAPtr->getPointeeType();
2726           A = APtr->getPointeeType();
2727         }
2728       }
2729     }
2730   }
2731 
2732   if (Context.hasSameUnqualifiedType(A, DeducedA))
2733     return false;
2734 
2735   if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2736       S.IsDerivedFrom(SourceLocation(), A, DeducedA))
2737     return false;
2738 
2739   return true;
2740 }
2741 
2742 /// \brief Finish template argument deduction for a function template,
2743 /// checking the deduced template arguments for completeness and forming
2744 /// the function template specialization.
2745 ///
2746 /// \param OriginalCallArgs If non-NULL, the original call arguments against
2747 /// which the deduced argument types should be compared.
2748 Sema::TemplateDeductionResult
2749 Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
2750                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2751                                       unsigned NumExplicitlySpecified,
2752                                       FunctionDecl *&Specialization,
2753                                       TemplateDeductionInfo &Info,
2754         SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2755                                       bool PartialOverloading) {
2756   TemplateParameterList *TemplateParams
2757     = FunctionTemplate->getTemplateParameters();
2758 
2759   // Unevaluated SFINAE context.
2760   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2761   SFINAETrap Trap(*this);
2762 
2763   // Enter a new template instantiation context while we instantiate the
2764   // actual function declaration.
2765   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2766   InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2767                              DeducedArgs,
2768               ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2769                              Info);
2770   if (Inst.isInvalid())
2771     return TDK_InstantiationDepth;
2772 
2773   ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2774 
2775   // C++ [temp.deduct.type]p2:
2776   //   [...] or if any template argument remains neither deduced nor
2777   //   explicitly specified, template argument deduction fails.
2778   SmallVector<TemplateArgument, 4> Builder;
2779   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2780     NamedDecl *Param = TemplateParams->getParam(I);
2781 
2782     if (!Deduced[I].isNull()) {
2783       if (I < NumExplicitlySpecified) {
2784         // We have already fully type-checked and converted this
2785         // argument, because it was explicitly-specified. Just record the
2786         // presence of this argument.
2787         Builder.push_back(Deduced[I]);
2788         // We may have had explicitly-specified template arguments for a
2789         // template parameter pack (that may or may not have been extended
2790         // via additional deduced arguments).
2791         if (Param->isParameterPack() && CurrentInstantiationScope) {
2792           if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2793               Param) {
2794             // Forget the partially-substituted pack; its substitution is now
2795             // complete.
2796             CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2797           }
2798         }
2799         continue;
2800       }
2801 
2802       // We have deduced this argument, so it still needs to be
2803       // checked and converted.
2804       if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2805                                          FunctionTemplate, Info,
2806                                          true, Builder)) {
2807         Info.Param = makeTemplateParameter(Param);
2808         // FIXME: These template arguments are temporary. Free them!
2809         Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2810                                                     Builder.size()));
2811         return TDK_SubstitutionFailure;
2812       }
2813 
2814       continue;
2815     }
2816 
2817     // C++0x [temp.arg.explicit]p3:
2818     //    A trailing template parameter pack (14.5.3) not otherwise deduced will
2819     //    be deduced to an empty sequence of template arguments.
2820     // FIXME: Where did the word "trailing" come from?
2821     if (Param->isTemplateParameterPack()) {
2822       // We may have had explicitly-specified template arguments for this
2823       // template parameter pack. If so, our empty deduction extends the
2824       // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2825       const TemplateArgument *ExplicitArgs;
2826       unsigned NumExplicitArgs;
2827       if (CurrentInstantiationScope &&
2828           CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
2829                                                              &NumExplicitArgs)
2830             == Param) {
2831         Builder.push_back(TemplateArgument(
2832             llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2833 
2834         // Forget the partially-substituted pack; its substitution is now
2835         // complete.
2836         CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2837       } else {
2838         // Go through the motions of checking the empty argument pack against
2839         // the parameter pack.
2840         DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
2841         if (ConvertDeducedTemplateArgument(*this, Param, DeducedPack,
2842                                            FunctionTemplate, Info, true,
2843                                            Builder)) {
2844           Info.Param = makeTemplateParameter(Param);
2845           // FIXME: These template arguments are temporary. Free them!
2846           Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2847                                                       Builder.size()));
2848           return TDK_SubstitutionFailure;
2849         }
2850       }
2851       continue;
2852     }
2853 
2854     // Substitute into the default template argument, if available.
2855     bool HasDefaultArg = false;
2856     TemplateArgumentLoc DefArg
2857       = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2858                                               FunctionTemplate->getLocation(),
2859                                   FunctionTemplate->getSourceRange().getEnd(),
2860                                                 Param,
2861                                                 Builder, HasDefaultArg);
2862 
2863     // If there was no default argument, deduction is incomplete.
2864     if (DefArg.getArgument().isNull()) {
2865       Info.Param = makeTemplateParameter(
2866                          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2867       Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2868                                                   Builder.size()));
2869       if (PartialOverloading) break;
2870 
2871       return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
2872     }
2873 
2874     // Check whether we can actually use the default argument.
2875     if (CheckTemplateArgument(Param, DefArg,
2876                               FunctionTemplate,
2877                               FunctionTemplate->getLocation(),
2878                               FunctionTemplate->getSourceRange().getEnd(),
2879                               0, Builder,
2880                               CTAK_Specified)) {
2881       Info.Param = makeTemplateParameter(
2882                          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2883       // FIXME: These template arguments are temporary. Free them!
2884       Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2885                                                   Builder.size()));
2886       return TDK_SubstitutionFailure;
2887     }
2888 
2889     // If we get here, we successfully used the default template argument.
2890   }
2891 
2892   // Form the template argument list from the deduced template arguments.
2893   TemplateArgumentList *DeducedArgumentList
2894     = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
2895   Info.reset(DeducedArgumentList);
2896 
2897   // Substitute the deduced template arguments into the function template
2898   // declaration to produce the function template specialization.
2899   DeclContext *Owner = FunctionTemplate->getDeclContext();
2900   if (FunctionTemplate->getFriendObjectKind())
2901     Owner = FunctionTemplate->getLexicalDeclContext();
2902   Specialization = cast_or_null<FunctionDecl>(
2903                       SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
2904                          MultiLevelTemplateArgumentList(*DeducedArgumentList)));
2905   if (!Specialization || Specialization->isInvalidDecl())
2906     return TDK_SubstitutionFailure;
2907 
2908   assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2909          FunctionTemplate->getCanonicalDecl());
2910 
2911   // If the template argument list is owned by the function template
2912   // specialization, release it.
2913   if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2914       !Trap.hasErrorOccurred())
2915     Info.take();
2916 
2917   // There may have been an error that did not prevent us from constructing a
2918   // declaration. Mark the declaration invalid and return with a substitution
2919   // failure.
2920   if (Trap.hasErrorOccurred()) {
2921     Specialization->setInvalidDecl(true);
2922     return TDK_SubstitutionFailure;
2923   }
2924 
2925   if (OriginalCallArgs) {
2926     // C++ [temp.deduct.call]p4:
2927     //   In general, the deduction process attempts to find template argument
2928     //   values that will make the deduced A identical to A (after the type A
2929     //   is transformed as described above). [...]
2930     for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2931       OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
2932       unsigned ParamIdx = OriginalArg.ArgIdx;
2933 
2934       if (ParamIdx >= Specialization->getNumParams())
2935         continue;
2936 
2937       QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
2938       if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2939         Info.FirstArg = TemplateArgument(DeducedA);
2940         Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2941         Info.CallArgIndex = OriginalArg.ArgIdx;
2942         return TDK_DeducedMismatch;
2943       }
2944     }
2945   }
2946 
2947   // If we suppressed any diagnostics while performing template argument
2948   // deduction, and if we haven't already instantiated this declaration,
2949   // keep track of these diagnostics. They'll be emitted if this specialization
2950   // is actually used.
2951   if (Info.diag_begin() != Info.diag_end()) {
2952     SuppressedDiagnosticsMap::iterator
2953       Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2954     if (Pos == SuppressedDiagnostics.end())
2955         SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2956           .append(Info.diag_begin(), Info.diag_end());
2957   }
2958 
2959   return TDK_Success;
2960 }
2961 
2962 /// Gets the type of a function for template-argument-deducton
2963 /// purposes when it's considered as part of an overload set.
2964 static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
2965                                   FunctionDecl *Fn) {
2966   // We may need to deduce the return type of the function now.
2967   if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
2968       S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
2969     return QualType();
2970 
2971   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
2972     if (Method->isInstance()) {
2973       // An instance method that's referenced in a form that doesn't
2974       // look like a member pointer is just invalid.
2975       if (!R.HasFormOfMemberPointer) return QualType();
2976 
2977       return S.Context.getMemberPointerType(Fn->getType(),
2978                S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
2979     }
2980 
2981   if (!R.IsAddressOfOperand) return Fn->getType();
2982   return S.Context.getPointerType(Fn->getType());
2983 }
2984 
2985 /// Apply the deduction rules for overload sets.
2986 ///
2987 /// \return the null type if this argument should be treated as an
2988 /// undeduced context
2989 static QualType
2990 ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
2991                             Expr *Arg, QualType ParamType,
2992                             bool ParamWasReference) {
2993 
2994   OverloadExpr::FindResult R = OverloadExpr::find(Arg);
2995 
2996   OverloadExpr *Ovl = R.Expression;
2997 
2998   // C++0x [temp.deduct.call]p4
2999   unsigned TDF = 0;
3000   if (ParamWasReference)
3001     TDF |= TDF_ParamWithReferenceType;
3002   if (R.IsAddressOfOperand)
3003     TDF |= TDF_IgnoreQualifiers;
3004 
3005   // C++0x [temp.deduct.call]p6:
3006   //   When P is a function type, pointer to function type, or pointer
3007   //   to member function type:
3008 
3009   if (!ParamType->isFunctionType() &&
3010       !ParamType->isFunctionPointerType() &&
3011       !ParamType->isMemberFunctionPointerType()) {
3012     if (Ovl->hasExplicitTemplateArgs()) {
3013       // But we can still look for an explicit specialization.
3014       if (FunctionDecl *ExplicitSpec
3015             = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
3016         return GetTypeOfFunction(S, R, ExplicitSpec);
3017     }
3018 
3019     DeclAccessPair DAP;
3020     if (FunctionDecl *Viable =
3021             S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3022       return GetTypeOfFunction(S, R, Viable);
3023 
3024     return QualType();
3025   }
3026 
3027   // Gather the explicit template arguments, if any.
3028   TemplateArgumentListInfo ExplicitTemplateArgs;
3029   if (Ovl->hasExplicitTemplateArgs())
3030     Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
3031   QualType Match;
3032   for (UnresolvedSetIterator I = Ovl->decls_begin(),
3033          E = Ovl->decls_end(); I != E; ++I) {
3034     NamedDecl *D = (*I)->getUnderlyingDecl();
3035 
3036     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3037       //   - If the argument is an overload set containing one or more
3038       //     function templates, the parameter is treated as a
3039       //     non-deduced context.
3040       if (!Ovl->hasExplicitTemplateArgs())
3041         return QualType();
3042 
3043       // Otherwise, see if we can resolve a function type
3044       FunctionDecl *Specialization = nullptr;
3045       TemplateDeductionInfo Info(Ovl->getNameLoc());
3046       if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3047                                     Specialization, Info))
3048         continue;
3049 
3050       D = Specialization;
3051     }
3052 
3053     FunctionDecl *Fn = cast<FunctionDecl>(D);
3054     QualType ArgType = GetTypeOfFunction(S, R, Fn);
3055     if (ArgType.isNull()) continue;
3056 
3057     // Function-to-pointer conversion.
3058     if (!ParamWasReference && ParamType->isPointerType() &&
3059         ArgType->isFunctionType())
3060       ArgType = S.Context.getPointerType(ArgType);
3061 
3062     //   - If the argument is an overload set (not containing function
3063     //     templates), trial argument deduction is attempted using each
3064     //     of the members of the set. If deduction succeeds for only one
3065     //     of the overload set members, that member is used as the
3066     //     argument value for the deduction. If deduction succeeds for
3067     //     more than one member of the overload set the parameter is
3068     //     treated as a non-deduced context.
3069 
3070     // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3071     //   Type deduction is done independently for each P/A pair, and
3072     //   the deduced template argument values are then combined.
3073     // So we do not reject deductions which were made elsewhere.
3074     SmallVector<DeducedTemplateArgument, 8>
3075       Deduced(TemplateParams->size());
3076     TemplateDeductionInfo Info(Ovl->getNameLoc());
3077     Sema::TemplateDeductionResult Result
3078       = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3079                                            ArgType, Info, Deduced, TDF);
3080     if (Result) continue;
3081     if (!Match.isNull()) return QualType();
3082     Match = ArgType;
3083   }
3084 
3085   return Match;
3086 }
3087 
3088 /// \brief Perform the adjustments to the parameter and argument types
3089 /// described in C++ [temp.deduct.call].
3090 ///
3091 /// \returns true if the caller should not attempt to perform any template
3092 /// argument deduction based on this P/A pair because the argument is an
3093 /// overloaded function set that could not be resolved.
3094 static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3095                                           TemplateParameterList *TemplateParams,
3096                                                       QualType &ParamType,
3097                                                       QualType &ArgType,
3098                                                       Expr *Arg,
3099                                                       unsigned &TDF) {
3100   // C++0x [temp.deduct.call]p3:
3101   //   If P is a cv-qualified type, the top level cv-qualifiers of P's type
3102   //   are ignored for type deduction.
3103   if (ParamType.hasQualifiers())
3104     ParamType = ParamType.getUnqualifiedType();
3105 
3106   //   [...] If P is a reference type, the type referred to by P is
3107   //   used for type deduction.
3108   const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
3109   if (ParamRefType)
3110     ParamType = ParamRefType->getPointeeType();
3111 
3112   // Overload sets usually make this parameter an undeduced context,
3113   // but there are sometimes special circumstances.  Typically
3114   // involving a template-id-expr.
3115   if (ArgType == S.Context.OverloadTy) {
3116     ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3117                                           Arg, ParamType,
3118                                           ParamRefType != nullptr);
3119     if (ArgType.isNull())
3120       return true;
3121   }
3122 
3123   if (ParamRefType) {
3124     // If the argument has incomplete array type, try to complete its type.
3125     if (ArgType->isIncompleteArrayType()) {
3126       S.completeExprArrayBound(Arg);
3127       ArgType = Arg->getType();
3128     }
3129 
3130     // C++0x [temp.deduct.call]p3:
3131     //   If P is an rvalue reference to a cv-unqualified template
3132     //   parameter and the argument is an lvalue, the type "lvalue
3133     //   reference to A" is used in place of A for type deduction.
3134     if (ParamRefType->isRValueReferenceType() &&
3135         !ParamType.getQualifiers() &&
3136         isa<TemplateTypeParmType>(ParamType) &&
3137         Arg->isLValue())
3138       ArgType = S.Context.getLValueReferenceType(ArgType);
3139   } else {
3140     // C++ [temp.deduct.call]p2:
3141     //   If P is not a reference type:
3142     //   - If A is an array type, the pointer type produced by the
3143     //     array-to-pointer standard conversion (4.2) is used in place of
3144     //     A for type deduction; otherwise,
3145     if (ArgType->isArrayType())
3146       ArgType = S.Context.getArrayDecayedType(ArgType);
3147     //   - If A is a function type, the pointer type produced by the
3148     //     function-to-pointer standard conversion (4.3) is used in place
3149     //     of A for type deduction; otherwise,
3150     else if (ArgType->isFunctionType())
3151       ArgType = S.Context.getPointerType(ArgType);
3152     else {
3153       // - If A is a cv-qualified type, the top level cv-qualifiers of A's
3154       //   type are ignored for type deduction.
3155       ArgType = ArgType.getUnqualifiedType();
3156     }
3157   }
3158 
3159   // C++0x [temp.deduct.call]p4:
3160   //   In general, the deduction process attempts to find template argument
3161   //   values that will make the deduced A identical to A (after the type A
3162   //   is transformed as described above). [...]
3163   TDF = TDF_SkipNonDependent;
3164 
3165   //     - If the original P is a reference type, the deduced A (i.e., the
3166   //       type referred to by the reference) can be more cv-qualified than
3167   //       the transformed A.
3168   if (ParamRefType)
3169     TDF |= TDF_ParamWithReferenceType;
3170   //     - The transformed A can be another pointer or pointer to member
3171   //       type that can be converted to the deduced A via a qualification
3172   //       conversion (4.4).
3173   if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3174       ArgType->isObjCObjectPointerType())
3175     TDF |= TDF_IgnoreQualifiers;
3176   //     - If P is a class and P has the form simple-template-id, then the
3177   //       transformed A can be a derived class of the deduced A. Likewise,
3178   //       if P is a pointer to a class of the form simple-template-id, the
3179   //       transformed A can be a pointer to a derived class pointed to by
3180   //       the deduced A.
3181   if (isSimpleTemplateIdType(ParamType) ||
3182       (isa<PointerType>(ParamType) &&
3183        isSimpleTemplateIdType(
3184                               ParamType->getAs<PointerType>()->getPointeeType())))
3185     TDF |= TDF_DerivedClass;
3186 
3187   return false;
3188 }
3189 
3190 static bool
3191 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3192                                QualType T);
3193 
3194 static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3195     Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3196     Expr *Arg, TemplateDeductionInfo &Info,
3197     SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3198 
3199 /// \brief Attempt template argument deduction from an initializer list
3200 ///        deemed to be an argument in a function call.
3201 static bool
3202 DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3203                           QualType AdjustedParamType, InitListExpr *ILE,
3204                           TemplateDeductionInfo &Info,
3205                           SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3206                           unsigned TDF, Sema::TemplateDeductionResult &Result) {
3207 
3208   // [temp.deduct.call] p1 (post CWG-1591)
3209   // If removing references and cv-qualifiers from P gives
3210   // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3211   // non-empty initializer list (8.5.4), then deduction is performed instead for
3212   // each element of the initializer list, taking P0 as a function template
3213   // parameter type and the initializer element as its argument, and in the
3214   // P0[N] case, if N is a non-type template parameter, N is deduced from the
3215   // length of the initializer list. Otherwise, an initializer list argument
3216   // causes the parameter to be considered a non-deduced context
3217 
3218   const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3219 
3220   const bool IsDependentSizedArray =
3221       !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3222 
3223   QualType ElTy;  // The element type of the std::initializer_list or the array.
3224 
3225   const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3226                          S.isStdInitializerList(AdjustedParamType, &ElTy);
3227 
3228   if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
3229     return false;
3230 
3231   Result = Sema::TDK_Success;
3232   // If we are not deducing against the 'T' in a std::initializer_list<T> then
3233   // deduce against the 'T' in T[N].
3234   if (ElTy.isNull()) {
3235     assert(!IsSTDList);
3236     ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
3237   }
3238   // Deduction only needs to be done for dependent types.
3239   if (ElTy->isDependentType()) {
3240     for (Expr *E : ILE->inits()) {
3241       if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3242                                                         E, Info, Deduced, TDF)))
3243         return true;
3244     }
3245   }
3246   if (IsDependentSizedArray) {
3247     const DependentSizedArrayType *ArrTy =
3248         S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3249     // Determine the array bound is something we can deduce.
3250     if (NonTypeTemplateParmDecl *NTTP =
3251             getDeducedParameterFromExpr(ArrTy->getSizeExpr())) {
3252       // We can perform template argument deduction for the given non-type
3253       // template parameter.
3254       assert(NTTP->getDepth() == 0 &&
3255              "Cannot deduce non-type template argument at depth > 0");
3256       llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3257                        ILE->getNumInits());
3258 
3259       Result = DeduceNonTypeTemplateArgument(
3260           S, NTTP, llvm::APSInt(Size), NTTP->getType(),
3261           /*ArrayBound=*/true, Info, Deduced);
3262     }
3263   }
3264   return true;
3265 }
3266 
3267 /// \brief Perform template argument deduction by matching a parameter type
3268 ///        against a single expression, where the expression is an element of
3269 ///        an initializer list that was originally matched against a parameter
3270 ///        of type \c initializer_list\<ParamType\>.
3271 static Sema::TemplateDeductionResult
3272 DeduceTemplateArgumentByListElement(Sema &S,
3273                                     TemplateParameterList *TemplateParams,
3274                                     QualType ParamType, Expr *Arg,
3275                                     TemplateDeductionInfo &Info,
3276                               SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3277                                     unsigned TDF) {
3278   // Handle the case where an init list contains another init list as the
3279   // element.
3280   if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3281     Sema::TemplateDeductionResult Result;
3282     if (!DeduceFromInitializerList(S, TemplateParams,
3283                                    ParamType.getNonReferenceType(), ILE, Info,
3284                                    Deduced, TDF, Result))
3285       return Sema::TDK_Success; // Just ignore this expression.
3286 
3287     return Result;
3288   }
3289 
3290   // For all other cases, just match by type.
3291   QualType ArgType = Arg->getType();
3292   if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
3293                                                 ArgType, Arg, TDF)) {
3294     Info.Expression = Arg;
3295     return Sema::TDK_FailedOverloadResolution;
3296   }
3297   return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3298                                             ArgType, Info, Deduced, TDF);
3299 }
3300 
3301 /// \brief Perform template argument deduction from a function call
3302 /// (C++ [temp.deduct.call]).
3303 ///
3304 /// \param FunctionTemplate the function template for which we are performing
3305 /// template argument deduction.
3306 ///
3307 /// \param ExplicitTemplateArgs the explicit template arguments provided
3308 /// for this call.
3309 ///
3310 /// \param Args the function call arguments
3311 ///
3312 /// \param Specialization if template argument deduction was successful,
3313 /// this will be set to the function template specialization produced by
3314 /// template argument deduction.
3315 ///
3316 /// \param Info the argument will be updated to provide additional information
3317 /// about template argument deduction.
3318 ///
3319 /// \returns the result of template argument deduction.
3320 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3321     FunctionTemplateDecl *FunctionTemplate,
3322     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3323     FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3324     bool PartialOverloading) {
3325   if (FunctionTemplate->isInvalidDecl())
3326     return TDK_Invalid;
3327 
3328   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3329   unsigned NumParams = Function->getNumParams();
3330 
3331   // C++ [temp.deduct.call]p1:
3332   //   Template argument deduction is done by comparing each function template
3333   //   parameter type (call it P) with the type of the corresponding argument
3334   //   of the call (call it A) as described below.
3335   unsigned CheckArgs = Args.size();
3336   if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
3337     return TDK_TooFewArguments;
3338   else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
3339     const FunctionProtoType *Proto
3340       = Function->getType()->getAs<FunctionProtoType>();
3341     if (Proto->isTemplateVariadic())
3342       /* Do nothing */;
3343     else if (Proto->isVariadic())
3344       CheckArgs = NumParams;
3345     else
3346       return TDK_TooManyArguments;
3347   }
3348 
3349   // The types of the parameters from which we will perform template argument
3350   // deduction.
3351   LocalInstantiationScope InstScope(*this);
3352   TemplateParameterList *TemplateParams
3353     = FunctionTemplate->getTemplateParameters();
3354   SmallVector<DeducedTemplateArgument, 4> Deduced;
3355   SmallVector<QualType, 4> ParamTypes;
3356   unsigned NumExplicitlySpecified = 0;
3357   if (ExplicitTemplateArgs) {
3358     TemplateDeductionResult Result =
3359       SubstituteExplicitTemplateArguments(FunctionTemplate,
3360                                           *ExplicitTemplateArgs,
3361                                           Deduced,
3362                                           ParamTypes,
3363                                           nullptr,
3364                                           Info);
3365     if (Result)
3366       return Result;
3367 
3368     NumExplicitlySpecified = Deduced.size();
3369   } else {
3370     // Just fill in the parameter types from the function declaration.
3371     for (unsigned I = 0; I != NumParams; ++I)
3372       ParamTypes.push_back(Function->getParamDecl(I)->getType());
3373   }
3374 
3375   // Deduce template arguments from the function parameters.
3376   Deduced.resize(TemplateParams->size());
3377   unsigned ArgIdx = 0;
3378   SmallVector<OriginalCallArg, 4> OriginalCallArgs;
3379   for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3380        ParamIdx != NumParamTypes; ++ParamIdx) {
3381     QualType OrigParamType = ParamTypes[ParamIdx];
3382     QualType ParamType = OrigParamType;
3383 
3384     const PackExpansionType *ParamExpansion
3385       = dyn_cast<PackExpansionType>(ParamType);
3386     if (!ParamExpansion) {
3387       // Simple case: matching a function parameter to a function argument.
3388       if (ArgIdx >= CheckArgs)
3389         break;
3390 
3391       Expr *Arg = Args[ArgIdx++];
3392       QualType ArgType = Arg->getType();
3393 
3394       unsigned TDF = 0;
3395       if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3396                                                     ParamType, ArgType, Arg,
3397                                                     TDF))
3398         continue;
3399 
3400       // If we have nothing to deduce, we're done.
3401       if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3402         continue;
3403 
3404       // If the argument is an initializer list ...
3405       if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3406         TemplateDeductionResult Result;
3407         // Removing references was already done.
3408         if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3409                                        Info, Deduced, TDF, Result))
3410           continue;
3411 
3412         if (Result)
3413           return Result;
3414         // Don't track the argument type, since an initializer list has none.
3415         continue;
3416       }
3417 
3418       // Keep track of the argument type and corresponding parameter index,
3419       // so we can check for compatibility between the deduced A and A.
3420       OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3421                                                  ArgType));
3422 
3423       if (TemplateDeductionResult Result
3424             = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3425                                                  ParamType, ArgType,
3426                                                  Info, Deduced, TDF))
3427         return Result;
3428 
3429       continue;
3430     }
3431 
3432     // C++0x [temp.deduct.call]p1:
3433     //   For a function parameter pack that occurs at the end of the
3434     //   parameter-declaration-list, the type A of each remaining argument of
3435     //   the call is compared with the type P of the declarator-id of the
3436     //   function parameter pack. Each comparison deduces template arguments
3437     //   for subsequent positions in the template parameter packs expanded by
3438     //   the function parameter pack. For a function parameter pack that does
3439     //   not occur at the end of the parameter-declaration-list, the type of
3440     //   the parameter pack is a non-deduced context.
3441     if (ParamIdx + 1 < NumParamTypes)
3442       break;
3443 
3444     QualType ParamPattern = ParamExpansion->getPattern();
3445     PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3446                                  ParamPattern);
3447 
3448     bool HasAnyArguments = false;
3449     for (; ArgIdx < Args.size(); ++ArgIdx) {
3450       HasAnyArguments = true;
3451 
3452       QualType OrigParamType = ParamPattern;
3453       ParamType = OrigParamType;
3454       Expr *Arg = Args[ArgIdx];
3455       QualType ArgType = Arg->getType();
3456 
3457       unsigned TDF = 0;
3458       if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3459                                                     ParamType, ArgType, Arg,
3460                                                     TDF)) {
3461         // We can't actually perform any deduction for this argument, so stop
3462         // deduction at this point.
3463         ++ArgIdx;
3464         break;
3465       }
3466 
3467       // As above, initializer lists need special handling.
3468       if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3469         TemplateDeductionResult Result;
3470         if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3471                                        Info, Deduced, TDF, Result)) {
3472           ++ArgIdx;
3473           break;
3474         }
3475 
3476         if (Result)
3477           return Result;
3478       } else {
3479 
3480         // Keep track of the argument type and corresponding argument index,
3481         // so we can check for compatibility between the deduced A and A.
3482         if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3483           OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3484                                                      ArgType));
3485 
3486         if (TemplateDeductionResult Result
3487             = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3488                                                  ParamType, ArgType, Info,
3489                                                  Deduced, TDF))
3490           return Result;
3491       }
3492 
3493       PackScope.nextPackElement();
3494     }
3495 
3496     // Build argument packs for each of the parameter packs expanded by this
3497     // pack expansion.
3498     if (auto Result = PackScope.finish(HasAnyArguments))
3499       return Result;
3500 
3501     // After we've matching against a parameter pack, we're done.
3502     break;
3503   }
3504 
3505   return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3506                                          NumExplicitlySpecified, Specialization,
3507                                          Info, &OriginalCallArgs,
3508                                          PartialOverloading);
3509 }
3510 
3511 QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3512                                    QualType FunctionType) {
3513   if (ArgFunctionType.isNull())
3514     return ArgFunctionType;
3515 
3516   const FunctionProtoType *FunctionTypeP =
3517       FunctionType->castAs<FunctionProtoType>();
3518   CallingConv CC = FunctionTypeP->getCallConv();
3519   bool NoReturn = FunctionTypeP->getNoReturnAttr();
3520   const FunctionProtoType *ArgFunctionTypeP =
3521       ArgFunctionType->getAs<FunctionProtoType>();
3522   if (ArgFunctionTypeP->getCallConv() == CC &&
3523       ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3524     return ArgFunctionType;
3525 
3526   FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3527   EI = EI.withNoReturn(NoReturn);
3528   ArgFunctionTypeP =
3529       cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3530   return QualType(ArgFunctionTypeP, 0);
3531 }
3532 
3533 /// \brief Deduce template arguments when taking the address of a function
3534 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3535 /// a template.
3536 ///
3537 /// \param FunctionTemplate the function template for which we are performing
3538 /// template argument deduction.
3539 ///
3540 /// \param ExplicitTemplateArgs the explicitly-specified template
3541 /// arguments.
3542 ///
3543 /// \param ArgFunctionType the function type that will be used as the
3544 /// "argument" type (A) when performing template argument deduction from the
3545 /// function template's function type. This type may be NULL, if there is no
3546 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
3547 ///
3548 /// \param Specialization if template argument deduction was successful,
3549 /// this will be set to the function template specialization produced by
3550 /// template argument deduction.
3551 ///
3552 /// \param Info the argument will be updated to provide additional information
3553 /// about template argument deduction.
3554 ///
3555 /// \returns the result of template argument deduction.
3556 Sema::TemplateDeductionResult
3557 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3558                               TemplateArgumentListInfo *ExplicitTemplateArgs,
3559                               QualType ArgFunctionType,
3560                               FunctionDecl *&Specialization,
3561                               TemplateDeductionInfo &Info,
3562                               bool InOverloadResolution) {
3563   if (FunctionTemplate->isInvalidDecl())
3564     return TDK_Invalid;
3565 
3566   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3567   TemplateParameterList *TemplateParams
3568     = FunctionTemplate->getTemplateParameters();
3569   QualType FunctionType = Function->getType();
3570   if (!InOverloadResolution)
3571     ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
3572 
3573   // Substitute any explicit template arguments.
3574   LocalInstantiationScope InstScope(*this);
3575   SmallVector<DeducedTemplateArgument, 4> Deduced;
3576   unsigned NumExplicitlySpecified = 0;
3577   SmallVector<QualType, 4> ParamTypes;
3578   if (ExplicitTemplateArgs) {
3579     if (TemplateDeductionResult Result
3580           = SubstituteExplicitTemplateArguments(FunctionTemplate,
3581                                                 *ExplicitTemplateArgs,
3582                                                 Deduced, ParamTypes,
3583                                                 &FunctionType, Info))
3584       return Result;
3585 
3586     NumExplicitlySpecified = Deduced.size();
3587   }
3588 
3589   // Unevaluated SFINAE context.
3590   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
3591   SFINAETrap Trap(*this);
3592 
3593   Deduced.resize(TemplateParams->size());
3594 
3595   // If the function has a deduced return type, substitute it for a dependent
3596   // type so that we treat it as a non-deduced context in what follows.
3597   bool HasDeducedReturnType = false;
3598   if (getLangOpts().CPlusPlus14 && InOverloadResolution &&
3599       Function->getReturnType()->getContainedAutoType()) {
3600     FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
3601     HasDeducedReturnType = true;
3602   }
3603 
3604   if (!ArgFunctionType.isNull()) {
3605     unsigned TDF = TDF_TopLevelParameterTypeList;
3606     if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
3607     // Deduce template arguments from the function type.
3608     if (TemplateDeductionResult Result
3609           = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3610                                                FunctionType, ArgFunctionType,
3611                                                Info, Deduced, TDF))
3612       return Result;
3613   }
3614 
3615   if (TemplateDeductionResult Result
3616         = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3617                                           NumExplicitlySpecified,
3618                                           Specialization, Info))
3619     return Result;
3620 
3621   // If the function has a deduced return type, deduce it now, so we can check
3622   // that the deduced function type matches the requested type.
3623   if (HasDeducedReturnType &&
3624       Specialization->getReturnType()->isUndeducedType() &&
3625       DeduceReturnType(Specialization, Info.getLocation(), false))
3626     return TDK_MiscellaneousDeductionFailure;
3627 
3628   // If the requested function type does not match the actual type of the
3629   // specialization with respect to arguments of compatible pointer to function
3630   // types, template argument deduction fails.
3631   if (!ArgFunctionType.isNull()) {
3632     if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3633                            Context.getCanonicalType(Specialization->getType()),
3634                            Context.getCanonicalType(ArgFunctionType)))
3635       return TDK_MiscellaneousDeductionFailure;
3636     else if(!InOverloadResolution &&
3637             !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3638       return TDK_MiscellaneousDeductionFailure;
3639   }
3640 
3641   return TDK_Success;
3642 }
3643 
3644 /// \brief Given a function declaration (e.g. a generic lambda conversion
3645 ///  function) that contains an 'auto' in its result type, substitute it
3646 ///  with TypeToReplaceAutoWith.  Be careful to pass in the type you want
3647 ///  to replace 'auto' with and not the actual result type you want
3648 ///  to set the function to.
3649 static inline void
3650 SubstAutoWithinFunctionReturnType(FunctionDecl *F,
3651                                     QualType TypeToReplaceAutoWith, Sema &S) {
3652   assert(!TypeToReplaceAutoWith->getContainedAutoType());
3653   QualType AutoResultType = F->getReturnType();
3654   assert(AutoResultType->getContainedAutoType());
3655   QualType DeducedResultType = S.SubstAutoType(AutoResultType,
3656                                                TypeToReplaceAutoWith);
3657   S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3658 }
3659 
3660 /// \brief Given a specialized conversion operator of a generic lambda
3661 /// create the corresponding specializations of the call operator and
3662 /// the static-invoker. If the return type of the call operator is auto,
3663 /// deduce its return type and check if that matches the
3664 /// return type of the destination function ptr.
3665 
3666 static inline Sema::TemplateDeductionResult
3667 SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3668     CXXConversionDecl *ConversionSpecialized,
3669     SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3670     QualType ReturnTypeOfDestFunctionPtr,
3671     TemplateDeductionInfo &TDInfo,
3672     Sema &S) {
3673 
3674   CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3675   assert(LambdaClass && LambdaClass->isGenericLambda());
3676 
3677   CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
3678   QualType CallOpResultType = CallOpGeneric->getReturnType();
3679   const bool GenericLambdaCallOperatorHasDeducedReturnType =
3680       CallOpResultType->getContainedAutoType();
3681 
3682   FunctionTemplateDecl *CallOpTemplate =
3683       CallOpGeneric->getDescribedFunctionTemplate();
3684 
3685   FunctionDecl *CallOpSpecialized = nullptr;
3686   // Use the deduced arguments of the conversion function, to specialize our
3687   // generic lambda's call operator.
3688   if (Sema::TemplateDeductionResult Result
3689       = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3690                                           DeducedArguments,
3691                                           0, CallOpSpecialized, TDInfo))
3692     return Result;
3693 
3694   // If we need to deduce the return type, do so (instantiates the callop).
3695   if (GenericLambdaCallOperatorHasDeducedReturnType &&
3696       CallOpSpecialized->getReturnType()->isUndeducedType())
3697     S.DeduceReturnType(CallOpSpecialized,
3698                        CallOpSpecialized->getPointOfInstantiation(),
3699                        /*Diagnose*/ true);
3700 
3701   // Check to see if the return type of the destination ptr-to-function
3702   // matches the return type of the call operator.
3703   if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
3704                              ReturnTypeOfDestFunctionPtr))
3705     return Sema::TDK_NonDeducedMismatch;
3706   // Since we have succeeded in matching the source and destination
3707   // ptr-to-functions (now including return type), and have successfully
3708   // specialized our corresponding call operator, we are ready to
3709   // specialize the static invoker with the deduced arguments of our
3710   // ptr-to-function.
3711   FunctionDecl *InvokerSpecialized = nullptr;
3712   FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3713                   getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3714 
3715 #ifndef NDEBUG
3716   Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3717 #endif
3718     S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
3719           InvokerSpecialized, TDInfo);
3720   assert(Result == Sema::TDK_Success &&
3721     "If the call operator succeeded so should the invoker!");
3722   // Set the result type to match the corresponding call operator
3723   // specialization's result type.
3724   if (GenericLambdaCallOperatorHasDeducedReturnType &&
3725       InvokerSpecialized->getReturnType()->isUndeducedType()) {
3726     // Be sure to get the type to replace 'auto' with and not
3727     // the full result type of the call op specialization
3728     // to substitute into the 'auto' of the invoker and conversion
3729     // function.
3730     // For e.g.
3731     //  int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3732     // We don't want to subst 'int*' into 'auto' to get int**.
3733 
3734     QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3735                                          ->getContainedAutoType()
3736                                          ->getDeducedType();
3737     SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3738         TypeToReplaceAutoWith, S);
3739     SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3740         TypeToReplaceAutoWith, S);
3741   }
3742 
3743   // Ensure that static invoker doesn't have a const qualifier.
3744   // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3745   // do not use the CallOperator's TypeSourceInfo which allows
3746   // the const qualifier to leak through.
3747   const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3748                   getType().getTypePtr()->castAs<FunctionProtoType>();
3749   FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3750   EPI.TypeQuals = 0;
3751   InvokerSpecialized->setType(S.Context.getFunctionType(
3752       InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
3753   return Sema::TDK_Success;
3754 }
3755 /// \brief Deduce template arguments for a templated conversion
3756 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
3757 /// conversion function template specialization.
3758 Sema::TemplateDeductionResult
3759 Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
3760                               QualType ToType,
3761                               CXXConversionDecl *&Specialization,
3762                               TemplateDeductionInfo &Info) {
3763   if (ConversionTemplate->isInvalidDecl())
3764     return TDK_Invalid;
3765 
3766   CXXConversionDecl *ConversionGeneric
3767     = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3768 
3769   QualType FromType = ConversionGeneric->getConversionType();
3770 
3771   // Canonicalize the types for deduction.
3772   QualType P = Context.getCanonicalType(FromType);
3773   QualType A = Context.getCanonicalType(ToType);
3774 
3775   // C++0x [temp.deduct.conv]p2:
3776   //   If P is a reference type, the type referred to by P is used for
3777   //   type deduction.
3778   if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3779     P = PRef->getPointeeType();
3780 
3781   // C++0x [temp.deduct.conv]p4:
3782   //   [...] If A is a reference type, the type referred to by A is used
3783   //   for type deduction.
3784   if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3785     A = ARef->getPointeeType().getUnqualifiedType();
3786   // C++ [temp.deduct.conv]p3:
3787   //
3788   //   If A is not a reference type:
3789   else {
3790     assert(!A->isReferenceType() && "Reference types were handled above");
3791 
3792     //   - If P is an array type, the pointer type produced by the
3793     //     array-to-pointer standard conversion (4.2) is used in place
3794     //     of P for type deduction; otherwise,
3795     if (P->isArrayType())
3796       P = Context.getArrayDecayedType(P);
3797     //   - If P is a function type, the pointer type produced by the
3798     //     function-to-pointer standard conversion (4.3) is used in
3799     //     place of P for type deduction; otherwise,
3800     else if (P->isFunctionType())
3801       P = Context.getPointerType(P);
3802     //   - If P is a cv-qualified type, the top level cv-qualifiers of
3803     //     P's type are ignored for type deduction.
3804     else
3805       P = P.getUnqualifiedType();
3806 
3807     // C++0x [temp.deduct.conv]p4:
3808     //   If A is a cv-qualified type, the top level cv-qualifiers of A's
3809     //   type are ignored for type deduction. If A is a reference type, the type
3810     //   referred to by A is used for type deduction.
3811     A = A.getUnqualifiedType();
3812   }
3813 
3814   // Unevaluated SFINAE context.
3815   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
3816   SFINAETrap Trap(*this);
3817 
3818   // C++ [temp.deduct.conv]p1:
3819   //   Template argument deduction is done by comparing the return
3820   //   type of the template conversion function (call it P) with the
3821   //   type that is required as the result of the conversion (call it
3822   //   A) as described in 14.8.2.4.
3823   TemplateParameterList *TemplateParams
3824     = ConversionTemplate->getTemplateParameters();
3825   SmallVector<DeducedTemplateArgument, 4> Deduced;
3826   Deduced.resize(TemplateParams->size());
3827 
3828   // C++0x [temp.deduct.conv]p4:
3829   //   In general, the deduction process attempts to find template
3830   //   argument values that will make the deduced A identical to
3831   //   A. However, there are two cases that allow a difference:
3832   unsigned TDF = 0;
3833   //     - If the original A is a reference type, A can be more
3834   //       cv-qualified than the deduced A (i.e., the type referred to
3835   //       by the reference)
3836   if (ToType->isReferenceType())
3837     TDF |= TDF_ParamWithReferenceType;
3838   //     - The deduced A can be another pointer or pointer to member
3839   //       type that can be converted to A via a qualification
3840   //       conversion.
3841   //
3842   // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3843   // both P and A are pointers or member pointers. In this case, we
3844   // just ignore cv-qualifiers completely).
3845   if ((P->isPointerType() && A->isPointerType()) ||
3846       (P->isMemberPointerType() && A->isMemberPointerType()))
3847     TDF |= TDF_IgnoreQualifiers;
3848   if (TemplateDeductionResult Result
3849         = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3850                                              P, A, Info, Deduced, TDF))
3851     return Result;
3852 
3853   // Create an Instantiation Scope for finalizing the operator.
3854   LocalInstantiationScope InstScope(*this);
3855   // Finish template argument deduction.
3856   FunctionDecl *ConversionSpecialized = nullptr;
3857   TemplateDeductionResult Result
3858       = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3859                                         ConversionSpecialized, Info);
3860   Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3861 
3862   // If the conversion operator is being invoked on a lambda closure to convert
3863   // to a ptr-to-function, use the deduced arguments from the conversion
3864   // function to specialize the corresponding call operator.
3865   //   e.g., int (*fp)(int) = [](auto a) { return a; };
3866   if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3867 
3868     // Get the return type of the destination ptr-to-function we are converting
3869     // to.  This is necessary for matching the lambda call operator's return
3870     // type to that of the destination ptr-to-function's return type.
3871     assert(A->isPointerType() &&
3872         "Can only convert from lambda to ptr-to-function");
3873     const FunctionType *ToFunType =
3874         A->getPointeeType().getTypePtr()->getAs<FunctionType>();
3875     const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3876 
3877     // Create the corresponding specializations of the call operator and
3878     // the static-invoker; and if the return type is auto,
3879     // deduce the return type and check if it matches the
3880     // DestFunctionPtrReturnType.
3881     // For instance:
3882     //   auto L = [](auto a) { return f(a); };
3883     //   int (*fp)(int) = L;
3884     //   char (*fp2)(int) = L; <-- Not OK.
3885 
3886     Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3887         Specialization, Deduced, DestFunctionPtrReturnType,
3888         Info, *this);
3889   }
3890   return Result;
3891 }
3892 
3893 /// \brief Deduce template arguments for a function template when there is
3894 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3895 ///
3896 /// \param FunctionTemplate the function template for which we are performing
3897 /// template argument deduction.
3898 ///
3899 /// \param ExplicitTemplateArgs the explicitly-specified template
3900 /// arguments.
3901 ///
3902 /// \param Specialization if template argument deduction was successful,
3903 /// this will be set to the function template specialization produced by
3904 /// template argument deduction.
3905 ///
3906 /// \param Info the argument will be updated to provide additional information
3907 /// about template argument deduction.
3908 ///
3909 /// \returns the result of template argument deduction.
3910 Sema::TemplateDeductionResult
3911 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3912                               TemplateArgumentListInfo *ExplicitTemplateArgs,
3913                               FunctionDecl *&Specialization,
3914                               TemplateDeductionInfo &Info,
3915                               bool InOverloadResolution) {
3916   return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
3917                                  QualType(), Specialization, Info,
3918                                  InOverloadResolution);
3919 }
3920 
3921 namespace {
3922   /// Substitute the 'auto' type specifier within a type for a given replacement
3923   /// type.
3924   class SubstituteAutoTransform :
3925     public TreeTransform<SubstituteAutoTransform> {
3926     QualType Replacement;
3927   public:
3928     SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3929         : TreeTransform<SubstituteAutoTransform>(SemaRef),
3930           Replacement(Replacement) {}
3931 
3932     QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3933       // If we're building the type pattern to deduce against, don't wrap the
3934       // substituted type in an AutoType. Certain template deduction rules
3935       // apply only when a template type parameter appears directly (and not if
3936       // the parameter is found through desugaring). For instance:
3937       //   auto &&lref = lvalue;
3938       // must transform into "rvalue reference to T" not "rvalue reference to
3939       // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
3940       if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
3941         QualType Result = Replacement;
3942         TemplateTypeParmTypeLoc NewTL =
3943           TLB.push<TemplateTypeParmTypeLoc>(Result);
3944         NewTL.setNameLoc(TL.getNameLoc());
3945         return Result;
3946       } else {
3947         bool Dependent =
3948           !Replacement.isNull() && Replacement->isDependentType();
3949         QualType Result =
3950           SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
3951                                       TL.getTypePtr()->getKeyword(),
3952                                       Dependent);
3953         AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3954         NewTL.setNameLoc(TL.getNameLoc());
3955         return Result;
3956       }
3957     }
3958 
3959     ExprResult TransformLambdaExpr(LambdaExpr *E) {
3960       // Lambdas never need to be transformed.
3961       return E;
3962     }
3963 
3964     QualType Apply(TypeLoc TL) {
3965       // Create some scratch storage for the transformed type locations.
3966       // FIXME: We're just going to throw this information away. Don't build it.
3967       TypeLocBuilder TLB;
3968       TLB.reserve(TL.getFullDataSize());
3969       return TransformType(TLB, TL);
3970     }
3971   };
3972 }
3973 
3974 Sema::DeduceAutoResult
3975 Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3976   return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3977 }
3978 
3979 /// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
3980 ///
3981 /// \param Type the type pattern using the auto type-specifier.
3982 /// \param Init the initializer for the variable whose type is to be deduced.
3983 /// \param Result if type deduction was successful, this will be set to the
3984 ///        deduced type.
3985 Sema::DeduceAutoResult
3986 Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
3987   if (Init->getType()->isNonOverloadPlaceholderType()) {
3988     ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3989     if (NonPlaceholder.isInvalid())
3990       return DAR_FailedAlreadyDiagnosed;
3991     Init = NonPlaceholder.get();
3992   }
3993 
3994   if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
3995     Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
3996     assert(!Result.isNull() && "substituting DependentTy can't fail");
3997     return DAR_Succeeded;
3998   }
3999 
4000   // If this is a 'decltype(auto)' specifier, do the decltype dance.
4001   // Since 'decltype(auto)' can only occur at the top of the type, we
4002   // don't need to go digging for it.
4003   if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
4004     if (AT->isDecltypeAuto()) {
4005       if (isa<InitListExpr>(Init)) {
4006         Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4007         return DAR_FailedAlreadyDiagnosed;
4008       }
4009 
4010       QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
4011       if (Deduced.isNull())
4012         return DAR_FailedAlreadyDiagnosed;
4013       // FIXME: Support a non-canonical deduced type for 'auto'.
4014       Deduced = Context.getCanonicalType(Deduced);
4015       Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
4016       if (Result.isNull())
4017         return DAR_FailedAlreadyDiagnosed;
4018       return DAR_Succeeded;
4019     } else if (!getLangOpts().CPlusPlus) {
4020       if (isa<InitListExpr>(Init)) {
4021         Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4022         return DAR_FailedAlreadyDiagnosed;
4023       }
4024     }
4025   }
4026 
4027   SourceLocation Loc = Init->getExprLoc();
4028 
4029   LocalInstantiationScope InstScope(*this);
4030 
4031   // Build template<class TemplParam> void Func(FuncParam);
4032   TemplateTypeParmDecl *TemplParam =
4033     TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4034                                  nullptr, false, false);
4035   QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4036   NamedDecl *TemplParamPtr = TemplParam;
4037   FixedSizeTemplateParameterListStorage<1> TemplateParamsSt(
4038       Loc, Loc, TemplParamPtr, Loc);
4039 
4040   QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4041   assert(!FuncParam.isNull() &&
4042          "substituting template parameter for 'auto' failed");
4043 
4044   // Deduce type of TemplParam in Func(Init)
4045   SmallVector<DeducedTemplateArgument, 1> Deduced;
4046   Deduced.resize(1);
4047   QualType InitType = Init->getType();
4048   unsigned TDF = 0;
4049 
4050   TemplateDeductionInfo Info(Loc);
4051 
4052   InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
4053   if (InitList) {
4054     for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
4055       if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4056                                               TemplArg, InitList->getInit(i),
4057                                               Info, Deduced, TDF))
4058         return DAR_Failed;
4059     }
4060   } else {
4061     if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4062       Diag(Loc, diag::err_auto_bitfield);
4063       return DAR_FailedAlreadyDiagnosed;
4064     }
4065 
4066     if (AdjustFunctionParmAndArgTypesForDeduction(
4067             *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
4068       return DAR_Failed;
4069 
4070     if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4071                                            FuncParam, InitType, Info, Deduced,
4072                                            TDF))
4073       return DAR_Failed;
4074   }
4075 
4076   if (Deduced[0].getKind() != TemplateArgument::Type)
4077     return DAR_Failed;
4078 
4079   QualType DeducedType = Deduced[0].getAsType();
4080 
4081   if (InitList) {
4082     DeducedType = BuildStdInitializerList(DeducedType, Loc);
4083     if (DeducedType.isNull())
4084       return DAR_FailedAlreadyDiagnosed;
4085   }
4086 
4087   Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
4088   if (Result.isNull())
4089    return DAR_FailedAlreadyDiagnosed;
4090 
4091   // Check that the deduced argument type is compatible with the original
4092   // argument type per C++ [temp.deduct.call]p4.
4093   if (!InitList && !Result.isNull() &&
4094       CheckOriginalCallArgDeduction(*this,
4095                                     Sema::OriginalCallArg(FuncParam,0,InitType),
4096                                     Result)) {
4097     Result = QualType();
4098     return DAR_Failed;
4099   }
4100 
4101   return DAR_Succeeded;
4102 }
4103 
4104 QualType Sema::SubstAutoType(QualType TypeWithAuto,
4105                              QualType TypeToReplaceAuto) {
4106   return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4107                TransformType(TypeWithAuto);
4108 }
4109 
4110 TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4111                              QualType TypeToReplaceAuto) {
4112     return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4113                TransformType(TypeWithAuto);
4114 }
4115 
4116 void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4117   if (isa<InitListExpr>(Init))
4118     Diag(VDecl->getLocation(),
4119          VDecl->isInitCapture()
4120              ? diag::err_init_capture_deduction_failure_from_init_list
4121              : diag::err_auto_var_deduction_failure_from_init_list)
4122       << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4123   else
4124     Diag(VDecl->getLocation(),
4125          VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4126                                 : diag::err_auto_var_deduction_failure)
4127       << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4128       << Init->getSourceRange();
4129 }
4130 
4131 bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4132                             bool Diagnose) {
4133   assert(FD->getReturnType()->isUndeducedType());
4134 
4135   if (FD->getTemplateInstantiationPattern())
4136     InstantiateFunctionDefinition(Loc, FD);
4137 
4138   bool StillUndeduced = FD->getReturnType()->isUndeducedType();
4139   if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4140     Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4141     Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4142   }
4143 
4144   return StillUndeduced;
4145 }
4146 
4147 static void
4148 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
4149                            bool OnlyDeduced,
4150                            unsigned Level,
4151                            llvm::SmallBitVector &Deduced);
4152 
4153 /// \brief If this is a non-static member function,
4154 static void
4155 AddImplicitObjectParameterType(ASTContext &Context,
4156                                CXXMethodDecl *Method,
4157                                SmallVectorImpl<QualType> &ArgTypes) {
4158   // C++11 [temp.func.order]p3:
4159   //   [...] The new parameter is of type "reference to cv A," where cv are
4160   //   the cv-qualifiers of the function template (if any) and A is
4161   //   the class of which the function template is a member.
4162   //
4163   // The standard doesn't say explicitly, but we pick the appropriate kind of
4164   // reference type based on [over.match.funcs]p4.
4165   QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4166   ArgTy = Context.getQualifiedType(ArgTy,
4167                         Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
4168   if (Method->getRefQualifier() == RQ_RValue)
4169     ArgTy = Context.getRValueReferenceType(ArgTy);
4170   else
4171     ArgTy = Context.getLValueReferenceType(ArgTy);
4172   ArgTypes.push_back(ArgTy);
4173 }
4174 
4175 /// \brief Determine whether the function template \p FT1 is at least as
4176 /// specialized as \p FT2.
4177 static bool isAtLeastAsSpecializedAs(Sema &S,
4178                                      SourceLocation Loc,
4179                                      FunctionTemplateDecl *FT1,
4180                                      FunctionTemplateDecl *FT2,
4181                                      TemplatePartialOrderingContext TPOC,
4182                                      unsigned NumCallArguments1) {
4183   FunctionDecl *FD1 = FT1->getTemplatedDecl();
4184   FunctionDecl *FD2 = FT2->getTemplatedDecl();
4185   const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4186   const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
4187 
4188   assert(Proto1 && Proto2 && "Function templates must have prototypes");
4189   TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
4190   SmallVector<DeducedTemplateArgument, 4> Deduced;
4191   Deduced.resize(TemplateParams->size());
4192 
4193   // C++0x [temp.deduct.partial]p3:
4194   //   The types used to determine the ordering depend on the context in which
4195   //   the partial ordering is done:
4196   TemplateDeductionInfo Info(Loc);
4197   SmallVector<QualType, 4> Args2;
4198   switch (TPOC) {
4199   case TPOC_Call: {
4200     //   - In the context of a function call, the function parameter types are
4201     //     used.
4202     CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4203     CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
4204 
4205     // C++11 [temp.func.order]p3:
4206     //   [...] If only one of the function templates is a non-static
4207     //   member, that function template is considered to have a new
4208     //   first parameter inserted in its function parameter list. The
4209     //   new parameter is of type "reference to cv A," where cv are
4210     //   the cv-qualifiers of the function template (if any) and A is
4211     //   the class of which the function template is a member.
4212     //
4213     // Note that we interpret this to mean "if one of the function
4214     // templates is a non-static member and the other is a non-member";
4215     // otherwise, the ordering rules for static functions against non-static
4216     // functions don't make any sense.
4217     //
4218     // C++98/03 doesn't have this provision but we've extended DR532 to cover
4219     // it as wording was broken prior to it.
4220     SmallVector<QualType, 4> Args1;
4221 
4222     unsigned NumComparedArguments = NumCallArguments1;
4223 
4224     if (!Method2 && Method1 && !Method1->isStatic()) {
4225       // Compare 'this' from Method1 against first parameter from Method2.
4226       AddImplicitObjectParameterType(S.Context, Method1, Args1);
4227       ++NumComparedArguments;
4228     } else if (!Method1 && Method2 && !Method2->isStatic()) {
4229       // Compare 'this' from Method2 against first parameter from Method1.
4230       AddImplicitObjectParameterType(S.Context, Method2, Args2);
4231     }
4232 
4233     Args1.insert(Args1.end(), Proto1->param_type_begin(),
4234                  Proto1->param_type_end());
4235     Args2.insert(Args2.end(), Proto2->param_type_begin(),
4236                  Proto2->param_type_end());
4237 
4238     // C++ [temp.func.order]p5:
4239     //   The presence of unused ellipsis and default arguments has no effect on
4240     //   the partial ordering of function templates.
4241     if (Args1.size() > NumComparedArguments)
4242       Args1.resize(NumComparedArguments);
4243     if (Args2.size() > NumComparedArguments)
4244       Args2.resize(NumComparedArguments);
4245     if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4246                                 Args1.data(), Args1.size(), Info, Deduced,
4247                                 TDF_None, /*PartialOrdering=*/true))
4248       return false;
4249 
4250     break;
4251   }
4252 
4253   case TPOC_Conversion:
4254     //   - In the context of a call to a conversion operator, the return types
4255     //     of the conversion function templates are used.
4256     if (DeduceTemplateArgumentsByTypeMatch(
4257             S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4258             Info, Deduced, TDF_None,
4259             /*PartialOrdering=*/true))
4260       return false;
4261     break;
4262 
4263   case TPOC_Other:
4264     //   - In other contexts (14.6.6.2) the function template's function type
4265     //     is used.
4266     if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4267                                            FD2->getType(), FD1->getType(),
4268                                            Info, Deduced, TDF_None,
4269                                            /*PartialOrdering=*/true))
4270       return false;
4271     break;
4272   }
4273 
4274   // C++0x [temp.deduct.partial]p11:
4275   //   In most cases, all template parameters must have values in order for
4276   //   deduction to succeed, but for partial ordering purposes a template
4277   //   parameter may remain without a value provided it is not used in the
4278   //   types being used for partial ordering. [ Note: a template parameter used
4279   //   in a non-deduced context is considered used. -end note]
4280   unsigned ArgIdx = 0, NumArgs = Deduced.size();
4281   for (; ArgIdx != NumArgs; ++ArgIdx)
4282     if (Deduced[ArgIdx].isNull())
4283       break;
4284 
4285   if (ArgIdx == NumArgs) {
4286     // All template arguments were deduced. FT1 is at least as specialized
4287     // as FT2.
4288     return true;
4289   }
4290 
4291   // Figure out which template parameters were used.
4292   llvm::SmallBitVector UsedParameters(TemplateParams->size());
4293   switch (TPOC) {
4294   case TPOC_Call:
4295     for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4296       ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4297                                    TemplateParams->getDepth(),
4298                                    UsedParameters);
4299     break;
4300 
4301   case TPOC_Conversion:
4302     ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4303                                  TemplateParams->getDepth(), UsedParameters);
4304     break;
4305 
4306   case TPOC_Other:
4307     ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4308                                  TemplateParams->getDepth(),
4309                                  UsedParameters);
4310     break;
4311   }
4312 
4313   for (; ArgIdx != NumArgs; ++ArgIdx)
4314     // If this argument had no value deduced but was used in one of the types
4315     // used for partial ordering, then deduction fails.
4316     if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4317       return false;
4318 
4319   return true;
4320 }
4321 
4322 /// \brief Determine whether this a function template whose parameter-type-list
4323 /// ends with a function parameter pack.
4324 static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4325   FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4326   unsigned NumParams = Function->getNumParams();
4327   if (NumParams == 0)
4328     return false;
4329 
4330   ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4331   if (!Last->isParameterPack())
4332     return false;
4333 
4334   // Make sure that no previous parameter is a parameter pack.
4335   while (--NumParams > 0) {
4336     if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4337       return false;
4338   }
4339 
4340   return true;
4341 }
4342 
4343 /// \brief Returns the more specialized function template according
4344 /// to the rules of function template partial ordering (C++ [temp.func.order]).
4345 ///
4346 /// \param FT1 the first function template
4347 ///
4348 /// \param FT2 the second function template
4349 ///
4350 /// \param TPOC the context in which we are performing partial ordering of
4351 /// function templates.
4352 ///
4353 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
4354 /// only when \c TPOC is \c TPOC_Call.
4355 ///
4356 /// \param NumCallArguments2 The number of arguments in the call to FT2, used
4357 /// only when \c TPOC is \c TPOC_Call.
4358 ///
4359 /// \returns the more specialized function template. If neither
4360 /// template is more specialized, returns NULL.
4361 FunctionTemplateDecl *
4362 Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4363                                  FunctionTemplateDecl *FT2,
4364                                  SourceLocation Loc,
4365                                  TemplatePartialOrderingContext TPOC,
4366                                  unsigned NumCallArguments1,
4367                                  unsigned NumCallArguments2) {
4368   bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
4369                                           NumCallArguments1);
4370   bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
4371                                           NumCallArguments2);
4372 
4373   if (Better1 != Better2) // We have a clear winner
4374     return Better1 ? FT1 : FT2;
4375 
4376   if (!Better1 && !Better2) // Neither is better than the other
4377     return nullptr;
4378 
4379   // FIXME: This mimics what GCC implements, but doesn't match up with the
4380   // proposed resolution for core issue 692. This area needs to be sorted out,
4381   // but for now we attempt to maintain compatibility.
4382   bool Variadic1 = isVariadicFunctionTemplate(FT1);
4383   bool Variadic2 = isVariadicFunctionTemplate(FT2);
4384   if (Variadic1 != Variadic2)
4385     return Variadic1? FT2 : FT1;
4386 
4387   return nullptr;
4388 }
4389 
4390 /// \brief Determine if the two templates are equivalent.
4391 static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4392   if (T1 == T2)
4393     return true;
4394 
4395   if (!T1 || !T2)
4396     return false;
4397 
4398   return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4399 }
4400 
4401 /// \brief Retrieve the most specialized of the given function template
4402 /// specializations.
4403 ///
4404 /// \param SpecBegin the start iterator of the function template
4405 /// specializations that we will be comparing.
4406 ///
4407 /// \param SpecEnd the end iterator of the function template
4408 /// specializations, paired with \p SpecBegin.
4409 ///
4410 /// \param Loc the location where the ambiguity or no-specializations
4411 /// diagnostic should occur.
4412 ///
4413 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
4414 /// no matching candidates.
4415 ///
4416 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4417 /// occurs.
4418 ///
4419 /// \param CandidateDiag partial diagnostic used for each function template
4420 /// specialization that is a candidate in the ambiguous ordering. One parameter
4421 /// in this diagnostic should be unbound, which will correspond to the string
4422 /// describing the template arguments for the function template specialization.
4423 ///
4424 /// \returns the most specialized function template specialization, if
4425 /// found. Otherwise, returns SpecEnd.
4426 UnresolvedSetIterator Sema::getMostSpecialized(
4427     UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4428     TemplateSpecCandidateSet &FailedCandidates,
4429     SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4430     const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4431     bool Complain, QualType TargetType) {
4432   if (SpecBegin == SpecEnd) {
4433     if (Complain) {
4434       Diag(Loc, NoneDiag);
4435       FailedCandidates.NoteCandidates(*this, Loc);
4436     }
4437     return SpecEnd;
4438   }
4439 
4440   if (SpecBegin + 1 == SpecEnd)
4441     return SpecBegin;
4442 
4443   // Find the function template that is better than all of the templates it
4444   // has been compared to.
4445   UnresolvedSetIterator Best = SpecBegin;
4446   FunctionTemplateDecl *BestTemplate
4447     = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
4448   assert(BestTemplate && "Not a function template specialization?");
4449   for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4450     FunctionTemplateDecl *Challenger
4451       = cast<FunctionDecl>(*I)->getPrimaryTemplate();
4452     assert(Challenger && "Not a function template specialization?");
4453     if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
4454                                                   Loc, TPOC_Other, 0, 0),
4455                        Challenger)) {
4456       Best = I;
4457       BestTemplate = Challenger;
4458     }
4459   }
4460 
4461   // Make sure that the "best" function template is more specialized than all
4462   // of the others.
4463   bool Ambiguous = false;
4464   for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4465     FunctionTemplateDecl *Challenger
4466       = cast<FunctionDecl>(*I)->getPrimaryTemplate();
4467     if (I != Best &&
4468         !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
4469                                                    Loc, TPOC_Other, 0, 0),
4470                         BestTemplate)) {
4471       Ambiguous = true;
4472       break;
4473     }
4474   }
4475 
4476   if (!Ambiguous) {
4477     // We found an answer. Return it.
4478     return Best;
4479   }
4480 
4481   // Diagnose the ambiguity.
4482   if (Complain) {
4483     Diag(Loc, AmbigDiag);
4484 
4485     // FIXME: Can we order the candidates in some sane way?
4486     for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4487       PartialDiagnostic PD = CandidateDiag;
4488       PD << getTemplateArgumentBindingsText(
4489           cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
4490                     *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
4491       if (!TargetType.isNull())
4492         HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4493                                    TargetType);
4494       Diag((*I)->getLocation(), PD);
4495     }
4496   }
4497 
4498   return SpecEnd;
4499 }
4500 
4501 /// \brief Returns the more specialized class template partial specialization
4502 /// according to the rules of partial ordering of class template partial
4503 /// specializations (C++ [temp.class.order]).
4504 ///
4505 /// \param PS1 the first class template partial specialization
4506 ///
4507 /// \param PS2 the second class template partial specialization
4508 ///
4509 /// \returns the more specialized class template partial specialization. If
4510 /// neither partial specialization is more specialized, returns NULL.
4511 ClassTemplatePartialSpecializationDecl *
4512 Sema::getMoreSpecializedPartialSpecialization(
4513                                   ClassTemplatePartialSpecializationDecl *PS1,
4514                                   ClassTemplatePartialSpecializationDecl *PS2,
4515                                               SourceLocation Loc) {
4516   // C++ [temp.class.order]p1:
4517   //   For two class template partial specializations, the first is at least as
4518   //   specialized as the second if, given the following rewrite to two
4519   //   function templates, the first function template is at least as
4520   //   specialized as the second according to the ordering rules for function
4521   //   templates (14.6.6.2):
4522   //     - the first function template has the same template parameters as the
4523   //       first partial specialization and has a single function parameter
4524   //       whose type is a class template specialization with the template
4525   //       arguments of the first partial specialization, and
4526   //     - the second function template has the same template parameters as the
4527   //       second partial specialization and has a single function parameter
4528   //       whose type is a class template specialization with the template
4529   //       arguments of the second partial specialization.
4530   //
4531   // Rather than synthesize function templates, we merely perform the
4532   // equivalent partial ordering by performing deduction directly on
4533   // the template arguments of the class template partial
4534   // specializations. This computation is slightly simpler than the
4535   // general problem of function template partial ordering, because
4536   // class template partial specializations are more constrained. We
4537   // know that every template parameter is deducible from the class
4538   // template partial specialization's template arguments, for
4539   // example.
4540   SmallVector<DeducedTemplateArgument, 4> Deduced;
4541   TemplateDeductionInfo Info(Loc);
4542 
4543   QualType PT1 = PS1->getInjectedSpecializationType();
4544   QualType PT2 = PS2->getInjectedSpecializationType();
4545 
4546   // Determine whether PS1 is at least as specialized as PS2
4547   Deduced.resize(PS2->getTemplateParameters()->size());
4548   bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4549                                             PS2->getTemplateParameters(),
4550                                             PT2, PT1, Info, Deduced, TDF_None,
4551                                             /*PartialOrdering=*/true);
4552   if (Better1) {
4553     SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
4554     InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
4555     Better1 = !::FinishTemplateArgumentDeduction(
4556         *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4557   }
4558 
4559   // Determine whether PS2 is at least as specialized as PS1
4560   Deduced.clear();
4561   Deduced.resize(PS1->getTemplateParameters()->size());
4562   bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4563       *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
4564       /*PartialOrdering=*/true);
4565   if (Better2) {
4566     SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4567                                                  Deduced.end());
4568     InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
4569     Better2 = !::FinishTemplateArgumentDeduction(
4570         *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4571   }
4572 
4573   if (Better1 == Better2)
4574     return nullptr;
4575 
4576   return Better1 ? PS1 : PS2;
4577 }
4578 
4579 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4580 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
4581 ///        VarTemplate(Partial)SpecializationDecl with a new data
4582 ///        structure Template(Partial)SpecializationDecl, and
4583 ///        using Template(Partial)SpecializationDecl as input type.
4584 VarTemplatePartialSpecializationDecl *
4585 Sema::getMoreSpecializedPartialSpecialization(
4586     VarTemplatePartialSpecializationDecl *PS1,
4587     VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4588   SmallVector<DeducedTemplateArgument, 4> Deduced;
4589   TemplateDeductionInfo Info(Loc);
4590 
4591   assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
4592          "the partial specializations being compared should specialize"
4593          " the same template.");
4594   TemplateName Name(PS1->getSpecializedTemplate());
4595   TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4596   QualType PT1 = Context.getTemplateSpecializationType(
4597       CanonTemplate, PS1->getTemplateArgs().data(),
4598       PS1->getTemplateArgs().size());
4599   QualType PT2 = Context.getTemplateSpecializationType(
4600       CanonTemplate, PS2->getTemplateArgs().data(),
4601       PS2->getTemplateArgs().size());
4602 
4603   // Determine whether PS1 is at least as specialized as PS2
4604   Deduced.resize(PS2->getTemplateParameters()->size());
4605   bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4606       *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
4607       /*PartialOrdering=*/true);
4608   if (Better1) {
4609     SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4610                                                  Deduced.end());
4611     InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
4612     Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4613                                                  PS1->getTemplateArgs(),
4614                                                  Deduced, Info);
4615   }
4616 
4617   // Determine whether PS2 is at least as specialized as PS1
4618   Deduced.clear();
4619   Deduced.resize(PS1->getTemplateParameters()->size());
4620   bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4621                                             PS1->getTemplateParameters(),
4622                                             PT1, PT2, Info, Deduced, TDF_None,
4623                                             /*PartialOrdering=*/true);
4624   if (Better2) {
4625     SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
4626     InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
4627     Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4628                                                  PS2->getTemplateArgs(),
4629                                                  Deduced, Info);
4630   }
4631 
4632   if (Better1 == Better2)
4633     return nullptr;
4634 
4635   return Better1? PS1 : PS2;
4636 }
4637 
4638 static void
4639 MarkUsedTemplateParameters(ASTContext &Ctx,
4640                            const TemplateArgument &TemplateArg,
4641                            bool OnlyDeduced,
4642                            unsigned Depth,
4643                            llvm::SmallBitVector &Used);
4644 
4645 /// \brief Mark the template parameters that are used by the given
4646 /// expression.
4647 static void
4648 MarkUsedTemplateParameters(ASTContext &Ctx,
4649                            const Expr *E,
4650                            bool OnlyDeduced,
4651                            unsigned Depth,
4652                            llvm::SmallBitVector &Used) {
4653   // We can deduce from a pack expansion.
4654   if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4655     E = Expansion->getPattern();
4656 
4657   // Skip through any implicit casts we added while type-checking, and any
4658   // substitutions performed by template alias expansion.
4659   while (1) {
4660     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4661       E = ICE->getSubExpr();
4662     else if (const SubstNonTypeTemplateParmExpr *Subst =
4663                dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4664       E = Subst->getReplacement();
4665     else
4666       break;
4667   }
4668 
4669   // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
4670   // find other occurrences of template parameters.
4671   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
4672   if (!DRE)
4673     return;
4674 
4675   const NonTypeTemplateParmDecl *NTTP
4676     = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4677   if (!NTTP)
4678     return;
4679 
4680   if (NTTP->getDepth() == Depth)
4681     Used[NTTP->getIndex()] = true;
4682 }
4683 
4684 /// \brief Mark the template parameters that are used by the given
4685 /// nested name specifier.
4686 static void
4687 MarkUsedTemplateParameters(ASTContext &Ctx,
4688                            NestedNameSpecifier *NNS,
4689                            bool OnlyDeduced,
4690                            unsigned Depth,
4691                            llvm::SmallBitVector &Used) {
4692   if (!NNS)
4693     return;
4694 
4695   MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
4696                              Used);
4697   MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
4698                              OnlyDeduced, Depth, Used);
4699 }
4700 
4701 /// \brief Mark the template parameters that are used by the given
4702 /// template name.
4703 static void
4704 MarkUsedTemplateParameters(ASTContext &Ctx,
4705                            TemplateName Name,
4706                            bool OnlyDeduced,
4707                            unsigned Depth,
4708                            llvm::SmallBitVector &Used) {
4709   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4710     if (TemplateTemplateParmDecl *TTP
4711           = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4712       if (TTP->getDepth() == Depth)
4713         Used[TTP->getIndex()] = true;
4714     }
4715     return;
4716   }
4717 
4718   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
4719     MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
4720                                Depth, Used);
4721   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
4722     MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
4723                                Depth, Used);
4724 }
4725 
4726 /// \brief Mark the template parameters that are used by the given
4727 /// type.
4728 static void
4729 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
4730                            bool OnlyDeduced,
4731                            unsigned Depth,
4732                            llvm::SmallBitVector &Used) {
4733   if (T.isNull())
4734     return;
4735 
4736   // Non-dependent types have nothing deducible
4737   if (!T->isDependentType())
4738     return;
4739 
4740   T = Ctx.getCanonicalType(T);
4741   switch (T->getTypeClass()) {
4742   case Type::Pointer:
4743     MarkUsedTemplateParameters(Ctx,
4744                                cast<PointerType>(T)->getPointeeType(),
4745                                OnlyDeduced,
4746                                Depth,
4747                                Used);
4748     break;
4749 
4750   case Type::BlockPointer:
4751     MarkUsedTemplateParameters(Ctx,
4752                                cast<BlockPointerType>(T)->getPointeeType(),
4753                                OnlyDeduced,
4754                                Depth,
4755                                Used);
4756     break;
4757 
4758   case Type::LValueReference:
4759   case Type::RValueReference:
4760     MarkUsedTemplateParameters(Ctx,
4761                                cast<ReferenceType>(T)->getPointeeType(),
4762                                OnlyDeduced,
4763                                Depth,
4764                                Used);
4765     break;
4766 
4767   case Type::MemberPointer: {
4768     const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
4769     MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
4770                                Depth, Used);
4771     MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
4772                                OnlyDeduced, Depth, Used);
4773     break;
4774   }
4775 
4776   case Type::DependentSizedArray:
4777     MarkUsedTemplateParameters(Ctx,
4778                                cast<DependentSizedArrayType>(T)->getSizeExpr(),
4779                                OnlyDeduced, Depth, Used);
4780     // Fall through to check the element type
4781 
4782   case Type::ConstantArray:
4783   case Type::IncompleteArray:
4784     MarkUsedTemplateParameters(Ctx,
4785                                cast<ArrayType>(T)->getElementType(),
4786                                OnlyDeduced, Depth, Used);
4787     break;
4788 
4789   case Type::Vector:
4790   case Type::ExtVector:
4791     MarkUsedTemplateParameters(Ctx,
4792                                cast<VectorType>(T)->getElementType(),
4793                                OnlyDeduced, Depth, Used);
4794     break;
4795 
4796   case Type::DependentSizedExtVector: {
4797     const DependentSizedExtVectorType *VecType
4798       = cast<DependentSizedExtVectorType>(T);
4799     MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
4800                                Depth, Used);
4801     MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
4802                                Depth, Used);
4803     break;
4804   }
4805 
4806   case Type::FunctionProto: {
4807     const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
4808     MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4809                                Used);
4810     for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4811       MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
4812                                  Depth, Used);
4813     break;
4814   }
4815 
4816   case Type::TemplateTypeParm: {
4817     const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4818     if (TTP->getDepth() == Depth)
4819       Used[TTP->getIndex()] = true;
4820     break;
4821   }
4822 
4823   case Type::SubstTemplateTypeParmPack: {
4824     const SubstTemplateTypeParmPackType *Subst
4825       = cast<SubstTemplateTypeParmPackType>(T);
4826     MarkUsedTemplateParameters(Ctx,
4827                                QualType(Subst->getReplacedParameter(), 0),
4828                                OnlyDeduced, Depth, Used);
4829     MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
4830                                OnlyDeduced, Depth, Used);
4831     break;
4832   }
4833 
4834   case Type::InjectedClassName:
4835     T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4836     // fall through
4837 
4838   case Type::TemplateSpecialization: {
4839     const TemplateSpecializationType *Spec
4840       = cast<TemplateSpecializationType>(T);
4841     MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
4842                                Depth, Used);
4843 
4844     // C++0x [temp.deduct.type]p9:
4845     //   If the template argument list of P contains a pack expansion that is
4846     //   not the last template argument, the entire template argument list is a
4847     //   non-deduced context.
4848     if (OnlyDeduced &&
4849         hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4850       break;
4851 
4852     for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
4853       MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
4854                                  Used);
4855     break;
4856   }
4857 
4858   case Type::Complex:
4859     if (!OnlyDeduced)
4860       MarkUsedTemplateParameters(Ctx,
4861                                  cast<ComplexType>(T)->getElementType(),
4862                                  OnlyDeduced, Depth, Used);
4863     break;
4864 
4865   case Type::Atomic:
4866     if (!OnlyDeduced)
4867       MarkUsedTemplateParameters(Ctx,
4868                                  cast<AtomicType>(T)->getValueType(),
4869                                  OnlyDeduced, Depth, Used);
4870     break;
4871 
4872   case Type::DependentName:
4873     if (!OnlyDeduced)
4874       MarkUsedTemplateParameters(Ctx,
4875                                  cast<DependentNameType>(T)->getQualifier(),
4876                                  OnlyDeduced, Depth, Used);
4877     break;
4878 
4879   case Type::DependentTemplateSpecialization: {
4880     // C++14 [temp.deduct.type]p5:
4881     //   The non-deduced contexts are:
4882     //     -- The nested-name-specifier of a type that was specified using a
4883     //        qualified-id
4884     //
4885     // C++14 [temp.deduct.type]p6:
4886     //   When a type name is specified in a way that includes a non-deduced
4887     //   context, all of the types that comprise that type name are also
4888     //   non-deduced.
4889     if (OnlyDeduced)
4890       break;
4891 
4892     const DependentTemplateSpecializationType *Spec
4893       = cast<DependentTemplateSpecializationType>(T);
4894 
4895     MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4896                                OnlyDeduced, Depth, Used);
4897 
4898     for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
4899       MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
4900                                  Used);
4901     break;
4902   }
4903 
4904   case Type::TypeOf:
4905     if (!OnlyDeduced)
4906       MarkUsedTemplateParameters(Ctx,
4907                                  cast<TypeOfType>(T)->getUnderlyingType(),
4908                                  OnlyDeduced, Depth, Used);
4909     break;
4910 
4911   case Type::TypeOfExpr:
4912     if (!OnlyDeduced)
4913       MarkUsedTemplateParameters(Ctx,
4914                                  cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4915                                  OnlyDeduced, Depth, Used);
4916     break;
4917 
4918   case Type::Decltype:
4919     if (!OnlyDeduced)
4920       MarkUsedTemplateParameters(Ctx,
4921                                  cast<DecltypeType>(T)->getUnderlyingExpr(),
4922                                  OnlyDeduced, Depth, Used);
4923     break;
4924 
4925   case Type::UnaryTransform:
4926     if (!OnlyDeduced)
4927       MarkUsedTemplateParameters(Ctx,
4928                                cast<UnaryTransformType>(T)->getUnderlyingType(),
4929                                  OnlyDeduced, Depth, Used);
4930     break;
4931 
4932   case Type::PackExpansion:
4933     MarkUsedTemplateParameters(Ctx,
4934                                cast<PackExpansionType>(T)->getPattern(),
4935                                OnlyDeduced, Depth, Used);
4936     break;
4937 
4938   case Type::Auto:
4939     MarkUsedTemplateParameters(Ctx,
4940                                cast<AutoType>(T)->getDeducedType(),
4941                                OnlyDeduced, Depth, Used);
4942 
4943   // None of these types have any template parameters in them.
4944   case Type::Builtin:
4945   case Type::VariableArray:
4946   case Type::FunctionNoProto:
4947   case Type::Record:
4948   case Type::Enum:
4949   case Type::ObjCInterface:
4950   case Type::ObjCObject:
4951   case Type::ObjCObjectPointer:
4952   case Type::UnresolvedUsing:
4953   case Type::Pipe:
4954 #define TYPE(Class, Base)
4955 #define ABSTRACT_TYPE(Class, Base)
4956 #define DEPENDENT_TYPE(Class, Base)
4957 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4958 #include "clang/AST/TypeNodes.def"
4959     break;
4960   }
4961 }
4962 
4963 /// \brief Mark the template parameters that are used by this
4964 /// template argument.
4965 static void
4966 MarkUsedTemplateParameters(ASTContext &Ctx,
4967                            const TemplateArgument &TemplateArg,
4968                            bool OnlyDeduced,
4969                            unsigned Depth,
4970                            llvm::SmallBitVector &Used) {
4971   switch (TemplateArg.getKind()) {
4972   case TemplateArgument::Null:
4973   case TemplateArgument::Integral:
4974   case TemplateArgument::Declaration:
4975     break;
4976 
4977   case TemplateArgument::NullPtr:
4978     MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4979                                Depth, Used);
4980     break;
4981 
4982   case TemplateArgument::Type:
4983     MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
4984                                Depth, Used);
4985     break;
4986 
4987   case TemplateArgument::Template:
4988   case TemplateArgument::TemplateExpansion:
4989     MarkUsedTemplateParameters(Ctx,
4990                                TemplateArg.getAsTemplateOrTemplatePattern(),
4991                                OnlyDeduced, Depth, Used);
4992     break;
4993 
4994   case TemplateArgument::Expression:
4995     MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
4996                                Depth, Used);
4997     break;
4998 
4999   case TemplateArgument::Pack:
5000     for (const auto &P : TemplateArg.pack_elements())
5001       MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
5002     break;
5003   }
5004 }
5005 
5006 /// \brief Mark which template parameters can be deduced from a given
5007 /// template argument list.
5008 ///
5009 /// \param TemplateArgs the template argument list from which template
5010 /// parameters will be deduced.
5011 ///
5012 /// \param Used a bit vector whose elements will be set to \c true
5013 /// to indicate when the corresponding template parameter will be
5014 /// deduced.
5015 void
5016 Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5017                                  bool OnlyDeduced, unsigned Depth,
5018                                  llvm::SmallBitVector &Used) {
5019   // C++0x [temp.deduct.type]p9:
5020   //   If the template argument list of P contains a pack expansion that is not
5021   //   the last template argument, the entire template argument list is a
5022   //   non-deduced context.
5023   if (OnlyDeduced &&
5024       hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5025     return;
5026 
5027   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5028     ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
5029                                  Depth, Used);
5030 }
5031 
5032 /// \brief Marks all of the template parameters that will be deduced by a
5033 /// call to the given function template.
5034 void Sema::MarkDeducedTemplateParameters(
5035     ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5036     llvm::SmallBitVector &Deduced) {
5037   TemplateParameterList *TemplateParams
5038     = FunctionTemplate->getTemplateParameters();
5039   Deduced.clear();
5040   Deduced.resize(TemplateParams->size());
5041 
5042   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5043   for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
5044     ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
5045                                  true, TemplateParams->getDepth(), Deduced);
5046 }
5047 
5048 bool hasDeducibleTemplateParameters(Sema &S,
5049                                     FunctionTemplateDecl *FunctionTemplate,
5050                                     QualType T) {
5051   if (!T->isDependentType())
5052     return false;
5053 
5054   TemplateParameterList *TemplateParams
5055     = FunctionTemplate->getTemplateParameters();
5056   llvm::SmallBitVector Deduced(TemplateParams->size());
5057   ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5058                                Deduced);
5059 
5060   return Deduced.any();
5061 }
5062