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