Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Sema/SemaTemplateDeduction.cpp
Warning:line 2097, column 31
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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