clang 23.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"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/DeclCXX.h"
23#include "clang/Sema/Overload.h"
25#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 "llvm/Support/SaveAndRestore.h"
33#include "llvm/Support/TimeProfiler.h"
34
35using namespace clang;
36using namespace sema;
37
38namespace {
39class LogicalBinOp {
40 SourceLocation Loc;
42 const Expr *LHS = nullptr;
43 const Expr *RHS = nullptr;
44
45public:
46 LogicalBinOp(const Expr *E) {
47 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
48 Op = BinaryOperator::getOverloadedOperator(BO->getOpcode());
49 LHS = BO->getLHS();
50 RHS = BO->getRHS();
51 Loc = BO->getExprLoc();
52 } else if (auto *OO = dyn_cast<CXXOperatorCallExpr>(E)) {
53 // If OO is not || or && it might not have exactly 2 arguments.
54 if (OO->getNumArgs() == 2) {
55 Op = OO->getOperator();
56 LHS = OO->getArg(0);
57 RHS = OO->getArg(1);
58 Loc = OO->getOperatorLoc();
59 }
60 }
61 }
62
63 bool isAnd() const { return Op == OO_AmpAmp; }
64 bool isOr() const { return Op == OO_PipePipe; }
65 explicit operator bool() const { return isAnd() || isOr(); }
66
67 const Expr *getLHS() const { return LHS; }
68 const Expr *getRHS() const { return RHS; }
69 OverloadedOperatorKind getOp() const { return Op; }
70
71 ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS) const {
72 return recreateBinOp(SemaRef, LHS, const_cast<Expr *>(getRHS()));
73 }
74
75 ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS,
76 ExprResult RHS) const {
77 assert((isAnd() || isOr()) && "Not the right kind of op?");
78 assert((!LHS.isInvalid() && !RHS.isInvalid()) && "not good expressions?");
79
80 if (!LHS.isUsable() || !RHS.isUsable())
81 return ExprEmpty();
82
83 // We should just be able to 'normalize' these to the builtin Binary
84 // Operator, since that is how they are evaluated in constriant checks.
85 return BinaryOperator::Create(SemaRef.Context, LHS.get(), RHS.get(),
87 SemaRef.Context.BoolTy, VK_PRValue,
88 OK_Ordinary, Loc, FPOptionsOverride{});
89 }
90};
91} // namespace
92
93bool Sema::CheckConstraintExpression(const Expr *ConstraintExpression,
94 Token NextToken, bool *PossibleNonPrimary,
95 bool IsTrailingRequiresClause) {
96 // C++2a [temp.constr.atomic]p1
97 // ..E shall be a constant expression of type bool.
98
99 ConstraintExpression = ConstraintExpression->IgnoreParenImpCasts();
100
101 if (LogicalBinOp BO = ConstraintExpression) {
102 return CheckConstraintExpression(BO.getLHS(), NextToken,
103 PossibleNonPrimary) &&
104 CheckConstraintExpression(BO.getRHS(), NextToken,
105 PossibleNonPrimary);
106 } else if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpression))
107 return CheckConstraintExpression(C->getSubExpr(), NextToken,
108 PossibleNonPrimary);
109
110 QualType Type = ConstraintExpression->getType();
111
112 auto CheckForNonPrimary = [&] {
113 if (!PossibleNonPrimary)
114 return;
115
116 *PossibleNonPrimary =
117 // We have the following case:
118 // template<typename> requires func(0) struct S { };
119 // The user probably isn't aware of the parentheses required around
120 // the function call, and we're only going to parse 'func' as the
121 // primary-expression, and complain that it is of non-bool type.
122 //
123 // However, if we're in a lambda, this might also be:
124 // []<typename> requires var () {};
125 // Which also looks like a function call due to the lambda parentheses,
126 // but unlike the first case, isn't an error, so this check is skipped.
127 (NextToken.is(tok::l_paren) &&
128 (IsTrailingRequiresClause ||
129 (Type->isDependentType() &&
130 isa<UnresolvedLookupExpr>(ConstraintExpression) &&
131 !dyn_cast_if_present<LambdaScopeInfo>(getCurFunction())) ||
132 Type->isFunctionType() ||
133 Type->isSpecificBuiltinType(BuiltinType::Overload))) ||
134 // We have the following case:
135 // template<typename T> requires size_<T> == 0 struct S { };
136 // The user probably isn't aware of the parentheses required around
137 // the binary operator, and we're only going to parse 'func' as the
138 // first operand, and complain that it is of non-bool type.
139 getBinOpPrecedence(NextToken.getKind(),
140 /*GreaterThanIsOperator=*/true,
142 };
143
144 // An atomic constraint!
145 if (ConstraintExpression->isTypeDependent()) {
146 CheckForNonPrimary();
147 return true;
148 }
149
150 if (!Context.hasSameUnqualifiedType(Type, Context.BoolTy)) {
151 Diag(ConstraintExpression->getExprLoc(),
152 diag::err_non_bool_atomic_constraint)
153 << Type << ConstraintExpression->getSourceRange();
154 CheckForNonPrimary();
155 return false;
156 }
157
158 if (PossibleNonPrimary)
159 *PossibleNonPrimary = false;
160 return true;
161}
162
163namespace {
164struct SatisfactionStackRAII {
165 Sema &SemaRef;
166 bool Inserted = false;
167 SatisfactionStackRAII(Sema &SemaRef, const NamedDecl *ND,
168 const llvm::FoldingSetNodeID &FSNID)
169 : SemaRef(SemaRef) {
170 if (ND) {
171 SemaRef.PushSatisfactionStackEntry(ND, FSNID);
172 Inserted = true;
173 }
174 }
175 ~SatisfactionStackRAII() {
176 if (Inserted)
178 }
179};
180} // namespace
181
183 Sema &S, llvm::FoldingSetNodeID &ID, const NamedDecl *Templ, const Expr *E,
184 const MultiLevelTemplateArgumentList *MLTAL = nullptr) {
185 E->Profile(ID, S.Context, /*Canonical=*/true);
186 if (MLTAL) {
187 for (const auto &List : *MLTAL)
188 for (const auto &TemplateArg : List.Args)
190 .Profile(ID, S.Context);
191 }
192 if (S.SatisfactionStackContains(Templ, ID)) {
193 S.Diag(E->getExprLoc(), diag::err_constraint_depends_on_self)
194 << E << E->getSourceRange();
195 return true;
196 }
197 return false;
198}
199
200// Figure out the to-translation-unit depth for this function declaration for
201// the purpose of seeing if they differ by constraints. This isn't the same as
202// getTemplateDepth, because it includes already instantiated parents.
203static unsigned
205 bool SkipForSpecialization = false) {
207 ND, ND->getLexicalDeclContext(), /*Final=*/false,
208 /*Innermost=*/std::nullopt,
209 /*RelativeToPrimary=*/true,
210 /*Pattern=*/nullptr,
211 /*ForConstraintInstantiation=*/true, SkipForSpecialization);
212 return MLTAL.getNumLevels();
213}
214
215namespace {
216class AdjustConstraints : public TreeTransform<AdjustConstraints> {
217 unsigned TemplateDepth = 0;
218
219 bool RemoveNonPackExpansionPacks = false;
220
221public:
222 using inherited = TreeTransform<AdjustConstraints>;
223 AdjustConstraints(Sema &SemaRef, unsigned TemplateDepth,
224 bool RemoveNonPackExpansionPacks = false)
225 : inherited(SemaRef), TemplateDepth(TemplateDepth),
226 RemoveNonPackExpansionPacks(RemoveNonPackExpansionPacks) {}
227
228 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
229 UnsignedOrNone NumExpansions) {
230 return inherited::RebuildPackExpansion(Pattern, EllipsisLoc, NumExpansions);
231 }
232
233 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
234 SourceLocation EllipsisLoc,
235 UnsignedOrNone NumExpansions) {
236 if (!RemoveNonPackExpansionPacks)
237 return inherited::RebuildPackExpansion(Pattern, EllipsisLoc,
238 NumExpansions);
239 return Pattern;
240 }
241
242 bool PreparePackForExpansion(TemplateArgumentLoc In, bool Uneval,
243 TemplateArgumentLoc &Out, UnexpandedInfo &Info) {
244 if (!RemoveNonPackExpansionPacks)
245 return inherited::PreparePackForExpansion(In, Uneval, Out, Info);
246 assert(In.getArgument().isPackExpansion());
247 Out = In;
248 Info.Expand = false;
249 return false;
250 }
251
252 using inherited::TransformTemplateTypeParmType;
253 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
254 TemplateTypeParmTypeLoc TL, bool) {
255 const TemplateTypeParmType *T = TL.getTypePtr();
256
257 TemplateTypeParmDecl *NewTTPDecl = nullptr;
258 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
259 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
260 TransformDecl(TL.getNameLoc(), OldTTPDecl));
261
262 QualType Result = getSema().Context.getTemplateTypeParmType(
263 T->getDepth() + TemplateDepth, T->getIndex(),
264 RemoveNonPackExpansionPacks ? false : T->isParameterPack(), NewTTPDecl);
265 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
266 NewTL.setNameLoc(TL.getNameLoc());
267 return Result;
268 }
269
270 bool AlreadyTransformed(QualType T) {
271 if (T.isNull())
272 return true;
273
276 return false;
277 return true;
278 }
279};
280} // namespace
281
282namespace {
283
284// FIXME: Convert it to DynamicRecursiveASTVisitor
285class HashParameterMapping : public RecursiveASTVisitor<HashParameterMapping> {
286 using inherited = RecursiveASTVisitor<HashParameterMapping>;
287 friend inherited;
288
289 Sema &SemaRef;
290 const MultiLevelTemplateArgumentList &TemplateArgs;
291 llvm::FoldingSetNodeID &ID;
292 llvm::SmallVector<TemplateArgument, 10> UsedTemplateArgs;
293
294 UnsignedOrNone OuterPackSubstIndex;
295
296 bool shouldVisitTemplateInstantiations() const { return true; }
297
298public:
299 HashParameterMapping(Sema &SemaRef,
300 const MultiLevelTemplateArgumentList &TemplateArgs,
301 llvm::FoldingSetNodeID &ID,
302 UnsignedOrNone OuterPackSubstIndex)
303 : SemaRef(SemaRef), TemplateArgs(TemplateArgs), ID(ID),
304 OuterPackSubstIndex(OuterPackSubstIndex) {}
305
306 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
307 // A lambda expression can introduce template parameters that don't have
308 // corresponding template arguments yet.
309 if (T->getDepth() >= TemplateArgs.getNumLevels())
310 return true;
311
312 // There might not be a corresponding template argument before substituting
313 // into the parameter mapping, e.g. a sizeof... expression.
314 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex()))
315 return true;
316
317 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
318
319 // In concept parameter mapping for fold expressions, packs that aren't
320 // expanded in place are treated as having non-pack dependency, so that
321 // a PackExpansionType won't prevent expanding the packs outside the
322 // TreeTransform. However we still need to check the pack at this point.
323 if ((T->isParameterPack() ||
324 (T->getDecl() && T->getDecl()->isTemplateParameterPack())) &&
325 SemaRef.ArgPackSubstIndex) {
326 assert(Arg.getKind() == TemplateArgument::Pack &&
327 "Missing argument pack");
328
329 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
330 }
331
332 UsedTemplateArgs.push_back(
334 return true;
335 }
336
337 bool VisitDeclRefExpr(DeclRefExpr *E) {
338 NamedDecl *D = E->getDecl();
339 NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D);
340 if (!NTTP)
341 return TraverseDecl(D);
342
343 if (NTTP->getDepth() >= TemplateArgs.getNumLevels())
344 return true;
345
346 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(), NTTP->getIndex()))
347 return true;
348
349 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
350 if (NTTP->isParameterPack() && SemaRef.ArgPackSubstIndex) {
351 assert(Arg.getKind() == TemplateArgument::Pack &&
352 "Missing argument pack");
353 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
354 }
355
356 UsedTemplateArgs.push_back(
358 return true;
359 }
360
361 bool VisitTypedefType(TypedefType *TT) {
362 return inherited::TraverseType(TT->desugar());
363 }
364
365 bool TraverseDecl(Decl *D) {
366 if (auto *VD = dyn_cast<ValueDecl>(D)) {
367 if (auto *Var = dyn_cast<VarDecl>(VD))
368 TraverseStmt(Var->getInit());
369 return TraverseType(VD->getType());
370 }
371
372 return inherited::TraverseDecl(D);
373 }
374
375 bool TraverseCallExpr(CallExpr *CE) {
376 inherited::TraverseStmt(CE->getCallee());
377
378 for (Expr *Arg : CE->arguments())
379 inherited::TraverseStmt(Arg);
380
381 return true;
382 }
383
384 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) {
385 // We don't care about TypeLocs. So traverse Types instead.
386 return TraverseType(TL.getType().getCanonicalType(), TraverseQualifier);
387 }
388
389 bool TraverseDependentNameType(const DependentNameType *T,
390 bool /*TraverseQualifier*/) {
391 return TraverseNestedNameSpecifier(T->getQualifier());
392 }
393
394 bool TraverseTagType(const TagType *T, bool TraverseQualifier) {
395 // T's parent can be dependent while T doesn't have any template arguments.
396 // We should have already traversed its qualifier.
397 // FIXME: Add an assert to catch cases where we failed to profile the
398 // concept.
399 return true;
400 }
401
402 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
403 bool TraverseQualifier) {
404 return TraverseTemplateArguments(T->getTemplateArgs(SemaRef.Context));
405 }
406
407 bool TraverseTemplateArgument(const TemplateArgument &Arg) {
409 // Act as if we are fully expanding this pack, if it is a PackExpansion.
410 Sema::ArgPackSubstIndexRAII _1(SemaRef, std::nullopt);
411 llvm::SaveAndRestore<UnsignedOrNone> _2(OuterPackSubstIndex,
412 std::nullopt);
413 return inherited::TraverseTemplateArgument(Arg);
414 }
415
416 Sema::ArgPackSubstIndexRAII _1(SemaRef, OuterPackSubstIndex);
417 return inherited::TraverseTemplateArgument(Arg);
418 }
419
420 bool TraverseSizeOfPackExpr(SizeOfPackExpr *SOPE) {
421 return TraverseDecl(SOPE->getPack());
422 }
423
424 bool VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
425 return inherited::TraverseStmt(E->getReplacement());
426 }
427
428 bool TraverseTemplateName(TemplateName Template) {
429 if (auto *TTP = dyn_cast_if_present<TemplateTemplateParmDecl>(
430 Template.getAsTemplateDecl());
431 TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) {
432 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
433 TTP->getPosition()))
434 return true;
435
436 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
437 if (TTP->isParameterPack() && SemaRef.ArgPackSubstIndex) {
438 assert(Arg.getKind() == TemplateArgument::Pack &&
439 "Missing argument pack");
440 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
441 }
442 assert(!Arg.getAsTemplate().isNull() &&
443 "Null template template argument");
444 UsedTemplateArgs.push_back(
446 }
447 return inherited::TraverseTemplateName(Template);
448 }
449
450 void VisitConstraint(const NormalizedConstraintWithParamMapping &Constraint) {
451 if (!Constraint.hasParameterMapping()) {
452 for (const auto &List : TemplateArgs)
453 for (const TemplateArgument &Arg : List.Args)
455 ID, SemaRef.Context);
456 return;
457 }
458
459 llvm::ArrayRef<TemplateArgumentLoc> Mapping =
460 Constraint.getParameterMapping();
461 for (auto &ArgLoc : Mapping) {
462 TemplateArgument Canonical =
463 SemaRef.Context.getCanonicalTemplateArgument(ArgLoc.getArgument());
464 // We don't want sugars to impede the profile of cache.
465 UsedTemplateArgs.push_back(Canonical);
466 TraverseTemplateArgument(Canonical);
467 }
468
469 for (auto &Used : UsedTemplateArgs) {
470 llvm::FoldingSetNodeID R;
471 Used.Profile(R, SemaRef.Context);
472 ID.AddNodeID(R);
473 }
474 }
475};
476
477class ConstraintSatisfactionChecker {
478 Sema &S;
479 const NamedDecl *Template;
480 SourceLocation TemplateNameLoc;
481 UnsignedOrNone PackSubstitutionIndex;
482 ConstraintSatisfaction &Satisfaction;
483 bool BuildExpression;
484
485 // The most closest concept declaration when evaluating atomic constriants.
486 // This is to make sure that lambdas in the atomic expression live in the
487 // right context.
488 ConceptDecl *ParentConcept = nullptr;
489
490private:
492 EvaluateAtomicConstraint(const Expr *AtomicExpr,
493 const MultiLevelTemplateArgumentList &MLTAL);
494
495 UnsignedOrNone EvaluateFoldExpandedConstraintSize(
496 const FoldExpandedConstraint &FE,
497 const MultiLevelTemplateArgumentList &MLTAL);
498
499 // XXX: It is SLOW! Use it very carefully.
500 std::optional<MultiLevelTemplateArgumentList> SubstitutionInTemplateArguments(
501 const NormalizedConstraintWithParamMapping &Constraint,
502 const MultiLevelTemplateArgumentList &MLTAL,
503 llvm::SmallVector<TemplateArgument> &SubstitutedOuterMost);
504
505 ExprResult EvaluateSlow(const AtomicConstraint &Constraint,
506 const MultiLevelTemplateArgumentList &MLTAL);
507
508 ExprResult Evaluate(const AtomicConstraint &Constraint,
509 const MultiLevelTemplateArgumentList &MLTAL);
510
511 ExprResult EvaluateSlow(const FoldExpandedConstraint &Constraint,
512 const MultiLevelTemplateArgumentList &MLTAL);
513
514 ExprResult Evaluate(const FoldExpandedConstraint &Constraint,
515 const MultiLevelTemplateArgumentList &MLTAL);
516
517 ExprResult EvaluateSlow(const ConceptIdConstraint &Constraint,
518 const MultiLevelTemplateArgumentList &MLTAL,
519 unsigned int Size);
520
521 ExprResult Evaluate(const ConceptIdConstraint &Constraint,
522 const MultiLevelTemplateArgumentList &MLTAL);
523
524 ExprResult Evaluate(const CompoundConstraint &Constraint,
525 const MultiLevelTemplateArgumentList &MLTAL);
526
527public:
528 ConstraintSatisfactionChecker(Sema &SemaRef, const NamedDecl *Template,
529 SourceLocation TemplateNameLoc,
530 UnsignedOrNone PackSubstitutionIndex,
531 ConstraintSatisfaction &Satisfaction,
532 bool BuildExpression)
533 : S(SemaRef), Template(Template), TemplateNameLoc(TemplateNameLoc),
534 PackSubstitutionIndex(PackSubstitutionIndex),
535 Satisfaction(Satisfaction), BuildExpression(BuildExpression) {}
536
537 ExprResult Evaluate(const NormalizedConstraint &Constraint,
538 const MultiLevelTemplateArgumentList &MLTAL);
539};
540
541StringRef allocateStringFromConceptDiagnostic(const Sema &S,
542 const PartialDiagnostic Diag) {
543 SmallString<128> DiagString;
544 DiagString = ": ";
545 Diag.EmitToString(S.getDiagnostics(), DiagString);
546 return S.getASTContext().backupStr(DiagString);
547}
548
549} // namespace
550
551ExprResult ConstraintSatisfactionChecker::EvaluateAtomicConstraint(
552 const Expr *AtomicExpr, const MultiLevelTemplateArgumentList &MLTAL) {
553 llvm::FoldingSetNodeID ID;
554 if (Template &&
556 Satisfaction.IsSatisfied = false;
557 Satisfaction.ContainsErrors = true;
558 return ExprEmpty();
559 }
560 SatisfactionStackRAII StackRAII(S, Template, ID);
561
562 // Atomic constraint - substitute arguments and check satisfaction.
563 ExprResult SubstitutedExpression = const_cast<Expr *>(AtomicExpr);
564 {
565 TemplateDeductionInfo Info(TemplateNameLoc);
569 // FIXME: improve const-correctness of InstantiatingTemplate
570 const_cast<NamedDecl *>(Template), AtomicExpr->getSourceRange());
571 if (Inst.isInvalid())
572 return ExprError();
573
574 // We do not want error diagnostics escaping here.
575 Sema::SFINAETrap Trap(S, Info);
576 SubstitutedExpression =
577 S.SubstConstraintExpr(const_cast<Expr *>(AtomicExpr), MLTAL);
578
579 if (SubstitutedExpression.isInvalid() || Trap.hasErrorOccurred()) {
580 // C++2a [temp.constr.atomic]p1
581 // ...If substitution results in an invalid type or expression, the
582 // constraint is not satisfied.
583 if (!Trap.hasErrorOccurred())
584 // A non-SFINAE error has occurred as a result of this
585 // substitution.
586 return ExprError();
587
590 Info.takeSFINAEDiagnostic(SubstDiag);
591 // FIXME: This is an unfortunate consequence of there
592 // being no serialization code for PartialDiagnostics and the fact
593 // that serializing them would likely take a lot more storage than
594 // just storing them as strings. We would still like, in the
595 // future, to serialize the proper PartialDiagnostic as serializing
596 // it as a string defeats the purpose of the diagnostic mechanism.
597 Satisfaction.Details.emplace_back(
599 SubstDiag.first,
600 allocateStringFromConceptDiagnostic(S, SubstDiag.second)});
601 Satisfaction.IsSatisfied = false;
602 return ExprEmpty();
603 }
604 }
605
606 if (!S.CheckConstraintExpression(SubstitutedExpression.get()))
607 return ExprError();
608
609 // [temp.constr.atomic]p3: To determine if an atomic constraint is
610 // satisfied, the parameter mapping and template arguments are first
611 // substituted into its expression. If substitution results in an
612 // invalid type or expression, the constraint is not satisfied.
613 // Otherwise, the lvalue-to-rvalue conversion is performed if necessary,
614 // and E shall be a constant expression of type bool.
615 //
616 // Perform the L to R Value conversion if necessary. We do so for all
617 // non-PRValue categories, else we fail to extend the lifetime of
618 // temporaries, and that fails the constant expression check.
619 if (!SubstitutedExpression.get()->isPRValue())
620 SubstitutedExpression = ImplicitCastExpr::Create(
621 S.Context, SubstitutedExpression.get()->getType(), CK_LValueToRValue,
622 SubstitutedExpression.get(),
623 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
624
625 return SubstitutedExpression;
626}
627
628std::optional<MultiLevelTemplateArgumentList>
629ConstraintSatisfactionChecker::SubstitutionInTemplateArguments(
630 const NormalizedConstraintWithParamMapping &Constraint,
632 llvm::SmallVector<TemplateArgument> &SubstitutedOutermost) {
633
634 if (!Constraint.hasParameterMapping()) {
635 if (MLTAL.getNumSubstitutedLevels())
636 SubstitutedOutermost.assign(MLTAL.getOutermost());
637 return MLTAL;
638 }
639
640 // The mapping is empty, meaning no template arguments are needed for
641 // evaluation.
642 if (Constraint.getParameterMapping().empty())
644
645 TemplateDeductionInfo Info(Constraint.getBeginLoc());
646 Sema::SFINAETrap Trap(S, Info);
648 S, Constraint.getBeginLoc(),
650 // FIXME: improve const-correctness of InstantiatingTemplate
651 const_cast<NamedDecl *>(Template), Constraint.getSourceRange());
652 if (Inst.isInvalid())
653 return std::nullopt;
654
655 TemplateArgumentListInfo SubstArgs;
657 S, Constraint.getPackSubstitutionIndex()
658 ? Constraint.getPackSubstitutionIndex()
659 : PackSubstitutionIndex);
660
662 Constraint.getParameterMapping(), Constraint.getBeginLoc(), MLTAL,
663 SubstArgs)) {
664 Satisfaction.IsSatisfied = false;
665 return std::nullopt;
666 }
667
669 auto *TD = const_cast<TemplateDecl *>(
672 TD->getLocation(), SubstArgs,
673 /*DefaultArguments=*/{},
674 /*PartialTemplateArgs=*/false, CTAI))
675 return std::nullopt;
677 Constraint.mappingOccurenceList();
678 // The empty MLTAL situation should only occur when evaluating non-dependent
679 // constraints.
680 if (MLTAL.getNumSubstitutedLevels())
681 SubstitutedOutermost =
682 llvm::to_vector_of<TemplateArgument>(MLTAL.getOutermost());
683 unsigned Offset = 0;
684 for (unsigned I = 0, MappedIndex = 0; I < Used.size(); I++) {
686 if (Used[I])
688 CTAI.SugaredConverted[MappedIndex++]);
689 if (I < SubstitutedOutermost.size()) {
690 SubstitutedOutermost[I] = Arg;
691 Offset = I + 1;
692 } else {
693 SubstitutedOutermost.push_back(Arg);
694 Offset = SubstitutedOutermost.size();
695 }
696 }
697 if (Offset < SubstitutedOutermost.size())
698 SubstitutedOutermost.erase(SubstitutedOutermost.begin() + Offset);
699
700 MultiLevelTemplateArgumentList SubstitutedTemplateArgs;
701 SubstitutedTemplateArgs.addOuterTemplateArguments(TD, SubstitutedOutermost,
702 /*Final=*/false);
703 return std::move(SubstitutedTemplateArgs);
704}
705
706ExprResult ConstraintSatisfactionChecker::EvaluateSlow(
707 const AtomicConstraint &Constraint,
708 const MultiLevelTemplateArgumentList &MLTAL) {
709 std::optional<EnterExpressionEvaluationContext> EvaluationContext;
710 EvaluationContext.emplace(
713
714 llvm::SmallVector<TemplateArgument> SubstitutedOutermost;
715 std::optional<MultiLevelTemplateArgumentList> SubstitutedArgs =
716 SubstitutionInTemplateArguments(Constraint, MLTAL, SubstitutedOutermost);
717 if (!SubstitutedArgs) {
718 Satisfaction.IsSatisfied = false;
719 return ExprEmpty();
720 }
721
722 // Note that generic lambdas inside requires body require a lambda context
723 // decl from which to fetch correct template arguments. But we don't have any
724 // proper decls because the constraints are already normalized.
725 if (ParentConcept) {
726 // FIXME: the evaluation context should learn to track template arguments
727 // separately from a Decl.
728 EvaluationContext.emplace(
730 /*LambdaContextDecl=*/
732 S.Context, ParentConcept->getDeclContext(),
733 ParentConcept->getBeginLoc(), SubstitutedOutermost));
734 }
735
736 Sema::ArgPackSubstIndexRAII SubstIndex(S, PackSubstitutionIndex);
737 ExprResult SubstitutedAtomicExpr = EvaluateAtomicConstraint(
738 Constraint.getConstraintExpr(), *SubstitutedArgs);
739
740 if (SubstitutedAtomicExpr.isInvalid())
741 return ExprError();
742
743 if (SubstitutedAtomicExpr.isUnset())
744 // Evaluator has decided satisfaction without yielding an expression.
745 return ExprEmpty();
746
747 // We don't have the ability to evaluate this, since it contains a
748 // RecoveryExpr, so we want to fail overload resolution. Otherwise,
749 // we'd potentially pick up a different overload, and cause confusing
750 // diagnostics. SO, add a failure detail that will cause us to make this
751 // overload set not viable.
752 if (SubstitutedAtomicExpr.get()->containsErrors()) {
753 Satisfaction.IsSatisfied = false;
754 Satisfaction.ContainsErrors = true;
755
756 PartialDiagnostic Msg = S.PDiag(diag::note_constraint_references_error);
757 Satisfaction.Details.emplace_back(
759 SubstitutedAtomicExpr.get()->getBeginLoc(),
760 allocateStringFromConceptDiagnostic(S, Msg)});
761 return SubstitutedAtomicExpr;
762 }
763
764 if (SubstitutedAtomicExpr.get()->isValueDependent()) {
765 Satisfaction.IsSatisfied = true;
766 Satisfaction.ContainsErrors = false;
767 return SubstitutedAtomicExpr;
768 }
769
771 Expr::EvalResult EvalResult;
772 EvalResult.Diag = &EvaluationDiags;
773 if (!SubstitutedAtomicExpr.get()->EvaluateAsConstantExpr(EvalResult,
774 S.Context) ||
775 !EvaluationDiags.empty()) {
776 // C++2a [temp.constr.atomic]p1
777 // ...E shall be a constant expression of type bool.
778 S.Diag(SubstitutedAtomicExpr.get()->getBeginLoc(),
779 diag::err_non_constant_constraint_expression)
780 << SubstitutedAtomicExpr.get()->getSourceRange();
781 for (const PartialDiagnosticAt &PDiag : EvaluationDiags)
782 S.Diag(PDiag.first, PDiag.second);
783 return ExprError();
784 }
785
786 assert(EvalResult.Val.isInt() &&
787 "evaluating bool expression didn't produce int");
788 Satisfaction.IsSatisfied = EvalResult.Val.getInt().getBoolValue();
789 if (!Satisfaction.IsSatisfied)
790 Satisfaction.Details.emplace_back(SubstitutedAtomicExpr.get());
791
792 return SubstitutedAtomicExpr;
793}
794
795ExprResult ConstraintSatisfactionChecker::Evaluate(
796 const AtomicConstraint &Constraint,
797 const MultiLevelTemplateArgumentList &MLTAL) {
798
799 unsigned Size = Satisfaction.Details.size();
800 llvm::FoldingSetNodeID ID;
801 UnsignedOrNone OuterPackSubstIndex =
802 Constraint.getPackSubstitutionIndex()
803 ? Constraint.getPackSubstitutionIndex()
804 : PackSubstitutionIndex;
805
806 ID.AddPointer(Constraint.getConstraintExpr());
807 ID.AddInteger(OuterPackSubstIndex.toInternalRepresentation());
808 HashParameterMapping(S, MLTAL, ID, OuterPackSubstIndex)
809 .VisitConstraint(Constraint);
810
811 if (auto Iter = S.UnsubstitutedConstraintSatisfactionCache.find(ID);
813 auto &Cached = Iter->second.Satisfaction;
814 Satisfaction.ContainsErrors = Cached.ContainsErrors;
815 Satisfaction.IsSatisfied = Cached.IsSatisfied;
816 Satisfaction.Details.insert(Satisfaction.Details.begin() + Size,
817 Cached.Details.begin(), Cached.Details.end());
818 return Iter->second.SubstExpr;
819 }
820
821 ExprResult E = EvaluateSlow(Constraint, MLTAL);
822
824 Cache.Satisfaction.ContainsErrors = Satisfaction.ContainsErrors;
825 Cache.Satisfaction.IsSatisfied = Satisfaction.IsSatisfied;
826 Cache.Satisfaction.Details.insert(Cache.Satisfaction.Details.end(),
827 Satisfaction.Details.begin() + Size,
828 Satisfaction.Details.end());
829 Cache.SubstExpr = E;
830 S.UnsubstitutedConstraintSatisfactionCache.insert({ID, std::move(Cache)});
831
832 return E;
833}
834
836ConstraintSatisfactionChecker::EvaluateFoldExpandedConstraintSize(
837 const FoldExpandedConstraint &FE,
838 const MultiLevelTemplateArgumentList &MLTAL) {
839
840 Expr *Pattern = const_cast<Expr *>(FE.getPattern());
841
843 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
844 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
845 bool Expand = true;
846 bool RetainExpansion = false;
847 UnsignedOrNone NumExpansions(std::nullopt);
849 Pattern->getExprLoc(), Pattern->getSourceRange(), Unexpanded, MLTAL,
850 /*FailOnPackProducingTemplates=*/false, Expand, RetainExpansion,
851 NumExpansions, /*Diagnose=*/false) ||
852 !Expand || RetainExpansion)
853 return std::nullopt;
854
855 if (NumExpansions && S.getLangOpts().BracketDepth < *NumExpansions)
856 return std::nullopt;
857 return NumExpansions;
858}
859
860ExprResult ConstraintSatisfactionChecker::EvaluateSlow(
861 const FoldExpandedConstraint &Constraint,
862 const MultiLevelTemplateArgumentList &MLTAL) {
863
864 bool Conjunction = Constraint.getFoldOperator() ==
866 unsigned EffectiveDetailEndIndex = Satisfaction.Details.size();
867
868 llvm::SmallVector<TemplateArgument> SubstitutedOutermost;
869 // FIXME: Is PackSubstitutionIndex correct?
870 llvm::SaveAndRestore _(PackSubstitutionIndex, S.ArgPackSubstIndex);
871 std::optional<MultiLevelTemplateArgumentList> SubstitutedArgs =
872 SubstitutionInTemplateArguments(
873 static_cast<const NormalizedConstraintWithParamMapping &>(Constraint),
874 MLTAL, SubstitutedOutermost);
875 if (!SubstitutedArgs) {
876 Satisfaction.IsSatisfied = false;
877 return ExprError();
878 }
879
881 UnsignedOrNone NumExpansions =
882 EvaluateFoldExpandedConstraintSize(Constraint, *SubstitutedArgs);
883 if (!NumExpansions)
884 return ExprEmpty();
885
886 if (*NumExpansions == 0) {
887 Satisfaction.IsSatisfied = Conjunction;
888 return ExprEmpty();
889 }
890
891 for (unsigned I = 0; I < *NumExpansions; I++) {
892 Sema::ArgPackSubstIndexRAII SubstIndex(S, I);
893 Satisfaction.IsSatisfied = false;
894 Satisfaction.ContainsErrors = false;
896 ConstraintSatisfactionChecker(S, Template, TemplateNameLoc,
897 UnsignedOrNone(I), Satisfaction,
898 /*BuildExpression=*/false)
899 .Evaluate(Constraint.getNormalizedPattern(), *SubstitutedArgs);
900 if (BuildExpression && Expr.isUsable()) {
901 if (Out.isUnset())
902 Out = Expr;
903 else
904 Out = BinaryOperator::Create(S.Context, Out.get(), Expr.get(),
905 Conjunction ? BinaryOperatorKind::BO_LAnd
906 : BinaryOperatorKind::BO_LOr,
908 Constraint.getBeginLoc(),
910 } else {
911 assert(!BuildExpression || !Satisfaction.IsSatisfied);
912 }
913 if (!Conjunction && Satisfaction.IsSatisfied) {
914 Satisfaction.Details.erase(Satisfaction.Details.begin() +
915 EffectiveDetailEndIndex,
916 Satisfaction.Details.end());
917 break;
918 }
919 if (Satisfaction.IsSatisfied != Conjunction)
920 return Out;
921 }
922
923 return Out;
924}
925
926ExprResult ConstraintSatisfactionChecker::Evaluate(
927 const FoldExpandedConstraint &Constraint,
928 const MultiLevelTemplateArgumentList &MLTAL) {
929
930 llvm::FoldingSetNodeID ID;
931 ID.AddPointer(Constraint.getPattern());
932 HashParameterMapping(S, MLTAL, ID, std::nullopt).VisitConstraint(Constraint);
933
934 if (auto Iter = S.UnsubstitutedConstraintSatisfactionCache.find(ID);
936
937 auto &Cached = Iter->second.Satisfaction;
938 Satisfaction.ContainsErrors = Cached.ContainsErrors;
939 Satisfaction.IsSatisfied = Cached.IsSatisfied;
940 Satisfaction.Details.insert(Satisfaction.Details.end(),
941 Cached.Details.begin(), Cached.Details.end());
942 return Iter->second.SubstExpr;
943 }
944
945 unsigned Size = Satisfaction.Details.size();
946
947 ExprResult E = EvaluateSlow(Constraint, MLTAL);
949 Cache.Satisfaction.ContainsErrors = Satisfaction.ContainsErrors;
950 Cache.Satisfaction.IsSatisfied = Satisfaction.IsSatisfied;
951 Cache.Satisfaction.Details.insert(Cache.Satisfaction.Details.end(),
952 Satisfaction.Details.begin() + Size,
953 Satisfaction.Details.end());
954 Cache.SubstExpr = E;
955 S.UnsubstitutedConstraintSatisfactionCache.insert({ID, std::move(Cache)});
956 return E;
957}
958
959ExprResult ConstraintSatisfactionChecker::EvaluateSlow(
960 const ConceptIdConstraint &Constraint,
961 const MultiLevelTemplateArgumentList &MLTAL, unsigned Size) {
962 const ConceptReference *ConceptId = Constraint.getConceptId();
963
964 llvm::SmallVector<TemplateArgument> SubstitutedOutermost;
965 std::optional<MultiLevelTemplateArgumentList> SubstitutedArgs =
966 SubstitutionInTemplateArguments(Constraint, MLTAL, SubstitutedOutermost);
967
968 if (!SubstitutedArgs) {
969 Satisfaction.IsSatisfied = false;
970 // FIXME: diagnostics?
971 return ExprError();
972 }
973
975 S, Constraint.getPackSubstitutionIndex()
976 ? Constraint.getPackSubstitutionIndex()
977 : PackSubstitutionIndex);
978
979 const ASTTemplateArgumentListInfo *Ori =
980 ConceptId->getTemplateArgsAsWritten();
981 TemplateDeductionInfo Info(TemplateNameLoc);
982 Sema::SFINAETrap Trap(S, Info);
985 const_cast<NamedDecl *>(Template), Constraint.getSourceRange());
986
987 TemplateArgumentListInfo OutArgs(Ori->LAngleLoc, Ori->RAngleLoc);
988 if (S.SubstTemplateArguments(Ori->arguments(), *SubstitutedArgs, OutArgs) ||
989 Trap.hasErrorOccurred()) {
990 Satisfaction.IsSatisfied = false;
991 if (!Trap.hasErrorOccurred())
992 return ExprError();
993
996 Info.takeSFINAEDiagnostic(SubstDiag);
997 // FIXME: This is an unfortunate consequence of there
998 // being no serialization code for PartialDiagnostics and the fact
999 // that serializing them would likely take a lot more storage than
1000 // just storing them as strings. We would still like, in the
1001 // future, to serialize the proper PartialDiagnostic as serializing
1002 // it as a string defeats the purpose of the diagnostic mechanism.
1003 Satisfaction.Details.insert(
1004 Satisfaction.Details.begin() + Size,
1006 SubstDiag.first,
1007 allocateStringFromConceptDiagnostic(S, SubstDiag.second)});
1008 return ExprError();
1009 }
1010
1011 CXXScopeSpec SS;
1012 SS.Adopt(ConceptId->getNestedNameSpecifierLoc());
1013
1014 ExprResult SubstitutedConceptId = S.CheckConceptTemplateId(
1015 SS, ConceptId->getTemplateKWLoc(), ConceptId->getConceptNameInfo(),
1016 ConceptId->getFoundDecl(), ConceptId->getNamedConcept(), &OutArgs,
1017 /*DoCheckConstraintSatisfaction=*/false);
1018
1019 if (SubstitutedConceptId.isInvalid() || Trap.hasErrorOccurred())
1020 return ExprError();
1021
1022 if (Size != Satisfaction.Details.size()) {
1023 Satisfaction.Details.insert(
1024 Satisfaction.Details.begin() + Size,
1026 SubstitutedConceptId.getAs<ConceptSpecializationExpr>()
1027 ->getConceptReference()));
1028 }
1029 return SubstitutedConceptId;
1030}
1031
1032ExprResult ConstraintSatisfactionChecker::Evaluate(
1033 const ConceptIdConstraint &Constraint,
1034 const MultiLevelTemplateArgumentList &MLTAL) {
1035
1036 const ConceptReference *ConceptId = Constraint.getConceptId();
1037
1038 UnsignedOrNone OuterPackSubstIndex =
1039 Constraint.getPackSubstitutionIndex()
1040 ? Constraint.getPackSubstitutionIndex()
1041 : PackSubstitutionIndex;
1042
1043 Sema::InstantiatingTemplate InstTemplate(
1044 S, ConceptId->getBeginLoc(),
1046 ConceptId->getNamedConcept(),
1047 // We may have empty template arguments when checking non-dependent
1048 // nested constraint expressions.
1049 // In such cases, non-SFINAE errors would have already been diagnosed
1050 // during parameter mapping substitution, so the instantiating template
1051 // arguments are less useful here.
1052 MLTAL.getNumSubstitutedLevels() ? MLTAL.getInnermost()
1054 Constraint.getSourceRange());
1055 if (InstTemplate.isInvalid())
1056 return ExprError();
1057
1058 llvm::SaveAndRestore PushConceptDecl(
1059 ParentConcept, cast<ConceptDecl>(ConceptId->getNamedConcept()));
1060
1061 unsigned Size = Satisfaction.Details.size();
1062
1063 ExprResult E = Evaluate(Constraint.getNormalizedConstraint(), MLTAL);
1064
1065 if (E.isInvalid()) {
1066 Satisfaction.Details.insert(Satisfaction.Details.begin() + Size, ConceptId);
1067 return E;
1068 }
1069
1070 // ConceptIdConstraint is only relevant for diagnostics,
1071 // so if the normalized constraint is satisfied, we should not
1072 // substitute into the constraint.
1073 if (Satisfaction.IsSatisfied)
1074 return E;
1075
1076 llvm::FoldingSetNodeID ID;
1077 ID.AddPointer(Constraint.getConceptId());
1078 ID.AddInteger(OuterPackSubstIndex.toInternalRepresentation());
1079 HashParameterMapping(S, MLTAL, ID, OuterPackSubstIndex)
1080 .VisitConstraint(Constraint);
1081
1082 if (auto Iter = S.UnsubstitutedConstraintSatisfactionCache.find(ID);
1084
1085 auto &Cached = Iter->second.Satisfaction;
1086 Satisfaction.ContainsErrors = Cached.ContainsErrors;
1087 Satisfaction.IsSatisfied = Cached.IsSatisfied;
1088 Satisfaction.Details.insert(Satisfaction.Details.begin() + Size,
1089 Cached.Details.begin(), Cached.Details.end());
1090 return Iter->second.SubstExpr;
1091 }
1092
1093 ExprResult CE = EvaluateSlow(Constraint, MLTAL, Size);
1094 if (CE.isInvalid())
1095 return E;
1097 Cache.Satisfaction.ContainsErrors = Satisfaction.ContainsErrors;
1098 Cache.Satisfaction.IsSatisfied = Satisfaction.IsSatisfied;
1099 Cache.Satisfaction.Details.insert(Cache.Satisfaction.Details.end(),
1100 Satisfaction.Details.begin() + Size,
1101 Satisfaction.Details.end());
1102 Cache.SubstExpr = CE;
1103 S.UnsubstitutedConstraintSatisfactionCache.insert({ID, std::move(Cache)});
1104 return CE;
1105}
1106
1107ExprResult ConstraintSatisfactionChecker::Evaluate(
1108 const CompoundConstraint &Constraint,
1109 const MultiLevelTemplateArgumentList &MLTAL) {
1110
1111 unsigned EffectiveDetailEndIndex = Satisfaction.Details.size();
1112
1113 bool Conjunction =
1115
1116 ExprResult LHS = Evaluate(Constraint.getLHS(), MLTAL);
1117
1118 if (Conjunction && (!Satisfaction.IsSatisfied || Satisfaction.ContainsErrors))
1119 return LHS;
1120
1121 if (!Conjunction && !LHS.isInvalid() && Satisfaction.IsSatisfied &&
1122 !Satisfaction.ContainsErrors)
1123 return LHS;
1124
1125 Satisfaction.ContainsErrors = false;
1126 Satisfaction.IsSatisfied = false;
1127
1128 ExprResult RHS = Evaluate(Constraint.getRHS(), MLTAL);
1129
1130 if (!Conjunction && !RHS.isInvalid() && Satisfaction.IsSatisfied &&
1131 !Satisfaction.ContainsErrors)
1132 Satisfaction.Details.erase(Satisfaction.Details.begin() +
1133 EffectiveDetailEndIndex,
1134 Satisfaction.Details.end());
1135
1136 if (!BuildExpression)
1137 return Satisfaction.ContainsErrors ? ExprError() : ExprEmpty();
1138
1139 if (!LHS.isUsable())
1140 return RHS;
1141
1142 if (!RHS.isUsable())
1143 return LHS;
1144
1145 return BinaryOperator::Create(S.Context, LHS.get(), RHS.get(),
1146 Conjunction ? BinaryOperatorKind::BO_LAnd
1147 : BinaryOperatorKind::BO_LOr,
1149 Constraint.getBeginLoc(), FPOptionsOverride{});
1150}
1151
1152ExprResult ConstraintSatisfactionChecker::Evaluate(
1153 const NormalizedConstraint &Constraint,
1154 const MultiLevelTemplateArgumentList &MLTAL) {
1155 switch (Constraint.getKind()) {
1157 return Evaluate(static_cast<const AtomicConstraint &>(Constraint), MLTAL);
1158
1160 return Evaluate(static_cast<const FoldExpandedConstraint &>(Constraint),
1161 MLTAL);
1162
1164 return Evaluate(static_cast<const ConceptIdConstraint &>(Constraint),
1165 MLTAL);
1166
1168 return Evaluate(static_cast<const CompoundConstraint &>(Constraint), MLTAL);
1169 }
1170 llvm_unreachable("Unknown ConstraintKind enum");
1171}
1172
1174 Sema &S, const NamedDecl *Template,
1175 ArrayRef<AssociatedConstraint> AssociatedConstraints,
1176 const MultiLevelTemplateArgumentList &TemplateArgsLists,
1177 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
1178 Expr **ConvertedExpr, const ConceptReference *TopLevelConceptId = nullptr) {
1179
1180 if (ConvertedExpr)
1181 *ConvertedExpr = nullptr;
1182
1183 if (AssociatedConstraints.empty()) {
1184 Satisfaction.IsSatisfied = true;
1185 return false;
1186 }
1187
1188 if (TemplateArgsLists.isAnyArgInstantiationDependent(S.Context)) {
1189 // No need to check satisfaction for dependent constraint expressions.
1190 Satisfaction.IsSatisfied = true;
1191 return false;
1192 }
1193
1195 if (TemplateArgsLists.getNumLevels() != 0)
1196 Args = TemplateArgsLists.getInnermost();
1197
1198 struct SynthesisContextPair {
1201 SynthesisContextPair(Sema &S, NamedDecl *Template,
1202 ArrayRef<TemplateArgument> TemplateArgs,
1203 SourceRange InstantiationRange)
1204 : Inst(S, InstantiationRange.getBegin(),
1206 TemplateArgs, InstantiationRange),
1207 NSC(S) {}
1208 };
1209 std::optional<SynthesisContextPair> SynthesisContext;
1210 if (!TopLevelConceptId)
1211 SynthesisContext.emplace(S, const_cast<NamedDecl *>(Template), Args,
1212 TemplateIDRange);
1213
1214 const NormalizedConstraint *C =
1215 S.getNormalizedAssociatedConstraints(Template, AssociatedConstraints);
1216 if (!C) {
1217 Satisfaction.IsSatisfied = false;
1218 return true;
1219 }
1220
1221 if (TopLevelConceptId)
1222 C = ConceptIdConstraint::Create(S.getASTContext(), TopLevelConceptId,
1223 const_cast<NormalizedConstraint *>(C),
1224 Template, /*CSE=*/nullptr,
1226
1227 ExprResult Res = ConstraintSatisfactionChecker(
1228 S, Template, TemplateIDRange.getBegin(),
1229 S.ArgPackSubstIndex, Satisfaction,
1230 /*BuildExpression=*/ConvertedExpr != nullptr)
1231 .Evaluate(*C, TemplateArgsLists);
1232
1233 if (Res.isInvalid())
1234 return true;
1235
1236 if (Res.isUsable() && ConvertedExpr)
1237 *ConvertedExpr = Res.get();
1238
1239 return false;
1240}
1241
1244 ArrayRef<AssociatedConstraint> AssociatedConstraints,
1245 const MultiLevelTemplateArgumentList &TemplateArgsLists,
1246 SourceRange TemplateIDRange, ConstraintSatisfaction &OutSatisfaction,
1247 const ConceptReference *TopLevelConceptId, Expr **ConvertedExpr) {
1248 llvm::TimeTraceScope TimeScope(
1249 "CheckConstraintSatisfaction", [TemplateIDRange, this] {
1250 return TemplateIDRange.printToString(getSourceManager());
1251 });
1252 if (AssociatedConstraints.empty()) {
1253 OutSatisfaction.IsSatisfied = true;
1254 return false;
1255 }
1256 const auto *Template = Entity.dyn_cast<const NamedDecl *>();
1257 if (!Template) {
1258 return ::CheckConstraintSatisfaction(
1259 *this, nullptr, AssociatedConstraints, TemplateArgsLists,
1260 TemplateIDRange, OutSatisfaction, ConvertedExpr, TopLevelConceptId);
1261 }
1262 // Invalid templates could make their way here. Substituting them could result
1263 // in dependent expressions.
1264 if (Template->isInvalidDecl()) {
1265 OutSatisfaction.IsSatisfied = false;
1266 return true;
1267 }
1268
1269 // A list of the template argument list flattened in a predictible manner for
1270 // the purposes of caching. The ConstraintSatisfaction type is in AST so it
1271 // has no access to the MultiLevelTemplateArgumentList, so this has to happen
1272 // here.
1274 for (auto List : TemplateArgsLists)
1275 for (const TemplateArgument &Arg : List.Args)
1276 FlattenedArgs.emplace_back(Context.getCanonicalTemplateArgument(Arg));
1277
1278 const NamedDecl *Owner = Template;
1279 if (TopLevelConceptId)
1280 Owner = TopLevelConceptId->getNamedConcept();
1281
1282 llvm::FoldingSetNodeID ID;
1283 ConstraintSatisfaction::Profile(ID, Context, Owner, FlattenedArgs);
1284 void *InsertPos;
1285 if (auto *Cached = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos)) {
1286 OutSatisfaction = *Cached;
1287 return false;
1288 }
1289
1290 auto Satisfaction =
1291 std::make_unique<ConstraintSatisfaction>(Owner, FlattenedArgs);
1293 *this, Template, AssociatedConstraints, TemplateArgsLists,
1294 TemplateIDRange, *Satisfaction, ConvertedExpr, TopLevelConceptId)) {
1295 OutSatisfaction = std::move(*Satisfaction);
1296 return true;
1297 }
1298
1299 if (auto *Cached = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos)) {
1300 // The evaluation of this constraint resulted in us trying to re-evaluate it
1301 // recursively. This isn't really possible, except we try to form a
1302 // RecoveryExpr as a part of the evaluation. If this is the case, just
1303 // return the 'cached' version (which will have the same result), and save
1304 // ourselves the extra-insert. If it ever becomes possible to legitimately
1305 // recursively check a constraint, we should skip checking the 'inner' one
1306 // above, and replace the cached version with this one, as it would be more
1307 // specific.
1308 OutSatisfaction = *Cached;
1309 return false;
1310 }
1311
1312 // Else we can simply add this satisfaction to the list.
1313 OutSatisfaction = *Satisfaction;
1314 // We cannot use InsertPos here because CheckConstraintSatisfaction might have
1315 // invalidated it.
1316 // Note that entries of SatisfactionCache are deleted in Sema's destructor.
1317 SatisfactionCache.InsertNode(Satisfaction.release());
1318 return false;
1319}
1320
1321static ExprResult
1323 const ConceptSpecializationExpr *CSE,
1324 UnsignedOrNone SubstIndex) {
1325
1326 // [C++2c] [temp.constr.normal]
1327 // Otherwise, to form CE, any non-dependent concept template argument Ai
1328 // is substituted into the constraint-expression of C.
1329 // If any such substitution results in an invalid concept-id,
1330 // the program is ill-formed; no diagnostic is required.
1331
1333 Sema::ArgPackSubstIndexRAII _(S, SubstIndex);
1334
1335 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1337 if (llvm::none_of(
1338 ArgsAsWritten->arguments(), [&](const TemplateArgumentLoc &ArgLoc) {
1339 return !ArgLoc.getArgument().isDependent() &&
1340 ArgLoc.getArgument().isConceptOrConceptTemplateParameter();
1341 })) {
1342 return Concept->getConstraintExpr();
1343 }
1344
1346 Concept, Concept->getLexicalDeclContext(),
1347 /*Final=*/false, CSE->getTemplateArguments(),
1348 /*RelativeToPrimary=*/true,
1349 /*Pattern=*/nullptr,
1350 /*ForConstraintInstantiation=*/true);
1351 return S.SubstConceptTemplateArguments(CSE, Concept->getConstraintExpr(),
1352 MLTAL);
1353}
1354
1355bool Sema::SetupConstraintScope(
1356 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
1357 const MultiLevelTemplateArgumentList &MLTAL,
1359 assert(!isLambdaCallOperator(FD) &&
1360 "Use LambdaScopeForCallOperatorInstantiationRAII to handle lambda "
1361 "instantiations");
1362 if (FD->isTemplateInstantiation() && FD->getPrimaryTemplate()) {
1363 FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
1365 *this, FD->getPointOfInstantiation(),
1366 Sema::InstantiatingTemplate::ConstraintsCheck{}, PrimaryTemplate,
1367 TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
1368 SourceRange());
1369 if (Inst.isInvalid())
1370 return true;
1371
1372 // addInstantiatedParametersToScope creates a map of 'uninstantiated' to
1373 // 'instantiated' parameters and adds it to the context. For the case where
1374 // this function is a template being instantiated NOW, we also need to add
1375 // the list of current template arguments to the list so that they also can
1376 // be picked out of the map.
1377 if (auto *SpecArgs = FD->getTemplateSpecializationArgs()) {
1378 MultiLevelTemplateArgumentList JustTemplArgs(FD, SpecArgs->asArray(),
1379 /*Final=*/false);
1380 if (addInstantiatedParametersToScope(
1381 FD, PrimaryTemplate->getTemplatedDecl(), Scope, JustTemplArgs))
1382 return true;
1383 }
1384
1385 // If this is a member function, make sure we get the parameters that
1386 // reference the original primary template.
1387 if (FunctionTemplateDecl *FromMemTempl =
1388 PrimaryTemplate->getInstantiatedFromMemberTemplate()) {
1389 if (addInstantiatedParametersToScope(FD, FromMemTempl->getTemplatedDecl(),
1390 Scope, MLTAL))
1391 return true;
1392 }
1393
1394 return false;
1395 }
1396
1399 FunctionDecl *InstantiatedFrom =
1403
1405 *this, FD->getPointOfInstantiation(),
1406 Sema::InstantiatingTemplate::ConstraintsCheck{}, InstantiatedFrom,
1407 TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
1408 SourceRange());
1409 if (Inst.isInvalid())
1410 return true;
1411
1412 // Case where this was not a template, but instantiated as a
1413 // child-function.
1414 if (addInstantiatedParametersToScope(FD, InstantiatedFrom, Scope, MLTAL))
1415 return true;
1416 }
1417
1418 return false;
1419}
1420
1421// This function collects all of the template arguments for the purposes of
1422// constraint-instantiation and checking.
1423std::optional<MultiLevelTemplateArgumentList>
1424Sema::SetupConstraintCheckingTemplateArgumentsAndScope(
1425 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
1427 MultiLevelTemplateArgumentList MLTAL;
1428
1429 // Collect the list of template arguments relative to the 'primary' template.
1430 // We need the entire list, since the constraint is completely uninstantiated
1431 // at this point.
1432 MLTAL =
1434 /*Final=*/false, /*Innermost=*/std::nullopt,
1435 /*RelativeToPrimary=*/true,
1436 /*Pattern=*/nullptr,
1437 /*ForConstraintInstantiation=*/true);
1438 // Lambdas are handled by LambdaScopeForCallOperatorInstantiationRAII.
1439 if (isLambdaCallOperator(FD))
1440 return MLTAL;
1441 if (SetupConstraintScope(FD, TemplateArgs, MLTAL, Scope))
1442 return std::nullopt;
1443
1444 return MLTAL;
1445}
1446
1448 ConstraintSatisfaction &Satisfaction,
1449 SourceLocation UsageLoc,
1450 bool ForOverloadResolution) {
1451 // Don't check constraints if the function is dependent. Also don't check if
1452 // this is a function template specialization, as the call to
1453 // CheckFunctionTemplateConstraints after this will check it
1454 // better.
1455 if (FD->isDependentContext() ||
1456 FD->getTemplatedKind() ==
1458 Satisfaction.IsSatisfied = true;
1459 return false;
1460 }
1461
1462 // A lambda conversion operator has the same constraints as the call operator
1463 // and constraints checking relies on whether we are in a lambda call operator
1464 // (and may refer to its parameters), so check the call operator instead.
1465 // Note that the declarations outside of the lambda should also be
1466 // considered. Turning on the 'ForOverloadResolution' flag results in the
1467 // LocalInstantiationScope not looking into its parents, but we can still
1468 // access Decls from the parents while building a lambda RAII scope later.
1469 if (const auto *MD = dyn_cast<CXXConversionDecl>(FD);
1470 MD && isLambdaConversionOperator(const_cast<CXXConversionDecl *>(MD)))
1471 return CheckFunctionConstraints(MD->getParent()->getLambdaCallOperator(),
1472 Satisfaction, UsageLoc,
1473 /*ShouldAddDeclsFromParentScope=*/true);
1474
1475 DeclContext *CtxToSave = const_cast<FunctionDecl *>(FD);
1476
1477 while (isLambdaCallOperator(CtxToSave) || FD->isTransparentContext()) {
1478 if (isLambdaCallOperator(CtxToSave))
1479 CtxToSave = CtxToSave->getParent()->getParent();
1480 else
1481 CtxToSave = CtxToSave->getNonTransparentContext();
1482 }
1483
1484 ContextRAII SavedContext{*this, CtxToSave};
1485 LocalInstantiationScope Scope(*this, !ForOverloadResolution);
1486 std::optional<MultiLevelTemplateArgumentList> MLTAL =
1487 SetupConstraintCheckingTemplateArgumentsAndScope(
1488 const_cast<FunctionDecl *>(FD), {}, Scope);
1489
1490 if (!MLTAL)
1491 return true;
1492
1493 Qualifiers ThisQuals;
1494 CXXRecordDecl *Record = nullptr;
1495 if (auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
1496 ThisQuals = Method->getMethodQualifiers();
1497 Record = const_cast<CXXRecordDecl *>(Method->getParent());
1498 }
1499 CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
1500
1502 *this, const_cast<FunctionDecl *>(FD), *MLTAL, Scope,
1503 ForOverloadResolution);
1504
1506 FD, FD->getTrailingRequiresClause(), *MLTAL,
1507 SourceRange(UsageLoc.isValid() ? UsageLoc : FD->getLocation()),
1508 Satisfaction);
1509}
1510
1512 Sema &S, const Sema::TemplateCompareNewDeclInfo &DeclInfo,
1513 const Expr *ConstrExpr) {
1515 DeclInfo.getDecl(), DeclInfo.getDeclContext(), /*Final=*/false,
1516 /*Innermost=*/std::nullopt,
1517 /*RelativeToPrimary=*/true,
1518 /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
1519 /*SkipForSpecialization*/ false);
1520
1521 if (MLTAL.getNumSubstitutedLevels() == 0)
1522 return ConstrExpr;
1523
1526 S, DeclInfo.getLocation(),
1528 const_cast<NamedDecl *>(DeclInfo.getDecl()), SourceRange{});
1529 if (Inst.isInvalid())
1530 return nullptr;
1531
1532 // Set up a dummy 'instantiation' scope in the case of reference to function
1533 // parameters that the surrounding function hasn't been instantiated yet. Note
1534 // this may happen while we're comparing two templates' constraint
1535 // equivalence.
1536 std::optional<LocalInstantiationScope> ScopeForParameters;
1537 if (const NamedDecl *ND = DeclInfo.getDecl();
1538 ND && ND->isFunctionOrFunctionTemplate()) {
1539 ScopeForParameters.emplace(S, /*CombineWithOuterScope=*/true);
1540 const FunctionDecl *FD = ND->getAsFunction();
1542 Template && Template->getInstantiatedFromMemberTemplate())
1543 FD = Template->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
1544 for (auto *PVD : FD->parameters()) {
1545 if (ScopeForParameters->getInstantiationOfIfExists(PVD))
1546 continue;
1547 if (!PVD->isParameterPack()) {
1548 ScopeForParameters->InstantiatedLocal(PVD, PVD);
1549 continue;
1550 }
1551 // This is hacky: we're mapping the parameter pack to a size-of-1 argument
1552 // to avoid building SubstTemplateTypeParmPackTypes for
1553 // PackExpansionTypes. The SubstTemplateTypeParmPackType node would
1554 // otherwise reference the AssociatedDecl of the template arguments, which
1555 // is, in this case, the template declaration.
1556 //
1557 // However, as we are in the process of comparing potential
1558 // re-declarations, the canonical declaration is the declaration itself at
1559 // this point. So if we didn't expand these packs, we would end up with an
1560 // incorrect profile difference because we will be profiling the
1561 // canonical types!
1562 //
1563 // FIXME: Improve the "no-transform" machinery in FindInstantiatedDecl so
1564 // that we can eliminate the Scope in the cases where the declarations are
1565 // not necessarily instantiated. It would also benefit the noexcept
1566 // specifier comparison.
1567 ScopeForParameters->MakeInstantiatedLocalArgPack(PVD);
1568 ScopeForParameters->InstantiatedLocalPackArg(PVD, PVD);
1569 }
1570 }
1571
1572 std::optional<Sema::CXXThisScopeRAII> ThisScope;
1573
1574 // See TreeTransform::RebuildTemplateSpecializationType. A context scope is
1575 // essential for having an injected class as the canonical type for a template
1576 // specialization type at the rebuilding stage. This guarantees that, for
1577 // out-of-line definitions, injected class name types and their equivalent
1578 // template specializations can be profiled to the same value, which makes it
1579 // possible that e.g. constraints involving C<Class<T>> and C<Class> are
1580 // perceived identical.
1581 std::optional<Sema::ContextRAII> ContextScope;
1582 const DeclContext *DC = [&] {
1583 if (!DeclInfo.getDecl())
1584 return DeclInfo.getDeclContext();
1585 return DeclInfo.getDecl()->getFriendObjectKind()
1586 ? DeclInfo.getLexicalDeclContext()
1587 : DeclInfo.getDeclContext();
1588 }();
1589 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
1590 ThisScope.emplace(S, const_cast<CXXRecordDecl *>(RD), Qualifiers());
1591 ContextScope.emplace(S, const_cast<DeclContext *>(cast<DeclContext>(RD)),
1592 /*NewThisContext=*/false);
1593 }
1594 EnterExpressionEvaluationContext UnevaluatedContext(
1598 const_cast<clang::Expr *>(ConstrExpr), MLTAL);
1599 if (!SubstConstr.isUsable())
1600 return nullptr;
1601 return SubstConstr.get();
1602}
1603
1605 const Expr *OldConstr,
1607 const Expr *NewConstr) {
1608 if (OldConstr == NewConstr)
1609 return true;
1610 // C++ [temp.constr.decl]p4
1611 if (Old && !New.isInvalid() && !New.ContainsDecl(Old) &&
1612 Old->getLexicalDeclContext() != New.getLexicalDeclContext()) {
1613 if (const Expr *SubstConstr =
1615 OldConstr))
1616 OldConstr = SubstConstr;
1617 else
1618 return false;
1619 if (const Expr *SubstConstr =
1621 NewConstr))
1622 NewConstr = SubstConstr;
1623 else
1624 return false;
1625 }
1626
1627 llvm::FoldingSetNodeID ID1, ID2;
1628 OldConstr->Profile(ID1, Context, /*Canonical=*/true);
1629 NewConstr->Profile(ID2, Context, /*Canonical=*/true);
1630 return ID1 == ID2;
1631}
1632
1634 assert(FD->getFriendObjectKind() && "Must be a friend!");
1635
1636 // The logic for non-templates is handled in ASTContext::isSameEntity, so we
1637 // don't have to bother checking 'DependsOnEnclosingTemplate' for a
1638 // non-function-template.
1639 assert(FD->getDescribedFunctionTemplate() &&
1640 "Non-function templates don't need to be checked");
1641
1644
1645 unsigned OldTemplateDepth = CalculateTemplateDepthForConstraints(*this, FD);
1646 for (const AssociatedConstraint &AC : ACs)
1647 if (ConstraintExpressionDependsOnEnclosingTemplate(FD, OldTemplateDepth,
1648 AC.ConstraintExpr))
1649 return true;
1650
1651 return false;
1652}
1653
1655 TemplateDecl *TD, const MultiLevelTemplateArgumentList &TemplateArgsLists,
1656 SourceRange TemplateIDRange) {
1657 ConstraintSatisfaction Satisfaction;
1658 llvm::SmallVector<AssociatedConstraint, 3> AssociatedConstraints;
1659 TD->getAssociatedConstraints(AssociatedConstraints);
1660 if (CheckConstraintSatisfaction(TD, AssociatedConstraints, TemplateArgsLists,
1661 TemplateIDRange, Satisfaction))
1662 return true;
1663
1664 if (!Satisfaction.IsSatisfied) {
1665 SmallString<128> TemplateArgString;
1666 TemplateArgString = " ";
1667 TemplateArgString += getTemplateArgumentBindingsText(
1668 TD->getTemplateParameters(), TemplateArgsLists.getInnermost().data(),
1669 TemplateArgsLists.getInnermost().size());
1670
1671 Diag(TemplateIDRange.getBegin(),
1672 diag::err_template_arg_list_constraints_not_satisfied)
1674 << TemplateArgString << TemplateIDRange;
1675 DiagnoseUnsatisfiedConstraint(Satisfaction);
1676 return true;
1677 }
1678 return false;
1679}
1680
1682 Sema &SemaRef, SourceLocation PointOfInstantiation,
1684 ConstraintSatisfaction &Satisfaction) {
1686 Template->getAssociatedConstraints(TemplateAC);
1687 if (TemplateAC.empty()) {
1688 Satisfaction.IsSatisfied = true;
1689 return false;
1690 }
1691
1693
1694 FunctionDecl *FD = Template->getTemplatedDecl();
1695 // Collect the list of template arguments relative to the 'primary'
1696 // template. We need the entire list, since the constraint is completely
1697 // uninstantiated at this point.
1698
1700 {
1701 // getTemplateInstantiationArgs uses this instantiation context to find out
1702 // template arguments for uninstantiated functions.
1703 // We don't want this RAII object to persist, because there would be
1704 // otherwise duplicate diagnostic notes.
1706 SemaRef, PointOfInstantiation,
1708 PointOfInstantiation);
1709 if (Inst.isInvalid())
1710 return true;
1711 MLTAL = SemaRef.getTemplateInstantiationArgs(
1712 /*D=*/FD, FD,
1713 /*Final=*/false, /*Innermost=*/{}, /*RelativeToPrimary=*/true,
1714 /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true);
1715 }
1716
1717 Sema::ContextRAII SavedContext(SemaRef, FD);
1718 return SemaRef.CheckConstraintSatisfaction(
1719 Template, TemplateAC, MLTAL, PointOfInstantiation, Satisfaction);
1720}
1721
1723 SourceLocation PointOfInstantiation, FunctionDecl *Decl,
1724 ArrayRef<TemplateArgument> TemplateArgs,
1725 ConstraintSatisfaction &Satisfaction) {
1726 // In most cases we're not going to have constraints, so check for that first.
1727 FunctionTemplateDecl *Template = Decl->getPrimaryTemplate();
1728
1729 if (!Template)
1730 return ::CheckFunctionConstraintsWithoutInstantiation(
1731 *this, PointOfInstantiation, Decl->getDescribedFunctionTemplate(),
1732 TemplateArgs, Satisfaction);
1733
1734 // Note - code synthesis context for the constraints check is created
1735 // inside CheckConstraintsSatisfaction.
1737 Template->getAssociatedConstraints(TemplateAC);
1738 if (TemplateAC.empty()) {
1739 Satisfaction.IsSatisfied = true;
1740 return false;
1741 }
1742
1743 // Enter the scope of this instantiation. We don't use
1744 // PushDeclContext because we don't have a scope.
1745 Sema::ContextRAII savedContext(*this, Decl);
1747
1748 std::optional<MultiLevelTemplateArgumentList> MLTAL =
1749 SetupConstraintCheckingTemplateArgumentsAndScope(Decl, TemplateArgs,
1750 Scope);
1751
1752 if (!MLTAL)
1753 return true;
1754
1755 Qualifiers ThisQuals;
1756 CXXRecordDecl *Record = nullptr;
1757 if (auto *Method = dyn_cast<CXXMethodDecl>(Decl)) {
1758 ThisQuals = Method->getMethodQualifiers();
1759 Record = Method->getParent();
1760 }
1761
1762 CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
1763 LambdaScopeForCallOperatorInstantiationRAII LambdaScope(*this, Decl, *MLTAL,
1764 Scope);
1765
1766 return CheckConstraintSatisfaction(Template, TemplateAC, *MLTAL,
1767 PointOfInstantiation, Satisfaction);
1768}
1769
1772 bool First) {
1773 assert(!Req->isSatisfied() &&
1774 "Diagnose() can only be used on an unsatisfied requirement");
1775 switch (Req->getSatisfactionStatus()) {
1777 llvm_unreachable("Diagnosing a dependent requirement");
1778 break;
1780 auto *SubstDiag = Req->getExprSubstitutionDiagnostic();
1781 if (!SubstDiag->DiagMessage.empty())
1782 S.Diag(SubstDiag->DiagLoc,
1783 diag::note_expr_requirement_expr_substitution_error)
1784 << (int)First << SubstDiag->SubstitutedEntity
1785 << SubstDiag->DiagMessage;
1786 else
1787 S.Diag(SubstDiag->DiagLoc,
1788 diag::note_expr_requirement_expr_unknown_substitution_error)
1789 << (int)First << SubstDiag->SubstitutedEntity;
1790 break;
1791 }
1793 S.Diag(Req->getNoexceptLoc(), diag::note_expr_requirement_noexcept_not_met)
1794 << (int)First << Req->getExpr();
1795 break;
1797 auto *SubstDiag =
1799 if (!SubstDiag->DiagMessage.empty())
1800 S.Diag(SubstDiag->DiagLoc,
1801 diag::note_expr_requirement_type_requirement_substitution_error)
1802 << (int)First << SubstDiag->SubstitutedEntity
1803 << SubstDiag->DiagMessage;
1804 else
1805 S.Diag(
1806 SubstDiag->DiagLoc,
1807 diag::
1808 note_expr_requirement_type_requirement_unknown_substitution_error)
1809 << (int)First << SubstDiag->SubstitutedEntity;
1810 break;
1811 }
1813 ConceptSpecializationExpr *ConstraintExpr =
1815 S.DiagnoseUnsatisfiedConstraint(ConstraintExpr);
1816 break;
1817 }
1819 llvm_unreachable("We checked this above");
1820 }
1821}
1822
1825 bool First) {
1826 assert(!Req->isSatisfied() &&
1827 "Diagnose() can only be used on an unsatisfied requirement");
1828 switch (Req->getSatisfactionStatus()) {
1830 llvm_unreachable("Diagnosing a dependent requirement");
1831 return;
1833 auto *SubstDiag = Req->getSubstitutionDiagnostic();
1834 if (!SubstDiag->DiagMessage.empty())
1835 S.Diag(SubstDiag->DiagLoc, diag::note_type_requirement_substitution_error)
1836 << (int)First << SubstDiag->SubstitutedEntity
1837 << SubstDiag->DiagMessage;
1838 else
1839 S.Diag(SubstDiag->DiagLoc,
1840 diag::note_type_requirement_unknown_substitution_error)
1841 << (int)First << SubstDiag->SubstitutedEntity;
1842 return;
1843 }
1844 default:
1845 llvm_unreachable("Unknown satisfaction status");
1846 return;
1847 }
1848}
1849
1852 SourceLocation Loc, bool First) {
1853 if (Concept->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
1854 S.Diag(
1855 Loc,
1856 diag::
1857 note_single_arg_concept_specialization_constraint_evaluated_to_false)
1858 << (int)First
1859 << Concept->getTemplateArgsAsWritten()->arguments()[0].getArgument()
1860 << Concept->getNamedConcept();
1861 } else {
1862 S.Diag(Loc, diag::note_concept_specialization_constraint_evaluated_to_false)
1863 << (int)First << Concept;
1864 }
1865}
1866
1869 bool First, concepts::NestedRequirement *Req = nullptr);
1870
1873 bool First = true, concepts::NestedRequirement *Req = nullptr) {
1874 for (auto &Record : Records) {
1876 Loc = {};
1878 }
1879}
1880
1890
1892 const Expr *SubstExpr,
1893 bool First) {
1894 SubstExpr = SubstExpr->IgnoreParenImpCasts();
1895 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(SubstExpr)) {
1896 switch (BO->getOpcode()) {
1897 // These two cases will in practice only be reached when using fold
1898 // expressions with || and &&, since otherwise the || and && will have been
1899 // broken down into atomic constraints during satisfaction checking.
1900 case BO_LOr:
1901 // Or evaluated to false - meaning both RHS and LHS evaluated to false.
1904 /*First=*/false);
1905 return;
1906 case BO_LAnd: {
1907 bool LHSSatisfied =
1908 BO->getLHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
1909 if (LHSSatisfied) {
1910 // LHS is true, so RHS must be false.
1912 return;
1913 }
1914 // LHS is false
1916
1917 // RHS might also be false
1918 bool RHSSatisfied =
1919 BO->getRHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
1920 if (!RHSSatisfied)
1922 /*First=*/false);
1923 return;
1924 }
1925 case BO_GE:
1926 case BO_LE:
1927 case BO_GT:
1928 case BO_LT:
1929 case BO_EQ:
1930 case BO_NE:
1931 if (BO->getLHS()->getType()->isIntegerType() &&
1932 BO->getRHS()->getType()->isIntegerType()) {
1933 Expr::EvalResult SimplifiedLHS;
1934 Expr::EvalResult SimplifiedRHS;
1935 BO->getLHS()->EvaluateAsInt(SimplifiedLHS, S.Context,
1937 /*InConstantContext=*/true);
1938 BO->getRHS()->EvaluateAsInt(SimplifiedRHS, S.Context,
1940 /*InConstantContext=*/true);
1941 if (!SimplifiedLHS.Diag && !SimplifiedRHS.Diag) {
1942 S.Diag(SubstExpr->getBeginLoc(),
1943 diag::note_atomic_constraint_evaluated_to_false_elaborated)
1944 << (int)First << SubstExpr
1945 << toString(SimplifiedLHS.Val.getInt(), 10)
1946 << BinaryOperator::getOpcodeStr(BO->getOpcode())
1947 << toString(SimplifiedRHS.Val.getInt(), 10);
1948 return;
1949 }
1950 }
1951 break;
1952
1953 default:
1954 break;
1955 }
1956 } else if (auto *RE = dyn_cast<RequiresExpr>(SubstExpr)) {
1957 // FIXME: RequiresExpr should store dependent diagnostics.
1958 for (concepts::Requirement *Req : RE->getRequirements())
1959 if (!Req->isDependent() && !Req->isSatisfied()) {
1960 if (auto *E = dyn_cast<concepts::ExprRequirement>(Req))
1962 else if (auto *T = dyn_cast<concepts::TypeRequirement>(Req))
1964 else
1967 break;
1968 }
1969 return;
1970 } else if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(SubstExpr)) {
1971 // Drill down concept ids treated as atomic constraints
1973 return;
1974 } else if (auto *TTE = dyn_cast<TypeTraitExpr>(SubstExpr);
1975 TTE && TTE->getTrait() == clang::TypeTrait::BTT_IsDeducible) {
1976 assert(TTE->getNumArgs() == 2);
1977 S.Diag(SubstExpr->getSourceRange().getBegin(),
1978 diag::note_is_deducible_constraint_evaluated_to_false)
1979 << TTE->getArg(0)->getType() << TTE->getArg(1)->getType();
1980 return;
1981 }
1982
1983 S.Diag(SubstExpr->getSourceRange().getBegin(),
1984 diag::note_atomic_constraint_evaluated_to_false)
1985 << (int)First << SubstExpr;
1986 S.DiagnoseTypeTraitDetails(SubstExpr);
1987}
1988
1992 if (auto *Diag =
1993 Record
1994 .template dyn_cast<const ConstraintSubstitutionDiagnostic *>()) {
1995 if (Req)
1996 S.Diag(Diag->first, diag::note_nested_requirement_substitution_error)
1997 << (int)First << Req->getInvalidConstraintEntity() << Diag->second;
1998 else
1999 S.Diag(Diag->first, diag::note_substituted_constraint_expr_is_ill_formed)
2000 << Diag->second;
2001 return;
2002 }
2003 if (const auto *Concept = dyn_cast<const ConceptReference *>(Record)) {
2004 if (Loc.isInvalid())
2005 Loc = Concept->getBeginLoc();
2007 return;
2008 }
2011}
2012
2014 const ConstraintSatisfaction &Satisfaction, SourceLocation Loc,
2015 bool First) {
2016
2017 assert(!Satisfaction.IsSatisfied &&
2018 "Attempted to diagnose a satisfied constraint");
2019 ::DiagnoseUnsatisfiedConstraint(*this, Satisfaction.Details, Loc, First);
2020}
2021
2023 const ConceptSpecializationExpr *ConstraintExpr, bool First) {
2024
2025 const ASTConstraintSatisfaction &Satisfaction =
2026 ConstraintExpr->getSatisfaction();
2027
2028 assert(!Satisfaction.IsSatisfied &&
2029 "Attempted to diagnose a satisfied constraint");
2030
2031 ::DiagnoseUnsatisfiedConstraint(*this, Satisfaction.records(),
2032 ConstraintExpr->getBeginLoc(), First);
2033}
2034
2035namespace {
2036
2037class SubstituteParameterMappings {
2038 Sema &SemaRef;
2039
2040 const MultiLevelTemplateArgumentList *MLTAL;
2041 const ASTTemplateArgumentListInfo *ArgsAsWritten;
2042
2043 // When normalizing a fold constraint, e.g.
2044 // C<Pack1, Pack2...> && ...
2045 // we want the TreeTransform to expand only Pack2 but not Pack1,
2046 // since Pack1 will be expanded during the evaluation of the fold expression.
2047 // This flag helps rewrite any non-PackExpansion packs into "expanded"
2048 // parameters.
2049 bool RemovePacksForFoldExpr;
2050
2051 SubstituteParameterMappings(Sema &SemaRef,
2052 const MultiLevelTemplateArgumentList *MLTAL,
2053 const ASTTemplateArgumentListInfo *ArgsAsWritten,
2054 bool RemovePacksForFoldExpr)
2055 : SemaRef(SemaRef), MLTAL(MLTAL), ArgsAsWritten(ArgsAsWritten),
2056 RemovePacksForFoldExpr(RemovePacksForFoldExpr) {}
2057
2058 void buildParameterMapping(NormalizedConstraintWithParamMapping &N);
2059
2060 bool substitute(NormalizedConstraintWithParamMapping &N);
2061
2062 bool substitute(ConceptIdConstraint &CC);
2063
2064public:
2065 SubstituteParameterMappings(Sema &SemaRef,
2066 bool RemovePacksForFoldExpr = false)
2067 : SemaRef(SemaRef), MLTAL(nullptr), ArgsAsWritten(nullptr),
2068 RemovePacksForFoldExpr(RemovePacksForFoldExpr) {}
2069
2070 bool substitute(NormalizedConstraint &N);
2071};
2072
2073void SubstituteParameterMappings::buildParameterMapping(
2075 TemplateParameterList *TemplateParams =
2076 cast<TemplateDecl>(N.getConstraintDecl())->getTemplateParameters();
2077
2078 llvm::SmallBitVector OccurringIndices(TemplateParams->size());
2079 llvm::SmallBitVector OccurringIndicesForSubsumption(TemplateParams->size());
2080
2083 static_cast<AtomicConstraint &>(N).getConstraintExpr(),
2084 /*OnlyDeduced=*/false,
2085 /*Depth=*/0, OccurringIndices);
2086
2088 static_cast<AtomicConstraint &>(N).getConstraintExpr(),
2089 /*Depth=*/0, OccurringIndicesForSubsumption);
2090
2091 } else if (N.getKind() ==
2094 static_cast<FoldExpandedConstraint &>(N).getPattern(),
2095 /*OnlyDeduced=*/false,
2096 /*Depth=*/0, OccurringIndices);
2098 auto *Args = static_cast<ConceptIdConstraint &>(N)
2099 .getConceptId()
2100 ->getTemplateArgsAsWritten();
2101 if (Args)
2102 SemaRef.MarkUsedTemplateParameters(Args->arguments(),
2103 /*Depth=*/0, OccurringIndices);
2104 }
2105 unsigned Size = OccurringIndices.count();
2106 // When the constraint is independent of any template parameters,
2107 // we build an empty mapping so that we can distinguish these cases
2108 // from cases where no mapping exists at all, e.g. when there are only atomic
2109 // constraints.
2110 TemplateArgumentLoc *TempArgs =
2111 new (SemaRef.Context) TemplateArgumentLoc[Size];
2113 for (unsigned I = 0, J = 0, C = TemplateParams->size(); I != C; ++I) {
2114 SourceLocation Loc = ArgsAsWritten->NumTemplateArgs > I
2115 ? ArgsAsWritten->arguments()[I].getLocation()
2116 : SourceLocation();
2117 // FIXME: Investigate why we couldn't always preserve the SourceLoc. We
2118 // can't assert Loc.isValid() now.
2119 if (OccurringIndices[I]) {
2120 NamedDecl *Param = TemplateParams->begin()[I];
2121 new (&(TempArgs)[J]) TemplateArgumentLoc(
2122 SemaRef.getIdentityTemplateArgumentLoc(Param, Loc));
2123 UsedParams.push_back(Param);
2124 J++;
2125 }
2126 }
2127 auto *UsedList = TemplateParameterList::Create(
2128 SemaRef.Context, TemplateParams->getTemplateLoc(),
2129 TemplateParams->getLAngleLoc(), UsedParams,
2130 /*RAngleLoc=*/SourceLocation(),
2131 /*RequiresClause=*/nullptr);
2133 std::move(OccurringIndices), std::move(OccurringIndicesForSubsumption),
2134 MutableArrayRef<TemplateArgumentLoc>{TempArgs, Size}, UsedList);
2135}
2136
2137bool SubstituteParameterMappings::substitute(
2139 if (!N.hasParameterMapping())
2140 buildParameterMapping(N);
2141
2142 // If the parameter mapping is empty, there is nothing to substitute.
2143 if (N.getParameterMapping().empty())
2144 return false;
2145
2146 SourceLocation InstLocBegin, InstLocEnd;
2147 llvm::ArrayRef Arguments = ArgsAsWritten->arguments();
2148 if (Arguments.empty()) {
2149 InstLocBegin = ArgsAsWritten->getLAngleLoc();
2150 InstLocEnd = ArgsAsWritten->getRAngleLoc();
2151 } else {
2152 auto SR = Arguments[0].getSourceRange();
2153 InstLocBegin = SR.getBegin();
2154 InstLocEnd = SR.getEnd();
2155 }
2156 Sema::NonSFINAEContext _(SemaRef);
2158 SemaRef, InstLocBegin,
2160 const_cast<NamedDecl *>(N.getConstraintDecl()),
2161 {InstLocBegin, InstLocEnd});
2162 if (Inst.isInvalid())
2163 return true;
2164
2165 // TransformTemplateArguments is unable to preserve the source location of a
2166 // pack. The SourceLocation is necessary for the instantiation location.
2167 // FIXME: The BaseLoc will be used as the location of the pack expansion,
2168 // which is wrong.
2169 TemplateArgumentListInfo SubstArgs;
2171 N.getParameterMapping(), N.getBeginLoc(), *MLTAL, SubstArgs))
2172 return true;
2174 auto *TD =
2177 TD->getLocation(), SubstArgs,
2178 /*DefaultArguments=*/{},
2179 /*PartialTemplateArgs=*/false, CTAI))
2180 return true;
2181
2182 TemplateArgumentLoc *TempArgs =
2183 new (SemaRef.Context) TemplateArgumentLoc[CTAI.SugaredConverted.size()];
2184
2185 for (unsigned I = 0; I < CTAI.SugaredConverted.size(); ++I) {
2186 SourceLocation Loc;
2187 // If this is an empty pack, we have no corresponding SubstArgs.
2188 if (I < SubstArgs.size())
2189 Loc = SubstArgs.arguments()[I].getLocation();
2190
2191 TempArgs[I] = SemaRef.getTrivialTemplateArgumentLoc(
2192 CTAI.SugaredConverted[I], QualType(), Loc);
2193 }
2194
2195 MutableArrayRef<TemplateArgumentLoc> Mapping(TempArgs,
2196 CTAI.SugaredConverted.size());
2200 return false;
2201}
2202
2203bool SubstituteParameterMappings::substitute(ConceptIdConstraint &CC) {
2204 assert(CC.getConstraintDecl() && MLTAL && ArgsAsWritten);
2205
2206 if (substitute(static_cast<NormalizedConstraintWithParamMapping &>(CC)))
2207 return true;
2208
2209 auto *CSE = CC.getConceptSpecializationExpr();
2210 assert(CSE);
2211 assert(!CC.getBeginLoc().isInvalid());
2212
2213 SourceLocation InstLocBegin, InstLocEnd;
2214 if (llvm::ArrayRef Arguments = ArgsAsWritten->arguments();
2215 Arguments.empty()) {
2216 InstLocBegin = ArgsAsWritten->getLAngleLoc();
2217 InstLocEnd = ArgsAsWritten->getRAngleLoc();
2218 } else {
2219 auto SR = Arguments[0].getSourceRange();
2220 InstLocBegin = SR.getBegin();
2221 InstLocEnd = SR.getEnd();
2222 }
2223 Sema::NonSFINAEContext _(SemaRef);
2224 // This is useful for name lookup across modules; see Sema::getLookupModules.
2226 SemaRef, InstLocBegin,
2228 const_cast<NamedDecl *>(CC.getConstraintDecl()),
2229 {InstLocBegin, InstLocEnd});
2230 if (Inst.isInvalid())
2231 return true;
2232
2234 // TransformTemplateArguments is unable to preserve the source location of a
2235 // pack. The SourceLocation is necessary for the instantiation location.
2236 // FIXME: The BaseLoc will be used as the location of the pack expansion,
2237 // which is wrong.
2238 const ASTTemplateArgumentListInfo *ArgsAsWritten =
2239 CSE->getTemplateArgsAsWritten();
2241 ArgsAsWritten->arguments(), CC.getBeginLoc(), *MLTAL, Out))
2242 return true;
2244 if (SemaRef.CheckTemplateArgumentList(CSE->getNamedConcept(),
2245 CSE->getConceptNameInfo().getLoc(), Out,
2246 /*DefaultArgs=*/{},
2247 /*PartialTemplateArgs=*/false, CTAI,
2248 /*UpdateArgsWithConversions=*/false))
2249 return true;
2250 auto TemplateArgs = *MLTAL;
2251 TemplateArgs.replaceOutermostTemplateArguments(CSE->getNamedConcept(),
2252 CTAI.SugaredConverted);
2253 return SubstituteParameterMappings(SemaRef, &TemplateArgs, ArgsAsWritten,
2254 RemovePacksForFoldExpr)
2255 .substitute(CC.getNormalizedConstraint());
2256}
2257
2258bool SubstituteParameterMappings::substitute(NormalizedConstraint &N) {
2259 switch (N.getKind()) {
2261 if (!MLTAL) {
2262 assert(!ArgsAsWritten);
2263 return false;
2264 }
2265 return substitute(static_cast<NormalizedConstraintWithParamMapping &>(N));
2266 }
2268 auto &FE = static_cast<FoldExpandedConstraint &>(N);
2269 if (!MLTAL) {
2270 llvm::SaveAndRestore _1(RemovePacksForFoldExpr, true);
2271 assert(!ArgsAsWritten);
2272 return substitute(FE.getNormalizedPattern());
2273 }
2274 Sema::ArgPackSubstIndexRAII _(SemaRef, std::nullopt);
2275 substitute(static_cast<NormalizedConstraintWithParamMapping &>(FE));
2276 return SubstituteParameterMappings(SemaRef, /*RemovePacksForFoldExpr=*/true)
2277 .substitute(FE.getNormalizedPattern());
2278 }
2280 auto &CC = static_cast<ConceptIdConstraint &>(N);
2281 if (MLTAL) {
2282 assert(ArgsAsWritten);
2283 return substitute(CC);
2284 }
2285 assert(!ArgsAsWritten);
2289 if (RemovePacksForFoldExpr) {
2291 ArrayRef<TemplateArgumentLoc> InputArgLoc =
2293 if (AdjustConstraints(SemaRef, /*TemplateDepth=*/0,
2294 /*RemoveNonPackExpansionPacks=*/true)
2295 .TransformTemplateArguments(InputArgLoc.begin(),
2296 InputArgLoc.end(), OutArgs))
2297 return true;
2299 // Repack the packs.
2300 if (SemaRef.CheckTemplateArgumentList(
2301 Concept, Concept->getTemplateParameters(), Concept->getBeginLoc(),
2302 OutArgs,
2303 /*DefaultArguments=*/{},
2304 /*PartialTemplateArgs=*/false, CTAI))
2305 return true;
2306 InnerArgs = std::move(CTAI.SugaredConverted);
2307 }
2308
2310 Concept, Concept->getLexicalDeclContext(),
2311 /*Final=*/true, InnerArgs,
2312 /*RelativeToPrimary=*/true,
2313 /*Pattern=*/nullptr,
2314 /*ForConstraintInstantiation=*/true);
2315
2316 return SubstituteParameterMappings(SemaRef, &MLTAL,
2318 RemovePacksForFoldExpr)
2319 .substitute(CC.getNormalizedConstraint());
2320 }
2322 auto &Compound = static_cast<CompoundConstraint &>(N);
2323 if (substitute(Compound.getLHS()))
2324 return true;
2325 return substitute(Compound.getRHS());
2326 }
2327 }
2328 llvm_unreachable("Unknown ConstraintKind enum");
2329}
2330
2331} // namespace
2332
2333NormalizedConstraint *NormalizedConstraint::fromAssociatedConstraints(
2334 Sema &S, const NamedDecl *D, ArrayRef<AssociatedConstraint> ACs) {
2335 assert(ACs.size() != 0);
2336 auto *Conjunction =
2337 fromConstraintExpr(S, D, ACs[0].ConstraintExpr, ACs[0].ArgPackSubstIndex);
2338 if (!Conjunction)
2339 return nullptr;
2340 for (unsigned I = 1; I < ACs.size(); ++I) {
2341 auto *Next = fromConstraintExpr(S, D, ACs[I].ConstraintExpr,
2342 ACs[I].ArgPackSubstIndex);
2343 if (!Next)
2344 return nullptr;
2346 Conjunction, Next);
2347 }
2348 return Conjunction;
2349}
2350
2351NormalizedConstraint *NormalizedConstraint::fromConstraintExpr(
2352 Sema &S, const NamedDecl *D, const Expr *E, UnsignedOrNone SubstIndex) {
2353 assert(E != nullptr);
2354
2355 // C++ [temp.constr.normal]p1.1
2356 // [...]
2357 // - The normal form of an expression (E) is the normal form of E.
2358 // [...]
2359 E = E->IgnoreParenImpCasts();
2360
2361 llvm::FoldingSetNodeID ID;
2362 if (D && DiagRecursiveConstraintEval(S, ID, D, E)) {
2363 return nullptr;
2364 }
2365 SatisfactionStackRAII StackRAII(S, D, ID);
2366
2367 // C++2a [temp.param]p4:
2368 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
2369 // Fold expression is considered atomic constraints per current wording.
2370 // See http://cplusplus.github.io/concepts-ts/ts-active.html#28
2371
2372 if (LogicalBinOp BO = E) {
2373 auto *LHS = fromConstraintExpr(S, D, BO.getLHS(), SubstIndex);
2374 if (!LHS)
2375 return nullptr;
2376 auto *RHS = fromConstraintExpr(S, D, BO.getRHS(), SubstIndex);
2377 if (!RHS)
2378 return nullptr;
2379
2381 S.Context, LHS, BO.isAnd() ? CCK_Conjunction : CCK_Disjunction, RHS);
2382 } else if (auto *CSE = dyn_cast<const ConceptSpecializationExpr>(E)) {
2383 NormalizedConstraint *SubNF;
2384 {
2385 Sema::NonSFINAEContext _(S);
2386 Sema::InstantiatingTemplate Inst(
2387 S, CSE->getExprLoc(),
2388 Sema::InstantiatingTemplate::ConstraintNormalization{},
2389 // FIXME: improve const-correctness of InstantiatingTemplate
2390 const_cast<NamedDecl *>(D), CSE->getSourceRange());
2391 if (Inst.isInvalid())
2392 return nullptr;
2393 // C++ [temp.constr.normal]p1.1
2394 // [...]
2395 // The normal form of an id-expression of the form C<A1, A2, ..., AN>,
2396 // where C names a concept, is the normal form of the
2397 // constraint-expression of C, after substituting A1, A2, ..., AN for C’s
2398 // respective template parameters in the parameter mappings in each atomic
2399 // constraint. If any such substitution results in an invalid type or
2400 // expression, the program is ill-formed; no diagnostic is required.
2401 // [...]
2402
2403 // Use canonical declarations to merge ConceptDecls across
2404 // different modules.
2405 ConceptDecl *CD = CSE->getNamedConcept()->getCanonicalDecl();
2406
2407 ExprResult Res =
2408 SubstituteConceptsInConstraintExpression(S, D, CSE, SubstIndex);
2409 if (!Res.isUsable())
2410 return nullptr;
2411
2412 SubNF = NormalizedConstraint::fromAssociatedConstraints(
2413 S, CD, AssociatedConstraint(Res.get(), SubstIndex));
2414
2415 if (!SubNF)
2416 return nullptr;
2417 }
2418
2420 CSE->getConceptReference(), SubNF, D,
2421 CSE, SubstIndex);
2422
2423 } else if (auto *FE = dyn_cast<const CXXFoldExpr>(E);
2424 FE && S.getLangOpts().CPlusPlus26 &&
2425 (FE->getOperator() == BinaryOperatorKind::BO_LAnd ||
2426 FE->getOperator() == BinaryOperatorKind::BO_LOr)) {
2427
2428 // Normalize fold expressions in C++26.
2429
2431 FE->getOperator() == BinaryOperatorKind::BO_LAnd
2434
2435 if (FE->getInit()) {
2436 auto *LHS = fromConstraintExpr(S, D, FE->getLHS(), SubstIndex);
2437 auto *RHS = fromConstraintExpr(S, D, FE->getRHS(), SubstIndex);
2438 if (!LHS || !RHS)
2439 return nullptr;
2440
2441 if (FE->isRightFold())
2443 FE->getPattern(), D, Kind, LHS);
2444 else
2446 FE->getPattern(), D, Kind, RHS);
2447
2449 S.getASTContext(), LHS,
2450 (FE->getOperator() == BinaryOperatorKind::BO_LAnd ? CCK_Conjunction
2451 : CCK_Disjunction),
2452 RHS);
2453 }
2454 auto *Sub = fromConstraintExpr(S, D, FE->getPattern(), SubstIndex);
2455 if (!Sub)
2456 return nullptr;
2458 D, Kind, Sub);
2459 }
2460 return AtomicConstraint::Create(S.getASTContext(), E, D, SubstIndex);
2461}
2462
2464 ConstrainedDeclOrNestedRequirement ConstrainedDeclOrNestedReq,
2465 ArrayRef<AssociatedConstraint> AssociatedConstraints) {
2466 if (!ConstrainedDeclOrNestedReq) {
2467 auto *Normalized = NormalizedConstraint::fromAssociatedConstraints(
2468 *this, nullptr, AssociatedConstraints);
2469 if (!Normalized ||
2470 SubstituteParameterMappings(*this).substitute(*Normalized))
2471 return nullptr;
2472
2473 return Normalized;
2474 }
2475
2476 // FIXME: ConstrainedDeclOrNestedReq is never a NestedRequirement!
2477 const NamedDecl *ND =
2478 ConstrainedDeclOrNestedReq.dyn_cast<const NamedDecl *>();
2479 auto CacheEntry = NormalizationCache.find(ConstrainedDeclOrNestedReq);
2480 if (CacheEntry == NormalizationCache.end()) {
2481 auto *Normalized = NormalizedConstraint::fromAssociatedConstraints(
2482 *this, ND, AssociatedConstraints);
2483 if (!Normalized) {
2484 NormalizationCache.try_emplace(ConstrainedDeclOrNestedReq, nullptr);
2485 return nullptr;
2486 }
2487 // substitute() can invalidate iterators of NormalizationCache.
2488 bool Failed = SubstituteParameterMappings(*this).substitute(*Normalized);
2489 CacheEntry =
2490 NormalizationCache.try_emplace(ConstrainedDeclOrNestedReq, Normalized)
2491 .first;
2492 if (Failed)
2493 return nullptr;
2494 }
2495 return CacheEntry->second;
2496}
2497
2500
2501 // [C++26] [temp.constr.fold]
2502 // Two fold expanded constraints are compatible for subsumption
2503 // if their respective constraints both contain an equivalent unexpanded pack.
2504
2507 APacks);
2509 BPacks);
2510
2511 for (const UnexpandedParameterPack &APack : APacks) {
2512 auto ADI = getDepthAndIndex(APack);
2513 if (!ADI)
2514 continue;
2515 auto It = llvm::find_if(BPacks, [&](const UnexpandedParameterPack &BPack) {
2516 return getDepthAndIndex(BPack) == ADI;
2517 });
2518 if (It != BPacks.end())
2519 return true;
2520 }
2521 return false;
2522}
2523
2526 const NamedDecl *D2,
2528 bool &Result) {
2529#ifndef NDEBUG
2530 if (const auto *FD1 = dyn_cast<FunctionDecl>(D1)) {
2531 auto IsExpectedEntity = [](const FunctionDecl *FD) {
2533 return Kind == FunctionDecl::TK_NonTemplate ||
2535 };
2536 const auto *FD2 = dyn_cast<FunctionDecl>(D2);
2537 assert(IsExpectedEntity(FD1) && FD2 && IsExpectedEntity(FD2) &&
2538 "use non-instantiated function declaration for constraints partial "
2539 "ordering");
2540 }
2541#endif
2542
2543 if (AC1.empty()) {
2544 Result = AC2.empty();
2545 return false;
2546 }
2547 if (AC2.empty()) {
2548 // TD1 has associated constraints and TD2 does not.
2549 Result = true;
2550 return false;
2551 }
2552
2553 std::pair<const NamedDecl *, const NamedDecl *> Key{D1, D2};
2554 auto CacheEntry = SubsumptionCache.find(Key);
2555 if (CacheEntry != SubsumptionCache.end()) {
2556 Result = CacheEntry->second;
2557 return false;
2558 }
2559
2560 unsigned Depth1 = CalculateTemplateDepthForConstraints(*this, D1, true);
2561 unsigned Depth2 = CalculateTemplateDepthForConstraints(*this, D2, true);
2562
2563 for (size_t I = 0; I != AC1.size() && I != AC2.size(); ++I) {
2564 if (Depth2 > Depth1) {
2565 AC1[I].ConstraintExpr =
2566 AdjustConstraints(*this, Depth2 - Depth1)
2567 .TransformExpr(const_cast<Expr *>(AC1[I].ConstraintExpr))
2568 .get();
2569 } else if (Depth1 > Depth2) {
2570 AC2[I].ConstraintExpr =
2571 AdjustConstraints(*this, Depth1 - Depth2)
2572 .TransformExpr(const_cast<Expr *>(AC2[I].ConstraintExpr))
2573 .get();
2574 }
2575 }
2576
2577 SubsumptionChecker SC(*this);
2578 std::optional<bool> Subsumes = SC.Subsumes(D1, AC1, D2, AC2);
2579 if (!Subsumes) {
2580 // Normalization failed
2581 return true;
2582 }
2583 Result = *Subsumes;
2584 SubsumptionCache.try_emplace(Key, *Subsumes);
2585 return false;
2586}
2587
2591 if (isSFINAEContext())
2592 // No need to work here because our notes would be discarded.
2593 return false;
2594
2595 if (AC1.empty() || AC2.empty())
2596 return false;
2597
2598 const Expr *AmbiguousAtomic1 = nullptr, *AmbiguousAtomic2 = nullptr;
2599 auto IdenticalExprEvaluator = [&](const AtomicConstraint &A,
2600 const AtomicConstraint &B) {
2602 return false;
2603 const Expr *EA = A.getConstraintExpr(), *EB = B.getConstraintExpr();
2604 if (EA == EB)
2605 return true;
2606
2607 // Not the same source level expression - are the expressions
2608 // identical?
2609 llvm::FoldingSetNodeID IDA, IDB;
2610 EA->Profile(IDA, Context, /*Canonical=*/true);
2611 EB->Profile(IDB, Context, /*Canonical=*/true);
2612 if (IDA != IDB)
2613 return false;
2614
2615 AmbiguousAtomic1 = EA;
2616 AmbiguousAtomic2 = EB;
2617 return true;
2618 };
2619
2620 {
2621 auto *Normalized1 = getNormalizedAssociatedConstraints(D1, AC1);
2622 if (!Normalized1)
2623 return false;
2624
2625 auto *Normalized2 = getNormalizedAssociatedConstraints(D2, AC2);
2626 if (!Normalized2)
2627 return false;
2628
2629 SubsumptionChecker SC(*this);
2630
2631 bool Is1AtLeastAs2Normally = SC.Subsumes(Normalized1, Normalized2);
2632 bool Is2AtLeastAs1Normally = SC.Subsumes(Normalized2, Normalized1);
2633
2634 SubsumptionChecker SC2(*this, IdenticalExprEvaluator);
2635 bool Is1AtLeastAs2 = SC2.Subsumes(Normalized1, Normalized2);
2636 bool Is2AtLeastAs1 = SC2.Subsumes(Normalized2, Normalized1);
2637
2638 if (Is1AtLeastAs2 == Is1AtLeastAs2Normally &&
2639 Is2AtLeastAs1 == Is2AtLeastAs1Normally)
2640 // Same result - no ambiguity was caused by identical atomic expressions.
2641 return false;
2642 }
2643 // A different result! Some ambiguous atomic constraint(s) caused a difference
2644 assert(AmbiguousAtomic1 && AmbiguousAtomic2);
2645
2646 Diag(AmbiguousAtomic1->getBeginLoc(), diag::note_ambiguous_atomic_constraints)
2647 << AmbiguousAtomic1->getSourceRange();
2648 Diag(AmbiguousAtomic2->getBeginLoc(),
2649 diag::note_ambiguous_atomic_constraints_similar_expression)
2650 << AmbiguousAtomic2->getSourceRange();
2651 return true;
2652}
2653
2654//
2655//
2656// ------------------------ Subsumption -----------------------------------
2657//
2658//
2660 SubsumptionCallable Callable)
2661 : SemaRef(SemaRef), Callable(Callable), NextID(1) {}
2662
2663uint16_t SubsumptionChecker::getNewLiteralId() {
2664 assert((unsigned(NextID) + 1 < std::numeric_limits<uint16_t>::max()) &&
2665 "too many constraints!");
2666 return NextID++;
2667}
2668
2669auto SubsumptionChecker::find(const AtomicConstraint *Ori) -> Literal {
2670 auto &Elems = AtomicMap[Ori->getConstraintExpr()];
2671 // C++ [temp.constr.order] p2
2672 // - an atomic constraint A subsumes another atomic constraint B
2673 // if and only if the A and B are identical [...]
2674 //
2675 // C++ [temp.constr.atomic] p2
2676 // Two atomic constraints are identical if they are formed from the
2677 // same expression and the targets of the parameter mappings are
2678 // equivalent according to the rules for expressions [...]
2679
2680 // Because subsumption of atomic constraints is an identity
2681 // relationship that does not require further analysis
2682 // We cache the results such that if an atomic constraint literal
2683 // subsumes another, their literal will be the same
2684
2685 llvm::FoldingSetNodeID ID;
2686 ID.AddBoolean(Ori->hasParameterMapping());
2687 if (Ori->hasParameterMapping()) {
2688 const auto &Mapping = Ori->getParameterMapping();
2690 Ori->mappingOccurenceListForSubsumption();
2691 for (auto [Idx, TAL] : llvm::enumerate(Mapping)) {
2692 if (Indexes[Idx])
2693 SemaRef.getASTContext()
2694 .getCanonicalTemplateArgument(TAL.getArgument())
2695 .Profile(ID, SemaRef.getASTContext());
2696 }
2697 }
2698 auto It = Elems.find(ID);
2699 if (It == Elems.end()) {
2700 It = Elems
2701 .insert({ID,
2702 MappedAtomicConstraint{
2703 Ori, {getNewLiteralId(), Literal::Atomic}}})
2704 .first;
2705 ReverseMap[It->second.ID.Value] = Ori;
2706 }
2707 return It->getSecond().ID;
2708}
2709
2710auto SubsumptionChecker::find(const FoldExpandedConstraint *Ori) -> Literal {
2711 auto &Elems = FoldMap[Ori->getPattern()];
2712
2713 FoldExpendedConstraintKey K;
2714 K.Kind = Ori->getFoldOperator();
2715
2716 auto It = llvm::find_if(Elems, [&K](const FoldExpendedConstraintKey &Other) {
2717 return K.Kind == Other.Kind;
2718 });
2719 if (It == Elems.end()) {
2720 K.ID = {getNewLiteralId(), Literal::FoldExpanded};
2721 It = Elems.insert(Elems.end(), std::move(K));
2722 ReverseMap[It->ID.Value] = Ori;
2723 }
2724 return It->ID;
2725}
2726
2727auto SubsumptionChecker::CNF(const NormalizedConstraint &C) -> CNFFormula {
2728 return SubsumptionChecker::Normalize<CNFFormula>(C);
2729}
2730auto SubsumptionChecker::DNF(const NormalizedConstraint &C) -> DNFFormula {
2731 return SubsumptionChecker::Normalize<DNFFormula>(C);
2732}
2733
2734///
2735/// \brief SubsumptionChecker::Normalize
2736///
2737/// Normalize a formula to Conjunctive Normal Form or
2738/// Disjunctive normal form.
2739///
2740/// Each Atomic (and Fold Expanded) constraint gets represented by
2741/// a single id to reduce space.
2742///
2743/// To minimize risks of exponential blow up, if two atomic
2744/// constraints subsumes each other (same constraint and mapping),
2745/// they are represented by the same literal.
2746///
2747template <typename FormulaType>
2748FormulaType SubsumptionChecker::Normalize(const NormalizedConstraint &NC) {
2749 FormulaType Res;
2750
2751 auto Add = [&, this](Clause C) {
2752 // Sort each clause and remove duplicates for faster comparisons.
2753 llvm::sort(C);
2754 C.erase(llvm::unique(C), C.end());
2755 AddUniqueClauseToFormula(Res, std::move(C));
2756 };
2757
2758 switch (NC.getKind()) {
2760 return {{find(&static_cast<const AtomicConstraint &>(NC))}};
2761
2763 return {{find(&static_cast<const FoldExpandedConstraint &>(NC))}};
2764
2766 return Normalize<FormulaType>(
2767 static_cast<const ConceptIdConstraint &>(NC).getNormalizedConstraint());
2768
2770 const auto &Compound = static_cast<const CompoundConstraint &>(NC);
2771 FormulaType Left, Right;
2772 SemaRef.runWithSufficientStackSpace(SourceLocation(), [&] {
2773 Left = Normalize<FormulaType>(Compound.getLHS());
2774 Right = Normalize<FormulaType>(Compound.getRHS());
2775 });
2776
2777 if (Compound.getCompoundKind() == FormulaType::Kind) {
2778 unsigned SizeLeft = Left.size();
2779 Res = std::move(Left);
2780 Res.reserve(SizeLeft + Right.size());
2781 std::for_each(std::make_move_iterator(Right.begin()),
2782 std::make_move_iterator(Right.end()), Add);
2783 return Res;
2784 }
2785
2786 Res.reserve(Left.size() * Right.size());
2787 for (const auto &LTransform : Left) {
2788 for (const auto &RTransform : Right) {
2789 Clause Combined;
2790 Combined.reserve(LTransform.size() + RTransform.size());
2791 llvm::copy(LTransform, std::back_inserter(Combined));
2792 llvm::copy(RTransform, std::back_inserter(Combined));
2793 Add(std::move(Combined));
2794 }
2795 }
2796 return Res;
2797 }
2798 }
2799 llvm_unreachable("Unknown ConstraintKind enum");
2800}
2801
2802void SubsumptionChecker::AddUniqueClauseToFormula(Formula &F, Clause C) {
2803 for (auto &Other : F) {
2804 if (llvm::equal(C, Other))
2805 return;
2806 }
2807 F.push_back(C);
2808}
2809
2811 const NamedDecl *DP, ArrayRef<AssociatedConstraint> P, const NamedDecl *DQ,
2813 const NormalizedConstraint *PNormalized =
2814 SemaRef.getNormalizedAssociatedConstraints(DP, P);
2815 if (!PNormalized)
2816 return std::nullopt;
2817
2818 const NormalizedConstraint *QNormalized =
2819 SemaRef.getNormalizedAssociatedConstraints(DQ, Q);
2820 if (!QNormalized)
2821 return std::nullopt;
2822
2823 return Subsumes(PNormalized, QNormalized);
2824}
2825
2827 const NormalizedConstraint *Q) {
2828
2829 DNFFormula DNFP = DNF(*P);
2830 CNFFormula CNFQ = CNF(*Q);
2831 return Subsumes(DNFP, CNFQ);
2832}
2833
2834bool SubsumptionChecker::Subsumes(const DNFFormula &PDNF,
2835 const CNFFormula &QCNF) {
2836 for (const auto &Pi : PDNF) {
2837 for (const auto &Qj : QCNF) {
2838 // C++ [temp.constr.order] p2
2839 // - [...] a disjunctive clause Pi subsumes a conjunctive clause Qj if
2840 // and only if there exists an atomic constraint Pia in Pi for which
2841 // there exists an atomic constraint, Qjb, in Qj such that Pia
2842 // subsumes Qjb.
2843 if (!DNFSubsumes(Pi, Qj))
2844 return false;
2845 }
2846 }
2847 return true;
2848}
2849
2850bool SubsumptionChecker::DNFSubsumes(const Clause &P, const Clause &Q) {
2851
2852 return llvm::any_of(P, [&](Literal LP) {
2853 return llvm::any_of(Q, [this, LP](Literal LQ) { return Subsumes(LP, LQ); });
2854 });
2855}
2856
2858 const FoldExpandedConstraint *B) {
2859 std::pair<const FoldExpandedConstraint *, const FoldExpandedConstraint *> Key{
2860 A, B};
2861
2862 auto It = FoldSubsumptionCache.find(Key);
2863 if (It == FoldSubsumptionCache.end()) {
2864 // C++ [temp.constr.order]
2865 // a fold expanded constraint A subsumes another fold expanded
2866 // constraint B if they are compatible for subsumption, have the same
2867 // fold-operator, and the constraint of A subsumes that of B.
2868 bool DoesSubsume =
2869 A->getFoldOperator() == B->getFoldOperator() &&
2872 It = FoldSubsumptionCache.try_emplace(std::move(Key), DoesSubsume).first;
2873 }
2874 return It->second;
2875}
2876
2877bool SubsumptionChecker::Subsumes(Literal A, Literal B) {
2878 if (A.Kind != B.Kind)
2879 return false;
2880 switch (A.Kind) {
2881 case Literal::Atomic:
2882 if (!Callable)
2883 return A.Value == B.Value;
2884 return Callable(
2885 *static_cast<const AtomicConstraint *>(ReverseMap[A.Value]),
2886 *static_cast<const AtomicConstraint *>(ReverseMap[B.Value]));
2887 case Literal::FoldExpanded:
2888 return Subsumes(
2889 static_cast<const FoldExpandedConstraint *>(ReverseMap[A.Value]),
2890 static_cast<const FoldExpandedConstraint *>(ReverseMap[B.Value]));
2891 }
2892 llvm_unreachable("unknown literal kind");
2893}
This file provides AST data structures related to concepts.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines Expressions and AST nodes for C++2a concepts.
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
FormatToken * Next
The next token in the unwrapped line.
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::Records Records
Definition MachO.h:40
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 void diagnoseUnsatisfiedConstraintExpr(Sema &S, const UnsatisfiedConstraintRecord &Record, SourceLocation Loc, bool First, concepts::NestedRequirement *Req=nullptr)
static ExprResult SubstituteConceptsInConstraintExpression(Sema &S, const NamedDecl *D, const ConceptSpecializationExpr *CSE, UnsignedOrNone SubstIndex)
static void DiagnoseUnsatisfiedConstraint(Sema &S, ArrayRef< UnsatisfiedConstraintRecord > Records, SourceLocation Loc, bool First=true, concepts::NestedRequirement *Req=nullptr)
static const Expr * SubstituteConstraintExpressionWithoutSatisfaction(Sema &S, const Sema::TemplateCompareNewDeclInfo &DeclInfo, const Expr *ConstrExpr)
static void diagnoseWellFormedUnsatisfiedConstraintExpr(Sema &S, const Expr *SubstExpr, bool First)
static bool DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID &ID, const NamedDecl *Templ, const Expr *E, const MultiLevelTemplateArgumentList *MLTAL=nullptr)
static bool CheckConstraintSatisfaction(Sema &S, const NamedDecl *Template, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgsLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction, Expr **ConvertedExpr, const ConceptReference *TopLevelConceptId=nullptr)
static void diagnoseUnsatisfiedRequirement(Sema &S, concepts::ExprRequirement *Req, bool First)
static void diagnoseUnsatisfiedConceptIdExpr(Sema &S, const ConceptReference *Concept, SourceLocation Loc, bool First)
static bool CheckFunctionConstraintsWithoutInstantiation(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *Template, ArrayRef< TemplateArgument > TemplateArgs, ConstraintSatisfaction &Satisfaction)
static unsigned CalculateTemplateDepthForConstraints(Sema &S, const NamedDecl *ND, bool SkipForSpecialization=false)
static bool PreparePackForExpansion(Sema &S, const CXXBaseSpecifier &Base, const MultiLevelTemplateArgumentList &TemplateArgs, TypeSourceInfo *&Out, UnexpandedInfo &Info)
APSInt & getInt()
Definition APValue.h:508
bool isInt() const
Definition APValue.h:485
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
CanQualType BoolTy
llvm::StringRef backupStr(llvm::StringRef S) const
Definition ASTContext.h:879
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
const Expr * getConstraintExpr() const
static AtomicConstraint * Create(ASTContext &Ctx, const Expr *ConstraintExpr, const NamedDecl *ConstraintDecl, UnsignedOrNone PackIndex)
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6927
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7058
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2180
StringRef getOpcodeStr() const
Definition Expr.h:4107
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:5076
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2142
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2946
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:74
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Expr * getCallee()
Definition Expr.h:3093
arg_range arguments()
Definition Expr.h:3198
const NormalizedConstraint & getLHS() const
static CompoundConstraint * CreateConjunction(ASTContext &Ctx, NormalizedConstraint *LHS, NormalizedConstraint *RHS)
CompoundConstraintKind getCompoundKind() const
const NormalizedConstraint & getRHS() const
static CompoundConstraint * Create(ASTContext &Ctx, NormalizedConstraint *LHS, CompoundConstraintKind CCK, NormalizedConstraint *RHS)
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
const NormalizedConstraint & getNormalizedConstraint() const
const ConceptSpecializationExpr * getConceptSpecializationExpr() const
static ConceptIdConstraint * Create(ASTContext &Ctx, const ConceptReference *ConceptId, NormalizedConstraint *SubConstraint, const NamedDecl *ConstraintDecl, const ConceptSpecializationExpr *CSE, UnsignedOrNone PackIndex)
const ConceptReference * getConceptId() const
A reference to a concept and its template args, as it appears in the code.
Definition ASTConcept.h:130
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition ASTConcept.h:170
NamedDecl * getFoundDecl() const
Definition ASTConcept.h:197
const DeclarationNameInfo & getConceptNameInfo() const
Definition ASTConcept.h:174
SourceLocation getBeginLoc() const LLVM_READONLY
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:203
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:201
SourceLocation getTemplateKWLoc() const
Definition ASTConcept.h:180
Represents the specialization of a concept - evaluates to a prvalue of type bool.
SourceLocation getBeginLoc() const LLVM_READONLY
SourceLocation getExprLoc() const LLVM_READONLY
ArrayRef< TemplateArgument > getTemplateArguments() const
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
ConceptReference * getConceptReference() const
const ASTConstraintSatisfaction & getSatisfaction() const
Get elaborated satisfaction info about the template arguments' satisfaction of the named concept.
ConceptDecl * getNamedConcept() const
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C)
Definition ASTConcept.h:69
llvm::SmallVector< UnsatisfiedConstraintRecord, 4 > Details
The substituted constraint expr, if the template arguments could be substituted into them,...
Definition ASTConcept.h:67
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getNonTransparentContext()
ValueDecl * getDecl()
Definition Expr.h:1341
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:1226
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition DeclBase.h:1119
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
RAII object that enters a new expression evaluation context.
This represents one expression.
Definition Expr.h:112
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:674
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3090
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool isPRValue() const
Definition Expr.h:285
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:144
Represents difference between two FPOptions values.
static bool AreCompatibleForSubsumption(const FoldExpandedConstraint &A, const FoldExpandedConstraint &B)
FoldOperatorKind getFoldOperator() const
const Expr * getPattern() const
static FoldExpandedConstraint * Create(ASTContext &Ctx, const Expr *Pattern, const NamedDecl *ConstraintDecl, FoldOperatorKind OpKind, NormalizedConstraint *Constraint)
const NormalizedConstraint & getNormalizedPattern() const
Represents a function declaration or definition.
Definition Decl.h:2000
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4194
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4515
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4314
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4330
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4258
TemplatedKind
The kind of templated function a FunctionDecl can be.
Definition Decl.h:2005
@ TK_FunctionTemplateSpecialization
Definition Decl.h:2016
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4145
FunctionDecl * getInstantiatedFromDecl() const
Definition Decl.cpp:4218
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4166
Declaration of a template function.
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:2073
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:372
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
bool hasTemplateArgument(unsigned Depth, unsigned Index) const
Determine whether there is a non-NULL template argument at the given depth and index.
Definition Template.h:175
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition Template.h:272
bool isAnyArgInstantiationDependent(const ASTContext &C) const
Definition Template.h:188
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:213
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
void replaceOutermostTemplateArguments(Decl *AssociatedDecl, ArgList Args)
Definition Template.h:254
const ArgList & getOutermost() const
Retrieve the outermost template argument list.
Definition Template.h:276
This represents a decl that may have a name.
Definition Decl.h:274
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
UnsignedOrNone getPackSubstitutionIndex() const
const NamedDecl * getConstraintDecl() const
bool hasMatchingParameterMapping(ASTContext &C, const NormalizedConstraint &Other) const
const OccurenceList & mappingOccurenceList() const
const OccurenceList & mappingOccurenceListForSubsumption() const
TemplateParameterList * getUsedTemplateParamList() const
llvm::MutableArrayRef< TemplateArgumentLoc > getParameterMapping() const
void updateParameterMapping(OccurenceList Indexes, OccurenceList IndexesForSubsumption, llvm::MutableArrayRef< TemplateArgumentLoc > Args, TemplateParameterList *ParamList)
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
QualType getCanonicalType() const
Definition TypeBase.h:8440
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13721
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8499
A RAII object to temporarily push a declaration context.
Definition Sema.h:3518
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12517
SourceLocation getLocation() const
Definition Sema.h:12275
const DeclContext * getDeclContext() const
Definition Sema.h:12271
const NamedDecl * getDecl() const
Definition Sema.h:12263
const DeclContext * getLexicalDeclContext() const
Definition Sema.h:12267
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
ExprResult SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr, const MultiLevelTemplateArgumentList &MLTAL)
Substitute concept template arguments in the constraint expression of a concept-id.
llvm::DenseMap< llvm::FoldingSetNodeID, UnsubstitutedConstraintSatisfactionCacheResult > UnsubstitutedConstraintSatisfactionCache
Cache the satisfaction of an atomic constraint.
Definition Sema.h:15082
ASTContext & Context
Definition Sema.h:1300
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
void MarkUsedTemplateParametersForSubsumptionParameterMapping(const Expr *E, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are named in a given expression.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
void DiagnoseTypeTraitDetails(const Expr *E)
If E represents a built-in type trait, or a known standard type trait, try to print more information ...
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool FailOnPackProducingTemplates, bool &ShouldExpand, bool &RetainExpansion, UnsignedOrNone &NumExpansions, bool Diagnose=true)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
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.
ASTContext & getASTContext() const
Definition Sema.h:939
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, bool DoCheckConstraintSatisfaction=true)
llvm::PointerUnion< const NamedDecl *, const concepts::NestedRequirement * > ConstrainedDeclOrNestedRequirement
Definition Sema.h:14951
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
bool CheckConstraintSatisfaction(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction, const ConceptReference *TopLevelConceptId=nullptr, Expr **ConvertedExpr=nullptr)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
const NormalizedConstraint * getNormalizedAssociatedConstraints(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints)
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:932
@ ReuseLambdaContextDecl
Definition Sema.h:7067
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool SubstTemplateArgumentsInParameterMapping(ArrayRef< TemplateArgumentLoc > Args, SourceLocation BaseLoc, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Out)
TemplateArgument getPackSubstitutedTemplateArgument(TemplateArgument Arg) const
Definition Sema.h:11833
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1333
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, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
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)
SourceManager & getSourceManager() const
Definition Sema.h:937
bool isSFINAEContext() const
Definition Sema.h:13759
UnsignedOrNone ArgPackSubstIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition Sema.h:13715
void PushSatisfactionStackEntry(const NamedDecl *D, const llvm::FoldingSetNodeID &ID)
Definition Sema.h:14907
void PopSatisfactionStackEntry()
Definition Sema.h:14913
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...
Definition Sema.h:6780
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6759
bool SatisfactionStackContains(const NamedDecl *D, const llvm::FoldingSetNodeID &ID) const
Definition Sema.h:14915
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location)
Get a template argument mapping the given template parameter to itself, e.g.
bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef< TemplateArgument > TemplateArgs, ConstraintSatisfaction &Satisfaction)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
NamedDecl * getPack() const
Retrieve the parameter pack.
Definition ExprCXX.h:4510
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
std::string printToString(const SourceManager &SM) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
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:355
SubsumptionChecker establishes subsumption between two set of constraints.
std::optional< bool > Subsumes(const NamedDecl *DP, ArrayRef< AssociatedConstraint > P, const NamedDecl *DQ, ArrayRef< AssociatedConstraint > Q)
SubsumptionChecker(Sema &SemaRef, SubsumptionCallable Callable={})
llvm::function_ref< bool( const AtomicConstraint &, const AtomicConstraint &)> SubsumptionCallable
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
Represents a template argument.
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
Used to insert TemplateArguments into FoldingSets.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
bool containsUnexpandedParameterPack() const
Whether this template argument contains an unexpanded parameter pack.
@ Pack
The template argument is actually a parameter pack.
ArgKind getKind() const
Return the kind of stored template argument.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
The base class of all kinds of template declarations (e.g., class, function, etc.).
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
Get the total constraint-expression associated with this template, including constraint-expressions d...
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
bool isNull() const
Determine whether this template name is NULL.
Stores a list of template parameters for a TemplateDecl and its derived classes.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
SourceLocation getLAngleLoc() const
SourceLocation getTemplateLoc() const
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:104
tok::TokenKind getKind() const
Definition Token.h:99
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
SourceLocation getNameLoc() const
Definition TypeLoc.h:547
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1839
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2798
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8960
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2790
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2411
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2808
bool isFunctionType() const
Definition TypeBase.h:8621
QualType desugar() const
Definition Type.cpp:4115
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
A requires-expression requirement which queries the validity and properties of an expression ('simple...
SubstitutionDiagnostic * getExprSubstitutionDiagnostic() const
ConceptSpecializationExpr * getReturnTypeRequirementSubstitutedConstraintExpr() const
const ReturnTypeRequirement & getReturnTypeRequirement() const
SatisfactionStatus getSatisfactionStatus() const
SourceLocation getNoexceptLoc() const
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
const ASTConstraintSatisfaction & getConstraintSatisfaction() const
A static requirement that can be used in a requires-expression to check properties of types and expre...
A requires-expression requirement which queries the existence of a type name or type template special...
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
SatisfactionStatus getSatisfactionStatus() const
Provides information about an attempted template argument deduction, whose success or failure was des...
#define bool
Definition gpuintrin.h:32
__inline void unsigned int _2
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
bool Sub(InterpState &S, CodePtr OpPC)
Definition Interp.h:346
bool Add(InterpState &S, CodePtr OpPC)
Definition Interp.h:326
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus11
@ CPlusPlus26
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
llvm::PointerUnion< const Expr *, const ConceptReference *, const ConstraintSubstitutionDiagnostic * > UnsatisfiedConstraintRecord
Definition ASTConcept.h:41
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:238
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
ExprResult ExprEmpty()
Definition Ownership.h:272
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ExprResult ExprError()
Definition Ownership.h:265
@ Concept
The name was classified as a concept name.
Definition Sema.h:591
std::pair< SourceLocation, StringRef > ConstraintSubstitutionDiagnostic
Unsatisfied constraint expressions if the template arguments could be substituted into them,...
Definition ASTConcept.h:40
prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus11)
Return the precedence of the specified binary operator token.
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition ASTLambda.h:69
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
U cast(CodeGen::Address addr)
Definition Address.h:327
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:91
ArrayRef< UnsatisfiedConstraintRecord > records() const
Definition ASTConcept.h:104
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
ArrayRef< TemplateArgumentLoc > arguments() const
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
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:636
A normalized constraint, as defined in C++ [temp.constr.normal], is either an atomic constraint,...
Definition SemaConcept.h:36
NormalizedConstraint(const Expr *ConstraintExpr, const NamedDecl *ConstraintDecl, UnsignedOrNone PackIndex)
SourceRange getSourceRange() const
ConstraintKind getKind() const
SourceLocation getBeginLoc() const
llvm::SmallBitVector OccurenceList
Definition SemaConcept.h:51
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12051
A stack object to be created when performing template instantiation.
Definition Sema.h:13359
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13512
constexpr unsigned toInternalRepresentation() const