1 //===- WatchedLiteralsSolver.cpp --------------------------------*- C++ -*-===//
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 defines a SAT solver implementation that can be used by dataflow
10 //  analyses.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include <cassert>
15 #include <cstdint>
16 #include <iterator>
17 #include <queue>
18 #include <vector>
19 
20 #include "clang/Analysis/FlowSensitive/Solver.h"
21 #include "clang/Analysis/FlowSensitive/Value.h"
22 #include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/STLExtras.h"
26 
27 namespace clang {
28 namespace dataflow {
29 
30 // `WatchedLiteralsSolver` is an implementation of Algorithm D from Knuth's
31 // The Art of Computer Programming Volume 4: Satisfiability, Fascicle 6. It is
32 // based on the backtracking DPLL algorithm [1], keeps references to a single
33 // "watched" literal per clause, and uses a set of "active" variables to perform
34 // unit propagation.
35 //
36 // The solver expects that its input is a boolean formula in conjunctive normal
37 // form that consists of clauses of at least one literal. A literal is either a
38 // boolean variable or its negation. Below we define types, data structures, and
39 // utilities that are used to represent boolean formulas in conjunctive normal
40 // form.
41 //
42 // [1] https://en.wikipedia.org/wiki/DPLL_algorithm
43 
44 /// Boolean variables are represented as positive integers.
45 using Variable = uint32_t;
46 
47 /// A null boolean variable is used as a placeholder in various data structures
48 /// and algorithms.
49 static constexpr Variable NullVar = 0;
50 
51 /// Literals are represented as positive integers. Specifically, for a boolean
52 /// variable `V` that is represented as the positive integer `I`, the positive
53 /// literal `V` is represented as the integer `2*I` and the negative literal
54 /// `!V` is represented as the integer `2*I+1`.
55 using Literal = uint32_t;
56 
57 /// A null literal is used as a placeholder in various data structures and
58 /// algorithms.
59 static constexpr Literal NullLit = 0;
60 
61 /// Returns the positive literal `V`.
62 static constexpr Literal posLit(Variable V) { return 2 * V; }
63 
64 /// Returns the negative literal `!V`.
65 static constexpr Literal negLit(Variable V) { return 2 * V + 1; }
66 
67 /// Returns the negated literal `!L`.
68 static constexpr Literal notLit(Literal L) { return L ^ 1; }
69 
70 /// Returns the variable of `L`.
71 static constexpr Variable var(Literal L) { return L >> 1; }
72 
73 /// Clause identifiers are represented as positive integers.
74 using ClauseID = uint32_t;
75 
76 /// A null clause identifier is used as a placeholder in various data structures
77 /// and algorithms.
78 static constexpr ClauseID NullClause = 0;
79 
80 /// A boolean formula in conjunctive normal form.
81 struct BooleanFormula {
82   /// `LargestVar` is equal to the largest positive integer that represents a
83   /// variable in the formula.
84   const Variable LargestVar;
85 
86   /// Literals of all clauses in the formula.
87   ///
88   /// The element at index 0 stands for the literal in the null clause. It is
89   /// set to 0 and isn't used. Literals of clauses in the formula start from the
90   /// element at index 1.
91   ///
92   /// For example, for the formula `(L1 v L2) ^ (L2 v L3 v L4)` the elements of
93   /// `Clauses` will be `[0, L1, L2, L2, L3, L4]`.
94   std::vector<Literal> Clauses;
95 
96   /// Start indices of clauses of the formula in `Clauses`.
97   ///
98   /// The element at index 0 stands for the start index of the null clause. It
99   /// is set to 0 and isn't used. Start indices of clauses in the formula start
100   /// from the element at index 1.
101   ///
102   /// For example, for the formula `(L1 v L2) ^ (L2 v L3 v L4)` the elements of
103   /// `ClauseStarts` will be `[0, 1, 3]`. Note that the literals of the first
104   /// clause always start at index 1. The start index for the literals of the
105   /// second clause depends on the size of the first clause and so on.
106   std::vector<size_t> ClauseStarts;
107 
108   /// Maps literals (indices of the vector) to clause identifiers (elements of
109   /// the vector) that watch the respective literals.
110   ///
111   /// For a given clause, its watched literal is always its first literal in
112   /// `Clauses`. This invariant is maintained when watched literals change.
113   std::vector<ClauseID> WatchedHead;
114 
115   /// Maps clause identifiers (elements of the vector) to identifiers of other
116   /// clauses that watch the same literals, forming a set of linked lists.
117   ///
118   /// The element at index 0 stands for the identifier of the clause that
119   /// follows the null clause. It is set to 0 and isn't used. Identifiers of
120   /// clauses in the formula start from the element at index 1.
121   std::vector<ClauseID> NextWatched;
122 
123   /// Stores the variable identifier and value location for atomic booleans in
124   /// the formula.
125   llvm::DenseMap<Variable, AtomicBoolValue *> Atomics;
126 
127   explicit BooleanFormula(Variable LargestVar,
128                           llvm::DenseMap<Variable, AtomicBoolValue *> Atomics)
129       : LargestVar(LargestVar), Atomics(std::move(Atomics)) {
130     Clauses.push_back(0);
131     ClauseStarts.push_back(0);
132     NextWatched.push_back(0);
133     const size_t NumLiterals = 2 * LargestVar + 1;
134     WatchedHead.resize(NumLiterals + 1, 0);
135   }
136 
137   /// Adds the `L1 v L2 v L3` clause to the formula. If `L2` or `L3` are
138   /// `NullLit` they are respectively omitted from the clause.
139   ///
140   /// Requirements:
141   ///
142   ///  `L1` must not be `NullLit`.
143   ///
144   ///  All literals in the input that are not `NullLit` must be distinct.
145   void addClause(Literal L1, Literal L2 = NullLit, Literal L3 = NullLit) {
146     // The literals are guaranteed to be distinct from properties of BoolValue
147     // and the construction in `buildBooleanFormula`.
148     assert(L1 != NullLit && L1 != L2 && L1 != L3 &&
149            (L2 != L3 || L2 == NullLit));
150 
151     const ClauseID C = ClauseStarts.size();
152     const size_t S = Clauses.size();
153     ClauseStarts.push_back(S);
154 
155     Clauses.push_back(L1);
156     if (L2 != NullLit)
157       Clauses.push_back(L2);
158     if (L3 != NullLit)
159       Clauses.push_back(L3);
160 
161     // Designate the first literal as the "watched" literal of the clause.
162     NextWatched.push_back(WatchedHead[L1]);
163     WatchedHead[L1] = C;
164   }
165 
166   /// Returns the number of literals in clause `C`.
167   size_t clauseSize(ClauseID C) const {
168     return C == ClauseStarts.size() - 1 ? Clauses.size() - ClauseStarts[C]
169                                         : ClauseStarts[C + 1] - ClauseStarts[C];
170   }
171 
172   /// Returns the literals of clause `C`.
173   llvm::ArrayRef<Literal> clauseLiterals(ClauseID C) const {
174     return llvm::ArrayRef<Literal>(&Clauses[ClauseStarts[C]], clauseSize(C));
175   }
176 };
177 
178 /// Converts the conjunction of `Vals` into a formula in conjunctive normal
179 /// form where each clause has at least one and at most three literals.
180 BooleanFormula buildBooleanFormula(const llvm::DenseSet<BoolValue *> &Vals) {
181   // The general strategy of the algorithm implemented below is to map each
182   // of the sub-values in `Vals` to a unique variable and use these variables in
183   // the resulting CNF expression to avoid exponential blow up. The number of
184   // literals in the resulting formula is guaranteed to be linear in the number
185   // of sub-values in `Vals`.
186 
187   // Map each sub-value in `Vals` to a unique variable.
188   llvm::DenseMap<BoolValue *, Variable> SubValsToVar;
189   // Store variable identifiers and value location of atomic booleans.
190   llvm::DenseMap<Variable, AtomicBoolValue *> Atomics;
191   Variable NextVar = 1;
192   {
193     std::queue<BoolValue *> UnprocessedSubVals;
194     for (BoolValue *Val : Vals)
195       UnprocessedSubVals.push(Val);
196     while (!UnprocessedSubVals.empty()) {
197       Variable Var = NextVar;
198       BoolValue *Val = UnprocessedSubVals.front();
199       UnprocessedSubVals.pop();
200 
201       if (!SubValsToVar.try_emplace(Val, Var).second)
202         continue;
203       ++NextVar;
204 
205       // Visit the sub-values of `Val`.
206       switch (Val->getKind()) {
207       case Value::Kind::Conjunction: {
208         auto *C = cast<ConjunctionValue>(Val);
209         UnprocessedSubVals.push(&C->getLeftSubValue());
210         UnprocessedSubVals.push(&C->getRightSubValue());
211         break;
212       }
213       case Value::Kind::Disjunction: {
214         auto *D = cast<DisjunctionValue>(Val);
215         UnprocessedSubVals.push(&D->getLeftSubValue());
216         UnprocessedSubVals.push(&D->getRightSubValue());
217         break;
218       }
219       case Value::Kind::Negation: {
220         auto *N = cast<NegationValue>(Val);
221         UnprocessedSubVals.push(&N->getSubVal());
222         break;
223       }
224       case Value::Kind::AtomicBool: {
225         Atomics[Var] = cast<AtomicBoolValue>(Val);
226         break;
227       }
228       default:
229         llvm_unreachable("buildBooleanFormula: unhandled value kind");
230       }
231     }
232   }
233 
234   auto GetVar = [&SubValsToVar](const BoolValue *Val) {
235     auto ValIt = SubValsToVar.find(Val);
236     assert(ValIt != SubValsToVar.end());
237     return ValIt->second;
238   };
239 
240   BooleanFormula Formula(NextVar - 1, std::move(Atomics));
241   std::vector<bool> ProcessedSubVals(NextVar, false);
242 
243   // Add a conjunct for each variable that represents a top-level conjunction
244   // value in `Vals`.
245   for (BoolValue *Val : Vals)
246     Formula.addClause(posLit(GetVar(Val)));
247 
248   // Add conjuncts that represent the mapping between newly-created variables
249   // and their corresponding sub-values.
250   std::queue<BoolValue *> UnprocessedSubVals;
251   for (BoolValue *Val : Vals)
252     UnprocessedSubVals.push(Val);
253   while (!UnprocessedSubVals.empty()) {
254     const BoolValue *Val = UnprocessedSubVals.front();
255     UnprocessedSubVals.pop();
256     const Variable Var = GetVar(Val);
257 
258     if (ProcessedSubVals[Var])
259       continue;
260     ProcessedSubVals[Var] = true;
261 
262     if (auto *C = dyn_cast<ConjunctionValue>(Val)) {
263       const Variable LeftSubVar = GetVar(&C->getLeftSubValue());
264       const Variable RightSubVar = GetVar(&C->getRightSubValue());
265 
266       if (LeftSubVar == RightSubVar) {
267         // `X <=> (A ^ A)` is equivalent to `(!X v A) ^ (X v !A)` which is
268         // already in conjunctive normal form. Below we add each of the
269         // conjuncts of the latter expression to the result.
270         Formula.addClause(negLit(Var), posLit(LeftSubVar));
271         Formula.addClause(posLit(Var), negLit(LeftSubVar));
272 
273         // Visit a sub-value of `Val` (pick any, they are identical).
274         UnprocessedSubVals.push(&C->getLeftSubValue());
275       } else {
276         // `X <=> (A ^ B)` is equivalent to `(!X v A) ^ (!X v B) ^ (X v !A v !B)`
277         // which is already in conjunctive normal form. Below we add each of the
278         // conjuncts of the latter expression to the result.
279         Formula.addClause(negLit(Var), posLit(LeftSubVar));
280         Formula.addClause(negLit(Var), posLit(RightSubVar));
281         Formula.addClause(posLit(Var), negLit(LeftSubVar), negLit(RightSubVar));
282 
283         // Visit the sub-values of `Val`.
284         UnprocessedSubVals.push(&C->getLeftSubValue());
285         UnprocessedSubVals.push(&C->getRightSubValue());
286       }
287     } else if (auto *D = dyn_cast<DisjunctionValue>(Val)) {
288       const Variable LeftSubVar = GetVar(&D->getLeftSubValue());
289       const Variable RightSubVar = GetVar(&D->getRightSubValue());
290 
291       if (LeftSubVar == RightSubVar) {
292         // `X <=> (A v A)` is equivalent to `(!X v A) ^ (X v !A)` which is
293         // already in conjunctive normal form. Below we add each of the
294         // conjuncts of the latter expression to the result.
295         Formula.addClause(negLit(Var), posLit(LeftSubVar));
296         Formula.addClause(posLit(Var), negLit(LeftSubVar));
297 
298         // Visit a sub-value of `Val` (pick any, they are identical).
299         UnprocessedSubVals.push(&D->getLeftSubValue());
300       } else {
301         // `X <=> (A v B)` is equivalent to `(!X v A v B) ^ (X v !A) ^ (X v !B)`
302         // which is already in conjunctive normal form. Below we add each of the
303         // conjuncts of the latter expression to the result.
304         Formula.addClause(negLit(Var), posLit(LeftSubVar), posLit(RightSubVar));
305         Formula.addClause(posLit(Var), negLit(LeftSubVar));
306         Formula.addClause(posLit(Var), negLit(RightSubVar));
307 
308         // Visit the sub-values of `Val`.
309         UnprocessedSubVals.push(&D->getLeftSubValue());
310         UnprocessedSubVals.push(&D->getRightSubValue());
311       }
312     } else if (auto *N = dyn_cast<NegationValue>(Val)) {
313       const Variable SubVar = GetVar(&N->getSubVal());
314 
315       // `X <=> !Y` is equivalent to `(!X v !Y) ^ (X v Y)` which is already in
316       // conjunctive normal form. Below we add each of the conjuncts of the
317       // latter expression to the result.
318       Formula.addClause(negLit(Var), negLit(SubVar));
319       Formula.addClause(posLit(Var), posLit(SubVar));
320 
321       // Visit the sub-values of `Val`.
322       UnprocessedSubVals.push(&N->getSubVal());
323     }
324   }
325 
326   return Formula;
327 }
328 
329 class WatchedLiteralsSolverImpl {
330   /// A boolean formula in conjunctive normal form that the solver will attempt
331   /// to prove satisfiable. The formula will be modified in the process.
332   BooleanFormula Formula;
333 
334   /// The search for a satisfying assignment of the variables in `Formula` will
335   /// proceed in levels, starting from 1 and going up to `Formula.LargestVar`
336   /// (inclusive). The current level is stored in `Level`. At each level the
337   /// solver will assign a value to an unassigned variable. If this leads to a
338   /// consistent partial assignment, `Level` will be incremented. Otherwise, if
339   /// it results in a conflict, the solver will backtrack by decrementing
340   /// `Level` until it reaches the most recent level where a decision was made.
341   size_t Level = 0;
342 
343   /// Maps levels (indices of the vector) to variables (elements of the vector)
344   /// that are assigned values at the respective levels.
345   ///
346   /// The element at index 0 isn't used. Variables start from the element at
347   /// index 1.
348   std::vector<Variable> LevelVars;
349 
350   /// State of the solver at a particular level.
351   enum class State : uint8_t {
352     /// Indicates that the solver made a decision.
353     Decision = 0,
354 
355     /// Indicates that the solver made a forced move.
356     Forced = 1,
357   };
358 
359   /// State of the solver at a particular level. It keeps track of previous
360   /// decisions that the solver can refer to when backtracking.
361   ///
362   /// The element at index 0 isn't used. States start from the element at index
363   /// 1.
364   std::vector<State> LevelStates;
365 
366   enum class Assignment : int8_t {
367     Unassigned = -1,
368     AssignedFalse = 0,
369     AssignedTrue = 1
370   };
371 
372   /// Maps variables (indices of the vector) to their assignments (elements of
373   /// the vector).
374   ///
375   /// The element at index 0 isn't used. Variable assignments start from the
376   /// element at index 1.
377   std::vector<Assignment> VarAssignments;
378 
379   /// A set of unassigned variables that appear in watched literals in
380   /// `Formula`. The vector is guaranteed to contain unique elements.
381   std::vector<Variable> ActiveVars;
382 
383 public:
384   explicit WatchedLiteralsSolverImpl(const llvm::DenseSet<BoolValue *> &Vals)
385       : Formula(buildBooleanFormula(Vals)), LevelVars(Formula.LargestVar + 1),
386         LevelStates(Formula.LargestVar + 1) {
387     assert(!Vals.empty());
388 
389     // Initialize the state at the root level to a decision so that in
390     // `reverseForcedMoves` we don't have to check that `Level >= 0` on each
391     // iteration.
392     LevelStates[0] = State::Decision;
393 
394     // Initialize all variables as unassigned.
395     VarAssignments.resize(Formula.LargestVar + 1, Assignment::Unassigned);
396 
397     // Initialize the active variables.
398     for (Variable Var = Formula.LargestVar; Var != NullVar; --Var) {
399       if (isWatched(posLit(Var)) || isWatched(negLit(Var)))
400         ActiveVars.push_back(Var);
401     }
402   }
403 
404   Solver::Result solve() && {
405     size_t I = 0;
406     while (I < ActiveVars.size()) {
407       // Assert that the following invariants hold:
408       // 1. All active variables are unassigned.
409       // 2. All active variables form watched literals.
410       // 3. Unassigned variables that form watched literals are active.
411       // FIXME: Consider replacing these with test cases that fail if the any
412       // of the invariants is broken. That might not be easy due to the
413       // transformations performed by `buildBooleanFormula`.
414       assert(activeVarsAreUnassigned());
415       assert(activeVarsFormWatchedLiterals());
416       assert(unassignedVarsFormingWatchedLiteralsAreActive());
417 
418       const Variable ActiveVar = ActiveVars[I];
419 
420       // Look for unit clauses that contain the active variable.
421       const bool unitPosLit = watchedByUnitClause(posLit(ActiveVar));
422       const bool unitNegLit = watchedByUnitClause(negLit(ActiveVar));
423       if (unitPosLit && unitNegLit) {
424         // We found a conflict!
425 
426         // Backtrack and rewind the `Level` until the most recent non-forced
427         // assignment.
428         reverseForcedMoves();
429 
430         // If the root level is reached, then all possible assignments lead to
431         // a conflict.
432         if (Level == 0)
433           return Solver::Result::Unsatisfiable();
434 
435         // Otherwise, take the other branch at the most recent level where a
436         // decision was made.
437         LevelStates[Level] = State::Forced;
438         const Variable Var = LevelVars[Level];
439         VarAssignments[Var] = VarAssignments[Var] == Assignment::AssignedTrue
440                                   ? Assignment::AssignedFalse
441                                   : Assignment::AssignedTrue;
442 
443         updateWatchedLiterals();
444       } else if (unitPosLit || unitNegLit) {
445         // We found a unit clause! The value of its unassigned variable is
446         // forced.
447         ++Level;
448 
449         LevelVars[Level] = ActiveVar;
450         LevelStates[Level] = State::Forced;
451         VarAssignments[ActiveVar] =
452             unitPosLit ? Assignment::AssignedTrue : Assignment::AssignedFalse;
453 
454         // Remove the variable that was just assigned from the set of active
455         // variables.
456         if (I + 1 < ActiveVars.size()) {
457           // Replace the variable that was just assigned with the last active
458           // variable for efficient removal.
459           ActiveVars[I] = ActiveVars.back();
460         } else {
461           // This was the last active variable. Repeat the process from the
462           // beginning.
463           I = 0;
464         }
465         ActiveVars.pop_back();
466 
467         updateWatchedLiterals();
468       } else if (I + 1 == ActiveVars.size()) {
469         // There are no remaining unit clauses in the formula! Make a decision
470         // for one of the active variables at the current level.
471         ++Level;
472 
473         LevelVars[Level] = ActiveVar;
474         LevelStates[Level] = State::Decision;
475         VarAssignments[ActiveVar] = decideAssignment(ActiveVar);
476 
477         // Remove the variable that was just assigned from the set of active
478         // variables.
479         ActiveVars.pop_back();
480 
481         updateWatchedLiterals();
482 
483         // This was the last active variable. Repeat the process from the
484         // beginning.
485         I = 0;
486       } else {
487         ++I;
488       }
489     }
490     return Solver::Result::Satisfiable(buildSolution());
491   }
492 
493 private:
494   /// Returns a satisfying truth assignment to the atomic values in the boolean
495   /// formula.
496   llvm::DenseMap<AtomicBoolValue *, Solver::Result::Assignment>
497   buildSolution() {
498     llvm::DenseMap<AtomicBoolValue *, Solver::Result::Assignment> Solution;
499     for (auto &Atomic : Formula.Atomics) {
500       // A variable may have a definite true/false assignment, or it may be
501       // unassigned indicating its truth value does not affect the result of
502       // the formula. Unassigned variables are assigned to true as a default.
503       Solution[Atomic.second] =
504           VarAssignments[Atomic.first] == Assignment::AssignedFalse
505               ? Solver::Result::Assignment::AssignedFalse
506               : Solver::Result::Assignment::AssignedTrue;
507     }
508     return Solution;
509   }
510 
511   /// Reverses forced moves until the most recent level where a decision was
512   /// made on the assignment of a variable.
513   void reverseForcedMoves() {
514     for (; LevelStates[Level] == State::Forced; --Level) {
515       const Variable Var = LevelVars[Level];
516 
517       VarAssignments[Var] = Assignment::Unassigned;
518 
519       // If the variable that we pass through is watched then we add it to the
520       // active variables.
521       if (isWatched(posLit(Var)) || isWatched(negLit(Var)))
522         ActiveVars.push_back(Var);
523     }
524   }
525 
526   /// Updates watched literals that are affected by a variable assignment.
527   void updateWatchedLiterals() {
528     const Variable Var = LevelVars[Level];
529 
530     // Update the watched literals of clauses that currently watch the literal
531     // that falsifies `Var`.
532     const Literal FalseLit = VarAssignments[Var] == Assignment::AssignedTrue
533                                  ? negLit(Var)
534                                  : posLit(Var);
535     ClauseID FalseLitWatcher = Formula.WatchedHead[FalseLit];
536     Formula.WatchedHead[FalseLit] = NullClause;
537     while (FalseLitWatcher != NullClause) {
538       const ClauseID NextFalseLitWatcher = Formula.NextWatched[FalseLitWatcher];
539 
540       // Pick the first non-false literal as the new watched literal.
541       const size_t FalseLitWatcherStart = Formula.ClauseStarts[FalseLitWatcher];
542       size_t NewWatchedLitIdx = FalseLitWatcherStart + 1;
543       while (isCurrentlyFalse(Formula.Clauses[NewWatchedLitIdx]))
544         ++NewWatchedLitIdx;
545       const Literal NewWatchedLit = Formula.Clauses[NewWatchedLitIdx];
546       const Variable NewWatchedLitVar = var(NewWatchedLit);
547 
548       // Swap the old watched literal for the new one in `FalseLitWatcher` to
549       // maintain the invariant that the watched literal is at the beginning of
550       // the clause.
551       Formula.Clauses[NewWatchedLitIdx] = FalseLit;
552       Formula.Clauses[FalseLitWatcherStart] = NewWatchedLit;
553 
554       // If the new watched literal isn't watched by any other clause and its
555       // variable isn't assigned we need to add it to the active variables.
556       if (!isWatched(NewWatchedLit) && !isWatched(notLit(NewWatchedLit)) &&
557           VarAssignments[NewWatchedLitVar] == Assignment::Unassigned)
558         ActiveVars.push_back(NewWatchedLitVar);
559 
560       Formula.NextWatched[FalseLitWatcher] = Formula.WatchedHead[NewWatchedLit];
561       Formula.WatchedHead[NewWatchedLit] = FalseLitWatcher;
562 
563       // Go to the next clause that watches `FalseLit`.
564       FalseLitWatcher = NextFalseLitWatcher;
565     }
566   }
567 
568   /// Returns true if and only if one of the clauses that watch `Lit` is a unit
569   /// clause.
570   bool watchedByUnitClause(Literal Lit) const {
571     for (ClauseID LitWatcher = Formula.WatchedHead[Lit];
572          LitWatcher != NullClause;
573          LitWatcher = Formula.NextWatched[LitWatcher]) {
574       llvm::ArrayRef<Literal> Clause = Formula.clauseLiterals(LitWatcher);
575 
576       // Assert the invariant that the watched literal is always the first one
577       // in the clause.
578       // FIXME: Consider replacing this with a test case that fails if the
579       // invariant is broken by `updateWatchedLiterals`. That might not be easy
580       // due to the transformations performed by `buildBooleanFormula`.
581       assert(Clause.front() == Lit);
582 
583       if (isUnit(Clause))
584         return true;
585     }
586     return false;
587   }
588 
589   /// Returns true if and only if `Clause` is a unit clause.
590   bool isUnit(llvm::ArrayRef<Literal> Clause) const {
591     return llvm::all_of(Clause.drop_front(),
592                         [this](Literal L) { return isCurrentlyFalse(L); });
593   }
594 
595   /// Returns true if and only if `Lit` evaluates to `false` in the current
596   /// partial assignment.
597   bool isCurrentlyFalse(Literal Lit) const {
598     return static_cast<int8_t>(VarAssignments[var(Lit)]) ==
599            static_cast<int8_t>(Lit & 1);
600   }
601 
602   /// Returns true if and only if `Lit` is watched by a clause in `Formula`.
603   bool isWatched(Literal Lit) const {
604     return Formula.WatchedHead[Lit] != NullClause;
605   }
606 
607   /// Returns an assignment for an unassigned variable.
608   Assignment decideAssignment(Variable Var) const {
609     return !isWatched(posLit(Var)) || isWatched(negLit(Var))
610                ? Assignment::AssignedFalse
611                : Assignment::AssignedTrue;
612   }
613 
614   /// Returns a set of all watched literals.
615   llvm::DenseSet<Literal> watchedLiterals() const {
616     llvm::DenseSet<Literal> WatchedLiterals;
617     for (Literal Lit = 2; Lit < Formula.WatchedHead.size(); Lit++) {
618       if (Formula.WatchedHead[Lit] == NullClause)
619         continue;
620       WatchedLiterals.insert(Lit);
621     }
622     return WatchedLiterals;
623   }
624 
625   /// Returns true if and only if all active variables are unassigned.
626   bool activeVarsAreUnassigned() const {
627     return llvm::all_of(ActiveVars, [this](Variable Var) {
628       return VarAssignments[Var] == Assignment::Unassigned;
629     });
630   }
631 
632   /// Returns true if and only if all active variables form watched literals.
633   bool activeVarsFormWatchedLiterals() const {
634     const llvm::DenseSet<Literal> WatchedLiterals = watchedLiterals();
635     return llvm::all_of(ActiveVars, [&WatchedLiterals](Variable Var) {
636       return WatchedLiterals.contains(posLit(Var)) ||
637              WatchedLiterals.contains(negLit(Var));
638     });
639   }
640 
641   /// Returns true if and only if all unassigned variables that are forming
642   /// watched literals are active.
643   bool unassignedVarsFormingWatchedLiteralsAreActive() const {
644     const llvm::DenseSet<Variable> ActiveVarsSet(ActiveVars.begin(),
645                                                  ActiveVars.end());
646     for (Literal Lit : watchedLiterals()) {
647       const Variable Var = var(Lit);
648       if (VarAssignments[Var] != Assignment::Unassigned)
649         continue;
650       if (ActiveVarsSet.contains(Var))
651         continue;
652       return false;
653     }
654     return true;
655   }
656 };
657 
658 Solver::Result WatchedLiteralsSolver::solve(llvm::DenseSet<BoolValue *> Vals) {
659   return Vals.empty() ? Solver::Result::Satisfiable({{}})
660                       : WatchedLiteralsSolverImpl(Vals).solve();
661 }
662 
663 } // namespace dataflow
664 } // namespace clang
665