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