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