clang 19.0.0git
SemaTemplateDeduction.cpp
Go to the documentation of this file.
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"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
29#include "clang/AST/Type.h"
30#include "clang/AST/TypeLoc.h"
34#include "clang/Basic/LLVM.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Sema/Template.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
62namespace clang {
63
64 /// Various flags that control template argument deduction.
65 ///
66 /// These flags can be bitwise-OR'd together.
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).
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.
77
78 /// Within template argument deduction from a function call, we
79 /// are matching in a case where we ignore cv-qualifiers.
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.
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.
91
92 /// Whether we are performing template argument deduction for
93 /// parameters and arguments in a top-level template argument
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.
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.
109 };
110}
111
112using namespace clang;
113using namespace sema;
114
115/// Compare two APSInts, extending and switching the sign as
116/// necessary to compare their values regardless of underlying type.
117static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
118 if (Y.getBitWidth() > X.getBitWidth())
119 X = X.extend(Y.getBitWidth());
120 else if (Y.getBitWidth() < X.getBitWidth())
121 Y = Y.extend(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
137 Sema &S, TemplateParameterList *TemplateParams, QualType Param,
139 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
140 bool PartialOrdering = false, bool DeducedFromArrayBound = false);
141
148 bool NumberOfArgumentsMustMatch);
149
152 bool OnlyDeduced, unsigned Depth,
153 llvm::SmallBitVector &Used);
154
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.
162static const NonTypeTemplateParmDecl *
163getDeducedParameterFromExpr(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>(E))
168 E = IC->getSubExpr();
169 else if (const auto *CE = dyn_cast<ConstantExpr>(E))
170 E = CE->getSubExpr();
171 else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
172 E = Subst->getReplacement();
173 else if (const auto *CCE = dyn_cast<CXXConstructExpr>(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(0);
180 } else
181 break;
182 }
183
184 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
185 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
186 if (NTTP->getDepth() == Depth)
187 return NTTP;
188
189 return nullptr;
190}
191
192static const NonTypeTemplateParmDecl *
195}
196
197/// Determine whether two declaration pointers refer to the same
198/// declaration.
199static bool isSameDeclaration(Decl *X, Decl *Y) {
200 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
201 X = NX->getUnderlyingDecl();
202 if (NamedDecl *NY = dyn_cast<NamedDecl>(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.
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()) {
232 if (YType.isNull() || !Context.hasSameType(XType, YType))
234 }
235 }
236
237 switch (X.getKind()) {
239 llvm_unreachable("Non-deduced template arguments handled above");
240
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(TX, TY))
245 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
246 X.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.
256 }
257
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.
265 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
266 return X.wasDeducedFromArrayBound() ? Y : X;
267
268 // All other combinations are incompatible.
270
272 // If we deduced a value and a dependent expression, keep the value.
275 X.structurallyEquals(Y)))
276 return X;
277
278 // All other combinations are incompatible.
280
283 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
284 return X;
285
286 // All other combinations are incompatible.
288
291 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
293 return X;
294
295 // All other combinations are incompatible.
297
300 return checkDeducedTemplateArguments(Context, 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.
311 }
312
314 assert(!X.wasDeducedFromArrayBound());
315
316 // If we deduced a declaration and a dependent expression, keep the
317 // declaration.
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.
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.
334 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
335 return X;
336
337 // All other combinations are incompatible.
339
341 // If we deduced a null pointer and a dependent expression, keep the
342 // null pointer.
345 X.getNullPtrType(), Y.getAsExpr()->getType()),
346 true);
347
348 // If we deduced a null pointer and an integral constant, keep the
349 // integral constant.
351 return Y;
352
353 // If we deduced two null pointers, they are the same.
355 return TemplateArgument(
356 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
357 true);
358
359 // All other combinations are incompatible.
361
363 if (Y.getKind() != TemplateArgument::Pack ||
364 (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
366
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) {
374 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
376 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
378 NewPack.push_back(Merged);
379 } else {
380 NewPack.push_back(*XA);
381 }
382 }
383
385 TemplateArgument::CreatePackCopy(Context, 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.
397 Sema &S, TemplateParameterList *TemplateParams,
398 const NonTypeTemplateParmDecl *NTTP,
399 const DeducedTemplateArgument &NewDeduced, QualType ValueType,
402 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
403 "deducing non-type template argument with wrong depth");
404
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(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
443 S, TemplateParams, ParamType, ValueType, Info, Deduced,
444 TDF_SkipNonDependent, /*PartialOrdering=*/false,
445 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
446}
447
448/// Deduce the value of the given non-type template parameter
449/// from the given integral constant.
451 Sema &S, TemplateParameterList *TemplateParams,
452 const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
453 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
456 S, TemplateParams, NTTP,
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.
465 Sema &S, TemplateParameterList *TemplateParams,
466 const NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
471 NTTP->getLocation()),
472 NullPtrType,
473 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
474 : CK_NullToPointer)
475 .get();
476 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
478 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.
486 Sema &S, TemplateParameterList *TemplateParams,
487 const NonTypeTemplateParmDecl *NTTP, Expr *Value,
490 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
492 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.
500 Sema &S, TemplateParameterList *TemplateParams,
501 const NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
504 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
505 TemplateArgument New(D, T);
507 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
508}
509
512 TemplateName Param, TemplateName Arg,
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>(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
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(Param, 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.
573 const QualType P, QualType A,
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>(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, TNP, 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, PResolved,
614 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>(RA->getDecl()) : nullptr;
624 if (!SA) {
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, TP->getTemplateName(),
633 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, PResolved,
639 SA->getTemplateArgs().asArray(), Info, Deduced,
640 /*NumberOfArgumentsMustMatch=*/true);
641}
642
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:
662 cast<ArrayType>(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.
674}
675
676/// Helper function to build a TemplateParameter when we don't
677/// know its type statically.
679 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
680 return TemplateParameter(TTP);
681 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
682 return TemplateParameter(NTTP);
683
684 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
685}
686
687/// A pack that we're currently deducing.
689 // The index of the pack.
690 unsigned Index;
691
692 // The old value of the pack before we started deducing it.
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.
698
699 // The new value of the pack.
701
702 // The outer deduction for this pack, if any.
703 DeducedPack *Outer = nullptr;
704
705 DeducedPack(unsigned Index) : Index(Index) {}
706};
707
708namespace {
709
710/// A scope in which we're performing pack deduction.
711class PackDeductionScope {
712public:
713 /// Prepare to deduce the packs named within Pattern.
714 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
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,
727 TemplateDeductionInfo &Info, unsigned Index)
728 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
729 addPack(Index);
730 finishConstruction(1);
731 }
732
733private:
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(TemplateParams->getParam(Index)))
747 FixedNumExpansions = ExpandedPackExpansions;
748
749 Packs.push_back(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());
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 TemplateParams->getParam(Index))) {
770 if (!NTTP->isExpandedParameterPack())
771 if (auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType()))
772 ExtraDeductions.push_back(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) {
780 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
781 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
782 unsigned Depth, Index;
783 std::tie(Depth, Index) = getDepthAndIndex(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 &PartialPackArgs, &NumPartialPackArgs))
811 PartialPackDepthIndex = getDepthAndIndex(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(Info.getDeducedDepth(), 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(Pack.Index + 1);
841 Info.PendingDeducedPacks[Pack.Index] = &Pack;
842
843 if (PartialPackDepthIndex ==
844 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
845 Pack.New.append(PartialPackArgs, 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
860public:
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(Packs.begin() + 1, Packs.end(), [&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(DeducedTemplateArgument());
909 if (Pack.New.size() == PackElements)
910 Pack.New.push_back(DeducedArg);
911 else
912 Pack.New[PackElements] = DeducedArg;
913 DeducedArg = Pack.New.size() > PackElements + 1
914 ? Pack.New[PackElements + 1]
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(PackElements);
945
946 // Build or find a new value for this pack.
948 if (Pack.New.empty()) {
949 // If we deduced an empty argument pack, create it now.
951 } else {
952 TemplateArgument *ArgumentPack =
953 new (S.Context) TemplateArgument[Pack.New.size()];
954 std::copy(Pack.New.begin(), Pack.New.end(), 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.
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;
982 S.Context, OldPack, NewPack, 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(S.Context, OldPack, NewPack);
994 }
995
996 NamedDecl *Param = TemplateParams->getParam(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
1020private:
1021 Sema &S;
1022 TemplateParameterList *TemplateParams;
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
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.
1069 const QualType *Params, unsigned NumParams,
1070 const QualType *Args, unsigned NumArgs,
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>(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>(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
1100 S, TemplateParams, Params[ParamIdx].getUnqualifiedType(),
1101 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
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.
1127 S, TemplateParams, Pattern.getUnqualifiedType(),
1128 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>(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.
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.
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(P, A);
1230
1231 // Noreturn and noexcept adjustment.
1232 QualType AdjustedParam;
1233 if (IsFunctionConversion(P, A, AdjustedParam))
1234 return Context.hasSameType(AdjustedParam, A);
1235
1236 // FIXME: Compatible calling conventions.
1237
1238 return Context.hasSameType(P, 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.
1246 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(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.
1253static 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
1268 return cast<CXXRecordDecl>(
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.
1292 TemplateParameterList *TemplateParams, QualType P,
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.
1316 // We iterate over this later, so we have to use MapVector to ensure
1317 // determinism.
1318 llvm::MapVector<const CXXRecordDecl *,
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(::getCanonicalRD(T)).second)
1327 ToVisit.push_back(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());
1343 S, TemplateParams, P, NextT, BaseInfo, 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(NextT);
1349 Matches.insert({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(ToVisit.pop_back_val());
1369 Matches.erase(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())
1379 if (Matches.size() > 1)
1381
1382 std::swap(Matches.front().second, Deduced);
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.
1411 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
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>(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(P, 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(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);
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(P, 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(A, 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(P, Quals);
1485 P = S.Context.getQualifiedType(UnqualP, 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(P, /*FirstInnerIndex=*/0) &&
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())
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(A, Quals);
1527 if (Quals)
1528 A = S.Context.getQualifiedType(A, Quals);
1529 }
1530
1531 // The argument type can not be less qualified than the parameter
1532 // type.
1533 if (!(TDF & TDF_IgnoreQualifiers) &&
1535 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1536 Info.FirstArg = TemplateArgument(P);
1537 Info.SecondArg = TemplateArgument(A);
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())
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");
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(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() &&
1569 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1570 Info.FirstArg = TemplateArgument(P);
1571 Info.SecondArg = TemplateArgument(A);
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())
1581
1582 DeducedType =
1583 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1584
1585 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1587 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1588 if (Result.isNull()) {
1589 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1590 Info.FirstArg = Deduced[Index];
1591 Info.SecondArg = NewDeduced;
1593 }
1594
1595 Deduced[Index] = Result;
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>())
1609
1610 // Check the cv-qualifiers on the parameter and argument types.
1611 if (!(TDF & TDF_IgnoreQualifiers)) {
1612 if (TDF & TDF_ParamWithReferenceType) {
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(P.getQualifiers()))
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(A, Quals);
1626 A = S.Context.getQualifiedType(A, P.getQualifiers());
1627 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1628 if (P.getCVRQualifiers() != A.getCVRQualifiers())
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)
1638 : S.Context.hasSameType(P, A))
1643 if (!(TDF & TDF_IgnoreQualifiers))
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())
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)
1683 : S.Context.hasSameType(P, A))
1686
1687 // _Complex T [placeholder extension]
1688 case Type::Complex: {
1689 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1690 if (!CA)
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)
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 {
1716 }
1718 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1719 PointeeType, Info, Deduced,
1721 }
1722
1723 // T &
1724 case Type::LValueReference: {
1725 const auto *RP = P->castAs<LValueReferenceType>(),
1726 *RA = A->getAs<LValueReferenceType>();
1727 if (!RA)
1729
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)
1741
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(A);
1750 if (!IAA)
1752
1753 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1754 assert(IAP && "Template parameter not of incomplete array type");
1755
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(A),
1765 assert(CAP);
1766 if (!CAA || CAA->getSize() != CAP->getSize())
1768
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(A);
1777 if (!AA)
1779
1780 // Check the element type of the arrays
1781 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1782 assert(DAP);
1784 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1785 Info, Deduced, TDF & TDF_IgnoreQualifiers);
1787 return Result;
1788
1789 // Determine the array bound is something we can deduce.
1790 const NonTypeTemplateParmDecl *NTTP =
1791 getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
1792 if (!NTTP)
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());
1802 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
1803 /*ArrayBound=*/true, Info, Deduced);
1804 }
1805 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
1806 if (DAA->getSizeExpr())
1808 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info, Deduced);
1809
1810 // Incomplete type does not match a dependently-sized array type
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)
1822
1823 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
1824 FPP->getRefQualifier() != FPA->getRefQualifier() ||
1825 FPP->isVariadic() != FPA->isVariadic())
1827
1828 // Check return types.
1830 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
1831 Info, Deduced, 0,
1832 /*PartialOrdering=*/false,
1833 /*DeducedFromArrayBound=*/false);
1835 return Result;
1836
1837 // Check parameter types.
1839 S, TemplateParams, FPP->param_type_begin(), FPP->getNumParams(),
1840 FPA->param_type_begin(), FPA->getNumParams(), Info, Deduced,
1843 return Result;
1844
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, 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?
1868 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1869 /*DeducedFromArrayBound=*/true, Info, Deduced);
1870
1871 case CT_Dependent:
1872 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
1874 S, TemplateParams, NTTP, 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
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);
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(Info.getLocation(), A))
1915 return Result;
1916
1917 // Reset the incorrectly deduced argument from above.
1918 Deduced = DeducedOrig;
1919
1920 // Check bases according to C++14 [temp.deduct.call] p4b3:
1922 TemplateParams, P, Info, Deduced);
1924 : Result;
1925 }
1926
1927 // T type::*
1928 // T T::*
1929 // T (type::*)()
1930 // type (T::*)()
1931 // type (type::*)(T)
1932 // type (T::*)(T)
1933 // T (type::*)(T)
1934 // T (T::*)()
1935 // T (T::*)(T)
1936 case Type::MemberPointer: {
1937 const auto *MPP = P->castAs<MemberPointerType>(),
1938 *MPA = A->getAs<MemberPointerType>();
1939 if (!MPA)
1941
1942 QualType PPT = MPP->getPointeeType();
1943 if (PPT->isFunctionType())
1944 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
1945 /*IsCtorOrDtor=*/false, Info.getLocation());
1946 QualType APT = MPA->getPointeeType();
1947 if (APT->isFunctionType())
1948 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
1949 /*IsCtorOrDtor=*/false, Info.getLocation());
1950
1951 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1953 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF);
1955 return Result;
1957 S, TemplateParams, QualType(MPP->getClass(), 0),
1958 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF);
1959 }
1960
1961 // (clang extension)
1962 //
1963 // type(^)(T)
1964 // T(^)()
1965 // T(^)(T)
1966 case Type::BlockPointer: {
1967 const auto *BPP = P->castAs<BlockPointerType>(),
1968 *BPA = A->getAs<BlockPointerType>();
1969 if (!BPA)
1972 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
1973 Deduced, 0);
1974 }
1975
1976 // (clang extension)
1977 //
1978 // T __attribute__(((ext_vector_type(<integral constant>))))
1979 case Type::ExtVector: {
1980 const auto *VP = P->castAs<ExtVectorType>();
1981 QualType ElementType;
1982 if (const auto *VA = A->getAs<ExtVectorType>()) {
1983 // Make sure that the vectors have the same number of elements.
1984 if (VP->getNumElements() != VA->getNumElements())
1986 ElementType = VA->getElementType();
1987 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
1988 // We can't check the number of elements, since the argument has a
1989 // dependent number of elements. This can only occur during partial
1990 // ordering.
1991 ElementType = VA->getElementType();
1992 } else {
1994 }
1995 // Perform deduction on the element types.
1997 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
1998 TDF);
1999 }
2000
2001 case Type::DependentVector: {
2002 const auto *VP = P->castAs<DependentVectorType>();
2003
2004 if (const auto *VA = A->getAs<VectorType>()) {
2005 // Perform deduction on the element types.
2007 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2008 Info, Deduced, TDF);
2010 return Result;
2011
2012 // Perform deduction on the vector size, if we can.
2013 const NonTypeTemplateParmDecl *NTTP =
2014 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2015 if (!NTTP)
2017
2018 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2019 ArgSize = VA->getNumElements();
2020 // Note that we use the "array bound" rules here; just like in that
2021 // case, we don't have any particular type for the vector size, but
2022 // we can provide one if necessary.
2023 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2024 S.Context.UnsignedIntTy, true,
2025 Info, Deduced);
2026 }
2027
2028 if (const auto *VA = A->getAs<DependentVectorType>()) {
2029 // Perform deduction on the element types.
2031 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2032 Info, Deduced, TDF);
2034 return Result;
2035
2036 // Perform deduction on the vector size, if we can.
2037 const NonTypeTemplateParmDecl *NTTP =
2038 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2039 if (!NTTP)
2041
2042 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2043 VA->getSizeExpr(), Info, Deduced);
2044 }
2045
2047 }
2048
2049 // (clang extension)
2050 //
2051 // T __attribute__(((ext_vector_type(N))))
2052 case Type::DependentSizedExtVector: {
2053 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2054
2055 if (const auto *VA = A->getAs<ExtVectorType>()) {
2056 // Perform deduction on the element types.
2058 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2059 Info, Deduced, TDF);
2061 return Result;
2062
2063 // Perform deduction on the vector size, if we can.
2064 const NonTypeTemplateParmDecl *NTTP =
2065 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2066 if (!NTTP)
2068
2069 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2070 ArgSize = VA->getNumElements();
2071 // Note that we use the "array bound" rules here; just like in that
2072 // case, we don't have any particular type for the vector size, but
2073 // we can provide one if necessary.
2074 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2075 S.Context.IntTy, true, Info,
2076 Deduced);
2077 }
2078
2079 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2080 // Perform deduction on the element types.
2082 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2083 Info, Deduced, TDF);
2085 return Result;
2086
2087 // Perform deduction on the vector size, if we can.
2088 const NonTypeTemplateParmDecl *NTTP =
2089 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2090 if (!NTTP)
2092
2093 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2094 VA->getSizeExpr(), Info, Deduced);
2095 }
2096
2098 }
2099
2100 // (clang extension)
2101 //
2102 // T __attribute__((matrix_type(<integral constant>,
2103 // <integral constant>)))
2104 case Type::ConstantMatrix: {
2105 const auto *MP = P->castAs<ConstantMatrixType>(),
2106 *MA = A->getAs<ConstantMatrixType>();
2107 if (!MA)
2109
2110 // Check that the dimensions are the same
2111 if (MP->getNumRows() != MA->getNumRows() ||
2112 MP->getNumColumns() != MA->getNumColumns()) {
2114 }
2115 // Perform deduction on element types.
2117 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2118 Deduced, TDF);
2119 }
2120
2121 case Type::DependentSizedMatrix: {
2122 const auto *MP = P->castAs<DependentSizedMatrixType>();
2123 const auto *MA = A->getAs<MatrixType>();
2124 if (!MA)
2126
2127 // Check the element type of the matrixes.
2129 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2130 Info, Deduced, TDF);
2132 return Result;
2133
2134 // Try to deduce a matrix dimension.
2135 auto DeduceMatrixArg =
2136 [&S, &Info, &Deduced, &TemplateParams](
2137 Expr *ParamExpr, const MatrixType *A,
2138 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2139 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2140 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2141 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2142 if (!ParamExpr->isValueDependent()) {
2143 std::optional<llvm::APSInt> ParamConst =
2144 ParamExpr->getIntegerConstantExpr(S.Context);
2145 if (!ParamConst)
2147
2148 if (ACM) {
2149 if ((ACM->*GetArgDimension)() == *ParamConst)
2152 }
2153
2154 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2155 if (std::optional<llvm::APSInt> ArgConst =
2156 ArgExpr->getIntegerConstantExpr(S.Context))
2157 if (*ArgConst == *ParamConst)
2160 }
2161
2162 const NonTypeTemplateParmDecl *NTTP =
2163 getDeducedParameterFromExpr(Info, ParamExpr);
2164 if (!NTTP)
2166
2167 if (ACM) {
2168 llvm::APSInt ArgConst(
2170 ArgConst = (ACM->*GetArgDimension)();
2172 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2173 /*ArrayBound=*/true, Info, Deduced);
2174 }
2175
2176 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2177 (ADM->*GetArgDimensionExpr)(),
2178 Info, Deduced);
2179 };
2180
2181 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2185 return Result;
2186
2187 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2190 }
2191
2192 // (clang extension)
2193 //
2194 // T __attribute__(((address_space(N))))
2195 case Type::DependentAddressSpace: {
2196 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2197
2198 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2199 // Perform deduction on the pointer type.
2201 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2202 Info, Deduced, TDF);
2204 return Result;
2205
2206 // Perform deduction on the address space, if we can.
2207 const NonTypeTemplateParmDecl *NTTP =
2208 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2209 if (!NTTP)
2211
2213 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info, Deduced);
2214 }
2215
2217 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2218 false);
2219 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2220
2221 // Perform deduction on the pointer types.
2223 S, TemplateParams, ASP->getPointeeType(),
2224 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF);
2226 return Result;
2227
2228 // Perform deduction on the address space, if we can.
2229 const NonTypeTemplateParmDecl *NTTP =
2230 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2231 if (!NTTP)
2233
2234 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2235 ArgAddressSpace, S.Context.IntTy,
2236 true, Info, Deduced);
2237 }
2238
2240 }
2241 case Type::DependentBitInt: {
2242 const auto *IP = P->castAs<DependentBitIntType>();
2243
2244 if (const auto *IA = A->getAs<BitIntType>()) {
2245 if (IP->isUnsigned() != IA->isUnsigned())
2247
2248 const NonTypeTemplateParmDecl *NTTP =
2249 getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
2250 if (!NTTP)
2252
2253 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2254 ArgSize = IA->getNumBits();
2255
2256 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2257 S.Context.IntTy, true, Info,
2258 Deduced);
2259 }
2260
2261 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2262 if (IP->isUnsigned() != IA->isUnsigned())
2265 }
2266
2268 }
2269
2270 case Type::TypeOfExpr:
2271 case Type::TypeOf:
2272 case Type::DependentName:
2273 case Type::UnresolvedUsing:
2274 case Type::Decltype:
2275 case Type::UnaryTransform:
2276 case Type::DeducedTemplateSpecialization:
2277 case Type::DependentTemplateSpecialization:
2278 case Type::PackExpansion:
2279 case Type::Pipe:
2280 // No template argument deduction for these types
2282
2283 case Type::PackIndexing: {
2284 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2285 if (PIT->hasSelectedType()) {
2287 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF);
2288 }
2290 }
2291 }
2292
2293 llvm_unreachable("Invalid Type Class!");
2294}
2295
2301 // If the template argument is a pack expansion, perform template argument
2302 // deduction against the pattern of that expansion. This only occurs during
2303 // partial ordering.
2304 if (A.isPackExpansion())
2306
2307 switch (P.getKind()) {
2309 llvm_unreachable("Null template argument in parameter list");
2310
2314 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0);
2315 Info.FirstArg = P;
2316 Info.SecondArg = A;
2318
2321 return DeduceTemplateArguments(S, TemplateParams, P.getAsTemplate(),
2322 A.getAsTemplate(), Info, Deduced);
2323 Info.FirstArg = P;
2324 Info.SecondArg = A;
2326
2328 llvm_unreachable("caller should handle pack expansions");
2329
2332 isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
2334
2335 Info.FirstArg = P;
2336 Info.SecondArg = A;
2338
2341 S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
2343
2344 Info.FirstArg = P;
2345 Info.SecondArg = A;
2347
2350 if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
2352 }
2353 Info.FirstArg = P;
2354 Info.SecondArg = A;
2356
2361
2362 Info.FirstArg = P;
2363 Info.SecondArg = A;
2365
2367 if (const NonTypeTemplateParmDecl *NTTP =
2368 getDeducedParameterFromExpr(Info, P.getAsExpr())) {
2369 switch (A.getKind()) {
2374 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2375 A.getNonTypeTemplateArgumentType(), Info, Deduced);
2376
2378 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2379 A.getNullPtrType(), Info, Deduced);
2380
2383 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2384 Info, Deduced);
2385
2391 Info.FirstArg = P;
2392 Info.SecondArg = A;
2394 }
2395 llvm_unreachable("Unknown template argument kind");
2396 }
2397
2398 // Can't deduce anything, but that's okay.
2401 llvm_unreachable("Argument packs should be expanded by the caller!");
2402 }
2403
2404 llvm_unreachable("Invalid TemplateArgument Kind!");
2405}
2406
2407/// Determine whether there is a template argument to be used for
2408/// deduction.
2409///
2410/// This routine "expands" argument packs in-place, overriding its input
2411/// parameters so that \c Args[ArgIdx] will be the available template argument.
2412///
2413/// \returns true if there is another template argument (which will be at
2414/// \c Args[ArgIdx]), false otherwise.
2416 unsigned &ArgIdx) {
2417 if (ArgIdx == Args.size())
2418 return false;
2419
2420 const TemplateArgument &Arg = Args[ArgIdx];
2421 if (Arg.getKind() != TemplateArgument::Pack)
2422 return true;
2423
2424 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2425 Args = Arg.pack_elements();
2426 ArgIdx = 0;
2427 return ArgIdx < Args.size();
2428}
2429
2430/// Determine whether the given set of template arguments has a pack
2431/// expansion that is not the last template argument.
2433 bool FoundPackExpansion = false;
2434 for (const auto &A : Args) {
2435 if (FoundPackExpansion)
2436 return true;
2437
2438 if (A.getKind() == TemplateArgument::Pack)
2439 return hasPackExpansionBeforeEnd(A.pack_elements());
2440
2441 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2442 // templates, it should not be treated as a pack expansion.
2443 if (A.isPackExpansion())
2444 FoundPackExpansion = true;
2445 }
2446
2447 return false;
2448}
2449
2456 bool NumberOfArgumentsMustMatch) {
2457 // C++0x [temp.deduct.type]p9:
2458 // If the template argument list of P contains a pack expansion that is not
2459 // the last template argument, the entire template argument list is a
2460 // non-deduced context.
2463
2464 // C++0x [temp.deduct.type]p9:
2465 // If P has a form that contains <T> or <i>, then each argument Pi of the
2466 // respective template argument list P is compared with the corresponding
2467 // argument Ai of the corresponding template argument list of A.
2468 unsigned ArgIdx = 0, ParamIdx = 0;
2470 const TemplateArgument &P = Ps[ParamIdx];
2471 if (!P.isPackExpansion()) {
2472 // The simple case: deduce template arguments by matching Pi and Ai.
2473
2474 // Check whether we have enough arguments.
2475 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2476 return NumberOfArgumentsMustMatch
2479
2480 // C++1z [temp.deduct.type]p9:
2481 // During partial ordering, if Ai was originally a pack expansion [and]
2482 // Pi is not a pack expansion, template argument deduction fails.
2483 if (As[ArgIdx].isPackExpansion())
2485
2486 // Perform deduction for this Pi/Ai pair.
2487 if (auto Result = DeduceTemplateArguments(S, TemplateParams, P,
2488 As[ArgIdx], Info, Deduced);
2490 return Result;
2491
2492 // Move to the next argument.
2493 ++ArgIdx;
2494 continue;
2495 }
2496
2497 // The parameter is a pack expansion.
2498
2499 // C++0x [temp.deduct.type]p9:
2500 // If Pi is a pack expansion, then the pattern of Pi is compared with
2501 // each remaining argument in the template argument list of A. Each
2502 // comparison deduces template arguments for subsequent positions in the
2503 // template parameter packs expanded by Pi.
2504 TemplateArgument Pattern = P.getPackExpansionPattern();
2505
2506 // Prepare to deduce the packs within the pattern.
2507 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2508
2509 // Keep track of the deduced template arguments for each parameter pack
2510 // expanded by this pack expansion (the outer index) and for each
2511 // template argument (the inner SmallVectors).
2512 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2513 PackScope.hasNextElement();
2514 ++ArgIdx) {
2515 // Deduce template arguments from the pattern.
2516 if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pattern,
2517 As[ArgIdx], Info, Deduced);
2519 return Result;
2520
2521 PackScope.nextPackElement();
2522 }
2523
2524 // Build argument packs for each of the parameter packs expanded by this
2525 // pack expansion.
2526 if (auto Result = PackScope.finish();
2528 return Result;
2529 }
2530
2532}
2533
2538 bool NumberOfArgumentsMustMatch) {
2539 return ::DeduceTemplateArguments(*this, TemplateParams, Ps, As, Info, Deduced,
2540 NumberOfArgumentsMustMatch);
2541}
2542
2543/// Determine whether two template arguments are the same.
2544static bool isSameTemplateArg(ASTContext &Context,
2546 const TemplateArgument &Y,
2547 bool PartialOrdering,
2548 bool PackExpansionMatchesPack = false) {
2549 // If we're checking deduced arguments (X) against original arguments (Y),
2550 // we will have flattened packs to non-expansions in X.
2551 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2552 X = X.getPackExpansionPattern();
2553
2554 if (X.getKind() != Y.getKind())
2555 return false;
2556
2557 switch (X.getKind()) {
2559 llvm_unreachable("Comparing NULL template argument");
2560
2562 return Context.getCanonicalType(X.getAsType()) ==
2563 Context.getCanonicalType(Y.getAsType());
2564
2566 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2567
2569 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2570
2573 return Context.getCanonicalTemplateName(
2574 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2577
2579 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2580
2582 return X.structurallyEquals(Y);
2583
2585 llvm::FoldingSetNodeID XID, YID;
2586 X.getAsExpr()->Profile(XID, Context, true);
2587 Y.getAsExpr()->Profile(YID, Context, true);
2588 return XID == YID;
2589 }
2590
2592 unsigned PackIterationSize = X.pack_size();
2593 if (X.pack_size() != Y.pack_size()) {
2594 if (!PartialOrdering)
2595 return false;
2596
2597 // C++0x [temp.deduct.type]p9:
2598 // During partial ordering, if Ai was originally a pack expansion:
2599 // - if P does not contain a template argument corresponding to Ai
2600 // then Ai is ignored;
2601 bool XHasMoreArg = X.pack_size() > Y.pack_size();
2602 if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
2603 !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
2604 return false;
2605
2606 if (XHasMoreArg)
2607 PackIterationSize = Y.pack_size();
2608 }
2609
2610 ArrayRef<TemplateArgument> XP = X.pack_elements();
2612 for (unsigned i = 0; i < PackIterationSize; ++i)
2613 if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
2614 PackExpansionMatchesPack))
2615 return false;
2616 return true;
2617 }
2618 }
2619
2620 llvm_unreachable("Invalid TemplateArgument Kind!");
2621}
2622
2623/// Allocate a TemplateArgumentLoc where all locations have
2624/// been initialized to the given location.
2625///
2626/// \param Arg The template argument we are producing template argument
2627/// location information for.
2628///
2629/// \param NTTPType For a declaration template argument, the type of
2630/// the non-type template parameter that corresponds to this template
2631/// argument. Can be null if no type sugar is available to add to the
2632/// type from the template argument.
2633///
2634/// \param Loc The source location to use for the resulting template
2635/// argument.
2638 QualType NTTPType, SourceLocation Loc) {
2639 switch (Arg.getKind()) {
2641 llvm_unreachable("Can't get a NULL template argument here");
2642
2644 return TemplateArgumentLoc(
2645 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2646
2648 if (NTTPType.isNull())
2649 NTTPType = Arg.getParamTypeForDecl();
2650 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2651 .getAs<Expr>();
2653 }
2654
2656 if (NTTPType.isNull())
2657 NTTPType = Arg.getNullPtrType();
2658 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2659 .getAs<Expr>();
2660 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2661 E);
2662 }
2663
2668 }
2669
2675 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2676 else if (QualifiedTemplateName *QTN =
2677 Template.getAsQualifiedTemplateName())
2678 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2679
2681 return TemplateArgumentLoc(Context, Arg,
2682 Builder.getWithLocInContext(Context), Loc);
2683
2684 return TemplateArgumentLoc(
2685 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
2686 }
2687
2689 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2690
2693 }
2694
2695 llvm_unreachable("Invalid TemplateArgument Kind!");
2696}
2697
2700 SourceLocation Location) {
2702 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2703}
2704
2705/// Convert the given deduced template argument and add it to the set of
2706/// fully-converted template arguments.
2708 Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template,
2709 TemplateDeductionInfo &Info, bool IsDeduced,
2710 SmallVectorImpl<TemplateArgument> &SugaredOutput,
2711 SmallVectorImpl<TemplateArgument> &CanonicalOutput) {
2712 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2713 unsigned ArgumentPackIndex) {
2714 // Convert the deduced template argument into a template
2715 // argument that we can check, almost as if the user had written
2716 // the template argument explicitly.
2717 TemplateArgumentLoc ArgLoc =
2719
2720 // Check the template argument, converting it as necessary.
2721 return S.CheckTemplateArgument(
2722 Param, ArgLoc, Template, Template->getLocation(),
2723 Template->getSourceRange().getEnd(), ArgumentPackIndex, SugaredOutput,
2724 CanonicalOutput,
2725 IsDeduced
2729 };
2730
2731 if (Arg.getKind() == TemplateArgument::Pack) {
2732 // This is a template argument pack, so check each of its arguments against
2733 // the template parameter.
2734 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2735 CanonicalPackedArgsBuilder;
2736 for (const auto &P : Arg.pack_elements()) {
2737 // When converting the deduced template argument, append it to the
2738 // general output list. We need to do this so that the template argument
2739 // checking logic has all of the prior template arguments available.
2740 DeducedTemplateArgument InnerArg(P);
2742 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2743 "deduced nested pack");
2744 if (P.isNull()) {
2745 // We deduced arguments for some elements of this pack, but not for
2746 // all of them. This happens if we get a conditionally-non-deduced
2747 // context in a pack expansion (such as an overload set in one of the
2748 // arguments).
2749 S.Diag(Param->getLocation(),
2750 diag::err_template_arg_deduced_incomplete_pack)
2751 << Arg << Param;
2752 return true;
2753 }
2754 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2755 return true;
2756
2757 // Move the converted template argument into our argument pack.
2758 SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
2759 CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
2760 }
2761
2762 // If the pack is empty, we still need to substitute into the parameter
2763 // itself, in case that substitution fails.
2764 if (SugaredPackedArgsBuilder.empty()) {
2766 MultiLevelTemplateArgumentList Args(Template, SugaredOutput,
2767 /*Final=*/true);
2768
2769 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2770 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2771 NTTP, SugaredOutput,
2772 Template->getSourceRange());
2773 if (Inst.isInvalid() ||
2774 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2775 NTTP->getDeclName()).isNull())
2776 return true;
2777 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2778 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2779 TTP, SugaredOutput,
2780 Template->getSourceRange());
2781 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2782 return true;
2783 }
2784 // For type parameters, no substitution is ever required.
2785 }
2786
2787 // Create the resulting argument pack.
2788 SugaredOutput.push_back(
2789 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
2790 CanonicalOutput.push_back(TemplateArgument::CreatePackCopy(
2791 S.Context, CanonicalPackedArgsBuilder));
2792 return false;
2793 }
2794
2795 return ConvertArg(Arg, 0);
2796}
2797
2798// FIXME: This should not be a template, but
2799// ClassTemplatePartialSpecializationDecl sadly does not derive from
2800// TemplateDecl.
2801template <typename TemplateDeclT>
2803 Sema &S, TemplateDeclT *Template, bool IsDeduced,
2806 SmallVectorImpl<TemplateArgument> &SugaredBuilder,
2807 SmallVectorImpl<TemplateArgument> &CanonicalBuilder,
2808 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2809 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2810 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2811
2812 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2813 NamedDecl *Param = TemplateParams->getParam(I);
2814
2815 // C++0x [temp.arg.explicit]p3:
2816 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2817 // be deduced to an empty sequence of template arguments.
2818 // FIXME: Where did the word "trailing" come from?
2819 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2820 if (auto Result =
2821 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
2823 return Result;
2824 }
2825
2826 if (!Deduced[I].isNull()) {
2827 if (I < NumAlreadyConverted) {
2828 // We may have had explicitly-specified template arguments for a
2829 // template parameter pack (that may or may not have been extended
2830 // via additional deduced arguments).
2831 if (Param->isParameterPack() && CurrentInstantiationScope &&
2832 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2833 // Forget the partially-substituted pack; its substitution is now
2834 // complete.
2835 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2836 // We still need to check the argument in case it was extended by
2837 // deduction.
2838 } else {
2839 // We have already fully type-checked and converted this
2840 // argument, because it was explicitly-specified. Just record the
2841 // presence of this argument.
2842 SugaredBuilder.push_back(Deduced[I]);
2843 CanonicalBuilder.push_back(
2845 continue;
2846 }
2847 }
2848
2849 // We may have deduced this argument, so it still needs to be
2850 // checked and converted.
2851 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2852 IsDeduced, SugaredBuilder,
2853 CanonicalBuilder)) {
2854 Info.Param = makeTemplateParameter(Param);
2855 // FIXME: These template arguments are temporary. Free them!
2856 Info.reset(
2857 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
2858 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
2860 }
2861
2862 continue;
2863 }
2864
2865 // Substitute into the default template argument, if available.
2866 bool HasDefaultArg = false;
2867 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2868 if (!TD) {
2869 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2870 isa<VarTemplatePartialSpecializationDecl>(Template));
2872 }
2873
2874 TemplateArgumentLoc DefArg;
2875 {
2876 Qualifiers ThisTypeQuals;
2877 CXXRecordDecl *ThisContext = nullptr;
2878 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
2879 if (Rec->isLambda())
2880 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
2881 ThisContext = Method->getParent();
2882 ThisTypeQuals = Method->getMethodQualifiers();
2883 }
2884
2885 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
2886 S.getLangOpts().CPlusPlus17);
2887
2889 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param,
2890 SugaredBuilder, CanonicalBuilder, HasDefaultArg);
2891 }
2892
2893 // If there was no default argument, deduction is incomplete.
2894 if (DefArg.getArgument().isNull()) {
2896 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2897 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
2898 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
2899 if (PartialOverloading) break;
2900
2903 }
2904
2905 // Check whether we can actually use the default argument.
2907 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
2908 0, SugaredBuilder, CanonicalBuilder, Sema::CTAK_Specified)) {
2910 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2911 // FIXME: These template arguments are temporary. Free them!
2912 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
2913 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
2915 }
2916
2917 // If we get here, we successfully used the default template argument.
2918 }
2919
2921}
2922
2924 if (auto *DC = dyn_cast<DeclContext>(D))
2925 return DC;
2926 return D->getDeclContext();
2927}
2928
2929template<typename T> struct IsPartialSpecialization {
2930 static constexpr bool value = false;
2931};
2932template<>
2934 static constexpr bool value = true;
2935};
2936template<>
2938 static constexpr bool value = true;
2939};
2940template <typename TemplateDeclT>
2941static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
2942 return false;
2943}
2944template <>
2947 return !Spec->isClassScopeExplicitSpecialization();
2948}
2949template <>
2952 return !Spec->isClassScopeExplicitSpecialization();
2953}
2954
2955template <typename TemplateDeclT>
2957CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
2958 ArrayRef<TemplateArgument> SugaredDeducedArgs,
2959 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
2960 TemplateDeductionInfo &Info) {
2961 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
2962 Template->getAssociatedConstraints(AssociatedConstraints);
2963
2964 std::optional<ArrayRef<TemplateArgument>> Innermost;
2965 // If we don't need to replace the deduced template arguments,
2966 // we can add them immediately as the inner-most argument list.
2967 if (!DeducedArgsNeedReplacement(Template))
2968 Innermost = CanonicalDeducedArgs;
2969
2971 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
2972 /*RelativeToPrimary=*/true, /*Pattern=*/
2973 nullptr, /*ForConstraintInstantiation=*/true);
2974
2975 // getTemplateInstantiationArgs picks up the non-deduced version of the
2976 // template args when this is a variable template partial specialization and
2977 // not class-scope explicit specialization, so replace with Deduced Args
2978 // instead of adding to inner-most.
2979 if (!Innermost)
2980 MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs);
2981
2982 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
2983 Info.getLocation(),
2986 Info.reset(
2987 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
2988 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
2990 }
2992}
2993
2994/// Complete template argument deduction for a partial specialization.
2995template <typename T>
2996static std::enable_if_t<IsPartialSpecialization<T>::value,
2999 Sema &S, T *Partial, bool IsPartialOrdering,
3000 ArrayRef<TemplateArgument> TemplateArgs,
3002 TemplateDeductionInfo &Info) {
3003 // Unevaluated SFINAE context.
3006 Sema::SFINAETrap Trap(S);
3007
3008 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
3009
3010 // C++ [temp.deduct.type]p2:
3011 // [...] or if any template argument remains neither deduced nor
3012 // explicitly specified, template argument deduction fails.
3013 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3015 S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
3016 CanonicalBuilder);
3018 return Result;
3019
3020 // Form the template argument list from the deduced template arguments.
3021 TemplateArgumentList *SugaredDeducedArgumentList =
3022 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
3023 TemplateArgumentList *CanonicalDeducedArgumentList =
3024 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
3025
3026 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3027
3028 // Substitute the deduced template arguments into the template
3029 // arguments of the class template partial specialization, and
3030 // verify that the instantiated template arguments are both valid
3031 // and are equivalent to the template arguments originally provided
3032 // to the class template.
3033 LocalInstantiationScope InstScope(S);
3034 auto *Template = Partial->getSpecializedTemplate();
3035 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
3036 Partial->getTemplateArgsAsWritten();
3037
3038 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
3039 PartialTemplArgInfo->RAngleLoc);
3040
3041 if (S.SubstTemplateArguments(PartialTemplArgInfo->arguments(),
3043 SugaredBuilder,
3044 /*Final=*/true),
3045 InstArgs)) {
3046 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3047 if (ParamIdx >= Partial->getTemplateParameters()->size())
3048 ParamIdx = Partial->getTemplateParameters()->size() - 1;
3049
3050 Decl *Param = const_cast<NamedDecl *>(
3051 Partial->getTemplateParameters()->getParam(ParamIdx));
3052 Info.Param = makeTemplateParameter(Param);
3053 Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
3055 }
3056
3058 SmallVector<TemplateArgument, 4> SugaredConvertedInstArgs,
3059 CanonicalConvertedInstArgs;
3061 Template, Partial->getLocation(), InstArgs, false,
3062 SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
3063 /*UpdateArgsWithConversions=*/true, &ConstraintsNotSatisfied))
3067
3068 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3069 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3070 TemplateArgument InstArg = SugaredConvertedInstArgs.data()[I];
3071 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
3072 IsPartialOrdering)) {
3073 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3074 Info.FirstArg = TemplateArgs[I];
3075 Info.SecondArg = InstArg;
3077 }
3078 }
3079
3080 if (Trap.hasErrorOccurred())
3082
3083 if (auto Result = CheckDeducedArgumentConstraints(S, Partial, SugaredBuilder,
3084 CanonicalBuilder, Info);
3086 return Result;
3087
3089}
3090
3091/// Complete template argument deduction for a class or variable template,
3092/// when partial ordering against a partial specialization.
3093// FIXME: Factor out duplication with partial specialization version above.
3095 Sema &S, TemplateDecl *Template, bool PartialOrdering,
3096 ArrayRef<TemplateArgument> TemplateArgs,
3098 TemplateDeductionInfo &Info) {
3099 // Unevaluated SFINAE context.
3102 Sema::SFINAETrap Trap(S);
3103
3104 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
3105
3106 // C++ [temp.deduct.type]p2:
3107 // [...] or if any template argument remains neither deduced nor
3108 // explicitly specified, template argument deduction fails.
3109 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3111 S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info,
3112 SugaredBuilder, CanonicalBuilder,
3113 /*CurrentInstantiationScope=*/nullptr,
3114 /*NumAlreadyConverted=*/0U, /*PartialOverloading=*/false);
3116 return Result;
3117
3118 // Check that we produced the correct argument list.
3119 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3120 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3121 TemplateArgument InstArg = CanonicalBuilder[I];
3122 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, PartialOrdering,
3123 /*PackExpansionMatchesPack=*/true)) {
3124 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3125 Info.FirstArg = TemplateArgs[I];
3126 Info.SecondArg = InstArg;
3128 }
3129 }
3130
3131 if (Trap.hasErrorOccurred())
3133
3134 if (auto Result = CheckDeducedArgumentConstraints(S, Template, SugaredBuilder,
3135 CanonicalBuilder, Info);
3137 return Result;
3138
3140}
3141
3142/// Perform template argument deduction to determine whether
3143/// the given template arguments match the given class template
3144/// partial specialization per C++ [temp.class.spec.match].
3147 ArrayRef<TemplateArgument> TemplateArgs,
3148 TemplateDeductionInfo &Info) {
3149 if (Partial->isInvalidDecl())
3151
3152 // C++ [temp.class.spec.match]p2:
3153 // A partial specialization matches a given actual template
3154 // argument list if the template arguments of the partial
3155 // specialization can be deduced from the actual template argument
3156 // list (14.8.2).
3157
3158 // Unevaluated SFINAE context.
3161 SFINAETrap Trap(*this);
3162
3163 // This deduction has no relation to any outer instantiation we might be
3164 // performing.
3165 LocalInstantiationScope InstantiationScope(*this);
3166
3168 Deduced.resize(Partial->getTemplateParameters()->size());
3170 *this, Partial->getTemplateParameters(),
3171 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3172 /*NumberOfArgumentsMustMatch=*/false);
3174 return Result;
3175
3176 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3177 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
3178 Info);
3179 if (Inst.isInvalid())
3181
3182 if (Trap.hasErrorOccurred())
3184
3187 Result = ::FinishTemplateArgumentDeduction(*this, Partial,
3188 /*IsPartialOrdering=*/false,
3189 TemplateArgs, Deduced, Info);
3190 });
3191 return Result;
3192}
3193
3194/// Perform template argument deduction to determine whether
3195/// the given template arguments match the given variable template
3196/// partial specialization per C++ [temp.class.spec.match].
3199 ArrayRef<TemplateArgument> TemplateArgs,
3200 TemplateDeductionInfo &Info) {
3201 if (Partial->isInvalidDecl())
3203
3204 // C++ [temp.class.spec.match]p2:
3205 // A partial specialization matches a given actual template
3206 // argument list if the template arguments of the partial
3207 // specialization can be deduced from the actual template argument
3208 // list (14.8.2).
3209
3210 // Unevaluated SFINAE context.
3213 SFINAETrap Trap(*this);
3214
3215 // This deduction has no relation to any outer instantiation we might be
3216 // performing.
3217 LocalInstantiationScope InstantiationScope(*this);
3218
3220 Deduced.resize(Partial->getTemplateParameters()->size());
3222 *this, Partial->getTemplateParameters(),
3223 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3224 /*NumberOfArgumentsMustMatch=*/false);
3226 return Result;
3227
3228 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3229 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
3230 Info);
3231 if (Inst.isInvalid())
3233
3234 if (Trap.hasErrorOccurred())
3236
3239 Result = ::FinishTemplateArgumentDeduction(*this, Partial,
3240 /*IsPartialOrdering=*/false,
3241 TemplateArgs, Deduced, Info);
3242 });
3243 return Result;
3244}
3245
3246/// Determine whether the given type T is a simple-template-id type.
3248 if (const TemplateSpecializationType *Spec
3250 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3251
3252 // C++17 [temp.local]p2:
3253 // the injected-class-name [...] is equivalent to the template-name followed
3254 // by the template-arguments of the class template specialization or partial
3255 // specialization enclosed in <>
3256 // ... which means it's equivalent to a simple-template-id.
3257 //
3258 // This only arises during class template argument deduction for a copy
3259 // deduction candidate, where it permits slicing.
3260 if (T->getAs<InjectedClassNameType>())
3261 return true;
3262
3263 return false;
3264}
3265
3266/// Substitute the explicitly-provided template arguments into the
3267/// given function template according to C++ [temp.arg.explicit].
3268///
3269/// \param FunctionTemplate the function template into which the explicit
3270/// template arguments will be substituted.
3271///
3272/// \param ExplicitTemplateArgs the explicitly-specified template
3273/// arguments.
3274///
3275/// \param Deduced the deduced template arguments, which will be populated
3276/// with the converted and checked explicit template arguments.
3277///
3278/// \param ParamTypes will be populated with the instantiated function
3279/// parameters.
3280///
3281/// \param FunctionType if non-NULL, the result type of the function template
3282/// will also be instantiated and the pointed-to value will be updated with
3283/// the instantiated function type.
3284///
3285/// \param Info if substitution fails for any reason, this object will be
3286/// populated with more information about the failure.
3287///
3288/// \returns TemplateDeductionResult::Success if substitution was successful, or
3289/// some failure condition.
3291 FunctionTemplateDecl *FunctionTemplate,
3292 TemplateArgumentListInfo &ExplicitTemplateArgs,
3295 TemplateDeductionInfo &Info) {
3296 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3297 TemplateParameterList *TemplateParams
3298 = FunctionTemplate->getTemplateParameters();
3299
3300 if (ExplicitTemplateArgs.size() == 0) {
3301 // No arguments to substitute; just copy over the parameter types and
3302 // fill in the function type.
3303 for (auto *P : Function->parameters())
3304 ParamTypes.push_back(P->getType());
3305
3306 if (FunctionType)
3307 *FunctionType = Function->getType();
3309 }
3310
3311 // Unevaluated SFINAE context.
3314 SFINAETrap Trap(*this);
3315
3316 // C++ [temp.arg.explicit]p3:
3317 // Template arguments that are present shall be specified in the
3318 // declaration order of their corresponding template-parameters. The
3319 // template argument list shall not specify more template-arguments than
3320 // there are corresponding template-parameters.
3321 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3322
3323 // Enter a new template instantiation context where we check the
3324 // explicitly-specified template arguments against this function template,
3325 // and then substitute them into the function parameter types.
3328 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3330 if (Inst.isInvalid())
3332
3334 ExplicitTemplateArgs, true, SugaredBuilder,
3335 CanonicalBuilder,
3336 /*UpdateArgsWithConversions=*/false) ||
3337 Trap.hasErrorOccurred()) {
3338 unsigned Index = SugaredBuilder.size();
3339 if (Index >= TemplateParams->size())
3341 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3343 }
3344
3345 // Form the template argument list from the explicitly-specified
3346 // template arguments.
3347 TemplateArgumentList *SugaredExplicitArgumentList =
3349 TemplateArgumentList *CanonicalExplicitArgumentList =
3350 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3351 Info.setExplicitArgs(SugaredExplicitArgumentList,
3352 CanonicalExplicitArgumentList);
3353
3354 // Template argument deduction and the final substitution should be
3355 // done in the context of the templated declaration. Explicit
3356 // argument substitution, on the other hand, needs to happen in the
3357 // calling context.
3358 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3359
3360 // If we deduced template arguments for a template parameter pack,
3361 // note that the template argument pack is partially substituted and record
3362 // the explicit template arguments. They'll be used as part of deduction
3363 // for this template parameter pack.
3364 unsigned PartiallySubstitutedPackIndex = -1u;
3365 if (!CanonicalBuilder.empty()) {
3366 const TemplateArgument &Arg = CanonicalBuilder.back();
3367 if (Arg.getKind() == TemplateArgument::Pack) {
3368 auto *Param = TemplateParams->getParam(CanonicalBuilder.size() - 1);
3369 // If this is a fully-saturated fixed-size pack, it should be
3370 // fully-substituted, not partially-substituted.
3371 std::optional<unsigned> Expansions = getExpandedPackSize(Param);
3372 if (!Expansions || Arg.pack_size() < *Expansions) {
3373 PartiallySubstitutedPackIndex = CanonicalBuilder.size() - 1;
3375 Param, Arg.pack_begin(), Arg.pack_size());
3376 }
3377 }
3378 }
3379
3380 const FunctionProtoType *Proto
3381 = Function->getType()->getAs<FunctionProtoType>();
3382 assert(Proto && "Function template does not have a prototype?");
3383
3384 // Isolate our substituted parameters from our caller.
3385 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3386
3387 ExtParameterInfoBuilder ExtParamInfos;
3388
3390 SugaredExplicitArgumentList->asArray(),
3391 /*Final=*/true);
3392
3393 // Instantiate the types of each of the function parameters given the
3394 // explicitly-specified template arguments. If the function has a trailing
3395 // return type, substitute it after the arguments to ensure we substitute
3396 // in lexical order.
3397 if (Proto->hasTrailingReturn()) {
3398 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3399 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3400 /*params=*/nullptr, ExtParamInfos))
3402 }
3403
3404 // Instantiate the return type.
3405 QualType ResultType;
3406 {
3407 // C++11 [expr.prim.general]p3:
3408 // If a declaration declares a member function or member function
3409 // template of a class X, the expression this is a prvalue of type
3410 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3411 // and the end of the function-definition, member-declarator, or
3412 // declarator.
3413 Qualifiers ThisTypeQuals;
3414 CXXRecordDecl *ThisContext = nullptr;
3415 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3416 ThisContext = Method->getParent();
3417 ThisTypeQuals = Method->getMethodQualifiers();
3418 }
3419
3420 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3422
3423 ResultType =
3424 SubstType(Proto->getReturnType(), MLTAL,
3425 Function->getTypeSpecStartLoc(), Function->getDeclName());
3426 if (ResultType.isNull() || Trap.hasErrorOccurred())
3428 // CUDA: Kernel function must have 'void' return type.
3429 if (getLangOpts().CUDA)
3430 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3431 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3432 << Function->getType() << Function->getSourceRange();
3434 }
3435 }
3436
3437 // Instantiate the types of each of the function parameters given the
3438 // explicitly-specified template arguments if we didn't do so earlier.
3439 if (!Proto->hasTrailingReturn() &&
3440 SubstParmTypes(Function->getLocation(), Function->parameters(),
3441 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3442 /*params*/ nullptr, ExtParamInfos))
3444
3445 if (FunctionType) {
3446 auto EPI = Proto->getExtProtoInfo();
3447 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3448
3449 // In C++1z onwards, exception specifications are part of the function type,
3450 // so substitution into the type must also substitute into the exception
3451 // specification.
3452 SmallVector<QualType, 4> ExceptionStorage;
3453 if (getLangOpts().CPlusPlus17 &&
3455 Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
3457 FunctionTemplate, nullptr, /*Final=*/true,
3458 /*Innermost=*/SugaredExplicitArgumentList->asArray(),
3459 /*RelativeToPrimary=*/false,
3460 /*Pattern=*/nullptr,
3461 /*ForConstraintInstantiation=*/false,
3462 /*SkipForSpecialization=*/true)))
3464
3465 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3466 Function->getLocation(),
3467 Function->getDeclName(),
3468 EPI);
3469 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3471 }
3472
3473 // C++ [temp.arg.explicit]p2:
3474 // Trailing template arguments that can be deduced (14.8.2) may be
3475 // omitted from the list of explicit template-arguments. If all of the
3476 // template arguments can be deduced, they may all be omitted; in this
3477 // case, the empty template argument list <> itself may also be omitted.
3478 //
3479 // Take all of the explicitly-specified arguments and put them into
3480 // the set of deduced template arguments. The partially-substituted
3481 // parameter pack, however, will be set to NULL since the deduction
3482 // mechanism handles the partially-substituted argument pack directly.
3483 Deduced.reserve(TemplateParams->size());
3484 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3485 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3486 if (I == PartiallySubstitutedPackIndex)
3487 Deduced.push_back(DeducedTemplateArgument());
3488 else
3489 Deduced.push_back(Arg);
3490 }
3491
3493}
3494
3495/// Check whether the deduced argument type for a call to a function
3496/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3499 Sema::OriginalCallArg OriginalArg,
3500 QualType DeducedA) {
3501 ASTContext &Context = S.Context;
3502
3503 auto Failed = [&]() -> TemplateDeductionResult {
3504 Info.FirstArg = TemplateArgument(DeducedA);
3505 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3506 Info.CallArgIndex = OriginalArg.ArgIdx;
3507 return OriginalArg.DecomposedParam
3510 };
3511
3512 QualType A = OriginalArg.OriginalArgType;
3513 QualType OriginalParamType = OriginalArg.OriginalParamType;
3514
3515 // Check for type equality (top-level cv-qualifiers are ignored).
3516 if (Context.hasSameUnqualifiedType(A, DeducedA))
3518
3519 // Strip off references on the argument types; they aren't needed for
3520 // the following checks.
3521 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3522 DeducedA = DeducedARef->getPointeeType();
3523 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3524 A = ARef->getPointeeType();
3525
3526 // C++ [temp.deduct.call]p4:
3527 // [...] However, there are three cases that allow a difference:
3528 // - If the original P is a reference type, the deduced A (i.e., the
3529 // type referred to by the reference) can be more cv-qualified than
3530 // the transformed A.
3531 if (const ReferenceType *OriginalParamRef
3532 = OriginalParamType->getAs<ReferenceType>()) {
3533 // We don't want to keep the reference around any more.
3534 OriginalParamType = OriginalParamRef->getPointeeType();
3535
3536 // FIXME: Resolve core issue (no number yet): if the original P is a
3537 // reference type and the transformed A is function type "noexcept F",
3538 // the deduced A can be F.
3539 QualType Tmp;
3540 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3542
3543 Qualifiers AQuals = A.getQualifiers();
3544 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3545
3546 // Under Objective-C++ ARC, the deduced type may have implicitly
3547 // been given strong or (when dealing with a const reference)
3548 // unsafe_unretained lifetime. If so, update the original
3549 // qualifiers to include this lifetime.
3550 if (S.getLangOpts().ObjCAutoRefCount &&
3551 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3553 (DeducedAQuals.hasConst() &&
3554 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3555 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3556 }
3557
3558 if (AQuals == DeducedAQuals) {
3559 // Qualifiers match; there's nothing to do.
3560 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
3561 return Failed();
3562 } else {
3563 // Qualifiers are compatible, so have the argument type adopt the
3564 // deduced argument type's qualifiers as if we had performed the
3565 // qualification conversion.
3566 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3567 }
3568 }
3569
3570 // - The transformed A can be another pointer or pointer to member
3571 // type that can be converted to the deduced A via a function pointer
3572 // conversion and/or a qualification conversion.
3573 //
3574 // Also allow conversions which merely strip __attribute__((noreturn)) from
3575 // function types (recursively).
3576 bool ObjCLifetimeConversion = false;
3577 QualType ResultTy;
3578 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3579 (S.IsQualificationConversion(A, DeducedA, false,
3580 ObjCLifetimeConversion) ||
3581 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3583
3584 // - If P is a class and P has the form simple-template-id, then the
3585 // transformed A can be a derived class of the deduced A. [...]
3586 // [...] Likewise, if P is a pointer to a class of the form
3587 // simple-template-id, the transformed A can be a pointer to a
3588 // derived class pointed to by the deduced A.
3589 if (const PointerType *OriginalParamPtr
3590 = OriginalParamType->getAs<PointerType>()) {
3591 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3592 if (const PointerType *APtr = A->getAs<PointerType>()) {
3593 if (A->getPointeeType()->isRecordType()) {
3594 OriginalParamType = OriginalParamPtr->getPointeeType();
3595 DeducedA = DeducedAPtr->getPointeeType();
3596 A = APtr->getPointeeType();
3597 }
3598 }
3599 }
3600 }
3601
3602 if (Context.hasSameUnqualifiedType(A, DeducedA))
3604
3605 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3606 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3608
3609 return Failed();
3610}
3611
3612/// Find the pack index for a particular parameter index in an instantiation of
3613/// a function template with specific arguments.
3614///
3615/// \return The pack index for whichever pack produced this parameter, or -1
3616/// if this was not produced by a parameter. Intended to be used as the
3617/// ArgumentPackSubstitutionIndex for further substitutions.
3618// FIXME: We should track this in OriginalCallArgs so we don't need to
3619// reconstruct it here.
3620static unsigned getPackIndexForParam(Sema &S,
3621 FunctionTemplateDecl *FunctionTemplate,
3623 unsigned ParamIdx) {
3624 unsigned Idx = 0;
3625 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3626 if (PD->isParameterPack()) {
3627 unsigned NumExpansions =
3628 S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
3629 if (Idx + NumExpansions > ParamIdx)
3630 return ParamIdx - Idx;
3631 Idx += NumExpansions;
3632 } else {
3633 if (Idx == ParamIdx)
3634 return -1; // Not a pack expansion
3635 ++Idx;
3636 }
3637 }
3638
3639 llvm_unreachable("parameter index would not be produced from template");
3640}
3641
3642// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3643// we'll try to instantiate and update its explicit specifier after constraint
3644// checking.
3647 const MultiLevelTemplateArgumentList &SubstArgs,
3648 TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate,
3649 ArrayRef<TemplateArgument> DeducedArgs) {
3650 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3651 return isa<CXXConstructorDecl>(D)
3652 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3653 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3654 };
3655 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3656 isa<CXXConstructorDecl>(D)
3657 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3658 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3659 };
3660
3661 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3662 Expr *ExplicitExpr = ES.getExpr();
3663 if (!ExplicitExpr)
3665 if (!ExplicitExpr->isValueDependent())
3667
3669 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3671 if (Inst.isInvalid())
3673 Sema::SFINAETrap Trap(S);
3674 const ExplicitSpecifier InstantiatedES =
3675 S.instantiateExplicitSpecifier(SubstArgs, ES);
3676 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3677 Specialization->setInvalidDecl(true);
3679 }
3680 SetExplicitSpecifier(Specialization, InstantiatedES);
3682}
3683
3684/// Finish template argument deduction for a function template,
3685/// checking the deduced template arguments for completeness and forming
3686/// the function template specialization.
3687///
3688/// \param OriginalCallArgs If non-NULL, the original call arguments against
3689/// which the deduced argument types should be compared.
3691 FunctionTemplateDecl *FunctionTemplate,
3693 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3695 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3696 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3697 // Unevaluated SFINAE context.
3700 SFINAETrap Trap(*this);
3701
3702 // Enter a new template instantiation context while we instantiate the
3703 // actual function declaration.
3704 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3706 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3708 if (Inst.isInvalid())
3710
3711 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3712
3713 // C++ [temp.deduct.type]p2:
3714 // [...] or if any template argument remains neither deduced nor
3715 // explicitly specified, template argument deduction fails.
3716 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3718 *this, FunctionTemplate, /*IsDeduced*/ true, Deduced, Info,
3719 SugaredBuilder, CanonicalBuilder, CurrentInstantiationScope,
3720 NumExplicitlySpecified, PartialOverloading);
3722 return Result;
3723
3724 // C++ [temp.deduct.call]p10: [DR1391]
3725 // If deduction succeeds for all parameters that contain
3726 // template-parameters that participate in template argument deduction,
3727 // and all template arguments are explicitly specified, deduced, or
3728 // obtained from default template arguments, remaining parameters are then
3729 // compared with the corresponding arguments. For each remaining parameter
3730 // P with a type that was non-dependent before substitution of any
3731 // explicitly-specified template arguments, if the corresponding argument
3732 // A cannot be implicitly converted to P, deduction fails.
3733 if (CheckNonDependent())
3735
3736 // Form the template argument list from the deduced template arguments.
3737 TemplateArgumentList *SugaredDeducedArgumentList =
3739 TemplateArgumentList *CanonicalDeducedArgumentList =
3740 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3741 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3742
3743 // Substitute the deduced template arguments into the function template
3744 // declaration to produce the function template specialization.
3745 DeclContext *Owner = FunctionTemplate->getDeclContext();
3746 if (FunctionTemplate->getFriendObjectKind())
3747 Owner = FunctionTemplate->getLexicalDeclContext();
3748 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3749 // additional check for inline friend,
3750 // ```
3751 // template <class F1> int foo(F1 X);
3752 // template <int A1> struct A {
3753 // template <class F1> friend int foo(F1 X) { return A1; }
3754 // };
3755 // template struct A<1>;
3756 // int a = foo(1.0);
3757 // ```
3758 const FunctionDecl *FDFriend;
3760 FD->isDefined(FDFriend, /*CheckForPendingFriendDefinition*/ true) &&
3762 FD = const_cast<FunctionDecl *>(FDFriend);
3763 Owner = FD->getLexicalDeclContext();
3764 }
3766 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
3767 /*Final=*/false);
3768 Specialization = cast_or_null<FunctionDecl>(
3769 SubstDecl(FD, Owner, SubstArgs));
3770 if (!Specialization || Specialization->isInvalidDecl())
3772
3773 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
3774 FunctionTemplate->getCanonicalDecl());
3775
3776 // If the template argument list is owned by the function template
3777 // specialization, release it.
3778 if (Specialization->getTemplateSpecializationArgs() ==
3779 CanonicalDeducedArgumentList &&
3780 !Trap.hasErrorOccurred())
3781 Info.takeCanonical();
3782
3783 // There may have been an error that did not prevent us from constructing a
3784 // declaration. Mark the declaration invalid and return with a substitution
3785 // failure.
3786 if (Trap.hasErrorOccurred()) {
3787 Specialization->setInvalidDecl(true);
3789 }
3790
3791 // C++2a [temp.deduct]p5
3792 // [...] When all template arguments have been deduced [...] all uses of
3793 // template parameters [...] are replaced with the corresponding deduced
3794 // or default argument values.
3795 // [...] If the function template has associated constraints
3796 // ([temp.constr.decl]), those constraints are checked for satisfaction
3797 // ([temp.constr.constr]). If the constraints are not satisfied, type
3798 // deduction fails.
3799 if (!PartialOverloading ||
3800 (CanonicalBuilder.size() ==
3801 FunctionTemplate->getTemplateParameters()->size())) {
3803 Info.getLocation(), Specialization, CanonicalBuilder,
3806
3808 Info.reset(Info.takeSugared(),
3809 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
3811 }
3812 }
3813
3814 // We skipped the instantiation of the explicit-specifier during the
3815 // substitution of `FD` before. So, we try to instantiate it back if
3816 // `Specialization` is either a constructor or a conversion function.
3817 if (isa<CXXConstructorDecl, CXXConversionDecl>(Specialization)) {
3820 Info, FunctionTemplate,
3821 DeducedArgs)) {
3823 }
3824 }
3825
3826 if (OriginalCallArgs) {
3827 // C++ [temp.deduct.call]p4:
3828 // In general, the deduction process attempts to find template argument
3829 // values that will make the deduced A identical to A (after the type A
3830 // is transformed as described above). [...]
3831 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
3832 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3833 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
3834
3835 auto ParamIdx = OriginalArg.ArgIdx;
3836 unsigned ExplicitOffset =
3837 Specialization->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
3838 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
3839 // FIXME: This presumably means a pack ended up smaller than we
3840 // expected while deducing. Should this not result in deduction
3841 // failure? Can it even happen?
3842 continue;
3843
3844 QualType DeducedA;
3845 if (!OriginalArg.DecomposedParam) {
3846 // P is one of the function parameters, just look up its substituted
3847 // type.
3848 DeducedA =
3849 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
3850 } else {
3851 // P is a decomposed element of a parameter corresponding to a
3852 // braced-init-list argument. Substitute back into P to find the
3853 // deduced A.
3854 QualType &CacheEntry =
3855 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3856 if (CacheEntry.isNull()) {
3858 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3859 ParamIdx));
3860 CacheEntry =
3861 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3862 Specialization->getTypeSpecStartLoc(),
3863 Specialization->getDeclName());
3864 }
3865 DeducedA = CacheEntry;
3866 }
3867
3868 if (auto TDK =
3869 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
3871 return TDK;
3872 }
3873 }
3874
3875 // If we suppressed any diagnostics while performing template argument
3876 // deduction, and if we haven't already instantiated this declaration,
3877 // keep track of these diagnostics. They'll be emitted if this specialization
3878 // is actually used.
3879 if (Info.diag_begin() != Info.diag_end()) {
3880 SuppressedDiagnosticsMap::iterator
3881 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3882 if (Pos == SuppressedDiagnostics.end())
3883 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3884 .append(Info.diag_begin(), Info.diag_end());
3885 }
3886
3888}
3889
3890/// Gets the type of a function for template-argument-deducton
3891/// purposes when it's considered as part of an overload set.
3893 FunctionDecl *Fn) {
3894 // We may need to deduce the return type of the function now.
3895 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
3896 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
3897 return {};
3898
3899 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
3900 if (Method->isImplicitObjectMemberFunction()) {
3901 // An instance method that's referenced in a form that doesn't
3902 // look like a member pointer is just invalid.
3904 return {};
3905
3906 return S.Context.getMemberPointerType(Fn->getType(),
3907 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
3908 }
3909
3910 if (!R.IsAddressOfOperand) return Fn->getType();
3911 return S.Context.getPointerType(Fn->getType());
3912}
3913
3914/// Apply the deduction rules for overload sets.
3915///
3916/// \return the null type if this argument should be treated as an
3917/// undeduced context
3918static QualType
3920 Expr *Arg, QualType ParamType,
3921 bool ParamWasReference,
3922 TemplateSpecCandidateSet *FailedTSC = nullptr) {
3923
3925
3926 OverloadExpr *Ovl = R.Expression;
3927
3928 // C++0x [temp.deduct.call]p4
3929 unsigned TDF = 0;
3930 if (ParamWasReference)
3932 if (R.IsAddressOfOperand)
3933 TDF |= TDF_IgnoreQualifiers;
3934
3935 // C++0x [temp.deduct.call]p6:
3936 // When P is a function type, pointer to function type, or pointer
3937 // to member function type:
3938
3939 if (!ParamType->isFunctionType() &&
3940 !ParamType->isFunctionPointerType() &&
3941 !ParamType->isMemberFunctionPointerType()) {
3942 if (Ovl->hasExplicitTemplateArgs()) {
3943 // But we can still look for an explicit specialization.
3944 if (FunctionDecl *ExplicitSpec =
3946 Ovl, /*Complain=*/false,
3947 /*FoundDeclAccessPair=*/nullptr, FailedTSC))
3948 return GetTypeOfFunction(S, R, ExplicitSpec);
3949 }
3950
3951 DeclAccessPair DAP;
3952 if (FunctionDecl *Viable =
3954 return GetTypeOfFunction(S, R, Viable);
3955
3956 return {};
3957 }
3958
3959 // Gather the explicit template arguments, if any.
3960 TemplateArgumentListInfo ExplicitTemplateArgs;
3961 if (Ovl->hasExplicitTemplateArgs())
3962 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
3963 QualType Match;
3964 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3965 E = Ovl->decls_end(); I != E; ++I) {
3966 NamedDecl *D = (*I)->getUnderlyingDecl();
3967
3968 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3969 // - If the argument is an overload set containing one or more
3970 // function templates, the parameter is treated as a
3971 // non-deduced context.
3972 if (!Ovl->hasExplicitTemplateArgs())
3973 return {};
3974
3975 // Otherwise, see if we can resolve a function type
3976 FunctionDecl *Specialization = nullptr;
3977 TemplateDeductionInfo Info(Ovl->getNameLoc());
3978 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3981 continue;
3982
3983 D = Specialization;
3984 }
3985
3986 FunctionDecl *Fn = cast<FunctionDecl>(D);
3987 QualType ArgType = GetTypeOfFunction(S, R, Fn);
3988 if (ArgType.isNull()) continue;
3989
3990 // Function-to-pointer conversion.
3991 if (!ParamWasReference && ParamType->isPointerType() &&
3992 ArgType->isFunctionType())
3993 ArgType = S.Context.getPointerType(ArgType);
3994
3995 // - If the argument is an overload set (not containing function
3996 // templates), trial argument deduction is attempted using each
3997 // of the members of the set. If deduction succeeds for only one
3998 // of the overload set members, that member is used as the
3999 // argument value for the deduction. If deduction succeeds for
4000 // more than one member of the overload set the parameter is
4001 // treated as a non-deduced context.
4002
4003 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4004 // Type deduction is done independently for each P/A pair, and
4005 // the deduced template argument values are then combined.
4006 // So we do not reject deductions which were made elsewhere.
4008 Deduced(TemplateParams->size());
4009 TemplateDeductionInfo Info(Ovl->getNameLoc());
4011 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF);
4013 continue;
4014 if (!Match.isNull())
4015 return {};
4016 Match = ArgType;
4017 }
4018
4019 return Match;
4020}
4021
4022/// Perform the adjustments to the parameter and argument types
4023/// described in C++ [temp.deduct.call].
4024///
4025/// \returns true if the caller should not attempt to perform any template
4026/// argument deduction based on this P/A pair because the argument is an
4027/// overloaded function set that could not be resolved.
4029 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4030 QualType &ParamType, QualType &ArgType,
4031 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4032 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4033 // C++0x [temp.deduct.call]p3:
4034 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4035 // are ignored for type deduction.
4036 if (ParamType.hasQualifiers())
4037 ParamType = ParamType.getUnqualifiedType();
4038
4039 // [...] If P is a reference type, the type referred to by P is
4040 // used for type deduction.
4041 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4042 if (ParamRefType)
4043 ParamType = ParamRefType->getPointeeType();
4044
4045 // Overload sets usually make this parameter an undeduced context,
4046 // but there are sometimes special circumstances. Typically
4047 // involving a template-id-expr.
4048 if (ArgType == S.Context.OverloadTy) {
4049 assert(Arg && "expected a non-null arg expression");
4050 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4051 ParamRefType != nullptr, FailedTSC);
4052 if (ArgType.isNull())
4053 return true;
4054 }
4055
4056 if (ParamRefType) {
4057 // If the argument has incomplete array type, try to complete its type.
4058 if (ArgType->isIncompleteArrayType()) {
4059 assert(Arg && "expected a non-null arg expression");
4060 ArgType = S.getCompletedType(Arg);
4061 }
4062
4063 // C++1z [temp.deduct.call]p3:
4064 // If P is a forwarding reference and the argument is an lvalue, the type
4065 // "lvalue reference to A" is used in place of A for type deduction.
4066 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4067 ArgClassification.isLValue()) {
4068 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4069 ArgType = S.Context.getAddrSpaceQualType(
4071 ArgType = S.Context.getLValueReferenceType(ArgType);
4072 }
4073 } else {
4074 // C++ [temp.deduct.call]p2:
4075 // If P is not a reference type:
4076 // - If A is an array type, the pointer type produced by the
4077 // array-to-pointer standard conversion (4.2) is used in place of
4078 // A for type deduction; otherwise,
4079 // - If A is a function type, the pointer type produced by the
4080 // function-to-pointer standard conversion (4.3) is used in place
4081 // of A for type deduction; otherwise,
4082 if (ArgType->canDecayToPointerType())
4083 ArgType = S.Context.getDecayedType(ArgType);
4084 else {
4085 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4086 // type are ignored for type deduction.
4087 ArgType = ArgType.getUnqualifiedType();
4088 }
4089 }
4090
4091 // C++0x [temp.deduct.call]p4:
4092 // In general, the deduction process attempts to find template argument
4093 // values that will make the deduced A identical to A (after the type A
4094 // is transformed as described above). [...]
4096
4097 // - If the original P is a reference type, the deduced A (i.e., the
4098 // type referred to by the reference) can be more cv-qualified than
4099 // the transformed A.
4100 if (ParamRefType)
4102 // - The transformed A can be another pointer or pointer to member
4103 // type that can be converted to the deduced A via a qualification
4104 // conversion (4.4).
4105 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4106 ArgType->isObjCObjectPointerType())
4107 TDF |= TDF_IgnoreQualifiers;
4108 // - If P is a class and P has the form simple-template-id, then the
4109 // transformed A can be a derived class of the deduced A. Likewise,
4110 // if P is a pointer to a class of the form simple-template-id, the
4111 // transformed A can be a pointer to a derived class pointed to by
4112 // the deduced A.
4113 if (isSimpleTemplateIdType(ParamType) ||
4114 (isa<PointerType>(ParamType) &&
4116 ParamType->castAs<PointerType>()->getPointeeType())))
4117 TDF |= TDF_DerivedClass;
4118
4119 return false;
4120}
4121
4122static bool
4124 QualType T);
4125
4127 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4128 QualType ParamType, QualType ArgType,
4129 Expr::Classification ArgClassification, Expr *Arg,
4133 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4134 TemplateSpecCandidateSet *FailedTSC = nullptr);
4135
4136/// Attempt template argument deduction from an initializer list
4137/// deemed to be an argument in a function call.
4139 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4142 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4143 unsigned TDF) {
4144 // C++ [temp.deduct.call]p1: (CWG 1591)
4145 // If removing references and cv-qualifiers from P gives
4146 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4147 // a non-empty initializer list, then deduction is performed instead for
4148 // each element of the initializer list, taking P0 as a function template
4149 // parameter type and the initializer element as its argument
4150 //
4151 // We've already removed references and cv-qualifiers here.
4152 if (!ILE->getNumInits())
4154
4155 QualType ElTy;
4156 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4157 if (ArrTy)
4158 ElTy = ArrTy->getElementType();
4159 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4160 // Otherwise, an initializer list argument causes the parameter to be
4161 // considered a non-deduced context
4163 }
4164
4165 // Resolving a core issue: a braced-init-list containing any designators is
4166 // a non-deduced context.
4167 for (Expr *E : ILE->inits())
4168 if (isa<DesignatedInitExpr>(E))
4170
4171 // Deduction only needs to be done for dependent types.
4172 if (ElTy->isDependentType()) {
4173 for (Expr *E : ILE->inits()) {
4175 S, TemplateParams, 0, ElTy, E->getType(),
4176 E->Classify(S.getASTContext()), E, Info, Deduced,
4177 OriginalCallArgs, true, ArgIdx, TDF);
4179 return Result;
4180 }
4181 }
4182
4183 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4184 // from the length of the initializer list.
4185 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4186 // Determine the array bound is something we can deduce.
4187 if (const NonTypeTemplateParmDecl *NTTP =
4188 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
4189 // We can perform template argument deduction for the given non-type
4190 // template parameter.
4191 // C++ [temp.deduct.type]p13:
4192 // The type of N in the type T[N] is std::size_t.
4194 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
4196 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4197 /*ArrayBound=*/true, Info, Deduced);
4199 return Result;
4200 }
4201 }
4202
4204}
4205
4206/// Perform template argument deduction per [temp.deduct.call] for a
4207/// single parameter / argument pair.
4209 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4210 QualType ParamType, QualType ArgType,
4211 Expr::Classification ArgClassification, Expr *Arg,
4215 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4216 TemplateSpecCandidateSet *FailedTSC) {
4217
4218 QualType OrigParamType = ParamType;
4219
4220 // If P is a reference type [...]
4221 // If P is a cv-qualified type [...]
4223 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4224 ArgClassification, Arg, TDF, FailedTSC))
4226
4227 // If [...] the argument is a non-empty initializer list [...]
4228 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4229 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4230 Deduced, OriginalCallArgs, ArgIdx, TDF);
4231
4232 // [...] the deduction process attempts to find template argument values
4233 // that will make the deduced A identical to A
4234 //
4235 // Keep track of the argument type and corresponding parameter index,
4236 // so we can check for compatibility between the deduced A and A.
4237 if (Arg)
4238 OriginalCallArgs.push_back(
4239 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4240 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
4241 ArgType, Info, Deduced, TDF);
4242}
4243
4244/// Perform template argument deduction from a function call
4245/// (C++ [temp.deduct.call]).
4246///
4247/// \param FunctionTemplate the function template for which we are performing
4248/// template argument deduction.
4249///
4250/// \param ExplicitTemplateArgs the explicit template arguments provided
4251/// for this call.
4252///
4253/// \param Args the function call arguments
4254///
4255/// \param Specialization if template argument deduction was successful,
4256/// this will be set to the function template specialization produced by
4257/// template argument deduction.
4258///
4259/// \param Info the argument will be updated to provide additional information
4260/// about template argument deduction.
4261///
4262/// \param CheckNonDependent A callback to invoke to check conversions for
4263/// non-dependent parameters, between deduction and substitution, per DR1391.
4264/// If this returns true, substitution will be skipped and we return
4265/// TemplateDeductionResult::NonDependentConversionFailure. The callback is
4266/// passed the parameter types (after substituting explicit template arguments).
4267///
4268/// \returns the result of template argument deduction.
4270 FunctionTemplateDecl *FunctionTemplate,
4271 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4273 bool PartialOverloading, bool AggregateDeductionCandidate,
4274 QualType ObjectType, Expr::Classification ObjectClassification,
4275 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
4276 if (FunctionTemplate->isInvalidDecl())
4278
4279 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4280 unsigned NumParams = Function->getNumParams();
4281 bool HasExplicitObject = false;
4282 int ExplicitObjectOffset = 0;
4283 if (Function->hasCXXExplicitFunctionObjectParameter()) {
4284 HasExplicitObject = true;
4285 ExplicitObjectOffset = 1;
4286 }
4287
4288 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4289
4290 // C++ [temp.deduct.call]p1:
4291 // Template argument deduction is done by comparing each function template
4292 // parameter type (call it P) with the type of the corresponding argument
4293 // of the call (call it A) as described below.
4294 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4295 !PartialOverloading)
4297 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4298 PartialOverloading)) {
4299 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4300 if (Proto->isTemplateVariadic())
4301 /* Do nothing */;
4302 else if (!Proto->isVariadic())
4304 }
4305
4306 // The types of the parameters from which we will perform template argument
4307 // deduction.
4308 LocalInstantiationScope InstScope(*this);
4309 TemplateParameterList *TemplateParams
4310 = FunctionTemplate->getTemplateParameters();
4312 SmallVector<QualType, 8> ParamTypes;
4313 unsigned NumExplicitlySpecified = 0;
4314 if (ExplicitTemplateArgs) {
4317 Result = SubstituteExplicitTemplateArguments(
4318 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4319 Info);
4320 });
4322 return Result;
4323
4324 NumExplicitlySpecified = Deduced.size();
4325 } else {
4326 // Just fill in the parameter types from the function declaration.
4327 for (unsigned I = 0; I != NumParams; ++I)
4328 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4329 }
4330
4331 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4332
4333 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4334 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4335 bool ExplicitObjetArgument) {
4336 // C++ [demp.deduct.call]p1: (DR1391)
4337 // Template argument deduction is done by comparing each function template
4338 // parameter that contains template-parameters that participate in
4339 // template argument deduction ...
4340 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4342
4343 if (ExplicitObjetArgument) {
4344 // ... with the type of the corresponding argument
4346 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4347 ObjectClassification,
4348 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4349 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4350 }
4351
4352 // ... with the type of the corresponding argument
4354 *this, TemplateParams, FirstInnerIndex, ParamType,
4355 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4356 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4357 ArgIdx, /*TDF*/ 0);
4358 };
4359
4360 // Deduce template arguments from the function parameters.
4361 Deduced.resize(TemplateParams->size());
4362 SmallVector<QualType, 8> ParamTypesForArgChecking;
4363 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4364 ParamIdx != NumParamTypes; ++ParamIdx) {
4365 QualType ParamType = ParamTypes[ParamIdx];
4366
4367 const PackExpansionType *ParamExpansion =
4368 dyn_cast<PackExpansionType>(ParamType);
4369 if (!ParamExpansion) {
4370 // Simple case: matching a function parameter to a function argument.
4371 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4372 break;
4373
4374 ParamTypesForArgChecking.push_back(ParamType);
4375
4376 if (ParamIdx == 0 && HasExplicitObject) {
4377 if (auto Result = DeduceCallArgument(ParamType, 0,
4378 /*ExplicitObjetArgument=*/true);
4380 return Result;
4381 continue;
4382 }
4383
4384 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4385 /*ExplicitObjetArgument=*/false);
4387 return Result;
4388
4389 continue;
4390 }
4391
4392 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4393
4394 QualType ParamPattern = ParamExpansion->getPattern();
4395 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4396 ParamPattern,
4397 AggregateDeductionCandidate && IsTrailingPack);
4398
4399 // C++0x [temp.deduct.call]p1:
4400 // For a function parameter pack that occurs at the end of the
4401 // parameter-declaration-list, the type A of each remaining argument of
4402 // the call is compared with the type P of the declarator-id of the
4403 // function parameter pack. Each comparison deduces template arguments
4404 // for subsequent positions in the template parameter packs expanded by
4405 // the function parameter pack. When a function parameter pack appears
4406 // in a non-deduced context [not at the end of the list], the type of
4407 // that parameter pack is never deduced.
4408 //
4409 // FIXME: The above rule allows the size of the parameter pack to change
4410 // after we skip it (in the non-deduced case). That makes no sense, so
4411 // we instead notionally deduce the pack against N arguments, where N is
4412 // the length of the explicitly-specified pack if it's expanded by the
4413 // parameter pack and 0 otherwise, and we treat each deduction as a
4414 // non-deduced context.
4415 if (IsTrailingPack || PackScope.hasFixedArity()) {
4416 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4417 PackScope.nextPackElement(), ++ArgIdx) {
4418 ParamTypesForArgChecking.push_back(ParamPattern);
4419 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4420 /*ExplicitObjetArgument=*/false);
4422 return Result;
4423 }
4424 } else {
4425 // If the parameter type contains an explicitly-specified pack that we
4426 // could not expand, skip the number of parameters notionally created
4427 // by the expansion.
4428 std::optional<unsigned> NumExpansions =
4429 ParamExpansion->getNumExpansions();
4430 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4431 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4432 ++I, ++ArgIdx) {
4433 ParamTypesForArgChecking.push_back(ParamPattern);
4434 // FIXME: Should we add OriginalCallArgs for these? What if the
4435 // corresponding argument is a list?
4436 PackScope.nextPackElement();
4437 }
4438 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4439 PackScope.isDeducedFromEarlierParameter()) {
4440 // [temp.deduct.general#3]
4441 // When all template arguments have been deduced
4442 // or obtained from default template arguments, all uses of template
4443 // parameters in the template parameter list of the template are
4444 // replaced with the corresponding deduced or default argument values
4445 //
4446 // If we have a trailing parameter pack, that has been deduced
4447 // previously we substitute the pack here in a similar fashion as
4448 // above with the trailing parameter packs. The main difference here is
4449 // that, in this case we are not processing all of the remaining
4450 // arguments. We are only process as many arguments as we have in
4451 // the already deduced parameter.
4452 std::optional<unsigned> ArgPosAfterSubstitution =
4453 PackScope.getSavedPackSizeIfAllEqual();
4454 if (!ArgPosAfterSubstitution)
4455 continue;
4456
4457 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4458 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4459 ParamTypesForArgChecking.push_back(ParamPattern);
4460 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4461 /*ExplicitObjetArgument=*/false);
4463 return Result;
4464
4465 PackScope.nextPackElement();
4466 }
4467 }
4468 }
4469
4470 // Build argument packs for each of the parameter packs expanded by this
4471 // pack expansion.
4472 if (auto Result = PackScope.finish();
4474 return Result;
4475 }
4476
4477 // Capture the context in which the function call is made. This is the context
4478 // that is needed when the accessibility of template arguments is checked.
4479 DeclContext *CallingCtx = CurContext;
4480
4483 Result = FinishTemplateArgumentDeduction(
4484 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4485 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
4486 ContextRAII SavedContext(*this, CallingCtx);
4487 return CheckNonDependent(ParamTypesForArgChecking);
4488 });
4489 });
4490 return Result;
4491}
4492
4495 bool AdjustExceptionSpec) {
4496 if (ArgFunctionType.isNull())
4497 return ArgFunctionType;
4498
4499 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4500 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4501 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4502 bool Rebuild = false;
4503
4504 CallingConv CC = FunctionTypeP->getCallConv();
4505 if (EPI.ExtInfo.getCC() != CC) {
4506 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4507 Rebuild = true;
4508 }
4509
4510 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4511 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4512 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4513 Rebuild = true;
4514 }
4515
4516 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4517 ArgFunctionTypeP->hasExceptionSpec())) {
4518 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4519 Rebuild = true;
4520 }
4521
4522 if (!Rebuild)
4523 return ArgFunctionType;
4524
4525 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4526 ArgFunctionTypeP->getParamTypes(), EPI);
4527}
4528
4529/// Deduce template arguments when taking the address of a function
4530/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
4531/// a template.
4532///
4533/// \param FunctionTemplate the function template for which we are performing
4534/// template argument deduction.
4535///
4536/// \param ExplicitTemplateArgs the explicitly-specified template
4537/// arguments.
4538///
4539/// \param ArgFunctionType the function type that will be used as the
4540/// "argument" type (A) when performing template argument deduction from the
4541/// function template's function type. This type may be NULL, if there is no
4542/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
4543///
4544/// \param Specialization if template argument deduction was successful,
4545/// this will be set to the function template specialization produced by
4546/// template argument deduction.
4547///
4548/// \param Info the argument will be updated to provide additional information
4549/// about template argument deduction.
4550///
4551/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4552/// the address of a function template per [temp.deduct.funcaddr] and
4553/// [over.over]. If \c false, we are looking up a function template
4554/// specialization based on its signature, per [temp.deduct.decl].
4555///
4556/// \returns the result of template argument deduction.
4558 FunctionTemplateDecl *FunctionTemplate,
4559 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4561 bool IsAddressOfFunction) {
4562 if (FunctionTemplate->isInvalidDecl())
4564
4565 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4566 TemplateParameterList *TemplateParams
4567 = FunctionTemplate->getTemplateParameters();
4568 QualType FunctionType = Function->getType();
4569
4570 // Substitute any explicit template arguments.
4571 LocalInstantiationScope InstScope(*this);
4573 unsigned NumExplicitlySpecified = 0;
4574 SmallVector<QualType, 4> ParamTypes;
4575 if (ExplicitTemplateArgs) {
4578 Result = SubstituteExplicitTemplateArguments(
4579 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4580 &FunctionType, Info);
4581 });
4583 return Result;
4584
4585 NumExplicitlySpecified = Deduced.size();
4586 }
4587
4588 // When taking the address of a function, we require convertibility of
4589 // the resulting function type. Otherwise, we allow arbitrary mismatches
4590 // of calling convention and noreturn.
4591 if (!IsAddressOfFunction)
4592 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4593 /*AdjustExceptionSpec*/false);
4594
4595 // Unevaluated SFINAE context.
4598 SFINAETrap Trap(*this);
4599
4600 Deduced.resize(TemplateParams->size());
4601
4602 // If the function has a deduced return type, substitute it for a dependent
4603 // type so that we treat it as a non-deduced context in what follows.
4604 bool HasDeducedReturnType = false;
4605 if (getLangOpts().CPlusPlus14 &&
4606 Function->getReturnType()->getContainedAutoType()) {
4608 HasDeducedReturnType = true;
4609 }
4610
4611 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4612 unsigned TDF =
4614 // Deduce template arguments from the function type.
4616 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4617 TDF);
4619 return Result;
4620 }
4621
4624 Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4625 NumExplicitlySpecified,
4626 Specialization, Info);
4627 });
4629 return Result;
4630
4631 // If the function has a deduced return type, deduce it now, so we can check
4632 // that the deduced function type matches the requested type.
4633 if (HasDeducedReturnType && IsAddressOfFunction &&
4634 Specialization->getReturnType()->isUndeducedType() &&
4637
4638 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4639 Specialization->isImmediateEscalating() &&
4641 Info.getLocation()))
4643
4644 auto *SpecializationFPT =
4645 Specialization->getType()->castAs<FunctionProtoType>();
4646 if (IsAddressOfFunction && getLangOpts().CPlusPlus17 &&
4647 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
4648 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
4650
4651 // Adjust the exception specification of the argument to match the
4652 // substituted and resolved type we just formed. (Calling convention and
4653 // noreturn can't be dependent, so we don't actually need this for them
4654 // right now.)
4655 QualType SpecializationType = Specialization->getType();
4656 if (!IsAddressOfFunction) {
4657 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4658 /*AdjustExceptionSpec*/true);
4659
4660 // Revert placeholder types in the return type back to undeduced types so
4661 // that the comparison below compares the declared return types.
4662 if (HasDeducedReturnType) {
4663 SpecializationType = SubstAutoType(SpecializationType, QualType());
4664 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4665 }
4666 }
4667
4668 // If the requested function type does not match the actual type of the
4669 // specialization with respect to arguments of compatible pointer to function
4670 // types, template argument deduction fails.
4671 if (!ArgFunctionType.isNull()) {
4672 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4673 Context.getCanonicalType(SpecializationType),
4674 Context.getCanonicalType(ArgFunctionType))
4676 SpecializationType, ArgFunctionType)) {
4677 Info.FirstArg = TemplateArgument(SpecializationType);
4678 Info.SecondArg = TemplateArgument(ArgFunctionType);
4680 }
4681 }
4682
4684}
4685
4686/// Deduce template arguments for a templated conversion
4687/// function (C++ [temp.deduct.conv]) and, if successful, produce a
4688/// conversion function template specialization.
4690 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4691 Expr::Classification ObjectClassification, QualType ToType,
4693 if (ConversionTemplate->isInvalidDecl())
4695
4696 CXXConversionDecl *ConversionGeneric
4697 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4698
4699 QualType FromType = ConversionGeneric->getConversionType();
4700
4701 // Canonicalize the types for deduction.
4702 QualType P = Context.getCanonicalType(FromType);
4703 QualType A = Context.getCanonicalType(ToType);
4704
4705 // C++0x [temp.deduct.conv]p2:
4706 // If P is a reference type, the type referred to by P is used for
4707 // type deduction.
4708 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4709 P = PRef->getPointeeType();
4710
4711 // C++0x [temp.deduct.conv]p4:
4712 // [...] If A is a reference type, the type referred to by A is used
4713 // for type deduction.
4714 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4715 A = ARef->getPointeeType();
4716 // We work around a defect in the standard here: cv-qualifiers are also
4717 // removed from P and A in this case, unless P was a reference type. This
4718 // seems to mostly match what other compilers are doing.
4719 if (!FromType->getAs<ReferenceType>()) {
4720 A = A.getUnqualifiedType();
4721 P = P.getUnqualifiedType();
4722 }
4723
4724 // C++ [temp.deduct.conv]p3:
4725 //
4726 // If A is not a reference type:
4727 } else {
4728 assert(!A->isReferenceType() && "Reference types were handled above");
4729
4730 // - If P is an array type, the pointer type produced by the
4731 // array-to-pointer standard conversion (4.2) is used in place
4732 // of P for type deduction; otherwise,
4733 if (P->isArrayType())
4735 // - If P is a function type, the pointer type produced by the
4736 // function-to-pointer standard conversion (4.3) is used in
4737 // place of P for type deduction; otherwise,
4738 else if (P->isFunctionType())
4740 // - If P is a cv-qualified type, the top level cv-qualifiers of
4741 // P's type are ignored for type deduction.
4742 else
4743 P = P.getUnqualifiedType();
4744
4745 // C++0x [temp.deduct.conv]p4:
4746 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4747 // type are ignored for type deduction. If A is a reference type, the type
4748 // referred to by A is used for type deduction.
4749 A = A.getUnqualifiedType();
4750 }
4751
4752 // Unevaluated SFINAE context.
4755 SFINAETrap Trap(*this);
4756
4757 // C++ [temp.deduct.conv]p1:
4758 // Template argument deduction is done by comparing the return
4759 // type of the template conversion function (call it P) with the
4760 // type that is required as the result of the conversion (call it
4761 // A) as described in 14.8.2.4.
4762 TemplateParameterList *TemplateParams
4763 = ConversionTemplate->getTemplateParameters();
4765 Deduced.resize(TemplateParams->size());
4766
4767 // C++0x [temp.deduct.conv]p4:
4768 // In general, the deduction process attempts to find template
4769 // argument values that will make the deduced A identical to
4770 // A. However, there are two cases that allow a difference:
4771 unsigned TDF = 0;
4772 // - If the original A is a reference type, A can be more
4773 // cv-qualified than the deduced A (i.e., the type referred to
4774 // by the reference)
4775 if (ToType->isReferenceType())
4777 // - The deduced A can be another pointer or pointer to member
4778 // type that can be converted to A via a qualification
4779 // conversion.
4780 //
4781 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4782 // both P and A are pointers or member pointers. In this case, we
4783 // just ignore cv-qualifiers completely).
4784 if ((P->isPointerType() && A->isPointerType()) ||
4785 (P->isMemberPointerType() && A->isMemberPointerType()))
4786 TDF |= TDF_IgnoreQualifiers;
4787
4789 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
4790 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
4793 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
4794 ParamType, ObjectType, ObjectClassification,
4795 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4796 /*Decomposed*/ false, 0, /*TDF*/ 0);
4798 return Result;
4799 }
4800
4802 *this, TemplateParams, P, A, Info, Deduced, TDF);
4804 return Result;
4805
4806 // Create an Instantiation Scope for finalizing the operator.
4807 LocalInstantiationScope InstScope(*this);
4808 // Finish template argument deduction.
4809 FunctionDecl *ConversionSpecialized = nullptr;
4812 Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4813 ConversionSpecialized, Info,
4814 &OriginalCallArgs);
4815 });
4816 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4817 return Result;
4818}
4819
4820/// Deduce template arguments for a function template when there is
4821/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4822///
4823/// \param FunctionTemplate the function template for which we are performing
4824/// template argument deduction.
4825///
4826/// \param ExplicitTemplateArgs the explicitly-specified template
4827/// arguments.
4828///
4829/// \param Specialization if template argument deduction was successful,
4830/// this will be set to the function template specialization produced by
4831/// template argument deduction.
4832///
4833/// \param Info the argument will be updated to provide additional information
4834/// about template argument deduction.
4835///
4836/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4837/// the address of a function template in a context where we do not have a
4838/// target type, per [over.over]. If \c false, we are looking up a function
4839/// template specialization based on its signature, which only happens when
4840/// deducing a function parameter type from an argument that is a template-id
4841/// naming a function template specialization.
4842///
4843/// \returns the result of template argument deduction.
4846 TemplateArgumentListInfo *ExplicitTemplateArgs,
4849 bool IsAddressOfFunction) {
4850 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4851 QualType(), Specialization, Info,
4852 IsAddressOfFunction);
4853}
4854
4855namespace {
4856 struct DependentAuto { bool IsPack; };
4857
4858 /// Substitute the 'auto' specifier or deduced template specialization type
4859 /// specifier within a type for a given replacement type.
4860 class SubstituteDeducedTypeTransform :
4861 public TreeTransform<SubstituteDeducedTypeTransform> {
4862 QualType Replacement;
4863 bool ReplacementIsPack;
4864 bool UseTypeSugar;
4866
4867 public:
4868 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
4869 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4870 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
4871
4872 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4873 bool UseTypeSugar = true)
4874 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4875 Replacement(Replacement), ReplacementIsPack(false),
4876 UseTypeSugar(UseTypeSugar) {}
4877
4878 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4879 assert(isa<TemplateTypeParmType>(Replacement) &&
4880 "unexpected unsugared replacement kind");
4881 QualType Result = Replacement;
4883 NewTL.setNameLoc(TL.getNameLoc());
4884 return Result;
4885 }
4886
4887 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4888 // If we're building the type pattern to deduce against, don't wrap the
4889 // substituted type in an AutoType. Certain template deduction rules
4890 // apply only when a template type parameter appears directly (and not if
4891 // the parameter is found through desugaring). For instance:
4892 // auto &&lref = lvalue;
4893 // must transform into "rvalue reference to T" not "rvalue reference to
4894 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
4895 //
4896 // FIXME: Is this still necessary?
4897 if (!UseTypeSugar)
4898 return TransformDesugared(TLB, TL);
4899
4900 QualType Result = SemaRef.Context.getAutoType(
4901 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
4902 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
4904 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4905 NewTL.copy(TL);
4906 return Result;
4907 }
4908
4909 QualType TransformDeducedTemplateSpecializationType(
4911 if (!UseTypeSugar)
4912 return TransformDesugared(TLB, TL);
4913
4914 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4916 Replacement, Replacement.isNull());
4917 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4918 NewTL.setNameLoc(TL.getNameLoc());
4919 return Result;
4920 }
4921
4922 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4923 // Lambdas never need to be transformed.
4924 return E;
4925 }
4926 bool TransformExceptionSpec(SourceLocation Loc,
4928 SmallVectorImpl<QualType> &Exceptions,
4929 bool &Changed) {
4930 if (ESI.Type == EST_Uninstantiated) {
4931 ESI.instantiate();
4932 Changed = true;
4933 }
4934 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
4935 }
4936
4937 QualType Apply(TypeLoc TL) {
4938 // Create some scratch storage for the transformed type locations.
4939 // FIXME: We're just going to throw this information away. Don't build it.
4940 TypeLocBuilder TLB;
4941 TLB.reserve(TL.getFullDataSize());
4942 return TransformType(TLB, TL);
4943 }
4944 };
4945
4946} // namespace
4947
4950 QualType Deduced) {
4951 ConstraintSatisfaction Satisfaction;
4952 ConceptDecl *Concept = Type.getTypeConstraintConcept();
4953 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
4954 TypeLoc.getRAngleLoc());
4955 TemplateArgs.addArgument(
4958 Deduced, TypeLoc.getNameLoc())));
4959 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
4960 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
4961
4962 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4963 if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs,
4964 /*PartialTemplateArgs=*/false,
4965 SugaredConverted, CanonicalConverted))
4966 return true;
4967 MultiLevelTemplateArgumentList MLTAL(Concept, CanonicalConverted,
4968 /*Final=*/false);
4969 if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
4971 Satisfaction))
4972 return true;
4973 if (!Satisfaction.IsSatisfied) {
4974 std::string Buf;
4975 llvm::raw_string_ostream OS(Buf);
4976 OS << "'" << Concept->getName();
4977 if (TypeLoc.hasExplicitTemplateArgs()) {
4979 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
4980 Type.getTypeConstraintConcept()->getTemplateParameters());
4981 }
4982 OS << "'";
4983 OS.flush();
4984 S.Diag(TypeLoc.getConceptNameLoc(),
4985 diag::err_placeholder_constraints_not_satisfied)
4986 << Deduced << Buf << TypeLoc.getLocalSourceRange();
4987 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
4988 return true;
4989 }
4990 return false;
4991}
4992
4993/// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
4994///
4995/// Note that this is done even if the initializer is dependent. (This is
4996/// necessary to support partial ordering of templates using 'auto'.)
4997/// A dependent type will be produced when deducing from a dependent type.
4998///
4999/// \param Type the type pattern using the auto type-specifier.
5000/// \param Init the initializer for the variable whose type is to be deduced.
5001/// \param Result if type deduction was successful, this will be set to the
5002/// deduced type.
5003/// \param Info the argument will be updated to provide additional information
5004/// about template argument deduction.
5005/// \param DependentDeduction Set if we should permit deduction in
5006/// dependent cases. This is necessary for template partial ordering with
5007/// 'auto' template parameters. The template parameter depth to be used
5008/// should be specified in the 'Info' parameter.
5009/// \param IgnoreConstraints Set if we should not fail if the deduced type does
5010/// not satisfy the type-constraint in the auto type.
5013 TemplateDeductionInfo &Info, bool DependentDeduction,
5014 bool IgnoreConstraints,
5015 TemplateSpecCandidateSet *FailedTSC) {
5016 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5017 if (Init->containsErrors())
5019
5020 const AutoType *AT = Type.getType()->getContainedAutoType();
5021 assert(AT);
5022
5023 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5024 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5025 if (NonPlaceholder.isInvalid())
5027 Init = NonPlaceholder.get();
5028 }
5029
5030 DependentAuto DependentResult = {
5031 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5032
5033 if (!DependentDeduction &&
5034 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5035 Init->containsUnexpandedParameterPack())) {
5036 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5037 assert(!Result.isNull() && "substituting DependentTy can't fail");
5039 }
5040
5041 // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode.
5042 auto *String = dyn_cast<StringLiteral>(Init);
5043 if (getLangOpts().C23 && String && Type.getType()->isArrayType()) {
5044 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5045 TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData());
5046 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL);
5047 assert(!Result.isNull() && "substituting DependentTy can't fail");
5049 }
5050
5051 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5052 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5053 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5054 }
5055
5056 auto *InitList = dyn_cast<InitListExpr>(Init);
5057 if (!getLangOpts().CPlusPlus && InitList) {
5058 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5059 << (int)AT->getKeyword() << getLangOpts().C23;
5061 }
5062
5063 // Deduce type of TemplParam in Func(Init)
5065 Deduced.resize(1);
5066
5067 // If deduction failed, don't diagnose if the initializer is dependent; it
5068 // might acquire a matching type in the instantiation.
5069 auto DeductionFailed = [&](TemplateDeductionResult TDK) {
5070 if (Init->isTypeDependent()) {
5071 Result =
5072 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5073 assert(!Result.isNull() && "substituting DependentTy can't fail");
5075 }
5076 return TDK;
5077 };
5078
5079 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5080
5082 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5083 if (AT->isDecltypeAuto()) {
5084 if (InitList) {
5085 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5087 }
5088
5090 assert(!DeducedType.isNull());
5091 } else {
5092 LocalInstantiationScope InstScope(*this);
5093
5094 // Build template<class TemplParam> void Func(FuncParam);
5095 SourceLocation Loc = Init->getExprLoc();
5097 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5098 nullptr, false, false, false);
5099 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5100 NamedDecl *TemplParamPtr = TemplParam;
5102 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5103
5104 if (InitList) {
5105 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5106 // deduce against that. Such deduction only succeeds if removing
5107 // cv-qualifiers and references results in std::initializer_list<T>.
5108 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5110
5111 SourceRange DeducedFromInitRange;
5112 for (Expr *Init : InitList->inits()) {
5113 // Resolving a core issue: a braced-init-list containing any designators
5114 // is a non-deduced context.
5115 if (isa<DesignatedInitExpr>(Init))
5118 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5119 Init->Classify(getASTContext()), Init, Info, Deduced,
5120 OriginalCallArgs, /*Decomposed=*/true,
5121 /*ArgIdx=*/0, /*TDF=*/0);
5124 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5125 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5126 << Init->getSourceRange();
5127 return DeductionFailed(TemplateDeductionResult::AlreadyDiagnosed);
5128 }
5129 return DeductionFailed(TDK);
5130 }
5131
5132 if (DeducedFromInitRange.isInvalid() &&
5133 Deduced[0].getKind() != TemplateArgument::Null)
5134 DeducedFromInitRange = Init->getSourceRange();
5135 }
5136 } else {
5137 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5138 Diag(Loc, diag::err_auto_bitfield);
5140 }
5141 QualType FuncParam =
5142 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5143 assert(!FuncParam.isNull() &&
5144 "substituting template parameter for 'auto' failed");
5146 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5147 Init->Classify(getASTContext()), Init, Info, Deduced,
5148 OriginalCallArgs, /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0,
5149 FailedTSC);
5151 return DeductionFailed(TDK);
5152 }
5153
5154 // Could be null if somehow 'auto' appears in a non-deduced context.
5155 if (Deduced[0].getKind() != TemplateArgument::Type)
5156 return DeductionFailed(TemplateDeductionResult::Incomplete);
5157 DeducedType = Deduced[0].getAsType();
5158
5159 if (InitList) {
5161 if (DeducedType.isNull())
5163 }
5164 }
5165
5166 if (!Result.isNull()) {
5168 Info.FirstArg = Result;
5169 Info.SecondArg = DeducedType;
5170 return DeductionFailed(TemplateDeductionResult::Inconsistent);
5171 }
5173 }
5174
5175 if (AT->isConstrained() && !IgnoreConstraints &&
5177 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5179
5180 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5181 if (Result.isNull())
5183
5184 // Check that the deduced argument type is compatible with the original
5185 // argument type per C++ [temp.deduct.call]p4.
5186 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5187 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5188 assert((bool)InitList == OriginalArg.DecomposedParam &&
5189 "decomposed non-init-list in auto deduction?");
5190 if (auto TDK =
5191 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5193 Result = QualType();
5194 return DeductionFailed(TDK);
5195 }
5196 }
5197
5199}
5200
5202 QualType TypeToReplaceAuto) {
5203 assert(TypeToReplaceAuto != Context.DependentTy);
5204 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5205 .TransformType(TypeWithAuto);
5206}
5207
5209 QualType TypeToReplaceAuto) {
5210 assert(TypeToReplaceAuto != Context.DependentTy);
5211 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5212 .TransformType(TypeWithAuto);
5213}
5214
5216 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5217 .TransformType(TypeWithAuto);
5218}
5219
5222 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5223 .TransformType(TypeWithAuto);
5224}
5225
5227 QualType TypeToReplaceAuto) {
5228 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5229 /*UseTypeSugar*/ false)
5230 .TransformType(TypeWithAuto);
5231}
5232
5234 QualType TypeToReplaceAuto) {
5235 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5236 /*UseTypeSugar*/ false)
5237 .TransformType(TypeWithAuto);
5238}
5239
5241 if (isa<InitListExpr>(Init))
5242 Diag(VDecl->getLocation(),
5243 VDecl->isInitCapture()
5244 ? diag::err_init_capture_deduction_failure_from_init_list
5245 : diag::err_auto_var_deduction_failure_from_init_list)
5246 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5247 else
5248 Diag(VDecl->getLocation(),
5249 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5250 : diag::err_auto_var_deduction_failure)
5251 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5252 << Init->getSourceRange();
5253}
5254
5256 bool Diagnose) {
5257 assert(FD->getReturnType()->isUndeducedType());
5258
5259 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5260 // within the return type from the call operator's type.
5262 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5263 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5264
5265 // For a generic lambda, instantiate the call operator if needed.
5266 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5268 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5269 if (!CallOp || CallOp->isInvalidDecl())
5270 return true;
5271
5272 // We might need to deduce the return type by instantiating the definition
5273 // of the operator() function.
5274 if (CallOp->getReturnType()->isUndeducedType()) {
5276 InstantiateFunctionDefinition(Loc, CallOp);
5277 });
5278 }
5279 }
5280
5281 if (CallOp->isInvalidDecl())
5282 return true;
5283 assert(!CallOp->getReturnType()->isUndeducedType() &&
5284 "failed to deduce lambda return type");
5285
5286 // Build the new return type from scratch.
5287 CallingConv RetTyCC = FD->getReturnType()
5288 ->getPointeeType()
5289 ->castAs<FunctionType>()
5290 ->getCallConv();
5292 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5293 if (FD->getReturnType()->getAs<PointerType>())
5294 RetType = Context.getPointerType(RetType);
5295 else {
5296 assert(FD->getReturnType()->getAs<BlockPointerType>());
5297 RetType = Context.getBlockPointerType(RetType);
5298 }
5300 return false;
5301 }
5302
5306 });
5307 }
5308
5309 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5310 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5311 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5312 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5313 }
5314
5315 return StillUndeduced;
5316}
5317
5319 SourceLocation Loc) {
5320 assert(FD->isImmediateEscalating());
5321
5323 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5324 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5325
5326 // For a generic lambda, instantiate the call operator if needed.
5327 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5329 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5330 if (!CallOp || CallOp->isInvalidDecl())
5331 return true;
5333 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5334 }
5335 return CallOp->isInvalidDecl();
5336 }
5337
5340 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5341 }
5342 return false;
5343}
5344
5346 const CXXMethodDecl *Method,
5347 QualType RawType,
5348 bool IsOtherRvr) {
5349 // C++20 [temp.func.order]p3.1, p3.2:
5350 // - The type X(M) is "rvalue reference to cv A" if the optional
5351 // ref-qualifier of M is && or if M has no ref-qualifier and the
5352 // positionally-corresponding parameter of the other transformed template
5353 // has rvalue reference type; if this determination depends recursively
5354 // upon whether X(M) is an rvalue reference type, it is not considered to
5355 // have rvalue reference type.
5356 //
5357 // - Otherwise, X(M) is "lvalue reference to cv A".
5358 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5359 "expected a member function with no explicit object parameter");
5360
5361 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5362 if (Method->getRefQualifier() == RQ_RValue ||
5363 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5364 return Context.getRValueReferenceType(RawType);
5365 return Context.getLValueReferenceType(RawType);
5366}
5367
5368/// Determine whether the function template \p FT1 is at least as
5369/// specialized as \p FT2.
5371 const FunctionTemplateDecl *FT1,
5372 const FunctionTemplateDecl *FT2,
5374 bool Reversed,
5375 const SmallVector<QualType> &Args1,
5376 const SmallVector<QualType> &Args2) {
5377 assert(!Reversed || TPOC == TPOC_Call);
5378
5379 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5380 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5381 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5382 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5383
5384 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5385 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5387 Deduced.resize(TemplateParams->size());
5388
5389 // C++0x [temp.deduct.partial]p3:
5390 // The types used to determine the ordering depend on the context in which
5391 // the partial ordering is done:
5392 TemplateDeductionInfo Info(Loc);
5393 switch (TPOC) {
5394 case TPOC_Call:
5395 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
5396 Args1.data(), Args1.size(), Info, Deduced,
5397 TDF_None, /*PartialOrdering=*/true) !=
5399 return false;
5400
5401 break;
5402
5403 case TPOC_Conversion:
5404 // - In the context of a call to a conversion operator, the return types
5405 // of the conversion function templates are used.
5407 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5408 Info, Deduced, TDF_None,
5409 /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
5410 return false;
5411 break;
5412
5413 case TPOC_Other:
5414 // - In other contexts (14.6.6.2) the function template's function type
5415 // is used.
5417 S, TemplateParams, FD2->getType(), FD1->getType(), Info, Deduced,
5418 TDF_None,
5419 /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
5420 return false;
5421 break;
5422 }
5423
5424 // C++0x [temp.deduct.partial]p11:
5425 // In most cases, all template parameters must have values in order for
5426 // deduction to succeed, but for partial ordering purposes a template
5427 // parameter may remain without a value provided it is not used in the
5428 // types being used for partial ordering. [ Note: a template parameter used
5429 // in a non-deduced context is considered used. -end note]
5430 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5431 for (; ArgIdx != NumArgs; ++ArgIdx)
5432 if (Deduced[ArgIdx].isNull())
5433 break;
5434
5435 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
5436 // to substitute the deduced arguments back into the template and check that
5437 // we get the right type.
5438
5439 if (ArgIdx == NumArgs) {
5440 // All template arguments were deduced. FT1 is at least as specialized
5441 // as FT2.
5442 return true;
5443 }
5444
5445 // Figure out which template parameters were used.
5446 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5447 switch (TPOC) {
5448 case TPOC_Call:
5449 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5450 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
5451 TemplateParams->getDepth(),
5452 UsedParameters);
5453 break;
5454
5455 case TPOC_Conversion:
5456 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
5457 TemplateParams->getDepth(), UsedParameters);
5458 break;
5459
5460 case TPOC_Other:
5462 TemplateParams->getDepth(),
5463 UsedParameters);
5464 break;
5465 }
5466
5467 for (; ArgIdx != NumArgs; ++ArgIdx)
5468 // If this argument had no value deduced but was used in one of the types
5469 // used for partial ordering, then deduction fails.
5470 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5471 return false;
5472
5473 return true;
5474}
5475
5476/// Returns the more specialized function template according
5477/// to the rules of function template partial ordering (C++ [temp.func.order]).
5478///
5479/// \param FT1 the first function template
5480///
5481/// \param FT2 the second function template
5482///
5483/// \param TPOC the context in which we are performing partial ordering of
5484/// function templates.
5485///
5486/// \param NumCallArguments1 The number of arguments in the call to FT1, used
5487/// only when \c TPOC is \c TPOC_Call.
5488///
5489/// \param RawObj1Ty The type of the object parameter of FT1 if a member
5490/// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
5491/// template from a member function
5492///
5493/// \param RawObj2Ty The type of the object parameter of FT2 if a member
5494/// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
5495/// template from a member function
5496///
5497/// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
5498/// candidate with a reversed parameter order. In this case, the corresponding
5499/// P/A pairs between FT1 and FT2 are reversed.
5500///
5501/// \returns the more specialized function template. If neither
5502/// template is more specialized, returns NULL.
5505 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5506 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed) {
5509 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5510 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5511 bool ShouldConvert1 = false;
5512 bool ShouldConvert2 = false;
5513 QualType Obj1Ty;
5514 QualType Obj2Ty;
5515 if (TPOC == TPOC_Call) {
5516 const FunctionProtoType *Proto1 =
5517 FD1->getType()->getAs<FunctionProtoType>();
5518 const FunctionProtoType *Proto2 =
5519 FD2->getType()->getAs<FunctionProtoType>();
5520
5521 // - In the context of a function call, the function parameter types are
5522 // used.
5523 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5524 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5525 // C++20 [temp.func.order]p3
5526 // [...] Each function template M that is a member function is
5527 // considered to have a new first parameter of type
5528 // X(M), described below, inserted in its function parameter list.
5529 //
5530 // Note that we interpret "that is a member function" as
5531 // "that is a member function with no expicit object argument".
5532 // Otherwise the ordering rules for methods with expicit objet arguments
5533 // against anything else make no sense.
5534 ShouldConvert1 = Method1 && !Method1->isExplicitObjectMemberFunction();
5535 ShouldConvert2 = Method2 && !Method2->isExplicitObjectMemberFunction();
5536 if (ShouldConvert1) {
5537 bool IsRValRef2 =
5538 ShouldConvert2
5539 ? Method2->getRefQualifier() == RQ_RValue
5540 : Proto2->param_type_begin()[0]->isRValueReferenceType();
5541 // Compare 'this' from Method1 against first parameter from Method2.
5542 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1, RawObj1Ty,
5543 IsRValRef2);
5544 Args1.push_back(Obj1Ty);
5545 }
5546 if (ShouldConvert2) {
5547 bool IsRValRef1 =
5548 ShouldConvert1
5549 ? Method1->getRefQualifier() == RQ_RValue
5550 : Proto1->param_type_begin()[0]->isRValueReferenceType();
5551 // Compare 'this' from Method2 against first parameter from Method1.
5552 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2, RawObj2Ty,
5553 IsRValRef1);
5554 Args2.push_back(Obj2Ty);
5555 }
5556 size_t NumComparedArguments = NumCallArguments1 + ShouldConvert1;
5557
5558 Args1.insert(Args1.end(), Proto1->param_type_begin(),
5559 Proto1->param_type_end());
5560 Args2.insert(Args2.end(), Proto2->param_type_begin(),
5561 Proto2->param_type_end());
5562
5563 // C++ [temp.func.order]p5:
5564 // The presence of unused ellipsis and default arguments has no effect on
5565 // the partial ordering of function templates.
5566 Args1.resize(std::min(Args1.size(), NumComparedArguments));
5567 Args2.resize(std::min(Args2.size(), NumComparedArguments));
5568
5569 if (Reversed)
5570 std::reverse(Args2.begin(), Args2.end());
5571 }
5572 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Reversed,
5573 Args1, Args2);
5574 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Reversed,
5575 Args2, Args1);
5576 // C++ [temp.deduct.partial]p10:
5577 // F is more specialized than G if F is at least as specialized as G and G
5578 // is not at least as specialized as F.
5579 if (Better1 != Better2) // We have a clear winner
5580 return Better1 ? FT1 : FT2;
5581
5582 if (!Better1 && !Better2) // Neither is better than the other
5583 return nullptr;
5584
5585 // C++ [temp.deduct.partial]p11:
5586 // ... and if G has a trailing function parameter pack for which F does not
5587 // have a corresponding parameter, and if F does not have a trailing
5588 // function parameter pack, then F is more specialized than G.
5589
5590 SmallVector<QualType> Param1;
5591 Param1.reserve(FD1->param_size() + ShouldConvert1);
5592 if (ShouldConvert1)
5593 Param1.push_back(Obj1Ty);
5594 for (const auto &P : FD1->parameters())
5595 Param1.push_back(P->getType());
5596
5597 SmallVector<QualType> Param2;
5598 Param2.reserve(FD2->param_size() + ShouldConvert2);
5599 if (ShouldConvert2)
5600 Param2.push_back(Obj2Ty);
5601 for (const auto &P : FD2->parameters())
5602 Param2.push_back(P->getType());
5603
5604 unsigned NumParams1 = Param1.size();
5605 unsigned NumParams2 = Param2.size();
5606
5607 bool Variadic1 =
5608 FD1->param_size() && FD1->parameters().back()->isParameterPack();
5609 bool Variadic2 =
5610 FD2->param_size() && FD2->parameters().back()->isParameterPack();
5611 if (Variadic1 != Variadic2) {
5612 if (Variadic1 && NumParams1 > NumParams2)
5613 return FT2;
5614 if (Variadic2 && NumParams2 > NumParams1)
5615 return FT1;
5616 }
5617
5618 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5619 // there is no wording or even resolution for this issue.
5620 for (int i = 0, e = std::min(NumParams1, NumParams2); i < e; ++i) {
5621 QualType T1 = Param1[i].getCanonicalType();
5622 QualType T2 = Param2[i].getCanonicalType();
5623 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
5624 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
5625 if (!TST1 || !TST2)
5626 continue;
5627 const TemplateArgument &TA1 = TST1->template_arguments().back();
5628 if (TA1.getKind() == TemplateArgument::Pack) {
5629 assert(TST1->template_arguments().size() ==
5630 TST2->template_arguments().size());
5631 const TemplateArgument &TA2 = TST2->template_arguments().back();
5632 assert(TA2.getKind() == TemplateArgument::Pack);
5633 unsigned PackSize1 = TA1.pack_size();
5634 unsigned PackSize2 = TA2.pack_size();
5635 bool IsPackExpansion1 =
5636 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5637 bool IsPackExpansion2 =
5638 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5639 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
5640 if (PackSize1 > PackSize2 && IsPackExpansion1)
5641 return FT2;
5642 if (PackSize1 < PackSize2 && IsPackExpansion2)
5643 return FT1;
5644 }
5645 }
5646 }
5647
5648 if (!Context.getLangOpts().CPlusPlus20)
5649 return nullptr;
5650
5651 // Match GCC on not implementing [temp.func.order]p6.2.1.
5652
5653 // C++20 [temp.func.order]p6:
5654 // If deduction against the other template succeeds for both transformed
5655 // templates, constraints can be considered as follows:
5656
5657 // C++20 [temp.func.order]p6.1:
5658 // If their template-parameter-lists (possibly including template-parameters
5659 // invented for an abbreviated function template ([dcl.fct])) or function
5660 // parameter lists differ in length, neither template is more specialized
5661 // than the other.
5664 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
5665 return nullptr;
5666
5667 // C++20 [temp.func.order]p6.2.2:
5668 // Otherwise, if the corresponding template-parameters of the
5669 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
5670 // function parameters that positionally correspond between the two
5671 // templates are not of the same type, neither template is more specialized
5672 // than the other.
5673 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
5675 return nullptr;
5676
5677 // [dcl.fct]p5:
5678 // Any top-level cv-qualifiers modifying a parameter type are deleted when
5679 // forming the function type.
5680 for (unsigned i = 0; i < NumParams1; ++i)
5681 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
5682 return nullptr;
5683
5684 // C++20 [temp.func.order]p6.3:
5685 // Otherwise, if the context in which the partial ordering is done is
5686 // that of a call to a conversion function and the return types of the
5687 // templates are not the same, then neither template is more specialized
5688 // than the other.
5689 if (TPOC == TPOC_Conversion &&
5691 return nullptr;
5692
5694 FT1->getAssociatedConstraints(AC1);
5695 FT2->getAssociatedConstraints(AC2);
5696 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5697 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
5698 return nullptr;
5699 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
5700 return nullptr;
5701 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5702 return nullptr;
5703 return AtLeastAsConstrained1 ? FT1 : FT2;
5704}
5705
5706/// Determine if the two templates are equivalent.
5708 if (T1 == T2)
5709 return true;
5710
5711 if (!T1 || !T2)
5712 return false;
5713
5714 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
5715}
5716
5717/// Retrieve the most specialized of the given function template
5718/// specializations.
5719///
5720/// \param SpecBegin the start iterator of the function template
5721/// specializations that we will be comparing.
5722///
5723/// \param SpecEnd the end iterator of the function template
5724/// specializations, paired with \p SpecBegin.
5725///
5726/// \param Loc the location where the ambiguity or no-specializations
5727/// diagnostic should occur.
5728///
5729/// \param NoneDiag partial diagnostic used to diagnose cases where there are
5730/// no matching candidates.
5731///
5732/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
5733/// occurs.
5734///
5735/// \param CandidateDiag partial diagnostic used for each function template
5736/// specialization that is a candidate in the ambiguous ordering. One parameter
5737/// in this diagnostic should be unbound, which will correspond to the string
5738/// describing the template arguments for the function template specialization.
5739///
5740/// \returns the most specialized function template specialization, if
5741/// found. Otherwise, returns SpecEnd.
5744 TemplateSpecCandidateSet &FailedCandidates,
5745 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
5746 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
5747 bool Complain, QualType TargetType) {
5748 if (SpecBegin == SpecEnd) {
5749 if (Complain) {
5750 Diag(Loc, NoneDiag);
5751 FailedCandidates.NoteCandidates(*this, Loc);
5752 }
5753 return SpecEnd;
5754 }
5755
5756 if (SpecBegin + 1 == SpecEnd)
5757 return SpecBegin;
5758
5759 // Find the function template that is better than all of the templates it
5760 // has been compared to.
5761 UnresolvedSetIterator Best = SpecBegin;
5762 FunctionTemplateDecl *BestTemplate
5763 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
5764 assert(BestTemplate && "Not a function template specialization?");
5765 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
5766 FunctionTemplateDecl *Challenger
5767 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5768 assert(Challenger && "Not a function template specialization?");
5769 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, Loc,
5770 TPOC_Other, 0),
5771 Challenger)) {
5772 Best = I;
5773 BestTemplate = Challenger;
5774 }
5775 }
5776
5777 // Make sure that the "best" function template is more specialized than all
5778 // of the others.
5779 bool Ambiguous = false;
5780 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5781 FunctionTemplateDecl *Challenger
5782 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5783 if (I != Best &&
5784 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
5785 Loc, TPOC_Other, 0),
5786 BestTemplate)) {
5787 Ambiguous = true;
5788 break;
5789 }
5790 }
5791
5792 if (!Ambiguous) {
5793 // We found an answer. Return it.
5794 return Best;
5795 }
5796
5797 // Diagnose the ambiguity.
5798 if (Complain) {
5799 Diag(Loc, AmbigDiag);
5800
5801 // FIXME: Can we order the candidates in some sane way?
5802 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5803 PartialDiagnostic PD = CandidateDiag;
5804 const auto *FD = cast<FunctionDecl>(*I);
5806 FD->getPrimaryTemplate()->getTemplateParameters(),
5807 *FD->getTemplateSpecializationArgs());
5808 if (!TargetType.isNull())
5809 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
5810 Diag((*I)->getLocation(), PD);
5811 }
5812 }
5813
5814 return SpecEnd;
5815}
5816
5817/// Determine whether one partial specialization, P1, is at least as
5818/// specialized than another, P2.
5819///
5820/// \tparam TemplateLikeDecl The kind of P2, which must be a
5821/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
5822/// \param T1 The injected-class-name of P1 (faked for a variable template).
5823/// \param T2 The injected-class-name of P2 (faked for a variable template).
5824template<typename TemplateLikeDecl>
5826 TemplateLikeDecl *P2,
5827 TemplateDeductionInfo &Info) {
5828 // C++ [temp.class.order]p1:
5829 // For two class template partial specializations, the first is at least as
5830 // specialized as the second if, given the following rewrite to two
5831 // function templates, the first function template is at least as
5832 // specialized as the second according to the ordering rules for function
5833 // templates (14.6.6.2):
5834 // - the first function template has the same template parameters as the
5835 // first partial specialization and has a single function parameter
5836 // whose type is a class template specialization with the template
5837 // arguments of the first partial specialization, and
5838 // - the second function template has the same template parameters as the
5839 // second partial specialization and has a single function parameter
5840 // whose type is a class template specialization with the template
5841 // arguments of the second partial specialization.
5842 //
5843 // Rather than synthesize function templates, we merely perform the
5844 // equivalent partial ordering by performing deduction directly on
5845 // the template arguments of the class template partial
5846 // specializations. This computation is slightly simpler than the
5847 // general problem of function template partial ordering, because
5848 // class template partial specializations are more constrained. We
5849 // know that every template parameter is deducible from the class
5850 // template partial specialization's template arguments, for
5851 // example.
5853
5854 // Determine whether P1 is at least as specialized as P2.
5855 Deduced.resize(P2->getTemplateParameters()->size());
5857 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
5858 /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
5859 return false;
5860
5861 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
5862 Deduced.end());
5863 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
5864 Info);
5865 if (Inst.isInvalid())
5866 return false;
5867
5868 const auto *TST1 = cast<TemplateSpecializationType>(T1);
5869 bool AtLeastAsSpecialized;
5871 AtLeastAsSpecialized =
5872 FinishTemplateArgumentDeduction(
5873 S, P2, /*IsPartialOrdering=*/true, TST1->template_arguments(),
5874 Deduced, Info) == TemplateDeductionResult::Success;
5875 });
5876 return AtLeastAsSpecialized;
5877}
5878
5879namespace {
5880// A dummy class to return nullptr instead of P2 when performing "more
5881// specialized than primary" check.
5882struct GetP2 {
5883 template <typename T1, typename T2,
5884 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
5885 T2 *operator()(T1 *, T2 *P2) {
5886 return P2;
5887 }
5888 template <typename T1, typename T2,
5889 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
5890 T1 *operator()(T1 *, T2 *) {
5891 return nullptr;
5892 }
5893};
5894
5895// The assumption is that two template argument lists have the same size.
5896struct TemplateArgumentListAreEqual {
5897 ASTContext &Ctx;
5898 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
5899
5900 template <typename T1, typename T2,
5901 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
5902 bool operator()(T1 *PS1, T2 *PS2) {
5903 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
5904 Args2 = PS2->getTemplateArgs().asArray();
5905
5906 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
5907 // We use profile, instead of structural comparison of the arguments,
5908 // because canonicalization can't do the right thing for dependent
5909 // expressions.
5910 llvm::FoldingSetNodeID IDA, IDB;
5911 Args1[I].Profile(IDA, Ctx);
5912 Args2[I].Profile(IDB, Ctx);
5913 if (IDA != IDB)
5914 return false;
5915 }
5916 return true;
5917 }
5918
5919 template <typename T1, typename T2,
5920 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
5921 bool operator()(T1 *Spec, T2 *Primary) {
5922 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
5923 Args2 = Primary->getInjectedTemplateArgs();
5924
5925 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
5926 // We use profile, instead of structural comparison of the arguments,
5927 // because canonicalization can't do the right thing for dependent
5928 // expressions.
5929 llvm::FoldingSetNodeID IDA, IDB;
5930 Args1[I].Profile(IDA, Ctx);
5931 // Unlike the specialization arguments, the injected arguments are not
5932 // always canonical.
5933 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
5934 if (IDA != IDB)
5935 return false;
5936 }
5937 return true;
5938 }
5939};
5940} // namespace
5941
5942/// Returns the more specialized template specialization between T1/P1 and
5943/// T2/P2.
5944/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
5945/// specialization and T2/P2 is the primary template.
5946/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
5947///
5948/// \param T1 the type of the first template partial specialization
5949///
5950/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
5951/// template partial specialization; otherwise, the type of the
5952/// primary template.
5953///
5954/// \param P1 the first template partial specialization
5955///
5956/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
5957/// partial specialization; otherwise, the primary template.
5958///
5959/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
5960/// more specialized, returns nullptr if P1 is not more specialized.
5961/// - otherwise, returns the more specialized template partial
5962/// specialization. If neither partial specialization is more
5963/// specialized, returns NULL.
5964template <typename TemplateLikeDecl, typename PrimaryDel>
5965static TemplateLikeDecl *
5966getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
5967 PrimaryDel *P2, TemplateDeductionInfo &Info) {
5968 constexpr bool IsMoreSpecialThanPrimaryCheck =
5969 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
5970
5971 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, Info);
5972 if (IsMoreSpecialThanPrimaryCheck && !Better1)
5973 return nullptr;
5974
5975 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1, Info);
5976 if (IsMoreSpecialThanPrimaryCheck && !Better2)
5977 return P1;
5978
5979 // C++ [temp.deduct.partial]p10:
5980 // F is more specialized than G if F is at least as specialized as G and G
5981 // is not at least as specialized as F.
5982 if (Better1 != Better2) // We have a clear winner
5983 return Better1 ? P1 : GetP2()(P1, P2);
5984
5985 if (!Better1 && !Better2)
5986 return nullptr;
5987
5988 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5989 // there is no wording or even resolution for this issue.
5990 auto *TST1 = cast<TemplateSpecializationType>(T1);
5991 auto *TST2 = cast<TemplateSpecializationType>(T2);
5992 const TemplateArgument &TA1 = TST1->template_arguments().back();
5993 if (TA1.getKind() == TemplateArgument::Pack) {
5994 assert(TST1->template_arguments().size() ==
5995 TST2->template_arguments().size());
5996 const TemplateArgument &TA2 = TST2->template_arguments().back();
5997 assert(TA2.getKind() == TemplateArgument::Pack);
5998 unsigned PackSize1 = TA1.pack_size();
5999 unsigned PackSize2 = TA2.pack_size();
6000 bool IsPackExpansion1 =
6001 PackSize1 && TA1.pack_elements().back().isPackExpansion();
6002 bool IsPackExpansion2 =
6003 PackSize2 && TA2.pack_elements().back().isPackExpansion();
6004 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
6005 if (PackSize1 > PackSize2 && IsPackExpansion1)
6006 return GetP2()(P1, P2);
6007 if (PackSize1 < PackSize2 && IsPackExpansion2)
6008 return P1;
6009 }
6010 }
6011
6012 if (!S.Context.getLangOpts().CPlusPlus20)
6013 return nullptr;
6014
6015 // Match GCC on not implementing [temp.func.order]p6.2.1.
6016
6017 // C++20 [temp.func.order]p6:
6018 // If deduction against the other template succeeds for both transformed
6019 // templates, constraints can be considered as follows:
6020
6021 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6022 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6023 if (TPL1->size() != TPL2->size())
6024 return nullptr;
6025
6026 // C++20 [temp.func.order]p6.2.2:
6027 // Otherwise, if the corresponding template-parameters of the
6028 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6029 // function parameters that positionally correspond between the two
6030 // templates are not of the same type, neither template is more specialized
6031 // than the other.
6032 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6034 return nullptr;
6035
6036 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6037 return nullptr;
6038
6040 P1->getAssociatedConstraints(AC1);
6041 P2->getAssociatedConstraints(AC2);
6042 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6043 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6044 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6045 return nullptr;
6046 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6047 return nullptr;
6048 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6049 return nullptr;
6050 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6051}
6052
6053/// Returns the more specialized class template partial specialization
6054/// according to the rules of partial ordering of class template partial
6055/// specializations (C++ [temp.class.order]).
6056///
6057/// \param PS1 the first class template partial specialization
6058///
6059/// \param PS2 the second class template partial specialization
6060///
6061/// \returns the more specialized class template partial specialization. If
6062/// neither partial specialization is more specialized, returns NULL.
6067 SourceLocation Loc) {
6070
6071 TemplateDeductionInfo Info(Loc);
6072 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6073}
6074
6077 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6078 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
6079 QualType PartialT = Spec->getInjectedSpecializationType();
6080
6082 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6083 if (MaybeSpec)
6084 Info.clearSFINAEDiagnostic();
6085 return MaybeSpec;
6086}
6087
6092 // Pretend the variable template specializations are class template
6093 // specializations and form a fake injected class name type for comparison.
6094 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6095 "the partial specializations being compared should specialize"
6096 " the same template.");
6098 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6100 CanonTemplate, PS1->getTemplateArgs().asArray());
6102 CanonTemplate, PS2->getTemplateArgs().asArray());
6103
6104 TemplateDeductionInfo Info(Loc);
6105 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6106}
6107
6110 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6111 TemplateName CanonTemplate =
6114 CanonTemplate, Primary->getInjectedTemplateArgs());
6116 CanonTemplate, Spec->getTemplateArgs().asArray());
6117
6119 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6120 if (MaybeSpec)
6121 Info.clearSFINAEDiagnostic();
6122 return MaybeSpec;
6123}
6124
6127 // C++1z [temp.arg.template]p4: (DR 150)
6128 // A template template-parameter P is at least as specialized as a
6129 // template template-argument A if, given the following rewrite to two
6130 // function templates...
6131
6132 // Rather than synthesize function templates, we merely perform the
6133 // equivalent partial ordering by performing deduction directly on
6134 // the template parameter lists of the template template parameters.
6135 //
6136 // Given an invented class template X with the template parameter list of
6137 // A (including default arguments):
6140
6141 // - Each function template has a single function parameter whose type is
6142 // a specialization of X with template arguments corresponding to the
6143 // template parameters from the respective function template
6146
6147 // Check P's arguments against A's parameter list. This will fill in default
6148 // template arguments as needed. AArgs are already correct by construction.
6149 // We can't just use CheckTemplateIdType because that will expand alias
6150 // templates.
6152 {
6153 SFINAETrap Trap(*this);
6154
6156 TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
6157 P->getRAngleLoc());
6158 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6159 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6160 // expansions, to form an "as written" argument list.
6161 TemplateArgument Arg = PArgs[I];
6162 if (Arg.getKind() == TemplateArgument::Pack) {
6163 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6164 Arg = *Arg.pack_begin();
6165 }
6167 Arg, QualType(), P->getParam(I)->getLocation()));
6168 }
6169 PArgs.clear();
6170
6171 // C++1z [temp.arg.template]p3:
6172 // If the rewrite produces an invalid type, then P is not at least as
6173 // specialized as A.
6175 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, SugaredPArgs,
6176 PArgs) ||
6177 Trap.hasErrorOccurred())
6178 return false;
6179 }
6180
6183
6184 // ... the function template corresponding to P is at least as specialized
6185 // as the function template corresponding to A according to the partial
6186 // ordering rules for function templates.
6187 TemplateDeductionInfo Info(Loc, A->getDepth());
6188 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
6189}
6190
6191namespace {
6192struct MarkUsedTemplateParameterVisitor :
6193 RecursiveASTVisitor<MarkUsedTemplateParameterVisitor> {
6194 llvm::SmallBitVector &Used;
6195 unsigned Depth;
6196
6197 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
6198 unsigned Depth)
6199 : Used(Used), Depth(Depth) { }
6200
6201 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
6202 if (T->getDepth() == Depth)
6203 Used[T->getIndex()] = true;
6204 return true;
6205 }
6206
6207 bool TraverseTemplateName(TemplateName Template) {
6208 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6209 Template.getAsTemplateDecl()))
6210 if (TTP->getDepth() == Depth)
6211 Used[TTP->getIndex()] = true;
6213 TraverseTemplateName(Template);
6214 return true;
6215 }
6216
6217 bool VisitDeclRefExpr(DeclRefExpr *E) {
6218 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6219 if (NTTP->getDepth() == Depth)
6220 Used[NTTP->getIndex()] = true;
6221 return true;
6222 }
6223};
6224}
6225
6226/// Mark the template parameters that are used by the given
6227/// expression.
6228static void
6230 const Expr *E,
6231 bool OnlyDeduced,
6232 unsigned Depth,
6233 llvm::SmallBitVector &Used) {
6234 if (!OnlyDeduced) {
6235 MarkUsedTemplateParameterVisitor(Used, Depth)
6236 .TraverseStmt(const_cast<Expr *>(E));
6237 return;
6238 }
6239
6240 // We can deduce from a pack expansion.
6241 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6242 E = Expansion->getPattern();
6243
6245 if (!NTTP)
6246 return;
6247
6248 if (NTTP->getDepth() == Depth)
6249 Used[NTTP->getIndex()] = true;
6250
6251 // In C++17 mode, additional arguments may be deduced from the type of a
6252 // non-type argument.
6253 if (Ctx.getLangOpts().CPlusPlus17)
6254 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
6255}
6256
6257/// Mark the template parameters that are used by the given
6258/// nested name specifier.
6259static void
6262 bool OnlyDeduced,
6263 unsigned Depth,
6264 llvm::SmallBitVector &Used) {
6265 if (!NNS)
6266 return;
6267
6268 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
6269 Used);
6271 OnlyDeduced, Depth, Used);
6272}
6273
6274/// Mark the template parameters that are used by the given
6275/// template name.
6276static void
6278 TemplateName Name,
6279 bool OnlyDeduced,
6280 unsigned Depth,
6281 llvm::SmallBitVector &Used) {
6282 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6284 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6285 if (TTP->getDepth() == Depth)
6286 Used[TTP->getIndex()] = true;
6287 }
6288 return;
6289 }
6290
6291 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
6292 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6293 Depth, Used);
6294 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
6295 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6296 Depth, Used);
6297}
6298
6299/// Mark the template parameters that are used by the given
6300/// type.
6301static void
6303 bool OnlyDeduced,
6304 unsigned Depth,
6305 llvm::SmallBitVector &Used) {
6306 if (T.isNull())
6307 return;
6308
6309 // Non-dependent types have nothing deducible
6310 if (!T->isDependentType())
6311 return;
6312
6313 T = Ctx.getCanonicalType(T);
6314 switch (T->getTypeClass()) {
6315 case Type::Pointer:
6317 cast<PointerType>(T)->getPointeeType(),
6318 OnlyDeduced,
6319 Depth,
6320 Used);
6321 break;
6322
6323 case Type::BlockPointer:
6325 cast<BlockPointerType>(T)->getPointeeType(),
6326 OnlyDeduced,
6327 Depth,
6328 Used);
6329 break;
6330
6331 case Type::LValueReference:
6332 case Type::RValueReference:
6334 cast<ReferenceType>(T)->getPointeeType(),
6335 OnlyDeduced,
6336 Depth,
6337 Used);
6338 break;
6339
6340 case Type::MemberPointer: {
6341 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
6342 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
6343 Depth, Used);
6344 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
6345 OnlyDeduced, Depth, Used);
6346 break;
6347 }
6348
6349 case Type::DependentSizedArray:
6351 cast<DependentSizedArrayType>(T)->getSizeExpr(),
6352 OnlyDeduced, Depth, Used);
6353 // Fall through to check the element type
6354 [[fallthrough]];
6355
6356 case Type::ConstantArray:
6357 case Type::IncompleteArray:
6359 cast<ArrayType>(T)->getElementType(),
6360 OnlyDeduced, Depth, Used);
6361 break;
6362
6363 case Type::Vector:
6364 case Type::ExtVector:
6366 cast<VectorType>(T)->getElementType(),
6367 OnlyDeduced, Depth, Used);
6368 break;
6369
6370 case Type::DependentVector: {
6371 const auto *VecType = cast<DependentVectorType>(T);
6372 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6373 Depth, Used);
6374 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
6375 Used);
6376 break;
6377 }
6378 case Type::DependentSizedExtVector: {
6379 const DependentSizedExtVectorType *VecType
6380 = cast<DependentSizedExtVectorType>(T);
6381 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6382 Depth, Used);
6383 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
6384 Depth, Used);
6385 break;
6386 }
6387
6388 case Type::DependentAddressSpace: {
6389 const DependentAddressSpaceType *DependentASType =
6390 cast<DependentAddressSpaceType>(T);
6391 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
6392 OnlyDeduced, Depth, Used);
6394 DependentASType->getAddrSpaceExpr(),
6395 OnlyDeduced, Depth, Used);
6396 break;
6397 }
6398
6399 case Type::ConstantMatrix: {
6400 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
6401 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6402 Depth, Used);
6403 break;
6404 }
6405
6406 case Type::DependentSizedMatrix: {
6407 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
6408 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6409 Depth, Used);
6410 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
6411 Used);
6412 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
6413 Depth, Used);
6414 break;
6415 }
6416
6417 case Type::FunctionProto: {
6418 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
6419 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
6420 Used);
6421 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6422 // C++17 [temp.deduct.type]p5:
6423 // The non-deduced contexts are: [...]
6424 // -- A function parameter pack that does not occur at the end of the
6425 // parameter-declaration-list.
6426 if (!OnlyDeduced || I + 1 == N ||
6427 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
6428 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
6429 Depth, Used);
6430 } else {
6431 // FIXME: C++17 [temp.deduct.call]p1:
6432 // When a function parameter pack appears in a non-deduced context,
6433 // the type of that pack is never deduced.
6434 //
6435 // We should also track a set of "never deduced" parameters, and
6436 // subtract that from the list of deduced parameters after marking.
6437 }
6438 }
6439 if (auto *E = Proto->getNoexceptExpr())
6440 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6441 break;
6442 }
6443
6444 case Type::TemplateTypeParm: {
6445 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
6446 if (TTP->getDepth() == Depth)
6447 Used[TTP->getIndex()] = true;
6448 break;
6449 }
6450
6451 case Type::SubstTemplateTypeParmPack: {
6453 = cast<SubstTemplateTypeParmPackType>(T);
6454 if (Subst->getReplacedParameter()->getDepth() == Depth)
6455 Used[Subst->getIndex()] = true;
6457 OnlyDeduced, Depth, Used);
6458 break;
6459 }
6460
6461 case Type::InjectedClassName:
6462 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
6463 [[fallthrough]];
6464
6465 case Type::TemplateSpecialization: {
6466 const TemplateSpecializationType *Spec
6467 = cast<TemplateSpecializationType>(T);
6468 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
6469 Depth, Used);
6470
6471 // C++0x [temp.deduct.type]p9:
6472 // If the template argument list of P contains a pack expansion that is
6473 // not the last template argument, the entire template argument list is a
6474 // non-deduced context.
6475 if (OnlyDeduced &&
6477 break;
6478
6479 for (const auto &Arg : Spec->template_arguments())
6480 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6481 break;
6482 }
6483
6484 case Type::Complex:
6485 if (!OnlyDeduced)
6487 cast<ComplexType>(T)->getElementType(),
6488 OnlyDeduced, Depth, Used);
6489 break;
6490
6491 case Type::Atomic:
6492 if (!OnlyDeduced)
6494 cast<AtomicType>(T)->getValueType(),
6495 OnlyDeduced, Depth, Used);
6496 break;
6497
6498 case Type::DependentName:
6499 if (!OnlyDeduced)
6501 cast<DependentNameType>(T)->getQualifier(),
6502 OnlyDeduced, Depth, Used);
6503 break;
6504
6505 case Type::DependentTemplateSpecialization: {
6506 // C++14 [temp.deduct.type]p5:
6507 // The non-deduced contexts are:
6508 // -- The nested-name-specifier of a type that was specified using a
6509 // qualified-id
6510 //
6511 // C++14 [temp.deduct.type]p6:
6512 // When a type name is specified in a way that includes a non-deduced
6513 // context, all of the types that comprise that type name are also
6514 // non-deduced.
6515 if (OnlyDeduced)
6516 break;
6517
6519 = cast<DependentTemplateSpecializationType>(T);
6520
6522 OnlyDeduced, Depth, Used);
6523
6524 for (const auto &Arg : Spec->template_arguments())
6525 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6526 break;
6527 }
6528
6529 case Type::TypeOf:
6530 if (!OnlyDeduced)
6531 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
6532 OnlyDeduced, Depth, Used);
6533 break;
6534
6535 case Type::TypeOfExpr:
6536 if (!OnlyDeduced)
6538 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
6539 OnlyDeduced, Depth, Used);
6540 break;
6541
6542 case Type::Decltype:
6543 if (!OnlyDeduced)
6545 cast<DecltypeType>(T)->getUnderlyingExpr(),
6546 OnlyDeduced, Depth, Used);
6547 break;
6548
6549 case Type::PackIndexing:
6550 if (!OnlyDeduced) {
6551 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getPattern(),
6552 OnlyDeduced, Depth, Used);
6553 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getIndexExpr(),
6554 OnlyDeduced, Depth, Used);
6555 }
6556 break;
6557
6558 case Type::UnaryTransform:
6559 if (!OnlyDeduced)
6561 cast<UnaryTransformType>(T)->getUnderlyingType(),
6562 OnlyDeduced, Depth, Used);
6563 break;
6564
6565 case Type::PackExpansion:
6567 cast<PackExpansionType>(T)->getPattern(),
6568 OnlyDeduced, Depth, Used);
6569 break;
6570
6571 case Type::Auto:
6572 case Type::DeducedTemplateSpecialization:
6574 cast<DeducedType>(T)->getDeducedType(),
6575 OnlyDeduced, Depth, Used);
6576 break;
6577 case Type::DependentBitInt:
6579 cast<DependentBitIntType>(T)->getNumBitsExpr(),
6580 OnlyDeduced, Depth, Used);
6581 break;
6582
6583 // None of these types have any template parameters in them.
6584 case Type::Builtin:
6585 case Type::VariableArray:
6586 case Type::FunctionNoProto:
6587 case Type::Record:
6588 case Type::Enum:
6589 case Type::ObjCInterface:
6590 case Type::ObjCObject:
6591 case Type::ObjCObjectPointer:
6592 case Type::UnresolvedUsing:
6593 case Type::Pipe:
6594 case Type::BitInt:
6595#define TYPE(Class, Base)
6596#define ABSTRACT_TYPE(Class, Base)
6597#define DEPENDENT_TYPE(Class, Base)
6598#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6599#include "clang/AST/TypeNodes.inc"
6600 break;
6601 }
6602}
6603
6604/// Mark the template parameters that are used by this
6605/// template argument.
6606static void
6609 bool OnlyDeduced,
6610 unsigned Depth,
6611 llvm::SmallBitVector &Used) {
6612 switch (TemplateArg.getKind()) {
6618 break;
6619
6621 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
6622 Depth, Used);
6623 break;
6624
6628 TemplateArg.getAsTemplateOrTemplatePattern(),
6629 OnlyDeduced, Depth, Used);
6630 break;
6631
6633 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
6634 Depth, Used);
6635 break;
6636
6638 for (const auto &P : TemplateArg.pack_elements())
6639 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
6640 break;
6641 }
6642}
6643
6644/// Mark which template parameters are used in a given expression.
6645///
6646/// \param E the expression from which template parameters will be deduced.
6647///
6648/// \param Used a bit vector whose elements will be set to \c true
6649/// to indicate when the corresponding template parameter will be
6650/// deduced.
6651void
6652Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
6653 unsigned Depth,
6654 llvm::SmallBitVector &Used) {
6655 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
6656}
6657
6658/// Mark which template parameters can be deduced from a given
6659/// template argument list.
6660///
6661/// \param TemplateArgs the template argument list from which template
6662/// parameters will be deduced.
6663///
6664/// \param Used a bit vector whose elements will be set to \c true
6665/// to indicate when the corresponding template parameter will be
6666/// deduced.
6667void
6669 bool OnlyDeduced, unsigned Depth,
6670 llvm::SmallBitVector &Used) {
6671 // C++0x [temp.deduct.type]p9:
6672 // If the template argument list of P contains a pack expansion that is not
6673 // the last template argument, the entire template argument list is a
6674 // non-deduced context.
6675 if (OnlyDeduced &&
6676 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
6677 return;
6678
6679 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6680 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
6681 Depth, Used);
6682}
6683
6684/// Marks all of the template parameters that will be deduced by a
6685/// call to the given function template.
6687 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
6688 llvm::SmallBitVector &Deduced) {
6689 TemplateParameterList *TemplateParams
6690 = FunctionTemplate->getTemplateParameters();
6691 Deduced.clear();
6692 Deduced.resize(TemplateParams->size());
6693
6694 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
6695 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
6696 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
6697 true, TemplateParams->getDepth(), Deduced);
6698}
6699
6701 FunctionTemplateDecl *FunctionTemplate,
6702 QualType T) {
6703 if (!T->isDependentType())
6704 return false;
6705
6706 TemplateParameterList *TemplateParams
6707 = FunctionTemplate->getTemplateParameters();
6708 llvm::SmallBitVector Deduced(TemplateParams->size());
6709 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
6710 Deduced);
6711
6712 return Deduced.any();
6713}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Provides definitions for the various language-specific address spaces.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1110
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:146
#define X(type, name)
Definition: Value.h:142
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static QualType getUnderlyingType(const SubRegion *R)
static bool isSameTemplateArg(ASTContext &Context, TemplateArgument X, const TemplateArgument &Y, bool PartialOrdering, bool PackExpansionMatchesPack=false)
Determine whether two template arguments are the same.
static bool isAtLeastAsSpecializedAs(Sema &S, SourceLocation Loc, const FunctionTemplateDecl *FT1, const FunctionTemplateDecl *FT2, TemplatePartialOrderingContext TPOC, bool Reversed, const SmallVector< QualType > &Args1, const SmallVector< QualType > &Args2)
Determine whether the function template FT1 is at least as specialized as FT2.
static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y)
Compare two APSInts, extending and switching the sign as necessary to compare their values regardless...
static TemplateLikeDecl * getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1, PrimaryDel *P2, TemplateDeductionInfo &Info)
Returns the more specialized template specialization between T1/P1 and T2/P2.
static DeducedTemplateArgument checkDeducedTemplateArguments(ASTContext &Context, const DeducedTemplateArgument &X, const DeducedTemplateArgument &Y, bool AggregateCandidateDeduction=false)
Verify that the given, deduced template arguments are compatible.
static bool isSameDeclaration(Decl *X, Decl *Y)
Determine whether two declaration pointers refer to the same declaration.
static CXXRecordDecl * getCanonicalRD(QualType T)
static bool hasTemplateArgumentForDeduction(ArrayRef< TemplateArgument > &Args, unsigned &ArgIdx)
Determine whether there is a template argument to be used for deduction.
static DeclContext * getAsDeclContextOrEnclosing(Decl *D)
static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, QualType ArgType)
Determine whether the parameter has qualifiers that the argument lacks.
static void MarkUsedTemplateParameters(ASTContext &Ctx, const TemplateArgument &TemplateArg, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark the template parameters that are used by this template argument.
static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, FunctionDecl *Fn)
Gets the type of a function for template-argument-deducton purposes when it's considered as part of a...
static TemplateDeductionResult CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template, ArrayRef< TemplateArgument > SugaredDeducedArgs, ArrayRef< TemplateArgument > CanonicalDeducedArgs, TemplateDeductionInfo &Info)
static TemplateDeductionResult DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD, TemplateParameterList *TemplateParams, QualType P, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced)
Attempt to deduce the template arguments by checking the base types according to (C++20 [temp....
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch)
static const NonTypeTemplateParmDecl * getDeducedParameterFromExpr(const Expr *E, unsigned Depth)
If the given expression is of a form that permits the deduction of a non-type template parameter,...
static TemplateDeductionResult DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams, const QualType P, QualType A, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced)
Deduce the template arguments by comparing the template parameter type (which is a template-id) with ...
static bool hasPackExpansionBeforeEnd(ArrayRef< TemplateArgument > Args)
Determine whether the given set of template arguments has a pack expansion that is not the last templ...
static bool isSimpleTemplateIdType(QualType T)
Determine whether the given type T is a simple-template-id type.
static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template, TemplateDeductionInfo &Info, bool IsDeduced, SmallVectorImpl< TemplateArgument > &SugaredOutput, SmallVectorImpl< TemplateArgument > &CanonicalOutput)
Convert the given deduced template argument and add it to the set of fully-converted template argumen...
static TemplateParameter makeTemplateParameter(Decl *D)
Helper function to build a TemplateParameter when we don't know its type statically.
static TemplateDeductionResult CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info, Sema::OriginalCallArg OriginalArg, QualType DeducedA)
Check whether the deduced argument type for a call to a function template matches the actual argument...
static TemplateDeductionResult DeduceNullPtrTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, const NonTypeTemplateParmDecl *NTTP, QualType NullPtrType, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced)
Deduce the value of the given non-type template parameter from the given null pointer template argume...
static unsigned getPackIndexForParam(Sema &S, FunctionTemplateDecl *FunctionTemplate, const MultiLevelTemplateArgumentList &Args, unsigned ParamIdx)
Find the pack index for a particular parameter index in an instantiation of a function template with ...
static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, QualType &ParamType, QualType &ArgType, Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF, TemplateSpecCandidateSet *FailedTSC=nullptr)
Perform the adjustments to the parameter and argument types described in C++ [temp....
static TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, QualType ParamType, QualType ArgType, Expr::Classification ArgClassification, Expr *Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< Sema::OriginalCallArg > &OriginalCallArgs, bool DecomposedParam, unsigned ArgIdx, unsigned TDF, TemplateSpecCandidateSet *FailedTSC=nullptr)
Perform template argument deduction per [temp.deduct.call] for a single parameter / argument pair.
static QualType GetImplicitObjectParameterType(ASTContext &Context, const CXXMethodDecl *Method, QualType RawType, bool IsOtherRvr)
static TemplateDeductionResult DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType, InitListExpr *ILE, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< Sema::OriginalCallArg > &OriginalCallArgs, unsigned ArgIdx, unsigned TDF)
Attempt template argument deduction from an initializer list deemed to be an argument in a function c...
static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2)
Determine if the two templates are equivalent.
static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD)
Get the index of the first template parameter that was originally from the innermost template-paramet...
static TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(Sema &S, TemplateParameterList *TemplateParams, QualType Param, QualType Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned TDF, bool PartialOrdering=false, bool DeducedFromArrayBound=false)
Deduce the template arguments by comparing the parameter type and the argument type (C++ [temp....
static TemplateDeductionResult DeduceNonTypeTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, const NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced, QualType ValueType, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced)
Deduce the value of the given non-type template parameter as the given deduced template argument.
static TemplateDeductionResult ConvertDeducedTemplateArguments(Sema &S, TemplateDeclT *Template, bool IsDeduced, SmallVectorImpl< DeducedTemplateArgument > &Deduced, TemplateDeductionInfo &Info, SmallVectorImpl< TemplateArgument > &SugaredBuilder, SmallVectorImpl< TemplateArgument > &CanonicalBuilder, LocalInstantiationScope *CurrentInstantiationScope=nullptr, unsigned NumAlreadyConverted=0, bool PartialOverloading=false)
static bool DeducedArgsNeedReplacement(TemplateDeclT *Template)
static QualType ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams, Expr *Arg, QualType ParamType, bool ParamWasReference, TemplateSpecCandidateSet *FailedTSC=nullptr)
Apply the deduction rules for overload sets.
static bool IsPossiblyOpaquelyQualifiedType(QualType T)
Determines whether the given type is an opaque type that might be more qualified when instantiated.
static std::enable_if_t< IsPartialSpecialization< T >::value, TemplateDeductionResult > FinishTemplateArgumentDeduction(Sema &S, T *Partial, bool IsPartialOrdering, ArrayRef< TemplateArgument > TemplateArgs, SmallVectorImpl< DeducedTemplateArgument > &Deduced, TemplateDeductionInfo &Info)
Complete template argument deduction for a partial specialization.
static TemplateDeductionResult instantiateExplicitSpecifierDeferred(Sema &S, FunctionDecl *Specialization, const MultiLevelTemplateArgumentList &SubstArgs, TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate, ArrayRef< TemplateArgument > DeducedArgs)
static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type, AutoTypeLoc TypeLoc, QualType Deduced)
static bool IsPossiblyOpaquelyQualifiedTypeInternal(const Type *T)
static bool hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate, QualType T)
static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex)
Determine whether a type denotes a forwarding reference.
bool DeducedArgsNeedReplacement< VarTemplatePartialSpecializationDecl >(VarTemplatePartialSpecializationDecl *Spec)
bool DeducedArgsNeedReplacement< ClassTemplatePartialSpecializationDecl >(ClassTemplatePartialSpecializationDecl *Spec)
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__device__ int
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2742
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
TemplateName getCanonicalTemplateName(const TemplateName &Name) const
Retrieves the "canonical" template name that refers to a given template.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2549
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2565
void getInjectedTemplateArgs(const TemplateParameterList *Params, SmallVectorImpl< TemplateArgument > &Args)
Get a template argument list with one argument per template parameter in a template parameter list,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2748
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1114
CanQualType NullPtrTy
Definition: ASTContext.h:1113
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1575
const LangOptions & getLangOpts() const
Definition: ASTContext.h:770
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl)
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
CanQualType BoolTy
Definition: ASTContext.h:1087
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const
Determine whether the given template names refer to the same template.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
Definition: ASTContext.h:1095
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2141
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
Definition: ASTContext.h:1400
CanQualType OverloadTy
Definition: ASTContext.h:1114
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2592
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2315
CanQualType UnsignedIntTy
Definition: ASTContext.h:1096
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1553
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
const DependentSizedArrayType * getAsDependentSizedArrayType(QualType T) const
Definition: ASTContext.h:2751
The result of parsing/analyzing an expression, statement etc.
Definition: Ownership.h:153
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5524
ArrayRef< TemplateArgument > getTypeConstraintArguments() const
Definition: Type.h:5534
bool isDecltypeAuto() const
Definition: Type.h:5547
ConceptDecl * getTypeConstraintConcept() const
Definition: Type.h:5539
AutoTypeKeyword getKeyword() const
Definition: Type.h:5555
bool isConstrained() const
Definition: Type.h:5543
A fixed int type of a specified bitwidth.
Definition: Type.h:6785
Pointer to a block type.
Definition: Type.h:2978
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2855
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2895
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2053
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2453
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2229
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2214
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
base_class_range bases()
Definition: DeclCXX.h:618
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1593
Declaration of a class template.
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template.
QualType getInjectedSpecializationType() const
Retrieves the injected specialization type for this partial specialization.
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
bool isClassScopeExplicitSpecialization() const
Is this an explicit specialization at class scope (within the class that owns the primary template)?...
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
Complex values, per C99 6.2.5p11.
Definition: Type.h:2845
Declaration of a C++20 concept.
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:3710
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:3731
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:3728
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
A POD class for pairing a NamedDecl* with an access specifier.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1446
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2076
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
ValueDecl * getDecl()
Definition: Expr.h:1328
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1226
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:220
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1217
bool isInvalidDecl() const
Definition: DeclBase.h:593
SourceLocation getLocation() const
Definition: DeclBase.h:444
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:210
DeclContext * getDeclContext()
Definition: DeclBase.h:453
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:918
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:978
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:432
Captures a template argument whose value has been deduced via c++ template argument deduction.
Definition: Template.h:327
void setDeducedFromArrayBound(bool Deduced)
Specify whether the given non-type template argument was deduced from an array bound.
Definition: Template.h:354
bool wasDeducedFromArrayBound() const
For a non-type template argument, determine whether the template argument was deduced from an array b...
Definition: Template.h:350
TemplateName getTemplateName() const
Retrieve the name of the template that we are deducing.
Definition: Type.h:5592
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5490
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3402
Expr * getAddrSpaceExpr() const
Definition: Type.h:3413
QualType getPointeeType() const
Definition: Type.h:3414
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3442
QualType getElementType() const
Definition: Type.h:3457
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:3769
Expr * getColumnExpr() const
Definition: Type.h:3782
Expr * getRowExpr() const
Definition: Type.h:3781
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:488
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:6047
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6066
NestedNameSpecifier * getQualifier() const
Definition: Type.h:6063
Represents a vector type where either the type or size is dependent.
Definition: Type.h:3564
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1892
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition: DeclCXX.h:1921
const Expr * getExpr() const
Definition: DeclCXX.h:1901
The return type of classify().
Definition: Expr.h:330
bool isLValue() const
Definition: Expr.h:380
This represents one expression.
Definition: Expr.h:110
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:3604
Stores a list of template parameters and the associated requires-clause (if any) for a TemplateDecl a...
Definition: DeclTemplate.h:222
Represents a function declaration or definition.
Definition: Decl.h:1959
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2674
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4007
QualType getReturnType() const
Definition: Decl.h:2722
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2651
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4078
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4143
bool isImmediateEscalating() const
Definition: Decl.cpp:3233
size_t param_size() const
Definition: Decl.h:2667
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3168
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4199
param_type_iterator param_type_begin() const
Definition: Type.h:4591
const ExtParameterInfo * getExtParameterInfosOrNull() const
Return a pointer to the beginning of the array of extra parameter information, if present,...
Definition: Type.h:4629
unsigned getNumParams() const
Definition: Type.h:4432
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:4571
QualType getParamType(unsigned i) const
Definition: Type.h:4434
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:4464
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4443
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:4516
param_type_iterator param_type_end() const
Definition: Type.h:4595
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4439
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3799
QualType getReturnType() const
Definition: Type.h:4116
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:4841
unsigned getNumInits() const
Definition: Expr.h:4871
ArrayRef< Expr * > inits()
Definition: Expr.h:4881
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:5764
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3053
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1938
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
void SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs)
Note that the given parameter pack has been partially substituted via explicit specification of templ...
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:3674
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:3688
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3089
QualType getPointeeType() const
Definition: Type.h:3105
const Type * getClass() const
Definition: Type.h:3119
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args)
Replaces the current 'innermost' level with the provided argument list.
Definition: Template.h:237
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
Class that aids in the construction of nested-name-specifiers along with source-location information ...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Represents a pointer to an Objective C object.
Definition: Type.h:6551
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2966
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3117
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3026
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3078
decls_iterator decls_begin() const
Definition: ExprCXX.h:3058
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3137
decls_iterator decls_end() const
Definition: ExprCXX.h:3061
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4142
Represents a pack expansion of types.
Definition: Type.h:6112
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:6133
std::optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:6137
bool hasSelectedType() const
Definition: Type.h:4978
QualType getSelectedType() const
Definition: Type.h:4971
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2898
QualType getPointeeType() const
Definition: Type.h:2908
A (possibly-)qualified type.
Definition: Type.h:737
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6990
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:804
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6902
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7027
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6942
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7102
QualType getCanonicalType() const
Definition: Type.h:6954
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6995
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7022
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:6948
Represents a template name that was expressed as a qualified name.
Definition: TemplateName.h:431
The collection of all-type qualifiers we support.
Definition: Type.h:147
unsigned getCVRQualifiers() const
Definition: Type.h:295
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:302
GC getObjCGCAttr() const
Definition: Type.h:326
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:175
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:168
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:164
void removeObjCLifetime()
Definition: Type.h:358
bool isStrictSupersetOf(Qualifiers Other) const
Determine whether this set of qualifiers is a strict superset of another set of qualifiers,...
Definition: Type.cpp:60
bool hasConst() const
Definition: Type.h:264
bool hasNonTrivialObjCLifetime() const
True if the lifetime is neither None or ExplicitNone.
Definition: Type.h:366
bool hasAddressSpace() const
Definition: Type.h:377
void removeObjCGCAttr()
Definition: Type.h:330
void removeAddressSpace()
Definition: Type.h:403
bool hasObjCGCAttr() const
Definition: Type.h:325
void setCVRQualifiers(unsigned mask)
Definition: Type.h:298
bool hasObjCLifetime() const
Definition: Type.h:351
ObjCLifetime getObjCLifetime() const
Definition: Type.h:352
Qualifiers withoutObjCLifetime() const
Definition: Type.h:340
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:532
LangAS getAddressSpace() const
Definition: Type.h:378
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:355
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3071
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5092
RecordDecl * getDecl() const
Definition: Type.h:5102
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
bool TraverseTemplateName(TemplateName Template)
Recursively visit a template name and dispatch to the appropriate method.
ArrayRef< TemplateArgument > getInjectedTemplateArgs()
Retrieve the "injected" template arguments that correspond to the template parameters of this templat...
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3009
QualType getPointeeType() const
Definition: Type.h:3027
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:10543
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6786
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2671
A helper class for building up ExtParameterInfos.
Definition: Sema.h:10005
const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams)
Return a pointer (suitable for setting in an ExtProtoInfo) to the ExtParameterInfo array we've built ...
Definition: Sema.h:10024
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9755
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9785
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:426
bool CheckInstantiatedFunctionTemplateConstraints(SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef< TemplateArgument > TemplateArgs, ConstraintSatisfaction &Satisfaction)
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:10034
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement)
Completely replace the auto in TypeWithAuto by Replacement.
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc)
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1911
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
@ CTAK_DeducedFromArrayBound
The template argument was deduced from an array bound via template argument deduction.
Definition: Sema.h:9433
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:9425
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:9429
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:1030
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:3075
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
ASTContext & getASTContext() const
Definition: Sema.h:501
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:947
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:9547
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
const LangOptions & getLangOpts() const
Definition: Sema.h:494
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:636
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:11484
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false)
Returns the more specialized function template according to the rules of function template partial or...
std::optional< unsigned > getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
TemplateDeductionResult SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< QualType > &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info)
Substitute the explicitly-provided template arguments into the given function template according to C...
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init)
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1163
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition: Sema.h:9818
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
Definition: SemaType.cpp:9760
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21731
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
TypeSourceInfo * ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11943
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC)
Get the return type to use for a lambda's conversion function(s) to function pointer type,...
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
Definition: SemaType.cpp:9190
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location)
Get a template argument mapping the given template parameter to itself, e.g.
bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD, SourceLocation Loc)
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
Perform template argument deduction to determine whether the given template arguments match the given...
TemplateDeductionResult FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl< OriginalCallArg > const *OriginalCallArgs=nullptr, bool PartialOverloading=false, llvm::function_ref< bool()> CheckNonDependent=[] { return false;})
Finish template argument deduction for a function template, checking the deduced template arguments f...
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:511
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
Definition: SemaType.cpp:8337
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:9969
Encodes a location in the source.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:5432
TemplateArgument getArgumentPack() const
Definition: Type.cpp:4069
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: Type.h:5458
const TemplateTypeParmDecl * getReplacedParameter() const
Gets the template parameter declaration that was substituted for.
Definition: Type.cpp:4061
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4693
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
A template argument list.
Definition: DeclTemplate.h:244
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:280
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:265
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
Represents a template argument.
Definition: TemplateBase.h:61
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
pack_iterator pack_end() const
Iterator referencing one past the last argument of a template argument pack.
Definition: TemplateBase.h:425
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:418
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
Used to insert TemplateArguments into FoldingSets.
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:363
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
Definition: TemplateBase.h:298
static TemplateArgument getEmptyPack()
Definition: TemplateBase.h:285
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:432
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
bool isTypeAlias() const
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: DeclTemplate.h:438
void getAssociatedConstraints(llvm::SmallVectorImpl< const Expr * > &AC) const
Get the total constraint-expression associated with this template, including constraint-expressions d...
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:357
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:5632
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:5700
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:5698
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
unsigned getDepth() const
Retrieve the depth of the template parameter.
Wrapper for template type parameters.
Definition: TypeLoc.h:758
unsigned getIndex() const
Definition: Type.h:5322
unsigned getDepth() const
Definition: Type.h:5321
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
const Type * getTypeForDecl() const
Definition: Decl.h:3381
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:159
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:164
void copy(TypeLoc other)
Copies the other type loc into this one.
Definition: TypeLoc.cpp:168
A container of type source information.
Definition: Type.h:6873
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1606
bool isVoidType() const
Definition: Type.h:7443
bool isIncompleteArrayType() const
Definition: Type.h:7228
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:7419
bool isRValueReferenceType() const
Definition: Type.h:7174
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:7594
bool isArrayType() const
Definition: Type.h:7220
bool isFunctionPointerType() const
Definition: Type.h:7188
bool isPointerType() const
Definition: Type.h:7154
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7724
bool isReferenceType() const
Definition: Type.h:7166
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:651
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2525
bool isLValueReferenceType() const
Definition: Type.h:7170
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2420
QualType getCanonicalTypeInternal() const
Definition: Type.h:2703
bool isMemberPointerType() const
Definition: Type.h:7202
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4778
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7573
bool isFunctionType() const
Definition: Type.h:7150
bool isObjCObjectPointerType() const
Definition: Type.h:7282
bool isMemberFunctionPointerType() const
Definition: Type.h:7206
bool isAnyPointerType() const
Definition: Type.h:7158
TypeClass getTypeClass() const
Definition: Type.h:2074
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2100
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7657
bool isRecordType() const
Definition: Type.h:7244
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:918
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1555
Declaration of a variable template.
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Represents a GCC generic vector type.
Definition: Type.h:3512
Provides information about an attempted template argument deduction, whose success or failure was des...
void setExplicitArgs(TemplateArgumentList *NewDeducedSugared, TemplateArgumentList *NewDeducedCanonical)
Provide an initial template argument list that contains the explicitly-specified arguments.
TemplateArgumentList * takeCanonical()
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
SourceLocation getLocation() const
Returns the location at which template argument is occurring.
void clearSFINAEDiagnostic()
Discard any SFINAE diagnostics.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
diag_iterator diag_end() const
Returns an iterator at the end of the sequence of suppressed diagnostics.
void reset(TemplateArgumentList *NewDeducedSugared, TemplateArgumentList *NewDeducedCanonical)
Provide a new template argument list that contains the results of template argument deduction.
unsigned getDeducedDepth() const
The depth of template parameters for which deduction is being performed.
diag_iterator diag_begin() const
Returns an iterator at the beginning of the sequence of suppressed diagnostics.
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
The JSON file list parser is used to communicate input to InstallAPI.
@ CPlusPlus20
Definition: LangStandard.h:58
@ CPlusPlus
Definition: LangStandard.h:54
@ CPlusPlus11
Definition: LangStandard.h:55
@ CPlusPlus14
Definition: LangStandard.h:56
@ CPlusPlus17
Definition: LangStandard.h:57
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:77
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1555
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1561
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:81
@ Result
The result type of a method or function.
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:65
std::optional< unsigned > getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition: ASTLambda.h:62
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
TPOC
The context in which partial ordering of function templates occurs.
Definition: Template.h:298
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition: Template.h:304
@ TPOC_Other
Partial ordering of function templates in other contexts, e.g., taking the address of a function temp...
Definition: Template.h:309
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition: Template.h:300
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:367
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Invalid
The declaration was invalid; do nothing.
@ Success
Template argument deduction was successful.
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ EST_Uninstantiated
not instantiated yet
TemplateDeductionFlags
Various flags that control template argument deduction.
@ TDF_None
No template argument deduction flags, which indicates the strictest results for template argument ded...
@ TDF_DerivedClass
Within template argument deduction from a function call, we are matching in a case where we can perfo...
@ TDF_TopLevelParameterTypeList
Whether we are performing template argument deduction for parameters and arguments in a top-level tem...
@ TDF_IgnoreQualifiers
Within template argument deduction from a function call, we are matching in a case where we ignore cv...
@ TDF_ParamWithReferenceType
Within template argument deduction from a function call, we are matching with a parameter type for wh...
@ TDF_SkipNonDependent
Allow non-dependent types to differ, e.g., when performing template argument deduction from a functio...
@ TDF_AllowCompatibleFunctionType
Within template argument deduction from overload resolution per C++ [over.over] allow matching functi...
@ TDF_ArgWithReferenceType
Within template argument deduction for a conversion function, we are matching with an argument type f...
ActionResult< CXXBaseSpecifier * > BaseResult
Definition: Ownership.h:251
#define true
Definition: stdbool.h:21
#define false
Definition: stdbool.h:22
#define bool
Definition: stdbool.h:20
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
Definition: TemplateBase.h:691
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
Definition: TemplateBase.h:688
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:705
A pack that we're currently deducing.
SmallVector< DeducedTemplateArgument, 4 > New
DeducedTemplateArgument Saved
DeducedTemplateArgument DeferredDeduction
Holds information about the various types of exception specification.
Definition: Type.h:4250
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4252
Extra information about a function prototype.
Definition: Type.h:4278
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:4286
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4279
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:10072
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:10079
A stack object to be created when performing template instantiation.
Definition: Sema.h:10233
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:10381
brief A function argument from which we performed template argument
Definition: Sema.h:9864
Location information for a TemplateArgument.
Definition: TemplateBase.h:472