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