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