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,
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 if (getCanonicalRD(A)->isInvalidDecl())
1918 return Result;
1919
1920 // Reset the incorrectly deduced argument from above.
1921 Deduced = DeducedOrig;
1922
1923 // Check bases according to C++14 [temp.deduct.call] p4b3:
1925 TemplateParams, P, Info, Deduced);
1927 : Result;
1928 }
1929
1930 // T type::*
1931 // T T::*
1932 // T (type::*)()
1933 // type (T::*)()
1934 // type (type::*)(T)
1935 // type (T::*)(T)
1936 // T (type::*)(T)
1937 // T (T::*)()
1938 // T (T::*)(T)
1939 case Type::MemberPointer: {
1940 const auto *MPP = P->castAs<MemberPointerType>(),
1941 *MPA = A->getAs<MemberPointerType>();
1942 if (!MPA)
1944
1945 QualType PPT = MPP->getPointeeType();
1946 if (PPT->isFunctionType())
1947 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
1948 /*IsCtorOrDtor=*/false, Info.getLocation());
1949 QualType APT = MPA->getPointeeType();
1950 if (APT->isFunctionType())
1951 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
1952 /*IsCtorOrDtor=*/false, Info.getLocation());
1953
1954 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1956 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF);
1958 return Result;
1960 S, TemplateParams, QualType(MPP->getClass(), 0),
1961 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF);
1962 }
1963
1964 // (clang extension)
1965 //
1966 // type(^)(T)
1967 // T(^)()
1968 // T(^)(T)
1969 case Type::BlockPointer: {
1970 const auto *BPP = P->castAs<BlockPointerType>(),
1971 *BPA = A->getAs<BlockPointerType>();
1972 if (!BPA)
1975 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
1976 Deduced, 0);
1977 }
1978
1979 // (clang extension)
1980 //
1981 // T __attribute__(((ext_vector_type(<integral constant>))))
1982 case Type::ExtVector: {
1983 const auto *VP = P->castAs<ExtVectorType>();
1984 QualType ElementType;
1985 if (const auto *VA = A->getAs<ExtVectorType>()) {
1986 // Make sure that the vectors have the same number of elements.
1987 if (VP->getNumElements() != VA->getNumElements())
1989 ElementType = VA->getElementType();
1990 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
1991 // We can't check the number of elements, since the argument has a
1992 // dependent number of elements. This can only occur during partial
1993 // ordering.
1994 ElementType = VA->getElementType();
1995 } else {
1997 }
1998 // Perform deduction on the element types.
2000 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2001 TDF);
2002 }
2003
2004 case Type::DependentVector: {
2005 const auto *VP = P->castAs<DependentVectorType>();
2006
2007 if (const auto *VA = A->getAs<VectorType>()) {
2008 // Perform deduction on the element types.
2010 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2011 Info, Deduced, TDF);
2013 return Result;
2014
2015 // Perform deduction on the vector size, if we can.
2016 const NonTypeTemplateParmDecl *NTTP =
2017 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2018 if (!NTTP)
2020
2021 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2022 ArgSize = VA->getNumElements();
2023 // Note that we use the "array bound" rules here; just like in that
2024 // case, we don't have any particular type for the vector size, but
2025 // we can provide one if necessary.
2026 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2027 S.Context.UnsignedIntTy, true,
2028 Info, Deduced);
2029 }
2030
2031 if (const auto *VA = A->getAs<DependentVectorType>()) {
2032 // Perform deduction on the element types.
2034 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2035 Info, Deduced, TDF);
2037 return Result;
2038
2039 // Perform deduction on the vector size, if we can.
2040 const NonTypeTemplateParmDecl *NTTP =
2041 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2042 if (!NTTP)
2044
2045 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2046 VA->getSizeExpr(), Info, Deduced);
2047 }
2048
2050 }
2051
2052 // (clang extension)
2053 //
2054 // T __attribute__(((ext_vector_type(N))))
2055 case Type::DependentSizedExtVector: {
2056 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2057
2058 if (const auto *VA = A->getAs<ExtVectorType>()) {
2059 // Perform deduction on the element types.
2061 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2062 Info, Deduced, TDF);
2064 return Result;
2065
2066 // Perform deduction on the vector size, if we can.
2067 const NonTypeTemplateParmDecl *NTTP =
2068 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2069 if (!NTTP)
2071
2072 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2073 ArgSize = VA->getNumElements();
2074 // Note that we use the "array bound" rules here; just like in that
2075 // case, we don't have any particular type for the vector size, but
2076 // we can provide one if necessary.
2077 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2078 S.Context.IntTy, true, Info,
2079 Deduced);
2080 }
2081
2082 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2083 // Perform deduction on the element types.
2085 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2086 Info, Deduced, TDF);
2088 return Result;
2089
2090 // Perform deduction on the vector size, if we can.
2091 const NonTypeTemplateParmDecl *NTTP =
2092 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2093 if (!NTTP)
2095
2096 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2097 VA->getSizeExpr(), Info, Deduced);
2098 }
2099
2101 }
2102
2103 // (clang extension)
2104 //
2105 // T __attribute__((matrix_type(<integral constant>,
2106 // <integral constant>)))
2107 case Type::ConstantMatrix: {
2108 const auto *MP = P->castAs<ConstantMatrixType>(),
2109 *MA = A->getAs<ConstantMatrixType>();
2110 if (!MA)
2112
2113 // Check that the dimensions are the same
2114 if (MP->getNumRows() != MA->getNumRows() ||
2115 MP->getNumColumns() != MA->getNumColumns()) {
2117 }
2118 // Perform deduction on element types.
2120 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2121 Deduced, TDF);
2122 }
2123
2124 case Type::DependentSizedMatrix: {
2125 const auto *MP = P->castAs<DependentSizedMatrixType>();
2126 const auto *MA = A->getAs<MatrixType>();
2127 if (!MA)
2129
2130 // Check the element type of the matrixes.
2132 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2133 Info, Deduced, TDF);
2135 return Result;
2136
2137 // Try to deduce a matrix dimension.
2138 auto DeduceMatrixArg =
2139 [&S, &Info, &Deduced, &TemplateParams](
2140 Expr *ParamExpr, const MatrixType *A,
2141 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2142 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2143 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2144 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2145 if (!ParamExpr->isValueDependent()) {
2146 std::optional<llvm::APSInt> ParamConst =
2147 ParamExpr->getIntegerConstantExpr(S.Context);
2148 if (!ParamConst)
2150
2151 if (ACM) {
2152 if ((ACM->*GetArgDimension)() == *ParamConst)
2155 }
2156
2157 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2158 if (std::optional<llvm::APSInt> ArgConst =
2159 ArgExpr->getIntegerConstantExpr(S.Context))
2160 if (*ArgConst == *ParamConst)
2163 }
2164
2165 const NonTypeTemplateParmDecl *NTTP =
2166 getDeducedParameterFromExpr(Info, ParamExpr);
2167 if (!NTTP)
2169
2170 if (ACM) {
2171 llvm::APSInt ArgConst(
2173 ArgConst = (ACM->*GetArgDimension)();
2175 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2176 /*ArrayBound=*/true, Info, Deduced);
2177 }
2178
2179 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2180 (ADM->*GetArgDimensionExpr)(),
2181 Info, Deduced);
2182 };
2183
2184 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2188 return Result;
2189
2190 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2193 }
2194
2195 // (clang extension)
2196 //
2197 // T __attribute__(((address_space(N))))
2198 case Type::DependentAddressSpace: {
2199 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2200
2201 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2202 // Perform deduction on the pointer type.
2204 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2205 Info, Deduced, TDF);
2207 return Result;
2208
2209 // Perform deduction on the address space, if we can.
2210 const NonTypeTemplateParmDecl *NTTP =
2211 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2212 if (!NTTP)
2214
2216 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info, Deduced);
2217 }
2218
2220 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2221 false);
2222 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2223
2224 // Perform deduction on the pointer types.
2226 S, TemplateParams, ASP->getPointeeType(),
2227 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF);
2229 return Result;
2230
2231 // Perform deduction on the address space, if we can.
2232 const NonTypeTemplateParmDecl *NTTP =
2233 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2234 if (!NTTP)
2236
2237 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2238 ArgAddressSpace, S.Context.IntTy,
2239 true, Info, Deduced);
2240 }
2241
2243 }
2244 case Type::DependentBitInt: {
2245 const auto *IP = P->castAs<DependentBitIntType>();
2246
2247 if (const auto *IA = A->getAs<BitIntType>()) {
2248 if (IP->isUnsigned() != IA->isUnsigned())
2250
2251 const NonTypeTemplateParmDecl *NTTP =
2252 getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
2253 if (!NTTP)
2255
2256 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2257 ArgSize = IA->getNumBits();
2258
2259 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2260 S.Context.IntTy, true, Info,
2261 Deduced);
2262 }
2263
2264 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2265 if (IP->isUnsigned() != IA->isUnsigned())
2268 }
2269
2271 }
2272
2273 case Type::TypeOfExpr:
2274 case Type::TypeOf:
2275 case Type::DependentName:
2276 case Type::UnresolvedUsing:
2277 case Type::Decltype:
2278 case Type::UnaryTransform:
2279 case Type::DeducedTemplateSpecialization:
2280 case Type::DependentTemplateSpecialization:
2281 case Type::PackExpansion:
2282 case Type::Pipe:
2283 case Type::ArrayParameter:
2284 // No template argument deduction for these types
2286
2287 case Type::PackIndexing: {
2288 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2289 if (PIT->hasSelectedType()) {
2291 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF);
2292 }
2294 }
2295 }
2296
2297 llvm_unreachable("Invalid Type Class!");
2298}
2299
2305 // If the template argument is a pack expansion, perform template argument
2306 // deduction against the pattern of that expansion. This only occurs during
2307 // partial ordering.
2308 if (A.isPackExpansion())
2310
2311 switch (P.getKind()) {
2313 llvm_unreachable("Null template argument in parameter list");
2314
2318 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0);
2319 Info.FirstArg = P;
2320 Info.SecondArg = A;
2322
2325 return DeduceTemplateArguments(S, TemplateParams, P.getAsTemplate(),
2326 A.getAsTemplate(), Info, Deduced);
2327 Info.FirstArg = P;
2328 Info.SecondArg = A;
2330
2332 llvm_unreachable("caller should handle pack expansions");
2333
2336 isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
2338
2339 Info.FirstArg = P;
2340 Info.SecondArg = A;
2342
2345 S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
2347
2348 Info.FirstArg = P;
2349 Info.SecondArg = A;
2351
2354 if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
2356 }
2357 Info.FirstArg = P;
2358 Info.SecondArg = A;
2360
2365
2366 Info.FirstArg = P;
2367 Info.SecondArg = A;
2369
2371 if (const NonTypeTemplateParmDecl *NTTP =
2372 getDeducedParameterFromExpr(Info, P.getAsExpr())) {
2373 switch (A.getKind()) {
2378 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2379 A.getNonTypeTemplateArgumentType(), Info, Deduced);
2380
2382 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2383 A.getNullPtrType(), Info, Deduced);
2384
2387 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2388 Info, Deduced);
2389
2395 Info.FirstArg = P;
2396 Info.SecondArg = A;
2398 }
2399 llvm_unreachable("Unknown template argument kind");
2400 }
2401
2402 // Can't deduce anything, but that's okay.
2405 llvm_unreachable("Argument packs should be expanded by the caller!");
2406 }
2407
2408 llvm_unreachable("Invalid TemplateArgument Kind!");
2409}
2410
2411/// Determine whether there is a template argument to be used for
2412/// deduction.
2413///
2414/// This routine "expands" argument packs in-place, overriding its input
2415/// parameters so that \c Args[ArgIdx] will be the available template argument.
2416///
2417/// \returns true if there is another template argument (which will be at
2418/// \c Args[ArgIdx]), false otherwise.
2420 unsigned &ArgIdx) {
2421 if (ArgIdx == Args.size())
2422 return false;
2423
2424 const TemplateArgument &Arg = Args[ArgIdx];
2425 if (Arg.getKind() != TemplateArgument::Pack)
2426 return true;
2427
2428 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2429 Args = Arg.pack_elements();
2430 ArgIdx = 0;
2431 return ArgIdx < Args.size();
2432}
2433
2434/// Determine whether the given set of template arguments has a pack
2435/// expansion that is not the last template argument.
2437 bool FoundPackExpansion = false;
2438 for (const auto &A : Args) {
2439 if (FoundPackExpansion)
2440 return true;
2441
2442 if (A.getKind() == TemplateArgument::Pack)
2443 return hasPackExpansionBeforeEnd(A.pack_elements());
2444
2445 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2446 // templates, it should not be treated as a pack expansion.
2447 if (A.isPackExpansion())
2448 FoundPackExpansion = true;
2449 }
2450
2451 return false;
2452}
2453
2460 bool NumberOfArgumentsMustMatch) {
2461 // C++0x [temp.deduct.type]p9:
2462 // If the template argument list of P contains a pack expansion that is not
2463 // the last template argument, the entire template argument list is a
2464 // non-deduced context.
2467
2468 // C++0x [temp.deduct.type]p9:
2469 // If P has a form that contains <T> or <i>, then each argument Pi of the
2470 // respective template argument list P is compared with the corresponding
2471 // argument Ai of the corresponding template argument list of A.
2472 unsigned ArgIdx = 0, ParamIdx = 0;
2474 const TemplateArgument &P = Ps[ParamIdx];
2475 if (!P.isPackExpansion()) {
2476 // The simple case: deduce template arguments by matching Pi and Ai.
2477
2478 // Check whether we have enough arguments.
2479 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2480 return NumberOfArgumentsMustMatch
2483
2484 // C++1z [temp.deduct.type]p9:
2485 // During partial ordering, if Ai was originally a pack expansion [and]
2486 // Pi is not a pack expansion, template argument deduction fails.
2487 if (As[ArgIdx].isPackExpansion())
2489
2490 // Perform deduction for this Pi/Ai pair.
2491 if (auto Result = DeduceTemplateArguments(S, TemplateParams, P,
2492 As[ArgIdx], Info, Deduced);
2494 return Result;
2495
2496 // Move to the next argument.
2497 ++ArgIdx;
2498 continue;
2499 }
2500
2501 // The parameter is a pack expansion.
2502
2503 // C++0x [temp.deduct.type]p9:
2504 // If Pi is a pack expansion, then the pattern of Pi is compared with
2505 // each remaining argument in the template argument list of A. Each
2506 // comparison deduces template arguments for subsequent positions in the
2507 // template parameter packs expanded by Pi.
2508 TemplateArgument Pattern = P.getPackExpansionPattern();
2509
2510 // Prepare to deduce the packs within the pattern.
2511 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2512
2513 // Keep track of the deduced template arguments for each parameter pack
2514 // expanded by this pack expansion (the outer index) and for each
2515 // template argument (the inner SmallVectors).
2516 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2517 PackScope.hasNextElement();
2518 ++ArgIdx) {
2519 // Deduce template arguments from the pattern.
2520 if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pattern,
2521 As[ArgIdx], Info, Deduced);
2523 return Result;
2524
2525 PackScope.nextPackElement();
2526 }
2527
2528 // Build argument packs for each of the parameter packs expanded by this
2529 // pack expansion.
2530 if (auto Result = PackScope.finish();
2532 return Result;
2533 }
2534
2536}
2537
2542 bool NumberOfArgumentsMustMatch) {
2543 return ::DeduceTemplateArguments(*this, TemplateParams, Ps, As, Info, Deduced,
2544 NumberOfArgumentsMustMatch);
2545}
2546
2547/// Determine whether two template arguments are the same.
2548static bool isSameTemplateArg(ASTContext &Context,
2550 const TemplateArgument &Y,
2551 bool PartialOrdering,
2552 bool PackExpansionMatchesPack = false) {
2553 // If we're checking deduced arguments (X) against original arguments (Y),
2554 // we will have flattened packs to non-expansions in X.
2555 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2556 X = X.getPackExpansionPattern();
2557
2558 if (X.getKind() != Y.getKind())
2559 return false;
2560
2561 switch (X.getKind()) {
2563 llvm_unreachable("Comparing NULL template argument");
2564
2566 return Context.getCanonicalType(X.getAsType()) ==
2567 Context.getCanonicalType(Y.getAsType());
2568
2570 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2571
2573 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2574
2577 return Context.getCanonicalTemplateName(
2578 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2581
2583 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2584
2586 return X.structurallyEquals(Y);
2587
2589 llvm::FoldingSetNodeID XID, YID;
2590 X.getAsExpr()->Profile(XID, Context, true);
2591 Y.getAsExpr()->Profile(YID, Context, true);
2592 return XID == YID;
2593 }
2594
2596 unsigned PackIterationSize = X.pack_size();
2597 if (X.pack_size() != Y.pack_size()) {
2598 if (!PartialOrdering)
2599 return false;
2600
2601 // C++0x [temp.deduct.type]p9:
2602 // During partial ordering, if Ai was originally a pack expansion:
2603 // - if P does not contain a template argument corresponding to Ai
2604 // then Ai is ignored;
2605 bool XHasMoreArg = X.pack_size() > Y.pack_size();
2606 if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
2607 !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
2608 return false;
2609
2610 if (XHasMoreArg)
2611 PackIterationSize = Y.pack_size();
2612 }
2613
2614 ArrayRef<TemplateArgument> XP = X.pack_elements();
2616 for (unsigned i = 0; i < PackIterationSize; ++i)
2617 if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
2618 PackExpansionMatchesPack))
2619 return false;
2620 return true;
2621 }
2622 }
2623
2624 llvm_unreachable("Invalid TemplateArgument Kind!");
2625}
2626
2627/// Allocate a TemplateArgumentLoc where all locations have
2628/// been initialized to the given location.
2629///
2630/// \param Arg The template argument we are producing template argument
2631/// location information for.
2632///
2633/// \param NTTPType For a declaration template argument, the type of
2634/// the non-type template parameter that corresponds to this template
2635/// argument. Can be null if no type sugar is available to add to the
2636/// type from the template argument.
2637///
2638/// \param Loc The source location to use for the resulting template
2639/// argument.
2642 QualType NTTPType, SourceLocation Loc) {
2643 switch (Arg.getKind()) {
2645 llvm_unreachable("Can't get a NULL template argument here");
2646
2648 return TemplateArgumentLoc(
2649 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2650
2652 if (NTTPType.isNull())
2653 NTTPType = Arg.getParamTypeForDecl();
2654 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2655 .getAs<Expr>();
2657 }
2658
2660 if (NTTPType.isNull())
2661 NTTPType = Arg.getNullPtrType();
2662 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2663 .getAs<Expr>();
2664 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2665 E);
2666 }
2667
2672 }
2673
2679 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2680 else if (QualifiedTemplateName *QTN =
2681 Template.getAsQualifiedTemplateName())
2682 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2683
2685 return TemplateArgumentLoc(Context, Arg,
2686 Builder.getWithLocInContext(Context), Loc);
2687
2688 return TemplateArgumentLoc(
2689 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
2690 }
2691
2693 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2694
2697 }
2698
2699 llvm_unreachable("Invalid TemplateArgument Kind!");
2700}
2701
2704 SourceLocation Location) {
2706 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2707}
2708
2709/// Convert the given deduced template argument and add it to the set of
2710/// fully-converted template arguments.
2712 Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template,
2713 TemplateDeductionInfo &Info, bool IsDeduced,
2714 SmallVectorImpl<TemplateArgument> &SugaredOutput,
2715 SmallVectorImpl<TemplateArgument> &CanonicalOutput) {
2716 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2717 unsigned ArgumentPackIndex) {
2718 // Convert the deduced template argument into a template
2719 // argument that we can check, almost as if the user had written
2720 // the template argument explicitly.
2721 TemplateArgumentLoc ArgLoc =
2723
2724 // Check the template argument, converting it as necessary.
2725 return S.CheckTemplateArgument(
2726 Param, ArgLoc, Template, Template->getLocation(),
2727 Template->getSourceRange().getEnd(), ArgumentPackIndex, SugaredOutput,
2728 CanonicalOutput,
2729 IsDeduced
2733 };
2734
2735 if (Arg.getKind() == TemplateArgument::Pack) {
2736 // This is a template argument pack, so check each of its arguments against
2737 // the template parameter.
2738 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2739 CanonicalPackedArgsBuilder;
2740 for (const auto &P : Arg.pack_elements()) {
2741 // When converting the deduced template argument, append it to the
2742 // general output list. We need to do this so that the template argument
2743 // checking logic has all of the prior template arguments available.
2744 DeducedTemplateArgument InnerArg(P);
2746 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2747 "deduced nested pack");
2748 if (P.isNull()) {
2749 // We deduced arguments for some elements of this pack, but not for
2750 // all of them. This happens if we get a conditionally-non-deduced
2751 // context in a pack expansion (such as an overload set in one of the
2752 // arguments).
2753 S.Diag(Param->getLocation(),
2754 diag::err_template_arg_deduced_incomplete_pack)
2755 << Arg << Param;
2756 return true;
2757 }
2758 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2759 return true;
2760
2761 // Move the converted template argument into our argument pack.
2762 SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
2763 CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
2764 }
2765
2766 // If the pack is empty, we still need to substitute into the parameter
2767 // itself, in case that substitution fails.
2768 if (SugaredPackedArgsBuilder.empty()) {
2770 MultiLevelTemplateArgumentList Args(Template, SugaredOutput,
2771 /*Final=*/true);
2772
2773 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2774 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2775 NTTP, SugaredOutput,
2776 Template->getSourceRange());
2777 if (Inst.isInvalid() ||
2778 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2779 NTTP->getDeclName()).isNull())
2780 return true;
2781 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2782 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2783 TTP, SugaredOutput,
2784 Template->getSourceRange());
2785 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2786 return true;
2787 }
2788 // For type parameters, no substitution is ever required.
2789 }
2790
2791 // Create the resulting argument pack.
2792 SugaredOutput.push_back(
2793 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
2794 CanonicalOutput.push_back(TemplateArgument::CreatePackCopy(
2795 S.Context, CanonicalPackedArgsBuilder));
2796 return false;
2797 }
2798
2799 return ConvertArg(Arg, 0);
2800}
2801
2802// FIXME: This should not be a template, but
2803// ClassTemplatePartialSpecializationDecl sadly does not derive from
2804// TemplateDecl.
2805template <typename TemplateDeclT>
2807 Sema &S, TemplateDeclT *Template, bool IsDeduced,
2810 SmallVectorImpl<TemplateArgument> &SugaredBuilder,
2811 SmallVectorImpl<TemplateArgument> &CanonicalBuilder,
2812 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2813 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2814 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2815
2816 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2817 NamedDecl *Param = TemplateParams->getParam(I);
2818
2819 // C++0x [temp.arg.explicit]p3:
2820 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2821 // be deduced to an empty sequence of template arguments.
2822 // FIXME: Where did the word "trailing" come from?
2823 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2824 if (auto Result =
2825 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
2827 return Result;
2828 }
2829
2830 if (!Deduced[I].isNull()) {
2831 if (I < NumAlreadyConverted) {
2832 // We may have had explicitly-specified template arguments for a
2833 // template parameter pack (that may or may not have been extended
2834 // via additional deduced arguments).
2835 if (Param->isParameterPack() && CurrentInstantiationScope &&
2836 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2837 // Forget the partially-substituted pack; its substitution is now
2838 // complete.
2839 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2840 // We still need to check the argument in case it was extended by
2841 // deduction.
2842 } else {
2843 // We have already fully type-checked and converted this
2844 // argument, because it was explicitly-specified. Just record the
2845 // presence of this argument.
2846 SugaredBuilder.push_back(Deduced[I]);
2847 CanonicalBuilder.push_back(
2849 continue;
2850 }
2851 }
2852
2853 // We may have deduced this argument, so it still needs to be
2854 // checked and converted.
2855 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2856 IsDeduced, SugaredBuilder,
2857 CanonicalBuilder)) {
2858 Info.Param = makeTemplateParameter(Param);
2859 // FIXME: These template arguments are temporary. Free them!
2860 Info.reset(
2861 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
2862 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
2864 }
2865
2866 continue;
2867 }
2868
2869 // Substitute into the default template argument, if available.
2870 bool HasDefaultArg = false;
2871 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2872 if (!TD) {
2873 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2874 isa<VarTemplatePartialSpecializationDecl>(Template));
2876 }
2877
2878 TemplateArgumentLoc DefArg;
2879 {
2880 Qualifiers ThisTypeQuals;
2881 CXXRecordDecl *ThisContext = nullptr;
2882 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
2883 if (Rec->isLambda())
2884 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
2885 ThisContext = Method->getParent();
2886 ThisTypeQuals = Method->getMethodQualifiers();
2887 }
2888
2889 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
2890 S.getLangOpts().CPlusPlus17);
2891
2893 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param,
2894 SugaredBuilder, CanonicalBuilder, HasDefaultArg);
2895 }
2896
2897 // If there was no default argument, deduction is incomplete.
2898 if (DefArg.getArgument().isNull()) {
2900 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2901 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
2902 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
2903 if (PartialOverloading) break;
2904
2907 }
2908
2909 // Check whether we can actually use the default argument.
2911 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
2912 0, SugaredBuilder, CanonicalBuilder, Sema::CTAK_Specified)) {
2914 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2915 // FIXME: These template arguments are temporary. Free them!
2916 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
2917 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
2919 }
2920
2921 // If we get here, we successfully used the default template argument.
2922 }
2923
2925}
2926
2928 if (auto *DC = dyn_cast<DeclContext>(D))
2929 return DC;
2930 return D->getDeclContext();
2931}
2932
2933template<typename T> struct IsPartialSpecialization {
2934 static constexpr bool value = false;
2935};
2936template<>
2938 static constexpr bool value = true;
2939};
2940template<>
2942 static constexpr bool value = true;
2943};
2944template <typename TemplateDeclT>
2945static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
2946 return false;
2947}
2948template <>
2951 return !Spec->isClassScopeExplicitSpecialization();
2952}
2953template <>
2956 return !Spec->isClassScopeExplicitSpecialization();
2957}
2958
2959template <typename TemplateDeclT>
2961CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
2962 ArrayRef<TemplateArgument> SugaredDeducedArgs,
2963 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
2964 TemplateDeductionInfo &Info) {
2965 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
2966 Template->getAssociatedConstraints(AssociatedConstraints);
2967
2968 std::optional<ArrayRef<TemplateArgument>> Innermost;
2969 // If we don't need to replace the deduced template arguments,
2970 // we can add them immediately as the inner-most argument list.
2971 if (!DeducedArgsNeedReplacement(Template))
2972 Innermost = CanonicalDeducedArgs;
2973
2975 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
2976 /*RelativeToPrimary=*/true, /*Pattern=*/
2977 nullptr, /*ForConstraintInstantiation=*/true);
2978
2979 // getTemplateInstantiationArgs picks up the non-deduced version of the
2980 // template args when this is a variable template partial specialization and
2981 // not class-scope explicit specialization, so replace with Deduced Args
2982 // instead of adding to inner-most.
2983 if (!Innermost)
2984 MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs);
2985
2986 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
2987 Info.getLocation(),
2990 Info.reset(
2991 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
2992 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
2994 }
2996}
2997
2998/// Complete template argument deduction for a partial specialization.
2999template <typename T>
3000static std::enable_if_t<IsPartialSpecialization<T>::value,
3003 Sema &S, T *Partial, bool IsPartialOrdering,
3004 ArrayRef<TemplateArgument> TemplateArgs,
3006 TemplateDeductionInfo &Info) {
3007 // Unevaluated SFINAE context.
3010 Sema::SFINAETrap Trap(S);
3011
3012 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
3013
3014 // C++ [temp.deduct.type]p2:
3015 // [...] or if any template argument remains neither deduced nor
3016 // explicitly specified, template argument deduction fails.
3017 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3019 S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
3020 CanonicalBuilder);
3022 return Result;
3023
3024 // Form the template argument list from the deduced template arguments.
3025 TemplateArgumentList *SugaredDeducedArgumentList =
3026 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
3027 TemplateArgumentList *CanonicalDeducedArgumentList =
3028 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
3029
3030 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3031
3032 // Substitute the deduced template arguments into the template
3033 // arguments of the class template partial specialization, and
3034 // verify that the instantiated template arguments are both valid
3035 // and are equivalent to the template arguments originally provided
3036 // to the class template.
3037 LocalInstantiationScope InstScope(S);
3038 auto *Template = Partial->getSpecializedTemplate();
3039 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
3040 Partial->getTemplateArgsAsWritten();
3041
3042 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
3043 PartialTemplArgInfo->RAngleLoc);
3044
3045 if (S.SubstTemplateArguments(PartialTemplArgInfo->arguments(),
3047 SugaredBuilder,
3048 /*Final=*/true),
3049 InstArgs)) {
3050 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3051 if (ParamIdx >= Partial->getTemplateParameters()->size())
3052 ParamIdx = Partial->getTemplateParameters()->size() - 1;
3053
3054 Decl *Param = const_cast<NamedDecl *>(
3055 Partial->getTemplateParameters()->getParam(ParamIdx));
3056 Info.Param = makeTemplateParameter(Param);
3057 Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
3059 }
3060
3062 SmallVector<TemplateArgument, 4> SugaredConvertedInstArgs,
3063 CanonicalConvertedInstArgs;
3065 Template, Partial->getLocation(), InstArgs, false,
3066 SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
3067 /*UpdateArgsWithConversions=*/true, &ConstraintsNotSatisfied))
3071
3072 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3073 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3074 TemplateArgument InstArg = SugaredConvertedInstArgs.data()[I];
3075 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
3076 IsPartialOrdering)) {
3077 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3078 Info.FirstArg = TemplateArgs[I];
3079 Info.SecondArg = InstArg;
3081 }
3082 }
3083
3084 if (Trap.hasErrorOccurred())
3086
3087 if (auto Result = CheckDeducedArgumentConstraints(S, Partial, SugaredBuilder,
3088 CanonicalBuilder, Info);
3090 return Result;
3091
3093}
3094
3095/// Complete template argument deduction for a class or variable template,
3096/// when partial ordering against a partial specialization.
3097// FIXME: Factor out duplication with partial specialization version above.
3099 Sema &S, TemplateDecl *Template, bool PartialOrdering,
3100 ArrayRef<TemplateArgument> TemplateArgs,
3102 TemplateDeductionInfo &Info) {
3103 // Unevaluated SFINAE context.
3106 Sema::SFINAETrap Trap(S);
3107
3108 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
3109
3110 // C++ [temp.deduct.type]p2:
3111 // [...] or if any template argument remains neither deduced nor
3112 // explicitly specified, template argument deduction fails.
3113 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3115 S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info,
3116 SugaredBuilder, CanonicalBuilder,
3117 /*CurrentInstantiationScope=*/nullptr,
3118 /*NumAlreadyConverted=*/0U, /*PartialOverloading=*/false);
3120 return Result;
3121
3122 // Check that we produced the correct argument list.
3123 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3124 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3125 TemplateArgument InstArg = CanonicalBuilder[I];
3126 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, PartialOrdering,
3127 /*PackExpansionMatchesPack=*/true)) {
3128 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3129 Info.FirstArg = TemplateArgs[I];
3130 Info.SecondArg = InstArg;
3132 }
3133 }
3134
3135 if (Trap.hasErrorOccurred())
3137
3138 if (auto Result = CheckDeducedArgumentConstraints(S, Template, SugaredBuilder,
3139 CanonicalBuilder, Info);
3141 return Result;
3142
3144}
3145
3146/// Perform template argument deduction to determine whether the given template
3147/// arguments match the given class or variable template partial specialization
3148/// per C++ [temp.class.spec.match].
3149template <typename T>
3150static std::enable_if_t<IsPartialSpecialization<T>::value,
3153 ArrayRef<TemplateArgument> TemplateArgs,
3154 TemplateDeductionInfo &Info) {
3155 if (Partial->isInvalidDecl())
3157
3158 // C++ [temp.class.spec.match]p2:
3159 // A partial specialization matches a given actual template
3160 // argument list if the template arguments of the partial
3161 // specialization can be deduced from the actual template argument
3162 // list (14.8.2).
3163
3164 // Unevaluated SFINAE context.
3167 Sema::SFINAETrap Trap(S);
3168
3169 // This deduction has no relation to any outer instantiation we might be
3170 // performing.
3171 LocalInstantiationScope InstantiationScope(S);
3172
3174 Deduced.resize(Partial->getTemplateParameters()->size());
3176 S, Partial->getTemplateParameters(),
3177 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3178 /*NumberOfArgumentsMustMatch=*/false);
3180 return Result;
3181
3182 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3183 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs,
3184 Info);
3185 if (Inst.isInvalid())
3187
3188 if (Trap.hasErrorOccurred())
3190
3193 Result = ::FinishTemplateArgumentDeduction(S, Partial,
3194 /*IsPartialOrdering=*/false,
3195 TemplateArgs, Deduced, Info);
3196 });
3197 return Result;
3198}
3199
3202 ArrayRef<TemplateArgument> TemplateArgs,
3203 TemplateDeductionInfo &Info) {
3204 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3205}
3208 ArrayRef<TemplateArgument> TemplateArgs,
3209 TemplateDeductionInfo &Info) {
3210 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3211}
3212
3213/// Determine whether the given type T is a simple-template-id type.
3215 if (const TemplateSpecializationType *Spec
3217 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3218
3219 // C++17 [temp.local]p2:
3220 // the injected-class-name [...] is equivalent to the template-name followed
3221 // by the template-arguments of the class template specialization or partial
3222 // specialization enclosed in <>
3223 // ... which means it's equivalent to a simple-template-id.
3224 //
3225 // This only arises during class template argument deduction for a copy
3226 // deduction candidate, where it permits slicing.
3228 return true;
3229
3230 return false;
3231}
3232
3233/// Substitute the explicitly-provided template arguments into the
3234/// given function template according to C++ [temp.arg.explicit].
3235///
3236/// \param FunctionTemplate the function template into which the explicit
3237/// template arguments will be substituted.
3238///
3239/// \param ExplicitTemplateArgs the explicitly-specified template
3240/// arguments.
3241///
3242/// \param Deduced the deduced template arguments, which will be populated
3243/// with the converted and checked explicit template arguments.
3244///
3245/// \param ParamTypes will be populated with the instantiated function
3246/// parameters.
3247///
3248/// \param FunctionType if non-NULL, the result type of the function template
3249/// will also be instantiated and the pointed-to value will be updated with
3250/// the instantiated function type.
3251///
3252/// \param Info if substitution fails for any reason, this object will be
3253/// populated with more information about the failure.
3254///
3255/// \returns TemplateDeductionResult::Success if substitution was successful, or
3256/// some failure condition.
3258 FunctionTemplateDecl *FunctionTemplate,
3259 TemplateArgumentListInfo &ExplicitTemplateArgs,
3262 TemplateDeductionInfo &Info) {
3263 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3264 TemplateParameterList *TemplateParams
3265 = FunctionTemplate->getTemplateParameters();
3266
3267 if (ExplicitTemplateArgs.size() == 0) {
3268 // No arguments to substitute; just copy over the parameter types and
3269 // fill in the function type.
3270 for (auto *P : Function->parameters())
3271 ParamTypes.push_back(P->getType());
3272
3273 if (FunctionType)
3274 *FunctionType = Function->getType();
3276 }
3277
3278 // Unevaluated SFINAE context.
3281 SFINAETrap Trap(*this);
3282
3283 // C++ [temp.arg.explicit]p3:
3284 // Template arguments that are present shall be specified in the
3285 // declaration order of their corresponding template-parameters. The
3286 // template argument list shall not specify more template-arguments than
3287 // there are corresponding template-parameters.
3288 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3289
3290 // Enter a new template instantiation context where we check the
3291 // explicitly-specified template arguments against this function template,
3292 // and then substitute them into the function parameter types.
3295 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3297 if (Inst.isInvalid())
3299
3301 ExplicitTemplateArgs, true, SugaredBuilder,
3302 CanonicalBuilder,
3303 /*UpdateArgsWithConversions=*/false) ||
3304 Trap.hasErrorOccurred()) {
3305 unsigned Index = SugaredBuilder.size();
3306 if (Index >= TemplateParams->size())
3308 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3310 }
3311
3312 // Form the template argument list from the explicitly-specified
3313 // template arguments.
3314 TemplateArgumentList *SugaredExplicitArgumentList =
3316 TemplateArgumentList *CanonicalExplicitArgumentList =
3317 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3318 Info.setExplicitArgs(SugaredExplicitArgumentList,
3319 CanonicalExplicitArgumentList);
3320
3321 // Template argument deduction and the final substitution should be
3322 // done in the context of the templated declaration. Explicit
3323 // argument substitution, on the other hand, needs to happen in the
3324 // calling context.
3325 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3326
3327 // If we deduced template arguments for a template parameter pack,
3328 // note that the template argument pack is partially substituted and record
3329 // the explicit template arguments. They'll be used as part of deduction
3330 // for this template parameter pack.
3331 unsigned PartiallySubstitutedPackIndex = -1u;
3332 if (!CanonicalBuilder.empty()) {
3333 const TemplateArgument &Arg = CanonicalBuilder.back();
3334 if (Arg.getKind() == TemplateArgument::Pack) {
3335 auto *Param = TemplateParams->getParam(CanonicalBuilder.size() - 1);
3336 // If this is a fully-saturated fixed-size pack, it should be
3337 // fully-substituted, not partially-substituted.
3338 std::optional<unsigned> Expansions = getExpandedPackSize(Param);
3339 if (!Expansions || Arg.pack_size() < *Expansions) {
3340 PartiallySubstitutedPackIndex = CanonicalBuilder.size() - 1;
3342 Param, Arg.pack_begin(), Arg.pack_size());
3343 }
3344 }
3345 }
3346
3347 const FunctionProtoType *Proto
3348 = Function->getType()->getAs<FunctionProtoType>();
3349 assert(Proto && "Function template does not have a prototype?");
3350
3351 // Isolate our substituted parameters from our caller.
3352 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3353
3354 ExtParameterInfoBuilder ExtParamInfos;
3355
3357 SugaredExplicitArgumentList->asArray(),
3358 /*Final=*/true);
3359
3360 // Instantiate the types of each of the function parameters given the
3361 // explicitly-specified template arguments. If the function has a trailing
3362 // return type, substitute it after the arguments to ensure we substitute
3363 // in lexical order.
3364 if (Proto->hasTrailingReturn()) {
3365 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3366 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3367 /*params=*/nullptr, ExtParamInfos))
3369 }
3370
3371 // Instantiate the return type.
3372 QualType ResultType;
3373 {
3374 // C++11 [expr.prim.general]p3:
3375 // If a declaration declares a member function or member function
3376 // template of a class X, the expression this is a prvalue of type
3377 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3378 // and the end of the function-definition, member-declarator, or
3379 // declarator.
3380 Qualifiers ThisTypeQuals;
3381 CXXRecordDecl *ThisContext = nullptr;
3382 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3383 ThisContext = Method->getParent();
3384 ThisTypeQuals = Method->getMethodQualifiers();
3385 }
3386
3387 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3389
3390 ResultType =
3391 SubstType(Proto->getReturnType(), MLTAL,
3392 Function->getTypeSpecStartLoc(), Function->getDeclName());
3393 if (ResultType.isNull() || Trap.hasErrorOccurred())
3395 // CUDA: Kernel function must have 'void' return type.
3396 if (getLangOpts().CUDA)
3397 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3398 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3399 << Function->getType() << Function->getSourceRange();
3401 }
3402 }
3403
3404 // Instantiate the types of each of the function parameters given the
3405 // explicitly-specified template arguments if we didn't do so earlier.
3406 if (!Proto->hasTrailingReturn() &&
3407 SubstParmTypes(Function->getLocation(), Function->parameters(),
3408 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3409 /*params*/ nullptr, ExtParamInfos))
3411
3412 if (FunctionType) {
3413 auto EPI = Proto->getExtProtoInfo();
3414 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3415
3416 // In C++1z onwards, exception specifications are part of the function type,
3417 // so substitution into the type must also substitute into the exception
3418 // specification.
3419 SmallVector<QualType, 4> ExceptionStorage;
3420 if (getLangOpts().CPlusPlus17 &&
3422 Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
3424 FunctionTemplate, nullptr, /*Final=*/true,
3425 /*Innermost=*/SugaredExplicitArgumentList->asArray(),
3426 /*RelativeToPrimary=*/false,
3427 /*Pattern=*/nullptr,
3428 /*ForConstraintInstantiation=*/false,
3429 /*SkipForSpecialization=*/true)))
3431
3432 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3433 Function->getLocation(),
3434 Function->getDeclName(),
3435 EPI);
3436 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3438 }
3439
3440 // C++ [temp.arg.explicit]p2:
3441 // Trailing template arguments that can be deduced (14.8.2) may be
3442 // omitted from the list of explicit template-arguments. If all of the
3443 // template arguments can be deduced, they may all be omitted; in this
3444 // case, the empty template argument list <> itself may also be omitted.
3445 //
3446 // Take all of the explicitly-specified arguments and put them into
3447 // the set of deduced template arguments. The partially-substituted
3448 // parameter pack, however, will be set to NULL since the deduction
3449 // mechanism handles the partially-substituted argument pack directly.
3450 Deduced.reserve(TemplateParams->size());
3451 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3452 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3453 if (I == PartiallySubstitutedPackIndex)
3454 Deduced.push_back(DeducedTemplateArgument());
3455 else
3456 Deduced.push_back(Arg);
3457 }
3458
3460}
3461
3462/// Check whether the deduced argument type for a call to a function
3463/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3466 Sema::OriginalCallArg OriginalArg,
3467 QualType DeducedA) {
3468 ASTContext &Context = S.Context;
3469
3470 auto Failed = [&]() -> TemplateDeductionResult {
3471 Info.FirstArg = TemplateArgument(DeducedA);
3472 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3473 Info.CallArgIndex = OriginalArg.ArgIdx;
3474 return OriginalArg.DecomposedParam
3477 };
3478
3479 QualType A = OriginalArg.OriginalArgType;
3480 QualType OriginalParamType = OriginalArg.OriginalParamType;
3481
3482 // Check for type equality (top-level cv-qualifiers are ignored).
3483 if (Context.hasSameUnqualifiedType(A, DeducedA))
3485
3486 // Strip off references on the argument types; they aren't needed for
3487 // the following checks.
3488 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3489 DeducedA = DeducedARef->getPointeeType();
3490 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3491 A = ARef->getPointeeType();
3492
3493 // C++ [temp.deduct.call]p4:
3494 // [...] However, there are three cases that allow a difference:
3495 // - If the original P is a reference type, the deduced A (i.e., the
3496 // type referred to by the reference) can be more cv-qualified than
3497 // the transformed A.
3498 if (const ReferenceType *OriginalParamRef
3499 = OriginalParamType->getAs<ReferenceType>()) {
3500 // We don't want to keep the reference around any more.
3501 OriginalParamType = OriginalParamRef->getPointeeType();
3502
3503 // FIXME: Resolve core issue (no number yet): if the original P is a
3504 // reference type and the transformed A is function type "noexcept F",
3505 // the deduced A can be F.
3506 QualType Tmp;
3507 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3509
3510 Qualifiers AQuals = A.getQualifiers();
3511 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3512
3513 // Under Objective-C++ ARC, the deduced type may have implicitly
3514 // been given strong or (when dealing with a const reference)
3515 // unsafe_unretained lifetime. If so, update the original
3516 // qualifiers to include this lifetime.
3517 if (S.getLangOpts().ObjCAutoRefCount &&
3518 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3520 (DeducedAQuals.hasConst() &&
3521 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3522 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3523 }
3524
3525 if (AQuals == DeducedAQuals) {
3526 // Qualifiers match; there's nothing to do.
3527 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
3528 return Failed();
3529 } else {
3530 // Qualifiers are compatible, so have the argument type adopt the
3531 // deduced argument type's qualifiers as if we had performed the
3532 // qualification conversion.
3533 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3534 }
3535 }
3536
3537 // - The transformed A can be another pointer or pointer to member
3538 // type that can be converted to the deduced A via a function pointer
3539 // conversion and/or a qualification conversion.
3540 //
3541 // Also allow conversions which merely strip __attribute__((noreturn)) from
3542 // function types (recursively).
3543 bool ObjCLifetimeConversion = false;
3544 QualType ResultTy;
3545 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3546 (S.IsQualificationConversion(A, DeducedA, false,
3547 ObjCLifetimeConversion) ||
3548 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3550
3551 // - If P is a class and P has the form simple-template-id, then the
3552 // transformed A can be a derived class of the deduced A. [...]
3553 // [...] Likewise, if P is a pointer to a class of the form
3554 // simple-template-id, the transformed A can be a pointer to a
3555 // derived class pointed to by the deduced A.
3556 if (const PointerType *OriginalParamPtr
3557 = OriginalParamType->getAs<PointerType>()) {
3558 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3559 if (const PointerType *APtr = A->getAs<PointerType>()) {
3560 if (A->getPointeeType()->isRecordType()) {
3561 OriginalParamType = OriginalParamPtr->getPointeeType();
3562 DeducedA = DeducedAPtr->getPointeeType();
3563 A = APtr->getPointeeType();
3564 }
3565 }
3566 }
3567 }
3568
3569 if (Context.hasSameUnqualifiedType(A, DeducedA))
3571
3572 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3573 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3575
3576 return Failed();
3577}
3578
3579/// Find the pack index for a particular parameter index in an instantiation of
3580/// a function template with specific arguments.
3581///
3582/// \return The pack index for whichever pack produced this parameter, or -1
3583/// if this was not produced by a parameter. Intended to be used as the
3584/// ArgumentPackSubstitutionIndex for further substitutions.
3585// FIXME: We should track this in OriginalCallArgs so we don't need to
3586// reconstruct it here.
3587static unsigned getPackIndexForParam(Sema &S,
3588 FunctionTemplateDecl *FunctionTemplate,
3590 unsigned ParamIdx) {
3591 unsigned Idx = 0;
3592 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3593 if (PD->isParameterPack()) {
3594 unsigned NumExpansions =
3595 S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
3596 if (Idx + NumExpansions > ParamIdx)
3597 return ParamIdx - Idx;
3598 Idx += NumExpansions;
3599 } else {
3600 if (Idx == ParamIdx)
3601 return -1; // Not a pack expansion
3602 ++Idx;
3603 }
3604 }
3605
3606 llvm_unreachable("parameter index would not be produced from template");
3607}
3608
3609// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3610// we'll try to instantiate and update its explicit specifier after constraint
3611// checking.
3614 const MultiLevelTemplateArgumentList &SubstArgs,
3615 TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate,
3616 ArrayRef<TemplateArgument> DeducedArgs) {
3617 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3618 return isa<CXXConstructorDecl>(D)
3619 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3620 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3621 };
3622 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3623 isa<CXXConstructorDecl>(D)
3624 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3625 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3626 };
3627
3628 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3629 Expr *ExplicitExpr = ES.getExpr();
3630 if (!ExplicitExpr)
3632 if (!ExplicitExpr->isValueDependent())
3634
3636 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3638 if (Inst.isInvalid())
3640 Sema::SFINAETrap Trap(S);
3641 const ExplicitSpecifier InstantiatedES =
3642 S.instantiateExplicitSpecifier(SubstArgs, ES);
3643 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3644 Specialization->setInvalidDecl(true);
3646 }
3647 SetExplicitSpecifier(Specialization, InstantiatedES);
3649}
3650
3651/// Finish template argument deduction for a function template,
3652/// checking the deduced template arguments for completeness and forming
3653/// the function template specialization.
3654///
3655/// \param OriginalCallArgs If non-NULL, the original call arguments against
3656/// which the deduced argument types should be compared.
3658 FunctionTemplateDecl *FunctionTemplate,
3660 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3662 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3663 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3664 // Unevaluated SFINAE context.
3667 SFINAETrap Trap(*this);
3668
3669 // Enter a new template instantiation context while we instantiate the
3670 // actual function declaration.
3671 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3673 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3675 if (Inst.isInvalid())
3677
3678 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3679
3680 // C++ [temp.deduct.type]p2:
3681 // [...] or if any template argument remains neither deduced nor
3682 // explicitly specified, template argument deduction fails.
3683 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3685 *this, FunctionTemplate, /*IsDeduced*/ true, Deduced, Info,
3686 SugaredBuilder, CanonicalBuilder, CurrentInstantiationScope,
3687 NumExplicitlySpecified, PartialOverloading);
3689 return Result;
3690
3691 // C++ [temp.deduct.call]p10: [DR1391]
3692 // If deduction succeeds for all parameters that contain
3693 // template-parameters that participate in template argument deduction,
3694 // and all template arguments are explicitly specified, deduced, or
3695 // obtained from default template arguments, remaining parameters are then
3696 // compared with the corresponding arguments. For each remaining parameter
3697 // P with a type that was non-dependent before substitution of any
3698 // explicitly-specified template arguments, if the corresponding argument
3699 // A cannot be implicitly converted to P, deduction fails.
3700 if (CheckNonDependent())
3702
3703 // Form the template argument list from the deduced template arguments.
3704 TemplateArgumentList *SugaredDeducedArgumentList =
3706 TemplateArgumentList *CanonicalDeducedArgumentList =
3707 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3708 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3709
3710 // Substitute the deduced template arguments into the function template
3711 // declaration to produce the function template specialization.
3712 DeclContext *Owner = FunctionTemplate->getDeclContext();
3713 if (FunctionTemplate->getFriendObjectKind())
3714 Owner = FunctionTemplate->getLexicalDeclContext();
3715 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3716 // additional check for inline friend,
3717 // ```
3718 // template <class F1> int foo(F1 X);
3719 // template <int A1> struct A {
3720 // template <class F1> friend int foo(F1 X) { return A1; }
3721 // };
3722 // template struct A<1>;
3723 // int a = foo(1.0);
3724 // ```
3725 const FunctionDecl *FDFriend;
3727 FD->isDefined(FDFriend, /*CheckForPendingFriendDefinition*/ true) &&
3729 FD = const_cast<FunctionDecl *>(FDFriend);
3730 Owner = FD->getLexicalDeclContext();
3731 }
3733 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
3734 /*Final=*/false);
3735 Specialization = cast_or_null<FunctionDecl>(
3736 SubstDecl(FD, Owner, SubstArgs));
3737 if (!Specialization || Specialization->isInvalidDecl())
3739
3740 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
3741 FunctionTemplate->getCanonicalDecl());
3742
3743 // If the template argument list is owned by the function template
3744 // specialization, release it.
3745 if (Specialization->getTemplateSpecializationArgs() ==
3746 CanonicalDeducedArgumentList &&
3747 !Trap.hasErrorOccurred())
3748 Info.takeCanonical();
3749
3750 // There may have been an error that did not prevent us from constructing a
3751 // declaration. Mark the declaration invalid and return with a substitution
3752 // failure.
3753 if (Trap.hasErrorOccurred()) {
3754 Specialization->setInvalidDecl(true);
3756 }
3757
3758 // C++2a [temp.deduct]p5
3759 // [...] When all template arguments have been deduced [...] all uses of
3760 // template parameters [...] are replaced with the corresponding deduced
3761 // or default argument values.
3762 // [...] If the function template has associated constraints
3763 // ([temp.constr.decl]), those constraints are checked for satisfaction
3764 // ([temp.constr.constr]). If the constraints are not satisfied, type
3765 // deduction fails.
3766 if (!PartialOverloading ||
3767 (CanonicalBuilder.size() ==
3768 FunctionTemplate->getTemplateParameters()->size())) {
3770 Info.getLocation(), Specialization, CanonicalBuilder,
3773
3775 Info.reset(Info.takeSugared(),
3776 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
3778 }
3779 }
3780
3781 // We skipped the instantiation of the explicit-specifier during the
3782 // substitution of `FD` before. So, we try to instantiate it back if
3783 // `Specialization` is either a constructor or a conversion function.
3784 if (isa<CXXConstructorDecl, CXXConversionDecl>(Specialization)) {
3787 Info, FunctionTemplate,
3788 DeducedArgs)) {
3790 }
3791 }
3792
3793 if (OriginalCallArgs) {
3794 // C++ [temp.deduct.call]p4:
3795 // In general, the deduction process attempts to find template argument
3796 // values that will make the deduced A identical to A (after the type A
3797 // is transformed as described above). [...]
3798 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
3799 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3800 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
3801
3802 auto ParamIdx = OriginalArg.ArgIdx;
3803 unsigned ExplicitOffset =
3804 Specialization->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
3805 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
3806 // FIXME: This presumably means a pack ended up smaller than we
3807 // expected while deducing. Should this not result in deduction
3808 // failure? Can it even happen?
3809 continue;
3810
3811 QualType DeducedA;
3812 if (!OriginalArg.DecomposedParam) {
3813 // P is one of the function parameters, just look up its substituted
3814 // type.
3815 DeducedA =
3816 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
3817 } else {
3818 // P is a decomposed element of a parameter corresponding to a
3819 // braced-init-list argument. Substitute back into P to find the
3820 // deduced A.
3821 QualType &CacheEntry =
3822 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3823 if (CacheEntry.isNull()) {
3825 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3826 ParamIdx));
3827 CacheEntry =
3828 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3829 Specialization->getTypeSpecStartLoc(),
3830 Specialization->getDeclName());
3831 }
3832 DeducedA = CacheEntry;
3833 }
3834
3835 if (auto TDK =
3836 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
3838 return TDK;
3839 }
3840 }
3841
3842 // If we suppressed any diagnostics while performing template argument
3843 // deduction, and if we haven't already instantiated this declaration,
3844 // keep track of these diagnostics. They'll be emitted if this specialization
3845 // is actually used.
3846 if (Info.diag_begin() != Info.diag_end()) {
3847 SuppressedDiagnosticsMap::iterator
3848 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3849 if (Pos == SuppressedDiagnostics.end())
3850 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3851 .append(Info.diag_begin(), Info.diag_end());
3852 }
3853
3855}
3856
3857/// Gets the type of a function for template-argument-deducton
3858/// purposes when it's considered as part of an overload set.
3860 FunctionDecl *Fn) {
3861 // We may need to deduce the return type of the function now.
3862 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
3863 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
3864 return {};
3865
3866 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
3867 if (Method->isImplicitObjectMemberFunction()) {
3868 // An instance method that's referenced in a form that doesn't
3869 // look like a member pointer is just invalid.
3871 return {};
3872
3873 return S.Context.getMemberPointerType(Fn->getType(),
3874 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
3875 }
3876
3877 if (!R.IsAddressOfOperand) return Fn->getType();
3878 return S.Context.getPointerType(Fn->getType());
3879}
3880
3881/// Apply the deduction rules for overload sets.
3882///
3883/// \return the null type if this argument should be treated as an
3884/// undeduced context
3885static QualType
3887 Expr *Arg, QualType ParamType,
3888 bool ParamWasReference,
3889 TemplateSpecCandidateSet *FailedTSC = nullptr) {
3890
3892
3893 OverloadExpr *Ovl = R.Expression;
3894
3895 // C++0x [temp.deduct.call]p4
3896 unsigned TDF = 0;
3897 if (ParamWasReference)
3899 if (R.IsAddressOfOperand)
3900 TDF |= TDF_IgnoreQualifiers;
3901
3902 // C++0x [temp.deduct.call]p6:
3903 // When P is a function type, pointer to function type, or pointer
3904 // to member function type:
3905
3906 if (!ParamType->isFunctionType() &&
3907 !ParamType->isFunctionPointerType() &&
3908 !ParamType->isMemberFunctionPointerType()) {
3909 if (Ovl->hasExplicitTemplateArgs()) {
3910 // But we can still look for an explicit specialization.
3911 if (FunctionDecl *ExplicitSpec =
3913 Ovl, /*Complain=*/false,
3914 /*FoundDeclAccessPair=*/nullptr, FailedTSC))
3915 return GetTypeOfFunction(S, R, ExplicitSpec);
3916 }
3917
3918 DeclAccessPair DAP;
3919 if (FunctionDecl *Viable =
3921 return GetTypeOfFunction(S, R, Viable);
3922
3923 return {};
3924 }
3925
3926 // Gather the explicit template arguments, if any.
3927 TemplateArgumentListInfo ExplicitTemplateArgs;
3928 if (Ovl->hasExplicitTemplateArgs())
3929 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
3930 QualType Match;
3931 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3932 E = Ovl->decls_end(); I != E; ++I) {
3933 NamedDecl *D = (*I)->getUnderlyingDecl();
3934
3935 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3936 // - If the argument is an overload set containing one or more
3937 // function templates, the parameter is treated as a
3938 // non-deduced context.
3939 if (!Ovl->hasExplicitTemplateArgs())
3940 return {};
3941
3942 // Otherwise, see if we can resolve a function type
3943 FunctionDecl *Specialization = nullptr;
3944 TemplateDeductionInfo Info(Ovl->getNameLoc());
3945 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3948 continue;
3949
3950 D = Specialization;
3951 }
3952
3953 FunctionDecl *Fn = cast<FunctionDecl>(D);
3954 QualType ArgType = GetTypeOfFunction(S, R, Fn);
3955 if (ArgType.isNull()) continue;
3956
3957 // Function-to-pointer conversion.
3958 if (!ParamWasReference && ParamType->isPointerType() &&
3959 ArgType->isFunctionType())
3960 ArgType = S.Context.getPointerType(ArgType);
3961
3962 // - If the argument is an overload set (not containing function
3963 // templates), trial argument deduction is attempted using each
3964 // of the members of the set. If deduction succeeds for only one
3965 // of the overload set members, that member is used as the
3966 // argument value for the deduction. If deduction succeeds for
3967 // more than one member of the overload set the parameter is
3968 // treated as a non-deduced context.
3969
3970 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3971 // Type deduction is done independently for each P/A pair, and
3972 // the deduced template argument values are then combined.
3973 // So we do not reject deductions which were made elsewhere.
3975 Deduced(TemplateParams->size());
3976 TemplateDeductionInfo Info(Ovl->getNameLoc());
3978 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF);
3980 continue;
3981 if (!Match.isNull())
3982 return {};
3983 Match = ArgType;
3984 }
3985
3986 return Match;
3987}
3988
3989/// Perform the adjustments to the parameter and argument types
3990/// described in C++ [temp.deduct.call].
3991///
3992/// \returns true if the caller should not attempt to perform any template
3993/// argument deduction based on this P/A pair because the argument is an
3994/// overloaded function set that could not be resolved.
3996 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3997 QualType &ParamType, QualType &ArgType,
3998 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
3999 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4000 // C++0x [temp.deduct.call]p3:
4001 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4002 // are ignored for type deduction.
4003 if (ParamType.hasQualifiers())
4004 ParamType = ParamType.getUnqualifiedType();
4005
4006 // [...] If P is a reference type, the type referred to by P is
4007 // used for type deduction.
4008 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4009 if (ParamRefType)
4010 ParamType = ParamRefType->getPointeeType();
4011
4012 // Overload sets usually make this parameter an undeduced context,
4013 // but there are sometimes special circumstances. Typically
4014 // involving a template-id-expr.
4015 if (ArgType == S.Context.OverloadTy) {
4016 assert(Arg && "expected a non-null arg expression");
4017 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4018 ParamRefType != nullptr, FailedTSC);
4019 if (ArgType.isNull())
4020 return true;
4021 }
4022
4023 if (ParamRefType) {
4024 // If the argument has incomplete array type, try to complete its type.
4025 if (ArgType->isIncompleteArrayType()) {
4026 assert(Arg && "expected a non-null arg expression");
4027 ArgType = S.getCompletedType(Arg);
4028 }
4029
4030 // C++1z [temp.deduct.call]p3:
4031 // If P is a forwarding reference and the argument is an lvalue, the type
4032 // "lvalue reference to A" is used in place of A for type deduction.
4033 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4034 ArgClassification.isLValue()) {
4035 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4036 ArgType = S.Context.getAddrSpaceQualType(
4038 ArgType = S.Context.getLValueReferenceType(ArgType);
4039 }
4040 } else {
4041 // C++ [temp.deduct.call]p2:
4042 // If P is not a reference type:
4043 // - If A is an array type, the pointer type produced by the
4044 // array-to-pointer standard conversion (4.2) is used in place of
4045 // A for type deduction; otherwise,
4046 // - If A is a function type, the pointer type produced by the
4047 // function-to-pointer standard conversion (4.3) is used in place
4048 // of A for type deduction; otherwise,
4049 if (ArgType->canDecayToPointerType())
4050 ArgType = S.Context.getDecayedType(ArgType);
4051 else {
4052 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4053 // type are ignored for type deduction.
4054 ArgType = ArgType.getUnqualifiedType();
4055 }
4056 }
4057
4058 // C++0x [temp.deduct.call]p4:
4059 // In general, the deduction process attempts to find template argument
4060 // values that will make the deduced A identical to A (after the type A
4061 // is transformed as described above). [...]
4063
4064 // - If the original P is a reference type, the deduced A (i.e., the
4065 // type referred to by the reference) can be more cv-qualified than
4066 // the transformed A.
4067 if (ParamRefType)
4069 // - The transformed A can be another pointer or pointer to member
4070 // type that can be converted to the deduced A via a qualification
4071 // conversion (4.4).
4072 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4073 ArgType->isObjCObjectPointerType())
4074 TDF |= TDF_IgnoreQualifiers;
4075 // - If P is a class and P has the form simple-template-id, then the
4076 // transformed A can be a derived class of the deduced A. Likewise,
4077 // if P is a pointer to a class of the form simple-template-id, the
4078 // transformed A can be a pointer to a derived class pointed to by
4079 // the deduced A.
4080 if (isSimpleTemplateIdType(ParamType) ||
4081 (isa<PointerType>(ParamType) &&
4083 ParamType->castAs<PointerType>()->getPointeeType())))
4084 TDF |= TDF_DerivedClass;
4085
4086 return false;
4087}
4088
4089static bool
4091 QualType T);
4092
4094 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4095 QualType ParamType, QualType ArgType,
4096 Expr::Classification ArgClassification, Expr *Arg,
4100 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4101 TemplateSpecCandidateSet *FailedTSC = nullptr);
4102
4103/// Attempt template argument deduction from an initializer list
4104/// deemed to be an argument in a function call.
4106 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4109 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4110 unsigned TDF) {
4111 // C++ [temp.deduct.call]p1: (CWG 1591)
4112 // If removing references and cv-qualifiers from P gives
4113 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4114 // a non-empty initializer list, then deduction is performed instead for
4115 // each element of the initializer list, taking P0 as a function template
4116 // parameter type and the initializer element as its argument
4117 //
4118 // We've already removed references and cv-qualifiers here.
4119 if (!ILE->getNumInits())
4121
4122 QualType ElTy;
4123 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4124 if (ArrTy)
4125 ElTy = ArrTy->getElementType();
4126 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4127 // Otherwise, an initializer list argument causes the parameter to be
4128 // considered a non-deduced context
4130 }
4131
4132 // Resolving a core issue: a braced-init-list containing any designators is
4133 // a non-deduced context.
4134 for (Expr *E : ILE->inits())
4135 if (isa<DesignatedInitExpr>(E))
4137
4138 // Deduction only needs to be done for dependent types.
4139 if (ElTy->isDependentType()) {
4140 for (Expr *E : ILE->inits()) {
4142 S, TemplateParams, 0, ElTy, E->getType(),
4143 E->Classify(S.getASTContext()), E, Info, Deduced,
4144 OriginalCallArgs, true, ArgIdx, TDF);
4146 return Result;
4147 }
4148 }
4149
4150 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4151 // from the length of the initializer list.
4152 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4153 // Determine the array bound is something we can deduce.
4154 if (const NonTypeTemplateParmDecl *NTTP =
4155 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
4156 // We can perform template argument deduction for the given non-type
4157 // template parameter.
4158 // C++ [temp.deduct.type]p13:
4159 // The type of N in the type T[N] is std::size_t.
4161 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
4163 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4164 /*ArrayBound=*/true, Info, Deduced);
4166 return Result;
4167 }
4168 }
4169
4171}
4172
4173/// Perform template argument deduction per [temp.deduct.call] for a
4174/// single parameter / argument pair.
4176 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4177 QualType ParamType, QualType ArgType,
4178 Expr::Classification ArgClassification, Expr *Arg,
4182 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4183 TemplateSpecCandidateSet *FailedTSC) {
4184
4185 QualType OrigParamType = ParamType;
4186
4187 // If P is a reference type [...]
4188 // If P is a cv-qualified type [...]
4190 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4191 ArgClassification, Arg, TDF, FailedTSC))
4193
4194 // If [...] the argument is a non-empty initializer list [...]
4195 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4196 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4197 Deduced, OriginalCallArgs, ArgIdx, TDF);
4198
4199 // [...] the deduction process attempts to find template argument values
4200 // that will make the deduced A identical to A
4201 //
4202 // Keep track of the argument type and corresponding parameter index,
4203 // so we can check for compatibility between the deduced A and A.
4204 if (Arg)
4205 OriginalCallArgs.push_back(
4206 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4207 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
4208 ArgType, Info, Deduced, TDF);
4209}
4210
4211/// Perform template argument deduction from a function call
4212/// (C++ [temp.deduct.call]).
4213///
4214/// \param FunctionTemplate the function template for which we are performing
4215/// template argument deduction.
4216///
4217/// \param ExplicitTemplateArgs the explicit template arguments provided
4218/// for this call.
4219///
4220/// \param Args the function call arguments
4221///
4222/// \param Specialization if template argument deduction was successful,
4223/// this will be set to the function template specialization produced by
4224/// template argument deduction.
4225///
4226/// \param Info the argument will be updated to provide additional information
4227/// about template argument deduction.
4228///
4229/// \param CheckNonDependent A callback to invoke to check conversions for
4230/// non-dependent parameters, between deduction and substitution, per DR1391.
4231/// If this returns true, substitution will be skipped and we return
4232/// TemplateDeductionResult::NonDependentConversionFailure. The callback is
4233/// passed the parameter types (after substituting explicit template arguments).
4234///
4235/// \returns the result of template argument deduction.
4237 FunctionTemplateDecl *FunctionTemplate,
4238 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4240 bool PartialOverloading, bool AggregateDeductionCandidate,
4241 QualType ObjectType, Expr::Classification ObjectClassification,
4242 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
4243 if (FunctionTemplate->isInvalidDecl())
4245
4246 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4247 unsigned NumParams = Function->getNumParams();
4248 bool HasExplicitObject = false;
4249 int ExplicitObjectOffset = 0;
4250 if (Function->hasCXXExplicitFunctionObjectParameter()) {
4251 HasExplicitObject = true;
4252 ExplicitObjectOffset = 1;
4253 }
4254
4255 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4256
4257 // C++ [temp.deduct.call]p1:
4258 // Template argument deduction is done by comparing each function template
4259 // parameter type (call it P) with the type of the corresponding argument
4260 // of the call (call it A) as described below.
4261 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4262 !PartialOverloading)
4264 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4265 PartialOverloading)) {
4266 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4267 if (Proto->isTemplateVariadic())
4268 /* Do nothing */;
4269 else if (!Proto->isVariadic())
4271 }
4272
4273 // The types of the parameters from which we will perform template argument
4274 // deduction.
4275 LocalInstantiationScope InstScope(*this);
4276 TemplateParameterList *TemplateParams
4277 = FunctionTemplate->getTemplateParameters();
4279 SmallVector<QualType, 8> ParamTypes;
4280 unsigned NumExplicitlySpecified = 0;
4281 if (ExplicitTemplateArgs) {
4284 Result = SubstituteExplicitTemplateArguments(
4285 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4286 Info);
4287 });
4289 return Result;
4290
4291 NumExplicitlySpecified = Deduced.size();
4292 } else {
4293 // Just fill in the parameter types from the function declaration.
4294 for (unsigned I = 0; I != NumParams; ++I)
4295 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4296 }
4297
4298 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4299
4300 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4301 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4302 bool ExplicitObjetArgument) {
4303 // C++ [demp.deduct.call]p1: (DR1391)
4304 // Template argument deduction is done by comparing each function template
4305 // parameter that contains template-parameters that participate in
4306 // template argument deduction ...
4307 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4309
4310 if (ExplicitObjetArgument) {
4311 // ... with the type of the corresponding argument
4313 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4314 ObjectClassification,
4315 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4316 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4317 }
4318
4319 // ... with the type of the corresponding argument
4321 *this, TemplateParams, FirstInnerIndex, ParamType,
4322 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4323 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4324 ArgIdx, /*TDF*/ 0);
4325 };
4326
4327 // Deduce template arguments from the function parameters.
4328 Deduced.resize(TemplateParams->size());
4329 SmallVector<QualType, 8> ParamTypesForArgChecking;
4330 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4331 ParamIdx != NumParamTypes; ++ParamIdx) {
4332 QualType ParamType = ParamTypes[ParamIdx];
4333
4334 const PackExpansionType *ParamExpansion =
4335 dyn_cast<PackExpansionType>(ParamType);
4336 if (!ParamExpansion) {
4337 // Simple case: matching a function parameter to a function argument.
4338 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4339 break;
4340
4341 ParamTypesForArgChecking.push_back(ParamType);
4342
4343 if (ParamIdx == 0 && HasExplicitObject) {
4344 if (auto Result = DeduceCallArgument(ParamType, 0,
4345 /*ExplicitObjetArgument=*/true);
4347 return Result;
4348 continue;
4349 }
4350
4351 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4352 /*ExplicitObjetArgument=*/false);
4354 return Result;
4355
4356 continue;
4357 }
4358
4359 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4360
4361 QualType ParamPattern = ParamExpansion->getPattern();
4362 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4363 ParamPattern,
4364 AggregateDeductionCandidate && IsTrailingPack);
4365
4366 // C++0x [temp.deduct.call]p1:
4367 // For a function parameter pack that occurs at the end of the
4368 // parameter-declaration-list, the type A of each remaining argument of
4369 // the call is compared with the type P of the declarator-id of the
4370 // function parameter pack. Each comparison deduces template arguments
4371 // for subsequent positions in the template parameter packs expanded by
4372 // the function parameter pack. When a function parameter pack appears
4373 // in a non-deduced context [not at the end of the list], the type of
4374 // that parameter pack is never deduced.
4375 //
4376 // FIXME: The above rule allows the size of the parameter pack to change
4377 // after we skip it (in the non-deduced case). That makes no sense, so
4378 // we instead notionally deduce the pack against N arguments, where N is
4379 // the length of the explicitly-specified pack if it's expanded by the
4380 // parameter pack and 0 otherwise, and we treat each deduction as a
4381 // non-deduced context.
4382 if (IsTrailingPack || PackScope.hasFixedArity()) {
4383 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4384 PackScope.nextPackElement(), ++ArgIdx) {
4385 ParamTypesForArgChecking.push_back(ParamPattern);
4386 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4387 /*ExplicitObjetArgument=*/false);
4389 return Result;
4390 }
4391 } else {
4392 // If the parameter type contains an explicitly-specified pack that we
4393 // could not expand, skip the number of parameters notionally created
4394 // by the expansion.
4395 std::optional<unsigned> NumExpansions =
4396 ParamExpansion->getNumExpansions();
4397 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4398 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4399 ++I, ++ArgIdx) {
4400 ParamTypesForArgChecking.push_back(ParamPattern);
4401 // FIXME: Should we add OriginalCallArgs for these? What if the
4402 // corresponding argument is a list?
4403 PackScope.nextPackElement();
4404 }
4405 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4406 PackScope.isDeducedFromEarlierParameter()) {
4407 // [temp.deduct.general#3]
4408 // When all template arguments have been deduced
4409 // or obtained from default template arguments, all uses of template
4410 // parameters in the template parameter list of the template are
4411 // replaced with the corresponding deduced or default argument values
4412 //
4413 // If we have a trailing parameter pack, that has been deduced
4414 // previously we substitute the pack here in a similar fashion as
4415 // above with the trailing parameter packs. The main difference here is
4416 // that, in this case we are not processing all of the remaining
4417 // arguments. We are only process as many arguments as we have in
4418 // the already deduced parameter.
4419 std::optional<unsigned> ArgPosAfterSubstitution =
4420 PackScope.getSavedPackSizeIfAllEqual();
4421 if (!ArgPosAfterSubstitution)
4422 continue;
4423
4424 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4425 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4426 ParamTypesForArgChecking.push_back(ParamPattern);
4427 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4428 /*ExplicitObjetArgument=*/false);
4430 return Result;
4431
4432 PackScope.nextPackElement();
4433 }
4434 }
4435 }
4436
4437 // Build argument packs for each of the parameter packs expanded by this
4438 // pack expansion.
4439 if (auto Result = PackScope.finish();
4441 return Result;
4442 }
4443
4444 // Capture the context in which the function call is made. This is the context
4445 // that is needed when the accessibility of template arguments is checked.
4446 DeclContext *CallingCtx = CurContext;
4447
4450 Result = FinishTemplateArgumentDeduction(
4451 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4452 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
4453 ContextRAII SavedContext(*this, CallingCtx);
4454 return CheckNonDependent(ParamTypesForArgChecking);
4455 });
4456 });
4457 return Result;
4458}
4459
4462 bool AdjustExceptionSpec) {
4463 if (ArgFunctionType.isNull())
4464 return ArgFunctionType;
4465
4466 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4467 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4468 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4469 bool Rebuild = false;
4470
4471 CallingConv CC = FunctionTypeP->getCallConv();
4472 if (EPI.ExtInfo.getCC() != CC) {
4473 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4474 Rebuild = true;
4475 }
4476
4477 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4478 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4479 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4480 Rebuild = true;
4481 }
4482
4483 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4484 ArgFunctionTypeP->hasExceptionSpec())) {
4485 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4486 Rebuild = true;
4487 }
4488
4489 if (!Rebuild)
4490 return ArgFunctionType;
4491
4492 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4493 ArgFunctionTypeP->getParamTypes(), EPI);
4494}
4495
4496/// Deduce template arguments when taking the address of a function
4497/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
4498/// a template.
4499///
4500/// \param FunctionTemplate the function template for which we are performing
4501/// template argument deduction.
4502///
4503/// \param ExplicitTemplateArgs the explicitly-specified template
4504/// arguments.
4505///
4506/// \param ArgFunctionType the function type that will be used as the
4507/// "argument" type (A) when performing template argument deduction from the
4508/// function template's function type. This type may be NULL, if there is no
4509/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
4510///
4511/// \param Specialization if template argument deduction was successful,
4512/// this will be set to the function template specialization produced by
4513/// template argument deduction.
4514///
4515/// \param Info the argument will be updated to provide additional information
4516/// about template argument deduction.
4517///
4518/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4519/// the address of a function template per [temp.deduct.funcaddr] and
4520/// [over.over]. If \c false, we are looking up a function template
4521/// specialization based on its signature, per [temp.deduct.decl].
4522///
4523/// \returns the result of template argument deduction.
4525 FunctionTemplateDecl *FunctionTemplate,
4526 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4528 bool IsAddressOfFunction) {
4529 if (FunctionTemplate->isInvalidDecl())
4531
4532 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4533 TemplateParameterList *TemplateParams
4534 = FunctionTemplate->getTemplateParameters();
4535 QualType FunctionType = Function->getType();
4536
4537 // Substitute any explicit template arguments.
4538 LocalInstantiationScope InstScope(*this);
4540 unsigned NumExplicitlySpecified = 0;
4541 SmallVector<QualType, 4> ParamTypes;
4542 if (ExplicitTemplateArgs) {
4545 Result = SubstituteExplicitTemplateArguments(
4546 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4547 &FunctionType, Info);
4548 });
4550 return Result;
4551
4552 NumExplicitlySpecified = Deduced.size();
4553 }
4554
4555 // When taking the address of a function, we require convertibility of
4556 // the resulting function type. Otherwise, we allow arbitrary mismatches
4557 // of calling convention and noreturn.
4558 if (!IsAddressOfFunction)
4559 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4560 /*AdjustExceptionSpec*/false);
4561
4562 // Unevaluated SFINAE context.
4565 SFINAETrap Trap(*this);
4566
4567 Deduced.resize(TemplateParams->size());
4568
4569 // If the function has a deduced return type, substitute it for a dependent
4570 // type so that we treat it as a non-deduced context in what follows.
4571 bool HasDeducedReturnType = false;
4572 if (getLangOpts().CPlusPlus14 &&
4573 Function->getReturnType()->getContainedAutoType()) {
4575 HasDeducedReturnType = true;
4576 }
4577
4578 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4579 unsigned TDF =
4581 // Deduce template arguments from the function type.
4583 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4584 TDF);
4586 return Result;
4587 }
4588
4591 Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4592 NumExplicitlySpecified,
4593 Specialization, Info);
4594 });
4596 return Result;
4597
4598 // If the function has a deduced return type, deduce it now, so we can check
4599 // that the deduced function type matches the requested type.
4600 if (HasDeducedReturnType && IsAddressOfFunction &&
4601 Specialization->getReturnType()->isUndeducedType() &&
4604
4605 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4606 Specialization->isImmediateEscalating() &&
4608 Info.getLocation()))
4610
4611 auto *SpecializationFPT =
4612 Specialization->getType()->castAs<FunctionProtoType>();
4613 if (IsAddressOfFunction && getLangOpts().CPlusPlus17 &&
4614 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
4615 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
4617
4618 // Adjust the exception specification of the argument to match the
4619 // substituted and resolved type we just formed. (Calling convention and
4620 // noreturn can't be dependent, so we don't actually need this for them
4621 // right now.)
4622 QualType SpecializationType = Specialization->getType();
4623 if (!IsAddressOfFunction) {
4624 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4625 /*AdjustExceptionSpec*/true);
4626
4627 // Revert placeholder types in the return type back to undeduced types so
4628 // that the comparison below compares the declared return types.
4629 if (HasDeducedReturnType) {
4630 SpecializationType = SubstAutoType(SpecializationType, QualType());
4631 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4632 }
4633 }
4634
4635 // If the requested function type does not match the actual type of the
4636 // specialization with respect to arguments of compatible pointer to function
4637 // types, template argument deduction fails.
4638 if (!ArgFunctionType.isNull()) {
4639 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4640 Context.getCanonicalType(SpecializationType),
4641 Context.getCanonicalType(ArgFunctionType))
4643 SpecializationType, ArgFunctionType)) {
4644 Info.FirstArg = TemplateArgument(SpecializationType);
4645 Info.SecondArg = TemplateArgument(ArgFunctionType);
4647 }
4648 }
4649
4651}
4652
4653/// Deduce template arguments for a templated conversion
4654/// function (C++ [temp.deduct.conv]) and, if successful, produce a
4655/// conversion function template specialization.
4657 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4658 Expr::Classification ObjectClassification, QualType ToType,
4660 if (ConversionTemplate->isInvalidDecl())
4662
4663 CXXConversionDecl *ConversionGeneric
4664 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4665
4666 QualType FromType = ConversionGeneric->getConversionType();
4667
4668 // Canonicalize the types for deduction.
4669 QualType P = Context.getCanonicalType(FromType);
4670 QualType A = Context.getCanonicalType(ToType);
4671
4672 // C++0x [temp.deduct.conv]p2:
4673 // If P is a reference type, the type referred to by P is used for
4674 // type deduction.
4675 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4676 P = PRef->getPointeeType();
4677
4678 // C++0x [temp.deduct.conv]p4:
4679 // [...] If A is a reference type, the type referred to by A is used
4680 // for type deduction.
4681 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4682 A = ARef->getPointeeType();
4683 // We work around a defect in the standard here: cv-qualifiers are also
4684 // removed from P and A in this case, unless P was a reference type. This
4685 // seems to mostly match what other compilers are doing.
4686 if (!FromType->getAs<ReferenceType>()) {
4687 A = A.getUnqualifiedType();
4688 P = P.getUnqualifiedType();
4689 }
4690
4691 // C++ [temp.deduct.conv]p3:
4692 //
4693 // If A is not a reference type:
4694 } else {
4695 assert(!A->isReferenceType() && "Reference types were handled above");
4696
4697 // - If P is an array type, the pointer type produced by the
4698 // array-to-pointer standard conversion (4.2) is used in place
4699 // of P for type deduction; otherwise,
4700 if (P->isArrayType())
4702 // - If P is a function type, the pointer type produced by the
4703 // function-to-pointer standard conversion (4.3) is used in
4704 // place of P for type deduction; otherwise,
4705 else if (P->isFunctionType())
4707 // - If P is a cv-qualified type, the top level cv-qualifiers of
4708 // P's type are ignored for type deduction.
4709 else
4710 P = P.getUnqualifiedType();
4711
4712 // C++0x [temp.deduct.conv]p4:
4713 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4714 // type are ignored for type deduction. If A is a reference type, the type
4715 // referred to by A is used for type deduction.
4716 A = A.getUnqualifiedType();
4717 }
4718
4719 // Unevaluated SFINAE context.
4722 SFINAETrap Trap(*this);
4723
4724 // C++ [temp.deduct.conv]p1:
4725 // Template argument deduction is done by comparing the return
4726 // type of the template conversion function (call it P) with the
4727 // type that is required as the result of the conversion (call it
4728 // A) as described in 14.8.2.4.
4729 TemplateParameterList *TemplateParams
4730 = ConversionTemplate->getTemplateParameters();
4732 Deduced.resize(TemplateParams->size());
4733
4734 // C++0x [temp.deduct.conv]p4:
4735 // In general, the deduction process attempts to find template
4736 // argument values that will make the deduced A identical to
4737 // A. However, there are two cases that allow a difference:
4738 unsigned TDF = 0;
4739 // - If the original A is a reference type, A can be more
4740 // cv-qualified than the deduced A (i.e., the type referred to
4741 // by the reference)
4742 if (ToType->isReferenceType())
4744 // - The deduced A can be another pointer or pointer to member
4745 // type that can be converted to A via a qualification
4746 // conversion.
4747 //
4748 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4749 // both P and A are pointers or member pointers. In this case, we
4750 // just ignore cv-qualifiers completely).
4751 if ((P->isPointerType() && A->isPointerType()) ||
4752 (P->isMemberPointerType() && A->isMemberPointerType()))
4753 TDF |= TDF_IgnoreQualifiers;
4754
4756 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
4757 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
4760 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
4761 ParamType, ObjectType, ObjectClassification,
4762 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4763 /*Decomposed*/ false, 0, /*TDF*/ 0);
4765 return Result;
4766 }
4767
4769 *this, TemplateParams, P, A, Info, Deduced, TDF);
4771 return Result;
4772
4773 // Create an Instantiation Scope for finalizing the operator.
4774 LocalInstantiationScope InstScope(*this);
4775 // Finish template argument deduction.
4776 FunctionDecl *ConversionSpecialized = nullptr;
4779 Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4780 ConversionSpecialized, Info,
4781 &OriginalCallArgs);
4782 });
4783 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4784 return Result;
4785}
4786
4787/// Deduce template arguments for a function template when there is
4788/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4789///
4790/// \param FunctionTemplate the function template for which we are performing
4791/// template argument deduction.
4792///
4793/// \param ExplicitTemplateArgs the explicitly-specified template
4794/// arguments.
4795///
4796/// \param Specialization if template argument deduction was successful,
4797/// this will be set to the function template specialization produced by
4798/// template argument deduction.
4799///
4800/// \param Info the argument will be updated to provide additional information
4801/// about template argument deduction.
4802///
4803/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4804/// the address of a function template in a context where we do not have a
4805/// target type, per [over.over]. If \c false, we are looking up a function
4806/// template specialization based on its signature, which only happens when
4807/// deducing a function parameter type from an argument that is a template-id
4808/// naming a function template specialization.
4809///
4810/// \returns the result of template argument deduction.
4813 TemplateArgumentListInfo *ExplicitTemplateArgs,
4816 bool IsAddressOfFunction) {
4817 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4818 QualType(), Specialization, Info,
4819 IsAddressOfFunction);
4820}
4821
4822namespace {
4823 struct DependentAuto { bool IsPack; };
4824
4825 /// Substitute the 'auto' specifier or deduced template specialization type
4826 /// specifier within a type for a given replacement type.
4827 class SubstituteDeducedTypeTransform :
4828 public TreeTransform<SubstituteDeducedTypeTransform> {
4829 QualType Replacement;
4830 bool ReplacementIsPack;
4831 bool UseTypeSugar;
4833
4834 public:
4835 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
4836 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4837 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
4838
4839 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4840 bool UseTypeSugar = true)
4841 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4842 Replacement(Replacement), ReplacementIsPack(false),
4843 UseTypeSugar(UseTypeSugar) {}
4844
4845 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4846 assert(isa<TemplateTypeParmType>(Replacement) &&
4847 "unexpected unsugared replacement kind");
4848 QualType Result = Replacement;
4850 NewTL.setNameLoc(TL.getNameLoc());
4851 return Result;
4852 }
4853
4854 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4855 // If we're building the type pattern to deduce against, don't wrap the
4856 // substituted type in an AutoType. Certain template deduction rules
4857 // apply only when a template type parameter appears directly (and not if
4858 // the parameter is found through desugaring). For instance:
4859 // auto &&lref = lvalue;
4860 // must transform into "rvalue reference to T" not "rvalue reference to
4861 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
4862 //
4863 // FIXME: Is this still necessary?
4864 if (!UseTypeSugar)
4865 return TransformDesugared(TLB, TL);
4866
4867 QualType Result = SemaRef.Context.getAutoType(
4868 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
4869 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
4871 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4872 NewTL.copy(TL);
4873 return Result;
4874 }
4875
4876 QualType TransformDeducedTemplateSpecializationType(
4878 if (!UseTypeSugar)
4879 return TransformDesugared(TLB, TL);
4880
4881 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4883 Replacement, Replacement.isNull());
4884 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4885 NewTL.setNameLoc(TL.getNameLoc());
4886 return Result;
4887 }
4888
4889 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4890 // Lambdas never need to be transformed.
4891 return E;
4892 }
4893 bool TransformExceptionSpec(SourceLocation Loc,
4895 SmallVectorImpl<QualType> &Exceptions,
4896 bool &Changed) {
4897 if (ESI.Type == EST_Uninstantiated) {
4898 ESI.instantiate();
4899 Changed = true;
4900 }
4901 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
4902 }
4903
4904 QualType Apply(TypeLoc TL) {
4905 // Create some scratch storage for the transformed type locations.
4906 // FIXME: We're just going to throw this information away. Don't build it.
4907 TypeLocBuilder TLB;
4908 TLB.reserve(TL.getFullDataSize());
4909 return TransformType(TLB, TL);
4910 }
4911 };
4912
4913} // namespace
4914
4917 QualType Deduced) {
4918 ConstraintSatisfaction Satisfaction;
4919 ConceptDecl *Concept = Type.getTypeConstraintConcept();
4920 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
4921 TypeLoc.getRAngleLoc());
4922 TemplateArgs.addArgument(
4925 Deduced, TypeLoc.getNameLoc())));
4926 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
4927 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
4928
4929 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4930 if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs,
4931 /*PartialTemplateArgs=*/false,
4932 SugaredConverted, CanonicalConverted))
4933 return true;
4934 MultiLevelTemplateArgumentList MLTAL(Concept, CanonicalConverted,
4935 /*Final=*/false);
4936 if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
4938 Satisfaction))
4939 return true;
4940 if (!Satisfaction.IsSatisfied) {
4941 std::string Buf;
4942 llvm::raw_string_ostream OS(Buf);
4943 OS << "'" << Concept->getName();
4944 if (TypeLoc.hasExplicitTemplateArgs()) {
4946 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
4947 Type.getTypeConstraintConcept()->getTemplateParameters());
4948 }
4949 OS << "'";
4950 OS.flush();
4951 S.Diag(TypeLoc.getConceptNameLoc(),
4952 diag::err_placeholder_constraints_not_satisfied)
4953 << Deduced << Buf << TypeLoc.getLocalSourceRange();
4954 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
4955 return true;
4956 }
4957 return false;
4958}
4959
4960/// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
4961///
4962/// Note that this is done even if the initializer is dependent. (This is
4963/// necessary to support partial ordering of templates using 'auto'.)
4964/// A dependent type will be produced when deducing from a dependent type.
4965///
4966/// \param Type the type pattern using the auto type-specifier.
4967/// \param Init the initializer for the variable whose type is to be deduced.
4968/// \param Result if type deduction was successful, this will be set to the
4969/// deduced type.
4970/// \param Info the argument will be updated to provide additional information
4971/// about template argument deduction.
4972/// \param DependentDeduction Set if we should permit deduction in
4973/// dependent cases. This is necessary for template partial ordering with
4974/// 'auto' template parameters. The template parameter depth to be used
4975/// should be specified in the 'Info' parameter.
4976/// \param IgnoreConstraints Set if we should not fail if the deduced type does
4977/// not satisfy the type-constraint in the auto type.
4980 TemplateDeductionInfo &Info, bool DependentDeduction,
4981 bool IgnoreConstraints,
4982 TemplateSpecCandidateSet *FailedTSC) {
4983 assert(DependentDeduction || Info.getDeducedDepth() == 0);
4984 if (Init->containsErrors())
4986
4987 const AutoType *AT = Type.getType()->getContainedAutoType();
4988 assert(AT);
4989
4990 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
4991 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4992 if (NonPlaceholder.isInvalid())
4994 Init = NonPlaceholder.get();
4995 }
4996
4997 DependentAuto DependentResult = {
4998 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
4999
5000 if (!DependentDeduction &&
5001 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5002 Init->containsUnexpandedParameterPack())) {
5003 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5004 assert(!Result.isNull() && "substituting DependentTy can't fail");
5006 }
5007
5008 // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode.
5009 auto *String = dyn_cast<StringLiteral>(Init);
5010 if (getLangOpts().C23 && String && Type.getType()->isArrayType()) {
5011 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5012 TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData());
5013 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL);
5014 assert(!Result.isNull() && "substituting DependentTy can't fail");
5016 }
5017
5018 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5019 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5020 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5021 }
5022
5023 auto *InitList = dyn_cast<InitListExpr>(Init);
5024 if (!getLangOpts().CPlusPlus && InitList) {
5025 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5026 << (int)AT->getKeyword() << getLangOpts().C23;
5028 }
5029
5030 // Deduce type of TemplParam in Func(Init)
5032 Deduced.resize(1);
5033
5034 // If deduction failed, don't diagnose if the initializer is dependent; it
5035 // might acquire a matching type in the instantiation.
5036 auto DeductionFailed = [&](TemplateDeductionResult TDK) {
5037 if (Init->isTypeDependent()) {
5038 Result =
5039 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5040 assert(!Result.isNull() && "substituting DependentTy can't fail");
5042 }
5043 return TDK;
5044 };
5045
5046 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5047
5049 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5050 if (AT->isDecltypeAuto()) {
5051 if (InitList) {
5052 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5054 }
5055
5057 assert(!DeducedType.isNull());
5058 } else {
5059 LocalInstantiationScope InstScope(*this);
5060
5061 // Build template<class TemplParam> void Func(FuncParam);
5062 SourceLocation Loc = Init->getExprLoc();
5064 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5065 nullptr, false, false, false);
5066 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5067 NamedDecl *TemplParamPtr = TemplParam;
5069 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5070
5071 if (InitList) {
5072 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5073 // deduce against that. Such deduction only succeeds if removing
5074 // cv-qualifiers and references results in std::initializer_list<T>.
5075 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5077
5078 SourceRange DeducedFromInitRange;
5079 for (Expr *Init : InitList->inits()) {
5080 // Resolving a core issue: a braced-init-list containing any designators
5081 // is a non-deduced context.
5082 if (isa<DesignatedInitExpr>(Init))
5085 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5086 Init->Classify(getASTContext()), Init, Info, Deduced,
5087 OriginalCallArgs, /*Decomposed=*/true,
5088 /*ArgIdx=*/0, /*TDF=*/0);
5091 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5092 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5093 << Init->getSourceRange();
5094 return DeductionFailed(TemplateDeductionResult::AlreadyDiagnosed);
5095 }
5096 return DeductionFailed(TDK);
5097 }
5098
5099 if (DeducedFromInitRange.isInvalid() &&
5100 Deduced[0].getKind() != TemplateArgument::Null)
5101 DeducedFromInitRange = Init->getSourceRange();
5102 }
5103 } else {
5104 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5105 Diag(Loc, diag::err_auto_bitfield);
5107 }
5108 QualType FuncParam =
5109 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5110 assert(!FuncParam.isNull() &&
5111 "substituting template parameter for 'auto' failed");
5113 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5114 Init->Classify(getASTContext()), Init, Info, Deduced,
5115 OriginalCallArgs, /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0,
5116 FailedTSC);
5118 return DeductionFailed(TDK);
5119 }
5120
5121 // Could be null if somehow 'auto' appears in a non-deduced context.
5122 if (Deduced[0].getKind() != TemplateArgument::Type)
5123 return DeductionFailed(TemplateDeductionResult::Incomplete);
5124 DeducedType = Deduced[0].getAsType();
5125
5126 if (InitList) {
5128 if (DeducedType.isNull())
5130 }
5131 }
5132
5133 if (!Result.isNull()) {
5135 Info.FirstArg = Result;
5136 Info.SecondArg = DeducedType;
5137 return DeductionFailed(TemplateDeductionResult::Inconsistent);
5138 }
5140 }
5141
5142 if (AT->isConstrained() && !IgnoreConstraints &&
5144 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5146
5147 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5148 if (Result.isNull())
5150
5151 // Check that the deduced argument type is compatible with the original
5152 // argument type per C++ [temp.deduct.call]p4.
5153 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5154 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5155 assert((bool)InitList == OriginalArg.DecomposedParam &&
5156 "decomposed non-init-list in auto deduction?");
5157 if (auto TDK =
5158 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5160 Result = QualType();
5161 return DeductionFailed(TDK);
5162 }
5163 }
5164
5166}
5167
5169 QualType TypeToReplaceAuto) {
5170 assert(TypeToReplaceAuto != Context.DependentTy);
5171 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5172 .TransformType(TypeWithAuto);
5173}
5174
5176 QualType TypeToReplaceAuto) {
5177 assert(TypeToReplaceAuto != Context.DependentTy);
5178 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5179 .TransformType(TypeWithAuto);
5180}
5181
5183 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5184 .TransformType(TypeWithAuto);
5185}
5186
5189 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5190 .TransformType(TypeWithAuto);
5191}
5192
5194 QualType TypeToReplaceAuto) {
5195 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5196 /*UseTypeSugar*/ false)
5197 .TransformType(TypeWithAuto);
5198}
5199
5201 QualType TypeToReplaceAuto) {
5202 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5203 /*UseTypeSugar*/ false)
5204 .TransformType(TypeWithAuto);
5205}
5206
5208 if (isa<InitListExpr>(Init))
5209 Diag(VDecl->getLocation(),
5210 VDecl->isInitCapture()
5211 ? diag::err_init_capture_deduction_failure_from_init_list
5212 : diag::err_auto_var_deduction_failure_from_init_list)
5213 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5214 else
5215 Diag(VDecl->getLocation(),
5216 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5217 : diag::err_auto_var_deduction_failure)
5218 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5219 << Init->getSourceRange();
5220}
5221
5223 bool Diagnose) {
5224 assert(FD->getReturnType()->isUndeducedType());
5225
5226 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5227 // within the return type from the call operator's type.
5229 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5230 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5231
5232 // For a generic lambda, instantiate the call operator if needed.
5233 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5235 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5236 if (!CallOp || CallOp->isInvalidDecl())
5237 return true;
5238
5239 // We might need to deduce the return type by instantiating the definition
5240 // of the operator() function.
5241 if (CallOp->getReturnType()->isUndeducedType()) {
5243 InstantiateFunctionDefinition(Loc, CallOp);
5244 });
5245 }
5246 }
5247
5248 if (CallOp->isInvalidDecl())
5249 return true;
5250 assert(!CallOp->getReturnType()->isUndeducedType() &&
5251 "failed to deduce lambda return type");
5252
5253 // Build the new return type from scratch.
5254 CallingConv RetTyCC = FD->getReturnType()
5255 ->getPointeeType()
5256 ->castAs<FunctionType>()
5257 ->getCallConv();
5259 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5260 if (FD->getReturnType()->getAs<PointerType>())
5261 RetType = Context.getPointerType(RetType);
5262 else {
5263 assert(FD->getReturnType()->getAs<BlockPointerType>());
5264 RetType = Context.getBlockPointerType(RetType);
5265 }
5267 return false;
5268 }
5269
5273 });
5274 }
5275
5276 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5277 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5278 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5279 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5280 }
5281
5282 return StillUndeduced;
5283}
5284
5286 SourceLocation Loc) {
5287 assert(FD->isImmediateEscalating());
5288
5290 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5291 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5292
5293 // For a generic lambda, instantiate the call operator if needed.
5294 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5296 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5297 if (!CallOp || CallOp->isInvalidDecl())
5298 return true;
5300 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5301 }
5302 return CallOp->isInvalidDecl();
5303 }
5304
5307 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5308 }
5309 return false;
5310}
5311
5313 const CXXMethodDecl *Method,
5314 QualType RawType,
5315 bool IsOtherRvr) {
5316 // C++20 [temp.func.order]p3.1, p3.2:
5317 // - The type X(M) is "rvalue reference to cv A" if the optional
5318 // ref-qualifier of M is && or if M has no ref-qualifier and the
5319 // positionally-corresponding parameter of the other transformed template
5320 // has rvalue reference type; if this determination depends recursively
5321 // upon whether X(M) is an rvalue reference type, it is not considered to
5322 // have rvalue reference type.
5323 //
5324 // - Otherwise, X(M) is "lvalue reference to cv A".
5325 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5326 "expected a member function with no explicit object parameter");
5327
5328 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5329 if (Method->getRefQualifier() == RQ_RValue ||
5330 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5331 return Context.getRValueReferenceType(RawType);
5332 return Context.getLValueReferenceType(RawType);
5333}
5334
5335/// Determine whether the function template \p FT1 is at least as
5336/// specialized as \p FT2.
5338 const FunctionTemplateDecl *FT1,
5339 const FunctionTemplateDecl *FT2,
5341 bool Reversed,
5342 const SmallVector<QualType> &Args1,
5343 const SmallVector<QualType> &Args2) {
5344 assert(!Reversed || TPOC == TPOC_Call);
5345
5346 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5347 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5348 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5349 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5350
5351 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5352 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5354 Deduced.resize(TemplateParams->size());
5355
5356 // C++0x [temp.deduct.partial]p3:
5357 // The types used to determine the ordering depend on the context in which
5358 // the partial ordering is done:
5359 TemplateDeductionInfo Info(Loc);
5360 switch (TPOC) {
5361 case TPOC_Call:
5362 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
5363 Args1.data(), Args1.size(), Info, Deduced,
5364 TDF_None, /*PartialOrdering=*/true) !=
5366 return false;
5367
5368 break;
5369
5370 case TPOC_Conversion:
5371 // - In the context of a call to a conversion operator, the return types
5372 // of the conversion function templates are used.
5374 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5375 Info, Deduced, TDF_None,
5376 /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
5377 return false;
5378 break;
5379
5380 case TPOC_Other:
5381 // - In other contexts (14.6.6.2) the function template's function type
5382 // is used.
5384 S, TemplateParams, FD2->getType(), FD1->getType(), Info, Deduced,
5385 TDF_None,
5386 /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
5387 return false;
5388 break;
5389 }
5390
5391 // C++0x [temp.deduct.partial]p11:
5392 // In most cases, all template parameters must have values in order for
5393 // deduction to succeed, but for partial ordering purposes a template
5394 // parameter may remain without a value provided it is not used in the
5395 // types being used for partial ordering. [ Note: a template parameter used
5396 // in a non-deduced context is considered used. -end note]
5397 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5398 for (; ArgIdx != NumArgs; ++ArgIdx)
5399 if (Deduced[ArgIdx].isNull())
5400 break;
5401
5402 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
5403 // to substitute the deduced arguments back into the template and check that
5404 // we get the right type.
5405
5406 if (ArgIdx == NumArgs) {
5407 // All template arguments were deduced. FT1 is at least as specialized
5408 // as FT2.
5409 return true;
5410 }
5411
5412 // Figure out which template parameters were used.
5413 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5414 switch (TPOC) {
5415 case TPOC_Call:
5416 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5417 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
5418 TemplateParams->getDepth(),
5419 UsedParameters);
5420 break;
5421
5422 case TPOC_Conversion:
5423 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
5424 TemplateParams->getDepth(), UsedParameters);
5425 break;
5426
5427 case TPOC_Other:
5429 TemplateParams->getDepth(),
5430 UsedParameters);
5431 break;
5432 }
5433
5434 for (; ArgIdx != NumArgs; ++ArgIdx)
5435 // If this argument had no value deduced but was used in one of the types
5436 // used for partial ordering, then deduction fails.
5437 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5438 return false;
5439
5440 return true;
5441}
5442
5443/// Returns the more specialized function template according
5444/// to the rules of function template partial ordering (C++ [temp.func.order]).
5445///
5446/// \param FT1 the first function template
5447///
5448/// \param FT2 the second function template
5449///
5450/// \param TPOC the context in which we are performing partial ordering of
5451/// function templates.
5452///
5453/// \param NumCallArguments1 The number of arguments in the call to FT1, used
5454/// only when \c TPOC is \c TPOC_Call.
5455///
5456/// \param RawObj1Ty The type of the object parameter of FT1 if a member
5457/// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
5458/// template from a member function
5459///
5460/// \param RawObj2Ty The type of the object parameter of FT2 if a member
5461/// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
5462/// template from a member function
5463///
5464/// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
5465/// candidate with a reversed parameter order. In this case, the corresponding
5466/// P/A pairs between FT1 and FT2 are reversed.
5467///
5468/// \returns the more specialized function template. If neither
5469/// template is more specialized, returns NULL.
5472 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5473 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed) {
5476 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5477 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5478 bool ShouldConvert1 = false;
5479 bool ShouldConvert2 = false;
5480 QualType Obj1Ty;
5481 QualType Obj2Ty;
5482 if (TPOC == TPOC_Call) {
5483 const FunctionProtoType *Proto1 =
5484 FD1->getType()->castAs<FunctionProtoType>();
5485 const FunctionProtoType *Proto2 =
5486 FD2->getType()->castAs<FunctionProtoType>();
5487
5488 // - In the context of a function call, the function parameter types are
5489 // used.
5490 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5491 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5492 // C++20 [temp.func.order]p3
5493 // [...] Each function template M that is a member function is
5494 // considered to have a new first parameter of type
5495 // X(M), described below, inserted in its function parameter list.
5496 //
5497 // Note that we interpret "that is a member function" as
5498 // "that is a member function with no expicit object argument".
5499 // Otherwise the ordering rules for methods with expicit objet arguments
5500 // against anything else make no sense.
5501 ShouldConvert1 = Method1 && !Method1->isExplicitObjectMemberFunction();
5502 ShouldConvert2 = Method2 && !Method2->isExplicitObjectMemberFunction();
5503 if (ShouldConvert1) {
5504 bool IsRValRef2 =
5505 ShouldConvert2
5506 ? Method2->getRefQualifier() == RQ_RValue
5507 : Proto2->param_type_begin()[0]->isRValueReferenceType();
5508 // Compare 'this' from Method1 against first parameter from Method2.
5509 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1, RawObj1Ty,
5510 IsRValRef2);
5511 Args1.push_back(Obj1Ty);
5512 }
5513 if (ShouldConvert2) {
5514 bool IsRValRef1 =
5515 ShouldConvert1
5516 ? Method1->getRefQualifier() == RQ_RValue
5517 : Proto1->param_type_begin()[0]->isRValueReferenceType();
5518 // Compare 'this' from Method2 against first parameter from Method1.
5519 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2, RawObj2Ty,
5520 IsRValRef1);
5521 Args2.push_back(Obj2Ty);
5522 }
5523 size_t NumComparedArguments = NumCallArguments1 + ShouldConvert1;
5524
5525 Args1.insert(Args1.end(), Proto1->param_type_begin(),
5526 Proto1->param_type_end());
5527 Args2.insert(Args2.end(), Proto2->param_type_begin(),
5528 Proto2->param_type_end());
5529
5530 // C++ [temp.func.order]p5:
5531 // The presence of unused ellipsis and default arguments has no effect on
5532 // the partial ordering of function templates.
5533 Args1.resize(std::min(Args1.size(), NumComparedArguments));
5534 Args2.resize(std::min(Args2.size(), NumComparedArguments));
5535
5536 if (Reversed)
5537 std::reverse(Args2.begin(), Args2.end());
5538 }
5539 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Reversed,
5540 Args1, Args2);
5541 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Reversed,
5542 Args2, Args1);
5543 // C++ [temp.deduct.partial]p10:
5544 // F is more specialized than G if F is at least as specialized as G and G
5545 // is not at least as specialized as F.
5546 if (Better1 != Better2) // We have a clear winner
5547 return Better1 ? FT1 : FT2;
5548
5549 if (!Better1 && !Better2) // Neither is better than the other
5550 return nullptr;
5551
5552 // C++ [temp.deduct.partial]p11:
5553 // ... and if G has a trailing function parameter pack for which F does not
5554 // have a corresponding parameter, and if F does not have a trailing
5555 // function parameter pack, then F is more specialized than G.
5556
5557 SmallVector<QualType> Param1;
5558 Param1.reserve(FD1->param_size() + ShouldConvert1);
5559 if (ShouldConvert1)
5560 Param1.push_back(Obj1Ty);
5561 for (const auto &P : FD1->parameters())
5562 Param1.push_back(P->getType());
5563
5564 SmallVector<QualType> Param2;
5565 Param2.reserve(FD2->param_size() + ShouldConvert2);
5566 if (ShouldConvert2)
5567 Param2.push_back(Obj2Ty);
5568 for (const auto &P : FD2->parameters())
5569 Param2.push_back(P->getType());
5570
5571 unsigned NumParams1 = Param1.size();
5572 unsigned NumParams2 = Param2.size();
5573
5574 bool Variadic1 =
5575 FD1->param_size() && FD1->parameters().back()->isParameterPack();
5576 bool Variadic2 =
5577 FD2->param_size() && FD2->parameters().back()->isParameterPack();
5578 if (Variadic1 != Variadic2) {
5579 if (Variadic1 && NumParams1 > NumParams2)
5580 return FT2;
5581 if (Variadic2 && NumParams2 > NumParams1)
5582 return FT1;
5583 }
5584
5585 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5586 // there is no wording or even resolution for this issue.
5587 for (int i = 0, e = std::min(NumParams1, NumParams2); i < e; ++i) {
5588 QualType T1 = Param1[i].getCanonicalType();
5589 QualType T2 = Param2[i].getCanonicalType();
5590 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
5591 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
5592 if (!TST1 || !TST2)
5593 continue;
5594 const TemplateArgument &TA1 = TST1->template_arguments().back();
5595 if (TA1.getKind() == TemplateArgument::Pack) {
5596 assert(TST1->template_arguments().size() ==
5597 TST2->template_arguments().size());
5598 const TemplateArgument &TA2 = TST2->template_arguments().back();
5599 assert(TA2.getKind() == TemplateArgument::Pack);
5600 unsigned PackSize1 = TA1.pack_size();
5601 unsigned PackSize2 = TA2.pack_size();
5602 bool IsPackExpansion1 =
5603 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5604 bool IsPackExpansion2 =
5605 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5606 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
5607 if (PackSize1 > PackSize2 && IsPackExpansion1)
5608 return FT2;
5609 if (PackSize1 < PackSize2 && IsPackExpansion2)
5610 return FT1;
5611 }
5612 }
5613 }
5614
5615 if (!Context.getLangOpts().CPlusPlus20)
5616 return nullptr;
5617
5618 // Match GCC on not implementing [temp.func.order]p6.2.1.
5619
5620 // C++20 [temp.func.order]p6:
5621 // If deduction against the other template succeeds for both transformed
5622 // templates, constraints can be considered as follows:
5623
5624 // C++20 [temp.func.order]p6.1:
5625 // If their template-parameter-lists (possibly including template-parameters
5626 // invented for an abbreviated function template ([dcl.fct])) or function
5627 // parameter lists differ in length, neither template is more specialized
5628 // than the other.
5631 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
5632 return nullptr;
5633
5634 // C++20 [temp.func.order]p6.2.2:
5635 // Otherwise, if the corresponding template-parameters of the
5636 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
5637 // function parameters that positionally correspond between the two
5638 // templates are not of the same type, neither template is more specialized
5639 // than the other.
5640 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
5642 return nullptr;
5643
5644 // [dcl.fct]p5:
5645 // Any top-level cv-qualifiers modifying a parameter type are deleted when
5646 // forming the function type.
5647 for (unsigned i = 0; i < NumParams1; ++i)
5648 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
5649 return nullptr;
5650
5651 // C++20 [temp.func.order]p6.3:
5652 // Otherwise, if the context in which the partial ordering is done is
5653 // that of a call to a conversion function and the return types of the
5654 // templates are not the same, then neither template is more specialized
5655 // than the other.
5656 if (TPOC == TPOC_Conversion &&
5658 return nullptr;
5659
5661 FT1->getAssociatedConstraints(AC1);
5662 FT2->getAssociatedConstraints(AC2);
5663 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5664 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
5665 return nullptr;
5666 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
5667 return nullptr;
5668 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5669 return nullptr;
5670 return AtLeastAsConstrained1 ? FT1 : FT2;
5671}
5672
5673/// Determine if the two templates are equivalent.
5675 if (T1 == T2)
5676 return true;
5677
5678 if (!T1 || !T2)
5679 return false;
5680
5681 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
5682}
5683
5684/// Retrieve the most specialized of the given function template
5685/// specializations.
5686///
5687/// \param SpecBegin the start iterator of the function template
5688/// specializations that we will be comparing.
5689///
5690/// \param SpecEnd the end iterator of the function template
5691/// specializations, paired with \p SpecBegin.
5692///
5693/// \param Loc the location where the ambiguity or no-specializations
5694/// diagnostic should occur.
5695///
5696/// \param NoneDiag partial diagnostic used to diagnose cases where there are
5697/// no matching candidates.
5698///
5699/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
5700/// occurs.
5701///
5702/// \param CandidateDiag partial diagnostic used for each function template
5703/// specialization that is a candidate in the ambiguous ordering. One parameter
5704/// in this diagnostic should be unbound, which will correspond to the string
5705/// describing the template arguments for the function template specialization.
5706///
5707/// \returns the most specialized function template specialization, if
5708/// found. Otherwise, returns SpecEnd.
5711 TemplateSpecCandidateSet &FailedCandidates,
5712 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
5713 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
5714 bool Complain, QualType TargetType) {
5715 if (SpecBegin == SpecEnd) {
5716 if (Complain) {
5717 Diag(Loc, NoneDiag);
5718 FailedCandidates.NoteCandidates(*this, Loc);
5719 }
5720 return SpecEnd;
5721 }
5722
5723 if (SpecBegin + 1 == SpecEnd)
5724 return SpecBegin;
5725
5726 // Find the function template that is better than all of the templates it
5727 // has been compared to.
5728 UnresolvedSetIterator Best = SpecBegin;
5729 FunctionTemplateDecl *BestTemplate
5730 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
5731 assert(BestTemplate && "Not a function template specialization?");
5732 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
5733 FunctionTemplateDecl *Challenger
5734 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5735 assert(Challenger && "Not a function template specialization?");
5736 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, Loc,
5737 TPOC_Other, 0),
5738 Challenger)) {
5739 Best = I;
5740 BestTemplate = Challenger;
5741 }
5742 }
5743
5744 // Make sure that the "best" function template is more specialized than all
5745 // of the others.
5746 bool Ambiguous = false;
5747 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5748 FunctionTemplateDecl *Challenger
5749 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5750 if (I != Best &&
5751 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
5752 Loc, TPOC_Other, 0),
5753 BestTemplate)) {
5754 Ambiguous = true;
5755 break;
5756 }
5757 }
5758
5759 if (!Ambiguous) {
5760 // We found an answer. Return it.
5761 return Best;
5762 }
5763
5764 // Diagnose the ambiguity.
5765 if (Complain) {
5766 Diag(Loc, AmbigDiag);
5767
5768 // FIXME: Can we order the candidates in some sane way?
5769 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5770 PartialDiagnostic PD = CandidateDiag;
5771 const auto *FD = cast<FunctionDecl>(*I);
5773 FD->getPrimaryTemplate()->getTemplateParameters(),
5774 *FD->getTemplateSpecializationArgs());
5775 if (!TargetType.isNull())
5776 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
5777 Diag((*I)->getLocation(), PD);
5778 }
5779 }
5780
5781 return SpecEnd;
5782}
5783
5784/// Determine whether one partial specialization, P1, is at least as
5785/// specialized than another, P2.
5786///
5787/// \tparam TemplateLikeDecl The kind of P2, which must be a
5788/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
5789/// \param T1 The injected-class-name of P1 (faked for a variable template).
5790/// \param T2 The injected-class-name of P2 (faked for a variable template).
5791template<typename TemplateLikeDecl>
5793 TemplateLikeDecl *P2,
5794 TemplateDeductionInfo &Info) {
5795 // C++ [temp.class.order]p1:
5796 // For two class template partial specializations, the first is at least as
5797 // specialized as the second if, given the following rewrite to two
5798 // function templates, the first function template is at least as
5799 // specialized as the second according to the ordering rules for function
5800 // templates (14.6.6.2):
5801 // - the first function template has the same template parameters as the
5802 // first partial specialization and has a single function parameter
5803 // whose type is a class template specialization with the template
5804 // arguments of the first partial specialization, and
5805 // - the second function template has the same template parameters as the
5806 // second partial specialization and has a single function parameter
5807 // whose type is a class template specialization with the template
5808 // arguments of the second partial specialization.
5809 //
5810 // Rather than synthesize function templates, we merely perform the
5811 // equivalent partial ordering by performing deduction directly on
5812 // the template arguments of the class template partial
5813 // specializations. This computation is slightly simpler than the
5814 // general problem of function template partial ordering, because
5815 // class template partial specializations are more constrained. We
5816 // know that every template parameter is deducible from the class
5817 // template partial specialization's template arguments, for
5818 // example.
5820
5821 // Determine whether P1 is at least as specialized as P2.
5822 Deduced.resize(P2->getTemplateParameters()->size());
5824 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
5825 /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
5826 return false;
5827
5828 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
5829 Deduced.end());
5830 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
5831 Info);
5832 if (Inst.isInvalid())
5833 return false;
5834
5835 const auto *TST1 = cast<TemplateSpecializationType>(T1);
5836 bool AtLeastAsSpecialized;
5838 AtLeastAsSpecialized =
5839 FinishTemplateArgumentDeduction(
5840 S, P2, /*IsPartialOrdering=*/true, TST1->template_arguments(),
5841 Deduced, Info) == TemplateDeductionResult::Success;
5842 });
5843 return AtLeastAsSpecialized;
5844}
5845
5846namespace {
5847// A dummy class to return nullptr instead of P2 when performing "more
5848// specialized than primary" check.
5849struct GetP2 {
5850 template <typename T1, typename T2,
5851 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
5852 T2 *operator()(T1 *, T2 *P2) {
5853 return P2;
5854 }
5855 template <typename T1, typename T2,
5856 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
5857 T1 *operator()(T1 *, T2 *) {
5858 return nullptr;
5859 }
5860};
5861
5862// The assumption is that two template argument lists have the same size.
5863struct TemplateArgumentListAreEqual {
5864 ASTContext &Ctx;
5865 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
5866
5867 template <typename T1, typename T2,
5868 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
5869 bool operator()(T1 *PS1, T2 *PS2) {
5870 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
5871 Args2 = PS2->getTemplateArgs().asArray();
5872
5873 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
5874 // We use profile, instead of structural comparison of the arguments,
5875 // because canonicalization can't do the right thing for dependent
5876 // expressions.
5877 llvm::FoldingSetNodeID IDA, IDB;
5878 Args1[I].Profile(IDA, Ctx);
5879 Args2[I].Profile(IDB, Ctx);
5880 if (IDA != IDB)
5881 return false;
5882 }
5883 return true;
5884 }
5885
5886 template <typename T1, typename T2,
5887 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
5888 bool operator()(T1 *Spec, T2 *Primary) {
5889 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
5890 Args2 = Primary->getInjectedTemplateArgs();
5891
5892 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
5893 // We use profile, instead of structural comparison of the arguments,
5894 // because canonicalization can't do the right thing for dependent
5895 // expressions.
5896 llvm::FoldingSetNodeID IDA, IDB;
5897 Args1[I].Profile(IDA, Ctx);
5898 // Unlike the specialization arguments, the injected arguments are not
5899 // always canonical.
5900 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
5901 if (IDA != IDB)
5902 return false;
5903 }
5904 return true;
5905 }
5906};
5907} // namespace
5908
5909/// Returns the more specialized template specialization between T1/P1 and
5910/// T2/P2.
5911/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
5912/// specialization and T2/P2 is the primary template.
5913/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
5914///
5915/// \param T1 the type of the first template partial specialization
5916///
5917/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
5918/// template partial specialization; otherwise, the type of the
5919/// primary template.
5920///
5921/// \param P1 the first template partial specialization
5922///
5923/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
5924/// partial specialization; otherwise, the primary template.
5925///
5926/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
5927/// more specialized, returns nullptr if P1 is not more specialized.
5928/// - otherwise, returns the more specialized template partial
5929/// specialization. If neither partial specialization is more
5930/// specialized, returns NULL.
5931template <typename TemplateLikeDecl, typename PrimaryDel>
5932static TemplateLikeDecl *
5933getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
5934 PrimaryDel *P2, TemplateDeductionInfo &Info) {
5935 constexpr bool IsMoreSpecialThanPrimaryCheck =
5936 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
5937
5938 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, Info);
5939 if (IsMoreSpecialThanPrimaryCheck && !Better1)
5940 return nullptr;
5941
5942 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1, Info);
5943 if (IsMoreSpecialThanPrimaryCheck && !Better2)
5944 return P1;
5945
5946 // C++ [temp.deduct.partial]p10:
5947 // F is more specialized than G if F is at least as specialized as G and G
5948 // is not at least as specialized as F.
5949 if (Better1 != Better2) // We have a clear winner
5950 return Better1 ? P1 : GetP2()(P1, P2);
5951
5952 if (!Better1 && !Better2)
5953 return nullptr;
5954
5955 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5956 // there is no wording or even resolution for this issue.
5957 auto *TST1 = cast<TemplateSpecializationType>(T1);
5958 auto *TST2 = cast<TemplateSpecializationType>(T2);
5959 const TemplateArgument &TA1 = TST1->template_arguments().back();
5960 if (TA1.getKind() == TemplateArgument::Pack) {
5961 assert(TST1->template_arguments().size() ==
5962 TST2->template_arguments().size());
5963 const TemplateArgument &TA2 = TST2->template_arguments().back();
5964 assert(TA2.getKind() == TemplateArgument::Pack);
5965 unsigned PackSize1 = TA1.pack_size();
5966 unsigned PackSize2 = TA2.pack_size();
5967 bool IsPackExpansion1 =
5968 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5969 bool IsPackExpansion2 =
5970 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5971 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
5972 if (PackSize1 > PackSize2 && IsPackExpansion1)
5973 return GetP2()(P1, P2);
5974 if (PackSize1 < PackSize2 && IsPackExpansion2)
5975 return P1;
5976 }
5977 }
5978
5979 if (!S.Context.getLangOpts().CPlusPlus20)
5980 return nullptr;
5981
5982 // Match GCC on not implementing [temp.func.order]p6.2.1.
5983
5984 // C++20 [temp.func.order]p6:
5985 // If deduction against the other template succeeds for both transformed
5986 // templates, constraints can be considered as follows:
5987
5988 TemplateParameterList *TPL1 = P1->getTemplateParameters();
5989 TemplateParameterList *TPL2 = P2->getTemplateParameters();
5990 if (TPL1->size() != TPL2->size())
5991 return nullptr;
5992
5993 // C++20 [temp.func.order]p6.2.2:
5994 // Otherwise, if the corresponding template-parameters of the
5995 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
5996 // function parameters that positionally correspond between the two
5997 // templates are not of the same type, neither template is more specialized
5998 // than the other.
5999 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6001 return nullptr;
6002
6003 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6004 return nullptr;
6005
6007 P1->getAssociatedConstraints(AC1);
6008 P2->getAssociatedConstraints(AC2);
6009 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6010 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6011 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6012 return nullptr;
6013 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6014 return nullptr;
6015 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6016 return nullptr;
6017 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6018}
6019
6020/// Returns the more specialized class template partial specialization
6021/// according to the rules of partial ordering of class template partial
6022/// specializations (C++ [temp.class.order]).
6023///
6024/// \param PS1 the first class template partial specialization
6025///
6026/// \param PS2 the second class template partial specialization
6027///
6028/// \returns the more specialized class template partial specialization. If
6029/// neither partial specialization is more specialized, returns NULL.
6034 SourceLocation Loc) {
6037
6038 TemplateDeductionInfo Info(Loc);
6039 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6040}
6041
6044 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6045 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
6046 QualType PartialT = Spec->getInjectedSpecializationType();
6047
6049 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6050 if (MaybeSpec)
6051 Info.clearSFINAEDiagnostic();
6052 return MaybeSpec;
6053}
6054
6059 // Pretend the variable template specializations are class template
6060 // specializations and form a fake injected class name type for comparison.
6061 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6062 "the partial specializations being compared should specialize"
6063 " the same template.");
6065 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6067 CanonTemplate, PS1->getTemplateArgs().asArray());
6069 CanonTemplate, PS2->getTemplateArgs().asArray());
6070
6071 TemplateDeductionInfo Info(Loc);
6072 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6073}
6074
6077 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6078 TemplateName CanonTemplate =
6081 CanonTemplate, Primary->getInjectedTemplateArgs());
6083 CanonTemplate, Spec->getTemplateArgs().asArray());
6084
6086 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6087 if (MaybeSpec)
6088 Info.clearSFINAEDiagnostic();
6089 return MaybeSpec;
6090}
6091
6094 // C++1z [temp.arg.template]p4: (DR 150)
6095 // A template template-parameter P is at least as specialized as a
6096 // template template-argument A if, given the following rewrite to two
6097 // function templates...
6098
6099 // Rather than synthesize function templates, we merely perform the
6100 // equivalent partial ordering by performing deduction directly on
6101 // the template parameter lists of the template template parameters.
6102 //
6103 // Given an invented class template X with the template parameter list of
6104 // A (including default arguments):
6107
6108 // - Each function template has a single function parameter whose type is
6109 // a specialization of X with template arguments corresponding to the
6110 // template parameters from the respective function template
6113
6114 // Check P's arguments against A's parameter list. This will fill in default
6115 // template arguments as needed. AArgs are already correct by construction.
6116 // We can't just use CheckTemplateIdType because that will expand alias
6117 // templates.
6119 {
6120 SFINAETrap Trap(*this);
6121
6123 TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
6124 P->getRAngleLoc());
6125 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6126 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6127 // expansions, to form an "as written" argument list.
6128 TemplateArgument Arg = PArgs[I];
6129 if (Arg.getKind() == TemplateArgument::Pack) {
6130 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6131 Arg = *Arg.pack_begin();
6132 }
6134 Arg, QualType(), P->getParam(I)->getLocation()));
6135 }
6136 PArgs.clear();
6137
6138 // C++1z [temp.arg.template]p3:
6139 // If the rewrite produces an invalid type, then P is not at least as
6140 // specialized as A.
6142 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, SugaredPArgs,
6143 PArgs) ||
6144 Trap.hasErrorOccurred())
6145 return false;
6146 }
6147
6150
6151 // ... the function template corresponding to P is at least as specialized
6152 // as the function template corresponding to A according to the partial
6153 // ordering rules for function templates.
6154 TemplateDeductionInfo Info(Loc, A->getDepth());
6155 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
6156}
6157
6158namespace {
6159struct MarkUsedTemplateParameterVisitor :
6160 RecursiveASTVisitor<MarkUsedTemplateParameterVisitor> {
6161 llvm::SmallBitVector &Used;
6162 unsigned Depth;
6163
6164 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
6165 unsigned Depth)
6166 : Used(Used), Depth(Depth) { }
6167
6168 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
6169 if (T->getDepth() == Depth)
6170 Used[T->getIndex()] = true;
6171 return true;
6172 }
6173
6174 bool TraverseTemplateName(TemplateName Template) {
6175 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6176 Template.getAsTemplateDecl()))
6177 if (TTP->getDepth() == Depth)
6178 Used[TTP->getIndex()] = true;
6180 TraverseTemplateName(Template);
6181 return true;
6182 }
6183
6184 bool VisitDeclRefExpr(DeclRefExpr *E) {
6185 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6186 if (NTTP->getDepth() == Depth)
6187 Used[NTTP->getIndex()] = true;
6188 return true;
6189 }
6190};
6191}
6192
6193/// Mark the template parameters that are used by the given
6194/// expression.
6195static void
6197 const Expr *E,
6198 bool OnlyDeduced,
6199 unsigned Depth,
6200 llvm::SmallBitVector &Used) {
6201 if (!OnlyDeduced) {
6202 MarkUsedTemplateParameterVisitor(Used, Depth)
6203 .TraverseStmt(const_cast<Expr *>(E));
6204 return;
6205 }
6206
6207 // We can deduce from a pack expansion.
6208 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6209 E = Expansion->getPattern();
6210
6212 if (!NTTP)
6213 return;
6214
6215 if (NTTP->getDepth() == Depth)
6216 Used[NTTP->getIndex()] = true;
6217
6218 // In C++17 mode, additional arguments may be deduced from the type of a
6219 // non-type argument.
6220 if (Ctx.getLangOpts().CPlusPlus17)
6221 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
6222}
6223
6224/// Mark the template parameters that are used by the given
6225/// nested name specifier.
6226static void
6229 bool OnlyDeduced,
6230 unsigned Depth,
6231 llvm::SmallBitVector &Used) {
6232 if (!NNS)
6233 return;
6234
6235 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
6236 Used);
6238 OnlyDeduced, Depth, Used);
6239}
6240
6241/// Mark the template parameters that are used by the given
6242/// template name.
6243static void
6245 TemplateName Name,
6246 bool OnlyDeduced,
6247 unsigned Depth,
6248 llvm::SmallBitVector &Used) {
6249 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6251 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6252 if (TTP->getDepth() == Depth)
6253 Used[TTP->getIndex()] = true;
6254 }
6255 return;
6256 }
6257
6258 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
6259 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6260 Depth, Used);
6261 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
6262 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6263 Depth, Used);
6264}
6265
6266/// Mark the template parameters that are used by the given
6267/// type.
6268static void
6270 bool OnlyDeduced,
6271 unsigned Depth,
6272 llvm::SmallBitVector &Used) {
6273 if (T.isNull())
6274 return;
6275
6276 // Non-dependent types have nothing deducible
6277 if (!T->isDependentType())
6278 return;
6279
6280 T = Ctx.getCanonicalType(T);
6281 switch (T->getTypeClass()) {
6282 case Type::Pointer:
6284 cast<PointerType>(T)->getPointeeType(),
6285 OnlyDeduced,
6286 Depth,
6287 Used);
6288 break;
6289
6290 case Type::BlockPointer:
6292 cast<BlockPointerType>(T)->getPointeeType(),
6293 OnlyDeduced,
6294 Depth,
6295 Used);
6296 break;
6297
6298 case Type::LValueReference:
6299 case Type::RValueReference:
6301 cast<ReferenceType>(T)->getPointeeType(),
6302 OnlyDeduced,
6303 Depth,
6304 Used);
6305 break;
6306
6307 case Type::MemberPointer: {
6308 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
6309 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
6310 Depth, Used);
6311 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
6312 OnlyDeduced, Depth, Used);
6313 break;
6314 }
6315
6316 case Type::DependentSizedArray:
6318 cast<DependentSizedArrayType>(T)->getSizeExpr(),
6319 OnlyDeduced, Depth, Used);
6320 // Fall through to check the element type
6321 [[fallthrough]];
6322
6323 case Type::ConstantArray:
6324 case Type::IncompleteArray:
6325 case Type::ArrayParameter:
6327 cast<ArrayType>(T)->getElementType(),
6328 OnlyDeduced, Depth, Used);
6329 break;
6330 case Type::Vector:
6331 case Type::ExtVector:
6333 cast<VectorType>(T)->getElementType(),
6334 OnlyDeduced, Depth, Used);
6335 break;
6336
6337 case Type::DependentVector: {
6338 const auto *VecType = cast<DependentVectorType>(T);
6339 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6340 Depth, Used);
6341 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
6342 Used);
6343 break;
6344 }
6345 case Type::DependentSizedExtVector: {
6346 const DependentSizedExtVectorType *VecType
6347 = cast<DependentSizedExtVectorType>(T);
6348 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6349 Depth, Used);
6350 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
6351 Depth, Used);
6352 break;
6353 }
6354
6355 case Type::DependentAddressSpace: {
6356 const DependentAddressSpaceType *DependentASType =
6357 cast<DependentAddressSpaceType>(T);
6358 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
6359 OnlyDeduced, Depth, Used);
6361 DependentASType->getAddrSpaceExpr(),
6362 OnlyDeduced, Depth, Used);
6363 break;
6364 }
6365
6366 case Type::ConstantMatrix: {
6367 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
6368 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6369 Depth, Used);
6370 break;
6371 }
6372
6373 case Type::DependentSizedMatrix: {
6374 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
6375 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6376 Depth, Used);
6377 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
6378 Used);
6379 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
6380 Depth, Used);
6381 break;
6382 }
6383
6384 case Type::FunctionProto: {
6385 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
6386 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
6387 Used);
6388 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6389 // C++17 [temp.deduct.type]p5:
6390 // The non-deduced contexts are: [...]
6391 // -- A function parameter pack that does not occur at the end of the
6392 // parameter-declaration-list.
6393 if (!OnlyDeduced || I + 1 == N ||
6394 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
6395 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
6396 Depth, Used);
6397 } else {
6398 // FIXME: C++17 [temp.deduct.call]p1:
6399 // When a function parameter pack appears in a non-deduced context,
6400 // the type of that pack is never deduced.
6401 //
6402 // We should also track a set of "never deduced" parameters, and
6403 // subtract that from the list of deduced parameters after marking.
6404 }
6405 }
6406 if (auto *E = Proto->getNoexceptExpr())
6407 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6408 break;
6409 }
6410
6411 case Type::TemplateTypeParm: {
6412 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
6413 if (TTP->getDepth() == Depth)
6414 Used[TTP->getIndex()] = true;
6415 break;
6416 }
6417
6418 case Type::SubstTemplateTypeParmPack: {
6420 = cast<SubstTemplateTypeParmPackType>(T);
6421 if (Subst->getReplacedParameter()->getDepth() == Depth)
6422 Used[Subst->getIndex()] = true;
6424 OnlyDeduced, Depth, Used);
6425 break;
6426 }
6427
6428 case Type::InjectedClassName:
6429 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
6430 [[fallthrough]];
6431
6432 case Type::TemplateSpecialization: {
6433 const TemplateSpecializationType *Spec
6434 = cast<TemplateSpecializationType>(T);
6435 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
6436 Depth, Used);
6437
6438 // C++0x [temp.deduct.type]p9:
6439 // If the template argument list of P contains a pack expansion that is
6440 // not the last template argument, the entire template argument list is a
6441 // non-deduced context.
6442 if (OnlyDeduced &&
6444 break;
6445
6446 for (const auto &Arg : Spec->template_arguments())
6447 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6448 break;
6449 }
6450
6451 case Type::Complex:
6452 if (!OnlyDeduced)
6454 cast<ComplexType>(T)->getElementType(),
6455 OnlyDeduced, Depth, Used);
6456 break;
6457
6458 case Type::Atomic:
6459 if (!OnlyDeduced)
6461 cast<AtomicType>(T)->getValueType(),
6462 OnlyDeduced, Depth, Used);
6463 break;
6464
6465 case Type::DependentName:
6466 if (!OnlyDeduced)
6468 cast<DependentNameType>(T)->getQualifier(),
6469 OnlyDeduced, Depth, Used);
6470 break;
6471
6472 case Type::DependentTemplateSpecialization: {
6473 // C++14 [temp.deduct.type]p5:
6474 // The non-deduced contexts are:
6475 // -- The nested-name-specifier of a type that was specified using a
6476 // qualified-id
6477 //
6478 // C++14 [temp.deduct.type]p6:
6479 // When a type name is specified in a way that includes a non-deduced
6480 // context, all of the types that comprise that type name are also
6481 // non-deduced.
6482 if (OnlyDeduced)
6483 break;
6484
6486 = cast<DependentTemplateSpecializationType>(T);
6487
6489 OnlyDeduced, Depth, Used);
6490
6491 for (const auto &Arg : Spec->template_arguments())
6492 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6493 break;
6494 }
6495
6496 case Type::TypeOf:
6497 if (!OnlyDeduced)
6498 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
6499 OnlyDeduced, Depth, Used);
6500 break;
6501
6502 case Type::TypeOfExpr:
6503 if (!OnlyDeduced)
6505 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
6506 OnlyDeduced, Depth, Used);
6507 break;
6508
6509 case Type::Decltype:
6510 if (!OnlyDeduced)
6512 cast<DecltypeType>(T)->getUnderlyingExpr(),
6513 OnlyDeduced, Depth, Used);
6514 break;
6515
6516 case Type::PackIndexing:
6517 if (!OnlyDeduced) {
6518 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getPattern(),
6519 OnlyDeduced, Depth, Used);
6520 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getIndexExpr(),
6521 OnlyDeduced, Depth, Used);
6522 }
6523 break;
6524
6525 case Type::UnaryTransform:
6526 if (!OnlyDeduced)
6528 cast<UnaryTransformType>(T)->getUnderlyingType(),
6529 OnlyDeduced, Depth, Used);
6530 break;
6531
6532 case Type::PackExpansion:
6534 cast<PackExpansionType>(T)->getPattern(),
6535 OnlyDeduced, Depth, Used);
6536 break;
6537
6538 case Type::Auto:
6539 case Type::DeducedTemplateSpecialization:
6541 cast<DeducedType>(T)->getDeducedType(),
6542 OnlyDeduced, Depth, Used);
6543 break;
6544 case Type::DependentBitInt:
6546 cast<DependentBitIntType>(T)->getNumBitsExpr(),
6547 OnlyDeduced, Depth, Used);
6548 break;
6549
6550 // None of these types have any template parameters in them.
6551 case Type::Builtin:
6552 case Type::VariableArray:
6553 case Type::FunctionNoProto:
6554 case Type::Record:
6555 case Type::Enum:
6556 case Type::ObjCInterface:
6557 case Type::ObjCObject:
6558 case Type::ObjCObjectPointer:
6559 case Type::UnresolvedUsing:
6560 case Type::Pipe:
6561 case Type::BitInt:
6562#define TYPE(Class, Base)
6563#define ABSTRACT_TYPE(Class, Base)
6564#define DEPENDENT_TYPE(Class, Base)
6565#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6566#include "clang/AST/TypeNodes.inc"
6567 break;
6568 }
6569}
6570
6571/// Mark the template parameters that are used by this
6572/// template argument.
6573static void
6576 bool OnlyDeduced,
6577 unsigned Depth,
6578 llvm::SmallBitVector &Used) {
6579 switch (TemplateArg.getKind()) {
6585 break;
6586
6588 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
6589 Depth, Used);
6590 break;
6591
6595 TemplateArg.getAsTemplateOrTemplatePattern(),
6596 OnlyDeduced, Depth, Used);
6597 break;
6598
6600 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
6601 Depth, Used);
6602 break;
6603
6605 for (const auto &P : TemplateArg.pack_elements())
6606 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
6607 break;
6608 }
6609}
6610
6611/// Mark which template parameters are used in a given expression.
6612///
6613/// \param E the expression from which template parameters will be deduced.
6614///
6615/// \param Used a bit vector whose elements will be set to \c true
6616/// to indicate when the corresponding template parameter will be
6617/// deduced.
6618void
6619Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
6620 unsigned Depth,
6621 llvm::SmallBitVector &Used) {
6622 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
6623}
6624
6625/// Mark which template parameters can be deduced from a given
6626/// template argument list.
6627///
6628/// \param TemplateArgs the template argument list from which template
6629/// parameters will be deduced.
6630///
6631/// \param Used a bit vector whose elements will be set to \c true
6632/// to indicate when the corresponding template parameter will be
6633/// deduced.
6634void
6636 bool OnlyDeduced, unsigned Depth,
6637 llvm::SmallBitVector &Used) {
6638 // C++0x [temp.deduct.type]p9:
6639 // If the template argument list of P contains a pack expansion that is not
6640 // the last template argument, the entire template argument list is a
6641 // non-deduced context.
6642 if (OnlyDeduced &&
6643 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
6644 return;
6645
6646 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6647 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
6648 Depth, Used);
6649}
6650
6651/// Marks all of the template parameters that will be deduced by a
6652/// call to the given function template.
6654 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
6655 llvm::SmallBitVector &Deduced) {
6656 TemplateParameterList *TemplateParams
6657 = FunctionTemplate->getTemplateParameters();
6658 Deduced.clear();
6659 Deduced.resize(TemplateParams->size());
6660
6661 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
6662 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
6663 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
6664 true, TemplateParams->getDepth(), Deduced);
6665}
6666
6668 FunctionTemplateDecl *FunctionTemplate,
6669 QualType T) {
6670 if (!T->isDependentType())
6671 return false;
6672
6673 TemplateParameterList *TemplateParams
6674 = FunctionTemplate->getTemplateParameters();
6675 llvm::SmallBitVector Deduced(TemplateParams->size());
6676 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
6677 Deduced);
6678
6679 return Deduced.any();
6680}
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:1109
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:143
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:2767
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:2574
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2590
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:2773
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:1119
CanQualType NullPtrTy
Definition: ASTContext.h:1118
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:1590
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
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:1092
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:1100
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2156
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:1415
CanQualType OverloadTy
Definition: ASTContext.h:1119
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2617
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:2340
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
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:1568
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:2776
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:5977
ArrayRef< TemplateArgument > getTypeConstraintArguments() const
Definition: Type.h:5987
bool isDecltypeAuto() const
Definition: Type.h:6000
ConceptDecl * getTypeConstraintConcept() const
Definition: Type.h:5992
AutoTypeKeyword getKeyword() const
Definition: Type.h:6008
bool isConstrained() const
Definition: Type.h:5996
A fixed int type of a specified bitwidth.
Definition: Type.h:7238
Pointer to a block type.
Definition: Type.h:3345
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2902
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
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:2455
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2236
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2221
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:619
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1594
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.
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)?...
Complex values, per C99 6.2.5p11.
Definition: Type.h:3082
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:4163
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4184
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4181
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:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
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:86
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:220
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
bool isInvalidDecl() const
Definition: DeclBase.h:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:210
DeclContext * getDeclContext()
Definition: DeclBase.h:454
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:433
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:6045
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5943
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3855
Expr * getAddrSpaceExpr() const
Definition: Type.h:3866
QualType getPointeeType() const
Definition: Type.h:3867
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3895
QualType getElementType() const
Definition: Type.h:3910
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4222
Expr * getColumnExpr() const
Definition: Type.h:4235
Expr * getRowExpr() const
Definition: Type.h:4234
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:6500
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6519
NestedNameSpecifier * getQualifier() const
Definition: Type.h:6516
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4017
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition: DeclCXX.h:1926
const Expr * getExpr() const
Definition: DeclCXX.h:1906
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:4057
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:1971
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2707
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4042
QualType getReturnType() const
Definition: Decl.h:2755
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2684
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:4113
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4178
bool isImmediateEscalating() const
Definition: Decl.cpp:3268
size_t param_size() const
Definition: Decl.h:2700
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:3203
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4652
param_type_iterator param_type_begin() const
Definition: Type.h:5044
const ExtParameterInfo * getExtParameterInfosOrNull() const
Return a pointer to the beginning of the array of extra parameter information, if present,...
Definition: Type.h:5082
unsigned getNumParams() const
Definition: Type.h:4885
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:5024
QualType getParamType(unsigned i) const
Definition: Type.h:4887
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:4917
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4896
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:4969
param_type_iterator param_type_end() const
Definition: Type.h:5048
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4892
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:4252
QualType getReturnType() const
Definition: Type.h:4569
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:4847
unsigned getNumInits() const
Definition: Expr.h:4877
ArrayRef< Expr * > inits()
Definition: Expr.h:4887
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6217
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3420
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1948
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:4127
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4141
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3456
QualType getPointeeType() const
Definition: Type.h:3472
const Type * getClass() const
Definition: Type.h:3486
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:7004
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2976
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3127
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3036
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3088
decls_iterator decls_begin() const
Definition: ExprCXX.h:3068
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3147
decls_iterator decls_end() const
Definition: ExprCXX.h:3071
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4149
Represents a pack expansion of types.
Definition: Type.h:6565
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:6586
std::optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:6590
bool hasSelectedType() const
Definition: Type.h:5431
QualType getSelectedType() const
Definition: Type.h:5424
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:3135
QualType getPointeeType() const
Definition: Type.h:3145
A (possibly-)qualified type.
Definition: Type.h:940
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7444
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7355
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7481
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7395
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:7556
QualType getCanonicalType() const
Definition: Type.h:7407
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7449
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7476
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7401
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:318
unsigned getCVRQualifiers() const
Definition: Type.h:474
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:481
GC getObjCGCAttr() const
Definition: Type.h:505
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:340
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:336
void removeObjCLifetime()
Definition: Type.h:537
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:443
bool hasNonTrivialObjCLifetime() const
True if the lifetime is neither None or ExplicitNone.
Definition: Type.h:545
bool hasAddressSpace() const
Definition: Type.h:556
void removeObjCGCAttr()
Definition: Type.h:509
void removeAddressSpace()
Definition: Type.h:582
bool hasObjCGCAttr() const
Definition: Type.h:504
void setCVRQualifiers(unsigned mask)
Definition: Type.h:477
bool hasObjCLifetime() const
Definition: Type.h:530
ObjCLifetime getObjCLifetime() const
Definition: Type.h:531
Qualifiers withoutObjCLifetime() const
Definition: Type.h:519
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:731
LangAS getAddressSpace() const
Definition: Type.h:557
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:534
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3438
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5545
RecordDecl * getDecl() const
Definition: Type.h:5555
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:3376
QualType getPointeeType() const
Definition: Type.h:3394
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:10305
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6552
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2544
A helper class for building up ExtParameterInfos.
Definition: Sema.h:9758
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:9777
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9508
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9538
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
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:9787
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement)
Completely replace the auto in TypeWithAuto by Replacement.
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc)
SemaCUDA & CUDA()
Definition: Sema.h:998
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:9184
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:9176
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:9180
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:858
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:3084
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
ASTContext & getASTContext() const
Definition: Sema.h:527
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.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:645
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:775
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:9298
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:520
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.
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:11246
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:996
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition: Sema.h:9571
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
Definition: SemaType.cpp:9808
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21227
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:11707
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:9217
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)
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:520
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:8364
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:9722
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:5885
TemplateArgument getArgumentPack() const
Definition: Type.cpp:4161
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: Type.h:5911
const TemplateTypeParmDecl * getReplacedParameter() const
Gets the template parameter declaration that was substituted for.
Definition: Type.cpp:4153
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4728
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:6085
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6153
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6151
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:5775
unsigned getDepth() const
Definition: Type.h:5774
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
const Type * getTypeForDecl() const
Definition: Decl.h:3415
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:7326
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:1813
bool isVoidType() const
Definition: Type.h:7901
bool isIncompleteArrayType() const
Definition: Type.h:7682
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:7877
bool isRValueReferenceType() const
Definition: Type.h:7628
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8056
bool isArrayType() const
Definition: Type.h:7674
bool isFunctionPointerType() const
Definition: Type.h:7642
bool isPointerType() const
Definition: Type.h:7608
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8186
bool isReferenceType() const
Definition: Type.h:7620
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2754
bool isLValueReferenceType() const
Definition: Type.h:7624
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2649
QualType getCanonicalTypeInternal() const
Definition: Type.h:2932
bool isMemberPointerType() const
Definition: Type.h:7656
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4882
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8035
bool isFunctionType() const
Definition: Type.h:7604
bool isObjCObjectPointerType() const
Definition: Type.h:7740
bool isMemberFunctionPointerType() const
Definition: Type.h:7660
bool isAnyPointerType() const
Definition: Type.h:7612
TypeClass getTypeClass() const
Definition: Type.h:2300
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2326
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8119
bool isRecordType() const
Definition: Type.h:7702
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:1558
Declaration of a variable template.
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:3965
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:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
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:1762
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1768
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
const FunctionProtoType * T
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:373
@ 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:4703
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4705
Extra information about a function prototype.
Definition: Type.h:4731
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:4739
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4732
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:9825
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:9832
A stack object to be created when performing template instantiation.
Definition: Sema.h:9989
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:10143
brief A function argument from which we performed template argument
Definition: Sema.h:9617
Location information for a TemplateArgument.
Definition: TemplateBase.h:472