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