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