Bug Summary

File:clang/lib/Sema/SemaTemplateDeduction.cpp
Warning:line 3732, column 31
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateDeduction.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaTemplateDeduction.cpp

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