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