Coverage Report

Created: 2020-02-18 08:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaTemplateDeduction.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements C++ template argument deduction.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Sema/TemplateDeduction.h"
14
#include "TreeTransform.h"
15
#include "TypeLocBuilder.h"
16
#include "clang/AST/ASTContext.h"
17
#include "clang/AST/ASTLambda.h"
18
#include "clang/AST/Decl.h"
19
#include "clang/AST/DeclAccessPair.h"
20
#include "clang/AST/DeclBase.h"
21
#include "clang/AST/DeclCXX.h"
22
#include "clang/AST/DeclTemplate.h"
23
#include "clang/AST/DeclarationName.h"
24
#include "clang/AST/Expr.h"
25
#include "clang/AST/ExprCXX.h"
26
#include "clang/AST/NestedNameSpecifier.h"
27
#include "clang/AST/RecursiveASTVisitor.h"
28
#include "clang/AST/TemplateBase.h"
29
#include "clang/AST/TemplateName.h"
30
#include "clang/AST/Type.h"
31
#include "clang/AST/TypeLoc.h"
32
#include "clang/AST/UnresolvedSet.h"
33
#include "clang/Basic/AddressSpaces.h"
34
#include "clang/Basic/ExceptionSpecificationType.h"
35
#include "clang/Basic/LLVM.h"
36
#include "clang/Basic/LangOptions.h"
37
#include "clang/Basic/PartialDiagnostic.h"
38
#include "clang/Basic/SourceLocation.h"
39
#include "clang/Basic/Specifiers.h"
40
#include "clang/Sema/Ownership.h"
41
#include "clang/Sema/Sema.h"
42
#include "clang/Sema/Template.h"
43
#include "llvm/ADT/APInt.h"
44
#include "llvm/ADT/APSInt.h"
45
#include "llvm/ADT/ArrayRef.h"
46
#include "llvm/ADT/DenseMap.h"
47
#include "llvm/ADT/FoldingSet.h"
48
#include "llvm/ADT/Optional.h"
49
#include "llvm/ADT/SmallBitVector.h"
50
#include "llvm/ADT/SmallPtrSet.h"
51
#include "llvm/ADT/SmallVector.h"
52
#include "llvm/Support/Casting.h"
53
#include "llvm/Support/Compiler.h"
54
#include "llvm/Support/ErrorHandling.h"
55
#include <algorithm>
56
#include <cassert>
57
#include <tuple>
58
#include <utility>
59
60
namespace clang {
61
62
  /// Various flags that control template argument deduction.
63
  ///
64
  /// These flags can be bitwise-OR'd together.
65
  enum TemplateDeductionFlags {
66
    /// No template argument deduction flags, which indicates the
67
    /// strictest results for template argument deduction (as used for, e.g.,
68
    /// matching class template partial specializations).
69
    TDF_None = 0,
70
71
    /// Within template argument deduction from a function call, we are
72
    /// matching with a parameter type for which the original parameter was
73
    /// a reference.
74
    TDF_ParamWithReferenceType = 0x1,
75
76
    /// Within template argument deduction from a function call, we
77
    /// are matching in a case where we ignore cv-qualifiers.
78
    TDF_IgnoreQualifiers = 0x02,
79
80
    /// Within template argument deduction from a function call,
81
    /// we are matching in a case where we can perform template argument
82
    /// deduction from a template-id of a derived class of the argument type.
83
    TDF_DerivedClass = 0x04,
84
85
    /// Allow non-dependent types to differ, e.g., when performing
86
    /// template argument deduction from a function call where conversions
87
    /// may apply.
88
    TDF_SkipNonDependent = 0x08,
89
90
    /// Whether we are performing template argument deduction for
91
    /// parameters and arguments in a top-level template argument
92
    TDF_TopLevelParameterTypeList = 0x10,
93
94
    /// Within template argument deduction from overload resolution per
95
    /// C++ [over.over] allow matching function types that are compatible in
96
    /// terms of noreturn and default calling convention adjustments, or
97
    /// similarly matching a declared template specialization against a
98
    /// possible template, per C++ [temp.deduct.decl]. In either case, permit
99
    /// deduction where the parameter is a function type that can be converted
100
    /// to the argument type.
101
    TDF_AllowCompatibleFunctionType = 0x20,
102
103
    /// Within template argument deduction for a conversion function, we are
104
    /// matching with an argument type for which the original argument was
105
    /// a reference.
106
    TDF_ArgWithReferenceType = 0x40,
107
  };
108
}
109
110
using namespace clang;
111
using namespace sema;
112
113
/// Compare two APSInts, extending and switching the sign as
114
/// necessary to compare their values regardless of underlying type.
115
391k
static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
116
391k
  if (Y.getBitWidth() > X.getBitWidth())
117
12
    X = X.extend(Y.getBitWidth());
118
391k
  else if (Y.getBitWidth() < X.getBitWidth())
119
10
    Y = Y.extend(X.getBitWidth());
120
391k
121
391k
  // If there is a signedness mismatch, correct it.
122
391k
  if (X.isSigned() != Y.isSigned()) {
123
14
    // If the signed value is negative, then the values cannot be the same.
124
14
    if ((Y.isSigned() && 
Y.isNegative()7
) || (X.isSigned() &&
X.isNegative()7
))
125
0
      return false;
126
14
127
14
    Y.setIsSigned(true);
128
14
    X.setIsSigned(true);
129
14
  }
130
391k
131
391k
  return X == Y;
132
391k
}
133
134
static Sema::TemplateDeductionResult
135
DeduceTemplateArguments(Sema &S,
136
                        TemplateParameterList *TemplateParams,
137
                        const TemplateArgument &Param,
138
                        TemplateArgument Arg,
139
                        TemplateDeductionInfo &Info,
140
                        SmallVectorImpl<DeducedTemplateArgument> &Deduced);
141
142
static Sema::TemplateDeductionResult
143
DeduceTemplateArgumentsByTypeMatch(Sema &S,
144
                                   TemplateParameterList *TemplateParams,
145
                                   QualType Param,
146
                                   QualType Arg,
147
                                   TemplateDeductionInfo &Info,
148
                                   SmallVectorImpl<DeducedTemplateArgument> &
149
                                                      Deduced,
150
                                   unsigned TDF,
151
                                   bool PartialOrdering = false,
152
                                   bool DeducedFromArrayBound = false);
153
154
static Sema::TemplateDeductionResult
155
DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
156
                        ArrayRef<TemplateArgument> Params,
157
                        ArrayRef<TemplateArgument> Args,
158
                        TemplateDeductionInfo &Info,
159
                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
160
                        bool NumberOfArgumentsMustMatch);
161
162
static void MarkUsedTemplateParameters(ASTContext &Ctx,
163
                                       const TemplateArgument &TemplateArg,
164
                                       bool OnlyDeduced, unsigned Depth,
165
                                       llvm::SmallBitVector &Used);
166
167
static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
168
                                       bool OnlyDeduced, unsigned Level,
169
                                       llvm::SmallBitVector &Deduced);
170
171
/// If the given expression is of a form that permits the deduction
172
/// of a non-type template parameter, return the declaration of that
173
/// non-type template parameter.
174
static NonTypeTemplateParmDecl *
175
226k
getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
176
226k
  // If we are within an alias template, the expression may have undergone
177
226k
  // any number of parameter substitutions already.
178
226k
  while (true) {
179
226k
    if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
180
269
      E = IC->getSubExpr();
181
226k
    else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(E))
182
0
      E = CE->getSubExpr();
183
226k
    else if (SubstNonTypeTemplateParmExpr *Subst =
184
11
               dyn_cast<SubstNonTypeTemplateParmExpr>(E))
185
11
      E = Subst->getReplacement();
186
226k
    else
187
226k
      break;
188
226k
  }
189
226k
190
226k
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
191
226k
    if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
192
226k
      if (NTTP->getDepth() == Info.getDeducedDepth())
193
226k
        return NTTP;
194
201
195
201
  return nullptr;
196
201
}
197
198
/// Determine whether two declaration pointers refer to the same
199
/// declaration.
200
34
static bool isSameDeclaration(Decl *X, Decl *Y) {
201
34
  if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
202
34
    X = NX->getUnderlyingDecl();
203
34
  if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
204
34
    Y = NY->getUnderlyingDecl();
205
34
206
34
  return X->getCanonicalDecl() == Y->getCanonicalDecl();
207
34
}
208
209
/// Verify that the given, deduced template arguments are compatible.
210
///
211
/// \returns The deduced template argument, or a NULL template argument if
212
/// the deduced template arguments were incompatible.
213
static DeducedTemplateArgument
214
checkDeducedTemplateArguments(ASTContext &Context,
215
                              const DeducedTemplateArgument &X,
216
1.50M
                              const DeducedTemplateArgument &Y) {
217
1.50M
  // We have no deduction for one or both of the arguments; they're compatible.
218
1.50M
  if (X.isNull())
219
1.41M
    return Y;
220
94.5k
  if (Y.isNull())
221
58
    return X;
222
94.4k
223
94.4k
  // If we have two non-type template argument values deduced for the same
224
94.4k
  // parameter, they must both match the type of the parameter, and thus must
225
94.4k
  // match each other's type. As we're only keeping one of them, we must check
226
94.4k
  // for that now. The exception is that if either was deduced from an array
227
94.4k
  // bound, the type is permitted to differ.
228
94.4k
  if (!X.wasDeducedFromArrayBound() && 
!Y.wasDeducedFromArrayBound()94.3k
) {
229
94.3k
    QualType XType = X.getNonTypeTemplateArgumentType();
230
94.3k
    if (!XType.isNull()) {
231
544
      QualType YType = Y.getNonTypeTemplateArgumentType();
232
544
      if (YType.isNull() || !Context.hasSameType(XType, YType))
233
24
        return DeducedTemplateArgument();
234
94.4k
    }
235
94.3k
  }
236
94.4k
237
94.4k
  switch (X.getKind()) {
238
0
  case TemplateArgument::Null:
239
0
    llvm_unreachable("Non-deduced template arguments handled above");
240
0
241
93.6k
  case TemplateArgument::Type:
242
93.6k
    // If two template type arguments have the same type, they're compatible.
243
93.6k
    if (Y.getKind() == TemplateArgument::Type &&
244
93.6k
        Context.hasSameType(X.getAsType(), Y.getAsType()))
245
62.8k
      return X;
246
30.7k
247
30.7k
    // If one of the two arguments was deduced from an array bound, the other
248
30.7k
    // supersedes it.
249
30.7k
    if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
250
22
      return X.wasDeducedFromArrayBound() ? 
Y3
:
X19
;
251
30.7k
252
30.7k
    // The arguments are not compatible.
253
30.7k
    return DeducedTemplateArgument();
254
30.7k
255
30.7k
  case TemplateArgument::Integral:
256
199
    // If we deduced a constant in one case and either a dependent expression or
257
199
    // declaration in another case, keep the integral constant.
258
199
    // If both are integral constants with the same value, keep that value.
259
199
    if (Y.getKind() == TemplateArgument::Expression ||
260
199
        Y.getKind() == TemplateArgument::Declaration ||
261
199
        (Y.getKind() == TemplateArgument::Integral &&
262
199
         hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
263
180
      return X.wasDeducedFromArrayBound() ? 
Y123
:
X57
;
264
19
265
19
    // All other combinations are incompatible.
266
19
    return DeducedTemplateArgument();
267
19
268
26
  case TemplateArgument::Template:
269
26
    if (Y.getKind() == TemplateArgument::Template &&
270
26
        Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
271
26
      return X;
272
0
273
0
    // All other combinations are incompatible.
274
0
    return DeducedTemplateArgument();
275
0
276
0
  case TemplateArgument::TemplateExpansion:
277
0
    if (Y.getKind() == TemplateArgument::TemplateExpansion &&
278
0
        Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
279
0
                                    Y.getAsTemplateOrTemplatePattern()))
280
0
      return X;
281
0
282
0
    // All other combinations are incompatible.
283
0
    return DeducedTemplateArgument();
284
0
285
462
  case TemplateArgument::Expression: {
286
462
    if (Y.getKind() != TemplateArgument::Expression)
287
0
      return checkDeducedTemplateArguments(Context, Y, X);
288
462
289
462
    // Compare the expressions for equality
290
462
    llvm::FoldingSetNodeID ID1, ID2;
291
462
    X.getAsExpr()->Profile(ID1, Context, true);
292
462
    Y.getAsExpr()->Profile(ID2, Context, true);
293
462
    if (ID1 == ID2)
294
16
      return X.wasDeducedFromArrayBound() ? 
Y0
: X;
295
446
296
446
    // Differing dependent expressions are incompatible.
297
446
    return DeducedTemplateArgument();
298
446
  }
299
446
300
446
  case TemplateArgument::Declaration:
301
0
    assert(!X.wasDeducedFromArrayBound());
302
0
303
0
    // If we deduced a declaration and a dependent expression, keep the
304
0
    // declaration.
305
0
    if (Y.getKind() == TemplateArgument::Expression)
306
0
      return X;
307
0
308
0
    // If we deduced a declaration and an integral constant, keep the
309
0
    // integral constant and whichever type did not come from an array
310
0
    // bound.
311
0
    if (Y.getKind() == TemplateArgument::Integral) {
312
0
      if (Y.wasDeducedFromArrayBound())
313
0
        return TemplateArgument(Context, Y.getAsIntegral(),
314
0
                                X.getParamTypeForDecl());
315
0
      return Y;
316
0
    }
317
0
318
0
    // If we deduced two declarations, make sure that they refer to the
319
0
    // same declaration.
320
0
    if (Y.getKind() == TemplateArgument::Declaration &&
321
0
        isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
322
0
      return X;
323
0
324
0
    // All other combinations are incompatible.
325
0
    return DeducedTemplateArgument();
326
0
327
0
  case TemplateArgument::NullPtr:
328
0
    // If we deduced a null pointer and a dependent expression, keep the
329
0
    // null pointer.
330
0
    if (Y.getKind() == TemplateArgument::Expression)
331
0
      return X;
332
0
333
0
    // If we deduced a null pointer and an integral constant, keep the
334
0
    // integral constant.
335
0
    if (Y.getKind() == TemplateArgument::Integral)
336
0
      return Y;
337
0
338
0
    // If we deduced two null pointers, they are the same.
339
0
    if (Y.getKind() == TemplateArgument::NullPtr)
340
0
      return X;
341
0
342
0
    // All other combinations are incompatible.
343
0
    return DeducedTemplateArgument();
344
0
345
120
  case TemplateArgument::Pack: {
346
120
    if (Y.getKind() != TemplateArgument::Pack ||
347
120
        X.pack_size() != Y.pack_size())
348
36
      return DeducedTemplateArgument();
349
84
350
84
    llvm::SmallVector<TemplateArgument, 8> NewPack;
351
84
    for (TemplateArgument::pack_iterator XA = X.pack_begin(),
352
84
                                      XAEnd = X.pack_end(),
353
84
                                         YA = Y.pack_begin();
354
209
         XA != XAEnd; 
++XA, ++YA125
) {
355
144
      TemplateArgument Merged = checkDeducedTemplateArguments(
356
144
          Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
357
144
          DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
358
144
      if (Merged.isNull())
359
19
        return DeducedTemplateArgument();
360
125
      NewPack.push_back(Merged);
361
125
    }
362
84
363
84
    return DeducedTemplateArgument(
364
65
        TemplateArgument::CreatePackCopy(Context, NewPack),
365
65
        X.wasDeducedFromArrayBound() && 
Y.wasDeducedFromArrayBound()0
);
366
0
  }
367
0
  }
368
0
369
0
  llvm_unreachable("Invalid TemplateArgument Kind!");
370
0
}
371
372
/// Deduce the value of the given non-type template parameter
373
/// as the given deduced template argument. All non-type template parameter
374
/// deduction is funneled through here.
375
static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
376
    Sema &S, TemplateParameterList *TemplateParams,
377
    NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
378
    QualType ValueType, TemplateDeductionInfo &Info,
379
226k
    SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
380
226k
  assert(NTTP->getDepth() == Info.getDeducedDepth() &&
381
226k
         "deducing non-type template argument with wrong depth");
382
226k
383
226k
  DeducedTemplateArgument Result = checkDeducedTemplateArguments(
384
226k
      S.Context, Deduced[NTTP->getIndex()], NewDeduced);
385
226k
  if (Result.isNull()) {
386
488
    Info.Param = NTTP;
387
488
    Info.FirstArg = Deduced[NTTP->getIndex()];
388
488
    Info.SecondArg = NewDeduced;
389
488
    return Sema::TDK_Inconsistent;
390
488
  }
391
225k
392
225k
  Deduced[NTTP->getIndex()] = Result;
393
225k
  if (!S.getLangOpts().CPlusPlus17)
394
221k
    return Sema::TDK_Success;
395
4.26k
396
4.26k
  if (NTTP->isExpandedParameterPack())
397
21
    // FIXME: We may still need to deduce parts of the type here! But we
398
21
    // don't have any way to find which slice of the type to use, and the
399
21
    // type stored on the NTTP itself is nonsense. Perhaps the type of an
400
21
    // expanded NTTP should be a pack expansion type?
401
21
    return Sema::TDK_Success;
402
4.24k
403
4.24k
  // Get the type of the parameter for deduction. If it's a (dependent) array
404
4.24k
  // or function type, we will not have decayed it yet, so do that now.
405
4.24k
  QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
406
4.24k
  if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
407
28
    ParamType = Expansion->getPattern();
408
4.24k
409
4.24k
  // FIXME: It's not clear how deduction of a parameter of reference
410
4.24k
  // type from an argument (of non-reference type) should be performed.
411
4.24k
  // For now, we just remove reference types from both sides and let
412
4.24k
  // the final check for matching types sort out the mess.
413
4.24k
  return DeduceTemplateArgumentsByTypeMatch(
414
4.24k
      S, TemplateParams, ParamType.getNonReferenceType(),
415
4.24k
      ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
416
4.24k
      /*PartialOrdering=*/false,
417
4.24k
      /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
418
4.24k
}
419
420
/// Deduce the value of the given non-type template parameter
421
/// from the given integral constant.
422
static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
423
    Sema &S, TemplateParameterList *TemplateParams,
424
    NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
425
    QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
426
166k
    SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
427
166k
  return DeduceNonTypeTemplateArgument(
428
166k
      S, TemplateParams, NTTP,
429
166k
      DeducedTemplateArgument(S.Context, Value, ValueType,
430
166k
                              DeducedFromArrayBound),
431
166k
      ValueType, Info, Deduced);
432
166k
}
433
434
/// Deduce the value of the given non-type template parameter
435
/// from the given null pointer template argument type.
436
static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
437
    Sema &S, TemplateParameterList *TemplateParams,
438
    NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
439
    TemplateDeductionInfo &Info,
440
27
    SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
441
27
  Expr *Value =
442
27
      S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
443
27
                              S.Context.NullPtrTy, NTTP->getLocation()),
444
27
                          NullPtrType, CK_NullToPointer)
445
27
          .get();
446
27
  return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
447
27
                                       DeducedTemplateArgument(Value),
448
27
                                       Value->getType(), Info, Deduced);
449
27
}
450
451
/// Deduce the value of the given non-type template parameter
452
/// from the given type- or value-dependent expression.
453
///
454
/// \returns true if deduction succeeded, false otherwise.
455
static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
456
    Sema &S, TemplateParameterList *TemplateParams,
457
    NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
458
58.4k
    SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
459
58.4k
  return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
460
58.4k
                                       DeducedTemplateArgument(Value),
461
58.4k
                                       Value->getType(), Info, Deduced);
462
58.4k
}
463
464
/// Deduce the value of the given non-type template parameter
465
/// from the given declaration.
466
///
467
/// \returns true if deduction succeeded, false otherwise.
468
static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
469
    Sema &S, TemplateParameterList *TemplateParams,
470
    NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
471
    TemplateDeductionInfo &Info,
472
1.12k
    SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
473
1.12k
  D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : 
nullptr0
;
474
1.12k
  TemplateArgument New(D, T);
475
1.12k
  return DeduceNonTypeTemplateArgument(
476
1.12k
      S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
477
1.12k
}
478
479
static Sema::TemplateDeductionResult
480
DeduceTemplateArguments(Sema &S,
481
                        TemplateParameterList *TemplateParams,
482
                        TemplateName Param,
483
                        TemplateName Arg,
484
                        TemplateDeductionInfo &Info,
485
561k
                        SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
486
561k
  TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
487
561k
  if (!ParamDecl) {
488
12
    // The parameter type is dependent and is not a template template parameter,
489
12
    // so there is nothing that we can deduce.
490
12
    return Sema::TDK_Success;
491
12
  }
492
561k
493
561k
  if (TemplateTemplateParmDecl *TempParam
494
2.60k
        = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
495
2.60k
    // If we're not deducing at this depth, there's nothing to deduce.
496
2.60k
    if (TempParam->getDepth() != Info.getDeducedDepth())
497
0
      return Sema::TDK_Success;
498
2.60k
499
2.60k
    DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
500
2.60k
    DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
501
2.60k
                                                 Deduced[TempParam->getIndex()],
502
2.60k
                                                                   NewDeduced);
503
2.60k
    if (Result.isNull()) {
504
0
      Info.Param = TempParam;
505
0
      Info.FirstArg = Deduced[TempParam->getIndex()];
506
0
      Info.SecondArg = NewDeduced;
507
0
      return Sema::TDK_Inconsistent;
508
0
    }
509
2.60k
510
2.60k
    Deduced[TempParam->getIndex()] = Result;
511
2.60k
    return Sema::TDK_Success;
512
2.60k
  }
513
559k
514
559k
  // Verify that the two template names are equivalent.
515
559k
  if (S.Context.hasSameTemplateName(Param, Arg))
516
453k
    return Sema::TDK_Success;
517
105k
518
105k
  // Mismatch of non-dependent template parameter to argument.
519
105k
  Info.FirstArg = TemplateArgument(Param);
520
105k
  Info.SecondArg = TemplateArgument(Arg);
521
105k
  return Sema::TDK_NonDeducedMismatch;
522
105k
}
523
524
/// Deduce the template arguments by comparing the template parameter
525
/// type (which is a template-id) with the template argument type.
526
///
527
/// \param S the Sema
528
///
529
/// \param TemplateParams the template parameters that we are deducing
530
///
531
/// \param Param the parameter type
532
///
533
/// \param Arg the argument type
534
///
535
/// \param Info information about the template argument deduction itself
536
///
537
/// \param Deduced the deduced template arguments
538
///
539
/// \returns the result of template argument deduction so far. Note that a
540
/// "success" result means that template argument deduction has not yet failed,
541
/// but it may still fail, later, for other reasons.
542
static Sema::TemplateDeductionResult
543
DeduceTemplateArguments(Sema &S,
544
                        TemplateParameterList *TemplateParams,
545
                        const TemplateSpecializationType *Param,
546
                        QualType Arg,
547
                        TemplateDeductionInfo &Info,
548
1.03M
                        SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
549
1.03M
  assert(Arg.isCanonical() && "Argument type must be canonical");
550
1.03M
551
1.03M
  // Treat an injected-class-name as its underlying template-id.
552
1.03M
  if (auto *Injected = dyn_cast<InjectedClassNameType>(Arg))
553
14
    Arg = Injected->getInjectedSpecializationType();
554
1.03M
555
1.03M
  // Check whether the template argument is a dependent template-id.
556
1.03M
  if (const TemplateSpecializationType *SpecArg
557
333k
        = dyn_cast<TemplateSpecializationType>(Arg)) {
558
333k
    // Perform template argument deduction for the template name.
559
333k
    if (Sema::TemplateDeductionResult Result
560
6
          = DeduceTemplateArguments(S, TemplateParams,
561
6
                                    Param->getTemplateName(),
562
6
                                    SpecArg->getTemplateName(),
563
6
                                    Info, Deduced))
564
6
      return Result;
565
333k
566
333k
567
333k
    // Perform template argument deduction on each template
568
333k
    // argument. Ignore any missing/extra arguments, since they could be
569
333k
    // filled in by default arguments.
570
333k
    return DeduceTemplateArguments(S, TemplateParams,
571
333k
                                   Param->template_arguments(),
572
333k
                                   SpecArg->template_arguments(), Info, Deduced,
573
333k
                                   /*NumberOfArgumentsMustMatch=*/false);
574
333k
  }
575
703k
576
703k
  // If the argument type is a class template specialization, we
577
703k
  // perform template argument deduction using its template
578
703k
  // arguments.
579
703k
  const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
580
703k
  if (!RecordArg) {
581
372k
    Info.FirstArg = TemplateArgument(QualType(Param, 0));
582
372k
    Info.SecondArg = TemplateArgument(Arg);
583
372k
    return Sema::TDK_NonDeducedMismatch;
584
372k
  }
585
331k
586
331k
  ClassTemplateSpecializationDecl *SpecArg
587
331k
    = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
588
331k
  if (!SpecArg) {
589
103k
    Info.FirstArg = TemplateArgument(QualType(Param, 0));
590
103k
    Info.SecondArg = TemplateArgument(Arg);
591
103k
    return Sema::TDK_NonDeducedMismatch;
592
103k
  }
593
227k
594
227k
  // Perform template argument deduction for the template name.
595
227k
  if (Sema::TemplateDeductionResult Result
596
105k
        = DeduceTemplateArguments(S,
597
105k
                                  TemplateParams,
598
105k
                                  Param->getTemplateName(),
599
105k
                               TemplateName(SpecArg->getSpecializedTemplate()),
600
105k
                                  Info, Deduced))
601
105k
    return Result;
602
122k
603
122k
  // Perform template argument deduction for the template arguments.
604
122k
  return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
605
122k
                                 SpecArg->getTemplateArgs().asArray(), Info,
606
122k
                                 Deduced, /*NumberOfArgumentsMustMatch=*/true);
607
122k
}
608
609
/// Determines whether the given type is an opaque type that
610
/// might be more qualified when instantiated.
611
1.16M
static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
612
1.16M
  switch (T->getTypeClass()) {
613
111k
  case Type::TypeOfExpr:
614
111k
  case Type::TypeOf:
615
111k
  case Type::DependentName:
616
111k
  case Type::Decltype:
617
111k
  case Type::UnresolvedUsing:
618
111k
  case Type::TemplateTypeParm:
619
111k
    return true;
620
111k
621
111k
  case Type::ConstantArray:
622
76.7k
  case Type::IncompleteArray:
623
76.7k
  case Type::VariableArray:
624
76.7k
  case Type::DependentSizedArray:
625
76.7k
    return IsPossiblyOpaquelyQualifiedType(
626
76.7k
                                      cast<ArrayType>(T)->getElementType());
627
76.7k
628
975k
  default:
629
975k
    return false;
630
1.16M
  }
631
1.16M
}
632
633
/// Helper function to build a TemplateParameter when we don't
634
/// know its type statically.
635
61.9k
static TemplateParameter makeTemplateParameter(Decl *D) {
636
61.9k
  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
637
48.2k
    return TemplateParameter(TTP);
638
13.6k
  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
639
13.6k
    return TemplateParameter(NTTP);
640
26
641
26
  return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
642
26
}
643
644
/// If \p Param is an expanded parameter pack, get the number of expansions.
645
152k
static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
646
152k
  if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
647
141k
    if (TTP->isExpandedParameterPack())
648
10
      return TTP->getNumExpansionParameters();
649
152k
650
152k
  if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
651
10.6k
    if (NTTP->isExpandedParameterPack())
652
48
      return NTTP->getNumExpansionTypes();
653
152k
654
152k
  if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param))
655
57
    if (TTP->isExpandedParameterPack())
656
4
      return TTP->getNumExpansionTemplateParameters();
657
152k
658
152k
  return None;
659
152k
}
660
661
/// A pack that we're currently deducing.
662
struct clang::DeducedPack {
663
  // The index of the pack.
664
  unsigned Index;
665
666
  // The old value of the pack before we started deducing it.
667
  DeducedTemplateArgument Saved;
668
669
  // A deferred value of this pack from an inner deduction, that couldn't be
670
  // deduced because this deduction hadn't happened yet.
671
  DeducedTemplateArgument DeferredDeduction;
672
673
  // The new value of the pack.
674
  SmallVector<DeducedTemplateArgument, 4> New;
675
676
  // The outer deduction for this pack, if any.
677
  DeducedPack *Outer = nullptr;
678
679
67.9k
  DeducedPack(unsigned Index) : Index(Index) {}
680
};
681
682
namespace {
683
684
/// A scope in which we're performing pack deduction.
685
class PackDeductionScope {
686
public:
687
  /// Prepare to deduce the packs named within Pattern.
688
  PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
689
                     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
690
                     TemplateDeductionInfo &Info, TemplateArgument Pattern)
691
50.7k
      : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
692
50.7k
    unsigned NumNamedPacks = addPacks(Pattern);
693
50.7k
    finishConstruction(NumNamedPacks);
694
50.7k
  }
695
696
  /// Prepare to directly deduce arguments of the parameter with index \p Index.
697
  PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
698
                     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
699
                     TemplateDeductionInfo &Info, unsigned Index)
700
17.2k
      : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
701
17.2k
    addPack(Index);
702
17.2k
    finishConstruction(1);
703
17.2k
  }
704
705
private:
706
67.9k
  void addPack(unsigned Index) {
707
67.9k
    // Save the deduced template argument for the parameter pack expanded
708
67.9k
    // by this pack expansion, then clear out the deduction.
709
67.9k
    DeducedPack Pack(Index);
710
67.9k
    Pack.Saved = Deduced[Index];
711
67.9k
    Deduced[Index] = TemplateArgument();
712
67.9k
713
67.9k
    // FIXME: What if we encounter multiple packs with different numbers of
714
67.9k
    // pre-expanded expansions? (This should already have been diagnosed
715
67.9k
    // during substitution.)
716
67.9k
    if (Optional<unsigned> ExpandedPackExpansions =
717
26
            getExpandedPackSize(TemplateParams->getParam(Index)))
718
26
      FixedNumExpansions = ExpandedPackExpansions;
719
67.9k
720
67.9k
    Packs.push_back(Pack);
721
67.9k
  }
722
723
50.7k
  unsigned addPacks(TemplateArgument Pattern) {
724
50.7k
    // Compute the set of template parameter indices that correspond to
725
50.7k
    // parameter packs expanded by the pack expansion.
726
50.7k
    llvm::SmallBitVector SawIndices(TemplateParams->size());
727
50.7k
    llvm::SmallVector<TemplateArgument, 4> ExtraDeductions;
728
50.7k
729
50.7k
    auto AddPack = [&](unsigned Index) {
730
50.7k
      if (SawIndices[Index])
731
13
        return;
732
50.7k
      SawIndices[Index] = true;
733
50.7k
      addPack(Index);
734
50.7k
735
50.7k
      // Deducing a parameter pack that is a pack expansion also constrains the
736
50.7k
      // packs appearing in that parameter to have the same deduced arity. Also,
737
50.7k
      // in C++17 onwards, deducing a non-type template parameter deduces its
738
50.7k
      // type, so we need to collect the pending deduced values for those packs.
739
50.7k
      if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
740
5.07k
              TemplateParams->getParam(Index))) {
741
5.07k
        if (auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType()))
742
23
          ExtraDeductions.push_back(Expansion->getPattern());
743
5.07k
      }
744
50.7k
      // FIXME: Also collect the unexpanded packs in any type and template
745
50.7k
      // parameter packs that are pack expansions.
746
50.7k
    };
747
50.7k
748
50.7k
    auto Collect = [&](TemplateArgument Pattern) {
749
50.7k
      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
750
50.7k
      S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
751
101k
      for (unsigned I = 0, N = Unexpanded.size(); I != N; 
++I50.7k
) {
752
50.7k
        unsigned Depth, Index;
753
50.7k
        std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
754
50.7k
        if (Depth == Info.getDeducedDepth())
755
50.7k
          AddPack(Index);
756
50.7k
      }
757
50.7k
    };
758
50.7k
759
50.7k
    // Look for unexpanded packs in the pattern.
760
50.7k
    Collect(Pattern);
761
50.7k
    assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
762
50.7k
763
50.7k
    unsigned NumNamedPacks = Packs.size();
764
50.7k
765
50.7k
    // Also look for unexpanded packs that are indirectly deduced by deducing
766
50.7k
    // the sizes of the packs in this pattern.
767
50.7k
    while (!ExtraDeductions.empty())
768
23
      Collect(ExtraDeductions.pop_back_val());
769
50.7k
770
50.7k
    return NumNamedPacks;
771
50.7k
  }
772
773
67.9k
  void finishConstruction(unsigned NumNamedPacks) {
774
67.9k
    // Dig out the partially-substituted pack, if there is one.
775
67.9k
    const TemplateArgument *PartialPackArgs = nullptr;
776
67.9k
    unsigned NumPartialPackArgs = 0;
777
67.9k
    std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
778
67.9k
    if (auto *Scope = S.CurrentInstantiationScope)
779
60.0k
      if (auto *Partial = Scope->getPartiallySubstitutedPack(
780
16.8k
              &PartialPackArgs, &NumPartialPackArgs))
781
16.8k
        PartialPackDepthIndex = getDepthAndIndex(Partial);
782
67.9k
783
67.9k
    // This pack expansion will have been partially or fully expanded if
784
67.9k
    // it only names explicitly-specified parameter packs (including the
785
67.9k
    // partially-substituted one, if any).
786
67.9k
    bool IsExpanded = true;
787
84.7k
    for (unsigned I = 0; I != NumNamedPacks; 
++I16.7k
) {
788
67.9k
      if (Packs[I].Index >= Info.getNumExplicitArgs()) {
789
51.2k
        IsExpanded = false;
790
51.2k
        IsPartiallyExpanded = false;
791
51.2k
        break;
792
51.2k
      }
793
16.7k
      if (PartialPackDepthIndex ==
794
16.7k
            std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
795
16.7k
        IsPartiallyExpanded = true;
796
16.7k
      }
797
16.7k
    }
798
67.9k
799
67.9k
    // Skip over the pack elements that were expanded into separate arguments.
800
67.9k
    // If we partially expanded, this is the number of partial arguments.
801
67.9k
    if (IsPartiallyExpanded)
802
16.7k
      PackElements += NumPartialPackArgs;
803
51.2k
    else if (IsExpanded)
804
0
      PackElements += *FixedNumExpansions;
805
67.9k
806
67.9k
    for (auto &Pack : Packs) {
807
67.9k
      if (Info.PendingDeducedPacks.size() > Pack.Index)
808
165
        Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
809
67.8k
      else
810
67.8k
        Info.PendingDeducedPacks.resize(Pack.Index + 1);
811
67.9k
      Info.PendingDeducedPacks[Pack.Index] = &Pack;
812
67.9k
813
67.9k
      if (PartialPackDepthIndex ==
814
67.9k
            std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
815
16.7k
        Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
816
16.7k
        // We pre-populate the deduced value of the partially-substituted
817
16.7k
        // pack with the specified value. This is not entirely correct: the
818
16.7k
        // value is supposed to have been substituted, not deduced, but the
819
16.7k
        // cases where this is observable require an exact type match anyway.
820
16.7k
        //
821
16.7k
        // FIXME: If we could represent a "depth i, index j, pack elem k"
822
16.7k
        // parameter, we could substitute the partially-substituted pack
823
16.7k
        // everywhere and avoid this.
824
16.7k
        if (!IsPartiallyExpanded)
825
0
          Deduced[Pack.Index] = Pack.New[PackElements];
826
16.7k
      }
827
67.9k
    }
828
67.9k
  }
829
830
public:
831
67.9k
  ~PackDeductionScope() {
832
67.9k
    for (auto &Pack : Packs)
833
67.9k
      Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
834
67.9k
  }
835
836
  /// Determine whether this pack has already been partially expanded into a
837
  /// sequence of (prior) function parameters / template arguments.
838
12
  bool isPartiallyExpanded() { return IsPartiallyExpanded; }
839
840
  /// Determine whether this pack expansion scope has a known, fixed arity.
841
  /// This happens if it involves a pack from an outer template that has
842
  /// (notionally) already been expanded.
843
155
  bool hasFixedArity() { return FixedNumExpansions.hasValue(); }
844
845
  /// Determine whether the next element of the argument is still part of this
846
  /// pack. This is the case unless the pack is already expanded to a fixed
847
  /// length.
848
151k
  bool hasNextElement() {
849
151k
    return !FixedNumExpansions || 
*FixedNumExpansions > PackElements31
;
850
151k
  }
851
852
  /// Move to deducing the next element in each pack that is being deduced.
853
151k
  void nextPackElement() {
854
151k
    // Capture the deduced template arguments for each parameter pack expanded
855
151k
    // by this pack expansion, add them to the list of arguments we've deduced
856
151k
    // for that pack, then clear out the deduced argument.
857
151k
    for (auto &Pack : Packs) {
858
151k
      DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
859
151k
      if (!Pack.New.empty() || 
!DeducedArg.isNull()40.3k
) {
860
151k
        while (Pack.New.size() < PackElements)
861
44
          Pack.New.push_back(DeducedTemplateArgument());
862
150k
        if (Pack.New.size() == PackElements)
863
150k
          Pack.New.push_back(DeducedArg);
864
0
        else
865
0
          Pack.New[PackElements] = DeducedArg;
866
150k
        DeducedArg = Pack.New.size() > PackElements + 1
867
150k
                         ? 
Pack.New[PackElements + 1]0
868
150k
                         : DeducedTemplateArgument();
869
150k
      }
870
151k
    }
871
151k
    ++PackElements;
872
151k
  }
873
874
  /// Finish template argument deduction for a set of argument packs,
875
  /// producing the argument packs and checking for consistency with prior
876
  /// deductions.
877
67.9k
  Sema::TemplateDeductionResult finish() {
878
67.9k
    // Build argument packs for each of the parameter packs expanded by this
879
67.9k
    // pack expansion.
880
67.9k
    for (auto &Pack : Packs) {
881
67.9k
      // Put back the old value for this pack.
882
67.9k
      Deduced[Pack.Index] = Pack.Saved;
883
67.9k
884
67.9k
      // Always make sure the size of this pack is correct, even if we didn't
885
67.9k
      // deduce any values for it.
886
67.9k
      //
887
67.9k
      // FIXME: This isn't required by the normative wording, but substitution
888
67.9k
      // and post-substitution checking will always fail if the arity of any
889
67.9k
      // pack is not equal to the number of elements we processed. (Either that
890
67.9k
      // or something else has gone *very* wrong.) We're permitted to skip any
891
67.9k
      // hard errors from those follow-on steps by the intent (but not the
892
67.9k
      // wording) of C++ [temp.inst]p8:
893
67.9k
      //
894
67.9k
      //   If the function selected by overload resolution can be determined
895
67.9k
      //   without instantiating a class template definition, it is unspecified
896
67.9k
      //   whether that instantiation actually takes place
897
67.9k
      Pack.New.resize(PackElements);
898
67.9k
899
67.9k
      // Build or find a new value for this pack.
900
67.9k
      DeducedTemplateArgument NewPack;
901
67.9k
      if (Pack.New.empty()) {
902
10.9k
        // If we deduced an empty argument pack, create it now.
903
10.9k
        NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
904
57.0k
      } else {
905
57.0k
        TemplateArgument *ArgumentPack =
906
57.0k
            new (S.Context) TemplateArgument[Pack.New.size()];
907
57.0k
        std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
908
57.0k
        NewPack = DeducedTemplateArgument(
909
57.0k
            TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
910
57.0k
            // FIXME: This is wrong, it's possible that some pack elements are
911
57.0k
            // deduced from an array bound and others are not:
912
57.0k
            //   template<typename ...T, T ...V> void g(const T (&...p)[V]);
913
57.0k
            //   g({1, 2, 3}, {{}, {}});
914
57.0k
            // ... should deduce T = {int, size_t (from array bound)}.
915
57.0k
            Pack.New[0].wasDeducedFromArrayBound());
916
57.0k
      }
917
67.9k
918
67.9k
      // Pick where we're going to put the merged pack.
919
67.9k
      DeducedTemplateArgument *Loc;
920
67.9k
      if (Pack.Outer) {
921
17
        if (Pack.Outer->DeferredDeduction.isNull()) {
922
8
          // Defer checking this pack until we have a complete pack to compare
923
8
          // it against.
924
8
          Pack.Outer->DeferredDeduction = NewPack;
925
8
          continue;
926
8
        }
927
9
        Loc = &Pack.Outer->DeferredDeduction;
928
67.9k
      } else {
929
67.9k
        Loc = &Deduced[Pack.Index];
930
67.9k
      }
931
67.9k
932
67.9k
      // Check the new pack matches any previous value.
933
67.9k
      DeducedTemplateArgument OldPack = *Loc;
934
67.9k
      DeducedTemplateArgument Result =
935
67.9k
          checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
936
67.9k
937
67.9k
      // If we deferred a deduction of this pack, check that one now too.
938
67.9k
      if (!Result.isNull() && 
!Pack.DeferredDeduction.isNull()67.9k
) {
939
5
        OldPack = Result;
940
5
        NewPack = Pack.DeferredDeduction;
941
5
        Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
942
5
      }
943
67.9k
944
67.9k
      NamedDecl *Param = TemplateParams->getParam(Pack.Index);
945
67.9k
      if (Result.isNull()) {
946
55
        Info.Param = makeTemplateParameter(Param);
947
55
        Info.FirstArg = OldPack;
948
55
        Info.SecondArg = NewPack;
949
55
        return Sema::TDK_Inconsistent;
950
55
      }
951
67.8k
952
67.8k
      // If we have a pre-expanded pack and we didn't deduce enough elements
953
67.8k
      // for it, fail deduction.
954
67.8k
      if (Optional<unsigned> Expansions = getExpandedPackSize(Param)) {
955
26
        if (*Expansions != PackElements) {
956
9
          Info.Param = makeTemplateParameter(Param);
957
9
          Info.FirstArg = Result;
958
9
          return Sema::TDK_IncompletePack;
959
9
        }
960
67.8k
      }
961
67.8k
962
67.8k
      *Loc = Result;
963
67.8k
    }
964
67.9k
965
67.9k
    
return Sema::TDK_Success67.8k
;
966
67.9k
  }
967
968
private:
969
  Sema &S;
970
  TemplateParameterList *TemplateParams;
971
  SmallVectorImpl<DeducedTemplateArgument> &Deduced;
972
  TemplateDeductionInfo &Info;
973
  unsigned PackElements = 0;
974
  bool IsPartiallyExpanded = false;
975
  /// The number of expansions, if we have a fully-expanded pack in this scope.
976
  Optional<unsigned> FixedNumExpansions;
977
978
  SmallVector<DeducedPack, 2> Packs;
979
};
980
981
} // namespace
982
983
/// Deduce the template arguments by comparing the list of parameter
984
/// types to the list of argument types, as in the parameter-type-lists of
985
/// function types (C++ [temp.deduct.type]p10).
986
///
987
/// \param S The semantic analysis object within which we are deducing
988
///
989
/// \param TemplateParams The template parameters that we are deducing
990
///
991
/// \param Params The list of parameter types
992
///
993
/// \param NumParams The number of types in \c Params
994
///
995
/// \param Args The list of argument types
996
///
997
/// \param NumArgs The number of types in \c Args
998
///
999
/// \param Info information about the template argument deduction itself
1000
///
1001
/// \param Deduced the deduced template arguments
1002
///
1003
/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1004
/// how template argument deduction is performed.
1005
///
1006
/// \param PartialOrdering If true, we are performing template argument
1007
/// deduction for during partial ordering for a call
1008
/// (C++0x [temp.deduct.partial]).
1009
///
1010
/// \returns the result of template argument deduction so far. Note that a
1011
/// "success" result means that template argument deduction has not yet failed,
1012
/// but it may still fail, later, for other reasons.
1013
static Sema::TemplateDeductionResult
1014
DeduceTemplateArguments(Sema &S,
1015
                        TemplateParameterList *TemplateParams,
1016
                        const QualType *Params, unsigned NumParams,
1017
                        const QualType *Args, unsigned NumArgs,
1018
                        TemplateDeductionInfo &Info,
1019
                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1020
                        unsigned TDF,
1021
100k
                        bool PartialOrdering = false) {
1022
100k
  // C++0x [temp.deduct.type]p10:
1023
100k
  //   Similarly, if P has a form that contains (T), then each parameter type
1024
100k
  //   Pi of the respective parameter-type- list of P is compared with the
1025
100k
  //   corresponding parameter type Ai of the corresponding parameter-type-list
1026
100k
  //   of A. [...]
1027
100k
  unsigned ArgIdx = 0, ParamIdx = 0;
1028
188k
  for (; ParamIdx != NumParams; 
++ParamIdx87.8k
) {
1029
162k
    // Check argument types.
1030
162k
    const PackExpansionType *Expansion
1031
162k
                                = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1032
162k
    if (!Expansion) {
1033
161k
      // Simple case: compare the parameter and argument types at this point.
1034
161k
1035
161k
      // Make sure we have an argument.
1036
161k
      if (ArgIdx >= NumArgs)
1037
5.52k
        return Sema::TDK_MiscellaneousDeductionFailure;
1038
155k
1039
155k
      if (isa<PackExpansionType>(Args[ArgIdx])) {
1040
856
        // C++0x [temp.deduct.type]p22:
1041
856
        //   If the original function parameter associated with A is a function
1042
856
        //   parameter pack and the function parameter associated with P is not
1043
856
        //   a function parameter pack, then template argument deduction fails.
1044
856
        return Sema::TDK_MiscellaneousDeductionFailure;
1045
856
      }
1046
154k
1047
154k
      if (Sema::TemplateDeductionResult Result
1048
68.2k
            = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1049
68.2k
                                                 Params[ParamIdx], Args[ArgIdx],
1050
68.2k
                                                 Info, Deduced, TDF,
1051
68.2k
                                                 PartialOrdering))
1052
68.2k
        return Result;
1053
86.4k
1054
86.4k
      ++ArgIdx;
1055
86.4k
      continue;
1056
86.4k
    }
1057
1.36k
1058
1.36k
    // C++0x [temp.deduct.type]p10:
1059
1.36k
    //   If the parameter-declaration corresponding to Pi is a function
1060
1.36k
    //   parameter pack, then the type of its declarator- id is compared with
1061
1.36k
    //   each remaining parameter type in the parameter-type-list of A. Each
1062
1.36k
    //   comparison deduces template arguments for subsequent positions in the
1063
1.36k
    //   template parameter packs expanded by the function parameter pack.
1064
1.36k
1065
1.36k
    QualType Pattern = Expansion->getPattern();
1066
1.36k
    PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1067
1.36k
1068
1.36k
    // A pack scope with fixed arity is not really a pack any more, so is not
1069
1.36k
    // a non-deduced context.
1070
1.36k
    if (ParamIdx + 1 == NumParams || 
PackScope.hasFixedArity()9
) {
1071
3.00k
      for (; ArgIdx < NumArgs && 
PackScope.hasNextElement()1.64k
;
++ArgIdx1.64k
) {
1072
1.64k
        // Deduce template arguments from the pattern.
1073
1.64k
        if (Sema::TemplateDeductionResult Result
1074
5
              = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
1075
5
                                                   Args[ArgIdx], Info, Deduced,
1076
5
                                                   TDF, PartialOrdering))
1077
5
          return Result;
1078
1.64k
1079
1.64k
        PackScope.nextPackElement();
1080
1.64k
      }
1081
1.35k
    } else {
1082
9
      // C++0x [temp.deduct.type]p5:
1083
9
      //   The non-deduced contexts are:
1084
9
      //     - A function parameter pack that does not occur at the end of the
1085
9
      //       parameter-declaration-clause.
1086
9
      //
1087
9
      // FIXME: There is no wording to say what we should do in this case. We
1088
9
      // choose to resolve this by applying the same rule that is applied for a
1089
9
      // function call: that is, deduce all contained packs to their
1090
9
      // explicitly-specified values (or to <> if there is no such value).
1091
9
      //
1092
9
      // This is seemingly-arbitrarily different from the case of a template-id
1093
9
      // with a non-trailing pack-expansion in its arguments, which renders the
1094
9
      // entire template-argument-list a non-deduced context.
1095
9
1096
9
      // If the parameter type contains an explicitly-specified pack that we
1097
9
      // could not expand, skip the number of parameters notionally created
1098
9
      // by the expansion.
1099
9
      Optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1100
9
      if (NumExpansions && 
!PackScope.isPartiallyExpanded()0
) {
1101
0
        for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
1102
0
             ++I, ++ArgIdx)
1103
0
          PackScope.nextPackElement();
1104
0
      }
1105
9
    }
1106
1.36k
1107
1.36k
    // Build argument packs for each of the parameter packs expanded by this
1108
1.36k
    // pack expansion.
1109
1.36k
    
if (auto 1.36k
Result1.36k
= PackScope.finish())
1110
2
      return Result;
1111
1.36k
  }
1112
100k
1113
100k
  // Make sure we don't have any extra arguments.
1114
100k
  
if (25.9k
ArgIdx < NumArgs25.9k
)
1115
3.86k
    return Sema::TDK_MiscellaneousDeductionFailure;
1116
22.0k
1117
22.0k
  return Sema::TDK_Success;
1118
22.0k
}
1119
1120
/// Determine whether the parameter has qualifiers that the argument
1121
/// lacks. Put another way, determine whether there is no way to add
1122
/// a deduced set of qualifiers to the ParamType that would result in
1123
/// its qualifiers matching those of the ArgType.
1124
static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
1125
1.68M
                                                  QualType ArgType) {
1126
1.68M
  Qualifiers ParamQs = ParamType.getQualifiers();
1127
1.68M
  Qualifiers ArgQs = ArgType.getQualifiers();
1128
1.68M
1129
1.68M
  if (ParamQs == ArgQs)
1130
1.55M
    return false;
1131
124k
1132
124k
  // Mismatched (but not missing) Objective-C GC attributes.
1133
124k
  if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1134
124k
      
ParamQs.hasObjCGCAttr()0
)
1135
0
    return true;
1136
124k
1137
124k
  // Mismatched (but not missing) address spaces.
1138
124k
  if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1139
124k
      
ParamQs.hasAddressSpace()17
)
1140
4
    return true;
1141
124k
1142
124k
  // Mismatched (but not missing) Objective-C lifetime qualifiers.
1143
124k
  if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1144
124k
      
ParamQs.hasObjCLifetime()159
)
1145
95
    return true;
1146
124k
1147
124k
  // CVR qualifiers inconsistent or a superset.
1148
124k
  return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1149
124k
}
1150
1151
/// Compare types for equality with respect to possibly compatible
1152
/// function types (noreturn adjustment, implicit calling conventions). If any
1153
/// of parameter and argument is not a function, just perform type comparison.
1154
///
1155
/// \param Param the template parameter type.
1156
///
1157
/// \param Arg the argument type.
1158
bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
1159
25.9k
                                          CanQualType Arg) {
1160
25.9k
  const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
1161
25.9k
                     *ArgFunction   = Arg->getAs<FunctionType>();
1162
25.9k
1163
25.9k
  // Just compare if not functions.
1164
25.9k
  if (!ParamFunction || !ArgFunction)
1165
0
    return Param == Arg;
1166
25.9k
1167
25.9k
  // Noreturn and noexcept adjustment.
1168
25.9k
  QualType AdjustedParam;
1169
25.9k
  if (IsFunctionConversion(Param, Arg, AdjustedParam))
1170
270
    return Arg == Context.getCanonicalType(AdjustedParam);
1171
25.7k
1172
25.7k
  // FIXME: Compatible calling conventions.
1173
25.7k
1174
25.7k
  return Param == Arg;
1175
25.7k
}
1176
1177
/// Get the index of the first template parameter that was originally from the
1178
/// innermost template-parameter-list. This is 0 except when we concatenate
1179
/// the template parameter lists of a class template and a constructor template
1180
/// when forming an implicit deduction guide.
1181
1.18M
static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
1182
1.18M
  auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1183
1.18M
  if (!Guide || 
!Guide->isImplicit()799
)
1184
1.18M
    return 0;
1185
644
  return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1186
644
}
1187
1188
/// Determine whether a type denotes a forwarding reference.
1189
718k
static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1190
718k
  // C++1z [temp.deduct.call]p3:
1191
718k
  //   A forwarding reference is an rvalue reference to a cv-unqualified
1192
718k
  //   template parameter that does not represent a template parameter of a
1193
718k
  //   class template.
1194
718k
  if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1195
89.8k
    if (ParamRef->getPointeeType().getQualifiers())
1196
4.28k
      return false;
1197
85.5k
    auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1198
85.5k
    return TypeParm && 
TypeParm->getIndex() >= FirstInnerIndex64.9k
;
1199
85.5k
  }
1200
629k
  return false;
1201
629k
}
1202
1203
/// Deduce the template arguments by comparing the parameter type and
1204
/// the argument type (C++ [temp.deduct.type]).
1205
///
1206
/// \param S the semantic analysis object within which we are deducing
1207
///
1208
/// \param TemplateParams the template parameters that we are deducing
1209
///
1210
/// \param ParamIn the parameter type
1211
///
1212
/// \param ArgIn the argument type
1213
///
1214
/// \param Info information about the template argument deduction itself
1215
///
1216
/// \param Deduced the deduced template arguments
1217
///
1218
/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1219
/// how template argument deduction is performed.
1220
///
1221
/// \param PartialOrdering Whether we're performing template argument deduction
1222
/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1223
///
1224
/// \returns the result of template argument deduction so far. Note that a
1225
/// "success" result means that template argument deduction has not yet failed,
1226
/// but it may still fail, later, for other reasons.
1227
static Sema::TemplateDeductionResult
1228
DeduceTemplateArgumentsByTypeMatch(Sema &S,
1229
                                   TemplateParameterList *TemplateParams,
1230
                                   QualType ParamIn, QualType ArgIn,
1231
                                   TemplateDeductionInfo &Info,
1232
                            SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1233
                                   unsigned TDF,
1234
                                   bool PartialOrdering,
1235
2.91M
                                   bool DeducedFromArrayBound) {
1236
2.91M
  // We only want to look at the canonical types, since typedefs and
1237
2.91M
  // sugar are not part of template argument deduction.
1238
2.91M
  QualType Param = S.Context.getCanonicalType(ParamIn);
1239
2.91M
  QualType Arg = S.Context.getCanonicalType(ArgIn);
1240
2.91M
1241
2.91M
  // If the argument type is a pack expansion, look at its pattern.
1242
2.91M
  // This isn't explicitly called out
1243
2.91M
  if (const PackExpansionType *ArgExpansion
1244
48
                                            = dyn_cast<PackExpansionType>(Arg))
1245
48
    Arg = ArgExpansion->getPattern();
1246
2.91M
1247
2.91M
  if (PartialOrdering) {
1248
355k
    // C++11 [temp.deduct.partial]p5:
1249
355k
    //   Before the partial ordering is done, certain transformations are
1250
355k
    //   performed on the types used for partial ordering:
1251
355k
    //     - If P is a reference type, P is replaced by the type referred to.
1252
355k
    const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1253
355k
    if (ParamRef)
1254
9.18k
      Param = ParamRef->getPointeeType();
1255
355k
1256
355k
    //     - If A is a reference type, A is replaced by the type referred to.
1257
355k
    const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1258
355k
    if (ArgRef)
1259
9.16k
      Arg = ArgRef->getPointeeType();
1260
355k
1261
355k
    if (ParamRef && 
ArgRef9.18k
&&
S.Context.hasSameUnqualifiedType(Param, Arg)4.66k
) {
1262
1.75k
      // C++11 [temp.deduct.partial]p9:
1263
1.75k
      //   If, for a given type, deduction succeeds in both directions (i.e.,
1264
1.75k
      //   the types are identical after the transformations above) and both
1265
1.75k
      //   P and A were reference types [...]:
1266
1.75k
      //     - if [one type] was an lvalue reference and [the other type] was
1267
1.75k
      //       not, [the other type] is not considered to be at least as
1268
1.75k
      //       specialized as [the first type]
1269
1.75k
      //     - if [one type] is more cv-qualified than [the other type],
1270
1.75k
      //       [the other type] is not considered to be at least as specialized
1271
1.75k
      //       as [the first type]
1272
1.75k
      // Objective-C ARC adds:
1273
1.75k
      //     - [one type] has non-trivial lifetime, [the other type] has
1274
1.75k
      //       __unsafe_unretained lifetime, and the types are otherwise
1275
1.75k
      //       identical
1276
1.75k
      //
1277
1.75k
      // A is "considered to be at least as specialized" as P iff deduction
1278
1.75k
      // succeeds, so we model this as a deduction failure. Note that
1279
1.75k
      // [the first type] is P and [the other type] is A here; the standard
1280
1.75k
      // gets this backwards.
1281
1.75k
      Qualifiers ParamQuals = Param.getQualifiers();
1282
1.75k
      Qualifiers ArgQuals = Arg.getQualifiers();
1283
1.75k
      if ((ParamRef->isLValueReferenceType() &&
1284
1.75k
           
!ArgRef->isLValueReferenceType()1.66k
) ||
1285
1.75k
          
ParamQuals.isStrictSupersetOf(ArgQuals)1.74k
||
1286
1.75k
          
(1.67k
ParamQuals.hasNonTrivialObjCLifetime()1.67k
&&
1287
1.67k
           
ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone4
&&
1288
1.67k
           ParamQuals.withoutObjCLifetime() ==
1289
84
               ArgQuals.withoutObjCLifetime())) {
1290
84
        Info.FirstArg = TemplateArgument(ParamIn);
1291
84
        Info.SecondArg = TemplateArgument(ArgIn);
1292
84
        return Sema::TDK_NonDeducedMismatch;
1293
84
      }
1294
355k
    }
1295
355k
1296
355k
    // C++11 [temp.deduct.partial]p7:
1297
355k
    //   Remove any top-level cv-qualifiers:
1298
355k
    //     - If P is a cv-qualified type, P is replaced by the cv-unqualified
1299
355k
    //       version of P.
1300
355k
    Param = Param.getUnqualifiedType();
1301
355k
    //     - If A is a cv-qualified type, A is replaced by the cv-unqualified
1302
355k
    //       version of A.
1303
355k
    Arg = Arg.getUnqualifiedType();
1304
2.55M
  } else {
1305
2.55M
    // C++0x [temp.deduct.call]p4 bullet 1:
1306
2.55M
    //   - If the original P is a reference type, the deduced A (i.e., the type
1307
2.55M
    //     referred to by the reference) can be more cv-qualified than the
1308
2.55M
    //     transformed A.
1309
2.55M
    if (TDF & TDF_ParamWithReferenceType) {
1310
591k
      Qualifiers Quals;
1311
591k
      QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1312
591k
      Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
1313
591k
                             Arg.getCVRQualifiers());
1314
591k
      Param = S.Context.getQualifiedType(UnqualParam, Quals);
1315
591k
    }
1316
2.55M
1317
2.55M
    if ((TDF & TDF_TopLevelParameterTypeList) && 
!Param->isFunctionType()239k
) {
1318
127k
      // C++0x [temp.deduct.type]p10:
1319
127k
      //   If P and A are function types that originated from deduction when
1320
127k
      //   taking the address of a function template (14.8.2.2) or when deducing
1321
127k
      //   template arguments from a function declaration (14.8.2.6) and Pi and
1322
127k
      //   Ai are parameters of the top-level parameter-type-list of P and A,
1323
127k
      //   respectively, Pi is adjusted if it is a forwarding reference and Ai
1324
127k
      //   is an lvalue reference, in
1325
127k
      //   which case the type of Pi is changed to be the template parameter
1326
127k
      //   type (i.e., T&& is changed to simply T). [ Note: As a result, when
1327
127k
      //   Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1328
127k
      //   deduced as X&. - end note ]
1329
127k
      TDF &= ~TDF_TopLevelParameterTypeList;
1330
127k
      if (isForwardingReference(Param, 0) && 
Arg->isLValueReferenceType()3
)
1331
3
        Param = Param->getPointeeType();
1332
127k
    }
1333
2.55M
  }
1334
2.91M
1335
2.91M
  // C++ [temp.deduct.type]p9:
1336
2.91M
  //   A template type argument T, a template template argument TT or a
1337
2.91M
  //   template non-type argument i can be deduced if P and A have one of
1338
2.91M
  //   the following forms:
1339
2.91M
  //
1340
2.91M
  //     T
1341
2.91M
  //     cv-list T
1342
2.91M
  
if (const TemplateTypeParmType *2.91M
TemplateTypeParm2.91M
1343
1.29M
        = Param->getAs<TemplateTypeParmType>()) {
1344
1.29M
    // Just skip any attempts to deduce from a placeholder type or a parameter
1345
1.29M
    // at a different depth.
1346
1.29M
    if (Arg->isPlaceholderType() ||
1347
1.29M
        Info.getDeducedDepth() != TemplateTypeParm->getDepth())
1348
4
      return Sema::TDK_Success;
1349
1.29M
1350
1.29M
    unsigned Index = TemplateTypeParm->getIndex();
1351
1.29M
    bool RecanonicalizeArg = false;
1352
1.29M
1353
1.29M
    // If the argument type is an array type, move the qualifiers up to the
1354
1.29M
    // top level, so they can be matched with the qualifiers on the parameter.
1355
1.29M
    if (isa<ArrayType>(Arg)) {
1356
10.3k
      Qualifiers Quals;
1357
10.3k
      Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1358
10.3k
      if (Quals) {
1359
468
        Arg = S.Context.getQualifiedType(Arg, Quals);
1360
468
        RecanonicalizeArg = true;
1361
468
      }
1362
10.3k
    }
1363
1.29M
1364
1.29M
    // The argument type can not be less qualified than the parameter
1365
1.29M
    // type.
1366
1.29M
    if (!(TDF & TDF_IgnoreQualifiers) &&
1367
1.29M
        
hasInconsistentOrSupersetQualifiersOf(Param, Arg)1.23M
) {
1368
86.5k
      Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1369
86.5k
      Info.FirstArg = TemplateArgument(Param);
1370
86.5k
      Info.SecondArg = TemplateArgument(Arg);
1371
86.5k
      return Sema::TDK_Underqualified;
1372
86.5k
    }
1373
1.21M
1374
1.21M
    // Do not match a function type with a cv-qualified type.
1375
1.21M
    // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1376
1.21M
    if (Arg->isFunctionType() && 
Param.hasQualifiers()6.66k
) {
1377
8
      return Sema::TDK_NonDeducedMismatch;
1378
8
    }
1379
1.21M
1380
1.21M
    assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1381
1.21M
           "saw template type parameter with wrong depth");
1382
1.21M
    assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
1383
1.21M
    QualType DeducedType = Arg;
1384
1.21M
1385
1.21M
    // Remove any qualifiers on the parameter from the deduced type.
1386
1.21M
    // We checked the qualifiers for consistency above.
1387
1.21M
    Qualifiers DeducedQs = DeducedType.getQualifiers();
1388
1.21M
    Qualifiers ParamQs = Param.getQualifiers();
1389
1.21M
    DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1390
1.21M
    if (ParamQs.hasObjCGCAttr())
1391
0
      DeducedQs.removeObjCGCAttr();
1392
1.21M
    if (ParamQs.hasAddressSpace())
1393
4
      DeducedQs.removeAddressSpace();
1394
1.21M
    if (ParamQs.hasObjCLifetime())
1395
63
      DeducedQs.removeObjCLifetime();
1396
1.21M
1397
1.21M
    // Objective-C ARC:
1398
1.21M
    //   If template deduction would produce a lifetime qualifier on a type
1399
1.21M
    //   that is not a lifetime type, template argument deduction fails.
1400
1.21M
    if (ParamQs.hasObjCLifetime() && 
!DeducedType->isObjCLifetimeType()63
&&
1401
1.21M
        
!DeducedType->isDependentType()2
) {
1402
2
      Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1403
2
      Info.FirstArg = TemplateArgument(Param);
1404
2
      Info.SecondArg = TemplateArgument(Arg);
1405
2
      return Sema::TDK_Underqualified;
1406
2
    }
1407
1.21M
1408
1.21M
    // Objective-C ARC:
1409
1.21M
    //   If template deduction would produce an argument type with lifetime type
1410
1.21M
    //   but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1411
1.21M
    if (S.getLangOpts().ObjCAutoRefCount &&
1412
1.21M
        
DeducedType->isObjCLifetimeType()390
&&
1413
1.21M
        
!DeducedQs.hasObjCLifetime()177
)
1414
123
      DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1415
1.21M
1416
1.21M
    DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1417
1.21M
                                             DeducedQs);
1418
1.21M
1419
1.21M
    if (RecanonicalizeArg)
1420
467
      DeducedType = S.Context.getCanonicalType(DeducedType);
1421
1.21M
1422
1.21M
    DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1423
1.21M
    DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
1424
1.21M
                                                                 Deduced[Index],
1425
1.21M
                                                                   NewDeduced);
1426
1.21M
    if (Result.isNull()) {
1427
30.7k
      Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1428
30.7k
      Info.FirstArg = Deduced[Index];
1429
30.7k
      Info.SecondArg = NewDeduced;
1430
30.7k
      return Sema::TDK_Inconsistent;
1431
30.7k
    }
1432
1.18M
1433
1.18M
    Deduced[Index] = Result;
1434
1.18M
    return Sema::TDK_Success;
1435
1.18M
  }
1436
1.61M
1437
1.61M
  // Set up the template argument deduction information for a failure.
1438
1.61M
  Info.FirstArg = TemplateArgument(ParamIn);
1439
1.61M
  Info.SecondArg = TemplateArgument(ArgIn);
1440
1.61M
1441
1.61M
  // If the parameter is an already-substituted template parameter
1442
1.61M
  // pack, do nothing: we don't know which of its arguments to look
1443
1.61M
  // at, so we have to wait until all of the parameter packs in this
1444
1.61M
  // expansion have arguments.
1445
1.61M
  if (isa<SubstTemplateTypeParmPackType>(Param))
1446
41
    return Sema::TDK_Success;
1447
1.61M
1448
1.61M
  // Check the cv-qualifiers on the parameter and argument types.
1449
1.61M
  CanQualType CanParam = S.Context.getCanonicalType(Param);
1450
1.61M
  CanQualType CanArg = S.Context.getCanonicalType(Arg);
1451
1.61M
  if (!(TDF & TDF_IgnoreQualifiers)) {
1452
1.53M
    if (TDF & TDF_ParamWithReferenceType) {
1453
446k
      if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
1454
0
        return Sema::TDK_NonDeducedMismatch;
1455
1.08M
    } else if (TDF & TDF_ArgWithReferenceType) {
1456
34
      // C++ [temp.deduct.conv]p4:
1457
34
      //   If the original A is a reference type, A can be more cv-qualified
1458
34
      //   than the deduced A
1459
34
      if (!Arg.getQualifiers().compatiblyIncludes(Param.getQualifiers()))
1460
0
        return Sema::TDK_NonDeducedMismatch;
1461
34
1462
34
      // Strip out all extra qualifiers from the argument to figure out the
1463
34
      // type we're converting to, prior to the qualification conversion.
1464
34
      Qualifiers Quals;
1465
34
      Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1466
34
      Arg = S.Context.getQualifiedType(Arg, Param.getQualifiers());
1467
1.08M
    } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
1468
975k
      if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
1469
22.2k
        return Sema::TDK_NonDeducedMismatch;
1470
1.51M
    }
1471
1.51M
1472
1.51M
    // If the parameter type is not dependent, there is nothing to deduce.
1473
1.51M
    if (!Param->isDependentType()) {
1474
95.6k
      if (!(TDF & TDF_SkipNonDependent)) {
1475
91.6k
        bool NonDeduced =
1476
91.6k
            (TDF & TDF_AllowCompatibleFunctionType)
1477
91.6k
                ? 
!S.isSameOrCompatibleFunctionType(CanParam, CanArg)21.3k
1478
91.6k
                : 
Param != Arg70.3k
;
1479
91.6k
        if (NonDeduced) {
1480
29.4k
          return Sema::TDK_NonDeducedMismatch;
1481
29.4k
        }
1482
66.2k
      }
1483
66.2k
      return Sema::TDK_Success;
1484
66.2k
    }
1485
84.3k
  } else if (!Param->isDependentType()) {
1486
65
    CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1487
65
                ArgUnqualType = CanArg.getUnqualifiedType();
1488
65
    bool Success =
1489
65
        (TDF & TDF_AllowCompatibleFunctionType)
1490
65
            ? 
S.isSameOrCompatibleFunctionType(ParamUnqualType, ArgUnqualType)0
1491
65
            : ParamUnqualType == ArgUnqualType;
1492
65
    if (Success)
1493
63
      return Sema::TDK_Success;
1494
1.49M
  }
1495
1.49M
1496
1.49M
  switch (Param->getTypeClass()) {
1497
0
    // Non-canonical types cannot appear here.
1498
0
#define NON_CANONICAL_TYPE(Class, Base) \
1499
0
  case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1500
0
#define TYPE(Class, Base)
1501
0
#include "clang/AST/TypeNodes.inc"
1502
0
1503
0
    case Type::TemplateTypeParm:
1504
0
    case Type::SubstTemplateTypeParmPack:
1505
0
      llvm_unreachable("Type nodes handled above");
1506
0
1507
0
    // These types cannot be dependent, so simply check whether the types are
1508
0
    // the same.
1509
0
    case Type::Builtin:
1510
0
    case Type::VariableArray:
1511
0
    case Type::Vector:
1512
0
    case Type::FunctionNoProto:
1513
0
    case Type::Record:
1514
0
    case Type::Enum:
1515
0
    case Type::ObjCObject:
1516
0
    case Type::ObjCInterface:
1517
0
    case Type::ObjCObjectPointer:
1518
0
      if (TDF & TDF_SkipNonDependent)
1519
0
        return Sema::TDK_Success;
1520
0
1521
0
      if (TDF & TDF_IgnoreQualifiers) {
1522
0
        Param = Param.getUnqualifiedType();
1523
0
        Arg = Arg.getUnqualifiedType();
1524
0
      }
1525
0
1526
0
      return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1527
0
1528
0
    //     _Complex T   [placeholder extension]
1529
0
    case Type::Complex:
1530
0
      if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
1531
0
        return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1532
0
                                    cast<ComplexType>(Param)->getElementType(),
1533
0
                                    ComplexArg->getElementType(),
1534
0
                                    Info, Deduced, TDF);
1535
0
1536
0
      return Sema::TDK_NonDeducedMismatch;
1537
0
1538
0
    //     _Atomic T   [extension]
1539
0
    case Type::Atomic:
1540
0
      if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
1541
0
        return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1542
0
                                       cast<AtomicType>(Param)->getValueType(),
1543
0
                                       AtomicArg->getValueType(),
1544
0
                                       Info, Deduced, TDF);
1545
0
1546
0
      return Sema::TDK_NonDeducedMismatch;
1547
0
1548
0
    //     T *
1549
61.0k
    case Type::Pointer: {
1550
61.0k
      QualType PointeeType;
1551
61.0k
      if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1552
29.4k
        PointeeType = PointerArg->getPointeeType();
1553
31.5k
      } else if (const ObjCObjectPointerType *PointerArg
1554
44
                   = Arg->getAs<ObjCObjectPointerType>()) {
1555
44
        PointeeType = PointerArg->getPointeeType();
1556
31.5k
      } else {
1557
31.5k
        return Sema::TDK_NonDeducedMismatch;
1558
31.5k
      }
1559
29.4k
1560
29.4k
      unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
1561
29.4k
      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1562
29.4k
                                     cast<PointerType>(Param)->getPointeeType(),
1563
29.4k
                                     PointeeType,
1564
29.4k
                                     Info, Deduced, SubTDF);
1565
29.4k
    }
1566
29.4k
1567
29.4k
    //     T &
1568
89.7k
    case Type::LValueReference: {
1569
89.7k
      const LValueReferenceType *ReferenceArg =
1570
89.7k
          Arg->getAs<LValueReferenceType>();
1571
89.7k
      if (!ReferenceArg)
1572
56.7k
        return Sema::TDK_NonDeducedMismatch;
1573
33.0k
1574
33.0k
      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1575
33.0k
                           cast<LValueReferenceType>(Param)->getPointeeType(),
1576
33.0k
                           ReferenceArg->getPointeeType(), Info, Deduced, 0);
1577
33.0k
    }
1578
33.0k
1579
33.0k
    //     T && [C++0x]
1580
36.4k
    case Type::RValueReference: {
1581
36.4k
      const RValueReferenceType *ReferenceArg =
1582
36.4k
          Arg->getAs<RValueReferenceType>();
1583
36.4k
      if (!ReferenceArg)
1584
35.6k
        return Sema::TDK_NonDeducedMismatch;
1585
732
1586
732
      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1587
732
                             cast<RValueReferenceType>(Param)->getPointeeType(),
1588
732
                             ReferenceArg->getPointeeType(),
1589
732
                             Info, Deduced, 0);
1590
732
    }
1591
732
1592
732
    //     T [] (implied, but not stated explicitly)
1593
39.9k
    case Type::IncompleteArray: {
1594
39.9k
      const IncompleteArrayType *IncompleteArrayArg =
1595
39.9k
        S.Context.getAsIncompleteArrayType(Arg);
1596
39.9k
      if (!IncompleteArrayArg)
1597
39.7k
        return Sema::TDK_NonDeducedMismatch;
1598
282
1599
282
      unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1600
282
      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1601
282
                    S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1602
282
                    IncompleteArrayArg->getElementType(),
1603
282
                    Info, Deduced, SubTDF);
1604
282
    }
1605
282
1606
282
    //     T [integer-constant]
1607
282
    case Type::ConstantArray: {
1608
56
      const ConstantArrayType *ConstantArrayArg =
1609
56
        S.Context.getAsConstantArrayType(Arg);
1610
56
      if (!ConstantArrayArg)
1611
11
        return Sema::TDK_NonDeducedMismatch;
1612
45
1613
45
      const ConstantArrayType *ConstantArrayParm =
1614
45
        S.Context.getAsConstantArrayType(Param);
1615
45
      if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
1616
4
        return Sema::TDK_NonDeducedMismatch;
1617
41
1618
41
      unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1619
41
      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1620
41
                                           ConstantArrayParm->getElementType(),
1621
41
                                           ConstantArrayArg->getElementType(),
1622
41
                                           Info, Deduced, SubTDF);
1623
41
    }
1624
41
1625
41
    //     type [i]
1626
39.8k
    case Type::DependentSizedArray: {
1627
39.8k
      const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
1628
39.8k
      if (!ArrayArg)
1629
39.3k
        return Sema::TDK_NonDeducedMismatch;
1630
513
1631
513
      unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1632
513
1633
513
      // Check the element type of the arrays
1634
513
      const DependentSizedArrayType *DependentArrayParm
1635
513
        = S.Context.getAsDependentSizedArrayType(Param);
1636
513
      if (Sema::TemplateDeductionResult Result
1637
42
            = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1638
42
                                          DependentArrayParm->getElementType(),
1639
42
                                          ArrayArg->getElementType(),
1640
42
                                          Info, Deduced, SubTDF))
1641
42
        return Result;
1642
471
1643
471
      // Determine the array bound is something we can deduce.
1644
471
      NonTypeTemplateParmDecl *NTTP
1645
471
        = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
1646
471
      if (!NTTP)
1647
4
        return Sema::TDK_Success;
1648
467
1649
467
      // We can perform template argument deduction for the given non-type
1650
467
      // template parameter.
1651
467
      assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1652
467
             "saw non-type template parameter with wrong depth");
1653
467
      if (const ConstantArrayType *ConstantArrayArg
1654
376
            = dyn_cast<ConstantArrayType>(ArrayArg)) {
1655
376
        llvm::APSInt Size(ConstantArrayArg->getSize());
1656
376
        return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
1657
376
                                             S.Context.getSizeType(),
1658
376
                                             /*ArrayBound=*/true,
1659
376
                                             Info, Deduced);
1660
376
      }
1661
91
      if (const DependentSizedArrayType *DependentArrayArg
1662
34
            = dyn_cast<DependentSizedArrayType>(ArrayArg))
1663
34
        if (DependentArrayArg->getSizeExpr())
1664
34
          return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1665
34
                                               DependentArrayArg->getSizeExpr(),
1666
34
                                               Info, Deduced);
1667
57
1668
57
      // Incomplete type does not match a dependently-sized array type
1669
57
      return Sema::TDK_NonDeducedMismatch;
1670
57
    }
1671
57
1672
57
    //     type(*)(T)
1673
57
    //     T(*)()
1674
57
    //     T(*)(T)
1675
98.6k
    case Type::FunctionProto: {
1676
98.6k
      unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
1677
98.6k
      const FunctionProtoType *FunctionProtoArg =
1678
98.6k
        dyn_cast<FunctionProtoType>(Arg);
1679
98.6k
      if (!FunctionProtoArg)
1680
8.08k
        return Sema::TDK_NonDeducedMismatch;
1681
90.5k
1682
90.5k
      const FunctionProtoType *FunctionProtoParam =
1683
90.5k
        cast<FunctionProtoType>(Param);
1684
90.5k
1685
90.5k
      if (FunctionProtoParam->getMethodQuals()
1686
90.5k
            != FunctionProtoArg->getMethodQuals() ||
1687
90.5k
          FunctionProtoParam->getRefQualifier()
1688
90.4k
            != FunctionProtoArg->getRefQualifier() ||
1689
90.5k
          
FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic()90.4k
)
1690
109
        return Sema::TDK_NonDeducedMismatch;
1691
90.4k
1692
90.4k
      // Check return types.
1693
90.4k
      if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1694
10.1k
              S, TemplateParams, FunctionProtoParam->getReturnType(),
1695
10.1k
              FunctionProtoArg->getReturnType(), Info, Deduced, 0))
1696
10.1k
        return Result;
1697
80.3k
1698
80.3k
      // Check parameter types.
1699
80.3k
      if (auto Result = DeduceTemplateArguments(
1700
68.8k
              S, TemplateParams, FunctionProtoParam->param_type_begin(),
1701
68.8k
              FunctionProtoParam->getNumParams(),
1702
68.8k
              FunctionProtoArg->param_type_begin(),
1703
68.8k
              FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF))
1704
68.8k
        return Result;
1705
11.5k
1706
11.5k
      if (TDF & TDF_AllowCompatibleFunctionType)
1707
10.2k
        return Sema::TDK_Success;
1708
1.25k
1709
1.25k
      // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1710
1.25k
      // deducing through the noexcept-specifier if it's part of the canonical
1711
1.25k
      // type. libstdc++ relies on this.
1712
1.25k
      Expr *NoexceptExpr = FunctionProtoParam->getNoexceptExpr();
1713
1.25k
      if (NonTypeTemplateParmDecl *NTTP =
1714
13
          NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1715
13
                       : nullptr) {
1716
13
        assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1717
13
               "saw non-type template parameter with wrong depth");
1718
13
1719
13
        llvm::APSInt Noexcept(1);
1720
13
        switch (FunctionProtoArg->canThrow()) {
1721
8
        case CT_Cannot:
1722
8
          Noexcept = 1;
1723
8
          LLVM_FALLTHROUGH;
1724
8
1725
13
        case CT_Can:
1726
13
          // We give E in noexcept(E) the "deduced from array bound" treatment.
1727
13
          // FIXME: Should we?
1728
13
          return DeduceNonTypeTemplateArgument(
1729
13
              S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1730
13
              /*ArrayBound*/true, Info, Deduced);
1731
8
1732
8
        case CT_Dependent:
1733
0
          if (Expr *ArgNoexceptExpr = FunctionProtoArg->getNoexceptExpr())
1734
0
            return DeduceNonTypeTemplateArgument(
1735
0
                S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1736
0
          // Can't deduce anything from throw(T...).
1737
0
          break;
1738
13
        }
1739
13
      }
1740
1.24k
      // FIXME: Detect non-deduced exception specification mismatches?
1741
1.24k
      //
1742
1.24k
      // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
1743
1.24k
      // top-level differences in noexcept-specifications.
1744
1.24k
1745
1.24k
      return Sema::TDK_Success;
1746
1.24k
    }
1747
1.24k
1748
1.24k
    case Type::InjectedClassName:
1749
170
      // Treat a template's injected-class-name as if the template
1750
170
      // specialization type had been used.
1751
170
      Param = cast<InjectedClassNameType>(Param)
1752
170
        ->getInjectedSpecializationType();
1753
170
      assert(isa<TemplateSpecializationType>(Param) &&
1754
170
             "injected class name is not a template specialization type");
1755
170
      LLVM_FALLTHROUGH;
1756
170
1757
170
    //     template-name<T> (where template-name refers to a class template)
1758
170
    //     template-name<i>
1759
170
    //     TT<T>
1760
170
    //     TT<i>
1761
170
    //     TT<>
1762
1.02M
    case Type::TemplateSpecialization: {
1763
1.02M
      const TemplateSpecializationType *SpecParam =
1764
1.02M
          cast<TemplateSpecializationType>(Param);
1765
1.02M
1766
1.02M
      // When Arg cannot be a derived class, we can just try to deduce template
1767
1.02M
      // arguments from the template-id.
1768
1.02M
      const RecordType *RecordT = Arg->getAs<RecordType>();
1769
1.02M
      if (!(TDF & TDF_DerivedClass) || 
!RecordT560k
)
1770
803k
        return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1771
803k
                                       Deduced);
1772
222k
1773
222k
      SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1774
222k
                                                          Deduced.end());
1775
222k
1776
222k
      Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1777
222k
          S, TemplateParams, SpecParam, Arg, Info, Deduced);
1778
222k
1779
222k
      if (Result == Sema::TDK_Success)
1780
55.4k
        return Result;
1781
167k
1782
167k
      // We cannot inspect base classes as part of deduction when the type
1783
167k
      // is incomplete, so either instantiate any templates necessary to
1784
167k
      // complete the type, or skip over it if it cannot be completed.
1785
167k
      if (!S.isCompleteType(Info.getLocation(), Arg))
1786
4
        return Result;
1787
167k
1788
167k
      // C++14 [temp.deduct.call] p4b3:
1789
167k
      //   If P is a class and P has the form simple-template-id, then the
1790
167k
      //   transformed A can be a derived class of the deduced A. Likewise if
1791
167k
      //   P is a pointer to a class of the form simple-template-id, the
1792
167k
      //   transformed A can be a pointer to a derived class pointed to by the
1793
167k
      //   deduced A.
1794
167k
      //
1795
167k
      //   These alternatives are considered only if type deduction would
1796
167k
      //   otherwise fail. If they yield more than one possible deduced A, the
1797
167k
      //   type deduction fails.
1798
167k
1799
167k
      // Reset the incorrectly deduced argument from above.
1800
167k
      Deduced = DeducedOrig;
1801
167k
1802
167k
      // Use data recursion to crawl through the list of base classes.
1803
167k
      // Visited contains the set of nodes we have already visited, while
1804
167k
      // ToVisit is our stack of records that we still need to visit.
1805
167k
      llvm::SmallPtrSet<const RecordType *, 8> Visited;
1806
167k
      SmallVector<const RecordType *, 8> ToVisit;
1807
167k
      ToVisit.push_back(RecordT);
1808
167k
      bool Successful = false;
1809
167k
      SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
1810
346k
      while (!ToVisit.empty()) {
1811
178k
        // Retrieve the next class in the inheritance hierarchy.
1812
178k
        const RecordType *NextT = ToVisit.pop_back_val();
1813
178k
1814
178k
        // If we have already seen this type, skip it.
1815
178k
        if (!Visited.insert(NextT).second)
1816
0
          continue;
1817
178k
1818
178k
        // If this is a base class, try to perform template argument
1819
178k
        // deduction from it.
1820
178k
        if (NextT != RecordT) {
1821
11.4k
          TemplateDeductionInfo BaseInfo(TemplateDeductionInfo::ForBase, Info);
1822
11.4k
          Sema::TemplateDeductionResult BaseResult =
1823
11.4k
              DeduceTemplateArguments(S, TemplateParams, SpecParam,
1824
11.4k
                                      QualType(NextT, 0), BaseInfo, Deduced);
1825
11.4k
1826
11.4k
          // If template argument deduction for this base was successful,
1827
11.4k
          // note that we had some success. Otherwise, ignore any deductions
1828
11.4k
          // from this base class.
1829
11.4k
          if (BaseResult == Sema::TDK_Success) {
1830
4.34k
            // If we've already seen some success, then deduction fails due to
1831
4.34k
            // an ambiguity (temp.deduct.call p5).
1832
4.34k
            if (Successful)
1833
2
              return Sema::TDK_MiscellaneousDeductionFailure;
1834
4.34k
1835
4.34k
            Successful = true;
1836
4.34k
            std::swap(SuccessfulDeduced, Deduced);
1837
4.34k
1838
4.34k
            Info.Param = BaseInfo.Param;
1839
4.34k
            Info.FirstArg = BaseInfo.FirstArg;
1840
4.34k
            Info.SecondArg = BaseInfo.SecondArg;
1841
4.34k
          }
1842
11.4k
1843
11.4k
          Deduced = DeducedOrig;
1844
11.4k
        }
1845
178k
1846
178k
        // Visit base classes
1847
178k
        CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1848
178k
        for (const auto &Base : Next->bases()) {
1849
11.4k
          assert(Base.getType()->isRecordType() &&
1850
11.4k
                 "Base class that isn't a record?");
1851
11.4k
          ToVisit.push_back(Base.getType()->getAs<RecordType>());
1852
11.4k
        }
1853
178k
      }
1854
167k
1855
167k
      
if (167k
Successful167k
) {
1856
4.34k
        std::swap(SuccessfulDeduced, Deduced);
1857
4.34k
        return Sema::TDK_Success;
1858
4.34k
      }
1859
162k
1860
162k
      return Result;
1861
162k
    }
1862
162k
1863
162k
    //     T type::*
1864
162k
    //     T T::*
1865
162k
    //     T (type::*)()
1866
162k
    //     type (T::*)()
1867
162k
    //     type (type::*)(T)
1868
162k
    //     type (T::*)(T)
1869
162k
    //     T (type::*)(T)
1870
162k
    //     T (T::*)()
1871
162k
    //     T (T::*)(T)
1872
162k
    case Type::MemberPointer: {
1873
21.2k
      const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1874
21.2k
      const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1875
21.2k
      if (!MemPtrArg)
1876
20.9k
        return Sema::TDK_NonDeducedMismatch;
1877
240
1878
240
      QualType ParamPointeeType = MemPtrParam->getPointeeType();
1879
240
      if (ParamPointeeType->isFunctionType())
1880
139
        S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1881
139
                                 /*IsCtorOrDtor=*/false, Info.getLocation());
1882
240
      QualType ArgPointeeType = MemPtrArg->getPointeeType();
1883
240
      if (ArgPointeeType->isFunctionType())
1884
158
        S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1885
158
                                 /*IsCtorOrDtor=*/false, Info.getLocation());
1886
240
1887
240
      if (Sema::TemplateDeductionResult Result
1888
81
            = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1889
81
                                                 ParamPointeeType,
1890
81
                                                 ArgPointeeType,
1891
81
                                                 Info, Deduced,
1892
81
                                                 TDF & TDF_IgnoreQualifiers))
1893
81
        return Result;
1894
159
1895
159
      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1896
159
                                           QualType(MemPtrParam->getClass(), 0),
1897
159
                                           QualType(MemPtrArg->getClass(), 0),
1898
159
                                           Info, Deduced,
1899
159
                                           TDF & TDF_IgnoreQualifiers);
1900
159
    }
1901
159
1902
159
    //     (clang extension)
1903
159
    //
1904
159
    //     type(^)(T)
1905
159
    //     T(^)()
1906
159
    //     T(^)(T)
1907
612
    case Type::BlockPointer: {
1908
612
      const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1909
612
      const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
1910
612
1911
612
      if (!BlockPtrArg)
1912
600
        return Sema::TDK_NonDeducedMismatch;
1913
12
1914
12
      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1915
12
                                                BlockPtrParam->getPointeeType(),
1916
12
                                                BlockPtrArg->getPointeeType(),
1917
12
                                                Info, Deduced, 0);
1918
12
    }
1919
12
1920
12
    //     (clang extension)
1921
12
    //
1922
12
    //     T __attribute__(((ext_vector_type(<integral constant>))))
1923
12
    case Type::ExtVector: {
1924
6
      const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1925
6
      if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1926
3
        // Make sure that the vectors have the same number of elements.
1927
3
        if (VectorParam->getNumElements() != VectorArg->getNumElements())
1928
2
          return Sema::TDK_NonDeducedMismatch;
1929
1
1930
1
        // Perform deduction on the element types.
1931
1
        return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1932
1
                                                  VectorParam->getElementType(),
1933
1
                                                  VectorArg->getElementType(),
1934
1
                                                  Info, Deduced, TDF);
1935
1
      }
1936
3
1937
3
      if (const DependentSizedExtVectorType *VectorArg
1938
2
                                = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1939
2
        // We can't check the number of elements, since the argument has a
1940
2
        // dependent number of elements. This can only occur during partial
1941
2
        // ordering.
1942
2
1943
2
        // Perform deduction on the element types.
1944
2
        return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1945
2
                                                  VectorParam->getElementType(),
1946
2
                                                  VectorArg->getElementType(),
1947
2
                                                  Info, Deduced, TDF);
1948
2
      }
1949
1
1950
1
      return Sema::TDK_NonDeducedMismatch;
1951
1
    }
1952
1
1953
1
    case Type::DependentVector: {
1954
0
      const auto *VectorParam = cast<DependentVectorType>(Param);
1955
0
1956
0
      if (const auto *VectorArg = dyn_cast<VectorType>(Arg)) {
1957
0
        // Perform deduction on the element types.
1958
0
        if (Sema::TemplateDeductionResult Result =
1959
0
                DeduceTemplateArgumentsByTypeMatch(
1960
0
                    S, TemplateParams, VectorParam->getElementType(),
1961
0
                    VectorArg->getElementType(), Info, Deduced, TDF))
1962
0
          return Result;
1963
0
1964
0
        // Perform deduction on the vector size, if we can.
1965
0
        NonTypeTemplateParmDecl *NTTP =
1966
0
            getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
1967
0
        if (!NTTP)
1968
0
          return Sema::TDK_Success;
1969
0
1970
0
        llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1971
0
        ArgSize = VectorArg->getNumElements();
1972
0
        // Note that we use the "array bound" rules here; just like in that
1973
0
        // case, we don't have any particular type for the vector size, but
1974
0
        // we can provide one if necessary.
1975
0
        return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
1976
0
                                             S.Context.UnsignedIntTy, true,
1977
0
                                             Info, Deduced);
1978
0
      }
1979
0
1980
0
      if (const auto *VectorArg = dyn_cast<DependentVectorType>(Arg)) {
1981
0
        // Perform deduction on the element types.
1982
0
        if (Sema::TemplateDeductionResult Result =
1983
0
                DeduceTemplateArgumentsByTypeMatch(
1984
0
                    S, TemplateParams, VectorParam->getElementType(),
1985
0
                    VectorArg->getElementType(), Info, Deduced, TDF))
1986
0
          return Result;
1987
0
1988
0
        // Perform deduction on the vector size, if we can.
1989
0
        NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
1990
0
            Info, VectorParam->getSizeExpr());
1991
0
        if (!NTTP)
1992
0
          return Sema::TDK_Success;
1993
0
1994
0
        return DeduceNonTypeTemplateArgument(
1995
0
            S, TemplateParams, NTTP, VectorArg->getSizeExpr(), Info, Deduced);
1996
0
      }
1997
0
1998
0
      return Sema::TDK_NonDeducedMismatch;
1999
0
    }
2000
0
2001
0
    //     (clang extension)
2002
0
    //
2003
0
    //     T __attribute__(((ext_vector_type(N))))
2004
14
    case Type::DependentSizedExtVector: {
2005
14
      const DependentSizedExtVectorType *VectorParam
2006
14
        = cast<DependentSizedExtVectorType>(Param);
2007
14
2008
14
      if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
2009
8
        // Perform deduction on the element types.
2010
8
        if (Sema::TemplateDeductionResult Result
2011
2
              = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2012
2
                                                  VectorParam->getElementType(),
2013
2
                                                   VectorArg->getElementType(),
2014
2
                                                   Info, Deduced, TDF))
2015
2
          return Result;
2016
6
2017
6
        // Perform deduction on the vector size, if we can.
2018
6
        NonTypeTemplateParmDecl *NTTP
2019
6
          = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
2020
6
        if (!NTTP)
2021
0
          return Sema::TDK_Success;
2022
6
2023
6
        llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2024
6
        ArgSize = VectorArg->getNumElements();
2025
6
        // Note that we use the "array bound" rules here; just like in that
2026
6
        // case, we don't have any particular type for the vector size, but
2027
6
        // we can provide one if necessary.
2028
6
        return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2029
6
                                             S.Context.IntTy, true, Info,
2030
6
                                             Deduced);
2031
6
      }
2032
6
2033
6
      if (const DependentSizedExtVectorType *VectorArg
2034
4
                                = dyn_cast<DependentSizedExtVectorType>(Arg)) {
2035
4
        // Perform deduction on the element types.
2036
4
        if (Sema::TemplateDeductionResult Result
2037
2
            = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2038
2
                                                 VectorParam->getElementType(),
2039
2
                                                 VectorArg->getElementType(),
2040
2
                                                 Info, Deduced, TDF))
2041
2
          return Result;
2042
2
2043
2
        // Perform deduction on the vector size, if we can.
2044
2
        NonTypeTemplateParmDecl *NTTP
2045
2
          = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
2046
2
        if (!NTTP)
2047
0
          return Sema::TDK_Success;
2048
2
2049
2
        return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2050
2
                                             VectorArg->getSizeExpr(),
2051
2
                                             Info, Deduced);
2052
2
      }
2053
2
2054
2
      return Sema::TDK_NonDeducedMismatch;
2055
2
    }
2056
2
2057
2
    //     (clang extension)
2058
2
    //
2059
2
    //     T __attribute__(((address_space(N))))
2060
2
    case Type::DependentAddressSpace: {
2061
2
      const DependentAddressSpaceType *AddressSpaceParam =
2062
2
          cast<DependentAddressSpaceType>(Param);
2063
2
2064
2
      if (const DependentAddressSpaceType *AddressSpaceArg =
2065
0
              dyn_cast<DependentAddressSpaceType>(Arg)) {
2066
0
        // Perform deduction on the pointer type.
2067
0
        if (Sema::TemplateDeductionResult Result =
2068
0
                DeduceTemplateArgumentsByTypeMatch(
2069
0
                    S, TemplateParams, AddressSpaceParam->getPointeeType(),
2070
0
                    AddressSpaceArg->getPointeeType(), Info, Deduced, TDF))
2071
0
          return Result;
2072
0
2073
0
        // Perform deduction on the address space, if we can.
2074
0
        NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2075
0
            Info, AddressSpaceParam->getAddrSpaceExpr());
2076
0
        if (!NTTP)
2077
0
          return Sema::TDK_Success;
2078
0
2079
0
        return DeduceNonTypeTemplateArgument(
2080
0
            S, TemplateParams, NTTP, AddressSpaceArg->getAddrSpaceExpr(), Info,
2081
0
            Deduced);
2082
0
      }
2083
2
2084
2
      if (isTargetAddressSpace(Arg.getAddressSpace())) {
2085
2
        llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2086
2
                                     false);
2087
2
        ArgAddressSpace = toTargetAddressSpace(Arg.getAddressSpace());
2088
2
2089
2
        // Perform deduction on the pointer types.
2090
2
        if (Sema::TemplateDeductionResult Result =
2091
0
                DeduceTemplateArgumentsByTypeMatch(
2092
0
                    S, TemplateParams, AddressSpaceParam->getPointeeType(),
2093
0
                    S.Context.removeAddrSpaceQualType(Arg), Info, Deduced, TDF))
2094
0
          return Result;
2095
2
2096
2
        // Perform deduction on the address space, if we can.
2097
2
        NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2098
2
            Info, AddressSpaceParam->getAddrSpaceExpr());
2099
2
        if (!NTTP)
2100
0
          return Sema::TDK_Success;
2101
2
2102
2
        return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2103
2
                                             ArgAddressSpace, S.Context.IntTy,
2104
2
                                             true, Info, Deduced);
2105
2
      }
2106
0
2107
0
      return Sema::TDK_NonDeducedMismatch;
2108
0
    }
2109
0
2110
85.8k
    case Type::TypeOfExpr:
2111
85.8k
    case Type::TypeOf:
2112
85.8k
    case Type::DependentName:
2113
85.8k
    case Type::UnresolvedUsing:
2114
85.8k
    case Type::Decltype:
2115
85.8k
    case Type::UnaryTransform:
2116
85.8k
    case Type::Auto:
2117
85.8k
    case Type::DeducedTemplateSpecialization:
2118
85.8k
    case Type::DependentTemplateSpecialization:
2119
85.8k
    case Type::PackExpansion:
2120
85.8k
    case Type::Pipe:
2121
85.8k
      // No template argument deduction for these types
2122
85.8k
      return Sema::TDK_Success;
2123
0
  }
2124
0
2125
0
  llvm_unreachable("Invalid Type Class!");
2126
0
}
2127
2128
static Sema::TemplateDeductionResult
2129
DeduceTemplateArguments(Sema &S,
2130
                        TemplateParameterList *TemplateParams,
2131
                        const TemplateArgument &Param,
2132
                        TemplateArgument Arg,
2133
                        TemplateDeductionInfo &Info,
2134
1.79M
                        SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
2135
1.79M
  // If the template argument is a pack expansion, perform template argument
2136
1.79M
  // deduction against the pattern of that expansion. This only occurs during
2137
1.79M
  // partial ordering.
2138
1.79M
  if (Arg.isPackExpansion())
2139
4.50k
    Arg = Arg.getPackExpansionPattern();
2140
1.79M
2141
1.79M
  switch (Param.getKind()) {
2142
0
  case TemplateArgument::Null:
2143
0
    llvm_unreachable("Null template argument in parameter list");
2144
0
2145
1.33M
  case TemplateArgument::Type:
2146
1.33M
    if (Arg.getKind() == TemplateArgument::Type)
2147
1.33M
      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2148
1.33M
                                                Param.getAsType(),
2149
1.33M
                                                Arg.getAsType(),
2150
1.33M
                                                Info, Deduced, 0);
2151
3
    Info.FirstArg = Param;
2152
3
    Info.SecondArg = Arg;
2153
3
    return Sema::TDK_NonDeducedMismatch;
2154
3
2155
95
  case TemplateArgument::Template:
2156
95
    if (Arg.getKind() == TemplateArgument::Template)
2157
95
      return DeduceTemplateArguments(S, TemplateParams,
2158
95
                                     Param.getAsTemplate(),
2159
95
                                     Arg.getAsTemplate(), Info, Deduced);
2160
0
    Info.FirstArg = Param;
2161
0
    Info.SecondArg = Arg;
2162
0
    return Sema::TDK_NonDeducedMismatch;
2163
0
2164
0
  case TemplateArgument::TemplateExpansion:
2165
0
    llvm_unreachable("caller should handle pack expansions");
2166
0
2167
6
  case TemplateArgument::Declaration:
2168
6
    if (Arg.getKind() == TemplateArgument::Declaration &&
2169
6
        
isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl())5
)
2170
5
      return Sema::TDK_Success;
2171
1
2172
1
    Info.FirstArg = Param;
2173
1
    Info.SecondArg = Arg;
2174
1
    return Sema::TDK_NonDeducedMismatch;
2175
1
2176
6
  case TemplateArgument::NullPtr:
2177
6
    if (Arg.getKind() == TemplateArgument::NullPtr &&
2178
6
        
S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType())5
)
2179
5
      return Sema::TDK_Success;
2180
1
2181
1
    Info.FirstArg = Param;
2182
1
    Info.SecondArg = Arg;
2183
1
    return Sema::TDK_NonDeducedMismatch;
2184
1
2185
235k
  case TemplateArgument::Integral:
2186
235k
    if (Arg.getKind() == TemplateArgument::Integral) {
2187
179k
      if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
2188
89.4k
        return Sema::TDK_Success;
2189
89.8k
2190
89.8k
      Info.FirstArg = Param;
2191
89.8k
      Info.SecondArg = Arg;
2192
89.8k
      return Sema::TDK_NonDeducedMismatch;
2193
89.8k
    }
2194
56.6k
2195
56.6k
    if (Arg.getKind() == TemplateArgument::Expression) {
2196
56.6k
      Info.FirstArg = Param;
2197
56.6k
      Info.SecondArg = Arg;
2198
56.6k
      return Sema::TDK_NonDeducedMismatch;
2199
56.6k
    }
2200
0
2201
0
    Info.FirstArg = Param;
2202
0
    Info.SecondArg = Arg;
2203
0
    return Sema::TDK_NonDeducedMismatch;
2204
0
2205
225k
  case TemplateArgument::Expression:
2206
225k
    if (NonTypeTemplateParmDecl *NTTP
2207
225k
          = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
2208
225k
      if (Arg.getKind() == TemplateArgument::Integral)
2209
165k
        return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2210
165k
                                             Arg.getAsIntegral(),
2211
165k
                                             Arg.getIntegralType(),
2212
165k
                                             /*ArrayBound=*/false,
2213
165k
                                             Info, Deduced);
2214
59.5k
      if (Arg.getKind() == TemplateArgument::NullPtr)
2215
27
        return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2216
27
                                             Arg.getNullPtrType(),
2217
27
                                             Info, Deduced);
2218
59.5k
      if (Arg.getKind() == TemplateArgument::Expression)
2219
58.4k
        return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2220
58.4k
                                             Arg.getAsExpr(), Info, Deduced);
2221
1.12k
      if (Arg.getKind() == TemplateArgument::Declaration)
2222
1.12k
        return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2223
1.12k
                                             Arg.getAsDecl(),
2224
1.12k
                                             Arg.getParamTypeForDecl(),
2225
1.12k
                                             Info, Deduced);
2226
6
2227
6
      Info.FirstArg = Param;
2228
6
      Info.SecondArg = Arg;
2229
6
      return Sema::TDK_NonDeducedMismatch;
2230
6
    }
2231
197
2232
197
    // Can't deduce anything, but that's okay.
2233
197
    return Sema::TDK_Success;
2234
197
2235
197
  case TemplateArgument::Pack:
2236
0
    llvm_unreachable("Argument packs should be expanded by the caller!");
2237
0
  }
2238
0
2239
0
  llvm_unreachable("Invalid TemplateArgument Kind!");
2240
0
}
2241
2242
/// Determine whether there is a template argument to be used for
2243
/// deduction.
2244
///
2245
/// This routine "expands" argument packs in-place, overriding its input
2246
/// parameters so that \c Args[ArgIdx] will be the available template argument.
2247
///
2248
/// \returns true if there is another template argument (which will be at
2249
/// \c Args[ArgIdx]), false otherwise.
2250
static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
2251
4.02M
                                            unsigned &ArgIdx) {
2252
4.02M
  if (ArgIdx == Args.size())
2253
502k
    return false;
2254
3.52M
2255
3.52M
  const TemplateArgument &Arg = Args[ArgIdx];
2256
3.52M
  if (Arg.getKind() != TemplateArgument::Pack)
2257
3.37M
    return true;
2258
144k
2259
144k
  assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2260
144k
  Args = Arg.pack_elements();
2261
144k
  ArgIdx = 0;
2262
144k
  return ArgIdx < Args.size();
2263
144k
}
2264
2265
/// Determine whether the given set of template arguments has a pack
2266
/// expansion that is not the last template argument.
2267
1.89M
static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
2268
1.89M
  bool FoundPackExpansion = false;
2269
3.37M
  for (const auto &A : Args) {
2270
3.37M
    if (FoundPackExpansion)
2271
7
      return true;
2272
3.37M
2273
3.37M
    if (A.getKind() == TemplateArgument::Pack)
2274
143k
      return hasPackExpansionBeforeEnd(A.pack_elements());
2275
3.22M
2276
3.22M
    // FIXME: If this is a fixed-arity pack expansion from an outer level of
2277
3.22M
    // templates, it should not be treated as a pack expansion.
2278
3.22M
    if (A.isPackExpansion())
2279
106k
      FoundPackExpansion = true;
2280
3.22M
  }
2281
1.89M
2282
1.89M
  
return false1.75M
;
2283
1.89M
}
2284
2285
static Sema::TemplateDeductionResult
2286
DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
2287
                        ArrayRef<TemplateArgument> Params,
2288
                        ArrayRef<TemplateArgument> Args,
2289
                        TemplateDeductionInfo &Info,
2290
                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2291
999k
                        bool NumberOfArgumentsMustMatch) {
2292
999k
  // C++0x [temp.deduct.type]p9:
2293
999k
  //   If the template argument list of P contains a pack expansion that is not
2294
999k
  //   the last template argument, the entire template argument list is a
2295
999k
  //   non-deduced context.
2296
999k
  if (hasPackExpansionBeforeEnd(Params))
2297
2
    return Sema::TDK_Success;
2298
999k
2299
999k
  // C++0x [temp.deduct.type]p9:
2300
999k
  //   If P has a form that contains <T> or <i>, then each argument Pi of the
2301
999k
  //   respective template argument list P is compared with the corresponding
2302
999k
  //   argument Ai of the corresponding template argument list of A.
2303
999k
  unsigned ArgIdx = 0, ParamIdx = 0;
2304
2.17M
  for (; hasTemplateArgumentForDeduction(Params, ParamIdx); 
++ParamIdx1.17M
) {
2305
1.71M
    if (!Params[ParamIdx].isPackExpansion()) {
2306
1.67M
      // The simple case: deduce template arguments by matching Pi and Ai.
2307
1.67M
2308
1.67M
      // Check whether we have enough arguments.
2309
1.67M
      if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
2310
7.60k
        return NumberOfArgumentsMustMatch
2311
7.60k
                   ? 
Sema::TDK_MiscellaneousDeductionFailure500
2312
7.60k
                   : 
Sema::TDK_Success7.10k
;
2313
1.66M
2314
1.66M
      // C++1z [temp.deduct.type]p9:
2315
1.66M
      //   During partial ordering, if Ai was originally a pack expansion [and]
2316
1.66M
      //   Pi is not a pack expansion, template argument deduction fails.
2317
1.66M
      if (Args[ArgIdx].isPackExpansion())
2318
3.98k
        return Sema::TDK_MiscellaneousDeductionFailure;
2319
1.66M
2320
1.66M
      // Perform deduction for this Pi/Ai pair.
2321
1.66M
      if (Sema::TemplateDeductionResult Result
2322
522k
            = DeduceTemplateArguments(S, TemplateParams,
2323
522k
                                      Params[ParamIdx], Args[ArgIdx],
2324
522k
                                      Info, Deduced))
2325
522k
        return Result;
2326
1.14M
2327
1.14M
      // Move to the next argument.
2328
1.14M
      ++ArgIdx;
2329
1.14M
      continue;
2330
1.14M
    }
2331
35.4k
2332
35.4k
    // The parameter is a pack expansion.
2333
35.4k
2334
35.4k
    // C++0x [temp.deduct.type]p9:
2335
35.4k
    //   If Pi is a pack expansion, then the pattern of Pi is compared with
2336
35.4k
    //   each remaining argument in the template argument list of A. Each
2337
35.4k
    //   comparison deduces template arguments for subsequent positions in the
2338
35.4k
    //   template parameter packs expanded by Pi.
2339
35.4k
    TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
2340
35.4k
2341
35.4k
    // Prepare to deduce the packs within the pattern.
2342
35.4k
    PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2343
35.4k
2344
35.4k
    // Keep track of the deduced template arguments for each parameter pack
2345
35.4k
    // expanded by this pack expansion (the outer index) and for each
2346
35.4k
    // template argument (the inner SmallVectors).
2347
168k
    for (; hasTemplateArgumentForDeduction(Args, ArgIdx) &&
2348
168k
           
PackScope.hasNextElement()133k
;
2349
133k
         
++ArgIdx133k
) {
2350
133k
      // Deduce template arguments from the pattern.
2351
133k
      if (Sema::TemplateDeductionResult Result
2352
21
            = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
2353
21
                                      Info, Deduced))
2354
21
        return Result;
2355
133k
2356
133k
      PackScope.nextPackElement();
2357
133k
    }
2358
35.4k
2359
35.4k
    // Build argument packs for each of the parameter packs expanded by this
2360
35.4k
    // pack expansion.
2361
35.4k
    
if (auto 35.4k
Result35.4k
= PackScope.finish())
2362
14
      return Result;
2363
35.4k
  }
2364
999k
2365
999k
  
return Sema::TDK_Success465k
;
2366
999k
}
2367
2368
static Sema::TemplateDeductionResult
2369
DeduceTemplateArguments(Sema &S,
2370
                        TemplateParameterList *TemplateParams,
2371
                        const TemplateArgumentList &ParamList,
2372
                        const TemplateArgumentList &ArgList,
2373
                        TemplateDeductionInfo &Info,
2374
543k
                        SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
2375
543k
  return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
2376
543k
                                 ArgList.asArray(), Info, Deduced,
2377
543k
                                 /*NumberOfArgumentsMustMatch*/false);
2378
543k
}
2379
2380
/// Determine whether two template arguments are the same.
2381
static bool isSameTemplateArg(ASTContext &Context,
2382
                              TemplateArgument X,
2383
                              const TemplateArgument &Y,
2384
723k
                              bool PackExpansionMatchesPack = false) {
2385
723k
  // If we're checking deduced arguments (X) against original arguments (Y),
2386
723k
  // we will have flattened packs to non-expansions in X.
2387
723k
  if (PackExpansionMatchesPack && 
X.isPackExpansion()350k
&&
!Y.isPackExpansion()4.39k
)
2388
4.39k
    X = X.getPackExpansionPattern();
2389
723k
2390
723k
  if (X.getKind() != Y.getKind())
2391
0
    return false;
2392
723k
2393
723k
  switch (X.getKind()) {
2394
0
    case TemplateArgument::Null:
2395
0
      llvm_unreachable("Comparing NULL template argument");
2396
0
2397
451k
    case TemplateArgument::Type:
2398
451k
      return Context.getCanonicalType(X.getAsType()) ==
2399
451k
             Context.getCanonicalType(Y.getAsType());
2400
0
2401
29
    case TemplateArgument::Declaration:
2402
29
      return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2403
0
2404
6
    case TemplateArgument::NullPtr:
2405
6
      return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2406
0
2407
64
    case TemplateArgument::Template:
2408
64
    case TemplateArgument::TemplateExpansion:
2409
64
      return Context.getCanonicalTemplateName(
2410
64
                    X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2411
64
             Context.getCanonicalTemplateName(
2412
64
                    Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
2413
64
2414
212k
    case TemplateArgument::Integral:
2415
212k
      return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2416
64
2417
34.9k
    case TemplateArgument::Expression: {
2418
34.9k
      llvm::FoldingSetNodeID XID, YID;
2419
34.9k
      X.getAsExpr()->Profile(XID, Context, true);
2420
34.9k
      Y.getAsExpr()->Profile(YID, Context, true);
2421
34.9k
      return XID == YID;
2422
64
    }
2423
64
2424
24.7k
    case TemplateArgument::Pack:
2425
24.7k
      if (X.pack_size() != Y.pack_size())
2426
4.86k
        return false;
2427
19.8k
2428
19.8k
      for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2429
19.8k
                                        XPEnd = X.pack_end(),
2430
19.8k
                                           YP = Y.pack_begin();
2431
53.6k
           XP != XPEnd; 
++XP, ++YP33.7k
)
2432
33.7k
        if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
2433
0
          return false;
2434
19.8k
2435
19.8k
      return true;
2436
0
  }
2437
0
2438
0
  llvm_unreachable("Invalid TemplateArgument Kind!");
2439
0
}
2440
2441
/// Allocate a TemplateArgumentLoc where all locations have
2442
/// been initialized to the given location.
2443
///
2444
/// \param Arg The template argument we are producing template argument
2445
/// location information for.
2446
///
2447
/// \param NTTPType For a declaration template argument, the type of
2448
/// the non-type template parameter that corresponds to this template
2449
/// argument. Can be null if no type sugar is available to add to the
2450
/// type from the template argument.
2451
///
2452
/// \param Loc The source location to use for the resulting template
2453
/// argument.
2454
TemplateArgumentLoc
2455
Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2456
1.06M
                                    QualType NTTPType, SourceLocation Loc) {
2457
1.06M
  switch (Arg.getKind()) {
2458
0
  case TemplateArgument::Null:
2459
0
    llvm_unreachable("Can't get a NULL template argument here");
2460
0
2461
874k
  case TemplateArgument::Type:
2462
874k
    return TemplateArgumentLoc(
2463
874k
        Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2464
0
2465
76
  case TemplateArgument::Declaration: {
2466
76
    if (NTTPType.isNull())
2467
76
      NTTPType = Arg.getParamTypeForDecl();
2468
76
    Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2469
76
                  .getAs<Expr>();
2470
76
    return TemplateArgumentLoc(TemplateArgument(E), E);
2471
0
  }
2472
0
2473
1
  case TemplateArgument::NullPtr: {
2474
1
    if (NTTPType.isNull())
2475
1
      NTTPType = Arg.getNullPtrType();
2476
1
    Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2477
1
                  .getAs<Expr>();
2478
1
    return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2479
1
                               E);
2480
0
  }
2481
0
2482
150k
  case TemplateArgument::Integral: {
2483
150k
    Expr *E =
2484
150k
        BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
2485
150k
    return TemplateArgumentLoc(TemplateArgument(E), E);
2486
0
  }
2487
0
2488
1.60k
    case TemplateArgument::Template:
2489
1.60k
    case TemplateArgument::TemplateExpansion: {
2490
1.60k
      NestedNameSpecifierLocBuilder Builder;
2491
1.60k
      TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
2492
1.60k
      if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2493
0
        Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2494
1.60k
      else if (QualifiedTemplateName *QTN =
2495
0
                   Template.getAsQualifiedTemplateName())
2496
0
        Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2497
1.60k
2498
1.60k
      if (Arg.getKind() == TemplateArgument::Template)
2499
1.60k
        return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2500
1.60k
                                   Loc);
2501
0
2502
0
      return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2503
0
                                 Loc, Loc);
2504
0
    }
2505
0
2506
34.9k
  case TemplateArgument::Expression:
2507
34.9k
    return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2508
0
2509
6
  case TemplateArgument::Pack:
2510
6
    return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2511
0
  }
2512
0
2513
0
  llvm_unreachable("Invalid TemplateArgument Kind!");
2514
0
}
2515
2516
TemplateArgumentLoc
2517
Sema::getIdentityTemplateArgumentLoc(NamedDecl *TemplateParm,
2518
86
                                     SourceLocation Location) {
2519
86
  return getTrivialTemplateArgumentLoc(
2520
86
      Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2521
86
}
2522
2523
/// Convert the given deduced template argument and add it to the set of
2524
/// fully-converted template arguments.
2525
static bool
2526
ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2527
                               DeducedTemplateArgument Arg,
2528
                               NamedDecl *Template,
2529
                               TemplateDeductionInfo &Info,
2530
                               bool IsDeduced,
2531
940k
                               SmallVectorImpl<TemplateArgument> &Output) {
2532
940k
  auto ConvertArg = [&](DeducedTemplateArgument Arg,
2533
1.04M
                        unsigned ArgumentPackIndex) {
2534
1.04M
    // Convert the deduced template argument into a template
2535
1.04M
    // argument that we can check, almost as if the user had written
2536
1.04M
    // the template argument explicitly.
2537
1.04M
    TemplateArgumentLoc ArgLoc =
2538
1.04M
        S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
2539
1.04M
2540
1.04M
    // Check the template argument, converting it as necessary.
2541
1.04M
    return S.CheckTemplateArgument(
2542
1.04M
        Param, ArgLoc, Template, Template->getLocation(),
2543
1.04M
        Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2544
1.04M
        IsDeduced
2545
1.04M
            ? 
(Arg.wasDeducedFromArrayBound() 691k
?
Sema::CTAK_DeducedFromArrayBound440
2546
691k
                                              : 
Sema::CTAK_Deduced690k
)
2547
1.04M
            : 
Sema::CTAK_Specified352k
);
2548
1.04M
  };
2549
940k
2550
940k
  if (Arg.getKind() == TemplateArgument::Pack) {
2551
63.2k
    // This is a template argument pack, so check each of its arguments against
2552
63.2k
    // the template parameter.
2553
63.2k
    SmallVector<TemplateArgument, 2> PackedArgsBuilder;
2554
166k
    for (const auto &P : Arg.pack_elements()) {
2555
166k
      // When converting the deduced template argument, append it to the
2556
166k
      // general output list. We need to do this so that the template argument
2557
166k
      // checking logic has all of the prior template arguments available.
2558
166k
      DeducedTemplateArgument InnerArg(P);
2559
166k
      InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
2560
166k
      assert(InnerArg.getKind() != TemplateArgument::Pack &&
2561
166k
             "deduced nested pack");
2562
166k
      if (P.isNull()) {
2563
19
        // We deduced arguments for some elements of this pack, but not for
2564
19
        // all of them. This happens if we get a conditionally-non-deduced
2565
19
        // context in a pack expansion (such as an overload set in one of the
2566
19
        // arguments).
2567
19
        S.Diag(Param->getLocation(),
2568
19
               diag::err_template_arg_deduced_incomplete_pack)
2569
19
          << Arg << Param;
2570
19
        return true;
2571
19
      }
2572
166k
      if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
2573
2
        return true;
2574
166k
2575
166k
      // Move the converted template argument into our argument pack.
2576
166k
      PackedArgsBuilder.push_back(Output.pop_back_val());
2577
166k
    }
2578
63.2k
2579
63.2k
    // If the pack is empty, we still need to substitute into the parameter
2580
63.2k
    // itself, in case that substitution fails.
2581
63.2k
    
if (63.2k
PackedArgsBuilder.empty()63.2k
) {
2582
9.02k
      LocalInstantiationScope Scope(S);
2583
9.02k
      TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
2584
9.02k
      MultiLevelTemplateArgumentList Args(TemplateArgs);
2585
9.02k
2586
9.02k
      if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2587
2.10k
        Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2588
2.10k
                                         NTTP, Output,
2589
2.10k
                                         Template->getSourceRange());
2590
2.10k
        if (Inst.isInvalid() ||
2591
2.10k
            S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2592
2.10k
                        NTTP->getDeclName()).isNull())
2593
2
          return true;
2594
6.91k
      } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2595
14
        Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2596
14
                                         TTP, Output,
2597
14
                                         Template->getSourceRange());
2598
14
        if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2599
4
          return true;
2600
63.2k
      }
2601
9.02k
      // For type parameters, no substitution is ever required.
2602
9.02k
    }
2603
63.2k
2604
63.2k
    // Create the resulting argument pack.
2605
63.2k
    Output.push_back(
2606
63.2k
        TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
2607
63.2k
    return false;
2608
63.2k
  }
2609
877k
2610
877k
  return ConvertArg(Arg, 0);
2611
877k
}
2612
2613
// FIXME: This should not be a template, but
2614
// ClassTemplatePartialSpecializationDecl sadly does not derive from
2615
// TemplateDecl.
2616
template<typename TemplateDeclT>
2617
static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
2618
    Sema &S, TemplateDeclT *Template, bool IsDeduced,
2619
    SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2620
    TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2621
    LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2622
861k
    unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2623
861k
  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2624
861k
2625
2.12M
  for (unsigned I = 0, N = TemplateParams->size(); I != N; 
++I1.26M
) {
2626
1.31M
    NamedDecl *Param = TemplateParams->getParam(I);
2627
1.31M
2628
1.31M
    // C++0x [temp.arg.explicit]p3:
2629
1.31M
    //    A trailing template parameter pack (14.5.3) not otherwise deduced will
2630
1.31M
    //    be deduced to an empty sequence of template arguments.
2631
1.31M
    // FIXME: Where did the word "trailing" come from?
2632
1.31M
    if (Deduced[I].isNull() && 
Param->isTemplateParameterPack()114k
) {
2633
17.2k
      if (auto Result =
2634
8
              PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish())
2635
8
        return Result;
2636
1.31M
    }
2637
1.31M
2638
1.31M
    if (!Deduced[I].isNull()) {
2639
1.21M
      if (I < NumAlreadyConverted) {
2640
291k
        // We may have had explicitly-specified template arguments for a
2641
291k
        // template parameter pack (that may or may not have been extended
2642
291k
        // via additional deduced arguments).
2643
291k
        if (Param->isParameterPack() && 
CurrentInstantiationScope16.7k
&&
2644
291k
            
CurrentInstantiationScope->getPartiallySubstitutedPack() == Param16.7k
) {
2645
16.7k
          // Forget the partially-substituted pack; its substitution is now
2646
16.7k
          // complete.
2647
16.7k
          CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2648
16.7k
          // We still need to check the argument in case it was extended by
2649
16.7k
          // deduction.
2650
275k
        } else {
2651
275k
          // We have already fully type-checked and converted this
2652
275k
          // argument, because it was explicitly-specified. Just record the
2653
275k
          // presence of this argument.
2654
275k
          Builder.push_back(Deduced[I]);
2655
275k
          continue;
2656
275k
        }
2657
940k
      }
2658
940k
2659
940k
      // We may have deduced this argument, so it still needs to be
2660
940k
      // checked and converted.
2661
940k
      if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2662
940k
                                         IsDeduced, Builder)) {
2663
80
        Info.Param = makeTemplateParameter(Param);
2664
80
        // FIXME: These template arguments are temporary. Free them!
2665
80
        Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2666
80
        return Sema::TDK_SubstitutionFailure;
2667
80
      }
2668
940k
2669
940k
      continue;
2670
940k
    }
2671
97.6k
2672
97.6k
    // Substitute into the default template argument, if available.
2673
97.6k
    bool HasDefaultArg = false;
2674
97.6k
    TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2675
97.6k
    if (!TD) {
2676
7.11k
      assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2677
7.11k
             isa<VarTemplatePartialSpecializationDecl>(Template));
2678
7.11k
      return Sema::TDK_Incomplete;
2679
7.11k
    }
2680
90.5k
2681
90.5k
    TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2682
90.5k
        TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2683
90.5k
        HasDefaultArg);
2684
90.5k
2685
90.5k
    // If there was no default argument, deduction is incomplete.
2686
90.5k
    if (DefArg.getArgument().isNull()) {
2687
27.3k
      Info.Param = makeTemplateParameter(
2688
27.3k
          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2689
27.3k
      Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2690
27.3k
      if (PartialOverloading) 
break62
;
2691
27.2k
2692
27.2k
      return HasDefaultArg ? 
Sema::TDK_SubstitutionFailure25.8k
2693
27.2k
                           : 
Sema::TDK_Incomplete1.35k
;
2694
27.2k
    }
2695
63.2k
2696
63.2k
    // Check whether we can actually use the default argument.
2697
63.2k
    if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2698
63.2k
                                TD->getSourceRange().getEnd(), 0, Builder,
2699
63.2k
                                Sema::CTAK_Specified)) {
2700
12.4k
      Info.Param = makeTemplateParameter(
2701
12.4k
                         const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2702
12.4k
      // FIXME: These template arguments are temporary. Free them!
2703
12.4k
      Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2704
12.4k
      return Sema::TDK_SubstitutionFailure;
2705
12.4k
    }
2706
63.2k
2707
63.2k
    // If we get here, we successfully used the default template argument.
2708
63.2k
  }
2709
861k
2710
861k
  
return Sema::TDK_Success814k
;
2711
861k
}
SemaTemplateDeduction.cpp:clang::Sema::TemplateDeductionResult ConvertDeducedTemplateArguments<clang::ClassTemplatePartialSpecializationDecl>(clang::Sema&, clang::ClassTemplatePartialSpecializationDecl*, bool, llvm::SmallVectorImpl<clang::DeducedTemplateArgument>&, clang::sema::TemplateDeductionInfo&, llvm::SmallVectorImpl<clang::TemplateArgument>&, clang::LocalInstantiationScope*, unsigned int, bool)
Line
Count
Source
2622
194k
    unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2623
194k
  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2624
194k
2625
479k
  for (unsigned I = 0, N = TemplateParams->size(); I != N; 
++I284k
) {
2626
292k
    NamedDecl *Param = TemplateParams->getParam(I);
2627
292k
2628
292k
    // C++0x [temp.arg.explicit]p3:
2629
292k
    //    A trailing template parameter pack (14.5.3) not otherwise deduced will
2630
292k
    //    be deduced to an empty sequence of template arguments.
2631
292k
    // FIXME: Where did the word "trailing" come from?
2632
292k
    if (Deduced[I].isNull() && 
Param->isTemplateParameterPack()7.11k
) {
2633
2
      if (auto Result =
2634
0
              PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish())
2635
0
        return Result;
2636
292k
    }
2637
292k
2638
292k
    if (!Deduced[I].isNull()) {
2639
284k
      if (I < NumAlreadyConverted) {
2640
0
        // We may have had explicitly-specified template arguments for a
2641
0
        // template parameter pack (that may or may not have been extended
2642
0
        // via additional deduced arguments).
2643
0
        if (Param->isParameterPack() && CurrentInstantiationScope &&
2644
0
            CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2645
0
          // Forget the partially-substituted pack; its substitution is now
2646
0
          // complete.
2647
0
          CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2648
0
          // We still need to check the argument in case it was extended by
2649
0
          // deduction.
2650
0
        } else {
2651
0
          // We have already fully type-checked and converted this
2652
0
          // argument, because it was explicitly-specified. Just record the
2653
0
          // presence of this argument.
2654
0
          Builder.push_back(Deduced[I]);
2655
0
          continue;
2656
0
        }
2657
284k
      }
2658
284k
2659
284k
      // We may have deduced this argument, so it still needs to be
2660
284k
      // checked and converted.
2661
284k
      if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2662
284k
                                         IsDeduced, Builder)) {
2663
43
        Info.Param = makeTemplateParameter(Param);
2664
43
        // FIXME: These template arguments are temporary. Free them!
2665
43
        Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2666
43
        return Sema::TDK_SubstitutionFailure;
2667
43
      }
2668
284k
2669
284k
      continue;
2670
284k
    }
2671
7.11k
2672
7.11k
    // Substitute into the default template argument, if available.
2673
7.11k
    bool HasDefaultArg = false;
2674
7.11k
    TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2675
7.11k
    if (!TD) {
2676
7.11k
      assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2677
7.11k
             isa<VarTemplatePartialSpecializationDecl>(Template));
2678
7.11k
      return Sema::TDK_Incomplete;
2679
7.11k
    }
2680
0
2681
0
    TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2682
0
        TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2683
0
        HasDefaultArg);
2684
0
2685
0
    // If there was no default argument, deduction is incomplete.
2686
0
    if (DefArg.getArgument().isNull()) {
2687
0
      Info.Param = makeTemplateParameter(
2688
0
          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2689
0
      Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2690
0
      if (PartialOverloading) break;
2691
0
2692
0
      return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2693
0
                           : Sema::TDK_Incomplete;
2694
0
    }
2695
0
2696
0
    // Check whether we can actually use the default argument.
2697
0
    if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2698
0
                                TD->getSourceRange().getEnd(), 0, Builder,
2699
0
                                Sema::CTAK_Specified)) {
2700
0
      Info.Param = makeTemplateParameter(
2701
0
                         const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2702
0
      // FIXME: These template arguments are temporary. Free them!
2703
0
      Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2704
0
      return Sema::TDK_SubstitutionFailure;
2705
0
    }
2706
0
2707
0
    // If we get here, we successfully used the default template argument.
2708
0
  }
2709
194k
2710
194k
  
return Sema::TDK_Success187k
;
2711
194k
}
SemaTemplateDeduction.cpp:clang::Sema::TemplateDeductionResult ConvertDeducedTemplateArguments<clang::VarTemplatePartialSpecializationDecl>(clang::Sema&, clang::VarTemplatePartialSpecializationDecl*, bool, llvm::SmallVectorImpl<clang::DeducedTemplateArgument>&, clang::sema::TemplateDeductionInfo&, llvm::SmallVectorImpl<clang::TemplateArgument>&, clang::LocalInstantiationScope*, unsigned int, bool)
Line
Count
Source
2622
229
    unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2623
229
  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2624
229
2625
461
  for (unsigned I = 0, N = TemplateParams->size(); I != N; 
++I232
) {
2626
233
    NamedDecl *Param = TemplateParams->getParam(I);
2627
233
2628
233
    // C++0x [temp.arg.explicit]p3:
2629
233
    //    A trailing template parameter pack (14.5.3) not otherwise deduced will
2630
233
    //    be deduced to an empty sequence of template arguments.
2631
233
    // FIXME: Where did the word "trailing" come from?
2632
233
    if (Deduced[I].isNull() && 
Param->isTemplateParameterPack()1
) {
2633
0
      if (auto Result =
2634
0
              PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish())
2635
0
        return Result;
2636
233
    }
2637
233
2638
233
    if (!Deduced[I].isNull()) {
2639
232
      if (I < NumAlreadyConverted) {
2640
0
        // We may have had explicitly-specified template arguments for a
2641
0
        // template parameter pack (that may or may not have been extended
2642
0
        // via additional deduced arguments).
2643
0
        if (Param->isParameterPack() && CurrentInstantiationScope &&
2644
0
            CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2645
0
          // Forget the partially-substituted pack; its substitution is now
2646
0
          // complete.
2647
0
          CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2648
0
          // We still need to check the argument in case it was extended by
2649
0
          // deduction.
2650
0
        } else {
2651
0
          // We have already fully type-checked and converted this
2652
0
          // argument, because it was explicitly-specified. Just record the
2653
0
          // presence of this argument.
2654
0
          Builder.push_back(Deduced[I]);
2655
0
          continue;
2656
0
        }
2657
232
      }
2658
232
2659
232
      // We may have deduced this argument, so it still needs to be
2660
232
      // checked and converted.
2661
232
      if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2662
232
                                         IsDeduced, Builder)) {
2663
0
        Info.Param = makeTemplateParameter(Param);
2664
0
        // FIXME: These template arguments are temporary. Free them!
2665
0
        Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2666
0
        return Sema::TDK_SubstitutionFailure;
2667
0
      }
2668
232
2669
232
      continue;
2670
232
    }
2671
1
2672
1
    // Substitute into the default template argument, if available.
2673
1
    bool HasDefaultArg = false;
2674
1
    TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2675
1
    if (!TD) {
2676
1
      assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2677
1
             isa<VarTemplatePartialSpecializationDecl>(Template));
2678
1
      return Sema::TDK_Incomplete;
2679
1
    }
2680
0
2681
0
    TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2682
0
        TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2683
0
        HasDefaultArg);
2684
0
2685
0
    // If there was no default argument, deduction is incomplete.
2686
0
    if (DefArg.getArgument().isNull()) {
2687
0
      Info.Param = makeTemplateParameter(
2688
0
          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2689
0
      Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2690
0
      if (PartialOverloading) break;
2691
0
2692
0
      return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2693
0
                           : Sema::TDK_Incomplete;
2694
0
    }
2695
0
2696
0
    // Check whether we can actually use the default argument.
2697
0
    if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2698
0
                                TD->getSourceRange().getEnd(), 0, Builder,
2699
0
                                Sema::CTAK_Specified)) {
2700
0
      Info.Param = makeTemplateParameter(
2701
0
                         const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2702
0
      // FIXME: These template arguments are temporary. Free them!
2703
0
      Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2704
0
      return Sema::TDK_SubstitutionFailure;
2705
0
    }
2706
0
2707
0
    // If we get here, we successfully used the default template argument.
2708
0
  }
2709
229
2710
229
  
return Sema::TDK_Success228
;
2711
229
}
SemaTemplateDeduction.cpp:clang::Sema::TemplateDeductionResult ConvertDeducedTemplateArguments<clang::FunctionTemplateDecl>(clang::Sema&, clang::FunctionTemplateDecl*, bool, llvm::SmallVectorImpl<clang::DeducedTemplateArgument>&, clang::sema::TemplateDeductionInfo&, llvm::SmallVectorImpl<clang::TemplateArgument>&, clang::LocalInstantiationScope*, unsigned int, bool)
Line
Count
Source
2622
507k
    unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2623
507k
  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2624
507k
2625
1.15M
  for (unsigned I = 0, N = TemplateParams->size(); I != N; 
++I643k
) {
2626
683k
    NamedDecl *Param = TemplateParams->getParam(I);
2627
683k
2628
683k
    // C++0x [temp.arg.explicit]p3:
2629
683k
    //    A trailing template parameter pack (14.5.3) not otherwise deduced will
2630
683k
    //    be deduced to an empty sequence of template arguments.
2631
683k
    // FIXME: Where did the word "trailing" come from?
2632
683k
    if (Deduced[I].isNull() && 
Param->isTemplateParameterPack()107k
) {
2633
17.2k
      if (auto Result =
2634
8
              PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish())
2635
8
        return Result;
2636
683k
    }
2637
683k
2638
683k
    if (!Deduced[I].isNull()) {
2639
592k
      if (I < NumAlreadyConverted) {
2640
291k
        // We may have had explicitly-specified template arguments for a
2641
291k
        // template parameter pack (that may or may not have been extended
2642
291k
        // via additional deduced arguments).
2643
291k
        if (Param->isParameterPack() && 
CurrentInstantiationScope16.7k
&&
2644
291k
            
CurrentInstantiationScope->getPartiallySubstitutedPack() == Param16.7k
) {
2645
16.7k
          // Forget the partially-substituted pack; its substitution is now
2646
16.7k
          // complete.
2647
16.7k
          CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2648
16.7k
          // We still need to check the argument in case it was extended by
2649
16.7k
          // deduction.
2650
275k
        } else {
2651
275k
          // We have already fully type-checked and converted this
2652
275k
          // argument, because it was explicitly-specified. Just record the
2653
275k
          // presence of this argument.
2654
275k
          Builder.push_back(Deduced[I]);
2655
275k
          continue;
2656
275k
        }
2657
317k
      }
2658
317k
2659
317k
      // We may have deduced this argument, so it still needs to be
2660
317k
      // checked and converted.
2661
317k
      if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2662
317k
                                         IsDeduced, Builder)) {
2663
34
        Info.Param = makeTemplateParameter(Param);
2664
34
        // FIXME: These template arguments are temporary. Free them!
2665
34
        Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2666
34
        return Sema::TDK_SubstitutionFailure;
2667
34
      }
2668
317k
2669
317k
      continue;
2670
317k
    }
2671
90.5k
2672
90.5k
    // Substitute into the default template argument, if available.
2673
90.5k
    bool HasDefaultArg = false;
2674
90.5k
    TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2675
90.5k
    if (!TD) {
2676
0
      assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2677
0
             isa<VarTemplatePartialSpecializationDecl>(Template));
2678
0
      return Sema::TDK_Incomplete;
2679
0
    }
2680
90.5k
2681
90.5k
    TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2682
90.5k
        TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2683
90.5k
        HasDefaultArg);
2684
90.5k
2685
90.5k
    // If there was no default argument, deduction is incomplete.
2686
90.5k
    if (DefArg.getArgument().isNull()) {
2687
27.3k
      Info.Param = makeTemplateParameter(
2688
27.3k
          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2689
27.3k
      Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2690
27.3k
      if (PartialOverloading) 
break62
;
2691
27.2k
2692
27.2k
      return HasDefaultArg ? 
Sema::TDK_SubstitutionFailure25.8k
2693
27.2k
                           : 
Sema::TDK_Incomplete1.35k
;
2694
27.2k
    }
2695
63.2k
2696
63.2k
    // Check whether we can actually use the default argument.
2697
63.2k
    if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2698
63.2k
                                TD->getSourceRange().getEnd(), 0, Builder,
2699
63.2k
                                Sema::CTAK_Specified)) {
2700
12.4k
      Info.Param = makeTemplateParameter(
2701
12.4k
                         const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2702
12.4k
      // FIXME: These template arguments are temporary. Free them!
2703
12.4k
      Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2704
12.4k
      return Sema::TDK_SubstitutionFailure;
2705
12.4k
    }
2706
63.2k
2707
63.2k
    // If we get here, we successfully used the default template argument.
2708
63.2k
  }
2709
507k
2710
507k
  
return Sema::TDK_Success468k
;
2711
507k
}
SemaTemplateDeduction.cpp:clang::Sema::TemplateDeductionResult ConvertDeducedTemplateArguments<clang::TemplateDecl>(clang::Sema&, clang::TemplateDecl*, bool, llvm::SmallVectorImpl<clang::DeducedTemplateArgument>&, clang::sema::TemplateDeductionInfo&, llvm::SmallVectorImpl<clang::TemplateArgument>&, clang::LocalInstantiationScope*, unsigned int, bool)
Line
Count
Source
2622
158k
    unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2623
158k
  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2624
158k
2625
496k
  for (unsigned I = 0, N = TemplateParams->size(); I != N; 
++I337k
) {
2626
337k
    NamedDecl *Param = TemplateParams->getParam(I);
2627
337k
2628
337k
    // C++0x [temp.arg.explicit]p3:
2629
337k
    //    A trailing template parameter pack (14.5.3) not otherwise deduced will
2630
337k
    //    be deduced to an empty sequence of template arguments.
2631
337k
    // FIXME: Where did the word "trailing" come from?
2632
337k
    if (Deduced[I].isNull() && 
Param->isTemplateParameterPack()0
) {
2633
0
      if (auto Result =
2634
0
              PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish())
2635
0
        return Result;
2636
337k
    }
2637
337k
2638
337k
    if (!Deduced[I].isNull()) {
2639
337k
      if (I < NumAlreadyConverted) {
2640
0
        // We may have had explicitly-specified template arguments for a
2641
0
        // template parameter pack (that may or may not have been extended
2642
0
        // via additional deduced arguments).
2643
0
        if (Param->isParameterPack() && CurrentInstantiationScope &&
2644
0
            CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2645
0
          // Forget the partially-substituted pack; its substitution is now
2646
0
          // complete.
2647
0
          CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2648
0
          // We still need to check the argument in case it was extended by
2649
0
          // deduction.
2650
0
        } else {
2651
0
          // We have already fully type-checked and converted this
2652
0
          // argument, because it was explicitly-specified. Just record the
2653
0
          // presence of this argument.
2654
0
          Builder.push_back(Deduced[I]);
2655
0
          continue;
2656
0
        }
2657
337k
      }
2658
337k
2659
337k
      // We may have deduced this argument, so it still needs to be
2660
337k
      // checked and converted.
2661
337k
      if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2662
337k
                                         IsDeduced, Builder)) {
2663
3
        Info.Param = makeTemplateParameter(Param);
2664
3
        // FIXME: These template arguments are temporary. Free them!
2665
3
        Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2666
3
        return Sema::TDK_SubstitutionFailure;
2667
3
      }
2668
337k
2669
337k
      continue;
2670
337k
    }
2671
0
2672
0
    // Substitute into the default template argument, if available.
2673
0
    bool HasDefaultArg = false;
2674
0
    TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2675
0
    if (!TD) {
2676
0
      assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2677
0
             isa<VarTemplatePartialSpecializationDecl>(Template));
2678
0
      return Sema::TDK_Incomplete;
2679
0
    }
2680
0
2681
0
    TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2682
0
        TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2683
0
        HasDefaultArg);
2684
0
2685
0
    // If there was no default argument, deduction is incomplete.
2686
0
    if (DefArg.getArgument().isNull()) {
2687
0
      Info.Param = makeTemplateParameter(
2688
0
          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2689
0
      Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2690
0
      if (PartialOverloading) break;
2691
0
2692
0
      return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2693
0
                           : Sema::TDK_Incomplete;
2694
0
    }
2695
0
2696
0
    // Check whether we can actually use the default argument.
2697
0
    if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2698
0
                                TD->getSourceRange().getEnd(), 0, Builder,
2699
0
                                Sema::CTAK_Specified)) {
2700
0
      Info.Param = makeTemplateParameter(
2701
0
                         const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2702
0
      // FIXME: These template arguments are temporary. Free them!
2703
0
      Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2704
0
      return Sema::TDK_SubstitutionFailure;
2705
0
    }
2706
0
2707
0
    // If we get here, we successfully used the default template argument.
2708
0
  }
2709
158k
2710
158k
  
return Sema::TDK_Success158k
;
2711
158k
}
2712
2713
353k
static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2714
353k
  if (auto *DC = dyn_cast<DeclContext>(D))
2715
194k
    return DC;
2716
159k
  return D->getDeclContext();
2717
159k
}
2718
2719
template<typename T> struct IsPartialSpecialization {
2720
  static constexpr bool value = false;
2721
};
2722
template<>
2723
struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2724
  static constexpr bool value = true;
2725
};
2726
template<>
2727
struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2728
  static constexpr bool value = true;
2729
};
2730
2731
template<typename TemplateDeclT>
2732
static Sema::TemplateDeductionResult
2733
CheckDeducedArgumentConstraints(Sema& S, TemplateDeclT *Template,
2734
                                ArrayRef<TemplateArgument> DeducedArgs,
2735
325k
                                TemplateDeductionInfo& Info) {
2736
325k
  llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
2737
325k
  Template->getAssociatedConstraints(AssociatedConstraints);
2738
325k
  if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints,
2739
325k
                                    DeducedArgs, Info.getLocation(),
2740
325k
                                    Info.AssociatedConstraintsSatisfaction) ||
2741
325k
      
!Info.AssociatedConstraintsSatisfaction.IsSatisfied325k
) {
2742
14
    Info.reset(TemplateArgumentList::CreateCopy(S.Context, DeducedArgs));
2743
14
    return Sema::TDK_ConstraintsNotSatisfied;
2744
14
  }
2745
325k
  return Sema::TDK_Success;
2746
325k
}
SemaTemplateDeduction.cpp:clang::Sema::TemplateDeductionResult CheckDeducedArgumentConstraints<clang::ClassTemplatePartialSpecializationDecl>(clang::Sema&, clang::ClassTemplatePartialSpecializationDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&)
Line
Count
Source
2735
166k
                                TemplateDeductionInfo& Info) {
2736
166k
  llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
2737
166k
  Template->getAssociatedConstraints(AssociatedConstraints);
2738
166k
  if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints,
2739
166k
                                    DeducedArgs, Info.getLocation(),
2740
166k
                                    Info.AssociatedConstraintsSatisfaction) ||
2741
166k
      
!Info.AssociatedConstraintsSatisfaction.IsSatisfied166k
) {
2742
7
    Info.reset(TemplateArgumentList::CreateCopy(S.Context, DeducedArgs));
2743
7
    return Sema::TDK_ConstraintsNotSatisfied;
2744
7
  }
2745
166k
  return Sema::TDK_Success;
2746
166k
}
SemaTemplateDeduction.cpp:clang::Sema::TemplateDeductionResult CheckDeducedArgumentConstraints<clang::VarTemplatePartialSpecializationDecl>(clang::Sema&, clang::VarTemplatePartialSpecializationDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&)
Line
Count
Source
2735
224
                                TemplateDeductionInfo& Info) {
2736
224
  llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
2737
224
  Template->getAssociatedConstraints(AssociatedConstraints);
2738
224
  if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints,
2739
224
                                    DeducedArgs, Info.getLocation(),
2740
224
                                    Info.AssociatedConstraintsSatisfaction) ||
2741
224
      
!Info.AssociatedConstraintsSatisfaction.IsSatisfied222
) {
2742
7
    Info.reset(TemplateArgumentList::CreateCopy(S.Context, DeducedArgs));
2743
7
    return Sema::TDK_ConstraintsNotSatisfied;
2744
7
  }
2745
217
  return Sema::TDK_Success;
2746
217
}
SemaTemplateDeduction.cpp:clang::Sema::TemplateDeductionResult CheckDeducedArgumentConstraints<clang::TemplateDecl>(clang::Sema&, clang::TemplateDecl*, llvm::ArrayRef<clang::TemplateArgument>, clang::sema::TemplateDeductionInfo&)
Line
Count
Source
2735
158k
                                TemplateDeductionInfo& Info) {
2736
158k
  llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
2737
158k
  Template->getAssociatedConstraints(AssociatedConstraints);
2738
158k
  if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints,
2739
158k
                                    DeducedArgs, Info.getLocation(),
2740
158k
                                    Info.AssociatedConstraintsSatisfaction) ||
2741
158k
      !Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
2742
0
    Info.reset(TemplateArgumentList::CreateCopy(S.Context, DeducedArgs));
2743
0
    return Sema::TDK_ConstraintsNotSatisfied;
2744
0
  }
2745
158k
  return Sema::TDK_Success;
2746
158k
}
2747
2748
/// Complete template argument deduction for a partial specialization.
2749
template <typename T>
2750
static std::enable_if_t<IsPartialSpecialization<T>::value,
2751
                        Sema::TemplateDeductionResult>
2752
FinishTemplateArgumentDeduction(
2753
    Sema &S, T *Partial, bool IsPartialOrdering,
2754
    const TemplateArgumentList &TemplateArgs,
2755
    SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2756
195k
    TemplateDeductionInfo &Info) {
2757
195k
  // Unevaluated SFINAE context.
2758
195k
  EnterExpressionEvaluationContext Unevaluated(
2759
195k
      S, Sema::ExpressionEvaluationContext::Unevaluated);
2760
195k
  Sema::SFINAETrap Trap(S);
2761
195k
2762
195k
  Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
2763
195k
2764
195k
  // C++ [temp.deduct.type]p2:
2765
195k
  //   [...] or if any template argument remains neither deduced nor
2766
195k
  //   explicitly specified, template argument deduction fails.
2767
195k
  SmallVector<TemplateArgument, 4> Builder;
2768
195k
  if (auto Result = ConvertDeducedTemplateArguments(
2769
7.16k
          S, Partial, IsPartialOrdering, Deduced, Info, Builder))
2770
7.16k
    return Result;
2771
187k
2772
187k
  // Form the template argument list from the deduced template arguments.
2773
187k
  TemplateArgumentList *DeducedArgumentList
2774
187k
    = TemplateArgumentList::CreateCopy(S.Context, Builder);
2775
187k
2776
187k
  Info.reset(DeducedArgumentList);
2777
187k
2778
187k
  // Substitute the deduced template arguments into the template
2779
187k
  // arguments of the class template partial specialization, and
2780
187k
  // verify that the instantiated template arguments are both valid
2781
187k
  // and are equivalent to the template arguments originally provided
2782
187k
  // to the class template.
2783
187k
  LocalInstantiationScope InstScope(S);
2784
187k
  auto *Template = Partial->getSpecializedTemplate();
2785
187k
  const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2786
187k
      Partial->getTemplateArgsAsWritten();
2787
187k
  const TemplateArgumentLoc *PartialTemplateArgs =
2788
187k
      PartialTemplArgInfo->getTemplateArgs();
2789
187k
2790
187k
  TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2791
187k
                                    PartialTemplArgInfo->RAngleLoc);
2792
187k
2793
187k
  if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2794
187k
              InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2795
10.3k
    unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2796
10.3k
    if (ParamIdx >= Partial->getTemplateParameters()->size())
2797
10.3k
      ParamIdx = Partial->getTemplateParameters()->size() - 1;
2798
10.3k
2799
10.3k
    Decl *Param = const_cast<NamedDecl *>(
2800
10.3k
        Partial->getTemplateParameters()->getParam(ParamIdx));
2801
10.3k
    Info.Param = makeTemplateParameter(Param);
2802
10.3k
    Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2803
10.3k
    return Sema::TDK_SubstitutionFailure;
2804
10.3k
  }
2805
177k
2806
177k
  bool ConstraintsNotSatisfied;
2807
177k
  SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2808
177k
  if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2809
177k
                                  false, ConvertedInstArgs,
2810
177k
                                  /*UpdateArgsWithConversions=*/true,
2811
177k
                                  &ConstraintsNotSatisfied))
2812
2
    return ConstraintsNotSatisfied ? 
Sema::TDK_ConstraintsNotSatisfied0
:
2813
2
                                     Sema::TDK_SubstitutionFailure;
2814
177k
2815
177k
  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2816
518k
  for (unsigned I = 0, E = TemplateParams->size(); I != E; 
++I340k
) {
2817
351k
    TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2818
351k
    if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2819
10.8k
      Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2820
10.8k
      Info.FirstArg = TemplateArgs[I];
2821
10.8k
      Info.SecondArg = InstArg;
2822
10.8k
      return Sema::TDK_NonDeducedMismatch;
2823
10.8k
    }
2824
351k
  }
2825
177k
2826
177k
  
if (166k
Trap.hasErrorOccurred()166k
)
2827
0
    return Sema::TDK_SubstitutionFailure;
2828
166k
2829
166k
  if (auto Result = CheckDeducedArgumentConstraints(S, Partial, Builder, Info))
2830
14
    return Result;
2831
166k
2832
166k
  return Sema::TDK_Success;
2833
166k
}
SemaTemplateDeduction.cpp:std::__1::enable_if<IsPartialSpecialization<clang::ClassTemplatePartialSpecializationDecl>::value, clang::Sema::TemplateDeductionResult>::type FinishTemplateArgumentDeduction<clang::ClassTemplatePartialSpecializationDecl>(clang::Sema&, clang::ClassTemplatePartialSpecializationDecl*, bool, clang::TemplateArgumentList const&, llvm::SmallVectorImpl<clang::DeducedTemplateArgument>&, clang::sema::TemplateDeductionInfo&)
Line
Count
Source
2756
194k
    TemplateDeductionInfo &Info) {
2757
194k
  // Unevaluated SFINAE context.
2758
194k
  EnterExpressionEvaluationContext Unevaluated(
2759
194k
      S, Sema::ExpressionEvaluationContext::Unevaluated);
2760
194k
  Sema::SFINAETrap Trap(S);
2761
194k
2762
194k
  Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
2763
194k
2764
194k
  // C++ [temp.deduct.type]p2:
2765
194k
  //   [...] or if any template argument remains neither deduced nor
2766
194k
  //   explicitly specified, template argument deduction fails.
2767
194k
  SmallVector<TemplateArgument, 4> Builder;
2768
194k
  if (auto Result = ConvertDeducedTemplateArguments(
2769
7.15k
          S, Partial, IsPartialOrdering, Deduced, Info, Builder))
2770
7.15k
    return Result;
2771
187k
2772
187k
  // Form the template argument list from the deduced template arguments.
2773
187k
  TemplateArgumentList *DeducedArgumentList
2774
187k
    = TemplateArgumentList::CreateCopy(S.Context, Builder);
2775
187k
2776
187k
  Info.reset(DeducedArgumentList);
2777
187k
2778
187k
  // Substitute the deduced template arguments into the template
2779
187k
  // arguments of the class template partial specialization, and
2780
187k
  // verify that the instantiated template arguments are both valid
2781
187k
  // and are equivalent to the template arguments originally provided
2782
187k
  // to the class template.
2783
187k
  LocalInstantiationScope InstScope(S);
2784
187k
  auto *Template = Partial->getSpecializedTemplate();
2785
187k
  const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2786
187k
      Partial->getTemplateArgsAsWritten();
2787
187k
  const TemplateArgumentLoc *PartialTemplateArgs =
2788
187k
      PartialTemplArgInfo->getTemplateArgs();
2789
187k
2790
187k
  TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2791
187k
                                    PartialTemplArgInfo->RAngleLoc);
2792
187k
2793
187k
  if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2794
187k
              InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2795
10.3k
    unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2796
10.3k
    if (ParamIdx >= Partial->getTemplateParameters()->size())
2797
10.3k
      ParamIdx = Partial->getTemplateParameters()->size() - 1;
2798
10.3k
2799
10.3k
    Decl *Param = const_cast<NamedDecl *>(
2800
10.3k
        Partial->getTemplateParameters()->getParam(ParamIdx));
2801
10.3k
    Info.Param = makeTemplateParameter(Param);
2802
10.3k
    Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2803
10.3k
    return Sema::TDK_SubstitutionFailure;
2804
10.3k
  }
2805
177k
2806
177k
  bool ConstraintsNotSatisfied;
2807
177k
  SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2808
177k
  if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2809
177k
                                  false, ConvertedInstArgs,
2810
177k
                                  /*UpdateArgsWithConversions=*/true,
2811
177k
                                  &ConstraintsNotSatisfied))
2812
2
    return ConstraintsNotSatisfied ? 
Sema::TDK_ConstraintsNotSatisfied0
:
2813
2
                                     Sema::TDK_SubstitutionFailure;
2814
177k
2815
177k
  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2816
517k
  for (unsigned I = 0, E = TemplateParams->size(); I != E; 
++I340k
) {
2817
351k
    TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2818
351k
    if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2819
10.8k
      Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2820
10.8k
      Info.FirstArg = TemplateArgs[I];
2821
10.8k
      Info.SecondArg = InstArg;
2822
10.8k
      return Sema::TDK_NonDeducedMismatch;
2823
10.8k
    }
2824
351k
  }
2825
177k
2826
177k
  
if (166k
Trap.hasErrorOccurred()166k
)
2827
0
    return Sema::TDK_SubstitutionFailure;
2828
166k
2829
166k
  if (auto Result = CheckDeducedArgumentConstraints(S, Partial, Builder, Info))
2830
7
    return Result;
2831
166k
2832
166k
  return Sema::TDK_Success;
2833
166k
}
SemaTemplateDeduction.cpp:std::__1::enable_if<IsPartialSpecialization<clang::VarTemplatePartialSpecializationDecl>::value, clang::Sema::TemplateDeductionResult>::type FinishTemplateArgumentDeduction<clang::VarTemplatePartialSpecializationDecl>(clang::Sema&, clang::VarTemplatePartialSpecializationDecl*, bool, clang::TemplateArgumentList const&, llvm::SmallVectorImpl<clang::DeducedTemplateArgument>&, clang::sema::TemplateDeductionInfo&)
Line
Count
Source
2756
229
    TemplateDeductionInfo &Info) {
2757
229
  // Unevaluated SFINAE context.
2758
229
  EnterExpressionEvaluationContext Unevaluated(
2759
229
      S, Sema::ExpressionEvaluationContext::Unevaluated);
2760
229
  Sema::SFINAETrap Trap(S);
2761
229
2762
229
  Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
2763
229
2764
229
  // C++ [temp.deduct.type]p2:
2765
229
  //   [...] or if any template argument remains neither deduced nor
2766
229
  //   explicitly specified, template argument deduction fails.
2767
229
  SmallVector<TemplateArgument, 4> Builder;
2768
229
  if (auto Result = ConvertDeducedTemplateArguments(
2769
1
          S, Partial, IsPartialOrdering, Deduced, Info, Builder))
2770
1
    return Result;
2771
228
2772
228
  // Form the template argument list from the deduced template arguments.
2773
228
  TemplateArgumentList *DeducedArgumentList
2774
228
    = TemplateArgumentList::CreateCopy(S.Context, Builder);
2775
228
2776
228
  Info.reset(DeducedArgumentList);
2777
228
2778
228
  // Substitute the deduced template arguments into the template
2779
228
  // arguments of the class template partial specialization, and
2780
228
  // verify that the instantiated template arguments are both valid
2781
228
  // and are equivalent to the template arguments originally provided
2782
228
  // to the class template.
2783
228
  LocalInstantiationScope InstScope(S);
2784
228
  auto *Template = Partial->getSpecializedTemplate();
2785
228
  const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2786
228
      Partial->getTemplateArgsAsWritten();
2787
228
  const TemplateArgumentLoc *PartialTemplateArgs =
2788
228
      PartialTemplArgInfo->getTemplateArgs();
2789
228
2790
228
  TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2791
228
                                    PartialTemplArgInfo->RAngleLoc);
2792
228
2793
228
  if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2794
228
              InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2795
2
    unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2796
2
    if (ParamIdx >= Partial->getTemplateParameters()->size())
2797
2
      ParamIdx = Partial->getTemplateParameters()->size() - 1;
2798
2
2799
2
    Decl *Param = const_cast<NamedDecl *>(
2800
2
        Partial->getTemplateParameters()->getParam(ParamIdx));
2801
2
    Info.Param = makeTemplateParameter(Param);
2802
2
    Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2803
2
    return Sema::TDK_SubstitutionFailure;
2804
2
  }
2805
226
2806
226
  bool ConstraintsNotSatisfied;
2807
226
  SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2808
226
  if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2809
226
                                  false, ConvertedInstArgs,
2810
226
                                  /*UpdateArgsWithConversions=*/true,
2811
226
                                  &ConstraintsNotSatisfied))
2812
0
    return ConstraintsNotSatisfied ? Sema::TDK_ConstraintsNotSatisfied :
2813
0
                                     Sema::TDK_SubstitutionFailure;
2814
226
2815
226
  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2816
576
  for (unsigned I = 0, E = TemplateParams->size(); I != E; 
++I350
) {
2817
352
    TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2818
352
    if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2819
2
      Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2820
2
      Info.FirstArg = TemplateArgs[I];
2821
2
      Info.SecondArg = InstArg;
2822
2
      return Sema::TDK_NonDeducedMismatch;
2823
2
    }
2824
352
  }
2825
226
2826
226
  
if (224
Trap.hasErrorOccurred()224
)
2827
0
    return Sema::TDK_SubstitutionFailure;
2828
224
2829
224
  if (auto Result = CheckDeducedArgumentConstraints(S, Partial, Builder, Info))
2830
7
    return Result;
2831
217
2832
217
  return Sema::TDK_Success;
2833
217
}
2834
2835
/// Complete template argument deduction for a class or variable template,
2836
/// when partial ordering against a partial specialization.
2837
// FIXME: Factor out duplication with partial specialization version above.
2838
static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2839
    Sema &S, TemplateDecl *Template, bool PartialOrdering,
2840
    const TemplateArgumentList &TemplateArgs,
2841
    SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2842
158k
    TemplateDeductionInfo &Info) {
2843
158k
  // Unevaluated SFINAE context.
2844
158k
  EnterExpressionEvaluationContext Unevaluated(
2845
158k
      S, Sema::ExpressionEvaluationContext::Unevaluated);
2846
158k
  Sema::SFINAETrap Trap(S);
2847
158k
2848
158k
  Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2849
158k
2850
158k
  // C++ [temp.deduct.type]p2:
2851
158k
  //   [...] or if any template argument remains neither deduced nor
2852
158k
  //   explicitly specified, template argument deduction fails.
2853
158k
  SmallVector<TemplateArgument, 4> Builder;
2854
158k
  if (auto Result = ConvertDeducedTemplateArguments(
2855
3
          S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2856
3
    return Result;
2857
158k
2858
158k
  // Check that we produced the correct argument list.
2859
158k
  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2860
496k
  for (unsigned I = 0, E = TemplateParams->size(); I != E; 
++I337k
) {
2861
337k
    TemplateArgument InstArg = Builder[I];
2862
337k
    if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2863
337k
                           /*PackExpansionMatchesPack*/true)) {
2864
0
      Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2865
0
      Info.FirstArg = TemplateArgs[I];
2866
0
      Info.SecondArg = InstArg;
2867
0
      return Sema::TDK_NonDeducedMismatch;
2868
0
    }
2869
337k
  }
2870
158k
2871
158k
  if (Trap.hasErrorOccurred())
2872
0
    return Sema::TDK_SubstitutionFailure;
2873
158k
2874
158k
  if (auto Result = CheckDeducedArgumentConstraints(S, Template, Builder,
2875
0
                                                    Info))
2876
0
    return Result;
2877
158k
2878
158k
  return Sema::TDK_Success;
2879
158k
}
2880
2881
/// Perform template argument deduction to determine whether
2882
/// the given template arguments match the given class template
2883
/// partial specialization per C++ [temp.class.spec.match].
2884
Sema::TemplateDeductionResult
2885
Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
2886
                              const TemplateArgumentList &TemplateArgs,
2887
542k
                              TemplateDeductionInfo &Info) {
2888
542k
  if (Partial->isInvalidDecl())
2889
0
    return TDK_Invalid;
2890
542k
2891
542k
  // C++ [temp.class.spec.match]p2:
2892
542k
  //   A partial specialization matches a given actual template
2893
542k
  //   argument list if the template arguments of the partial
2894
542k
  //   specialization can be deduced from the actual template argument
2895
542k
  //   list (14.8.2).
2896
542k
2897
542k
  // Unevaluated SFINAE context.
2898
542k
  EnterExpressionEvaluationContext Unevaluated(
2899
542k
      *this, Sema::ExpressionEvaluationContext::Unevaluated);
2900
542k
  SFINAETrap Trap(*this);
2901
542k
2902
542k
  SmallVector<DeducedTemplateArgument, 4> Deduced;
2903
542k
  Deduced.resize(Partial->getTemplateParameters()->size());
2904
542k
  if (TemplateDeductionResult Result
2905
359k
        = ::DeduceTemplateArguments(*this,
2906
359k
                                    Partial->getTemplateParameters(),
2907
359k
                                    Partial->getTemplateArgs(),
2908
359k
                                    TemplateArgs, Info, Deduced))
2909
359k
    return Result;
2910
183k
2911
183k
  SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2912
183k
  InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2913
183k
                             Info);
2914
183k
  if (Inst.isInvalid())
2915
0
    return TDK_InstantiationDepth;
2916
183k
2917
183k
  if (Trap.hasErrorOccurred())
2918
0
    return Sema::TDK_SubstitutionFailure;
2919
183k
2920
183k
  return ::FinishTemplateArgumentDeduction(
2921
183k
      *this, Partial, /*IsPartialOrdering=*/false, TemplateArgs, Deduced, Info);
2922
183k
}
2923
2924
/// Perform template argument deduction to determine whether
2925
/// the given template arguments match the given variable template
2926
/// partial specialization per C++ [temp.class.spec.match].
2927
Sema::TemplateDeductionResult
2928
Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2929
                              const TemplateArgumentList &TemplateArgs,
2930
338
                              TemplateDeductionInfo &Info) {
2931
338
  if (Partial->isInvalidDecl())
2932
0
    return TDK_Invalid;
2933
338
2934
338
  // C++ [temp.class.spec.match]p2:
2935
338
  //   A partial specialization matches a given actual template
2936
338
  //   argument list if the template arguments of the partial
2937
338
  //   specialization can be deduced from the actual template argument
2938
338
  //   list (14.8.2).
2939
338
2940
338
  // Unevaluated SFINAE context.
2941
338
  EnterExpressionEvaluationContext Unevaluated(
2942
338
      *this, Sema::ExpressionEvaluationContext::Unevaluated);
2943
338
  SFINAETrap Trap(*this);
2944
338
2945
338
  SmallVector<DeducedTemplateArgument, 4> Deduced;
2946
338
  Deduced.resize(Partial->getTemplateParameters()->size());
2947
338
  if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2948
123
          *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2949
123
          TemplateArgs, Info, Deduced))
2950
123
    return Result;
2951
215
2952
215
  SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2953
215
  InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2954
215
                             Info);
2955
215
  if (Inst.isInvalid())
2956
0
    return TDK_InstantiationDepth;
2957
215
2958
215
  if (Trap.hasErrorOccurred())
2959
0
    return Sema::TDK_SubstitutionFailure;
2960
215
2961
215
  return ::FinishTemplateArgumentDeduction(
2962
215
      *this, Partial, /*IsPartialOrdering=*/false, TemplateArgs, Deduced, Info);
2963
215
}
2964
2965
/// Determine whether the given type T is a simple-template-id type.
2966
857k
static bool isSimpleTemplateIdType(QualType T) {
2967
857k
  if (const TemplateSpecializationType *Spec
2968
564k
        = T->getAs<TemplateSpecializationType>())
2969
564k
    return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
2970
293k
2971
293k
  // C++17 [temp.local]p2:
2972
293k
  //   the injected-class-name [...] is equivalent to the template-name followed
2973
293k
  //   by the template-arguments of the class template specialization or partial
2974
293k
  //   specialization enclosed in <>
2975
293k
  // ... which means it's equivalent to a simple-template-id.
2976
293k
  //
2977
293k
  // This only arises during class template argument deduction for a copy
2978
293k
  // deduction candidate, where it permits slicing.
2979
293k
  if (T->getAs<InjectedClassNameType>())
2980
141
    return true;
2981
293k
2982
293k
  return false;
2983
293k
}
2984
2985
/// Substitute the explicitly-provided template arguments into the
2986
/// given function template according to C++ [temp.arg.explicit].
2987
///
2988
/// \param FunctionTemplate the function template into which the explicit
2989
/// template arguments will be substituted.
2990
///
2991
/// \param ExplicitTemplateArgs the explicitly-specified template
2992
/// arguments.
2993
///
2994
/// \param Deduced the deduced template arguments, which will be populated
2995
/// with the converted and checked explicit template arguments.
2996
///
2997
/// \param ParamTypes will be populated with the instantiated function
2998
/// parameters.
2999
///
3000
/// \param FunctionType if non-NULL, the result type of the function template
3001
/// will also be instantiated and the pointed-to value will be updated with
3002
/// the instantiated function type.
3003
///
3004
/// \param Info if substitution fails for any reason, this object will be
3005
/// populated with more information about the failure.
3006
///
3007
/// \returns TDK_Success if substitution was successful, or some failure
3008
/// condition.
3009
Sema::TemplateDeductionResult
3010
Sema::SubstituteExplicitTemplateArguments(
3011
                                      FunctionTemplateDecl *FunctionTemplate,
3012
                               TemplateArgumentListInfo &ExplicitTemplateArgs,
3013
                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3014
                                 SmallVectorImpl<QualType> &ParamTypes,
3015
                                          QualType *FunctionType,
3016
302k
                                          TemplateDeductionInfo &Info) {
3017
302k
  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3018
302k
  TemplateParameterList *TemplateParams
3019
302k
    = FunctionTemplate->getTemplateParameters();
3020
302k
3021
302k
  if (ExplicitTemplateArgs.size() == 0) {
3022
30.3k
    // No arguments to substitute; just copy over the parameter types and
3023
30.3k
    // fill in the function type.
3024
30.3k
    for (auto P : Function->parameters())
3025
56.1k
      ParamTypes.push_back(P->getType());
3026
30.3k
3027
30.3k
    if (FunctionType)
3028
29.7k
      *FunctionType = Function->getType();
3029
30.3k
    return TDK_Success;
3030
30.3k
  }
3031
272k
3032
272k
  // Unevaluated SFINAE context.
3033
272k
  EnterExpressionEvaluationContext Unevaluated(
3034
272k
      *this, Sema::ExpressionEvaluationContext::Unevaluated);
3035
272k
  SFINAETrap Trap(*this);
3036
272k
3037
272k
  // C++ [temp.arg.explicit]p3:
3038
272k
  //   Template arguments that are present shall be specified in the
3039
272k
  //   declaration order of their corresponding template-parameters. The
3040
272k
  //   template argument list shall not specify more template-arguments than
3041
272k
  //   there are corresponding template-parameters.
3042
272k
  SmallVector<TemplateArgument, 4> Builder;
3043
272k
3044
272k
  // Enter a new template instantiation context where we check the
3045
272k
  // explicitly-specified template arguments against this function template,
3046
272k
  // and then substitute them into the function parameter types.
3047
272k
  SmallVector<TemplateArgument, 4> DeducedArgs;
3048
272k
  InstantiatingTemplate Inst(
3049
272k
      *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3050
272k
      CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
3051
272k
  if (Inst.isInvalid())
3052
0
    return TDK_InstantiationDepth;
3053
272k
3054
272k
  if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
3055
272k
                                ExplicitTemplateArgs, true, Builder, false) ||
3056
272k
      
Trap.hasErrorOccurred()270k
) {
3057
1.69k
    unsigned Index = Builder.size();
3058
1.69k
    if (Index >= TemplateParams->size())
3059
843
      return TDK_SubstitutionFailure;
3060
856
    Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3061
856
    return TDK_InvalidExplicitArguments;
3062
856
  }
3063
270k
3064
270k
  // Form the template argument list from the explicitly-specified
3065
270k
  // template arguments.
3066
270k
  TemplateArgumentList *ExplicitArgumentList
3067
270k
    = TemplateArgumentList::CreateCopy(Context, Builder);
3068
270k
  Info.setExplicitArgs(ExplicitArgumentList);
3069
270k
3070
270k
  // Template argument deduction and the final substitution should be
3071
270k
  // done in the context of the templated declaration.  Explicit
3072
270k
  // argument substitution, on the other hand, needs to happen in the
3073
270k
  // calling context.
3074
270k
  ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3075
270k
3076
270k
  // If we deduced template arguments for a template parameter pack,
3077
270k
  // note that the template argument pack is partially substituted and record
3078
270k
  // the explicit template arguments. They'll be used as part of deduction
3079
270k
  // for this template parameter pack.
3080
270k
  unsigned PartiallySubstitutedPackIndex = -1u;
3081
270k
  if (!Builder.empty()) {
3082
270k
    const TemplateArgument &Arg = Builder.back();
3083
270k
    if (Arg.getKind() == TemplateArgument::Pack) {
3084
16.7k
      auto *Param = TemplateParams->getParam(Builder.size() - 1);
3085
16.7k
      // If this is a fully-saturated fixed-size pack, it should be
3086
16.7k
      // fully-substituted, not partially-substituted.
3087
16.7k
      Optional<unsigned> Expansions = getExpandedPackSize(Param);
3088
16.7k
      if (!Expansions || 
Arg.pack_size() < *Expansions10
) {
3089
16.7k
        PartiallySubstitutedPackIndex = Builder.size() - 1;
3090
16.7k
        CurrentInstantiationScope->SetPartiallySubstitutedPack(
3091
16.7k
            Param, Arg.pack_begin(), Arg.pack_size());
3092
16.7k
      }
3093
16.7k
    }
3094
270k
  }
3095
270k
3096
270k
  const FunctionProtoType *Proto
3097
270k
    = Function->getType()->getAs<FunctionProtoType>();
3098
270k
  assert(Proto && "Function template does not have a prototype?");
3099
270k
3100
270k
  // Isolate our substituted parameters from our caller.
3101
270k
  LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3102
270k
3103
270k
  ExtParameterInfoBuilder ExtParamInfos;
3104
270k
3105
270k
  // Instantiate the types of each of the function parameters given the
3106
270k
  // explicitly-specified template arguments. If the function has a trailing
3107
270k
  // return type, substitute it after the arguments to ensure we substitute
3108
270k
  // in lexical order.
3109
270k
  if (Proto->hasTrailingReturn()) {
3110
3.63k
    if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3111
3.63k
                       Proto->getExtParameterInfosOrNull(),
3112
3.63k
                       MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3113
3.63k
                       ParamTypes, /*params*/ nullptr, ExtParamInfos))
3114
1
      return TDK_SubstitutionFailure;
3115
270k
  }
3116
270k
3117
270k
  // Instantiate the return type.
3118
270k
  QualType ResultType;
3119
270k
  {
3120
270k
    // C++11 [expr.prim.general]p3:
3121
270k
    //   If a declaration declares a member function or member function
3122
270k
    //   template of a class X, the expression this is a prvalue of type
3123
270k
    //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3124
270k
    //   and the end of the function-definition, member-declarator, or
3125
270k
    //   declarator.
3126
270k
    Qualifiers ThisTypeQuals;
3127
270k
    CXXRecordDecl *ThisContext = nullptr;
3128
270k
    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3129
79.8k
      ThisContext = Method->getParent();
3130
79.8k
      ThisTypeQuals = Method->getMethodQualifiers();
3131
79.8k
    }
3132
270k
3133
270k
    CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3134
270k
                               getLangOpts().CPlusPlus11);
3135
270k
3136
270k
    ResultType =
3137
270k
        SubstType(Proto->getReturnType(),
3138
270k
                  MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3139
270k
                  Function->getTypeSpecStartLoc(), Function->getDeclName());
3140
270k
    if (ResultType.isNull() || 
Trap.hasErrorOccurred()269k
)
3141
818
      return TDK_SubstitutionFailure;
3142
269k
    // CUDA: Kernel function must have 'void' return type.
3143
269k
    if (getLangOpts().CUDA)
3144
179
      if (Function->hasAttr<CUDAGlobalAttr>() && 
!ResultType->isVoidType()36
) {
3145
1
        Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3146
1
            << Function->getType() << Function->getSourceRange();
3147
1
        return TDK_SubstitutionFailure;
3148
1
      }
3149
269k
  }
3150
269k
3151
269k
  // Instantiate the types of each of the function parameters given the
3152
269k
  // explicitly-specified template arguments if we didn't do so earlier.
3153
269k
  if (!Proto->hasTrailingReturn() &&
3154
269k
      SubstParmTypes(Function->getLocation(), Function->parameters(),
3155
266k
                     Proto->getExtParameterInfosOrNull(),
3156
266k
                     MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3157
266k
                     ParamTypes, /*params*/ nullptr, ExtParamInfos))
3158
402
    return TDK_SubstitutionFailure;
3159
269k
3160
269k
  if (FunctionType) {
3161
17.2k
    auto EPI = Proto->getExtProtoInfo();
3162
17.2k
    EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3163
17.2k
3164
17.2k
    // In C++1z onwards, exception specifications are part of the function type,
3165
17.2k
    // so substitution into the type must also substitute into the exception
3166
17.2k
    // specification.
3167
17.2k
    SmallVector<QualType, 4> ExceptionStorage;
3168
17.2k
    if (getLangOpts().CPlusPlus17 &&
3169
17.2k
        SubstExceptionSpec(
3170
790
            Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
3171
790
            MultiLevelTemplateArgumentList(*ExplicitArgumentList)))
3172
2
      return TDK_SubstitutionFailure;
3173
17.2k
3174
17.2k
    *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3175
17.2k
                                      Function->getLocation(),
3176
17.2k
                                      Function->getDeclName(),
3177
17.2k
                                      EPI);
3178
17.2k
    if (FunctionType->isNull() || Trap.hasErrorOccurred())
3179
1
      return TDK_SubstitutionFailure;
3180
269k
  }
3181
269k
3182
269k
  // C++ [temp.arg.explicit]p2:
3183
269k
  //   Trailing template arguments that can be deduced (14.8.2) may be
3184
269k
  //   omitted from the list of explicit template-arguments. If all of the
3185
269k
  //   template arguments can be deduced, they may all be omitted; in this
3186
269k
  //   case, the empty template argument list <> itself may also be omitted.
3187
269k
  //
3188
269k
  // Take all of the explicitly-specified arguments and put them into
3189
269k
  // the set of deduced template arguments. The partially-substituted
3190
269k
  // parameter pack, however, will be set to NULL since the deduction
3191
269k
  // mechanism handles the partially-substituted argument pack directly.
3192
269k
  Deduced.reserve(TemplateParams->size());
3193
571k
  for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; 
++I302k
) {
3194
302k
    const TemplateArgument &Arg = ExplicitArgumentList->get(I);
3195
302k
    if (I == PartiallySubstitutedPackIndex)
3196
16.7k
      Deduced.push_back(DeducedTemplateArgument());
3197
285k
    else
3198
285k
      Deduced.push_back(Arg);
3199
302k
  }
3200
269k
3201
269k
  return TDK_Success;
3202
269k
}
3203
3204
/// Check whether the deduced argument type for a call to a function
3205
/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3206
static Sema::TemplateDeductionResult
3207
CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
3208
                              Sema::OriginalCallArg OriginalArg,
3209
196k
                              QualType DeducedA) {
3210
196k
  ASTContext &Context = S.Context;
3211
196k
3212
196k
  auto Failed = [&]() -> Sema::TemplateDeductionResult {
3213
1.02k
    Info.FirstArg = TemplateArgument(DeducedA);
3214
1.02k
    Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3215
1.02k
    Info.CallArgIndex = OriginalArg.ArgIdx;
3216
1.02k
    return OriginalArg.DecomposedParam ? 
Sema::TDK_DeducedMismatchNested1
3217
1.02k
                                       : 
Sema::TDK_DeducedMismatch1.02k
;
3218
1.02k
  };
3219
196k
3220
196k
  QualType A = OriginalArg.OriginalArgType;
3221
196k
  QualType OriginalParamType = OriginalArg.OriginalParamType;
3222
196k
3223
196k
  // Check for type equality (top-level cv-qualifiers are ignored).
3224
196k
  if (Context.hasSameUnqualifiedType(A, DeducedA))
3225
102k
    return Sema::TDK_Success;
3226
93.5k
3227
93.5k
  // Strip off references on the argument types; they aren't needed for
3228
93.5k
  // the following checks.
3229
93.5k
  if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3230
89.6k
    DeducedA = DeducedARef->getPointeeType();
3231
93.5k
  if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3232
0
    A = ARef->getPointeeType();
3233
93.5k
3234
93.5k
  // C++ [temp.deduct.call]p4:
3235
93.5k
  //   [...] However, there are three cases that allow a difference:
3236
93.5k
  //     - If the original P is a reference type, the deduced A (i.e., the
3237
93.5k
  //       type referred to by the reference) can be more cv-qualified than
3238
93.5k
  //       the transformed A.
3239
93.5k
  if (const ReferenceType *OriginalParamRef
3240
89.6k
      = OriginalParamType->getAs<ReferenceType>()) {
3241
89.6k
    // We don't want to keep the reference around any more.
3242
89.6k
    OriginalParamType = OriginalParamRef->getPointeeType();
3243
89.6k
3244
89.6k
    // FIXME: Resolve core issue (no number yet): if the original P is a
3245
89.6k
    // reference type and the transformed A is function type "noexcept F",
3246
89.6k
    // the deduced A can be F.
3247
89.6k
    QualType Tmp;
3248
89.6k
    if (A->isFunctionType() && 
S.IsFunctionConversion(A, DeducedA, Tmp)52
)
3249
1
      return Sema::TDK_Success;
3250
89.6k
3251
89.6k
    Qualifiers AQuals = A.getQualifiers();
3252
89.6k
    Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3253
89.6k
3254
89.6k
    // Under Objective-C++ ARC, the deduced type may have implicitly
3255
89.6k
    // been given strong or (when dealing with a const reference)
3256
89.6k
    // unsafe_unretained lifetime. If so, update the original
3257
89.6k
    // qualifiers to include this lifetime.
3258
89.6k
    if (S.getLangOpts().ObjCAutoRefCount &&
3259
89.6k
        
(86
(86
DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong86
&&
3260
86
          
AQuals.getObjCLifetime() == Qualifiers::OCL_None20
) ||
3261
86
         
(85
DeducedAQuals.hasConst()85
&&
3262
85
          
DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone16
))) {
3263
6
      AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3264
6
    }
3265
89.6k
3266
89.6k
    if (AQuals == DeducedAQuals) {
3267
53.1k
      // Qualifiers match; there's nothing to do.
3268
53.1k
    } else 
if (36.5k
!DeducedAQuals.compatiblyIncludes(AQuals)36.5k
) {
3269
991
      return Failed();
3270
35.5k
    } else {
3271
35.5k
      // Qualifiers are compatible, so have the argument type adopt the
3272
35.5k
      // deduced argument type's qualifiers as if we had performed the
3273
35.5k
      // qualification conversion.
3274
35.5k
      A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3275
35.5k
    }
3276
89.6k
  }
3277
93.5k
3278
93.5k
  //    - The transformed A can be another pointer or pointer to member
3279
93.5k
  //      type that can be converted to the deduced A via a function pointer
3280
93.5k
  //      conversion and/or a qualification conversion.
3281
93.5k
  //
3282
93.5k
  // Also allow conversions which merely strip __attribute__((noreturn)) from
3283
93.5k
  // function types (recursively).
3284
93.5k
  bool ObjCLifetimeConversion = false;
3285
92.5k
  QualType ResultTy;
3286
92.5k
  if ((A->isAnyPointerType() || 
A->isMemberPointerType()77.4k
) &&
3287
92.5k
      
(15.1k
S.IsQualificationConversion(A, DeducedA, false,
3288
15.1k
                                   ObjCLifetimeConversion) ||
3289
15.1k
       
S.IsFunctionConversion(A, DeducedA, ResultTy)14.9k
))
3290
239
    return Sema::TDK_Success;
3291
92.2k
3292
92.2k
  //    - If P is a class and P has the form simple-template-id, then the
3293
92.2k
  //      transformed A can be a derived class of the deduced A. [...]
3294
92.2k
  //     [...] Likewise, if P is a pointer to a class of the form
3295
92.2k
  //      simple-template-id, the transformed A can be a pointer to a
3296
92.2k
  //      derived class pointed to by the deduced A.
3297
92.2k
  if (const PointerType *OriginalParamPtr
3298
4.09k
      = OriginalParamType->getAs<PointerType>()) {
3299
4.09k
    if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3300
4.09k
      if (const PointerType *APtr = A->getAs<PointerType>()) {
3301
4.09k
        if (A->getPointeeType()->isRecordType()) {
3302
3.63k
          OriginalParamType = OriginalParamPtr->getPointeeType();
3303
3.63k
          DeducedA = DeducedAPtr->getPointeeType();
3304
3.63k
          A = APtr->getPointeeType();
3305
3.63k
        }
3306
4.09k
      }
3307
4.09k
    }
3308
4.09k
  }
3309
92.2k
3310
92.2k
  if (Context.hasSameUnqualifiedType(A, DeducedA))
3311
88.5k
    return Sema::TDK_Success;
3312
3.75k
3313
3.75k
  if (A->isRecordType() && 
isSimpleTemplateIdType(OriginalParamType)3.73k
&&
3314
3.75k
      
S.IsDerivedFrom(Info.getLocation(), A, DeducedA)3.73k
)
3315
3.72k
    return Sema::TDK_Success;
3316
30
3317
30
  return Failed();
3318
30
}
3319
3320
/// Find the pack index for a particular parameter index in an instantiation of
3321
/// a function template with specific arguments.
3322
///
3323
/// \return The pack index for whichever pack produced this parameter, or -1
3324
///         if this was not produced by a parameter. Intended to be used as the
3325
///         ArgumentPackSubstitutionIndex for further substitutions.
3326
// FIXME: We should track this in OriginalCallArgs so we don't need to
3327
// reconstruct it here.
3328
static unsigned getPackIndexForParam(Sema &S,
3329
                                     FunctionTemplateDecl *FunctionTemplate,
3330
                                     const MultiLevelTemplateArgumentList &Args,
3331
105
                                     unsigned ParamIdx) {
3332
105
  unsigned Idx = 0;
3333
105
  for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3334
105
    if (PD->isParameterPack()) {
3335
15
      unsigned NumExpansions =
3336
15
          S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
3337
15
      if (Idx + NumExpansions > ParamIdx)
3338
15
        return ParamIdx - Idx;
3339
0
      Idx += NumExpansions;
3340
90
    } else {
3341
90
      if (Idx == ParamIdx)
3342
90
        return -1; // Not a pack expansion
3343
0
      ++Idx;
3344
0
    }
3345
105
  }
3346
105
3347
105
  
llvm_unreachable0
("parameter index would not be produced from template");
3348
105
}
3349
3350
/// Finish template argument deduction for a function template,
3351
/// checking the deduced template arguments for completeness and forming
3352
/// the function template specialization.
3353
///
3354
/// \param OriginalCallArgs If non-NULL, the original call arguments against
3355
/// which the deduced argument types should be compared.
3356
Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
3357
    FunctionTemplateDecl *FunctionTemplate,
3358
    SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3359
    unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3360
    TemplateDeductionInfo &Info,
3361
    SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3362
508k
    bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3363
508k
  // Unevaluated SFINAE context.
3364
508k
  EnterExpressionEvaluationContext Unevaluated(
3365
508k
      *this, Sema::ExpressionEvaluationContext::Unevaluated);
3366
508k
  SFINAETrap Trap(*this);
3367
508k
3368
508k
  // Enter a new template instantiation context while we instantiate the
3369
508k
  // actual function declaration.
3370
508k
  SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3371
508k
  InstantiatingTemplate Inst(
3372
508k
      *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3373
508k
      CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
3374
508k
  if (Inst.isInvalid())
3375
1.03k
    return TDK_InstantiationDepth;
3376
507k
3377
507k
  ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3378
507k
3379
507k
  // C++ [temp.deduct.type]p2:
3380
507k
  //   [...] or if any template argument remains neither deduced nor
3381
507k
  //   explicitly specified, template argument deduction fails.
3382
507k
  SmallVector<TemplateArgument, 4> Builder;
3383
507k
  if (auto Result = ConvertDeducedTemplateArguments(
3384
39.7k
          *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
3385
39.7k
          CurrentInstantiationScope, NumExplicitlySpecified,
3386
39.7k
          PartialOverloading))
3387
39.7k
    return Result;
3388
468k
3389
468k
  // C++ [temp.deduct.call]p10: [DR1391]
3390
468k
  //   If deduction succeeds for all parameters that contain
3391
468k
  //   template-parameters that participate in template argument deduction,
3392
468k
  //   and all template arguments are explicitly specified, deduced, or
3393
468k
  //   obtained from default template arguments, remaining parameters are then
3394
468k
  //   compared with the corresponding arguments. For each remaining parameter
3395
468k
  //   P with a type that was non-dependent before substitution of any
3396
468k
  //   explicitly-specified template arguments, if the corresponding argument
3397
468k
  //   A cannot be implicitly converted to P, deduction fails.
3398
468k
  if (CheckNonDependent())
3399
33.3k
    return TDK_NonDependentConversionFailure;
3400
434k
3401
434k
  // Form the template argument list from the deduced template arguments.
3402
434k
  TemplateArgumentList *DeducedArgumentList
3403
434k
    = TemplateArgumentList::CreateCopy(Context, Builder);
3404
434k
  Info.reset(DeducedArgumentList);
3405
434k
3406
434k
  // Substitute the deduced template arguments into the function template
3407
434k
  // declaration to produce the function template specialization.
3408
434k
  DeclContext *Owner = FunctionTemplate->getDeclContext();
3409
434k
  if (FunctionTemplate->getFriendObjectKind())
3410
47
    Owner = FunctionTemplate->getLexicalDeclContext();
3411
434k
  MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
3412
434k
  Specialization = cast_or_null<FunctionDecl>(
3413
434k
      SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
3414
434k
  if (!Specialization || 
Specialization->isInvalidDecl()379k
)
3415
55.1k
    return TDK_SubstitutionFailure;
3416
379k
3417
379k
  assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
3418
379k
         FunctionTemplate->getCanonicalDecl());
3419
379k
3420
379k
  // If the template argument list is owned by the function template
3421
379k
  // specialization, release it.
3422
379k
  if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3423
379k
      
!Trap.hasErrorOccurred()0
)
3424
0
    Info.take();
3425
379k
3426
379k
  // There may have been an error that did not prevent us from constructing a
3427
379k
  // declaration. Mark the declaration invalid and return with a substitution
3428
379k
  // failure.
3429
379k
  if (Trap.hasErrorOccurred()) {
3430
95
    Specialization->setInvalidDecl(true);
3431
95
    return TDK_SubstitutionFailure;
3432
95
  }
3433
379k
3434
379k
  // C++2a [temp.deduct]p5
3435
379k
  //   [...] When all template arguments have been deduced [...] all uses of
3436
379k
  //   template parameters [...] are replaced with the corresponding deduced
3437
379k
  //   or default argument values.
3438
379k
  //   [...] If the function template has associated constraints
3439
379k
  //   ([temp.constr.decl]), those constraints are checked for satisfaction
3440
379k
  //   ([temp.constr.constr]). If the constraints are not satisfied, type
3441
379k
  //   deduction fails.
3442
379k
  if (!PartialOverloading ||
3443
379k
      
(Builder.size() == FunctionTemplate->getTemplateParameters()->size())80
) {
3444
379k
    if (CheckInstantiatedFunctionTemplateConstraints(Info.getLocation(),
3445
379k
            Specialization, Builder, Info.AssociatedConstraintsSatisfaction))
3446
1
      return TDK_MiscellaneousDeductionFailure;
3447
379k
3448
379k
    if (!Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
3449
73
      Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
3450
73
      return TDK_ConstraintsNotSatisfied;
3451
73
    }
3452
379k
  }
3453
379k
3454
379k
  if (OriginalCallArgs) {
3455
355k
    // C++ [temp.deduct.call]p4:
3456
355k
    //   In general, the deduction process attempts to find template argument
3457
355k
    //   values that will make the deduced A identical to A (after the type A
3458
355k
    //   is transformed as described above). [...]
3459
355k
    llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
3460
537k
    for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; 
++I182k
) {
3461
183k
      OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
3462
183k
3463
183k
      auto ParamIdx = OriginalArg.ArgIdx;
3464
183k
      if (ParamIdx >= Specialization->getNumParams())
3465
0
        // FIXME: This presumably means a pack ended up smaller than we
3466
0
        // expected while deducing. Should this not result in deduction
3467
0
        // failure? Can it even happen?
3468
0
        continue;
3469
183k
3470
183k
      QualType DeducedA;
3471
183k
      if (!OriginalArg.DecomposedParam) {
3472
182k
        // P is one of the function parameters, just look up its substituted
3473
182k
        // type.
3474
182k
        DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3475
182k
      } else {
3476
383
        // P is a decomposed element of a parameter corresponding to a
3477
383
        // braced-init-list argument. Substitute back into P to find the
3478
383
        // deduced A.
3479
383
        QualType &CacheEntry =
3480
383
            DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3481
383
        if (CacheEntry.isNull()) {
3482
105
          ArgumentPackSubstitutionIndexRAII PackIndex(
3483
105
              *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3484
105
                                          ParamIdx));
3485
105
          CacheEntry =
3486
105
              SubstType(OriginalArg.OriginalParamType, SubstArgs,
3487
105
                        Specialization->getTypeSpecStartLoc(),
3488
105
                        Specialization->getDeclName());
3489
105
        }
3490
383
        DeducedA = CacheEntry;
3491
383
      }
3492
183k
3493
183k
      if (auto TDK =
3494
1.01k
              CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
3495
1.01k
        return TDK;
3496
183k
    }
3497
355k
  }
3498
379k
3499
379k
  // If we suppressed any diagnostics while performing template argument
3500
379k
  // deduction, and if we haven't already instantiated this declaration,
3501
379k
  // keep track of these diagnostics. They'll be emitted if this specialization
3502
379k
  // is actually used.
3503
379k
  
if (378k
Info.diag_begin() != Info.diag_end()378k
) {
3504
5.59k
    SuppressedDiagnosticsMap::iterator
3505
5.59k
      Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3506
5.59k
    if (Pos == SuppressedDiagnostics.end())
3507
2.96k
        SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3508
2.96k
          .append(Info.diag_begin(), Info.diag_end());
3509
5.59k
  }
3510
378k
3511
378k
  return TDK_Success;
3512
379k
}
3513
3514
/// Gets the type of a function for template-argument-deducton
3515
/// purposes when it's considered as part of an overload set.
3516
static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
3517
380
                                  FunctionDecl *Fn) {
3518
380
  // We may need to deduce the return type of the function now.
3519
380
  if (S.getLangOpts().CPlusPlus14 && 
Fn->getReturnType()->isUndeducedType()201
&&
3520
380
      
S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false)12
)
3521
0
    return {};
3522
380
3523
380
  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
3524
98
    if (Method->isInstance()) {
3525
45
      // An instance method that's referenced in a form that doesn't
3526
45
      // look like a member pointer is just invalid.
3527
45
      if (!R.HasFormOfMemberPointer)
3528
18
        return {};
3529
27
3530
27
      return S.Context.getMemberPointerType(Fn->getType(),
3531
27
               S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
3532
27
    }
3533
335
3534
335
  if (!R.IsAddressOfOperand) 
return Fn->getType()221
;
3535
114
  return S.Context.getPointerType(Fn->getType());
3536
114
}
3537
3538
/// Apply the deduction rules for overload sets.
3539
///
3540
/// \return the null type if this argument should be treated as an
3541
/// undeduced context
3542
static QualType
3543
ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
3544
                            Expr *Arg, QualType ParamType,
3545
1.04k
                            bool ParamWasReference) {
3546
1.04k
3547
1.04k
  OverloadExpr::FindResult R = OverloadExpr::find(Arg);
3548
1.04k
3549
1.04k
  OverloadExpr *Ovl = R.Expression;
3550
1.04k
3551
1.04k
  // C++0x [temp.deduct.call]p4
3552
1.04k
  unsigned TDF = 0;
3553
1.04k
  if (ParamWasReference)
3554
400
    TDF |= TDF_ParamWithReferenceType;
3555
1.04k
  if (R.IsAddressOfOperand)
3556
188
    TDF |= TDF_IgnoreQualifiers;
3557
1.04k
3558
1.04k
  // C++0x [temp.deduct.call]p6:
3559
1.04k
  //   When P is a function type, pointer to function type, or pointer
3560
1.04k
  //   to member function type:
3561
1.04k
3562
1.04k
  if (!ParamType->isFunctionType() &&
3563
1.04k
      
!ParamType->isFunctionPointerType()1.03k
&&
3564
1.04k
      
!ParamType->isMemberFunctionPointerType()849
) {
3565
829
    if (Ovl->hasExplicitTemplateArgs()) {
3566
75
      // But we can still look for an explicit specialization.
3567
75
      if (FunctionDecl *ExplicitSpec
3568
71
            = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
3569
71
        return GetTypeOfFunction(S, R, ExplicitSpec);
3570
758
    }
3571
758
3572
758
    DeclAccessPair DAP;
3573
758
    if (FunctionDecl *Viable =
3574
6
            S.resolveAddressOfSingleOverloadCandidate(Arg, DAP))
3575
6
      return GetTypeOfFunction(S, R, Viable);
3576
752
3577
752
    return {};
3578
752
  }
3579
211
3580
211
  // Gather the explicit template arguments, if any.
3581
211
  TemplateArgumentListInfo ExplicitTemplateArgs;
3582
211
  if (Ovl->hasExplicitTemplateArgs())
3583
53
    Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
3584
211
  QualType Match;
3585
211
  for (UnresolvedSetIterator I = Ovl->decls_begin(),
3586
460
         E = Ovl->decls_end(); I != E; 
++I249
) {
3587
349
    NamedDecl *D = (*I)->getUnderlyingDecl();
3588
349
3589
349
    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3590
95
      //   - If the argument is an overload set containing one or more
3591
95
      //     function templates, the parameter is treated as a
3592
95
      //     non-deduced context.
3593
95
      if (!Ovl->hasExplicitTemplateArgs())
3594
36
        return {};
3595
59
3596
59
      // Otherwise, see if we can resolve a function type
3597
59
      FunctionDecl *Specialization = nullptr;
3598
59
      TemplateDeductionInfo Info(Ovl->getNameLoc());
3599
59
      if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3600
59
                                    Specialization, Info))
3601
10
        continue;
3602
49
3603
49
      D = Specialization;
3604
49
    }
3605
349
3606
349
    FunctionDecl *Fn = cast<FunctionDecl>(D);
3607
303
    QualType ArgType = GetTypeOfFunction(S, R, Fn);
3608
303
    if (ArgType.isNull()) 
continue18
;
3609
285
3610
285
    // Function-to-pointer conversion.
3611
285
    if (!ParamWasReference && 
ParamType->isPointerType()277
&&
3612
285
        
ArgType->isFunctionType()246
)
3613
177
      ArgType = S.Context.getPointerType(ArgType);
3614
285
3615
285
    //   - If the argument is an overload set (not containing function
3616
285
    //     templates), trial argument deduction is attempted using each
3617
285
    //     of the members of the set. If deduction succeeds for only one
3618
285
    //     of the overload set members, that member is used as the
3619
285
    //     argument value for the deduction. If deduction succeeds for
3620
285
    //     more than one member of the overload set the parameter is
3621
285
    //     treated as a non-deduced context.
3622
285
3623
285
    // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3624
285
    //   Type deduction is done independently for each P/A pair, and
3625
285
    //   the deduced template argument values are then combined.
3626
285
    // So we do not reject deductions which were made elsewhere.
3627
285
    SmallVector<DeducedTemplateArgument, 8>
3628
285
      Deduced(TemplateParams->size());
3629
285
    TemplateDeductionInfo Info(Ovl->getNameLoc());
3630
285
    Sema::TemplateDeductionResult Result
3631
285
      = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3632
285
                                           ArgType, Info, Deduced, TDF);
3633
285
    if (Result) 
continue76
;
3634
209
    if (!Match.isNull())
3635
64
      return {};
3636
145
    Match = ArgType;
3637
145
  }
3638
211
3639
211
  
return Match111
;
3640
211
}
3641
3642
/// Perform the adjustments to the parameter and argument types
3643
/// described in C++ [temp.deduct.call].
3644
///
3645
/// \returns true if the caller should not attempt to perform any template
3646
/// argument deduction based on this P/A pair because the argument is an
3647
/// overloaded function set that could not be resolved.
3648
static bool AdjustFunctionParmAndArgTypesForDeduction(
3649
    Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3650
820k
    QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
3651
820k
  // C++0x [temp.deduct.call]p3:
3652
820k
  //   If P is a cv-qualified type, the top level cv-qualifiers of P's type
3653
820k
  //   are ignored for type deduction.
3654
820k
  if (ParamType.hasQualifiers())
3655
827
    ParamType = ParamType.getUnqualifiedType();
3656
820k
3657
820k
  //   [...] If P is a reference type, the type referred to by P is
3658
820k
  //   used for type deduction.
3659
820k
  const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
3660
820k
  if (ParamRefType)
3661
591k
    ParamType = ParamRefType->getPointeeType();
3662
820k
3663
820k
  // Overload sets usually make this parameter an undeduced context,
3664
820k
  // but there are sometimes special circumstances.  Typically
3665
820k
  // involving a template-id-expr.
3666
820k
  if (ArgType == S.Context.OverloadTy) {
3667
1.04k
    ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3668
1.04k
                                          Arg, ParamType,
3669
1.04k
                                          ParamRefType != nullptr);
3670
1.04k
    if (ArgType.isNull())
3671
886
      return true;
3672
819k
  }
3673
819k
3674
819k
  if (ParamRefType) {
3675
591k
    // If the argument has incomplete array type, try to complete its type.
3676
591k
    if (ArgType->isIncompleteArrayType()) {
3677
8
      S.completeExprArrayBound(Arg);
3678
8
      ArgType = Arg->getType();
3679
8
    }
3680
591k
3681
591k
    // C++1z [temp.deduct.call]p3:
3682
591k
    //   If P is a forwarding reference and the argument is an lvalue, the type
3683
591k
    //   "lvalue reference to A" is used in place of A for type deduction.
3684
591k
    if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
3685
591k
        
Arg->isLValue()64.9k
)
3686
26.9k
      ArgType = S.Context.getLValueReferenceType(ArgType);
3687
591k
  } else {
3688
227k
    // C++ [temp.deduct.call]p2:
3689
227k
    //   If P is not a reference type:
3690
227k
    //   - If A is an array type, the pointer type produced by the
3691
227k
    //     array-to-pointer standard conversion (4.2) is used in place of
3692
227k
    //     A for type deduction; otherwise,
3693
227k
    if (ArgType->isArrayType())
3694
1.87k
      ArgType = S.Context.getArrayDecayedType(ArgType);
3695
225k
    //   - If A is a function type, the pointer type produced by the
3696
225k
    //     function-to-pointer standard conversion (4.3) is used in place
3697
225k
    //     of A for type deduction; otherwise,
3698
225k
    else if (ArgType->isFunctionType())
3699
271
      ArgType = S.Context.getPointerType(ArgType);
3700
225k
    else {
3701
225k
      // - If A is a cv-qualified type, the top level cv-qualifiers of A's
3702
225k
      //   type are ignored for type deduction.
3703
225k
      ArgType = ArgType.getUnqualifiedType();
3704
225k
    }
3705
227k
  }
3706
819k
3707
819k
  // C++0x [temp.deduct.call]p4:
3708
819k
  //   In general, the deduction process attempts to find template argument
3709
819k
  //   values that will make the deduced A identical to A (after the type A
3710
819k
  //   is transformed as described above). [...]
3711
819k
  TDF = TDF_SkipNonDependent;
3712
819k
3713
819k
  //     - If the original P is a reference type, the deduced A (i.e., the
3714
819k
  //       type referred to by the reference) can be more cv-qualified than
3715
819k
  //       the transformed A.
3716
819k
  if (ParamRefType)
3717
591k
    TDF |= TDF_ParamWithReferenceType;
3718
819k
  //     - The transformed A can be another pointer or pointer to member
3719
819k
  //       type that can be converted to the deduced A via a qualification
3720
819k
  //       conversion (4.4).
3721
819k
  if (ArgType->isPointerType() || 
ArgType->isMemberPointerType()696k
||
3722
819k
      
ArgType->isObjCObjectPointerType()695k
)
3723
123k
    TDF |= TDF_IgnoreQualifiers;
3724
819k
  //     - If P is a class and P has the form simple-template-id, then the
3725
819k
  //       transformed A can be a derived class of the deduced A. Likewise,
3726
819k
  //       if P is a pointer to a class of the form simple-template-id, the
3727
819k
  //       transformed A can be a pointer to a derived class pointed to by
3728
819k
  //       the deduced A.
3729
819k
  if (isSimpleTemplateIdType(ParamType) ||
3730
819k
      
(262k
isa<PointerType>(ParamType)262k
&&
3731
262k
       isSimpleTemplateIdType(
3732
34.9k
                              ParamType->getAs<PointerType>()->getPointeeType())))
3733
560k
    TDF |= TDF_DerivedClass;
3734
819k
3735
819k
  return false;
3736
819k
}
3737
3738
static bool
3739
hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3740
                               QualType T);
3741
3742
static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3743
    Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3744
    QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
3745
    SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3746
    SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3747
    bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
3748
3749
/// Attempt template argument deduction from an initializer list
3750
///        deemed to be an argument in a function call.
3751
static Sema::TemplateDeductionResult DeduceFromInitializerList(
3752
    Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3753
    InitListExpr *ILE, TemplateDeductionInfo &Info,
3754
    SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3755
    SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3756
821
    unsigned TDF) {
3757
821
  // C++ [temp.deduct.call]p1: (CWG 1591)
3758
821
  //   If removing references and cv-qualifiers from P gives
3759
821
  //   std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3760
821
  //   a non-empty initializer list, then deduction is performed instead for
3761
821
  //   each element of the initializer list, taking P0 as a function template
3762
821
  //   parameter type and the initializer element as its argument
3763
821
  //
3764
821
  // We've already removed references and cv-qualifiers here.
3765
821
  if (!ILE->getNumInits())
3766
29
    return Sema::TDK_Success;
3767
792
3768
792
  QualType ElTy;
3769
792
  auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3770
792
  if (ArrTy)
3771
400
    ElTy = ArrTy->getElementType();
3772
392
  else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3773
307
    //   Otherwise, an initializer list argument causes the parameter to be
3774
307
    //   considered a non-deduced context
3775
307
    return Sema::TDK_Success;
3776
307
  }
3777
485
3778
485
  // Resolving a core issue: a braced-init-list containing any designators is
3779
485
  // a non-deduced context.
3780
485
  for (Expr *E : ILE->inits())
3781
1.09k
    if (isa<DesignatedInitExpr>(E))
3782
4
      return Sema::TDK_Success;
3783
485
3784
485
  // Deduction only needs to be done for dependent types.
3785
485
  
if (481
ElTy->isDependentType()481
) {
3786
960
    for (Expr *E : ILE->inits()) {
3787
960
      if (auto Result = DeduceTemplateArgumentsFromCallArgument(
3788
72
              S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
3789
72
              ArgIdx, TDF))
3790
72
        return Result;
3791
960
    }
3792
455
  }
3793
481
3794
481
  //   in the P0[N] case, if N is a non-type template parameter, N is deduced
3795
481
  //   from the length of the initializer list.
3796
481
  
if (auto *409
DependentArrTy409
= dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
3797
315
    // Determine the array bound is something we can deduce.
3798
315
    if (NonTypeTemplateParmDecl *NTTP =
3799
315
            getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
3800
315
      // We can perform template argument deduction for the given non-type
3801
315
      // template parameter.
3802
315
      // C++ [temp.deduct.type]p13:
3803
315
      //   The type of N in the type T[N] is std::size_t.
3804
315
      QualType T = S.Context.getSizeType();
3805
315
      llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
3806
315
      if (auto Result = DeduceNonTypeTemplateArgument(
3807
11
              S, TemplateParams, NTTP, llvm::APSInt(Size), T,
3808
11
              /*ArrayBound=*/true, Info, Deduced))
3809
11
        return Result;
3810
398
    }
3811
315
  }
3812
398
3813
398
  return Sema::TDK_Success;
3814
398
}
3815
3816
/// Perform template argument deduction per [temp.deduct.call] for a
3817
///        single parameter / argument pair.
3818
static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3819
    Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3820
    QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
3821
    SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3822
    SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3823
820k
    bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
3824
820k
  QualType ArgType = Arg->getType();
3825
820k
  QualType OrigParamType = ParamType;
3826
820k
3827
820k
  //   If P is a reference type [...]
3828
820k
  //   If P is a cv-qualified type [...]
3829
820k
  if (AdjustFunctionParmAndArgTypesForDeduction(
3830
820k
          S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
3831
886
    return Sema::TDK_Success;
3832
819k
3833
819k
  //   If [...] the argument is a non-empty initializer list [...]
3834
819k
  if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3835
821
    return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
3836
821
                                     Deduced, OriginalCallArgs, ArgIdx, TDF);
3837
818k
3838
818k
  //   [...] the deduction process attempts to find template argument values
3839
818k
  //   that will make the deduced A identical to A
3840
818k
  //
3841
818k
  // Keep track of the argument type and corresponding parameter index,
3842
818k
  // so we can check for compatibility between the deduced A and A.
3843
818k
  OriginalCallArgs.push_back(
3844
818k
      Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
3845
818k
  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3846
818k
                                            ArgType, Info, Deduced, TDF);
3847
818k
}
3848
3849
/// Perform template argument deduction from a function call
3850
/// (C++ [temp.deduct.call]).
3851
///
3852
/// \param FunctionTemplate the function template for which we are performing
3853
/// template argument deduction.
3854
///
3855
/// \param ExplicitTemplateArgs the explicit template arguments provided
3856
/// for this call.
3857
///
3858
/// \param Args the function call arguments
3859
///
3860
/// \param Specialization if template argument deduction was successful,
3861
/// this will be set to the function template specialization produced by
3862
/// template argument deduction.
3863
///
3864
/// \param Info the argument will be updated to provide additional information
3865
/// about template argument deduction.
3866
///
3867
/// \param CheckNonDependent A callback to invoke to check conversions for
3868
/// non-dependent parameters, between deduction and substitution, per DR1391.
3869
/// If this returns true, substitution will be skipped and we return
3870
/// TDK_NonDependentConversionFailure. The callback is passed the parameter
3871
/// types (after substituting explicit template arguments).
3872
///
3873
/// \returns the result of template argument deduction.
3874
Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3875
    FunctionTemplateDecl *FunctionTemplate,
3876
    TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3877
    FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3878
    bool PartialOverloading,
3879
1.18M
    llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
3880
1.18M
  if (FunctionTemplate->isInvalidDecl())
3881
11
    return TDK_Invalid;
3882
1.18M
3883
1.18M
  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3884
1.18M
  unsigned NumParams = Function->getNumParams();
3885
1.18M
3886
1.18M
  unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3887
1.18M
3888
1.18M
  // C++ [temp.deduct.call]p1:
3889
1.18M
  //   Template argument deduction is done by comparing each function template
3890
1.18M
  //   parameter type (call it P) with the type of the corresponding argument
3891
1.18M
  //   of the call (call it A) as described below.
3892
1.18M
  if (Args.size() < Function->getMinRequiredArguments() && 
!PartialOverloading149k
)
3893
149k
    return TDK_TooFewArguments;
3894
1.03M
  else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
3895
66.1k
    const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
3896
66.1k
    if (Proto->isTemplateVariadic())
3897
3.04k
      /* Do nothing */;
3898
63.1k
    else if (!Proto->isVariadic())
3899
31.6k
      return TDK_TooManyArguments;
3900
1.00M
  }
3901
1.00M
3902
1.00M
  // The types of the parameters from which we will perform template argument
3903
1.00M
  // deduction.
3904
1.00M
  LocalInstantiationScope InstScope(*this);
3905
1.00M
  TemplateParameterList *TemplateParams
3906
1.00M
    = FunctionTemplate->getTemplateParameters();
3907
1.00M
  SmallVector<DeducedTemplateArgument, 4> Deduced;
3908
1.00M
  SmallVector<QualType, 8> ParamTypes;
3909
1.00M
  unsigned NumExplicitlySpecified = 0;
3910
1.00M
  if (ExplicitTemplateArgs) {
3911
254k
    TemplateDeductionResult Result =
3912
254k
      SubstituteExplicitTemplateArguments(FunctionTemplate,
3913
254k
                                          *ExplicitTemplateArgs,
3914
254k
                                          Deduced,
3915
254k
                                          ParamTypes,
3916
254k
                                          nullptr,
3917
254k
                                          Info);
3918
254k
    if (Result)
3919
2.02k
      return Result;
3920
252k
3921
252k
    NumExplicitlySpecified = Deduced.size();
3922
745k
  } else {
3923
745k
    // Just fill in the parameter types from the function declaration.
3924
2.10M
    for (unsigned I = 0; I != NumParams; 
++I1.36M
)
3925
1.36M
      ParamTypes.push_back(Function->getParamDecl(I)->getType());
3926
745k
  }
3927
1.00M
3928
1.00M
  SmallVector<OriginalCallArg, 8> OriginalCallArgs;
3929
998k
3930
998k
  // Deduce an argument of type ParamType from an expression with index ArgIdx.
3931
1.07M
  auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
3932
1.07M
    // C++ [demp.deduct.call]p1: (DR1391)
3933
1.07M
    //   Template argument deduction is done by comparing each function template
3934
1.07M
    //   parameter that contains template-parameters that participate in
3935
1.07M
    //   template argument deduction ...
3936
1.07M
    if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3937
266k
      return Sema::TDK_Success;
3938
806k
3939
806k
    //   ... with the type of the corresponding argument
3940
806k
    return DeduceTemplateArgumentsFromCallArgument(
3941
806k
        *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
3942
806k
        OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
3943
806k
  };
3944
998k
3945
998k
  // Deduce template arguments from the function parameters.
3946
998k
  Deduced.resize(TemplateParams->size());
3947
998k
  SmallVector<QualType, 8> ParamTypesForArgChecking;
3948
998k
  for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
3949
1.54M
       ParamIdx != NumParamTypes; 
++ParamIdx551k
) {
3950
1.11M
    QualType ParamType = ParamTypes[ParamIdx];
3951
1.11M
3952
1.11M
    const PackExpansionType *ParamExpansion =
3953
1.11M
        dyn_cast<PackExpansionType>(ParamType);
3954
1.11M
    if (!ParamExpansion) {
3955
1.09M
      // Simple case: matching a function parameter to a function argument.
3956
1.09M
      if (ArgIdx >= Args.size())
3957
40.4k
        break;
3958
1.05M
3959
1.05M
      ParamTypesForArgChecking.push_back(ParamType);
3960
1.05M
      if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
3961
518k
        return Result;
3962
537k
3963
537k
      continue;
3964
537k
    }
3965
13.9k
3966
13.9k
    QualType ParamPattern = ParamExpansion->getPattern();
3967
13.9k
    PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3968
13.9k
                                 ParamPattern);
3969
13.9k
3970
13.9k
    // C++0x [temp.deduct.call]p1:
3971
13.9k
    //   For a function parameter pack that occurs at the end of the
3972
13.9k
    //   parameter-declaration-list, the type A of each remaining argument of
3973
13.9k
    //   the call is compared with the type P of the declarator-id of the
3974
13.9k
    //   function parameter pack. Each comparison deduces template arguments
3975
13.9k
    //   for subsequent positions in the template parameter packs expanded by
3976
13.9k
    //   the function parameter pack. When a function parameter pack appears
3977
13.9k
    //   in a non-deduced context [not at the end of the list], the type of
3978
13.9k
    //   that parameter pack is never deduced.
3979
13.9k
    //
3980
13.9k
    // FIXME: The above rule allows the size of the parameter pack to change
3981
13.9k
    // after we skip it (in the non-deduced case). That makes no sense, so
3982
13.9k
    // we instead notionally deduce the pack against N arguments, where N is
3983
13.9k
    // the length of the explicitly-specified pack if it's expanded by the
3984
13.9k
    // parameter pack and 0 otherwise, and we treat each deduction as a
3985
13.9k
    // non-deduced context.
3986
13.9k
    if (ParamIdx + 1 == NumParamTypes || 
PackScope.hasFixedArity()146
) {
3987
29.9k
      for (; ArgIdx < Args.size() && 
PackScope.hasNextElement()16.2k
;
3988
16.2k
           
PackScope.nextPackElement(), ++ArgIdx16.2k
) {
3989
16.2k
        ParamTypesForArgChecking.push_back(ParamPattern);
3990
16.2k
        if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3991
10
          return Result;
3992
16.2k
      }
3993
13.7k
    } else {
3994
144
      // If the parameter type contains an explicitly-specified pack that we
3995
144
      // could not expand, skip the number of parameters notionally created
3996
144
      // by the expansion.
3997
144
      Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
3998
144
      if (NumExpansions && 
!PackScope.isPartiallyExpanded()12
) {
3999
36
        for (unsigned I = 0; I != *NumExpansions && 
ArgIdx < Args.size()24
;
4000
24
             ++I, ++ArgIdx) {
4001
24
          ParamTypesForArgChecking.push_back(ParamPattern);
4002
24
          // FIXME: Should we add OriginalCallArgs for these? What if the
4003
24
          // corresponding argument is a list?
4004
24
          PackScope.nextPackElement();
4005
24
        }
4006
12
      }
4007
144
    }
4008
13.9k
4009
13.9k
    // Build argument packs for each of the parameter packs expanded by this
4010
13.9k
    // pack expansion.
4011
13.9k
    
if (auto 13.8k
Result13.8k
= PackScope.finish())
4012
40
      return Result;
4013
13.8k
  }
4014
998k
4015
998k
  // Capture the context in which the function call is made. This is the context
4016
998k
  // that is needed when the accessibility of template arguments is checked.
4017
998k
  DeclContext *CallingCtx = CurContext;
4018
479k
4019
479k
  return FinishTemplateArgumentDeduction(
4020
479k
      FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4021
479k
      &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
4022
441k
        ContextRAII SavedContext(*this, CallingCtx);
4023
441k
        return CheckNonDependent(ParamTypesForArgChecking);
4024
441k
      });
4025
998k
}
4026
4027
QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
4028
                                   QualType FunctionType,
4029
277k
                                   bool AdjustExceptionSpec) {
4030
277k
  if (ArgFunctionType.isNull())
4031
108
    return ArgFunctionType;
4032
277k
4033
277k
  const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4034
277k
  const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4035
277k
  FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4036
277k
  bool Rebuild = false;
4037
277k
4038
277k
  CallingConv CC = FunctionTypeP->getCallConv();
4039
277k
  if (EPI.ExtInfo.getCC() != CC) {
4040
155
    EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4041
155
    Rebuild = true;
4042
155
  }
4043
277k
4044
277k
  bool NoReturn = FunctionTypeP->getNoReturnAttr();
4045
277k
  if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4046
1
    EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4047
1
    Rebuild = true;
4048
1
  }
4049
277k
4050
277k
  if (AdjustExceptionSpec && 
(166k
FunctionTypeP->hasExceptionSpec()166k
||
4051
166k
                              
ArgFunctionTypeP->hasExceptionSpec()135k
)) {
4052
35.8k
    EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4053
35.8k
    Rebuild = true;
4054
35.8k
  }
4055
277k
4056
277k
  if (!Rebuild)
4057
241k
    return ArgFunctionType;
4058
36.0k
4059
36.0k
  return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4060
36.0k
                                 ArgFunctionTypeP->getParamTypes(), EPI);
4061
36.0k
}
4062
4063
/// Deduce template arguments when taking the address of a function
4064
/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
4065
/// a template.
4066
///
4067
/// \param FunctionTemplate the function template for which we are performing
4068
/// template argument deduction.
4069
///
4070
/// \param ExplicitTemplateArgs the explicitly-specified template
4071
/// arguments.
4072
///
4073
/// \param ArgFunctionType the function type that will be used as the
4074
/// "argument" type (A) when performing template argument deduction from the
4075
/// function template's function type. This type may be NULL, if there is no
4076
/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
4077
///
4078
/// \param Specialization if template argument deduction was successful,
4079
/// this will be set to the function template specialization produced by
4080
/// template argument deduction.
4081
///
4082
/// \param Info the argument will be updated to provide additional information
4083
/// about template argument deduction.
4084
///
4085
/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4086
/// the address of a function template per [temp.deduct.funcaddr] and
4087
/// [over.over]. If \c false, we are looking up a function template
4088
/// specialization based on its signature, per [temp.deduct.decl].
4089
///
4090
/// \returns the result of template argument deduction.
4091
Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4092
    FunctionTemplateDecl *FunctionTemplate,
4093
    TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4094
    FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4095
114k
    bool IsAddressOfFunction) {
4096
114k
  if (FunctionTemplate->isInvalidDecl())
4097
0
    return TDK_Invalid;
4098
114k
4099
114k
  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4100
114k
  TemplateParameterList *TemplateParams
4101
114k
    = FunctionTemplate->getTemplateParameters();
4102
114k
  QualType FunctionType = Function->getType();
4103
114k
4104
114k
  // Substitute any explicit template arguments.
4105
114k
  LocalInstantiationScope InstScope(*this);
4106
114k
  SmallVector<DeducedTemplateArgument, 4> Deduced;
4107
114k
  unsigned NumExplicitlySpecified = 0;
4108
114k
  SmallVector<QualType, 4> ParamTypes;
4109
114k
  if (ExplicitTemplateArgs) {
4110
47.9k
    if (TemplateDeductionResult Result
4111
896
          = SubstituteExplicitTemplateArguments(FunctionTemplate,
4112
896
                                                *ExplicitTemplateArgs,
4113
896
                                                Deduced, ParamTypes,
4114
896
                                                &FunctionType, Info))
4115
896
      return Result;
4116
47.0k
4117
47.0k
    NumExplicitlySpecified = Deduced.size();
4118
47.0k
  }
4119
114k
4120
114k
  // When taking the address of a function, we require convertibility of
4121
114k
  // the resulting function type. Otherwise, we allow arbitrary mismatches
4122
114k
  // of calling convention and noreturn.
4123
114k
  
if (113k
!IsAddressOfFunction113k
)
4124
107k
    ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4125
107k
                                          /*AdjustExceptionSpec*/false);
4126
113k
4127
113k
  // Unevaluated SFINAE context.
4128
113k
  EnterExpressionEvaluationContext Unevaluated(
4129
113k
      *this, Sema::ExpressionEvaluationContext::Unevaluated);
4130
113k
  SFINAETrap Trap(*this);
4131
113k
4132
113k
  Deduced.resize(TemplateParams->size());
4133
113k
4134
113k
  // If the function has a deduced return type, substitute it for a dependent
4135
113k
  // type so that we treat it as a non-deduced context in what follows. If we
4136
113k
  // are looking up by signature, the signature type should also have a deduced
4137
113k
  // return type, which we instead expect to exactly match.
4138
113k
  bool HasDeducedReturnType = false;
4139
113k
  if (getLangOpts().CPlusPlus14 && 
IsAddressOfFunction8.27k
&&
4140
113k
      
Function->getReturnType()->getContainedAutoType()1.71k
) {
4141
160
    FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
4142
160
    HasDeducedReturnType = true;
4143
160
  }
4144
113k
4145
113k
  if (!ArgFunctionType.isNull()) {
4146
112k
    unsigned TDF =
4147
112k
        TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
4148
112k
    // Deduce template arguments from the function type.
4149
112k
    if (TemplateDeductionResult Result
4150
86.9k
          = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4151
86.9k
                                               FunctionType, ArgFunctionType,
4152
86.9k
                                               Info, Deduced, TDF))
4153
86.9k
      return Result;
4154
26.1k
  }
4155
26.1k
4156
26.1k
  if (TemplateDeductionResult Result
4157
4.98k
        = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4158
4.98k
                                          NumExplicitlySpecified,
4159
4.98k
                                          Specialization, Info))
4160
4.98k
    return Result;
4161
21.2k
4162
21.2k
  // If the function has a deduced return type, deduce it now, so we can check
4163
21.2k
  // that the deduced function type matches the requested type.
4164
21.2k
  if (HasDeducedReturnType &&
4165
21.2k
      
Specialization->getReturnType()->isUndeducedType()116
&&
4166
21.2k
      
DeduceReturnType(Specialization, Info.getLocation(), false)20
)
4167
4
    return TDK_MiscellaneousDeductionFailure;
4168
21.2k
4169
21.2k
  // If the function has a dependent exception specification, resolve it now,
4170
21.2k
  // so we can check that the exception specification matches.
4171
21.2k
  auto *SpecializationFPT =
4172
21.2k
      Specialization->getType()->castAs<FunctionProtoType>();
4173
21.2k
  if (getLangOpts().CPlusPlus17 &&
4174
21.2k
      
isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType())1.30k
&&
4175
21.2k
      
!ResolveExceptionSpec(Info.getLocation(), SpecializationFPT)8
)
4176
0
    return TDK_MiscellaneousDeductionFailure;
4177
21.2k
4178
21.2k
  // Adjust the exception specification of the argument to match the
4179
21.2k
  // substituted and resolved type we just formed. (Calling convention and
4180
21.2k
  // noreturn can't be dependent, so we don't actually need this for them
4181
21.2k
  // right now.)
4182
21.2k
  QualType SpecializationType = Specialization->getType();
4183
21.2k
  if (!IsAddressOfFunction)
4184
18.2k
    ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4185
18.2k
                                          /*AdjustExceptionSpec*/true);
4186
21.2k
4187
21.2k
  // If the requested function type does not match the actual type of the
4188
21.2k
  // specialization with respect to arguments of compatible pointer to function
4189
21.2k
  // types, template argument deduction fails.
4190
21.2k
  if (!ArgFunctionType.isNull()) {
4191
20.5k
    if (IsAddressOfFunction &&
4192
20.5k
        !isSameOrCompatibleFunctionType(
4193
2.34k
            Context.getCanonicalType(SpecializationType),
4194
2.34k
            Context.getCanonicalType(ArgFunctionType)))
4195
23
      return TDK_MiscellaneousDeductionFailure;
4196
20.5k
4197
20.5k
    if (!IsAddressOfFunction &&
4198
20.5k
        
!Context.hasSameType(SpecializationType, ArgFunctionType)18.2k
)
4199
11
      return TDK_MiscellaneousDeductionFailure;
4200
21.1k
  }
4201
21.1k
4202
21.1k
  return TDK_Success;
4203
21.1k
}
4204
4205
/// Deduce template arguments for a templated conversion
4206
/// function (C++ [temp.deduct.conv]) and, if successful, produce a
4207
/// conversion function template specialization.
4208
Sema::TemplateDeductionResult
4209
Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
4210
                              QualType ToType,
4211
                              CXXConversionDecl *&Specialization,
4212
3.27k
                              TemplateDeductionInfo &Info) {
4213
3.27k
  if (ConversionTemplate->isInvalidDecl())
4214
0
    return TDK_Invalid;
4215
3.27k
4216
3.27k
  CXXConversionDecl *ConversionGeneric
4217
3.27k
    = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4218
3.27k
4219
3.27k
  QualType FromType = ConversionGeneric->getConversionType();
4220
3.27k
4221
3.27k
  // Canonicalize the types for deduction.
4222
3.27k
  QualType P = Context.getCanonicalType(FromType);
4223
3.27k
  QualType A = Context.getCanonicalType(ToType);
4224
3.27k
4225
3.27k
  // C++0x [temp.deduct.conv]p2:
4226
3.27k
  //   If P is a reference type, the type referred to by P is used for
4227
3.27k
  //   type deduction.
4228
3.27k
  if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4229
82
    P = PRef->getPointeeType();
4230
3.27k
4231
3.27k
  // C++0x [temp.deduct.conv]p4:
4232
3.27k
  //   [...] If A is a reference type, the type referred to by A is used
4233
3.27k
  //   for type deduction.
4234
3.27k
  if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4235
160
    A = ARef->getPointeeType();
4236
160
    // We work around a defect in the standard here: cv-qualifiers are also
4237
160
    // removed from P and A in this case, unless P was a reference type. This
4238
160
    // seems to mostly match what other compilers are doing.
4239
160
    if (!FromType->getAs<ReferenceType>()) {
4240
100
      A = A.getUnqualifiedType();
4241
100
      P = P.getUnqualifiedType();
4242
100
    }
4243
160
4244
160
  // C++ [temp.deduct.conv]p3:
4245
160
  //
4246
160
  //   If A is not a reference type:
4247
3.11k
  } else {
4248
3.11k
    assert(!A->isReferenceType() && "Reference types were handled above");
4249
3.11k
4250
3.11k
    //   - If P is an array type, the pointer type produced by the
4251
3.11k
    //     array-to-pointer standard conversion (4.2) is used in place
4252
3.11k
    //     of P for type deduction; otherwise,
4253
3.11k
    if (P->isArrayType())
4254
1
      P = Context.getArrayDecayedType(P);
4255
3.11k
    //   - If P is a function type, the pointer type produced by the
4256
3.11k
    //     function-to-pointer standard conversion (4.3) is used in
4257
3.11k
    //     place of P for type deduction; otherwise,
4258
3.11k
    else if (P->isFunctionType())
4259
0
      P = Context.getPointerType(P);
4260
3.11k
    //   - If P is a cv-qualified type, the top level cv-qualifiers of
4261
3.11k
    //     P's type are ignored for type deduction.
4262
3.11k
    else
4263
3.11k
      P = P.getUnqualifiedType();
4264
3.11k
4265
3.11k
    // C++0x [temp.deduct.conv]p4:
4266
3.11k
    //   If A is a cv-qualified type, the top level cv-qualifiers of A's
4267
3.11k
    //   type are ignored for type deduction. If A is a reference type, the type
4268
3.11k
    //   referred to by A is used for type deduction.
4269
3.11k
    A = A.getUnqualifiedType();
4270
3.11k
  }
4271
3.27k
4272
3.27k
  // Unevaluated SFINAE context.
4273
3.27k
  EnterExpressionEvaluationContext Unevaluated(
4274
3.27k
      *this, Sema::ExpressionEvaluationContext::Unevaluated);
4275
3.27k
  SFINAETrap Trap(*this);
4276
3.27k
4277
3.27k
  // C++ [temp.deduct.conv]p1:
4278
3.27k
  //   Template argument deduction is done by comparing the return
4279
3.27k
  //   type of the template conversion function (call it P) with the
4280
3.27k
  //   type that is required as the result of the conversion (call it
4281
3.27k
  //   A) as described in 14.8.2.4.
4282
3.27k
  TemplateParameterList *TemplateParams
4283
3.27k
    = ConversionTemplate->getTemplateParameters();
4284
3.27k
  SmallVector<DeducedTemplateArgument, 4> Deduced;
4285
3.27k
  Deduced.resize(TemplateParams->size());
4286
3.27k
4287
3.27k
  // C++0x [temp.deduct.conv]p4:
4288
3.27k
  //   In general, the deduction process attempts to find template
4289
3.27k
  //   argument values that will make the deduced A identical to
4290
3.27k
  //   A. However, there are two cases that allow a difference:
4291
3.27k
  unsigned TDF = 0;
4292
3.27k
  //     - If the original A is a reference type, A can be more
4293
3.27k
  //       cv-qualified than the deduced A (i.e., the type referred to
4294
3.27k
  //       by the reference)
4295
3.27k
  if (ToType->isReferenceType())
4296
160
    TDF |= TDF_ArgWithReferenceType;
4297
3.27k
  //     - The deduced A can be another pointer or pointer to member
4298
3.27k
  //       type that can be converted to A via a qualification
4299
3.27k
  //       conversion.
4300
3.27k
  //
4301
3.27k
  // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4302
3.27k
  // both P and A are pointers or member pointers. In this case, we
4303
3.27k
  // just ignore cv-qualifiers completely).
4304
3.27k
  if ((P->isPointerType() && 
A->isPointerType()384
) ||
4305
3.27k
      
(2.94k
P->isMemberPointerType()2.94k
&&
A->isMemberPointerType()18
))
4306
357
    TDF |= TDF_IgnoreQualifiers;
4307
3.27k
  if (TemplateDeductionResult Result
4308
76
        = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4309
76
                                             P, A, Info, Deduced, TDF))
4310
76
    return Result;
4311
3.20k
4312
3.20k
  // Create an Instantiation Scope for finalizing the operator.
4313
3.20k
  LocalInstantiationScope InstScope(*this);
4314
3.20k
  // Finish template argument deduction.
4315
3.20k
  FunctionDecl *ConversionSpecialized = nullptr;
4316
3.20k
  TemplateDeductionResult Result
4317
3.20k
      = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4318
3.20k
                                        ConversionSpecialized, Info);
4319
3.20k
  Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4320
3.20k
  return Result;
4321
3.20k
}
4322
4323
/// Deduce template arguments for a function template when there is
4324
/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4325
///
4326
/// \param FunctionTemplate the function template for which we are performing
4327
/// template argument deduction.
4328
///
4329
/// \param ExplicitTemplateArgs the explicitly-specified template
4330
/// arguments.
4331
///
4332
/// \param Specialization if template argument deduction was successful,
4333
/// this will be set to the function template specialization produced by
4334
/// template argument deduction.
4335
///
4336
/// \param Info the argument will be updated to provide additional information
4337
/// about template argument deduction.
4338
///
4339
/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4340
/// the address of a function template in a context where we do not have a
4341
/// target type, per [over.over]. If \c false, we are looking up a function
4342
/// template specialization based on its signature, which only happens when
4343
/// deducing a function parameter type from an argument that is a template-id
4344
/// naming a function template specialization.
4345
///
4346
/// \returns the result of template argument deduction.
4347
Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4348
    FunctionTemplateDecl *FunctionTemplate,
4349
    TemplateArgumentListInfo *ExplicitTemplateArgs,
4350
    FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4351
733
    bool IsAddressOfFunction) {
4352
733
  return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4353
733
                                 QualType(), Specialization, Info,
4354
733
                                 IsAddressOfFunction);
4355
733
}
4356
4357
namespace {
4358
  struct DependentAuto { bool IsPack; };
4359
4360
  /// Substitute the 'auto' specifier or deduced template specialization type
4361
  /// specifier within a type for a given replacement type.
4362
  class SubstituteDeducedTypeTransform :
4363
      public TreeTransform<SubstituteDeducedTypeTransform> {
4364
    QualType Replacement;
4365
    bool ReplacementIsPack;
4366
    bool UseTypeSugar;
4367
4368
  public:
4369
    SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
4370
        : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef), Replacement(),
4371
5.02k
          ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
4372
4373
    SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4374
                                   bool UseTypeSugar = true)
4375
        : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4376
          Replacement(Replacement), ReplacementIsPack(false),
4377
28.7k
          UseTypeSugar(UseTypeSugar) {}
4378
4379
14.1k
    QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4380
14.1k
      assert(isa<TemplateTypeParmType>(Replacement) &&
4381
14.1k
             "unexpected unsugared replacement kind");
4382
14.1k
      QualType Result = Replacement;
4383
14.1k
      TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4384
14.1k
      NewTL.setNameLoc(TL.getNameLoc());
4385
14.1k
      return Result;
4386
14.1k
    }
4387
4388
33.3k
    QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4389
33.3k
      // If we're building the type pattern to deduce against, don't wrap the
4390
33.3k
      // substituted type in an AutoType. Certain template deduction rules
4391
33.3k
      // apply only when a template type parameter appears directly (and not if
4392
33.3k
      // the parameter is found through desugaring). For instance:
4393
33.3k
      //   auto &&lref = lvalue;
4394
33.3k
      // must transform into "rvalue reference to T" not "rvalue reference to
4395
33.3k
      // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
4396
33.3k
      //
4397
33.3k
      // FIXME: Is this still necessary?
4398
33.3k
      if (!UseTypeSugar)
4399
14.1k
        return TransformDesugared(TLB, TL);
4400
19.2k
4401
19.2k
      QualType Result = SemaRef.Context.getAutoType(
4402
19.2k
          Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
4403
19.2k
          ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
4404
19.2k
          TL.getTypePtr()->getTypeConstraintArguments());
4405
19.2k
      auto NewTL = TLB.push<AutoTypeLoc>(Result);
4406
19.2k
      NewTL.copy(TL);
4407
19.2k
      return Result;
4408
19.2k
    }
4409
4410
    QualType TransformDeducedTemplateSpecializationType(
4411
266