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