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 "TreeTransform.h" |
14 | #include "TypeLocBuilder.h" |
15 | #include "clang/AST/ASTContext.h" |
16 | #include "clang/AST/ASTLambda.h" |
17 | #include "clang/AST/Decl.h" |
18 | #include "clang/AST/DeclAccessPair.h" |
19 | #include "clang/AST/DeclBase.h" |
20 | #include "clang/AST/DeclCXX.h" |
21 | #include "clang/AST/DeclTemplate.h" |
22 | #include "clang/AST/DeclarationName.h" |
23 | #include "clang/AST/DynamicRecursiveASTVisitor.h" |
24 | #include "clang/AST/Expr.h" |
25 | #include "clang/AST/ExprCXX.h" |
26 | #include "clang/AST/NestedNameSpecifier.h" |
27 | #include "clang/AST/TemplateBase.h" |
28 | #include "clang/AST/TemplateName.h" |
29 | #include "clang/AST/Type.h" |
30 | #include "clang/AST/TypeLoc.h" |
31 | #include "clang/AST/TypeOrdering.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/EnterExpressionEvaluationContext.h" |
41 | #include "clang/Sema/Ownership.h" |
42 | #include "clang/Sema/Sema.h" |
43 | #include "clang/Sema/Template.h" |
44 | #include "clang/Sema/TemplateDeduction.h" |
45 | #include "llvm/ADT/APInt.h" |
46 | #include "llvm/ADT/APSInt.h" |
47 | #include "llvm/ADT/ArrayRef.h" |
48 | #include "llvm/ADT/DenseMap.h" |
49 | #include "llvm/ADT/FoldingSet.h" |
50 | #include "llvm/ADT/SmallBitVector.h" |
51 | #include "llvm/ADT/SmallPtrSet.h" |
52 | #include "llvm/ADT/SmallVector.h" |
53 | #include "llvm/Support/Casting.h" |
54 | #include "llvm/Support/Compiler.h" |
55 | #include "llvm/Support/ErrorHandling.h" |
56 | #include "llvm/Support/SaveAndRestore.h" |
57 | #include <algorithm> |
58 | #include <cassert> |
59 | #include <optional> |
60 | #include <tuple> |
61 | #include <type_traits> |
62 | #include <utility> |
63 | |
64 | namespace clang { |
65 | |
66 | /// Various flags that control template argument deduction. |
67 | /// |
68 | /// These flags can be bitwise-OR'd together. |
69 | enum TemplateDeductionFlags { |
70 | /// No template argument deduction flags, which indicates the |
71 | /// strictest results for template argument deduction (as used for, e.g., |
72 | /// matching class template partial specializations). |
73 | TDF_None = 0, |
74 | |
75 | /// Within template argument deduction from a function call, we are |
76 | /// matching with a parameter type for which the original parameter was |
77 | /// a reference. |
78 | TDF_ParamWithReferenceType = 0x1, |
79 | |
80 | /// Within template argument deduction from a function call, we |
81 | /// are matching in a case where we ignore cv-qualifiers. |
82 | TDF_IgnoreQualifiers = 0x02, |
83 | |
84 | /// Within template argument deduction from a function call, |
85 | /// we are matching in a case where we can perform template argument |
86 | /// deduction from a template-id of a derived class of the argument type. |
87 | TDF_DerivedClass = 0x04, |
88 | |
89 | /// Allow non-dependent types to differ, e.g., when performing |
90 | /// template argument deduction from a function call where conversions |
91 | /// may apply. |
92 | TDF_SkipNonDependent = 0x08, |
93 | |
94 | /// Whether we are performing template argument deduction for |
95 | /// parameters and arguments in a top-level template argument |
96 | TDF_TopLevelParameterTypeList = 0x10, |
97 | |
98 | /// Within template argument deduction from overload resolution per |
99 | /// C++ [over.over] allow matching function types that are compatible in |
100 | /// terms of noreturn and default calling convention adjustments, or |
101 | /// similarly matching a declared template specialization against a |
102 | /// possible template, per C++ [temp.deduct.decl]. In either case, permit |
103 | /// deduction where the parameter is a function type that can be converted |
104 | /// to the argument type. |
105 | TDF_AllowCompatibleFunctionType = 0x20, |
106 | |
107 | /// Within template argument deduction for a conversion function, we are |
108 | /// matching with an argument type for which the original argument was |
109 | /// a reference. |
110 | TDF_ArgWithReferenceType = 0x40, |
111 | }; |
112 | } |
113 | |
114 | using namespace clang; |
115 | using namespace sema; |
116 | |
117 | /// The kind of PartialOrdering we're performing template argument deduction |
118 | /// for (C++11 [temp.deduct.partial]). |
119 | enum class PartialOrderingKind { None, NonCall, Call }; |
120 | |
121 | static TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch( |
122 | Sema &S, TemplateParameterList *TemplateParams, QualType Param, |
123 | QualType Arg, TemplateDeductionInfo &Info, |
124 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF, |
125 | PartialOrderingKind POK, bool DeducedFromArrayBound, |
126 | bool *HasDeducedAnyParam); |
127 | |
128 | /// What directions packs are allowed to match non-packs. |
129 | enum class PackFold { ParameterToArgument, ArgumentToParameter, Both }; |
130 | |
131 | static TemplateDeductionResult |
132 | DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, |
133 | ArrayRef<TemplateArgument> Ps, |
134 | ArrayRef<TemplateArgument> As, |
135 | TemplateDeductionInfo &Info, |
136 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
137 | bool NumberOfArgumentsMustMatch, bool PartialOrdering, |
138 | PackFold PackFold, bool *HasDeducedAnyParam); |
139 | |
140 | static void MarkUsedTemplateParameters(ASTContext &Ctx, |
141 | const TemplateArgument &TemplateArg, |
142 | bool OnlyDeduced, unsigned Depth, |
143 | llvm::SmallBitVector &Used); |
144 | |
145 | static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, |
146 | bool OnlyDeduced, unsigned Level, |
147 | llvm::SmallBitVector &Deduced); |
148 | |
149 | /// If the given expression is of a form that permits the deduction |
150 | /// of a non-type template parameter, return the declaration of that |
151 | /// non-type template parameter. |
152 | static const NonTypeTemplateParmDecl * |
153 | getDeducedParameterFromExpr(const Expr *E, unsigned Depth) { |
154 | // If we are within an alias template, the expression may have undergone |
155 | // any number of parameter substitutions already. |
156 | while (true) { |
157 | if (const auto *IC = dyn_cast<ImplicitCastExpr>(Val: E)) |
158 | E = IC->getSubExpr(); |
159 | else if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) |
160 | E = CE->getSubExpr(); |
161 | else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(Val: E)) |
162 | E = Subst->getReplacement(); |
163 | else if (const auto *CCE = dyn_cast<CXXConstructExpr>(Val: E)) { |
164 | // Look through implicit copy construction from an lvalue of the same type. |
165 | if (CCE->getParenOrBraceRange().isValid()) |
166 | break; |
167 | // Note, there could be default arguments. |
168 | assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg"); |
169 | E = CCE->getArg(Arg: 0); |
170 | } else |
171 | break; |
172 | } |
173 | |
174 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
175 | if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl())) |
176 | if (NTTP->getDepth() == Depth) |
177 | return NTTP; |
178 | |
179 | return nullptr; |
180 | } |
181 | |
182 | static const NonTypeTemplateParmDecl * |
183 | getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) { |
184 | return getDeducedParameterFromExpr(E, Depth: Info.getDeducedDepth()); |
185 | } |
186 | |
187 | /// Determine whether two declaration pointers refer to the same |
188 | /// declaration. |
189 | static bool isSameDeclaration(Decl *X, Decl *Y) { |
190 | if (NamedDecl *NX = dyn_cast<NamedDecl>(Val: X)) |
191 | X = NX->getUnderlyingDecl(); |
192 | if (NamedDecl *NY = dyn_cast<NamedDecl>(Val: Y)) |
193 | Y = NY->getUnderlyingDecl(); |
194 | |
195 | return X->getCanonicalDecl() == Y->getCanonicalDecl(); |
196 | } |
197 | |
198 | /// Verify that the given, deduced template arguments are compatible. |
199 | /// |
200 | /// \returns The deduced template argument, or a NULL template argument if |
201 | /// the deduced template arguments were incompatible. |
202 | static DeducedTemplateArgument |
203 | checkDeducedTemplateArguments(ASTContext &Context, |
204 | const DeducedTemplateArgument &X, |
205 | const DeducedTemplateArgument &Y, |
206 | bool AggregateCandidateDeduction = false) { |
207 | // We have no deduction for one or both of the arguments; they're compatible. |
208 | if (X.isNull()) |
209 | return Y; |
210 | if (Y.isNull()) |
211 | return X; |
212 | |
213 | // If we have two non-type template argument values deduced for the same |
214 | // parameter, they must both match the type of the parameter, and thus must |
215 | // match each other's type. As we're only keeping one of them, we must check |
216 | // for that now. The exception is that if either was deduced from an array |
217 | // bound, the type is permitted to differ. |
218 | if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) { |
219 | QualType XType = X.getNonTypeTemplateArgumentType(); |
220 | if (!XType.isNull()) { |
221 | QualType YType = Y.getNonTypeTemplateArgumentType(); |
222 | if (YType.isNull() || !Context.hasSameType(T1: XType, T2: YType)) |
223 | return DeducedTemplateArgument(); |
224 | } |
225 | } |
226 | |
227 | switch (X.getKind()) { |
228 | case TemplateArgument::Null: |
229 | llvm_unreachable("Non-deduced template arguments handled above"); |
230 | |
231 | case TemplateArgument::Type: { |
232 | // If two template type arguments have the same type, they're compatible. |
233 | QualType TX = X.getAsType(), TY = Y.getAsType(); |
234 | if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(T1: TX, T2: TY)) |
235 | return DeducedTemplateArgument(Context.getCommonSugaredType(X: TX, Y: TY), |
236 | X.wasDeducedFromArrayBound() || |
237 | Y.wasDeducedFromArrayBound()); |
238 | |
239 | // If one of the two arguments was deduced from an array bound, the other |
240 | // supersedes it. |
241 | if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound()) |
242 | return X.wasDeducedFromArrayBound() ? Y : X; |
243 | |
244 | // The arguments are not compatible. |
245 | return DeducedTemplateArgument(); |
246 | } |
247 | |
248 | case TemplateArgument::Integral: |
249 | // If we deduced a constant in one case and either a dependent expression or |
250 | // declaration in another case, keep the integral constant. |
251 | // If both are integral constants with the same value, keep that value. |
252 | if (Y.getKind() == TemplateArgument::Expression || |
253 | Y.getKind() == TemplateArgument::Declaration || |
254 | (Y.getKind() == TemplateArgument::Integral && |
255 | llvm::APSInt::isSameValue(I1: X.getAsIntegral(), I2: Y.getAsIntegral()))) |
256 | return X.wasDeducedFromArrayBound() ? Y : X; |
257 | |
258 | // All other combinations are incompatible. |
259 | return DeducedTemplateArgument(); |
260 | |
261 | case TemplateArgument::StructuralValue: |
262 | // If we deduced a value and a dependent expression, keep the value. |
263 | if (Y.getKind() == TemplateArgument::Expression || |
264 | (Y.getKind() == TemplateArgument::StructuralValue && |
265 | X.structurallyEquals(Other: Y))) |
266 | return X; |
267 | |
268 | // All other combinations are incompatible. |
269 | return DeducedTemplateArgument(); |
270 | |
271 | case TemplateArgument::Template: |
272 | if (Y.getKind() == TemplateArgument::Template && |
273 | Context.hasSameTemplateName(X: X.getAsTemplate(), Y: Y.getAsTemplate())) |
274 | return X; |
275 | |
276 | // All other combinations are incompatible. |
277 | return DeducedTemplateArgument(); |
278 | |
279 | case TemplateArgument::TemplateExpansion: |
280 | if (Y.getKind() == TemplateArgument::TemplateExpansion && |
281 | Context.hasSameTemplateName(X: X.getAsTemplateOrTemplatePattern(), |
282 | Y: Y.getAsTemplateOrTemplatePattern())) |
283 | return X; |
284 | |
285 | // All other combinations are incompatible. |
286 | return DeducedTemplateArgument(); |
287 | |
288 | case TemplateArgument::Expression: { |
289 | if (Y.getKind() != TemplateArgument::Expression) |
290 | return checkDeducedTemplateArguments(Context, X: Y, Y: X); |
291 | |
292 | // Compare the expressions for equality |
293 | llvm::FoldingSetNodeID ID1, ID2; |
294 | X.getAsExpr()->Profile(ID1, Context, true); |
295 | Y.getAsExpr()->Profile(ID2, Context, true); |
296 | if (ID1 == ID2) |
297 | return X.wasDeducedFromArrayBound() ? Y : X; |
298 | |
299 | // Differing dependent expressions are incompatible. |
300 | return DeducedTemplateArgument(); |
301 | } |
302 | |
303 | case TemplateArgument::Declaration: |
304 | assert(!X.wasDeducedFromArrayBound()); |
305 | |
306 | // If we deduced a declaration and a dependent expression, keep the |
307 | // declaration. |
308 | if (Y.getKind() == TemplateArgument::Expression) |
309 | return X; |
310 | |
311 | // If we deduced a declaration and an integral constant, keep the |
312 | // integral constant and whichever type did not come from an array |
313 | // bound. |
314 | if (Y.getKind() == TemplateArgument::Integral) { |
315 | if (Y.wasDeducedFromArrayBound()) |
316 | return TemplateArgument(Context, Y.getAsIntegral(), |
317 | X.getParamTypeForDecl()); |
318 | return Y; |
319 | } |
320 | |
321 | // If we deduced two declarations, make sure that they refer to the |
322 | // same declaration. |
323 | if (Y.getKind() == TemplateArgument::Declaration && |
324 | isSameDeclaration(X.getAsDecl(), Y.getAsDecl())) |
325 | return X; |
326 | |
327 | // All other combinations are incompatible. |
328 | return DeducedTemplateArgument(); |
329 | |
330 | case TemplateArgument::NullPtr: |
331 | // If we deduced a null pointer and a dependent expression, keep the |
332 | // null pointer. |
333 | if (Y.getKind() == TemplateArgument::Expression) |
334 | return TemplateArgument(Context.getCommonSugaredType( |
335 | X: X.getNullPtrType(), Y: Y.getAsExpr()->getType()), |
336 | true); |
337 | |
338 | // If we deduced a null pointer and an integral constant, keep the |
339 | // integral constant. |
340 | if (Y.getKind() == TemplateArgument::Integral) |
341 | return Y; |
342 | |
343 | // If we deduced two null pointers, they are the same. |
344 | if (Y.getKind() == TemplateArgument::NullPtr) |
345 | return TemplateArgument( |
346 | Context.getCommonSugaredType(X: X.getNullPtrType(), Y: Y.getNullPtrType()), |
347 | true); |
348 | |
349 | // All other combinations are incompatible. |
350 | return DeducedTemplateArgument(); |
351 | |
352 | case TemplateArgument::Pack: { |
353 | if (Y.getKind() != TemplateArgument::Pack || |
354 | (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size())) |
355 | return DeducedTemplateArgument(); |
356 | |
357 | llvm::SmallVector<TemplateArgument, 8> NewPack; |
358 | for (TemplateArgument::pack_iterator |
359 | XA = X.pack_begin(), |
360 | XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end(); |
361 | XA != XAEnd; ++XA) { |
362 | if (YA != YAEnd) { |
363 | TemplateArgument Merged = checkDeducedTemplateArguments( |
364 | Context, X: DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()), |
365 | Y: DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound())); |
366 | if (Merged.isNull() && !(XA->isNull() && YA->isNull())) |
367 | return DeducedTemplateArgument(); |
368 | NewPack.push_back(Elt: Merged); |
369 | ++YA; |
370 | } else { |
371 | NewPack.push_back(Elt: *XA); |
372 | } |
373 | } |
374 | |
375 | return DeducedTemplateArgument( |
376 | TemplateArgument::CreatePackCopy(Context, Args: NewPack), |
377 | X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound()); |
378 | } |
379 | } |
380 | |
381 | llvm_unreachable("Invalid TemplateArgument Kind!"); |
382 | } |
383 | |
384 | /// Deduce the value of the given non-type template parameter |
385 | /// as the given deduced template argument. All non-type template parameter |
386 | /// deduction is funneled through here. |
387 | static TemplateDeductionResult |
388 | DeduceNonTypeTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, |
389 | const NonTypeTemplateParmDecl *NTTP, |
390 | const DeducedTemplateArgument &NewDeduced, |
391 | QualType ValueType, TemplateDeductionInfo &Info, |
392 | bool PartialOrdering, |
393 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
394 | bool *HasDeducedAnyParam) { |
395 | assert(NTTP->getDepth() == Info.getDeducedDepth() && |
396 | "deducing non-type template argument with wrong depth"); |
397 | |
398 | DeducedTemplateArgument Result = checkDeducedTemplateArguments( |
399 | S.Context, Deduced[NTTP->getIndex()], NewDeduced); |
400 | if (Result.isNull()) { |
401 | Info.Param = const_cast<NonTypeTemplateParmDecl*>(NTTP); |
402 | Info.FirstArg = Deduced[NTTP->getIndex()]; |
403 | Info.SecondArg = NewDeduced; |
404 | return TemplateDeductionResult::Inconsistent; |
405 | } |
406 | |
407 | Deduced[NTTP->getIndex()] = Result; |
408 | if (!S.getLangOpts().CPlusPlus17) |
409 | return TemplateDeductionResult::Success; |
410 | |
411 | if (NTTP->isExpandedParameterPack()) |
412 | // FIXME: We may still need to deduce parts of the type here! But we |
413 | // don't have any way to find which slice of the type to use, and the |
414 | // type stored on the NTTP itself is nonsense. Perhaps the type of an |
415 | // expanded NTTP should be a pack expansion type? |
416 | return TemplateDeductionResult::Success; |
417 | |
418 | // Get the type of the parameter for deduction. If it's a (dependent) array |
419 | // or function type, we will not have decayed it yet, so do that now. |
420 | QualType ParamType = S.Context.getAdjustedParameterType(T: NTTP->getType()); |
421 | if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType)) |
422 | ParamType = Expansion->getPattern(); |
423 | |
424 | // FIXME: It's not clear how deduction of a parameter of reference |
425 | // type from an argument (of non-reference type) should be performed. |
426 | // For now, we just make the argument have same reference type as the |
427 | // parameter. |
428 | if (ParamType->isReferenceType() && !ValueType->isReferenceType()) { |
429 | if (ParamType->isRValueReferenceType()) |
430 | ValueType = S.Context.getRValueReferenceType(T: ValueType); |
431 | else |
432 | ValueType = S.Context.getLValueReferenceType(T: ValueType); |
433 | } |
434 | |
435 | return DeduceTemplateArgumentsByTypeMatch( |
436 | S, TemplateParams, Param: ParamType, Arg: ValueType, Info, Deduced, |
437 | TDF: TDF_SkipNonDependent | TDF_IgnoreQualifiers, |
438 | POK: PartialOrdering ? PartialOrderingKind::NonCall |
439 | : PartialOrderingKind::None, |
440 | /*ArrayBound=*/DeducedFromArrayBound: NewDeduced.wasDeducedFromArrayBound(), HasDeducedAnyParam); |
441 | } |
442 | |
443 | /// Deduce the value of the given non-type template parameter |
444 | /// from the given integral constant. |
445 | static TemplateDeductionResult DeduceNonTypeTemplateArgument( |
446 | Sema &S, TemplateParameterList *TemplateParams, |
447 | const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value, |
448 | QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info, |
449 | bool PartialOrdering, SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
450 | bool *HasDeducedAnyParam) { |
451 | return DeduceNonTypeTemplateArgument( |
452 | S, TemplateParams, NTTP, |
453 | NewDeduced: DeducedTemplateArgument(S.Context, Value, ValueType, |
454 | DeducedFromArrayBound), |
455 | ValueType, Info, PartialOrdering, Deduced, HasDeducedAnyParam); |
456 | } |
457 | |
458 | /// Deduce the value of the given non-type template parameter |
459 | /// from the given null pointer template argument type. |
460 | static TemplateDeductionResult |
461 | DeduceNullPtrTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, |
462 | const NonTypeTemplateParmDecl *NTTP, |
463 | QualType NullPtrType, TemplateDeductionInfo &Info, |
464 | bool PartialOrdering, |
465 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
466 | bool *HasDeducedAnyParam) { |
467 | Expr *Value = S.ImpCastExprToType( |
468 | new (S.Context) CXXNullPtrLiteralExpr(S.Context.NullPtrTy, |
469 | NTTP->getLocation()), |
470 | NullPtrType, |
471 | NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer |
472 | : CK_NullToPointer) |
473 | .get(); |
474 | return DeduceNonTypeTemplateArgument( |
475 | S, TemplateParams, NTTP, NewDeduced: TemplateArgument(Value, /*IsCanonical=*/false), |
476 | ValueType: Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam); |
477 | } |
478 | |
479 | /// Deduce the value of the given non-type template parameter |
480 | /// from the given type- or value-dependent expression. |
481 | /// |
482 | /// \returns true if deduction succeeded, false otherwise. |
483 | static TemplateDeductionResult |
484 | DeduceNonTypeTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, |
485 | const NonTypeTemplateParmDecl *NTTP, Expr *Value, |
486 | TemplateDeductionInfo &Info, bool PartialOrdering, |
487 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
488 | bool *HasDeducedAnyParam) { |
489 | return DeduceNonTypeTemplateArgument( |
490 | S, TemplateParams, NTTP, NewDeduced: TemplateArgument(Value, /*IsCanonical=*/false), |
491 | ValueType: Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam); |
492 | } |
493 | |
494 | /// Deduce the value of the given non-type template parameter |
495 | /// from the given declaration. |
496 | /// |
497 | /// \returns true if deduction succeeded, false otherwise. |
498 | static TemplateDeductionResult |
499 | DeduceNonTypeTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, |
500 | const NonTypeTemplateParmDecl *NTTP, ValueDecl *D, |
501 | QualType T, TemplateDeductionInfo &Info, |
502 | bool PartialOrdering, |
503 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
504 | bool *HasDeducedAnyParam) { |
505 | TemplateArgument New(D, T); |
506 | return DeduceNonTypeTemplateArgument( |
507 | S, TemplateParams, NTTP, NewDeduced: DeducedTemplateArgument(New), ValueType: T, Info, |
508 | PartialOrdering, Deduced, HasDeducedAnyParam); |
509 | } |
510 | |
511 | static TemplateDeductionResult DeduceTemplateArguments( |
512 | Sema &S, TemplateParameterList *TemplateParams, TemplateName Param, |
513 | TemplateName Arg, TemplateDeductionInfo &Info, |
514 | ArrayRef<TemplateArgument> DefaultArguments, bool PartialOrdering, |
515 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
516 | bool *HasDeducedAnyParam) { |
517 | TemplateDecl *ParamDecl = Param.getAsTemplateDecl(); |
518 | if (!ParamDecl) { |
519 | // The parameter type is dependent and is not a template template parameter, |
520 | // so there is nothing that we can deduce. |
521 | return TemplateDeductionResult::Success; |
522 | } |
523 | |
524 | if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(Val: ParamDecl)) { |
525 | // If we're not deducing at this depth, there's nothing to deduce. |
526 | if (TempParam->getDepth() != Info.getDeducedDepth()) |
527 | return TemplateDeductionResult::Success; |
528 | |
529 | ArrayRef<NamedDecl *> Params = |
530 | ParamDecl->getTemplateParameters()->asArray(); |
531 | unsigned StartPos = 0; |
532 | for (unsigned I = 0, E = std::min(a: Params.size(), b: DefaultArguments.size()); |
533 | I < E; ++I) { |
534 | if (Params[I]->isParameterPack()) { |
535 | StartPos = DefaultArguments.size(); |
536 | break; |
537 | } |
538 | StartPos = I + 1; |
539 | } |
540 | |
541 | // Provisional resolution for CWG2398: If Arg names a template |
542 | // specialization, then we deduce a synthesized template name |
543 | // based on A, but using the TS's extra arguments, relative to P, as |
544 | // defaults. |
545 | DeducedTemplateArgument NewDeduced = |
546 | PartialOrdering |
547 | ? TemplateArgument(S.Context.getDeducedTemplateName( |
548 | Underlying: Arg, DefaultArgs: {.StartPos: StartPos, .Args: DefaultArguments.drop_front(N: StartPos)})) |
549 | : Arg; |
550 | |
551 | DeducedTemplateArgument Result = checkDeducedTemplateArguments( |
552 | S.Context, Deduced[TempParam->getIndex()], NewDeduced); |
553 | if (Result.isNull()) { |
554 | Info.Param = TempParam; |
555 | Info.FirstArg = Deduced[TempParam->getIndex()]; |
556 | Info.SecondArg = NewDeduced; |
557 | return TemplateDeductionResult::Inconsistent; |
558 | } |
559 | |
560 | Deduced[TempParam->getIndex()] = Result; |
561 | if (HasDeducedAnyParam) |
562 | *HasDeducedAnyParam = true; |
563 | return TemplateDeductionResult::Success; |
564 | } |
565 | |
566 | // Verify that the two template names are equivalent. |
567 | if (S.Context.hasSameTemplateName( |
568 | X: Param, Y: Arg, /*IgnoreDeduced=*/DefaultArguments.size() != 0)) |
569 | return TemplateDeductionResult::Success; |
570 | |
571 | // Mismatch of non-dependent template parameter to argument. |
572 | Info.FirstArg = TemplateArgument(Param); |
573 | Info.SecondArg = TemplateArgument(Arg); |
574 | return TemplateDeductionResult::NonDeducedMismatch; |
575 | } |
576 | |
577 | /// Deduce the template arguments by comparing the template parameter |
578 | /// type (which is a template-id) with the template argument type. |
579 | /// |
580 | /// \param S the Sema |
581 | /// |
582 | /// \param TemplateParams the template parameters that we are deducing |
583 | /// |
584 | /// \param P the parameter type |
585 | /// |
586 | /// \param A the argument type |
587 | /// |
588 | /// \param Info information about the template argument deduction itself |
589 | /// |
590 | /// \param Deduced the deduced template arguments |
591 | /// |
592 | /// \returns the result of template argument deduction so far. Note that a |
593 | /// "success" result means that template argument deduction has not yet failed, |
594 | /// but it may still fail, later, for other reasons. |
595 | |
596 | static const TemplateSpecializationType *getLastTemplateSpecType(QualType QT) { |
597 | const TemplateSpecializationType *LastTST = nullptr; |
598 | for (const Type *T = QT.getTypePtr(); /**/; /**/) { |
599 | const TemplateSpecializationType *TST = |
600 | T->getAs<TemplateSpecializationType>(); |
601 | if (!TST) |
602 | return LastTST; |
603 | if (!TST->isSugared()) |
604 | return TST; |
605 | LastTST = TST; |
606 | T = TST->desugar().getTypePtr(); |
607 | } |
608 | } |
609 | |
610 | static TemplateDeductionResult |
611 | DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams, |
612 | const QualType P, QualType A, |
613 | TemplateDeductionInfo &Info, bool PartialOrdering, |
614 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
615 | bool *HasDeducedAnyParam) { |
616 | QualType UP = P; |
617 | if (const auto *IP = P->getAs<InjectedClassNameType>()) |
618 | UP = IP->getInjectedSpecializationType(); |
619 | |
620 | assert(isa<TemplateSpecializationType>(UP.getCanonicalType())); |
621 | const TemplateSpecializationType *TP = ::getLastTemplateSpecType(QT: UP); |
622 | TemplateName TNP = TP->getTemplateName(); |
623 | |
624 | // If the parameter is an alias template, there is nothing to deduce. |
625 | if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias()) |
626 | return TemplateDeductionResult::Success; |
627 | |
628 | // FIXME: To preserve sugar, the TST needs to carry sugared resolved |
629 | // arguments. |
630 | ArrayRef<TemplateArgument> PResolved = |
631 | TP->getCanonicalTypeInternal() |
632 | ->castAs<TemplateSpecializationType>() |
633 | ->template_arguments(); |
634 | |
635 | QualType UA = A; |
636 | std::optional<NestedNameSpecifier *> NNS; |
637 | // Treat an injected-class-name as its underlying template-id. |
638 | if (const auto *Elaborated = A->getAs<ElaboratedType>()) { |
639 | NNS = Elaborated->getQualifier(); |
640 | } else if (const auto *Injected = A->getAs<InjectedClassNameType>()) { |
641 | UA = Injected->getInjectedSpecializationType(); |
642 | NNS = nullptr; |
643 | } |
644 | |
645 | // Check whether the template argument is a dependent template-id. |
646 | if (isa<TemplateSpecializationType>(Val: UA.getCanonicalType())) { |
647 | const TemplateSpecializationType *SA = ::getLastTemplateSpecType(QT: UA); |
648 | TemplateName TNA = SA->getTemplateName(); |
649 | |
650 | // If the argument is an alias template, there is nothing to deduce. |
651 | if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias()) |
652 | return TemplateDeductionResult::Success; |
653 | |
654 | // FIXME: To preserve sugar, the TST needs to carry sugared resolved |
655 | // arguments. |
656 | ArrayRef<TemplateArgument> AResolved = |
657 | SA->getCanonicalTypeInternal() |
658 | ->castAs<TemplateSpecializationType>() |
659 | ->template_arguments(); |
660 | |
661 | // Perform template argument deduction for the template name. |
662 | if (auto Result = DeduceTemplateArguments(S, TemplateParams, Param: TNP, Arg: TNA, Info, |
663 | /*DefaultArguments=*/AResolved, |
664 | PartialOrdering, Deduced, |
665 | HasDeducedAnyParam); |
666 | Result != TemplateDeductionResult::Success) |
667 | return Result; |
668 | |
669 | // Perform template argument deduction on each template |
670 | // argument. Ignore any missing/extra arguments, since they could be |
671 | // filled in by default arguments. |
672 | return DeduceTemplateArguments( |
673 | S, TemplateParams, Ps: PResolved, As: AResolved, Info, Deduced, |
674 | /*NumberOfArgumentsMustMatch=*/false, PartialOrdering, |
675 | PackFold: PackFold::ParameterToArgument, HasDeducedAnyParam); |
676 | } |
677 | |
678 | // If the argument type is a class template specialization, we |
679 | // perform template argument deduction using its template |
680 | // arguments. |
681 | const auto *RA = UA->getAs<RecordType>(); |
682 | const auto *SA = |
683 | RA ? dyn_cast<ClassTemplateSpecializationDecl>(Val: RA->getDecl()) : nullptr; |
684 | if (!SA) { |
685 | Info.FirstArg = TemplateArgument(P); |
686 | Info.SecondArg = TemplateArgument(A); |
687 | return TemplateDeductionResult::NonDeducedMismatch; |
688 | } |
689 | |
690 | TemplateName TNA = TemplateName(SA->getSpecializedTemplate()); |
691 | if (NNS) |
692 | TNA = S.Context.getQualifiedTemplateName( |
693 | NNS: *NNS, TemplateKeyword: false, Template: TemplateName(SA->getSpecializedTemplate())); |
694 | |
695 | // Perform template argument deduction for the template name. |
696 | if (auto Result = DeduceTemplateArguments( |
697 | S, TemplateParams, Param: TNP, Arg: TNA, Info, |
698 | /*DefaultArguments=*/SA->getTemplateArgs().asArray(), PartialOrdering, |
699 | Deduced, HasDeducedAnyParam); |
700 | Result != TemplateDeductionResult::Success) |
701 | return Result; |
702 | |
703 | // Perform template argument deduction for the template arguments. |
704 | return DeduceTemplateArguments(S, TemplateParams, Ps: PResolved, |
705 | As: SA->getTemplateArgs().asArray(), Info, Deduced, |
706 | /*NumberOfArgumentsMustMatch=*/true, |
707 | PartialOrdering, PackFold: PackFold::ParameterToArgument, |
708 | HasDeducedAnyParam); |
709 | } |
710 | |
711 | static bool IsPossiblyOpaquelyQualifiedTypeInternal(const Type *T) { |
712 | assert(T->isCanonicalUnqualified()); |
713 | |
714 | switch (T->getTypeClass()) { |
715 | case Type::TypeOfExpr: |
716 | case Type::TypeOf: |
717 | case Type::DependentName: |
718 | case Type::Decltype: |
719 | case Type::PackIndexing: |
720 | case Type::UnresolvedUsing: |
721 | case Type::TemplateTypeParm: |
722 | case Type::Auto: |
723 | return true; |
724 | |
725 | case Type::ConstantArray: |
726 | case Type::IncompleteArray: |
727 | case Type::VariableArray: |
728 | case Type::DependentSizedArray: |
729 | return IsPossiblyOpaquelyQualifiedTypeInternal( |
730 | T: cast<ArrayType>(Val: T)->getElementType().getTypePtr()); |
731 | |
732 | default: |
733 | return false; |
734 | } |
735 | } |
736 | |
737 | /// Determines whether the given type is an opaque type that |
738 | /// might be more qualified when instantiated. |
739 | static bool IsPossiblyOpaquelyQualifiedType(QualType T) { |
740 | return IsPossiblyOpaquelyQualifiedTypeInternal( |
741 | T: T->getCanonicalTypeInternal().getTypePtr()); |
742 | } |
743 | |
744 | /// Helper function to build a TemplateParameter when we don't |
745 | /// know its type statically. |
746 | static TemplateParameter makeTemplateParameter(Decl *D) { |
747 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: D)) |
748 | return TemplateParameter(TTP); |
749 | if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: D)) |
750 | return TemplateParameter(NTTP); |
751 | |
752 | return TemplateParameter(cast<TemplateTemplateParmDecl>(Val: D)); |
753 | } |
754 | |
755 | /// A pack that we're currently deducing. |
756 | struct clang::DeducedPack { |
757 | // The index of the pack. |
758 | unsigned Index; |
759 | |
760 | // The old value of the pack before we started deducing it. |
761 | DeducedTemplateArgument Saved; |
762 | |
763 | // A deferred value of this pack from an inner deduction, that couldn't be |
764 | // deduced because this deduction hadn't happened yet. |
765 | DeducedTemplateArgument DeferredDeduction; |
766 | |
767 | // The new value of the pack. |
768 | SmallVector<DeducedTemplateArgument, 4> New; |
769 | |
770 | // The outer deduction for this pack, if any. |
771 | DeducedPack *Outer = nullptr; |
772 | |
773 | DeducedPack(unsigned Index) : Index(Index) {} |
774 | }; |
775 | |
776 | namespace { |
777 | |
778 | /// A scope in which we're performing pack deduction. |
779 | class PackDeductionScope { |
780 | public: |
781 | /// Prepare to deduce the packs named within Pattern. |
782 | /// \param FinishingDeduction Don't attempt to deduce the pack. Useful when |
783 | /// just checking a previous deduction of the pack. |
784 | PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams, |
785 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
786 | TemplateDeductionInfo &Info, TemplateArgument Pattern, |
787 | bool DeducePackIfNotAlreadyDeduced = false, |
788 | bool FinishingDeduction = false) |
789 | : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info), |
790 | DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced), |
791 | FinishingDeduction(FinishingDeduction) { |
792 | unsigned NumNamedPacks = addPacks(Pattern); |
793 | finishConstruction(NumNamedPacks); |
794 | } |
795 | |
796 | /// Prepare to directly deduce arguments of the parameter with index \p Index. |
797 | PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams, |
798 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
799 | TemplateDeductionInfo &Info, unsigned Index) |
800 | : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) { |
801 | addPack(Index); |
802 | finishConstruction(NumNamedPacks: 1); |
803 | } |
804 | |
805 | private: |
806 | void addPack(unsigned Index) { |
807 | // Save the deduced template argument for the parameter pack expanded |
808 | // by this pack expansion, then clear out the deduction. |
809 | DeducedFromEarlierParameter = !Deduced[Index].isNull(); |
810 | DeducedPack Pack(Index); |
811 | if (!FinishingDeduction) { |
812 | Pack.Saved = Deduced[Index]; |
813 | Deduced[Index] = TemplateArgument(); |
814 | } |
815 | |
816 | // FIXME: What if we encounter multiple packs with different numbers of |
817 | // pre-expanded expansions? (This should already have been diagnosed |
818 | // during substitution.) |
819 | if (UnsignedOrNone ExpandedPackExpansions = |
820 | getExpandedPackSize(Param: TemplateParams->getParam(Idx: Index))) |
821 | FixedNumExpansions = ExpandedPackExpansions; |
822 | |
823 | Packs.push_back(Elt: Pack); |
824 | } |
825 | |
826 | unsigned addPacks(TemplateArgument Pattern) { |
827 | // Compute the set of template parameter indices that correspond to |
828 | // parameter packs expanded by the pack expansion. |
829 | llvm::SmallBitVector SawIndices(TemplateParams->size()); |
830 | llvm::SmallVector<TemplateArgument, 4> ExtraDeductions; |
831 | |
832 | auto AddPack = [&](unsigned Index) { |
833 | if (SawIndices[Index]) |
834 | return; |
835 | SawIndices[Index] = true; |
836 | addPack(Index); |
837 | |
838 | // Deducing a parameter pack that is a pack expansion also constrains the |
839 | // packs appearing in that parameter to have the same deduced arity. Also, |
840 | // in C++17 onwards, deducing a non-type template parameter deduces its |
841 | // type, so we need to collect the pending deduced values for those packs. |
842 | if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>( |
843 | Val: TemplateParams->getParam(Idx: Index))) { |
844 | if (!NTTP->isExpandedParameterPack()) |
845 | // FIXME: CWG2982 suggests a type-constraint forms a non-deduced |
846 | // context, however it is not yet resolved. |
847 | if (auto *Expansion = dyn_cast<PackExpansionType>( |
848 | S.Context.getUnconstrainedType(NTTP->getType()))) |
849 | ExtraDeductions.push_back(Elt: Expansion->getPattern()); |
850 | } |
851 | // FIXME: Also collect the unexpanded packs in any type and template |
852 | // parameter packs that are pack expansions. |
853 | }; |
854 | |
855 | auto Collect = [&](TemplateArgument Pattern) { |
856 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
857 | S.collectUnexpandedParameterPacks(Arg: Pattern, Unexpanded); |
858 | for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { |
859 | unsigned Depth, Index; |
860 | std::tie(args&: Depth, args&: Index) = getDepthAndIndex(UPP: Unexpanded[I]); |
861 | if (Depth == Info.getDeducedDepth()) |
862 | AddPack(Index); |
863 | } |
864 | }; |
865 | |
866 | // Look for unexpanded packs in the pattern. |
867 | Collect(Pattern); |
868 | assert(!Packs.empty() && "Pack expansion without unexpanded packs?"); |
869 | |
870 | unsigned NumNamedPacks = Packs.size(); |
871 | |
872 | // Also look for unexpanded packs that are indirectly deduced by deducing |
873 | // the sizes of the packs in this pattern. |
874 | while (!ExtraDeductions.empty()) |
875 | Collect(ExtraDeductions.pop_back_val()); |
876 | |
877 | return NumNamedPacks; |
878 | } |
879 | |
880 | void finishConstruction(unsigned NumNamedPacks) { |
881 | // Dig out the partially-substituted pack, if there is one. |
882 | const TemplateArgument *PartialPackArgs = nullptr; |
883 | unsigned NumPartialPackArgs = 0; |
884 | std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u); |
885 | if (auto *Scope = S.CurrentInstantiationScope) |
886 | if (auto *Partial = Scope->getPartiallySubstitutedPack( |
887 | ExplicitArgs: &PartialPackArgs, NumExplicitArgs: &NumPartialPackArgs)) |
888 | PartialPackDepthIndex = getDepthAndIndex(ND: Partial); |
889 | |
890 | // This pack expansion will have been partially or fully expanded if |
891 | // it only names explicitly-specified parameter packs (including the |
892 | // partially-substituted one, if any). |
893 | bool IsExpanded = true; |
894 | for (unsigned I = 0; I != NumNamedPacks; ++I) { |
895 | if (Packs[I].Index >= Info.getNumExplicitArgs()) { |
896 | IsExpanded = false; |
897 | IsPartiallyExpanded = false; |
898 | break; |
899 | } |
900 | if (PartialPackDepthIndex == |
901 | std::make_pair(x: Info.getDeducedDepth(), y&: Packs[I].Index)) { |
902 | IsPartiallyExpanded = true; |
903 | } |
904 | } |
905 | |
906 | // Skip over the pack elements that were expanded into separate arguments. |
907 | // If we partially expanded, this is the number of partial arguments. |
908 | // FIXME: `&& FixedNumExpansions` is a workaround for UB described in |
909 | // https://github.com/llvm/llvm-project/issues/100095 |
910 | if (IsPartiallyExpanded) |
911 | PackElements += NumPartialPackArgs; |
912 | else if (IsExpanded && FixedNumExpansions) |
913 | PackElements += *FixedNumExpansions; |
914 | |
915 | for (auto &Pack : Packs) { |
916 | if (Info.PendingDeducedPacks.size() > Pack.Index) |
917 | Pack.Outer = Info.PendingDeducedPacks[Pack.Index]; |
918 | else |
919 | Info.PendingDeducedPacks.resize(N: Pack.Index + 1); |
920 | Info.PendingDeducedPacks[Pack.Index] = &Pack; |
921 | |
922 | if (PartialPackDepthIndex == |
923 | std::make_pair(x: Info.getDeducedDepth(), y&: Pack.Index)) { |
924 | Pack.New.append(in_start: PartialPackArgs, in_end: PartialPackArgs + NumPartialPackArgs); |
925 | // We pre-populate the deduced value of the partially-substituted |
926 | // pack with the specified value. This is not entirely correct: the |
927 | // value is supposed to have been substituted, not deduced, but the |
928 | // cases where this is observable require an exact type match anyway. |
929 | // |
930 | // FIXME: If we could represent a "depth i, index j, pack elem k" |
931 | // parameter, we could substitute the partially-substituted pack |
932 | // everywhere and avoid this. |
933 | if (!FinishingDeduction && !IsPartiallyExpanded) |
934 | Deduced[Pack.Index] = Pack.New[PackElements]; |
935 | } |
936 | } |
937 | } |
938 | |
939 | public: |
940 | ~PackDeductionScope() { |
941 | for (auto &Pack : Packs) |
942 | Info.PendingDeducedPacks[Pack.Index] = Pack.Outer; |
943 | } |
944 | |
945 | // Return the size of the saved packs if all of them has the same size. |
946 | UnsignedOrNone getSavedPackSizeIfAllEqual() const { |
947 | unsigned PackSize = Packs[0].Saved.pack_size(); |
948 | |
949 | if (std::all_of(first: Packs.begin() + 1, last: Packs.end(), pred: [&PackSize](const auto &P) { |
950 | return P.Saved.pack_size() == PackSize; |
951 | })) |
952 | return PackSize; |
953 | return std::nullopt; |
954 | } |
955 | |
956 | /// Determine whether this pack has already been deduced from a previous |
957 | /// argument. |
958 | bool isDeducedFromEarlierParameter() const { |
959 | return DeducedFromEarlierParameter; |
960 | } |
961 | |
962 | /// Determine whether this pack has already been partially expanded into a |
963 | /// sequence of (prior) function parameters / template arguments. |
964 | bool isPartiallyExpanded() { return IsPartiallyExpanded; } |
965 | |
966 | /// Determine whether this pack expansion scope has a known, fixed arity. |
967 | /// This happens if it involves a pack from an outer template that has |
968 | /// (notionally) already been expanded. |
969 | bool hasFixedArity() { return static_cast<bool>(FixedNumExpansions); } |
970 | |
971 | /// Determine whether the next element of the argument is still part of this |
972 | /// pack. This is the case unless the pack is already expanded to a fixed |
973 | /// length. |
974 | bool hasNextElement() { |
975 | return !FixedNumExpansions || *FixedNumExpansions > PackElements; |
976 | } |
977 | |
978 | /// Move to deducing the next element in each pack that is being deduced. |
979 | void nextPackElement() { |
980 | // Capture the deduced template arguments for each parameter pack expanded |
981 | // by this pack expansion, add them to the list of arguments we've deduced |
982 | // for that pack, then clear out the deduced argument. |
983 | if (!FinishingDeduction) { |
984 | for (auto &Pack : Packs) { |
985 | DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index]; |
986 | if (!Pack.New.empty() || !DeducedArg.isNull()) { |
987 | while (Pack.New.size() < PackElements) |
988 | Pack.New.push_back(Elt: DeducedTemplateArgument()); |
989 | if (Pack.New.size() == PackElements) |
990 | Pack.New.push_back(Elt: DeducedArg); |
991 | else |
992 | Pack.New[PackElements] = DeducedArg; |
993 | DeducedArg = Pack.New.size() > PackElements + 1 |
994 | ? Pack.New[PackElements + 1] |
995 | : DeducedTemplateArgument(); |
996 | } |
997 | } |
998 | } |
999 | ++PackElements; |
1000 | } |
1001 | |
1002 | /// Finish template argument deduction for a set of argument packs, |
1003 | /// producing the argument packs and checking for consistency with prior |
1004 | /// deductions. |
1005 | TemplateDeductionResult finish() { |
1006 | if (FinishingDeduction) |
1007 | return TemplateDeductionResult::Success; |
1008 | // Build argument packs for each of the parameter packs expanded by this |
1009 | // pack expansion. |
1010 | for (auto &Pack : Packs) { |
1011 | // Put back the old value for this pack. |
1012 | if (!FinishingDeduction) |
1013 | Deduced[Pack.Index] = Pack.Saved; |
1014 | |
1015 | // Always make sure the size of this pack is correct, even if we didn't |
1016 | // deduce any values for it. |
1017 | // |
1018 | // FIXME: This isn't required by the normative wording, but substitution |
1019 | // and post-substitution checking will always fail if the arity of any |
1020 | // pack is not equal to the number of elements we processed. (Either that |
1021 | // or something else has gone *very* wrong.) We're permitted to skip any |
1022 | // hard errors from those follow-on steps by the intent (but not the |
1023 | // wording) of C++ [temp.inst]p8: |
1024 | // |
1025 | // If the function selected by overload resolution can be determined |
1026 | // without instantiating a class template definition, it is unspecified |
1027 | // whether that instantiation actually takes place |
1028 | Pack.New.resize(N: PackElements); |
1029 | |
1030 | // Build or find a new value for this pack. |
1031 | DeducedTemplateArgument NewPack; |
1032 | if (Pack.New.empty()) { |
1033 | // If we deduced an empty argument pack, create it now. |
1034 | NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack()); |
1035 | } else { |
1036 | TemplateArgument *ArgumentPack = |
1037 | new (S.Context) TemplateArgument[Pack.New.size()]; |
1038 | std::copy(first: Pack.New.begin(), last: Pack.New.end(), result: ArgumentPack); |
1039 | NewPack = DeducedTemplateArgument( |
1040 | TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())), |
1041 | // FIXME: This is wrong, it's possible that some pack elements are |
1042 | // deduced from an array bound and others are not: |
1043 | // template<typename ...T, T ...V> void g(const T (&...p)[V]); |
1044 | // g({1, 2, 3}, {{}, {}}); |
1045 | // ... should deduce T = {int, size_t (from array bound)}. |
1046 | Pack.New[0].wasDeducedFromArrayBound()); |
1047 | } |
1048 | |
1049 | // Pick where we're going to put the merged pack. |
1050 | DeducedTemplateArgument *Loc; |
1051 | if (Pack.Outer) { |
1052 | if (Pack.Outer->DeferredDeduction.isNull()) { |
1053 | // Defer checking this pack until we have a complete pack to compare |
1054 | // it against. |
1055 | Pack.Outer->DeferredDeduction = NewPack; |
1056 | continue; |
1057 | } |
1058 | Loc = &Pack.Outer->DeferredDeduction; |
1059 | } else { |
1060 | Loc = &Deduced[Pack.Index]; |
1061 | } |
1062 | |
1063 | // Check the new pack matches any previous value. |
1064 | DeducedTemplateArgument OldPack = *Loc; |
1065 | DeducedTemplateArgument Result = checkDeducedTemplateArguments( |
1066 | Context&: S.Context, X: OldPack, Y: NewPack, AggregateCandidateDeduction: DeducePackIfNotAlreadyDeduced); |
1067 | |
1068 | Info.AggregateDeductionCandidateHasMismatchedArity = |
1069 | OldPack.getKind() == TemplateArgument::Pack && |
1070 | NewPack.getKind() == TemplateArgument::Pack && |
1071 | OldPack.pack_size() != NewPack.pack_size() && !Result.isNull(); |
1072 | |
1073 | // If we deferred a deduction of this pack, check that one now too. |
1074 | if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) { |
1075 | OldPack = Result; |
1076 | NewPack = Pack.DeferredDeduction; |
1077 | Result = checkDeducedTemplateArguments(Context&: S.Context, X: OldPack, Y: NewPack); |
1078 | } |
1079 | |
1080 | NamedDecl *Param = TemplateParams->getParam(Idx: Pack.Index); |
1081 | if (Result.isNull()) { |
1082 | Info.Param = makeTemplateParameter(Param); |
1083 | Info.FirstArg = OldPack; |
1084 | Info.SecondArg = NewPack; |
1085 | return TemplateDeductionResult::Inconsistent; |
1086 | } |
1087 | |
1088 | // If we have a pre-expanded pack and we didn't deduce enough elements |
1089 | // for it, fail deduction. |
1090 | if (UnsignedOrNone Expansions = getExpandedPackSize(Param)) { |
1091 | if (*Expansions != PackElements) { |
1092 | Info.Param = makeTemplateParameter(Param); |
1093 | Info.FirstArg = Result; |
1094 | return TemplateDeductionResult::IncompletePack; |
1095 | } |
1096 | } |
1097 | |
1098 | *Loc = Result; |
1099 | } |
1100 | |
1101 | return TemplateDeductionResult::Success; |
1102 | } |
1103 | |
1104 | private: |
1105 | Sema &S; |
1106 | TemplateParameterList *TemplateParams; |
1107 | SmallVectorImpl<DeducedTemplateArgument> &Deduced; |
1108 | TemplateDeductionInfo &Info; |
1109 | unsigned PackElements = 0; |
1110 | bool IsPartiallyExpanded = false; |
1111 | bool DeducePackIfNotAlreadyDeduced = false; |
1112 | bool DeducedFromEarlierParameter = false; |
1113 | bool FinishingDeduction = false; |
1114 | /// The number of expansions, if we have a fully-expanded pack in this scope. |
1115 | UnsignedOrNone FixedNumExpansions = std::nullopt; |
1116 | |
1117 | SmallVector<DeducedPack, 2> Packs; |
1118 | }; |
1119 | |
1120 | } // namespace |
1121 | |
1122 | template <class T> |
1123 | static TemplateDeductionResult DeduceForEachType( |
1124 | Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params, |
1125 | ArrayRef<QualType> Args, TemplateDeductionInfo &Info, |
1126 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, PartialOrderingKind POK, |
1127 | bool FinishingDeduction, T &&DeductFunc) { |
1128 | // C++0x [temp.deduct.type]p10: |
1129 | // Similarly, if P has a form that contains (T), then each parameter type |
1130 | // Pi of the respective parameter-type- list of P is compared with the |
1131 | // corresponding parameter type Ai of the corresponding parameter-type-list |
1132 | // of A. [...] |
1133 | unsigned ArgIdx = 0, ParamIdx = 0; |
1134 | for (; ParamIdx != Params.size(); ++ParamIdx) { |
1135 | // Check argument types. |
1136 | const PackExpansionType *Expansion |
1137 | = dyn_cast<PackExpansionType>(Val: Params[ParamIdx]); |
1138 | if (!Expansion) { |
1139 | // Simple case: compare the parameter and argument types at this point. |
1140 | |
1141 | // Make sure we have an argument. |
1142 | if (ArgIdx >= Args.size()) |
1143 | return TemplateDeductionResult::MiscellaneousDeductionFailure; |
1144 | |
1145 | if (isa<PackExpansionType>(Val: Args[ArgIdx])) { |
1146 | // C++0x [temp.deduct.type]p22: |
1147 | // If the original function parameter associated with A is a function |
1148 | // parameter pack and the function parameter associated with P is not |
1149 | // a function parameter pack, then template argument deduction fails. |
1150 | return TemplateDeductionResult::MiscellaneousDeductionFailure; |
1151 | } |
1152 | |
1153 | if (TemplateDeductionResult Result = |
1154 | DeductFunc(S, TemplateParams, ParamIdx, ArgIdx, |
1155 | Params[ParamIdx].getUnqualifiedType(), |
1156 | Args[ArgIdx].getUnqualifiedType(), Info, Deduced, POK); |
1157 | Result != TemplateDeductionResult::Success) |
1158 | return Result; |
1159 | |
1160 | ++ArgIdx; |
1161 | continue; |
1162 | } |
1163 | |
1164 | // C++0x [temp.deduct.type]p10: |
1165 | // If the parameter-declaration corresponding to Pi is a function |
1166 | // parameter pack, then the type of its declarator- id is compared with |
1167 | // each remaining parameter type in the parameter-type-list of A. Each |
1168 | // comparison deduces template arguments for subsequent positions in the |
1169 | // template parameter packs expanded by the function parameter pack. |
1170 | |
1171 | QualType Pattern = Expansion->getPattern(); |
1172 | PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern, |
1173 | /*DeducePackIfNotAlreadyDeduced=*/false, |
1174 | FinishingDeduction); |
1175 | |
1176 | // A pack scope with fixed arity is not really a pack any more, so is not |
1177 | // a non-deduced context. |
1178 | if (ParamIdx + 1 == Params.size() || PackScope.hasFixedArity()) { |
1179 | for (; ArgIdx < Args.size() && PackScope.hasNextElement(); ++ArgIdx) { |
1180 | // Deduce template arguments from the pattern. |
1181 | if (TemplateDeductionResult Result = DeductFunc( |
1182 | S, TemplateParams, ParamIdx, ArgIdx, |
1183 | Pattern.getUnqualifiedType(), Args[ArgIdx].getUnqualifiedType(), |
1184 | Info, Deduced, POK); |
1185 | Result != TemplateDeductionResult::Success) |
1186 | return Result; |
1187 | PackScope.nextPackElement(); |
1188 | } |
1189 | } else { |
1190 | // C++0x [temp.deduct.type]p5: |
1191 | // The non-deduced contexts are: |
1192 | // - A function parameter pack that does not occur at the end of the |
1193 | // parameter-declaration-clause. |
1194 | // |
1195 | // FIXME: There is no wording to say what we should do in this case. We |
1196 | // choose to resolve this by applying the same rule that is applied for a |
1197 | // function call: that is, deduce all contained packs to their |
1198 | // explicitly-specified values (or to <> if there is no such value). |
1199 | // |
1200 | // This is seemingly-arbitrarily different from the case of a template-id |
1201 | // with a non-trailing pack-expansion in its arguments, which renders the |
1202 | // entire template-argument-list a non-deduced context. |
1203 | |
1204 | // If the parameter type contains an explicitly-specified pack that we |
1205 | // could not expand, skip the number of parameters notionally created |
1206 | // by the expansion. |
1207 | UnsignedOrNone NumExpansions = Expansion->getNumExpansions(); |
1208 | if (NumExpansions && !PackScope.isPartiallyExpanded()) { |
1209 | for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size(); |
1210 | ++I, ++ArgIdx) |
1211 | PackScope.nextPackElement(); |
1212 | } |
1213 | } |
1214 | |
1215 | // Build argument packs for each of the parameter packs expanded by this |
1216 | // pack expansion. |
1217 | if (auto Result = PackScope.finish(); |
1218 | Result != TemplateDeductionResult::Success) |
1219 | return Result; |
1220 | } |
1221 | |
1222 | // DR692, DR1395 |
1223 | // C++0x [temp.deduct.type]p10: |
1224 | // If the parameter-declaration corresponding to P_i ... |
1225 | // During partial ordering, if Ai was originally a function parameter pack: |
1226 | // - if P does not contain a function parameter type corresponding to Ai then |
1227 | // Ai is ignored; |
1228 | if (POK == PartialOrderingKind::Call && ArgIdx + 1 == Args.size() && |
1229 | isa<PackExpansionType>(Val: Args[ArgIdx])) |
1230 | return TemplateDeductionResult::Success; |
1231 | |
1232 | // Make sure we don't have any extra arguments. |
1233 | if (ArgIdx < Args.size()) |
1234 | return TemplateDeductionResult::MiscellaneousDeductionFailure; |
1235 | |
1236 | return TemplateDeductionResult::Success; |
1237 | } |
1238 | |
1239 | /// Deduce the template arguments by comparing the list of parameter |
1240 | /// types to the list of argument types, as in the parameter-type-lists of |
1241 | /// function types (C++ [temp.deduct.type]p10). |
1242 | /// |
1243 | /// \param S The semantic analysis object within which we are deducing |
1244 | /// |
1245 | /// \param TemplateParams The template parameters that we are deducing |
1246 | /// |
1247 | /// \param Params The list of parameter types |
1248 | /// |
1249 | /// \param Args The list of argument types |
1250 | /// |
1251 | /// \param Info information about the template argument deduction itself |
1252 | /// |
1253 | /// \param Deduced the deduced template arguments |
1254 | /// |
1255 | /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe |
1256 | /// how template argument deduction is performed. |
1257 | /// |
1258 | /// \param PartialOrdering If true, we are performing template argument |
1259 | /// deduction for during partial ordering for a call |
1260 | /// (C++0x [temp.deduct.partial]). |
1261 | /// |
1262 | /// \param HasDeducedAnyParam If set, the object pointed at will indicate |
1263 | /// whether any template parameter was deduced. |
1264 | /// |
1265 | /// \param HasDeducedParam If set, the bit vector will be used to represent |
1266 | /// which template parameters were deduced, in order. |
1267 | /// |
1268 | /// \returns the result of template argument deduction so far. Note that a |
1269 | /// "success" result means that template argument deduction has not yet failed, |
1270 | /// but it may still fail, later, for other reasons. |
1271 | static TemplateDeductionResult DeduceTemplateArguments( |
1272 | Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params, |
1273 | ArrayRef<QualType> Args, TemplateDeductionInfo &Info, |
1274 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF, |
1275 | PartialOrderingKind POK, bool *HasDeducedAnyParam, |
1276 | llvm::SmallBitVector *HasDeducedParam) { |
1277 | return ::DeduceForEachType( |
1278 | S, TemplateParams, Params, Args, Info, Deduced, POK, |
1279 | /*FinishingDeduction=*/false, |
1280 | DeductFunc: [&](Sema &S, TemplateParameterList *TemplateParams, int ParamIdx, |
1281 | int ArgIdx, QualType P, QualType A, TemplateDeductionInfo &Info, |
1282 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
1283 | PartialOrderingKind POK) { |
1284 | bool HasDeducedAnyParamCopy = false; |
1285 | TemplateDeductionResult TDR = DeduceTemplateArgumentsByTypeMatch( |
1286 | S, TemplateParams, Param: P, Arg: A, Info, Deduced, TDF, POK, |
1287 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam: &HasDeducedAnyParamCopy); |
1288 | if (HasDeducedAnyParam && HasDeducedAnyParamCopy) |
1289 | *HasDeducedAnyParam = true; |
1290 | if (HasDeducedParam && HasDeducedAnyParamCopy) |
1291 | (*HasDeducedParam)[ParamIdx] = true; |
1292 | return TDR; |
1293 | }); |
1294 | } |
1295 | |
1296 | /// Determine whether the parameter has qualifiers that the argument |
1297 | /// lacks. Put another way, determine whether there is no way to add |
1298 | /// a deduced set of qualifiers to the ParamType that would result in |
1299 | /// its qualifiers matching those of the ArgType. |
1300 | static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, |
1301 | QualType ArgType) { |
1302 | Qualifiers ParamQs = ParamType.getQualifiers(); |
1303 | Qualifiers ArgQs = ArgType.getQualifiers(); |
1304 | |
1305 | if (ParamQs == ArgQs) |
1306 | return false; |
1307 | |
1308 | // Mismatched (but not missing) Objective-C GC attributes. |
1309 | if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() && |
1310 | ParamQs.hasObjCGCAttr()) |
1311 | return true; |
1312 | |
1313 | // Mismatched (but not missing) address spaces. |
1314 | if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() && |
1315 | ParamQs.hasAddressSpace()) |
1316 | return true; |
1317 | |
1318 | // Mismatched (but not missing) Objective-C lifetime qualifiers. |
1319 | if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() && |
1320 | ParamQs.hasObjCLifetime()) |
1321 | return true; |
1322 | |
1323 | // CVR qualifiers inconsistent or a superset. |
1324 | return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0; |
1325 | } |
1326 | |
1327 | bool Sema::isSameOrCompatibleFunctionType(QualType P, QualType A) { |
1328 | const FunctionType *PF = P->getAs<FunctionType>(), |
1329 | *AF = A->getAs<FunctionType>(); |
1330 | |
1331 | // Just compare if not functions. |
1332 | if (!PF || !AF) |
1333 | return Context.hasSameType(T1: P, T2: A); |
1334 | |
1335 | // Noreturn and noexcept adjustment. |
1336 | if (QualType AdjustedParam; TryFunctionConversion(FromType: P, ToType: A, ResultTy&: AdjustedParam)) |
1337 | P = AdjustedParam; |
1338 | |
1339 | // FIXME: Compatible calling conventions. |
1340 | return Context.hasSameFunctionTypeIgnoringExceptionSpec(T: P, U: A); |
1341 | } |
1342 | |
1343 | /// Get the index of the first template parameter that was originally from the |
1344 | /// innermost template-parameter-list. This is 0 except when we concatenate |
1345 | /// the template parameter lists of a class template and a constructor template |
1346 | /// when forming an implicit deduction guide. |
1347 | static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) { |
1348 | auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: FTD->getTemplatedDecl()); |
1349 | if (!Guide || !Guide->isImplicit()) |
1350 | return 0; |
1351 | return Guide->getDeducedTemplate()->getTemplateParameters()->size(); |
1352 | } |
1353 | |
1354 | /// Determine whether a type denotes a forwarding reference. |
1355 | static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) { |
1356 | // C++1z [temp.deduct.call]p3: |
1357 | // A forwarding reference is an rvalue reference to a cv-unqualified |
1358 | // template parameter that does not represent a template parameter of a |
1359 | // class template. |
1360 | if (auto *ParamRef = Param->getAs<RValueReferenceType>()) { |
1361 | if (ParamRef->getPointeeType().getQualifiers()) |
1362 | return false; |
1363 | auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>(); |
1364 | return TypeParm && TypeParm->getIndex() >= FirstInnerIndex; |
1365 | } |
1366 | return false; |
1367 | } |
1368 | |
1369 | /// Attempt to deduce the template arguments by checking the base types |
1370 | /// according to (C++20 [temp.deduct.call] p4b3. |
1371 | /// |
1372 | /// \param S the semantic analysis object within which we are deducing. |
1373 | /// |
1374 | /// \param RD the top level record object we are deducing against. |
1375 | /// |
1376 | /// \param TemplateParams the template parameters that we are deducing. |
1377 | /// |
1378 | /// \param P the template specialization parameter type. |
1379 | /// |
1380 | /// \param Info information about the template argument deduction itself. |
1381 | /// |
1382 | /// \param Deduced the deduced template arguments. |
1383 | /// |
1384 | /// \returns the result of template argument deduction with the bases. "invalid" |
1385 | /// means no matches, "success" found a single item, and the |
1386 | /// "MiscellaneousDeductionFailure" result happens when the match is ambiguous. |
1387 | static TemplateDeductionResult |
1388 | DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD, |
1389 | TemplateParameterList *TemplateParams, QualType P, |
1390 | TemplateDeductionInfo &Info, bool PartialOrdering, |
1391 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
1392 | bool *HasDeducedAnyParam) { |
1393 | // C++14 [temp.deduct.call] p4b3: |
1394 | // If P is a class and P has the form simple-template-id, then the |
1395 | // transformed A can be a derived class of the deduced A. Likewise if |
1396 | // P is a pointer to a class of the form simple-template-id, the |
1397 | // transformed A can be a pointer to a derived class pointed to by the |
1398 | // deduced A. However, if there is a class C that is a (direct or |
1399 | // indirect) base class of D and derived (directly or indirectly) from a |
1400 | // class B and that would be a valid deduced A, the deduced A cannot be |
1401 | // B or pointer to B, respectively. |
1402 | // |
1403 | // These alternatives are considered only if type deduction would |
1404 | // otherwise fail. If they yield more than one possible deduced A, the |
1405 | // type deduction fails. |
1406 | |
1407 | // Use a breadth-first search through the bases to collect the set of |
1408 | // successful matches. Visited contains the set of nodes we have already |
1409 | // visited, while ToVisit is our stack of records that we still need to |
1410 | // visit. Matches contains a list of matches that have yet to be |
1411 | // disqualified. |
1412 | llvm::SmallPtrSet<const CXXRecordDecl *, 8> Visited; |
1413 | SmallVector<QualType, 8> ToVisit; |
1414 | // We iterate over this later, so we have to use MapVector to ensure |
1415 | // determinism. |
1416 | struct MatchValue { |
1417 | SmallVector<DeducedTemplateArgument, 8> Deduced; |
1418 | bool HasDeducedAnyParam; |
1419 | }; |
1420 | llvm::MapVector<const CXXRecordDecl *, MatchValue> Matches; |
1421 | |
1422 | auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) { |
1423 | for (const auto &Base : RD->bases()) { |
1424 | QualType T = Base.getType(); |
1425 | assert(T->isRecordType() && "Base class that isn't a record?"); |
1426 | if (Visited.insert(Ptr: T->getAsCXXRecordDecl()).second) |
1427 | ToVisit.push_back(Elt: T); |
1428 | } |
1429 | }; |
1430 | |
1431 | // Set up the loop by adding all the bases. |
1432 | AddBases(RD); |
1433 | |
1434 | // Search each path of bases until we either run into a successful match |
1435 | // (where all bases of it are invalid), or we run out of bases. |
1436 | while (!ToVisit.empty()) { |
1437 | QualType NextT = ToVisit.pop_back_val(); |
1438 | |
1439 | SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(), |
1440 | Deduced.end()); |
1441 | TemplateDeductionInfo BaseInfo(TemplateDeductionInfo::ForBase, Info); |
1442 | bool HasDeducedAnyParamCopy = false; |
1443 | TemplateDeductionResult BaseResult = DeduceTemplateSpecArguments( |
1444 | S, TemplateParams, P, A: NextT, Info&: BaseInfo, PartialOrdering, Deduced&: DeducedCopy, |
1445 | HasDeducedAnyParam: &HasDeducedAnyParamCopy); |
1446 | |
1447 | // If this was a successful deduction, add it to the list of matches, |
1448 | // otherwise we need to continue searching its bases. |
1449 | const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl(); |
1450 | if (BaseResult == TemplateDeductionResult::Success) |
1451 | Matches.insert(KV: {RD, {.Deduced: DeducedCopy, .HasDeducedAnyParam: HasDeducedAnyParamCopy}}); |
1452 | else |
1453 | AddBases(RD); |
1454 | } |
1455 | |
1456 | // At this point, 'Matches' contains a list of seemingly valid bases, however |
1457 | // in the event that we have more than 1 match, it is possible that the base |
1458 | // of one of the matches might be disqualified for being a base of another |
1459 | // valid match. We can count on cyclical instantiations being invalid to |
1460 | // simplify the disqualifications. That is, if A & B are both matches, and B |
1461 | // inherits from A (disqualifying A), we know that A cannot inherit from B. |
1462 | if (Matches.size() > 1) { |
1463 | Visited.clear(); |
1464 | for (const auto &Match : Matches) |
1465 | AddBases(Match.first); |
1466 | |
1467 | // We can give up once we have a single item (or have run out of things to |
1468 | // search) since cyclical inheritance isn't valid. |
1469 | while (Matches.size() > 1 && !ToVisit.empty()) { |
1470 | const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl(); |
1471 | Matches.erase(Key: RD); |
1472 | |
1473 | // Always add all bases, since the inheritance tree can contain |
1474 | // disqualifications for multiple matches. |
1475 | AddBases(RD); |
1476 | } |
1477 | } |
1478 | |
1479 | if (Matches.empty()) |
1480 | return TemplateDeductionResult::Invalid; |
1481 | if (Matches.size() > 1) |
1482 | return TemplateDeductionResult::MiscellaneousDeductionFailure; |
1483 | |
1484 | std::swap(LHS&: Matches.front().second.Deduced, RHS&: Deduced); |
1485 | if (bool HasDeducedAnyParamCopy = Matches.front().second.HasDeducedAnyParam; |
1486 | HasDeducedAnyParamCopy && HasDeducedAnyParam) |
1487 | *HasDeducedAnyParam = HasDeducedAnyParamCopy; |
1488 | return TemplateDeductionResult::Success; |
1489 | } |
1490 | |
1491 | /// When propagating a partial ordering kind into a NonCall context, |
1492 | /// this is used to downgrade a 'Call' into a 'NonCall', so that |
1493 | /// the kind still reflects whether we are in a partial ordering context. |
1494 | static PartialOrderingKind |
1495 | degradeCallPartialOrderingKind(PartialOrderingKind POK) { |
1496 | return std::min(a: POK, b: PartialOrderingKind::NonCall); |
1497 | } |
1498 | |
1499 | /// Deduce the template arguments by comparing the parameter type and |
1500 | /// the argument type (C++ [temp.deduct.type]). |
1501 | /// |
1502 | /// \param S the semantic analysis object within which we are deducing |
1503 | /// |
1504 | /// \param TemplateParams the template parameters that we are deducing |
1505 | /// |
1506 | /// \param P the parameter type |
1507 | /// |
1508 | /// \param A the argument type |
1509 | /// |
1510 | /// \param Info information about the template argument deduction itself |
1511 | /// |
1512 | /// \param Deduced the deduced template arguments |
1513 | /// |
1514 | /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe |
1515 | /// how template argument deduction is performed. |
1516 | /// |
1517 | /// \param PartialOrdering Whether we're performing template argument deduction |
1518 | /// in the context of partial ordering (C++0x [temp.deduct.partial]). |
1519 | /// |
1520 | /// \returns the result of template argument deduction so far. Note that a |
1521 | /// "success" result means that template argument deduction has not yet failed, |
1522 | /// but it may still fail, later, for other reasons. |
1523 | static TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch( |
1524 | Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A, |
1525 | TemplateDeductionInfo &Info, |
1526 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF, |
1527 | PartialOrderingKind POK, bool DeducedFromArrayBound, |
1528 | bool *HasDeducedAnyParam) { |
1529 | |
1530 | // If the argument type is a pack expansion, look at its pattern. |
1531 | // This isn't explicitly called out |
1532 | if (const auto *AExp = dyn_cast<PackExpansionType>(Val&: A)) |
1533 | A = AExp->getPattern(); |
1534 | assert(!isa<PackExpansionType>(A.getCanonicalType())); |
1535 | |
1536 | if (POK == PartialOrderingKind::Call) { |
1537 | // C++11 [temp.deduct.partial]p5: |
1538 | // Before the partial ordering is done, certain transformations are |
1539 | // performed on the types used for partial ordering: |
1540 | // - If P is a reference type, P is replaced by the type referred to. |
1541 | const ReferenceType *PRef = P->getAs<ReferenceType>(); |
1542 | if (PRef) |
1543 | P = PRef->getPointeeType(); |
1544 | |
1545 | // - If A is a reference type, A is replaced by the type referred to. |
1546 | const ReferenceType *ARef = A->getAs<ReferenceType>(); |
1547 | if (ARef) |
1548 | A = A->getPointeeType(); |
1549 | |
1550 | if (PRef && ARef && S.Context.hasSameUnqualifiedType(T1: P, T2: A)) { |
1551 | // C++11 [temp.deduct.partial]p9: |
1552 | // If, for a given type, deduction succeeds in both directions (i.e., |
1553 | // the types are identical after the transformations above) and both |
1554 | // P and A were reference types [...]: |
1555 | // - if [one type] was an lvalue reference and [the other type] was |
1556 | // not, [the other type] is not considered to be at least as |
1557 | // specialized as [the first type] |
1558 | // - if [one type] is more cv-qualified than [the other type], |
1559 | // [the other type] is not considered to be at least as specialized |
1560 | // as [the first type] |
1561 | // Objective-C ARC adds: |
1562 | // - [one type] has non-trivial lifetime, [the other type] has |
1563 | // __unsafe_unretained lifetime, and the types are otherwise |
1564 | // identical |
1565 | // |
1566 | // A is "considered to be at least as specialized" as P iff deduction |
1567 | // succeeds, so we model this as a deduction failure. Note that |
1568 | // [the first type] is P and [the other type] is A here; the standard |
1569 | // gets this backwards. |
1570 | Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers(); |
1571 | if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) || |
1572 | PQuals.isStrictSupersetOf(Other: AQuals) || |
1573 | (PQuals.hasNonTrivialObjCLifetime() && |
1574 | AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone && |
1575 | PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) { |
1576 | Info.FirstArg = TemplateArgument(P); |
1577 | Info.SecondArg = TemplateArgument(A); |
1578 | return TemplateDeductionResult::NonDeducedMismatch; |
1579 | } |
1580 | } |
1581 | Qualifiers DiscardedQuals; |
1582 | // C++11 [temp.deduct.partial]p7: |
1583 | // Remove any top-level cv-qualifiers: |
1584 | // - If P is a cv-qualified type, P is replaced by the cv-unqualified |
1585 | // version of P. |
1586 | P = S.Context.getUnqualifiedArrayType(T: P, Quals&: DiscardedQuals); |
1587 | // - If A is a cv-qualified type, A is replaced by the cv-unqualified |
1588 | // version of A. |
1589 | A = S.Context.getUnqualifiedArrayType(T: A, Quals&: DiscardedQuals); |
1590 | } else { |
1591 | // C++0x [temp.deduct.call]p4 bullet 1: |
1592 | // - If the original P is a reference type, the deduced A (i.e., the type |
1593 | // referred to by the reference) can be more cv-qualified than the |
1594 | // transformed A. |
1595 | if (TDF & TDF_ParamWithReferenceType) { |
1596 | Qualifiers Quals; |
1597 | QualType UnqualP = S.Context.getUnqualifiedArrayType(T: P, Quals); |
1598 | Quals.setCVRQualifiers(Quals.getCVRQualifiers() & A.getCVRQualifiers()); |
1599 | P = S.Context.getQualifiedType(T: UnqualP, Qs: Quals); |
1600 | } |
1601 | |
1602 | if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) { |
1603 | // C++0x [temp.deduct.type]p10: |
1604 | // If P and A are function types that originated from deduction when |
1605 | // taking the address of a function template (14.8.2.2) or when deducing |
1606 | // template arguments from a function declaration (14.8.2.6) and Pi and |
1607 | // Ai are parameters of the top-level parameter-type-list of P and A, |
1608 | // respectively, Pi is adjusted if it is a forwarding reference and Ai |
1609 | // is an lvalue reference, in |
1610 | // which case the type of Pi is changed to be the template parameter |
1611 | // type (i.e., T&& is changed to simply T). [ Note: As a result, when |
1612 | // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be |
1613 | // deduced as X&. - end note ] |
1614 | TDF &= ~TDF_TopLevelParameterTypeList; |
1615 | if (isForwardingReference(Param: P, /*FirstInnerIndex=*/0) && |
1616 | A->isLValueReferenceType()) |
1617 | P = P->getPointeeType(); |
1618 | } |
1619 | } |
1620 | |
1621 | // C++ [temp.deduct.type]p9: |
1622 | // A template type argument T, a template template argument TT or a |
1623 | // template non-type argument i can be deduced if P and A have one of |
1624 | // the following forms: |
1625 | // |
1626 | // T |
1627 | // cv-list T |
1628 | if (const auto *TTP = P->getAs<TemplateTypeParmType>()) { |
1629 | // Just skip any attempts to deduce from a placeholder type or a parameter |
1630 | // at a different depth. |
1631 | if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth()) |
1632 | return TemplateDeductionResult::Success; |
1633 | |
1634 | unsigned Index = TTP->getIndex(); |
1635 | |
1636 | // If the argument type is an array type, move the qualifiers up to the |
1637 | // top level, so they can be matched with the qualifiers on the parameter. |
1638 | if (A->isArrayType()) { |
1639 | Qualifiers Quals; |
1640 | A = S.Context.getUnqualifiedArrayType(T: A, Quals); |
1641 | if (Quals) |
1642 | A = S.Context.getQualifiedType(T: A, Qs: Quals); |
1643 | } |
1644 | |
1645 | // The argument type can not be less qualified than the parameter |
1646 | // type. |
1647 | if (!(TDF & TDF_IgnoreQualifiers) && |
1648 | hasInconsistentOrSupersetQualifiersOf(ParamType: P, ArgType: A)) { |
1649 | Info.Param = cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: Index)); |
1650 | Info.FirstArg = TemplateArgument(P); |
1651 | Info.SecondArg = TemplateArgument(A); |
1652 | return TemplateDeductionResult::Underqualified; |
1653 | } |
1654 | |
1655 | // Do not match a function type with a cv-qualified type. |
1656 | // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584 |
1657 | if (A->isFunctionType() && P.hasQualifiers()) |
1658 | return TemplateDeductionResult::NonDeducedMismatch; |
1659 | |
1660 | assert(TTP->getDepth() == Info.getDeducedDepth() && |
1661 | "saw template type parameter with wrong depth"); |
1662 | assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy && |
1663 | "Unresolved overloaded function"); |
1664 | QualType DeducedType = A; |
1665 | |
1666 | // Remove any qualifiers on the parameter from the deduced type. |
1667 | // We checked the qualifiers for consistency above. |
1668 | Qualifiers DeducedQs = DeducedType.getQualifiers(); |
1669 | Qualifiers ParamQs = P.getQualifiers(); |
1670 | DeducedQs.removeCVRQualifiers(mask: ParamQs.getCVRQualifiers()); |
1671 | if (ParamQs.hasObjCGCAttr()) |
1672 | DeducedQs.removeObjCGCAttr(); |
1673 | if (ParamQs.hasAddressSpace()) |
1674 | DeducedQs.removeAddressSpace(); |
1675 | if (ParamQs.hasObjCLifetime()) |
1676 | DeducedQs.removeObjCLifetime(); |
1677 | |
1678 | // Objective-C ARC: |
1679 | // If template deduction would produce a lifetime qualifier on a type |
1680 | // that is not a lifetime type, template argument deduction fails. |
1681 | if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() && |
1682 | !DeducedType->isDependentType()) { |
1683 | Info.Param = cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: Index)); |
1684 | Info.FirstArg = TemplateArgument(P); |
1685 | Info.SecondArg = TemplateArgument(A); |
1686 | return TemplateDeductionResult::Underqualified; |
1687 | } |
1688 | |
1689 | // Objective-C ARC: |
1690 | // If template deduction would produce an argument type with lifetime type |
1691 | // but no lifetime qualifier, the __strong lifetime qualifier is inferred. |
1692 | if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() && |
1693 | !DeducedQs.hasObjCLifetime()) |
1694 | DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong); |
1695 | |
1696 | DeducedType = |
1697 | S.Context.getQualifiedType(T: DeducedType.getUnqualifiedType(), Qs: DeducedQs); |
1698 | |
1699 | DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound); |
1700 | DeducedTemplateArgument Result = |
1701 | checkDeducedTemplateArguments(Context&: S.Context, X: Deduced[Index], Y: NewDeduced); |
1702 | if (Result.isNull()) { |
1703 | // We can also get inconsistencies when matching NTTP type. |
1704 | switch (NamedDecl *Param = TemplateParams->getParam(Idx: Index); |
1705 | Param->getKind()) { |
1706 | case Decl::TemplateTypeParm: |
1707 | Info.Param = cast<TemplateTypeParmDecl>(Val: Param); |
1708 | break; |
1709 | case Decl::NonTypeTemplateParm: |
1710 | Info.Param = cast<NonTypeTemplateParmDecl>(Val: Param); |
1711 | break; |
1712 | case Decl::TemplateTemplateParm: |
1713 | Info.Param = cast<TemplateTemplateParmDecl>(Val: Param); |
1714 | break; |
1715 | default: |
1716 | llvm_unreachable("unexpected kind"); |
1717 | } |
1718 | Info.FirstArg = Deduced[Index]; |
1719 | Info.SecondArg = NewDeduced; |
1720 | return TemplateDeductionResult::Inconsistent; |
1721 | } |
1722 | |
1723 | Deduced[Index] = Result; |
1724 | if (HasDeducedAnyParam) |
1725 | *HasDeducedAnyParam = true; |
1726 | return TemplateDeductionResult::Success; |
1727 | } |
1728 | |
1729 | // Set up the template argument deduction information for a failure. |
1730 | Info.FirstArg = TemplateArgument(P); |
1731 | Info.SecondArg = TemplateArgument(A); |
1732 | |
1733 | // If the parameter is an already-substituted template parameter |
1734 | // pack, do nothing: we don't know which of its arguments to look |
1735 | // at, so we have to wait until all of the parameter packs in this |
1736 | // expansion have arguments. |
1737 | if (P->getAs<SubstTemplateTypeParmPackType>()) |
1738 | return TemplateDeductionResult::Success; |
1739 | |
1740 | // Check the cv-qualifiers on the parameter and argument types. |
1741 | if (!(TDF & TDF_IgnoreQualifiers)) { |
1742 | if (TDF & TDF_ParamWithReferenceType) { |
1743 | if (hasInconsistentOrSupersetQualifiersOf(ParamType: P, ArgType: A)) |
1744 | return TemplateDeductionResult::NonDeducedMismatch; |
1745 | } else if (TDF & TDF_ArgWithReferenceType) { |
1746 | // C++ [temp.deduct.conv]p4: |
1747 | // If the original A is a reference type, A can be more cv-qualified |
1748 | // than the deduced A |
1749 | if (!A.getQualifiers().compatiblyIncludes(other: P.getQualifiers(), |
1750 | Ctx: S.getASTContext())) |
1751 | return TemplateDeductionResult::NonDeducedMismatch; |
1752 | |
1753 | // Strip out all extra qualifiers from the argument to figure out the |
1754 | // type we're converting to, prior to the qualification conversion. |
1755 | Qualifiers Quals; |
1756 | A = S.Context.getUnqualifiedArrayType(T: A, Quals); |
1757 | A = S.Context.getQualifiedType(T: A, Qs: P.getQualifiers()); |
1758 | } else if (!IsPossiblyOpaquelyQualifiedType(T: P)) { |
1759 | if (P.getCVRQualifiers() != A.getCVRQualifiers()) |
1760 | return TemplateDeductionResult::NonDeducedMismatch; |
1761 | } |
1762 | } |
1763 | |
1764 | // If the parameter type is not dependent, there is nothing to deduce. |
1765 | if (!P->isDependentType()) { |
1766 | if (TDF & TDF_SkipNonDependent) |
1767 | return TemplateDeductionResult::Success; |
1768 | if ((TDF & TDF_IgnoreQualifiers) ? S.Context.hasSameUnqualifiedType(T1: P, T2: A) |
1769 | : S.Context.hasSameType(T1: P, T2: A)) |
1770 | return TemplateDeductionResult::Success; |
1771 | if (TDF & TDF_AllowCompatibleFunctionType && |
1772 | S.isSameOrCompatibleFunctionType(P, A)) |
1773 | return TemplateDeductionResult::Success; |
1774 | if (!(TDF & TDF_IgnoreQualifiers)) |
1775 | return TemplateDeductionResult::NonDeducedMismatch; |
1776 | // Otherwise, when ignoring qualifiers, the types not having the same |
1777 | // unqualified type does not mean they do not match, so in this case we |
1778 | // must keep going and analyze with a non-dependent parameter type. |
1779 | } |
1780 | |
1781 | switch (P.getCanonicalType()->getTypeClass()) { |
1782 | // Non-canonical types cannot appear here. |
1783 | #define NON_CANONICAL_TYPE(Class, Base) \ |
1784 | case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class); |
1785 | #define TYPE(Class, Base) |
1786 | #include "clang/AST/TypeNodes.inc" |
1787 | |
1788 | case Type::TemplateTypeParm: |
1789 | case Type::SubstTemplateTypeParmPack: |
1790 | llvm_unreachable("Type nodes handled above"); |
1791 | |
1792 | case Type::Auto: |
1793 | // C++23 [temp.deduct.funcaddr]/3: |
1794 | // A placeholder type in the return type of a function template is a |
1795 | // non-deduced context. |
1796 | // There's no corresponding wording for [temp.deduct.decl], but we treat |
1797 | // it the same to match other compilers. |
1798 | if (P->isDependentType()) |
1799 | return TemplateDeductionResult::Success; |
1800 | [[fallthrough]]; |
1801 | case Type::Builtin: |
1802 | case Type::VariableArray: |
1803 | case Type::Vector: |
1804 | case Type::FunctionNoProto: |
1805 | case Type::Record: |
1806 | case Type::Enum: |
1807 | case Type::ObjCObject: |
1808 | case Type::ObjCInterface: |
1809 | case Type::ObjCObjectPointer: |
1810 | case Type::BitInt: |
1811 | return (TDF & TDF_SkipNonDependent) || |
1812 | ((TDF & TDF_IgnoreQualifiers) |
1813 | ? S.Context.hasSameUnqualifiedType(T1: P, T2: A) |
1814 | : S.Context.hasSameType(T1: P, T2: A)) |
1815 | ? TemplateDeductionResult::Success |
1816 | : TemplateDeductionResult::NonDeducedMismatch; |
1817 | |
1818 | // _Complex T [placeholder extension] |
1819 | case Type::Complex: { |
1820 | const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>(); |
1821 | if (!CA) |
1822 | return TemplateDeductionResult::NonDeducedMismatch; |
1823 | return DeduceTemplateArgumentsByTypeMatch( |
1824 | S, TemplateParams, CP->getElementType(), CA->getElementType(), Info, |
1825 | Deduced, TDF, degradeCallPartialOrderingKind(POK), |
1826 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
1827 | } |
1828 | |
1829 | // _Atomic T [extension] |
1830 | case Type::Atomic: { |
1831 | const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>(); |
1832 | if (!AA) |
1833 | return TemplateDeductionResult::NonDeducedMismatch; |
1834 | return DeduceTemplateArgumentsByTypeMatch( |
1835 | S, TemplateParams, PA->getValueType(), AA->getValueType(), Info, |
1836 | Deduced, TDF, degradeCallPartialOrderingKind(POK), |
1837 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
1838 | } |
1839 | |
1840 | // T * |
1841 | case Type::Pointer: { |
1842 | QualType PointeeType; |
1843 | if (const auto *PA = A->getAs<PointerType>()) { |
1844 | PointeeType = PA->getPointeeType(); |
1845 | } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) { |
1846 | PointeeType = PA->getPointeeType(); |
1847 | } else { |
1848 | return TemplateDeductionResult::NonDeducedMismatch; |
1849 | } |
1850 | return DeduceTemplateArgumentsByTypeMatch( |
1851 | S, TemplateParams, P->castAs<PointerType>()->getPointeeType(), |
1852 | PointeeType, Info, Deduced, |
1853 | TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass), |
1854 | degradeCallPartialOrderingKind(POK), |
1855 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
1856 | } |
1857 | |
1858 | // T & |
1859 | case Type::LValueReference: { |
1860 | const auto *RP = P->castAs<LValueReferenceType>(), |
1861 | *RA = A->getAs<LValueReferenceType>(); |
1862 | if (!RA) |
1863 | return TemplateDeductionResult::NonDeducedMismatch; |
1864 | |
1865 | return DeduceTemplateArgumentsByTypeMatch( |
1866 | S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info, |
1867 | Deduced, 0, degradeCallPartialOrderingKind(POK), |
1868 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
1869 | } |
1870 | |
1871 | // T && [C++0x] |
1872 | case Type::RValueReference: { |
1873 | const auto *RP = P->castAs<RValueReferenceType>(), |
1874 | *RA = A->getAs<RValueReferenceType>(); |
1875 | if (!RA) |
1876 | return TemplateDeductionResult::NonDeducedMismatch; |
1877 | |
1878 | return DeduceTemplateArgumentsByTypeMatch( |
1879 | S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info, |
1880 | Deduced, 0, degradeCallPartialOrderingKind(POK), |
1881 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
1882 | } |
1883 | |
1884 | // T [] (implied, but not stated explicitly) |
1885 | case Type::IncompleteArray: { |
1886 | const auto *IAA = S.Context.getAsIncompleteArrayType(T: A); |
1887 | if (!IAA) |
1888 | return TemplateDeductionResult::NonDeducedMismatch; |
1889 | |
1890 | const auto *IAP = S.Context.getAsIncompleteArrayType(T: P); |
1891 | assert(IAP && "Template parameter not of incomplete array type"); |
1892 | |
1893 | return DeduceTemplateArgumentsByTypeMatch( |
1894 | S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info, |
1895 | Deduced, TDF & TDF_IgnoreQualifiers, |
1896 | degradeCallPartialOrderingKind(POK), |
1897 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
1898 | } |
1899 | |
1900 | // T [integer-constant] |
1901 | case Type::ConstantArray: { |
1902 | const auto *CAA = S.Context.getAsConstantArrayType(T: A), |
1903 | *CAP = S.Context.getAsConstantArrayType(T: P); |
1904 | assert(CAP); |
1905 | if (!CAA || CAA->getSize() != CAP->getSize()) |
1906 | return TemplateDeductionResult::NonDeducedMismatch; |
1907 | |
1908 | return DeduceTemplateArgumentsByTypeMatch( |
1909 | S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info, |
1910 | Deduced, TDF & TDF_IgnoreQualifiers, |
1911 | degradeCallPartialOrderingKind(POK), |
1912 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
1913 | } |
1914 | |
1915 | // type [i] |
1916 | case Type::DependentSizedArray: { |
1917 | const auto *AA = S.Context.getAsArrayType(T: A); |
1918 | if (!AA) |
1919 | return TemplateDeductionResult::NonDeducedMismatch; |
1920 | |
1921 | // Check the element type of the arrays |
1922 | const auto *DAP = S.Context.getAsDependentSizedArrayType(T: P); |
1923 | assert(DAP); |
1924 | if (auto Result = DeduceTemplateArgumentsByTypeMatch( |
1925 | S, TemplateParams, DAP->getElementType(), AA->getElementType(), |
1926 | Info, Deduced, TDF & TDF_IgnoreQualifiers, |
1927 | degradeCallPartialOrderingKind(POK), |
1928 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
1929 | Result != TemplateDeductionResult::Success) |
1930 | return Result; |
1931 | |
1932 | // Determine the array bound is something we can deduce. |
1933 | const NonTypeTemplateParmDecl *NTTP = |
1934 | getDeducedParameterFromExpr(Info, E: DAP->getSizeExpr()); |
1935 | if (!NTTP) |
1936 | return TemplateDeductionResult::Success; |
1937 | |
1938 | // We can perform template argument deduction for the given non-type |
1939 | // template parameter. |
1940 | assert(NTTP->getDepth() == Info.getDeducedDepth() && |
1941 | "saw non-type template parameter with wrong depth"); |
1942 | if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) { |
1943 | llvm::APSInt Size(CAA->getSize()); |
1944 | return DeduceNonTypeTemplateArgument( |
1945 | S, TemplateParams, NTTP, Value: Size, ValueType: S.Context.getSizeType(), |
1946 | /*ArrayBound=*/DeducedFromArrayBound: true, Info, PartialOrdering: POK != PartialOrderingKind::None, |
1947 | Deduced, HasDeducedAnyParam); |
1948 | } |
1949 | if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA)) |
1950 | if (DAA->getSizeExpr()) |
1951 | return DeduceNonTypeTemplateArgument( |
1952 | S, TemplateParams, NTTP, DAA->getSizeExpr(), Info, |
1953 | POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam); |
1954 | |
1955 | // Incomplete type does not match a dependently-sized array type |
1956 | return TemplateDeductionResult::NonDeducedMismatch; |
1957 | } |
1958 | |
1959 | // type(*)(T) |
1960 | // T(*)() |
1961 | // T(*)(T) |
1962 | case Type::FunctionProto: { |
1963 | const auto *FPP = P->castAs<FunctionProtoType>(), |
1964 | *FPA = A->getAs<FunctionProtoType>(); |
1965 | if (!FPA) |
1966 | return TemplateDeductionResult::NonDeducedMismatch; |
1967 | |
1968 | if (FPP->getMethodQuals() != FPA->getMethodQuals() || |
1969 | FPP->getRefQualifier() != FPA->getRefQualifier() || |
1970 | FPP->isVariadic() != FPA->isVariadic()) |
1971 | return TemplateDeductionResult::NonDeducedMismatch; |
1972 | |
1973 | // Check return types. |
1974 | if (auto Result = DeduceTemplateArgumentsByTypeMatch( |
1975 | S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(), |
1976 | Info, Deduced, 0, degradeCallPartialOrderingKind(POK), |
1977 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
1978 | Result != TemplateDeductionResult::Success) |
1979 | return Result; |
1980 | |
1981 | // Check parameter types. |
1982 | if (auto Result = DeduceTemplateArguments( |
1983 | S, TemplateParams, FPP->param_types(), FPA->param_types(), Info, |
1984 | Deduced, TDF & TDF_TopLevelParameterTypeList, POK, |
1985 | HasDeducedAnyParam, |
1986 | /*HasDeducedParam=*/nullptr); |
1987 | Result != TemplateDeductionResult::Success) |
1988 | return Result; |
1989 | |
1990 | if (TDF & TDF_AllowCompatibleFunctionType) |
1991 | return TemplateDeductionResult::Success; |
1992 | |
1993 | // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit |
1994 | // deducing through the noexcept-specifier if it's part of the canonical |
1995 | // type. libstdc++ relies on this. |
1996 | Expr *NoexceptExpr = FPP->getNoexceptExpr(); |
1997 | if (const NonTypeTemplateParmDecl *NTTP = |
1998 | NoexceptExpr ? getDeducedParameterFromExpr(Info, E: NoexceptExpr) |
1999 | : nullptr) { |
2000 | assert(NTTP->getDepth() == Info.getDeducedDepth() && |
2001 | "saw non-type template parameter with wrong depth"); |
2002 | |
2003 | llvm::APSInt Noexcept(1); |
2004 | switch (FPA->canThrow()) { |
2005 | case CT_Cannot: |
2006 | Noexcept = 1; |
2007 | [[fallthrough]]; |
2008 | |
2009 | case CT_Can: |
2010 | // We give E in noexcept(E) the "deduced from array bound" treatment. |
2011 | // FIXME: Should we? |
2012 | return DeduceNonTypeTemplateArgument( |
2013 | S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy, |
2014 | /*DeducedFromArrayBound=*/true, Info, |
2015 | POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam); |
2016 | |
2017 | case CT_Dependent: |
2018 | if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr()) |
2019 | return DeduceNonTypeTemplateArgument( |
2020 | S, TemplateParams, NTTP, Value: ArgNoexceptExpr, Info, |
2021 | PartialOrdering: POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam); |
2022 | // Can't deduce anything from throw(T...). |
2023 | break; |
2024 | } |
2025 | } |
2026 | // FIXME: Detect non-deduced exception specification mismatches? |
2027 | // |
2028 | // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow |
2029 | // top-level differences in noexcept-specifications. |
2030 | |
2031 | return TemplateDeductionResult::Success; |
2032 | } |
2033 | |
2034 | case Type::InjectedClassName: |
2035 | // Treat a template's injected-class-name as if the template |
2036 | // specialization type had been used. |
2037 | |
2038 | // template-name<T> (where template-name refers to a class template) |
2039 | // template-name<i> |
2040 | // TT<T> |
2041 | // TT<i> |
2042 | // TT<> |
2043 | case Type::TemplateSpecialization: { |
2044 | // When Arg cannot be a derived class, we can just try to deduce template |
2045 | // arguments from the template-id. |
2046 | if (!(TDF & TDF_DerivedClass) || !A->isRecordType()) |
2047 | return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info, |
2048 | PartialOrdering: POK != PartialOrderingKind::None, |
2049 | Deduced, HasDeducedAnyParam); |
2050 | |
2051 | SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(), |
2052 | Deduced.end()); |
2053 | |
2054 | auto Result = DeduceTemplateSpecArguments( |
2055 | S, TemplateParams, P, A, Info, PartialOrdering: POK != PartialOrderingKind::None, |
2056 | Deduced, HasDeducedAnyParam); |
2057 | if (Result == TemplateDeductionResult::Success) |
2058 | return Result; |
2059 | |
2060 | // We cannot inspect base classes as part of deduction when the type |
2061 | // is incomplete, so either instantiate any templates necessary to |
2062 | // complete the type, or skip over it if it cannot be completed. |
2063 | if (!S.isCompleteType(Loc: Info.getLocation(), T: A)) |
2064 | return Result; |
2065 | |
2066 | const CXXRecordDecl *RD = A->getAsCXXRecordDecl(); |
2067 | if (RD->isInvalidDecl()) |
2068 | return Result; |
2069 | |
2070 | // Reset the incorrectly deduced argument from above. |
2071 | Deduced = DeducedOrig; |
2072 | |
2073 | // Check bases according to C++14 [temp.deduct.call] p4b3: |
2074 | auto BaseResult = DeduceTemplateBases(S, RD, TemplateParams, P, Info, |
2075 | PartialOrdering: POK != PartialOrderingKind::None, |
2076 | Deduced, HasDeducedAnyParam); |
2077 | return BaseResult != TemplateDeductionResult::Invalid ? BaseResult |
2078 | : Result; |
2079 | } |
2080 | |
2081 | // T type::* |
2082 | // T T::* |
2083 | // T (type::*)() |
2084 | // type (T::*)() |
2085 | // type (type::*)(T) |
2086 | // type (T::*)(T) |
2087 | // T (type::*)(T) |
2088 | // T (T::*)() |
2089 | // T (T::*)(T) |
2090 | case Type::MemberPointer: { |
2091 | const auto *MPP = P->castAs<MemberPointerType>(), |
2092 | *MPA = A->getAs<MemberPointerType>(); |
2093 | if (!MPA) |
2094 | return TemplateDeductionResult::NonDeducedMismatch; |
2095 | |
2096 | QualType PPT = MPP->getPointeeType(); |
2097 | if (PPT->isFunctionType()) |
2098 | S.adjustMemberFunctionCC(T&: PPT, /*HasThisPointer=*/false, |
2099 | /*IsCtorOrDtor=*/false, Loc: Info.getLocation()); |
2100 | QualType APT = MPA->getPointeeType(); |
2101 | if (APT->isFunctionType()) |
2102 | S.adjustMemberFunctionCC(T&: APT, /*HasThisPointer=*/false, |
2103 | /*IsCtorOrDtor=*/false, Loc: Info.getLocation()); |
2104 | |
2105 | unsigned SubTDF = TDF & TDF_IgnoreQualifiers; |
2106 | if (auto Result = DeduceTemplateArgumentsByTypeMatch( |
2107 | S, TemplateParams, P: PPT, A: APT, Info, Deduced, TDF: SubTDF, |
2108 | POK: degradeCallPartialOrderingKind(POK), |
2109 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2110 | Result != TemplateDeductionResult::Success) |
2111 | return Result; |
2112 | |
2113 | QualType TP; |
2114 | if (MPP->isSugared()) { |
2115 | TP = S.Context.getTypeDeclType(Decl: MPP->getMostRecentCXXRecordDecl()); |
2116 | } else { |
2117 | NestedNameSpecifier *QP = MPP->getQualifier(); |
2118 | if (QP->getKind() == NestedNameSpecifier::Identifier) |
2119 | // Skip translation if it's a non-deduced context anyway. |
2120 | return TemplateDeductionResult::Success; |
2121 | TP = QualType(QP->translateToType(Context: S.Context), 0); |
2122 | } |
2123 | assert(!TP.isNull() && "member pointer with non-type class"); |
2124 | |
2125 | QualType TA; |
2126 | if (MPA->isSugared()) { |
2127 | TA = S.Context.getTypeDeclType(Decl: MPA->getMostRecentCXXRecordDecl()); |
2128 | } else { |
2129 | NestedNameSpecifier *QA = MPA->getQualifier(); |
2130 | TA = QualType(QA->translateToType(Context: S.Context), 0).getUnqualifiedType(); |
2131 | } |
2132 | assert(!TA.isNull() && "member pointer with non-type class"); |
2133 | return DeduceTemplateArgumentsByTypeMatch( |
2134 | S, TemplateParams, P: TP, A: TA, Info, Deduced, TDF: SubTDF, |
2135 | POK: degradeCallPartialOrderingKind(POK), |
2136 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2137 | } |
2138 | |
2139 | // (clang extension) |
2140 | // |
2141 | // type(^)(T) |
2142 | // T(^)() |
2143 | // T(^)(T) |
2144 | case Type::BlockPointer: { |
2145 | const auto *BPP = P->castAs<BlockPointerType>(), |
2146 | *BPA = A->getAs<BlockPointerType>(); |
2147 | if (!BPA) |
2148 | return TemplateDeductionResult::NonDeducedMismatch; |
2149 | return DeduceTemplateArgumentsByTypeMatch( |
2150 | S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info, |
2151 | Deduced, 0, degradeCallPartialOrderingKind(POK), |
2152 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2153 | } |
2154 | |
2155 | // (clang extension) |
2156 | // |
2157 | // T __attribute__(((ext_vector_type(<integral constant>)))) |
2158 | case Type::ExtVector: { |
2159 | const auto *VP = P->castAs<ExtVectorType>(); |
2160 | QualType ElementType; |
2161 | if (const auto *VA = A->getAs<ExtVectorType>()) { |
2162 | // Make sure that the vectors have the same number of elements. |
2163 | if (VP->getNumElements() != VA->getNumElements()) |
2164 | return TemplateDeductionResult::NonDeducedMismatch; |
2165 | ElementType = VA->getElementType(); |
2166 | } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) { |
2167 | // We can't check the number of elements, since the argument has a |
2168 | // dependent number of elements. This can only occur during partial |
2169 | // ordering. |
2170 | ElementType = VA->getElementType(); |
2171 | } else { |
2172 | return TemplateDeductionResult::NonDeducedMismatch; |
2173 | } |
2174 | // Perform deduction on the element types. |
2175 | return DeduceTemplateArgumentsByTypeMatch( |
2176 | S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced, |
2177 | TDF, degradeCallPartialOrderingKind(POK), |
2178 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2179 | } |
2180 | |
2181 | case Type::DependentVector: { |
2182 | const auto *VP = P->castAs<DependentVectorType>(); |
2183 | |
2184 | if (const auto *VA = A->getAs<VectorType>()) { |
2185 | // Perform deduction on the element types. |
2186 | if (auto Result = DeduceTemplateArgumentsByTypeMatch( |
2187 | S, TemplateParams, VP->getElementType(), VA->getElementType(), |
2188 | Info, Deduced, TDF, degradeCallPartialOrderingKind(POK), |
2189 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2190 | Result != TemplateDeductionResult::Success) |
2191 | return Result; |
2192 | |
2193 | // Perform deduction on the vector size, if we can. |
2194 | const NonTypeTemplateParmDecl *NTTP = |
2195 | getDeducedParameterFromExpr(Info, VP->getSizeExpr()); |
2196 | if (!NTTP) |
2197 | return TemplateDeductionResult::Success; |
2198 | |
2199 | llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false); |
2200 | ArgSize = VA->getNumElements(); |
2201 | // Note that we use the "array bound" rules here; just like in that |
2202 | // case, we don't have any particular type for the vector size, but |
2203 | // we can provide one if necessary. |
2204 | return DeduceNonTypeTemplateArgument( |
2205 | S, TemplateParams, NTTP, ArgSize, S.Context.UnsignedIntTy, true, |
2206 | Info, POK != PartialOrderingKind::None, Deduced, |
2207 | HasDeducedAnyParam); |
2208 | } |
2209 | |
2210 | if (const auto *VA = A->getAs<DependentVectorType>()) { |
2211 | // Perform deduction on the element types. |
2212 | if (auto Result = DeduceTemplateArgumentsByTypeMatch( |
2213 | S, TemplateParams, VP->getElementType(), VA->getElementType(), |
2214 | Info, Deduced, TDF, degradeCallPartialOrderingKind(POK), |
2215 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2216 | Result != TemplateDeductionResult::Success) |
2217 | return Result; |
2218 | |
2219 | // Perform deduction on the vector size, if we can. |
2220 | const NonTypeTemplateParmDecl *NTTP = |
2221 | getDeducedParameterFromExpr(Info, VP->getSizeExpr()); |
2222 | if (!NTTP) |
2223 | return TemplateDeductionResult::Success; |
2224 | |
2225 | return DeduceNonTypeTemplateArgument( |
2226 | S, TemplateParams, NTTP, VA->getSizeExpr(), Info, |
2227 | POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam); |
2228 | } |
2229 | |
2230 | return TemplateDeductionResult::NonDeducedMismatch; |
2231 | } |
2232 | |
2233 | // (clang extension) |
2234 | // |
2235 | // T __attribute__(((ext_vector_type(N)))) |
2236 | case Type::DependentSizedExtVector: { |
2237 | const auto *VP = P->castAs<DependentSizedExtVectorType>(); |
2238 | |
2239 | if (const auto *VA = A->getAs<ExtVectorType>()) { |
2240 | // Perform deduction on the element types. |
2241 | if (auto Result = DeduceTemplateArgumentsByTypeMatch( |
2242 | S, TemplateParams, VP->getElementType(), VA->getElementType(), |
2243 | Info, Deduced, TDF, degradeCallPartialOrderingKind(POK), |
2244 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2245 | Result != TemplateDeductionResult::Success) |
2246 | return Result; |
2247 | |
2248 | // Perform deduction on the vector size, if we can. |
2249 | const NonTypeTemplateParmDecl *NTTP = |
2250 | getDeducedParameterFromExpr(Info, VP->getSizeExpr()); |
2251 | if (!NTTP) |
2252 | return TemplateDeductionResult::Success; |
2253 | |
2254 | llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false); |
2255 | ArgSize = VA->getNumElements(); |
2256 | // Note that we use the "array bound" rules here; just like in that |
2257 | // case, we don't have any particular type for the vector size, but |
2258 | // we can provide one if necessary. |
2259 | return DeduceNonTypeTemplateArgument( |
2260 | S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info, |
2261 | POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam); |
2262 | } |
2263 | |
2264 | if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) { |
2265 | // Perform deduction on the element types. |
2266 | if (auto Result = DeduceTemplateArgumentsByTypeMatch( |
2267 | S, TemplateParams, VP->getElementType(), VA->getElementType(), |
2268 | Info, Deduced, TDF, degradeCallPartialOrderingKind(POK), |
2269 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2270 | Result != TemplateDeductionResult::Success) |
2271 | return Result; |
2272 | |
2273 | // Perform deduction on the vector size, if we can. |
2274 | const NonTypeTemplateParmDecl *NTTP = |
2275 | getDeducedParameterFromExpr(Info, VP->getSizeExpr()); |
2276 | if (!NTTP) |
2277 | return TemplateDeductionResult::Success; |
2278 | |
2279 | return DeduceNonTypeTemplateArgument( |
2280 | S, TemplateParams, NTTP, VA->getSizeExpr(), Info, |
2281 | POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam); |
2282 | } |
2283 | |
2284 | return TemplateDeductionResult::NonDeducedMismatch; |
2285 | } |
2286 | |
2287 | // (clang extension) |
2288 | // |
2289 | // T __attribute__((matrix_type(<integral constant>, |
2290 | // <integral constant>))) |
2291 | case Type::ConstantMatrix: { |
2292 | const auto *MP = P->castAs<ConstantMatrixType>(), |
2293 | *MA = A->getAs<ConstantMatrixType>(); |
2294 | if (!MA) |
2295 | return TemplateDeductionResult::NonDeducedMismatch; |
2296 | |
2297 | // Check that the dimensions are the same |
2298 | if (MP->getNumRows() != MA->getNumRows() || |
2299 | MP->getNumColumns() != MA->getNumColumns()) { |
2300 | return TemplateDeductionResult::NonDeducedMismatch; |
2301 | } |
2302 | // Perform deduction on element types. |
2303 | return DeduceTemplateArgumentsByTypeMatch( |
2304 | S, TemplateParams, MP->getElementType(), MA->getElementType(), Info, |
2305 | Deduced, TDF, degradeCallPartialOrderingKind(POK), |
2306 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2307 | } |
2308 | |
2309 | case Type::DependentSizedMatrix: { |
2310 | const auto *MP = P->castAs<DependentSizedMatrixType>(); |
2311 | const auto *MA = A->getAs<MatrixType>(); |
2312 | if (!MA) |
2313 | return TemplateDeductionResult::NonDeducedMismatch; |
2314 | |
2315 | // Check the element type of the matrixes. |
2316 | if (auto Result = DeduceTemplateArgumentsByTypeMatch( |
2317 | S, TemplateParams, MP->getElementType(), MA->getElementType(), |
2318 | Info, Deduced, TDF, degradeCallPartialOrderingKind(POK), |
2319 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2320 | Result != TemplateDeductionResult::Success) |
2321 | return Result; |
2322 | |
2323 | // Try to deduce a matrix dimension. |
2324 | auto DeduceMatrixArg = |
2325 | [&S, &Info, &Deduced, &TemplateParams, &HasDeducedAnyParam, POK]( |
2326 | Expr *ParamExpr, const MatrixType *A, |
2327 | unsigned (ConstantMatrixType::*GetArgDimension)() const, |
2328 | Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) { |
2329 | const auto *ACM = dyn_cast<ConstantMatrixType>(A); |
2330 | const auto *ADM = dyn_cast<DependentSizedMatrixType>(A); |
2331 | if (!ParamExpr->isValueDependent()) { |
2332 | std::optional<llvm::APSInt> ParamConst = |
2333 | ParamExpr->getIntegerConstantExpr(Ctx: S.Context); |
2334 | if (!ParamConst) |
2335 | return TemplateDeductionResult::NonDeducedMismatch; |
2336 | |
2337 | if (ACM) { |
2338 | if ((ACM->*GetArgDimension)() == *ParamConst) |
2339 | return TemplateDeductionResult::Success; |
2340 | return TemplateDeductionResult::NonDeducedMismatch; |
2341 | } |
2342 | |
2343 | Expr *ArgExpr = (ADM->*GetArgDimensionExpr)(); |
2344 | if (std::optional<llvm::APSInt> ArgConst = |
2345 | ArgExpr->getIntegerConstantExpr(Ctx: S.Context)) |
2346 | if (*ArgConst == *ParamConst) |
2347 | return TemplateDeductionResult::Success; |
2348 | return TemplateDeductionResult::NonDeducedMismatch; |
2349 | } |
2350 | |
2351 | const NonTypeTemplateParmDecl *NTTP = |
2352 | getDeducedParameterFromExpr(Info, E: ParamExpr); |
2353 | if (!NTTP) |
2354 | return TemplateDeductionResult::Success; |
2355 | |
2356 | if (ACM) { |
2357 | llvm::APSInt ArgConst( |
2358 | S.Context.getTypeSize(T: S.Context.getSizeType())); |
2359 | ArgConst = (ACM->*GetArgDimension)(); |
2360 | return DeduceNonTypeTemplateArgument( |
2361 | S, TemplateParams, NTTP, Value: ArgConst, ValueType: S.Context.getSizeType(), |
2362 | /*ArrayBound=*/DeducedFromArrayBound: true, Info, PartialOrdering: POK != PartialOrderingKind::None, |
2363 | Deduced, HasDeducedAnyParam); |
2364 | } |
2365 | |
2366 | return DeduceNonTypeTemplateArgument( |
2367 | S, TemplateParams, NTTP, (ADM->*GetArgDimensionExpr)(), Info, |
2368 | POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam); |
2369 | }; |
2370 | |
2371 | if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA, |
2372 | &ConstantMatrixType::getNumRows, |
2373 | &DependentSizedMatrixType::getRowExpr); |
2374 | Result != TemplateDeductionResult::Success) |
2375 | return Result; |
2376 | |
2377 | return DeduceMatrixArg(MP->getColumnExpr(), MA, |
2378 | &ConstantMatrixType::getNumColumns, |
2379 | &DependentSizedMatrixType::getColumnExpr); |
2380 | } |
2381 | |
2382 | // (clang extension) |
2383 | // |
2384 | // T __attribute__(((address_space(N)))) |
2385 | case Type::DependentAddressSpace: { |
2386 | const auto *ASP = P->castAs<DependentAddressSpaceType>(); |
2387 | |
2388 | if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) { |
2389 | // Perform deduction on the pointer type. |
2390 | if (auto Result = DeduceTemplateArgumentsByTypeMatch( |
2391 | S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(), |
2392 | Info, Deduced, TDF, degradeCallPartialOrderingKind(POK), |
2393 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2394 | Result != TemplateDeductionResult::Success) |
2395 | return Result; |
2396 | |
2397 | // Perform deduction on the address space, if we can. |
2398 | const NonTypeTemplateParmDecl *NTTP = |
2399 | getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr()); |
2400 | if (!NTTP) |
2401 | return TemplateDeductionResult::Success; |
2402 | |
2403 | return DeduceNonTypeTemplateArgument( |
2404 | S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info, |
2405 | POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam); |
2406 | } |
2407 | |
2408 | if (isTargetAddressSpace(AS: A.getAddressSpace())) { |
2409 | llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy), |
2410 | false); |
2411 | ArgAddressSpace = toTargetAddressSpace(AS: A.getAddressSpace()); |
2412 | |
2413 | // Perform deduction on the pointer types. |
2414 | if (auto Result = DeduceTemplateArgumentsByTypeMatch( |
2415 | S, TemplateParams, ASP->getPointeeType(), |
2416 | S.Context.removeAddrSpaceQualType(T: A), Info, Deduced, TDF, |
2417 | degradeCallPartialOrderingKind(POK), |
2418 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2419 | Result != TemplateDeductionResult::Success) |
2420 | return Result; |
2421 | |
2422 | // Perform deduction on the address space, if we can. |
2423 | const NonTypeTemplateParmDecl *NTTP = |
2424 | getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr()); |
2425 | if (!NTTP) |
2426 | return TemplateDeductionResult::Success; |
2427 | |
2428 | return DeduceNonTypeTemplateArgument( |
2429 | S, TemplateParams, NTTP, ArgAddressSpace, S.Context.IntTy, true, |
2430 | Info, POK != PartialOrderingKind::None, Deduced, |
2431 | HasDeducedAnyParam); |
2432 | } |
2433 | |
2434 | return TemplateDeductionResult::NonDeducedMismatch; |
2435 | } |
2436 | case Type::DependentBitInt: { |
2437 | const auto *IP = P->castAs<DependentBitIntType>(); |
2438 | |
2439 | if (const auto *IA = A->getAs<BitIntType>()) { |
2440 | if (IP->isUnsigned() != IA->isUnsigned()) |
2441 | return TemplateDeductionResult::NonDeducedMismatch; |
2442 | |
2443 | const NonTypeTemplateParmDecl *NTTP = |
2444 | getDeducedParameterFromExpr(Info, IP->getNumBitsExpr()); |
2445 | if (!NTTP) |
2446 | return TemplateDeductionResult::Success; |
2447 | |
2448 | llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false); |
2449 | ArgSize = IA->getNumBits(); |
2450 | |
2451 | return DeduceNonTypeTemplateArgument( |
2452 | S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info, |
2453 | POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam); |
2454 | } |
2455 | |
2456 | if (const auto *IA = A->getAs<DependentBitIntType>()) { |
2457 | if (IP->isUnsigned() != IA->isUnsigned()) |
2458 | return TemplateDeductionResult::NonDeducedMismatch; |
2459 | return TemplateDeductionResult::Success; |
2460 | } |
2461 | |
2462 | return TemplateDeductionResult::NonDeducedMismatch; |
2463 | } |
2464 | |
2465 | case Type::TypeOfExpr: |
2466 | case Type::TypeOf: |
2467 | case Type::DependentName: |
2468 | case Type::UnresolvedUsing: |
2469 | case Type::Decltype: |
2470 | case Type::UnaryTransform: |
2471 | case Type::DeducedTemplateSpecialization: |
2472 | case Type::DependentTemplateSpecialization: |
2473 | case Type::PackExpansion: |
2474 | case Type::Pipe: |
2475 | case Type::ArrayParameter: |
2476 | case Type::HLSLAttributedResource: |
2477 | case Type::HLSLInlineSpirv: |
2478 | // No template argument deduction for these types |
2479 | return TemplateDeductionResult::Success; |
2480 | |
2481 | case Type::PackIndexing: { |
2482 | const PackIndexingType *PIT = P->getAs<PackIndexingType>(); |
2483 | if (PIT->hasSelectedType()) { |
2484 | return DeduceTemplateArgumentsByTypeMatch( |
2485 | S, TemplateParams, P: PIT->getSelectedType(), A, Info, Deduced, TDF, |
2486 | POK: degradeCallPartialOrderingKind(POK), |
2487 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2488 | } |
2489 | return TemplateDeductionResult::IncompletePack; |
2490 | } |
2491 | } |
2492 | |
2493 | llvm_unreachable("Invalid Type Class!"); |
2494 | } |
2495 | |
2496 | static TemplateDeductionResult |
2497 | DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, |
2498 | const TemplateArgument &P, TemplateArgument A, |
2499 | TemplateDeductionInfo &Info, bool PartialOrdering, |
2500 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
2501 | bool *HasDeducedAnyParam) { |
2502 | // If the template argument is a pack expansion, perform template argument |
2503 | // deduction against the pattern of that expansion. This only occurs during |
2504 | // partial ordering. |
2505 | if (A.isPackExpansion()) |
2506 | A = A.getPackExpansionPattern(); |
2507 | |
2508 | switch (P.getKind()) { |
2509 | case TemplateArgument::Null: |
2510 | llvm_unreachable("Null template argument in parameter list"); |
2511 | |
2512 | case TemplateArgument::Type: |
2513 | if (A.getKind() == TemplateArgument::Type) |
2514 | return DeduceTemplateArgumentsByTypeMatch( |
2515 | S, TemplateParams, P: P.getAsType(), A: A.getAsType(), Info, Deduced, TDF: 0, |
2516 | POK: PartialOrdering ? PartialOrderingKind::NonCall |
2517 | : PartialOrderingKind::None, |
2518 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2519 | Info.FirstArg = P; |
2520 | Info.SecondArg = A; |
2521 | return TemplateDeductionResult::NonDeducedMismatch; |
2522 | |
2523 | case TemplateArgument::Template: |
2524 | // PartialOrdering does not matter here, since template specializations are |
2525 | // not being deduced. |
2526 | if (A.getKind() == TemplateArgument::Template) |
2527 | return DeduceTemplateArguments( |
2528 | S, TemplateParams, Param: P.getAsTemplate(), Arg: A.getAsTemplate(), Info, |
2529 | /*DefaultArguments=*/{}, /*PartialOrdering=*/false, Deduced, |
2530 | HasDeducedAnyParam); |
2531 | Info.FirstArg = P; |
2532 | Info.SecondArg = A; |
2533 | return TemplateDeductionResult::NonDeducedMismatch; |
2534 | |
2535 | case TemplateArgument::TemplateExpansion: |
2536 | llvm_unreachable("caller should handle pack expansions"); |
2537 | |
2538 | case TemplateArgument::Declaration: |
2539 | if (A.getKind() == TemplateArgument::Declaration && |
2540 | isSameDeclaration(P.getAsDecl(), A.getAsDecl())) |
2541 | return TemplateDeductionResult::Success; |
2542 | |
2543 | Info.FirstArg = P; |
2544 | Info.SecondArg = A; |
2545 | return TemplateDeductionResult::NonDeducedMismatch; |
2546 | |
2547 | case TemplateArgument::NullPtr: |
2548 | // 'nullptr' has only one possible value, so it always matches. |
2549 | if (A.getKind() == TemplateArgument::NullPtr) |
2550 | return TemplateDeductionResult::Success; |
2551 | Info.FirstArg = P; |
2552 | Info.SecondArg = A; |
2553 | return TemplateDeductionResult::NonDeducedMismatch; |
2554 | |
2555 | case TemplateArgument::Integral: |
2556 | if (A.getKind() == TemplateArgument::Integral) { |
2557 | if (llvm::APSInt::isSameValue(I1: P.getAsIntegral(), I2: A.getAsIntegral())) |
2558 | return TemplateDeductionResult::Success; |
2559 | } |
2560 | Info.FirstArg = P; |
2561 | Info.SecondArg = A; |
2562 | return TemplateDeductionResult::NonDeducedMismatch; |
2563 | |
2564 | case TemplateArgument::StructuralValue: |
2565 | // FIXME: structural equality will also compare types, |
2566 | // but they should match iff they have the same value. |
2567 | if (A.getKind() == TemplateArgument::StructuralValue && |
2568 | A.structurallyEquals(Other: P)) |
2569 | return TemplateDeductionResult::Success; |
2570 | |
2571 | Info.FirstArg = P; |
2572 | Info.SecondArg = A; |
2573 | return TemplateDeductionResult::NonDeducedMismatch; |
2574 | |
2575 | case TemplateArgument::Expression: |
2576 | if (const NonTypeTemplateParmDecl *NTTP = |
2577 | getDeducedParameterFromExpr(Info, E: P.getAsExpr())) { |
2578 | switch (A.getKind()) { |
2579 | case TemplateArgument::Expression: { |
2580 | const Expr *E = A.getAsExpr(); |
2581 | // When checking NTTP, if either the parameter or the argument is |
2582 | // dependent, as there would be otherwise nothing to deduce, we force |
2583 | // the argument to the parameter type using this dependent implicit |
2584 | // cast, in order to maintain invariants. Now we can deduce the |
2585 | // resulting type from the original type, and deduce the original type |
2586 | // against the parameter we are checking. |
2587 | if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E); |
2588 | ICE && ICE->getCastKind() == clang::CK_Dependent) { |
2589 | E = ICE->getSubExpr(); |
2590 | if (auto Result = DeduceTemplateArgumentsByTypeMatch( |
2591 | S, TemplateParams, ICE->getType(), E->getType(), Info, |
2592 | Deduced, TDF_SkipNonDependent, |
2593 | PartialOrdering ? PartialOrderingKind::NonCall |
2594 | : PartialOrderingKind::None, |
2595 | /*DeducedFromArrayBound=*/false, HasDeducedAnyParam); |
2596 | Result != TemplateDeductionResult::Success) |
2597 | return Result; |
2598 | } |
2599 | return DeduceNonTypeTemplateArgument( |
2600 | S, TemplateParams, NTTP, NewDeduced: DeducedTemplateArgument(A), ValueType: E->getType(), |
2601 | Info, PartialOrdering, Deduced, HasDeducedAnyParam); |
2602 | } |
2603 | case TemplateArgument::Integral: |
2604 | case TemplateArgument::StructuralValue: |
2605 | return DeduceNonTypeTemplateArgument( |
2606 | S, TemplateParams, NTTP, NewDeduced: DeducedTemplateArgument(A), |
2607 | ValueType: A.getNonTypeTemplateArgumentType(), Info, PartialOrdering, Deduced, |
2608 | HasDeducedAnyParam); |
2609 | |
2610 | case TemplateArgument::NullPtr: |
2611 | return DeduceNullPtrTemplateArgument( |
2612 | S, TemplateParams, NTTP, NullPtrType: A.getNullPtrType(), Info, PartialOrdering, |
2613 | Deduced, HasDeducedAnyParam); |
2614 | |
2615 | case TemplateArgument::Declaration: |
2616 | return DeduceNonTypeTemplateArgument( |
2617 | S, TemplateParams, NTTP, D: A.getAsDecl(), T: A.getParamTypeForDecl(), |
2618 | Info, PartialOrdering, Deduced, HasDeducedAnyParam); |
2619 | |
2620 | case TemplateArgument::Null: |
2621 | case TemplateArgument::Type: |
2622 | case TemplateArgument::Template: |
2623 | case TemplateArgument::TemplateExpansion: |
2624 | case TemplateArgument::Pack: |
2625 | Info.FirstArg = P; |
2626 | Info.SecondArg = A; |
2627 | return TemplateDeductionResult::NonDeducedMismatch; |
2628 | } |
2629 | llvm_unreachable("Unknown template argument kind"); |
2630 | } |
2631 | |
2632 | // Can't deduce anything, but that's okay. |
2633 | return TemplateDeductionResult::Success; |
2634 | case TemplateArgument::Pack: |
2635 | llvm_unreachable("Argument packs should be expanded by the caller!"); |
2636 | } |
2637 | |
2638 | llvm_unreachable("Invalid TemplateArgument Kind!"); |
2639 | } |
2640 | |
2641 | /// Determine whether there is a template argument to be used for |
2642 | /// deduction. |
2643 | /// |
2644 | /// This routine "expands" argument packs in-place, overriding its input |
2645 | /// parameters so that \c Args[ArgIdx] will be the available template argument. |
2646 | /// |
2647 | /// \returns true if there is another template argument (which will be at |
2648 | /// \c Args[ArgIdx]), false otherwise. |
2649 | static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args, |
2650 | unsigned &ArgIdx) { |
2651 | if (ArgIdx == Args.size()) |
2652 | return false; |
2653 | |
2654 | const TemplateArgument &Arg = Args[ArgIdx]; |
2655 | if (Arg.getKind() != TemplateArgument::Pack) |
2656 | return true; |
2657 | |
2658 | assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?"); |
2659 | Args = Arg.pack_elements(); |
2660 | ArgIdx = 0; |
2661 | return ArgIdx < Args.size(); |
2662 | } |
2663 | |
2664 | /// Determine whether the given set of template arguments has a pack |
2665 | /// expansion that is not the last template argument. |
2666 | static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) { |
2667 | bool FoundPackExpansion = false; |
2668 | for (const auto &A : Args) { |
2669 | if (FoundPackExpansion) |
2670 | return true; |
2671 | |
2672 | if (A.getKind() == TemplateArgument::Pack) |
2673 | return hasPackExpansionBeforeEnd(Args: A.pack_elements()); |
2674 | |
2675 | // FIXME: If this is a fixed-arity pack expansion from an outer level of |
2676 | // templates, it should not be treated as a pack expansion. |
2677 | if (A.isPackExpansion()) |
2678 | FoundPackExpansion = true; |
2679 | } |
2680 | |
2681 | return false; |
2682 | } |
2683 | |
2684 | static TemplateDeductionResult |
2685 | DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, |
2686 | ArrayRef<TemplateArgument> Ps, |
2687 | ArrayRef<TemplateArgument> As, |
2688 | TemplateDeductionInfo &Info, |
2689 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
2690 | bool NumberOfArgumentsMustMatch, bool PartialOrdering, |
2691 | PackFold PackFold, bool *HasDeducedAnyParam) { |
2692 | bool FoldPackParameter = PackFold == PackFold::ParameterToArgument || |
2693 | PackFold == PackFold::Both, |
2694 | FoldPackArgument = PackFold == PackFold::ArgumentToParameter || |
2695 | PackFold == PackFold::Both; |
2696 | |
2697 | // C++0x [temp.deduct.type]p9: |
2698 | // If the template argument list of P contains a pack expansion that is not |
2699 | // the last template argument, the entire template argument list is a |
2700 | // non-deduced context. |
2701 | if (FoldPackParameter && hasPackExpansionBeforeEnd(Args: Ps)) |
2702 | return TemplateDeductionResult::Success; |
2703 | |
2704 | // C++0x [temp.deduct.type]p9: |
2705 | // If P has a form that contains <T> or <i>, then each argument Pi of the |
2706 | // respective template argument list P is compared with the corresponding |
2707 | // argument Ai of the corresponding template argument list of A. |
2708 | for (unsigned ArgIdx = 0, ParamIdx = 0; /**/; /**/) { |
2709 | if (!hasTemplateArgumentForDeduction(Args&: Ps, ArgIdx&: ParamIdx)) |
2710 | return !FoldPackParameter && hasTemplateArgumentForDeduction(Args&: As, ArgIdx) |
2711 | ? TemplateDeductionResult::MiscellaneousDeductionFailure |
2712 | : TemplateDeductionResult::Success; |
2713 | |
2714 | if (!Ps[ParamIdx].isPackExpansion()) { |
2715 | // The simple case: deduce template arguments by matching Pi and Ai. |
2716 | |
2717 | // Check whether we have enough arguments. |
2718 | if (!hasTemplateArgumentForDeduction(Args&: As, ArgIdx)) |
2719 | return !FoldPackArgument && NumberOfArgumentsMustMatch |
2720 | ? TemplateDeductionResult::MiscellaneousDeductionFailure |
2721 | : TemplateDeductionResult::Success; |
2722 | |
2723 | if (As[ArgIdx].isPackExpansion()) { |
2724 | // C++1z [temp.deduct.type]p9: |
2725 | // During partial ordering, if Ai was originally a pack expansion |
2726 | // [and] Pi is not a pack expansion, template argument deduction |
2727 | // fails. |
2728 | if (!FoldPackArgument) |
2729 | return TemplateDeductionResult::MiscellaneousDeductionFailure; |
2730 | |
2731 | TemplateArgument Pattern = As[ArgIdx].getPackExpansionPattern(); |
2732 | for (;;) { |
2733 | // Deduce template parameters from the pattern. |
2734 | if (auto Result = DeduceTemplateArguments( |
2735 | S, TemplateParams, P: Ps[ParamIdx], A: Pattern, Info, |
2736 | PartialOrdering, Deduced, HasDeducedAnyParam); |
2737 | Result != TemplateDeductionResult::Success) |
2738 | return Result; |
2739 | |
2740 | ++ParamIdx; |
2741 | if (!hasTemplateArgumentForDeduction(Args&: Ps, ArgIdx&: ParamIdx)) |
2742 | return TemplateDeductionResult::Success; |
2743 | if (Ps[ParamIdx].isPackExpansion()) |
2744 | break; |
2745 | } |
2746 | } else { |
2747 | // Perform deduction for this Pi/Ai pair. |
2748 | if (auto Result = DeduceTemplateArguments( |
2749 | S, TemplateParams, P: Ps[ParamIdx], A: As[ArgIdx], Info, |
2750 | PartialOrdering, Deduced, HasDeducedAnyParam); |
2751 | Result != TemplateDeductionResult::Success) |
2752 | return Result; |
2753 | |
2754 | ++ArgIdx; |
2755 | ++ParamIdx; |
2756 | continue; |
2757 | } |
2758 | } |
2759 | |
2760 | // The parameter is a pack expansion. |
2761 | |
2762 | // C++0x [temp.deduct.type]p9: |
2763 | // If Pi is a pack expansion, then the pattern of Pi is compared with |
2764 | // each remaining argument in the template argument list of A. Each |
2765 | // comparison deduces template arguments for subsequent positions in the |
2766 | // template parameter packs expanded by Pi. |
2767 | TemplateArgument Pattern = Ps[ParamIdx].getPackExpansionPattern(); |
2768 | |
2769 | // Prepare to deduce the packs within the pattern. |
2770 | PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern); |
2771 | |
2772 | // Keep track of the deduced template arguments for each parameter pack |
2773 | // expanded by this pack expansion (the outer index) and for each |
2774 | // template argument (the inner SmallVectors). |
2775 | for (; hasTemplateArgumentForDeduction(Args&: As, ArgIdx) && |
2776 | PackScope.hasNextElement(); |
2777 | ++ArgIdx) { |
2778 | if (!As[ArgIdx].isPackExpansion()) { |
2779 | if (!FoldPackParameter) |
2780 | return TemplateDeductionResult::MiscellaneousDeductionFailure; |
2781 | if (FoldPackArgument) |
2782 | Info.setStrictPackMatch(); |
2783 | } |
2784 | // Deduce template arguments from the pattern. |
2785 | if (auto Result = DeduceTemplateArguments( |
2786 | S, TemplateParams, P: Pattern, A: As[ArgIdx], Info, PartialOrdering, |
2787 | Deduced, HasDeducedAnyParam); |
2788 | Result != TemplateDeductionResult::Success) |
2789 | return Result; |
2790 | |
2791 | PackScope.nextPackElement(); |
2792 | } |
2793 | |
2794 | // Build argument packs for each of the parameter packs expanded by this |
2795 | // pack expansion. |
2796 | return PackScope.finish(); |
2797 | } |
2798 | } |
2799 | |
2800 | TemplateDeductionResult Sema::DeduceTemplateArguments( |
2801 | TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps, |
2802 | ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info, |
2803 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
2804 | bool NumberOfArgumentsMustMatch) { |
2805 | return ::DeduceTemplateArguments( |
2806 | S&: *this, TemplateParams, Ps, As, Info, Deduced, NumberOfArgumentsMustMatch, |
2807 | /*PartialOrdering=*/false, PackFold: PackFold::ParameterToArgument, |
2808 | /*HasDeducedAnyParam=*/nullptr); |
2809 | } |
2810 | |
2811 | TemplateArgumentLoc |
2812 | Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, |
2813 | QualType NTTPType, SourceLocation Loc, |
2814 | NamedDecl *TemplateParam) { |
2815 | switch (Arg.getKind()) { |
2816 | case TemplateArgument::Null: |
2817 | llvm_unreachable("Can't get a NULL template argument here"); |
2818 | |
2819 | case TemplateArgument::Type: |
2820 | return TemplateArgumentLoc( |
2821 | Arg, Context.getTrivialTypeSourceInfo(T: Arg.getAsType(), Loc)); |
2822 | |
2823 | case TemplateArgument::Declaration: { |
2824 | if (NTTPType.isNull()) |
2825 | NTTPType = Arg.getParamTypeForDecl(); |
2826 | Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, ParamType: NTTPType, Loc, |
2827 | TemplateParam) |
2828 | .getAs<Expr>(); |
2829 | return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E); |
2830 | } |
2831 | |
2832 | case TemplateArgument::NullPtr: { |
2833 | if (NTTPType.isNull()) |
2834 | NTTPType = Arg.getNullPtrType(); |
2835 | Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, ParamType: NTTPType, Loc) |
2836 | .getAs<Expr>(); |
2837 | return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true), |
2838 | E); |
2839 | } |
2840 | |
2841 | case TemplateArgument::Integral: |
2842 | case TemplateArgument::StructuralValue: { |
2843 | Expr *E = BuildExpressionFromNonTypeTemplateArgument(Arg, Loc).get(); |
2844 | return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E); |
2845 | } |
2846 | |
2847 | case TemplateArgument::Template: |
2848 | case TemplateArgument::TemplateExpansion: { |
2849 | NestedNameSpecifierLocBuilder Builder; |
2850 | TemplateName Template = Arg.getAsTemplateOrTemplatePattern(); |
2851 | if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) |
2852 | Builder.MakeTrivial(Context, Qualifier: DTN->getQualifier(), R: Loc); |
2853 | else if (QualifiedTemplateName *QTN = |
2854 | Template.getAsQualifiedTemplateName()) |
2855 | Builder.MakeTrivial(Context, Qualifier: QTN->getQualifier(), R: Loc); |
2856 | |
2857 | if (Arg.getKind() == TemplateArgument::Template) |
2858 | return TemplateArgumentLoc(Context, Arg, |
2859 | Builder.getWithLocInContext(Context), Loc); |
2860 | |
2861 | return TemplateArgumentLoc( |
2862 | Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc); |
2863 | } |
2864 | |
2865 | case TemplateArgument::Expression: |
2866 | return TemplateArgumentLoc(Arg, Arg.getAsExpr()); |
2867 | |
2868 | case TemplateArgument::Pack: |
2869 | return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo()); |
2870 | } |
2871 | |
2872 | llvm_unreachable("Invalid TemplateArgument Kind!"); |
2873 | } |
2874 | |
2875 | TemplateArgumentLoc |
2876 | Sema::getIdentityTemplateArgumentLoc(NamedDecl *TemplateParm, |
2877 | SourceLocation Location) { |
2878 | return getTrivialTemplateArgumentLoc( |
2879 | Arg: Context.getInjectedTemplateArg(ParamDecl: TemplateParm), NTTPType: QualType(), Loc: Location); |
2880 | } |
2881 | |
2882 | /// Convert the given deduced template argument and add it to the set of |
2883 | /// fully-converted template arguments. |
2884 | static bool |
2885 | ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, |
2886 | DeducedTemplateArgument Arg, NamedDecl *Template, |
2887 | TemplateDeductionInfo &Info, bool IsDeduced, |
2888 | Sema::CheckTemplateArgumentInfo &CTAI) { |
2889 | auto ConvertArg = [&](DeducedTemplateArgument Arg, |
2890 | unsigned ArgumentPackIndex) { |
2891 | // Convert the deduced template argument into a template |
2892 | // argument that we can check, almost as if the user had written |
2893 | // the template argument explicitly. |
2894 | TemplateArgumentLoc ArgLoc = S.getTrivialTemplateArgumentLoc( |
2895 | Arg, NTTPType: QualType(), Loc: Info.getLocation(), TemplateParam: Param); |
2896 | |
2897 | SaveAndRestore _1(CTAI.MatchingTTP, false); |
2898 | SaveAndRestore _2(CTAI.StrictPackMatch, false); |
2899 | // Check the template argument, converting it as necessary. |
2900 | auto Res = S.CheckTemplateArgument( |
2901 | Param, ArgLoc, Template, Template->getLocation(), |
2902 | Template->getSourceRange().getEnd(), ArgumentPackIndex, CTAI, |
2903 | IsDeduced |
2904 | ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound |
2905 | : Sema::CTAK_Deduced) |
2906 | : Sema::CTAK_Specified); |
2907 | if (CTAI.StrictPackMatch) |
2908 | Info.setStrictPackMatch(); |
2909 | return Res; |
2910 | }; |
2911 | |
2912 | if (Arg.getKind() == TemplateArgument::Pack) { |
2913 | // This is a template argument pack, so check each of its arguments against |
2914 | // the template parameter. |
2915 | SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder, |
2916 | CanonicalPackedArgsBuilder; |
2917 | for (const auto &P : Arg.pack_elements()) { |
2918 | // When converting the deduced template argument, append it to the |
2919 | // general output list. We need to do this so that the template argument |
2920 | // checking logic has all of the prior template arguments available. |
2921 | DeducedTemplateArgument InnerArg(P); |
2922 | InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound()); |
2923 | assert(InnerArg.getKind() != TemplateArgument::Pack && |
2924 | "deduced nested pack"); |
2925 | if (P.isNull()) { |
2926 | // We deduced arguments for some elements of this pack, but not for |
2927 | // all of them. This happens if we get a conditionally-non-deduced |
2928 | // context in a pack expansion (such as an overload set in one of the |
2929 | // arguments). |
2930 | S.Diag(Param->getLocation(), |
2931 | diag::err_template_arg_deduced_incomplete_pack) |
2932 | << Arg << Param; |
2933 | return true; |
2934 | } |
2935 | if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size())) |
2936 | return true; |
2937 | |
2938 | // Move the converted template argument into our argument pack. |
2939 | SugaredPackedArgsBuilder.push_back(Elt: CTAI.SugaredConverted.pop_back_val()); |
2940 | CanonicalPackedArgsBuilder.push_back( |
2941 | Elt: CTAI.CanonicalConverted.pop_back_val()); |
2942 | } |
2943 | |
2944 | // If the pack is empty, we still need to substitute into the parameter |
2945 | // itself, in case that substitution fails. |
2946 | if (SugaredPackedArgsBuilder.empty()) { |
2947 | LocalInstantiationScope Scope(S); |
2948 | MultiLevelTemplateArgumentList Args(Template, CTAI.SugaredConverted, |
2949 | /*Final=*/true); |
2950 | Sema::ArgPackSubstIndexRAII OnlySubstNonPackExpansion(S, std::nullopt); |
2951 | |
2952 | if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) { |
2953 | Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template, |
2954 | NTTP, CTAI.SugaredConverted, |
2955 | Template->getSourceRange()); |
2956 | if (Inst.isInvalid() || |
2957 | S.SubstType(NTTP->getType(), Args, NTTP->getLocation(), |
2958 | NTTP->getDeclName()).isNull()) |
2959 | return true; |
2960 | } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) { |
2961 | Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template, |
2962 | TTP, CTAI.SugaredConverted, |
2963 | Template->getSourceRange()); |
2964 | if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args)) |
2965 | return true; |
2966 | } |
2967 | // For type parameters, no substitution is ever required. |
2968 | } |
2969 | |
2970 | // Create the resulting argument pack. |
2971 | CTAI.SugaredConverted.push_back( |
2972 | Elt: TemplateArgument::CreatePackCopy(Context&: S.Context, Args: SugaredPackedArgsBuilder)); |
2973 | CTAI.CanonicalConverted.push_back(Elt: TemplateArgument::CreatePackCopy( |
2974 | Context&: S.Context, Args: CanonicalPackedArgsBuilder)); |
2975 | return false; |
2976 | } |
2977 | |
2978 | return ConvertArg(Arg, 0); |
2979 | } |
2980 | |
2981 | /// \param IsIncomplete When used, we only consider template parameters that |
2982 | /// were deduced, disregarding any default arguments. After the function |
2983 | /// finishes, the object pointed at will contain a value indicating if the |
2984 | /// conversion was actually incomplete. |
2985 | static TemplateDeductionResult ConvertDeducedTemplateArguments( |
2986 | Sema &S, NamedDecl *Template, TemplateParameterList *TemplateParams, |
2987 | bool IsDeduced, SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
2988 | TemplateDeductionInfo &Info, Sema::CheckTemplateArgumentInfo &CTAI, |
2989 | LocalInstantiationScope *CurrentInstantiationScope, |
2990 | unsigned NumAlreadyConverted, bool *IsIncomplete) { |
2991 | for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { |
2992 | NamedDecl *Param = TemplateParams->getParam(Idx: I); |
2993 | |
2994 | // C++0x [temp.arg.explicit]p3: |
2995 | // A trailing template parameter pack (14.5.3) not otherwise deduced will |
2996 | // be deduced to an empty sequence of template arguments. |
2997 | // FIXME: Where did the word "trailing" come from? |
2998 | if (Deduced[I].isNull() && Param->isTemplateParameterPack()) { |
2999 | if (auto Result = |
3000 | PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish(); |
3001 | Result != TemplateDeductionResult::Success) |
3002 | return Result; |
3003 | } |
3004 | |
3005 | if (!Deduced[I].isNull()) { |
3006 | if (I < NumAlreadyConverted) { |
3007 | // We may have had explicitly-specified template arguments for a |
3008 | // template parameter pack (that may or may not have been extended |
3009 | // via additional deduced arguments). |
3010 | if (Param->isParameterPack() && CurrentInstantiationScope && |
3011 | CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) { |
3012 | // Forget the partially-substituted pack; its substitution is now |
3013 | // complete. |
3014 | CurrentInstantiationScope->ResetPartiallySubstitutedPack(); |
3015 | // We still need to check the argument in case it was extended by |
3016 | // deduction. |
3017 | } else { |
3018 | // We have already fully type-checked and converted this |
3019 | // argument, because it was explicitly-specified. Just record the |
3020 | // presence of this argument. |
3021 | CTAI.SugaredConverted.push_back(Elt: Deduced[I]); |
3022 | CTAI.CanonicalConverted.push_back( |
3023 | Elt: S.Context.getCanonicalTemplateArgument(Arg: Deduced[I])); |
3024 | continue; |
3025 | } |
3026 | } |
3027 | |
3028 | // We may have deduced this argument, so it still needs to be |
3029 | // checked and converted. |
3030 | if (ConvertDeducedTemplateArgument(S, Param, Arg: Deduced[I], Template, Info, |
3031 | IsDeduced, CTAI)) { |
3032 | Info.Param = makeTemplateParameter(Param); |
3033 | // FIXME: These template arguments are temporary. Free them! |
3034 | Info.reset( |
3035 | NewDeducedSugared: TemplateArgumentList::CreateCopy(Context&: S.Context, Args: CTAI.SugaredConverted), |
3036 | NewDeducedCanonical: TemplateArgumentList::CreateCopy(Context&: S.Context, |
3037 | Args: CTAI.CanonicalConverted)); |
3038 | return TemplateDeductionResult::SubstitutionFailure; |
3039 | } |
3040 | |
3041 | continue; |
3042 | } |
3043 | |
3044 | // [C++26][temp.deduct.partial]p12 - When partial ordering, it's ok for |
3045 | // template parameters to remain not deduced. As a provisional fix for a |
3046 | // core issue that does not exist yet, which may be related to CWG2160, only |
3047 | // consider template parameters that were deduced, disregarding any default |
3048 | // arguments. |
3049 | if (IsIncomplete) { |
3050 | *IsIncomplete = true; |
3051 | CTAI.SugaredConverted.push_back(Elt: {}); |
3052 | CTAI.CanonicalConverted.push_back(Elt: {}); |
3053 | continue; |
3054 | } |
3055 | |
3056 | // Substitute into the default template argument, if available. |
3057 | bool HasDefaultArg = false; |
3058 | TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: Template); |
3059 | if (!TD) { |
3060 | assert(isa<ClassTemplatePartialSpecializationDecl>(Template) || |
3061 | isa<VarTemplatePartialSpecializationDecl>(Template)); |
3062 | return TemplateDeductionResult::Incomplete; |
3063 | } |
3064 | |
3065 | TemplateArgumentLoc DefArg; |
3066 | { |
3067 | Qualifiers ThisTypeQuals; |
3068 | CXXRecordDecl *ThisContext = nullptr; |
3069 | if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext())) |
3070 | if (Rec->isLambda()) |
3071 | if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) { |
3072 | ThisContext = Method->getParent(); |
3073 | ThisTypeQuals = Method->getMethodQualifiers(); |
3074 | } |
3075 | |
3076 | Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals, |
3077 | S.getLangOpts().CPlusPlus17); |
3078 | |
3079 | DefArg = S.SubstDefaultTemplateArgumentIfAvailable( |
3080 | Template: TD, TemplateLoc: TD->getLocation(), RAngleLoc: TD->getSourceRange().getEnd(), Param, |
3081 | SugaredConverted: CTAI.SugaredConverted, CanonicalConverted: CTAI.CanonicalConverted, HasDefaultArg); |
3082 | } |
3083 | |
3084 | // If there was no default argument, deduction is incomplete. |
3085 | if (DefArg.getArgument().isNull()) { |
3086 | Info.Param = makeTemplateParameter( |
3087 | const_cast<NamedDecl *>(TemplateParams->getParam(Idx: I))); |
3088 | Info.reset( |
3089 | NewDeducedSugared: TemplateArgumentList::CreateCopy(Context&: S.Context, Args: CTAI.SugaredConverted), |
3090 | NewDeducedCanonical: TemplateArgumentList::CreateCopy(Context&: S.Context, Args: CTAI.CanonicalConverted)); |
3091 | |
3092 | return HasDefaultArg ? TemplateDeductionResult::SubstitutionFailure |
3093 | : TemplateDeductionResult::Incomplete; |
3094 | } |
3095 | |
3096 | SaveAndRestore _1(CTAI.PartialOrdering, false); |
3097 | SaveAndRestore _2(CTAI.MatchingTTP, false); |
3098 | SaveAndRestore _3(CTAI.StrictPackMatch, false); |
3099 | // Check whether we can actually use the default argument. |
3100 | if (S.CheckTemplateArgument( |
3101 | Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(), |
3102 | /*ArgumentPackIndex=*/0, CTAI, Sema::CTAK_Specified)) { |
3103 | Info.Param = makeTemplateParameter( |
3104 | const_cast<NamedDecl *>(TemplateParams->getParam(Idx: I))); |
3105 | // FIXME: These template arguments are temporary. Free them! |
3106 | Info.reset( |
3107 | NewDeducedSugared: TemplateArgumentList::CreateCopy(Context&: S.Context, Args: CTAI.SugaredConverted), |
3108 | NewDeducedCanonical: TemplateArgumentList::CreateCopy(Context&: S.Context, Args: CTAI.CanonicalConverted)); |
3109 | return TemplateDeductionResult::SubstitutionFailure; |
3110 | } |
3111 | |
3112 | // If we get here, we successfully used the default template argument. |
3113 | } |
3114 | |
3115 | return TemplateDeductionResult::Success; |
3116 | } |
3117 | |
3118 | static DeclContext *getAsDeclContextOrEnclosing(Decl *D) { |
3119 | if (auto *DC = dyn_cast<DeclContext>(Val: D)) |
3120 | return DC; |
3121 | return D->getDeclContext(); |
3122 | } |
3123 | |
3124 | template<typename T> struct IsPartialSpecialization { |
3125 | static constexpr bool value = false; |
3126 | }; |
3127 | template<> |
3128 | struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> { |
3129 | static constexpr bool value = true; |
3130 | }; |
3131 | template<> |
3132 | struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> { |
3133 | static constexpr bool value = true; |
3134 | }; |
3135 | |
3136 | static TemplateDeductionResult |
3137 | CheckDeducedArgumentConstraints(Sema &S, NamedDecl *Template, |
3138 | ArrayRef<TemplateArgument> SugaredDeducedArgs, |
3139 | ArrayRef<TemplateArgument> CanonicalDeducedArgs, |
3140 | TemplateDeductionInfo &Info) { |
3141 | llvm::SmallVector<AssociatedConstraint, 3> AssociatedConstraints; |
3142 | bool DeducedArgsNeedReplacement = false; |
3143 | if (auto *TD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Template)) { |
3144 | TD->getAssociatedConstraints(AC&: AssociatedConstraints); |
3145 | DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization(); |
3146 | } else if (auto *TD = |
3147 | dyn_cast<VarTemplatePartialSpecializationDecl>(Val: Template)) { |
3148 | TD->getAssociatedConstraints(AC&: AssociatedConstraints); |
3149 | DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization(); |
3150 | } else { |
3151 | cast<TemplateDecl>(Val: Template)->getAssociatedConstraints( |
3152 | AC&: AssociatedConstraints); |
3153 | } |
3154 | |
3155 | std::optional<ArrayRef<TemplateArgument>> Innermost; |
3156 | // If we don't need to replace the deduced template arguments, |
3157 | // we can add them immediately as the inner-most argument list. |
3158 | if (!DeducedArgsNeedReplacement) |
3159 | Innermost = CanonicalDeducedArgs; |
3160 | |
3161 | MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs( |
3162 | Template, Template->getDeclContext(), /*Final=*/false, Innermost, |
3163 | /*RelativeToPrimary=*/true, /*Pattern=*/ |
3164 | nullptr, /*ForConstraintInstantiation=*/true); |
3165 | |
3166 | // getTemplateInstantiationArgs picks up the non-deduced version of the |
3167 | // template args when this is a variable template partial specialization and |
3168 | // not class-scope explicit specialization, so replace with Deduced Args |
3169 | // instead of adding to inner-most. |
3170 | if (!Innermost) |
3171 | MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs); |
3172 | |
3173 | if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, TemplateArgLists: MLTAL, |
3174 | TemplateIDRange: Info.getLocation(), |
3175 | Satisfaction&: Info.AssociatedConstraintsSatisfaction) || |
3176 | !Info.AssociatedConstraintsSatisfaction.IsSatisfied) { |
3177 | Info.reset( |
3178 | NewDeducedSugared: TemplateArgumentList::CreateCopy(Context&: S.Context, Args: SugaredDeducedArgs), |
3179 | NewDeducedCanonical: TemplateArgumentList::CreateCopy(Context&: S.Context, Args: CanonicalDeducedArgs)); |
3180 | return TemplateDeductionResult::ConstraintsNotSatisfied; |
3181 | } |
3182 | return TemplateDeductionResult::Success; |
3183 | } |
3184 | |
3185 | /// Complete template argument deduction. |
3186 | static TemplateDeductionResult FinishTemplateArgumentDeduction( |
3187 | Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL, |
3188 | TemplateDecl *Template, bool PartialOrdering, |
3189 | ArrayRef<TemplateArgumentLoc> Ps, ArrayRef<TemplateArgument> As, |
3190 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
3191 | TemplateDeductionInfo &Info, bool CopyDeducedArgs) { |
3192 | // Unevaluated SFINAE context. |
3193 | EnterExpressionEvaluationContext Unevaluated( |
3194 | S, Sema::ExpressionEvaluationContext::Unevaluated); |
3195 | |
3196 | Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Entity)); |
3197 | |
3198 | // C++ [temp.deduct.type]p2: |
3199 | // [...] or if any template argument remains neither deduced nor |
3200 | // explicitly specified, template argument deduction fails. |
3201 | Sema::CheckTemplateArgumentInfo CTAI(PartialOrdering); |
3202 | if (auto Result = ConvertDeducedTemplateArguments( |
3203 | S, Template: Entity, TemplateParams: EntityTPL, /*IsDeduced=*/PartialOrdering, Deduced, Info, |
3204 | CTAI, |
3205 | /*CurrentInstantiationScope=*/nullptr, |
3206 | /*NumAlreadyConverted=*/0U, /*IsIncomplete=*/nullptr); |
3207 | Result != TemplateDeductionResult::Success) |
3208 | return Result; |
3209 | |
3210 | if (CopyDeducedArgs) { |
3211 | // Form the template argument list from the deduced template arguments. |
3212 | TemplateArgumentList *SugaredDeducedArgumentList = |
3213 | TemplateArgumentList::CreateCopy(Context&: S.Context, Args: CTAI.SugaredConverted); |
3214 | TemplateArgumentList *CanonicalDeducedArgumentList = |
3215 | TemplateArgumentList::CreateCopy(Context&: S.Context, Args: CTAI.CanonicalConverted); |
3216 | Info.reset(NewDeducedSugared: SugaredDeducedArgumentList, NewDeducedCanonical: CanonicalDeducedArgumentList); |
3217 | } |
3218 | |
3219 | TemplateParameterList *TPL = Template->getTemplateParameters(); |
3220 | TemplateArgumentListInfo InstArgs(TPL->getLAngleLoc(), TPL->getRAngleLoc()); |
3221 | MultiLevelTemplateArgumentList MLTAL(Entity, CTAI.SugaredConverted, |
3222 | /*Final=*/true); |
3223 | MLTAL.addOuterRetainedLevels(Num: TPL->getDepth()); |
3224 | |
3225 | if (S.SubstTemplateArguments(Args: Ps, TemplateArgs: MLTAL, Outputs&: InstArgs)) { |
3226 | unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx; |
3227 | if (ParamIdx >= TPL->size()) |
3228 | ParamIdx = TPL->size() - 1; |
3229 | |
3230 | Decl *Param = const_cast<NamedDecl *>(TPL->getParam(Idx: ParamIdx)); |
3231 | Info.Param = makeTemplateParameter(D: Param); |
3232 | Info.FirstArg = Ps[ArgIdx].getArgument(); |
3233 | return TemplateDeductionResult::SubstitutionFailure; |
3234 | } |
3235 | |
3236 | bool ConstraintsNotSatisfied; |
3237 | Sema::CheckTemplateArgumentInfo InstCTAI; |
3238 | if (S.CheckTemplateArgumentList(Template, TemplateLoc: Template->getLocation(), TemplateArgs&: InstArgs, |
3239 | /*DefaultArgs=*/{}, PartialTemplateArgs: false, CTAI&: InstCTAI, |
3240 | /*UpdateArgsWithConversions=*/true, |
3241 | ConstraintsNotSatisfied: &ConstraintsNotSatisfied)) |
3242 | return ConstraintsNotSatisfied |
3243 | ? TemplateDeductionResult::ConstraintsNotSatisfied |
3244 | : TemplateDeductionResult::SubstitutionFailure; |
3245 | |
3246 | // Check that we produced the correct argument list. |
3247 | SmallVector<ArrayRef<TemplateArgument>, 4> PsStack{InstCTAI.SugaredConverted}, |
3248 | AsStack{As}; |
3249 | for (;;) { |
3250 | auto take = [](SmallVectorImpl<ArrayRef<TemplateArgument>> &Stack) |
3251 | -> std::tuple<ArrayRef<TemplateArgument> &, TemplateArgument> { |
3252 | while (!Stack.empty()) { |
3253 | auto &Xs = Stack.back(); |
3254 | if (Xs.empty()) { |
3255 | Stack.pop_back(); |
3256 | continue; |
3257 | } |
3258 | auto &X = Xs.front(); |
3259 | if (X.getKind() == TemplateArgument::Pack) { |
3260 | Stack.emplace_back(Args: X.getPackAsArray()); |
3261 | Xs = Xs.drop_front(); |
3262 | continue; |
3263 | } |
3264 | assert(!X.isNull()); |
3265 | return {Xs, X}; |
3266 | } |
3267 | static constexpr ArrayRef<TemplateArgument> None; |
3268 | return {const_cast<ArrayRef<TemplateArgument> &>(None), |
3269 | TemplateArgument()}; |
3270 | }; |
3271 | auto [Ps, P] = take(PsStack); |
3272 | auto [As, A] = take(AsStack); |
3273 | if (P.isNull() && A.isNull()) |
3274 | break; |
3275 | TemplateArgument PP = P.isPackExpansion() ? P.getPackExpansionPattern() : P, |
3276 | PA = A.isPackExpansion() ? A.getPackExpansionPattern() : A; |
3277 | if (!S.Context.isSameTemplateArgument(Arg1: PP, Arg2: PA)) { |
3278 | if (!P.isPackExpansion() && !A.isPackExpansion()) { |
3279 | Info.Param = makeTemplateParameter(TPL->getParam( |
3280 | Idx: (AsStack.empty() ? As.end() : AsStack.back().begin()) - |
3281 | As.begin())); |
3282 | Info.FirstArg = P; |
3283 | Info.SecondArg = A; |
3284 | return TemplateDeductionResult::NonDeducedMismatch; |
3285 | } |
3286 | if (P.isPackExpansion()) { |
3287 | Ps = Ps.drop_front(); |
3288 | continue; |
3289 | } |
3290 | if (A.isPackExpansion()) { |
3291 | As = As.drop_front(); |
3292 | continue; |
3293 | } |
3294 | } |
3295 | Ps = Ps.drop_front(N: P.isPackExpansion() ? 0 : 1); |
3296 | As = As.drop_front(N: A.isPackExpansion() && !P.isPackExpansion() ? 0 : 1); |
3297 | } |
3298 | assert(PsStack.empty()); |
3299 | assert(AsStack.empty()); |
3300 | |
3301 | if (!PartialOrdering) { |
3302 | if (auto Result = CheckDeducedArgumentConstraints( |
3303 | S, Template: Entity, SugaredDeducedArgs: CTAI.SugaredConverted, CanonicalDeducedArgs: CTAI.CanonicalConverted, Info); |
3304 | Result != TemplateDeductionResult::Success) |
3305 | return Result; |
3306 | } |
3307 | |
3308 | return TemplateDeductionResult::Success; |
3309 | } |
3310 | static TemplateDeductionResult FinishTemplateArgumentDeduction( |
3311 | Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL, |
3312 | TemplateDecl *Template, bool PartialOrdering, ArrayRef<TemplateArgument> Ps, |
3313 | ArrayRef<TemplateArgument> As, |
3314 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
3315 | TemplateDeductionInfo &Info, bool CopyDeducedArgs) { |
3316 | TemplateParameterList *TPL = Template->getTemplateParameters(); |
3317 | SmallVector<TemplateArgumentLoc, 8> PsLoc(Ps.size()); |
3318 | for (unsigned I = 0, N = Ps.size(); I != N; ++I) |
3319 | PsLoc[I] = S.getTrivialTemplateArgumentLoc(Arg: Ps[I], NTTPType: QualType(), |
3320 | Loc: TPL->getParam(Idx: I)->getLocation()); |
3321 | return FinishTemplateArgumentDeduction(S, Entity, EntityTPL, Template, |
3322 | PartialOrdering, Ps: PsLoc, As, Deduced, |
3323 | Info, CopyDeducedArgs); |
3324 | } |
3325 | |
3326 | /// Complete template argument deduction for DeduceTemplateArgumentsFromType. |
3327 | /// FIXME: this is mostly duplicated with the above two versions. Deduplicate |
3328 | /// the three implementations. |
3329 | static TemplateDeductionResult FinishTemplateArgumentDeduction( |
3330 | Sema &S, TemplateDecl *TD, |
3331 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
3332 | TemplateDeductionInfo &Info) { |
3333 | // Unevaluated SFINAE context. |
3334 | EnterExpressionEvaluationContext Unevaluated( |
3335 | S, Sema::ExpressionEvaluationContext::Unevaluated); |
3336 | |
3337 | Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(TD)); |
3338 | |
3339 | // C++ [temp.deduct.type]p2: |
3340 | // [...] or if any template argument remains neither deduced nor |
3341 | // explicitly specified, template argument deduction fails. |
3342 | Sema::CheckTemplateArgumentInfo CTAI; |
3343 | if (auto Result = ConvertDeducedTemplateArguments( |
3344 | S, TD, TD->getTemplateParameters(), /*IsDeduced=*/false, Deduced, |
3345 | Info, CTAI, |
3346 | /*CurrentInstantiationScope=*/nullptr, /*NumAlreadyConverted=*/0, |
3347 | /*IsIncomplete=*/nullptr); |
3348 | Result != TemplateDeductionResult::Success) |
3349 | return Result; |
3350 | |
3351 | return ::CheckDeducedArgumentConstraints(S, TD, CTAI.SugaredConverted, |
3352 | CTAI.CanonicalConverted, Info); |
3353 | } |
3354 | |
3355 | /// Perform template argument deduction to determine whether the given template |
3356 | /// arguments match the given class or variable template partial specialization |
3357 | /// per C++ [temp.class.spec.match]. |
3358 | template <typename T> |
3359 | static std::enable_if_t<IsPartialSpecialization<T>::value, |
3360 | TemplateDeductionResult> |
3361 | DeduceTemplateArguments(Sema &S, T *Partial, |
3362 | ArrayRef<TemplateArgument> TemplateArgs, |
3363 | TemplateDeductionInfo &Info) { |
3364 | if (Partial->isInvalidDecl()) |
3365 | return TemplateDeductionResult::Invalid; |
3366 | |
3367 | // C++ [temp.class.spec.match]p2: |
3368 | // A partial specialization matches a given actual template |
3369 | // argument list if the template arguments of the partial |
3370 | // specialization can be deduced from the actual template argument |
3371 | // list (14.8.2). |
3372 | |
3373 | // Unevaluated SFINAE context. |
3374 | EnterExpressionEvaluationContext Unevaluated( |
3375 | S, Sema::ExpressionEvaluationContext::Unevaluated); |
3376 | Sema::SFINAETrap Trap(S); |
3377 | |
3378 | // This deduction has no relation to any outer instantiation we might be |
3379 | // performing. |
3380 | LocalInstantiationScope InstantiationScope(S); |
3381 | |
3382 | SmallVector<DeducedTemplateArgument, 4> Deduced; |
3383 | Deduced.resize(Partial->getTemplateParameters()->size()); |
3384 | if (TemplateDeductionResult Result = ::DeduceTemplateArguments( |
3385 | S, Partial->getTemplateParameters(), |
3386 | Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced, |
3387 | /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/false, |
3388 | PackFold::ParameterToArgument, |
3389 | /*HasDeducedAnyParam=*/nullptr); |
3390 | Result != TemplateDeductionResult::Success) |
3391 | return Result; |
3392 | |
3393 | SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); |
3394 | Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs, |
3395 | Info); |
3396 | if (Inst.isInvalid()) |
3397 | return TemplateDeductionResult::InstantiationDepth; |
3398 | |
3399 | TemplateDeductionResult Result; |
3400 | S.runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] { |
3401 | Result = ::FinishTemplateArgumentDeduction( |
3402 | S, Partial, Partial->getTemplateParameters(), |
3403 | Partial->getSpecializedTemplate(), |
3404 | /*IsPartialOrdering=*/false, |
3405 | Partial->getTemplateArgsAsWritten()->arguments(), TemplateArgs, Deduced, |
3406 | Info, /*CopyDeducedArgs=*/true); |
3407 | }); |
3408 | |
3409 | if (Result != TemplateDeductionResult::Success) |
3410 | return Result; |
3411 | |
3412 | if (Trap.hasErrorOccurred()) |
3413 | return TemplateDeductionResult::SubstitutionFailure; |
3414 | |
3415 | return TemplateDeductionResult::Success; |
3416 | } |
3417 | |
3418 | TemplateDeductionResult |
3419 | Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, |
3420 | ArrayRef<TemplateArgument> TemplateArgs, |
3421 | TemplateDeductionInfo &Info) { |
3422 | return ::DeduceTemplateArguments(S&: *this, Partial, TemplateArgs, Info); |
3423 | } |
3424 | TemplateDeductionResult |
3425 | Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, |
3426 | ArrayRef<TemplateArgument> TemplateArgs, |
3427 | TemplateDeductionInfo &Info) { |
3428 | return ::DeduceTemplateArguments(S&: *this, Partial, TemplateArgs, Info); |
3429 | } |
3430 | |
3431 | TemplateDeductionResult |
3432 | Sema::DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType, |
3433 | sema::TemplateDeductionInfo &Info) { |
3434 | if (TD->isInvalidDecl()) |
3435 | return TemplateDeductionResult::Invalid; |
3436 | |
3437 | QualType PType; |
3438 | if (const auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) { |
3439 | // Use the InjectedClassNameType. |
3440 | PType = Context.getTypeDeclType(CTD->getTemplatedDecl()); |
3441 | } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Val: TD)) { |
3442 | PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType(); |
3443 | } else { |
3444 | assert(false && "Expected a class or alias template"); |
3445 | } |
3446 | |
3447 | // Unevaluated SFINAE context. |
3448 | EnterExpressionEvaluationContext Unevaluated( |
3449 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
3450 | SFINAETrap Trap(*this); |
3451 | |
3452 | // This deduction has no relation to any outer instantiation we might be |
3453 | // performing. |
3454 | LocalInstantiationScope InstantiationScope(*this); |
3455 | |
3456 | SmallVector<DeducedTemplateArgument> Deduced( |
3457 | TD->getTemplateParameters()->size()); |
3458 | SmallVector<TemplateArgument> PArgs = {TemplateArgument(PType)}; |
3459 | SmallVector<TemplateArgument> AArgs = {TemplateArgument(FromType)}; |
3460 | if (auto DeducedResult = DeduceTemplateArguments( |
3461 | TemplateParams: TD->getTemplateParameters(), Ps: PArgs, As: AArgs, Info, Deduced, NumberOfArgumentsMustMatch: false); |
3462 | DeducedResult != TemplateDeductionResult::Success) { |
3463 | return DeducedResult; |
3464 | } |
3465 | |
3466 | SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); |
3467 | InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info); |
3468 | if (Inst.isInvalid()) |
3469 | return TemplateDeductionResult::InstantiationDepth; |
3470 | |
3471 | TemplateDeductionResult Result; |
3472 | runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] { |
3473 | Result = ::FinishTemplateArgumentDeduction(S&: *this, TD, Deduced, Info); |
3474 | }); |
3475 | |
3476 | if (Result != TemplateDeductionResult::Success) |
3477 | return Result; |
3478 | |
3479 | if (Trap.hasErrorOccurred()) |
3480 | return TemplateDeductionResult::SubstitutionFailure; |
3481 | |
3482 | return TemplateDeductionResult::Success; |
3483 | } |
3484 | |
3485 | /// Determine whether the given type T is a simple-template-id type. |
3486 | static bool isSimpleTemplateIdType(QualType T) { |
3487 | if (const TemplateSpecializationType *Spec |
3488 | = T->getAs<TemplateSpecializationType>()) |
3489 | return Spec->getTemplateName().getAsTemplateDecl() != nullptr; |
3490 | |
3491 | // C++17 [temp.local]p2: |
3492 | // the injected-class-name [...] is equivalent to the template-name followed |
3493 | // by the template-arguments of the class template specialization or partial |
3494 | // specialization enclosed in <> |
3495 | // ... which means it's equivalent to a simple-template-id. |
3496 | // |
3497 | // This only arises during class template argument deduction for a copy |
3498 | // deduction candidate, where it permits slicing. |
3499 | if (T->getAs<InjectedClassNameType>()) |
3500 | return true; |
3501 | |
3502 | return false; |
3503 | } |
3504 | |
3505 | TemplateDeductionResult Sema::SubstituteExplicitTemplateArguments( |
3506 | FunctionTemplateDecl *FunctionTemplate, |
3507 | TemplateArgumentListInfo &ExplicitTemplateArgs, |
3508 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
3509 | SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, |
3510 | TemplateDeductionInfo &Info) { |
3511 | FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); |
3512 | TemplateParameterList *TemplateParams |
3513 | = FunctionTemplate->getTemplateParameters(); |
3514 | |
3515 | if (ExplicitTemplateArgs.size() == 0) { |
3516 | // No arguments to substitute; just copy over the parameter types and |
3517 | // fill in the function type. |
3518 | for (auto *P : Function->parameters()) |
3519 | ParamTypes.push_back(Elt: P->getType()); |
3520 | |
3521 | if (FunctionType) |
3522 | *FunctionType = Function->getType(); |
3523 | return TemplateDeductionResult::Success; |
3524 | } |
3525 | |
3526 | // Unevaluated SFINAE context. |
3527 | EnterExpressionEvaluationContext Unevaluated( |
3528 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
3529 | SFINAETrap Trap(*this); |
3530 | |
3531 | // C++ [temp.arg.explicit]p3: |
3532 | // Template arguments that are present shall be specified in the |
3533 | // declaration order of their corresponding template-parameters. The |
3534 | // template argument list shall not specify more template-arguments than |
3535 | // there are corresponding template-parameters. |
3536 | |
3537 | // Enter a new template instantiation context where we check the |
3538 | // explicitly-specified template arguments against this function template, |
3539 | // and then substitute them into the function parameter types. |
3540 | SmallVector<TemplateArgument, 4> DeducedArgs; |
3541 | InstantiatingTemplate Inst( |
3542 | *this, Info.getLocation(), FunctionTemplate, DeducedArgs, |
3543 | CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info); |
3544 | if (Inst.isInvalid()) |
3545 | return TemplateDeductionResult::InstantiationDepth; |
3546 | |
3547 | CheckTemplateArgumentInfo CTAI; |
3548 | if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(), |
3549 | ExplicitTemplateArgs, /*DefaultArgs=*/{}, |
3550 | /*PartialTemplateArgs=*/true, CTAI, |
3551 | /*UpdateArgsWithConversions=*/false) || |
3552 | Trap.hasErrorOccurred()) { |
3553 | unsigned Index = CTAI.SugaredConverted.size(); |
3554 | if (Index >= TemplateParams->size()) |
3555 | return TemplateDeductionResult::SubstitutionFailure; |
3556 | Info.Param = makeTemplateParameter(TemplateParams->getParam(Idx: Index)); |
3557 | return TemplateDeductionResult::InvalidExplicitArguments; |
3558 | } |
3559 | |
3560 | // Form the template argument list from the explicitly-specified |
3561 | // template arguments. |
3562 | TemplateArgumentList *SugaredExplicitArgumentList = |
3563 | TemplateArgumentList::CreateCopy(Context, Args: CTAI.SugaredConverted); |
3564 | TemplateArgumentList *CanonicalExplicitArgumentList = |
3565 | TemplateArgumentList::CreateCopy(Context, Args: CTAI.CanonicalConverted); |
3566 | Info.setExplicitArgs(NewDeducedSugared: SugaredExplicitArgumentList, |
3567 | NewDeducedCanonical: CanonicalExplicitArgumentList); |
3568 | |
3569 | // Template argument deduction and the final substitution should be |
3570 | // done in the context of the templated declaration. Explicit |
3571 | // argument substitution, on the other hand, needs to happen in the |
3572 | // calling context. |
3573 | ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); |
3574 | |
3575 | // If we deduced template arguments for a template parameter pack, |
3576 | // note that the template argument pack is partially substituted and record |
3577 | // the explicit template arguments. They'll be used as part of deduction |
3578 | // for this template parameter pack. |
3579 | unsigned PartiallySubstitutedPackIndex = -1u; |
3580 | if (!CTAI.SugaredConverted.empty()) { |
3581 | const TemplateArgument &Arg = CTAI.SugaredConverted.back(); |
3582 | if (Arg.getKind() == TemplateArgument::Pack) { |
3583 | auto *Param = TemplateParams->getParam(Idx: CTAI.SugaredConverted.size() - 1); |
3584 | // If this is a fully-saturated fixed-size pack, it should be |
3585 | // fully-substituted, not partially-substituted. |
3586 | UnsignedOrNone Expansions = getExpandedPackSize(Param); |
3587 | if (!Expansions || Arg.pack_size() < *Expansions) { |
3588 | PartiallySubstitutedPackIndex = CTAI.SugaredConverted.size() - 1; |
3589 | CurrentInstantiationScope->SetPartiallySubstitutedPack( |
3590 | Pack: Param, ExplicitArgs: Arg.pack_begin(), NumExplicitArgs: Arg.pack_size()); |
3591 | } |
3592 | } |
3593 | } |
3594 | |
3595 | const FunctionProtoType *Proto |
3596 | = Function->getType()->getAs<FunctionProtoType>(); |
3597 | assert(Proto && "Function template does not have a prototype?"); |
3598 | |
3599 | // Isolate our substituted parameters from our caller. |
3600 | LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true); |
3601 | |
3602 | ExtParameterInfoBuilder ExtParamInfos; |
3603 | |
3604 | MultiLevelTemplateArgumentList MLTAL(FunctionTemplate, |
3605 | SugaredExplicitArgumentList->asArray(), |
3606 | /*Final=*/true); |
3607 | |
3608 | // Instantiate the types of each of the function parameters given the |
3609 | // explicitly-specified template arguments. If the function has a trailing |
3610 | // return type, substitute it after the arguments to ensure we substitute |
3611 | // in lexical order. |
3612 | if (Proto->hasTrailingReturn()) { |
3613 | if (SubstParmTypes(Loc: Function->getLocation(), Params: Function->parameters(), |
3614 | ExtParamInfos: Proto->getExtParameterInfosOrNull(), TemplateArgs: MLTAL, ParamTypes, |
3615 | /*params=*/OutParams: nullptr, ParamInfos&: ExtParamInfos)) |
3616 | return TemplateDeductionResult::SubstitutionFailure; |
3617 | } |
3618 | |
3619 | // Instantiate the return type. |
3620 | QualType ResultType; |
3621 | { |
3622 | // C++11 [expr.prim.general]p3: |
3623 | // If a declaration declares a member function or member function |
3624 | // template of a class X, the expression this is a prvalue of type |
3625 | // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq |
3626 | // and the end of the function-definition, member-declarator, or |
3627 | // declarator. |
3628 | Qualifiers ThisTypeQuals; |
3629 | CXXRecordDecl *ThisContext = nullptr; |
3630 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) { |
3631 | ThisContext = Method->getParent(); |
3632 | ThisTypeQuals = Method->getMethodQualifiers(); |
3633 | } |
3634 | |
3635 | CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals, |
3636 | getLangOpts().CPlusPlus11); |
3637 | |
3638 | ResultType = |
3639 | SubstType(Proto->getReturnType(), MLTAL, |
3640 | Function->getTypeSpecStartLoc(), Function->getDeclName()); |
3641 | if (ResultType.isNull() || Trap.hasErrorOccurred()) |
3642 | return TemplateDeductionResult::SubstitutionFailure; |
3643 | // CUDA: Kernel function must have 'void' return type. |
3644 | if (getLangOpts().CUDA) |
3645 | if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) { |
3646 | Diag(Function->getLocation(), diag::err_kern_type_not_void_return) |
3647 | << Function->getType() << Function->getSourceRange(); |
3648 | return TemplateDeductionResult::SubstitutionFailure; |
3649 | } |
3650 | } |
3651 | |
3652 | // Instantiate the types of each of the function parameters given the |
3653 | // explicitly-specified template arguments if we didn't do so earlier. |
3654 | if (!Proto->hasTrailingReturn() && |
3655 | SubstParmTypes(Loc: Function->getLocation(), Params: Function->parameters(), |
3656 | ExtParamInfos: Proto->getExtParameterInfosOrNull(), TemplateArgs: MLTAL, ParamTypes, |
3657 | /*params*/ OutParams: nullptr, ParamInfos&: ExtParamInfos)) |
3658 | return TemplateDeductionResult::SubstitutionFailure; |
3659 | |
3660 | if (FunctionType) { |
3661 | auto EPI = Proto->getExtProtoInfo(); |
3662 | EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(numParams: ParamTypes.size()); |
3663 | *FunctionType = BuildFunctionType(T: ResultType, ParamTypes, |
3664 | Loc: Function->getLocation(), |
3665 | Entity: Function->getDeclName(), |
3666 | EPI: EPI); |
3667 | if (FunctionType->isNull() || Trap.hasErrorOccurred()) |
3668 | return TemplateDeductionResult::SubstitutionFailure; |
3669 | } |
3670 | |
3671 | // C++ [temp.arg.explicit]p2: |
3672 | // Trailing template arguments that can be deduced (14.8.2) may be |
3673 | // omitted from the list of explicit template-arguments. If all of the |
3674 | // template arguments can be deduced, they may all be omitted; in this |
3675 | // case, the empty template argument list <> itself may also be omitted. |
3676 | // |
3677 | // Take all of the explicitly-specified arguments and put them into |
3678 | // the set of deduced template arguments. The partially-substituted |
3679 | // parameter pack, however, will be set to NULL since the deduction |
3680 | // mechanism handles the partially-substituted argument pack directly. |
3681 | Deduced.reserve(N: TemplateParams->size()); |
3682 | for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) { |
3683 | const TemplateArgument &Arg = SugaredExplicitArgumentList->get(Idx: I); |
3684 | if (I == PartiallySubstitutedPackIndex) |
3685 | Deduced.push_back(Elt: DeducedTemplateArgument()); |
3686 | else |
3687 | Deduced.push_back(Elt: Arg); |
3688 | } |
3689 | |
3690 | return TemplateDeductionResult::Success; |
3691 | } |
3692 | |
3693 | /// Check whether the deduced argument type for a call to a function |
3694 | /// template matches the actual argument type per C++ [temp.deduct.call]p4. |
3695 | static TemplateDeductionResult |
3696 | CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info, |
3697 | Sema::OriginalCallArg OriginalArg, |
3698 | QualType DeducedA) { |
3699 | ASTContext &Context = S.Context; |
3700 | |
3701 | auto Failed = [&]() -> TemplateDeductionResult { |
3702 | Info.FirstArg = TemplateArgument(DeducedA); |
3703 | Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType); |
3704 | Info.CallArgIndex = OriginalArg.ArgIdx; |
3705 | return OriginalArg.DecomposedParam |
3706 | ? TemplateDeductionResult::DeducedMismatchNested |
3707 | : TemplateDeductionResult::DeducedMismatch; |
3708 | }; |
3709 | |
3710 | QualType A = OriginalArg.OriginalArgType; |
3711 | QualType OriginalParamType = OriginalArg.OriginalParamType; |
3712 | |
3713 | // Check for type equality (top-level cv-qualifiers are ignored). |
3714 | if (Context.hasSameUnqualifiedType(T1: A, T2: DeducedA)) |
3715 | return TemplateDeductionResult::Success; |
3716 | |
3717 | // Strip off references on the argument types; they aren't needed for |
3718 | // the following checks. |
3719 | if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>()) |
3720 | DeducedA = DeducedARef->getPointeeType(); |
3721 | if (const ReferenceType *ARef = A->getAs<ReferenceType>()) |
3722 | A = ARef->getPointeeType(); |
3723 | |
3724 | // C++ [temp.deduct.call]p4: |
3725 | // [...] However, there are three cases that allow a difference: |
3726 | // - If the original P is a reference type, the deduced A (i.e., the |
3727 | // type referred to by the reference) can be more cv-qualified than |
3728 | // the transformed A. |
3729 | if (const ReferenceType *OriginalParamRef |
3730 | = OriginalParamType->getAs<ReferenceType>()) { |
3731 | // We don't want to keep the reference around any more. |
3732 | OriginalParamType = OriginalParamRef->getPointeeType(); |
3733 | |
3734 | // FIXME: Resolve core issue (no number yet): if the original P is a |
3735 | // reference type and the transformed A is function type "noexcept F", |
3736 | // the deduced A can be F. |
3737 | if (A->isFunctionType() && S.IsFunctionConversion(FromType: A, ToType: DeducedA)) |
3738 | return TemplateDeductionResult::Success; |
3739 | |
3740 | Qualifiers AQuals = A.getQualifiers(); |
3741 | Qualifiers DeducedAQuals = DeducedA.getQualifiers(); |
3742 | |
3743 | // Under Objective-C++ ARC, the deduced type may have implicitly |
3744 | // been given strong or (when dealing with a const reference) |
3745 | // unsafe_unretained lifetime. If so, update the original |
3746 | // qualifiers to include this lifetime. |
3747 | if (S.getLangOpts().ObjCAutoRefCount && |
3748 | ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong && |
3749 | AQuals.getObjCLifetime() == Qualifiers::OCL_None) || |
3750 | (DeducedAQuals.hasConst() && |
3751 | DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) { |
3752 | AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime()); |
3753 | } |
3754 | |
3755 | if (AQuals == DeducedAQuals) { |
3756 | // Qualifiers match; there's nothing to do. |
3757 | } else if (!DeducedAQuals.compatiblyIncludes(other: AQuals, Ctx: S.getASTContext())) { |
3758 | return Failed(); |
3759 | } else { |
3760 | // Qualifiers are compatible, so have the argument type adopt the |
3761 | // deduced argument type's qualifiers as if we had performed the |
3762 | // qualification conversion. |
3763 | A = Context.getQualifiedType(T: A.getUnqualifiedType(), Qs: DeducedAQuals); |
3764 | } |
3765 | } |
3766 | |
3767 | // - The transformed A can be another pointer or pointer to member |
3768 | // type that can be converted to the deduced A via a function pointer |
3769 | // conversion and/or a qualification conversion. |
3770 | // |
3771 | // Also allow conversions which merely strip __attribute__((noreturn)) from |
3772 | // function types (recursively). |
3773 | bool ObjCLifetimeConversion = false; |
3774 | if ((A->isAnyPointerType() || A->isMemberPointerType()) && |
3775 | (S.IsQualificationConversion(FromType: A, ToType: DeducedA, CStyle: false, |
3776 | ObjCLifetimeConversion) || |
3777 | S.IsFunctionConversion(FromType: A, ToType: DeducedA))) |
3778 | return TemplateDeductionResult::Success; |
3779 | |
3780 | // - If P is a class and P has the form simple-template-id, then the |
3781 | // transformed A can be a derived class of the deduced A. [...] |
3782 | // [...] Likewise, if P is a pointer to a class of the form |
3783 | // simple-template-id, the transformed A can be a pointer to a |
3784 | // derived class pointed to by the deduced A. |
3785 | if (const PointerType *OriginalParamPtr |
3786 | = OriginalParamType->getAs<PointerType>()) { |
3787 | if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) { |
3788 | if (const PointerType *APtr = A->getAs<PointerType>()) { |
3789 | if (A->getPointeeType()->isRecordType()) { |
3790 | OriginalParamType = OriginalParamPtr->getPointeeType(); |
3791 | DeducedA = DeducedAPtr->getPointeeType(); |
3792 | A = APtr->getPointeeType(); |
3793 | } |
3794 | } |
3795 | } |
3796 | } |
3797 | |
3798 | if (Context.hasSameUnqualifiedType(T1: A, T2: DeducedA)) |
3799 | return TemplateDeductionResult::Success; |
3800 | |
3801 | if (A->isRecordType() && isSimpleTemplateIdType(T: OriginalParamType) && |
3802 | S.IsDerivedFrom(Loc: Info.getLocation(), Derived: A, Base: DeducedA)) |
3803 | return TemplateDeductionResult::Success; |
3804 | |
3805 | return Failed(); |
3806 | } |
3807 | |
3808 | /// Find the pack index for a particular parameter index in an instantiation of |
3809 | /// a function template with specific arguments. |
3810 | /// |
3811 | /// \return The pack index for whichever pack produced this parameter, or -1 |
3812 | /// if this was not produced by a parameter. Intended to be used as the |
3813 | /// ArgumentPackSubstitutionIndex for further substitutions. |
3814 | // FIXME: We should track this in OriginalCallArgs so we don't need to |
3815 | // reconstruct it here. |
3816 | static UnsignedOrNone |
3817 | getPackIndexForParam(Sema &S, FunctionTemplateDecl *FunctionTemplate, |
3818 | const MultiLevelTemplateArgumentList &Args, |
3819 | unsigned ParamIdx) { |
3820 | unsigned Idx = 0; |
3821 | for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) { |
3822 | if (PD->isParameterPack()) { |
3823 | UnsignedOrNone NumArgs = |
3824 | S.getNumArgumentsInExpansion(T: PD->getType(), TemplateArgs: Args); |
3825 | unsigned NumExpansions = NumArgs ? *NumArgs : 1; |
3826 | if (Idx + NumExpansions > ParamIdx) |
3827 | return ParamIdx - Idx; |
3828 | Idx += NumExpansions; |
3829 | } else { |
3830 | if (Idx == ParamIdx) |
3831 | return std::nullopt; // Not a pack expansion |
3832 | ++Idx; |
3833 | } |
3834 | } |
3835 | |
3836 | llvm_unreachable("parameter index would not be produced from template"); |
3837 | } |
3838 | |
3839 | // if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`, |
3840 | // we'll try to instantiate and update its explicit specifier after constraint |
3841 | // checking. |
3842 | static TemplateDeductionResult instantiateExplicitSpecifierDeferred( |
3843 | Sema &S, FunctionDecl *Specialization, |
3844 | const MultiLevelTemplateArgumentList &SubstArgs, |
3845 | TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate, |
3846 | ArrayRef<TemplateArgument> DeducedArgs) { |
3847 | auto GetExplicitSpecifier = [](FunctionDecl *D) { |
3848 | return isa<CXXConstructorDecl>(Val: D) |
3849 | ? cast<CXXConstructorDecl>(Val: D)->getExplicitSpecifier() |
3850 | : cast<CXXConversionDecl>(Val: D)->getExplicitSpecifier(); |
3851 | }; |
3852 | auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) { |
3853 | isa<CXXConstructorDecl>(Val: D) |
3854 | ? cast<CXXConstructorDecl>(Val: D)->setExplicitSpecifier(ES) |
3855 | : cast<CXXConversionDecl>(Val: D)->setExplicitSpecifier(ES); |
3856 | }; |
3857 | |
3858 | ExplicitSpecifier ES = GetExplicitSpecifier(Specialization); |
3859 | Expr *ExplicitExpr = ES.getExpr(); |
3860 | if (!ExplicitExpr) |
3861 | return TemplateDeductionResult::Success; |
3862 | if (!ExplicitExpr->isValueDependent()) |
3863 | return TemplateDeductionResult::Success; |
3864 | |
3865 | Sema::InstantiatingTemplate Inst( |
3866 | S, Info.getLocation(), FunctionTemplate, DeducedArgs, |
3867 | Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info); |
3868 | if (Inst.isInvalid()) |
3869 | return TemplateDeductionResult::InstantiationDepth; |
3870 | Sema::SFINAETrap Trap(S); |
3871 | const ExplicitSpecifier InstantiatedES = |
3872 | S.instantiateExplicitSpecifier(TemplateArgs: SubstArgs, ES); |
3873 | if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) { |
3874 | Specialization->setInvalidDecl(true); |
3875 | return TemplateDeductionResult::SubstitutionFailure; |
3876 | } |
3877 | SetExplicitSpecifier(Specialization, InstantiatedES); |
3878 | return TemplateDeductionResult::Success; |
3879 | } |
3880 | |
3881 | TemplateDeductionResult Sema::FinishTemplateArgumentDeduction( |
3882 | FunctionTemplateDecl *FunctionTemplate, |
3883 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
3884 | unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, |
3885 | TemplateDeductionInfo &Info, |
3886 | SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs, |
3887 | bool PartialOverloading, bool PartialOrdering, |
3888 | llvm::function_ref<bool(bool)> CheckNonDependent) { |
3889 | // Unevaluated SFINAE context. |
3890 | EnterExpressionEvaluationContext Unevaluated( |
3891 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
3892 | SFINAETrap Trap(*this); |
3893 | |
3894 | // Enter a new template instantiation context while we instantiate the |
3895 | // actual function declaration. |
3896 | SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); |
3897 | InstantiatingTemplate Inst( |
3898 | *this, Info.getLocation(), FunctionTemplate, DeducedArgs, |
3899 | CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info); |
3900 | if (Inst.isInvalid()) |
3901 | return TemplateDeductionResult::InstantiationDepth; |
3902 | |
3903 | ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); |
3904 | |
3905 | // C++ [temp.deduct.type]p2: |
3906 | // [...] or if any template argument remains neither deduced nor |
3907 | // explicitly specified, template argument deduction fails. |
3908 | bool IsIncomplete = false; |
3909 | CheckTemplateArgumentInfo CTAI(PartialOrdering); |
3910 | if (auto Result = ConvertDeducedTemplateArguments( |
3911 | *this, FunctionTemplate, FunctionTemplate->getTemplateParameters(), |
3912 | /*IsDeduced=*/true, Deduced, Info, CTAI, CurrentInstantiationScope, |
3913 | NumExplicitlySpecified, PartialOverloading ? &IsIncomplete : nullptr); |
3914 | Result != TemplateDeductionResult::Success) |
3915 | return Result; |
3916 | |
3917 | // Form the template argument list from the deduced template arguments. |
3918 | TemplateArgumentList *SugaredDeducedArgumentList = |
3919 | TemplateArgumentList::CreateCopy(Context, Args: CTAI.SugaredConverted); |
3920 | TemplateArgumentList *CanonicalDeducedArgumentList = |
3921 | TemplateArgumentList::CreateCopy(Context, Args: CTAI.CanonicalConverted); |
3922 | Info.reset(NewDeducedSugared: SugaredDeducedArgumentList, NewDeducedCanonical: CanonicalDeducedArgumentList); |
3923 | |
3924 | // Substitute the deduced template arguments into the function template |
3925 | // declaration to produce the function template specialization. |
3926 | DeclContext *Owner = FunctionTemplate->getDeclContext(); |
3927 | if (FunctionTemplate->getFriendObjectKind()) |
3928 | Owner = FunctionTemplate->getLexicalDeclContext(); |
3929 | FunctionDecl *FD = FunctionTemplate->getTemplatedDecl(); |
3930 | |
3931 | if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/true)) |
3932 | return TemplateDeductionResult::NonDependentConversionFailure; |
3933 | |
3934 | // C++20 [temp.deduct.general]p5: [CWG2369] |
3935 | // If the function template has associated constraints, those constraints |
3936 | // are checked for satisfaction. If the constraints are not satisfied, type |
3937 | // deduction fails. |
3938 | // |
3939 | // FIXME: We haven't implemented CWG2369 for lambdas yet, because we need |
3940 | // to figure out how to instantiate lambda captures to the scope without |
3941 | // first instantiating the lambda. |
3942 | bool IsLambda = isLambdaCallOperator(FD) || isLambdaConversionOperator(FD); |
3943 | if (!IsLambda && !IsIncomplete) { |
3944 | if (CheckFunctionTemplateConstraints( |
3945 | PointOfInstantiation: Info.getLocation(), |
3946 | Decl: FunctionTemplate->getCanonicalDecl()->getTemplatedDecl(), |
3947 | TemplateArgs: CTAI.CanonicalConverted, Satisfaction&: Info.AssociatedConstraintsSatisfaction)) |
3948 | return TemplateDeductionResult::MiscellaneousDeductionFailure; |
3949 | if (!Info.AssociatedConstraintsSatisfaction.IsSatisfied) { |
3950 | Info.reset(NewDeducedSugared: Info.takeSugared(), NewDeducedCanonical: TemplateArgumentList::CreateCopy( |
3951 | Context, Args: CTAI.CanonicalConverted)); |
3952 | return TemplateDeductionResult::ConstraintsNotSatisfied; |
3953 | } |
3954 | } |
3955 | // C++ [temp.deduct.call]p10: [CWG1391] |
3956 | // If deduction succeeds for all parameters that contain |
3957 | // template-parameters that participate in template argument deduction, |
3958 | // and all template arguments are explicitly specified, deduced, or |
3959 | // obtained from default template arguments, remaining parameters are then |
3960 | // compared with the corresponding arguments. For each remaining parameter |
3961 | // P with a type that was non-dependent before substitution of any |
3962 | // explicitly-specified template arguments, if the corresponding argument |
3963 | // A cannot be implicitly converted to P, deduction fails. |
3964 | if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/false)) |
3965 | return TemplateDeductionResult::NonDependentConversionFailure; |
3966 | |
3967 | MultiLevelTemplateArgumentList SubstArgs( |
3968 | FunctionTemplate, CanonicalDeducedArgumentList->asArray(), |
3969 | /*Final=*/false); |
3970 | Specialization = cast_or_null<FunctionDecl>( |
3971 | Val: SubstDecl(FD, Owner, SubstArgs)); |
3972 | if (!Specialization || Specialization->isInvalidDecl()) |
3973 | return TemplateDeductionResult::SubstitutionFailure; |
3974 | |
3975 | assert(isSameDeclaration(Specialization->getPrimaryTemplate(), |
3976 | FunctionTemplate)); |
3977 | |
3978 | // If the template argument list is owned by the function template |
3979 | // specialization, release it. |
3980 | if (Specialization->getTemplateSpecializationArgs() == |
3981 | CanonicalDeducedArgumentList && |
3982 | !Trap.hasErrorOccurred()) |
3983 | Info.takeCanonical(); |
3984 | |
3985 | // There may have been an error that did not prevent us from constructing a |
3986 | // declaration. Mark the declaration invalid and return with a substitution |
3987 | // failure. |
3988 | if (Trap.hasErrorOccurred()) { |
3989 | Specialization->setInvalidDecl(true); |
3990 | return TemplateDeductionResult::SubstitutionFailure; |
3991 | } |
3992 | |
3993 | // C++2a [temp.deduct]p5 |
3994 | // [...] When all template arguments have been deduced [...] all uses of |
3995 | // template parameters [...] are replaced with the corresponding deduced |
3996 | // or default argument values. |
3997 | // [...] If the function template has associated constraints |
3998 | // ([temp.constr.decl]), those constraints are checked for satisfaction |
3999 | // ([temp.constr.constr]). If the constraints are not satisfied, type |
4000 | // deduction fails. |
4001 | if (IsLambda && !IsIncomplete) { |
4002 | if (CheckFunctionTemplateConstraints( |
4003 | PointOfInstantiation: Info.getLocation(), Decl: Specialization, TemplateArgs: CTAI.CanonicalConverted, |
4004 | Satisfaction&: Info.AssociatedConstraintsSatisfaction)) |
4005 | return TemplateDeductionResult::MiscellaneousDeductionFailure; |
4006 | |
4007 | if (!Info.AssociatedConstraintsSatisfaction.IsSatisfied) { |
4008 | Info.reset(NewDeducedSugared: Info.takeSugared(), NewDeducedCanonical: TemplateArgumentList::CreateCopy( |
4009 | Context, Args: CTAI.CanonicalConverted)); |
4010 | return TemplateDeductionResult::ConstraintsNotSatisfied; |
4011 | } |
4012 | } |
4013 | |
4014 | // We skipped the instantiation of the explicit-specifier during the |
4015 | // substitution of `FD` before. So, we try to instantiate it back if |
4016 | // `Specialization` is either a constructor or a conversion function. |
4017 | if (isa<CXXConstructorDecl, CXXConversionDecl>(Val: Specialization)) { |
4018 | if (TemplateDeductionResult::Success != |
4019 | instantiateExplicitSpecifierDeferred(S&: *this, Specialization, SubstArgs, |
4020 | Info, FunctionTemplate, |
4021 | DeducedArgs)) { |
4022 | return TemplateDeductionResult::SubstitutionFailure; |
4023 | } |
4024 | } |
4025 | |
4026 | if (OriginalCallArgs) { |
4027 | // C++ [temp.deduct.call]p4: |
4028 | // In general, the deduction process attempts to find template argument |
4029 | // values that will make the deduced A identical to A (after the type A |
4030 | // is transformed as described above). [...] |
4031 | llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes; |
4032 | for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) { |
4033 | OriginalCallArg OriginalArg = (*OriginalCallArgs)[I]; |
4034 | |
4035 | auto ParamIdx = OriginalArg.ArgIdx; |
4036 | unsigned ExplicitOffset = |
4037 | Specialization->hasCXXExplicitFunctionObjectParameter() ? 1 : 0; |
4038 | if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset) |
4039 | // FIXME: This presumably means a pack ended up smaller than we |
4040 | // expected while deducing. Should this not result in deduction |
4041 | // failure? Can it even happen? |
4042 | continue; |
4043 | |
4044 | QualType DeducedA; |
4045 | if (!OriginalArg.DecomposedParam) { |
4046 | // P is one of the function parameters, just look up its substituted |
4047 | // type. |
4048 | DeducedA = |
4049 | Specialization->getParamDecl(i: ParamIdx + ExplicitOffset)->getType(); |
4050 | } else { |
4051 | // P is a decomposed element of a parameter corresponding to a |
4052 | // braced-init-list argument. Substitute back into P to find the |
4053 | // deduced A. |
4054 | QualType &CacheEntry = |
4055 | DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}]; |
4056 | if (CacheEntry.isNull()) { |
4057 | ArgPackSubstIndexRAII PackIndex( |
4058 | *this, getPackIndexForParam(S&: *this, FunctionTemplate, Args: SubstArgs, |
4059 | ParamIdx)); |
4060 | CacheEntry = |
4061 | SubstType(OriginalArg.OriginalParamType, SubstArgs, |
4062 | Specialization->getTypeSpecStartLoc(), |
4063 | Specialization->getDeclName()); |
4064 | } |
4065 | DeducedA = CacheEntry; |
4066 | } |
4067 | |
4068 | if (auto TDK = |
4069 | CheckOriginalCallArgDeduction(S&: *this, Info, OriginalArg, DeducedA); |
4070 | TDK != TemplateDeductionResult::Success) |
4071 | return TDK; |
4072 | } |
4073 | } |
4074 | |
4075 | // If we suppressed any diagnostics while performing template argument |
4076 | // deduction, and if we haven't already instantiated this declaration, |
4077 | // keep track of these diagnostics. They'll be emitted if this specialization |
4078 | // is actually used. |
4079 | if (Info.diag_begin() != Info.diag_end()) { |
4080 | auto [Pos, Inserted] = |
4081 | SuppressedDiagnostics.try_emplace(Specialization->getCanonicalDecl()); |
4082 | if (Inserted) |
4083 | Pos->second.append(Info.diag_begin(), Info.diag_end()); |
4084 | } |
4085 | |
4086 | return TemplateDeductionResult::Success; |
4087 | } |
4088 | |
4089 | /// Gets the type of a function for template-argument-deducton |
4090 | /// purposes when it's considered as part of an overload set. |
4091 | static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, |
4092 | FunctionDecl *Fn) { |
4093 | // We may need to deduce the return type of the function now. |
4094 | if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() && |
4095 | S.DeduceReturnType(FD: Fn, Loc: R.Expression->getExprLoc(), /*Diagnose*/ false)) |
4096 | return {}; |
4097 | |
4098 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) |
4099 | if (Method->isImplicitObjectMemberFunction()) { |
4100 | // An instance method that's referenced in a form that doesn't |
4101 | // look like a member pointer is just invalid. |
4102 | if (!R.HasFormOfMemberPointer) |
4103 | return {}; |
4104 | |
4105 | return S.Context.getMemberPointerType( |
4106 | T: Fn->getType(), /*Qualifier=*/nullptr, Cls: Method->getParent()); |
4107 | } |
4108 | |
4109 | if (!R.IsAddressOfOperand) return Fn->getType(); |
4110 | return S.Context.getPointerType(Fn->getType()); |
4111 | } |
4112 | |
4113 | /// Apply the deduction rules for overload sets. |
4114 | /// |
4115 | /// \return the null type if this argument should be treated as an |
4116 | /// undeduced context |
4117 | static QualType |
4118 | ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams, |
4119 | Expr *Arg, QualType ParamType, |
4120 | bool ParamWasReference, |
4121 | TemplateSpecCandidateSet *FailedTSC = nullptr) { |
4122 | |
4123 | OverloadExpr::FindResult R = OverloadExpr::find(E: Arg); |
4124 | |
4125 | OverloadExpr *Ovl = R.Expression; |
4126 | |
4127 | // C++0x [temp.deduct.call]p4 |
4128 | unsigned TDF = 0; |
4129 | if (ParamWasReference) |
4130 | TDF |= TDF_ParamWithReferenceType; |
4131 | if (R.IsAddressOfOperand) |
4132 | TDF |= TDF_IgnoreQualifiers; |
4133 | |
4134 | // C++0x [temp.deduct.call]p6: |
4135 | // When P is a function type, pointer to function type, or pointer |
4136 | // to member function type: |
4137 | |
4138 | if (!ParamType->isFunctionType() && |
4139 | !ParamType->isFunctionPointerType() && |
4140 | !ParamType->isMemberFunctionPointerType()) { |
4141 | if (Ovl->hasExplicitTemplateArgs()) { |
4142 | // But we can still look for an explicit specialization. |
4143 | if (FunctionDecl *ExplicitSpec = |
4144 | S.ResolveSingleFunctionTemplateSpecialization( |
4145 | ovl: Ovl, /*Complain=*/false, |
4146 | /*Found=*/nullptr, FailedTSC, |
4147 | /*ForTypeDeduction=*/true)) |
4148 | return GetTypeOfFunction(S, R, Fn: ExplicitSpec); |
4149 | } |
4150 | |
4151 | DeclAccessPair DAP; |
4152 | if (FunctionDecl *Viable = |
4153 | S.resolveAddressOfSingleOverloadCandidate(E: Arg, FoundResult&: DAP)) |
4154 | return GetTypeOfFunction(S, R, Fn: Viable); |
4155 | |
4156 | return {}; |
4157 | } |
4158 | |
4159 | // Gather the explicit template arguments, if any. |
4160 | TemplateArgumentListInfo ExplicitTemplateArgs; |
4161 | if (Ovl->hasExplicitTemplateArgs()) |
4162 | Ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs); |
4163 | QualType Match; |
4164 | for (UnresolvedSetIterator I = Ovl->decls_begin(), |
4165 | E = Ovl->decls_end(); I != E; ++I) { |
4166 | NamedDecl *D = (*I)->getUnderlyingDecl(); |
4167 | |
4168 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D)) { |
4169 | // - If the argument is an overload set containing one or more |
4170 | // function templates, the parameter is treated as a |
4171 | // non-deduced context. |
4172 | if (!Ovl->hasExplicitTemplateArgs()) |
4173 | return {}; |
4174 | |
4175 | // Otherwise, see if we can resolve a function type |
4176 | FunctionDecl *Specialization = nullptr; |
4177 | TemplateDeductionInfo Info(Ovl->getNameLoc()); |
4178 | if (S.DeduceTemplateArguments(FunctionTemplate: FunTmpl, ExplicitTemplateArgs: &ExplicitTemplateArgs, |
4179 | Specialization, |
4180 | Info) != TemplateDeductionResult::Success) |
4181 | continue; |
4182 | |
4183 | D = Specialization; |
4184 | } |
4185 | |
4186 | FunctionDecl *Fn = cast<FunctionDecl>(Val: D); |
4187 | QualType ArgType = GetTypeOfFunction(S, R, Fn); |
4188 | if (ArgType.isNull()) continue; |
4189 | |
4190 | // Function-to-pointer conversion. |
4191 | if (!ParamWasReference && ParamType->isPointerType() && |
4192 | ArgType->isFunctionType()) |
4193 | ArgType = S.Context.getPointerType(T: ArgType); |
4194 | |
4195 | // - If the argument is an overload set (not containing function |
4196 | // templates), trial argument deduction is attempted using each |
4197 | // of the members of the set. If deduction succeeds for only one |
4198 | // of the overload set members, that member is used as the |
4199 | // argument value for the deduction. If deduction succeeds for |
4200 | // more than one member of the overload set the parameter is |
4201 | // treated as a non-deduced context. |
4202 | |
4203 | // We do all of this in a fresh context per C++0x [temp.deduct.type]p2: |
4204 | // Type deduction is done independently for each P/A pair, and |
4205 | // the deduced template argument values are then combined. |
4206 | // So we do not reject deductions which were made elsewhere. |
4207 | SmallVector<DeducedTemplateArgument, 8> |
4208 | Deduced(TemplateParams->size()); |
4209 | TemplateDeductionInfo Info(Ovl->getNameLoc()); |
4210 | TemplateDeductionResult Result = DeduceTemplateArgumentsByTypeMatch( |
4211 | S, TemplateParams, P: ParamType, A: ArgType, Info, Deduced, TDF, |
4212 | POK: PartialOrderingKind::None, /*DeducedFromArrayBound=*/false, |
4213 | /*HasDeducedAnyParam=*/nullptr); |
4214 | if (Result != TemplateDeductionResult::Success) |
4215 | continue; |
4216 | // C++ [temp.deduct.call]p6: |
4217 | // [...] If all successful deductions yield the same deduced A, that |
4218 | // deduced A is the result of deduction; otherwise, the parameter is |
4219 | // treated as a non-deduced context. [...] |
4220 | if (!Match.isNull() && !S.isSameOrCompatibleFunctionType(P: Match, A: ArgType)) |
4221 | return {}; |
4222 | Match = ArgType; |
4223 | } |
4224 | |
4225 | return Match; |
4226 | } |
4227 | |
4228 | /// Perform the adjustments to the parameter and argument types |
4229 | /// described in C++ [temp.deduct.call]. |
4230 | /// |
4231 | /// \returns true if the caller should not attempt to perform any template |
4232 | /// argument deduction based on this P/A pair because the argument is an |
4233 | /// overloaded function set that could not be resolved. |
4234 | static bool AdjustFunctionParmAndArgTypesForDeduction( |
4235 | Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, |
4236 | QualType &ParamType, QualType &ArgType, |
4237 | Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF, |
4238 | TemplateSpecCandidateSet *FailedTSC = nullptr) { |
4239 | // C++0x [temp.deduct.call]p3: |
4240 | // If P is a cv-qualified type, the top level cv-qualifiers of P's type |
4241 | // are ignored for type deduction. |
4242 | if (ParamType.hasQualifiers()) |
4243 | ParamType = ParamType.getUnqualifiedType(); |
4244 | |
4245 | // [...] If P is a reference type, the type referred to by P is |
4246 | // used for type deduction. |
4247 | const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>(); |
4248 | if (ParamRefType) |
4249 | ParamType = ParamRefType->getPointeeType(); |
4250 | |
4251 | // Overload sets usually make this parameter an undeduced context, |
4252 | // but there are sometimes special circumstances. Typically |
4253 | // involving a template-id-expr. |
4254 | if (ArgType == S.Context.OverloadTy) { |
4255 | assert(Arg && "expected a non-null arg expression"); |
4256 | ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType, |
4257 | ParamWasReference: ParamRefType != nullptr, FailedTSC); |
4258 | if (ArgType.isNull()) |
4259 | return true; |
4260 | } |
4261 | |
4262 | if (ParamRefType) { |
4263 | // If the argument has incomplete array type, try to complete its type. |
4264 | if (ArgType->isIncompleteArrayType()) { |
4265 | assert(Arg && "expected a non-null arg expression"); |
4266 | ArgType = S.getCompletedType(E: Arg); |
4267 | } |
4268 | |
4269 | // C++1z [temp.deduct.call]p3: |
4270 | // If P is a forwarding reference and the argument is an lvalue, the type |
4271 | // "lvalue reference to A" is used in place of A for type deduction. |
4272 | if (isForwardingReference(Param: QualType(ParamRefType, 0), FirstInnerIndex) && |
4273 | ArgClassification.isLValue()) { |
4274 | if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace()) |
4275 | ArgType = S.Context.getAddrSpaceQualType( |
4276 | T: ArgType, AddressSpace: S.Context.getDefaultOpenCLPointeeAddrSpace()); |
4277 | ArgType = S.Context.getLValueReferenceType(T: ArgType); |
4278 | } |
4279 | } else { |
4280 | // C++ [temp.deduct.call]p2: |
4281 | // If P is not a reference type: |
4282 | // - If A is an array type, the pointer type produced by the |
4283 | // array-to-pointer standard conversion (4.2) is used in place of |
4284 | // A for type deduction; otherwise, |
4285 | // - If A is a function type, the pointer type produced by the |
4286 | // function-to-pointer standard conversion (4.3) is used in place |
4287 | // of A for type deduction; otherwise, |
4288 | if (ArgType->canDecayToPointerType()) |
4289 | ArgType = S.Context.getDecayedType(T: ArgType); |
4290 | else { |
4291 | // - If A is a cv-qualified type, the top level cv-qualifiers of A's |
4292 | // type are ignored for type deduction. |
4293 | ArgType = ArgType.getUnqualifiedType(); |
4294 | } |
4295 | } |
4296 | |
4297 | // C++0x [temp.deduct.call]p4: |
4298 | // In general, the deduction process attempts to find template argument |
4299 | // values that will make the deduced A identical to A (after the type A |
4300 | // is transformed as described above). [...] |
4301 | TDF = TDF_SkipNonDependent; |
4302 | |
4303 | // - If the original P is a reference type, the deduced A (i.e., the |
4304 | // type referred to by the reference) can be more cv-qualified than |
4305 | // the transformed A. |
4306 | if (ParamRefType) |
4307 | TDF |= TDF_ParamWithReferenceType; |
4308 | // - The transformed A can be another pointer or pointer to member |
4309 | // type that can be converted to the deduced A via a qualification |
4310 | // conversion (4.4). |
4311 | if (ArgType->isPointerType() || ArgType->isMemberPointerType() || |
4312 | ArgType->isObjCObjectPointerType()) |
4313 | TDF |= TDF_IgnoreQualifiers; |
4314 | // - If P is a class and P has the form simple-template-id, then the |
4315 | // transformed A can be a derived class of the deduced A. Likewise, |
4316 | // if P is a pointer to a class of the form simple-template-id, the |
4317 | // transformed A can be a pointer to a derived class pointed to by |
4318 | // the deduced A. |
4319 | if (isSimpleTemplateIdType(T: ParamType) || |
4320 | (ParamType->getAs<PointerType>() && |
4321 | isSimpleTemplateIdType( |
4322 | T: ParamType->castAs<PointerType>()->getPointeeType()))) |
4323 | TDF |= TDF_DerivedClass; |
4324 | |
4325 | return false; |
4326 | } |
4327 | |
4328 | static bool |
4329 | hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate, |
4330 | QualType T); |
4331 | |
4332 | static TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument( |
4333 | Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, |
4334 | QualType ParamType, QualType ArgType, |
4335 | Expr::Classification ArgClassification, Expr *Arg, |
4336 | TemplateDeductionInfo &Info, |
4337 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
4338 | SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, |
4339 | bool DecomposedParam, unsigned ArgIdx, unsigned TDF, |
4340 | TemplateSpecCandidateSet *FailedTSC = nullptr); |
4341 | |
4342 | /// Attempt template argument deduction from an initializer list |
4343 | /// deemed to be an argument in a function call. |
4344 | static TemplateDeductionResult DeduceFromInitializerList( |
4345 | Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType, |
4346 | InitListExpr *ILE, TemplateDeductionInfo &Info, |
4347 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
4348 | SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx, |
4349 | unsigned TDF) { |
4350 | // C++ [temp.deduct.call]p1: (CWG 1591) |
4351 | // If removing references and cv-qualifiers from P gives |
4352 | // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is |
4353 | // a non-empty initializer list, then deduction is performed instead for |
4354 | // each element of the initializer list, taking P0 as a function template |
4355 | // parameter type and the initializer element as its argument |
4356 | // |
4357 | // We've already removed references and cv-qualifiers here. |
4358 | if (!ILE->getNumInits()) |
4359 | return TemplateDeductionResult::Success; |
4360 | |
4361 | QualType ElTy; |
4362 | auto *ArrTy = S.Context.getAsArrayType(T: AdjustedParamType); |
4363 | if (ArrTy) |
4364 | ElTy = ArrTy->getElementType(); |
4365 | else if (!S.isStdInitializerList(Ty: AdjustedParamType, Element: &ElTy)) { |
4366 | // Otherwise, an initializer list argument causes the parameter to be |
4367 | // considered a non-deduced context |
4368 | return TemplateDeductionResult::Success; |
4369 | } |
4370 | |
4371 | // Resolving a core issue: a braced-init-list containing any designators is |
4372 | // a non-deduced context. |
4373 | for (Expr *E : ILE->inits()) |
4374 | if (isa<DesignatedInitExpr>(Val: E)) |
4375 | return TemplateDeductionResult::Success; |
4376 | |
4377 | // Deduction only needs to be done for dependent types. |
4378 | if (ElTy->isDependentType()) { |
4379 | for (Expr *E : ILE->inits()) { |
4380 | if (auto Result = DeduceTemplateArgumentsFromCallArgument( |
4381 | S, TemplateParams, FirstInnerIndex: 0, ParamType: ElTy, ArgType: E->getType(), |
4382 | ArgClassification: E->Classify(Ctx&: S.getASTContext()), Arg: E, Info, Deduced, |
4383 | OriginalCallArgs, DecomposedParam: true, ArgIdx, TDF); |
4384 | Result != TemplateDeductionResult::Success) |
4385 | return Result; |
4386 | } |
4387 | } |
4388 | |
4389 | // in the P0[N] case, if N is a non-type template parameter, N is deduced |
4390 | // from the length of the initializer list. |
4391 | if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(Val: ArrTy)) { |
4392 | // Determine the array bound is something we can deduce. |
4393 | if (const NonTypeTemplateParmDecl *NTTP = |
4394 | getDeducedParameterFromExpr(Info, E: DependentArrTy->getSizeExpr())) { |
4395 | // We can perform template argument deduction for the given non-type |
4396 | // template parameter. |
4397 | // C++ [temp.deduct.type]p13: |
4398 | // The type of N in the type T[N] is std::size_t. |
4399 | QualType T = S.Context.getSizeType(); |
4400 | llvm::APInt Size(S.Context.getIntWidth(T), |
4401 | ILE->getNumInitsWithEmbedExpanded()); |
4402 | if (auto Result = DeduceNonTypeTemplateArgument( |
4403 | S, TemplateParams, NTTP, Value: llvm::APSInt(Size), ValueType: T, |
4404 | /*ArrayBound=*/DeducedFromArrayBound: true, Info, /*PartialOrdering=*/false, Deduced, |
4405 | /*HasDeducedAnyParam=*/nullptr); |
4406 | Result != TemplateDeductionResult::Success) |
4407 | return Result; |
4408 | } |
4409 | } |
4410 | |
4411 | return TemplateDeductionResult::Success; |
4412 | } |
4413 | |
4414 | /// Perform template argument deduction per [temp.deduct.call] for a |
4415 | /// single parameter / argument pair. |
4416 | static TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument( |
4417 | Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, |
4418 | QualType ParamType, QualType ArgType, |
4419 | Expr::Classification ArgClassification, Expr *Arg, |
4420 | TemplateDeductionInfo &Info, |
4421 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
4422 | SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, |
4423 | bool DecomposedParam, unsigned ArgIdx, unsigned TDF, |
4424 | TemplateSpecCandidateSet *FailedTSC) { |
4425 | |
4426 | QualType OrigParamType = ParamType; |
4427 | |
4428 | // If P is a reference type [...] |
4429 | // If P is a cv-qualified type [...] |
4430 | if (AdjustFunctionParmAndArgTypesForDeduction( |
4431 | S, TemplateParams, FirstInnerIndex, ParamType, ArgType, |
4432 | ArgClassification, Arg, TDF, FailedTSC)) |
4433 | return TemplateDeductionResult::Success; |
4434 | |
4435 | // If [...] the argument is a non-empty initializer list [...] |
4436 | if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Val: Arg)) |
4437 | return DeduceFromInitializerList(S, TemplateParams, AdjustedParamType: ParamType, ILE, Info, |
4438 | Deduced, OriginalCallArgs, ArgIdx, TDF); |
4439 | |
4440 | // [...] the deduction process attempts to find template argument values |
4441 | // that will make the deduced A identical to A |
4442 | // |
4443 | // Keep track of the argument type and corresponding parameter index, |
4444 | // so we can check for compatibility between the deduced A and A. |
4445 | if (Arg) |
4446 | OriginalCallArgs.push_back( |
4447 | Elt: Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType)); |
4448 | return DeduceTemplateArgumentsByTypeMatch( |
4449 | S, TemplateParams, P: ParamType, A: ArgType, Info, Deduced, TDF, |
4450 | POK: PartialOrderingKind::None, /*DeducedFromArrayBound=*/false, |
4451 | /*HasDeducedAnyParam=*/nullptr); |
4452 | } |
4453 | |
4454 | TemplateDeductionResult Sema::DeduceTemplateArguments( |
4455 | FunctionTemplateDecl *FunctionTemplate, |
4456 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, |
4457 | FunctionDecl *&Specialization, TemplateDeductionInfo &Info, |
4458 | bool PartialOverloading, bool AggregateDeductionCandidate, |
4459 | bool PartialOrdering, QualType ObjectType, |
4460 | Expr::Classification ObjectClassification, |
4461 | bool ForOverloadSetAddressResolution, |
4462 | llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent) { |
4463 | if (FunctionTemplate->isInvalidDecl()) |
4464 | return TemplateDeductionResult::Invalid; |
4465 | |
4466 | FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); |
4467 | unsigned NumParams = Function->getNumParams(); |
4468 | bool HasExplicitObject = false; |
4469 | int ExplicitObjectOffset = 0; |
4470 | |
4471 | // [C++26] [over.call.func]p3 |
4472 | // If the primary-expression is the address of an overload set, |
4473 | // the argument list is the same as the expression-list in the call. |
4474 | // Otherwise, the argument list is the expression-list in the call augmented |
4475 | // by the addition of an implied object argument as in a qualified function |
4476 | // call. |
4477 | if (!ForOverloadSetAddressResolution && |
4478 | Function->hasCXXExplicitFunctionObjectParameter()) { |
4479 | HasExplicitObject = true; |
4480 | ExplicitObjectOffset = 1; |
4481 | } |
4482 | |
4483 | unsigned FirstInnerIndex = getFirstInnerIndex(FTD: FunctionTemplate); |
4484 | |
4485 | // C++ [temp.deduct.call]p1: |
4486 | // Template argument deduction is done by comparing each function template |
4487 | // parameter type (call it P) with the type of the corresponding argument |
4488 | // of the call (call it A) as described below. |
4489 | if (Args.size() < Function->getMinRequiredExplicitArguments() && |
4490 | !PartialOverloading) |
4491 | return TemplateDeductionResult::TooFewArguments; |
4492 | else if (TooManyArguments(NumParams, NumArgs: Args.size() + ExplicitObjectOffset, |
4493 | PartialOverloading)) { |
4494 | const auto *Proto = Function->getType()->castAs<FunctionProtoType>(); |
4495 | if (Proto->isTemplateVariadic()) |
4496 | /* Do nothing */; |
4497 | else if (!Proto->isVariadic()) |
4498 | return TemplateDeductionResult::TooManyArguments; |
4499 | } |
4500 | |
4501 | // The types of the parameters from which we will perform template argument |
4502 | // deduction. |
4503 | LocalInstantiationScope InstScope(*this); |
4504 | TemplateParameterList *TemplateParams |
4505 | = FunctionTemplate->getTemplateParameters(); |
4506 | SmallVector<DeducedTemplateArgument, 4> Deduced; |
4507 | SmallVector<QualType, 8> ParamTypes; |
4508 | unsigned NumExplicitlySpecified = 0; |
4509 | if (ExplicitTemplateArgs) { |
4510 | TemplateDeductionResult Result; |
4511 | runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] { |
4512 | Result = SubstituteExplicitTemplateArguments( |
4513 | FunctionTemplate, ExplicitTemplateArgs&: *ExplicitTemplateArgs, Deduced, ParamTypes, FunctionType: nullptr, |
4514 | Info); |
4515 | }); |
4516 | if (Result != TemplateDeductionResult::Success) |
4517 | return Result; |
4518 | |
4519 | NumExplicitlySpecified = Deduced.size(); |
4520 | } else { |
4521 | // Just fill in the parameter types from the function declaration. |
4522 | for (unsigned I = 0; I != NumParams; ++I) |
4523 | ParamTypes.push_back(Elt: Function->getParamDecl(i: I)->getType()); |
4524 | } |
4525 | |
4526 | SmallVector<OriginalCallArg, 8> OriginalCallArgs; |
4527 | |
4528 | // Deduce an argument of type ParamType from an expression with index ArgIdx. |
4529 | auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx, |
4530 | bool ExplicitObjectArgument) { |
4531 | // C++ [demp.deduct.call]p1: (DR1391) |
4532 | // Template argument deduction is done by comparing each function template |
4533 | // parameter that contains template-parameters that participate in |
4534 | // template argument deduction ... |
4535 | if (!hasDeducibleTemplateParameters(S&: *this, FunctionTemplate, T: ParamType)) |
4536 | return TemplateDeductionResult::Success; |
4537 | |
4538 | if (ExplicitObjectArgument) { |
4539 | // ... with the type of the corresponding argument |
4540 | return DeduceTemplateArgumentsFromCallArgument( |
4541 | *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType, |
4542 | ObjectClassification, |
4543 | /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs, |
4544 | /*Decomposed*/ false, ArgIdx, /*TDF*/ 0); |
4545 | } |
4546 | |
4547 | // ... with the type of the corresponding argument |
4548 | return DeduceTemplateArgumentsFromCallArgument( |
4549 | *this, TemplateParams, FirstInnerIndex, ParamType, |
4550 | Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()), |
4551 | Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false, |
4552 | ArgIdx, /*TDF*/ 0); |
4553 | }; |
4554 | |
4555 | // Deduce template arguments from the function parameters. |
4556 | Deduced.resize(N: TemplateParams->size()); |
4557 | SmallVector<QualType, 8> ParamTypesForArgChecking; |
4558 | for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0; |
4559 | ParamIdx != NumParamTypes; ++ParamIdx) { |
4560 | QualType ParamType = ParamTypes[ParamIdx]; |
4561 | |
4562 | const PackExpansionType *ParamExpansion = |
4563 | dyn_cast<PackExpansionType>(Val&: ParamType); |
4564 | if (!ParamExpansion) { |
4565 | // Simple case: matching a function parameter to a function argument. |
4566 | if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0)) |
4567 | break; |
4568 | |
4569 | ParamTypesForArgChecking.push_back(Elt: ParamType); |
4570 | |
4571 | if (ParamIdx == 0 && HasExplicitObject) { |
4572 | if (ObjectType.isNull()) |
4573 | return TemplateDeductionResult::InvalidExplicitArguments; |
4574 | |
4575 | if (auto Result = DeduceCallArgument(ParamType, 0, |
4576 | /*ExplicitObjectArgument=*/true); |
4577 | Result != TemplateDeductionResult::Success) |
4578 | return Result; |
4579 | continue; |
4580 | } |
4581 | |
4582 | if (auto Result = DeduceCallArgument(ParamType, ArgIdx++, |
4583 | /*ExplicitObjectArgument=*/false); |
4584 | Result != TemplateDeductionResult::Success) |
4585 | return Result; |
4586 | |
4587 | continue; |
4588 | } |
4589 | |
4590 | bool IsTrailingPack = ParamIdx + 1 == NumParamTypes; |
4591 | |
4592 | QualType ParamPattern = ParamExpansion->getPattern(); |
4593 | PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info, |
4594 | ParamPattern, |
4595 | AggregateDeductionCandidate && IsTrailingPack); |
4596 | |
4597 | // C++0x [temp.deduct.call]p1: |
4598 | // For a function parameter pack that occurs at the end of the |
4599 | // parameter-declaration-list, the type A of each remaining argument of |
4600 | // the call is compared with the type P of the declarator-id of the |
4601 | // function parameter pack. Each comparison deduces template arguments |
4602 | // for subsequent positions in the template parameter packs expanded by |
4603 | // the function parameter pack. When a function parameter pack appears |
4604 | // in a non-deduced context [not at the end of the list], the type of |
4605 | // that parameter pack is never deduced. |
4606 | // |
4607 | // FIXME: The above rule allows the size of the parameter pack to change |
4608 | // after we skip it (in the non-deduced case). That makes no sense, so |
4609 | // we instead notionally deduce the pack against N arguments, where N is |
4610 | // the length of the explicitly-specified pack if it's expanded by the |
4611 | // parameter pack and 0 otherwise, and we treat each deduction as a |
4612 | // non-deduced context. |
4613 | if (IsTrailingPack || PackScope.hasFixedArity()) { |
4614 | for (; ArgIdx < Args.size() && PackScope.hasNextElement(); |
4615 | PackScope.nextPackElement(), ++ArgIdx) { |
4616 | ParamTypesForArgChecking.push_back(Elt: ParamPattern); |
4617 | if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx, |
4618 | /*ExplicitObjectArgument=*/false); |
4619 | Result != TemplateDeductionResult::Success) |
4620 | return Result; |
4621 | } |
4622 | } else { |
4623 | // If the parameter type contains an explicitly-specified pack that we |
4624 | // could not expand, skip the number of parameters notionally created |
4625 | // by the expansion. |
4626 | UnsignedOrNone NumExpansions = ParamExpansion->getNumExpansions(); |
4627 | if (NumExpansions && !PackScope.isPartiallyExpanded()) { |
4628 | for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size(); |
4629 | ++I, ++ArgIdx) { |
4630 | ParamTypesForArgChecking.push_back(Elt: ParamPattern); |
4631 | // FIXME: Should we add OriginalCallArgs for these? What if the |
4632 | // corresponding argument is a list? |
4633 | PackScope.nextPackElement(); |
4634 | } |
4635 | } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() && |
4636 | PackScope.isDeducedFromEarlierParameter()) { |
4637 | // [temp.deduct.general#3] |
4638 | // When all template arguments have been deduced |
4639 | // or obtained from default template arguments, all uses of template |
4640 | // parameters in the template parameter list of the template are |
4641 | // replaced with the corresponding deduced or default argument values |
4642 | // |
4643 | // If we have a trailing parameter pack, that has been deduced |
4644 | // previously we substitute the pack here in a similar fashion as |
4645 | // above with the trailing parameter packs. The main difference here is |
4646 | // that, in this case we are not processing all of the remaining |
4647 | // arguments. We are only process as many arguments as we have in |
4648 | // the already deduced parameter. |
4649 | UnsignedOrNone ArgPosAfterSubstitution = |
4650 | PackScope.getSavedPackSizeIfAllEqual(); |
4651 | if (!ArgPosAfterSubstitution) |
4652 | continue; |
4653 | |
4654 | unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution; |
4655 | for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) { |
4656 | ParamTypesForArgChecking.push_back(Elt: ParamPattern); |
4657 | if (auto Result = |
4658 | DeduceCallArgument(ParamPattern, ArgIdx, |
4659 | /*ExplicitObjectArgument=*/false); |
4660 | Result != TemplateDeductionResult::Success) |
4661 | return Result; |
4662 | |
4663 | PackScope.nextPackElement(); |
4664 | } |
4665 | } |
4666 | } |
4667 | |
4668 | // Build argument packs for each of the parameter packs expanded by this |
4669 | // pack expansion. |
4670 | if (auto Result = PackScope.finish(); |
4671 | Result != TemplateDeductionResult::Success) |
4672 | return Result; |
4673 | } |
4674 | |
4675 | // Capture the context in which the function call is made. This is the context |
4676 | // that is needed when the accessibility of template arguments is checked. |
4677 | DeclContext *CallingCtx = CurContext; |
4678 | |
4679 | TemplateDeductionResult Result; |
4680 | runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] { |
4681 | Result = FinishTemplateArgumentDeduction( |
4682 | FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info, |
4683 | OriginalCallArgs: &OriginalCallArgs, PartialOverloading, PartialOrdering, |
4684 | CheckNonDependent: [&, CallingCtx](bool OnlyInitializeNonUserDefinedConversions) { |
4685 | ContextRAII SavedContext(*this, CallingCtx); |
4686 | return CheckNonDependent(ParamTypesForArgChecking, |
4687 | OnlyInitializeNonUserDefinedConversions); |
4688 | }); |
4689 | }); |
4690 | return Result; |
4691 | } |
4692 | |
4693 | QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType, |
4694 | QualType FunctionType, |
4695 | bool AdjustExceptionSpec) { |
4696 | if (ArgFunctionType.isNull()) |
4697 | return ArgFunctionType; |
4698 | |
4699 | const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>(); |
4700 | const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>(); |
4701 | FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo(); |
4702 | bool Rebuild = false; |
4703 | |
4704 | CallingConv CC = FunctionTypeP->getCallConv(); |
4705 | if (EPI.ExtInfo.getCC() != CC) { |
4706 | EPI.ExtInfo = EPI.ExtInfo.withCallingConv(cc: CC); |
4707 | Rebuild = true; |
4708 | } |
4709 | |
4710 | bool NoReturn = FunctionTypeP->getNoReturnAttr(); |
4711 | if (EPI.ExtInfo.getNoReturn() != NoReturn) { |
4712 | EPI.ExtInfo = EPI.ExtInfo.withNoReturn(noReturn: NoReturn); |
4713 | Rebuild = true; |
4714 | } |
4715 | |
4716 | if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() || |
4717 | ArgFunctionTypeP->hasExceptionSpec())) { |
4718 | EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec; |
4719 | Rebuild = true; |
4720 | } |
4721 | |
4722 | if (!Rebuild) |
4723 | return ArgFunctionType; |
4724 | |
4725 | return Context.getFunctionType(ResultTy: ArgFunctionTypeP->getReturnType(), |
4726 | Args: ArgFunctionTypeP->getParamTypes(), EPI); |
4727 | } |
4728 | |
4729 | TemplateDeductionResult Sema::DeduceTemplateArguments( |
4730 | FunctionTemplateDecl *FunctionTemplate, |
4731 | TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, |
4732 | FunctionDecl *&Specialization, TemplateDeductionInfo &Info, |
4733 | bool IsAddressOfFunction) { |
4734 | if (FunctionTemplate->isInvalidDecl()) |
4735 | return TemplateDeductionResult::Invalid; |
4736 | |
4737 | FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); |
4738 | TemplateParameterList *TemplateParams |
4739 | = FunctionTemplate->getTemplateParameters(); |
4740 | QualType FunctionType = Function->getType(); |
4741 | |
4742 | // Substitute any explicit template arguments. |
4743 | LocalInstantiationScope InstScope(*this); |
4744 | SmallVector<DeducedTemplateArgument, 4> Deduced; |
4745 | unsigned NumExplicitlySpecified = 0; |
4746 | SmallVector<QualType, 4> ParamTypes; |
4747 | if (ExplicitTemplateArgs) { |
4748 | TemplateDeductionResult Result; |
4749 | runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] { |
4750 | Result = SubstituteExplicitTemplateArguments( |
4751 | FunctionTemplate, ExplicitTemplateArgs&: *ExplicitTemplateArgs, Deduced, ParamTypes, |
4752 | FunctionType: &FunctionType, Info); |
4753 | }); |
4754 | if (Result != TemplateDeductionResult::Success) |
4755 | return Result; |
4756 | |
4757 | NumExplicitlySpecified = Deduced.size(); |
4758 | } |
4759 | |
4760 | // When taking the address of a function, we require convertibility of |
4761 | // the resulting function type. Otherwise, we allow arbitrary mismatches |
4762 | // of calling convention and noreturn. |
4763 | if (!IsAddressOfFunction) |
4764 | ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType, |
4765 | /*AdjustExceptionSpec*/false); |
4766 | |
4767 | // Unevaluated SFINAE context. |
4768 | std::optional<EnterExpressionEvaluationContext> Unevaluated( |
4769 | std::in_place, *this, Sema::ExpressionEvaluationContext::Unevaluated); |
4770 | SFINAETrap Trap(*this); |
4771 | |
4772 | Deduced.resize(N: TemplateParams->size()); |
4773 | |
4774 | // If the function has a deduced return type, substitute it for a dependent |
4775 | // type so that we treat it as a non-deduced context in what follows. |
4776 | bool HasDeducedReturnType = false; |
4777 | if (getLangOpts().CPlusPlus14 && |
4778 | Function->getReturnType()->getContainedAutoType()) { |
4779 | FunctionType = SubstAutoTypeDependent(TypeWithAuto: FunctionType); |
4780 | HasDeducedReturnType = true; |
4781 | } |
4782 | |
4783 | if (!ArgFunctionType.isNull() && !FunctionType.isNull()) { |
4784 | unsigned TDF = |
4785 | TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType; |
4786 | // Deduce template arguments from the function type. |
4787 | if (TemplateDeductionResult Result = DeduceTemplateArgumentsByTypeMatch( |
4788 | S&: *this, TemplateParams, P: FunctionType, A: ArgFunctionType, Info, Deduced, |
4789 | TDF, POK: PartialOrderingKind::None, /*DeducedFromArrayBound=*/false, |
4790 | /*HasDeducedAnyParam=*/nullptr); |
4791 | Result != TemplateDeductionResult::Success) |
4792 | return Result; |
4793 | } |
4794 | |
4795 | TemplateDeductionResult Result; |
4796 | runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] { |
4797 | Result = FinishTemplateArgumentDeduction( |
4798 | FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info, |
4799 | /*OriginalCallArgs=*/nullptr, /*PartialOverloading=*/false, |
4800 | /*PartialOrdering=*/true); |
4801 | }); |
4802 | if (Result != TemplateDeductionResult::Success) |
4803 | return Result; |
4804 | |
4805 | // If the function has a deduced return type, deduce it now, so we can check |
4806 | // that the deduced function type matches the requested type. |
4807 | if (HasDeducedReturnType && IsAddressOfFunction && |
4808 | Specialization->getReturnType()->isUndeducedType() && |
4809 | DeduceReturnType(FD: Specialization, Loc: Info.getLocation(), Diagnose: false)) |
4810 | return TemplateDeductionResult::MiscellaneousDeductionFailure; |
4811 | |
4812 | Unevaluated = std::nullopt; |
4813 | // [C++26][expr.const]/p17 |
4814 | // An expression or conversion is immediate-escalating if it is not initially |
4815 | // in an immediate function context and it is [...] |
4816 | // a potentially-evaluated id-expression that denotes an immediate function. |
4817 | if (IsAddressOfFunction && getLangOpts().CPlusPlus20 && |
4818 | Specialization->isImmediateEscalating() && |
4819 | currentEvaluationContext().isPotentiallyEvaluated() && |
4820 | CheckIfFunctionSpecializationIsImmediate(FD: Specialization, |
4821 | Loc: Info.getLocation())) |
4822 | return TemplateDeductionResult::MiscellaneousDeductionFailure; |
4823 | |
4824 | // Adjust the exception specification of the argument to match the |
4825 | // substituted and resolved type we just formed. (Calling convention and |
4826 | // noreturn can't be dependent, so we don't actually need this for them |
4827 | // right now.) |
4828 | QualType SpecializationType = Specialization->getType(); |
4829 | if (!IsAddressOfFunction) { |
4830 | ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType: SpecializationType, |
4831 | /*AdjustExceptionSpec*/true); |
4832 | |
4833 | // Revert placeholder types in the return type back to undeduced types so |
4834 | // that the comparison below compares the declared return types. |
4835 | if (HasDeducedReturnType) { |
4836 | SpecializationType = SubstAutoType(TypeWithAuto: SpecializationType, Replacement: QualType()); |
4837 | ArgFunctionType = SubstAutoType(TypeWithAuto: ArgFunctionType, Replacement: QualType()); |
4838 | } |
4839 | } |
4840 | |
4841 | // If the requested function type does not match the actual type of the |
4842 | // specialization with respect to arguments of compatible pointer to function |
4843 | // types, template argument deduction fails. |
4844 | if (!ArgFunctionType.isNull()) { |
4845 | if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType( |
4846 | P: SpecializationType, A: ArgFunctionType) |
4847 | : !Context.hasSameFunctionTypeIgnoringExceptionSpec( |
4848 | T: SpecializationType, U: ArgFunctionType)) { |
4849 | Info.FirstArg = TemplateArgument(SpecializationType); |
4850 | Info.SecondArg = TemplateArgument(ArgFunctionType); |
4851 | return TemplateDeductionResult::NonDeducedMismatch; |
4852 | } |
4853 | } |
4854 | |
4855 | return TemplateDeductionResult::Success; |
4856 | } |
4857 | |
4858 | TemplateDeductionResult Sema::DeduceTemplateArguments( |
4859 | FunctionTemplateDecl *ConversionTemplate, QualType ObjectType, |
4860 | Expr::Classification ObjectClassification, QualType A, |
4861 | CXXConversionDecl *&Specialization, TemplateDeductionInfo &Info) { |
4862 | if (ConversionTemplate->isInvalidDecl()) |
4863 | return TemplateDeductionResult::Invalid; |
4864 | |
4865 | CXXConversionDecl *ConversionGeneric |
4866 | = cast<CXXConversionDecl>(Val: ConversionTemplate->getTemplatedDecl()); |
4867 | |
4868 | QualType P = ConversionGeneric->getConversionType(); |
4869 | bool IsReferenceP = P->isReferenceType(); |
4870 | bool IsReferenceA = A->isReferenceType(); |
4871 | |
4872 | // C++0x [temp.deduct.conv]p2: |
4873 | // If P is a reference type, the type referred to by P is used for |
4874 | // type deduction. |
4875 | if (const ReferenceType *PRef = P->getAs<ReferenceType>()) |
4876 | P = PRef->getPointeeType(); |
4877 | |
4878 | // C++0x [temp.deduct.conv]p4: |
4879 | // [...] If A is a reference type, the type referred to by A is used |
4880 | // for type deduction. |
4881 | if (const ReferenceType *ARef = A->getAs<ReferenceType>()) { |
4882 | A = ARef->getPointeeType(); |
4883 | // We work around a defect in the standard here: cv-qualifiers are also |
4884 | // removed from P and A in this case, unless P was a reference type. This |
4885 | // seems to mostly match what other compilers are doing. |
4886 | if (!IsReferenceP) { |
4887 | A = A.getUnqualifiedType(); |
4888 | P = P.getUnqualifiedType(); |
4889 | } |
4890 | |
4891 | // C++ [temp.deduct.conv]p3: |
4892 | // |
4893 | // If A is not a reference type: |
4894 | } else { |
4895 | assert(!A->isReferenceType() && "Reference types were handled above"); |
4896 | |
4897 | // - If P is an array type, the pointer type produced by the |
4898 | // array-to-pointer standard conversion (4.2) is used in place |
4899 | // of P for type deduction; otherwise, |
4900 | if (P->isArrayType()) |
4901 | P = Context.getArrayDecayedType(T: P); |
4902 | // - If P is a function type, the pointer type produced by the |
4903 | // function-to-pointer standard conversion (4.3) is used in |
4904 | // place of P for type deduction; otherwise, |
4905 | else if (P->isFunctionType()) |
4906 | P = Context.getPointerType(T: P); |
4907 | // - If P is a cv-qualified type, the top level cv-qualifiers of |
4908 | // P's type are ignored for type deduction. |
4909 | else |
4910 | P = P.getUnqualifiedType(); |
4911 | |
4912 | // C++0x [temp.deduct.conv]p4: |
4913 | // If A is a cv-qualified type, the top level cv-qualifiers of A's |
4914 | // type are ignored for type deduction. If A is a reference type, the type |
4915 | // referred to by A is used for type deduction. |
4916 | A = A.getUnqualifiedType(); |
4917 | } |
4918 | |
4919 | // Unevaluated SFINAE context. |
4920 | EnterExpressionEvaluationContext Unevaluated( |
4921 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
4922 | SFINAETrap Trap(*this); |
4923 | |
4924 | // C++ [temp.deduct.conv]p1: |
4925 | // Template argument deduction is done by comparing the return |
4926 | // type of the template conversion function (call it P) with the |
4927 | // type that is required as the result of the conversion (call it |
4928 | // A) as described in 14.8.2.4. |
4929 | TemplateParameterList *TemplateParams |
4930 | = ConversionTemplate->getTemplateParameters(); |
4931 | SmallVector<DeducedTemplateArgument, 4> Deduced; |
4932 | Deduced.resize(N: TemplateParams->size()); |
4933 | |
4934 | // C++0x [temp.deduct.conv]p4: |
4935 | // In general, the deduction process attempts to find template |
4936 | // argument values that will make the deduced A identical to |
4937 | // A. However, there are two cases that allow a difference: |
4938 | unsigned TDF = 0; |
4939 | // - If the original A is a reference type, A can be more |
4940 | // cv-qualified than the deduced A (i.e., the type referred to |
4941 | // by the reference) |
4942 | if (IsReferenceA) |
4943 | TDF |= TDF_ArgWithReferenceType; |
4944 | // - The deduced A can be another pointer or pointer to member |
4945 | // type that can be converted to A via a qualification |
4946 | // conversion. |
4947 | // |
4948 | // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when |
4949 | // both P and A are pointers or member pointers. In this case, we |
4950 | // just ignore cv-qualifiers completely). |
4951 | if ((P->isPointerType() && A->isPointerType()) || |
4952 | (P->isMemberPointerType() && A->isMemberPointerType())) |
4953 | TDF |= TDF_IgnoreQualifiers; |
4954 | |
4955 | SmallVector<Sema::OriginalCallArg, 1> OriginalCallArgs; |
4956 | if (ConversionGeneric->isExplicitObjectMemberFunction()) { |
4957 | QualType ParamType = ConversionGeneric->getParamDecl(0)->getType(); |
4958 | if (TemplateDeductionResult Result = |
4959 | DeduceTemplateArgumentsFromCallArgument( |
4960 | S&: *this, TemplateParams, FirstInnerIndex: getFirstInnerIndex(FTD: ConversionTemplate), |
4961 | ParamType, ArgType: ObjectType, ArgClassification: ObjectClassification, |
4962 | /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs, |
4963 | /*Decomposed*/ DecomposedParam: false, ArgIdx: 0, /*TDF*/ 0); |
4964 | Result != TemplateDeductionResult::Success) |
4965 | return Result; |
4966 | } |
4967 | |
4968 | if (TemplateDeductionResult Result = DeduceTemplateArgumentsByTypeMatch( |
4969 | S&: *this, TemplateParams, P, A, Info, Deduced, TDF, |
4970 | POK: PartialOrderingKind::None, /*DeducedFromArrayBound=*/false, |
4971 | /*HasDeducedAnyParam=*/nullptr); |
4972 | Result != TemplateDeductionResult::Success) |
4973 | return Result; |
4974 | |
4975 | // Create an Instantiation Scope for finalizing the operator. |
4976 | LocalInstantiationScope InstScope(*this); |
4977 | // Finish template argument deduction. |
4978 | FunctionDecl *ConversionSpecialized = nullptr; |
4979 | TemplateDeductionResult Result; |
4980 | runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] { |
4981 | Result = FinishTemplateArgumentDeduction( |
4982 | FunctionTemplate: ConversionTemplate, Deduced, NumExplicitlySpecified: 0, Specialization&: ConversionSpecialized, Info, |
4983 | OriginalCallArgs: &OriginalCallArgs, /*PartialOverloading=*/false, |
4984 | /*PartialOrdering=*/false); |
4985 | }); |
4986 | Specialization = cast_or_null<CXXConversionDecl>(Val: ConversionSpecialized); |
4987 | return Result; |
4988 | } |
4989 | |
4990 | TemplateDeductionResult |
4991 | Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, |
4992 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
4993 | FunctionDecl *&Specialization, |
4994 | TemplateDeductionInfo &Info, |
4995 | bool IsAddressOfFunction) { |
4996 | return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, |
4997 | ArgFunctionType: QualType(), Specialization, Info, |
4998 | IsAddressOfFunction); |
4999 | } |
5000 | |
5001 | namespace { |
5002 | struct DependentAuto { bool IsPack; }; |
5003 | |
5004 | /// Substitute the 'auto' specifier or deduced template specialization type |
5005 | /// specifier within a type for a given replacement type. |
5006 | class SubstituteDeducedTypeTransform : |
5007 | public TreeTransform<SubstituteDeducedTypeTransform> { |
5008 | QualType Replacement; |
5009 | bool ReplacementIsPack; |
5010 | bool UseTypeSugar; |
5011 | using inherited = TreeTransform<SubstituteDeducedTypeTransform>; |
5012 | |
5013 | public: |
5014 | SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA) |
5015 | : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef), |
5016 | ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {} |
5017 | |
5018 | SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement, |
5019 | bool UseTypeSugar = true) |
5020 | : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef), |
5021 | Replacement(Replacement), ReplacementIsPack(false), |
5022 | UseTypeSugar(UseTypeSugar) {} |
5023 | |
5024 | QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) { |
5025 | assert(isa<TemplateTypeParmType>(Replacement) && |
5026 | "unexpected unsugared replacement kind"); |
5027 | QualType Result = Replacement; |
5028 | TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(T: Result); |
5029 | NewTL.setNameLoc(TL.getNameLoc()); |
5030 | return Result; |
5031 | } |
5032 | |
5033 | QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) { |
5034 | // If we're building the type pattern to deduce against, don't wrap the |
5035 | // substituted type in an AutoType. Certain template deduction rules |
5036 | // apply only when a template type parameter appears directly (and not if |
5037 | // the parameter is found through desugaring). For instance: |
5038 | // auto &&lref = lvalue; |
5039 | // must transform into "rvalue reference to T" not "rvalue reference to |
5040 | // auto type deduced as T" in order for [temp.deduct.call]p3 to apply. |
5041 | // |
5042 | // FIXME: Is this still necessary? |
5043 | if (!UseTypeSugar) |
5044 | return TransformDesugared(TLB, TL); |
5045 | |
5046 | QualType Result = SemaRef.Context.getAutoType( |
5047 | Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(), |
5048 | ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(), |
5049 | TL.getTypePtr()->getTypeConstraintArguments()); |
5050 | auto NewTL = TLB.push<AutoTypeLoc>(T: Result); |
5051 | NewTL.copy(Loc: TL); |
5052 | return Result; |
5053 | } |
5054 | |
5055 | QualType TransformDeducedTemplateSpecializationType( |
5056 | TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) { |
5057 | if (!UseTypeSugar) |
5058 | return TransformDesugared(TLB, TL); |
5059 | |
5060 | QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType( |
5061 | TL.getTypePtr()->getTemplateName(), |
5062 | Replacement, Replacement.isNull()); |
5063 | auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T: Result); |
5064 | NewTL.setNameLoc(TL.getNameLoc()); |
5065 | return Result; |
5066 | } |
5067 | |
5068 | ExprResult TransformLambdaExpr(LambdaExpr *E) { |
5069 | // Lambdas never need to be transformed. |
5070 | return E; |
5071 | } |
5072 | bool TransformExceptionSpec(SourceLocation Loc, |
5073 | FunctionProtoType::ExceptionSpecInfo &ESI, |
5074 | SmallVectorImpl<QualType> &Exceptions, |
5075 | bool &Changed) { |
5076 | if (ESI.Type == EST_Uninstantiated) { |
5077 | ESI.instantiate(); |
5078 | Changed = true; |
5079 | } |
5080 | return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed); |
5081 | } |
5082 | |
5083 | QualType Apply(TypeLoc TL) { |
5084 | // Create some scratch storage for the transformed type locations. |
5085 | // FIXME: We're just going to throw this information away. Don't build it. |
5086 | TypeLocBuilder TLB; |
5087 | TLB.reserve(Requested: TL.getFullDataSize()); |
5088 | return TransformType(TLB, TL); |
5089 | } |
5090 | }; |
5091 | |
5092 | } // namespace |
5093 | |
5094 | static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type, |
5095 | AutoTypeLoc TypeLoc, |
5096 | QualType Deduced) { |
5097 | ConstraintSatisfaction Satisfaction; |
5098 | ConceptDecl *Concept = Type.getTypeConstraintConcept(); |
5099 | TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(), |
5100 | TypeLoc.getRAngleLoc()); |
5101 | TemplateArgs.addArgument( |
5102 | Loc: TemplateArgumentLoc(TemplateArgument(Deduced), |
5103 | S.Context.getTrivialTypeSourceInfo( |
5104 | T: Deduced, Loc: TypeLoc.getNameLoc()))); |
5105 | for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I) |
5106 | TemplateArgs.addArgument(Loc: TypeLoc.getArgLoc(i: I)); |
5107 | |
5108 | Sema::CheckTemplateArgumentInfo CTAI; |
5109 | if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs, |
5110 | /*DefaultArgs=*/{}, |
5111 | /*PartialTemplateArgs=*/false, CTAI)) |
5112 | return true; |
5113 | MultiLevelTemplateArgumentList MLTAL(Concept, CTAI.CanonicalConverted, |
5114 | /*Final=*/false); |
5115 | // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so |
5116 | // that the template arguments of the constraint can be preserved. For |
5117 | // example: |
5118 | // |
5119 | // template <class T> |
5120 | // concept C = []<D U = void>() { return true; }(); |
5121 | // |
5122 | // We need the argument for T while evaluating type constraint D in |
5123 | // building the CallExpr to the lambda. |
5124 | EnterExpressionEvaluationContext EECtx( |
5125 | S, Sema::ExpressionEvaluationContext::Unevaluated, |
5126 | ImplicitConceptSpecializationDecl::Create( |
5127 | C: S.getASTContext(), DC: Concept->getDeclContext(), SL: Concept->getLocation(), |
5128 | ConvertedArgs: CTAI.CanonicalConverted)); |
5129 | if (S.CheckConstraintSatisfaction( |
5130 | Concept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL, |
5131 | TypeLoc.getLocalSourceRange(), Satisfaction)) |
5132 | return true; |
5133 | if (!Satisfaction.IsSatisfied) { |
5134 | std::string Buf; |
5135 | llvm::raw_string_ostream OS(Buf); |
5136 | OS << "'"<< Concept->getName(); |
5137 | if (TypeLoc.hasExplicitTemplateArgs()) { |
5138 | printTemplateArgumentList( |
5139 | OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(), |
5140 | Type.getTypeConstraintConcept()->getTemplateParameters()); |
5141 | } |
5142 | OS << "'"; |
5143 | S.Diag(TypeLoc.getConceptNameLoc(), |
5144 | diag::err_placeholder_constraints_not_satisfied) |
5145 | << Deduced << Buf << TypeLoc.getLocalSourceRange(); |
5146 | S.DiagnoseUnsatisfiedConstraint(Satisfaction); |
5147 | return true; |
5148 | } |
5149 | return false; |
5150 | } |
5151 | |
5152 | TemplateDeductionResult |
5153 | Sema::DeduceAutoType(TypeLoc Type, Expr *Init, QualType &Result, |
5154 | TemplateDeductionInfo &Info, bool DependentDeduction, |
5155 | bool IgnoreConstraints, |
5156 | TemplateSpecCandidateSet *FailedTSC) { |
5157 | assert(DependentDeduction || Info.getDeducedDepth() == 0); |
5158 | if (Init->containsErrors()) |
5159 | return TemplateDeductionResult::AlreadyDiagnosed; |
5160 | |
5161 | const AutoType *AT = Type.getType()->getContainedAutoType(); |
5162 | assert(AT); |
5163 | |
5164 | if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) { |
5165 | ExprResult NonPlaceholder = CheckPlaceholderExpr(E: Init); |
5166 | if (NonPlaceholder.isInvalid()) |
5167 | return TemplateDeductionResult::AlreadyDiagnosed; |
5168 | Init = NonPlaceholder.get(); |
5169 | } |
5170 | |
5171 | DependentAuto DependentResult = { |
5172 | /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()}; |
5173 | |
5174 | if (!DependentDeduction && |
5175 | (Type.getType()->isDependentType() || Init->isTypeDependent() || |
5176 | Init->containsUnexpandedParameterPack())) { |
5177 | Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL: Type); |
5178 | assert(!Result.isNull() && "substituting DependentTy can't fail"); |
5179 | return TemplateDeductionResult::Success; |
5180 | } |
5181 | |
5182 | // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode. |
5183 | auto *String = dyn_cast<StringLiteral>(Val: Init); |
5184 | if (getLangOpts().C23 && String && Type.getType()->isArrayType()) { |
5185 | Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier); |
5186 | TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData()); |
5187 | Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL); |
5188 | assert(!Result.isNull() && "substituting DependentTy can't fail"); |
5189 | return TemplateDeductionResult::Success; |
5190 | } |
5191 | |
5192 | // Emit a warning if 'auto*' is used in pedantic and in C23 mode. |
5193 | if (getLangOpts().C23 && Type.getType()->isPointerType()) { |
5194 | Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier); |
5195 | } |
5196 | |
5197 | auto *InitList = dyn_cast<InitListExpr>(Val: Init); |
5198 | if (!getLangOpts().CPlusPlus && InitList) { |
5199 | Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c) |
5200 | << (int)AT->getKeyword() << getLangOpts().C23; |
5201 | return TemplateDeductionResult::AlreadyDiagnosed; |
5202 | } |
5203 | |
5204 | // Deduce type of TemplParam in Func(Init) |
5205 | SmallVector<DeducedTemplateArgument, 1> Deduced; |
5206 | Deduced.resize(N: 1); |
5207 | |
5208 | // If deduction failed, don't diagnose if the initializer is dependent; it |
5209 | // might acquire a matching type in the instantiation. |
5210 | auto DeductionFailed = [&](TemplateDeductionResult TDK) { |
5211 | if (Init->isTypeDependent()) { |
5212 | Result = |
5213 | SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL: Type); |
5214 | assert(!Result.isNull() && "substituting DependentTy can't fail"); |
5215 | return TemplateDeductionResult::Success; |
5216 | } |
5217 | return TDK; |
5218 | }; |
5219 | |
5220 | SmallVector<OriginalCallArg, 4> OriginalCallArgs; |
5221 | |
5222 | QualType DeducedType; |
5223 | // If this is a 'decltype(auto)' specifier, do the decltype dance. |
5224 | if (AT->isDecltypeAuto()) { |
5225 | if (InitList) { |
5226 | Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list); |
5227 | return TemplateDeductionResult::AlreadyDiagnosed; |
5228 | } |
5229 | |
5230 | DeducedType = getDecltypeForExpr(E: Init); |
5231 | assert(!DeducedType.isNull()); |
5232 | } else { |
5233 | LocalInstantiationScope InstScope(*this); |
5234 | |
5235 | // Build template<class TemplParam> void Func(FuncParam); |
5236 | SourceLocation Loc = Init->getExprLoc(); |
5237 | TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create( |
5238 | C: Context, DC: nullptr, KeyLoc: SourceLocation(), NameLoc: Loc, D: Info.getDeducedDepth(), P: 0, |
5239 | Id: nullptr, Typename: false, ParameterPack: false, HasTypeConstraint: false); |
5240 | QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0); |
5241 | NamedDecl *TemplParamPtr = TemplParam; |
5242 | FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt( |
5243 | Context, Loc, Loc, TemplParamPtr, Loc, nullptr); |
5244 | |
5245 | if (InitList) { |
5246 | // Notionally, we substitute std::initializer_list<T> for 'auto' and |
5247 | // deduce against that. Such deduction only succeeds if removing |
5248 | // cv-qualifiers and references results in std::initializer_list<T>. |
5249 | if (!Type.getType().getNonReferenceType()->getAs<AutoType>()) |
5250 | return TemplateDeductionResult::Invalid; |
5251 | |
5252 | SourceRange DeducedFromInitRange; |
5253 | for (Expr *Init : InitList->inits()) { |
5254 | // Resolving a core issue: a braced-init-list containing any designators |
5255 | // is a non-deduced context. |
5256 | if (isa<DesignatedInitExpr>(Val: Init)) |
5257 | return TemplateDeductionResult::Invalid; |
5258 | if (auto TDK = DeduceTemplateArgumentsFromCallArgument( |
5259 | S&: *this, TemplateParams: TemplateParamsSt.get(), FirstInnerIndex: 0, ParamType: TemplArg, ArgType: Init->getType(), |
5260 | ArgClassification: Init->Classify(Ctx&: getASTContext()), Arg: Init, Info, Deduced, |
5261 | OriginalCallArgs, |
5262 | /*Decomposed=*/DecomposedParam: true, |
5263 | /*ArgIdx=*/0, /*TDF=*/0); |
5264 | TDK != TemplateDeductionResult::Success) { |
5265 | if (TDK == TemplateDeductionResult::Inconsistent) { |
5266 | Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction) |
5267 | << Info.FirstArg << Info.SecondArg << DeducedFromInitRange |
5268 | << Init->getSourceRange(); |
5269 | return DeductionFailed(TemplateDeductionResult::AlreadyDiagnosed); |
5270 | } |
5271 | return DeductionFailed(TDK); |
5272 | } |
5273 | |
5274 | if (DeducedFromInitRange.isInvalid() && |
5275 | Deduced[0].getKind() != TemplateArgument::Null) |
5276 | DeducedFromInitRange = Init->getSourceRange(); |
5277 | } |
5278 | } else { |
5279 | if (!getLangOpts().CPlusPlus && Init->refersToBitField()) { |
5280 | Diag(Loc, diag::err_auto_bitfield); |
5281 | return TemplateDeductionResult::AlreadyDiagnosed; |
5282 | } |
5283 | QualType FuncParam = |
5284 | SubstituteDeducedTypeTransform(*this, TemplArg).Apply(TL: Type); |
5285 | assert(!FuncParam.isNull() && |
5286 | "substituting template parameter for 'auto' failed"); |
5287 | if (auto TDK = DeduceTemplateArgumentsFromCallArgument( |
5288 | S&: *this, TemplateParams: TemplateParamsSt.get(), FirstInnerIndex: 0, ParamType: FuncParam, ArgType: Init->getType(), |
5289 | ArgClassification: Init->Classify(Ctx&: getASTContext()), Arg: Init, Info, Deduced, |
5290 | OriginalCallArgs, |
5291 | /*Decomposed=*/DecomposedParam: false, /*ArgIdx=*/0, /*TDF=*/0, FailedTSC); |
5292 | TDK != TemplateDeductionResult::Success) |
5293 | return DeductionFailed(TDK); |
5294 | } |
5295 | |
5296 | // Could be null if somehow 'auto' appears in a non-deduced context. |
5297 | if (Deduced[0].getKind() != TemplateArgument::Type) |
5298 | return DeductionFailed(TemplateDeductionResult::Incomplete); |
5299 | DeducedType = Deduced[0].getAsType(); |
5300 | |
5301 | if (InitList) { |
5302 | DeducedType = BuildStdInitializerList(Element: DeducedType, Loc); |
5303 | if (DeducedType.isNull()) |
5304 | return TemplateDeductionResult::AlreadyDiagnosed; |
5305 | } |
5306 | } |
5307 | |
5308 | if (!Result.isNull()) { |
5309 | if (!Context.hasSameType(T1: DeducedType, T2: Result)) { |
5310 | Info.FirstArg = Result; |
5311 | Info.SecondArg = DeducedType; |
5312 | return DeductionFailed(TemplateDeductionResult::Inconsistent); |
5313 | } |
5314 | DeducedType = Context.getCommonSugaredType(X: Result, Y: DeducedType); |
5315 | } |
5316 | |
5317 | if (AT->isConstrained() && !IgnoreConstraints && |
5318 | CheckDeducedPlaceholderConstraints( |
5319 | *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType)) |
5320 | return TemplateDeductionResult::AlreadyDiagnosed; |
5321 | |
5322 | Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(TL: Type); |
5323 | if (Result.isNull()) |
5324 | return TemplateDeductionResult::AlreadyDiagnosed; |
5325 | |
5326 | // Check that the deduced argument type is compatible with the original |
5327 | // argument type per C++ [temp.deduct.call]p4. |
5328 | QualType DeducedA = InitList ? Deduced[0].getAsType() : Result; |
5329 | for (const OriginalCallArg &OriginalArg : OriginalCallArgs) { |
5330 | assert((bool)InitList == OriginalArg.DecomposedParam && |
5331 | "decomposed non-init-list in auto deduction?"); |
5332 | if (auto TDK = |
5333 | CheckOriginalCallArgDeduction(S&: *this, Info, OriginalArg, DeducedA); |
5334 | TDK != TemplateDeductionResult::Success) { |
5335 | Result = QualType(); |
5336 | return DeductionFailed(TDK); |
5337 | } |
5338 | } |
5339 | |
5340 | return TemplateDeductionResult::Success; |
5341 | } |
5342 | |
5343 | QualType Sema::SubstAutoType(QualType TypeWithAuto, |
5344 | QualType TypeToReplaceAuto) { |
5345 | assert(TypeToReplaceAuto != Context.DependentTy); |
5346 | return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto) |
5347 | .TransformType(TypeWithAuto); |
5348 | } |
5349 | |
5350 | TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, |
5351 | QualType TypeToReplaceAuto) { |
5352 | assert(TypeToReplaceAuto != Context.DependentTy); |
5353 | return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto) |
5354 | .TransformType(TypeWithAuto); |
5355 | } |
5356 | |
5357 | QualType Sema::SubstAutoTypeDependent(QualType TypeWithAuto) { |
5358 | return SubstituteDeducedTypeTransform(*this, DependentAuto{.IsPack: false}) |
5359 | .TransformType(TypeWithAuto); |
5360 | } |
5361 | |
5362 | TypeSourceInfo * |
5363 | Sema::SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto) { |
5364 | return SubstituteDeducedTypeTransform(*this, DependentAuto{.IsPack: false}) |
5365 | .TransformType(TypeWithAuto); |
5366 | } |
5367 | |
5368 | QualType Sema::ReplaceAutoType(QualType TypeWithAuto, |
5369 | QualType TypeToReplaceAuto) { |
5370 | return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto, |
5371 | /*UseTypeSugar*/ false) |
5372 | .TransformType(TypeWithAuto); |
5373 | } |
5374 | |
5375 | TypeSourceInfo *Sema::ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, |
5376 | QualType TypeToReplaceAuto) { |
5377 | return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto, |
5378 | /*UseTypeSugar*/ false) |
5379 | .TransformType(TypeWithAuto); |
5380 | } |
5381 | |
5382 | void Sema::DiagnoseAutoDeductionFailure(const VarDecl *VDecl, |
5383 | const Expr *Init) { |
5384 | if (isa<InitListExpr>(Init)) |
5385 | Diag(VDecl->getLocation(), |
5386 | VDecl->isInitCapture() |
5387 | ? diag::err_init_capture_deduction_failure_from_init_list |
5388 | : diag::err_auto_var_deduction_failure_from_init_list) |
5389 | << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange(); |
5390 | else |
5391 | Diag(VDecl->getLocation(), |
5392 | VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure |
5393 | : diag::err_auto_var_deduction_failure) |
5394 | << VDecl->getDeclName() << VDecl->getType() << Init->getType() |
5395 | << Init->getSourceRange(); |
5396 | } |
5397 | |
5398 | bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, |
5399 | bool Diagnose) { |
5400 | assert(FD->getReturnType()->isUndeducedType()); |
5401 | |
5402 | // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)' |
5403 | // within the return type from the call operator's type. |
5404 | if (isLambdaConversionOperator(FD)) { |
5405 | CXXRecordDecl *Lambda = cast<CXXMethodDecl>(Val: FD)->getParent(); |
5406 | FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); |
5407 | |
5408 | // For a generic lambda, instantiate the call operator if needed. |
5409 | if (auto *Args = FD->getTemplateSpecializationArgs()) { |
5410 | CallOp = InstantiateFunctionDeclaration( |
5411 | FTD: CallOp->getDescribedFunctionTemplate(), Args, Loc); |
5412 | if (!CallOp || CallOp->isInvalidDecl()) |
5413 | return true; |
5414 | |
5415 | // We might need to deduce the return type by instantiating the definition |
5416 | // of the operator() function. |
5417 | if (CallOp->getReturnType()->isUndeducedType()) { |
5418 | runWithSufficientStackSpace(Loc, Fn: [&] { |
5419 | InstantiateFunctionDefinition(PointOfInstantiation: Loc, Function: CallOp); |
5420 | }); |
5421 | } |
5422 | } |
5423 | |
5424 | if (CallOp->isInvalidDecl()) |
5425 | return true; |
5426 | assert(!CallOp->getReturnType()->isUndeducedType() && |
5427 | "failed to deduce lambda return type"); |
5428 | |
5429 | // Build the new return type from scratch. |
5430 | CallingConv RetTyCC = FD->getReturnType() |
5431 | ->getPointeeType() |
5432 | ->castAs<FunctionType>() |
5433 | ->getCallConv(); |
5434 | QualType RetType = getLambdaConversionFunctionResultType( |
5435 | CallOpType: CallOp->getType()->castAs<FunctionProtoType>(), CC: RetTyCC); |
5436 | if (FD->getReturnType()->getAs<PointerType>()) |
5437 | RetType = Context.getPointerType(T: RetType); |
5438 | else { |
5439 | assert(FD->getReturnType()->getAs<BlockPointerType>()); |
5440 | RetType = Context.getBlockPointerType(T: RetType); |
5441 | } |
5442 | Context.adjustDeducedFunctionResultType(FD, ResultType: RetType); |
5443 | return false; |
5444 | } |
5445 | |
5446 | if (FD->getTemplateInstantiationPattern()) { |
5447 | runWithSufficientStackSpace(Loc, Fn: [&] { |
5448 | InstantiateFunctionDefinition(PointOfInstantiation: Loc, Function: FD); |
5449 | }); |
5450 | } |
5451 | |
5452 | bool StillUndeduced = FD->getReturnType()->isUndeducedType(); |
5453 | if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) { |
5454 | Diag(Loc, diag::err_auto_fn_used_before_defined) << FD; |
5455 | Diag(FD->getLocation(), diag::note_callee_decl) << FD; |
5456 | } |
5457 | |
5458 | return StillUndeduced; |
5459 | } |
5460 | |
5461 | bool Sema::CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD, |
5462 | SourceLocation Loc) { |
5463 | assert(FD->isImmediateEscalating()); |
5464 | |
5465 | if (isLambdaConversionOperator(FD)) { |
5466 | CXXRecordDecl *Lambda = cast<CXXMethodDecl>(Val: FD)->getParent(); |
5467 | FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); |
5468 | |
5469 | // For a generic lambda, instantiate the call operator if needed. |
5470 | if (auto *Args = FD->getTemplateSpecializationArgs()) { |
5471 | CallOp = InstantiateFunctionDeclaration( |
5472 | FTD: CallOp->getDescribedFunctionTemplate(), Args, Loc); |
5473 | if (!CallOp || CallOp->isInvalidDecl()) |
5474 | return true; |
5475 | runWithSufficientStackSpace( |
5476 | Loc, Fn: [&] { InstantiateFunctionDefinition(PointOfInstantiation: Loc, Function: CallOp); }); |
5477 | } |
5478 | return CallOp->isInvalidDecl(); |
5479 | } |
5480 | |
5481 | if (FD->getTemplateInstantiationPattern()) { |
5482 | runWithSufficientStackSpace( |
5483 | Loc, Fn: [&] { InstantiateFunctionDefinition(PointOfInstantiation: Loc, Function: FD); }); |
5484 | } |
5485 | return false; |
5486 | } |
5487 | |
5488 | static QualType GetImplicitObjectParameterType(ASTContext &Context, |
5489 | const CXXMethodDecl *Method, |
5490 | QualType RawType, |
5491 | bool IsOtherRvr) { |
5492 | // C++20 [temp.func.order]p3.1, p3.2: |
5493 | // - The type X(M) is "rvalue reference to cv A" if the optional |
5494 | // ref-qualifier of M is && or if M has no ref-qualifier and the |
5495 | // positionally-corresponding parameter of the other transformed template |
5496 | // has rvalue reference type; if this determination depends recursively |
5497 | // upon whether X(M) is an rvalue reference type, it is not considered to |
5498 | // have rvalue reference type. |
5499 | // |
5500 | // - Otherwise, X(M) is "lvalue reference to cv A". |
5501 | assert(Method && !Method->isExplicitObjectMemberFunction() && |
5502 | "expected a member function with no explicit object parameter"); |
5503 | |
5504 | RawType = Context.getQualifiedType(T: RawType, Qs: Method->getMethodQualifiers()); |
5505 | if (Method->getRefQualifier() == RQ_RValue || |
5506 | (IsOtherRvr && Method->getRefQualifier() == RQ_None)) |
5507 | return Context.getRValueReferenceType(T: RawType); |
5508 | return Context.getLValueReferenceType(T: RawType); |
5509 | } |
5510 | |
5511 | static TemplateDeductionResult CheckDeductionConsistency( |
5512 | Sema &S, FunctionTemplateDecl *FTD, UnsignedOrNone ArgIdx, QualType P, |
5513 | QualType A, ArrayRef<TemplateArgument> DeducedArgs, bool CheckConsistency) { |
5514 | MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs, |
5515 | /*Final=*/true); |
5516 | Sema::ArgPackSubstIndexRAII PackIndex( |
5517 | S, |
5518 | ArgIdx ? ::getPackIndexForParam(S, FunctionTemplate: FTD, Args: MLTAL, ParamIdx: *ArgIdx) : std::nullopt); |
5519 | bool IsIncompleteSubstitution = false; |
5520 | // FIXME: A substitution can be incomplete on a non-structural part of the |
5521 | // type. Use the canonical type for now, until the TemplateInstantiator can |
5522 | // deal with that. |
5523 | QualType InstP = S.SubstType(P.getCanonicalType(), MLTAL, FTD->getLocation(), |
5524 | FTD->getDeclName(), &IsIncompleteSubstitution); |
5525 | if (InstP.isNull() && !IsIncompleteSubstitution) |
5526 | return TemplateDeductionResult::SubstitutionFailure; |
5527 | if (!CheckConsistency) |
5528 | return TemplateDeductionResult::Success; |
5529 | if (IsIncompleteSubstitution) |
5530 | return TemplateDeductionResult::Incomplete; |
5531 | |
5532 | // [temp.deduct.call]/4 - Check we produced a consistent deduction. |
5533 | // This handles just the cases that can appear when partial ordering. |
5534 | if (auto *PA = dyn_cast<PackExpansionType>(Val&: A); |
5535 | PA && !isa<PackExpansionType>(Val: InstP)) |
5536 | A = PA->getPattern(); |
5537 | if (!S.Context.hasSameType( |
5538 | T1: S.Context.getUnqualifiedArrayType(T: InstP.getNonReferenceType()), |
5539 | T2: S.Context.getUnqualifiedArrayType(T: A.getNonReferenceType()))) |
5540 | return TemplateDeductionResult::NonDeducedMismatch; |
5541 | return TemplateDeductionResult::Success; |
5542 | } |
5543 | |
5544 | template <class T> |
5545 | static TemplateDeductionResult FinishTemplateArgumentDeduction( |
5546 | Sema &S, FunctionTemplateDecl *FTD, |
5547 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
5548 | TemplateDeductionInfo &Info, T &&CheckDeductionConsistency) { |
5549 | EnterExpressionEvaluationContext Unevaluated( |
5550 | S, Sema::ExpressionEvaluationContext::Unevaluated); |
5551 | Sema::SFINAETrap Trap(S); |
5552 | |
5553 | Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD)); |
5554 | |
5555 | // C++26 [temp.deduct.type]p2: |
5556 | // [...] or if any template argument remains neither deduced nor |
5557 | // explicitly specified, template argument deduction fails. |
5558 | bool IsIncomplete = false; |
5559 | Sema::CheckTemplateArgumentInfo CTAI(/*PartialOrdering=*/true); |
5560 | if (auto Result = ConvertDeducedTemplateArguments( |
5561 | S, FTD, FTD->getTemplateParameters(), /*IsDeduced=*/true, Deduced, |
5562 | Info, CTAI, |
5563 | /*CurrentInstantiationScope=*/nullptr, |
5564 | /*NumAlreadyConverted=*/0, &IsIncomplete); |
5565 | Result != TemplateDeductionResult::Success) |
5566 | return Result; |
5567 | |
5568 | // Form the template argument list from the deduced template arguments. |
5569 | TemplateArgumentList *SugaredDeducedArgumentList = |
5570 | TemplateArgumentList::CreateCopy(Context&: S.Context, Args: CTAI.SugaredConverted); |
5571 | TemplateArgumentList *CanonicalDeducedArgumentList = |
5572 | TemplateArgumentList::CreateCopy(Context&: S.Context, Args: CTAI.CanonicalConverted); |
5573 | |
5574 | Info.reset(NewDeducedSugared: SugaredDeducedArgumentList, NewDeducedCanonical: CanonicalDeducedArgumentList); |
5575 | |
5576 | // Substitute the deduced template arguments into the argument |
5577 | // and verify that the instantiated argument is both valid |
5578 | // and equivalent to the parameter. |
5579 | LocalInstantiationScope InstScope(S); |
5580 | |
5581 | if (auto TDR = CheckDeductionConsistency(S, FTD, CTAI.SugaredConverted); |
5582 | TDR != TemplateDeductionResult::Success) |
5583 | return TDR; |
5584 | |
5585 | return Trap.hasErrorOccurred() ? TemplateDeductionResult::SubstitutionFailure |
5586 | : TemplateDeductionResult::Success; |
5587 | } |
5588 | |
5589 | /// Determine whether the function template \p FT1 is at least as |
5590 | /// specialized as \p FT2. |
5591 | static bool isAtLeastAsSpecializedAs( |
5592 | Sema &S, SourceLocation Loc, FunctionTemplateDecl *FT1, |
5593 | FunctionTemplateDecl *FT2, TemplatePartialOrderingContext TPOC, |
5594 | ArrayRef<QualType> Args1, ArrayRef<QualType> Args2, bool Args1Offset) { |
5595 | FunctionDecl *FD1 = FT1->getTemplatedDecl(); |
5596 | FunctionDecl *FD2 = FT2->getTemplatedDecl(); |
5597 | const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>(); |
5598 | const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>(); |
5599 | assert(Proto1 && Proto2 && "Function templates must have prototypes"); |
5600 | |
5601 | // C++26 [temp.deduct.partial]p3: |
5602 | // The types used to determine the ordering depend on the context in which |
5603 | // the partial ordering is done: |
5604 | // - In the context of a function call, the types used are those function |
5605 | // parameter types for which the function call has arguments. |
5606 | // - In the context of a call to a conversion operator, the return types |
5607 | // of the conversion function templates are used. |
5608 | // - In other contexts (14.6.6.2) the function template's function type |
5609 | // is used. |
5610 | |
5611 | if (TPOC == TPOC_Other) { |
5612 | // We wouldn't be partial ordering these candidates if these didn't match. |
5613 | assert(Proto1->getMethodQuals() == Proto2->getMethodQuals() && |
5614 | Proto1->getRefQualifier() == Proto2->getRefQualifier() && |
5615 | Proto1->isVariadic() == Proto2->isVariadic() && |
5616 | "shouldn't partial order functions with different qualifiers in a " |
5617 | "context where the function type is used"); |
5618 | |
5619 | assert(Args1.empty() && Args2.empty() && |
5620 | "Only call context should have arguments"); |
5621 | Args1 = Proto1->getParamTypes(); |
5622 | Args2 = Proto2->getParamTypes(); |
5623 | } |
5624 | |
5625 | TemplateParameterList *TemplateParams = FT2->getTemplateParameters(); |
5626 | SmallVector<DeducedTemplateArgument, 4> Deduced(TemplateParams->size()); |
5627 | TemplateDeductionInfo Info(Loc); |
5628 | |
5629 | bool HasDeducedAnyParamFromReturnType = false; |
5630 | if (TPOC != TPOC_Call) { |
5631 | if (DeduceTemplateArgumentsByTypeMatch( |
5632 | S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(), |
5633 | Info, Deduced, TDF_None, PartialOrderingKind::Call, |
5634 | /*DeducedFromArrayBound=*/false, |
5635 | &HasDeducedAnyParamFromReturnType) != |
5636 | TemplateDeductionResult::Success) |
5637 | return false; |
5638 | } |
5639 | |
5640 | llvm::SmallBitVector HasDeducedParam; |
5641 | if (TPOC != TPOC_Conversion) { |
5642 | HasDeducedParam.resize(N: Args2.size()); |
5643 | if (DeduceTemplateArguments(S, TemplateParams, Params: Args2, Args: Args1, Info, Deduced, |
5644 | TDF: TDF_None, POK: PartialOrderingKind::Call, |
5645 | /*HasDeducedAnyParam=*/nullptr, |
5646 | HasDeducedParam: &HasDeducedParam) != |
5647 | TemplateDeductionResult::Success) |
5648 | return false; |
5649 | } |
5650 | |
5651 | SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); |
5652 | Sema::InstantiatingTemplate Inst( |
5653 | S, Info.getLocation(), FT2, DeducedArgs, |
5654 | Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info); |
5655 | if (Inst.isInvalid()) |
5656 | return false; |
5657 | |
5658 | bool AtLeastAsSpecialized; |
5659 | S.runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] { |
5660 | AtLeastAsSpecialized = |
5661 | ::FinishTemplateArgumentDeduction( |
5662 | S, FTD: FT2, Deduced, Info, |
5663 | CheckDeductionConsistency: [&](Sema &S, FunctionTemplateDecl *FTD, |
5664 | ArrayRef<TemplateArgument> DeducedArgs) { |
5665 | // As a provisional fix for a core issue that does not |
5666 | // exist yet, which may be related to CWG2160, only check the |
5667 | // consistency of parameters and return types which participated |
5668 | // in deduction. We will still try to substitute them though. |
5669 | if (TPOC != TPOC_Call) { |
5670 | if (auto TDR = ::CheckDeductionConsistency( |
5671 | S, FTD, /*ArgIdx=*/std::nullopt, |
5672 | Proto2->getReturnType(), Proto1->getReturnType(), |
5673 | DeducedArgs, |
5674 | /*CheckConsistency=*/HasDeducedAnyParamFromReturnType); |
5675 | TDR != TemplateDeductionResult::Success) |
5676 | return TDR; |
5677 | } |
5678 | |
5679 | if (TPOC == TPOC_Conversion) |
5680 | return TemplateDeductionResult::Success; |
5681 | |
5682 | return ::DeduceForEachType( |
5683 | S, TemplateParams, Args2, Args1, Info, Deduced, |
5684 | PartialOrderingKind::Call, /*FinishingDeduction=*/true, |
5685 | [&](Sema &S, TemplateParameterList *, int ParamIdx, |
5686 | UnsignedOrNone ArgIdx, QualType P, QualType A, |
5687 | TemplateDeductionInfo &Info, |
5688 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
5689 | PartialOrderingKind) { |
5690 | if (ArgIdx && *ArgIdx >= static_cast<unsigned>(Args1Offset)) |
5691 | ArgIdx = *ArgIdx - Args1Offset; |
5692 | else |
5693 | ArgIdx = std::nullopt; |
5694 | return ::CheckDeductionConsistency( |
5695 | S, FTD, ArgIdx, P, A, DeducedArgs, |
5696 | /*CheckConsistency=*/HasDeducedParam[ParamIdx]); |
5697 | }); |
5698 | }) == TemplateDeductionResult::Success; |
5699 | }); |
5700 | if (!AtLeastAsSpecialized) |
5701 | return false; |
5702 | |
5703 | // C++0x [temp.deduct.partial]p11: |
5704 | // In most cases, all template parameters must have values in order for |
5705 | // deduction to succeed, but for partial ordering purposes a template |
5706 | // parameter may remain without a value provided it is not used in the |
5707 | // types being used for partial ordering. [ Note: a template parameter used |
5708 | // in a non-deduced context is considered used. -end note] |
5709 | unsigned ArgIdx = 0, NumArgs = Deduced.size(); |
5710 | for (; ArgIdx != NumArgs; ++ArgIdx) |
5711 | if (Deduced[ArgIdx].isNull()) |
5712 | break; |
5713 | |
5714 | if (ArgIdx == NumArgs) { |
5715 | // All template arguments were deduced. FT1 is at least as specialized |
5716 | // as FT2. |
5717 | return true; |
5718 | } |
5719 | |
5720 | // Figure out which template parameters were used. |
5721 | llvm::SmallBitVector UsedParameters(TemplateParams->size()); |
5722 | switch (TPOC) { |
5723 | case TPOC_Call: |
5724 | for (unsigned I = 0, N = Args2.size(); I != N; ++I) |
5725 | ::MarkUsedTemplateParameters(Ctx&: S.Context, T: Args2[I], /*OnlyDeduced=*/false, |
5726 | Level: TemplateParams->getDepth(), Deduced&: UsedParameters); |
5727 | break; |
5728 | |
5729 | case TPOC_Conversion: |
5730 | ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), |
5731 | /*OnlyDeduced=*/false, |
5732 | TemplateParams->getDepth(), UsedParameters); |
5733 | break; |
5734 | |
5735 | case TPOC_Other: |
5736 | // We do not deduce template arguments from the exception specification |
5737 | // when determining the primary template of a function template |
5738 | // specialization or when taking the address of a function template. |
5739 | // Therefore, we do not mark template parameters in the exception |
5740 | // specification as used during partial ordering to prevent the following |
5741 | // from being ambiguous: |
5742 | // |
5743 | // template<typename T, typename U> |
5744 | // void f(U) noexcept(noexcept(T())); // #1 |
5745 | // |
5746 | // template<typename T> |
5747 | // void f(T*) noexcept; // #2 |
5748 | // |
5749 | // template<> |
5750 | // void f<int>(int*) noexcept; // explicit specialization of #2 |
5751 | // |
5752 | // Although there is no corresponding wording in the standard, this seems |
5753 | // to be the intended behavior given the definition of |
5754 | // 'deduction substitution loci' in [temp.deduct]. |
5755 | ::MarkUsedTemplateParameters( |
5756 | S.Context, |
5757 | S.Context.getFunctionTypeWithExceptionSpec(Orig: FD2->getType(), ESI: EST_None), |
5758 | /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters); |
5759 | break; |
5760 | } |
5761 | |
5762 | for (; ArgIdx != NumArgs; ++ArgIdx) |
5763 | // If this argument had no value deduced but was used in one of the types |
5764 | // used for partial ordering, then deduction fails. |
5765 | if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx]) |
5766 | return false; |
5767 | |
5768 | return true; |
5769 | } |
5770 | |
5771 | enum class MoreSpecializedTrailingPackTieBreakerResult { Equal, Less, More }; |
5772 | |
5773 | // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that |
5774 | // there is no wording or even resolution for this issue. |
5775 | static MoreSpecializedTrailingPackTieBreakerResult |
5776 | getMoreSpecializedTrailingPackTieBreaker( |
5777 | const TemplateSpecializationType *TST1, |
5778 | const TemplateSpecializationType *TST2) { |
5779 | ArrayRef<TemplateArgument> As1 = TST1->template_arguments(), |
5780 | As2 = TST2->template_arguments(); |
5781 | const TemplateArgument &TA1 = As1.back(), &TA2 = As2.back(); |
5782 | bool IsPack = TA1.getKind() == TemplateArgument::Pack; |
5783 | assert(IsPack == (TA2.getKind() == TemplateArgument::Pack)); |
5784 | if (!IsPack) |
5785 | return MoreSpecializedTrailingPackTieBreakerResult::Equal; |
5786 | assert(As1.size() == As2.size()); |
5787 | |
5788 | unsigned PackSize1 = TA1.pack_size(), PackSize2 = TA2.pack_size(); |
5789 | bool IsPackExpansion1 = |
5790 | PackSize1 && TA1.pack_elements().back().isPackExpansion(); |
5791 | bool IsPackExpansion2 = |
5792 | PackSize2 && TA2.pack_elements().back().isPackExpansion(); |
5793 | if (PackSize1 == PackSize2 && IsPackExpansion1 == IsPackExpansion2) |
5794 | return MoreSpecializedTrailingPackTieBreakerResult::Equal; |
5795 | if (PackSize1 > PackSize2 && IsPackExpansion1) |
5796 | return MoreSpecializedTrailingPackTieBreakerResult::More; |
5797 | if (PackSize1 < PackSize2 && IsPackExpansion2) |
5798 | return MoreSpecializedTrailingPackTieBreakerResult::Less; |
5799 | return MoreSpecializedTrailingPackTieBreakerResult::Equal; |
5800 | } |
5801 | |
5802 | FunctionTemplateDecl *Sema::getMoreSpecializedTemplate( |
5803 | FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, |
5804 | TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, |
5805 | QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed, |
5806 | bool PartialOverloading) { |
5807 | SmallVector<QualType> Args1; |
5808 | SmallVector<QualType> Args2; |
5809 | const FunctionDecl *FD1 = FT1->getTemplatedDecl(); |
5810 | const FunctionDecl *FD2 = FT2->getTemplatedDecl(); |
5811 | bool ShouldConvert1 = false; |
5812 | bool ShouldConvert2 = false; |
5813 | bool Args1Offset = false; |
5814 | bool Args2Offset = false; |
5815 | QualType Obj1Ty; |
5816 | QualType Obj2Ty; |
5817 | if (TPOC == TPOC_Call) { |
5818 | const FunctionProtoType *Proto1 = |
5819 | FD1->getType()->castAs<FunctionProtoType>(); |
5820 | const FunctionProtoType *Proto2 = |
5821 | FD2->getType()->castAs<FunctionProtoType>(); |
5822 | |
5823 | // - In the context of a function call, the function parameter types are |
5824 | // used. |
5825 | const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(Val: FD1); |
5826 | const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(Val: FD2); |
5827 | // C++20 [temp.func.order]p3 |
5828 | // [...] Each function template M that is a member function is |
5829 | // considered to have a new first parameter of type |
5830 | // X(M), described below, inserted in its function parameter list. |
5831 | // |
5832 | // Note that we interpret "that is a member function" as |
5833 | // "that is a member function with no expicit object argument". |
5834 | // Otherwise the ordering rules for methods with expicit objet arguments |
5835 | // against anything else make no sense. |
5836 | |
5837 | bool NonStaticMethod1 = Method1 && !Method1->isStatic(), |
5838 | NonStaticMethod2 = Method2 && !Method2->isStatic(); |
5839 | |
5840 | auto Params1Begin = Proto1->param_type_begin(), |
5841 | Params2Begin = Proto2->param_type_begin(); |
5842 | |
5843 | size_t NumComparedArguments = NumCallArguments1; |
5844 | |
5845 | if (auto OO = FD1->getOverloadedOperator(); |
5846 | (NonStaticMethod1 && NonStaticMethod2) || |
5847 | (OO != OO_None && OO != OO_Call && OO != OO_Subscript)) { |
5848 | ShouldConvert1 = |
5849 | NonStaticMethod1 && !Method1->hasCXXExplicitFunctionObjectParameter(); |
5850 | ShouldConvert2 = |
5851 | NonStaticMethod2 && !Method2->hasCXXExplicitFunctionObjectParameter(); |
5852 | NumComparedArguments += 1; |
5853 | |
5854 | if (ShouldConvert1) { |
5855 | bool IsRValRef2 = |
5856 | ShouldConvert2 |
5857 | ? Method2->getRefQualifier() == RQ_RValue |
5858 | : Proto2->param_type_begin()[0]->isRValueReferenceType(); |
5859 | // Compare 'this' from Method1 against first parameter from Method2. |
5860 | Obj1Ty = GetImplicitObjectParameterType(Context&: this->Context, Method: Method1, |
5861 | RawType: RawObj1Ty, IsOtherRvr: IsRValRef2); |
5862 | Args1.push_back(Elt: Obj1Ty); |
5863 | Args1Offset = true; |
5864 | } |
5865 | if (ShouldConvert2) { |
5866 | bool IsRValRef1 = |
5867 | ShouldConvert1 |
5868 | ? Method1->getRefQualifier() == RQ_RValue |
5869 | : Proto1->param_type_begin()[0]->isRValueReferenceType(); |
5870 | // Compare 'this' from Method2 against first parameter from Method1. |
5871 | Obj2Ty = GetImplicitObjectParameterType(Context&: this->Context, Method: Method2, |
5872 | RawType: RawObj2Ty, IsOtherRvr: IsRValRef1); |
5873 | Args2.push_back(Elt: Obj2Ty); |
5874 | Args2Offset = true; |
5875 | } |
5876 | } else { |
5877 | if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter()) |
5878 | Params1Begin += 1; |
5879 | if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter()) |
5880 | Params2Begin += 1; |
5881 | } |
5882 | Args1.insert(Args1.end(), Params1Begin, Proto1->param_type_end()); |
5883 | Args2.insert(Args2.end(), Params2Begin, Proto2->param_type_end()); |
5884 | |
5885 | // C++ [temp.func.order]p5: |
5886 | // The presence of unused ellipsis and default arguments has no effect on |
5887 | // the partial ordering of function templates. |
5888 | Args1.resize(N: std::min(a: Args1.size(), b: NumComparedArguments)); |
5889 | Args2.resize(N: std::min(a: Args2.size(), b: NumComparedArguments)); |
5890 | |
5891 | if (Reversed) |
5892 | std::reverse(first: Args2.begin(), last: Args2.end()); |
5893 | } else { |
5894 | assert(!Reversed && "Only call context could have reversed arguments"); |
5895 | } |
5896 | bool Better1 = isAtLeastAsSpecializedAs(S&: *this, Loc, FT1, FT2, TPOC, Args1, |
5897 | Args2, Args1Offset: Args2Offset); |
5898 | bool Better2 = isAtLeastAsSpecializedAs(S&: *this, Loc, FT1: FT2, FT2: FT1, TPOC, Args1: Args2, |
5899 | Args2: Args1, Args1Offset); |
5900 | // C++ [temp.deduct.partial]p10: |
5901 | // F is more specialized than G if F is at least as specialized as G and G |
5902 | // is not at least as specialized as F. |
5903 | if (Better1 != Better2) // We have a clear winner |
5904 | return Better1 ? FT1 : FT2; |
5905 | |
5906 | if (!Better1 && !Better2) // Neither is better than the other |
5907 | return nullptr; |
5908 | |
5909 | // C++ [temp.deduct.partial]p11: |
5910 | // ... and if G has a trailing function parameter pack for which F does not |
5911 | // have a corresponding parameter, and if F does not have a trailing |
5912 | // function parameter pack, then F is more specialized than G. |
5913 | |
5914 | SmallVector<QualType> Param1; |
5915 | Param1.reserve(N: FD1->param_size() + ShouldConvert1); |
5916 | if (ShouldConvert1) |
5917 | Param1.push_back(Elt: Obj1Ty); |
5918 | for (const auto &P : FD1->parameters()) |
5919 | Param1.push_back(Elt: P->getType()); |
5920 | |
5921 | SmallVector<QualType> Param2; |
5922 | Param2.reserve(N: FD2->param_size() + ShouldConvert2); |
5923 | if (ShouldConvert2) |
5924 | Param2.push_back(Elt: Obj2Ty); |
5925 | for (const auto &P : FD2->parameters()) |
5926 | Param2.push_back(Elt: P->getType()); |
5927 | |
5928 | unsigned NumParams1 = Param1.size(); |
5929 | unsigned NumParams2 = Param2.size(); |
5930 | |
5931 | bool Variadic1 = |
5932 | FD1->param_size() && FD1->parameters().back()->isParameterPack(); |
5933 | bool Variadic2 = |
5934 | FD2->param_size() && FD2->parameters().back()->isParameterPack(); |
5935 | if (Variadic1 != Variadic2) { |
5936 | if (Variadic1 && NumParams1 > NumParams2) |
5937 | return FT2; |
5938 | if (Variadic2 && NumParams2 > NumParams1) |
5939 | return FT1; |
5940 | } |
5941 | |
5942 | // Skip this tie breaker if we are performing overload resolution with partial |
5943 | // arguments, as this breaks some assumptions about how closely related the |
5944 | // candidates are. |
5945 | for (int i = 0, e = std::min(a: NumParams1, b: NumParams2); |
5946 | !PartialOverloading && i < e; ++i) { |
5947 | QualType T1 = Param1[i].getCanonicalType(); |
5948 | QualType T2 = Param2[i].getCanonicalType(); |
5949 | auto *TST1 = dyn_cast<TemplateSpecializationType>(Val&: T1); |
5950 | auto *TST2 = dyn_cast<TemplateSpecializationType>(Val&: T2); |
5951 | if (!TST1 || !TST2) |
5952 | continue; |
5953 | switch (getMoreSpecializedTrailingPackTieBreaker(TST1, TST2)) { |
5954 | case MoreSpecializedTrailingPackTieBreakerResult::Less: |
5955 | return FT1; |
5956 | case MoreSpecializedTrailingPackTieBreakerResult::More: |
5957 | return FT2; |
5958 | case MoreSpecializedTrailingPackTieBreakerResult::Equal: |
5959 | continue; |
5960 | } |
5961 | llvm_unreachable( |
5962 | "unknown MoreSpecializedTrailingPackTieBreakerResult value"); |
5963 | } |
5964 | |
5965 | if (!Context.getLangOpts().CPlusPlus20) |
5966 | return nullptr; |
5967 | |
5968 | // Match GCC on not implementing [temp.func.order]p6.2.1. |
5969 | |
5970 | // C++20 [temp.func.order]p6: |
5971 | // If deduction against the other template succeeds for both transformed |
5972 | // templates, constraints can be considered as follows: |
5973 | |
5974 | // C++20 [temp.func.order]p6.1: |
5975 | // If their template-parameter-lists (possibly including template-parameters |
5976 | // invented for an abbreviated function template ([dcl.fct])) or function |
5977 | // parameter lists differ in length, neither template is more specialized |
5978 | // than the other. |
5979 | TemplateParameterList *TPL1 = FT1->getTemplateParameters(); |
5980 | TemplateParameterList *TPL2 = FT2->getTemplateParameters(); |
5981 | if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2) |
5982 | return nullptr; |
5983 | |
5984 | // C++20 [temp.func.order]p6.2.2: |
5985 | // Otherwise, if the corresponding template-parameters of the |
5986 | // template-parameter-lists are not equivalent ([temp.over.link]) or if the |
5987 | // function parameters that positionally correspond between the two |
5988 | // templates are not of the same type, neither template is more specialized |
5989 | // than the other. |
5990 | if (!TemplateParameterListsAreEqual(New: TPL1, Old: TPL2, Complain: false, |
5991 | Kind: Sema::TPL_TemplateParamsEquivalent)) |
5992 | return nullptr; |
5993 | |
5994 | // [dcl.fct]p5: |
5995 | // Any top-level cv-qualifiers modifying a parameter type are deleted when |
5996 | // forming the function type. |
5997 | for (unsigned i = 0; i < NumParams1; ++i) |
5998 | if (!Context.hasSameUnqualifiedType(T1: Param1[i], T2: Param2[i])) |
5999 | return nullptr; |
6000 | |
6001 | // C++20 [temp.func.order]p6.3: |
6002 | // Otherwise, if the context in which the partial ordering is done is |
6003 | // that of a call to a conversion function and the return types of the |
6004 | // templates are not the same, then neither template is more specialized |
6005 | // than the other. |
6006 | if (TPOC == TPOC_Conversion && |
6007 | !Context.hasSameType(T1: FD1->getReturnType(), T2: FD2->getReturnType())) |
6008 | return nullptr; |
6009 | |
6010 | llvm::SmallVector<AssociatedConstraint, 3> AC1, AC2; |
6011 | FT1->getAssociatedConstraints(AC1); |
6012 | FT2->getAssociatedConstraints(AC2); |
6013 | bool AtLeastAsConstrained1, AtLeastAsConstrained2; |
6014 | if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1)) |
6015 | return nullptr; |
6016 | if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2)) |
6017 | return nullptr; |
6018 | if (AtLeastAsConstrained1 == AtLeastAsConstrained2) |
6019 | return nullptr; |
6020 | return AtLeastAsConstrained1 ? FT1 : FT2; |
6021 | } |
6022 | |
6023 | UnresolvedSetIterator Sema::getMostSpecialized( |
6024 | UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd, |
6025 | TemplateSpecCandidateSet &FailedCandidates, |
6026 | SourceLocation Loc, const PartialDiagnostic &NoneDiag, |
6027 | const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, |
6028 | bool Complain, QualType TargetType) { |
6029 | if (SpecBegin == SpecEnd) { |
6030 | if (Complain) { |
6031 | Diag(Loc, NoneDiag); |
6032 | FailedCandidates.NoteCandidates(S&: *this, Loc); |
6033 | } |
6034 | return SpecEnd; |
6035 | } |
6036 | |
6037 | if (SpecBegin + 1 == SpecEnd) |
6038 | return SpecBegin; |
6039 | |
6040 | // Find the function template that is better than all of the templates it |
6041 | // has been compared to. |
6042 | UnresolvedSetIterator Best = SpecBegin; |
6043 | FunctionTemplateDecl *BestTemplate |
6044 | = cast<FunctionDecl>(Val: *Best)->getPrimaryTemplate(); |
6045 | assert(BestTemplate && "Not a function template specialization?"); |
6046 | for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) { |
6047 | FunctionTemplateDecl *Challenger |
6048 | = cast<FunctionDecl>(Val: *I)->getPrimaryTemplate(); |
6049 | assert(Challenger && "Not a function template specialization?"); |
6050 | if (declaresSameEntity(getMoreSpecializedTemplate(FT1: BestTemplate, FT2: Challenger, |
6051 | Loc, TPOC: TPOC_Other, NumCallArguments1: 0), |
6052 | Challenger)) { |
6053 | Best = I; |
6054 | BestTemplate = Challenger; |
6055 | } |
6056 | } |
6057 | |
6058 | // Make sure that the "best" function template is more specialized than all |
6059 | // of the others. |
6060 | bool Ambiguous = false; |
6061 | for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { |
6062 | FunctionTemplateDecl *Challenger |
6063 | = cast<FunctionDecl>(Val: *I)->getPrimaryTemplate(); |
6064 | if (I != Best && |
6065 | !declaresSameEntity(getMoreSpecializedTemplate(FT1: BestTemplate, FT2: Challenger, |
6066 | Loc, TPOC: TPOC_Other, NumCallArguments1: 0), |
6067 | BestTemplate)) { |
6068 | Ambiguous = true; |
6069 | break; |
6070 | } |
6071 | } |
6072 | |
6073 | if (!Ambiguous) { |
6074 | // We found an answer. Return it. |
6075 | return Best; |
6076 | } |
6077 | |
6078 | // Diagnose the ambiguity. |
6079 | if (Complain) { |
6080 | Diag(Loc, AmbigDiag); |
6081 | |
6082 | // FIXME: Can we order the candidates in some sane way? |
6083 | for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { |
6084 | PartialDiagnostic PD = CandidateDiag; |
6085 | const auto *FD = cast<FunctionDecl>(Val: *I); |
6086 | PD << FD << getTemplateArgumentBindingsText( |
6087 | FD->getPrimaryTemplate()->getTemplateParameters(), |
6088 | *FD->getTemplateSpecializationArgs()); |
6089 | if (!TargetType.isNull()) |
6090 | HandleFunctionTypeMismatch(PDiag&: PD, FromType: FD->getType(), ToType: TargetType); |
6091 | Diag((*I)->getLocation(), PD); |
6092 | } |
6093 | } |
6094 | |
6095 | return SpecEnd; |
6096 | } |
6097 | |
6098 | FunctionDecl *Sema::getMoreConstrainedFunction(FunctionDecl *FD1, |
6099 | FunctionDecl *FD2) { |
6100 | assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() && |
6101 | "not for function templates"); |
6102 | assert(!FD1->isFunctionTemplateSpecialization() || |
6103 | (isa<CXXConversionDecl, CXXConstructorDecl>(FD1))); |
6104 | assert(!FD2->isFunctionTemplateSpecialization() || |
6105 | (isa<CXXConversionDecl, CXXConstructorDecl>(FD2))); |
6106 | |
6107 | FunctionDecl *F1 = FD1; |
6108 | if (FunctionDecl *P = FD1->getTemplateInstantiationPattern(ForDefinition: false)) |
6109 | F1 = P; |
6110 | |
6111 | FunctionDecl *F2 = FD2; |
6112 | if (FunctionDecl *P = FD2->getTemplateInstantiationPattern(ForDefinition: false)) |
6113 | F2 = P; |
6114 | |
6115 | llvm::SmallVector<AssociatedConstraint, 1> AC1, AC2; |
6116 | F1->getAssociatedConstraints(ACs&: AC1); |
6117 | F2->getAssociatedConstraints(ACs&: AC2); |
6118 | bool AtLeastAsConstrained1, AtLeastAsConstrained2; |
6119 | if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1)) |
6120 | return nullptr; |
6121 | if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2)) |
6122 | return nullptr; |
6123 | if (AtLeastAsConstrained1 == AtLeastAsConstrained2) |
6124 | return nullptr; |
6125 | return AtLeastAsConstrained1 ? FD1 : FD2; |
6126 | } |
6127 | |
6128 | /// Determine whether one template specialization, P1, is at least as |
6129 | /// specialized than another, P2. |
6130 | /// |
6131 | /// \tparam TemplateLikeDecl The kind of P2, which must be a |
6132 | /// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl. |
6133 | /// \param T1 The injected-class-name of P1 (faked for a variable template). |
6134 | /// \param T2 The injected-class-name of P2 (faked for a variable template). |
6135 | /// \param Template The primary template of P2, in case it is a partial |
6136 | /// specialization, the same as P2 otherwise. |
6137 | template <typename TemplateLikeDecl> |
6138 | static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2, |
6139 | TemplateLikeDecl *P2, |
6140 | TemplateDecl *Template, |
6141 | TemplateDeductionInfo &Info) { |
6142 | // C++ [temp.class.order]p1: |
6143 | // For two class template partial specializations, the first is at least as |
6144 | // specialized as the second if, given the following rewrite to two |
6145 | // function templates, the first function template is at least as |
6146 | // specialized as the second according to the ordering rules for function |
6147 | // templates (14.6.6.2): |
6148 | // - the first function template has the same template parameters as the |
6149 | // first partial specialization and has a single function parameter |
6150 | // whose type is a class template specialization with the template |
6151 | // arguments of the first partial specialization, and |
6152 | // - the second function template has the same template parameters as the |
6153 | // second partial specialization and has a single function parameter |
6154 | // whose type is a class template specialization with the template |
6155 | // arguments of the second partial specialization. |
6156 | // |
6157 | // Rather than synthesize function templates, we merely perform the |
6158 | // equivalent partial ordering by performing deduction directly on |
6159 | // the template arguments of the class template partial |
6160 | // specializations. This computation is slightly simpler than the |
6161 | // general problem of function template partial ordering, because |
6162 | // class template partial specializations are more constrained. We |
6163 | // know that every template parameter is deducible from the class |
6164 | // template partial specialization's template arguments, for |
6165 | // example. |
6166 | SmallVector<DeducedTemplateArgument, 4> Deduced; |
6167 | |
6168 | // Determine whether P1 is at least as specialized as P2. |
6169 | Deduced.resize(P2->getTemplateParameters()->size()); |
6170 | if (DeduceTemplateArgumentsByTypeMatch( |
6171 | S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None, |
6172 | PartialOrderingKind::Call, /*DeducedFromArrayBound=*/false, |
6173 | /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success) |
6174 | return false; |
6175 | |
6176 | SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), |
6177 | Deduced.end()); |
6178 | Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs, |
6179 | Info); |
6180 | if (Inst.isInvalid()) |
6181 | return false; |
6182 | |
6183 | ArrayRef<TemplateArgument> |
6184 | Ps = cast<TemplateSpecializationType>(Val&: T2)->template_arguments(), |
6185 | As = cast<TemplateSpecializationType>(Val&: T1)->template_arguments(); |
6186 | |
6187 | Sema::SFINAETrap Trap(S); |
6188 | |
6189 | TemplateDeductionResult Result; |
6190 | S.runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] { |
6191 | Result = ::FinishTemplateArgumentDeduction( |
6192 | S, P2, P2->getTemplateParameters(), Template, |
6193 | /*IsPartialOrdering=*/true, Ps, As, Deduced, Info, |
6194 | /*CopyDeducedArgs=*/false); |
6195 | }); |
6196 | |
6197 | if (Result != TemplateDeductionResult::Success) |
6198 | return false; |
6199 | |
6200 | if (Trap.hasErrorOccurred()) |
6201 | return false; |
6202 | |
6203 | return true; |
6204 | } |
6205 | |
6206 | namespace { |
6207 | // A dummy class to return nullptr instead of P2 when performing "more |
6208 | // specialized than primary" check. |
6209 | struct GetP2 { |
6210 | template <typename T1, typename T2, |
6211 | std::enable_if_t<std::is_same_v<T1, T2>, bool> = true> |
6212 | T2 *operator()(T1 *, T2 *P2) { |
6213 | return P2; |
6214 | } |
6215 | template <typename T1, typename T2, |
6216 | std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true> |
6217 | T1 *operator()(T1 *, T2 *) { |
6218 | return nullptr; |
6219 | } |
6220 | }; |
6221 | |
6222 | // The assumption is that two template argument lists have the same size. |
6223 | struct TemplateArgumentListAreEqual { |
6224 | ASTContext &Ctx; |
6225 | TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {} |
6226 | |
6227 | template <typename T1, typename T2, |
6228 | std::enable_if_t<std::is_same_v<T1, T2>, bool> = true> |
6229 | bool operator()(T1 *PS1, T2 *PS2) { |
6230 | ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(), |
6231 | Args2 = PS2->getTemplateArgs().asArray(); |
6232 | |
6233 | for (unsigned I = 0, E = Args1.size(); I < E; ++I) { |
6234 | // We use profile, instead of structural comparison of the arguments, |
6235 | // because canonicalization can't do the right thing for dependent |
6236 | // expressions. |
6237 | llvm::FoldingSetNodeID IDA, IDB; |
6238 | Args1[I].Profile(ID&: IDA, Context: Ctx); |
6239 | Args2[I].Profile(ID&: IDB, Context: Ctx); |
6240 | if (IDA != IDB) |
6241 | return false; |
6242 | } |
6243 | return true; |
6244 | } |
6245 | |
6246 | template <typename T1, typename T2, |
6247 | std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true> |
6248 | bool operator()(T1 *Spec, T2 *Primary) { |
6249 | ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(), |
6250 | Args2 = Primary->getInjectedTemplateArgs(Ctx); |
6251 | |
6252 | for (unsigned I = 0, E = Args1.size(); I < E; ++I) { |
6253 | // We use profile, instead of structural comparison of the arguments, |
6254 | // because canonicalization can't do the right thing for dependent |
6255 | // expressions. |
6256 | llvm::FoldingSetNodeID IDA, IDB; |
6257 | Args1[I].Profile(ID&: IDA, Context: Ctx); |
6258 | // Unlike the specialization arguments, the injected arguments are not |
6259 | // always canonical. |
6260 | Ctx.getCanonicalTemplateArgument(Arg: Args2[I]).Profile(ID&: IDB, Context: Ctx); |
6261 | if (IDA != IDB) |
6262 | return false; |
6263 | } |
6264 | return true; |
6265 | } |
6266 | }; |
6267 | } // namespace |
6268 | |
6269 | /// Returns the more specialized template specialization between T1/P1 and |
6270 | /// T2/P2. |
6271 | /// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial |
6272 | /// specialization and T2/P2 is the primary template. |
6273 | /// - otherwise, both T1/P1 and T2/P2 are the partial specialization. |
6274 | /// |
6275 | /// \param T1 the type of the first template partial specialization |
6276 | /// |
6277 | /// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second |
6278 | /// template partial specialization; otherwise, the type of the |
6279 | /// primary template. |
6280 | /// |
6281 | /// \param P1 the first template partial specialization |
6282 | /// |
6283 | /// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template |
6284 | /// partial specialization; otherwise, the primary template. |
6285 | /// |
6286 | /// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is |
6287 | /// more specialized, returns nullptr if P1 is not more specialized. |
6288 | /// - otherwise, returns the more specialized template partial |
6289 | /// specialization. If neither partial specialization is more |
6290 | /// specialized, returns NULL. |
6291 | template <typename TemplateLikeDecl, typename PrimaryDel> |
6292 | static TemplateLikeDecl * |
6293 | getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1, |
6294 | PrimaryDel *P2, TemplateDeductionInfo &Info) { |
6295 | constexpr bool IsMoreSpecialThanPrimaryCheck = |
6296 | !std::is_same_v<TemplateLikeDecl, PrimaryDel>; |
6297 | |
6298 | TemplateDecl *P2T; |
6299 | if constexpr (IsMoreSpecialThanPrimaryCheck) |
6300 | P2T = P2; |
6301 | else |
6302 | P2T = P2->getSpecializedTemplate(); |
6303 | |
6304 | bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, P2T, Info); |
6305 | if (IsMoreSpecialThanPrimaryCheck && !Better1) |
6306 | return nullptr; |
6307 | |
6308 | bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1, |
6309 | P1->getSpecializedTemplate(), Info); |
6310 | if (IsMoreSpecialThanPrimaryCheck && !Better2) |
6311 | return P1; |
6312 | |
6313 | // C++ [temp.deduct.partial]p10: |
6314 | // F is more specialized than G if F is at least as specialized as G and G |
6315 | // is not at least as specialized as F. |
6316 | if (Better1 != Better2) // We have a clear winner |
6317 | return Better1 ? P1 : GetP2()(P1, P2); |
6318 | |
6319 | if (!Better1 && !Better2) |
6320 | return nullptr; |
6321 | |
6322 | switch (getMoreSpecializedTrailingPackTieBreaker( |
6323 | TST1: cast<TemplateSpecializationType>(Val&: T1), |
6324 | TST2: cast<TemplateSpecializationType>(Val&: T2))) { |
6325 | case MoreSpecializedTrailingPackTieBreakerResult::Less: |
6326 | return P1; |
6327 | case MoreSpecializedTrailingPackTieBreakerResult::More: |
6328 | return GetP2()(P1, P2); |
6329 | case MoreSpecializedTrailingPackTieBreakerResult::Equal: |
6330 | break; |
6331 | } |
6332 | |
6333 | if (!S.Context.getLangOpts().CPlusPlus20) |
6334 | return nullptr; |
6335 | |
6336 | // Match GCC on not implementing [temp.func.order]p6.2.1. |
6337 | |
6338 | // C++20 [temp.func.order]p6: |
6339 | // If deduction against the other template succeeds for both transformed |
6340 | // templates, constraints can be considered as follows: |
6341 | |
6342 | TemplateParameterList *TPL1 = P1->getTemplateParameters(); |
6343 | TemplateParameterList *TPL2 = P2->getTemplateParameters(); |
6344 | if (TPL1->size() != TPL2->size()) |
6345 | return nullptr; |
6346 | |
6347 | // C++20 [temp.func.order]p6.2.2: |
6348 | // Otherwise, if the corresponding template-parameters of the |
6349 | // template-parameter-lists are not equivalent ([temp.over.link]) or if the |
6350 | // function parameters that positionally correspond between the two |
6351 | // templates are not of the same type, neither template is more specialized |
6352 | // than the other. |
6353 | if (!S.TemplateParameterListsAreEqual(New: TPL1, Old: TPL2, Complain: false, |
6354 | Kind: Sema::TPL_TemplateParamsEquivalent)) |
6355 | return nullptr; |
6356 | |
6357 | if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2)) |
6358 | return nullptr; |
6359 | |
6360 | llvm::SmallVector<AssociatedConstraint, 3> AC1, AC2; |
6361 | P1->getAssociatedConstraints(AC1); |
6362 | P2->getAssociatedConstraints(AC2); |
6363 | bool AtLeastAsConstrained1, AtLeastAsConstrained2; |
6364 | if (S.IsAtLeastAsConstrained(D1: P1, AC1, D2: P2, AC2, Result&: AtLeastAsConstrained1) || |
6365 | (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1)) |
6366 | return nullptr; |
6367 | if (S.IsAtLeastAsConstrained(D1: P2, AC1: AC2, D2: P1, AC2: AC1, Result&: AtLeastAsConstrained2)) |
6368 | return nullptr; |
6369 | if (AtLeastAsConstrained1 == AtLeastAsConstrained2) |
6370 | return nullptr; |
6371 | return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2); |
6372 | } |
6373 | |
6374 | ClassTemplatePartialSpecializationDecl * |
6375 | Sema::getMoreSpecializedPartialSpecialization( |
6376 | ClassTemplatePartialSpecializationDecl *PS1, |
6377 | ClassTemplatePartialSpecializationDecl *PS2, |
6378 | SourceLocation Loc) { |
6379 | QualType PT1 = PS1->getInjectedSpecializationType().getCanonicalType(); |
6380 | QualType PT2 = PS2->getInjectedSpecializationType().getCanonicalType(); |
6381 | |
6382 | TemplateDeductionInfo Info(Loc); |
6383 | return getMoreSpecialized(S&: *this, T1: PT1, T2: PT2, P1: PS1, P2: PS2, Info); |
6384 | } |
6385 | |
6386 | bool Sema::isMoreSpecializedThanPrimary( |
6387 | ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) { |
6388 | ClassTemplateDecl *Primary = Spec->getSpecializedTemplate(); |
6389 | QualType PrimaryT = |
6390 | Primary->getInjectedClassNameSpecialization().getCanonicalType(); |
6391 | QualType PartialT = Spec->getInjectedSpecializationType().getCanonicalType(); |
6392 | |
6393 | ClassTemplatePartialSpecializationDecl *MaybeSpec = |
6394 | getMoreSpecialized(S&: *this, T1: PartialT, T2: PrimaryT, P1: Spec, P2: Primary, Info); |
6395 | if (MaybeSpec) |
6396 | Info.clearSFINAEDiagnostic(); |
6397 | return MaybeSpec; |
6398 | } |
6399 | |
6400 | VarTemplatePartialSpecializationDecl * |
6401 | Sema::getMoreSpecializedPartialSpecialization( |
6402 | VarTemplatePartialSpecializationDecl *PS1, |
6403 | VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) { |
6404 | // Pretend the variable template specializations are class template |
6405 | // specializations and form a fake injected class name type for comparison. |
6406 | assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && |
6407 | "the partial specializations being compared should specialize" |
6408 | " the same template."); |
6409 | TemplateName Name(PS1->getSpecializedTemplate()->getCanonicalDecl()); |
6410 | QualType PT1 = Context.getCanonicalTemplateSpecializationType( |
6411 | T: Name, CanonicalArgs: PS1->getTemplateArgs().asArray()); |
6412 | QualType PT2 = Context.getCanonicalTemplateSpecializationType( |
6413 | T: Name, CanonicalArgs: PS2->getTemplateArgs().asArray()); |
6414 | |
6415 | TemplateDeductionInfo Info(Loc); |
6416 | return getMoreSpecialized(S&: *this, T1: PT1, T2: PT2, P1: PS1, P2: PS2, Info); |
6417 | } |
6418 | |
6419 | bool Sema::isMoreSpecializedThanPrimary( |
6420 | VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) { |
6421 | VarTemplateDecl *Primary = Spec->getSpecializedTemplate(); |
6422 | TemplateName Name(Primary->getCanonicalDecl()); |
6423 | |
6424 | SmallVector<TemplateArgument, 8> PrimaryCanonArgs( |
6425 | Primary->getInjectedTemplateArgs(Context)); |
6426 | Context.canonicalizeTemplateArguments(Args: PrimaryCanonArgs); |
6427 | |
6428 | QualType PrimaryT = |
6429 | Context.getCanonicalTemplateSpecializationType(T: Name, CanonicalArgs: PrimaryCanonArgs); |
6430 | QualType PartialT = Context.getCanonicalTemplateSpecializationType( |
6431 | T: Name, CanonicalArgs: Spec->getTemplateArgs().asArray()); |
6432 | |
6433 | VarTemplatePartialSpecializationDecl *MaybeSpec = |
6434 | getMoreSpecialized(S&: *this, T1: PartialT, T2: PrimaryT, P1: Spec, P2: Primary, Info); |
6435 | if (MaybeSpec) |
6436 | Info.clearSFINAEDiagnostic(); |
6437 | return MaybeSpec; |
6438 | } |
6439 | |
6440 | bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs( |
6441 | TemplateParameterList *P, TemplateDecl *PArg, TemplateDecl *AArg, |
6442 | const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, |
6443 | bool PartialOrdering, bool *StrictPackMatch) { |
6444 | // C++1z [temp.arg.template]p4: (DR 150) |
6445 | // A template template-parameter P is at least as specialized as a |
6446 | // template template-argument A if, given the following rewrite to two |
6447 | // function templates... |
6448 | |
6449 | // Rather than synthesize function templates, we merely perform the |
6450 | // equivalent partial ordering by performing deduction directly on |
6451 | // the template parameter lists of the template template parameters. |
6452 | // |
6453 | TemplateParameterList *A = AArg->getTemplateParameters(); |
6454 | |
6455 | Sema::InstantiatingTemplate Inst( |
6456 | *this, ArgLoc, Sema::InstantiatingTemplate::PartialOrderingTTP(), PArg, |
6457 | SourceRange(P->getTemplateLoc(), P->getRAngleLoc())); |
6458 | if (Inst.isInvalid()) |
6459 | return false; |
6460 | |
6461 | // Given an invented class template X with the template parameter list of |
6462 | // A (including default arguments): |
6463 | // - Each function template has a single function parameter whose type is |
6464 | // a specialization of X with template arguments corresponding to the |
6465 | // template parameters from the respective function template |
6466 | SmallVector<TemplateArgument, 8> AArgs(A->getInjectedTemplateArgs(Context)); |
6467 | |
6468 | // Check P's arguments against A's parameter list. This will fill in default |
6469 | // template arguments as needed. AArgs are already correct by construction. |
6470 | // We can't just use CheckTemplateIdType because that will expand alias |
6471 | // templates. |
6472 | SmallVector<TemplateArgument, 4> PArgs(P->getInjectedTemplateArgs(Context)); |
6473 | { |
6474 | TemplateArgumentListInfo PArgList(P->getLAngleLoc(), |
6475 | P->getRAngleLoc()); |
6476 | for (unsigned I = 0, N = P->size(); I != N; ++I) { |
6477 | // Unwrap packs that getInjectedTemplateArgs wrapped around pack |
6478 | // expansions, to form an "as written" argument list. |
6479 | TemplateArgument Arg = PArgs[I]; |
6480 | if (Arg.getKind() == TemplateArgument::Pack) { |
6481 | assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion()); |
6482 | Arg = *Arg.pack_begin(); |
6483 | } |
6484 | PArgList.addArgument(Loc: getTrivialTemplateArgumentLoc( |
6485 | Arg, NTTPType: QualType(), Loc: P->getParam(Idx: I)->getLocation())); |
6486 | } |
6487 | PArgs.clear(); |
6488 | |
6489 | // C++1z [temp.arg.template]p3: |
6490 | // If the rewrite produces an invalid type, then P is not at least as |
6491 | // specialized as A. |
6492 | CheckTemplateArgumentInfo CTAI( |
6493 | /*PartialOrdering=*/false, /*MatchingTTP=*/true); |
6494 | CTAI.SugaredConverted = std::move(PArgs); |
6495 | if (CheckTemplateArgumentList(Template: AArg, TemplateLoc: ArgLoc, TemplateArgs&: PArgList, DefaultArgs, |
6496 | /*PartialTemplateArgs=*/false, CTAI, |
6497 | /*UpdateArgsWithConversions=*/true, |
6498 | /*ConstraintsNotSatisfied=*/nullptr)) |
6499 | return false; |
6500 | PArgs = std::move(CTAI.SugaredConverted); |
6501 | if (StrictPackMatch) |
6502 | *StrictPackMatch |= CTAI.StrictPackMatch; |
6503 | } |
6504 | |
6505 | // Determine whether P1 is at least as specialized as P2. |
6506 | TemplateDeductionInfo Info(ArgLoc, A->getDepth()); |
6507 | SmallVector<DeducedTemplateArgument, 4> Deduced; |
6508 | Deduced.resize(N: A->size()); |
6509 | |
6510 | // ... the function template corresponding to P is at least as specialized |
6511 | // as the function template corresponding to A according to the partial |
6512 | // ordering rules for function templates. |
6513 | |
6514 | // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when |
6515 | // applying the partial ordering rules for function templates on |
6516 | // the rewritten template template parameters: |
6517 | // - In a deduced context, the matching of packs versus fixed-size needs to |
6518 | // be inverted between Ps and As. On non-deduced context, matching needs to |
6519 | // happen both ways, according to [temp.arg.template]p3, but this is |
6520 | // currently implemented as a special case elsewhere. |
6521 | switch (::DeduceTemplateArguments( |
6522 | S&: *this, TemplateParams: A, Ps: AArgs, As: PArgs, Info, Deduced, |
6523 | /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/true, |
6524 | PackFold: PartialOrdering ? PackFold::ArgumentToParameter : PackFold::Both, |
6525 | /*HasDeducedAnyParam=*/nullptr)) { |
6526 | case clang::TemplateDeductionResult::Success: |
6527 | if (StrictPackMatch && Info.hasStrictPackMatch()) |
6528 | *StrictPackMatch = true; |
6529 | break; |
6530 | |
6531 | case TemplateDeductionResult::MiscellaneousDeductionFailure: |
6532 | Diag(AArg->getLocation(), diag::err_template_param_list_different_arity) |
6533 | << (A->size() > P->size()) << /*isTemplateTemplateParameter=*/true |
6534 | << SourceRange(A->getTemplateLoc(), P->getRAngleLoc()); |
6535 | return false; |
6536 | case TemplateDeductionResult::NonDeducedMismatch: |
6537 | Diag(AArg->getLocation(), diag::err_non_deduced_mismatch) |
6538 | << Info.FirstArg << Info.SecondArg; |
6539 | return false; |
6540 | case TemplateDeductionResult::Inconsistent: |
6541 | Diag(getAsNamedDecl(Info.Param)->getLocation(), |
6542 | diag::err_inconsistent_deduction) |
6543 | << Info.FirstArg << Info.SecondArg; |
6544 | return false; |
6545 | case TemplateDeductionResult::AlreadyDiagnosed: |
6546 | return false; |
6547 | |
6548 | // None of these should happen for a plain deduction. |
6549 | case TemplateDeductionResult::Invalid: |
6550 | case TemplateDeductionResult::InstantiationDepth: |
6551 | case TemplateDeductionResult::Incomplete: |
6552 | case TemplateDeductionResult::IncompletePack: |
6553 | case TemplateDeductionResult::Underqualified: |
6554 | case TemplateDeductionResult::SubstitutionFailure: |
6555 | case TemplateDeductionResult::DeducedMismatch: |
6556 | case TemplateDeductionResult::DeducedMismatchNested: |
6557 | case TemplateDeductionResult::TooManyArguments: |
6558 | case TemplateDeductionResult::TooFewArguments: |
6559 | case TemplateDeductionResult::InvalidExplicitArguments: |
6560 | case TemplateDeductionResult::NonDependentConversionFailure: |
6561 | case TemplateDeductionResult::ConstraintsNotSatisfied: |
6562 | case TemplateDeductionResult::CUDATargetMismatch: |
6563 | llvm_unreachable("Unexpected Result"); |
6564 | } |
6565 | |
6566 | TemplateDeductionResult TDK; |
6567 | runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] { |
6568 | TDK = ::FinishTemplateArgumentDeduction( |
6569 | *this, AArg, AArg->getTemplateParameters(), AArg, PartialOrdering, |
6570 | AArgs, PArgs, Deduced, Info, /*CopyDeducedArgs=*/false); |
6571 | }); |
6572 | switch (TDK) { |
6573 | case TemplateDeductionResult::Success: |
6574 | return true; |
6575 | |
6576 | // It doesn't seem possible to get a non-deduced mismatch when partial |
6577 | // ordering TTPs, except with an invalid template parameter list which has |
6578 | // a parameter after a pack. |
6579 | case TemplateDeductionResult::NonDeducedMismatch: |
6580 | assert(PArg->isInvalidDecl() && "Unexpected NonDeducedMismatch"); |
6581 | return false; |
6582 | |
6583 | // Substitution failures should have already been diagnosed. |
6584 | case TemplateDeductionResult::AlreadyDiagnosed: |
6585 | case TemplateDeductionResult::SubstitutionFailure: |
6586 | case TemplateDeductionResult::InstantiationDepth: |
6587 | return false; |
6588 | |
6589 | // None of these should happen when just converting deduced arguments. |
6590 | case TemplateDeductionResult::Invalid: |
6591 | case TemplateDeductionResult::Incomplete: |
6592 | case TemplateDeductionResult::IncompletePack: |
6593 | case TemplateDeductionResult::Inconsistent: |
6594 | case TemplateDeductionResult::Underqualified: |
6595 | case TemplateDeductionResult::DeducedMismatch: |
6596 | case TemplateDeductionResult::DeducedMismatchNested: |
6597 | case TemplateDeductionResult::TooManyArguments: |
6598 | case TemplateDeductionResult::TooFewArguments: |
6599 | case TemplateDeductionResult::InvalidExplicitArguments: |
6600 | case TemplateDeductionResult::NonDependentConversionFailure: |
6601 | case TemplateDeductionResult::ConstraintsNotSatisfied: |
6602 | case TemplateDeductionResult::MiscellaneousDeductionFailure: |
6603 | case TemplateDeductionResult::CUDATargetMismatch: |
6604 | llvm_unreachable("Unexpected Result"); |
6605 | } |
6606 | llvm_unreachable("Unexpected TDK"); |
6607 | } |
6608 | |
6609 | namespace { |
6610 | struct MarkUsedTemplateParameterVisitor : DynamicRecursiveASTVisitor { |
6611 | llvm::SmallBitVector &Used; |
6612 | unsigned Depth; |
6613 | |
6614 | MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used, |
6615 | unsigned Depth) |
6616 | : Used(Used), Depth(Depth) { } |
6617 | |
6618 | bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override { |
6619 | if (T->getDepth() == Depth) |
6620 | Used[T->getIndex()] = true; |
6621 | return true; |
6622 | } |
6623 | |
6624 | bool TraverseTemplateName(TemplateName Template) override { |
6625 | if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>( |
6626 | Val: Template.getAsTemplateDecl())) |
6627 | if (TTP->getDepth() == Depth) |
6628 | Used[TTP->getIndex()] = true; |
6629 | DynamicRecursiveASTVisitor::TraverseTemplateName(Template); |
6630 | return true; |
6631 | } |
6632 | |
6633 | bool VisitDeclRefExpr(DeclRefExpr *E) override { |
6634 | if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl())) |
6635 | if (NTTP->getDepth() == Depth) |
6636 | Used[NTTP->getIndex()] = true; |
6637 | return true; |
6638 | } |
6639 | }; |
6640 | } |
6641 | |
6642 | /// Mark the template parameters that are used by the given |
6643 | /// expression. |
6644 | static void |
6645 | MarkUsedTemplateParameters(ASTContext &Ctx, |
6646 | const Expr *E, |
6647 | bool OnlyDeduced, |
6648 | unsigned Depth, |
6649 | llvm::SmallBitVector &Used) { |
6650 | if (!OnlyDeduced) { |
6651 | MarkUsedTemplateParameterVisitor(Used, Depth) |
6652 | .TraverseStmt(const_cast<Expr *>(E)); |
6653 | return; |
6654 | } |
6655 | |
6656 | // We can deduce from a pack expansion. |
6657 | if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: E)) |
6658 | E = Expansion->getPattern(); |
6659 | |
6660 | const NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(E, Depth); |
6661 | if (!NTTP) |
6662 | return; |
6663 | |
6664 | if (NTTP->getDepth() == Depth) |
6665 | Used[NTTP->getIndex()] = true; |
6666 | |
6667 | // In C++17 mode, additional arguments may be deduced from the type of a |
6668 | // non-type argument. |
6669 | if (Ctx.getLangOpts().CPlusPlus17) |
6670 | MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used); |
6671 | } |
6672 | |
6673 | /// Mark the template parameters that are used by the given |
6674 | /// nested name specifier. |
6675 | static void |
6676 | MarkUsedTemplateParameters(ASTContext &Ctx, |
6677 | NestedNameSpecifier *NNS, |
6678 | bool OnlyDeduced, |
6679 | unsigned Depth, |
6680 | llvm::SmallBitVector &Used) { |
6681 | if (!NNS) |
6682 | return; |
6683 | |
6684 | MarkUsedTemplateParameters(Ctx, NNS: NNS->getPrefix(), OnlyDeduced, Depth, |
6685 | Used); |
6686 | MarkUsedTemplateParameters(Ctx, T: QualType(NNS->getAsType(), 0), |
6687 | OnlyDeduced, Level: Depth, Deduced&: Used); |
6688 | } |
6689 | |
6690 | /// Mark the template parameters that are used by the given |
6691 | /// template name. |
6692 | static void |
6693 | MarkUsedTemplateParameters(ASTContext &Ctx, |
6694 | TemplateName Name, |
6695 | bool OnlyDeduced, |
6696 | unsigned Depth, |
6697 | llvm::SmallBitVector &Used) { |
6698 | if (TemplateDecl *Template = Name.getAsTemplateDecl()) { |
6699 | if (TemplateTemplateParmDecl *TTP |
6700 | = dyn_cast<TemplateTemplateParmDecl>(Val: Template)) { |
6701 | if (TTP->getDepth() == Depth) |
6702 | Used[TTP->getIndex()] = true; |
6703 | } |
6704 | return; |
6705 | } |
6706 | |
6707 | if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) |
6708 | MarkUsedTemplateParameters(Ctx, NNS: QTN->getQualifier(), OnlyDeduced, |
6709 | Depth, Used); |
6710 | if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) |
6711 | MarkUsedTemplateParameters(Ctx, NNS: DTN->getQualifier(), OnlyDeduced, |
6712 | Depth, Used); |
6713 | } |
6714 | |
6715 | /// Mark the template parameters that are used by the given |
6716 | /// type. |
6717 | static void |
6718 | MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, |
6719 | bool OnlyDeduced, |
6720 | unsigned Depth, |
6721 | llvm::SmallBitVector &Used) { |
6722 | if (T.isNull()) |
6723 | return; |
6724 | |
6725 | // Non-dependent types have nothing deducible |
6726 | if (!T->isDependentType()) |
6727 | return; |
6728 | |
6729 | T = Ctx.getCanonicalType(T); |
6730 | switch (T->getTypeClass()) { |
6731 | case Type::Pointer: |
6732 | MarkUsedTemplateParameters(Ctx, |
6733 | T: cast<PointerType>(Val&: T)->getPointeeType(), |
6734 | OnlyDeduced, |
6735 | Depth, |
6736 | Used); |
6737 | break; |
6738 | |
6739 | case Type::BlockPointer: |
6740 | MarkUsedTemplateParameters(Ctx, |
6741 | T: cast<BlockPointerType>(Val&: T)->getPointeeType(), |
6742 | OnlyDeduced, |
6743 | Depth, |
6744 | Used); |
6745 | break; |
6746 | |
6747 | case Type::LValueReference: |
6748 | case Type::RValueReference: |
6749 | MarkUsedTemplateParameters(Ctx, |
6750 | T: cast<ReferenceType>(Val&: T)->getPointeeType(), |
6751 | OnlyDeduced, |
6752 | Depth, |
6753 | Used); |
6754 | break; |
6755 | |
6756 | case Type::MemberPointer: { |
6757 | const MemberPointerType *MemPtr = cast<MemberPointerType>(Val: T.getTypePtr()); |
6758 | MarkUsedTemplateParameters(Ctx, T: MemPtr->getPointeeType(), OnlyDeduced, |
6759 | Depth, Used); |
6760 | MarkUsedTemplateParameters(Ctx, |
6761 | T: QualType(MemPtr->getQualifier()->getAsType(), 0), |
6762 | OnlyDeduced, Depth, Used); |
6763 | break; |
6764 | } |
6765 | |
6766 | case Type::DependentSizedArray: |
6767 | MarkUsedTemplateParameters(Ctx, |
6768 | E: cast<DependentSizedArrayType>(Val&: T)->getSizeExpr(), |
6769 | OnlyDeduced, Depth, Used); |
6770 | // Fall through to check the element type |
6771 | [[fallthrough]]; |
6772 | |
6773 | case Type::ConstantArray: |
6774 | case Type::IncompleteArray: |
6775 | case Type::ArrayParameter: |
6776 | MarkUsedTemplateParameters(Ctx, |
6777 | T: cast<ArrayType>(Val&: T)->getElementType(), |
6778 | OnlyDeduced, Depth, Used); |
6779 | break; |
6780 | case Type::Vector: |
6781 | case Type::ExtVector: |
6782 | MarkUsedTemplateParameters(Ctx, |
6783 | T: cast<VectorType>(Val&: T)->getElementType(), |
6784 | OnlyDeduced, Depth, Used); |
6785 | break; |
6786 | |
6787 | case Type::DependentVector: { |
6788 | const auto *VecType = cast<DependentVectorType>(Val&: T); |
6789 | MarkUsedTemplateParameters(Ctx, T: VecType->getElementType(), OnlyDeduced, |
6790 | Depth, Used); |
6791 | MarkUsedTemplateParameters(Ctx, E: VecType->getSizeExpr(), OnlyDeduced, Depth, |
6792 | Used); |
6793 | break; |
6794 | } |
6795 | case Type::DependentSizedExtVector: { |
6796 | const DependentSizedExtVectorType *VecType |
6797 | = cast<DependentSizedExtVectorType>(Val&: T); |
6798 | MarkUsedTemplateParameters(Ctx, T: VecType->getElementType(), OnlyDeduced, |
6799 | Depth, Used); |
6800 | MarkUsedTemplateParameters(Ctx, E: VecType->getSizeExpr(), OnlyDeduced, |
6801 | Depth, Used); |
6802 | break; |
6803 | } |
6804 | |
6805 | case Type::DependentAddressSpace: { |
6806 | const DependentAddressSpaceType *DependentASType = |
6807 | cast<DependentAddressSpaceType>(Val&: T); |
6808 | MarkUsedTemplateParameters(Ctx, T: DependentASType->getPointeeType(), |
6809 | OnlyDeduced, Depth, Used); |
6810 | MarkUsedTemplateParameters(Ctx, |
6811 | E: DependentASType->getAddrSpaceExpr(), |
6812 | OnlyDeduced, Depth, Used); |
6813 | break; |
6814 | } |
6815 | |
6816 | case Type::ConstantMatrix: { |
6817 | const ConstantMatrixType *MatType = cast<ConstantMatrixType>(Val&: T); |
6818 | MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced, |
6819 | Depth, Used); |
6820 | break; |
6821 | } |
6822 | |
6823 | case Type::DependentSizedMatrix: { |
6824 | const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(Val&: T); |
6825 | MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced, |
6826 | Depth, Used); |
6827 | MarkUsedTemplateParameters(Ctx, E: MatType->getRowExpr(), OnlyDeduced, Depth, |
6828 | Used); |
6829 | MarkUsedTemplateParameters(Ctx, E: MatType->getColumnExpr(), OnlyDeduced, |
6830 | Depth, Used); |
6831 | break; |
6832 | } |
6833 | |
6834 | case Type::FunctionProto: { |
6835 | const FunctionProtoType *Proto = cast<FunctionProtoType>(Val&: T); |
6836 | MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth, |
6837 | Used); |
6838 | for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) { |
6839 | // C++17 [temp.deduct.type]p5: |
6840 | // The non-deduced contexts are: [...] |
6841 | // -- A function parameter pack that does not occur at the end of the |
6842 | // parameter-declaration-list. |
6843 | if (!OnlyDeduced || I + 1 == N || |
6844 | !Proto->getParamType(i: I)->getAs<PackExpansionType>()) { |
6845 | MarkUsedTemplateParameters(Ctx, T: Proto->getParamType(i: I), OnlyDeduced, |
6846 | Depth, Used); |
6847 | } else { |
6848 | // FIXME: C++17 [temp.deduct.call]p1: |
6849 | // When a function parameter pack appears in a non-deduced context, |
6850 | // the type of that pack is never deduced. |
6851 | // |
6852 | // We should also track a set of "never deduced" parameters, and |
6853 | // subtract that from the list of deduced parameters after marking. |
6854 | } |
6855 | } |
6856 | if (auto *E = Proto->getNoexceptExpr()) |
6857 | MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used); |
6858 | break; |
6859 | } |
6860 | |
6861 | case Type::TemplateTypeParm: { |
6862 | const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(Val&: T); |
6863 | if (TTP->getDepth() == Depth) |
6864 | Used[TTP->getIndex()] = true; |
6865 | break; |
6866 | } |
6867 | |
6868 | case Type::SubstTemplateTypeParmPack: { |
6869 | const SubstTemplateTypeParmPackType *Subst |
6870 | = cast<SubstTemplateTypeParmPackType>(Val&: T); |
6871 | if (Subst->getReplacedParameter()->getDepth() == Depth) |
6872 | Used[Subst->getIndex()] = true; |
6873 | MarkUsedTemplateParameters(Ctx, TemplateArg: Subst->getArgumentPack(), |
6874 | OnlyDeduced, Depth, Used); |
6875 | break; |
6876 | } |
6877 | |
6878 | case Type::InjectedClassName: |
6879 | T = cast<InjectedClassNameType>(Val&: T)->getInjectedSpecializationType(); |
6880 | [[fallthrough]]; |
6881 | |
6882 | case Type::TemplateSpecialization: { |
6883 | const TemplateSpecializationType *Spec |
6884 | = cast<TemplateSpecializationType>(Val&: T); |
6885 | MarkUsedTemplateParameters(Ctx, Name: Spec->getTemplateName(), OnlyDeduced, |
6886 | Depth, Used); |
6887 | |
6888 | // C++0x [temp.deduct.type]p9: |
6889 | // If the template argument list of P contains a pack expansion that is |
6890 | // not the last template argument, the entire template argument list is a |
6891 | // non-deduced context. |
6892 | if (OnlyDeduced && |
6893 | hasPackExpansionBeforeEnd(Args: Spec->template_arguments())) |
6894 | break; |
6895 | |
6896 | for (const auto &Arg : Spec->template_arguments()) |
6897 | MarkUsedTemplateParameters(Ctx, TemplateArg: Arg, OnlyDeduced, Depth, Used); |
6898 | break; |
6899 | } |
6900 | |
6901 | case Type::Complex: |
6902 | if (!OnlyDeduced) |
6903 | MarkUsedTemplateParameters(Ctx, |
6904 | T: cast<ComplexType>(Val&: T)->getElementType(), |
6905 | OnlyDeduced, Depth, Used); |
6906 | break; |
6907 | |
6908 | case Type::Atomic: |
6909 | if (!OnlyDeduced) |
6910 | MarkUsedTemplateParameters(Ctx, |
6911 | T: cast<AtomicType>(Val&: T)->getValueType(), |
6912 | OnlyDeduced, Depth, Used); |
6913 | break; |
6914 | |
6915 | case Type::DependentName: |
6916 | if (!OnlyDeduced) |
6917 | MarkUsedTemplateParameters(Ctx, |
6918 | NNS: cast<DependentNameType>(Val&: T)->getQualifier(), |
6919 | OnlyDeduced, Depth, Used); |
6920 | break; |
6921 | |
6922 | case Type::DependentTemplateSpecialization: { |
6923 | // C++14 [temp.deduct.type]p5: |
6924 | // The non-deduced contexts are: |
6925 | // -- The nested-name-specifier of a type that was specified using a |
6926 | // qualified-id |
6927 | // |
6928 | // C++14 [temp.deduct.type]p6: |
6929 | // When a type name is specified in a way that includes a non-deduced |
6930 | // context, all of the types that comprise that type name are also |
6931 | // non-deduced. |
6932 | if (OnlyDeduced) |
6933 | break; |
6934 | |
6935 | const DependentTemplateSpecializationType *Spec |
6936 | = cast<DependentTemplateSpecializationType>(Val&: T); |
6937 | |
6938 | MarkUsedTemplateParameters(Ctx, |
6939 | NNS: Spec->getDependentTemplateName().getQualifier(), |
6940 | OnlyDeduced, Depth, Used); |
6941 | |
6942 | for (const auto &Arg : Spec->template_arguments()) |
6943 | MarkUsedTemplateParameters(Ctx, TemplateArg: Arg, OnlyDeduced, Depth, Used); |
6944 | break; |
6945 | } |
6946 | |
6947 | case Type::TypeOf: |
6948 | if (!OnlyDeduced) |
6949 | MarkUsedTemplateParameters(Ctx, T: cast<TypeOfType>(Val&: T)->getUnmodifiedType(), |
6950 | OnlyDeduced, Depth, Used); |
6951 | break; |
6952 | |
6953 | case Type::TypeOfExpr: |
6954 | if (!OnlyDeduced) |
6955 | MarkUsedTemplateParameters(Ctx, |
6956 | E: cast<TypeOfExprType>(Val&: T)->getUnderlyingExpr(), |
6957 | OnlyDeduced, Depth, Used); |
6958 | break; |
6959 | |
6960 | case Type::Decltype: |
6961 | if (!OnlyDeduced) |
6962 | MarkUsedTemplateParameters(Ctx, |
6963 | E: cast<DecltypeType>(Val&: T)->getUnderlyingExpr(), |
6964 | OnlyDeduced, Depth, Used); |
6965 | break; |
6966 | |
6967 | case Type::PackIndexing: |
6968 | if (!OnlyDeduced) { |
6969 | MarkUsedTemplateParameters(Ctx, T: cast<PackIndexingType>(Val&: T)->getPattern(), |
6970 | OnlyDeduced, Depth, Used); |
6971 | MarkUsedTemplateParameters(Ctx, E: cast<PackIndexingType>(Val&: T)->getIndexExpr(), |
6972 | OnlyDeduced, Depth, Used); |
6973 | } |
6974 | break; |
6975 | |
6976 | case Type::UnaryTransform: |
6977 | if (!OnlyDeduced) |
6978 | MarkUsedTemplateParameters(Ctx, |
6979 | T: cast<UnaryTransformType>(Val&: T)->getUnderlyingType(), |
6980 | OnlyDeduced, Depth, Used); |
6981 | break; |
6982 | |
6983 | case Type::PackExpansion: |
6984 | MarkUsedTemplateParameters(Ctx, |
6985 | T: cast<PackExpansionType>(Val&: T)->getPattern(), |
6986 | OnlyDeduced, Depth, Used); |
6987 | break; |
6988 | |
6989 | case Type::Auto: |
6990 | case Type::DeducedTemplateSpecialization: |
6991 | MarkUsedTemplateParameters(Ctx, |
6992 | T: cast<DeducedType>(Val&: T)->getDeducedType(), |
6993 | OnlyDeduced, Depth, Used); |
6994 | break; |
6995 | case Type::DependentBitInt: |
6996 | MarkUsedTemplateParameters(Ctx, |
6997 | E: cast<DependentBitIntType>(Val&: T)->getNumBitsExpr(), |
6998 | OnlyDeduced, Depth, Used); |
6999 | break; |
7000 | |
7001 | case Type::HLSLAttributedResource: |
7002 | MarkUsedTemplateParameters( |
7003 | Ctx, T: cast<HLSLAttributedResourceType>(Val&: T)->getWrappedType(), OnlyDeduced, |
7004 | Depth, Used); |
7005 | if (cast<HLSLAttributedResourceType>(Val&: T)->hasContainedType()) |
7006 | MarkUsedTemplateParameters( |
7007 | Ctx, T: cast<HLSLAttributedResourceType>(Val&: T)->getContainedType(), |
7008 | OnlyDeduced, Depth, Used); |
7009 | break; |
7010 | |
7011 | // None of these types have any template parameters in them. |
7012 | case Type::Builtin: |
7013 | case Type::VariableArray: |
7014 | case Type::FunctionNoProto: |
7015 | case Type::Record: |
7016 | case Type::Enum: |
7017 | case Type::ObjCInterface: |
7018 | case Type::ObjCObject: |
7019 | case Type::ObjCObjectPointer: |
7020 | case Type::UnresolvedUsing: |
7021 | case Type::Pipe: |
7022 | case Type::BitInt: |
7023 | case Type::HLSLInlineSpirv: |
7024 | #define TYPE(Class, Base) |
7025 | #define ABSTRACT_TYPE(Class, Base) |
7026 | #define DEPENDENT_TYPE(Class, Base) |
7027 | #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: |
7028 | #include "clang/AST/TypeNodes.inc" |
7029 | break; |
7030 | } |
7031 | } |
7032 | |
7033 | /// Mark the template parameters that are used by this |
7034 | /// template argument. |
7035 | static void |
7036 | MarkUsedTemplateParameters(ASTContext &Ctx, |
7037 | const TemplateArgument &TemplateArg, |
7038 | bool OnlyDeduced, |
7039 | unsigned Depth, |
7040 | llvm::SmallBitVector &Used) { |
7041 | switch (TemplateArg.getKind()) { |
7042 | case TemplateArgument::Null: |
7043 | case TemplateArgument::Integral: |
7044 | case TemplateArgument::Declaration: |
7045 | case TemplateArgument::NullPtr: |
7046 | case TemplateArgument::StructuralValue: |
7047 | break; |
7048 | |
7049 | case TemplateArgument::Type: |
7050 | MarkUsedTemplateParameters(Ctx, T: TemplateArg.getAsType(), OnlyDeduced, |
7051 | Depth, Used); |
7052 | break; |
7053 | |
7054 | case TemplateArgument::Template: |
7055 | case TemplateArgument::TemplateExpansion: |
7056 | MarkUsedTemplateParameters(Ctx, |
7057 | Name: TemplateArg.getAsTemplateOrTemplatePattern(), |
7058 | OnlyDeduced, Depth, Used); |
7059 | break; |
7060 | |
7061 | case TemplateArgument::Expression: |
7062 | MarkUsedTemplateParameters(Ctx, E: TemplateArg.getAsExpr(), OnlyDeduced, |
7063 | Depth, Used); |
7064 | break; |
7065 | |
7066 | case TemplateArgument::Pack: |
7067 | for (const auto &P : TemplateArg.pack_elements()) |
7068 | MarkUsedTemplateParameters(Ctx, TemplateArg: P, OnlyDeduced, Depth, Used); |
7069 | break; |
7070 | } |
7071 | } |
7072 | |
7073 | void |
7074 | Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, |
7075 | unsigned Depth, |
7076 | llvm::SmallBitVector &Used) { |
7077 | ::MarkUsedTemplateParameters(Ctx&: Context, E, OnlyDeduced, Depth, Used); |
7078 | } |
7079 | |
7080 | void |
7081 | Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, |
7082 | bool OnlyDeduced, unsigned Depth, |
7083 | llvm::SmallBitVector &Used) { |
7084 | // C++0x [temp.deduct.type]p9: |
7085 | // If the template argument list of P contains a pack expansion that is not |
7086 | // the last template argument, the entire template argument list is a |
7087 | // non-deduced context. |
7088 | if (OnlyDeduced && |
7089 | hasPackExpansionBeforeEnd(Args: TemplateArgs.asArray())) |
7090 | return; |
7091 | |
7092 | for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) |
7093 | ::MarkUsedTemplateParameters(Ctx&: Context, TemplateArg: TemplateArgs[I], OnlyDeduced, |
7094 | Depth, Used); |
7095 | } |
7096 | |
7097 | void Sema::MarkUsedTemplateParameters(ArrayRef<TemplateArgument> TemplateArgs, |
7098 | unsigned Depth, |
7099 | llvm::SmallBitVector &Used) { |
7100 | for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) |
7101 | ::MarkUsedTemplateParameters(Ctx&: Context, TemplateArg: TemplateArgs[I], |
7102 | /*OnlyDeduced=*/false, Depth, Used); |
7103 | } |
7104 | |
7105 | void Sema::MarkDeducedTemplateParameters( |
7106 | ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, |
7107 | llvm::SmallBitVector &Deduced) { |
7108 | TemplateParameterList *TemplateParams |
7109 | = FunctionTemplate->getTemplateParameters(); |
7110 | Deduced.clear(); |
7111 | Deduced.resize(N: TemplateParams->size()); |
7112 | |
7113 | FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); |
7114 | for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) |
7115 | ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(i: I)->getType(), |
7116 | true, TemplateParams->getDepth(), Deduced); |
7117 | } |
7118 | |
7119 | bool hasDeducibleTemplateParameters(Sema &S, |
7120 | FunctionTemplateDecl *FunctionTemplate, |
7121 | QualType T) { |
7122 | if (!T->isDependentType()) |
7123 | return false; |
7124 | |
7125 | TemplateParameterList *TemplateParams |
7126 | = FunctionTemplate->getTemplateParameters(); |
7127 | llvm::SmallBitVector Deduced(TemplateParams->size()); |
7128 | ::MarkUsedTemplateParameters(Ctx&: S.Context, T, OnlyDeduced: true, Depth: TemplateParams->getDepth(), |
7129 | Used&: Deduced); |
7130 | |
7131 | return Deduced.any(); |
7132 | } |
7133 |
Definitions
- TemplateDeductionFlags
- PartialOrderingKind
- PackFold
- getDeducedParameterFromExpr
- getDeducedParameterFromExpr
- isSameDeclaration
- checkDeducedTemplateArguments
- DeduceNonTypeTemplateArgument
- DeduceNonTypeTemplateArgument
- DeduceNullPtrTemplateArgument
- DeduceNonTypeTemplateArgument
- DeduceNonTypeTemplateArgument
- DeduceTemplateArguments
- getLastTemplateSpecType
- DeduceTemplateSpecArguments
- IsPossiblyOpaquelyQualifiedTypeInternal
- IsPossiblyOpaquelyQualifiedType
- makeTemplateParameter
- DeducedPack
- DeducedPack
- PackDeductionScope
- PackDeductionScope
- PackDeductionScope
- addPack
- addPacks
- finishConstruction
- ~PackDeductionScope
- getSavedPackSizeIfAllEqual
- isDeducedFromEarlierParameter
- isPartiallyExpanded
- hasFixedArity
- hasNextElement
- nextPackElement
- finish
- DeduceForEachType
- DeduceTemplateArguments
- hasInconsistentOrSupersetQualifiersOf
- isSameOrCompatibleFunctionType
- getFirstInnerIndex
- isForwardingReference
- DeduceTemplateBases
- degradeCallPartialOrderingKind
- DeduceTemplateArgumentsByTypeMatch
- DeduceTemplateArguments
- hasTemplateArgumentForDeduction
- hasPackExpansionBeforeEnd
- DeduceTemplateArguments
- DeduceTemplateArguments
- getTrivialTemplateArgumentLoc
- getIdentityTemplateArgumentLoc
- ConvertDeducedTemplateArgument
- ConvertDeducedTemplateArguments
- getAsDeclContextOrEnclosing
- IsPartialSpecialization
- value
- IsPartialSpecialization
- value
- IsPartialSpecialization
- value
- CheckDeducedArgumentConstraints
- FinishTemplateArgumentDeduction
- FinishTemplateArgumentDeduction
- FinishTemplateArgumentDeduction
- DeduceTemplateArguments
- DeduceTemplateArguments
- DeduceTemplateArguments
- DeduceTemplateArgumentsFromType
- isSimpleTemplateIdType
- SubstituteExplicitTemplateArguments
- CheckOriginalCallArgDeduction
- getPackIndexForParam
- instantiateExplicitSpecifierDeferred
- FinishTemplateArgumentDeduction
- GetTypeOfFunction
- ResolveOverloadForDeduction
- AdjustFunctionParmAndArgTypesForDeduction
- DeduceFromInitializerList
- DeduceTemplateArgumentsFromCallArgument
- DeduceTemplateArguments
- adjustCCAndNoReturn
- DeduceTemplateArguments
- DeduceTemplateArguments
- DeduceTemplateArguments
- DependentAuto
- SubstituteDeducedTypeTransform
- SubstituteDeducedTypeTransform
- SubstituteDeducedTypeTransform
- TransformDesugared
- TransformAutoType
- TransformDeducedTemplateSpecializationType
- TransformLambdaExpr
- TransformExceptionSpec
- Apply
- CheckDeducedPlaceholderConstraints
- DeduceAutoType
- SubstAutoType
- SubstAutoTypeSourceInfo
- SubstAutoTypeDependent
- SubstAutoTypeSourceInfoDependent
- ReplaceAutoType
- ReplaceAutoTypeSourceInfo
- DiagnoseAutoDeductionFailure
- DeduceReturnType
- CheckIfFunctionSpecializationIsImmediate
- GetImplicitObjectParameterType
- CheckDeductionConsistency
- FinishTemplateArgumentDeduction
- isAtLeastAsSpecializedAs
- MoreSpecializedTrailingPackTieBreakerResult
- getMoreSpecializedTrailingPackTieBreaker
- getMoreSpecializedTemplate
- getMostSpecialized
- getMoreConstrainedFunction
- isAtLeastAsSpecializedAs
- GetP2
- operator()
- operator()
- TemplateArgumentListAreEqual
- TemplateArgumentListAreEqual
- operator()
- operator()
- getMoreSpecialized
- getMoreSpecializedPartialSpecialization
- isMoreSpecializedThanPrimary
- getMoreSpecializedPartialSpecialization
- isMoreSpecializedThanPrimary
- isTemplateTemplateParameterAtLeastAsSpecializedAs
- MarkUsedTemplateParameterVisitor
- MarkUsedTemplateParameterVisitor
- VisitTemplateTypeParmType
- TraverseTemplateName
- VisitDeclRefExpr
- MarkUsedTemplateParameters
- MarkUsedTemplateParameters
- MarkUsedTemplateParameters
- MarkUsedTemplateParameters
- MarkUsedTemplateParameters
- MarkUsedTemplateParameters
- MarkUsedTemplateParameters
- MarkUsedTemplateParameters
- MarkDeducedTemplateParameters
Improve your Profiling and Debugging skills
Find out more