1 //===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
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 "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/Sema/DeclSpec.h"
23 #include "clang/Sema/Sema.h"
24 #include "clang/Sema/Template.h"
25 #include "llvm/ADT/SmallBitVector.h"
26 #include <algorithm>
27 
28 namespace clang {
29   using namespace sema;
30   /// \brief Various flags that control template argument deduction.
31   ///
32   /// These flags can be bitwise-OR'd together.
33   enum TemplateDeductionFlags {
34     /// \brief No template argument deduction flags, which indicates the
35     /// strictest results for template argument deduction (as used for, e.g.,
36     /// matching class template partial specializations).
37     TDF_None = 0,
38     /// \brief Within template argument deduction from a function call, we are
39     /// matching with a parameter type for which the original parameter was
40     /// a reference.
41     TDF_ParamWithReferenceType = 0x1,
42     /// \brief Within template argument deduction from a function call, we
43     /// are matching in a case where we ignore cv-qualifiers.
44     TDF_IgnoreQualifiers = 0x02,
45     /// \brief Within template argument deduction from a function call,
46     /// we are matching in a case where we can perform template argument
47     /// deduction from a template-id of a derived class of the argument type.
48     TDF_DerivedClass = 0x04,
49     /// \brief Allow non-dependent types to differ, e.g., when performing
50     /// template argument deduction from a function call where conversions
51     /// may apply.
52     TDF_SkipNonDependent = 0x08,
53     /// \brief Whether we are performing template argument deduction for
54     /// parameters and arguments in a top-level template argument
55     TDF_TopLevelParameterTypeList = 0x10,
56     /// \brief Within template argument deduction from overload resolution per
57     /// C++ [over.over] allow matching function types that are compatible in
58     /// terms of noreturn and default calling convention adjustments.
59     TDF_InOverloadResolution = 0x20
60   };
61 }
62 
63 using namespace clang;
64 
65 /// \brief Compare two APSInts, extending and switching the sign as
66 /// necessary to compare their values regardless of underlying type.
67 static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
68   if (Y.getBitWidth() > X.getBitWidth())
69     X = X.extend(Y.getBitWidth());
70   else if (Y.getBitWidth() < X.getBitWidth())
71     Y = Y.extend(X.getBitWidth());
72 
73   // If there is a signedness mismatch, correct it.
74   if (X.isSigned() != Y.isSigned()) {
75     // If the signed value is negative, then the values cannot be the same.
76     if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
77       return false;
78 
79     Y.setIsSigned(true);
80     X.setIsSigned(true);
81   }
82 
83   return X == Y;
84 }
85 
86 static Sema::TemplateDeductionResult
87 DeduceTemplateArguments(Sema &S,
88                         TemplateParameterList *TemplateParams,
89                         const TemplateArgument &Param,
90                         TemplateArgument Arg,
91                         TemplateDeductionInfo &Info,
92                         SmallVectorImpl<DeducedTemplateArgument> &Deduced);
93 
94 static Sema::TemplateDeductionResult
95 DeduceTemplateArgumentsByTypeMatch(Sema &S,
96                                    TemplateParameterList *TemplateParams,
97                                    QualType Param,
98                                    QualType Arg,
99                                    TemplateDeductionInfo &Info,
100                                    SmallVectorImpl<DeducedTemplateArgument> &
101                                                       Deduced,
102                                    unsigned TDF,
103                                    bool PartialOrdering = false);
104 
105 static Sema::TemplateDeductionResult
106 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
107                         const TemplateArgument *Params, unsigned NumParams,
108                         const TemplateArgument *Args, unsigned NumArgs,
109                         TemplateDeductionInfo &Info,
110                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
111                         bool NumberOfArgumentsMustMatch);
112 
113 /// \brief If the given expression is of a form that permits the deduction
114 /// of a non-type template parameter, return the declaration of that
115 /// non-type template parameter.
116 static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
117   // If we are within an alias template, the expression may have undergone
118   // any number of parameter substitutions already.
119   while (1) {
120     if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
121       E = IC->getSubExpr();
122     else if (SubstNonTypeTemplateParmExpr *Subst =
123                dyn_cast<SubstNonTypeTemplateParmExpr>(E))
124       E = Subst->getReplacement();
125     else
126       break;
127   }
128 
129   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
130     return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
131 
132   return nullptr;
133 }
134 
135 /// \brief Determine whether two declaration pointers refer to the same
136 /// declaration.
137 static bool isSameDeclaration(Decl *X, Decl *Y) {
138   if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
139     X = NX->getUnderlyingDecl();
140   if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
141     Y = NY->getUnderlyingDecl();
142 
143   return X->getCanonicalDecl() == Y->getCanonicalDecl();
144 }
145 
146 /// \brief Verify that the given, deduced template arguments are compatible.
147 ///
148 /// \returns The deduced template argument, or a NULL template argument if
149 /// the deduced template arguments were incompatible.
150 static DeducedTemplateArgument
151 checkDeducedTemplateArguments(ASTContext &Context,
152                               const DeducedTemplateArgument &X,
153                               const DeducedTemplateArgument &Y) {
154   // We have no deduction for one or both of the arguments; they're compatible.
155   if (X.isNull())
156     return Y;
157   if (Y.isNull())
158     return X;
159 
160   switch (X.getKind()) {
161   case TemplateArgument::Null:
162     llvm_unreachable("Non-deduced template arguments handled above");
163 
164   case TemplateArgument::Type:
165     // If two template type arguments have the same type, they're compatible.
166     if (Y.getKind() == TemplateArgument::Type &&
167         Context.hasSameType(X.getAsType(), Y.getAsType()))
168       return X;
169 
170     return DeducedTemplateArgument();
171 
172   case TemplateArgument::Integral:
173     // If we deduced a constant in one case and either a dependent expression or
174     // declaration in another case, keep the integral constant.
175     // If both are integral constants with the same value, keep that value.
176     if (Y.getKind() == TemplateArgument::Expression ||
177         Y.getKind() == TemplateArgument::Declaration ||
178         (Y.getKind() == TemplateArgument::Integral &&
179          hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
180       return DeducedTemplateArgument(X,
181                                      X.wasDeducedFromArrayBound() &&
182                                      Y.wasDeducedFromArrayBound());
183 
184     // All other combinations are incompatible.
185     return DeducedTemplateArgument();
186 
187   case TemplateArgument::Template:
188     if (Y.getKind() == TemplateArgument::Template &&
189         Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
190       return X;
191 
192     // All other combinations are incompatible.
193     return DeducedTemplateArgument();
194 
195   case TemplateArgument::TemplateExpansion:
196     if (Y.getKind() == TemplateArgument::TemplateExpansion &&
197         Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
198                                     Y.getAsTemplateOrTemplatePattern()))
199       return X;
200 
201     // All other combinations are incompatible.
202     return DeducedTemplateArgument();
203 
204   case TemplateArgument::Expression:
205     // If we deduced a dependent expression in one case and either an integral
206     // constant or a declaration in another case, keep the integral constant
207     // or declaration.
208     if (Y.getKind() == TemplateArgument::Integral ||
209         Y.getKind() == TemplateArgument::Declaration)
210       return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
211                                      Y.wasDeducedFromArrayBound());
212 
213     if (Y.getKind() == TemplateArgument::Expression) {
214       // Compare the expressions for equality
215       llvm::FoldingSetNodeID ID1, ID2;
216       X.getAsExpr()->Profile(ID1, Context, true);
217       Y.getAsExpr()->Profile(ID2, Context, true);
218       if (ID1 == ID2)
219         return X;
220     }
221 
222     // All other combinations are incompatible.
223     return DeducedTemplateArgument();
224 
225   case TemplateArgument::Declaration:
226     // If we deduced a declaration and a dependent expression, keep the
227     // declaration.
228     if (Y.getKind() == TemplateArgument::Expression)
229       return X;
230 
231     // If we deduced a declaration and an integral constant, keep the
232     // integral constant.
233     if (Y.getKind() == TemplateArgument::Integral)
234       return Y;
235 
236     // If we deduced two declarations, make sure they they refer to the
237     // same declaration.
238     if (Y.getKind() == TemplateArgument::Declaration &&
239         isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
240       return X;
241 
242     // All other combinations are incompatible.
243     return DeducedTemplateArgument();
244 
245   case TemplateArgument::NullPtr:
246     // If we deduced a null pointer and a dependent expression, keep the
247     // null pointer.
248     if (Y.getKind() == TemplateArgument::Expression)
249       return X;
250 
251     // If we deduced a null pointer and an integral constant, keep the
252     // integral constant.
253     if (Y.getKind() == TemplateArgument::Integral)
254       return Y;
255 
256     // If we deduced two null pointers, make sure they have the same type.
257     if (Y.getKind() == TemplateArgument::NullPtr &&
258         Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
259       return X;
260 
261     // All other combinations are incompatible.
262     return DeducedTemplateArgument();
263 
264   case TemplateArgument::Pack:
265     if (Y.getKind() != TemplateArgument::Pack ||
266         X.pack_size() != Y.pack_size())
267       return DeducedTemplateArgument();
268 
269     for (TemplateArgument::pack_iterator XA = X.pack_begin(),
270                                       XAEnd = X.pack_end(),
271                                          YA = Y.pack_begin();
272          XA != XAEnd; ++XA, ++YA) {
273       // FIXME: Do we need to merge the results together here?
274       if (checkDeducedTemplateArguments(Context,
275                     DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
276                     DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
277             .isNull())
278         return DeducedTemplateArgument();
279     }
280 
281     return X;
282   }
283 
284   llvm_unreachable("Invalid TemplateArgument Kind!");
285 }
286 
287 /// \brief Deduce the value of the given non-type template parameter
288 /// from the given constant.
289 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
290     Sema &S, NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
291     QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
292     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
293   assert(NTTP->getDepth() == 0 &&
294          "Cannot deduce non-type template argument with depth > 0");
295 
296   DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
297                                      DeducedFromArrayBound);
298   DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
299                                                      Deduced[NTTP->getIndex()],
300                                                                  NewDeduced);
301   if (Result.isNull()) {
302     Info.Param = NTTP;
303     Info.FirstArg = Deduced[NTTP->getIndex()];
304     Info.SecondArg = NewDeduced;
305     return Sema::TDK_Inconsistent;
306   }
307 
308   Deduced[NTTP->getIndex()] = Result;
309   return Sema::TDK_Success;
310 }
311 
312 /// \brief Deduce the value of the given non-type template parameter
313 /// from the given type- or value-dependent expression.
314 ///
315 /// \returns true if deduction succeeded, false otherwise.
316 static Sema::TemplateDeductionResult
317 DeduceNonTypeTemplateArgument(Sema &S,
318                               NonTypeTemplateParmDecl *NTTP,
319                               Expr *Value,
320                               TemplateDeductionInfo &Info,
321                     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
322   assert(NTTP->getDepth() == 0 &&
323          "Cannot deduce non-type template argument with depth > 0");
324   assert((Value->isTypeDependent() || Value->isValueDependent()) &&
325          "Expression template argument must be type- or value-dependent.");
326 
327   DeducedTemplateArgument NewDeduced(Value);
328   DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
329                                                      Deduced[NTTP->getIndex()],
330                                                                  NewDeduced);
331 
332   if (Result.isNull()) {
333     Info.Param = NTTP;
334     Info.FirstArg = Deduced[NTTP->getIndex()];
335     Info.SecondArg = NewDeduced;
336     return Sema::TDK_Inconsistent;
337   }
338 
339   Deduced[NTTP->getIndex()] = Result;
340   return Sema::TDK_Success;
341 }
342 
343 /// \brief Deduce the value of the given non-type template parameter
344 /// from the given declaration.
345 ///
346 /// \returns true if deduction succeeded, false otherwise.
347 static Sema::TemplateDeductionResult
348 DeduceNonTypeTemplateArgument(Sema &S,
349                             NonTypeTemplateParmDecl *NTTP,
350                             ValueDecl *D,
351                             TemplateDeductionInfo &Info,
352                             SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
353   assert(NTTP->getDepth() == 0 &&
354          "Cannot deduce non-type template argument with depth > 0");
355 
356   D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
357   TemplateArgument New(D, NTTP->getType());
358   DeducedTemplateArgument NewDeduced(New);
359   DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
360                                                      Deduced[NTTP->getIndex()],
361                                                                  NewDeduced);
362   if (Result.isNull()) {
363     Info.Param = NTTP;
364     Info.FirstArg = Deduced[NTTP->getIndex()];
365     Info.SecondArg = NewDeduced;
366     return Sema::TDK_Inconsistent;
367   }
368 
369   Deduced[NTTP->getIndex()] = Result;
370   return Sema::TDK_Success;
371 }
372 
373 static Sema::TemplateDeductionResult
374 DeduceTemplateArguments(Sema &S,
375                         TemplateParameterList *TemplateParams,
376                         TemplateName Param,
377                         TemplateName Arg,
378                         TemplateDeductionInfo &Info,
379                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
380   TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
381   if (!ParamDecl) {
382     // The parameter type is dependent and is not a template template parameter,
383     // so there is nothing that we can deduce.
384     return Sema::TDK_Success;
385   }
386 
387   if (TemplateTemplateParmDecl *TempParam
388         = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
389     DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
390     DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
391                                                  Deduced[TempParam->getIndex()],
392                                                                    NewDeduced);
393     if (Result.isNull()) {
394       Info.Param = TempParam;
395       Info.FirstArg = Deduced[TempParam->getIndex()];
396       Info.SecondArg = NewDeduced;
397       return Sema::TDK_Inconsistent;
398     }
399 
400     Deduced[TempParam->getIndex()] = Result;
401     return Sema::TDK_Success;
402   }
403 
404   // Verify that the two template names are equivalent.
405   if (S.Context.hasSameTemplateName(Param, Arg))
406     return Sema::TDK_Success;
407 
408   // Mismatch of non-dependent template parameter to argument.
409   Info.FirstArg = TemplateArgument(Param);
410   Info.SecondArg = TemplateArgument(Arg);
411   return Sema::TDK_NonDeducedMismatch;
412 }
413 
414 /// \brief Deduce the template arguments by comparing the template parameter
415 /// type (which is a template-id) with the template argument type.
416 ///
417 /// \param S the Sema
418 ///
419 /// \param TemplateParams the template parameters that we are deducing
420 ///
421 /// \param Param the parameter type
422 ///
423 /// \param Arg the argument type
424 ///
425 /// \param Info information about the template argument deduction itself
426 ///
427 /// \param Deduced the deduced template arguments
428 ///
429 /// \returns the result of template argument deduction so far. Note that a
430 /// "success" result means that template argument deduction has not yet failed,
431 /// but it may still fail, later, for other reasons.
432 static Sema::TemplateDeductionResult
433 DeduceTemplateArguments(Sema &S,
434                         TemplateParameterList *TemplateParams,
435                         const TemplateSpecializationType *Param,
436                         QualType Arg,
437                         TemplateDeductionInfo &Info,
438                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
439   assert(Arg.isCanonical() && "Argument type must be canonical");
440 
441   // Check whether the template argument is a dependent template-id.
442   if (const TemplateSpecializationType *SpecArg
443         = dyn_cast<TemplateSpecializationType>(Arg)) {
444     // Perform template argument deduction for the template name.
445     if (Sema::TemplateDeductionResult Result
446           = DeduceTemplateArguments(S, TemplateParams,
447                                     Param->getTemplateName(),
448                                     SpecArg->getTemplateName(),
449                                     Info, Deduced))
450       return Result;
451 
452 
453     // Perform template argument deduction on each template
454     // argument. Ignore any missing/extra arguments, since they could be
455     // filled in by default arguments.
456     return DeduceTemplateArguments(S, TemplateParams, Param->getArgs(),
457                                    Param->getNumArgs(), SpecArg->getArgs(),
458                                    SpecArg->getNumArgs(), Info, Deduced,
459                                    /*NumberOfArgumentsMustMatch=*/false);
460   }
461 
462   // If the argument type is a class template specialization, we
463   // perform template argument deduction using its template
464   // arguments.
465   const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
466   if (!RecordArg) {
467     Info.FirstArg = TemplateArgument(QualType(Param, 0));
468     Info.SecondArg = TemplateArgument(Arg);
469     return Sema::TDK_NonDeducedMismatch;
470   }
471 
472   ClassTemplateSpecializationDecl *SpecArg
473     = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
474   if (!SpecArg) {
475     Info.FirstArg = TemplateArgument(QualType(Param, 0));
476     Info.SecondArg = TemplateArgument(Arg);
477     return Sema::TDK_NonDeducedMismatch;
478   }
479 
480   // Perform template argument deduction for the template name.
481   if (Sema::TemplateDeductionResult Result
482         = DeduceTemplateArguments(S,
483                                   TemplateParams,
484                                   Param->getTemplateName(),
485                                TemplateName(SpecArg->getSpecializedTemplate()),
486                                   Info, Deduced))
487     return Result;
488 
489   // Perform template argument deduction for the template arguments.
490   return DeduceTemplateArguments(
491       S, TemplateParams, Param->getArgs(), Param->getNumArgs(),
492       SpecArg->getTemplateArgs().data(), SpecArg->getTemplateArgs().size(),
493       Info, Deduced, /*NumberOfArgumentsMustMatch=*/true);
494 }
495 
496 /// \brief Determines whether the given type is an opaque type that
497 /// might be more qualified when instantiated.
498 static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
499   switch (T->getTypeClass()) {
500   case Type::TypeOfExpr:
501   case Type::TypeOf:
502   case Type::DependentName:
503   case Type::Decltype:
504   case Type::UnresolvedUsing:
505   case Type::TemplateTypeParm:
506     return true;
507 
508   case Type::ConstantArray:
509   case Type::IncompleteArray:
510   case Type::VariableArray:
511   case Type::DependentSizedArray:
512     return IsPossiblyOpaquelyQualifiedType(
513                                       cast<ArrayType>(T)->getElementType());
514 
515   default:
516     return false;
517   }
518 }
519 
520 /// \brief Retrieve the depth and index of a template parameter.
521 static std::pair<unsigned, unsigned>
522 getDepthAndIndex(NamedDecl *ND) {
523   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
524     return std::make_pair(TTP->getDepth(), TTP->getIndex());
525 
526   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
527     return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
528 
529   TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
530   return std::make_pair(TTP->getDepth(), TTP->getIndex());
531 }
532 
533 /// \brief Retrieve the depth and index of an unexpanded parameter pack.
534 static std::pair<unsigned, unsigned>
535 getDepthAndIndex(UnexpandedParameterPack UPP) {
536   if (const TemplateTypeParmType *TTP
537                           = UPP.first.dyn_cast<const TemplateTypeParmType *>())
538     return std::make_pair(TTP->getDepth(), TTP->getIndex());
539 
540   return getDepthAndIndex(UPP.first.get<NamedDecl *>());
541 }
542 
543 /// \brief Helper function to build a TemplateParameter when we don't
544 /// know its type statically.
545 static TemplateParameter makeTemplateParameter(Decl *D) {
546   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
547     return TemplateParameter(TTP);
548   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
549     return TemplateParameter(NTTP);
550 
551   return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
552 }
553 
554 /// A pack that we're currently deducing.
555 struct clang::DeducedPack {
556   DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
557 
558   // The index of the pack.
559   unsigned Index;
560 
561   // The old value of the pack before we started deducing it.
562   DeducedTemplateArgument Saved;
563 
564   // A deferred value of this pack from an inner deduction, that couldn't be
565   // deduced because this deduction hadn't happened yet.
566   DeducedTemplateArgument DeferredDeduction;
567 
568   // The new value of the pack.
569   SmallVector<DeducedTemplateArgument, 4> New;
570 
571   // The outer deduction for this pack, if any.
572   DeducedPack *Outer;
573 };
574 
575 namespace {
576 /// A scope in which we're performing pack deduction.
577 class PackDeductionScope {
578 public:
579   PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
580                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
581                      TemplateDeductionInfo &Info, TemplateArgument Pattern)
582       : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
583     // Compute the set of template parameter indices that correspond to
584     // parameter packs expanded by the pack expansion.
585     {
586       llvm::SmallBitVector SawIndices(TemplateParams->size());
587       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
588       S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
589       for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
590         unsigned Depth, Index;
591         std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
592         if (Depth == 0 && !SawIndices[Index]) {
593           SawIndices[Index] = true;
594 
595           // Save the deduced template argument for the parameter pack expanded
596           // by this pack expansion, then clear out the deduction.
597           DeducedPack Pack(Index);
598           Pack.Saved = Deduced[Index];
599           Deduced[Index] = TemplateArgument();
600 
601           Packs.push_back(Pack);
602         }
603       }
604     }
605     assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
606 
607     for (auto &Pack : Packs) {
608       if (Info.PendingDeducedPacks.size() > Pack.Index)
609         Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
610       else
611         Info.PendingDeducedPacks.resize(Pack.Index + 1);
612       Info.PendingDeducedPacks[Pack.Index] = &Pack;
613 
614       if (S.CurrentInstantiationScope) {
615         // If the template argument pack was explicitly specified, add that to
616         // the set of deduced arguments.
617         const TemplateArgument *ExplicitArgs;
618         unsigned NumExplicitArgs;
619         NamedDecl *PartiallySubstitutedPack =
620             S.CurrentInstantiationScope->getPartiallySubstitutedPack(
621                 &ExplicitArgs, &NumExplicitArgs);
622         if (PartiallySubstitutedPack &&
623             getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
624           Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
625       }
626     }
627   }
628 
629   ~PackDeductionScope() {
630     for (auto &Pack : Packs)
631       Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
632   }
633 
634   /// Move to deducing the next element in each pack that is being deduced.
635   void nextPackElement() {
636     // Capture the deduced template arguments for each parameter pack expanded
637     // by this pack expansion, add them to the list of arguments we've deduced
638     // for that pack, then clear out the deduced argument.
639     for (auto &Pack : Packs) {
640       DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
641       if (!DeducedArg.isNull()) {
642         Pack.New.push_back(DeducedArg);
643         DeducedArg = DeducedTemplateArgument();
644       }
645     }
646   }
647 
648   /// \brief Finish template argument deduction for a set of argument packs,
649   /// producing the argument packs and checking for consistency with prior
650   /// deductions.
651   Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
652     // Build argument packs for each of the parameter packs expanded by this
653     // pack expansion.
654     for (auto &Pack : Packs) {
655       // Put back the old value for this pack.
656       Deduced[Pack.Index] = Pack.Saved;
657 
658       // Build or find a new value for this pack.
659       DeducedTemplateArgument NewPack;
660       if (HasAnyArguments && Pack.New.empty()) {
661         if (Pack.DeferredDeduction.isNull()) {
662           // We were not able to deduce anything for this parameter pack
663           // (because it only appeared in non-deduced contexts), so just
664           // restore the saved argument pack.
665           continue;
666         }
667 
668         NewPack = Pack.DeferredDeduction;
669         Pack.DeferredDeduction = TemplateArgument();
670       } else if (Pack.New.empty()) {
671         // If we deduced an empty argument pack, create it now.
672         NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
673       } else {
674         TemplateArgument *ArgumentPack =
675             new (S.Context) TemplateArgument[Pack.New.size()];
676         std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
677         NewPack = DeducedTemplateArgument(
678             TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
679             Pack.New[0].wasDeducedFromArrayBound());
680       }
681 
682       // Pick where we're going to put the merged pack.
683       DeducedTemplateArgument *Loc;
684       if (Pack.Outer) {
685         if (Pack.Outer->DeferredDeduction.isNull()) {
686           // Defer checking this pack until we have a complete pack to compare
687           // it against.
688           Pack.Outer->DeferredDeduction = NewPack;
689           continue;
690         }
691         Loc = &Pack.Outer->DeferredDeduction;
692       } else {
693         Loc = &Deduced[Pack.Index];
694       }
695 
696       // Check the new pack matches any previous value.
697       DeducedTemplateArgument OldPack = *Loc;
698       DeducedTemplateArgument Result =
699           checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
700 
701       // If we deferred a deduction of this pack, check that one now too.
702       if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
703         OldPack = Result;
704         NewPack = Pack.DeferredDeduction;
705         Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
706       }
707 
708       if (Result.isNull()) {
709         Info.Param =
710             makeTemplateParameter(TemplateParams->getParam(Pack.Index));
711         Info.FirstArg = OldPack;
712         Info.SecondArg = NewPack;
713         return Sema::TDK_Inconsistent;
714       }
715 
716       *Loc = Result;
717     }
718 
719     return Sema::TDK_Success;
720   }
721 
722 private:
723   Sema &S;
724   TemplateParameterList *TemplateParams;
725   SmallVectorImpl<DeducedTemplateArgument> &Deduced;
726   TemplateDeductionInfo &Info;
727 
728   SmallVector<DeducedPack, 2> Packs;
729 };
730 } // namespace
731 
732 /// \brief Deduce the template arguments by comparing the list of parameter
733 /// types to the list of argument types, as in the parameter-type-lists of
734 /// function types (C++ [temp.deduct.type]p10).
735 ///
736 /// \param S The semantic analysis object within which we are deducing
737 ///
738 /// \param TemplateParams The template parameters that we are deducing
739 ///
740 /// \param Params The list of parameter types
741 ///
742 /// \param NumParams The number of types in \c Params
743 ///
744 /// \param Args The list of argument types
745 ///
746 /// \param NumArgs The number of types in \c Args
747 ///
748 /// \param Info information about the template argument deduction itself
749 ///
750 /// \param Deduced the deduced template arguments
751 ///
752 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
753 /// how template argument deduction is performed.
754 ///
755 /// \param PartialOrdering If true, we are performing template argument
756 /// deduction for during partial ordering for a call
757 /// (C++0x [temp.deduct.partial]).
758 ///
759 /// \returns the result of template argument deduction so far. Note that a
760 /// "success" result means that template argument deduction has not yet failed,
761 /// but it may still fail, later, for other reasons.
762 static Sema::TemplateDeductionResult
763 DeduceTemplateArguments(Sema &S,
764                         TemplateParameterList *TemplateParams,
765                         const QualType *Params, unsigned NumParams,
766                         const QualType *Args, unsigned NumArgs,
767                         TemplateDeductionInfo &Info,
768                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
769                         unsigned TDF,
770                         bool PartialOrdering = false) {
771   // Fast-path check to see if we have too many/too few arguments.
772   if (NumParams != NumArgs &&
773       !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
774       !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
775     return Sema::TDK_MiscellaneousDeductionFailure;
776 
777   // C++0x [temp.deduct.type]p10:
778   //   Similarly, if P has a form that contains (T), then each parameter type
779   //   Pi of the respective parameter-type- list of P is compared with the
780   //   corresponding parameter type Ai of the corresponding parameter-type-list
781   //   of A. [...]
782   unsigned ArgIdx = 0, ParamIdx = 0;
783   for (; ParamIdx != NumParams; ++ParamIdx) {
784     // Check argument types.
785     const PackExpansionType *Expansion
786                                 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
787     if (!Expansion) {
788       // Simple case: compare the parameter and argument types at this point.
789 
790       // Make sure we have an argument.
791       if (ArgIdx >= NumArgs)
792         return Sema::TDK_MiscellaneousDeductionFailure;
793 
794       if (isa<PackExpansionType>(Args[ArgIdx])) {
795         // C++0x [temp.deduct.type]p22:
796         //   If the original function parameter associated with A is a function
797         //   parameter pack and the function parameter associated with P is not
798         //   a function parameter pack, then template argument deduction fails.
799         return Sema::TDK_MiscellaneousDeductionFailure;
800       }
801 
802       if (Sema::TemplateDeductionResult Result
803             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
804                                                  Params[ParamIdx], Args[ArgIdx],
805                                                  Info, Deduced, TDF,
806                                                  PartialOrdering))
807         return Result;
808 
809       ++ArgIdx;
810       continue;
811     }
812 
813     // C++0x [temp.deduct.type]p5:
814     //   The non-deduced contexts are:
815     //     - A function parameter pack that does not occur at the end of the
816     //       parameter-declaration-clause.
817     if (ParamIdx + 1 < NumParams)
818       return Sema::TDK_Success;
819 
820     // C++0x [temp.deduct.type]p10:
821     //   If the parameter-declaration corresponding to Pi is a function
822     //   parameter pack, then the type of its declarator- id is compared with
823     //   each remaining parameter type in the parameter-type-list of A. Each
824     //   comparison deduces template arguments for subsequent positions in the
825     //   template parameter packs expanded by the function parameter pack.
826 
827     QualType Pattern = Expansion->getPattern();
828     PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
829 
830     bool HasAnyArguments = false;
831     for (; ArgIdx < NumArgs; ++ArgIdx) {
832       HasAnyArguments = true;
833 
834       // Deduce template arguments from the pattern.
835       if (Sema::TemplateDeductionResult Result
836             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
837                                                  Args[ArgIdx], Info, Deduced,
838                                                  TDF, PartialOrdering))
839         return Result;
840 
841       PackScope.nextPackElement();
842     }
843 
844     // Build argument packs for each of the parameter packs expanded by this
845     // pack expansion.
846     if (auto Result = PackScope.finish(HasAnyArguments))
847       return Result;
848   }
849 
850   // Make sure we don't have any extra arguments.
851   if (ArgIdx < NumArgs)
852     return Sema::TDK_MiscellaneousDeductionFailure;
853 
854   return Sema::TDK_Success;
855 }
856 
857 /// \brief Determine whether the parameter has qualifiers that are either
858 /// inconsistent with or a superset of the argument's qualifiers.
859 static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
860                                                   QualType ArgType) {
861   Qualifiers ParamQs = ParamType.getQualifiers();
862   Qualifiers ArgQs = ArgType.getQualifiers();
863 
864   if (ParamQs == ArgQs)
865     return false;
866 
867   // Mismatched (but not missing) Objective-C GC attributes.
868   if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
869       ParamQs.hasObjCGCAttr())
870     return true;
871 
872   // Mismatched (but not missing) address spaces.
873   if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
874       ParamQs.hasAddressSpace())
875     return true;
876 
877   // Mismatched (but not missing) Objective-C lifetime qualifiers.
878   if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
879       ParamQs.hasObjCLifetime())
880     return true;
881 
882   // CVR qualifier superset.
883   return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
884       ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
885                                                 == ParamQs.getCVRQualifiers());
886 }
887 
888 /// \brief Compare types for equality with respect to possibly compatible
889 /// function types (noreturn adjustment, implicit calling conventions). If any
890 /// of parameter and argument is not a function, just perform type comparison.
891 ///
892 /// \param Param the template parameter type.
893 ///
894 /// \param Arg the argument type.
895 bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
896                                           CanQualType Arg) {
897   const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
898                      *ArgFunction   = Arg->getAs<FunctionType>();
899 
900   // Just compare if not functions.
901   if (!ParamFunction || !ArgFunction)
902     return Param == Arg;
903 
904   // Noreturn adjustment.
905   QualType AdjustedParam;
906   if (IsNoReturnConversion(Param, Arg, AdjustedParam))
907     return Arg == Context.getCanonicalType(AdjustedParam);
908 
909   // FIXME: Compatible calling conventions.
910 
911   return Param == Arg;
912 }
913 
914 /// \brief Deduce the template arguments by comparing the parameter type and
915 /// the argument type (C++ [temp.deduct.type]).
916 ///
917 /// \param S the semantic analysis object within which we are deducing
918 ///
919 /// \param TemplateParams the template parameters that we are deducing
920 ///
921 /// \param ParamIn the parameter type
922 ///
923 /// \param ArgIn the argument type
924 ///
925 /// \param Info information about the template argument deduction itself
926 ///
927 /// \param Deduced the deduced template arguments
928 ///
929 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
930 /// how template argument deduction is performed.
931 ///
932 /// \param PartialOrdering Whether we're performing template argument deduction
933 /// in the context of partial ordering (C++0x [temp.deduct.partial]).
934 ///
935 /// \returns the result of template argument deduction so far. Note that a
936 /// "success" result means that template argument deduction has not yet failed,
937 /// but it may still fail, later, for other reasons.
938 static Sema::TemplateDeductionResult
939 DeduceTemplateArgumentsByTypeMatch(Sema &S,
940                                    TemplateParameterList *TemplateParams,
941                                    QualType ParamIn, QualType ArgIn,
942                                    TemplateDeductionInfo &Info,
943                             SmallVectorImpl<DeducedTemplateArgument> &Deduced,
944                                    unsigned TDF,
945                                    bool PartialOrdering) {
946   // We only want to look at the canonical types, since typedefs and
947   // sugar are not part of template argument deduction.
948   QualType Param = S.Context.getCanonicalType(ParamIn);
949   QualType Arg = S.Context.getCanonicalType(ArgIn);
950 
951   // If the argument type is a pack expansion, look at its pattern.
952   // This isn't explicitly called out
953   if (const PackExpansionType *ArgExpansion
954                                             = dyn_cast<PackExpansionType>(Arg))
955     Arg = ArgExpansion->getPattern();
956 
957   if (PartialOrdering) {
958     // C++11 [temp.deduct.partial]p5:
959     //   Before the partial ordering is done, certain transformations are
960     //   performed on the types used for partial ordering:
961     //     - If P is a reference type, P is replaced by the type referred to.
962     const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
963     if (ParamRef)
964       Param = ParamRef->getPointeeType();
965 
966     //     - If A is a reference type, A is replaced by the type referred to.
967     const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
968     if (ArgRef)
969       Arg = ArgRef->getPointeeType();
970 
971     if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
972       // C++11 [temp.deduct.partial]p9:
973       //   If, for a given type, deduction succeeds in both directions (i.e.,
974       //   the types are identical after the transformations above) and both
975       //   P and A were reference types [...]:
976       //     - if [one type] was an lvalue reference and [the other type] was
977       //       not, [the other type] is not considered to be at least as
978       //       specialized as [the first type]
979       //     - if [one type] is more cv-qualified than [the other type],
980       //       [the other type] is not considered to be at least as specialized
981       //       as [the first type]
982       // Objective-C ARC adds:
983       //     - [one type] has non-trivial lifetime, [the other type] has
984       //       __unsafe_unretained lifetime, and the types are otherwise
985       //       identical
986       //
987       // A is "considered to be at least as specialized" as P iff deduction
988       // succeeds, so we model this as a deduction failure. Note that
989       // [the first type] is P and [the other type] is A here; the standard
990       // gets this backwards.
991       Qualifiers ParamQuals = Param.getQualifiers();
992       Qualifiers ArgQuals = Arg.getQualifiers();
993       if ((ParamRef->isLValueReferenceType() &&
994            !ArgRef->isLValueReferenceType()) ||
995           ParamQuals.isStrictSupersetOf(ArgQuals) ||
996           (ParamQuals.hasNonTrivialObjCLifetime() &&
997            ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
998            ParamQuals.withoutObjCLifetime() ==
999                ArgQuals.withoutObjCLifetime())) {
1000         Info.FirstArg = TemplateArgument(ParamIn);
1001         Info.SecondArg = TemplateArgument(ArgIn);
1002         return Sema::TDK_NonDeducedMismatch;
1003       }
1004     }
1005 
1006     // C++11 [temp.deduct.partial]p7:
1007     //   Remove any top-level cv-qualifiers:
1008     //     - If P is a cv-qualified type, P is replaced by the cv-unqualified
1009     //       version of P.
1010     Param = Param.getUnqualifiedType();
1011     //     - If A is a cv-qualified type, A is replaced by the cv-unqualified
1012     //       version of A.
1013     Arg = Arg.getUnqualifiedType();
1014   } else {
1015     // C++0x [temp.deduct.call]p4 bullet 1:
1016     //   - If the original P is a reference type, the deduced A (i.e., the type
1017     //     referred to by the reference) can be more cv-qualified than the
1018     //     transformed A.
1019     if (TDF & TDF_ParamWithReferenceType) {
1020       Qualifiers Quals;
1021       QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1022       Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
1023                              Arg.getCVRQualifiers());
1024       Param = S.Context.getQualifiedType(UnqualParam, Quals);
1025     }
1026 
1027     if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1028       // C++0x [temp.deduct.type]p10:
1029       //   If P and A are function types that originated from deduction when
1030       //   taking the address of a function template (14.8.2.2) or when deducing
1031       //   template arguments from a function declaration (14.8.2.6) and Pi and
1032       //   Ai are parameters of the top-level parameter-type-list of P and A,
1033       //   respectively, Pi is adjusted if it is an rvalue reference to a
1034       //   cv-unqualified template parameter and Ai is an lvalue reference, in
1035       //   which case the type of Pi is changed to be the template parameter
1036       //   type (i.e., T&& is changed to simply T). [ Note: As a result, when
1037       //   Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1038       //   deduced as X&. - end note ]
1039       TDF &= ~TDF_TopLevelParameterTypeList;
1040 
1041       if (const RValueReferenceType *ParamRef
1042                                         = Param->getAs<RValueReferenceType>()) {
1043         if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1044             !ParamRef->getPointeeType().getQualifiers())
1045           if (Arg->isLValueReferenceType())
1046             Param = ParamRef->getPointeeType();
1047       }
1048     }
1049   }
1050 
1051   // C++ [temp.deduct.type]p9:
1052   //   A template type argument T, a template template argument TT or a
1053   //   template non-type argument i can be deduced if P and A have one of
1054   //   the following forms:
1055   //
1056   //     T
1057   //     cv-list T
1058   if (const TemplateTypeParmType *TemplateTypeParm
1059         = Param->getAs<TemplateTypeParmType>()) {
1060     // Just skip any attempts to deduce from a placeholder type.
1061     if (Arg->isPlaceholderType())
1062       return Sema::TDK_Success;
1063 
1064     unsigned Index = TemplateTypeParm->getIndex();
1065     bool RecanonicalizeArg = false;
1066 
1067     // If the argument type is an array type, move the qualifiers up to the
1068     // top level, so they can be matched with the qualifiers on the parameter.
1069     if (isa<ArrayType>(Arg)) {
1070       Qualifiers Quals;
1071       Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1072       if (Quals) {
1073         Arg = S.Context.getQualifiedType(Arg, Quals);
1074         RecanonicalizeArg = true;
1075       }
1076     }
1077 
1078     // The argument type can not be less qualified than the parameter
1079     // type.
1080     if (!(TDF & TDF_IgnoreQualifiers) &&
1081         hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
1082       Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1083       Info.FirstArg = TemplateArgument(Param);
1084       Info.SecondArg = TemplateArgument(Arg);
1085       return Sema::TDK_Underqualified;
1086     }
1087 
1088     assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
1089     assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
1090     QualType DeducedType = Arg;
1091 
1092     // Remove any qualifiers on the parameter from the deduced type.
1093     // We checked the qualifiers for consistency above.
1094     Qualifiers DeducedQs = DeducedType.getQualifiers();
1095     Qualifiers ParamQs = Param.getQualifiers();
1096     DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1097     if (ParamQs.hasObjCGCAttr())
1098       DeducedQs.removeObjCGCAttr();
1099     if (ParamQs.hasAddressSpace())
1100       DeducedQs.removeAddressSpace();
1101     if (ParamQs.hasObjCLifetime())
1102       DeducedQs.removeObjCLifetime();
1103 
1104     // Objective-C ARC:
1105     //   If template deduction would produce a lifetime qualifier on a type
1106     //   that is not a lifetime type, template argument deduction fails.
1107     if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1108         !DeducedType->isDependentType()) {
1109       Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1110       Info.FirstArg = TemplateArgument(Param);
1111       Info.SecondArg = TemplateArgument(Arg);
1112       return Sema::TDK_Underqualified;
1113     }
1114 
1115     // Objective-C ARC:
1116     //   If template deduction would produce an argument type with lifetime type
1117     //   but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1118     if (S.getLangOpts().ObjCAutoRefCount &&
1119         DeducedType->isObjCLifetimeType() &&
1120         !DeducedQs.hasObjCLifetime())
1121       DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1122 
1123     DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1124                                              DeducedQs);
1125 
1126     if (RecanonicalizeArg)
1127       DeducedType = S.Context.getCanonicalType(DeducedType);
1128 
1129     DeducedTemplateArgument NewDeduced(DeducedType);
1130     DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
1131                                                                  Deduced[Index],
1132                                                                    NewDeduced);
1133     if (Result.isNull()) {
1134       Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1135       Info.FirstArg = Deduced[Index];
1136       Info.SecondArg = NewDeduced;
1137       return Sema::TDK_Inconsistent;
1138     }
1139 
1140     Deduced[Index] = Result;
1141     return Sema::TDK_Success;
1142   }
1143 
1144   // Set up the template argument deduction information for a failure.
1145   Info.FirstArg = TemplateArgument(ParamIn);
1146   Info.SecondArg = TemplateArgument(ArgIn);
1147 
1148   // If the parameter is an already-substituted template parameter
1149   // pack, do nothing: we don't know which of its arguments to look
1150   // at, so we have to wait until all of the parameter packs in this
1151   // expansion have arguments.
1152   if (isa<SubstTemplateTypeParmPackType>(Param))
1153     return Sema::TDK_Success;
1154 
1155   // Check the cv-qualifiers on the parameter and argument types.
1156   CanQualType CanParam = S.Context.getCanonicalType(Param);
1157   CanQualType CanArg = S.Context.getCanonicalType(Arg);
1158   if (!(TDF & TDF_IgnoreQualifiers)) {
1159     if (TDF & TDF_ParamWithReferenceType) {
1160       if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
1161         return Sema::TDK_NonDeducedMismatch;
1162     } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
1163       if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
1164         return Sema::TDK_NonDeducedMismatch;
1165     }
1166 
1167     // If the parameter type is not dependent, there is nothing to deduce.
1168     if (!Param->isDependentType()) {
1169       if (!(TDF & TDF_SkipNonDependent)) {
1170         bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1171                           !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1172                           Param != Arg;
1173         if (NonDeduced) {
1174           return Sema::TDK_NonDeducedMismatch;
1175         }
1176       }
1177       return Sema::TDK_Success;
1178     }
1179   } else if (!Param->isDependentType()) {
1180     CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1181                 ArgUnqualType = CanArg.getUnqualifiedType();
1182     bool Success = (TDF & TDF_InOverloadResolution)?
1183                    S.isSameOrCompatibleFunctionType(ParamUnqualType,
1184                                                     ArgUnqualType) :
1185                    ParamUnqualType == ArgUnqualType;
1186     if (Success)
1187       return Sema::TDK_Success;
1188   }
1189 
1190   switch (Param->getTypeClass()) {
1191     // Non-canonical types cannot appear here.
1192 #define NON_CANONICAL_TYPE(Class, Base) \
1193   case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1194 #define TYPE(Class, Base)
1195 #include "clang/AST/TypeNodes.def"
1196 
1197     case Type::TemplateTypeParm:
1198     case Type::SubstTemplateTypeParmPack:
1199       llvm_unreachable("Type nodes handled above");
1200 
1201     // These types cannot be dependent, so simply check whether the types are
1202     // the same.
1203     case Type::Builtin:
1204     case Type::VariableArray:
1205     case Type::Vector:
1206     case Type::FunctionNoProto:
1207     case Type::Record:
1208     case Type::Enum:
1209     case Type::ObjCObject:
1210     case Type::ObjCInterface:
1211     case Type::ObjCObjectPointer: {
1212       if (TDF & TDF_SkipNonDependent)
1213         return Sema::TDK_Success;
1214 
1215       if (TDF & TDF_IgnoreQualifiers) {
1216         Param = Param.getUnqualifiedType();
1217         Arg = Arg.getUnqualifiedType();
1218       }
1219 
1220       return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1221     }
1222 
1223     //     _Complex T   [placeholder extension]
1224     case Type::Complex:
1225       if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
1226         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1227                                     cast<ComplexType>(Param)->getElementType(),
1228                                     ComplexArg->getElementType(),
1229                                     Info, Deduced, TDF);
1230 
1231       return Sema::TDK_NonDeducedMismatch;
1232 
1233     //     _Atomic T   [extension]
1234     case Type::Atomic:
1235       if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
1236         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1237                                        cast<AtomicType>(Param)->getValueType(),
1238                                        AtomicArg->getValueType(),
1239                                        Info, Deduced, TDF);
1240 
1241       return Sema::TDK_NonDeducedMismatch;
1242 
1243     //     T *
1244     case Type::Pointer: {
1245       QualType PointeeType;
1246       if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1247         PointeeType = PointerArg->getPointeeType();
1248       } else if (const ObjCObjectPointerType *PointerArg
1249                    = Arg->getAs<ObjCObjectPointerType>()) {
1250         PointeeType = PointerArg->getPointeeType();
1251       } else {
1252         return Sema::TDK_NonDeducedMismatch;
1253       }
1254 
1255       unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
1256       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1257                                      cast<PointerType>(Param)->getPointeeType(),
1258                                      PointeeType,
1259                                      Info, Deduced, SubTDF);
1260     }
1261 
1262     //     T &
1263     case Type::LValueReference: {
1264       const LValueReferenceType *ReferenceArg =
1265           Arg->getAs<LValueReferenceType>();
1266       if (!ReferenceArg)
1267         return Sema::TDK_NonDeducedMismatch;
1268 
1269       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1270                            cast<LValueReferenceType>(Param)->getPointeeType(),
1271                            ReferenceArg->getPointeeType(), Info, Deduced, 0);
1272     }
1273 
1274     //     T && [C++0x]
1275     case Type::RValueReference: {
1276       const RValueReferenceType *ReferenceArg =
1277           Arg->getAs<RValueReferenceType>();
1278       if (!ReferenceArg)
1279         return Sema::TDK_NonDeducedMismatch;
1280 
1281       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1282                              cast<RValueReferenceType>(Param)->getPointeeType(),
1283                              ReferenceArg->getPointeeType(),
1284                              Info, Deduced, 0);
1285     }
1286 
1287     //     T [] (implied, but not stated explicitly)
1288     case Type::IncompleteArray: {
1289       const IncompleteArrayType *IncompleteArrayArg =
1290         S.Context.getAsIncompleteArrayType(Arg);
1291       if (!IncompleteArrayArg)
1292         return Sema::TDK_NonDeducedMismatch;
1293 
1294       unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1295       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1296                     S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1297                     IncompleteArrayArg->getElementType(),
1298                     Info, Deduced, SubTDF);
1299     }
1300 
1301     //     T [integer-constant]
1302     case Type::ConstantArray: {
1303       const ConstantArrayType *ConstantArrayArg =
1304         S.Context.getAsConstantArrayType(Arg);
1305       if (!ConstantArrayArg)
1306         return Sema::TDK_NonDeducedMismatch;
1307 
1308       const ConstantArrayType *ConstantArrayParm =
1309         S.Context.getAsConstantArrayType(Param);
1310       if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
1311         return Sema::TDK_NonDeducedMismatch;
1312 
1313       unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1314       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1315                                            ConstantArrayParm->getElementType(),
1316                                            ConstantArrayArg->getElementType(),
1317                                            Info, Deduced, SubTDF);
1318     }
1319 
1320     //     type [i]
1321     case Type::DependentSizedArray: {
1322       const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
1323       if (!ArrayArg)
1324         return Sema::TDK_NonDeducedMismatch;
1325 
1326       unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1327 
1328       // Check the element type of the arrays
1329       const DependentSizedArrayType *DependentArrayParm
1330         = S.Context.getAsDependentSizedArrayType(Param);
1331       if (Sema::TemplateDeductionResult Result
1332             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1333                                           DependentArrayParm->getElementType(),
1334                                           ArrayArg->getElementType(),
1335                                           Info, Deduced, SubTDF))
1336         return Result;
1337 
1338       // Determine the array bound is something we can deduce.
1339       NonTypeTemplateParmDecl *NTTP
1340         = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1341       if (!NTTP)
1342         return Sema::TDK_Success;
1343 
1344       // We can perform template argument deduction for the given non-type
1345       // template parameter.
1346       assert(NTTP->getDepth() == 0 &&
1347              "Cannot deduce non-type template argument at depth > 0");
1348       if (const ConstantArrayType *ConstantArrayArg
1349             = dyn_cast<ConstantArrayType>(ArrayArg)) {
1350         llvm::APSInt Size(ConstantArrayArg->getSize());
1351         return DeduceNonTypeTemplateArgument(S, NTTP, Size,
1352                                              S.Context.getSizeType(),
1353                                              /*ArrayBound=*/true,
1354                                              Info, Deduced);
1355       }
1356       if (const DependentSizedArrayType *DependentArrayArg
1357             = dyn_cast<DependentSizedArrayType>(ArrayArg))
1358         if (DependentArrayArg->getSizeExpr())
1359           return DeduceNonTypeTemplateArgument(S, NTTP,
1360                                                DependentArrayArg->getSizeExpr(),
1361                                                Info, Deduced);
1362 
1363       // Incomplete type does not match a dependently-sized array type
1364       return Sema::TDK_NonDeducedMismatch;
1365     }
1366 
1367     //     type(*)(T)
1368     //     T(*)()
1369     //     T(*)(T)
1370     case Type::FunctionProto: {
1371       unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
1372       const FunctionProtoType *FunctionProtoArg =
1373         dyn_cast<FunctionProtoType>(Arg);
1374       if (!FunctionProtoArg)
1375         return Sema::TDK_NonDeducedMismatch;
1376 
1377       const FunctionProtoType *FunctionProtoParam =
1378         cast<FunctionProtoType>(Param);
1379 
1380       if (FunctionProtoParam->getTypeQuals()
1381             != FunctionProtoArg->getTypeQuals() ||
1382           FunctionProtoParam->getRefQualifier()
1383             != FunctionProtoArg->getRefQualifier() ||
1384           FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
1385         return Sema::TDK_NonDeducedMismatch;
1386 
1387       // Check return types.
1388       if (Sema::TemplateDeductionResult Result =
1389               DeduceTemplateArgumentsByTypeMatch(
1390                   S, TemplateParams, FunctionProtoParam->getReturnType(),
1391                   FunctionProtoArg->getReturnType(), Info, Deduced, 0))
1392         return Result;
1393 
1394       return DeduceTemplateArguments(
1395           S, TemplateParams, FunctionProtoParam->param_type_begin(),
1396           FunctionProtoParam->getNumParams(),
1397           FunctionProtoArg->param_type_begin(),
1398           FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
1399     }
1400 
1401     case Type::InjectedClassName: {
1402       // Treat a template's injected-class-name as if the template
1403       // specialization type had been used.
1404       Param = cast<InjectedClassNameType>(Param)
1405         ->getInjectedSpecializationType();
1406       assert(isa<TemplateSpecializationType>(Param) &&
1407              "injected class name is not a template specialization type");
1408       // fall through
1409     }
1410 
1411     //     template-name<T> (where template-name refers to a class template)
1412     //     template-name<i>
1413     //     TT<T>
1414     //     TT<i>
1415     //     TT<>
1416     case Type::TemplateSpecialization: {
1417       const TemplateSpecializationType *SpecParam =
1418           cast<TemplateSpecializationType>(Param);
1419 
1420       // When Arg cannot be a derived class, we can just try to deduce template
1421       // arguments from the template-id.
1422       const RecordType *RecordT = Arg->getAs<RecordType>();
1423       if (!(TDF & TDF_DerivedClass) || !RecordT)
1424         return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1425                                        Deduced);
1426 
1427       SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1428                                                           Deduced.end());
1429 
1430       Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1431           S, TemplateParams, SpecParam, Arg, Info, Deduced);
1432 
1433       if (Result == Sema::TDK_Success)
1434         return Result;
1435 
1436       // We cannot inspect base classes as part of deduction when the type
1437       // is incomplete, so either instantiate any templates necessary to
1438       // complete the type, or skip over it if it cannot be completed.
1439       if (!S.isCompleteType(Info.getLocation(), Arg))
1440         return Result;
1441 
1442       // C++14 [temp.deduct.call] p4b3:
1443       //   If P is a class and P has the form simple-template-id, then the
1444       //   transformed A can be a derived class of the deduced A. Likewise if
1445       //   P is a pointer to a class of the form simple-template-id, the
1446       //   transformed A can be a pointer to a derived class pointed to by the
1447       //   deduced A.
1448       //
1449       //   These alternatives are considered only if type deduction would
1450       //   otherwise fail. If they yield more than one possible deduced A, the
1451       //   type deduction fails.
1452 
1453       // Reset the incorrectly deduced argument from above.
1454       Deduced = DeducedOrig;
1455 
1456       // Use data recursion to crawl through the list of base classes.
1457       // Visited contains the set of nodes we have already visited, while
1458       // ToVisit is our stack of records that we still need to visit.
1459       llvm::SmallPtrSet<const RecordType *, 8> Visited;
1460       SmallVector<const RecordType *, 8> ToVisit;
1461       ToVisit.push_back(RecordT);
1462       bool Successful = false;
1463       SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
1464       while (!ToVisit.empty()) {
1465         // Retrieve the next class in the inheritance hierarchy.
1466         const RecordType *NextT = ToVisit.pop_back_val();
1467 
1468         // If we have already seen this type, skip it.
1469         if (!Visited.insert(NextT).second)
1470           continue;
1471 
1472         // If this is a base class, try to perform template argument
1473         // deduction from it.
1474         if (NextT != RecordT) {
1475           TemplateDeductionInfo BaseInfo(Info.getLocation());
1476           Sema::TemplateDeductionResult BaseResult =
1477               DeduceTemplateArguments(S, TemplateParams, SpecParam,
1478                                       QualType(NextT, 0), BaseInfo, Deduced);
1479 
1480           // If template argument deduction for this base was successful,
1481           // note that we had some success. Otherwise, ignore any deductions
1482           // from this base class.
1483           if (BaseResult == Sema::TDK_Success) {
1484             // If we've already seen some success, then deduction fails due to
1485             // an ambiguity (temp.deduct.call p5).
1486             if (Successful)
1487               return Sema::TDK_MiscellaneousDeductionFailure;
1488 
1489             Successful = true;
1490             std::swap(SuccessfulDeduced, Deduced);
1491 
1492             Info.Param = BaseInfo.Param;
1493             Info.FirstArg = BaseInfo.FirstArg;
1494             Info.SecondArg = BaseInfo.SecondArg;
1495           }
1496 
1497           Deduced = DeducedOrig;
1498         }
1499 
1500         // Visit base classes
1501         CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1502         for (const auto &Base : Next->bases()) {
1503           assert(Base.getType()->isRecordType() &&
1504                  "Base class that isn't a record?");
1505           ToVisit.push_back(Base.getType()->getAs<RecordType>());
1506         }
1507       }
1508 
1509       if (Successful) {
1510         std::swap(SuccessfulDeduced, Deduced);
1511         return Sema::TDK_Success;
1512       }
1513 
1514       return Result;
1515     }
1516 
1517     //     T type::*
1518     //     T T::*
1519     //     T (type::*)()
1520     //     type (T::*)()
1521     //     type (type::*)(T)
1522     //     type (T::*)(T)
1523     //     T (type::*)(T)
1524     //     T (T::*)()
1525     //     T (T::*)(T)
1526     case Type::MemberPointer: {
1527       const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1528       const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1529       if (!MemPtrArg)
1530         return Sema::TDK_NonDeducedMismatch;
1531 
1532       QualType ParamPointeeType = MemPtrParam->getPointeeType();
1533       if (ParamPointeeType->isFunctionType())
1534         S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1535                                  /*IsCtorOrDtor=*/false, Info.getLocation());
1536       QualType ArgPointeeType = MemPtrArg->getPointeeType();
1537       if (ArgPointeeType->isFunctionType())
1538         S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1539                                  /*IsCtorOrDtor=*/false, Info.getLocation());
1540 
1541       if (Sema::TemplateDeductionResult Result
1542             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1543                                                  ParamPointeeType,
1544                                                  ArgPointeeType,
1545                                                  Info, Deduced,
1546                                                  TDF & TDF_IgnoreQualifiers))
1547         return Result;
1548 
1549       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1550                                            QualType(MemPtrParam->getClass(), 0),
1551                                            QualType(MemPtrArg->getClass(), 0),
1552                                            Info, Deduced,
1553                                            TDF & TDF_IgnoreQualifiers);
1554     }
1555 
1556     //     (clang extension)
1557     //
1558     //     type(^)(T)
1559     //     T(^)()
1560     //     T(^)(T)
1561     case Type::BlockPointer: {
1562       const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1563       const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
1564 
1565       if (!BlockPtrArg)
1566         return Sema::TDK_NonDeducedMismatch;
1567 
1568       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1569                                                 BlockPtrParam->getPointeeType(),
1570                                                 BlockPtrArg->getPointeeType(),
1571                                                 Info, Deduced, 0);
1572     }
1573 
1574     //     (clang extension)
1575     //
1576     //     T __attribute__(((ext_vector_type(<integral constant>))))
1577     case Type::ExtVector: {
1578       const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1579       if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1580         // Make sure that the vectors have the same number of elements.
1581         if (VectorParam->getNumElements() != VectorArg->getNumElements())
1582           return Sema::TDK_NonDeducedMismatch;
1583 
1584         // Perform deduction on the element types.
1585         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1586                                                   VectorParam->getElementType(),
1587                                                   VectorArg->getElementType(),
1588                                                   Info, Deduced, TDF);
1589       }
1590 
1591       if (const DependentSizedExtVectorType *VectorArg
1592                                 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1593         // We can't check the number of elements, since the argument has a
1594         // dependent number of elements. This can only occur during partial
1595         // ordering.
1596 
1597         // Perform deduction on the element types.
1598         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1599                                                   VectorParam->getElementType(),
1600                                                   VectorArg->getElementType(),
1601                                                   Info, Deduced, TDF);
1602       }
1603 
1604       return Sema::TDK_NonDeducedMismatch;
1605     }
1606 
1607     //     (clang extension)
1608     //
1609     //     T __attribute__(((ext_vector_type(N))))
1610     case Type::DependentSizedExtVector: {
1611       const DependentSizedExtVectorType *VectorParam
1612         = cast<DependentSizedExtVectorType>(Param);
1613 
1614       if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1615         // Perform deduction on the element types.
1616         if (Sema::TemplateDeductionResult Result
1617               = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1618                                                   VectorParam->getElementType(),
1619                                                    VectorArg->getElementType(),
1620                                                    Info, Deduced, TDF))
1621           return Result;
1622 
1623         // Perform deduction on the vector size, if we can.
1624         NonTypeTemplateParmDecl *NTTP
1625           = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1626         if (!NTTP)
1627           return Sema::TDK_Success;
1628 
1629         llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1630         ArgSize = VectorArg->getNumElements();
1631         return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1632                                              false, Info, Deduced);
1633       }
1634 
1635       if (const DependentSizedExtVectorType *VectorArg
1636                                 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1637         // Perform deduction on the element types.
1638         if (Sema::TemplateDeductionResult Result
1639             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1640                                                  VectorParam->getElementType(),
1641                                                  VectorArg->getElementType(),
1642                                                  Info, Deduced, TDF))
1643           return Result;
1644 
1645         // Perform deduction on the vector size, if we can.
1646         NonTypeTemplateParmDecl *NTTP
1647           = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1648         if (!NTTP)
1649           return Sema::TDK_Success;
1650 
1651         return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1652                                              Info, Deduced);
1653       }
1654 
1655       return Sema::TDK_NonDeducedMismatch;
1656     }
1657 
1658     case Type::TypeOfExpr:
1659     case Type::TypeOf:
1660     case Type::DependentName:
1661     case Type::UnresolvedUsing:
1662     case Type::Decltype:
1663     case Type::UnaryTransform:
1664     case Type::Auto:
1665     case Type::DependentTemplateSpecialization:
1666     case Type::PackExpansion:
1667     case Type::Pipe:
1668       // No template argument deduction for these types
1669       return Sema::TDK_Success;
1670   }
1671 
1672   llvm_unreachable("Invalid Type Class!");
1673 }
1674 
1675 static Sema::TemplateDeductionResult
1676 DeduceTemplateArguments(Sema &S,
1677                         TemplateParameterList *TemplateParams,
1678                         const TemplateArgument &Param,
1679                         TemplateArgument Arg,
1680                         TemplateDeductionInfo &Info,
1681                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1682   // If the template argument is a pack expansion, perform template argument
1683   // deduction against the pattern of that expansion. This only occurs during
1684   // partial ordering.
1685   if (Arg.isPackExpansion())
1686     Arg = Arg.getPackExpansionPattern();
1687 
1688   switch (Param.getKind()) {
1689   case TemplateArgument::Null:
1690     llvm_unreachable("Null template argument in parameter list");
1691 
1692   case TemplateArgument::Type:
1693     if (Arg.getKind() == TemplateArgument::Type)
1694       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1695                                                 Param.getAsType(),
1696                                                 Arg.getAsType(),
1697                                                 Info, Deduced, 0);
1698     Info.FirstArg = Param;
1699     Info.SecondArg = Arg;
1700     return Sema::TDK_NonDeducedMismatch;
1701 
1702   case TemplateArgument::Template:
1703     if (Arg.getKind() == TemplateArgument::Template)
1704       return DeduceTemplateArguments(S, TemplateParams,
1705                                      Param.getAsTemplate(),
1706                                      Arg.getAsTemplate(), Info, Deduced);
1707     Info.FirstArg = Param;
1708     Info.SecondArg = Arg;
1709     return Sema::TDK_NonDeducedMismatch;
1710 
1711   case TemplateArgument::TemplateExpansion:
1712     llvm_unreachable("caller should handle pack expansions");
1713 
1714   case TemplateArgument::Declaration:
1715     if (Arg.getKind() == TemplateArgument::Declaration &&
1716         isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
1717       return Sema::TDK_Success;
1718 
1719     Info.FirstArg = Param;
1720     Info.SecondArg = Arg;
1721     return Sema::TDK_NonDeducedMismatch;
1722 
1723   case TemplateArgument::NullPtr:
1724     if (Arg.getKind() == TemplateArgument::NullPtr &&
1725         S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
1726       return Sema::TDK_Success;
1727 
1728     Info.FirstArg = Param;
1729     Info.SecondArg = Arg;
1730     return Sema::TDK_NonDeducedMismatch;
1731 
1732   case TemplateArgument::Integral:
1733     if (Arg.getKind() == TemplateArgument::Integral) {
1734       if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
1735         return Sema::TDK_Success;
1736 
1737       Info.FirstArg = Param;
1738       Info.SecondArg = Arg;
1739       return Sema::TDK_NonDeducedMismatch;
1740     }
1741 
1742     if (Arg.getKind() == TemplateArgument::Expression) {
1743       Info.FirstArg = Param;
1744       Info.SecondArg = Arg;
1745       return Sema::TDK_NonDeducedMismatch;
1746     }
1747 
1748     Info.FirstArg = Param;
1749     Info.SecondArg = Arg;
1750     return Sema::TDK_NonDeducedMismatch;
1751 
1752   case TemplateArgument::Expression: {
1753     if (NonTypeTemplateParmDecl *NTTP
1754           = getDeducedParameterFromExpr(Param.getAsExpr())) {
1755       if (Arg.getKind() == TemplateArgument::Integral)
1756         return DeduceNonTypeTemplateArgument(S, NTTP,
1757                                              Arg.getAsIntegral(),
1758                                              Arg.getIntegralType(),
1759                                              /*ArrayBound=*/false,
1760                                              Info, Deduced);
1761       if (Arg.getKind() == TemplateArgument::Expression)
1762         return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
1763                                              Info, Deduced);
1764       if (Arg.getKind() == TemplateArgument::Declaration)
1765         return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
1766                                              Info, Deduced);
1767 
1768       Info.FirstArg = Param;
1769       Info.SecondArg = Arg;
1770       return Sema::TDK_NonDeducedMismatch;
1771     }
1772 
1773     // Can't deduce anything, but that's okay.
1774     return Sema::TDK_Success;
1775   }
1776   case TemplateArgument::Pack:
1777     llvm_unreachable("Argument packs should be expanded by the caller!");
1778   }
1779 
1780   llvm_unreachable("Invalid TemplateArgument Kind!");
1781 }
1782 
1783 /// \brief Determine whether there is a template argument to be used for
1784 /// deduction.
1785 ///
1786 /// This routine "expands" argument packs in-place, overriding its input
1787 /// parameters so that \c Args[ArgIdx] will be the available template argument.
1788 ///
1789 /// \returns true if there is another template argument (which will be at
1790 /// \c Args[ArgIdx]), false otherwise.
1791 static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1792                                             unsigned &ArgIdx,
1793                                             unsigned &NumArgs) {
1794   if (ArgIdx == NumArgs)
1795     return false;
1796 
1797   const TemplateArgument &Arg = Args[ArgIdx];
1798   if (Arg.getKind() != TemplateArgument::Pack)
1799     return true;
1800 
1801   assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1802   Args = Arg.pack_begin();
1803   NumArgs = Arg.pack_size();
1804   ArgIdx = 0;
1805   return ArgIdx < NumArgs;
1806 }
1807 
1808 /// \brief Determine whether the given set of template arguments has a pack
1809 /// expansion that is not the last template argument.
1810 static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1811                                       unsigned NumArgs) {
1812   unsigned ArgIdx = 0;
1813   while (ArgIdx < NumArgs) {
1814     const TemplateArgument &Arg = Args[ArgIdx];
1815 
1816     // Unwrap argument packs.
1817     if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1818       Args = Arg.pack_begin();
1819       NumArgs = Arg.pack_size();
1820       ArgIdx = 0;
1821       continue;
1822     }
1823 
1824     ++ArgIdx;
1825     if (ArgIdx == NumArgs)
1826       return false;
1827 
1828     if (Arg.isPackExpansion())
1829       return true;
1830   }
1831 
1832   return false;
1833 }
1834 
1835 static Sema::TemplateDeductionResult
1836 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
1837                         const TemplateArgument *Params, unsigned NumParams,
1838                         const TemplateArgument *Args, unsigned NumArgs,
1839                         TemplateDeductionInfo &Info,
1840                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1841                         bool NumberOfArgumentsMustMatch) {
1842   // C++0x [temp.deduct.type]p9:
1843   //   If the template argument list of P contains a pack expansion that is not
1844   //   the last template argument, the entire template argument list is a
1845   //   non-deduced context.
1846   if (hasPackExpansionBeforeEnd(Params, NumParams))
1847     return Sema::TDK_Success;
1848 
1849   // C++0x [temp.deduct.type]p9:
1850   //   If P has a form that contains <T> or <i>, then each argument Pi of the
1851   //   respective template argument list P is compared with the corresponding
1852   //   argument Ai of the corresponding template argument list of A.
1853   unsigned ArgIdx = 0, ParamIdx = 0;
1854   for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1855        ++ParamIdx) {
1856     if (!Params[ParamIdx].isPackExpansion()) {
1857       // The simple case: deduce template arguments by matching Pi and Ai.
1858 
1859       // Check whether we have enough arguments.
1860       if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
1861         return NumberOfArgumentsMustMatch ? Sema::TDK_TooFewArguments
1862                                           : Sema::TDK_Success;
1863 
1864       if (Args[ArgIdx].isPackExpansion()) {
1865         // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1866         // but applied to pack expansions that are template arguments.
1867         return Sema::TDK_MiscellaneousDeductionFailure;
1868       }
1869 
1870       // Perform deduction for this Pi/Ai pair.
1871       if (Sema::TemplateDeductionResult Result
1872             = DeduceTemplateArguments(S, TemplateParams,
1873                                       Params[ParamIdx], Args[ArgIdx],
1874                                       Info, Deduced))
1875         return Result;
1876 
1877       // Move to the next argument.
1878       ++ArgIdx;
1879       continue;
1880     }
1881 
1882     // The parameter is a pack expansion.
1883 
1884     // C++0x [temp.deduct.type]p9:
1885     //   If Pi is a pack expansion, then the pattern of Pi is compared with
1886     //   each remaining argument in the template argument list of A. Each
1887     //   comparison deduces template arguments for subsequent positions in the
1888     //   template parameter packs expanded by Pi.
1889     TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1890 
1891     // FIXME: If there are no remaining arguments, we can bail out early
1892     // and set any deduced parameter packs to an empty argument pack.
1893     // The latter part of this is a (minor) correctness issue.
1894 
1895     // Prepare to deduce the packs within the pattern.
1896     PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1897 
1898     // Keep track of the deduced template arguments for each parameter pack
1899     // expanded by this pack expansion (the outer index) and for each
1900     // template argument (the inner SmallVectors).
1901     bool HasAnyArguments = false;
1902     for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
1903       HasAnyArguments = true;
1904 
1905       // Deduce template arguments from the pattern.
1906       if (Sema::TemplateDeductionResult Result
1907             = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1908                                       Info, Deduced))
1909         return Result;
1910 
1911       PackScope.nextPackElement();
1912     }
1913 
1914     // Build argument packs for each of the parameter packs expanded by this
1915     // pack expansion.
1916     if (auto Result = PackScope.finish(HasAnyArguments))
1917       return Result;
1918   }
1919 
1920   return Sema::TDK_Success;
1921 }
1922 
1923 static Sema::TemplateDeductionResult
1924 DeduceTemplateArguments(Sema &S,
1925                         TemplateParameterList *TemplateParams,
1926                         const TemplateArgumentList &ParamList,
1927                         const TemplateArgumentList &ArgList,
1928                         TemplateDeductionInfo &Info,
1929                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1930   return DeduceTemplateArguments(S, TemplateParams,
1931                                  ParamList.data(), ParamList.size(),
1932                                  ArgList.data(), ArgList.size(),
1933                                  Info, Deduced, false);
1934 }
1935 
1936 /// \brief Determine whether two template arguments are the same.
1937 static bool isSameTemplateArg(ASTContext &Context,
1938                               const TemplateArgument &X,
1939                               const TemplateArgument &Y) {
1940   if (X.getKind() != Y.getKind())
1941     return false;
1942 
1943   switch (X.getKind()) {
1944     case TemplateArgument::Null:
1945       llvm_unreachable("Comparing NULL template argument");
1946 
1947     case TemplateArgument::Type:
1948       return Context.getCanonicalType(X.getAsType()) ==
1949              Context.getCanonicalType(Y.getAsType());
1950 
1951     case TemplateArgument::Declaration:
1952       return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
1953 
1954     case TemplateArgument::NullPtr:
1955       return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
1956 
1957     case TemplateArgument::Template:
1958     case TemplateArgument::TemplateExpansion:
1959       return Context.getCanonicalTemplateName(
1960                     X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1961              Context.getCanonicalTemplateName(
1962                     Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
1963 
1964     case TemplateArgument::Integral:
1965       return X.getAsIntegral() == Y.getAsIntegral();
1966 
1967     case TemplateArgument::Expression: {
1968       llvm::FoldingSetNodeID XID, YID;
1969       X.getAsExpr()->Profile(XID, Context, true);
1970       Y.getAsExpr()->Profile(YID, Context, true);
1971       return XID == YID;
1972     }
1973 
1974     case TemplateArgument::Pack:
1975       if (X.pack_size() != Y.pack_size())
1976         return false;
1977 
1978       for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1979                                         XPEnd = X.pack_end(),
1980                                            YP = Y.pack_begin();
1981            XP != XPEnd; ++XP, ++YP)
1982         if (!isSameTemplateArg(Context, *XP, *YP))
1983           return false;
1984 
1985       return true;
1986   }
1987 
1988   llvm_unreachable("Invalid TemplateArgument Kind!");
1989 }
1990 
1991 /// \brief Allocate a TemplateArgumentLoc where all locations have
1992 /// been initialized to the given location.
1993 ///
1994 /// \param Arg The template argument we are producing template argument
1995 /// location information for.
1996 ///
1997 /// \param NTTPType For a declaration template argument, the type of
1998 /// the non-type template parameter that corresponds to this template
1999 /// argument.
2000 ///
2001 /// \param Loc The source location to use for the resulting template
2002 /// argument.
2003 TemplateArgumentLoc
2004 Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2005                                     QualType NTTPType, SourceLocation Loc) {
2006   switch (Arg.getKind()) {
2007   case TemplateArgument::Null:
2008     llvm_unreachable("Can't get a NULL template argument here");
2009 
2010   case TemplateArgument::Type:
2011     return TemplateArgumentLoc(
2012         Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2013 
2014   case TemplateArgument::Declaration: {
2015     Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2016                   .getAs<Expr>();
2017     return TemplateArgumentLoc(TemplateArgument(E), E);
2018   }
2019 
2020   case TemplateArgument::NullPtr: {
2021     Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2022                   .getAs<Expr>();
2023     return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2024                                E);
2025   }
2026 
2027   case TemplateArgument::Integral: {
2028     Expr *E =
2029         BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
2030     return TemplateArgumentLoc(TemplateArgument(E), E);
2031   }
2032 
2033     case TemplateArgument::Template:
2034     case TemplateArgument::TemplateExpansion: {
2035       NestedNameSpecifierLocBuilder Builder;
2036       TemplateName Template = Arg.getAsTemplate();
2037       if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2038         Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2039       else if (QualifiedTemplateName *QTN =
2040                    Template.getAsQualifiedTemplateName())
2041         Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2042 
2043       if (Arg.getKind() == TemplateArgument::Template)
2044         return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2045                                    Loc);
2046 
2047       return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2048                                  Loc, Loc);
2049     }
2050 
2051   case TemplateArgument::Expression:
2052     return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2053 
2054   case TemplateArgument::Pack:
2055     return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2056   }
2057 
2058   llvm_unreachable("Invalid TemplateArgument Kind!");
2059 }
2060 
2061 
2062 /// \brief Convert the given deduced template argument and add it to the set of
2063 /// fully-converted template arguments.
2064 static bool
2065 ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2066                                DeducedTemplateArgument Arg,
2067                                NamedDecl *Template,
2068                                TemplateDeductionInfo &Info,
2069                                bool InFunctionTemplate,
2070                                SmallVectorImpl<TemplateArgument> &Output) {
2071   // First, for a non-type template parameter type that is
2072   // initialized by a declaration, we need the type of the
2073   // corresponding non-type template parameter.
2074   QualType NTTPType;
2075   if (NonTypeTemplateParmDecl *NTTP =
2076           dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2077     NTTPType = NTTP->getType();
2078     if (NTTPType->isDependentType()) {
2079       TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
2080       NTTPType = S.SubstType(NTTPType,
2081                              MultiLevelTemplateArgumentList(TemplateArgs),
2082                              NTTP->getLocation(),
2083                              NTTP->getDeclName());
2084       if (NTTPType.isNull())
2085         return true;
2086     }
2087   }
2088 
2089   auto ConvertArg = [&](DeducedTemplateArgument Arg,
2090                         unsigned ArgumentPackIndex) {
2091     // Convert the deduced template argument into a template
2092     // argument that we can check, almost as if the user had written
2093     // the template argument explicitly.
2094     TemplateArgumentLoc ArgLoc =
2095         S.getTrivialTemplateArgumentLoc(Arg, NTTPType, Info.getLocation());
2096 
2097     // Check the template argument, converting it as necessary.
2098     return S.CheckTemplateArgument(
2099         Param, ArgLoc, Template, Template->getLocation(),
2100         Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2101         InFunctionTemplate
2102             ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2103                                               : Sema::CTAK_Deduced)
2104             : Sema::CTAK_Specified);
2105   };
2106 
2107   if (Arg.getKind() == TemplateArgument::Pack) {
2108     // This is a template argument pack, so check each of its arguments against
2109     // the template parameter.
2110     SmallVector<TemplateArgument, 2> PackedArgsBuilder;
2111     for (const auto &P : Arg.pack_elements()) {
2112       // When converting the deduced template argument, append it to the
2113       // general output list. We need to do this so that the template argument
2114       // checking logic has all of the prior template arguments available.
2115       DeducedTemplateArgument InnerArg(P);
2116       InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
2117       assert(InnerArg.getKind() != TemplateArgument::Pack &&
2118              "deduced nested pack");
2119       if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
2120         return true;
2121 
2122       // Move the converted template argument into our argument pack.
2123       PackedArgsBuilder.push_back(Output.pop_back_val());
2124     }
2125 
2126     // If the pack is empty, we still need to substitute into the parameter
2127     // itself, in case that substitution fails. For non-type parameters, we did
2128     // this above. For type parameters, no substitution is ever required.
2129     auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param);
2130     if (TTP && PackedArgsBuilder.empty()) {
2131       // Set up a template instantiation context.
2132       LocalInstantiationScope Scope(S);
2133       Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2134                                        TTP, Output,
2135                                        Template->getSourceRange());
2136       if (Inst.isInvalid())
2137         return true;
2138 
2139       TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
2140       if (!S.SubstDecl(TTP, S.CurContext,
2141                        MultiLevelTemplateArgumentList(TemplateArgs)))
2142         return true;
2143     }
2144 
2145     // Create the resulting argument pack.
2146     Output.push_back(
2147         TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
2148     return false;
2149   }
2150 
2151   return ConvertArg(Arg, 0);
2152 }
2153 
2154 /// Complete template argument deduction for a class template partial
2155 /// specialization.
2156 static Sema::TemplateDeductionResult
2157 FinishTemplateArgumentDeduction(Sema &S,
2158                                 ClassTemplatePartialSpecializationDecl *Partial,
2159                                 const TemplateArgumentList &TemplateArgs,
2160                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2161                                 TemplateDeductionInfo &Info) {
2162   // Unevaluated SFINAE context.
2163   EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2164   Sema::SFINAETrap Trap(S);
2165 
2166   Sema::ContextRAII SavedContext(S, Partial);
2167 
2168   // C++ [temp.deduct.type]p2:
2169   //   [...] or if any template argument remains neither deduced nor
2170   //   explicitly specified, template argument deduction fails.
2171   SmallVector<TemplateArgument, 4> Builder;
2172   TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2173   for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2174     NamedDecl *Param = PartialParams->getParam(I);
2175     if (Deduced[I].isNull()) {
2176       Info.Param = makeTemplateParameter(Param);
2177       return Sema::TDK_Incomplete;
2178     }
2179 
2180     // We have deduced this argument, so it still needs to be
2181     // checked and converted.
2182     if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
2183                                        Partial, Info, false,
2184                                        Builder)) {
2185       Info.Param = makeTemplateParameter(Param);
2186       // FIXME: These template arguments are temporary. Free them!
2187       Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2188       return Sema::TDK_SubstitutionFailure;
2189     }
2190   }
2191 
2192   // Form the template argument list from the deduced template arguments.
2193   TemplateArgumentList *DeducedArgumentList
2194     = TemplateArgumentList::CreateCopy(S.Context, Builder);
2195 
2196   Info.reset(DeducedArgumentList);
2197 
2198   // Substitute the deduced template arguments into the template
2199   // arguments of the class template partial specialization, and
2200   // verify that the instantiated template arguments are both valid
2201   // and are equivalent to the template arguments originally provided
2202   // to the class template.
2203   LocalInstantiationScope InstScope(S);
2204   ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
2205   const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2206     = Partial->getTemplateArgsAsWritten();
2207   const TemplateArgumentLoc *PartialTemplateArgs
2208     = PartialTemplArgInfo->getTemplateArgs();
2209 
2210   TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2211                                     PartialTemplArgInfo->RAngleLoc);
2212 
2213   if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2214               InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2215     unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2216     if (ParamIdx >= Partial->getTemplateParameters()->size())
2217       ParamIdx = Partial->getTemplateParameters()->size() - 1;
2218 
2219     Decl *Param
2220       = const_cast<NamedDecl *>(
2221                           Partial->getTemplateParameters()->getParam(ParamIdx));
2222     Info.Param = makeTemplateParameter(Param);
2223     Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2224     return Sema::TDK_SubstitutionFailure;
2225   }
2226 
2227   SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2228   if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
2229                                   InstArgs, false, ConvertedInstArgs))
2230     return Sema::TDK_SubstitutionFailure;
2231 
2232   TemplateParameterList *TemplateParams
2233     = ClassTemplate->getTemplateParameters();
2234   for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2235     TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2236     if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2237       Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2238       Info.FirstArg = TemplateArgs[I];
2239       Info.SecondArg = InstArg;
2240       return Sema::TDK_NonDeducedMismatch;
2241     }
2242   }
2243 
2244   if (Trap.hasErrorOccurred())
2245     return Sema::TDK_SubstitutionFailure;
2246 
2247   return Sema::TDK_Success;
2248 }
2249 
2250 /// \brief Perform template argument deduction to determine whether
2251 /// the given template arguments match the given class template
2252 /// partial specialization per C++ [temp.class.spec.match].
2253 Sema::TemplateDeductionResult
2254 Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
2255                               const TemplateArgumentList &TemplateArgs,
2256                               TemplateDeductionInfo &Info) {
2257   if (Partial->isInvalidDecl())
2258     return TDK_Invalid;
2259 
2260   // C++ [temp.class.spec.match]p2:
2261   //   A partial specialization matches a given actual template
2262   //   argument list if the template arguments of the partial
2263   //   specialization can be deduced from the actual template argument
2264   //   list (14.8.2).
2265 
2266   // Unevaluated SFINAE context.
2267   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2268   SFINAETrap Trap(*this);
2269 
2270   SmallVector<DeducedTemplateArgument, 4> Deduced;
2271   Deduced.resize(Partial->getTemplateParameters()->size());
2272   if (TemplateDeductionResult Result
2273         = ::DeduceTemplateArguments(*this,
2274                                     Partial->getTemplateParameters(),
2275                                     Partial->getTemplateArgs(),
2276                                     TemplateArgs, Info, Deduced))
2277     return Result;
2278 
2279   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2280   InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2281                              Info);
2282   if (Inst.isInvalid())
2283     return TDK_InstantiationDepth;
2284 
2285   if (Trap.hasErrorOccurred())
2286     return Sema::TDK_SubstitutionFailure;
2287 
2288   return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2289                                            Deduced, Info);
2290 }
2291 
2292 /// Complete template argument deduction for a variable template partial
2293 /// specialization.
2294 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2295 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
2296 ///        VarTemplate(Partial)SpecializationDecl with a new data
2297 ///        structure Template(Partial)SpecializationDecl, and
2298 ///        using Template(Partial)SpecializationDecl as input type.
2299 static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2300     Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2301     const TemplateArgumentList &TemplateArgs,
2302     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2303     TemplateDeductionInfo &Info) {
2304   // Unevaluated SFINAE context.
2305   EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2306   Sema::SFINAETrap Trap(S);
2307 
2308   // C++ [temp.deduct.type]p2:
2309   //   [...] or if any template argument remains neither deduced nor
2310   //   explicitly specified, template argument deduction fails.
2311   SmallVector<TemplateArgument, 4> Builder;
2312   TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2313   for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2314     NamedDecl *Param = PartialParams->getParam(I);
2315     if (Deduced[I].isNull()) {
2316       Info.Param = makeTemplateParameter(Param);
2317       return Sema::TDK_Incomplete;
2318     }
2319 
2320     // We have deduced this argument, so it still needs to be
2321     // checked and converted.
2322     if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial,
2323                                        Info, false, Builder)) {
2324       Info.Param = makeTemplateParameter(Param);
2325       // FIXME: These template arguments are temporary. Free them!
2326       Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2327       return Sema::TDK_SubstitutionFailure;
2328     }
2329   }
2330 
2331   // Form the template argument list from the deduced template arguments.
2332   TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
2333       S.Context, Builder);
2334 
2335   Info.reset(DeducedArgumentList);
2336 
2337   // Substitute the deduced template arguments into the template
2338   // arguments of the class template partial specialization, and
2339   // verify that the instantiated template arguments are both valid
2340   // and are equivalent to the template arguments originally provided
2341   // to the class template.
2342   LocalInstantiationScope InstScope(S);
2343   VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
2344   const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2345     = Partial->getTemplateArgsAsWritten();
2346   const TemplateArgumentLoc *PartialTemplateArgs
2347     = PartialTemplArgInfo->getTemplateArgs();
2348 
2349   TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2350                                     PartialTemplArgInfo->RAngleLoc);
2351 
2352   if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2353               InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2354     unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2355     if (ParamIdx >= Partial->getTemplateParameters()->size())
2356       ParamIdx = Partial->getTemplateParameters()->size() - 1;
2357 
2358     Decl *Param = const_cast<NamedDecl *>(
2359         Partial->getTemplateParameters()->getParam(ParamIdx));
2360     Info.Param = makeTemplateParameter(Param);
2361     Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2362     return Sema::TDK_SubstitutionFailure;
2363   }
2364   SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2365   if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2366                                   false, ConvertedInstArgs))
2367     return Sema::TDK_SubstitutionFailure;
2368 
2369   TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2370   for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2371     TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2372     if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2373       Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2374       Info.FirstArg = TemplateArgs[I];
2375       Info.SecondArg = InstArg;
2376       return Sema::TDK_NonDeducedMismatch;
2377     }
2378   }
2379 
2380   if (Trap.hasErrorOccurred())
2381     return Sema::TDK_SubstitutionFailure;
2382 
2383   return Sema::TDK_Success;
2384 }
2385 
2386 /// \brief Perform template argument deduction to determine whether
2387 /// the given template arguments match the given variable template
2388 /// partial specialization per C++ [temp.class.spec.match].
2389 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2390 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
2391 ///        VarTemplate(Partial)SpecializationDecl with a new data
2392 ///        structure Template(Partial)SpecializationDecl, and
2393 ///        using Template(Partial)SpecializationDecl as input type.
2394 Sema::TemplateDeductionResult
2395 Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2396                               const TemplateArgumentList &TemplateArgs,
2397                               TemplateDeductionInfo &Info) {
2398   if (Partial->isInvalidDecl())
2399     return TDK_Invalid;
2400 
2401   // C++ [temp.class.spec.match]p2:
2402   //   A partial specialization matches a given actual template
2403   //   argument list if the template arguments of the partial
2404   //   specialization can be deduced from the actual template argument
2405   //   list (14.8.2).
2406 
2407   // Unevaluated SFINAE context.
2408   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2409   SFINAETrap Trap(*this);
2410 
2411   SmallVector<DeducedTemplateArgument, 4> Deduced;
2412   Deduced.resize(Partial->getTemplateParameters()->size());
2413   if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2414           *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2415           TemplateArgs, Info, Deduced))
2416     return Result;
2417 
2418   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2419   InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2420                              Info);
2421   if (Inst.isInvalid())
2422     return TDK_InstantiationDepth;
2423 
2424   if (Trap.hasErrorOccurred())
2425     return Sema::TDK_SubstitutionFailure;
2426 
2427   return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2428                                            Deduced, Info);
2429 }
2430 
2431 /// \brief Determine whether the given type T is a simple-template-id type.
2432 static bool isSimpleTemplateIdType(QualType T) {
2433   if (const TemplateSpecializationType *Spec
2434         = T->getAs<TemplateSpecializationType>())
2435     return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
2436 
2437   return false;
2438 }
2439 
2440 /// \brief Substitute the explicitly-provided template arguments into the
2441 /// given function template according to C++ [temp.arg.explicit].
2442 ///
2443 /// \param FunctionTemplate the function template into which the explicit
2444 /// template arguments will be substituted.
2445 ///
2446 /// \param ExplicitTemplateArgs the explicitly-specified template
2447 /// arguments.
2448 ///
2449 /// \param Deduced the deduced template arguments, which will be populated
2450 /// with the converted and checked explicit template arguments.
2451 ///
2452 /// \param ParamTypes will be populated with the instantiated function
2453 /// parameters.
2454 ///
2455 /// \param FunctionType if non-NULL, the result type of the function template
2456 /// will also be instantiated and the pointed-to value will be updated with
2457 /// the instantiated function type.
2458 ///
2459 /// \param Info if substitution fails for any reason, this object will be
2460 /// populated with more information about the failure.
2461 ///
2462 /// \returns TDK_Success if substitution was successful, or some failure
2463 /// condition.
2464 Sema::TemplateDeductionResult
2465 Sema::SubstituteExplicitTemplateArguments(
2466                                       FunctionTemplateDecl *FunctionTemplate,
2467                                TemplateArgumentListInfo &ExplicitTemplateArgs,
2468                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2469                                  SmallVectorImpl<QualType> &ParamTypes,
2470                                           QualType *FunctionType,
2471                                           TemplateDeductionInfo &Info) {
2472   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2473   TemplateParameterList *TemplateParams
2474     = FunctionTemplate->getTemplateParameters();
2475 
2476   if (ExplicitTemplateArgs.size() == 0) {
2477     // No arguments to substitute; just copy over the parameter types and
2478     // fill in the function type.
2479     for (auto P : Function->parameters())
2480       ParamTypes.push_back(P->getType());
2481 
2482     if (FunctionType)
2483       *FunctionType = Function->getType();
2484     return TDK_Success;
2485   }
2486 
2487   // Unevaluated SFINAE context.
2488   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2489   SFINAETrap Trap(*this);
2490 
2491   // C++ [temp.arg.explicit]p3:
2492   //   Template arguments that are present shall be specified in the
2493   //   declaration order of their corresponding template-parameters. The
2494   //   template argument list shall not specify more template-arguments than
2495   //   there are corresponding template-parameters.
2496   SmallVector<TemplateArgument, 4> Builder;
2497 
2498   // Enter a new template instantiation context where we check the
2499   // explicitly-specified template arguments against this function template,
2500   // and then substitute them into the function parameter types.
2501   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2502   InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2503                              DeducedArgs,
2504            ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2505                              Info);
2506   if (Inst.isInvalid())
2507     return TDK_InstantiationDepth;
2508 
2509   if (CheckTemplateArgumentList(FunctionTemplate,
2510                                 SourceLocation(),
2511                                 ExplicitTemplateArgs,
2512                                 true,
2513                                 Builder) || Trap.hasErrorOccurred()) {
2514     unsigned Index = Builder.size();
2515     if (Index >= TemplateParams->size())
2516       Index = TemplateParams->size() - 1;
2517     Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
2518     return TDK_InvalidExplicitArguments;
2519   }
2520 
2521   // Form the template argument list from the explicitly-specified
2522   // template arguments.
2523   TemplateArgumentList *ExplicitArgumentList
2524     = TemplateArgumentList::CreateCopy(Context, Builder);
2525   Info.reset(ExplicitArgumentList);
2526 
2527   // Template argument deduction and the final substitution should be
2528   // done in the context of the templated declaration.  Explicit
2529   // argument substitution, on the other hand, needs to happen in the
2530   // calling context.
2531   ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2532 
2533   // If we deduced template arguments for a template parameter pack,
2534   // note that the template argument pack is partially substituted and record
2535   // the explicit template arguments. They'll be used as part of deduction
2536   // for this template parameter pack.
2537   for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2538     const TemplateArgument &Arg = Builder[I];
2539     if (Arg.getKind() == TemplateArgument::Pack) {
2540       CurrentInstantiationScope->SetPartiallySubstitutedPack(
2541                                                  TemplateParams->getParam(I),
2542                                                              Arg.pack_begin(),
2543                                                              Arg.pack_size());
2544       break;
2545     }
2546   }
2547 
2548   const FunctionProtoType *Proto
2549     = Function->getType()->getAs<FunctionProtoType>();
2550   assert(Proto && "Function template does not have a prototype?");
2551 
2552   // Isolate our substituted parameters from our caller.
2553   LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2554 
2555   ExtParameterInfoBuilder ExtParamInfos;
2556 
2557   // Instantiate the types of each of the function parameters given the
2558   // explicitly-specified template arguments. If the function has a trailing
2559   // return type, substitute it after the arguments to ensure we substitute
2560   // in lexical order.
2561   if (Proto->hasTrailingReturn()) {
2562     if (SubstParmTypes(Function->getLocation(), Function->parameters(),
2563                        Proto->getExtParameterInfosOrNull(),
2564                        MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2565                        ParamTypes, /*params*/ nullptr, ExtParamInfos))
2566       return TDK_SubstitutionFailure;
2567   }
2568 
2569   // Instantiate the return type.
2570   QualType ResultType;
2571   {
2572     // C++11 [expr.prim.general]p3:
2573     //   If a declaration declares a member function or member function
2574     //   template of a class X, the expression this is a prvalue of type
2575     //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2576     //   and the end of the function-definition, member-declarator, or
2577     //   declarator.
2578     unsigned ThisTypeQuals = 0;
2579     CXXRecordDecl *ThisContext = nullptr;
2580     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2581       ThisContext = Method->getParent();
2582       ThisTypeQuals = Method->getTypeQualifiers();
2583     }
2584 
2585     CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
2586                                getLangOpts().CPlusPlus11);
2587 
2588     ResultType =
2589         SubstType(Proto->getReturnType(),
2590                   MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2591                   Function->getTypeSpecStartLoc(), Function->getDeclName());
2592     if (ResultType.isNull() || Trap.hasErrorOccurred())
2593       return TDK_SubstitutionFailure;
2594   }
2595 
2596   // Instantiate the types of each of the function parameters given the
2597   // explicitly-specified template arguments if we didn't do so earlier.
2598   if (!Proto->hasTrailingReturn() &&
2599       SubstParmTypes(Function->getLocation(), Function->parameters(),
2600                      Proto->getExtParameterInfosOrNull(),
2601                      MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2602                      ParamTypes, /*params*/ nullptr, ExtParamInfos))
2603     return TDK_SubstitutionFailure;
2604 
2605   if (FunctionType) {
2606     auto EPI = Proto->getExtProtoInfo();
2607     EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
2608     *FunctionType = BuildFunctionType(ResultType, ParamTypes,
2609                                       Function->getLocation(),
2610                                       Function->getDeclName(),
2611                                       EPI);
2612     if (FunctionType->isNull() || Trap.hasErrorOccurred())
2613       return TDK_SubstitutionFailure;
2614   }
2615 
2616   // C++ [temp.arg.explicit]p2:
2617   //   Trailing template arguments that can be deduced (14.8.2) may be
2618   //   omitted from the list of explicit template-arguments. If all of the
2619   //   template arguments can be deduced, they may all be omitted; in this
2620   //   case, the empty template argument list <> itself may also be omitted.
2621   //
2622   // Take all of the explicitly-specified arguments and put them into
2623   // the set of deduced template arguments. Explicitly-specified
2624   // parameter packs, however, will be set to NULL since the deduction
2625   // mechanisms handle explicitly-specified argument packs directly.
2626   Deduced.reserve(TemplateParams->size());
2627   for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2628     const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2629     if (Arg.getKind() == TemplateArgument::Pack)
2630       Deduced.push_back(DeducedTemplateArgument());
2631     else
2632       Deduced.push_back(Arg);
2633   }
2634 
2635   return TDK_Success;
2636 }
2637 
2638 /// \brief Check whether the deduced argument type for a call to a function
2639 /// template matches the actual argument type per C++ [temp.deduct.call]p4.
2640 static bool
2641 CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2642                               QualType DeducedA) {
2643   ASTContext &Context = S.Context;
2644 
2645   QualType A = OriginalArg.OriginalArgType;
2646   QualType OriginalParamType = OriginalArg.OriginalParamType;
2647 
2648   // Check for type equality (top-level cv-qualifiers are ignored).
2649   if (Context.hasSameUnqualifiedType(A, DeducedA))
2650     return false;
2651 
2652   // Strip off references on the argument types; they aren't needed for
2653   // the following checks.
2654   if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2655     DeducedA = DeducedARef->getPointeeType();
2656   if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2657     A = ARef->getPointeeType();
2658 
2659   // C++ [temp.deduct.call]p4:
2660   //   [...] However, there are three cases that allow a difference:
2661   //     - If the original P is a reference type, the deduced A (i.e., the
2662   //       type referred to by the reference) can be more cv-qualified than
2663   //       the transformed A.
2664   if (const ReferenceType *OriginalParamRef
2665       = OriginalParamType->getAs<ReferenceType>()) {
2666     // We don't want to keep the reference around any more.
2667     OriginalParamType = OriginalParamRef->getPointeeType();
2668 
2669     Qualifiers AQuals = A.getQualifiers();
2670     Qualifiers DeducedAQuals = DeducedA.getQualifiers();
2671 
2672     // Under Objective-C++ ARC, the deduced type may have implicitly
2673     // been given strong or (when dealing with a const reference)
2674     // unsafe_unretained lifetime. If so, update the original
2675     // qualifiers to include this lifetime.
2676     if (S.getLangOpts().ObjCAutoRefCount &&
2677         ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2678           AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2679          (DeducedAQuals.hasConst() &&
2680           DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2681       AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
2682     }
2683 
2684     if (AQuals == DeducedAQuals) {
2685       // Qualifiers match; there's nothing to do.
2686     } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
2687       return true;
2688     } else {
2689       // Qualifiers are compatible, so have the argument type adopt the
2690       // deduced argument type's qualifiers as if we had performed the
2691       // qualification conversion.
2692       A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2693     }
2694   }
2695 
2696   //    - The transformed A can be another pointer or pointer to member
2697   //      type that can be converted to the deduced A via a qualification
2698   //      conversion.
2699   //
2700   // Also allow conversions which merely strip [[noreturn]] from function types
2701   // (recursively) as an extension.
2702   // FIXME: Currently, this doesn't play nicely with qualification conversions.
2703   bool ObjCLifetimeConversion = false;
2704   QualType ResultTy;
2705   if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
2706       (S.IsQualificationConversion(A, DeducedA, false,
2707                                    ObjCLifetimeConversion) ||
2708        S.IsNoReturnConversion(A, DeducedA, ResultTy)))
2709     return false;
2710 
2711 
2712   //    - If P is a class and P has the form simple-template-id, then the
2713   //      transformed A can be a derived class of the deduced A. [...]
2714   //     [...] Likewise, if P is a pointer to a class of the form
2715   //      simple-template-id, the transformed A can be a pointer to a
2716   //      derived class pointed to by the deduced A.
2717   if (const PointerType *OriginalParamPtr
2718       = OriginalParamType->getAs<PointerType>()) {
2719     if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2720       if (const PointerType *APtr = A->getAs<PointerType>()) {
2721         if (A->getPointeeType()->isRecordType()) {
2722           OriginalParamType = OriginalParamPtr->getPointeeType();
2723           DeducedA = DeducedAPtr->getPointeeType();
2724           A = APtr->getPointeeType();
2725         }
2726       }
2727     }
2728   }
2729 
2730   if (Context.hasSameUnqualifiedType(A, DeducedA))
2731     return false;
2732 
2733   if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2734       S.IsDerivedFrom(SourceLocation(), A, DeducedA))
2735     return false;
2736 
2737   return true;
2738 }
2739 
2740 /// \brief Finish template argument deduction for a function template,
2741 /// checking the deduced template arguments for completeness and forming
2742 /// the function template specialization.
2743 ///
2744 /// \param OriginalCallArgs If non-NULL, the original call arguments against
2745 /// which the deduced argument types should be compared.
2746 Sema::TemplateDeductionResult
2747 Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
2748                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2749                                       unsigned NumExplicitlySpecified,
2750                                       FunctionDecl *&Specialization,
2751                                       TemplateDeductionInfo &Info,
2752         SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2753                                       bool PartialOverloading) {
2754   TemplateParameterList *TemplateParams
2755     = FunctionTemplate->getTemplateParameters();
2756 
2757   // Unevaluated SFINAE context.
2758   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2759   SFINAETrap Trap(*this);
2760 
2761   // Enter a new template instantiation context while we instantiate the
2762   // actual function declaration.
2763   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2764   InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2765                              DeducedArgs,
2766               ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2767                              Info);
2768   if (Inst.isInvalid())
2769     return TDK_InstantiationDepth;
2770 
2771   ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2772 
2773   // C++ [temp.deduct.type]p2:
2774   //   [...] or if any template argument remains neither deduced nor
2775   //   explicitly specified, template argument deduction fails.
2776   SmallVector<TemplateArgument, 4> Builder;
2777   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2778     NamedDecl *Param = TemplateParams->getParam(I);
2779 
2780     if (!Deduced[I].isNull()) {
2781       if (I < NumExplicitlySpecified) {
2782         // We have already fully type-checked and converted this
2783         // argument, because it was explicitly-specified. Just record the
2784         // presence of this argument.
2785         Builder.push_back(Deduced[I]);
2786         // We may have had explicitly-specified template arguments for a
2787         // template parameter pack (that may or may not have been extended
2788         // via additional deduced arguments).
2789         if (Param->isParameterPack() && CurrentInstantiationScope) {
2790           if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2791               Param) {
2792             // Forget the partially-substituted pack; its substitution is now
2793             // complete.
2794             CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2795           }
2796         }
2797         continue;
2798       }
2799 
2800       // We have deduced this argument, so it still needs to be
2801       // checked and converted.
2802       if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2803                                          FunctionTemplate, Info,
2804                                          true, Builder)) {
2805         Info.Param = makeTemplateParameter(Param);
2806         // FIXME: These template arguments are temporary. Free them!
2807         Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
2808         return TDK_SubstitutionFailure;
2809       }
2810 
2811       continue;
2812     }
2813 
2814     // C++0x [temp.arg.explicit]p3:
2815     //    A trailing template parameter pack (14.5.3) not otherwise deduced will
2816     //    be deduced to an empty sequence of template arguments.
2817     // FIXME: Where did the word "trailing" come from?
2818     if (Param->isTemplateParameterPack()) {
2819       // We may have had explicitly-specified template arguments for this
2820       // template parameter pack. If so, our empty deduction extends the
2821       // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2822       const TemplateArgument *ExplicitArgs;
2823       unsigned NumExplicitArgs;
2824       if (CurrentInstantiationScope &&
2825           CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
2826                                                              &NumExplicitArgs)
2827             == Param) {
2828         Builder.push_back(TemplateArgument(
2829             llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2830 
2831         // Forget the partially-substituted pack; its substitution is now
2832         // complete.
2833         CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2834       } else {
2835         // Go through the motions of checking the empty argument pack against
2836         // the parameter pack.
2837         DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
2838         if (ConvertDeducedTemplateArgument(*this, Param, DeducedPack,
2839                                            FunctionTemplate, Info, true,
2840                                            Builder)) {
2841           Info.Param = makeTemplateParameter(Param);
2842           // FIXME: These template arguments are temporary. Free them!
2843           Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
2844           return TDK_SubstitutionFailure;
2845         }
2846       }
2847       continue;
2848     }
2849 
2850     // Substitute into the default template argument, if available.
2851     bool HasDefaultArg = false;
2852     TemplateArgumentLoc DefArg
2853       = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2854                                               FunctionTemplate->getLocation(),
2855                                   FunctionTemplate->getSourceRange().getEnd(),
2856                                                 Param,
2857                                                 Builder, HasDefaultArg);
2858 
2859     // If there was no default argument, deduction is incomplete.
2860     if (DefArg.getArgument().isNull()) {
2861       Info.Param = makeTemplateParameter(
2862                          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2863       Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
2864       if (PartialOverloading) break;
2865 
2866       return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
2867     }
2868 
2869     // Check whether we can actually use the default argument.
2870     if (CheckTemplateArgument(Param, DefArg,
2871                               FunctionTemplate,
2872                               FunctionTemplate->getLocation(),
2873                               FunctionTemplate->getSourceRange().getEnd(),
2874                               0, Builder,
2875                               CTAK_Specified)) {
2876       Info.Param = makeTemplateParameter(
2877                          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2878       // FIXME: These template arguments are temporary. Free them!
2879       Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
2880       return TDK_SubstitutionFailure;
2881     }
2882 
2883     // If we get here, we successfully used the default template argument.
2884   }
2885 
2886   // Form the template argument list from the deduced template arguments.
2887   TemplateArgumentList *DeducedArgumentList
2888     = TemplateArgumentList::CreateCopy(Context, Builder);
2889   Info.reset(DeducedArgumentList);
2890 
2891   // Substitute the deduced template arguments into the function template
2892   // declaration to produce the function template specialization.
2893   DeclContext *Owner = FunctionTemplate->getDeclContext();
2894   if (FunctionTemplate->getFriendObjectKind())
2895     Owner = FunctionTemplate->getLexicalDeclContext();
2896   Specialization = cast_or_null<FunctionDecl>(
2897                       SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
2898                          MultiLevelTemplateArgumentList(*DeducedArgumentList)));
2899   if (!Specialization || Specialization->isInvalidDecl())
2900     return TDK_SubstitutionFailure;
2901 
2902   assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2903          FunctionTemplate->getCanonicalDecl());
2904 
2905   // If the template argument list is owned by the function template
2906   // specialization, release it.
2907   if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2908       !Trap.hasErrorOccurred())
2909     Info.take();
2910 
2911   // There may have been an error that did not prevent us from constructing a
2912   // declaration. Mark the declaration invalid and return with a substitution
2913   // failure.
2914   if (Trap.hasErrorOccurred()) {
2915     Specialization->setInvalidDecl(true);
2916     return TDK_SubstitutionFailure;
2917   }
2918 
2919   if (OriginalCallArgs) {
2920     // C++ [temp.deduct.call]p4:
2921     //   In general, the deduction process attempts to find template argument
2922     //   values that will make the deduced A identical to A (after the type A
2923     //   is transformed as described above). [...]
2924     for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2925       OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
2926       unsigned ParamIdx = OriginalArg.ArgIdx;
2927 
2928       if (ParamIdx >= Specialization->getNumParams())
2929         continue;
2930 
2931       QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
2932       if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2933         Info.FirstArg = TemplateArgument(DeducedA);
2934         Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2935         Info.CallArgIndex = OriginalArg.ArgIdx;
2936         return TDK_DeducedMismatch;
2937       }
2938     }
2939   }
2940 
2941   // If we suppressed any diagnostics while performing template argument
2942   // deduction, and if we haven't already instantiated this declaration,
2943   // keep track of these diagnostics. They'll be emitted if this specialization
2944   // is actually used.
2945   if (Info.diag_begin() != Info.diag_end()) {
2946     SuppressedDiagnosticsMap::iterator
2947       Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2948     if (Pos == SuppressedDiagnostics.end())
2949         SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2950           .append(Info.diag_begin(), Info.diag_end());
2951   }
2952 
2953   return TDK_Success;
2954 }
2955 
2956 /// Gets the type of a function for template-argument-deducton
2957 /// purposes when it's considered as part of an overload set.
2958 static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
2959                                   FunctionDecl *Fn) {
2960   // We may need to deduce the return type of the function now.
2961   if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
2962       S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
2963     return QualType();
2964 
2965   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
2966     if (Method->isInstance()) {
2967       // An instance method that's referenced in a form that doesn't
2968       // look like a member pointer is just invalid.
2969       if (!R.HasFormOfMemberPointer) return QualType();
2970 
2971       return S.Context.getMemberPointerType(Fn->getType(),
2972                S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
2973     }
2974 
2975   if (!R.IsAddressOfOperand) return Fn->getType();
2976   return S.Context.getPointerType(Fn->getType());
2977 }
2978 
2979 /// Apply the deduction rules for overload sets.
2980 ///
2981 /// \return the null type if this argument should be treated as an
2982 /// undeduced context
2983 static QualType
2984 ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
2985                             Expr *Arg, QualType ParamType,
2986                             bool ParamWasReference) {
2987 
2988   OverloadExpr::FindResult R = OverloadExpr::find(Arg);
2989 
2990   OverloadExpr *Ovl = R.Expression;
2991 
2992   // C++0x [temp.deduct.call]p4
2993   unsigned TDF = 0;
2994   if (ParamWasReference)
2995     TDF |= TDF_ParamWithReferenceType;
2996   if (R.IsAddressOfOperand)
2997     TDF |= TDF_IgnoreQualifiers;
2998 
2999   // C++0x [temp.deduct.call]p6:
3000   //   When P is a function type, pointer to function type, or pointer
3001   //   to member function type:
3002 
3003   if (!ParamType->isFunctionType() &&
3004       !ParamType->isFunctionPointerType() &&
3005       !ParamType->isMemberFunctionPointerType()) {
3006     if (Ovl->hasExplicitTemplateArgs()) {
3007       // But we can still look for an explicit specialization.
3008       if (FunctionDecl *ExplicitSpec
3009             = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
3010         return GetTypeOfFunction(S, R, ExplicitSpec);
3011     }
3012 
3013     DeclAccessPair DAP;
3014     if (FunctionDecl *Viable =
3015             S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3016       return GetTypeOfFunction(S, R, Viable);
3017 
3018     return QualType();
3019   }
3020 
3021   // Gather the explicit template arguments, if any.
3022   TemplateArgumentListInfo ExplicitTemplateArgs;
3023   if (Ovl->hasExplicitTemplateArgs())
3024     Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
3025   QualType Match;
3026   for (UnresolvedSetIterator I = Ovl->decls_begin(),
3027          E = Ovl->decls_end(); I != E; ++I) {
3028     NamedDecl *D = (*I)->getUnderlyingDecl();
3029 
3030     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3031       //   - If the argument is an overload set containing one or more
3032       //     function templates, the parameter is treated as a
3033       //     non-deduced context.
3034       if (!Ovl->hasExplicitTemplateArgs())
3035         return QualType();
3036 
3037       // Otherwise, see if we can resolve a function type
3038       FunctionDecl *Specialization = nullptr;
3039       TemplateDeductionInfo Info(Ovl->getNameLoc());
3040       if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3041                                     Specialization, Info))
3042         continue;
3043 
3044       D = Specialization;
3045     }
3046 
3047     FunctionDecl *Fn = cast<FunctionDecl>(D);
3048     QualType ArgType = GetTypeOfFunction(S, R, Fn);
3049     if (ArgType.isNull()) continue;
3050 
3051     // Function-to-pointer conversion.
3052     if (!ParamWasReference && ParamType->isPointerType() &&
3053         ArgType->isFunctionType())
3054       ArgType = S.Context.getPointerType(ArgType);
3055 
3056     //   - If the argument is an overload set (not containing function
3057     //     templates), trial argument deduction is attempted using each
3058     //     of the members of the set. If deduction succeeds for only one
3059     //     of the overload set members, that member is used as the
3060     //     argument value for the deduction. If deduction succeeds for
3061     //     more than one member of the overload set the parameter is
3062     //     treated as a non-deduced context.
3063 
3064     // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3065     //   Type deduction is done independently for each P/A pair, and
3066     //   the deduced template argument values are then combined.
3067     // So we do not reject deductions which were made elsewhere.
3068     SmallVector<DeducedTemplateArgument, 8>
3069       Deduced(TemplateParams->size());
3070     TemplateDeductionInfo Info(Ovl->getNameLoc());
3071     Sema::TemplateDeductionResult Result
3072       = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3073                                            ArgType, Info, Deduced, TDF);
3074     if (Result) continue;
3075     if (!Match.isNull()) return QualType();
3076     Match = ArgType;
3077   }
3078 
3079   return Match;
3080 }
3081 
3082 /// \brief Perform the adjustments to the parameter and argument types
3083 /// described in C++ [temp.deduct.call].
3084 ///
3085 /// \returns true if the caller should not attempt to perform any template
3086 /// argument deduction based on this P/A pair because the argument is an
3087 /// overloaded function set that could not be resolved.
3088 static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3089                                           TemplateParameterList *TemplateParams,
3090                                                       QualType &ParamType,
3091                                                       QualType &ArgType,
3092                                                       Expr *Arg,
3093                                                       unsigned &TDF) {
3094   // C++0x [temp.deduct.call]p3:
3095   //   If P is a cv-qualified type, the top level cv-qualifiers of P's type
3096   //   are ignored for type deduction.
3097   if (ParamType.hasQualifiers())
3098     ParamType = ParamType.getUnqualifiedType();
3099 
3100   //   [...] If P is a reference type, the type referred to by P is
3101   //   used for type deduction.
3102   const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
3103   if (ParamRefType)
3104     ParamType = ParamRefType->getPointeeType();
3105 
3106   // Overload sets usually make this parameter an undeduced context,
3107   // but there are sometimes special circumstances.  Typically
3108   // involving a template-id-expr.
3109   if (ArgType == S.Context.OverloadTy) {
3110     ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3111                                           Arg, ParamType,
3112                                           ParamRefType != nullptr);
3113     if (ArgType.isNull())
3114       return true;
3115   }
3116 
3117   if (ParamRefType) {
3118     // If the argument has incomplete array type, try to complete its type.
3119     if (ArgType->isIncompleteArrayType()) {
3120       S.completeExprArrayBound(Arg);
3121       ArgType = Arg->getType();
3122     }
3123 
3124     // C++0x [temp.deduct.call]p3:
3125     //   If P is an rvalue reference to a cv-unqualified template
3126     //   parameter and the argument is an lvalue, the type "lvalue
3127     //   reference to A" is used in place of A for type deduction.
3128     if (ParamRefType->isRValueReferenceType() &&
3129         !ParamType.getQualifiers() &&
3130         isa<TemplateTypeParmType>(ParamType) &&
3131         Arg->isLValue())
3132       ArgType = S.Context.getLValueReferenceType(ArgType);
3133   } else {
3134     // C++ [temp.deduct.call]p2:
3135     //   If P is not a reference type:
3136     //   - If A is an array type, the pointer type produced by the
3137     //     array-to-pointer standard conversion (4.2) is used in place of
3138     //     A for type deduction; otherwise,
3139     if (ArgType->isArrayType())
3140       ArgType = S.Context.getArrayDecayedType(ArgType);
3141     //   - If A is a function type, the pointer type produced by the
3142     //     function-to-pointer standard conversion (4.3) is used in place
3143     //     of A for type deduction; otherwise,
3144     else if (ArgType->isFunctionType())
3145       ArgType = S.Context.getPointerType(ArgType);
3146     else {
3147       // - If A is a cv-qualified type, the top level cv-qualifiers of A's
3148       //   type are ignored for type deduction.
3149       ArgType = ArgType.getUnqualifiedType();
3150     }
3151   }
3152 
3153   // C++0x [temp.deduct.call]p4:
3154   //   In general, the deduction process attempts to find template argument
3155   //   values that will make the deduced A identical to A (after the type A
3156   //   is transformed as described above). [...]
3157   TDF = TDF_SkipNonDependent;
3158 
3159   //     - If the original P is a reference type, the deduced A (i.e., the
3160   //       type referred to by the reference) can be more cv-qualified than
3161   //       the transformed A.
3162   if (ParamRefType)
3163     TDF |= TDF_ParamWithReferenceType;
3164   //     - The transformed A can be another pointer or pointer to member
3165   //       type that can be converted to the deduced A via a qualification
3166   //       conversion (4.4).
3167   if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3168       ArgType->isObjCObjectPointerType())
3169     TDF |= TDF_IgnoreQualifiers;
3170   //     - If P is a class and P has the form simple-template-id, then the
3171   //       transformed A can be a derived class of the deduced A. Likewise,
3172   //       if P is a pointer to a class of the form simple-template-id, the
3173   //       transformed A can be a pointer to a derived class pointed to by
3174   //       the deduced A.
3175   if (isSimpleTemplateIdType(ParamType) ||
3176       (isa<PointerType>(ParamType) &&
3177        isSimpleTemplateIdType(
3178                               ParamType->getAs<PointerType>()->getPointeeType())))
3179     TDF |= TDF_DerivedClass;
3180 
3181   return false;
3182 }
3183 
3184 static bool
3185 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3186                                QualType T);
3187 
3188 static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3189     Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3190     Expr *Arg, TemplateDeductionInfo &Info,
3191     SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3192 
3193 /// \brief Attempt template argument deduction from an initializer list
3194 ///        deemed to be an argument in a function call.
3195 static bool
3196 DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3197                           QualType AdjustedParamType, InitListExpr *ILE,
3198                           TemplateDeductionInfo &Info,
3199                           SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3200                           unsigned TDF, Sema::TemplateDeductionResult &Result) {
3201 
3202   // [temp.deduct.call] p1 (post CWG-1591)
3203   // If removing references and cv-qualifiers from P gives
3204   // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3205   // non-empty initializer list (8.5.4), then deduction is performed instead for
3206   // each element of the initializer list, taking P0 as a function template
3207   // parameter type and the initializer element as its argument, and in the
3208   // P0[N] case, if N is a non-type template parameter, N is deduced from the
3209   // length of the initializer list. Otherwise, an initializer list argument
3210   // causes the parameter to be considered a non-deduced context
3211 
3212   const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3213 
3214   const bool IsDependentSizedArray =
3215       !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3216 
3217   QualType ElTy;  // The element type of the std::initializer_list or the array.
3218 
3219   const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3220                          S.isStdInitializerList(AdjustedParamType, &ElTy);
3221 
3222   if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
3223     return false;
3224 
3225   Result = Sema::TDK_Success;
3226   // If we are not deducing against the 'T' in a std::initializer_list<T> then
3227   // deduce against the 'T' in T[N].
3228   if (ElTy.isNull()) {
3229     assert(!IsSTDList);
3230     ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
3231   }
3232   // Deduction only needs to be done for dependent types.
3233   if (ElTy->isDependentType()) {
3234     for (Expr *E : ILE->inits()) {
3235       if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3236                                                         E, Info, Deduced, TDF)))
3237         return true;
3238     }
3239   }
3240   if (IsDependentSizedArray) {
3241     const DependentSizedArrayType *ArrTy =
3242         S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3243     // Determine the array bound is something we can deduce.
3244     if (NonTypeTemplateParmDecl *NTTP =
3245             getDeducedParameterFromExpr(ArrTy->getSizeExpr())) {
3246       // We can perform template argument deduction for the given non-type
3247       // template parameter.
3248       assert(NTTP->getDepth() == 0 &&
3249              "Cannot deduce non-type template argument at depth > 0");
3250       llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3251                        ILE->getNumInits());
3252 
3253       Result = DeduceNonTypeTemplateArgument(
3254           S, NTTP, llvm::APSInt(Size), NTTP->getType(),
3255           /*ArrayBound=*/true, Info, Deduced);
3256     }
3257   }
3258   return true;
3259 }
3260 
3261 /// \brief Perform template argument deduction by matching a parameter type
3262 ///        against a single expression, where the expression is an element of
3263 ///        an initializer list that was originally matched against a parameter
3264 ///        of type \c initializer_list\<ParamType\>.
3265 static Sema::TemplateDeductionResult
3266 DeduceTemplateArgumentByListElement(Sema &S,
3267                                     TemplateParameterList *TemplateParams,
3268                                     QualType ParamType, Expr *Arg,
3269                                     TemplateDeductionInfo &Info,
3270                               SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3271                                     unsigned TDF) {
3272   // Handle the case where an init list contains another init list as the
3273   // element.
3274   if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3275     Sema::TemplateDeductionResult Result;
3276     if (!DeduceFromInitializerList(S, TemplateParams,
3277                                    ParamType.getNonReferenceType(), ILE, Info,
3278                                    Deduced, TDF, Result))
3279       return Sema::TDK_Success; // Just ignore this expression.
3280 
3281     return Result;
3282   }
3283 
3284   // For all other cases, just match by type.
3285   QualType ArgType = Arg->getType();
3286   if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
3287                                                 ArgType, Arg, TDF)) {
3288     Info.Expression = Arg;
3289     return Sema::TDK_FailedOverloadResolution;
3290   }
3291   return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3292                                             ArgType, Info, Deduced, TDF);
3293 }
3294 
3295 /// \brief Perform template argument deduction from a function call
3296 /// (C++ [temp.deduct.call]).
3297 ///
3298 /// \param FunctionTemplate the function template for which we are performing
3299 /// template argument deduction.
3300 ///
3301 /// \param ExplicitTemplateArgs the explicit template arguments provided
3302 /// for this call.
3303 ///
3304 /// \param Args the function call arguments
3305 ///
3306 /// \param Specialization if template argument deduction was successful,
3307 /// this will be set to the function template specialization produced by
3308 /// template argument deduction.
3309 ///
3310 /// \param Info the argument will be updated to provide additional information
3311 /// about template argument deduction.
3312 ///
3313 /// \returns the result of template argument deduction.
3314 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3315     FunctionTemplateDecl *FunctionTemplate,
3316     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3317     FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3318     bool PartialOverloading) {
3319   if (FunctionTemplate->isInvalidDecl())
3320     return TDK_Invalid;
3321 
3322   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3323   unsigned NumParams = Function->getNumParams();
3324 
3325   // C++ [temp.deduct.call]p1:
3326   //   Template argument deduction is done by comparing each function template
3327   //   parameter type (call it P) with the type of the corresponding argument
3328   //   of the call (call it A) as described below.
3329   unsigned CheckArgs = Args.size();
3330   if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
3331     return TDK_TooFewArguments;
3332   else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
3333     const FunctionProtoType *Proto
3334       = Function->getType()->getAs<FunctionProtoType>();
3335     if (Proto->isTemplateVariadic())
3336       /* Do nothing */;
3337     else if (Proto->isVariadic())
3338       CheckArgs = NumParams;
3339     else
3340       return TDK_TooManyArguments;
3341   }
3342 
3343   // The types of the parameters from which we will perform template argument
3344   // deduction.
3345   LocalInstantiationScope InstScope(*this);
3346   TemplateParameterList *TemplateParams
3347     = FunctionTemplate->getTemplateParameters();
3348   SmallVector<DeducedTemplateArgument, 4> Deduced;
3349   SmallVector<QualType, 4> ParamTypes;
3350   unsigned NumExplicitlySpecified = 0;
3351   if (ExplicitTemplateArgs) {
3352     TemplateDeductionResult Result =
3353       SubstituteExplicitTemplateArguments(FunctionTemplate,
3354                                           *ExplicitTemplateArgs,
3355                                           Deduced,
3356                                           ParamTypes,
3357                                           nullptr,
3358                                           Info);
3359     if (Result)
3360       return Result;
3361 
3362     NumExplicitlySpecified = Deduced.size();
3363   } else {
3364     // Just fill in the parameter types from the function declaration.
3365     for (unsigned I = 0; I != NumParams; ++I)
3366       ParamTypes.push_back(Function->getParamDecl(I)->getType());
3367   }
3368 
3369   // Deduce template arguments from the function parameters.
3370   Deduced.resize(TemplateParams->size());
3371   unsigned ArgIdx = 0;
3372   SmallVector<OriginalCallArg, 4> OriginalCallArgs;
3373   for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3374        ParamIdx != NumParamTypes; ++ParamIdx) {
3375     QualType OrigParamType = ParamTypes[ParamIdx];
3376     QualType ParamType = OrigParamType;
3377 
3378     const PackExpansionType *ParamExpansion
3379       = dyn_cast<PackExpansionType>(ParamType);
3380     if (!ParamExpansion) {
3381       // Simple case: matching a function parameter to a function argument.
3382       if (ArgIdx >= CheckArgs)
3383         break;
3384 
3385       Expr *Arg = Args[ArgIdx++];
3386       QualType ArgType = Arg->getType();
3387 
3388       unsigned TDF = 0;
3389       if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3390                                                     ParamType, ArgType, Arg,
3391                                                     TDF))
3392         continue;
3393 
3394       // If we have nothing to deduce, we're done.
3395       if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3396         continue;
3397 
3398       // If the argument is an initializer list ...
3399       if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3400         TemplateDeductionResult Result;
3401         // Removing references was already done.
3402         if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3403                                        Info, Deduced, TDF, Result))
3404           continue;
3405 
3406         if (Result)
3407           return Result;
3408         // Don't track the argument type, since an initializer list has none.
3409         continue;
3410       }
3411 
3412       // Keep track of the argument type and corresponding parameter index,
3413       // so we can check for compatibility between the deduced A and A.
3414       OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3415                                                  ArgType));
3416 
3417       if (TemplateDeductionResult Result
3418             = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3419                                                  ParamType, ArgType,
3420                                                  Info, Deduced, TDF))
3421         return Result;
3422 
3423       continue;
3424     }
3425 
3426     // C++0x [temp.deduct.call]p1:
3427     //   For a function parameter pack that occurs at the end of the
3428     //   parameter-declaration-list, the type A of each remaining argument of
3429     //   the call is compared with the type P of the declarator-id of the
3430     //   function parameter pack. Each comparison deduces template arguments
3431     //   for subsequent positions in the template parameter packs expanded by
3432     //   the function parameter pack. For a function parameter pack that does
3433     //   not occur at the end of the parameter-declaration-list, the type of
3434     //   the parameter pack is a non-deduced context.
3435     if (ParamIdx + 1 < NumParamTypes)
3436       break;
3437 
3438     QualType ParamPattern = ParamExpansion->getPattern();
3439     PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3440                                  ParamPattern);
3441 
3442     bool HasAnyArguments = false;
3443     for (; ArgIdx < Args.size(); ++ArgIdx) {
3444       HasAnyArguments = true;
3445 
3446       QualType OrigParamType = ParamPattern;
3447       ParamType = OrigParamType;
3448       Expr *Arg = Args[ArgIdx];
3449       QualType ArgType = Arg->getType();
3450 
3451       unsigned TDF = 0;
3452       if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3453                                                     ParamType, ArgType, Arg,
3454                                                     TDF)) {
3455         // We can't actually perform any deduction for this argument, so stop
3456         // deduction at this point.
3457         ++ArgIdx;
3458         break;
3459       }
3460 
3461       // As above, initializer lists need special handling.
3462       if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3463         TemplateDeductionResult Result;
3464         if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3465                                        Info, Deduced, TDF, Result)) {
3466           ++ArgIdx;
3467           break;
3468         }
3469 
3470         if (Result)
3471           return Result;
3472       } else {
3473 
3474         // Keep track of the argument type and corresponding argument index,
3475         // so we can check for compatibility between the deduced A and A.
3476         if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3477           OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3478                                                      ArgType));
3479 
3480         if (TemplateDeductionResult Result
3481             = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3482                                                  ParamType, ArgType, Info,
3483                                                  Deduced, TDF))
3484           return Result;
3485       }
3486 
3487       PackScope.nextPackElement();
3488     }
3489 
3490     // Build argument packs for each of the parameter packs expanded by this
3491     // pack expansion.
3492     if (auto Result = PackScope.finish(HasAnyArguments))
3493       return Result;
3494 
3495     // After we've matching against a parameter pack, we're done.
3496     break;
3497   }
3498 
3499   return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3500                                          NumExplicitlySpecified, Specialization,
3501                                          Info, &OriginalCallArgs,
3502                                          PartialOverloading);
3503 }
3504 
3505 QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3506                                    QualType FunctionType) {
3507   if (ArgFunctionType.isNull())
3508     return ArgFunctionType;
3509 
3510   const FunctionProtoType *FunctionTypeP =
3511       FunctionType->castAs<FunctionProtoType>();
3512   CallingConv CC = FunctionTypeP->getCallConv();
3513   bool NoReturn = FunctionTypeP->getNoReturnAttr();
3514   const FunctionProtoType *ArgFunctionTypeP =
3515       ArgFunctionType->getAs<FunctionProtoType>();
3516   if (ArgFunctionTypeP->getCallConv() == CC &&
3517       ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3518     return ArgFunctionType;
3519 
3520   FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3521   EI = EI.withNoReturn(NoReturn);
3522   ArgFunctionTypeP =
3523       cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3524   return QualType(ArgFunctionTypeP, 0);
3525 }
3526 
3527 /// \brief Deduce template arguments when taking the address of a function
3528 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3529 /// a template.
3530 ///
3531 /// \param FunctionTemplate the function template for which we are performing
3532 /// template argument deduction.
3533 ///
3534 /// \param ExplicitTemplateArgs the explicitly-specified template
3535 /// arguments.
3536 ///
3537 /// \param ArgFunctionType the function type that will be used as the
3538 /// "argument" type (A) when performing template argument deduction from the
3539 /// function template's function type. This type may be NULL, if there is no
3540 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
3541 ///
3542 /// \param Specialization if template argument deduction was successful,
3543 /// this will be set to the function template specialization produced by
3544 /// template argument deduction.
3545 ///
3546 /// \param Info the argument will be updated to provide additional information
3547 /// about template argument deduction.
3548 ///
3549 /// \returns the result of template argument deduction.
3550 Sema::TemplateDeductionResult
3551 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3552                               TemplateArgumentListInfo *ExplicitTemplateArgs,
3553                               QualType ArgFunctionType,
3554                               FunctionDecl *&Specialization,
3555                               TemplateDeductionInfo &Info,
3556                               bool InOverloadResolution) {
3557   if (FunctionTemplate->isInvalidDecl())
3558     return TDK_Invalid;
3559 
3560   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3561   TemplateParameterList *TemplateParams
3562     = FunctionTemplate->getTemplateParameters();
3563   QualType FunctionType = Function->getType();
3564   if (!InOverloadResolution)
3565     ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
3566 
3567   // Substitute any explicit template arguments.
3568   LocalInstantiationScope InstScope(*this);
3569   SmallVector<DeducedTemplateArgument, 4> Deduced;
3570   unsigned NumExplicitlySpecified = 0;
3571   SmallVector<QualType, 4> ParamTypes;
3572   if (ExplicitTemplateArgs) {
3573     if (TemplateDeductionResult Result
3574           = SubstituteExplicitTemplateArguments(FunctionTemplate,
3575                                                 *ExplicitTemplateArgs,
3576                                                 Deduced, ParamTypes,
3577                                                 &FunctionType, Info))
3578       return Result;
3579 
3580     NumExplicitlySpecified = Deduced.size();
3581   }
3582 
3583   // Unevaluated SFINAE context.
3584   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
3585   SFINAETrap Trap(*this);
3586 
3587   Deduced.resize(TemplateParams->size());
3588 
3589   // If the function has a deduced return type, substitute it for a dependent
3590   // type so that we treat it as a non-deduced context in what follows.
3591   bool HasDeducedReturnType = false;
3592   if (getLangOpts().CPlusPlus14 && InOverloadResolution &&
3593       Function->getReturnType()->getContainedAutoType()) {
3594     FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
3595     HasDeducedReturnType = true;
3596   }
3597 
3598   if (!ArgFunctionType.isNull()) {
3599     unsigned TDF = TDF_TopLevelParameterTypeList;
3600     if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
3601     // Deduce template arguments from the function type.
3602     if (TemplateDeductionResult Result
3603           = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3604                                                FunctionType, ArgFunctionType,
3605                                                Info, Deduced, TDF))
3606       return Result;
3607   }
3608 
3609   if (TemplateDeductionResult Result
3610         = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3611                                           NumExplicitlySpecified,
3612                                           Specialization, Info))
3613     return Result;
3614 
3615   // If the function has a deduced return type, deduce it now, so we can check
3616   // that the deduced function type matches the requested type.
3617   if (HasDeducedReturnType &&
3618       Specialization->getReturnType()->isUndeducedType() &&
3619       DeduceReturnType(Specialization, Info.getLocation(), false))
3620     return TDK_MiscellaneousDeductionFailure;
3621 
3622   // If the requested function type does not match the actual type of the
3623   // specialization with respect to arguments of compatible pointer to function
3624   // types, template argument deduction fails.
3625   if (!ArgFunctionType.isNull()) {
3626     if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3627                            Context.getCanonicalType(Specialization->getType()),
3628                            Context.getCanonicalType(ArgFunctionType)))
3629       return TDK_MiscellaneousDeductionFailure;
3630     else if(!InOverloadResolution &&
3631             !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3632       return TDK_MiscellaneousDeductionFailure;
3633   }
3634 
3635   return TDK_Success;
3636 }
3637 
3638 /// \brief Given a function declaration (e.g. a generic lambda conversion
3639 ///  function) that contains an 'auto' in its result type, substitute it
3640 ///  with TypeToReplaceAutoWith.  Be careful to pass in the type you want
3641 ///  to replace 'auto' with and not the actual result type you want
3642 ///  to set the function to.
3643 static inline void
3644 SubstAutoWithinFunctionReturnType(FunctionDecl *F,
3645                                     QualType TypeToReplaceAutoWith, Sema &S) {
3646   assert(!TypeToReplaceAutoWith->getContainedAutoType());
3647   QualType AutoResultType = F->getReturnType();
3648   assert(AutoResultType->getContainedAutoType());
3649   QualType DeducedResultType = S.SubstAutoType(AutoResultType,
3650                                                TypeToReplaceAutoWith);
3651   S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3652 }
3653 
3654 /// \brief Given a specialized conversion operator of a generic lambda
3655 /// create the corresponding specializations of the call operator and
3656 /// the static-invoker. If the return type of the call operator is auto,
3657 /// deduce its return type and check if that matches the
3658 /// return type of the destination function ptr.
3659 
3660 static inline Sema::TemplateDeductionResult
3661 SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3662     CXXConversionDecl *ConversionSpecialized,
3663     SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3664     QualType ReturnTypeOfDestFunctionPtr,
3665     TemplateDeductionInfo &TDInfo,
3666     Sema &S) {
3667 
3668   CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3669   assert(LambdaClass && LambdaClass->isGenericLambda());
3670 
3671   CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
3672   QualType CallOpResultType = CallOpGeneric->getReturnType();
3673   const bool GenericLambdaCallOperatorHasDeducedReturnType =
3674       CallOpResultType->getContainedAutoType();
3675 
3676   FunctionTemplateDecl *CallOpTemplate =
3677       CallOpGeneric->getDescribedFunctionTemplate();
3678 
3679   FunctionDecl *CallOpSpecialized = nullptr;
3680   // Use the deduced arguments of the conversion function, to specialize our
3681   // generic lambda's call operator.
3682   if (Sema::TemplateDeductionResult Result
3683       = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3684                                           DeducedArguments,
3685                                           0, CallOpSpecialized, TDInfo))
3686     return Result;
3687 
3688   // If we need to deduce the return type, do so (instantiates the callop).
3689   if (GenericLambdaCallOperatorHasDeducedReturnType &&
3690       CallOpSpecialized->getReturnType()->isUndeducedType())
3691     S.DeduceReturnType(CallOpSpecialized,
3692                        CallOpSpecialized->getPointOfInstantiation(),
3693                        /*Diagnose*/ true);
3694 
3695   // Check to see if the return type of the destination ptr-to-function
3696   // matches the return type of the call operator.
3697   if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
3698                              ReturnTypeOfDestFunctionPtr))
3699     return Sema::TDK_NonDeducedMismatch;
3700   // Since we have succeeded in matching the source and destination
3701   // ptr-to-functions (now including return type), and have successfully
3702   // specialized our corresponding call operator, we are ready to
3703   // specialize the static invoker with the deduced arguments of our
3704   // ptr-to-function.
3705   FunctionDecl *InvokerSpecialized = nullptr;
3706   FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3707                   getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3708 
3709 #ifndef NDEBUG
3710   Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3711 #endif
3712     S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
3713           InvokerSpecialized, TDInfo);
3714   assert(Result == Sema::TDK_Success &&
3715     "If the call operator succeeded so should the invoker!");
3716   // Set the result type to match the corresponding call operator
3717   // specialization's result type.
3718   if (GenericLambdaCallOperatorHasDeducedReturnType &&
3719       InvokerSpecialized->getReturnType()->isUndeducedType()) {
3720     // Be sure to get the type to replace 'auto' with and not
3721     // the full result type of the call op specialization
3722     // to substitute into the 'auto' of the invoker and conversion
3723     // function.
3724     // For e.g.
3725     //  int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3726     // We don't want to subst 'int*' into 'auto' to get int**.
3727 
3728     QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3729                                          ->getContainedAutoType()
3730                                          ->getDeducedType();
3731     SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3732         TypeToReplaceAutoWith, S);
3733     SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3734         TypeToReplaceAutoWith, S);
3735   }
3736 
3737   // Ensure that static invoker doesn't have a const qualifier.
3738   // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3739   // do not use the CallOperator's TypeSourceInfo which allows
3740   // the const qualifier to leak through.
3741   const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3742                   getType().getTypePtr()->castAs<FunctionProtoType>();
3743   FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3744   EPI.TypeQuals = 0;
3745   InvokerSpecialized->setType(S.Context.getFunctionType(
3746       InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
3747   return Sema::TDK_Success;
3748 }
3749 /// \brief Deduce template arguments for a templated conversion
3750 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
3751 /// conversion function template specialization.
3752 Sema::TemplateDeductionResult
3753 Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
3754                               QualType ToType,
3755                               CXXConversionDecl *&Specialization,
3756                               TemplateDeductionInfo &Info) {
3757   if (ConversionTemplate->isInvalidDecl())
3758     return TDK_Invalid;
3759 
3760   CXXConversionDecl *ConversionGeneric
3761     = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3762 
3763   QualType FromType = ConversionGeneric->getConversionType();
3764 
3765   // Canonicalize the types for deduction.
3766   QualType P = Context.getCanonicalType(FromType);
3767   QualType A = Context.getCanonicalType(ToType);
3768 
3769   // C++0x [temp.deduct.conv]p2:
3770   //   If P is a reference type, the type referred to by P is used for
3771   //   type deduction.
3772   if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3773     P = PRef->getPointeeType();
3774 
3775   // C++0x [temp.deduct.conv]p4:
3776   //   [...] If A is a reference type, the type referred to by A is used
3777   //   for type deduction.
3778   if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3779     A = ARef->getPointeeType().getUnqualifiedType();
3780   // C++ [temp.deduct.conv]p3:
3781   //
3782   //   If A is not a reference type:
3783   else {
3784     assert(!A->isReferenceType() && "Reference types were handled above");
3785 
3786     //   - If P is an array type, the pointer type produced by the
3787     //     array-to-pointer standard conversion (4.2) is used in place
3788     //     of P for type deduction; otherwise,
3789     if (P->isArrayType())
3790       P = Context.getArrayDecayedType(P);
3791     //   - If P is a function type, the pointer type produced by the
3792     //     function-to-pointer standard conversion (4.3) is used in
3793     //     place of P for type deduction; otherwise,
3794     else if (P->isFunctionType())
3795       P = Context.getPointerType(P);
3796     //   - If P is a cv-qualified type, the top level cv-qualifiers of
3797     //     P's type are ignored for type deduction.
3798     else
3799       P = P.getUnqualifiedType();
3800 
3801     // C++0x [temp.deduct.conv]p4:
3802     //   If A is a cv-qualified type, the top level cv-qualifiers of A's
3803     //   type are ignored for type deduction. If A is a reference type, the type
3804     //   referred to by A is used for type deduction.
3805     A = A.getUnqualifiedType();
3806   }
3807 
3808   // Unevaluated SFINAE context.
3809   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
3810   SFINAETrap Trap(*this);
3811 
3812   // C++ [temp.deduct.conv]p1:
3813   //   Template argument deduction is done by comparing the return
3814   //   type of the template conversion function (call it P) with the
3815   //   type that is required as the result of the conversion (call it
3816   //   A) as described in 14.8.2.4.
3817   TemplateParameterList *TemplateParams
3818     = ConversionTemplate->getTemplateParameters();
3819   SmallVector<DeducedTemplateArgument, 4> Deduced;
3820   Deduced.resize(TemplateParams->size());
3821 
3822   // C++0x [temp.deduct.conv]p4:
3823   //   In general, the deduction process attempts to find template
3824   //   argument values that will make the deduced A identical to
3825   //   A. However, there are two cases that allow a difference:
3826   unsigned TDF = 0;
3827   //     - If the original A is a reference type, A can be more
3828   //       cv-qualified than the deduced A (i.e., the type referred to
3829   //       by the reference)
3830   if (ToType->isReferenceType())
3831     TDF |= TDF_ParamWithReferenceType;
3832   //     - The deduced A can be another pointer or pointer to member
3833   //       type that can be converted to A via a qualification
3834   //       conversion.
3835   //
3836   // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3837   // both P and A are pointers or member pointers. In this case, we
3838   // just ignore cv-qualifiers completely).
3839   if ((P->isPointerType() && A->isPointerType()) ||
3840       (P->isMemberPointerType() && A->isMemberPointerType()))
3841     TDF |= TDF_IgnoreQualifiers;
3842   if (TemplateDeductionResult Result
3843         = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3844                                              P, A, Info, Deduced, TDF))
3845     return Result;
3846 
3847   // Create an Instantiation Scope for finalizing the operator.
3848   LocalInstantiationScope InstScope(*this);
3849   // Finish template argument deduction.
3850   FunctionDecl *ConversionSpecialized = nullptr;
3851   TemplateDeductionResult Result
3852       = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3853                                         ConversionSpecialized, Info);
3854   Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3855 
3856   // If the conversion operator is being invoked on a lambda closure to convert
3857   // to a ptr-to-function, use the deduced arguments from the conversion
3858   // function to specialize the corresponding call operator.
3859   //   e.g., int (*fp)(int) = [](auto a) { return a; };
3860   if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3861 
3862     // Get the return type of the destination ptr-to-function we are converting
3863     // to.  This is necessary for matching the lambda call operator's return
3864     // type to that of the destination ptr-to-function's return type.
3865     assert(A->isPointerType() &&
3866         "Can only convert from lambda to ptr-to-function");
3867     const FunctionType *ToFunType =
3868         A->getPointeeType().getTypePtr()->getAs<FunctionType>();
3869     const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3870 
3871     // Create the corresponding specializations of the call operator and
3872     // the static-invoker; and if the return type is auto,
3873     // deduce the return type and check if it matches the
3874     // DestFunctionPtrReturnType.
3875     // For instance:
3876     //   auto L = [](auto a) { return f(a); };
3877     //   int (*fp)(int) = L;
3878     //   char (*fp2)(int) = L; <-- Not OK.
3879 
3880     Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3881         Specialization, Deduced, DestFunctionPtrReturnType,
3882         Info, *this);
3883   }
3884   return Result;
3885 }
3886 
3887 /// \brief Deduce template arguments for a function template when there is
3888 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3889 ///
3890 /// \param FunctionTemplate the function template for which we are performing
3891 /// template argument deduction.
3892 ///
3893 /// \param ExplicitTemplateArgs the explicitly-specified template
3894 /// arguments.
3895 ///
3896 /// \param Specialization if template argument deduction was successful,
3897 /// this will be set to the function template specialization produced by
3898 /// template argument deduction.
3899 ///
3900 /// \param Info the argument will be updated to provide additional information
3901 /// about template argument deduction.
3902 ///
3903 /// \returns the result of template argument deduction.
3904 Sema::TemplateDeductionResult
3905 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3906                               TemplateArgumentListInfo *ExplicitTemplateArgs,
3907                               FunctionDecl *&Specialization,
3908                               TemplateDeductionInfo &Info,
3909                               bool InOverloadResolution) {
3910   return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
3911                                  QualType(), Specialization, Info,
3912                                  InOverloadResolution);
3913 }
3914 
3915 namespace {
3916   /// Substitute the 'auto' type specifier within a type for a given replacement
3917   /// type.
3918   class SubstituteAutoTransform :
3919     public TreeTransform<SubstituteAutoTransform> {
3920     QualType Replacement;
3921   public:
3922     SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3923         : TreeTransform<SubstituteAutoTransform>(SemaRef),
3924           Replacement(Replacement) {}
3925 
3926     QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3927       // If we're building the type pattern to deduce against, don't wrap the
3928       // substituted type in an AutoType. Certain template deduction rules
3929       // apply only when a template type parameter appears directly (and not if
3930       // the parameter is found through desugaring). For instance:
3931       //   auto &&lref = lvalue;
3932       // must transform into "rvalue reference to T" not "rvalue reference to
3933       // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
3934       if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
3935         QualType Result = Replacement;
3936         TemplateTypeParmTypeLoc NewTL =
3937           TLB.push<TemplateTypeParmTypeLoc>(Result);
3938         NewTL.setNameLoc(TL.getNameLoc());
3939         return Result;
3940       } else {
3941         bool Dependent =
3942           !Replacement.isNull() && Replacement->isDependentType();
3943         QualType Result =
3944           SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
3945                                       TL.getTypePtr()->getKeyword(),
3946                                       Dependent);
3947         AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3948         NewTL.setNameLoc(TL.getNameLoc());
3949         return Result;
3950       }
3951     }
3952 
3953     ExprResult TransformLambdaExpr(LambdaExpr *E) {
3954       // Lambdas never need to be transformed.
3955       return E;
3956     }
3957 
3958     QualType Apply(TypeLoc TL) {
3959       // Create some scratch storage for the transformed type locations.
3960       // FIXME: We're just going to throw this information away. Don't build it.
3961       TypeLocBuilder TLB;
3962       TLB.reserve(TL.getFullDataSize());
3963       return TransformType(TLB, TL);
3964     }
3965   };
3966 }
3967 
3968 Sema::DeduceAutoResult
3969 Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3970   return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3971 }
3972 
3973 /// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
3974 ///
3975 /// \param Type the type pattern using the auto type-specifier.
3976 /// \param Init the initializer for the variable whose type is to be deduced.
3977 /// \param Result if type deduction was successful, this will be set to the
3978 ///        deduced type.
3979 Sema::DeduceAutoResult
3980 Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
3981   if (Init->getType()->isNonOverloadPlaceholderType()) {
3982     ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3983     if (NonPlaceholder.isInvalid())
3984       return DAR_FailedAlreadyDiagnosed;
3985     Init = NonPlaceholder.get();
3986   }
3987 
3988   if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
3989     Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
3990     assert(!Result.isNull() && "substituting DependentTy can't fail");
3991     return DAR_Succeeded;
3992   }
3993 
3994   // If this is a 'decltype(auto)' specifier, do the decltype dance.
3995   // Since 'decltype(auto)' can only occur at the top of the type, we
3996   // don't need to go digging for it.
3997   if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
3998     if (AT->isDecltypeAuto()) {
3999       if (isa<InitListExpr>(Init)) {
4000         Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4001         return DAR_FailedAlreadyDiagnosed;
4002       }
4003 
4004       QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
4005       if (Deduced.isNull())
4006         return DAR_FailedAlreadyDiagnosed;
4007       // FIXME: Support a non-canonical deduced type for 'auto'.
4008       Deduced = Context.getCanonicalType(Deduced);
4009       Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
4010       if (Result.isNull())
4011         return DAR_FailedAlreadyDiagnosed;
4012       return DAR_Succeeded;
4013     } else if (!getLangOpts().CPlusPlus) {
4014       if (isa<InitListExpr>(Init)) {
4015         Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4016         return DAR_FailedAlreadyDiagnosed;
4017       }
4018     }
4019   }
4020 
4021   SourceLocation Loc = Init->getExprLoc();
4022 
4023   LocalInstantiationScope InstScope(*this);
4024 
4025   // Build template<class TemplParam> void Func(FuncParam);
4026   TemplateTypeParmDecl *TemplParam =
4027     TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4028                                  nullptr, false, false);
4029   QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4030   NamedDecl *TemplParamPtr = TemplParam;
4031   FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4032       Loc, Loc, TemplParamPtr, Loc, nullptr);
4033 
4034   QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4035   assert(!FuncParam.isNull() &&
4036          "substituting template parameter for 'auto' failed");
4037 
4038   // Deduce type of TemplParam in Func(Init)
4039   SmallVector<DeducedTemplateArgument, 1> Deduced;
4040   Deduced.resize(1);
4041   QualType InitType = Init->getType();
4042   unsigned TDF = 0;
4043 
4044   TemplateDeductionInfo Info(Loc);
4045 
4046   InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
4047   if (InitList) {
4048     for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
4049       if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4050                                               TemplArg, InitList->getInit(i),
4051                                               Info, Deduced, TDF))
4052         return DAR_Failed;
4053     }
4054   } else {
4055     if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4056       Diag(Loc, diag::err_auto_bitfield);
4057       return DAR_FailedAlreadyDiagnosed;
4058     }
4059 
4060     if (AdjustFunctionParmAndArgTypesForDeduction(
4061             *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
4062       return DAR_Failed;
4063 
4064     if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4065                                            FuncParam, InitType, Info, Deduced,
4066                                            TDF))
4067       return DAR_Failed;
4068   }
4069 
4070   if (Deduced[0].getKind() != TemplateArgument::Type)
4071     return DAR_Failed;
4072 
4073   QualType DeducedType = Deduced[0].getAsType();
4074 
4075   if (InitList) {
4076     DeducedType = BuildStdInitializerList(DeducedType, Loc);
4077     if (DeducedType.isNull())
4078       return DAR_FailedAlreadyDiagnosed;
4079   }
4080 
4081   Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
4082   if (Result.isNull())
4083    return DAR_FailedAlreadyDiagnosed;
4084 
4085   // Check that the deduced argument type is compatible with the original
4086   // argument type per C++ [temp.deduct.call]p4.
4087   if (!InitList && !Result.isNull() &&
4088       CheckOriginalCallArgDeduction(*this,
4089                                     Sema::OriginalCallArg(FuncParam,0,InitType),
4090                                     Result)) {
4091     Result = QualType();
4092     return DAR_Failed;
4093   }
4094 
4095   return DAR_Succeeded;
4096 }
4097 
4098 QualType Sema::SubstAutoType(QualType TypeWithAuto,
4099                              QualType TypeToReplaceAuto) {
4100   return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4101                TransformType(TypeWithAuto);
4102 }
4103 
4104 TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4105                              QualType TypeToReplaceAuto) {
4106     return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4107                TransformType(TypeWithAuto);
4108 }
4109 
4110 void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4111   if (isa<InitListExpr>(Init))
4112     Diag(VDecl->getLocation(),
4113          VDecl->isInitCapture()
4114              ? diag::err_init_capture_deduction_failure_from_init_list
4115              : diag::err_auto_var_deduction_failure_from_init_list)
4116       << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4117   else
4118     Diag(VDecl->getLocation(),
4119          VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4120                                 : diag::err_auto_var_deduction_failure)
4121       << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4122       << Init->getSourceRange();
4123 }
4124 
4125 bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4126                             bool Diagnose) {
4127   assert(FD->getReturnType()->isUndeducedType());
4128 
4129   if (FD->getTemplateInstantiationPattern())
4130     InstantiateFunctionDefinition(Loc, FD);
4131 
4132   bool StillUndeduced = FD->getReturnType()->isUndeducedType();
4133   if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4134     Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4135     Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4136   }
4137 
4138   return StillUndeduced;
4139 }
4140 
4141 static void
4142 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
4143                            bool OnlyDeduced,
4144                            unsigned Level,
4145                            llvm::SmallBitVector &Deduced);
4146 
4147 /// \brief If this is a non-static member function,
4148 static void
4149 AddImplicitObjectParameterType(ASTContext &Context,
4150                                CXXMethodDecl *Method,
4151                                SmallVectorImpl<QualType> &ArgTypes) {
4152   // C++11 [temp.func.order]p3:
4153   //   [...] The new parameter is of type "reference to cv A," where cv are
4154   //   the cv-qualifiers of the function template (if any) and A is
4155   //   the class of which the function template is a member.
4156   //
4157   // The standard doesn't say explicitly, but we pick the appropriate kind of
4158   // reference type based on [over.match.funcs]p4.
4159   QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4160   ArgTy = Context.getQualifiedType(ArgTy,
4161                         Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
4162   if (Method->getRefQualifier() == RQ_RValue)
4163     ArgTy = Context.getRValueReferenceType(ArgTy);
4164   else
4165     ArgTy = Context.getLValueReferenceType(ArgTy);
4166   ArgTypes.push_back(ArgTy);
4167 }
4168 
4169 /// \brief Determine whether the function template \p FT1 is at least as
4170 /// specialized as \p FT2.
4171 static bool isAtLeastAsSpecializedAs(Sema &S,
4172                                      SourceLocation Loc,
4173                                      FunctionTemplateDecl *FT1,
4174                                      FunctionTemplateDecl *FT2,
4175                                      TemplatePartialOrderingContext TPOC,
4176                                      unsigned NumCallArguments1) {
4177   FunctionDecl *FD1 = FT1->getTemplatedDecl();
4178   FunctionDecl *FD2 = FT2->getTemplatedDecl();
4179   const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4180   const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
4181 
4182   assert(Proto1 && Proto2 && "Function templates must have prototypes");
4183   TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
4184   SmallVector<DeducedTemplateArgument, 4> Deduced;
4185   Deduced.resize(TemplateParams->size());
4186 
4187   // C++0x [temp.deduct.partial]p3:
4188   //   The types used to determine the ordering depend on the context in which
4189   //   the partial ordering is done:
4190   TemplateDeductionInfo Info(Loc);
4191   SmallVector<QualType, 4> Args2;
4192   switch (TPOC) {
4193   case TPOC_Call: {
4194     //   - In the context of a function call, the function parameter types are
4195     //     used.
4196     CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4197     CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
4198 
4199     // C++11 [temp.func.order]p3:
4200     //   [...] If only one of the function templates is a non-static
4201     //   member, that function template is considered to have a new
4202     //   first parameter inserted in its function parameter list. The
4203     //   new parameter is of type "reference to cv A," where cv are
4204     //   the cv-qualifiers of the function template (if any) and A is
4205     //   the class of which the function template is a member.
4206     //
4207     // Note that we interpret this to mean "if one of the function
4208     // templates is a non-static member and the other is a non-member";
4209     // otherwise, the ordering rules for static functions against non-static
4210     // functions don't make any sense.
4211     //
4212     // C++98/03 doesn't have this provision but we've extended DR532 to cover
4213     // it as wording was broken prior to it.
4214     SmallVector<QualType, 4> Args1;
4215 
4216     unsigned NumComparedArguments = NumCallArguments1;
4217 
4218     if (!Method2 && Method1 && !Method1->isStatic()) {
4219       // Compare 'this' from Method1 against first parameter from Method2.
4220       AddImplicitObjectParameterType(S.Context, Method1, Args1);
4221       ++NumComparedArguments;
4222     } else if (!Method1 && Method2 && !Method2->isStatic()) {
4223       // Compare 'this' from Method2 against first parameter from Method1.
4224       AddImplicitObjectParameterType(S.Context, Method2, Args2);
4225     }
4226 
4227     Args1.insert(Args1.end(), Proto1->param_type_begin(),
4228                  Proto1->param_type_end());
4229     Args2.insert(Args2.end(), Proto2->param_type_begin(),
4230                  Proto2->param_type_end());
4231 
4232     // C++ [temp.func.order]p5:
4233     //   The presence of unused ellipsis and default arguments has no effect on
4234     //   the partial ordering of function templates.
4235     if (Args1.size() > NumComparedArguments)
4236       Args1.resize(NumComparedArguments);
4237     if (Args2.size() > NumComparedArguments)
4238       Args2.resize(NumComparedArguments);
4239     if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4240                                 Args1.data(), Args1.size(), Info, Deduced,
4241                                 TDF_None, /*PartialOrdering=*/true))
4242       return false;
4243 
4244     break;
4245   }
4246 
4247   case TPOC_Conversion:
4248     //   - In the context of a call to a conversion operator, the return types
4249     //     of the conversion function templates are used.
4250     if (DeduceTemplateArgumentsByTypeMatch(
4251             S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4252             Info, Deduced, TDF_None,
4253             /*PartialOrdering=*/true))
4254       return false;
4255     break;
4256 
4257   case TPOC_Other:
4258     //   - In other contexts (14.6.6.2) the function template's function type
4259     //     is used.
4260     if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4261                                            FD2->getType(), FD1->getType(),
4262                                            Info, Deduced, TDF_None,
4263                                            /*PartialOrdering=*/true))
4264       return false;
4265     break;
4266   }
4267 
4268   // C++0x [temp.deduct.partial]p11:
4269   //   In most cases, all template parameters must have values in order for
4270   //   deduction to succeed, but for partial ordering purposes a template
4271   //   parameter may remain without a value provided it is not used in the
4272   //   types being used for partial ordering. [ Note: a template parameter used
4273   //   in a non-deduced context is considered used. -end note]
4274   unsigned ArgIdx = 0, NumArgs = Deduced.size();
4275   for (; ArgIdx != NumArgs; ++ArgIdx)
4276     if (Deduced[ArgIdx].isNull())
4277       break;
4278 
4279   if (ArgIdx == NumArgs) {
4280     // All template arguments were deduced. FT1 is at least as specialized
4281     // as FT2.
4282     return true;
4283   }
4284 
4285   // Figure out which template parameters were used.
4286   llvm::SmallBitVector UsedParameters(TemplateParams->size());
4287   switch (TPOC) {
4288   case TPOC_Call:
4289     for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4290       ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4291                                    TemplateParams->getDepth(),
4292                                    UsedParameters);
4293     break;
4294 
4295   case TPOC_Conversion:
4296     ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4297                                  TemplateParams->getDepth(), UsedParameters);
4298     break;
4299 
4300   case TPOC_Other:
4301     ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4302                                  TemplateParams->getDepth(),
4303                                  UsedParameters);
4304     break;
4305   }
4306 
4307   for (; ArgIdx != NumArgs; ++ArgIdx)
4308     // If this argument had no value deduced but was used in one of the types
4309     // used for partial ordering, then deduction fails.
4310     if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4311       return false;
4312 
4313   return true;
4314 }
4315 
4316 /// \brief Determine whether this a function template whose parameter-type-list
4317 /// ends with a function parameter pack.
4318 static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4319   FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4320   unsigned NumParams = Function->getNumParams();
4321   if (NumParams == 0)
4322     return false;
4323 
4324   ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4325   if (!Last->isParameterPack())
4326     return false;
4327 
4328   // Make sure that no previous parameter is a parameter pack.
4329   while (--NumParams > 0) {
4330     if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4331       return false;
4332   }
4333 
4334   return true;
4335 }
4336 
4337 /// \brief Returns the more specialized function template according
4338 /// to the rules of function template partial ordering (C++ [temp.func.order]).
4339 ///
4340 /// \param FT1 the first function template
4341 ///
4342 /// \param FT2 the second function template
4343 ///
4344 /// \param TPOC the context in which we are performing partial ordering of
4345 /// function templates.
4346 ///
4347 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
4348 /// only when \c TPOC is \c TPOC_Call.
4349 ///
4350 /// \param NumCallArguments2 The number of arguments in the call to FT2, used
4351 /// only when \c TPOC is \c TPOC_Call.
4352 ///
4353 /// \returns the more specialized function template. If neither
4354 /// template is more specialized, returns NULL.
4355 FunctionTemplateDecl *
4356 Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4357                                  FunctionTemplateDecl *FT2,
4358                                  SourceLocation Loc,
4359                                  TemplatePartialOrderingContext TPOC,
4360                                  unsigned NumCallArguments1,
4361                                  unsigned NumCallArguments2) {
4362   bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
4363                                           NumCallArguments1);
4364   bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
4365                                           NumCallArguments2);
4366 
4367   if (Better1 != Better2) // We have a clear winner
4368     return Better1 ? FT1 : FT2;
4369 
4370   if (!Better1 && !Better2) // Neither is better than the other
4371     return nullptr;
4372 
4373   // FIXME: This mimics what GCC implements, but doesn't match up with the
4374   // proposed resolution for core issue 692. This area needs to be sorted out,
4375   // but for now we attempt to maintain compatibility.
4376   bool Variadic1 = isVariadicFunctionTemplate(FT1);
4377   bool Variadic2 = isVariadicFunctionTemplate(FT2);
4378   if (Variadic1 != Variadic2)
4379     return Variadic1? FT2 : FT1;
4380 
4381   return nullptr;
4382 }
4383 
4384 /// \brief Determine if the two templates are equivalent.
4385 static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4386   if (T1 == T2)
4387     return true;
4388 
4389   if (!T1 || !T2)
4390     return false;
4391 
4392   return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4393 }
4394 
4395 /// \brief Retrieve the most specialized of the given function template
4396 /// specializations.
4397 ///
4398 /// \param SpecBegin the start iterator of the function template
4399 /// specializations that we will be comparing.
4400 ///
4401 /// \param SpecEnd the end iterator of the function template
4402 /// specializations, paired with \p SpecBegin.
4403 ///
4404 /// \param Loc the location where the ambiguity or no-specializations
4405 /// diagnostic should occur.
4406 ///
4407 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
4408 /// no matching candidates.
4409 ///
4410 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4411 /// occurs.
4412 ///
4413 /// \param CandidateDiag partial diagnostic used for each function template
4414 /// specialization that is a candidate in the ambiguous ordering. One parameter
4415 /// in this diagnostic should be unbound, which will correspond to the string
4416 /// describing the template arguments for the function template specialization.
4417 ///
4418 /// \returns the most specialized function template specialization, if
4419 /// found. Otherwise, returns SpecEnd.
4420 UnresolvedSetIterator Sema::getMostSpecialized(
4421     UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4422     TemplateSpecCandidateSet &FailedCandidates,
4423     SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4424     const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4425     bool Complain, QualType TargetType) {
4426   if (SpecBegin == SpecEnd) {
4427     if (Complain) {
4428       Diag(Loc, NoneDiag);
4429       FailedCandidates.NoteCandidates(*this, Loc);
4430     }
4431     return SpecEnd;
4432   }
4433 
4434   if (SpecBegin + 1 == SpecEnd)
4435     return SpecBegin;
4436 
4437   // Find the function template that is better than all of the templates it
4438   // has been compared to.
4439   UnresolvedSetIterator Best = SpecBegin;
4440   FunctionTemplateDecl *BestTemplate
4441     = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
4442   assert(BestTemplate && "Not a function template specialization?");
4443   for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4444     FunctionTemplateDecl *Challenger
4445       = cast<FunctionDecl>(*I)->getPrimaryTemplate();
4446     assert(Challenger && "Not a function template specialization?");
4447     if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
4448                                                   Loc, TPOC_Other, 0, 0),
4449                        Challenger)) {
4450       Best = I;
4451       BestTemplate = Challenger;
4452     }
4453   }
4454 
4455   // Make sure that the "best" function template is more specialized than all
4456   // of the others.
4457   bool Ambiguous = false;
4458   for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4459     FunctionTemplateDecl *Challenger
4460       = cast<FunctionDecl>(*I)->getPrimaryTemplate();
4461     if (I != Best &&
4462         !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
4463                                                    Loc, TPOC_Other, 0, 0),
4464                         BestTemplate)) {
4465       Ambiguous = true;
4466       break;
4467     }
4468   }
4469 
4470   if (!Ambiguous) {
4471     // We found an answer. Return it.
4472     return Best;
4473   }
4474 
4475   // Diagnose the ambiguity.
4476   if (Complain) {
4477     Diag(Loc, AmbigDiag);
4478 
4479     // FIXME: Can we order the candidates in some sane way?
4480     for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4481       PartialDiagnostic PD = CandidateDiag;
4482       PD << getTemplateArgumentBindingsText(
4483           cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
4484                     *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
4485       if (!TargetType.isNull())
4486         HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4487                                    TargetType);
4488       Diag((*I)->getLocation(), PD);
4489     }
4490   }
4491 
4492   return SpecEnd;
4493 }
4494 
4495 /// \brief Returns the more specialized class template partial specialization
4496 /// according to the rules of partial ordering of class template partial
4497 /// specializations (C++ [temp.class.order]).
4498 ///
4499 /// \param PS1 the first class template partial specialization
4500 ///
4501 /// \param PS2 the second class template partial specialization
4502 ///
4503 /// \returns the more specialized class template partial specialization. If
4504 /// neither partial specialization is more specialized, returns NULL.
4505 ClassTemplatePartialSpecializationDecl *
4506 Sema::getMoreSpecializedPartialSpecialization(
4507                                   ClassTemplatePartialSpecializationDecl *PS1,
4508                                   ClassTemplatePartialSpecializationDecl *PS2,
4509                                               SourceLocation Loc) {
4510   // C++ [temp.class.order]p1:
4511   //   For two class template partial specializations, the first is at least as
4512   //   specialized as the second if, given the following rewrite to two
4513   //   function templates, the first function template is at least as
4514   //   specialized as the second according to the ordering rules for function
4515   //   templates (14.6.6.2):
4516   //     - the first function template has the same template parameters as the
4517   //       first partial specialization and has a single function parameter
4518   //       whose type is a class template specialization with the template
4519   //       arguments of the first partial specialization, and
4520   //     - the second function template has the same template parameters as the
4521   //       second partial specialization and has a single function parameter
4522   //       whose type is a class template specialization with the template
4523   //       arguments of the second partial specialization.
4524   //
4525   // Rather than synthesize function templates, we merely perform the
4526   // equivalent partial ordering by performing deduction directly on
4527   // the template arguments of the class template partial
4528   // specializations. This computation is slightly simpler than the
4529   // general problem of function template partial ordering, because
4530   // class template partial specializations are more constrained. We
4531   // know that every template parameter is deducible from the class
4532   // template partial specialization's template arguments, for
4533   // example.
4534   SmallVector<DeducedTemplateArgument, 4> Deduced;
4535   TemplateDeductionInfo Info(Loc);
4536 
4537   QualType PT1 = PS1->getInjectedSpecializationType();
4538   QualType PT2 = PS2->getInjectedSpecializationType();
4539 
4540   // Determine whether PS1 is at least as specialized as PS2
4541   Deduced.resize(PS2->getTemplateParameters()->size());
4542   bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4543                                             PS2->getTemplateParameters(),
4544                                             PT2, PT1, Info, Deduced, TDF_None,
4545                                             /*PartialOrdering=*/true);
4546   if (Better1) {
4547     SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
4548     InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
4549     Better1 = !::FinishTemplateArgumentDeduction(
4550         *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4551   }
4552 
4553   // Determine whether PS2 is at least as specialized as PS1
4554   Deduced.clear();
4555   Deduced.resize(PS1->getTemplateParameters()->size());
4556   bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4557       *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
4558       /*PartialOrdering=*/true);
4559   if (Better2) {
4560     SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4561                                                  Deduced.end());
4562     InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
4563     Better2 = !::FinishTemplateArgumentDeduction(
4564         *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4565   }
4566 
4567   if (Better1 == Better2)
4568     return nullptr;
4569 
4570   return Better1 ? PS1 : PS2;
4571 }
4572 
4573 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4574 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
4575 ///        VarTemplate(Partial)SpecializationDecl with a new data
4576 ///        structure Template(Partial)SpecializationDecl, and
4577 ///        using Template(Partial)SpecializationDecl as input type.
4578 VarTemplatePartialSpecializationDecl *
4579 Sema::getMoreSpecializedPartialSpecialization(
4580     VarTemplatePartialSpecializationDecl *PS1,
4581     VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4582   SmallVector<DeducedTemplateArgument, 4> Deduced;
4583   TemplateDeductionInfo Info(Loc);
4584 
4585   assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
4586          "the partial specializations being compared should specialize"
4587          " the same template.");
4588   TemplateName Name(PS1->getSpecializedTemplate());
4589   TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4590   QualType PT1 = Context.getTemplateSpecializationType(
4591       CanonTemplate, PS1->getTemplateArgs().asArray());
4592   QualType PT2 = Context.getTemplateSpecializationType(
4593       CanonTemplate, PS2->getTemplateArgs().asArray());
4594 
4595   // Determine whether PS1 is at least as specialized as PS2
4596   Deduced.resize(PS2->getTemplateParameters()->size());
4597   bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4598       *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
4599       /*PartialOrdering=*/true);
4600   if (Better1) {
4601     SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4602                                                  Deduced.end());
4603     InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
4604     Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4605                                                  PS1->getTemplateArgs(),
4606                                                  Deduced, Info);
4607   }
4608 
4609   // Determine whether PS2 is at least as specialized as PS1
4610   Deduced.clear();
4611   Deduced.resize(PS1->getTemplateParameters()->size());
4612   bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4613                                             PS1->getTemplateParameters(),
4614                                             PT1, PT2, Info, Deduced, TDF_None,
4615                                             /*PartialOrdering=*/true);
4616   if (Better2) {
4617     SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
4618     InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
4619     Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4620                                                  PS2->getTemplateArgs(),
4621                                                  Deduced, Info);
4622   }
4623 
4624   if (Better1 == Better2)
4625     return nullptr;
4626 
4627   return Better1? PS1 : PS2;
4628 }
4629 
4630 static void
4631 MarkUsedTemplateParameters(ASTContext &Ctx,
4632                            const TemplateArgument &TemplateArg,
4633                            bool OnlyDeduced,
4634                            unsigned Depth,
4635                            llvm::SmallBitVector &Used);
4636 
4637 /// \brief Mark the template parameters that are used by the given
4638 /// expression.
4639 static void
4640 MarkUsedTemplateParameters(ASTContext &Ctx,
4641                            const Expr *E,
4642                            bool OnlyDeduced,
4643                            unsigned Depth,
4644                            llvm::SmallBitVector &Used) {
4645   // We can deduce from a pack expansion.
4646   if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4647     E = Expansion->getPattern();
4648 
4649   // Skip through any implicit casts we added while type-checking, and any
4650   // substitutions performed by template alias expansion.
4651   while (1) {
4652     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4653       E = ICE->getSubExpr();
4654     else if (const SubstNonTypeTemplateParmExpr *Subst =
4655                dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4656       E = Subst->getReplacement();
4657     else
4658       break;
4659   }
4660 
4661   // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
4662   // find other occurrences of template parameters.
4663   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
4664   if (!DRE)
4665     return;
4666 
4667   const NonTypeTemplateParmDecl *NTTP
4668     = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4669   if (!NTTP)
4670     return;
4671 
4672   if (NTTP->getDepth() == Depth)
4673     Used[NTTP->getIndex()] = true;
4674 }
4675 
4676 /// \brief Mark the template parameters that are used by the given
4677 /// nested name specifier.
4678 static void
4679 MarkUsedTemplateParameters(ASTContext &Ctx,
4680                            NestedNameSpecifier *NNS,
4681                            bool OnlyDeduced,
4682                            unsigned Depth,
4683                            llvm::SmallBitVector &Used) {
4684   if (!NNS)
4685     return;
4686 
4687   MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
4688                              Used);
4689   MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
4690                              OnlyDeduced, Depth, Used);
4691 }
4692 
4693 /// \brief Mark the template parameters that are used by the given
4694 /// template name.
4695 static void
4696 MarkUsedTemplateParameters(ASTContext &Ctx,
4697                            TemplateName Name,
4698                            bool OnlyDeduced,
4699                            unsigned Depth,
4700                            llvm::SmallBitVector &Used) {
4701   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4702     if (TemplateTemplateParmDecl *TTP
4703           = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4704       if (TTP->getDepth() == Depth)
4705         Used[TTP->getIndex()] = true;
4706     }
4707     return;
4708   }
4709 
4710   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
4711     MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
4712                                Depth, Used);
4713   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
4714     MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
4715                                Depth, Used);
4716 }
4717 
4718 /// \brief Mark the template parameters that are used by the given
4719 /// type.
4720 static void
4721 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
4722                            bool OnlyDeduced,
4723                            unsigned Depth,
4724                            llvm::SmallBitVector &Used) {
4725   if (T.isNull())
4726     return;
4727 
4728   // Non-dependent types have nothing deducible
4729   if (!T->isDependentType())
4730     return;
4731 
4732   T = Ctx.getCanonicalType(T);
4733   switch (T->getTypeClass()) {
4734   case Type::Pointer:
4735     MarkUsedTemplateParameters(Ctx,
4736                                cast<PointerType>(T)->getPointeeType(),
4737                                OnlyDeduced,
4738                                Depth,
4739                                Used);
4740     break;
4741 
4742   case Type::BlockPointer:
4743     MarkUsedTemplateParameters(Ctx,
4744                                cast<BlockPointerType>(T)->getPointeeType(),
4745                                OnlyDeduced,
4746                                Depth,
4747                                Used);
4748     break;
4749 
4750   case Type::LValueReference:
4751   case Type::RValueReference:
4752     MarkUsedTemplateParameters(Ctx,
4753                                cast<ReferenceType>(T)->getPointeeType(),
4754                                OnlyDeduced,
4755                                Depth,
4756                                Used);
4757     break;
4758 
4759   case Type::MemberPointer: {
4760     const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
4761     MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
4762                                Depth, Used);
4763     MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
4764                                OnlyDeduced, Depth, Used);
4765     break;
4766   }
4767 
4768   case Type::DependentSizedArray:
4769     MarkUsedTemplateParameters(Ctx,
4770                                cast<DependentSizedArrayType>(T)->getSizeExpr(),
4771                                OnlyDeduced, Depth, Used);
4772     // Fall through to check the element type
4773 
4774   case Type::ConstantArray:
4775   case Type::IncompleteArray:
4776     MarkUsedTemplateParameters(Ctx,
4777                                cast<ArrayType>(T)->getElementType(),
4778                                OnlyDeduced, Depth, Used);
4779     break;
4780 
4781   case Type::Vector:
4782   case Type::ExtVector:
4783     MarkUsedTemplateParameters(Ctx,
4784                                cast<VectorType>(T)->getElementType(),
4785                                OnlyDeduced, Depth, Used);
4786     break;
4787 
4788   case Type::DependentSizedExtVector: {
4789     const DependentSizedExtVectorType *VecType
4790       = cast<DependentSizedExtVectorType>(T);
4791     MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
4792                                Depth, Used);
4793     MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
4794                                Depth, Used);
4795     break;
4796   }
4797 
4798   case Type::FunctionProto: {
4799     const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
4800     MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4801                                Used);
4802     for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4803       MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
4804                                  Depth, Used);
4805     break;
4806   }
4807 
4808   case Type::TemplateTypeParm: {
4809     const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4810     if (TTP->getDepth() == Depth)
4811       Used[TTP->getIndex()] = true;
4812     break;
4813   }
4814 
4815   case Type::SubstTemplateTypeParmPack: {
4816     const SubstTemplateTypeParmPackType *Subst
4817       = cast<SubstTemplateTypeParmPackType>(T);
4818     MarkUsedTemplateParameters(Ctx,
4819                                QualType(Subst->getReplacedParameter(), 0),
4820                                OnlyDeduced, Depth, Used);
4821     MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
4822                                OnlyDeduced, Depth, Used);
4823     break;
4824   }
4825 
4826   case Type::InjectedClassName:
4827     T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4828     // fall through
4829 
4830   case Type::TemplateSpecialization: {
4831     const TemplateSpecializationType *Spec
4832       = cast<TemplateSpecializationType>(T);
4833     MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
4834                                Depth, Used);
4835 
4836     // C++0x [temp.deduct.type]p9:
4837     //   If the template argument list of P contains a pack expansion that is
4838     //   not the last template argument, the entire template argument list is a
4839     //   non-deduced context.
4840     if (OnlyDeduced &&
4841         hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4842       break;
4843 
4844     for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
4845       MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
4846                                  Used);
4847     break;
4848   }
4849 
4850   case Type::Complex:
4851     if (!OnlyDeduced)
4852       MarkUsedTemplateParameters(Ctx,
4853                                  cast<ComplexType>(T)->getElementType(),
4854                                  OnlyDeduced, Depth, Used);
4855     break;
4856 
4857   case Type::Atomic:
4858     if (!OnlyDeduced)
4859       MarkUsedTemplateParameters(Ctx,
4860                                  cast<AtomicType>(T)->getValueType(),
4861                                  OnlyDeduced, Depth, Used);
4862     break;
4863 
4864   case Type::DependentName:
4865     if (!OnlyDeduced)
4866       MarkUsedTemplateParameters(Ctx,
4867                                  cast<DependentNameType>(T)->getQualifier(),
4868                                  OnlyDeduced, Depth, Used);
4869     break;
4870 
4871   case Type::DependentTemplateSpecialization: {
4872     // C++14 [temp.deduct.type]p5:
4873     //   The non-deduced contexts are:
4874     //     -- The nested-name-specifier of a type that was specified using a
4875     //        qualified-id
4876     //
4877     // C++14 [temp.deduct.type]p6:
4878     //   When a type name is specified in a way that includes a non-deduced
4879     //   context, all of the types that comprise that type name are also
4880     //   non-deduced.
4881     if (OnlyDeduced)
4882       break;
4883 
4884     const DependentTemplateSpecializationType *Spec
4885       = cast<DependentTemplateSpecializationType>(T);
4886 
4887     MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4888                                OnlyDeduced, Depth, Used);
4889 
4890     for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
4891       MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
4892                                  Used);
4893     break;
4894   }
4895 
4896   case Type::TypeOf:
4897     if (!OnlyDeduced)
4898       MarkUsedTemplateParameters(Ctx,
4899                                  cast<TypeOfType>(T)->getUnderlyingType(),
4900                                  OnlyDeduced, Depth, Used);
4901     break;
4902 
4903   case Type::TypeOfExpr:
4904     if (!OnlyDeduced)
4905       MarkUsedTemplateParameters(Ctx,
4906                                  cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4907                                  OnlyDeduced, Depth, Used);
4908     break;
4909 
4910   case Type::Decltype:
4911     if (!OnlyDeduced)
4912       MarkUsedTemplateParameters(Ctx,
4913                                  cast<DecltypeType>(T)->getUnderlyingExpr(),
4914                                  OnlyDeduced, Depth, Used);
4915     break;
4916 
4917   case Type::UnaryTransform:
4918     if (!OnlyDeduced)
4919       MarkUsedTemplateParameters(Ctx,
4920                                cast<UnaryTransformType>(T)->getUnderlyingType(),
4921                                  OnlyDeduced, Depth, Used);
4922     break;
4923 
4924   case Type::PackExpansion:
4925     MarkUsedTemplateParameters(Ctx,
4926                                cast<PackExpansionType>(T)->getPattern(),
4927                                OnlyDeduced, Depth, Used);
4928     break;
4929 
4930   case Type::Auto:
4931     MarkUsedTemplateParameters(Ctx,
4932                                cast<AutoType>(T)->getDeducedType(),
4933                                OnlyDeduced, Depth, Used);
4934 
4935   // None of these types have any template parameters in them.
4936   case Type::Builtin:
4937   case Type::VariableArray:
4938   case Type::FunctionNoProto:
4939   case Type::Record:
4940   case Type::Enum:
4941   case Type::ObjCInterface:
4942   case Type::ObjCObject:
4943   case Type::ObjCObjectPointer:
4944   case Type::UnresolvedUsing:
4945   case Type::Pipe:
4946 #define TYPE(Class, Base)
4947 #define ABSTRACT_TYPE(Class, Base)
4948 #define DEPENDENT_TYPE(Class, Base)
4949 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4950 #include "clang/AST/TypeNodes.def"
4951     break;
4952   }
4953 }
4954 
4955 /// \brief Mark the template parameters that are used by this
4956 /// template argument.
4957 static void
4958 MarkUsedTemplateParameters(ASTContext &Ctx,
4959                            const TemplateArgument &TemplateArg,
4960                            bool OnlyDeduced,
4961                            unsigned Depth,
4962                            llvm::SmallBitVector &Used) {
4963   switch (TemplateArg.getKind()) {
4964   case TemplateArgument::Null:
4965   case TemplateArgument::Integral:
4966   case TemplateArgument::Declaration:
4967     break;
4968 
4969   case TemplateArgument::NullPtr:
4970     MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4971                                Depth, Used);
4972     break;
4973 
4974   case TemplateArgument::Type:
4975     MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
4976                                Depth, Used);
4977     break;
4978 
4979   case TemplateArgument::Template:
4980   case TemplateArgument::TemplateExpansion:
4981     MarkUsedTemplateParameters(Ctx,
4982                                TemplateArg.getAsTemplateOrTemplatePattern(),
4983                                OnlyDeduced, Depth, Used);
4984     break;
4985 
4986   case TemplateArgument::Expression:
4987     MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
4988                                Depth, Used);
4989     break;
4990 
4991   case TemplateArgument::Pack:
4992     for (const auto &P : TemplateArg.pack_elements())
4993       MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
4994     break;
4995   }
4996 }
4997 
4998 /// \brief Mark which template parameters can be deduced from a given
4999 /// template argument list.
5000 ///
5001 /// \param TemplateArgs the template argument list from which template
5002 /// parameters will be deduced.
5003 ///
5004 /// \param Used a bit vector whose elements will be set to \c true
5005 /// to indicate when the corresponding template parameter will be
5006 /// deduced.
5007 void
5008 Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5009                                  bool OnlyDeduced, unsigned Depth,
5010                                  llvm::SmallBitVector &Used) {
5011   // C++0x [temp.deduct.type]p9:
5012   //   If the template argument list of P contains a pack expansion that is not
5013   //   the last template argument, the entire template argument list is a
5014   //   non-deduced context.
5015   if (OnlyDeduced &&
5016       hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5017     return;
5018 
5019   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5020     ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
5021                                  Depth, Used);
5022 }
5023 
5024 /// \brief Marks all of the template parameters that will be deduced by a
5025 /// call to the given function template.
5026 void Sema::MarkDeducedTemplateParameters(
5027     ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5028     llvm::SmallBitVector &Deduced) {
5029   TemplateParameterList *TemplateParams
5030     = FunctionTemplate->getTemplateParameters();
5031   Deduced.clear();
5032   Deduced.resize(TemplateParams->size());
5033 
5034   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5035   for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
5036     ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
5037                                  true, TemplateParams->getDepth(), Deduced);
5038 }
5039 
5040 bool hasDeducibleTemplateParameters(Sema &S,
5041                                     FunctionTemplateDecl *FunctionTemplate,
5042                                     QualType T) {
5043   if (!T->isDependentType())
5044     return false;
5045 
5046   TemplateParameterList *TemplateParams
5047     = FunctionTemplate->getTemplateParameters();
5048   llvm::SmallBitVector Deduced(TemplateParams->size());
5049   ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5050                                Deduced);
5051 
5052   return Deduced.any();
5053 }
5054