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