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