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-10/lib/clang/10.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-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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-10/lib/clang/10.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-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -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-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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 *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
647 if (NTTP->isExpandedParameterPack())
648 return NTTP->getNumExpansionTypes();
649
650 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param))
651 if (TTP->isExpandedParameterPack())
652 return TTP->getNumExpansionTemplateParameters();
653
654 return None;
655}
656
657/// A pack that we're currently deducing.
658struct clang::DeducedPack {
659 // The index of the pack.
660 unsigned Index;
661
662 // The old value of the pack before we started deducing it.
663 DeducedTemplateArgument Saved;
664
665 // A deferred value of this pack from an inner deduction, that couldn't be
666 // deduced because this deduction hadn't happened yet.
667 DeducedTemplateArgument DeferredDeduction;
668
669 // The new value of the pack.
670 SmallVector<DeducedTemplateArgument, 4> New;
671
672 // The outer deduction for this pack, if any.
673 DeducedPack *Outer = nullptr;
674
675 DeducedPack(unsigned Index) : Index(Index) {}
676};
677
678namespace {
679
680/// A scope in which we're performing pack deduction.
681class PackDeductionScope {
682public:
683 /// Prepare to deduce the packs named within Pattern.
684 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
685 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
686 TemplateDeductionInfo &Info, TemplateArgument Pattern)
687 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
688 unsigned NumNamedPacks = addPacks(Pattern);
689 finishConstruction(NumNamedPacks);
690 }
691
692 /// Prepare to directly deduce arguments of the parameter with index \p Index.
693 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
694 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
695 TemplateDeductionInfo &Info, unsigned Index)
696 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
697 addPack(Index);
698 finishConstruction(1);
699 }
700
701private:
702 void addPack(unsigned Index) {
703 // Save the deduced template argument for the parameter pack expanded
704 // by this pack expansion, then clear out the deduction.
705 DeducedPack Pack(Index);
706 Pack.Saved = Deduced[Index];
707 Deduced[Index] = TemplateArgument();
708
709 // FIXME: What if we encounter multiple packs with different numbers of
710 // pre-expanded expansions? (This should already have been diagnosed
711 // during substitution.)
712 if (Optional<unsigned> ExpandedPackExpansions =
713 getExpandedPackSize(TemplateParams->getParam(Index)))
714 FixedNumExpansions = ExpandedPackExpansions;
715
716 Packs.push_back(Pack);
717 }
718
719 unsigned addPacks(TemplateArgument Pattern) {
720 // Compute the set of template parameter indices that correspond to
721 // parameter packs expanded by the pack expansion.
722 llvm::SmallBitVector SawIndices(TemplateParams->size());
723
724 auto AddPack = [&](unsigned Index) {
725 if (SawIndices[Index])
726 return;
727 SawIndices[Index] = true;
728 addPack(Index);
729 };
730
731 // First look for unexpanded packs in the pattern.
732 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
733 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
734 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
735 unsigned Depth, Index;
736 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
737 if (Depth == Info.getDeducedDepth())
738 AddPack(Index);
739 }
740 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 740, __PRETTY_FUNCTION__))
;
741
742 unsigned NumNamedPacks = Packs.size();
743
744 // We can also have deduced template parameters that do not actually
745 // appear in the pattern, but can be deduced by it (the type of a non-type
746 // template parameter pack, in particular). These won't have prevented us
747 // from partially expanding the pack.
748 llvm::SmallBitVector Used(TemplateParams->size());
749 MarkUsedTemplateParameters(S.Context, Pattern, /*OnlyDeduced*/true,
750 Info.getDeducedDepth(), Used);
751 for (int Index = Used.find_first(); Index != -1;
752 Index = Used.find_next(Index))
753 if (TemplateParams->getParam(Index)->isParameterPack())
754 AddPack(Index);
755
756 return NumNamedPacks;
757 }
758
759 void finishConstruction(unsigned NumNamedPacks) {
760 // Dig out the partially-substituted pack, if there is one.
761 const TemplateArgument *PartialPackArgs = nullptr;
762 unsigned NumPartialPackArgs = 0;
763 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
764 if (auto *Scope = S.CurrentInstantiationScope)
765 if (auto *Partial = Scope->getPartiallySubstitutedPack(
766 &PartialPackArgs, &NumPartialPackArgs))
767 PartialPackDepthIndex = getDepthAndIndex(Partial);
768
769 // This pack expansion will have been partially or fully expanded if
770 // it only names explicitly-specified parameter packs (including the
771 // partially-substituted one, if any).
772 bool IsExpanded = true;
773 for (unsigned I = 0; I != NumNamedPacks; ++I) {
774 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
775 IsExpanded = false;
776 IsPartiallyExpanded = false;
777 break;
778 }
779 if (PartialPackDepthIndex ==
780 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
781 IsPartiallyExpanded = true;
782 }
783 }
784
785 // Skip over the pack elements that were expanded into separate arguments.
786 // If we partially expanded, this is the number of partial arguments.
787 if (IsPartiallyExpanded)
788 PackElements += NumPartialPackArgs;
789 else if (IsExpanded)
790 PackElements += *FixedNumExpansions;
791
792 for (auto &Pack : Packs) {
793 if (Info.PendingDeducedPacks.size() > Pack.Index)
794 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
795 else
796 Info.PendingDeducedPacks.resize(Pack.Index + 1);
797 Info.PendingDeducedPacks[Pack.Index] = &Pack;
798
799 if (PartialPackDepthIndex ==
800 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
801 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
802 // We pre-populate the deduced value of the partially-substituted
803 // pack with the specified value. This is not entirely correct: the
804 // value is supposed to have been substituted, not deduced, but the
805 // cases where this is observable require an exact type match anyway.
806 //
807 // FIXME: If we could represent a "depth i, index j, pack elem k"
808 // parameter, we could substitute the partially-substituted pack
809 // everywhere and avoid this.
810 if (!IsPartiallyExpanded)
811 Deduced[Pack.Index] = Pack.New[PackElements];
812 }
813 }
814 }
815
816public:
817 ~PackDeductionScope() {
818 for (auto &Pack : Packs)
819 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
820 }
821
822 /// Determine whether this pack has already been partially expanded into a
823 /// sequence of (prior) function parameters / template arguments.
824 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
825
826 /// Determine whether this pack expansion scope has a known, fixed arity.
827 /// This happens if it involves a pack from an outer template that has
828 /// (notionally) already been expanded.
829 bool hasFixedArity() { return FixedNumExpansions.hasValue(); }
830
831 /// Determine whether the next element of the argument is still part of this
832 /// pack. This is the case unless the pack is already expanded to a fixed
833 /// length.
834 bool hasNextElement() {
835 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
836 }
837
838 /// Move to deducing the next element in each pack that is being deduced.
839 void nextPackElement() {
840 // Capture the deduced template arguments for each parameter pack expanded
841 // by this pack expansion, add them to the list of arguments we've deduced
842 // for that pack, then clear out the deduced argument.
843 for (auto &Pack : Packs) {
844 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
845 if (!Pack.New.empty() || !DeducedArg.isNull()) {
846 while (Pack.New.size() < PackElements)
847 Pack.New.push_back(DeducedTemplateArgument());
848 if (Pack.New.size() == PackElements)
849 Pack.New.push_back(DeducedArg);
850 else
851 Pack.New[PackElements] = DeducedArg;
852 DeducedArg = Pack.New.size() > PackElements + 1
853 ? Pack.New[PackElements + 1]
854 : DeducedTemplateArgument();
855 }
856 }
857 ++PackElements;
858 }
859
860 /// Finish template argument deduction for a set of argument packs,
861 /// producing the argument packs and checking for consistency with prior
862 /// deductions.
863 Sema::TemplateDeductionResult finish() {
864 // Build argument packs for each of the parameter packs expanded by this
865 // pack expansion.
866 for (auto &Pack : Packs) {
867 // Put back the old value for this pack.
868 Deduced[Pack.Index] = Pack.Saved;
869
870 // Always make sure the size of this pack is correct, even if we didn't
871 // deduce any values for it.
872 //
873 // FIXME: This isn't required by the normative wording, but substitution
874 // and post-substitution checking will always fail if the arity of any
875 // pack is not equal to the number of elements we processed. (Either that
876 // or something else has gone *very* wrong.) We're permitted to skip any
877 // hard errors from those follow-on steps by the intent (but not the
878 // wording) of C++ [temp.inst]p8:
879 //
880 // If the function selected by overload resolution can be determined
881 // without instantiating a class template definition, it is unspecified
882 // whether that instantiation actually takes place
883 Pack.New.resize(PackElements);
884
885 // Build or find a new value for this pack.
886 DeducedTemplateArgument NewPack;
887 if (Pack.New.empty()) {
888 // If we deduced an empty argument pack, create it now.
889 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
890 } else {
891 TemplateArgument *ArgumentPack =
892 new (S.Context) TemplateArgument[Pack.New.size()];
893 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
894 NewPack = DeducedTemplateArgument(
895 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
896 // FIXME: This is wrong, it's possible that some pack elements are
897 // deduced from an array bound and others are not:
898 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
899 // g({1, 2, 3}, {{}, {}});
900 // ... should deduce T = {int, size_t (from array bound)}.
901 Pack.New[0].wasDeducedFromArrayBound());
902 }
903
904 // Pick where we're going to put the merged pack.
905 DeducedTemplateArgument *Loc;
906 if (Pack.Outer) {
907 if (Pack.Outer->DeferredDeduction.isNull()) {
908 // Defer checking this pack until we have a complete pack to compare
909 // it against.
910 Pack.Outer->DeferredDeduction = NewPack;
911 continue;
912 }
913 Loc = &Pack.Outer->DeferredDeduction;
914 } else {
915 Loc = &Deduced[Pack.Index];
916 }
917
918 // Check the new pack matches any previous value.
919 DeducedTemplateArgument OldPack = *Loc;
920 DeducedTemplateArgument Result =
921 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
922
923 // If we deferred a deduction of this pack, check that one now too.
924 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
925 OldPack = Result;
926 NewPack = Pack.DeferredDeduction;
927 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
928 }
929
930 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
931 if (Result.isNull()) {
932 Info.Param = makeTemplateParameter(Param);
933 Info.FirstArg = OldPack;
934 Info.SecondArg = NewPack;
935 return Sema::TDK_Inconsistent;
936 }
937
938 // If we have a pre-expanded pack and we didn't deduce enough elements
939 // for it, fail deduction.
940 if (Optional<unsigned> Expansions = getExpandedPackSize(Param)) {
941 if (*Expansions != PackElements) {
942 Info.Param = makeTemplateParameter(Param);
943 Info.FirstArg = Result;
944 return Sema::TDK_IncompletePack;
945 }
946 }
947
948 *Loc = Result;
949 }
950
951 return Sema::TDK_Success;
952 }
953
954private:
955 Sema &S;
956 TemplateParameterList *TemplateParams;
957 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
958 TemplateDeductionInfo &Info;
959 unsigned PackElements = 0;
960 bool IsPartiallyExpanded = false;
961 /// The number of expansions, if we have a fully-expanded pack in this scope.
962 Optional<unsigned> FixedNumExpansions;
963
964 SmallVector<DeducedPack, 2> Packs;
965};
966
967} // namespace
968
969/// Deduce the template arguments by comparing the list of parameter
970/// types to the list of argument types, as in the parameter-type-lists of
971/// function types (C++ [temp.deduct.type]p10).
972///
973/// \param S The semantic analysis object within which we are deducing
974///
975/// \param TemplateParams The template parameters that we are deducing
976///
977/// \param Params The list of parameter types
978///
979/// \param NumParams The number of types in \c Params
980///
981/// \param Args The list of argument types
982///
983/// \param NumArgs The number of types in \c Args
984///
985/// \param Info information about the template argument deduction itself
986///
987/// \param Deduced the deduced template arguments
988///
989/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
990/// how template argument deduction is performed.
991///
992/// \param PartialOrdering If true, we are performing template argument
993/// deduction for during partial ordering for a call
994/// (C++0x [temp.deduct.partial]).
995///
996/// \returns the result of template argument deduction so far. Note that a
997/// "success" result means that template argument deduction has not yet failed,
998/// but it may still fail, later, for other reasons.
999static Sema::TemplateDeductionResult
1000DeduceTemplateArguments(Sema &S,
1001 TemplateParameterList *TemplateParams,
1002 const QualType *Params, unsigned NumParams,
1003 const QualType *Args, unsigned NumArgs,
1004 TemplateDeductionInfo &Info,
1005 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1006 unsigned TDF,
1007 bool PartialOrdering = false) {
1008 // C++0x [temp.deduct.type]p10:
1009 // Similarly, if P has a form that contains (T), then each parameter type
1010 // Pi of the respective parameter-type- list of P is compared with the
1011 // corresponding parameter type Ai of the corresponding parameter-type-list
1012 // of A. [...]
1013 unsigned ArgIdx = 0, ParamIdx = 0;
1014 for (; ParamIdx != NumParams; ++ParamIdx) {
1015 // Check argument types.
1016 const PackExpansionType *Expansion
1017 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1018 if (!Expansion) {
1019 // Simple case: compare the parameter and argument types at this point.
1020
1021 // Make sure we have an argument.
1022 if (ArgIdx >= NumArgs)
1023 return Sema::TDK_MiscellaneousDeductionFailure;
1024
1025 if (isa<PackExpansionType>(Args[ArgIdx])) {
1026 // C++0x [temp.deduct.type]p22:
1027 // If the original function parameter associated with A is a function
1028 // parameter pack and the function parameter associated with P is not
1029 // a function parameter pack, then template argument deduction fails.
1030 return Sema::TDK_MiscellaneousDeductionFailure;
1031 }
1032
1033 if (Sema::TemplateDeductionResult Result
1034 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1035 Params[ParamIdx], Args[ArgIdx],
1036 Info, Deduced, TDF,
1037 PartialOrdering))
1038 return Result;
1039
1040 ++ArgIdx;
1041 continue;
1042 }
1043
1044 // C++0x [temp.deduct.type]p10:
1045 // If the parameter-declaration corresponding to Pi is a function
1046 // parameter pack, then the type of its declarator- id is compared with
1047 // each remaining parameter type in the parameter-type-list of A. Each
1048 // comparison deduces template arguments for subsequent positions in the
1049 // template parameter packs expanded by the function parameter pack.
1050
1051 QualType Pattern = Expansion->getPattern();
1052 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1053
1054 // A pack scope with fixed arity is not really a pack any more, so is not
1055 // a non-deduced context.
1056 if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
1057 for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
1058 // Deduce template arguments from the pattern.
1059 if (Sema::TemplateDeductionResult Result
1060 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
1061 Args[ArgIdx], Info, Deduced,
1062 TDF, PartialOrdering))
1063 return Result;
1064
1065 PackScope.nextPackElement();
1066 }
1067 } else {
1068 // C++0x [temp.deduct.type]p5:
1069 // The non-deduced contexts are:
1070 // - A function parameter pack that does not occur at the end of the
1071 // parameter-declaration-clause.
1072 //
1073 // FIXME: There is no wording to say what we should do in this case. We
1074 // choose to resolve this by applying the same rule that is applied for a
1075 // function call: that is, deduce all contained packs to their
1076 // explicitly-specified values (or to <> if there is no such value).
1077 //
1078 // This is seemingly-arbitrarily different from the case of a template-id
1079 // with a non-trailing pack-expansion in its arguments, which renders the
1080 // entire template-argument-list a non-deduced context.
1081
1082 // If the parameter type contains an explicitly-specified pack that we
1083 // could not expand, skip the number of parameters notionally created
1084 // by the expansion.
1085 Optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1086 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1087 for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
1088 ++I, ++ArgIdx)
1089 PackScope.nextPackElement();
1090 }
1091 }
1092
1093 // Build argument packs for each of the parameter packs expanded by this
1094 // pack expansion.
1095 if (auto Result = PackScope.finish())
1096 return Result;
1097 }
1098
1099 // Make sure we don't have any extra arguments.
1100 if (ArgIdx < NumArgs)
1101 return Sema::TDK_MiscellaneousDeductionFailure;
1102
1103 return Sema::TDK_Success;
1104}
1105
1106/// Determine whether the parameter has qualifiers that the argument
1107/// lacks. Put another way, determine whether there is no way to add
1108/// a deduced set of qualifiers to the ParamType that would result in
1109/// its qualifiers matching those of the ArgType.
1110static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
1111 QualType ArgType) {
1112 Qualifiers ParamQs = ParamType.getQualifiers();
1113 Qualifiers ArgQs = ArgType.getQualifiers();
1114
1115 if (ParamQs == ArgQs)
1116 return false;
1117
1118 // Mismatched (but not missing) Objective-C GC attributes.
1119 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1120 ParamQs.hasObjCGCAttr())
1121 return true;
1122
1123 // Mismatched (but not missing) address spaces.
1124 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1125 ParamQs.hasAddressSpace())
1126 return true;
1127
1128 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1129 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1130 ParamQs.hasObjCLifetime())
1131 return true;
1132
1133 // CVR qualifiers inconsistent or a superset.
1134 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1135}
1136
1137/// Compare types for equality with respect to possibly compatible
1138/// function types (noreturn adjustment, implicit calling conventions). If any
1139/// of parameter and argument is not a function, just perform type comparison.
1140///
1141/// \param Param the template parameter type.
1142///
1143/// \param Arg the argument type.
1144bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
1145 CanQualType Arg) {
1146 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
1147 *ArgFunction = Arg->getAs<FunctionType>();
1148
1149 // Just compare if not functions.
1150 if (!ParamFunction || !ArgFunction)
1151 return Param == Arg;
1152
1153 // Noreturn and noexcept adjustment.
1154 QualType AdjustedParam;
1155 if (IsFunctionConversion(Param, Arg, AdjustedParam))
1156 return Arg == Context.getCanonicalType(AdjustedParam);
1157
1158 // FIXME: Compatible calling conventions.
1159
1160 return Param == Arg;
1161}
1162
1163/// Get the index of the first template parameter that was originally from the
1164/// innermost template-parameter-list. This is 0 except when we concatenate
1165/// the template parameter lists of a class template and a constructor template
1166/// when forming an implicit deduction guide.
1167static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
1168 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1169 if (!Guide || !Guide->isImplicit())
1170 return 0;
1171 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1172}
1173
1174/// Determine whether a type denotes a forwarding reference.
1175static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1176 // C++1z [temp.deduct.call]p3:
1177 // A forwarding reference is an rvalue reference to a cv-unqualified
1178 // template parameter that does not represent a template parameter of a
1179 // class template.
1180 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1181 if (ParamRef->getPointeeType().getQualifiers())
1182 return false;
1183 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1184 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1185 }
1186 return false;
1187}
1188
1189/// Deduce the template arguments by comparing the parameter type and
1190/// the argument type (C++ [temp.deduct.type]).
1191///
1192/// \param S the semantic analysis object within which we are deducing
1193///
1194/// \param TemplateParams the template parameters that we are deducing
1195///
1196/// \param ParamIn the parameter type
1197///
1198/// \param ArgIn the argument type
1199///
1200/// \param Info information about the template argument deduction itself
1201///
1202/// \param Deduced the deduced template arguments
1203///
1204/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1205/// how template argument deduction is performed.
1206///
1207/// \param PartialOrdering Whether we're performing template argument deduction
1208/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1209///
1210/// \returns the result of template argument deduction so far. Note that a
1211/// "success" result means that template argument deduction has not yet failed,
1212/// but it may still fail, later, for other reasons.
1213static Sema::TemplateDeductionResult
1214DeduceTemplateArgumentsByTypeMatch(Sema &S,
1215 TemplateParameterList *TemplateParams,
1216 QualType ParamIn, QualType ArgIn,
1217 TemplateDeductionInfo &Info,
1218 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1219 unsigned TDF,
1220 bool PartialOrdering,
1221 bool DeducedFromArrayBound) {
1222 // We only want to look at the canonical types, since typedefs and
1223 // sugar are not part of template argument deduction.
1224 QualType Param = S.Context.getCanonicalType(ParamIn);
1225 QualType Arg = S.Context.getCanonicalType(ArgIn);
1226
1227 // If the argument type is a pack expansion, look at its pattern.
1228 // This isn't explicitly called out
1229 if (const PackExpansionType *ArgExpansion
1230 = dyn_cast<PackExpansionType>(Arg))
1231 Arg = ArgExpansion->getPattern();
1232
1233 if (PartialOrdering) {
1234 // C++11 [temp.deduct.partial]p5:
1235 // Before the partial ordering is done, certain transformations are
1236 // performed on the types used for partial ordering:
1237 // - If P is a reference type, P is replaced by the type referred to.
1238 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1239 if (ParamRef)
1240 Param = ParamRef->getPointeeType();
1241
1242 // - If A is a reference type, A is replaced by the type referred to.
1243 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1244 if (ArgRef)
1245 Arg = ArgRef->getPointeeType();
1246
1247 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1248 // C++11 [temp.deduct.partial]p9:
1249 // If, for a given type, deduction succeeds in both directions (i.e.,
1250 // the types are identical after the transformations above) and both
1251 // P and A were reference types [...]:
1252 // - if [one type] was an lvalue reference and [the other type] was
1253 // not, [the other type] is not considered to be at least as
1254 // specialized as [the first type]
1255 // - if [one type] is more cv-qualified than [the other type],
1256 // [the other type] is not considered to be at least as specialized
1257 // as [the first type]
1258 // Objective-C ARC adds:
1259 // - [one type] has non-trivial lifetime, [the other type] has
1260 // __unsafe_unretained lifetime, and the types are otherwise
1261 // identical
1262 //
1263 // A is "considered to be at least as specialized" as P iff deduction
1264 // succeeds, so we model this as a deduction failure. Note that
1265 // [the first type] is P and [the other type] is A here; the standard
1266 // gets this backwards.
1267 Qualifiers ParamQuals = Param.getQualifiers();
1268 Qualifiers ArgQuals = Arg.getQualifiers();
1269 if ((ParamRef->isLValueReferenceType() &&
1270 !ArgRef->isLValueReferenceType()) ||
1271 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1272 (ParamQuals.hasNonTrivialObjCLifetime() &&
1273 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1274 ParamQuals.withoutObjCLifetime() ==
1275 ArgQuals.withoutObjCLifetime())) {
1276 Info.FirstArg = TemplateArgument(ParamIn);
1277 Info.SecondArg = TemplateArgument(ArgIn);
1278 return Sema::TDK_NonDeducedMismatch;
1279 }
1280 }
1281
1282 // C++11 [temp.deduct.partial]p7:
1283 // Remove any top-level cv-qualifiers:
1284 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1285 // version of P.
1286 Param = Param.getUnqualifiedType();
1287 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1288 // version of A.
1289 Arg = Arg.getUnqualifiedType();
1290 } else {
1291 // C++0x [temp.deduct.call]p4 bullet 1:
1292 // - If the original P is a reference type, the deduced A (i.e., the type
1293 // referred to by the reference) can be more cv-qualified than the
1294 // transformed A.
1295 if (TDF & TDF_ParamWithReferenceType) {
1296 Qualifiers Quals;
1297 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1298 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
1299 Arg.getCVRQualifiers());
1300 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1301 }
1302
1303 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1304 // C++0x [temp.deduct.type]p10:
1305 // If P and A are function types that originated from deduction when
1306 // taking the address of a function template (14.8.2.2) or when deducing
1307 // template arguments from a function declaration (14.8.2.6) and Pi and
1308 // Ai are parameters of the top-level parameter-type-list of P and A,
1309 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1310 // is an lvalue reference, in
1311 // which case the type of Pi is changed to be the template parameter
1312 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1313 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1314 // deduced as X&. - end note ]
1315 TDF &= ~TDF_TopLevelParameterTypeList;
1316 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1317 Param = Param->getPointeeType();
1318 }
1319 }
1320
1321 // C++ [temp.deduct.type]p9:
1322 // A template type argument T, a template template argument TT or a
1323 // template non-type argument i can be deduced if P and A have one of
1324 // the following forms:
1325 //
1326 // T
1327 // cv-list T
1328 if (const TemplateTypeParmType *TemplateTypeParm
1329 = Param->getAs<TemplateTypeParmType>()) {
1330 // Just skip any attempts to deduce from a placeholder type or a parameter
1331 // at a different depth.
1332 if (Arg->isPlaceholderType() ||
1333 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
1334 return Sema::TDK_Success;
1335
1336 unsigned Index = TemplateTypeParm->getIndex();
1337 bool RecanonicalizeArg = false;
1338
1339 // If the argument type is an array type, move the qualifiers up to the
1340 // top level, so they can be matched with the qualifiers on the parameter.
1341 if (isa<ArrayType>(Arg)) {
1342 Qualifiers Quals;
1343 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1344 if (Quals) {
1345 Arg = S.Context.getQualifiedType(Arg, Quals);
1346 RecanonicalizeArg = true;
1347 }
1348 }
1349
1350 // The argument type can not be less qualified than the parameter
1351 // type.
1352 if (!(TDF & TDF_IgnoreQualifiers) &&
1353 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
1354 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1355 Info.FirstArg = TemplateArgument(Param);
1356 Info.SecondArg = TemplateArgument(Arg);
1357 return Sema::TDK_Underqualified;
1358 }
1359
1360 // Do not match a function type with a cv-qualified type.
1361 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1362 if (Arg->isFunctionType() && Param.hasQualifiers()) {
1363 return Sema::TDK_NonDeducedMismatch;
1364 }
1365
1366 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1367, __PRETTY_FUNCTION__))
1367 "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1367, __PRETTY_FUNCTION__))
;
1368 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1368, __PRETTY_FUNCTION__))
;
1369 QualType DeducedType = Arg;
1370
1371 // Remove any qualifiers on the parameter from the deduced type.
1372 // We checked the qualifiers for consistency above.
1373 Qualifiers DeducedQs = DeducedType.getQualifiers();
1374 Qualifiers ParamQs = Param.getQualifiers();
1375 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1376 if (ParamQs.hasObjCGCAttr())
1377 DeducedQs.removeObjCGCAttr();
1378 if (ParamQs.hasAddressSpace())
1379 DeducedQs.removeAddressSpace();
1380 if (ParamQs.hasObjCLifetime())
1381 DeducedQs.removeObjCLifetime();
1382
1383 // Objective-C ARC:
1384 // If template deduction would produce a lifetime qualifier on a type
1385 // that is not a lifetime type, template argument deduction fails.
1386 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1387 !DeducedType->isDependentType()) {
1388 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1389 Info.FirstArg = TemplateArgument(Param);
1390 Info.SecondArg = TemplateArgument(Arg);
1391 return Sema::TDK_Underqualified;
1392 }
1393
1394 // Objective-C ARC:
1395 // If template deduction would produce an argument type with lifetime type
1396 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1397 if (S.getLangOpts().ObjCAutoRefCount &&
1398 DeducedType->isObjCLifetimeType() &&
1399 !DeducedQs.hasObjCLifetime())
1400 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1401
1402 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1403 DeducedQs);
1404
1405 if (RecanonicalizeArg)
1406 DeducedType = S.Context.getCanonicalType(DeducedType);
1407
1408 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1409 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
1410 Deduced[Index],
1411 NewDeduced);
1412 if (Result.isNull()) {
1413 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1414 Info.FirstArg = Deduced[Index];
1415 Info.SecondArg = NewDeduced;
1416 return Sema::TDK_Inconsistent;
1417 }
1418
1419 Deduced[Index] = Result;
1420 return Sema::TDK_Success;
1421 }
1422
1423 // Set up the template argument deduction information for a failure.
1424 Info.FirstArg = TemplateArgument(ParamIn);
1425 Info.SecondArg = TemplateArgument(ArgIn);
1426
1427 // If the parameter is an already-substituted template parameter
1428 // pack, do nothing: we don't know which of its arguments to look
1429 // at, so we have to wait until all of the parameter packs in this
1430 // expansion have arguments.
1431 if (isa<SubstTemplateTypeParmPackType>(Param))
1432 return Sema::TDK_Success;
1433
1434 // Check the cv-qualifiers on the parameter and argument types.
1435 CanQualType CanParam = S.Context.getCanonicalType(Param);
1436 CanQualType CanArg = S.Context.getCanonicalType(Arg);
1437 if (!(TDF & TDF_IgnoreQualifiers)) {
1438 if (TDF & TDF_ParamWithReferenceType) {
1439 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
1440 return Sema::TDK_NonDeducedMismatch;
1441 } else if (TDF & TDF_ArgWithReferenceType) {
1442 // C++ [temp.deduct.conv]p4:
1443 // If the original A is a reference type, A can be more cv-qualified
1444 // than the deduced A
1445 if (!Arg.getQualifiers().compatiblyIncludes(Param.getQualifiers()))
1446 return Sema::TDK_NonDeducedMismatch;
1447
1448 // Strip out all extra qualifiers from the argument to figure out the
1449 // type we're converting to, prior to the qualification conversion.
1450 Qualifiers Quals;
1451 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1452 Arg = S.Context.getQualifiedType(Arg, Param.getQualifiers());
1453 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
1454 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
1455 return Sema::TDK_NonDeducedMismatch;
1456 }
1457
1458 // If the parameter type is not dependent, there is nothing to deduce.
1459 if (!Param->isDependentType()) {
1460 if (!(TDF & TDF_SkipNonDependent)) {
1461 bool NonDeduced =
1462 (TDF & TDF_AllowCompatibleFunctionType)
1463 ? !S.isSameOrCompatibleFunctionType(CanParam, CanArg)
1464 : Param != Arg;
1465 if (NonDeduced) {
1466 return Sema::TDK_NonDeducedMismatch;
1467 }
1468 }
1469 return Sema::TDK_Success;
1470 }
1471 } else if (!Param->isDependentType()) {
1472 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1473 ArgUnqualType = CanArg.getUnqualifiedType();
1474 bool Success =
1475 (TDF & TDF_AllowCompatibleFunctionType)
1476 ? S.isSameOrCompatibleFunctionType(ParamUnqualType, ArgUnqualType)
1477 : ParamUnqualType == ArgUnqualType;
1478 if (Success)
1479 return Sema::TDK_Success;
1480 }
1481
1482 switch (Param->getTypeClass()) {
1483 // Non-canonical types cannot appear here.
1484#define NON_CANONICAL_TYPE(Class, Base) \
1485 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class)::llvm::llvm_unreachable_internal("deducing non-canonical type: "
#Class, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1485)
;
1486#define TYPE(Class, Base)
1487#include "clang/AST/TypeNodes.inc"
1488
1489 case Type::TemplateTypeParm:
1490 case Type::SubstTemplateTypeParmPack:
1491 llvm_unreachable("Type nodes handled above")::llvm::llvm_unreachable_internal("Type nodes handled above",
"/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1491)
;
1492
1493 // These types cannot be dependent, so simply check whether the types are
1494 // the same.
1495 case Type::Builtin:
1496 case Type::VariableArray:
1497 case Type::Vector:
1498 case Type::FunctionNoProto:
1499 case Type::Record:
1500 case Type::Enum:
1501 case Type::ObjCObject:
1502 case Type::ObjCInterface:
1503 case Type::ObjCObjectPointer:
1504 if (TDF & TDF_SkipNonDependent)
1505 return Sema::TDK_Success;
1506
1507 if (TDF & TDF_IgnoreQualifiers) {
1508 Param = Param.getUnqualifiedType();
1509 Arg = Arg.getUnqualifiedType();
1510 }
1511
1512 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1513
1514 // _Complex T [placeholder extension]
1515 case Type::Complex:
1516 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
1517 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1518 cast<ComplexType>(Param)->getElementType(),
1519 ComplexArg->getElementType(),
1520 Info, Deduced, TDF);
1521
1522 return Sema::TDK_NonDeducedMismatch;
1523
1524 // _Atomic T [extension]
1525 case Type::Atomic:
1526 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
1527 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1528 cast<AtomicType>(Param)->getValueType(),
1529 AtomicArg->getValueType(),
1530 Info, Deduced, TDF);
1531
1532 return Sema::TDK_NonDeducedMismatch;
1533
1534 // T *
1535 case Type::Pointer: {
1536 QualType PointeeType;
1537 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1538 PointeeType = PointerArg->getPointeeType();
1539 } else if (const ObjCObjectPointerType *PointerArg
1540 = Arg->getAs<ObjCObjectPointerType>()) {
1541 PointeeType = PointerArg->getPointeeType();
1542 } else {
1543 return Sema::TDK_NonDeducedMismatch;
1544 }
1545
1546 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
1547 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1548 cast<PointerType>(Param)->getPointeeType(),
1549 PointeeType,
1550 Info, Deduced, SubTDF);
1551 }
1552
1553 // T &
1554 case Type::LValueReference: {
1555 const LValueReferenceType *ReferenceArg =
1556 Arg->getAs<LValueReferenceType>();
1557 if (!ReferenceArg)
1558 return Sema::TDK_NonDeducedMismatch;
1559
1560 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1561 cast<LValueReferenceType>(Param)->getPointeeType(),
1562 ReferenceArg->getPointeeType(), Info, Deduced, 0);
1563 }
1564
1565 // T && [C++0x]
1566 case Type::RValueReference: {
1567 const RValueReferenceType *ReferenceArg =
1568 Arg->getAs<RValueReferenceType>();
1569 if (!ReferenceArg)
1570 return Sema::TDK_NonDeducedMismatch;
1571
1572 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1573 cast<RValueReferenceType>(Param)->getPointeeType(),
1574 ReferenceArg->getPointeeType(),
1575 Info, Deduced, 0);
1576 }
1577
1578 // T [] (implied, but not stated explicitly)
1579 case Type::IncompleteArray: {
1580 const IncompleteArrayType *IncompleteArrayArg =
1581 S.Context.getAsIncompleteArrayType(Arg);
1582 if (!IncompleteArrayArg)
1583 return Sema::TDK_NonDeducedMismatch;
1584
1585 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1586 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1587 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1588 IncompleteArrayArg->getElementType(),
1589 Info, Deduced, SubTDF);
1590 }
1591
1592 // T [integer-constant]
1593 case Type::ConstantArray: {
1594 const ConstantArrayType *ConstantArrayArg =
1595 S.Context.getAsConstantArrayType(Arg);
1596 if (!ConstantArrayArg)
1597 return Sema::TDK_NonDeducedMismatch;
1598
1599 const ConstantArrayType *ConstantArrayParm =
1600 S.Context.getAsConstantArrayType(Param);
1601 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
1602 return Sema::TDK_NonDeducedMismatch;
1603
1604 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1605 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1606 ConstantArrayParm->getElementType(),
1607 ConstantArrayArg->getElementType(),
1608 Info, Deduced, SubTDF);
1609 }
1610
1611 // type [i]
1612 case Type::DependentSizedArray: {
1613 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
1614 if (!ArrayArg)
1615 return Sema::TDK_NonDeducedMismatch;
1616
1617 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1618
1619 // Check the element type of the arrays
1620 const DependentSizedArrayType *DependentArrayParm
1621 = S.Context.getAsDependentSizedArrayType(Param);
1622 if (Sema::TemplateDeductionResult Result
1623 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1624 DependentArrayParm->getElementType(),
1625 ArrayArg->getElementType(),
1626 Info, Deduced, SubTDF))
1627 return Result;
1628
1629 // Determine the array bound is something we can deduce.
1630 NonTypeTemplateParmDecl *NTTP
1631 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
1632 if (!NTTP)
1633 return Sema::TDK_Success;
1634
1635 // We can perform template argument deduction for the given non-type
1636 // template parameter.
1637 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1638, __PRETTY_FUNCTION__))
1638 "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1638, __PRETTY_FUNCTION__))
;
1639 if (const ConstantArrayType *ConstantArrayArg
1640 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1641 llvm::APSInt Size(ConstantArrayArg->getSize());
1642 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
1643 S.Context.getSizeType(),
1644 /*ArrayBound=*/true,
1645 Info, Deduced);
1646 }
1647 if (const DependentSizedArrayType *DependentArrayArg
1648 = dyn_cast<DependentSizedArrayType>(ArrayArg))
1649 if (DependentArrayArg->getSizeExpr())
1650 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1651 DependentArrayArg->getSizeExpr(),
1652 Info, Deduced);
1653
1654 // Incomplete type does not match a dependently-sized array type
1655 return Sema::TDK_NonDeducedMismatch;
1656 }
1657
1658 // type(*)(T)
1659 // T(*)()
1660 // T(*)(T)
1661 case Type::FunctionProto: {
1662 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
1663 const FunctionProtoType *FunctionProtoArg =
1664 dyn_cast<FunctionProtoType>(Arg);
1665 if (!FunctionProtoArg)
1666 return Sema::TDK_NonDeducedMismatch;
1667
1668 const FunctionProtoType *FunctionProtoParam =
1669 cast<FunctionProtoType>(Param);
1670
1671 if (FunctionProtoParam->getMethodQuals()
1672 != FunctionProtoArg->getMethodQuals() ||
1673 FunctionProtoParam->getRefQualifier()
1674 != FunctionProtoArg->getRefQualifier() ||
1675 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
1676 return Sema::TDK_NonDeducedMismatch;
1677
1678 // Check return types.
1679 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1680 S, TemplateParams, FunctionProtoParam->getReturnType(),
1681 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
1682 return Result;
1683
1684 // Check parameter types.
1685 if (auto Result = DeduceTemplateArguments(
1686 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1687 FunctionProtoParam->getNumParams(),
1688 FunctionProtoArg->param_type_begin(),
1689 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF))
1690 return Result;
1691
1692 if (TDF & TDF_AllowCompatibleFunctionType)
1693 return Sema::TDK_Success;
1694
1695 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1696 // deducing through the noexcept-specifier if it's part of the canonical
1697 // type. libstdc++ relies on this.
1698 Expr *NoexceptExpr = FunctionProtoParam->getNoexceptExpr();
1699 if (NonTypeTemplateParmDecl *NTTP =
1700 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1701 : nullptr) {
1702 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1703, __PRETTY_FUNCTION__))
1703 "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1703, __PRETTY_FUNCTION__))
;
1704
1705 llvm::APSInt Noexcept(1);
1706 switch (FunctionProtoArg->canThrow()) {
1707 case CT_Cannot:
1708 Noexcept = 1;
1709 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1710
1711 case CT_Can:
1712 // We give E in noexcept(E) the "deduced from array bound" treatment.
1713 // FIXME: Should we?
1714 return DeduceNonTypeTemplateArgument(
1715 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1716 /*ArrayBound*/true, Info, Deduced);
1717
1718 case CT_Dependent:
1719 if (Expr *ArgNoexceptExpr = FunctionProtoArg->getNoexceptExpr())
1720 return DeduceNonTypeTemplateArgument(
1721 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1722 // Can't deduce anything from throw(T...).
1723 break;
1724 }
1725 }
1726 // FIXME: Detect non-deduced exception specification mismatches?
1727 //
1728 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
1729 // top-level differences in noexcept-specifications.
1730
1731 return Sema::TDK_Success;
1732 }
1733
1734 case Type::InjectedClassName:
1735 // Treat a template's injected-class-name as if the template
1736 // specialization type had been used.
1737 Param = cast<InjectedClassNameType>(Param)
1738 ->getInjectedSpecializationType();
1739 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1740, __PRETTY_FUNCTION__))
1740 "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1740, __PRETTY_FUNCTION__))
;
1741 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1742
1743 // template-name<T> (where template-name refers to a class template)
1744 // template-name<i>
1745 // TT<T>
1746 // TT<i>
1747 // TT<>
1748 case Type::TemplateSpecialization: {
1749 const TemplateSpecializationType *SpecParam =
1750 cast<TemplateSpecializationType>(Param);
1751
1752 // When Arg cannot be a derived class, we can just try to deduce template
1753 // arguments from the template-id.
1754 const RecordType *RecordT = Arg->getAs<RecordType>();
1755 if (!(TDF & TDF_DerivedClass) || !RecordT)
1756 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1757 Deduced);
1758
1759 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1760 Deduced.end());
1761
1762 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1763 S, TemplateParams, SpecParam, Arg, Info, Deduced);
1764
1765 if (Result == Sema::TDK_Success)
1766 return Result;
1767
1768 // We cannot inspect base classes as part of deduction when the type
1769 // is incomplete, so either instantiate any templates necessary to
1770 // complete the type, or skip over it if it cannot be completed.
1771 if (!S.isCompleteType(Info.getLocation(), Arg))
1772 return Result;
1773
1774 // C++14 [temp.deduct.call] p4b3:
1775 // If P is a class and P has the form simple-template-id, then the
1776 // transformed A can be a derived class of the deduced A. Likewise if
1777 // P is a pointer to a class of the form simple-template-id, the
1778 // transformed A can be a pointer to a derived class pointed to by the
1779 // deduced A.
1780 //
1781 // These alternatives are considered only if type deduction would
1782 // otherwise fail. If they yield more than one possible deduced A, the
1783 // type deduction fails.
1784
1785 // Reset the incorrectly deduced argument from above.
1786 Deduced = DeducedOrig;
1787
1788 // Use data recursion to crawl through the list of base classes.
1789 // Visited contains the set of nodes we have already visited, while
1790 // ToVisit is our stack of records that we still need to visit.
1791 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1792 SmallVector<const RecordType *, 8> ToVisit;
1793 ToVisit.push_back(RecordT);
1794 bool Successful = false;
1795 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
1796 while (!ToVisit.empty()) {
1797 // Retrieve the next class in the inheritance hierarchy.
1798 const RecordType *NextT = ToVisit.pop_back_val();
1799
1800 // If we have already seen this type, skip it.
1801 if (!Visited.insert(NextT).second)
1802 continue;
1803
1804 // If this is a base class, try to perform template argument
1805 // deduction from it.
1806 if (NextT != RecordT) {
1807 TemplateDeductionInfo BaseInfo(Info.getLocation());
1808 Sema::TemplateDeductionResult BaseResult =
1809 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1810 QualType(NextT, 0), BaseInfo, Deduced);
1811
1812 // If template argument deduction for this base was successful,
1813 // note that we had some success. Otherwise, ignore any deductions
1814 // from this base class.
1815 if (BaseResult == Sema::TDK_Success) {
1816 // If we've already seen some success, then deduction fails due to
1817 // an ambiguity (temp.deduct.call p5).
1818 if (Successful)
1819 return Sema::TDK_MiscellaneousDeductionFailure;
1820
1821 Successful = true;
1822 std::swap(SuccessfulDeduced, Deduced);
1823
1824 Info.Param = BaseInfo.Param;
1825 Info.FirstArg = BaseInfo.FirstArg;
1826 Info.SecondArg = BaseInfo.SecondArg;
1827 }
1828
1829 Deduced = DeducedOrig;
1830 }
1831
1832 // Visit base classes
1833 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1834 for (const auto &Base : Next->bases()) {
1835 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1836, __PRETTY_FUNCTION__))
1836 "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1836, __PRETTY_FUNCTION__))
;
1837 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1838 }
1839 }
1840
1841 if (Successful) {
1842 std::swap(SuccessfulDeduced, Deduced);
1843 return Sema::TDK_Success;
1844 }
1845
1846 return Result;
1847 }
1848
1849 // T type::*
1850 // T T::*
1851 // T (type::*)()
1852 // type (T::*)()
1853 // type (type::*)(T)
1854 // type (T::*)(T)
1855 // T (type::*)(T)
1856 // T (T::*)()
1857 // T (T::*)(T)
1858 case Type::MemberPointer: {
1859 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1860 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1861 if (!MemPtrArg)
1862 return Sema::TDK_NonDeducedMismatch;
1863
1864 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1865 if (ParamPointeeType->isFunctionType())
1866 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1867 /*IsCtorOrDtor=*/false, Info.getLocation());
1868 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1869 if (ArgPointeeType->isFunctionType())
1870 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1871 /*IsCtorOrDtor=*/false, Info.getLocation());
1872
1873 if (Sema::TemplateDeductionResult Result
1874 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1875 ParamPointeeType,
1876 ArgPointeeType,
1877 Info, Deduced,
1878 TDF & TDF_IgnoreQualifiers))
1879 return Result;
1880
1881 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1882 QualType(MemPtrParam->getClass(), 0),
1883 QualType(MemPtrArg->getClass(), 0),
1884 Info, Deduced,
1885 TDF & TDF_IgnoreQualifiers);
1886 }
1887
1888 // (clang extension)
1889 //
1890 // type(^)(T)
1891 // T(^)()
1892 // T(^)(T)
1893 case Type::BlockPointer: {
1894 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1895 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
1896
1897 if (!BlockPtrArg)
1898 return Sema::TDK_NonDeducedMismatch;
1899
1900 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1901 BlockPtrParam->getPointeeType(),
1902 BlockPtrArg->getPointeeType(),
1903 Info, Deduced, 0);
1904 }
1905
1906 // (clang extension)
1907 //
1908 // T __attribute__(((ext_vector_type(<integral constant>))))
1909 case Type::ExtVector: {
1910 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1911 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1912 // Make sure that the vectors have the same number of elements.
1913 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1914 return Sema::TDK_NonDeducedMismatch;
1915
1916 // Perform deduction on the element types.
1917 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1918 VectorParam->getElementType(),
1919 VectorArg->getElementType(),
1920 Info, Deduced, TDF);
1921 }
1922
1923 if (const DependentSizedExtVectorType *VectorArg
1924 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1925 // We can't check the number of elements, since the argument has a
1926 // dependent number of elements. This can only occur during partial
1927 // ordering.
1928
1929 // Perform deduction on the element types.
1930 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1931 VectorParam->getElementType(),
1932 VectorArg->getElementType(),
1933 Info, Deduced, TDF);
1934 }
1935
1936 return Sema::TDK_NonDeducedMismatch;
1937 }
1938
1939 case Type::DependentVector: {
1940 const auto *VectorParam = cast<DependentVectorType>(Param);
1941
1942 if (const auto *VectorArg = dyn_cast<VectorType>(Arg)) {
1943 // Perform deduction on the element types.
1944 if (Sema::TemplateDeductionResult Result =
1945 DeduceTemplateArgumentsByTypeMatch(
1946 S, TemplateParams, VectorParam->getElementType(),
1947 VectorArg->getElementType(), Info, Deduced, TDF))
1948 return Result;
1949
1950 // Perform deduction on the vector size, if we can.
1951 NonTypeTemplateParmDecl *NTTP =
1952 getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
1953 if (!NTTP)
1954 return Sema::TDK_Success;
1955
1956 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1957 ArgSize = VectorArg->getNumElements();
1958 // Note that we use the "array bound" rules here; just like in that
1959 // case, we don't have any particular type for the vector size, but
1960 // we can provide one if necessary.
1961 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
1962 S.Context.UnsignedIntTy, true,
1963 Info, Deduced);
1964 }
1965
1966 if (const auto *VectorArg = dyn_cast<DependentVectorType>(Arg)) {
1967 // Perform deduction on the element types.
1968 if (Sema::TemplateDeductionResult Result =
1969 DeduceTemplateArgumentsByTypeMatch(
1970 S, TemplateParams, VectorParam->getElementType(),
1971 VectorArg->getElementType(), Info, Deduced, TDF))
1972 return Result;
1973
1974 // Perform deduction on the vector size, if we can.
1975 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
1976 Info, VectorParam->getSizeExpr());
1977 if (!NTTP)
1978 return Sema::TDK_Success;
1979
1980 return DeduceNonTypeTemplateArgument(
1981 S, TemplateParams, NTTP, VectorArg->getSizeExpr(), Info, Deduced);
1982 }
1983
1984 return Sema::TDK_NonDeducedMismatch;
1985 }
1986
1987 // (clang extension)
1988 //
1989 // T __attribute__(((ext_vector_type(N))))
1990 case Type::DependentSizedExtVector: {
1991 const DependentSizedExtVectorType *VectorParam
1992 = cast<DependentSizedExtVectorType>(Param);
1993
1994 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1995 // Perform deduction on the element types.
1996 if (Sema::TemplateDeductionResult Result
1997 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1998 VectorParam->getElementType(),
1999 VectorArg->getElementType(),
2000 Info, Deduced, TDF))
2001 return Result;
2002
2003 // Perform deduction on the vector size, if we can.
2004 NonTypeTemplateParmDecl *NTTP
2005 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
2006 if (!NTTP)
2007 return Sema::TDK_Success;
2008
2009 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2010 ArgSize = VectorArg->getNumElements();
2011 // Note that we use the "array bound" rules here; just like in that
2012 // case, we don't have any particular type for the vector size, but
2013 // we can provide one if necessary.
2014 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2015 S.Context.IntTy, true, Info,
2016 Deduced);
2017 }
2018
2019 if (const DependentSizedExtVectorType *VectorArg
2020 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
2021 // Perform deduction on the element types.
2022 if (Sema::TemplateDeductionResult Result
2023 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2024 VectorParam->getElementType(),
2025 VectorArg->getElementType(),
2026 Info, Deduced, TDF))
2027 return Result;
2028
2029 // Perform deduction on the vector size, if we can.
2030 NonTypeTemplateParmDecl *NTTP
2031 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
2032 if (!NTTP)
2033 return Sema::TDK_Success;
2034
2035 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2036 VectorArg->getSizeExpr(),
2037 Info, Deduced);
2038 }
2039
2040 return Sema::TDK_NonDeducedMismatch;
2041 }
2042
2043 // (clang extension)
2044 //
2045 // T __attribute__(((address_space(N))))
2046 case Type::DependentAddressSpace: {
2047 const DependentAddressSpaceType *AddressSpaceParam =
2048 cast<DependentAddressSpaceType>(Param);
2049
2050 if (const DependentAddressSpaceType *AddressSpaceArg =
2051 dyn_cast<DependentAddressSpaceType>(Arg)) {
2052 // Perform deduction on the pointer type.
2053 if (Sema::TemplateDeductionResult Result =
2054 DeduceTemplateArgumentsByTypeMatch(
2055 S, TemplateParams, AddressSpaceParam->getPointeeType(),
2056 AddressSpaceArg->getPointeeType(), Info, Deduced, TDF))
2057 return Result;
2058
2059 // Perform deduction on the address space, if we can.
2060 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2061 Info, AddressSpaceParam->getAddrSpaceExpr());
2062 if (!NTTP)
2063 return Sema::TDK_Success;
2064
2065 return DeduceNonTypeTemplateArgument(
2066 S, TemplateParams, NTTP, AddressSpaceArg->getAddrSpaceExpr(), Info,
2067 Deduced);
2068 }
2069
2070 if (isTargetAddressSpace(Arg.getAddressSpace())) {
2071 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2072 false);
2073 ArgAddressSpace = toTargetAddressSpace(Arg.getAddressSpace());
2074
2075 // Perform deduction on the pointer types.
2076 if (Sema::TemplateDeductionResult Result =
2077 DeduceTemplateArgumentsByTypeMatch(
2078 S, TemplateParams, AddressSpaceParam->getPointeeType(),
2079 S.Context.removeAddrSpaceQualType(Arg), Info, Deduced, TDF))
2080 return Result;
2081
2082 // Perform deduction on the address space, if we can.
2083 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2084 Info, AddressSpaceParam->getAddrSpaceExpr());
2085 if (!NTTP)
2086 return Sema::TDK_Success;
2087
2088 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2089 ArgAddressSpace, S.Context.IntTy,
2090 true, Info, Deduced);
2091 }
2092
2093 return Sema::TDK_NonDeducedMismatch;
2094 }
2095
2096 case Type::TypeOfExpr:
2097 case Type::TypeOf:
2098 case Type::DependentName:
2099 case Type::UnresolvedUsing:
2100 case Type::Decltype:
2101 case Type::UnaryTransform:
2102 case Type::Auto:
2103 case Type::DeducedTemplateSpecialization:
2104 case Type::DependentTemplateSpecialization:
2105 case Type::PackExpansion:
2106 case Type::Pipe:
2107 // No template argument deduction for these types
2108 return Sema::TDK_Success;
2109 }
2110
2111 llvm_unreachable("Invalid Type Class!")::llvm::llvm_unreachable_internal("Invalid Type Class!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2111)
;
2112}
2113
2114static Sema::TemplateDeductionResult
2115DeduceTemplateArguments(Sema &S,
2116 TemplateParameterList *TemplateParams,
2117 const TemplateArgument &Param,
2118 TemplateArgument Arg,
2119 TemplateDeductionInfo &Info,
2120 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
2121 // If the template argument is a pack expansion, perform template argument
2122 // deduction against the pattern of that expansion. This only occurs during
2123 // partial ordering.
2124 if (Arg.isPackExpansion())
2125 Arg = Arg.getPackExpansionPattern();
2126
2127 switch (Param.getKind()) {
2128 case TemplateArgument::Null:
2129 llvm_unreachable("Null template argument in parameter list")::llvm::llvm_unreachable_internal("Null template argument in parameter list"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2129)
;
2130
2131 case TemplateArgument::Type:
2132 if (Arg.getKind() == TemplateArgument::Type)
2133 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2134 Param.getAsType(),
2135 Arg.getAsType(),
2136 Info, Deduced, 0);
2137 Info.FirstArg = Param;
2138 Info.SecondArg = Arg;
2139 return Sema::TDK_NonDeducedMismatch;
2140
2141 case TemplateArgument::Template:
2142 if (Arg.getKind() == TemplateArgument::Template)
2143 return DeduceTemplateArguments(S, TemplateParams,
2144 Param.getAsTemplate(),
2145 Arg.getAsTemplate(), Info, Deduced);
2146 Info.FirstArg = Param;
2147 Info.SecondArg = Arg;
2148 return Sema::TDK_NonDeducedMismatch;
2149
2150 case TemplateArgument::TemplateExpansion:
2151 llvm_unreachable("caller should handle pack expansions")::llvm::llvm_unreachable_internal("caller should handle pack expansions"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2151)
;
2152
2153 case TemplateArgument::Declaration:
2154 if (Arg.getKind() == TemplateArgument::Declaration &&
2155 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
2156 return Sema::TDK_Success;
2157
2158 Info.FirstArg = Param;
2159 Info.SecondArg = Arg;
2160 return Sema::TDK_NonDeducedMismatch;
2161
2162 case TemplateArgument::NullPtr:
2163 if (Arg.getKind() == TemplateArgument::NullPtr &&
2164 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
2165 return Sema::TDK_Success;
2166
2167 Info.FirstArg = Param;
2168 Info.SecondArg = Arg;
2169 return Sema::TDK_NonDeducedMismatch;
2170
2171 case TemplateArgument::Integral:
2172 if (Arg.getKind() == TemplateArgument::Integral) {
2173 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
2174 return Sema::TDK_Success;
2175
2176 Info.FirstArg = Param;
2177 Info.SecondArg = Arg;
2178 return Sema::TDK_NonDeducedMismatch;
2179 }
2180
2181 if (Arg.getKind() == TemplateArgument::Expression) {
2182 Info.FirstArg = Param;
2183 Info.SecondArg = Arg;
2184 return Sema::TDK_NonDeducedMismatch;
2185 }
2186
2187 Info.FirstArg = Param;
2188 Info.SecondArg = Arg;
2189 return Sema::TDK_NonDeducedMismatch;
2190
2191 case TemplateArgument::Expression:
2192 if (NonTypeTemplateParmDecl *NTTP
2193 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
2194 if (Arg.getKind() == TemplateArgument::Integral)
2195 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2196 Arg.getAsIntegral(),
2197 Arg.getIntegralType(),
2198 /*ArrayBound=*/false,
2199 Info, Deduced);
2200 if (Arg.getKind() == TemplateArgument::NullPtr)
2201 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2202 Arg.getNullPtrType(),
2203 Info, Deduced);
2204 if (Arg.getKind() == TemplateArgument::Expression)
2205 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2206 Arg.getAsExpr(), Info, Deduced);
2207 if (Arg.getKind() == TemplateArgument::Declaration)
2208 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2209 Arg.getAsDecl(),
2210 Arg.getParamTypeForDecl(),
2211 Info, Deduced);
2212
2213 Info.FirstArg = Param;
2214 Info.SecondArg = Arg;
2215 return Sema::TDK_NonDeducedMismatch;
2216 }
2217
2218 // Can't deduce anything, but that's okay.
2219 return Sema::TDK_Success;
2220
2221 case TemplateArgument::Pack:
2222 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2222)
;
2223 }
2224
2225 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2225)
;
2226}
2227
2228/// Determine whether there is a template argument to be used for
2229/// deduction.
2230///
2231/// This routine "expands" argument packs in-place, overriding its input
2232/// parameters so that \c Args[ArgIdx] will be the available template argument.
2233///
2234/// \returns true if there is another template argument (which will be at
2235/// \c Args[ArgIdx]), false otherwise.
2236static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
2237 unsigned &ArgIdx) {
2238 if (ArgIdx == Args.size())
2239 return false;
2240
2241 const TemplateArgument &Arg = Args[ArgIdx];
2242 if (Arg.getKind() != TemplateArgument::Pack)
2243 return true;
2244
2245 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2245, __PRETTY_FUNCTION__))
;
2246 Args = Arg.pack_elements();
2247 ArgIdx = 0;
2248 return ArgIdx < Args.size();
2249}
2250
2251/// Determine whether the given set of template arguments has a pack
2252/// expansion that is not the last template argument.
2253static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
2254 bool FoundPackExpansion = false;
2255 for (const auto &A : Args) {
2256 if (FoundPackExpansion)
2257 return true;
2258
2259 if (A.getKind() == TemplateArgument::Pack)
2260 return hasPackExpansionBeforeEnd(A.pack_elements());
2261
2262 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2263 // templates, it should not be treated as a pack expansion.
2264 if (A.isPackExpansion())
2265 FoundPackExpansion = true;
2266 }
2267
2268 return false;
2269}
2270
2271static Sema::TemplateDeductionResult
2272DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
2273 ArrayRef<TemplateArgument> Params,
2274 ArrayRef<TemplateArgument> Args,
2275 TemplateDeductionInfo &Info,
2276 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2277 bool NumberOfArgumentsMustMatch) {
2278 // C++0x [temp.deduct.type]p9:
2279 // If the template argument list of P contains a pack expansion that is not
2280 // the last template argument, the entire template argument list is a
2281 // non-deduced context.
2282 if (hasPackExpansionBeforeEnd(Params))
2283 return Sema::TDK_Success;
2284
2285 // C++0x [temp.deduct.type]p9:
2286 // If P has a form that contains <T> or <i>, then each argument Pi of the
2287 // respective template argument list P is compared with the corresponding
2288 // argument Ai of the corresponding template argument list of A.
2289 unsigned ArgIdx = 0, ParamIdx = 0;
2290 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
2291 if (!Params[ParamIdx].isPackExpansion()) {
2292 // The simple case: deduce template arguments by matching Pi and Ai.
2293
2294 // Check whether we have enough arguments.
2295 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
2296 return NumberOfArgumentsMustMatch
2297 ? Sema::TDK_MiscellaneousDeductionFailure
2298 : Sema::TDK_Success;
2299
2300 // C++1z [temp.deduct.type]p9:
2301 // During partial ordering, if Ai was originally a pack expansion [and]
2302 // Pi is not a pack expansion, template argument deduction fails.
2303 if (Args[ArgIdx].isPackExpansion())
2304 return Sema::TDK_MiscellaneousDeductionFailure;
2305
2306 // Perform deduction for this Pi/Ai pair.
2307 if (Sema::TemplateDeductionResult Result
2308 = DeduceTemplateArguments(S, TemplateParams,
2309 Params[ParamIdx], Args[ArgIdx],
2310 Info, Deduced))
2311 return Result;
2312
2313 // Move to the next argument.
2314 ++ArgIdx;
2315 continue;
2316 }
2317
2318 // The parameter is a pack expansion.
2319
2320 // C++0x [temp.deduct.type]p9:
2321 // If Pi is a pack expansion, then the pattern of Pi is compared with
2322 // each remaining argument in the template argument list of A. Each
2323 // comparison deduces template arguments for subsequent positions in the
2324 // template parameter packs expanded by Pi.
2325 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
2326
2327 // Prepare to deduce the packs within the pattern.
2328 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2329
2330 // Keep track of the deduced template arguments for each parameter pack
2331 // expanded by this pack expansion (the outer index) and for each
2332 // template argument (the inner SmallVectors).
2333 for (; hasTemplateArgumentForDeduction(Args, ArgIdx) &&
2334 PackScope.hasNextElement();
2335 ++ArgIdx) {
2336 // Deduce template arguments from the pattern.
2337 if (Sema::TemplateDeductionResult Result
2338 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
2339 Info, Deduced))
2340 return Result;
2341
2342 PackScope.nextPackElement();
2343 }
2344
2345 // Build argument packs for each of the parameter packs expanded by this
2346 // pack expansion.
2347 if (auto Result = PackScope.finish())
2348 return Result;
2349 }
2350
2351 return Sema::TDK_Success;
2352}
2353
2354static Sema::TemplateDeductionResult
2355DeduceTemplateArguments(Sema &S,
2356 TemplateParameterList *TemplateParams,
2357 const TemplateArgumentList &ParamList,
2358 const TemplateArgumentList &ArgList,
2359 TemplateDeductionInfo &Info,
2360 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
2361 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
2362 ArgList.asArray(), Info, Deduced,
2363 /*NumberOfArgumentsMustMatch*/false);
2364}
2365
2366/// Determine whether two template arguments are the same.
2367static bool isSameTemplateArg(ASTContext &Context,
2368 TemplateArgument X,
2369 const TemplateArgument &Y,
2370 bool PackExpansionMatchesPack = false) {
2371 // If we're checking deduced arguments (X) against original arguments (Y),
2372 // we will have flattened packs to non-expansions in X.
2373 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2374 X = X.getPackExpansionPattern();
2375
2376 if (X.getKind() != Y.getKind())
2377 return false;
2378
2379 switch (X.getKind()) {
2380 case TemplateArgument::Null:
2381 llvm_unreachable("Comparing NULL template argument")::llvm::llvm_unreachable_internal("Comparing NULL template argument"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2381)
;
2382
2383 case TemplateArgument::Type:
2384 return Context.getCanonicalType(X.getAsType()) ==
2385 Context.getCanonicalType(Y.getAsType());
2386
2387 case TemplateArgument::Declaration:
2388 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2389
2390 case TemplateArgument::NullPtr:
2391 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2392
2393 case TemplateArgument::Template:
2394 case TemplateArgument::TemplateExpansion:
2395 return Context.getCanonicalTemplateName(
2396 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2397 Context.getCanonicalTemplateName(
2398 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
2399
2400 case TemplateArgument::Integral:
2401 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2402
2403 case TemplateArgument::Expression: {
2404 llvm::FoldingSetNodeID XID, YID;
2405 X.getAsExpr()->Profile(XID, Context, true);
2406 Y.getAsExpr()->Profile(YID, Context, true);
2407 return XID == YID;
2408 }
2409
2410 case TemplateArgument::Pack:
2411 if (X.pack_size() != Y.pack_size())
2412 return false;
2413
2414 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2415 XPEnd = X.pack_end(),
2416 YP = Y.pack_begin();
2417 XP != XPEnd; ++XP, ++YP)
2418 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
2419 return false;
2420
2421 return true;
2422 }
2423
2424 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2424)
;
2425}
2426
2427/// Allocate a TemplateArgumentLoc where all locations have
2428/// been initialized to the given location.
2429///
2430/// \param Arg The template argument we are producing template argument
2431/// location information for.
2432///
2433/// \param NTTPType For a declaration template argument, the type of
2434/// the non-type template parameter that corresponds to this template
2435/// argument. Can be null if no type sugar is available to add to the
2436/// type from the template argument.
2437///
2438/// \param Loc The source location to use for the resulting template
2439/// argument.
2440TemplateArgumentLoc
2441Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2442 QualType NTTPType, SourceLocation Loc) {
2443 switch (Arg.getKind()) {
2444 case TemplateArgument::Null:
2445 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2445)
;
2446
2447 case TemplateArgument::Type:
2448 return TemplateArgumentLoc(
2449 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2450
2451 case TemplateArgument::Declaration: {
2452 if (NTTPType.isNull())
2453 NTTPType = Arg.getParamTypeForDecl();
2454 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2455 .getAs<Expr>();
2456 return TemplateArgumentLoc(TemplateArgument(E), E);
2457 }
2458
2459 case TemplateArgument::NullPtr: {
2460 if (NTTPType.isNull())
2461 NTTPType = Arg.getNullPtrType();
2462 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2463 .getAs<Expr>();
2464 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2465 E);
2466 }
2467
2468 case TemplateArgument::Integral: {
2469 Expr *E =
2470 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
2471 return TemplateArgumentLoc(TemplateArgument(E), E);
2472 }
2473
2474 case TemplateArgument::Template:
2475 case TemplateArgument::TemplateExpansion: {
2476 NestedNameSpecifierLocBuilder Builder;
2477 TemplateName Template = Arg.getAsTemplate();
2478 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2479 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2480 else if (QualifiedTemplateName *QTN =
2481 Template.getAsQualifiedTemplateName())
2482 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2483
2484 if (Arg.getKind() == TemplateArgument::Template)
2485 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2486 Loc);
2487
2488 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2489 Loc, Loc);
2490 }
2491
2492 case TemplateArgument::Expression:
2493 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2494
2495 case TemplateArgument::Pack:
2496 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2497 }
2498
2499 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2499)
;
2500}
2501
2502TemplateArgumentLoc
2503Sema::getIdentityTemplateArgumentLoc(Decl *TemplateParm,
2504 SourceLocation Location) {
2505 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParm))
2506 return getTrivialTemplateArgumentLoc(
2507 TemplateArgument(
2508 Context.getTemplateTypeParmType(TTP->getDepth(), TTP->getIndex(),
2509 TTP->isParameterPack(), TTP)),
2510 QualType(), Location.isValid() ? Location : TTP->getLocation());
2511 else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParm))
2512 return getTrivialTemplateArgumentLoc(TemplateArgument(TemplateName(TTP)),
2513 QualType(),
2514 Location.isValid() ? Location :
2515 TTP->getLocation());
2516 auto *NTTP = cast<NonTypeTemplateParmDecl>(TemplateParm);
2517 CXXScopeSpec SS;
2518 DeclarationNameInfo Info(NTTP->getDeclName(),
2519 Location.isValid() ? Location : NTTP->getLocation());
2520 Expr *E = BuildDeclarationNameExpr(SS, Info, NTTP).get();
2521 return getTrivialTemplateArgumentLoc(TemplateArgument(E), NTTP->getType(),
2522 Location.isValid() ? Location :
2523 NTTP->getLocation());
2524}
2525
2526/// Convert the given deduced template argument and add it to the set of
2527/// fully-converted template arguments.
2528static bool
2529ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2530 DeducedTemplateArgument Arg,
2531 NamedDecl *Template,
2532 TemplateDeductionInfo &Info,
2533 bool IsDeduced,
2534 SmallVectorImpl<TemplateArgument> &Output) {
2535 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2536 unsigned ArgumentPackIndex) {
2537 // Convert the deduced template argument into a template
2538 // argument that we can check, almost as if the user had written
2539 // the template argument explicitly.
2540 TemplateArgumentLoc ArgLoc =
2541 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
2542
2543 // Check the template argument, converting it as necessary.
2544 return S.CheckTemplateArgument(
2545 Param, ArgLoc, Template, Template->getLocation(),
2546 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2547 IsDeduced
2548 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2549 : Sema::CTAK_Deduced)
2550 : Sema::CTAK_Specified);
2551 };
2552
2553 if (Arg.getKind() == TemplateArgument::Pack) {
2554 // This is a template argument pack, so check each of its arguments against
2555 // the template parameter.
2556 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
2557 for (const auto &P : Arg.pack_elements()) {
2558 // When converting the deduced template argument, append it to the
2559 // general output list. We need to do this so that the template argument
2560 // checking logic has all of the prior template arguments available.
2561 DeducedTemplateArgument InnerArg(P);
2562 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
2563 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2564, __PRETTY_FUNCTION__))
2564 "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2564, __PRETTY_FUNCTION__))
;
2565 if (P.isNull()) {
2566 // We deduced arguments for some elements of this pack, but not for
2567 // all of them. This happens if we get a conditionally-non-deduced
2568 // context in a pack expansion (such as an overload set in one of the
2569 // arguments).
2570 S.Diag(Param->getLocation(),
2571 diag::err_template_arg_deduced_incomplete_pack)
2572 << Arg << Param;
2573 return true;
2574 }
2575 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
2576 return true;
2577
2578 // Move the converted template argument into our argument pack.
2579 PackedArgsBuilder.push_back(Output.pop_back_val());
2580 }
2581
2582 // If the pack is empty, we still need to substitute into the parameter
2583 // itself, in case that substitution fails.
2584 if (PackedArgsBuilder.empty()) {
2585 LocalInstantiationScope Scope(S);
2586 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
2587 MultiLevelTemplateArgumentList Args(TemplateArgs);
2588
2589 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2590 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2591 NTTP, Output,
2592 Template->getSourceRange());
2593 if (Inst.isInvalid() ||
2594 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2595 NTTP->getDeclName()).isNull())
2596 return true;
2597 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2598 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2599 TTP, Output,
2600 Template->getSourceRange());
2601 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2602 return true;
2603 }
2604 // For type parameters, no substitution is ever required.
2605 }
2606
2607 // Create the resulting argument pack.
2608 Output.push_back(
2609 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
2610 return false;
2611 }
2612
2613 return ConvertArg(Arg, 0);
2614}
2615
2616// FIXME: This should not be a template, but
2617// ClassTemplatePartialSpecializationDecl sadly does not derive from
2618// TemplateDecl.
2619template<typename TemplateDeclT>
2620static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
2621 Sema &S, TemplateDeclT *Template, bool IsDeduced,
2622 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2623 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2624 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2625 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2626 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2627
2628 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2629 NamedDecl *Param = TemplateParams->getParam(I);
2630
2631 // C++0x [temp.arg.explicit]p3:
2632 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2633 // be deduced to an empty sequence of template arguments.
2634 // FIXME: Where did the word "trailing" come from?
2635 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2636 if (auto Result =
2637 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish())
2638 return Result;
2639 }
2640
2641 if (!Deduced[I].isNull()) {
2642 if (I < NumAlreadyConverted) {
2643 // We may have had explicitly-specified template arguments for a
2644 // template parameter pack (that may or may not have been extended
2645 // via additional deduced arguments).
2646 if (Param->isParameterPack() && CurrentInstantiationScope &&
2647 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2648 // Forget the partially-substituted pack; its substitution is now
2649 // complete.
2650 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2651 // We still need to check the argument in case it was extended by
2652 // deduction.
2653 } else {
2654 // We have already fully type-checked and converted this
2655 // argument, because it was explicitly-specified. Just record the
2656 // presence of this argument.
2657 Builder.push_back(Deduced[I]);
2658 continue;
2659 }
2660 }
2661
2662 // We may have deduced this argument, so it still needs to be
2663 // checked and converted.
2664 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2665 IsDeduced, Builder)) {
2666 Info.Param = makeTemplateParameter(Param);
2667 // FIXME: These template arguments are temporary. Free them!
2668 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2669 return Sema::TDK_SubstitutionFailure;
2670 }
2671
2672 continue;
2673 }
2674
2675 // Substitute into the default template argument, if available.
2676 bool HasDefaultArg = false;
2677 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2678 if (!TD) {
2679 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2680, __PRETTY_FUNCTION__))
2680 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2680, __PRETTY_FUNCTION__))
;
2681 return Sema::TDK_Incomplete;
2682 }
2683
2684 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2685 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2686 HasDefaultArg);
2687
2688 // If there was no default argument, deduction is incomplete.
2689 if (DefArg.getArgument().isNull()) {
2690 Info.Param = makeTemplateParameter(
2691 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2692 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2693 if (PartialOverloading) break;
2694
2695 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2696 : Sema::TDK_Incomplete;
2697 }
2698
2699 // Check whether we can actually use the default argument.
2700 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2701 TD->getSourceRange().getEnd(), 0, Builder,
2702 Sema::CTAK_Specified)) {
2703 Info.Param = makeTemplateParameter(
2704 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2705 // FIXME: These template arguments are temporary. Free them!
2706 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2707 return Sema::TDK_SubstitutionFailure;
2708 }
2709
2710 // If we get here, we successfully used the default template argument.
2711 }
2712
2713 return Sema::TDK_Success;
2714}
2715
2716static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2717 if (auto *DC = dyn_cast<DeclContext>(D))
2718 return DC;
2719 return D->getDeclContext();
2720}
2721
2722template<typename T> struct IsPartialSpecialization {
2723 static constexpr bool value = false;
2724};
2725template<>
2726struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2727 static constexpr bool value = true;
2728};
2729template<>
2730struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2731 static constexpr bool value = true;
2732};
2733
2734template<typename TemplateDeclT>
2735static Sema::TemplateDeductionResult
2736CheckDeducedArgumentConstraints(Sema& S, TemplateDeclT *Template,
2737 ArrayRef<TemplateArgument> DeducedArgs,
2738 TemplateDeductionInfo& Info) {
2739 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
2740 Template->getAssociatedConstraints(AssociatedConstraints);
2741 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints,
2742 DeducedArgs, Info.getLocation(),
2743 Info.AssociatedConstraintsSatisfaction) ||
2744 !Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
2745 Info.reset(TemplateArgumentList::CreateCopy(S.Context, DeducedArgs));
2746 return Sema::TDK_ConstraintsNotSatisfied;
2747 }
2748 return Sema::TDK_Success;
2749}
2750
2751/// Complete template argument deduction for a partial specialization.
2752template <typename T>
2753static typename std::enable_if<IsPartialSpecialization<T>::value,
2754 Sema::TemplateDeductionResult>::type
2755FinishTemplateArgumentDeduction(
2756 Sema &S, T *Partial, bool IsPartialOrdering,
2757 const TemplateArgumentList &TemplateArgs,
2758 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2759 TemplateDeductionInfo &Info) {
2760 // Unevaluated SFINAE context.
2761 EnterExpressionEvaluationContext Unevaluated(
2762 S, Sema::ExpressionEvaluationContext::Unevaluated);
2763 Sema::SFINAETrap Trap(S);
2764
2765 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
2766
2767 // C++ [temp.deduct.type]p2:
2768 // [...] or if any template argument remains neither deduced nor
2769 // explicitly specified, template argument deduction fails.
2770 SmallVector<TemplateArgument, 4> Builder;
2771 if (auto Result = ConvertDeducedTemplateArguments(
2772 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
2773 return Result;
2774
2775 // Form the template argument list from the deduced template arguments.
2776 TemplateArgumentList *DeducedArgumentList
2777 = TemplateArgumentList::CreateCopy(S.Context, Builder);
2778
2779 Info.reset(DeducedArgumentList);
2780
2781 // Substitute the deduced template arguments into the template
2782 // arguments of the class template partial specialization, and
2783 // verify that the instantiated template arguments are both valid
2784 // and are equivalent to the template arguments originally provided
2785 // to the class template.
2786 LocalInstantiationScope InstScope(S);
2787 auto *Template = Partial->getSpecializedTemplate();
2788 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2789 Partial->getTemplateArgsAsWritten();
2790 const TemplateArgumentLoc *PartialTemplateArgs =
2791 PartialTemplArgInfo->getTemplateArgs();
2792
2793 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2794 PartialTemplArgInfo->RAngleLoc);
2795
2796 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2797 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2798 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2799 if (ParamIdx >= Partial->getTemplateParameters()->size())
2800 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2801
2802 Decl *Param = const_cast<NamedDecl *>(
2803 Partial->getTemplateParameters()->getParam(ParamIdx));
2804 Info.Param = makeTemplateParameter(Param);
2805 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2806 return Sema::TDK_SubstitutionFailure;
2807 }
2808
2809 bool ConstraintsNotSatisfied;
2810 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2811 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2812 false, ConvertedInstArgs,
2813 /*UpdateArgsWithConversions=*/true,
2814 &ConstraintsNotSatisfied))
2815 return ConstraintsNotSatisfied ? Sema::TDK_ConstraintsNotSatisfied :
2816 Sema::TDK_SubstitutionFailure;
2817
2818 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2819 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2820 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2821 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2822 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2823 Info.FirstArg = TemplateArgs[I];
2824 Info.SecondArg = InstArg;
2825 return Sema::TDK_NonDeducedMismatch;
2826 }
2827 }
2828
2829 if (Trap.hasErrorOccurred())
2830 return Sema::TDK_SubstitutionFailure;
2831
2832 if (auto Result = CheckDeducedArgumentConstraints(S, Partial, Builder, Info))
2833 return Result;
2834
2835 return Sema::TDK_Success;
2836}
2837
2838/// Complete template argument deduction for a class or variable template,
2839/// when partial ordering against a partial specialization.
2840// FIXME: Factor out duplication with partial specialization version above.
2841static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2842 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2843 const TemplateArgumentList &TemplateArgs,
2844 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2845 TemplateDeductionInfo &Info) {
2846 // Unevaluated SFINAE context.
2847 EnterExpressionEvaluationContext Unevaluated(
2848 S, Sema::ExpressionEvaluationContext::Unevaluated);
2849 Sema::SFINAETrap Trap(S);
2850
2851 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2852
2853 // C++ [temp.deduct.type]p2:
2854 // [...] or if any template argument remains neither deduced nor
2855 // explicitly specified, template argument deduction fails.
2856 SmallVector<TemplateArgument, 4> Builder;
2857 if (auto Result = ConvertDeducedTemplateArguments(
2858 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2859 return Result;
2860
2861 // Check that we produced the correct argument list.
2862 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2863 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2864 TemplateArgument InstArg = Builder[I];
2865 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2866 /*PackExpansionMatchesPack*/true)) {
2867 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2868 Info.FirstArg = TemplateArgs[I];
2869 Info.SecondArg = InstArg;
2870 return Sema::TDK_NonDeducedMismatch;
2871 }
2872 }
2873
2874 if (Trap.hasErrorOccurred())
2875 return Sema::TDK_SubstitutionFailure;
2876
2877 if (auto Result = CheckDeducedArgumentConstraints(S, Template, Builder,
2878 Info))
2879 return Result;
2880
2881 return Sema::TDK_Success;
2882}
2883
2884/// Perform template argument deduction to determine whether
2885/// the given template arguments match the given class template
2886/// partial specialization per C++ [temp.class.spec.match].
2887Sema::TemplateDeductionResult
2888Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
2889 const TemplateArgumentList &TemplateArgs,
2890 TemplateDeductionInfo &Info) {
2891 if (Partial->isInvalidDecl())
2892 return TDK_Invalid;
2893
2894 // C++ [temp.class.spec.match]p2:
2895 // A partial specialization matches a given actual template
2896 // argument list if the template arguments of the partial
2897 // specialization can be deduced from the actual template argument
2898 // list (14.8.2).
2899
2900 // Unevaluated SFINAE context.
2901 EnterExpressionEvaluationContext Unevaluated(
2902 *this, Sema::ExpressionEvaluationContext::Unevaluated);
2903 SFINAETrap Trap(*this);
2904
2905 SmallVector<DeducedTemplateArgument, 4> Deduced;
2906 Deduced.resize(Partial->getTemplateParameters()->size());
2907 if (TemplateDeductionResult Result
2908 = ::DeduceTemplateArguments(*this,
2909 Partial->getTemplateParameters(),
2910 Partial->getTemplateArgs(),
2911 TemplateArgs, Info, Deduced))
2912 return Result;
2913
2914 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2915 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2916 Info);
2917 if (Inst.isInvalid())
2918 return TDK_InstantiationDepth;
2919
2920 if (Trap.hasErrorOccurred())
2921 return Sema::TDK_SubstitutionFailure;
2922
2923 return ::FinishTemplateArgumentDeduction(
2924 *this, Partial, /*IsPartialOrdering=*/false, TemplateArgs, Deduced, Info);
2925}
2926
2927/// Perform template argument deduction to determine whether
2928/// the given template arguments match the given variable template
2929/// partial specialization per C++ [temp.class.spec.match].
2930Sema::TemplateDeductionResult
2931Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2932 const TemplateArgumentList &TemplateArgs,
2933 TemplateDeductionInfo &Info) {
2934 if (Partial->isInvalidDecl())
2935 return TDK_Invalid;
2936
2937 // C++ [temp.class.spec.match]p2:
2938 // A partial specialization matches a given actual template
2939 // argument list if the template arguments of the partial
2940 // specialization can be deduced from the actual template argument
2941 // list (14.8.2).
2942
2943 // Unevaluated SFINAE context.
2944 EnterExpressionEvaluationContext Unevaluated(
2945 *this, Sema::ExpressionEvaluationContext::Unevaluated);
2946 SFINAETrap Trap(*this);
2947
2948 SmallVector<DeducedTemplateArgument, 4> Deduced;
2949 Deduced.resize(Partial->getTemplateParameters()->size());
2950 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2951 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2952 TemplateArgs, Info, Deduced))
2953 return Result;
2954
2955 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2956 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2957 Info);
2958 if (Inst.isInvalid())
2959 return TDK_InstantiationDepth;
2960
2961 if (Trap.hasErrorOccurred())
2962 return Sema::TDK_SubstitutionFailure;
2963
2964 return ::FinishTemplateArgumentDeduction(
2965 *this, Partial, /*IsPartialOrdering=*/false, TemplateArgs, Deduced, Info);
2966}
2967
2968/// Determine whether the given type T is a simple-template-id type.
2969static bool isSimpleTemplateIdType(QualType T) {
2970 if (const TemplateSpecializationType *Spec
36.1
'Spec' is non-null
36.1
'Spec' is non-null
36.1
'Spec' is non-null
37
Taking true branch
2971 = T->getAs<TemplateSpecializationType>())
36
Assuming the object is a 'TemplateSpecializationType'
2972 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
38
Assuming the condition is false
39
Returning zero, which participates in a condition later
2973 2974 // C++17 [temp.local]p2: 2975 // the injected-class-name [...] is equivalent to the template-name followed 2976 // by the template-arguments of the class template specialization or partial 2977 // specialization enclosed in <> 2978 // ... which means it's equivalent to a simple-template-id. 2979 // 2980 // This only arises during class template argument deduction for a copy 2981 // deduction candidate, where it permits slicing. 2982 if (T->getAs<InjectedClassNameType>()) 2983 return true; 2984 2985 return false; 2986} 2987 2988/// Substitute the explicitly-provided template arguments into the 2989/// given function template according to C++ [temp.arg.explicit]. 2990/// 2991/// \param FunctionTemplate the function template into which the explicit 2992/// template arguments will be substituted. 2993/// 2994/// \param ExplicitTemplateArgs the explicitly-specified template 2995/// arguments. 2996/// 2997/// \param Deduced the deduced template arguments, which will be populated 2998/// with the converted and checked explicit template arguments. 2999/// 3000/// \param ParamTypes will be populated with the instantiated function 3001/// parameters. 3002/// 3003/// \param FunctionType if non-NULL, the result type of the function template 3004/// will also be instantiated and the pointed-to value will be updated with 3005/// the instantiated function type. 3006/// 3007/// \param Info if substitution fails for any reason, this object will be 3008/// populated with more information about the failure. 3009/// 3010/// \returns TDK_Success if substitution was successful, or some failure 3011/// condition. 3012Sema::TemplateDeductionResult 3013Sema::SubstituteExplicitTemplateArguments( 3014 FunctionTemplateDecl *FunctionTemplate, 3015 TemplateArgumentListInfo &ExplicitTemplateArgs, 3016 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3017 SmallVectorImpl<QualType> &ParamTypes, 3018 QualType *FunctionType, 3019 TemplateDeductionInfo &Info) { 3020 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 3021 TemplateParameterList *TemplateParams 3022 = FunctionTemplate->getTemplateParameters(); 3023 3024 if (ExplicitTemplateArgs.size() == 0) { 3025 // No arguments to substitute; just copy over the parameter types and 3026 // fill in the function type. 3027 for (auto P : Function->parameters()) 3028 ParamTypes.push_back(P->getType()); 3029 3030 if (FunctionType) 3031 *FunctionType = Function->getType(); 3032 return TDK_Success; 3033 } 3034 3035 // Unevaluated SFINAE context. 3036 EnterExpressionEvaluationContext Unevaluated( 3037 *this, Sema::ExpressionEvaluationContext::Unevaluated); 3038 SFINAETrap Trap(*this); 3039 3040 // C++ [temp.arg.explicit]p3: 3041 // Template arguments that are present shall be specified in the 3042 // declaration order of their corresponding template-parameters. The 3043 // template argument list shall not specify more template-arguments than 3044 // there are corresponding template-parameters. 3045 SmallVector<TemplateArgument, 4> Builder; 3046 3047 // Enter a new template instantiation context where we check the 3048 // explicitly-specified template arguments against this function template, 3049 // and then substitute them into the function parameter types. 3050 SmallVector<TemplateArgument, 4> DeducedArgs; 3051 InstantiatingTemplate Inst( 3052 *this, Info.getLocation(), FunctionTemplate, DeducedArgs, 3053 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info); 3054 if (Inst.isInvalid()) 3055 return TDK_InstantiationDepth; 3056 3057 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(), 3058 ExplicitTemplateArgs, true, Builder, false) || 3059 Trap.hasErrorOccurred()) { 3060 unsigned Index = Builder.size(); 3061 if (Index >= TemplateParams->size()) 3062 return TDK_SubstitutionFailure; 3063 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index)); 3064 return TDK_InvalidExplicitArguments; 3065 } 3066 3067 // Form the template argument list from the explicitly-specified 3068 // template arguments. 3069 TemplateArgumentList *ExplicitArgumentList 3070 = TemplateArgumentList::CreateCopy(Context, Builder); 3071 Info.setExplicitArgs(ExplicitArgumentList); 3072 3073 // Template argument deduction and the final substitution should be 3074 // done in the context of the templated declaration. Explicit 3075 // argument substitution, on the other hand, needs to happen in the 3076 // calling context. 3077 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 3078 3079 // If we deduced template arguments for a template parameter pack, 3080 // note that the template argument pack is partially substituted and record 3081 // the explicit template arguments. They'll be used as part of deduction 3082 // for this template parameter pack. 3083 unsigned PartiallySubstitutedPackIndex = -1u; 3084 if (!Builder.empty()) { 3085 const TemplateArgument &Arg = Builder.back(); 3086 if (Arg.getKind() == TemplateArgument::Pack) { 3087 auto *Param = TemplateParams->getParam(Builder.size() - 1); 3088 // If this is a fully-saturated fixed-size pack, it should be 3089 // fully-substituted, not partially-substituted. 3090 Optional<unsigned> Expansions = getExpandedPackSize(Param); 3091 if (!Expansions || Arg.pack_size() < *Expansions) { 3092 PartiallySubstitutedPackIndex = Builder.size() - 1; 3093 CurrentInstantiationScope->SetPartiallySubstitutedPack( 3094 Param, Arg.pack_begin(), Arg.pack_size()); 3095 } 3096 } 3097 } 3098 3099 const FunctionProtoType *Proto 3100 = Function->getType()->getAs<FunctionProtoType>(); 3101 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 3101, __PRETTY_FUNCTION__))
; 3102 3103 // Isolate our substituted parameters from our caller. 3104 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true); 3105 3106 ExtParameterInfoBuilder ExtParamInfos; 3107 3108 // Instantiate the types of each of the function parameters given the 3109 // explicitly-specified template arguments. If the function has a trailing 3110 // return type, substitute it after the arguments to ensure we substitute 3111 // in lexical order. 3112 if (Proto->hasTrailingReturn()) { 3113 if (SubstParmTypes(Function->getLocation(), Function->parameters(), 3114 Proto->getExtParameterInfosOrNull(), 3115 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 3116 ParamTypes, /*params*/ nullptr, ExtParamInfos)) 3117 return TDK_SubstitutionFailure; 3118 } 3119 3120 // Instantiate the return type. 3121 QualType ResultType; 3122 { 3123 // C++11 [expr.prim.general]p3: 3124 // If a declaration declares a member function or member function 3125 // template of a class X, the expression this is a prvalue of type 3126 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 3127 // and the end of the function-definition, member-declarator, or 3128 // declarator. 3129 Qualifiers ThisTypeQuals; 3130 CXXRecordDecl *ThisContext = nullptr; 3131 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 3132 ThisContext = Method->getParent(); 3133 ThisTypeQuals = Method->getMethodQualifiers(); 3134 } 3135 3136 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals, 3137 getLangOpts().CPlusPlus11); 3138 3139 ResultType = 3140 SubstType(Proto->getReturnType(), 3141 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 3142 Function->getTypeSpecStartLoc(), Function->getDeclName()); 3143 if (ResultType.isNull() || Trap.hasErrorOccurred()) 3144 return TDK_SubstitutionFailure; 3145 // CUDA: Kernel function must have 'void' return type. 3146 if (getLangOpts().CUDA) 3147 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) { 3148 Diag(Function->getLocation(), diag::err_kern_type_not_void_return) 3149 << Function->getType() << Function->getSourceRange(); 3150 return TDK_SubstitutionFailure; 3151 } 3152 } 3153 3154 // Instantiate the types of each of the function parameters given the 3155 // explicitly-specified template arguments if we didn't do so earlier. 3156 if (!Proto->hasTrailingReturn() && 3157 SubstParmTypes(Function->getLocation(), Function->parameters(), 3158 Proto->getExtParameterInfosOrNull(), 3159 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 3160 ParamTypes, /*params*/ nullptr, ExtParamInfos)) 3161 return TDK_SubstitutionFailure; 3162 3163 if (FunctionType) { 3164 auto EPI = Proto->getExtProtoInfo(); 3165 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size()); 3166 3167 // In C++1z onwards, exception specifications are part of the function type, 3168 // so substitution into the type must also substitute into the exception 3169 // specification. 3170 SmallVector<QualType, 4> ExceptionStorage; 3171 if (getLangOpts().CPlusPlus17 && 3172 SubstExceptionSpec( 3173 Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage, 3174 MultiLevelTemplateArgumentList(*ExplicitArgumentList))) 3175 return TDK_SubstitutionFailure; 3176 3177 *FunctionType = BuildFunctionType(ResultType, ParamTypes, 3178 Function->getLocation(), 3179 Function->getDeclName(), 3180 EPI); 3181 if (FunctionType->isNull() || Trap.hasErrorOccurred()) 3182 return TDK_SubstitutionFailure; 3183 } 3184 3185 // C++ [temp.arg.explicit]p2: 3186 // Trailing template arguments that can be deduced (14.8.2) may be 3187 // omitted from the list of explicit template-arguments. If all of the 3188 // template arguments can be deduced, they may all be omitted; in this 3189 // case, the empty template argument list <> itself may also be omitted. 3190 // 3191 // Take all of the explicitly-specified arguments and put them into 3192 // the set of deduced template arguments. The partially-substituted 3193 // parameter pack, however, will be set to NULL since the deduction 3194 // mechanism handles the partially-substituted argument pack directly. 3195 Deduced.reserve(TemplateParams->size()); 3196 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) { 3197 const TemplateArgument &Arg = ExplicitArgumentList->get(I); 3198 if (I == PartiallySubstitutedPackIndex) 3199 Deduced.push_back(DeducedTemplateArgument()); 3200 else 3201 Deduced.push_back(Arg); 3202 } 3203 3204 return TDK_Success; 3205} 3206 3207/// Check whether the deduced argument type for a call to a function 3208/// template matches the actual argument type per C++ [temp.deduct.call]p4. 3209static Sema::TemplateDeductionResult 3210CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info, 3211 Sema::OriginalCallArg OriginalArg, 3212 QualType DeducedA) { 3213 ASTContext &Context = S.Context; 3214 3215 auto Failed = [&]() -> Sema::TemplateDeductionResult { 3216 Info.FirstArg = TemplateArgument(DeducedA); 3217 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType); 3218 Info.CallArgIndex = OriginalArg.ArgIdx; 3219 return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested 3220 : Sema::TDK_DeducedMismatch; 3221 }; 3222 3223 QualType A = OriginalArg.OriginalArgType; 3224 QualType OriginalParamType = OriginalArg.OriginalParamType; 3225 3226 // Check for type equality (top-level cv-qualifiers are ignored). 3227 if (Context.hasSameUnqualifiedType(A, DeducedA)) 3228 return Sema::TDK_Success; 3229 3230 // Strip off references on the argument types; they aren't needed for 3231 // the following checks. 3232 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>()) 3233 DeducedA = DeducedARef->getPointeeType(); 3234 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) 3235 A = ARef->getPointeeType(); 3236 3237 // C++ [temp.deduct.call]p4: 3238 // [...] However, there are three cases that allow a difference: 3239 // - If the original P is a reference type, the deduced A (i.e., the 3240 // type referred to by the reference) can be more cv-qualified than 3241 // the transformed A. 3242 if (const ReferenceType *OriginalParamRef 3243 = OriginalParamType->getAs<ReferenceType>()) { 3244 // We don't want to keep the reference around any more. 3245 OriginalParamType = OriginalParamRef->getPointeeType(); 3246 3247 // FIXME: Resolve core issue (no number yet): if the original P is a 3248 // reference type and the transformed A is function type "noexcept F", 3249 // the deduced A can be F. 3250 QualType Tmp; 3251 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp)) 3252 return Sema::TDK_Success; 3253 3254 Qualifiers AQuals = A.getQualifiers(); 3255 Qualifiers DeducedAQuals = DeducedA.getQualifiers(); 3256 3257 // Under Objective-C++ ARC, the deduced type may have implicitly 3258 // been given strong or (when dealing with a const reference) 3259 // unsafe_unretained lifetime. If so, update the original 3260 // qualifiers to include this lifetime. 3261 if (S.getLangOpts().ObjCAutoRefCount && 3262 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong && 3263 AQuals.getObjCLifetime() == Qualifiers::OCL_None) || 3264 (DeducedAQuals.hasConst() && 3265 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) { 3266 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime()); 3267 } 3268 3269 if (AQuals == DeducedAQuals) { 3270 // Qualifiers match; there's nothing to do. 3271 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) { 3272 return Failed(); 3273 } else { 3274 // Qualifiers are compatible, so have the argument type adopt the 3275 // deduced argument type's qualifiers as if we had performed the 3276 // qualification conversion. 3277 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals); 3278 } 3279 } 3280 3281 // - The transformed A can be another pointer or pointer to member 3282 // type that can be converted to the deduced A via a function pointer 3283 // conversion and/or a qualification conversion. 3284 // 3285 // Also allow conversions which merely strip __attribute__((noreturn)) from 3286 // function types (recursively). 3287 bool ObjCLifetimeConversion = false; 3288 QualType ResultTy; 3289 if ((A->isAnyPointerType() || A->isMemberPointerType()) && 3290 (S.IsQualificationConversion(A, DeducedA, false, 3291 ObjCLifetimeConversion) || 3292 S.IsFunctionConversion(A, DeducedA, ResultTy))) 3293 return Sema::TDK_Success; 3294 3295 // - If P is a class and P has the form simple-template-id, then the 3296 // transformed A can be a derived class of the deduced A. [...] 3297 // [...] Likewise, if P is a pointer to a class of the form 3298 // simple-template-id, the transformed A can be a pointer to a 3299 // derived class pointed to by the deduced A. 3300 if (const PointerType *OriginalParamPtr 3301 = OriginalParamType->getAs<PointerType>()) { 3302 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) { 3303 if (const PointerType *APtr = A->getAs<PointerType>()) { 3304 if (A->getPointeeType()->isRecordType()) { 3305 OriginalParamType = OriginalParamPtr->getPointeeType(); 3306 DeducedA = DeducedAPtr->getPointeeType(); 3307 A = APtr->getPointeeType(); 3308 } 3309 } 3310 } 3311 } 3312 3313 if (Context.hasSameUnqualifiedType(A, DeducedA)) 3314 return Sema::TDK_Success; 3315 3316 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) && 3317 S.IsDerivedFrom(Info.getLocation(), A, DeducedA)) 3318 return Sema::TDK_Success; 3319 3320 return Failed(); 3321} 3322 3323/// Find the pack index for a particular parameter index in an instantiation of 3324/// a function template with specific arguments. 3325/// 3326/// \return The pack index for whichever pack produced this parameter, or -1 3327/// if this was not produced by a parameter. Intended to be used as the 3328/// ArgumentPackSubstitutionIndex for further substitutions. 3329// FIXME: We should track this in OriginalCallArgs so we don't need to 3330// reconstruct it here. 3331static unsigned getPackIndexForParam(Sema &S, 3332 FunctionTemplateDecl *FunctionTemplate, 3333 const MultiLevelTemplateArgumentList &Args, 3334 unsigned ParamIdx) { 3335 unsigned Idx = 0; 3336 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) { 3337 if (PD->isParameterPack()) { 3338 unsigned NumExpansions = 3339 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1); 3340 if (Idx + NumExpansions > ParamIdx) 3341 return ParamIdx - Idx; 3342 Idx += NumExpansions; 3343 } else { 3344 if (Idx == ParamIdx) 3345 return -1; // Not a pack expansion 3346 ++Idx; 3347 } 3348 } 3349 3350 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 3350)
; 3351} 3352 3353/// Finish template argument deduction for a function template, 3354/// checking the deduced template arguments for completeness and forming 3355/// the function template specialization. 3356/// 3357/// \param OriginalCallArgs If non-NULL, the original call arguments against 3358/// which the deduced argument types should be compared. 3359Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction( 3360 FunctionTemplateDecl *FunctionTemplate, 3361 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3362 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, 3363 TemplateDeductionInfo &Info, 3364 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs, 3365 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) { 3366 // Unevaluated SFINAE context. 3367 EnterExpressionEvaluationContext Unevaluated( 3368 *this, Sema::ExpressionEvaluationContext::Unevaluated); 3369 SFINAETrap Trap(*this); 3370 3371 // Enter a new template instantiation context while we instantiate the 3372 // actual function declaration. 3373 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 3374 InstantiatingTemplate Inst( 3375 *this, Info.getLocation(), FunctionTemplate, DeducedArgs, 3376 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info); 3377 if (Inst.isInvalid()) 3378 return TDK_InstantiationDepth; 3379 3380 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 3381 3382 // C++ [temp.deduct.type]p2: 3383 // [...] or if any template argument remains neither deduced nor 3384 // explicitly specified, template argument deduction fails. 3385 SmallVector<TemplateArgument, 4> Builder; 3386 if (auto Result = ConvertDeducedTemplateArguments( 3387 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder, 3388 CurrentInstantiationScope, NumExplicitlySpecified, 3389 PartialOverloading)) 3390 return Result; 3391 3392 // C++ [temp.deduct.call]p10: [DR1391] 3393 // If deduction succeeds for all parameters that contain 3394 // template-parameters that participate in template argument deduction, 3395 // and all template arguments are explicitly specified, deduced, or 3396 // obtained from default template arguments, remaining parameters are then 3397 // compared with the corresponding arguments. For each remaining parameter 3398 // P with a type that was non-dependent before substitution of any 3399 // explicitly-specified template arguments, if the corresponding argument 3400 // A cannot be implicitly converted to P, deduction fails. 3401 if (CheckNonDependent()) 3402 return TDK_NonDependentConversionFailure; 3403 3404 // Form the template argument list from the deduced template arguments. 3405 TemplateArgumentList *DeducedArgumentList 3406 = TemplateArgumentList::CreateCopy(Context, Builder); 3407 Info.reset(DeducedArgumentList); 3408 3409 // Substitute the deduced template arguments into the function template 3410 // declaration to produce the function template specialization. 3411 DeclContext *Owner = FunctionTemplate->getDeclContext(); 3412 if (FunctionTemplate->getFriendObjectKind()) 3413 Owner = FunctionTemplate->getLexicalDeclContext(); 3414 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList); 3415 Specialization = cast_or_null<FunctionDecl>( 3416 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs)); 3417 if (!Specialization || Specialization->isInvalidDecl()) 3418 return TDK_SubstitutionFailure; 3419 3420 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==((Specialization->getPrimaryTemplate()->getCanonicalDecl
() == FunctionTemplate->getCanonicalDecl()) ? static_cast<
void> (0) : __assert_fail ("Specialization->getPrimaryTemplate()->getCanonicalDecl() == FunctionTemplate->getCanonicalDecl()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 3421, __PRETTY_FUNCTION__))
3421 FunctionTemplate->getCanonicalDecl())((Specialization->getPrimaryTemplate()->getCanonicalDecl
() == FunctionTemplate->getCanonicalDecl()) ? static_cast<
void> (0) : __assert_fail ("Specialization->getPrimaryTemplate()->getCanonicalDecl() == FunctionTemplate->getCanonicalDecl()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 3421, __PRETTY_FUNCTION__))
; 3422 3423 // If the template argument list is owned by the function template 3424 // specialization, release it. 3425 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList && 3426 !Trap.hasErrorOccurred()) 3427 Info.take(); 3428 3429 // There may have been an error that did not prevent us from constructing a 3430 // declaration. Mark the declaration invalid and return with a substitution 3431 // failure. 3432 if (Trap.hasErrorOccurred()) { 3433 Specialization->setInvalidDecl(true); 3434 return TDK_SubstitutionFailure; 3435 } 3436 3437 // C++2a [temp.deduct]p5 3438 // [...] When all template arguments have been deduced [...] all uses of 3439 // template parameters [...] are replaced with the corresponding deduced 3440 // or default argument values. 3441 // [...] If the function template has associated constraints 3442 // ([temp.constr.decl]), those constraints are checked for satisfaction 3443 // ([temp.constr.constr]). If the constraints are not satisfied, type 3444 // deduction fails. 3445 if (CheckInstantiatedFunctionTemplateConstraints(Info.getLocation(), 3446 Specialization, Builder, Info.AssociatedConstraintsSatisfaction)) 3447 return TDK_MiscellaneousDeductionFailure; 3448 3449 if (!Info.AssociatedConstraintsSatisfaction.IsSatisfied) { 3450 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder)); 3451 return TDK_ConstraintsNotSatisfied; 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())
18
Assuming the condition is false
19
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>();
20
Assuming the object is not a 'ReferenceType'
3660 if (ParamRefType
20.1
'ParamRefType' is null
20.1
'ParamRefType' is null
20.1
'ParamRefType' is null
)
21
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) {
22
Calling 'operator=='
28
Returning from 'operator=='
29
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
29.1
'ParamRefType' is null
29.1
'ParamRefType' is null
29.1
'ParamRefType' is null
) {
30
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())
31
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())
32
Taking true 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
32.1
'ParamRefType' is null
32.1
'ParamRefType' is null
32.1
'ParamRefType' is null
)
33
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() ||
34
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) ||
35
Calling 'isSimpleTemplateIdType'
40
Returning from 'isSimpleTemplateIdType'
3730 (isa<PointerType>(ParamType) &&
41
Assuming 'ParamType' is a 'PointerType'
3731 isSimpleTemplateIdType( 3732 ParamType->getAs<PointerType>()->getPointeeType())))
42
Assuming the object is not a 'PointerType'
43
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(
17
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())
1
Assuming the condition is false
2
Taking false branch
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)
3
Assuming the condition is false
3893 return TDK_TooFewArguments; 3894 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
4
Taking false branch
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) {
5
Assuming 'ExplicitTemplateArgs' is null
6
Taking false branch
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)
7
Assuming 'I' is equal to 'NumParams'
8
Loop condition is false. Execution continues on line 3928
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))
15
Taking false branch
3937 return Sema::TDK_Success; 3938 3939 // ... with the type of the corresponding argument 3940 return DeduceTemplateArgumentsFromCallArgument(
16
Calling '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;
10
Loop condition is true. Entering loop body
3949 ParamIdx != NumParamTypes; ++ParamIdx) {
9
Assuming 'ParamIdx' is not equal to 'NumParamTypes'
3950 QualType ParamType = ParamTypes[ParamIdx]; 3951 3952 const PackExpansionType *ParamExpansion = 3953 dyn_cast<PackExpansionType>(ParamType); 3954 if (!ParamExpansion
10.1
'ParamExpansion' is null
10.1
'ParamExpansion' is null
10.1
'ParamExpansion' is null
) {
11
Taking true branch
3955 // Simple case: matching a function parameter to a function argument. 3956 if (ArgIdx >= Args.size())
12
Assuming the condition is false
13
Taking false branch
3957 break; 3958 3959 ParamTypesForArgChecking.push_back(ParamType); 3960 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
14
Calling 'operator()'
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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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); 4404 auto NewTL = TLB.push<AutoTypeLoc>(Result); 4405 NewTL.setNameLoc(TL.getNameLoc()); 4406 return Result; 4407 } 4408 4409 QualType TransformDeducedTemplateSpecializationType( 4410 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) { 4411 if (!UseTypeSugar) 4412 return TransformDesugared(TLB, TL); 4413 4414 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType( 4415 TL.getTypePtr()->getTemplateName(), 4416 Replacement, Replacement.isNull()); 4417 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result); 4418 NewTL.setNameLoc(TL.getNameLoc()); 4419 return Result; 4420 } 4421 4422 ExprResult TransformLambdaExpr(LambdaExpr *E) { 4423 // Lambdas never need to be transformed. 4424 return E; 4425 } 4426 4427 QualType Apply(TypeLoc TL) { 4428 // Create some scratch storage for the transformed type locations. 4429 // FIXME: We're just going to throw this information away. Don't build it. 4430 TypeLocBuilder TLB; 4431 TLB.reserve(TL.getFullDataSize()); 4432 return TransformType(TLB, TL); 4433 } 4434 }; 4435 4436} // namespace 4437 4438Sema::DeduceAutoResult 4439Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result, 4440 Optional<unsigned> DependentDeductionDepth) { 4441 return DeduceAutoType(Type->getTypeLoc(), Init, Result, 4442 DependentDeductionDepth); 4443} 4444 4445/// Attempt to produce an informative diagostic explaining why auto deduction 4446/// failed. 4447/// \return \c true if diagnosed, \c false if not. 4448static bool diagnoseAutoDeductionFailure(Sema &S, 4449 Sema::TemplateDeductionResult TDK, 4450 TemplateDeductionInfo &Info, 4451 ArrayRef<SourceRange> Ranges) { 4452 switch (TDK) { 4453 case Sema::TDK_Inconsistent: { 4454 // Inconsistent deduction means we were deducing from an initializer list. 4455 auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction); 4456 D << Info.FirstArg << Info.SecondArg; 4457 for (auto R : Ranges) 4458 D << R; 4459 return true; 4460 } 4461 4462 // FIXME: Are there other cases for which a custom diagnostic is more useful 4463 // than the basic "types don't match" diagnostic? 4464 4465 default: 4466 return false; 4467 } 4468} 4469 4470/// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6) 4471/// 4472/// Note that this is done even if the initializer is dependent. (This is 4473/// necessary to support partial ordering of templates using 'auto'.) 4474/// A dependent type will be produced when deducing from a dependent type. 4475/// 4476/// \param Type the type pattern using the auto type-specifier. 4477/// \param Init the initializer for the variable whose type is to be deduced. 4478/// \param Result if type deduction was successful, this will be set to the 4479/// deduced type. 4480/// \param DependentDeductionDepth Set if we should permit deduction in 4481/// dependent cases. This is necessary for template partial ordering with 4482/// 'auto' template parameters. The value specified is the template 4483/// parameter depth at which we should perform 'auto' deduction. 4484Sema::DeduceAutoResult 4485Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result, 4486 Optional<unsigned> DependentDeductionDepth) { 4487 if (Init->getType()->isNonOverloadPlaceholderType()) { 4488 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init); 4489 if (NonPlaceholder.isInvalid()) 4490 return DAR_FailedAlreadyDiagnosed; 4491 Init = NonPlaceholder.get(); 4492 } 4493 4494 DependentAuto DependentResult = { 4495 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()}; 4496 4497 if (!DependentDeductionDepth && 4498 (Type.getType()->isDependentType() || Init->isTypeDependent() || 4499 Init->containsUnexpandedParameterPack())) { 4500 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type); 4501 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4501, __PRETTY_FUNCTION__))
; 4502 return DAR_Succeeded; 4503 } 4504 4505 // Find the depth of template parameter to synthesize. 4506 unsigned Depth = DependentDeductionDepth.getValueOr(0); 4507 4508 // If this is a 'decltype(auto)' specifier, do the decltype dance. 4509 // Since 'decltype(auto)' can only occur at the top of the type, we 4510 // don't need to go digging for it. 4511 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) { 4512 if (AT->isDecltypeAuto()) { 4513 if (isa<InitListExpr>(Init)) { 4514 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list); 4515 return DAR_FailedAlreadyDiagnosed; 4516 } 4517 4518 ExprResult ER = CheckPlaceholderExpr(Init); 4519 if (ER.isInvalid()) 4520 return DAR_FailedAlreadyDiagnosed; 4521 Init = ER.get(); 4522 QualType Deduced = BuildDecltypeType(Init, Init->getBeginLoc(), false); 4523 if (Deduced.isNull()) 4524 return DAR_FailedAlreadyDiagnosed; 4525 // FIXME: Support a non-canonical deduced type for 'auto'. 4526 Deduced = Context.getCanonicalType(Deduced); 4527 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type); 4528 if (Result.isNull()) 4529 return DAR_FailedAlreadyDiagnosed; 4530 return DAR_Succeeded; 4531 } else if (!getLangOpts().CPlusPlus) { 4532 if (isa<InitListExpr>(Init)) { 4533 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c); 4534 return DAR_FailedAlreadyDiagnosed; 4535 } 4536 } 4537 } 4538 4539 SourceLocation Loc = Init->getExprLoc(); 4540 4541 LocalInstantiationScope InstScope(*this); 4542 4543 // Build template<class TemplParam> void Func(FuncParam); 4544 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create( 4545 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false); 4546 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0); 4547 NamedDecl *TemplParamPtr = TemplParam; 4548 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt( 4549 Loc, Loc, TemplParamPtr, Loc, nullptr); 4550 4551 QualType FuncParam = 4552 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false) 4553 .Apply(Type); 4554 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4555, __PRETTY_FUNCTION__))
4555 "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4555, __PRETTY_FUNCTION__))
; 4556 4557 // Deduce type of TemplParam in Func(Init) 4558 SmallVector<DeducedTemplateArgument, 1> Deduced; 4559 Deduced.resize(1); 4560 4561 TemplateDeductionInfo Info(Loc, Depth); 4562 4563 // If deduction failed, don't diagnose if the initializer is dependent; it 4564 // might acquire a matching type in the instantiation. 4565 auto DeductionFailed = [&](TemplateDeductionResult TDK, 4566 ArrayRef<SourceRange> Ranges) -> DeduceAutoResult { 4567 if (Init->isTypeDependent()) { 4568 Result = 4569 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type); 4570 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4570, __PRETTY_FUNCTION__))
; 4571 return DAR_Succeeded; 4572 } 4573 if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges)) 4574 return DAR_FailedAlreadyDiagnosed; 4575 return DAR_Failed; 4576 }; 4577 4578 SmallVector<OriginalCallArg, 4> OriginalCallArgs; 4579 4580 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 4581 if (InitList) { 4582 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce 4583 // against that. Such deduction only succeeds if removing cv-qualifiers and 4584 // references results in std::initializer_list<T>. 4585 if (!Type.getType().getNonReferenceType()->getAs<AutoType>()) 4586 return DAR_Failed; 4587 4588 // Resolving a core issue: a braced-init-list containing any designators is 4589 // a non-deduced context. 4590 for (Expr *E : InitList->inits()) 4591 if (isa<DesignatedInitExpr>(E)) 4592 return DAR_Failed; 4593 4594 SourceRange DeducedFromInitRange; 4595 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) { 4596 Expr *Init = InitList->getInit(i); 4597 4598 if (auto TDK = DeduceTemplateArgumentsFromCallArgument( 4599 *this, TemplateParamsSt.get(), 0, TemplArg, Init, 4600 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true, 4601 /*ArgIdx*/ 0, /*TDF*/ 0)) 4602 return DeductionFailed(TDK, {DeducedFromInitRange, 4603 Init->getSourceRange()}); 4604 4605 if (DeducedFromInitRange.isInvalid() && 4606 Deduced[0].getKind() != TemplateArgument::Null) 4607 DeducedFromInitRange = Init->getSourceRange(); 4608 } 4609 } else { 4610 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) { 4611 Diag(Loc, diag::err_auto_bitfield); 4612 return DAR_FailedAlreadyDiagnosed; 4613 } 4614 4615 if (auto TDK = DeduceTemplateArgumentsFromCallArgument( 4616 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced, 4617 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0)) 4618 return DeductionFailed(TDK, {}); 4619 } 4620 4621 // Could be null if somehow 'auto' appears in a non-deduced context. 4622 if (Deduced[0].getKind() != TemplateArgument::Type) 4623 return DeductionFailed(TDK_Incomplete, {}); 4624 4625 QualType DeducedType = Deduced[0].getAsType(); 4626 4627 if (InitList) { 4628 DeducedType = BuildStdInitializerList(DeducedType, Loc); 4629 if (DeducedType.isNull()) 4630 return DAR_FailedAlreadyDiagnosed; 4631 } 4632 4633 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type); 4634 if (Result.isNull()) 4635 return DAR_FailedAlreadyDiagnosed; 4636 4637 // Check that the deduced argument type is compatible with the original 4638 // argument type per C++ [temp.deduct.call]p4. 4639 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result; 4640 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) { 4641 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4642, __PRETTY_FUNCTION__))
4642 "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4642, __PRETTY_FUNCTION__))
; 4643 if (auto TDK = 4644 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) { 4645 Result = QualType(); 4646 return DeductionFailed(TDK, {}); 4647 } 4648 } 4649 4650 return DAR_Succeeded; 4651} 4652 4653QualType Sema::SubstAutoType(QualType TypeWithAuto, 4654 QualType TypeToReplaceAuto) { 4655 if (TypeToReplaceAuto->isDependentType()) 4656 return SubstituteDeducedTypeTransform( 4657 *this, DependentAuto{ 4658 TypeToReplaceAuto->containsUnexpandedParameterPack()}) 4659 .TransformType(TypeWithAuto); 4660 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto) 4661 .TransformType(TypeWithAuto); 4662} 4663 4664TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 4665 QualType TypeToReplaceAuto) { 4666 if (TypeToReplaceAuto->isDependentType()) 4667 return SubstituteDeducedTypeTransform( 4668 *this, 4669 DependentAuto{ 4670 TypeToReplaceAuto->containsUnexpandedParameterPack()}) 4671 .TransformType(TypeWithAuto); 4672 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto) 4673 .TransformType(TypeWithAuto); 4674} 4675 4676QualType Sema::ReplaceAutoType(QualType TypeWithAuto, 4677 QualType TypeToReplaceAuto) { 4678 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto, 4679 /*UseTypeSugar*/ false) 4680 .TransformType(TypeWithAuto); 4681} 4682 4683void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) { 4684 if (isa<InitListExpr>(Init)) 4685 Diag(VDecl->getLocation(), 4686 VDecl->isInitCapture() 4687 ? diag::err_init_capture_deduction_failure_from_init_list 4688 : diag::err_auto_var_deduction_failure_from_init_list) 4689 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange(); 4690 else 4691 Diag(VDecl->getLocation(), 4692 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure 4693 : diag::err_auto_var_deduction_failure) 4694 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 4695 << Init->getSourceRange(); 4696} 4697 4698bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 4699 bool Diagnose) { 4700 assert(FD->getReturnType()->isUndeducedType())((FD->getReturnType()->isUndeducedType()) ? static_cast
<void> (0) : __assert_fail ("FD->getReturnType()->isUndeducedType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4700, __PRETTY_FUNCTION__))
; 4701 4702 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)' 4703 // within the return type from the call operator's type. 4704 if (isLambdaConversionOperator(FD)) { 4705 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent(); 4706 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 4707 4708 // For a generic lambda, instantiate the call operator if needed. 4709 if (auto *Args = FD->getTemplateSpecializationArgs()) { 4710 CallOp = InstantiateFunctionDeclaration( 4711 CallOp->getDescribedFunctionTemplate(), Args, Loc); 4712 if (!CallOp || CallOp->isInvalidDecl()) 4713 return true; 4714 4715 // We might need to deduce the return type by instantiating the definition 4716 // of the operator() function. 4717 if (CallOp->getReturnType()->isUndeducedType()) { 4718 runWithSufficientStackSpace(Loc, [&] { 4719 InstantiateFunctionDefinition(Loc, CallOp); 4720 }); 4721 } 4722 } 4723 4724 if (CallOp->isInvalidDecl()) 4725 return true; 4726 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4727, __PRETTY_FUNCTION__))
4727 "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4727, __PRETTY_FUNCTION__))
; 4728 4729 // Build the new return type from scratch. 4730 QualType RetType = getLambdaConversionFunctionResultType( 4731 CallOp->getType()->castAs<FunctionProtoType>()); 4732 if (FD->getReturnType()->getAs<PointerType>()) 4733 RetType = Context.getPointerType(RetType); 4734 else { 4735 assert(FD->getReturnType()->getAs<BlockPointerType>())((FD->getReturnType()->getAs<BlockPointerType>())
? static_cast<void> (0) : __assert_fail ("FD->getReturnType()->getAs<BlockPointerType>()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4735, __PRETTY_FUNCTION__))
; 4736 RetType = Context.getBlockPointerType(RetType); 4737 } 4738 Context.adjustDeducedFunctionResultType(FD, RetType); 4739 return false; 4740 } 4741 4742 if (FD->getTemplateInstantiationPattern()) { 4743 runWithSufficientStackSpace(Loc, [&] { 4744 InstantiateFunctionDefinition(Loc, FD); 4745 }); 4746 } 4747 4748 bool StillUndeduced = FD->getReturnType()->isUndeducedType(); 4749 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) { 4750 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD; 4751 Diag(FD->getLocation(), diag::note_callee_decl) << FD; 4752 } 4753 4754 return StillUndeduced; 4755} 4756 4757/// If this is a non-static member function, 4758static void 4759AddImplicitObjectParameterType(ASTContext &Context, 4760 CXXMethodDecl *Method, 4761 SmallVectorImpl<QualType> &ArgTypes) { 4762 // C++11 [temp.func.order]p3: 4763 // [...] The new parameter is of type "reference to cv A," where cv are 4764 // the cv-qualifiers of the function template (if any) and A is 4765 // the class of which the function template is a member. 4766 // 4767 // The standard doesn't say explicitly, but we pick the appropriate kind of 4768 // reference type based on [over.match.funcs]p4. 4769 QualType ArgTy = Context.getTypeDeclType(Method->getParent()); 4770 ArgTy = Context.getQualifiedType(ArgTy, Method->getMethodQualifiers()); 4771 if (Method->getRefQualifier() == RQ_RValue) 4772 ArgTy = Context.getRValueReferenceType(ArgTy); 4773 else 4774 ArgTy = Context.getLValueReferenceType(ArgTy); 4775 ArgTypes.push_back(ArgTy); 4776} 4777 4778/// Determine whether the function template \p FT1 is at least as 4779/// specialized as \p FT2. 4780static bool isAtLeastAsSpecializedAs(Sema &S, 4781 SourceLocation Loc, 4782 FunctionTemplateDecl *FT1, 4783 FunctionTemplateDecl *FT2, 4784 TemplatePartialOrderingContext TPOC, 4785 unsigned NumCallArguments1) { 4786 FunctionDecl *FD1 = FT1->getTemplatedDecl(); 4787 FunctionDecl *FD2 = FT2->getTemplatedDecl(); 4788 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>(); 4789 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>(); 4790 4791 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4791, __PRETTY_FUNCTION__))
; 4792 TemplateParameterList *TemplateParams = FT2->getTemplateParameters(); 4793 SmallVector<DeducedTemplateArgument, 4> Deduced; 4794 Deduced.resize(TemplateParams->size()); 4795 4796 // C++0x [temp.deduct.partial]p3: 4797 // The types used to determine the ordering depend on the context in which 4798 // the partial ordering is done: 4799 TemplateDeductionInfo Info(Loc); 4800 SmallVector<QualType, 4> Args2; 4801 switch (TPOC) { 4802 case TPOC_Call: { 4803 // - In the context of a function call, the function parameter types are 4804 // used. 4805 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1); 4806 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2); 4807 4808 // C++11 [temp.func.order]p3: 4809 // [...] If only one of the function templates is a non-static 4810 // member, that function template is considered to have a new 4811 // first parameter inserted in its function parameter list. The 4812 // new parameter is of type "reference to cv A," where cv are 4813 // the cv-qualifiers of the function template (if any) and A is 4814 // the class of which the function template is a member. 4815 // 4816 // Note that we interpret this to mean "if one of the function 4817 // templates is a non-static member and the other is a non-member"; 4818 // otherwise, the ordering rules for static functions against non-static 4819 // functions don't make any sense. 4820 // 4821 // C++98/03 doesn't have this provision but we've extended DR532 to cover 4822 // it as wording was broken prior to it. 4823 SmallVector<QualType, 4> Args1; 4824 4825 unsigned NumComparedArguments = NumCallArguments1; 4826 4827 if (!Method2 && Method1 && !Method1->isStatic()) { 4828 // Compare 'this' from Method1 against first parameter from Method2. 4829 AddImplicitObjectParameterType(S.Context, Method1, Args1); 4830 ++NumComparedArguments; 4831 } else if (!Method1 && Method2 && !Method2->isStatic()) { 4832 // Compare 'this' from Method2 against first parameter from Method1. 4833 AddImplicitObjectParameterType(S.Context, Method2, Args2); 4834 } 4835 4836 Args1.insert(Args1.end(), Proto1->param_type_begin(), 4837 Proto1->param_type_end()); 4838 Args2.insert(Args2.end(), Proto2->param_type_begin(), 4839 Proto2->param_type_end()); 4840 4841 // C++ [temp.func.order]p5: 4842 // The presence of unused ellipsis and default arguments has no effect on 4843 // the partial ordering of function templates. 4844 if (Args1.size() > NumComparedArguments) 4845 Args1.resize(NumComparedArguments); 4846 if (Args2.size() > NumComparedArguments) 4847 Args2.resize(NumComparedArguments); 4848 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(), 4849 Args1.data(), Args1.size(), Info, Deduced, 4850 TDF_None, /*PartialOrdering=*/true)) 4851 return false; 4852 4853 break; 4854 } 4855 4856 case TPOC_Conversion: 4857 // - In the context of a call to a conversion operator, the return types 4858 // of the conversion function templates are used. 4859 if (DeduceTemplateArgumentsByTypeMatch( 4860 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(), 4861 Info, Deduced, TDF_None, 4862 /*PartialOrdering=*/true)) 4863 return false; 4864 break; 4865 4866 case TPOC_Other: 4867 // - In other contexts (14.6.6.2) the function template's function type 4868 // is used. 4869 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 4870 FD2->getType(), FD1->getType(), 4871 Info, Deduced, TDF_None, 4872 /*PartialOrdering=*/true)) 4873 return false; 4874 break; 4875 } 4876 4877 // C++0x [temp.deduct.partial]p11: 4878 // In most cases, all template parameters must have values in order for 4879 // deduction to succeed, but for partial ordering purposes a template 4880 // parameter may remain without a value provided it is not used in the 4881 // types being used for partial ordering. [ Note: a template parameter used 4882 // in a non-deduced context is considered used. -end note] 4883 unsigned ArgIdx = 0, NumArgs = Deduced.size(); 4884 for (; ArgIdx != NumArgs; ++ArgIdx) 4885 if (Deduced[ArgIdx].isNull()) 4886 break; 4887 4888 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need 4889 // to substitute the deduced arguments back into the template and check that 4890 // we get the right type. 4891 4892 if (ArgIdx == NumArgs) { 4893 // All template arguments were deduced. FT1 is at least as specialized 4894 // as FT2. 4895 return true; 4896 } 4897 4898 // Figure out which template parameters were used. 4899 llvm::SmallBitVector UsedParameters(TemplateParams->size()); 4900 switch (TPOC) { 4901 case TPOC_Call: 4902 for (unsigned I = 0, N = Args2.size(); I != N; ++I) 4903 ::MarkUsedTemplateParameters(S.Context, Args2[I], false, 4904 TemplateParams->getDepth(), 4905 UsedParameters); 4906 break; 4907 4908 case TPOC_Conversion: 4909 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false, 4910 TemplateParams->getDepth(), UsedParameters); 4911 break; 4912 4913 case TPOC_Other: 4914 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false, 4915 TemplateParams->getDepth(), 4916 UsedParameters); 4917 break; 4918 } 4919 4920 for (; ArgIdx != NumArgs; ++ArgIdx) 4921 // If this argument had no value deduced but was used in one of the types 4922 // used for partial ordering, then deduction fails. 4923 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx]) 4924 return false; 4925 4926 return true; 4927} 4928 4929/// Determine whether this a function template whose parameter-type-list 4930/// ends with a function parameter pack. 4931static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) { 4932 FunctionDecl *Function = FunTmpl->getTemplatedDecl(); 4933 unsigned NumParams = Function->getNumParams(); 4934 if (NumParams == 0) 4935 return false; 4936 4937 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1); 4938 if (!Last->isParameterPack()) 4939 return false; 4940 4941 // Make sure that no previous parameter is a parameter pack. 4942 while (--NumParams > 0) { 4943 if (Function->getParamDecl(NumParams - 1)->isParameterPack()) 4944 return false; 4945 } 4946 4947 return true; 4948} 4949 4950/// Returns the more specialized function template according 4951/// to the rules of function template partial ordering (C++ [temp.func.order]). 4952/// 4953/// \param FT1 the first function template 4954/// 4955/// \param FT2 the second function template 4956/// 4957/// \param TPOC the context in which we are performing partial ordering of 4958/// function templates. 4959/// 4960/// \param NumCallArguments1 The number of arguments in the call to FT1, used 4961/// only when \c TPOC is \c TPOC_Call. 4962/// 4963/// \param NumCallArguments2 The number of arguments in the call to FT2, used 4964/// only when \c TPOC is \c TPOC_Call. 4965/// 4966/// \returns the more specialized function template. If neither 4967/// template is more specialized, returns NULL. 4968FunctionTemplateDecl * 4969Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 4970 FunctionTemplateDecl *FT2, 4971 SourceLocation Loc, 4972 TemplatePartialOrderingContext TPOC, 4973 unsigned NumCallArguments1, 4974 unsigned NumCallArguments2) { 4975 4976 auto JudgeByConstraints = [&] () -> FunctionTemplateDecl * { 4977 llvm::SmallVector<const Expr *, 3> AC1, AC2; 4978 FT1->getAssociatedConstraints(AC1); 4979 FT2->getAssociatedConstraints(AC2); 4980 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 4981 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1)) 4982 return nullptr; 4983 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2)) 4984 return nullptr; 4985 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 4986 return nullptr; 4987 return AtLeastAsConstrained1 ? FT1 : FT2; 4988 }; 4989 4990 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 4991 NumCallArguments1); 4992 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, 4993 NumCallArguments2); 4994 4995 if (Better1 != Better2) // We have a clear winner 4996 return Better1 ? FT1 : FT2; 4997 4998 if (!Better1 && !Better2) // Neither is better than the other 4999 return JudgeByConstraints(); 5000 5001 // FIXME: This mimics what GCC implements, but doesn't match up with the 5002 // proposed resolution for core issue 692. This area needs to be sorted out, 5003 // but for now we attempt to maintain compatibility. 5004 bool Variadic1 = isVariadicFunctionTemplate(FT1); 5005 bool Variadic2 = isVariadicFunctionTemplate(FT2); 5006 if (Variadic1 != Variadic2) 5007 return Variadic1? FT2 : FT1; 5008 5009 return JudgeByConstraints(); 5010} 5011 5012/// Determine if the two templates are equivalent. 5013static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) { 5014 if (T1 == T2) 5015 return true; 5016 5017 if (!T1 || !T2) 5018 return false; 5019 5020 return T1->getCanonicalDecl() == T2->getCanonicalDecl(); 5021} 5022 5023/// Retrieve the most specialized of the given function template 5024/// specializations. 5025/// 5026/// \param SpecBegin the start iterator of the function template 5027/// specializations that we will be comparing. 5028/// 5029/// \param SpecEnd the end iterator of the function template 5030/// specializations, paired with \p SpecBegin. 5031/// 5032/// \param Loc the location where the ambiguity or no-specializations 5033/// diagnostic should occur. 5034/// 5035/// \param NoneDiag partial diagnostic used to diagnose cases where there are 5036/// no matching candidates. 5037/// 5038/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one 5039/// occurs. 5040/// 5041/// \param CandidateDiag partial diagnostic used for each function template 5042/// specialization that is a candidate in the ambiguous ordering. One parameter 5043/// in this diagnostic should be unbound, which will correspond to the string 5044/// describing the template arguments for the function template specialization. 5045/// 5046/// \returns the most specialized function template specialization, if 5047/// found. Otherwise, returns SpecEnd. 5048UnresolvedSetIterator Sema::getMostSpecialized( 5049 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd, 5050 TemplateSpecCandidateSet &FailedCandidates, 5051 SourceLocation Loc, const PartialDiagnostic &NoneDiag, 5052 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, 5053 bool Complain, QualType TargetType) { 5054 if (SpecBegin == SpecEnd) { 5055 if (Complain) { 5056 Diag(Loc, NoneDiag); 5057 FailedCandidates.NoteCandidates(*this, Loc); 5058 } 5059 return SpecEnd; 5060 } 5061 5062 if (SpecBegin + 1 == SpecEnd) 5063 return SpecBegin; 5064 5065 // Find the function template that is better than all of the templates it 5066 // has been compared to. 5067 UnresolvedSetIterator Best = SpecBegin; 5068 FunctionTemplateDecl *BestTemplate 5069 = cast<FunctionDecl>(*Best)->getPrimaryTemplate(); 5070 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5070, __PRETTY_FUNCTION__))
; 5071 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) { 5072 FunctionTemplateDecl *Challenger 5073 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 5074 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5074, __PRETTY_FUNCTION__))
; 5075 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 5076 Loc, TPOC_Other, 0, 0), 5077 Challenger)) { 5078 Best = I; 5079 BestTemplate = Challenger; 5080 } 5081 } 5082 5083 // Make sure that the "best" function template is more specialized than all 5084 // of the others. 5085 bool Ambiguous = false; 5086 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 5087 FunctionTemplateDecl *Challenger 5088 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 5089 if (I != Best && 5090 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 5091 Loc, TPOC_Other, 0, 0), 5092 BestTemplate)) { 5093 Ambiguous = true; 5094 break; 5095 } 5096 } 5097 5098 if (!Ambiguous) { 5099 // We found an answer. Return it. 5100 return Best; 5101 } 5102 5103 // Diagnose the ambiguity. 5104 if (Complain) { 5105 Diag(Loc, AmbigDiag); 5106 5107 // FIXME: Can we order the candidates in some sane way? 5108 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 5109 PartialDiagnostic PD = CandidateDiag; 5110 const auto *FD = cast<FunctionDecl>(*I); 5111 PD << FD << getTemplateArgumentBindingsText( 5112 FD->getPrimaryTemplate()->getTemplateParameters(), 5113 *FD->getTemplateSpecializationArgs()); 5114 if (!TargetType.isNull()) 5115 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType); 5116 Diag((*I)->getLocation(), PD); 5117 } 5118 } 5119 5120 return SpecEnd; 5121} 5122 5123/// Determine whether one partial specialization, P1, is at least as 5124/// specialized than another, P2. 5125/// 5126/// \tparam TemplateLikeDecl The kind of P2, which must be a 5127/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl. 5128/// \param T1 The injected-class-name of P1 (faked for a variable template). 5129/// \param T2 The injected-class-name of P2 (faked for a variable template). 5130template<typename TemplateLikeDecl> 5131static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2, 5132 TemplateLikeDecl *P2, 5133 TemplateDeductionInfo &Info) { 5134 // C++ [temp.class.order]p1: 5135 // For two class template partial specializations, the first is at least as 5136 // specialized as the second if, given the following rewrite to two 5137 // function templates, the first function template is at least as 5138 // specialized as the second according to the ordering rules for function 5139 // templates (14.6.6.2): 5140 // - the first function template has the same template parameters as the 5141 // first partial specialization and has a single function parameter 5142 // whose type is a class template specialization with the template 5143 // arguments of the first partial specialization, and 5144 // - the second function template has the same template parameters as the 5145 // second partial specialization and has a single function parameter 5146 // whose type is a class template specialization with the template 5147 // arguments of the second partial specialization. 5148 // 5149 // Rather than synthesize function templates, we merely perform the 5150 // equivalent partial ordering by performing deduction directly on 5151 // the template arguments of the class template partial 5152 // specializations. This computation is slightly simpler than the 5153 // general problem of function template partial ordering, because 5154 // class template partial specializations are more constrained. We 5155 // know that every template parameter is deducible from the class 5156 // template partial specialization's template arguments, for 5157 // example. 5158 SmallVector<DeducedTemplateArgument, 4> Deduced; 5159 5160 // Determine whether P1 is at least as specialized as P2. 5161 Deduced.resize(P2->getTemplateParameters()->size()); 5162 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(), 5163 T2, T1, Info, Deduced, TDF_None, 5164 /*PartialOrdering=*/true)) 5165 return false; 5166 5167 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), 5168 Deduced.end()); 5169 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs, 5170 Info); 5171 auto *TST1 = T1->castAs<TemplateSpecializationType>(); 5172 if (FinishTemplateArgumentDeduction( 5173 S, P2, /*IsPartialOrdering=*/true, 5174 TemplateArgumentList(TemplateArgumentList::OnStack, 5175 TST1->template_arguments()), 5176 Deduced, Info)) 5177 return false; 5178 5179 return true; 5180} 5181 5182/// Returns the more specialized class template partial specialization 5183/// according to the rules of partial ordering of class template partial 5184/// specializations (C++ [temp.class.order]). 5185/// 5186/// \param PS1 the first class template partial specialization 5187/// 5188/// \param PS2 the second class template partial specialization 5189/// 5190/// \returns the more specialized class template partial specialization. If 5191/// neither partial specialization is more specialized, returns NULL. 5192ClassTemplatePartialSpecializationDecl * 5193Sema::getMoreSpecializedPartialSpecialization( 5194 ClassTemplatePartialSpecializationDecl *PS1, 5195 ClassTemplatePartialSpecializationDecl *PS2, 5196 SourceLocation Loc) { 5197 QualType PT1 = PS1->getInjectedSpecializationType(); 5198 QualType PT2 = PS2->getInjectedSpecializationType(); 5199 5200 TemplateDeductionInfo Info(Loc); 5201 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info); 5202 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info); 5203 5204 if (!Better1 && !Better2) 5205 return nullptr; 5206 if (Better1 && Better2) { 5207 llvm::SmallVector<const Expr *, 3> AC1, AC2; 5208 PS1->getAssociatedConstraints(AC1); 5209 PS2->getAssociatedConstraints(AC2); 5210 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 5211 if (IsAtLeastAsConstrained(PS1, AC1, PS2, AC2, AtLeastAsConstrained1)) 5212 return nullptr; 5213 if (IsAtLeastAsConstrained(PS2, AC2, PS1, AC1, AtLeastAsConstrained2)) 5214 return nullptr; 5215 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 5216 return nullptr; 5217 return AtLeastAsConstrained1 ? PS1 : PS2; 5218 } 5219 5220 return Better1 ? PS1 : PS2; 5221} 5222 5223bool Sema::isMoreSpecializedThanPrimary( 5224 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) { 5225 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate(); 5226 QualType PrimaryT = Primary->getInjectedClassNameSpecialization(); 5227 QualType PartialT = Spec->getInjectedSpecializationType(); 5228 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info)) 5229 return false; 5230 if (!isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) 5231 return true; 5232 Info.clearSFINAEDiagnostic(); 5233 llvm::SmallVector<const Expr *, 3> PrimaryAC, SpecAC; 5234 Primary->getAssociatedConstraints(PrimaryAC); 5235 Spec->getAssociatedConstraints(SpecAC); 5236 bool AtLeastAsConstrainedPrimary, AtLeastAsConstrainedSpec; 5237 if (IsAtLeastAsConstrained(Spec, SpecAC, Primary, PrimaryAC, 5238 AtLeastAsConstrainedSpec)) 5239 return false; 5240 if (!AtLeastAsConstrainedSpec) 5241 return false; 5242 if (IsAtLeastAsConstrained(Primary, PrimaryAC, Spec, SpecAC, 5243 AtLeastAsConstrainedPrimary)) 5244 return false; 5245 return !AtLeastAsConstrainedPrimary; 5246} 5247 5248VarTemplatePartialSpecializationDecl * 5249Sema::getMoreSpecializedPartialSpecialization( 5250 VarTemplatePartialSpecializationDecl *PS1, 5251 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) { 5252 // Pretend the variable template specializations are class template 5253 // specializations and form a fake injected class name type for comparison. 5254 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5256, __PRETTY_FUNCTION__))
5255 "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5256, __PRETTY_FUNCTION__))
5256 " 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5256, __PRETTY_FUNCTION__))
; 5257 TemplateName Name(PS1->getSpecializedTemplate()); 5258 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 5259 QualType PT1 = Context.getTemplateSpecializationType( 5260 CanonTemplate, PS1->getTemplateArgs().asArray()); 5261 QualType PT2 = Context.getTemplateSpecializationType( 5262 CanonTemplate, PS2->getTemplateArgs().asArray()); 5263 5264 TemplateDeductionInfo Info(Loc); 5265 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info); 5266 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info); 5267 5268 if (!Better1 && !Better2) 5269 return nullptr; 5270 if (Better1 && Better2) { 5271 llvm::SmallVector<const Expr *, 3> AC1, AC2; 5272 PS1->getAssociatedConstraints(AC1); 5273 PS2->getAssociatedConstraints(AC2); 5274 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 5275 if (IsAtLeastAsConstrained(PS1, AC1, PS2, AC2, AtLeastAsConstrained1)) 5276 return nullptr; 5277 if (IsAtLeastAsConstrained(PS2, AC2, PS1, AC1, AtLeastAsConstrained2)) 5278 return nullptr; 5279 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) { 5280 return nullptr; 5281 } 5282 return AtLeastAsConstrained1 ? PS1 : PS2; 5283 } 5284 5285 return Better1 ? PS1 : PS2; 5286} 5287 5288bool Sema::isMoreSpecializedThanPrimary( 5289 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) { 5290 TemplateDecl *Primary = Spec->getSpecializedTemplate(); 5291 // FIXME: Cache the injected template arguments rather than recomputing 5292 // them for each partial specialization. 5293 SmallVector<TemplateArgument, 8> PrimaryArgs; 5294 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(), 5295 PrimaryArgs); 5296 5297 TemplateName CanonTemplate = 5298 Context.getCanonicalTemplateName(TemplateName(Primary)); 5299 QualType PrimaryT = Context.getTemplateSpecializationType( 5300 CanonTemplate, PrimaryArgs); 5301 QualType PartialT = Context.getTemplateSpecializationType( 5302 CanonTemplate, Spec->getTemplateArgs().asArray()); 5303 5304 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info)) 5305 return false; 5306 if (!isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) 5307 return true; 5308 Info.clearSFINAEDiagnostic(); 5309 llvm::SmallVector<const Expr *, 3> PrimaryAC, SpecAC; 5310 Primary->getAssociatedConstraints(PrimaryAC); 5311 Spec->getAssociatedConstraints(SpecAC); 5312 bool AtLeastAsConstrainedPrimary, AtLeastAsConstrainedSpec; 5313 if (IsAtLeastAsConstrained(Spec, SpecAC, Primary, PrimaryAC, 5314 AtLeastAsConstrainedSpec)) 5315 return false; 5316 if (!AtLeastAsConstrainedSpec) 5317 return false; 5318 if (IsAtLeastAsConstrained(Primary, PrimaryAC, Spec, SpecAC, 5319 AtLeastAsConstrainedPrimary)) 5320 return false; 5321 return !AtLeastAsConstrainedPrimary; 5322} 5323 5324bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs( 5325 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) { 5326 // C++1z [temp.arg.template]p4: (DR 150) 5327 // A template template-parameter P is at least as specialized as a 5328 // template template-argument A if, given the following rewrite to two 5329 // function templates... 5330 5331 // Rather than synthesize function templates, we merely perform the 5332 // equivalent partial ordering by performing deduction directly on 5333 // the template parameter lists of the template template parameters. 5334 // 5335 // Given an invented class template X with the template parameter list of 5336 // A (including default arguments): 5337 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg)); 5338 TemplateParameterList *A = AArg->getTemplateParameters(); 5339 5340 // - Each function template has a single function parameter whose type is 5341 // a specialization of X with template arguments corresponding to the 5342 // template parameters from the respective function template 5343 SmallVector<TemplateArgument, 8> AArgs; 5344 Context.getInjectedTemplateArgs(A, AArgs); 5345 5346 // Check P's arguments against A's parameter list. This will fill in default 5347 // template arguments as needed. AArgs are already correct by construction. 5348 // We can't just use CheckTemplateIdType because that will expand alias 5349 // templates. 5350 SmallVector<TemplateArgument, 4> PArgs; 5351 { 5352 SFINAETrap Trap(*this); 5353 5354 Context.getInjectedTemplateArgs(P, PArgs); 5355 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc()); 5356 for (unsigned I = 0, N = P->size(); I != N; ++I) { 5357 // Unwrap packs that getInjectedTemplateArgs wrapped around pack 5358 // expansions, to form an "as written" argument list. 5359 TemplateArgument Arg = PArgs[I]; 5360 if (Arg.getKind() == TemplateArgument::Pack) { 5361 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5361, __PRETTY_FUNCTION__))
; 5362 Arg = *Arg.pack_begin(); 5363 } 5364 PArgList.addArgument(getTrivialTemplateArgumentLoc( 5365 Arg, QualType(), P->getParam(I)->getLocation())); 5366 } 5367 PArgs.clear(); 5368 5369 // C++1z [temp.arg.template]p3: 5370 // If the rewrite produces an invalid type, then P is not at least as 5371 // specialized as A. 5372 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) || 5373 Trap.hasErrorOccurred()) 5374 return false; 5375 } 5376 5377 QualType AType = Context.getTemplateSpecializationType(X, AArgs); 5378 QualType PType = Context.getTemplateSpecializationType(X, PArgs); 5379 5380 // ... the function template corresponding to P is at least as specialized 5381 // as the function template corresponding to A according to the partial 5382 // ordering rules for function templates. 5383 TemplateDeductionInfo Info(Loc, A->getDepth()); 5384 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info); 5385} 5386 5387namespace { 5388struct MarkUsedTemplateParameterVisitor : 5389 RecursiveASTVisitor<MarkUsedTemplateParameterVisitor> { 5390 llvm::SmallBitVector &Used; 5391 unsigned Depth; 5392 5393 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used, 5394 unsigned Depth) 5395 : Used(Used), Depth(Depth) { } 5396 5397 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) { 5398 if (T->getDepth() == Depth) 5399 Used[T->getIndex()] = true; 5400 return true; 5401 } 5402 5403 bool TraverseTemplateName(TemplateName Template) { 5404 if (auto *TTP = 5405 dyn_cast<TemplateTemplateParmDecl>(Template.getAsTemplateDecl())) 5406 if (TTP->getDepth() == Depth) 5407 Used[TTP->getIndex()] = true; 5408 RecursiveASTVisitor<MarkUsedTemplateParameterVisitor>:: 5409 TraverseTemplateName(Template); 5410 return true; 5411 } 5412 5413 bool VisitDeclRefExpr(DeclRefExpr *E) { 5414 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) 5415 if (NTTP->getDepth() == Depth) 5416 Used[NTTP->getIndex()] = true; 5417 return true; 5418 } 5419}; 5420} 5421 5422/// Mark the template parameters that are used by the given 5423/// expression. 5424static void 5425MarkUsedTemplateParameters(ASTContext &Ctx, 5426 const Expr *E, 5427 bool OnlyDeduced, 5428 unsigned Depth, 5429 llvm::SmallBitVector &Used) { 5430 if (!OnlyDeduced) { 5431 MarkUsedTemplateParameterVisitor(Used, Depth) 5432 .TraverseStmt(const_cast<Expr *>(E)); 5433 return; 5434 } 5435 5436 // We can deduce from a pack expansion. 5437 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E)) 5438 E = Expansion->getPattern(); 5439 5440 // Skip through any implicit casts we added while type-checking, and any 5441 // substitutions performed by template alias expansion. 5442 while (true) { 5443 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 5444 E = ICE->getSubExpr(); 5445 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(E)) 5446 E = CE->getSubExpr(); 5447 else if (const SubstNonTypeTemplateParmExpr *Subst = 5448 dyn_cast<SubstNonTypeTemplateParmExpr>(E)) 5449 E = Subst->getReplacement(); 5450 else 5451 break; 5452 } 5453 5454 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 5455 if (!DRE) 5456 return; 5457 5458 const NonTypeTemplateParmDecl *NTTP 5459 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); 5460 if (!NTTP) 5461 return; 5462 5463 if (NTTP->getDepth() == Depth) 5464 Used[NTTP->getIndex()] = true; 5465 5466 // In C++17 mode, additional arguments may be deduced from the type of a 5467 // non-type argument. 5468 if (Ctx.getLangOpts().CPlusPlus17) 5469 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used); 5470} 5471 5472/// Mark the template parameters that are used by the given 5473/// nested name specifier. 5474static void 5475MarkUsedTemplateParameters(ASTContext &Ctx, 5476 NestedNameSpecifier *NNS, 5477 bool OnlyDeduced, 5478 unsigned Depth, 5479 llvm::SmallBitVector &Used) { 5480 if (!NNS) 5481 return; 5482 5483 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth, 5484 Used); 5485 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0), 5486 OnlyDeduced, Depth, Used); 5487} 5488 5489/// Mark the template parameters that are used by the given 5490/// template name. 5491static void 5492MarkUsedTemplateParameters(ASTContext &Ctx, 5493 TemplateName Name, 5494 bool OnlyDeduced, 5495 unsigned Depth, 5496 llvm::SmallBitVector &Used) { 5497 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 5498 if (TemplateTemplateParmDecl *TTP 5499 = dyn_cast<TemplateTemplateParmDecl>(Template)) { 5500 if (TTP->getDepth() == Depth) 5501 Used[TTP->getIndex()] = true; 5502 } 5503 return; 5504 } 5505 5506 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) 5507 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced, 5508 Depth, Used); 5509 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) 5510 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced, 5511 Depth, Used); 5512} 5513 5514/// Mark the template parameters that are used by the given 5515/// type. 5516static void 5517MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, 5518 bool OnlyDeduced, 5519 unsigned Depth, 5520 llvm::SmallBitVector &Used) { 5521 if (T.isNull()) 5522 return; 5523 5524 // Non-dependent types have nothing deducible 5525 if (!T->isDependentType()) 5526 return; 5527 5528 T = Ctx.getCanonicalType(T); 5529 switch (T->getTypeClass()) { 5530 case Type::Pointer: 5531 MarkUsedTemplateParameters(Ctx, 5532 cast<PointerType>(T)->getPointeeType(), 5533 OnlyDeduced, 5534 Depth, 5535 Used); 5536 break; 5537 5538 case Type::BlockPointer: 5539 MarkUsedTemplateParameters(Ctx, 5540 cast<BlockPointerType>(T)->getPointeeType(), 5541 OnlyDeduced, 5542 Depth, 5543 Used); 5544 break; 5545 5546 case Type::LValueReference: 5547 case Type::RValueReference: 5548 MarkUsedTemplateParameters(Ctx, 5549 cast<ReferenceType>(T)->getPointeeType(), 5550 OnlyDeduced, 5551 Depth, 5552 Used); 5553 break; 5554 5555 case Type::MemberPointer: { 5556 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr()); 5557 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced, 5558 Depth, Used); 5559 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0), 5560 OnlyDeduced, Depth, Used); 5561 break; 5562 } 5563 5564 case Type::DependentSizedArray: 5565 MarkUsedTemplateParameters(Ctx, 5566 cast<DependentSizedArrayType>(T)->getSizeExpr(), 5567 OnlyDeduced, Depth, Used); 5568 // Fall through to check the element type 5569 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 5570 5571 case Type::ConstantArray: 5572 case Type::IncompleteArray: 5573 MarkUsedTemplateParameters(Ctx, 5574 cast<ArrayType>(T)->getElementType(), 5575 OnlyDeduced, Depth, Used); 5576 break; 5577 5578 case Type::Vector: 5579 case Type::ExtVector: 5580 MarkUsedTemplateParameters(Ctx, 5581 cast<VectorType>(T)->getElementType(), 5582 OnlyDeduced, Depth, Used); 5583 break; 5584 5585 case Type::DependentVector: { 5586 const auto *VecType = cast<DependentVectorType>(T); 5587 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced, 5588 Depth, Used); 5589 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth, 5590 Used); 5591 break; 5592 } 5593 case Type::DependentSizedExtVector: { 5594 const DependentSizedExtVectorType *VecType 5595 = cast<DependentSizedExtVectorType>(T); 5596 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced, 5597 Depth, Used); 5598 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, 5599 Depth, Used); 5600 break; 5601 } 5602 5603 case Type::DependentAddressSpace: { 5604 const DependentAddressSpaceType *DependentASType = 5605 cast<DependentAddressSpaceType>(T); 5606 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(), 5607 OnlyDeduced, Depth, Used); 5608 MarkUsedTemplateParameters(Ctx, 5609 DependentASType->getAddrSpaceExpr(), 5610 OnlyDeduced, Depth, Used); 5611 break; 5612 } 5613 5614 case Type::FunctionProto: { 5615 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 5616 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth, 5617 Used); 5618 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) { 5619 // C++17 [temp.deduct.type]p5: 5620 // The non-deduced contexts are: [...] 5621 // -- A function parameter pack that does not occur at the end of the 5622 // parameter-declaration-list. 5623 if (!OnlyDeduced || I + 1 == N || 5624 !Proto->getParamType(I)->getAs<PackExpansionType>()) { 5625 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced, 5626 Depth, Used); 5627 } else { 5628 // FIXME: C++17 [temp.deduct.call]p1: 5629 // When a function parameter pack appears in a non-deduced context, 5630 // the type of that pack is never deduced. 5631 // 5632 // We should also track a set of "never deduced" parameters, and 5633 // subtract that from the list of deduced parameters after marking. 5634 } 5635 } 5636 if (auto *E = Proto->getNoexceptExpr()) 5637 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used); 5638 break; 5639 } 5640 5641 case Type::TemplateTypeParm: { 5642 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T); 5643 if (TTP->getDepth() == Depth) 5644 Used[TTP->getIndex()] = true; 5645 break; 5646 } 5647 5648 case Type::SubstTemplateTypeParmPack: { 5649 const SubstTemplateTypeParmPackType *Subst 5650 = cast<SubstTemplateTypeParmPackType>(T); 5651 MarkUsedTemplateParameters(Ctx, 5652 QualType(Subst->getReplacedParameter(), 0), 5653 OnlyDeduced, Depth, Used); 5654 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), 5655 OnlyDeduced, Depth, Used); 5656 break; 5657 } 5658 5659 case Type::InjectedClassName: 5660 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType(); 5661 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 5662 5663 case Type::TemplateSpecialization: { 5664 const TemplateSpecializationType *Spec 5665 = cast<TemplateSpecializationType>(T); 5666 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced, 5667 Depth, Used); 5668 5669 // C++0x [temp.deduct.type]p9: 5670 // If the template argument list of P contains a pack expansion that is 5671 // not the last template argument, the entire template argument list is a 5672 // non-deduced context. 5673 if (OnlyDeduced && 5674 hasPackExpansionBeforeEnd(Spec->template_arguments())) 5675 break; 5676 5677 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 5678 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 5679 Used); 5680 break; 5681 } 5682 5683 case Type::Complex: 5684 if (!OnlyDeduced) 5685 MarkUsedTemplateParameters(Ctx, 5686 cast<ComplexType>(T)->getElementType(), 5687 OnlyDeduced, Depth, Used); 5688 break; 5689 5690 case Type::Atomic: 5691 if (!OnlyDeduced) 5692 MarkUsedTemplateParameters(Ctx, 5693 cast<AtomicType>(T)->getValueType(), 5694 OnlyDeduced, Depth, Used); 5695 break; 5696 5697 case Type::DependentName: 5698 if (!OnlyDeduced) 5699 MarkUsedTemplateParameters(Ctx, 5700 cast<DependentNameType>(T)->getQualifier(), 5701 OnlyDeduced, Depth, Used); 5702 break; 5703 5704 case Type::DependentTemplateSpecialization: { 5705 // C++14 [temp.deduct.type]p5: 5706 // The non-deduced contexts are: 5707 // -- The nested-name-specifier of a type that was specified using a 5708 // qualified-id 5709 // 5710 // C++14 [temp.deduct.type]p6: 5711 // When a type name is specified in a way that includes a non-deduced 5712 // context, all of the types that comprise that type name are also 5713 // non-deduced. 5714 if (OnlyDeduced) 5715 break; 5716 5717 const DependentTemplateSpecializationType *Spec 5718 = cast<DependentTemplateSpecializationType>(T); 5719 5720 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(), 5721 OnlyDeduced, Depth, Used); 5722 5723 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 5724 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 5725 Used); 5726 break; 5727 } 5728 5729 case Type::TypeOf: 5730 if (!OnlyDeduced) 5731 MarkUsedTemplateParameters(Ctx, 5732 cast<TypeOfType>(T)->getUnderlyingType(), 5733 OnlyDeduced, Depth, Used); 5734 break; 5735 5736 case Type::TypeOfExpr: 5737 if (!OnlyDeduced) 5738 MarkUsedTemplateParameters(Ctx, 5739 cast<TypeOfExprType>(T)->getUnderlyingExpr(), 5740 OnlyDeduced, Depth, Used); 5741 break; 5742 5743 case Type::Decltype: 5744 if (!OnlyDeduced) 5745 MarkUsedTemplateParameters(Ctx, 5746 cast<DecltypeType>(T)->getUnderlyingExpr(), 5747 OnlyDeduced, Depth, Used); 5748 break; 5749 5750 case Type::UnaryTransform: 5751 if (!OnlyDeduced) 5752 MarkUsedTemplateParameters(Ctx, 5753 cast<UnaryTransformType>(T)->getUnderlyingType(), 5754 OnlyDeduced, Depth, Used); 5755 break; 5756 5757 case Type::PackExpansion: 5758 MarkUsedTemplateParameters(Ctx, 5759 cast<PackExpansionType>(T)->getPattern(), 5760 OnlyDeduced, Depth, Used); 5761 break; 5762 5763 case Type::Auto: 5764 case Type::DeducedTemplateSpecialization: 5765 MarkUsedTemplateParameters(Ctx, 5766 cast<DeducedType>(T)->getDeducedType(), 5767 OnlyDeduced, Depth, Used); 5768 break; 5769 5770 // None of these types have any template parameters in them. 5771 case Type::Builtin: 5772 case Type::VariableArray: 5773 case Type::FunctionNoProto: 5774 case Type::Record: 5775 case Type::Enum: 5776 case Type::ObjCInterface: 5777 case Type::ObjCObject: 5778 case Type::ObjCObjectPointer: 5779 case Type::UnresolvedUsing: 5780 case Type::Pipe: 5781#define TYPE(Class, Base) 5782#define ABSTRACT_TYPE(Class, Base) 5783#define DEPENDENT_TYPE(Class, Base) 5784#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 5785#include "clang/AST/TypeNodes.inc" 5786 break; 5787 } 5788} 5789 5790/// Mark the template parameters that are used by this 5791/// template argument. 5792static void 5793MarkUsedTemplateParameters(ASTContext &Ctx, 5794 const TemplateArgument &TemplateArg, 5795 bool OnlyDeduced, 5796 unsigned Depth, 5797 llvm::SmallBitVector &Used) { 5798 switch (TemplateArg.getKind()) { 5799 case TemplateArgument::Null: 5800 case TemplateArgument::Integral: 5801 case TemplateArgument::Declaration: 5802 break; 5803 5804 case TemplateArgument::NullPtr: 5805 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced, 5806 Depth, Used); 5807 break; 5808 5809 case TemplateArgument::Type: 5810 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced, 5811 Depth, Used); 5812 break; 5813 5814 case TemplateArgument::Template: 5815 case TemplateArgument::TemplateExpansion: 5816 MarkUsedTemplateParameters(Ctx, 5817 TemplateArg.getAsTemplateOrTemplatePattern(), 5818 OnlyDeduced, Depth, Used); 5819 break; 5820 5821 case TemplateArgument::Expression: 5822 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced, 5823 Depth, Used); 5824 break; 5825 5826 case TemplateArgument::Pack: 5827 for (const auto &P : TemplateArg.pack_elements()) 5828 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used); 5829 break; 5830 } 5831} 5832 5833/// Mark which template parameters are used in a given expression. 5834/// 5835/// \param E the expression from which template parameters will be deduced. 5836/// 5837/// \param Used a bit vector whose elements will be set to \c true 5838/// to indicate when the corresponding template parameter will be 5839/// deduced. 5840void 5841Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, 5842 unsigned Depth, 5843 llvm::SmallBitVector &Used) { 5844 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used); 5845} 5846 5847/// Mark which template parameters can be deduced from a given 5848/// template argument list. 5849/// 5850/// \param TemplateArgs the template argument list from which template 5851/// parameters will be deduced. 5852/// 5853/// \param Used a bit vector whose elements will be set to \c true 5854/// to indicate when the corresponding template parameter will be 5855/// deduced. 5856void 5857Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 5858 bool OnlyDeduced, unsigned Depth, 5859 llvm::SmallBitVector &Used) { 5860 // C++0x [temp.deduct.type]p9: 5861 // If the template argument list of P contains a pack expansion that is not 5862 // the last template argument, the entire template argument list is a 5863 // non-deduced context. 5864 if (OnlyDeduced && 5865 hasPackExpansionBeforeEnd(TemplateArgs.asArray())) 5866 return; 5867 5868 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 5869 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced, 5870 Depth, Used); 5871} 5872 5873/// Marks all of the template parameters that will be deduced by a 5874/// call to the given function template. 5875void Sema::MarkDeducedTemplateParameters( 5876 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, 5877 llvm::SmallBitVector &Deduced) { 5878 TemplateParameterList *TemplateParams 5879 = FunctionTemplate->getTemplateParameters(); 5880 Deduced.clear(); 5881 Deduced.resize(TemplateParams->size()); 5882 5883 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 5884 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) 5885 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(), 5886 true, TemplateParams->getDepth(), Deduced); 5887} 5888 5889bool hasDeducibleTemplateParameters(Sema &S, 5890 FunctionTemplateDecl *FunctionTemplate, 5891 QualType T) { 5892 if (!T->isDependentType()) 5893 return false;