clang 20.0.0git
SemaConcept.cpp
Go to the documentation of this file.
1//===-- SemaConcept.cpp - Semantic Analysis for Constraints and Concepts --===//
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 semantic analysis for C++ constraints and concepts.
10//
11//===----------------------------------------------------------------------===//
12
14#include "TreeTransform.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/DeclCXX.h"
22#include "clang/Sema/Overload.h"
24#include "clang/Sema/Sema.h"
27#include "clang/Sema/Template.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/PointerUnion.h"
31#include "llvm/ADT/StringExtras.h"
32#include <optional>
33
34using namespace clang;
35using namespace sema;
36
37namespace {
38class LogicalBinOp {
41 const Expr *LHS = nullptr;
42 const Expr *RHS = nullptr;
43
44public:
45 LogicalBinOp(const Expr *E) {
46 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
47 Op = BinaryOperator::getOverloadedOperator(BO->getOpcode());
48 LHS = BO->getLHS();
49 RHS = BO->getRHS();
50 Loc = BO->getExprLoc();
51 } else if (auto *OO = dyn_cast<CXXOperatorCallExpr>(E)) {
52 // If OO is not || or && it might not have exactly 2 arguments.
53 if (OO->getNumArgs() == 2) {
54 Op = OO->getOperator();
55 LHS = OO->getArg(0);
56 RHS = OO->getArg(1);
57 Loc = OO->getOperatorLoc();
58 }
59 }
60 }
61
62 bool isAnd() const { return Op == OO_AmpAmp; }
63 bool isOr() const { return Op == OO_PipePipe; }
64 explicit operator bool() const { return isAnd() || isOr(); }
65
66 const Expr *getLHS() const { return LHS; }
67 const Expr *getRHS() const { return RHS; }
68 OverloadedOperatorKind getOp() const { return Op; }
69
70 ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS) const {
71 return recreateBinOp(SemaRef, LHS, const_cast<Expr *>(getRHS()));
72 }
73
74 ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS,
75 ExprResult RHS) const {
76 assert((isAnd() || isOr()) && "Not the right kind of op?");
77 assert((!LHS.isInvalid() && !RHS.isInvalid()) && "not good expressions?");
78
79 if (!LHS.isUsable() || !RHS.isUsable())
80 return ExprEmpty();
81
82 // We should just be able to 'normalize' these to the builtin Binary
83 // Operator, since that is how they are evaluated in constriant checks.
84 return BinaryOperator::Create(SemaRef.Context, LHS.get(), RHS.get(),
86 SemaRef.Context.BoolTy, VK_PRValue,
88 }
89};
90}
91
92bool Sema::CheckConstraintExpression(const Expr *ConstraintExpression,
93 Token NextToken, bool *PossibleNonPrimary,
94 bool IsTrailingRequiresClause) {
95 // C++2a [temp.constr.atomic]p1
96 // ..E shall be a constant expression of type bool.
97
98 ConstraintExpression = ConstraintExpression->IgnoreParenImpCasts();
99
100 if (LogicalBinOp BO = ConstraintExpression) {
101 return CheckConstraintExpression(BO.getLHS(), NextToken,
102 PossibleNonPrimary) &&
103 CheckConstraintExpression(BO.getRHS(), NextToken,
104 PossibleNonPrimary);
105 } else if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpression))
106 return CheckConstraintExpression(C->getSubExpr(), NextToken,
107 PossibleNonPrimary);
108
109 QualType Type = ConstraintExpression->getType();
110
111 auto CheckForNonPrimary = [&] {
112 if (!PossibleNonPrimary)
113 return;
114
115 *PossibleNonPrimary =
116 // We have the following case:
117 // template<typename> requires func(0) struct S { };
118 // The user probably isn't aware of the parentheses required around
119 // the function call, and we're only going to parse 'func' as the
120 // primary-expression, and complain that it is of non-bool type.
121 //
122 // However, if we're in a lambda, this might also be:
123 // []<typename> requires var () {};
124 // Which also looks like a function call due to the lambda parentheses,
125 // but unlike the first case, isn't an error, so this check is skipped.
126 (NextToken.is(tok::l_paren) &&
127 (IsTrailingRequiresClause ||
128 (Type->isDependentType() &&
129 isa<UnresolvedLookupExpr>(ConstraintExpression) &&
130 !dyn_cast_if_present<LambdaScopeInfo>(getCurFunction())) ||
131 Type->isFunctionType() ||
132 Type->isSpecificBuiltinType(BuiltinType::Overload))) ||
133 // We have the following case:
134 // template<typename T> requires size_<T> == 0 struct S { };
135 // The user probably isn't aware of the parentheses required around
136 // the binary operator, and we're only going to parse 'func' as the
137 // first operand, and complain that it is of non-bool type.
138 getBinOpPrecedence(NextToken.getKind(),
139 /*GreaterThanIsOperator=*/true,
141 };
142
143 // An atomic constraint!
144 if (ConstraintExpression->isTypeDependent()) {
145 CheckForNonPrimary();
146 return true;
147 }
148
150 Diag(ConstraintExpression->getExprLoc(),
151 diag::err_non_bool_atomic_constraint) << Type
152 << ConstraintExpression->getSourceRange();
153 CheckForNonPrimary();
154 return false;
155 }
156
157 if (PossibleNonPrimary)
158 *PossibleNonPrimary = false;
159 return true;
160}
161
162namespace {
163struct SatisfactionStackRAII {
164 Sema &SemaRef;
165 bool Inserted = false;
166 SatisfactionStackRAII(Sema &SemaRef, const NamedDecl *ND,
167 const llvm::FoldingSetNodeID &FSNID)
168 : SemaRef(SemaRef) {
169 if (ND) {
170 SemaRef.PushSatisfactionStackEntry(ND, FSNID);
171 Inserted = true;
172 }
173 }
174 ~SatisfactionStackRAII() {
175 if (Inserted)
177 }
178};
179} // namespace
180
181template <typename ConstraintEvaluator>
182static ExprResult
183calculateConstraintSatisfaction(Sema &S, const Expr *ConstraintExpr,
184 ConstraintSatisfaction &Satisfaction,
185 const ConstraintEvaluator &Evaluator);
186
187template <typename ConstraintEvaluator>
188static ExprResult
190 OverloadedOperatorKind Op, const Expr *RHS,
191 ConstraintSatisfaction &Satisfaction,
192 const ConstraintEvaluator &Evaluator) {
193 size_t EffectiveDetailEndIndex = Satisfaction.Details.size();
194
195 ExprResult LHSRes =
196 calculateConstraintSatisfaction(S, LHS, Satisfaction, Evaluator);
197
198 if (LHSRes.isInvalid())
199 return ExprError();
200
201 bool IsLHSSatisfied = Satisfaction.IsSatisfied;
202
203 if (Op == clang::OO_PipePipe && IsLHSSatisfied)
204 // [temp.constr.op] p3
205 // A disjunction is a constraint taking two operands. To determine if
206 // a disjunction is satisfied, the satisfaction of the first operand
207 // is checked. If that is satisfied, the disjunction is satisfied.
208 // Otherwise, the disjunction is satisfied if and only if the second
209 // operand is satisfied.
210 // LHS is instantiated while RHS is not. Skip creating invalid BinaryOp.
211 return LHSRes;
212
213 if (Op == clang::OO_AmpAmp && !IsLHSSatisfied)
214 // [temp.constr.op] p2
215 // A conjunction is a constraint taking two operands. To determine if
216 // a conjunction is satisfied, the satisfaction of the first operand
217 // is checked. If that is not satisfied, the conjunction is not
218 // satisfied. Otherwise, the conjunction is satisfied if and only if
219 // the second operand is satisfied.
220 // LHS is instantiated while RHS is not. Skip creating invalid BinaryOp.
221 return LHSRes;
222
223 ExprResult RHSRes =
224 calculateConstraintSatisfaction(S, RHS, Satisfaction, Evaluator);
225 if (RHSRes.isInvalid())
226 return ExprError();
227
228 bool IsRHSSatisfied = Satisfaction.IsSatisfied;
229 // Current implementation adds diagnostic information about the falsity
230 // of each false atomic constraint expression when it evaluates them.
231 // When the evaluation results to `false || true`, the information
232 // generated during the evaluation of left-hand side is meaningless
233 // because the whole expression evaluates to true.
234 // The following code removes the irrelevant diagnostic information.
235 // FIXME: We should probably delay the addition of diagnostic information
236 // until we know the entire expression is false.
237 if (Op == clang::OO_PipePipe && IsRHSSatisfied) {
238 auto EffectiveDetailEnd = Satisfaction.Details.begin();
239 std::advance(EffectiveDetailEnd, EffectiveDetailEndIndex);
240 Satisfaction.Details.erase(EffectiveDetailEnd, Satisfaction.Details.end());
241 }
242
243 if (!LHSRes.isUsable() || !RHSRes.isUsable())
244 return ExprEmpty();
245
246 return BinaryOperator::Create(S.Context, LHSRes.get(), RHSRes.get(),
250}
251
252template <typename ConstraintEvaluator>
253static ExprResult
255 ConstraintSatisfaction &Satisfaction,
256 const ConstraintEvaluator &Evaluator) {
257 bool Conjunction = FE->getOperator() == BinaryOperatorKind::BO_LAnd;
258 size_t EffectiveDetailEndIndex = Satisfaction.Details.size();
259
260 ExprResult Out;
261 if (FE->isLeftFold() && FE->getInit()) {
262 Out = calculateConstraintSatisfaction(S, FE->getInit(), Satisfaction,
263 Evaluator);
264 if (Out.isInvalid())
265 return ExprError();
266
267 // If the first clause of a conjunction is not satisfied,
268 // or if the first clause of a disjection is satisfied,
269 // we have established satisfaction of the whole constraint
270 // and we should not continue further.
271 if (Conjunction != Satisfaction.IsSatisfied)
272 return Out;
273 }
274 std::optional<unsigned> NumExpansions =
275 Evaluator.EvaluateFoldExpandedConstraintSize(FE);
276 if (!NumExpansions)
277 return ExprError();
278 for (unsigned I = 0; I < *NumExpansions; I++) {
281 Satisfaction, Evaluator);
282 if (Res.isInvalid())
283 return ExprError();
284 bool IsRHSSatisfied = Satisfaction.IsSatisfied;
285 if (!Conjunction && IsRHSSatisfied) {
286 auto EffectiveDetailEnd = Satisfaction.Details.begin();
287 std::advance(EffectiveDetailEnd, EffectiveDetailEndIndex);
288 Satisfaction.Details.erase(EffectiveDetailEnd,
289 Satisfaction.Details.end());
290 }
291 if (Out.isUnset())
292 Out = Res;
293 else if (!Res.isUnset()) {
295 S.Context, Out.get(), Res.get(), FE->getOperator(), S.Context.BoolTy,
297 }
298 if (Conjunction != IsRHSSatisfied)
299 return Out;
300 }
301
302 if (FE->isRightFold() && FE->getInit()) {
304 Satisfaction, Evaluator);
305 if (Out.isInvalid())
306 return ExprError();
307
308 if (Out.isUnset())
309 Out = Res;
310 else if (!Res.isUnset()) {
312 S.Context, Out.get(), Res.get(), FE->getOperator(), S.Context.BoolTy,
314 }
315 }
316
317 if (Out.isUnset()) {
318 Satisfaction.IsSatisfied = Conjunction;
319 Out = S.BuildEmptyCXXFoldExpr(FE->getBeginLoc(), FE->getOperator());
320 }
321 return Out;
322}
323
324template <typename ConstraintEvaluator>
325static ExprResult
326calculateConstraintSatisfaction(Sema &S, const Expr *ConstraintExpr,
327 ConstraintSatisfaction &Satisfaction,
328 const ConstraintEvaluator &Evaluator) {
329 ConstraintExpr = ConstraintExpr->IgnoreParenImpCasts();
330
331 if (LogicalBinOp BO = ConstraintExpr)
333 S, BO.getLHS(), BO.getOp(), BO.getRHS(), Satisfaction, Evaluator);
334
335 if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpr)) {
336 // These aren't evaluated, so we don't care about cleanups, so we can just
337 // evaluate these as if the cleanups didn't exist.
338 return calculateConstraintSatisfaction(S, C->getSubExpr(), Satisfaction,
339 Evaluator);
340 }
341
342 if (auto *FE = dyn_cast<CXXFoldExpr>(ConstraintExpr);
343 FE && S.getLangOpts().CPlusPlus26 &&
344 (FE->getOperator() == BinaryOperatorKind::BO_LAnd ||
345 FE->getOperator() == BinaryOperatorKind::BO_LOr)) {
346 return calculateConstraintSatisfaction(S, FE, Satisfaction, Evaluator);
347 }
348
349 // An atomic constraint expression
350 ExprResult SubstitutedAtomicExpr =
351 Evaluator.EvaluateAtomicConstraint(ConstraintExpr);
352
353 if (SubstitutedAtomicExpr.isInvalid())
354 return ExprError();
355
356 if (!SubstitutedAtomicExpr.isUsable())
357 // Evaluator has decided satisfaction without yielding an expression.
358 return ExprEmpty();
359
360 // We don't have the ability to evaluate this, since it contains a
361 // RecoveryExpr, so we want to fail overload resolution. Otherwise,
362 // we'd potentially pick up a different overload, and cause confusing
363 // diagnostics. SO, add a failure detail that will cause us to make this
364 // overload set not viable.
365 if (SubstitutedAtomicExpr.get()->containsErrors()) {
366 Satisfaction.IsSatisfied = false;
367 Satisfaction.ContainsErrors = true;
368
369 PartialDiagnostic Msg = S.PDiag(diag::note_constraint_references_error);
370 SmallString<128> DiagString;
371 DiagString = ": ";
372 Msg.EmitToString(S.getDiagnostics(), DiagString);
373 unsigned MessageSize = DiagString.size();
374 char *Mem = new (S.Context) char[MessageSize];
375 memcpy(Mem, DiagString.c_str(), MessageSize);
376 Satisfaction.Details.emplace_back(
378 SubstitutedAtomicExpr.get()->getBeginLoc(),
379 StringRef(Mem, MessageSize)});
380 return SubstitutedAtomicExpr;
381 }
382
383 EnterExpressionEvaluationContext ConstantEvaluated(
386 Expr::EvalResult EvalResult;
387 EvalResult.Diag = &EvaluationDiags;
388 if (!SubstitutedAtomicExpr.get()->EvaluateAsConstantExpr(EvalResult,
389 S.Context) ||
390 !EvaluationDiags.empty()) {
391 // C++2a [temp.constr.atomic]p1
392 // ...E shall be a constant expression of type bool.
393 S.Diag(SubstitutedAtomicExpr.get()->getBeginLoc(),
394 diag::err_non_constant_constraint_expression)
395 << SubstitutedAtomicExpr.get()->getSourceRange();
396 for (const PartialDiagnosticAt &PDiag : EvaluationDiags)
397 S.Diag(PDiag.first, PDiag.second);
398 return ExprError();
399 }
400
401 assert(EvalResult.Val.isInt() &&
402 "evaluating bool expression didn't produce int");
403 Satisfaction.IsSatisfied = EvalResult.Val.getInt().getBoolValue();
404 if (!Satisfaction.IsSatisfied)
405 Satisfaction.Details.emplace_back(SubstitutedAtomicExpr.get());
406
407 return SubstitutedAtomicExpr;
408}
409
410static bool
411DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID &ID,
412 const NamedDecl *Templ, const Expr *E,
413 const MultiLevelTemplateArgumentList &MLTAL) {
414 E->Profile(ID, S.Context, /*Canonical=*/true);
415 for (const auto &List : MLTAL)
416 for (const auto &TemplateArg : List.Args)
417 TemplateArg.Profile(ID, S.Context);
418
419 // Note that we have to do this with our own collection, because there are
420 // times where a constraint-expression check can cause us to need to evaluate
421 // other constriants that are unrelated, such as when evaluating a recovery
422 // expression, or when trying to determine the constexpr-ness of special
423 // members. Otherwise we could just use the
424 // Sema::InstantiatingTemplate::isAlreadyBeingInstantiated function.
425 if (S.SatisfactionStackContains(Templ, ID)) {
426 S.Diag(E->getExprLoc(), diag::err_constraint_depends_on_self)
427 << const_cast<Expr *>(E) << E->getSourceRange();
428 return true;
429 }
430
431 return false;
432}
433
435 Sema &S, const NamedDecl *Template, SourceLocation TemplateNameLoc,
436 const MultiLevelTemplateArgumentList &MLTAL, const Expr *ConstraintExpr,
437 ConstraintSatisfaction &Satisfaction) {
438
439 struct ConstraintEvaluator {
440 Sema &S;
441 const NamedDecl *Template;
442 SourceLocation TemplateNameLoc;
444 ConstraintSatisfaction &Satisfaction;
445
446 ExprResult EvaluateAtomicConstraint(const Expr *AtomicExpr) const {
447 EnterExpressionEvaluationContext ConstantEvaluated(
448 S, Sema::ExpressionEvaluationContext::ConstantEvaluated,
450
451 // Atomic constraint - substitute arguments and check satisfaction.
452 ExprResult SubstitutedExpression;
453 {
454 TemplateDeductionInfo Info(TemplateNameLoc);
458 const_cast<NamedDecl *>(Template), Info,
460 if (Inst.isInvalid())
461 return ExprError();
462
463 llvm::FoldingSetNodeID ID;
464 if (Template &&
465 DiagRecursiveConstraintEval(S, ID, Template, AtomicExpr, MLTAL)) {
466 Satisfaction.IsSatisfied = false;
467 Satisfaction.ContainsErrors = true;
468 return ExprEmpty();
469 }
470
471 SatisfactionStackRAII StackRAII(S, Template, ID);
472
473 // We do not want error diagnostics escaping here.
474 Sema::SFINAETrap Trap(S);
475 SubstitutedExpression =
476 S.SubstConstraintExpr(const_cast<Expr *>(AtomicExpr), MLTAL);
477
478 if (SubstitutedExpression.isInvalid() || Trap.hasErrorOccurred()) {
479 // C++2a [temp.constr.atomic]p1
480 // ...If substitution results in an invalid type or expression, the
481 // constraint is not satisfied.
482 if (!Trap.hasErrorOccurred())
483 // A non-SFINAE error has occurred as a result of this
484 // substitution.
485 return ExprError();
486
489 Info.takeSFINAEDiagnostic(SubstDiag);
490 // FIXME: Concepts: This is an unfortunate consequence of there
491 // being no serialization code for PartialDiagnostics and the fact
492 // that serializing them would likely take a lot more storage than
493 // just storing them as strings. We would still like, in the
494 // future, to serialize the proper PartialDiagnostic as serializing
495 // it as a string defeats the purpose of the diagnostic mechanism.
496 SmallString<128> DiagString;
497 DiagString = ": ";
498 SubstDiag.second.EmitToString(S.getDiagnostics(), DiagString);
499 unsigned MessageSize = DiagString.size();
500 char *Mem = new (S.Context) char[MessageSize];
501 memcpy(Mem, DiagString.c_str(), MessageSize);
502 Satisfaction.Details.emplace_back(
504 SubstDiag.first, StringRef(Mem, MessageSize)});
505 Satisfaction.IsSatisfied = false;
506 return ExprEmpty();
507 }
508 }
509
510 if (!S.CheckConstraintExpression(SubstitutedExpression.get()))
511 return ExprError();
512
513 // [temp.constr.atomic]p3: To determine if an atomic constraint is
514 // satisfied, the parameter mapping and template arguments are first
515 // substituted into its expression. If substitution results in an
516 // invalid type or expression, the constraint is not satisfied.
517 // Otherwise, the lvalue-to-rvalue conversion is performed if necessary,
518 // and E shall be a constant expression of type bool.
519 //
520 // Perform the L to R Value conversion if necessary. We do so for all
521 // non-PRValue categories, else we fail to extend the lifetime of
522 // temporaries, and that fails the constant expression check.
523 if (!SubstitutedExpression.get()->isPRValue())
524 SubstitutedExpression = ImplicitCastExpr::Create(
525 S.Context, SubstitutedExpression.get()->getType(),
526 CK_LValueToRValue, SubstitutedExpression.get(),
527 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
528
529 return SubstitutedExpression;
530 }
531
532 std::optional<unsigned>
533 EvaluateFoldExpandedConstraintSize(const CXXFoldExpr *FE) const {
534
535 // We should ignore errors in the presence of packs of different size.
536 Sema::SFINAETrap Trap(S);
537
538 Expr *Pattern = FE->getPattern();
539
541 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
542 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
543 bool Expand = true;
544 bool RetainExpansion = false;
545 std::optional<unsigned> OrigNumExpansions = FE->getNumExpansions(),
546 NumExpansions = OrigNumExpansions;
548 FE->getEllipsisLoc(), Pattern->getSourceRange(), Unexpanded,
549 MLTAL, Expand, RetainExpansion, NumExpansions) ||
550 !Expand || RetainExpansion)
551 return std::nullopt;
552
553 if (NumExpansions && S.getLangOpts().BracketDepth < NumExpansions) {
554 S.Diag(FE->getEllipsisLoc(),
555 clang::diag::err_fold_expression_limit_exceeded)
556 << *NumExpansions << S.getLangOpts().BracketDepth
557 << FE->getSourceRange();
558 S.Diag(FE->getEllipsisLoc(), diag::note_bracket_depth);
559 return std::nullopt;
560 }
561 return NumExpansions;
562 }
563 };
564
566 S, ConstraintExpr, Satisfaction,
567 ConstraintEvaluator{S, Template, TemplateNameLoc, MLTAL, Satisfaction});
568}
569
571 Sema &S, const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
573 const MultiLevelTemplateArgumentList &TemplateArgsLists,
574 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction) {
575 if (ConstraintExprs.empty()) {
576 Satisfaction.IsSatisfied = true;
577 return false;
578 }
579
580 if (TemplateArgsLists.isAnyArgInstantiationDependent()) {
581 // No need to check satisfaction for dependent constraint expressions.
582 Satisfaction.IsSatisfied = true;
583 return false;
584 }
585
586 ArrayRef<TemplateArgument> TemplateArgs =
587 TemplateArgsLists.getNumSubstitutedLevels() > 0
588 ? TemplateArgsLists.getOutermost()
590 Sema::InstantiatingTemplate Inst(S, TemplateIDRange.getBegin(),
592 const_cast<NamedDecl *>(Template), TemplateArgs, TemplateIDRange);
593 if (Inst.isInvalid())
594 return true;
595
596 for (const Expr *ConstraintExpr : ConstraintExprs) {
598 S, Template, TemplateIDRange.getBegin(), TemplateArgsLists,
599 ConstraintExpr, Satisfaction);
600 if (Res.isInvalid())
601 return true;
602
603 Converted.push_back(Res.get());
604 if (!Satisfaction.IsSatisfied) {
605 // Backfill the 'converted' list with nulls so we can keep the Converted
606 // and unconverted lists in sync.
607 Converted.append(ConstraintExprs.size() - Converted.size(), nullptr);
608 // [temp.constr.op] p2
609 // [...] To determine if a conjunction is satisfied, the satisfaction
610 // of the first operand is checked. If that is not satisfied, the
611 // conjunction is not satisfied. [...]
612 return false;
613 }
614 }
615 return false;
616}
617
619 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
620 llvm::SmallVectorImpl<Expr *> &ConvertedConstraints,
621 const MultiLevelTemplateArgumentList &TemplateArgsLists,
622 SourceRange TemplateIDRange, ConstraintSatisfaction &OutSatisfaction) {
623 if (ConstraintExprs.empty()) {
624 OutSatisfaction.IsSatisfied = true;
625 return false;
626 }
627 if (!Template) {
628 return ::CheckConstraintSatisfaction(
629 *this, nullptr, ConstraintExprs, ConvertedConstraints,
630 TemplateArgsLists, TemplateIDRange, OutSatisfaction);
631 }
632 // Invalid templates could make their way here. Substituting them could result
633 // in dependent expressions.
634 if (Template->isInvalidDecl()) {
635 OutSatisfaction.IsSatisfied = false;
636 return true;
637 }
638
639 // A list of the template argument list flattened in a predictible manner for
640 // the purposes of caching. The ConstraintSatisfaction type is in AST so it
641 // has no access to the MultiLevelTemplateArgumentList, so this has to happen
642 // here.
644 for (auto List : TemplateArgsLists)
645 FlattenedArgs.insert(FlattenedArgs.end(), List.Args.begin(),
646 List.Args.end());
647
648 llvm::FoldingSetNodeID ID;
649 ConstraintSatisfaction::Profile(ID, Context, Template, FlattenedArgs);
650 void *InsertPos;
651 if (auto *Cached = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos)) {
652 OutSatisfaction = *Cached;
653 return false;
654 }
655
656 auto Satisfaction =
657 std::make_unique<ConstraintSatisfaction>(Template, FlattenedArgs);
658 if (::CheckConstraintSatisfaction(*this, Template, ConstraintExprs,
659 ConvertedConstraints, TemplateArgsLists,
660 TemplateIDRange, *Satisfaction)) {
661 OutSatisfaction = *Satisfaction;
662 return true;
663 }
664
665 if (auto *Cached = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos)) {
666 // The evaluation of this constraint resulted in us trying to re-evaluate it
667 // recursively. This isn't really possible, except we try to form a
668 // RecoveryExpr as a part of the evaluation. If this is the case, just
669 // return the 'cached' version (which will have the same result), and save
670 // ourselves the extra-insert. If it ever becomes possible to legitimately
671 // recursively check a constraint, we should skip checking the 'inner' one
672 // above, and replace the cached version with this one, as it would be more
673 // specific.
674 OutSatisfaction = *Cached;
675 return false;
676 }
677
678 // Else we can simply add this satisfaction to the list.
679 OutSatisfaction = *Satisfaction;
680 // We cannot use InsertPos here because CheckConstraintSatisfaction might have
681 // invalidated it.
682 // Note that entries of SatisfactionCache are deleted in Sema's destructor.
683 SatisfactionCache.InsertNode(Satisfaction.release());
684 return false;
685}
686
687bool Sema::CheckConstraintSatisfaction(const Expr *ConstraintExpr,
688 ConstraintSatisfaction &Satisfaction) {
689
690 struct ConstraintEvaluator {
691 Sema &S;
692 ExprResult EvaluateAtomicConstraint(const Expr *AtomicExpr) const {
693 return S.PerformContextuallyConvertToBool(const_cast<Expr *>(AtomicExpr));
694 }
695
696 std::optional<unsigned>
697 EvaluateFoldExpandedConstraintSize(const CXXFoldExpr *FE) const {
698 return 0;
699 }
700 };
701
702 return calculateConstraintSatisfaction(*this, ConstraintExpr, Satisfaction,
703 ConstraintEvaluator{*this})
704 .isInvalid();
705}
706
707bool Sema::addInstantiatedCapturesToScope(
708 FunctionDecl *Function, const FunctionDecl *PatternDecl,
710 const MultiLevelTemplateArgumentList &TemplateArgs) {
711 const auto *LambdaClass = cast<CXXMethodDecl>(Function)->getParent();
712 const auto *LambdaPattern = cast<CXXMethodDecl>(PatternDecl)->getParent();
713
714 unsigned Instantiated = 0;
715
716 auto AddSingleCapture = [&](const ValueDecl *CapturedPattern,
717 unsigned Index) {
718 ValueDecl *CapturedVar = LambdaClass->getCapture(Index)->getCapturedVar();
719 assert(CapturedVar->isInitCapture());
720 Scope.InstantiatedLocal(CapturedPattern, CapturedVar);
721 };
722
723 for (const LambdaCapture &CapturePattern : LambdaPattern->captures()) {
724 if (!CapturePattern.capturesVariable()) {
725 Instantiated++;
726 continue;
727 }
728 ValueDecl *CapturedPattern = CapturePattern.getCapturedVar();
729
730 if (!CapturedPattern->isInitCapture()) {
731 continue;
732 }
733
734 if (!CapturedPattern->isParameterPack()) {
735 AddSingleCapture(CapturedPattern, Instantiated++);
736 } else {
737 Scope.MakeInstantiatedLocalArgPack(CapturedPattern);
740 dyn_cast<VarDecl>(CapturedPattern)->getInit(), Unexpanded);
741 auto NumArgumentsInExpansion =
742 getNumArgumentsInExpansionFromUnexpanded(Unexpanded, TemplateArgs);
743 if (!NumArgumentsInExpansion)
744 continue;
745 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg)
746 AddSingleCapture(CapturedPattern, Instantiated++);
747 }
748 }
749 return false;
750}
751
752bool Sema::SetupConstraintScope(
753 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
756 if (FD->isTemplateInstantiation() && FD->getPrimaryTemplate()) {
757 FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
758 InstantiatingTemplate Inst(
759 *this, FD->getPointOfInstantiation(),
761 TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
762 SourceRange());
763 if (Inst.isInvalid())
764 return true;
765
766 // addInstantiatedParametersToScope creates a map of 'uninstantiated' to
767 // 'instantiated' parameters and adds it to the context. For the case where
768 // this function is a template being instantiated NOW, we also need to add
769 // the list of current template arguments to the list so that they also can
770 // be picked out of the map.
771 if (auto *SpecArgs = FD->getTemplateSpecializationArgs()) {
772 MultiLevelTemplateArgumentList JustTemplArgs(FD, SpecArgs->asArray(),
773 /*Final=*/false);
774 if (addInstantiatedParametersToScope(
775 FD, PrimaryTemplate->getTemplatedDecl(), Scope, JustTemplArgs))
776 return true;
777 }
778
779 // If this is a member function, make sure we get the parameters that
780 // reference the original primary template.
781 // We walk up the instantiated template chain so that nested lambdas get
782 // handled properly.
783 // We should only collect instantiated parameters from the primary template.
784 // Otherwise, we may have mismatched template parameter depth!
785 if (FunctionTemplateDecl *FromMemTempl =
786 PrimaryTemplate->getInstantiatedFromMemberTemplate()) {
787 while (FromMemTempl->getInstantiatedFromMemberTemplate())
788 FromMemTempl = FromMemTempl->getInstantiatedFromMemberTemplate();
789 if (addInstantiatedParametersToScope(FD, FromMemTempl->getTemplatedDecl(),
790 Scope, MLTAL))
791 return true;
792 }
793
794 return false;
795 }
796
799 FunctionDecl *InstantiatedFrom =
803
804 InstantiatingTemplate Inst(
805 *this, FD->getPointOfInstantiation(),
807 TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
808 SourceRange());
809 if (Inst.isInvalid())
810 return true;
811
812 // Case where this was not a template, but instantiated as a
813 // child-function.
814 if (addInstantiatedParametersToScope(FD, InstantiatedFrom, Scope, MLTAL))
815 return true;
816 }
817
818 return false;
819}
820
821// This function collects all of the template arguments for the purposes of
822// constraint-instantiation and checking.
823std::optional<MultiLevelTemplateArgumentList>
824Sema::SetupConstraintCheckingTemplateArgumentsAndScope(
825 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
828
829 // Collect the list of template arguments relative to the 'primary' template.
830 // We need the entire list, since the constraint is completely uninstantiated
831 // at this point.
832 MLTAL =
834 /*Final=*/false, /*Innermost=*/std::nullopt,
835 /*RelativeToPrimary=*/true,
836 /*Pattern=*/nullptr,
837 /*ForConstraintInstantiation=*/true);
838 if (SetupConstraintScope(FD, TemplateArgs, MLTAL, Scope))
839 return std::nullopt;
840
841 return MLTAL;
842}
843
845 ConstraintSatisfaction &Satisfaction,
846 SourceLocation UsageLoc,
847 bool ForOverloadResolution) {
848 // Don't check constraints if the function is dependent. Also don't check if
849 // this is a function template specialization, as the call to
850 // CheckinstantiatedFunctionTemplateConstraints after this will check it
851 // better.
852 if (FD->isDependentContext() ||
853 FD->getTemplatedKind() ==
855 Satisfaction.IsSatisfied = true;
856 return false;
857 }
858
859 // A lambda conversion operator has the same constraints as the call operator
860 // and constraints checking relies on whether we are in a lambda call operator
861 // (and may refer to its parameters), so check the call operator instead.
862 // Note that the declarations outside of the lambda should also be
863 // considered. Turning on the 'ForOverloadResolution' flag results in the
864 // LocalInstantiationScope not looking into its parents, but we can still
865 // access Decls from the parents while building a lambda RAII scope later.
866 if (const auto *MD = dyn_cast<CXXConversionDecl>(FD);
867 MD && isLambdaConversionOperator(const_cast<CXXConversionDecl *>(MD)))
868 return CheckFunctionConstraints(MD->getParent()->getLambdaCallOperator(),
869 Satisfaction, UsageLoc,
870 /*ShouldAddDeclsFromParentScope=*/true);
871
872 DeclContext *CtxToSave = const_cast<FunctionDecl *>(FD);
873
874 while (isLambdaCallOperator(CtxToSave) || FD->isTransparentContext()) {
875 if (isLambdaCallOperator(CtxToSave))
876 CtxToSave = CtxToSave->getParent()->getParent();
877 else
878 CtxToSave = CtxToSave->getNonTransparentContext();
879 }
880
881 ContextRAII SavedContext{*this, CtxToSave};
882 LocalInstantiationScope Scope(*this, !ForOverloadResolution);
883 std::optional<MultiLevelTemplateArgumentList> MLTAL =
884 SetupConstraintCheckingTemplateArgumentsAndScope(
885 const_cast<FunctionDecl *>(FD), {}, Scope);
886
887 if (!MLTAL)
888 return true;
889
890 Qualifiers ThisQuals;
891 CXXRecordDecl *Record = nullptr;
892 if (auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
893 ThisQuals = Method->getMethodQualifiers();
894 Record = const_cast<CXXRecordDecl *>(Method->getParent());
895 }
896 CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
897
899 *this, const_cast<FunctionDecl *>(FD), *MLTAL, Scope,
900 ForOverloadResolution);
901
903 FD, {FD->getTrailingRequiresClause()}, *MLTAL,
904 SourceRange(UsageLoc.isValid() ? UsageLoc : FD->getLocation()),
905 Satisfaction);
906}
907
908
909// Figure out the to-translation-unit depth for this function declaration for
910// the purpose of seeing if they differ by constraints. This isn't the same as
911// getTemplateDepth, because it includes already instantiated parents.
912static unsigned
914 bool SkipForSpecialization = false) {
916 ND, ND->getLexicalDeclContext(), /*Final=*/false,
917 /*Innermost=*/std::nullopt,
918 /*RelativeToPrimary=*/true,
919 /*Pattern=*/nullptr,
920 /*ForConstraintInstantiation=*/true, SkipForSpecialization);
921 return MLTAL.getNumLevels();
922}
923
924namespace {
925 class AdjustConstraintDepth : public TreeTransform<AdjustConstraintDepth> {
926 unsigned TemplateDepth = 0;
927 public:
928 using inherited = TreeTransform<AdjustConstraintDepth>;
929 AdjustConstraintDepth(Sema &SemaRef, unsigned TemplateDepth)
930 : inherited(SemaRef), TemplateDepth(TemplateDepth) {}
931
932 using inherited::TransformTemplateTypeParmType;
933 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
934 TemplateTypeParmTypeLoc TL, bool) {
935 const TemplateTypeParmType *T = TL.getTypePtr();
936
937 TemplateTypeParmDecl *NewTTPDecl = nullptr;
938 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
939 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
940 TransformDecl(TL.getNameLoc(), OldTTPDecl));
941
942 QualType Result = getSema().Context.getTemplateTypeParmType(
943 T->getDepth() + TemplateDepth, T->getIndex(), T->isParameterPack(),
944 NewTTPDecl);
946 NewTL.setNameLoc(TL.getNameLoc());
947 return Result;
948 }
949 };
950} // namespace
951
953 Sema &S, const Sema::TemplateCompareNewDeclInfo &DeclInfo,
954 const Expr *ConstrExpr) {
956 DeclInfo.getDecl(), DeclInfo.getLexicalDeclContext(), /*Final=*/false,
957 /*Innermost=*/std::nullopt,
958 /*RelativeToPrimary=*/true,
959 /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
960 /*SkipForSpecialization*/ false);
961
962 if (MLTAL.getNumSubstitutedLevels() == 0)
963 return ConstrExpr;
964
965 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
966
968 S, DeclInfo.getLocation(),
970 const_cast<NamedDecl *>(DeclInfo.getDecl()), SourceRange{});
971 if (Inst.isInvalid())
972 return nullptr;
973
974 // Set up a dummy 'instantiation' scope in the case of reference to function
975 // parameters that the surrounding function hasn't been instantiated yet. Note
976 // this may happen while we're comparing two templates' constraint
977 // equivalence.
978 LocalInstantiationScope ScopeForParameters(S);
979 if (auto *FD = DeclInfo.getDecl()->getAsFunction())
980 for (auto *PVD : FD->parameters())
981 ScopeForParameters.InstantiatedLocal(PVD, PVD);
982
983 std::optional<Sema::CXXThisScopeRAII> ThisScope;
984
985 // See TreeTransform::RebuildTemplateSpecializationType. A context scope is
986 // essential for having an injected class as the canonical type for a template
987 // specialization type at the rebuilding stage. This guarantees that, for
988 // out-of-line definitions, injected class name types and their equivalent
989 // template specializations can be profiled to the same value, which makes it
990 // possible that e.g. constraints involving C<Class<T>> and C<Class> are
991 // perceived identical.
992 std::optional<Sema::ContextRAII> ContextScope;
993 if (auto *RD = dyn_cast<CXXRecordDecl>(DeclInfo.getDeclContext())) {
994 ThisScope.emplace(S, const_cast<CXXRecordDecl *>(RD), Qualifiers());
995 ContextScope.emplace(S, const_cast<DeclContext *>(cast<DeclContext>(RD)),
996 /*NewThisContext=*/false);
997 }
999 const_cast<clang::Expr *>(ConstrExpr), MLTAL);
1000 if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
1001 return nullptr;
1002 return SubstConstr.get();
1003}
1004
1006 const Expr *OldConstr,
1007 const TemplateCompareNewDeclInfo &New,
1008 const Expr *NewConstr) {
1009 if (OldConstr == NewConstr)
1010 return true;
1011 // C++ [temp.constr.decl]p4
1012 if (Old && !New.isInvalid() && !New.ContainsDecl(Old) &&
1014 if (const Expr *SubstConstr =
1016 OldConstr))
1017 OldConstr = SubstConstr;
1018 else
1019 return false;
1020 if (const Expr *SubstConstr =
1022 NewConstr))
1023 NewConstr = SubstConstr;
1024 else
1025 return false;
1026 }
1027
1028 llvm::FoldingSetNodeID ID1, ID2;
1029 OldConstr->Profile(ID1, Context, /*Canonical=*/true);
1030 NewConstr->Profile(ID2, Context, /*Canonical=*/true);
1031 return ID1 == ID2;
1032}
1033
1035 assert(FD->getFriendObjectKind() && "Must be a friend!");
1036
1037 // The logic for non-templates is handled in ASTContext::isSameEntity, so we
1038 // don't have to bother checking 'DependsOnEnclosingTemplate' for a
1039 // non-function-template.
1040 assert(FD->getDescribedFunctionTemplate() &&
1041 "Non-function templates don't need to be checked");
1042
1045
1046 unsigned OldTemplateDepth = CalculateTemplateDepthForConstraints(*this, FD);
1047 for (const Expr *Constraint : ACs)
1048 if (ConstraintExpressionDependsOnEnclosingTemplate(FD, OldTemplateDepth,
1049 Constraint))
1050 return true;
1051
1052 return false;
1053}
1054
1056 TemplateDecl *TD, const MultiLevelTemplateArgumentList &TemplateArgsLists,
1057 SourceRange TemplateIDRange) {
1058 ConstraintSatisfaction Satisfaction;
1059 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
1060 TD->getAssociatedConstraints(AssociatedConstraints);
1061 if (CheckConstraintSatisfaction(TD, AssociatedConstraints, TemplateArgsLists,
1062 TemplateIDRange, Satisfaction))
1063 return true;
1064
1065 if (!Satisfaction.IsSatisfied) {
1066 SmallString<128> TemplateArgString;
1067 TemplateArgString = " ";
1068 TemplateArgString += getTemplateArgumentBindingsText(
1069 TD->getTemplateParameters(), TemplateArgsLists.getInnermost().data(),
1070 TemplateArgsLists.getInnermost().size());
1071
1072 Diag(TemplateIDRange.getBegin(),
1073 diag::err_template_arg_list_constraints_not_satisfied)
1075 << TemplateArgString << TemplateIDRange;
1076 DiagnoseUnsatisfiedConstraint(Satisfaction);
1077 return true;
1078 }
1079 return false;
1080}
1081
1083 SourceLocation PointOfInstantiation, FunctionDecl *Decl,
1084 ArrayRef<TemplateArgument> TemplateArgs,
1085 ConstraintSatisfaction &Satisfaction) {
1086 // In most cases we're not going to have constraints, so check for that first.
1087 FunctionTemplateDecl *Template = Decl->getPrimaryTemplate();
1088 // Note - code synthesis context for the constraints check is created
1089 // inside CheckConstraintsSatisfaction.
1091 Template->getAssociatedConstraints(TemplateAC);
1092 if (TemplateAC.empty()) {
1093 Satisfaction.IsSatisfied = true;
1094 return false;
1095 }
1096
1097 // Enter the scope of this instantiation. We don't use
1098 // PushDeclContext because we don't have a scope.
1099 Sema::ContextRAII savedContext(*this, Decl);
1101
1102 std::optional<MultiLevelTemplateArgumentList> MLTAL =
1103 SetupConstraintCheckingTemplateArgumentsAndScope(Decl, TemplateArgs,
1104 Scope);
1105
1106 if (!MLTAL)
1107 return true;
1108
1109 Qualifiers ThisQuals;
1110 CXXRecordDecl *Record = nullptr;
1111 if (auto *Method = dyn_cast<CXXMethodDecl>(Decl)) {
1112 ThisQuals = Method->getMethodQualifiers();
1113 Record = Method->getParent();
1114 }
1115
1116 CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
1118 *this, const_cast<FunctionDecl *>(Decl), *MLTAL, Scope);
1119
1121 return CheckConstraintSatisfaction(Template, TemplateAC, Converted, *MLTAL,
1122 PointOfInstantiation, Satisfaction);
1123}
1124
1127 bool First) {
1128 assert(!Req->isSatisfied()
1129 && "Diagnose() can only be used on an unsatisfied requirement");
1130 switch (Req->getSatisfactionStatus()) {
1132 llvm_unreachable("Diagnosing a dependent requirement");
1133 break;
1135 auto *SubstDiag = Req->getExprSubstitutionDiagnostic();
1136 if (!SubstDiag->DiagMessage.empty())
1137 S.Diag(SubstDiag->DiagLoc,
1138 diag::note_expr_requirement_expr_substitution_error)
1139 << (int)First << SubstDiag->SubstitutedEntity
1140 << SubstDiag->DiagMessage;
1141 else
1142 S.Diag(SubstDiag->DiagLoc,
1143 diag::note_expr_requirement_expr_unknown_substitution_error)
1144 << (int)First << SubstDiag->SubstitutedEntity;
1145 break;
1146 }
1148 S.Diag(Req->getNoexceptLoc(),
1149 diag::note_expr_requirement_noexcept_not_met)
1150 << (int)First << Req->getExpr();
1151 break;
1153 auto *SubstDiag =
1155 if (!SubstDiag->DiagMessage.empty())
1156 S.Diag(SubstDiag->DiagLoc,
1157 diag::note_expr_requirement_type_requirement_substitution_error)
1158 << (int)First << SubstDiag->SubstitutedEntity
1159 << SubstDiag->DiagMessage;
1160 else
1161 S.Diag(SubstDiag->DiagLoc,
1162 diag::note_expr_requirement_type_requirement_unknown_substitution_error)
1163 << (int)First << SubstDiag->SubstitutedEntity;
1164 break;
1165 }
1167 ConceptSpecializationExpr *ConstraintExpr =
1169 if (ConstraintExpr->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
1170 // A simple case - expr type is the type being constrained and the concept
1171 // was not provided arguments.
1172 Expr *e = Req->getExpr();
1173 S.Diag(e->getBeginLoc(),
1174 diag::note_expr_requirement_constraints_not_satisfied_simple)
1176 << ConstraintExpr->getNamedConcept();
1177 } else {
1178 S.Diag(ConstraintExpr->getBeginLoc(),
1179 diag::note_expr_requirement_constraints_not_satisfied)
1180 << (int)First << ConstraintExpr;
1181 }
1183 break;
1184 }
1186 llvm_unreachable("We checked this above");
1187 }
1188}
1189
1192 bool First) {
1193 assert(!Req->isSatisfied()
1194 && "Diagnose() can only be used on an unsatisfied requirement");
1195 switch (Req->getSatisfactionStatus()) {
1197 llvm_unreachable("Diagnosing a dependent requirement");
1198 return;
1200 auto *SubstDiag = Req->getSubstitutionDiagnostic();
1201 if (!SubstDiag->DiagMessage.empty())
1202 S.Diag(SubstDiag->DiagLoc,
1203 diag::note_type_requirement_substitution_error) << (int)First
1204 << SubstDiag->SubstitutedEntity << SubstDiag->DiagMessage;
1205 else
1206 S.Diag(SubstDiag->DiagLoc,
1207 diag::note_type_requirement_unknown_substitution_error)
1208 << (int)First << SubstDiag->SubstitutedEntity;
1209 return;
1210 }
1211 default:
1212 llvm_unreachable("Unknown satisfaction status");
1213 return;
1214 }
1215}
1217 Expr *SubstExpr,
1218 bool First = true);
1219
1222 bool First) {
1223 using SubstitutionDiagnostic = std::pair<SourceLocation, StringRef>;
1224 for (auto &Record : Req->getConstraintSatisfaction()) {
1225 if (auto *SubstDiag = Record.dyn_cast<SubstitutionDiagnostic *>())
1226 S.Diag(SubstDiag->first, diag::note_nested_requirement_substitution_error)
1228 << SubstDiag->second;
1229 else
1231 First);
1232 First = false;
1233 }
1234}
1235
1237 Expr *SubstExpr,
1238 bool First) {
1239 SubstExpr = SubstExpr->IgnoreParenImpCasts();
1240 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SubstExpr)) {
1241 switch (BO->getOpcode()) {
1242 // These two cases will in practice only be reached when using fold
1243 // expressions with || and &&, since otherwise the || and && will have been
1244 // broken down into atomic constraints during satisfaction checking.
1245 case BO_LOr:
1246 // Or evaluated to false - meaning both RHS and LHS evaluated to false.
1249 /*First=*/false);
1250 return;
1251 case BO_LAnd: {
1252 bool LHSSatisfied =
1253 BO->getLHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
1254 if (LHSSatisfied) {
1255 // LHS is true, so RHS must be false.
1257 return;
1258 }
1259 // LHS is false
1261
1262 // RHS might also be false
1263 bool RHSSatisfied =
1264 BO->getRHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
1265 if (!RHSSatisfied)
1267 /*First=*/false);
1268 return;
1269 }
1270 case BO_GE:
1271 case BO_LE:
1272 case BO_GT:
1273 case BO_LT:
1274 case BO_EQ:
1275 case BO_NE:
1276 if (BO->getLHS()->getType()->isIntegerType() &&
1277 BO->getRHS()->getType()->isIntegerType()) {
1278 Expr::EvalResult SimplifiedLHS;
1279 Expr::EvalResult SimplifiedRHS;
1280 BO->getLHS()->EvaluateAsInt(SimplifiedLHS, S.Context,
1282 /*InConstantContext=*/true);
1283 BO->getRHS()->EvaluateAsInt(SimplifiedRHS, S.Context,
1285 /*InConstantContext=*/true);
1286 if (!SimplifiedLHS.Diag && ! SimplifiedRHS.Diag) {
1287 S.Diag(SubstExpr->getBeginLoc(),
1288 diag::note_atomic_constraint_evaluated_to_false_elaborated)
1289 << (int)First << SubstExpr
1290 << toString(SimplifiedLHS.Val.getInt(), 10)
1291 << BinaryOperator::getOpcodeStr(BO->getOpcode())
1292 << toString(SimplifiedRHS.Val.getInt(), 10);
1293 return;
1294 }
1295 }
1296 break;
1297
1298 default:
1299 break;
1300 }
1301 } else if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(SubstExpr)) {
1302 if (CSE->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
1303 S.Diag(
1304 CSE->getSourceRange().getBegin(),
1305 diag::
1306 note_single_arg_concept_specialization_constraint_evaluated_to_false)
1307 << (int)First
1308 << CSE->getTemplateArgsAsWritten()->arguments()[0].getArgument()
1309 << CSE->getNamedConcept();
1310 } else {
1311 S.Diag(SubstExpr->getSourceRange().getBegin(),
1312 diag::note_concept_specialization_constraint_evaluated_to_false)
1313 << (int)First << CSE;
1314 }
1315 S.DiagnoseUnsatisfiedConstraint(CSE->getSatisfaction());
1316 return;
1317 } else if (auto *RE = dyn_cast<RequiresExpr>(SubstExpr)) {
1318 // FIXME: RequiresExpr should store dependent diagnostics.
1319 for (concepts::Requirement *Req : RE->getRequirements())
1320 if (!Req->isDependent() && !Req->isSatisfied()) {
1321 if (auto *E = dyn_cast<concepts::ExprRequirement>(Req))
1323 else if (auto *T = dyn_cast<concepts::TypeRequirement>(Req))
1325 else
1327 S, cast<concepts::NestedRequirement>(Req), First);
1328 break;
1329 }
1330 return;
1331 } else if (auto *TTE = dyn_cast<TypeTraitExpr>(SubstExpr);
1332 TTE && TTE->getTrait() == clang::TypeTrait::BTT_IsDeducible) {
1333 assert(TTE->getNumArgs() == 2);
1334 S.Diag(SubstExpr->getSourceRange().getBegin(),
1335 diag::note_is_deducible_constraint_evaluated_to_false)
1336 << TTE->getArg(0)->getType() << TTE->getArg(1)->getType();
1337 return;
1338 }
1339
1340 S.Diag(SubstExpr->getSourceRange().getBegin(),
1341 diag::note_atomic_constraint_evaluated_to_false)
1342 << (int)First << SubstExpr;
1343}
1344
1345template <typename SubstitutionDiagnostic>
1347 Sema &S, const llvm::PointerUnion<Expr *, SubstitutionDiagnostic *> &Record,
1348 bool First = true) {
1349 if (auto *Diag = Record.template dyn_cast<SubstitutionDiagnostic *>()) {
1350 S.Diag(Diag->first, diag::note_substituted_constraint_expr_is_ill_formed)
1351 << Diag->second;
1352 return;
1353 }
1354
1356 Record.template get<Expr *>(), First);
1357}
1358
1359void
1361 bool First) {
1362 assert(!Satisfaction.IsSatisfied &&
1363 "Attempted to diagnose a satisfied constraint");
1364 for (auto &Record : Satisfaction.Details) {
1366 First = false;
1367 }
1368}
1369
1371 const ASTConstraintSatisfaction &Satisfaction,
1372 bool First) {
1373 assert(!Satisfaction.IsSatisfied &&
1374 "Attempted to diagnose a satisfied constraint");
1375 for (auto &Record : Satisfaction) {
1377 First = false;
1378 }
1379}
1380
1383 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints) {
1384 // In case the ConstrainedDecl comes from modules, it is necessary to use
1385 // the canonical decl to avoid different atomic constraints with the 'same'
1386 // declarations.
1387 ConstrainedDecl = cast<NamedDecl>(ConstrainedDecl->getCanonicalDecl());
1388
1389 auto CacheEntry = NormalizationCache.find(ConstrainedDecl);
1390 if (CacheEntry == NormalizationCache.end()) {
1391 auto Normalized =
1392 NormalizedConstraint::fromConstraintExprs(*this, ConstrainedDecl,
1393 AssociatedConstraints);
1394 CacheEntry =
1395 NormalizationCache
1396 .try_emplace(ConstrainedDecl,
1397 Normalized
1399 std::move(*Normalized))
1400 : nullptr)
1401 .first;
1402 }
1403 return CacheEntry->second;
1404}
1405
1407 Sema &S, NamedDecl *ConstrainedDecl,
1408 ArrayRef<const Expr *> AssociatedConstraints) {
1409 return S.getNormalizedAssociatedConstraints(ConstrainedDecl,
1410 AssociatedConstraints);
1411}
1412
1413static bool
1415 ConceptDecl *Concept,
1416 const MultiLevelTemplateArgumentList &MLTAL,
1417 const ASTTemplateArgumentListInfo *ArgsAsWritten) {
1418
1419 if (N.isCompound()) {
1420 if (substituteParameterMappings(S, N.getLHS(), Concept, MLTAL,
1421 ArgsAsWritten))
1422 return true;
1423 return substituteParameterMappings(S, N.getRHS(), Concept, MLTAL,
1424 ArgsAsWritten);
1425 }
1426
1427 if (N.isFoldExpanded()) {
1430 S, N.getFoldExpandedConstraint()->Constraint, Concept, MLTAL,
1431 ArgsAsWritten);
1432 }
1433
1434 TemplateParameterList *TemplateParams = Concept->getTemplateParameters();
1435
1437 TemplateArgumentListInfo SubstArgs;
1438 if (!Atomic.ParameterMapping) {
1439 llvm::SmallBitVector OccurringIndices(TemplateParams->size());
1440 S.MarkUsedTemplateParameters(Atomic.ConstraintExpr, /*OnlyDeduced=*/false,
1441 /*Depth=*/0, OccurringIndices);
1442 TemplateArgumentLoc *TempArgs =
1443 new (S.Context) TemplateArgumentLoc[OccurringIndices.count()];
1444 for (unsigned I = 0, J = 0, C = TemplateParams->size(); I != C; ++I)
1445 if (OccurringIndices[I])
1446 new (&(TempArgs)[J++])
1448 TemplateParams->begin()[I],
1449 // Here we assume we do not support things like
1450 // template<typename A, typename B>
1451 // concept C = ...;
1452 //
1453 // template<typename... Ts> requires C<Ts...>
1454 // struct S { };
1455 // The above currently yields a diagnostic.
1456 // We still might have default arguments for concept parameters.
1457 ArgsAsWritten->NumTemplateArgs > I
1458 ? ArgsAsWritten->arguments()[I].getLocation()
1459 : SourceLocation()));
1460 Atomic.ParameterMapping.emplace(TempArgs, OccurringIndices.count());
1461 }
1462 SourceLocation InstLocBegin =
1463 ArgsAsWritten->arguments().empty()
1464 ? ArgsAsWritten->getLAngleLoc()
1465 : ArgsAsWritten->arguments().front().getSourceRange().getBegin();
1466 SourceLocation InstLocEnd =
1467 ArgsAsWritten->arguments().empty()
1468 ? ArgsAsWritten->getRAngleLoc()
1469 : ArgsAsWritten->arguments().front().getSourceRange().getEnd();
1471 S, InstLocBegin,
1473 Atomic.ConstraintDecl, {InstLocBegin, InstLocEnd});
1474 if (Inst.isInvalid())
1475 return true;
1476 if (S.SubstTemplateArguments(*Atomic.ParameterMapping, MLTAL, SubstArgs))
1477 return true;
1478
1479 TemplateArgumentLoc *TempArgs =
1480 new (S.Context) TemplateArgumentLoc[SubstArgs.size()];
1481 std::copy(SubstArgs.arguments().begin(), SubstArgs.arguments().end(),
1482 TempArgs);
1483 Atomic.ParameterMapping.emplace(TempArgs, SubstArgs.size());
1484 return false;
1485}
1486
1488 const ConceptSpecializationExpr *CSE) {
1491 /*Final=*/false, CSE->getTemplateArguments(),
1492 /*RelativeToPrimary=*/true,
1493 /*Pattern=*/nullptr,
1494 /*ForConstraintInstantiation=*/true);
1495
1496 return substituteParameterMappings(S, N, CSE->getNamedConcept(), MLTAL,
1498}
1499
1504 : Constraint{CompoundConstraint{
1505 new(C) NormalizedConstraintPair{std::move(LHS), std::move(RHS)},
1506 Kind}} {}
1507
1509 const NormalizedConstraint &Other) {
1510 if (Other.isAtomic()) {
1511 Constraint = new (C) AtomicConstraint(*Other.getAtomicConstraint());
1512 } else if (Other.isFoldExpanded()) {
1514 Other.getFoldExpandedConstraint()->Kind,
1515 NormalizedConstraint(C, Other.getFoldExpandedConstraint()->Constraint),
1516 Other.getFoldExpandedConstraint()->Pattern);
1517 } else {
1519 new (C)
1521 NormalizedConstraint(C, Other.getRHS())},
1522 Other.getCompoundKind());
1523 }
1524}
1525
1527 assert(isCompound() && "getLHS called on a non-compound constraint.");
1528 return Constraint.get<CompoundConstraint>().getPointer()->LHS;
1529}
1530
1532 assert(isCompound() && "getRHS called on a non-compound constraint.");
1533 return Constraint.get<CompoundConstraint>().getPointer()->RHS;
1534}
1535
1536std::optional<NormalizedConstraint>
1537NormalizedConstraint::fromConstraintExprs(Sema &S, NamedDecl *D,
1539 assert(E.size() != 0);
1540 auto Conjunction = fromConstraintExpr(S, D, E[0]);
1541 if (!Conjunction)
1542 return std::nullopt;
1543 for (unsigned I = 1; I < E.size(); ++I) {
1544 auto Next = fromConstraintExpr(S, D, E[I]);
1545 if (!Next)
1546 return std::nullopt;
1547 *Conjunction = NormalizedConstraint(S.Context, std::move(*Conjunction),
1548 std::move(*Next), CCK_Conjunction);
1549 }
1550 return Conjunction;
1551}
1552
1553std::optional<NormalizedConstraint>
1554NormalizedConstraint::fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E) {
1555 assert(E != nullptr);
1556
1557 // C++ [temp.constr.normal]p1.1
1558 // [...]
1559 // - The normal form of an expression (E) is the normal form of E.
1560 // [...]
1561 E = E->IgnoreParenImpCasts();
1562
1563 // C++2a [temp.param]p4:
1564 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1565 // Fold expression is considered atomic constraints per current wording.
1566 // See http://cplusplus.github.io/concepts-ts/ts-active.html#28
1567
1568 if (LogicalBinOp BO = E) {
1569 auto LHS = fromConstraintExpr(S, D, BO.getLHS());
1570 if (!LHS)
1571 return std::nullopt;
1572 auto RHS = fromConstraintExpr(S, D, BO.getRHS());
1573 if (!RHS)
1574 return std::nullopt;
1575
1576 return NormalizedConstraint(S.Context, std::move(*LHS), std::move(*RHS),
1577 BO.isAnd() ? CCK_Conjunction : CCK_Disjunction);
1578 } else if (auto *CSE = dyn_cast<const ConceptSpecializationExpr>(E)) {
1579 const NormalizedConstraint *SubNF;
1580 {
1582 S, CSE->getExprLoc(),
1584 CSE->getSourceRange());
1585 if (Inst.isInvalid())
1586 return std::nullopt;
1587 // C++ [temp.constr.normal]p1.1
1588 // [...]
1589 // The normal form of an id-expression of the form C<A1, A2, ..., AN>,
1590 // where C names a concept, is the normal form of the
1591 // constraint-expression of C, after substituting A1, A2, ..., AN for C’s
1592 // respective template parameters in the parameter mappings in each atomic
1593 // constraint. If any such substitution results in an invalid type or
1594 // expression, the program is ill-formed; no diagnostic is required.
1595 // [...]
1596 ConceptDecl *CD = CSE->getNamedConcept();
1598 {CD->getConstraintExpr()});
1599 if (!SubNF)
1600 return std::nullopt;
1601 }
1602
1603 std::optional<NormalizedConstraint> New;
1604 New.emplace(S.Context, *SubNF);
1605
1606 if (substituteParameterMappings(S, *New, CSE))
1607 return std::nullopt;
1608
1609 return New;
1610 } else if (auto *FE = dyn_cast<const CXXFoldExpr>(E);
1611 FE && S.getLangOpts().CPlusPlus26 &&
1612 (FE->getOperator() == BinaryOperatorKind::BO_LAnd ||
1613 FE->getOperator() == BinaryOperatorKind::BO_LOr)) {
1614
1615 // Normalize fold expressions in C++26.
1616
1618 FE->getOperator() == BinaryOperatorKind::BO_LAnd
1621
1622 if (FE->getInit()) {
1623 auto LHS = fromConstraintExpr(S, D, FE->getLHS());
1624 auto RHS = fromConstraintExpr(S, D, FE->getRHS());
1625 if (!LHS || !RHS)
1626 return std::nullopt;
1627
1628 if (FE->isRightFold())
1630 Kind, std::move(*RHS), FE->getPattern()}};
1631 else
1633 Kind, std::move(*LHS), FE->getPattern()}};
1634
1635 return NormalizedConstraint(
1636 S.Context, std::move(*LHS), std::move(*RHS),
1637 FE->getOperator() == BinaryOperatorKind::BO_LAnd ? CCK_Conjunction
1638 : CCK_Disjunction);
1639 }
1640 auto Sub = fromConstraintExpr(S, D, FE->getPattern());
1641 if (!Sub)
1642 return std::nullopt;
1644 Kind, std::move(*Sub), FE->getPattern()}};
1645 }
1646
1648}
1649
1652
1653 // [C++26] [temp.constr.fold]
1654 // Two fold expanded constraints are compatible for subsumption
1655 // if their respective constraints both contain an equivalent unexpanded pack.
1656
1658 Sema::collectUnexpandedParameterPacks(const_cast<Expr *>(A.Pattern), APacks);
1659 Sema::collectUnexpandedParameterPacks(const_cast<Expr *>(B.Pattern), BPacks);
1660
1661 for (const UnexpandedParameterPack &APack : APacks) {
1662 std::pair<unsigned, unsigned> DepthAndIndex = getDepthAndIndex(APack);
1663 auto it = llvm::find_if(BPacks, [&](const UnexpandedParameterPack &BPack) {
1664 return getDepthAndIndex(BPack) == DepthAndIndex;
1665 });
1666 if (it != BPacks.end())
1667 return true;
1668 }
1669 return false;
1670}
1671
1673 if (Normalized.isAtomic())
1674 return {{Normalized.getAtomicConstraint()}};
1675
1676 else if (Normalized.isFoldExpanded())
1677 return {{Normalized.getFoldExpandedConstraint()}};
1678
1679 NormalForm LCNF = makeCNF(Normalized.getLHS());
1680 NormalForm RCNF = makeCNF(Normalized.getRHS());
1682 LCNF.reserve(LCNF.size() + RCNF.size());
1683 while (!RCNF.empty())
1684 LCNF.push_back(RCNF.pop_back_val());
1685 return LCNF;
1686 }
1687
1688 // Disjunction
1689 NormalForm Res;
1690 Res.reserve(LCNF.size() * RCNF.size());
1691 for (auto &LDisjunction : LCNF)
1692 for (auto &RDisjunction : RCNF) {
1693 NormalForm::value_type Combined;
1694 Combined.reserve(LDisjunction.size() + RDisjunction.size());
1695 std::copy(LDisjunction.begin(), LDisjunction.end(),
1696 std::back_inserter(Combined));
1697 std::copy(RDisjunction.begin(), RDisjunction.end(),
1698 std::back_inserter(Combined));
1699 Res.emplace_back(Combined);
1700 }
1701 return Res;
1702}
1703
1705 if (Normalized.isAtomic())
1706 return {{Normalized.getAtomicConstraint()}};
1707
1708 else if (Normalized.isFoldExpanded())
1709 return {{Normalized.getFoldExpandedConstraint()}};
1710
1711 NormalForm LDNF = makeDNF(Normalized.getLHS());
1712 NormalForm RDNF = makeDNF(Normalized.getRHS());
1714 LDNF.reserve(LDNF.size() + RDNF.size());
1715 while (!RDNF.empty())
1716 LDNF.push_back(RDNF.pop_back_val());
1717 return LDNF;
1718 }
1719
1720 // Conjunction
1721 NormalForm Res;
1722 Res.reserve(LDNF.size() * RDNF.size());
1723 for (auto &LConjunction : LDNF) {
1724 for (auto &RConjunction : RDNF) {
1725 NormalForm::value_type Combined;
1726 Combined.reserve(LConjunction.size() + RConjunction.size());
1727 std::copy(LConjunction.begin(), LConjunction.end(),
1728 std::back_inserter(Combined));
1729 std::copy(RConjunction.begin(), RConjunction.end(),
1730 std::back_inserter(Combined));
1731 Res.emplace_back(Combined);
1732 }
1733 }
1734 return Res;
1735}
1736
1739 NamedDecl *D2,
1741 bool &Result) {
1742 if (const auto *FD1 = dyn_cast<FunctionDecl>(D1)) {
1743 auto IsExpectedEntity = [](const FunctionDecl *FD) {
1745 return Kind == FunctionDecl::TK_NonTemplate ||
1747 };
1748 const auto *FD2 = dyn_cast<FunctionDecl>(D2);
1749 (void)IsExpectedEntity;
1750 (void)FD1;
1751 (void)FD2;
1752 assert(IsExpectedEntity(FD1) && FD2 && IsExpectedEntity(FD2) &&
1753 "use non-instantiated function declaration for constraints partial "
1754 "ordering");
1755 }
1756
1757 if (AC1.empty()) {
1758 Result = AC2.empty();
1759 return false;
1760 }
1761 if (AC2.empty()) {
1762 // TD1 has associated constraints and TD2 does not.
1763 Result = true;
1764 return false;
1765 }
1766
1767 std::pair<NamedDecl *, NamedDecl *> Key{D1, D2};
1768 auto CacheEntry = SubsumptionCache.find(Key);
1769 if (CacheEntry != SubsumptionCache.end()) {
1770 Result = CacheEntry->second;
1771 return false;
1772 }
1773
1774 unsigned Depth1 = CalculateTemplateDepthForConstraints(*this, D1, true);
1775 unsigned Depth2 = CalculateTemplateDepthForConstraints(*this, D2, true);
1776
1777 for (size_t I = 0; I != AC1.size() && I != AC2.size(); ++I) {
1778 if (Depth2 > Depth1) {
1779 AC1[I] = AdjustConstraintDepth(*this, Depth2 - Depth1)
1780 .TransformExpr(const_cast<Expr *>(AC1[I]))
1781 .get();
1782 } else if (Depth1 > Depth2) {
1783 AC2[I] = AdjustConstraintDepth(*this, Depth1 - Depth2)
1784 .TransformExpr(const_cast<Expr *>(AC2[I]))
1785 .get();
1786 }
1787 }
1788
1789 if (clang::subsumes(
1790 *this, D1, AC1, D2, AC2, Result,
1791 [this](const AtomicConstraint &A, const AtomicConstraint &B) {
1792 return A.subsumes(Context, B);
1793 }))
1794 return true;
1795 SubsumptionCache.try_emplace(Key, Result);
1796 return false;
1797}
1798
1801 if (isSFINAEContext())
1802 // No need to work here because our notes would be discarded.
1803 return false;
1804
1805 if (AC1.empty() || AC2.empty())
1806 return false;
1807
1808 auto NormalExprEvaluator =
1809 [this] (const AtomicConstraint &A, const AtomicConstraint &B) {
1810 return A.subsumes(Context, B);
1811 };
1812
1813 const Expr *AmbiguousAtomic1 = nullptr, *AmbiguousAtomic2 = nullptr;
1814 auto IdenticalExprEvaluator =
1815 [&] (const AtomicConstraint &A, const AtomicConstraint &B) {
1817 return false;
1818 const Expr *EA = A.ConstraintExpr, *EB = B.ConstraintExpr;
1819 if (EA == EB)
1820 return true;
1821
1822 // Not the same source level expression - are the expressions
1823 // identical?
1824 llvm::FoldingSetNodeID IDA, IDB;
1825 EA->Profile(IDA, Context, /*Canonical=*/true);
1826 EB->Profile(IDB, Context, /*Canonical=*/true);
1827 if (IDA != IDB)
1828 return false;
1829
1830 AmbiguousAtomic1 = EA;
1831 AmbiguousAtomic2 = EB;
1832 return true;
1833 };
1834
1835 {
1836 // The subsumption checks might cause diagnostics
1837 SFINAETrap Trap(*this);
1838 auto *Normalized1 = getNormalizedAssociatedConstraints(D1, AC1);
1839 if (!Normalized1)
1840 return false;
1841 const NormalForm DNF1 = makeDNF(*Normalized1);
1842 const NormalForm CNF1 = makeCNF(*Normalized1);
1843
1844 auto *Normalized2 = getNormalizedAssociatedConstraints(D2, AC2);
1845 if (!Normalized2)
1846 return false;
1847 const NormalForm DNF2 = makeDNF(*Normalized2);
1848 const NormalForm CNF2 = makeCNF(*Normalized2);
1849
1850 bool Is1AtLeastAs2Normally =
1851 clang::subsumes(DNF1, CNF2, NormalExprEvaluator);
1852 bool Is2AtLeastAs1Normally =
1853 clang::subsumes(DNF2, CNF1, NormalExprEvaluator);
1854 bool Is1AtLeastAs2 = clang::subsumes(DNF1, CNF2, IdenticalExprEvaluator);
1855 bool Is2AtLeastAs1 = clang::subsumes(DNF2, CNF1, IdenticalExprEvaluator);
1856 if (Is1AtLeastAs2 == Is1AtLeastAs2Normally &&
1857 Is2AtLeastAs1 == Is2AtLeastAs1Normally)
1858 // Same result - no ambiguity was caused by identical atomic expressions.
1859 return false;
1860 }
1861
1862 // A different result! Some ambiguous atomic constraint(s) caused a difference
1863 assert(AmbiguousAtomic1 && AmbiguousAtomic2);
1864
1865 Diag(AmbiguousAtomic1->getBeginLoc(), diag::note_ambiguous_atomic_constraints)
1866 << AmbiguousAtomic1->getSourceRange();
1867 Diag(AmbiguousAtomic2->getBeginLoc(),
1868 diag::note_ambiguous_atomic_constraints_similar_expression)
1869 << AmbiguousAtomic2->getSourceRange();
1870 return true;
1871}
1872
1874 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
1876 ConceptSpecializationExpr *SubstitutedConstraintExpr) :
1877 Requirement(IsSimple ? RK_Simple : RK_Compound, Status == SS_Dependent,
1878 Status == SS_Dependent &&
1879 (E->containsUnexpandedParameterPack() ||
1880 Req.containsUnexpandedParameterPack()),
1881 Status == SS_Satisfied), Value(E), NoexceptLoc(NoexceptLoc),
1882 TypeReq(Req), SubstitutedConstraintExpr(SubstitutedConstraintExpr),
1883 Status(Status) {
1884 assert((!IsSimple || (Req.isEmpty() && NoexceptLoc.isInvalid())) &&
1885 "Simple requirement must not have a return type requirement or a "
1886 "noexcept specification");
1887 assert((Status > SS_TypeRequirementSubstitutionFailure && Req.isTypeConstraint()) ==
1888 (SubstitutedConstraintExpr != nullptr));
1889}
1890
1892 SubstitutionDiagnostic *ExprSubstDiag, bool IsSimple,
1893 SourceLocation NoexceptLoc, ReturnTypeRequirement Req) :
1894 Requirement(IsSimple ? RK_Simple : RK_Compound, Req.isDependent(),
1895 Req.containsUnexpandedParameterPack(), /*IsSatisfied=*/false),
1896 Value(ExprSubstDiag), NoexceptLoc(NoexceptLoc), TypeReq(Req),
1897 Status(SS_ExprSubstitutionFailure) {
1898 assert((!IsSimple || (Req.isEmpty() && NoexceptLoc.isInvalid())) &&
1899 "Simple requirement must not have a return type requirement or a "
1900 "noexcept specification");
1901}
1902
1905 TypeConstraintInfo(TPL, false) {
1906 assert(TPL->size() == 1);
1907 const TypeConstraint *TC =
1908 cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint();
1909 assert(TC &&
1910 "TPL must have a template type parameter with a type constraint");
1911 auto *Constraint =
1912 cast<ConceptSpecializationExpr>(TC->getImmediatelyDeclaredConstraint());
1913 bool Dependent =
1914 Constraint->getTemplateArgsAsWritten() &&
1916 Constraint->getTemplateArgsAsWritten()->arguments().drop_front(1));
1917 TypeConstraintInfo.setInt(Dependent ? true : false);
1918}
1919
1921 Requirement(RK_Type, T->getType()->isInstantiationDependentType(),
1922 T->getType()->containsUnexpandedParameterPack(),
1923 // We reach this ctor with either dependent types (in which
1924 // IsSatisfied doesn't matter) or with non-dependent type in
1925 // which the existence of the type indicates satisfaction.
1926 /*IsSatisfied=*/true),
1927 Value(T),
1928 Status(T->getType()->isInstantiationDependentType() ? SS_Dependent
1929 : SS_Satisfied) {}
This file provides some common utility functions for processing Lambda related AST Constructs.
static char ID
Definition: Arena.cpp:183
const Decl * D
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines Expressions and AST nodes for C++2a concepts.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
Defines and computes precedence levels for binary/ternary operators.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static bool CheckConstraintSatisfaction(Sema &S, const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, llvm::SmallVectorImpl< Expr * > &Converted, const MultiLevelTemplateArgumentList &TemplateArgsLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
static const Expr * SubstituteConstraintExpressionWithoutSatisfaction(Sema &S, const Sema::TemplateCompareNewDeclInfo &DeclInfo, const Expr *ConstrExpr)
static ExprResult calculateConstraintSatisfaction(Sema &S, const Expr *ConstraintExpr, ConstraintSatisfaction &Satisfaction, const ConstraintEvaluator &Evaluator)
static bool DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID &ID, const NamedDecl *Templ, const Expr *E, const MultiLevelTemplateArgumentList &MLTAL)
static void diagnoseWellFormedUnsatisfiedConstraintExpr(Sema &S, Expr *SubstExpr, bool First=true)
static void diagnoseUnsatisfiedRequirement(Sema &S, concepts::ExprRequirement *Req, bool First)
static bool substituteParameterMappings(Sema &S, NormalizedConstraint &N, ConceptDecl *Concept, const MultiLevelTemplateArgumentList &MLTAL, const ASTTemplateArgumentListInfo *ArgsAsWritten)
static void diagnoseUnsatisfiedConstraintExpr(Sema &S, const llvm::PointerUnion< Expr *, SubstitutionDiagnostic * > &Record, bool First=true)
static unsigned CalculateTemplateDepthForConstraints(Sema &S, const NamedDecl *ND, bool SkipForSpecialization=false)
SourceLocation Loc
Definition: SemaObjC.cpp:759
static bool isInvalid(LocType Loc, bool *Invalid)
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ int
APSInt & getInt()
Definition: APValue.h:423
bool isInt() const
Definition: APValue.h:401
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
CanQualType BoolTy
Definition: ASTContext.h:1120
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2675
bool isUnset() const
Definition: Ownership.h:167
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6629
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:6736
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2181
StringRef getOpcodeStr() const
Definition: Expr.h:3926
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4859
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2143
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2866
Represents a folding of a pack over an operator.
Definition: ExprCXX.h:4839
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:4893
Expr * getInit() const
Get the operand that doesn't contain a pack, for a binary fold.
Definition: ExprCXX.h:4880
std::optional< unsigned > getNumExpansions() const
Definition: ExprCXX.h:4887
SourceLocation getEllipsisLoc() const
Definition: ExprCXX.h:4884
bool isLeftFold() const
Does this produce a left-associated sequence of operators?
Definition: ExprCXX.h:4874
bool isRightFold() const
Does this produce a right-associated sequence of operators?
Definition: ExprCXX.h:4869
Expr * getPattern() const
Get the pattern, that is, the operand that contains an unexpanded pack.
Definition: ExprCXX.h:4877
BinaryOperatorKind getOperator() const
Definition: ExprCXX.h:4885
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
Declaration of a C++20 concept.
Expr * getConstraintExpr() const
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprConcepts.h:143
ArrayRef< TemplateArgument > getTemplateArguments() const
Definition: ExprConcepts.h:81
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ExprConcepts.h:98
const ASTConstraintSatisfaction & getSatisfaction() const
Get elaborated satisfaction info about the template arguments' satisfaction of the named concept.
Definition: ExprConcepts.h:133
ConceptDecl * getNamedConcept() const
Definition: ExprConcepts.h:87
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
std::pair< SourceLocation, StringRef > SubstitutionDiagnostic
Definition: ASTConcept.h:49
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C)
Definition: ASTConcept.h:60
llvm::SmallVector< Detail, 4 > Details
The substituted constraint expr, if the template arguments could be substituted into them,...
Definition: ASTConcept.h:58
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:2090
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1367
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1414
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:242
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:249
bool isInvalidDecl() const
Definition: DeclBase.h:595
SourceLocation getLocation() const
Definition: DeclBase.h:446
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:434
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:807
RAII object that enters a new expression evaluation context.
This represents one expression.
Definition: Expr.h:110
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition: Expr.h:668
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3070
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
bool isPRValue() const
Definition: Expr.h:278
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
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
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:947
Represents a function declaration or definition.
Definition: Decl.h:1932
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4028
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4346
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4148
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4164
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4092
TemplatedKind
The kind of templated function a FunctionDecl can be.
Definition: Decl.h:1937
@ TK_MemberSpecialization
Definition: Decl.h:1944
@ TK_DependentNonTemplate
Definition: Decl.h:1953
@ TK_FunctionTemplateSpecialization
Definition: Decl.h:1948
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3979
FunctionDecl * getInstantiatedFromDecl() const
Definition: Decl.cpp:4052
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4000
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
void InstantiatedLocal(const Decl *D, Decl *Inst)
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition: Template.h:123
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition: Template.h:129
const ArgList & getOutermost() const
Retrieve the outermost template argument list.
Definition: Template.h:269
This represents a decl that may have a name.
Definition: Decl.h:249
void EmitToString(DiagnosticsEngine &Diags, SmallVectorImpl< char > &Buf) const
A (possibly-)qualified type.
Definition: Type.h:941
The collection of all-type qualifiers we support.
Definition: Type.h:319
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:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
Sema & SemaRef
Definition: SemaBase.h:40
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13205
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8073
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3023
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12099
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12129
SourceLocation getLocation() const
Definition: Sema.h:11873
bool ContainsDecl(const NamedDecl *ND) const
Definition: Sema.h:11863
const DeclContext * getDeclContext() const
Definition: Sema.h:11869
const NamedDecl * getDecl() const
Definition: Sema.h:11861
const DeclContext * getLexicalDeclContext() const
Definition: Sema.h:11865
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
bool CheckInstantiatedFunctionTemplateConstraints(SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef< TemplateArgument > TemplateArgs, ConstraintSatisfaction &Satisfaction)
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, std::optional< unsigned > &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
ASTContext & Context
Definition: Sema.h:962
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:557
ExprResult SubstConstraintExprWithoutSatisfaction(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
bool CheckConstraintExpression(const Expr *CE, Token NextToken=Token(), bool *PossibleNonPrimary=nullptr, bool IsTrailingRequiresClause=false)
Check whether the given expression is a valid constraint expression.
Definition: SemaConcept.cpp:92
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
std::optional< unsigned > getNumArgumentsInExpansionFromUnexpanded(llvm::ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs)
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
const LangOptions & getLangOpts() const
Definition: Sema.h:553
@ ReuseLambdaContextDecl
Definition: Sema.h:6551
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:14368
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:993
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef< const Expr * > AC1, NamedDecl *D2, ArrayRef< const Expr * > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1288
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...
void PushSatisfactionStackEntry(const NamedDecl *D, const llvm::FoldingSetNodeID &ID)
Definition: Sema.h:14305
void PopSatisfactionStackEntry()
Definition: Sema.h:14311
ExprResult SubstConstraintExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
bool SatisfactionStackContains(const NamedDecl *D, const llvm::FoldingSetNodeID &ID) const
Definition: Sema.h:14313
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator)
TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location)
Get a template argument mapping the given template parameter to itself, e.g.
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.
const NormalizedConstraint * getNormalizedAssociatedConstraints(NamedDecl *ConstrainedDecl, ArrayRef< const Expr * > AssociatedConstraints)
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...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
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:203
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
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4277
Declaration of a template type parameter.
Wrapper for template type parameters.
Definition: TypeLoc.h:758
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:99
tok::TokenKind getKind() const
Definition: Token.h:94
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:227
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:242
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
A container of type source information.
Definition: Type.h:7721
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:1829
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8288
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
bool isFunctionType() const
Definition: Type.h:7999
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5370
ReturnTypeRequirement()
No return type requirement was specified.
Definition: ExprConcepts.h:300
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
Definition: ExprConcepts.h:340
A requires-expression requirement which queries the validity and properties of an expression ('simple...
Definition: ExprConcepts.h:280
SubstitutionDiagnostic * getExprSubstitutionDiagnostic() const
Definition: ExprConcepts.h:408
ConceptSpecializationExpr * getReturnTypeRequirementSubstitutedConstraintExpr() const
Definition: ExprConcepts.h:403
const ReturnTypeRequirement & getReturnTypeRequirement() const
Definition: ExprConcepts.h:398
SatisfactionStatus getSatisfactionStatus() const
Definition: ExprConcepts.h:392
SourceLocation getNoexceptLoc() const
Definition: ExprConcepts.h:390
ExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc, ReturnTypeRequirement Req, SatisfactionStatus Status, ConceptSpecializationExpr *SubstitutedConstraintExpr=nullptr)
Construct a compound requirement.
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
Definition: ExprConcepts.h:429
const ASTConstraintSatisfaction & getConstraintSatisfaction() const
Definition: ExprConcepts.h:484
A static requirement that can be used in a requires-expression to check properties of types and expre...
Definition: ExprConcepts.h:168
bool containsUnexpandedParameterPack() const
Definition: ExprConcepts.h:218
A requires-expression requirement which queries the existence of a type name or type template special...
Definition: ExprConcepts.h:225
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
Definition: ExprConcepts.h:260
SatisfactionStatus getSatisfactionStatus() const
Definition: ExprConcepts.h:251
TypeRequirement(TypeSourceInfo *T)
Construct a type requirement from a type.
Provides information about an attempted template argument deduction, whose success or failure was des...
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
bool Sub(InterpState &S, CodePtr OpPC)
Definition: Interp.h:390
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
NormalForm makeCNF(const NormalizedConstraint &Normalized)
@ CPlusPlus11
Definition: LangStandard.h:57
@ CPlusPlus26
Definition: LangStandard.h:62
NormalForm makeDNF(const NormalizedConstraint &Normalized)
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
bool subsumes(const NormalForm &PDNF, const NormalForm &QCNF, const AtomicSubsumptionEvaluator &E)
Definition: SemaConcept.h:197
ExprResult ExprEmpty()
Definition: Ownership.h:271
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
const NormalizedConstraint * getNormalizedAssociatedConstraints(Sema &S, NamedDecl *ConstrainedDecl, ArrayRef< const Expr * > AssociatedConstraints)
ExprResult ExprError()
Definition: Ownership.h:264
prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus11)
Return the precedence of the specified binary operator token.
std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:61
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition: ASTLambda.h:62
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
const FunctionProtoType * T
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl * >, SourceLocation > UnexpandedParameterPack
Definition: Sema.h:216
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Other
Other implicit parameter.
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:89
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:696
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:705
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:694
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:697
bool subsumes(ASTContext &C, const AtomicConstraint &Other) const
Definition: SemaConcept.h:60
bool hasMatchingParameterMapping(ASTContext &C, const AtomicConstraint &Other) const
Definition: SemaConcept.h:39
const Expr * ConstraintExpr
Definition: SemaConcept.h:32
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
NormalizedConstraint Constraint
Definition: SemaConcept.h:177
static bool AreCompatibleForSubsumption(const FoldExpandedConstraint &A, const FoldExpandedConstraint &B)
A normalized constraint, as defined in C++ [temp.constr.normal], is either an atomic constraint,...
Definition: SemaConcept.h:106
llvm::PointerUnion< AtomicConstraint *, FoldExpandedConstraint *, CompoundConstraint > Constraint
Definition: SemaConcept.h:116
NormalizedConstraint & getRHS() const
llvm::PointerIntPair< NormalizedConstraintPair *, 1, CompoundConstraintKind > CompoundConstraint
Definition: SemaConcept.h:112
AtomicConstraint * getAtomicConstraint() const
Definition: SemaConcept.h:152
NormalizedConstraint(AtomicConstraint *C)
Definition: SemaConcept.h:118
CompoundConstraintKind getCompoundKind() const
Definition: SemaConcept.h:144
NormalizedConstraint & getLHS() const
FoldExpandedConstraint * getFoldExpandedConstraint() const
Definition: SemaConcept.h:158
A stack object to be created when performing template instantiation.
Definition: Sema.h:12858
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13012