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