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 
13 #include "clang/Sema/SemaConcept.h"
14 #include "clang/Sema/Sema.h"
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/Sema/SemaDiagnostic.h"
17 #include "clang/Sema/TemplateDeduction.h"
18 #include "clang/Sema/Template.h"
19 #include "clang/Sema/Overload.h"
20 #include "clang/Sema/Initialization.h"
21 #include "clang/AST/ExprConcepts.h"
22 #include "clang/AST/RecursiveASTVisitor.h"
23 #include "clang/Basic/OperatorPrecedence.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/PointerUnion.h"
26 #include "llvm/ADT/StringExtras.h"
27 
28 using namespace clang;
29 using namespace sema;
30 
31 namespace {
32 class LogicalBinOp {
33   SourceLocation Loc;
34   OverloadedOperatorKind Op = OO_None;
35   const Expr *LHS = nullptr;
36   const Expr *RHS = nullptr;
37 
38 public:
39   LogicalBinOp(const Expr *E) {
40     if (auto *BO = dyn_cast<BinaryOperator>(E)) {
41       Op = BinaryOperator::getOverloadedOperator(BO->getOpcode());
42       LHS = BO->getLHS();
43       RHS = BO->getRHS();
44       Loc = BO->getExprLoc();
45     } else if (auto *OO = dyn_cast<CXXOperatorCallExpr>(E)) {
46       // If OO is not || or && it might not have exactly 2 arguments.
47       if (OO->getNumArgs() == 2) {
48         Op = OO->getOperator();
49         LHS = OO->getArg(0);
50         RHS = OO->getArg(1);
51         Loc = OO->getOperatorLoc();
52       }
53     }
54   }
55 
56   bool isAnd() const { return Op == OO_AmpAmp; }
57   bool isOr() const { return Op == OO_PipePipe; }
58   explicit operator bool() const { return isAnd() || isOr(); }
59 
60   const Expr *getLHS() const { return LHS; }
61   const Expr *getRHS() const { return RHS; }
62 
63   ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS) const {
64     return recreateBinOp(SemaRef, LHS, const_cast<Expr *>(getRHS()));
65   }
66 
67   ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS,
68                            ExprResult RHS) const {
69     assert((isAnd() || isOr()) && "Not the right kind of op?");
70     assert((!LHS.isInvalid() && !RHS.isInvalid()) && "not good expressions?");
71 
72     if (!LHS.isUsable() || !RHS.isUsable())
73       return ExprEmpty();
74 
75     // We should just be able to 'normalize' these to the builtin Binary
76     // Operator, since that is how they are evaluated in constriant checks.
77     return BinaryOperator::Create(SemaRef.Context, LHS.get(), RHS.get(),
78                                   BinaryOperator::getOverloadedOpcode(Op),
79                                   SemaRef.Context.BoolTy, VK_PRValue,
80                                   OK_Ordinary, Loc, FPOptionsOverride{});
81   }
82 };
83 }
84 
85 bool Sema::CheckConstraintExpression(const Expr *ConstraintExpression,
86                                      Token NextToken, bool *PossibleNonPrimary,
87                                      bool IsTrailingRequiresClause) {
88   // C++2a [temp.constr.atomic]p1
89   // ..E shall be a constant expression of type bool.
90 
91   ConstraintExpression = ConstraintExpression->IgnoreParenImpCasts();
92 
93   if (LogicalBinOp BO = ConstraintExpression) {
94     return CheckConstraintExpression(BO.getLHS(), NextToken,
95                                      PossibleNonPrimary) &&
96            CheckConstraintExpression(BO.getRHS(), NextToken,
97                                      PossibleNonPrimary);
98   } else if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpression))
99     return CheckConstraintExpression(C->getSubExpr(), NextToken,
100                                      PossibleNonPrimary);
101 
102   QualType Type = ConstraintExpression->getType();
103 
104   auto CheckForNonPrimary = [&] {
105     if (PossibleNonPrimary)
106       *PossibleNonPrimary =
107           // We have the following case:
108           // template<typename> requires func(0) struct S { };
109           // The user probably isn't aware of the parentheses required around
110           // the function call, and we're only going to parse 'func' as the
111           // primary-expression, and complain that it is of non-bool type.
112           (NextToken.is(tok::l_paren) &&
113            (IsTrailingRequiresClause ||
114             (Type->isDependentType() &&
115              isa<UnresolvedLookupExpr>(ConstraintExpression)) ||
116             Type->isFunctionType() ||
117             Type->isSpecificBuiltinType(BuiltinType::Overload))) ||
118           // We have the following case:
119           // template<typename T> requires size_<T> == 0 struct S { };
120           // The user probably isn't aware of the parentheses required around
121           // the binary operator, and we're only going to parse 'func' as the
122           // first operand, and complain that it is of non-bool type.
123           getBinOpPrecedence(NextToken.getKind(),
124                              /*GreaterThanIsOperator=*/true,
125                              getLangOpts().CPlusPlus11) > prec::LogicalAnd;
126   };
127 
128   // An atomic constraint!
129   if (ConstraintExpression->isTypeDependent()) {
130     CheckForNonPrimary();
131     return true;
132   }
133 
134   if (!Context.hasSameUnqualifiedType(Type, Context.BoolTy)) {
135     Diag(ConstraintExpression->getExprLoc(),
136          diag::err_non_bool_atomic_constraint) << Type
137         << ConstraintExpression->getSourceRange();
138     CheckForNonPrimary();
139     return false;
140   }
141 
142   if (PossibleNonPrimary)
143       *PossibleNonPrimary = false;
144   return true;
145 }
146 
147 template <typename AtomicEvaluator>
148 static ExprResult
149 calculateConstraintSatisfaction(Sema &S, const Expr *ConstraintExpr,
150                                 ConstraintSatisfaction &Satisfaction,
151                                 AtomicEvaluator &&Evaluator) {
152   ConstraintExpr = ConstraintExpr->IgnoreParenImpCasts();
153 
154   if (LogicalBinOp BO = ConstraintExpr) {
155     ExprResult LHSRes = calculateConstraintSatisfaction(
156         S, BO.getLHS(), Satisfaction, Evaluator);
157 
158     if (LHSRes.isInvalid())
159       return ExprError();
160 
161     bool IsLHSSatisfied = Satisfaction.IsSatisfied;
162 
163     if (BO.isOr() && IsLHSSatisfied)
164       // [temp.constr.op] p3
165       //    A disjunction is a constraint taking two operands. To determine if
166       //    a disjunction is satisfied, the satisfaction of the first operand
167       //    is checked. If that is satisfied, the disjunction is satisfied.
168       //    Otherwise, the disjunction is satisfied if and only if the second
169       //    operand is satisfied.
170       return BO.recreateBinOp(S, LHSRes);
171 
172     if (BO.isAnd() && !IsLHSSatisfied)
173       // [temp.constr.op] p2
174       //    A conjunction is a constraint taking two operands. To determine if
175       //    a conjunction is satisfied, the satisfaction of the first operand
176       //    is checked. If that is not satisfied, the conjunction is not
177       //    satisfied. Otherwise, the conjunction is satisfied if and only if
178       //    the second operand is satisfied.
179       return BO.recreateBinOp(S, LHSRes);
180 
181     ExprResult RHSRes = calculateConstraintSatisfaction(
182         S, BO.getRHS(), Satisfaction, std::forward<AtomicEvaluator>(Evaluator));
183     if (RHSRes.isInvalid())
184       return ExprError();
185 
186     return BO.recreateBinOp(S, LHSRes, RHSRes);
187   }
188 
189   if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpr)) {
190     // These aren't evaluated, so we don't care about cleanups, so we can just
191     // evaluate these as if the cleanups didn't exist.
192     return calculateConstraintSatisfaction(
193         S, C->getSubExpr(), Satisfaction,
194         std::forward<AtomicEvaluator>(Evaluator));
195   }
196 
197   // An atomic constraint expression
198   ExprResult SubstitutedAtomicExpr = Evaluator(ConstraintExpr);
199 
200   if (SubstitutedAtomicExpr.isInvalid())
201     return ExprError();
202 
203   if (!SubstitutedAtomicExpr.isUsable())
204     // Evaluator has decided satisfaction without yielding an expression.
205     return ExprEmpty();
206 
207   EnterExpressionEvaluationContext ConstantEvaluated(
208       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
209   SmallVector<PartialDiagnosticAt, 2> EvaluationDiags;
210   Expr::EvalResult EvalResult;
211   EvalResult.Diag = &EvaluationDiags;
212   if (!SubstitutedAtomicExpr.get()->EvaluateAsConstantExpr(EvalResult,
213                                                            S.Context) ||
214       !EvaluationDiags.empty()) {
215     // C++2a [temp.constr.atomic]p1
216     //   ...E shall be a constant expression of type bool.
217     S.Diag(SubstitutedAtomicExpr.get()->getBeginLoc(),
218            diag::err_non_constant_constraint_expression)
219         << SubstitutedAtomicExpr.get()->getSourceRange();
220     for (const PartialDiagnosticAt &PDiag : EvaluationDiags)
221       S.Diag(PDiag.first, PDiag.second);
222     return ExprError();
223   }
224 
225   assert(EvalResult.Val.isInt() &&
226          "evaluating bool expression didn't produce int");
227   Satisfaction.IsSatisfied = EvalResult.Val.getInt().getBoolValue();
228   if (!Satisfaction.IsSatisfied)
229     Satisfaction.Details.emplace_back(ConstraintExpr,
230                                       SubstitutedAtomicExpr.get());
231 
232   return SubstitutedAtomicExpr;
233 }
234 
235 static ExprResult calculateConstraintSatisfaction(
236     Sema &S, const NamedDecl *Template, SourceLocation TemplateNameLoc,
237     const MultiLevelTemplateArgumentList &MLTAL, const Expr *ConstraintExpr,
238     ConstraintSatisfaction &Satisfaction) {
239   return calculateConstraintSatisfaction(
240       S, ConstraintExpr, Satisfaction, [&](const Expr *AtomicExpr) {
241         EnterExpressionEvaluationContext ConstantEvaluated(
242             S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
243 
244         // Atomic constraint - substitute arguments and check satisfaction.
245         ExprResult SubstitutedExpression;
246         {
247           TemplateDeductionInfo Info(TemplateNameLoc);
248           Sema::InstantiatingTemplate Inst(S, AtomicExpr->getBeginLoc(),
249               Sema::InstantiatingTemplate::ConstraintSubstitution{},
250               const_cast<NamedDecl *>(Template), Info,
251               AtomicExpr->getSourceRange());
252           if (Inst.isInvalid())
253             return ExprError();
254           // We do not want error diagnostics escaping here.
255           Sema::SFINAETrap Trap(S);
256           SubstitutedExpression =
257               S.SubstConstraintExpr(const_cast<Expr *>(AtomicExpr), MLTAL);
258           // Substitution might have stripped off a contextual conversion to
259           // bool if this is the operand of an '&&' or '||'. For example, we
260           // might lose an lvalue-to-rvalue conversion here. If so, put it back
261           // before we try to evaluate.
262           if (!SubstitutedExpression.isInvalid())
263             SubstitutedExpression =
264                 S.PerformContextuallyConvertToBool(SubstitutedExpression.get());
265           if (SubstitutedExpression.isInvalid() || Trap.hasErrorOccurred()) {
266             // C++2a [temp.constr.atomic]p1
267             //   ...If substitution results in an invalid type or expression, the
268             //   constraint is not satisfied.
269             if (!Trap.hasErrorOccurred())
270               // A non-SFINAE error has occurred as a result of this
271               // substitution.
272               return ExprError();
273 
274             PartialDiagnosticAt SubstDiag{SourceLocation(),
275                                           PartialDiagnostic::NullDiagnostic()};
276             Info.takeSFINAEDiagnostic(SubstDiag);
277             // FIXME: Concepts: This is an unfortunate consequence of there
278             //  being no serialization code for PartialDiagnostics and the fact
279             //  that serializing them would likely take a lot more storage than
280             //  just storing them as strings. We would still like, in the
281             //  future, to serialize the proper PartialDiagnostic as serializing
282             //  it as a string defeats the purpose of the diagnostic mechanism.
283             SmallString<128> DiagString;
284             DiagString = ": ";
285             SubstDiag.second.EmitToString(S.getDiagnostics(), DiagString);
286             unsigned MessageSize = DiagString.size();
287             char *Mem = new (S.Context) char[MessageSize];
288             memcpy(Mem, DiagString.c_str(), MessageSize);
289             Satisfaction.Details.emplace_back(
290                 AtomicExpr,
291                 new (S.Context) ConstraintSatisfaction::SubstitutionDiagnostic{
292                         SubstDiag.first, StringRef(Mem, MessageSize)});
293             Satisfaction.IsSatisfied = false;
294             return ExprEmpty();
295           }
296         }
297 
298         if (!S.CheckConstraintExpression(SubstitutedExpression.get()))
299           return ExprError();
300 
301         return SubstitutedExpression;
302       });
303 }
304 
305 static bool CheckConstraintSatisfaction(
306     Sema &S, const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
307     llvm::SmallVectorImpl<Expr *> &Converted,
308     const MultiLevelTemplateArgumentList &TemplateArgsList,
309     SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction) {
310   if (ConstraintExprs.empty()) {
311     Satisfaction.IsSatisfied = true;
312     return false;
313   }
314 
315   if (TemplateArgsList.isAnyArgInstantiationDependent()) {
316     //  No need to check satisfaction for dependent constraint expressions.
317     Satisfaction.IsSatisfied = true;
318     return false;
319   }
320 
321   ArrayRef<TemplateArgument> TemplateArgs =
322       TemplateArgsList.getNumSubstitutedLevels() > 0
323           ? TemplateArgsList.getOutermost()
324           : ArrayRef<TemplateArgument>{};
325 
326   Sema::InstantiatingTemplate Inst(
327       S, TemplateIDRange.getBegin(),
328       Sema::InstantiatingTemplate::ConstraintsCheck{},
329       const_cast<NamedDecl *>(Template), TemplateArgs, TemplateIDRange);
330   if (Inst.isInvalid())
331     return true;
332 
333   for (const Expr *ConstraintExpr : ConstraintExprs) {
334     ExprResult Res = calculateConstraintSatisfaction(
335         S, Template, TemplateIDRange.getBegin(), TemplateArgsList,
336         ConstraintExpr, Satisfaction);
337     if (Res.isInvalid())
338       return true;
339 
340     Converted.push_back(Res.get());
341     if (!Satisfaction.IsSatisfied) {
342       // Backfill the 'converted' list with nulls so we can keep the Converted
343       // and unconverted lists in sync.
344       Converted.append(ConstraintExprs.size() - Converted.size(), nullptr);
345       // [temp.constr.op] p2
346       // [...] To determine if a conjunction is satisfied, the satisfaction
347       // of the first operand is checked. If that is not satisfied, the
348       // conjunction is not satisfied. [...]
349       return false;
350     }
351   }
352   return false;
353 }
354 
355 bool Sema::CheckConstraintSatisfaction(
356     const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
357     llvm::SmallVectorImpl<Expr *> &ConvertedConstraints,
358     const MultiLevelTemplateArgumentList &TemplateArgsList,
359     SourceRange TemplateIDRange, ConstraintSatisfaction &OutSatisfaction) {
360   if (ConstraintExprs.empty()) {
361     OutSatisfaction.IsSatisfied = true;
362     return false;
363   }
364   if (!Template) {
365     return ::CheckConstraintSatisfaction(*this, nullptr, ConstraintExprs,
366                                          ConvertedConstraints, TemplateArgsList,
367                                          TemplateIDRange, OutSatisfaction);
368   }
369 
370   // A list of the template argument list flattened in a predictible manner for
371   // the purposes of caching. The ConstraintSatisfaction type is in AST so it
372   // has no access to the MultiLevelTemplateArgumentList, so this has to happen
373   // here.
374   llvm::SmallVector<TemplateArgument, 4> FlattenedArgs;
375   for (ArrayRef<TemplateArgument> List : TemplateArgsList)
376     FlattenedArgs.insert(FlattenedArgs.end(), List.begin(), List.end());
377 
378   llvm::FoldingSetNodeID ID;
379   ConstraintSatisfaction::Profile(ID, Context, Template, FlattenedArgs);
380 
381   void *InsertPos;
382   if (auto *Cached = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos)) {
383     OutSatisfaction = *Cached;
384     return false;
385   }
386   auto Satisfaction =
387       std::make_unique<ConstraintSatisfaction>(Template, FlattenedArgs);
388   if (::CheckConstraintSatisfaction(*this, Template, ConstraintExprs,
389                                     ConvertedConstraints, TemplateArgsList,
390                                     TemplateIDRange, *Satisfaction)) {
391     return true;
392   }
393   OutSatisfaction = *Satisfaction;
394   // We cannot use InsertPos here because CheckConstraintSatisfaction might have
395   // invalidated it.
396   // Note that entries of SatisfactionCache are deleted in Sema's destructor.
397   SatisfactionCache.InsertNode(Satisfaction.release());
398   return false;
399 }
400 
401 bool Sema::CheckConstraintSatisfaction(const Expr *ConstraintExpr,
402                                        ConstraintSatisfaction &Satisfaction) {
403   return calculateConstraintSatisfaction(
404              *this, ConstraintExpr, Satisfaction,
405              [this](const Expr *AtomicExpr) -> ExprResult {
406                // We only do this to immitate lvalue-to-rvalue conversion.
407                return PerformContextuallyConvertToBool(
408                    const_cast<Expr *>(AtomicExpr));
409              })
410       .isInvalid();
411 }
412 
413 bool Sema::SetupConstraintScope(
414     FunctionDecl *FD, llvm::Optional<ArrayRef<TemplateArgument>> TemplateArgs,
415     MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope) {
416   if (FD->isTemplateInstantiation() && FD->getPrimaryTemplate()) {
417     FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
418     InstantiatingTemplate Inst(
419         *this, FD->getPointOfInstantiation(),
420         Sema::InstantiatingTemplate::ConstraintsCheck{}, PrimaryTemplate,
421         TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
422         SourceRange());
423     if (Inst.isInvalid())
424       return true;
425 
426     // addInstantiatedParametersToScope creates a map of 'uninstantiated' to
427     // 'instantiated' parameters and adds it to the context. For the case where
428     // this function is a template being instantiated NOW, we also need to add
429     // the list of current template arguments to the list so that they also can
430     // be picked out of the map.
431     if (auto *SpecArgs = FD->getTemplateSpecializationArgs()) {
432       MultiLevelTemplateArgumentList JustTemplArgs(*SpecArgs);
433       if (addInstantiatedParametersToScope(
434               FD, PrimaryTemplate->getTemplatedDecl(), Scope, JustTemplArgs))
435         return true;
436     }
437 
438     // If this is a member function, make sure we get the parameters that
439     // reference the original primary template.
440     if (const auto *FromMemTempl =
441             PrimaryTemplate->getInstantiatedFromMemberTemplate()) {
442       if (addInstantiatedParametersToScope(FD, FromMemTempl->getTemplatedDecl(),
443                                            Scope, MLTAL))
444         return true;
445     }
446 
447     return false;
448   }
449 
450   if (FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization ||
451       FD->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate) {
452     FunctionDecl *InstantiatedFrom =
453         FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization
454             ? FD->getInstantiatedFromMemberFunction()
455             : FD->getInstantiatedFromDecl();
456 
457     InstantiatingTemplate Inst(
458         *this, FD->getPointOfInstantiation(),
459         Sema::InstantiatingTemplate::ConstraintsCheck{}, InstantiatedFrom,
460         TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
461         SourceRange());
462     if (Inst.isInvalid())
463       return true;
464 
465     // Case where this was not a template, but instantiated as a
466     // child-function.
467     if (addInstantiatedParametersToScope(FD, InstantiatedFrom, Scope, MLTAL))
468       return true;
469   }
470 
471   return false;
472 }
473 
474 // This function collects all of the template arguments for the purposes of
475 // constraint-instantiation and checking.
476 llvm::Optional<MultiLevelTemplateArgumentList>
477 Sema::SetupConstraintCheckingTemplateArgumentsAndScope(
478     FunctionDecl *FD, llvm::Optional<ArrayRef<TemplateArgument>> TemplateArgs,
479     LocalInstantiationScope &Scope) {
480   MultiLevelTemplateArgumentList MLTAL;
481 
482   // Collect the list of template arguments relative to the 'primary' template.
483   // We need the entire list, since the constraint is completely uninstantiated
484   // at this point.
485   MLTAL = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary*/ true,
486                                        /*Pattern*/ nullptr,
487                                        /*LookBeyondLambda*/ true);
488   if (SetupConstraintScope(FD, TemplateArgs, MLTAL, Scope))
489     return {};
490 
491   return MLTAL;
492 }
493 
494 bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
495                                     ConstraintSatisfaction &Satisfaction,
496                                     SourceLocation UsageLoc) {
497   // Don't check constraints if the function is dependent. Also don't check if
498   // this is a function template specialization, as the call to
499   // CheckinstantiatedFunctionTemplateConstraints after this will check it
500   // better.
501   if (FD->isDependentContext() ||
502       FD->getTemplatedKind() ==
503           FunctionDecl::TK_FunctionTemplateSpecialization) {
504     Satisfaction.IsSatisfied = true;
505     return false;
506   }
507 
508   ContextRAII SavedContext{
509       *this, cast<DeclContext>(
510                  const_cast<FunctionDecl *>(FD)->getNonClosureContext())};
511   LocalInstantiationScope Scope(*this, true);
512   llvm::Optional<MultiLevelTemplateArgumentList> MLTAL =
513       SetupConstraintCheckingTemplateArgumentsAndScope(
514           const_cast<FunctionDecl *>(FD), {}, Scope);
515 
516   Qualifiers ThisQuals;
517   CXXRecordDecl *Record = nullptr;
518   if (auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
519     ThisQuals = Method->getMethodQualifiers();
520     Record = const_cast<CXXRecordDecl *>(Method->getParent());
521   }
522   CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
523   // We substitute with empty arguments in order to rebuild the atomic
524   // constraint in a constant-evaluated context.
525   // FIXME: Should this be a dedicated TreeTransform?
526   const Expr *RC = FD->getTrailingRequiresClause();
527   llvm::SmallVector<Expr *, 1> Converted;
528 
529   if (CheckConstraintSatisfaction(
530           FD, {RC}, Converted, *MLTAL,
531           SourceRange(UsageLoc.isValid() ? UsageLoc : FD->getLocation()),
532           Satisfaction))
533     return true;
534 
535   // FIXME: we need to do this for the function constraints for
536   // comparison of constraints to work, but do we also need to do it for
537   // CheckInstantiatedFunctionConstraints?  That one is more difficult, but we
538   // seem to always just pick up the constraints from the primary template.
539   assert(Converted.size() <= 1 && "Got more expressions converted?");
540   if (!Converted.empty() && Converted[0] != nullptr)
541     const_cast<FunctionDecl *>(FD)->setTrailingRequiresClause(Converted[0]);
542   return false;
543 }
544 
545 bool Sema::EnsureTemplateArgumentListConstraints(
546     TemplateDecl *TD, MultiLevelTemplateArgumentList TemplateArgs,
547     SourceRange TemplateIDRange) {
548   ConstraintSatisfaction Satisfaction;
549   llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
550   TD->getAssociatedConstraints(AssociatedConstraints);
551   if (CheckConstraintSatisfaction(TD, AssociatedConstraints, TemplateArgs,
552                                   TemplateIDRange, Satisfaction))
553     return true;
554 
555   if (!Satisfaction.IsSatisfied) {
556     SmallString<128> TemplateArgString;
557     TemplateArgString = " ";
558     TemplateArgString += getTemplateArgumentBindingsText(
559         TD->getTemplateParameters(), TemplateArgs.getInnermost().data(),
560         TemplateArgs.getInnermost().size());
561 
562     Diag(TemplateIDRange.getBegin(),
563          diag::err_template_arg_list_constraints_not_satisfied)
564         << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << TD
565         << TemplateArgString << TemplateIDRange;
566     DiagnoseUnsatisfiedConstraint(Satisfaction);
567     return true;
568   }
569   return false;
570 }
571 
572 bool Sema::CheckInstantiatedFunctionTemplateConstraints(
573     SourceLocation PointOfInstantiation, FunctionDecl *Decl,
574     ArrayRef<TemplateArgument> TemplateArgs,
575     ConstraintSatisfaction &Satisfaction) {
576   // In most cases we're not going to have constraints, so check for that first.
577   FunctionTemplateDecl *Template = Decl->getPrimaryTemplate();
578   // Note - code synthesis context for the constraints check is created
579   // inside CheckConstraintsSatisfaction.
580   SmallVector<const Expr *, 3> TemplateAC;
581   Template->getAssociatedConstraints(TemplateAC);
582   if (TemplateAC.empty()) {
583     Satisfaction.IsSatisfied = true;
584     return false;
585   }
586 
587   // Enter the scope of this instantiation. We don't use
588   // PushDeclContext because we don't have a scope.
589   Sema::ContextRAII savedContext(*this, Decl);
590   LocalInstantiationScope Scope(*this);
591 
592   Optional<MultiLevelTemplateArgumentList> MLTAL =
593       SetupConstraintCheckingTemplateArgumentsAndScope(Decl, TemplateArgs,
594                                                        Scope);
595 
596   if (!MLTAL)
597     return true;
598 
599   Qualifiers ThisQuals;
600   CXXRecordDecl *Record = nullptr;
601   if (auto *Method = dyn_cast<CXXMethodDecl>(Decl)) {
602     ThisQuals = Method->getMethodQualifiers();
603     Record = Method->getParent();
604   }
605   CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
606   llvm::SmallVector<Expr *, 1> Converted;
607   return CheckConstraintSatisfaction(Template, TemplateAC, Converted, *MLTAL,
608                                      PointOfInstantiation, Satisfaction);
609 }
610 
611 static void diagnoseUnsatisfiedRequirement(Sema &S,
612                                            concepts::ExprRequirement *Req,
613                                            bool First) {
614   assert(!Req->isSatisfied()
615          && "Diagnose() can only be used on an unsatisfied requirement");
616   switch (Req->getSatisfactionStatus()) {
617     case concepts::ExprRequirement::SS_Dependent:
618       llvm_unreachable("Diagnosing a dependent requirement");
619       break;
620     case concepts::ExprRequirement::SS_ExprSubstitutionFailure: {
621       auto *SubstDiag = Req->getExprSubstitutionDiagnostic();
622       if (!SubstDiag->DiagMessage.empty())
623         S.Diag(SubstDiag->DiagLoc,
624                diag::note_expr_requirement_expr_substitution_error)
625                << (int)First << SubstDiag->SubstitutedEntity
626                << SubstDiag->DiagMessage;
627       else
628         S.Diag(SubstDiag->DiagLoc,
629                diag::note_expr_requirement_expr_unknown_substitution_error)
630             << (int)First << SubstDiag->SubstitutedEntity;
631       break;
632     }
633     case concepts::ExprRequirement::SS_NoexceptNotMet:
634       S.Diag(Req->getNoexceptLoc(),
635              diag::note_expr_requirement_noexcept_not_met)
636           << (int)First << Req->getExpr();
637       break;
638     case concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure: {
639       auto *SubstDiag =
640           Req->getReturnTypeRequirement().getSubstitutionDiagnostic();
641       if (!SubstDiag->DiagMessage.empty())
642         S.Diag(SubstDiag->DiagLoc,
643                diag::note_expr_requirement_type_requirement_substitution_error)
644             << (int)First << SubstDiag->SubstitutedEntity
645             << SubstDiag->DiagMessage;
646       else
647         S.Diag(SubstDiag->DiagLoc,
648                diag::note_expr_requirement_type_requirement_unknown_substitution_error)
649             << (int)First << SubstDiag->SubstitutedEntity;
650       break;
651     }
652     case concepts::ExprRequirement::SS_ConstraintsNotSatisfied: {
653       ConceptSpecializationExpr *ConstraintExpr =
654           Req->getReturnTypeRequirementSubstitutedConstraintExpr();
655       if (ConstraintExpr->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
656         // A simple case - expr type is the type being constrained and the concept
657         // was not provided arguments.
658         Expr *e = Req->getExpr();
659         S.Diag(e->getBeginLoc(),
660                diag::note_expr_requirement_constraints_not_satisfied_simple)
661             << (int)First << S.Context.getReferenceQualifiedType(e)
662             << ConstraintExpr->getNamedConcept();
663       } else {
664         S.Diag(ConstraintExpr->getBeginLoc(),
665                diag::note_expr_requirement_constraints_not_satisfied)
666             << (int)First << ConstraintExpr;
667       }
668       S.DiagnoseUnsatisfiedConstraint(ConstraintExpr->getSatisfaction());
669       break;
670     }
671     case concepts::ExprRequirement::SS_Satisfied:
672       llvm_unreachable("We checked this above");
673   }
674 }
675 
676 static void diagnoseUnsatisfiedRequirement(Sema &S,
677                                            concepts::TypeRequirement *Req,
678                                            bool First) {
679   assert(!Req->isSatisfied()
680          && "Diagnose() can only be used on an unsatisfied requirement");
681   switch (Req->getSatisfactionStatus()) {
682   case concepts::TypeRequirement::SS_Dependent:
683     llvm_unreachable("Diagnosing a dependent requirement");
684     return;
685   case concepts::TypeRequirement::SS_SubstitutionFailure: {
686     auto *SubstDiag = Req->getSubstitutionDiagnostic();
687     if (!SubstDiag->DiagMessage.empty())
688       S.Diag(SubstDiag->DiagLoc,
689              diag::note_type_requirement_substitution_error) << (int)First
690           << SubstDiag->SubstitutedEntity << SubstDiag->DiagMessage;
691     else
692       S.Diag(SubstDiag->DiagLoc,
693              diag::note_type_requirement_unknown_substitution_error)
694           << (int)First << SubstDiag->SubstitutedEntity;
695     return;
696   }
697   default:
698     llvm_unreachable("Unknown satisfaction status");
699     return;
700   }
701 }
702 
703 static void diagnoseUnsatisfiedRequirement(Sema &S,
704                                            concepts::NestedRequirement *Req,
705                                            bool First) {
706   if (Req->isSubstitutionFailure()) {
707     concepts::Requirement::SubstitutionDiagnostic *SubstDiag =
708         Req->getSubstitutionDiagnostic();
709     if (!SubstDiag->DiagMessage.empty())
710       S.Diag(SubstDiag->DiagLoc,
711              diag::note_nested_requirement_substitution_error)
712              << (int)First << SubstDiag->SubstitutedEntity
713              << SubstDiag->DiagMessage;
714     else
715       S.Diag(SubstDiag->DiagLoc,
716              diag::note_nested_requirement_unknown_substitution_error)
717           << (int)First << SubstDiag->SubstitutedEntity;
718     return;
719   }
720   S.DiagnoseUnsatisfiedConstraint(Req->getConstraintSatisfaction(), First);
721 }
722 
723 
724 static void diagnoseWellFormedUnsatisfiedConstraintExpr(Sema &S,
725                                                         Expr *SubstExpr,
726                                                         bool First = true) {
727   SubstExpr = SubstExpr->IgnoreParenImpCasts();
728   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SubstExpr)) {
729     switch (BO->getOpcode()) {
730     // These two cases will in practice only be reached when using fold
731     // expressions with || and &&, since otherwise the || and && will have been
732     // broken down into atomic constraints during satisfaction checking.
733     case BO_LOr:
734       // Or evaluated to false - meaning both RHS and LHS evaluated to false.
735       diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getLHS(), First);
736       diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(),
737                                                   /*First=*/false);
738       return;
739     case BO_LAnd: {
740       bool LHSSatisfied =
741           BO->getLHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
742       if (LHSSatisfied) {
743         // LHS is true, so RHS must be false.
744         diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(), First);
745         return;
746       }
747       // LHS is false
748       diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getLHS(), First);
749 
750       // RHS might also be false
751       bool RHSSatisfied =
752           BO->getRHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
753       if (!RHSSatisfied)
754         diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(),
755                                                     /*First=*/false);
756       return;
757     }
758     case BO_GE:
759     case BO_LE:
760     case BO_GT:
761     case BO_LT:
762     case BO_EQ:
763     case BO_NE:
764       if (BO->getLHS()->getType()->isIntegerType() &&
765           BO->getRHS()->getType()->isIntegerType()) {
766         Expr::EvalResult SimplifiedLHS;
767         Expr::EvalResult SimplifiedRHS;
768         BO->getLHS()->EvaluateAsInt(SimplifiedLHS, S.Context,
769                                     Expr::SE_NoSideEffects,
770                                     /*InConstantContext=*/true);
771         BO->getRHS()->EvaluateAsInt(SimplifiedRHS, S.Context,
772                                     Expr::SE_NoSideEffects,
773                                     /*InConstantContext=*/true);
774         if (!SimplifiedLHS.Diag && ! SimplifiedRHS.Diag) {
775           S.Diag(SubstExpr->getBeginLoc(),
776                  diag::note_atomic_constraint_evaluated_to_false_elaborated)
777               << (int)First << SubstExpr
778               << toString(SimplifiedLHS.Val.getInt(), 10)
779               << BinaryOperator::getOpcodeStr(BO->getOpcode())
780               << toString(SimplifiedRHS.Val.getInt(), 10);
781           return;
782         }
783       }
784       break;
785 
786     default:
787       break;
788     }
789   } else if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(SubstExpr)) {
790     if (CSE->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
791       S.Diag(
792           CSE->getSourceRange().getBegin(),
793           diag::
794           note_single_arg_concept_specialization_constraint_evaluated_to_false)
795           << (int)First
796           << CSE->getTemplateArgsAsWritten()->arguments()[0].getArgument()
797           << CSE->getNamedConcept();
798     } else {
799       S.Diag(SubstExpr->getSourceRange().getBegin(),
800              diag::note_concept_specialization_constraint_evaluated_to_false)
801           << (int)First << CSE;
802     }
803     S.DiagnoseUnsatisfiedConstraint(CSE->getSatisfaction());
804     return;
805   } else if (auto *RE = dyn_cast<RequiresExpr>(SubstExpr)) {
806     for (concepts::Requirement *Req : RE->getRequirements())
807       if (!Req->isDependent() && !Req->isSatisfied()) {
808         if (auto *E = dyn_cast<concepts::ExprRequirement>(Req))
809           diagnoseUnsatisfiedRequirement(S, E, First);
810         else if (auto *T = dyn_cast<concepts::TypeRequirement>(Req))
811           diagnoseUnsatisfiedRequirement(S, T, First);
812         else
813           diagnoseUnsatisfiedRequirement(
814               S, cast<concepts::NestedRequirement>(Req), First);
815         break;
816       }
817     return;
818   }
819 
820   S.Diag(SubstExpr->getSourceRange().getBegin(),
821          diag::note_atomic_constraint_evaluated_to_false)
822       << (int)First << SubstExpr;
823 }
824 
825 template<typename SubstitutionDiagnostic>
826 static void diagnoseUnsatisfiedConstraintExpr(
827     Sema &S, const Expr *E,
828     const llvm::PointerUnion<Expr *, SubstitutionDiagnostic *> &Record,
829     bool First = true) {
830   if (auto *Diag = Record.template dyn_cast<SubstitutionDiagnostic *>()){
831     S.Diag(Diag->first, diag::note_substituted_constraint_expr_is_ill_formed)
832         << Diag->second;
833     return;
834   }
835 
836   diagnoseWellFormedUnsatisfiedConstraintExpr(S,
837       Record.template get<Expr *>(), First);
838 }
839 
840 void
841 Sema::DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction& Satisfaction,
842                                     bool First) {
843   assert(!Satisfaction.IsSatisfied &&
844          "Attempted to diagnose a satisfied constraint");
845   for (auto &Pair : Satisfaction.Details) {
846     diagnoseUnsatisfiedConstraintExpr(*this, Pair.first, Pair.second, First);
847     First = false;
848   }
849 }
850 
851 void Sema::DiagnoseUnsatisfiedConstraint(
852     const ASTConstraintSatisfaction &Satisfaction,
853     bool First) {
854   assert(!Satisfaction.IsSatisfied &&
855          "Attempted to diagnose a satisfied constraint");
856   for (auto &Pair : Satisfaction) {
857     diagnoseUnsatisfiedConstraintExpr(*this, Pair.first, Pair.second, First);
858     First = false;
859   }
860 }
861 
862 const NormalizedConstraint *
863 Sema::getNormalizedAssociatedConstraints(
864     NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints) {
865   auto CacheEntry = NormalizationCache.find(ConstrainedDecl);
866   if (CacheEntry == NormalizationCache.end()) {
867     auto Normalized =
868         NormalizedConstraint::fromConstraintExprs(*this, ConstrainedDecl,
869                                                   AssociatedConstraints);
870     CacheEntry =
871         NormalizationCache
872             .try_emplace(ConstrainedDecl,
873                          Normalized
874                              ? new (Context) NormalizedConstraint(
875                                  std::move(*Normalized))
876                              : nullptr)
877             .first;
878   }
879   return CacheEntry->second;
880 }
881 
882 static bool
883 substituteParameterMappings(Sema &S, NormalizedConstraint &N,
884                             ConceptDecl *Concept,
885                             const MultiLevelTemplateArgumentList &MLTAL,
886                             const ASTTemplateArgumentListInfo *ArgsAsWritten) {
887   if (!N.isAtomic()) {
888     if (substituteParameterMappings(S, N.getLHS(), Concept, MLTAL,
889                                     ArgsAsWritten))
890       return true;
891     return substituteParameterMappings(S, N.getRHS(), Concept, MLTAL,
892                                        ArgsAsWritten);
893   }
894   TemplateParameterList *TemplateParams = Concept->getTemplateParameters();
895 
896   AtomicConstraint &Atomic = *N.getAtomicConstraint();
897   TemplateArgumentListInfo SubstArgs;
898   if (!Atomic.ParameterMapping) {
899     llvm::SmallBitVector OccurringIndices(TemplateParams->size());
900     S.MarkUsedTemplateParameters(Atomic.ConstraintExpr, /*OnlyDeduced=*/false,
901                                  /*Depth=*/0, OccurringIndices);
902     Atomic.ParameterMapping.emplace(
903         MutableArrayRef<TemplateArgumentLoc>(
904             new (S.Context) TemplateArgumentLoc[OccurringIndices.count()],
905             OccurringIndices.count()));
906     for (unsigned I = 0, J = 0, C = TemplateParams->size(); I != C; ++I)
907       if (OccurringIndices[I])
908         new (&(*Atomic.ParameterMapping)[J++]) TemplateArgumentLoc(
909             S.getIdentityTemplateArgumentLoc(TemplateParams->begin()[I],
910                 // Here we assume we do not support things like
911                 // template<typename A, typename B>
912                 // concept C = ...;
913                 //
914                 // template<typename... Ts> requires C<Ts...>
915                 // struct S { };
916                 // The above currently yields a diagnostic.
917                 // We still might have default arguments for concept parameters.
918                 ArgsAsWritten->NumTemplateArgs > I ?
919                 ArgsAsWritten->arguments()[I].getLocation() :
920                 SourceLocation()));
921   }
922   Sema::InstantiatingTemplate Inst(
923       S, ArgsAsWritten->arguments().front().getSourceRange().getBegin(),
924       Sema::InstantiatingTemplate::ParameterMappingSubstitution{}, Concept,
925       SourceRange(ArgsAsWritten->arguments()[0].getSourceRange().getBegin(),
926                   ArgsAsWritten->arguments().back().getSourceRange().getEnd()));
927   if (S.SubstTemplateArguments(*Atomic.ParameterMapping, MLTAL, SubstArgs,
928                                /*InstantiateConstraints=*/true))
929     return true;
930   Atomic.ParameterMapping.emplace(
931         MutableArrayRef<TemplateArgumentLoc>(
932             new (S.Context) TemplateArgumentLoc[SubstArgs.size()],
933             SubstArgs.size()));
934   std::copy(SubstArgs.arguments().begin(), SubstArgs.arguments().end(),
935             N.getAtomicConstraint()->ParameterMapping->begin());
936   return false;
937 }
938 
939 static bool substituteParameterMappings(Sema &S, NormalizedConstraint &N,
940                                         const ConceptSpecializationExpr *CSE) {
941   TemplateArgumentList TAL{TemplateArgumentList::OnStack,
942                            CSE->getTemplateArguments()};
943   MultiLevelTemplateArgumentList MLTAL =
944       S.getTemplateInstantiationArgs(CSE->getNamedConcept(), &TAL,
945                                      /*RelativeToPrimary*/ true,
946                                      /*Pattern*/ nullptr,
947                                      /*LookBeyondLambda*/ true);
948 
949   return substituteParameterMappings(S, N, CSE->getNamedConcept(), MLTAL,
950                                      CSE->getTemplateArgsAsWritten());
951 }
952 
953 Optional<NormalizedConstraint>
954 NormalizedConstraint::fromConstraintExprs(Sema &S, NamedDecl *D,
955                                           ArrayRef<const Expr *> E) {
956   assert(E.size() != 0);
957   auto Conjunction = fromConstraintExpr(S, D, E[0]);
958   if (!Conjunction)
959     return None;
960   for (unsigned I = 1; I < E.size(); ++I) {
961     auto Next = fromConstraintExpr(S, D, E[I]);
962     if (!Next)
963       return None;
964     *Conjunction = NormalizedConstraint(S.Context, std::move(*Conjunction),
965                                         std::move(*Next), CCK_Conjunction);
966   }
967   return Conjunction;
968 }
969 
970 llvm::Optional<NormalizedConstraint>
971 NormalizedConstraint::fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E) {
972   assert(E != nullptr);
973 
974   // C++ [temp.constr.normal]p1.1
975   // [...]
976   // - The normal form of an expression (E) is the normal form of E.
977   // [...]
978   E = E->IgnoreParenImpCasts();
979   if (LogicalBinOp BO = E) {
980     auto LHS = fromConstraintExpr(S, D, BO.getLHS());
981     if (!LHS)
982       return None;
983     auto RHS = fromConstraintExpr(S, D, BO.getRHS());
984     if (!RHS)
985       return None;
986 
987     return NormalizedConstraint(S.Context, std::move(*LHS), std::move(*RHS),
988                                 BO.isAnd() ? CCK_Conjunction : CCK_Disjunction);
989   } else if (auto *CSE = dyn_cast<const ConceptSpecializationExpr>(E)) {
990     const NormalizedConstraint *SubNF;
991     {
992       Sema::InstantiatingTemplate Inst(
993           S, CSE->getExprLoc(),
994           Sema::InstantiatingTemplate::ConstraintNormalization{}, D,
995           CSE->getSourceRange());
996       // C++ [temp.constr.normal]p1.1
997       // [...]
998       // The normal form of an id-expression of the form C<A1, A2, ..., AN>,
999       // where C names a concept, is the normal form of the
1000       // constraint-expression of C, after substituting A1, A2, ..., AN for C’s
1001       // respective template parameters in the parameter mappings in each atomic
1002       // constraint. If any such substitution results in an invalid type or
1003       // expression, the program is ill-formed; no diagnostic is required.
1004       // [...]
1005       ConceptDecl *CD = CSE->getNamedConcept();
1006       SubNF = S.getNormalizedAssociatedConstraints(CD,
1007                                                    {CD->getConstraintExpr()});
1008       if (!SubNF)
1009         return None;
1010     }
1011 
1012     Optional<NormalizedConstraint> New;
1013     New.emplace(S.Context, *SubNF);
1014 
1015     if (substituteParameterMappings(S, *New, CSE))
1016       return None;
1017 
1018     return New;
1019   }
1020   return NormalizedConstraint{new (S.Context) AtomicConstraint(S, E)};
1021 }
1022 
1023 using NormalForm =
1024     llvm::SmallVector<llvm::SmallVector<AtomicConstraint *, 2>, 4>;
1025 
1026 static NormalForm makeCNF(const NormalizedConstraint &Normalized) {
1027   if (Normalized.isAtomic())
1028     return {{Normalized.getAtomicConstraint()}};
1029 
1030   NormalForm LCNF = makeCNF(Normalized.getLHS());
1031   NormalForm RCNF = makeCNF(Normalized.getRHS());
1032   if (Normalized.getCompoundKind() == NormalizedConstraint::CCK_Conjunction) {
1033     LCNF.reserve(LCNF.size() + RCNF.size());
1034     while (!RCNF.empty())
1035       LCNF.push_back(RCNF.pop_back_val());
1036     return LCNF;
1037   }
1038 
1039   // Disjunction
1040   NormalForm Res;
1041   Res.reserve(LCNF.size() * RCNF.size());
1042   for (auto &LDisjunction : LCNF)
1043     for (auto &RDisjunction : RCNF) {
1044       NormalForm::value_type Combined;
1045       Combined.reserve(LDisjunction.size() + RDisjunction.size());
1046       std::copy(LDisjunction.begin(), LDisjunction.end(),
1047                 std::back_inserter(Combined));
1048       std::copy(RDisjunction.begin(), RDisjunction.end(),
1049                 std::back_inserter(Combined));
1050       Res.emplace_back(Combined);
1051     }
1052   return Res;
1053 }
1054 
1055 static NormalForm makeDNF(const NormalizedConstraint &Normalized) {
1056   if (Normalized.isAtomic())
1057     return {{Normalized.getAtomicConstraint()}};
1058 
1059   NormalForm LDNF = makeDNF(Normalized.getLHS());
1060   NormalForm RDNF = makeDNF(Normalized.getRHS());
1061   if (Normalized.getCompoundKind() == NormalizedConstraint::CCK_Disjunction) {
1062     LDNF.reserve(LDNF.size() + RDNF.size());
1063     while (!RDNF.empty())
1064       LDNF.push_back(RDNF.pop_back_val());
1065     return LDNF;
1066   }
1067 
1068   // Conjunction
1069   NormalForm Res;
1070   Res.reserve(LDNF.size() * RDNF.size());
1071   for (auto &LConjunction : LDNF) {
1072     for (auto &RConjunction : RDNF) {
1073       NormalForm::value_type Combined;
1074       Combined.reserve(LConjunction.size() + RConjunction.size());
1075       std::copy(LConjunction.begin(), LConjunction.end(),
1076                 std::back_inserter(Combined));
1077       std::copy(RConjunction.begin(), RConjunction.end(),
1078                 std::back_inserter(Combined));
1079       Res.emplace_back(Combined);
1080     }
1081   }
1082   return Res;
1083 }
1084 
1085 template<typename AtomicSubsumptionEvaluator>
1086 static bool subsumes(NormalForm PDNF, NormalForm QCNF,
1087                      AtomicSubsumptionEvaluator E) {
1088   // C++ [temp.constr.order] p2
1089   //   Then, P subsumes Q if and only if, for every disjunctive clause Pi in the
1090   //   disjunctive normal form of P, Pi subsumes every conjunctive clause Qj in
1091   //   the conjuctive normal form of Q, where [...]
1092   for (const auto &Pi : PDNF) {
1093     for (const auto &Qj : QCNF) {
1094       // C++ [temp.constr.order] p2
1095       //   - [...] a disjunctive clause Pi subsumes a conjunctive clause Qj if
1096       //     and only if there exists an atomic constraint Pia in Pi for which
1097       //     there exists an atomic constraint, Qjb, in Qj such that Pia
1098       //     subsumes Qjb.
1099       bool Found = false;
1100       for (const AtomicConstraint *Pia : Pi) {
1101         for (const AtomicConstraint *Qjb : Qj) {
1102           if (E(*Pia, *Qjb)) {
1103             Found = true;
1104             break;
1105           }
1106         }
1107         if (Found)
1108           break;
1109       }
1110       if (!Found)
1111         return false;
1112     }
1113   }
1114   return true;
1115 }
1116 
1117 template<typename AtomicSubsumptionEvaluator>
1118 static bool subsumes(Sema &S, NamedDecl *DP, ArrayRef<const Expr *> P,
1119                      NamedDecl *DQ, ArrayRef<const Expr *> Q, bool &Subsumes,
1120                      AtomicSubsumptionEvaluator E) {
1121   // C++ [temp.constr.order] p2
1122   //   In order to determine if a constraint P subsumes a constraint Q, P is
1123   //   transformed into disjunctive normal form, and Q is transformed into
1124   //   conjunctive normal form. [...]
1125   auto *PNormalized = S.getNormalizedAssociatedConstraints(DP, P);
1126   if (!PNormalized)
1127     return true;
1128   const NormalForm PDNF = makeDNF(*PNormalized);
1129 
1130   auto *QNormalized = S.getNormalizedAssociatedConstraints(DQ, Q);
1131   if (!QNormalized)
1132     return true;
1133   const NormalForm QCNF = makeCNF(*QNormalized);
1134 
1135   Subsumes = subsumes(PDNF, QCNF, E);
1136   return false;
1137 }
1138 
1139 bool Sema::IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
1140                                   NamedDecl *D2, ArrayRef<const Expr *> AC2,
1141                                   bool &Result) {
1142   if (AC1.empty()) {
1143     Result = AC2.empty();
1144     return false;
1145   }
1146   if (AC2.empty()) {
1147     // TD1 has associated constraints and TD2 does not.
1148     Result = true;
1149     return false;
1150   }
1151 
1152   std::pair<NamedDecl *, NamedDecl *> Key{D1, D2};
1153   auto CacheEntry = SubsumptionCache.find(Key);
1154   if (CacheEntry != SubsumptionCache.end()) {
1155     Result = CacheEntry->second;
1156     return false;
1157   }
1158 
1159   if (subsumes(*this, D1, AC1, D2, AC2, Result,
1160         [this] (const AtomicConstraint &A, const AtomicConstraint &B) {
1161           return A.subsumes(Context, B);
1162         }))
1163     return true;
1164   SubsumptionCache.try_emplace(Key, Result);
1165   return false;
1166 }
1167 
1168 bool Sema::MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
1169     ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2) {
1170   if (isSFINAEContext())
1171     // No need to work here because our notes would be discarded.
1172     return false;
1173 
1174   if (AC1.empty() || AC2.empty())
1175     return false;
1176 
1177   auto NormalExprEvaluator =
1178       [this] (const AtomicConstraint &A, const AtomicConstraint &B) {
1179         return A.subsumes(Context, B);
1180       };
1181 
1182   const Expr *AmbiguousAtomic1 = nullptr, *AmbiguousAtomic2 = nullptr;
1183   auto IdenticalExprEvaluator =
1184       [&] (const AtomicConstraint &A, const AtomicConstraint &B) {
1185         if (!A.hasMatchingParameterMapping(Context, B))
1186           return false;
1187         const Expr *EA = A.ConstraintExpr, *EB = B.ConstraintExpr;
1188         if (EA == EB)
1189           return true;
1190 
1191         // Not the same source level expression - are the expressions
1192         // identical?
1193         llvm::FoldingSetNodeID IDA, IDB;
1194         EA->Profile(IDA, Context, /*Canonical=*/true);
1195         EB->Profile(IDB, Context, /*Canonical=*/true);
1196         if (IDA != IDB)
1197           return false;
1198 
1199         AmbiguousAtomic1 = EA;
1200         AmbiguousAtomic2 = EB;
1201         return true;
1202       };
1203 
1204   {
1205     // The subsumption checks might cause diagnostics
1206     SFINAETrap Trap(*this);
1207     auto *Normalized1 = getNormalizedAssociatedConstraints(D1, AC1);
1208     if (!Normalized1)
1209       return false;
1210     const NormalForm DNF1 = makeDNF(*Normalized1);
1211     const NormalForm CNF1 = makeCNF(*Normalized1);
1212 
1213     auto *Normalized2 = getNormalizedAssociatedConstraints(D2, AC2);
1214     if (!Normalized2)
1215       return false;
1216     const NormalForm DNF2 = makeDNF(*Normalized2);
1217     const NormalForm CNF2 = makeCNF(*Normalized2);
1218 
1219     bool Is1AtLeastAs2Normally = subsumes(DNF1, CNF2, NormalExprEvaluator);
1220     bool Is2AtLeastAs1Normally = subsumes(DNF2, CNF1, NormalExprEvaluator);
1221     bool Is1AtLeastAs2 = subsumes(DNF1, CNF2, IdenticalExprEvaluator);
1222     bool Is2AtLeastAs1 = subsumes(DNF2, CNF1, IdenticalExprEvaluator);
1223     if (Is1AtLeastAs2 == Is1AtLeastAs2Normally &&
1224         Is2AtLeastAs1 == Is2AtLeastAs1Normally)
1225       // Same result - no ambiguity was caused by identical atomic expressions.
1226       return false;
1227   }
1228 
1229   // A different result! Some ambiguous atomic constraint(s) caused a difference
1230   assert(AmbiguousAtomic1 && AmbiguousAtomic2);
1231 
1232   Diag(AmbiguousAtomic1->getBeginLoc(), diag::note_ambiguous_atomic_constraints)
1233       << AmbiguousAtomic1->getSourceRange();
1234   Diag(AmbiguousAtomic2->getBeginLoc(),
1235        diag::note_ambiguous_atomic_constraints_similar_expression)
1236       << AmbiguousAtomic2->getSourceRange();
1237   return true;
1238 }
1239 
1240 concepts::ExprRequirement::ExprRequirement(
1241     Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
1242     ReturnTypeRequirement Req, SatisfactionStatus Status,
1243     ConceptSpecializationExpr *SubstitutedConstraintExpr) :
1244     Requirement(IsSimple ? RK_Simple : RK_Compound, Status == SS_Dependent,
1245                 Status == SS_Dependent &&
1246                 (E->containsUnexpandedParameterPack() ||
1247                  Req.containsUnexpandedParameterPack()),
1248                 Status == SS_Satisfied), Value(E), NoexceptLoc(NoexceptLoc),
1249     TypeReq(Req), SubstitutedConstraintExpr(SubstitutedConstraintExpr),
1250     Status(Status) {
1251   assert((!IsSimple || (Req.isEmpty() && NoexceptLoc.isInvalid())) &&
1252          "Simple requirement must not have a return type requirement or a "
1253          "noexcept specification");
1254   assert((Status > SS_TypeRequirementSubstitutionFailure && Req.isTypeConstraint()) ==
1255          (SubstitutedConstraintExpr != nullptr));
1256 }
1257 
1258 concepts::ExprRequirement::ExprRequirement(
1259     SubstitutionDiagnostic *ExprSubstDiag, bool IsSimple,
1260     SourceLocation NoexceptLoc, ReturnTypeRequirement Req) :
1261     Requirement(IsSimple ? RK_Simple : RK_Compound, Req.isDependent(),
1262                 Req.containsUnexpandedParameterPack(), /*IsSatisfied=*/false),
1263     Value(ExprSubstDiag), NoexceptLoc(NoexceptLoc), TypeReq(Req),
1264     Status(SS_ExprSubstitutionFailure) {
1265   assert((!IsSimple || (Req.isEmpty() && NoexceptLoc.isInvalid())) &&
1266          "Simple requirement must not have a return type requirement or a "
1267          "noexcept specification");
1268 }
1269 
1270 concepts::ExprRequirement::ReturnTypeRequirement::
1271 ReturnTypeRequirement(TemplateParameterList *TPL) :
1272     TypeConstraintInfo(TPL, false) {
1273   assert(TPL->size() == 1);
1274   const TypeConstraint *TC =
1275       cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint();
1276   assert(TC &&
1277          "TPL must have a template type parameter with a type constraint");
1278   auto *Constraint =
1279       cast<ConceptSpecializationExpr>(TC->getImmediatelyDeclaredConstraint());
1280   bool Dependent =
1281       Constraint->getTemplateArgsAsWritten() &&
1282       TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
1283           Constraint->getTemplateArgsAsWritten()->arguments().drop_front(1));
1284   TypeConstraintInfo.setInt(Dependent ? true : false);
1285 }
1286 
1287 concepts::TypeRequirement::TypeRequirement(TypeSourceInfo *T) :
1288     Requirement(RK_Type, T->getType()->isInstantiationDependentType(),
1289                 T->getType()->containsUnexpandedParameterPack(),
1290                 // We reach this ctor with either dependent types (in which
1291                 // IsSatisfied doesn't matter) or with non-dependent type in
1292                 // which the existence of the type indicates satisfaction.
1293                 /*IsSatisfied=*/true),
1294     Value(T),
1295     Status(T->getType()->isInstantiationDependentType() ? SS_Dependent
1296                                                         : SS_Satisfied) {}
1297