1 //===- Simplex.cpp - MLIR Simplex Class -----------------------------------===//
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 #include "mlir/Analysis/Presburger/Simplex.h"
10 #include "mlir/Analysis/Presburger/Matrix.h"
11 #include "mlir/Support/MathExtras.h"
12 #include "llvm/ADT/Optional.h"
13 
14 using namespace mlir;
15 using namespace presburger;
16 
17 using Direction = Simplex::Direction;
18 
19 const int nullIndex = std::numeric_limits<int>::max();
20 
21 SimplexBase::SimplexBase(unsigned nVar, bool mustUseBigM)
22     : usingBigM(mustUseBigM), nRow(0), nCol(getNumFixedCols() + nVar),
23       nRedundant(0), tableau(0, nCol), empty(false) {
24   colUnknown.insert(colUnknown.begin(), getNumFixedCols(), nullIndex);
25   for (unsigned i = 0; i < nVar; ++i) {
26     var.emplace_back(Orientation::Column, /*restricted=*/false,
27                      /*pos=*/getNumFixedCols() + i);
28     colUnknown.push_back(i);
29   }
30 }
31 
32 const Simplex::Unknown &SimplexBase::unknownFromIndex(int index) const {
33   assert(index != nullIndex && "nullIndex passed to unknownFromIndex");
34   return index >= 0 ? var[index] : con[~index];
35 }
36 
37 const Simplex::Unknown &SimplexBase::unknownFromColumn(unsigned col) const {
38   assert(col < nCol && "Invalid column");
39   return unknownFromIndex(colUnknown[col]);
40 }
41 
42 const Simplex::Unknown &SimplexBase::unknownFromRow(unsigned row) const {
43   assert(row < nRow && "Invalid row");
44   return unknownFromIndex(rowUnknown[row]);
45 }
46 
47 Simplex::Unknown &SimplexBase::unknownFromIndex(int index) {
48   assert(index != nullIndex && "nullIndex passed to unknownFromIndex");
49   return index >= 0 ? var[index] : con[~index];
50 }
51 
52 Simplex::Unknown &SimplexBase::unknownFromColumn(unsigned col) {
53   assert(col < nCol && "Invalid column");
54   return unknownFromIndex(colUnknown[col]);
55 }
56 
57 Simplex::Unknown &SimplexBase::unknownFromRow(unsigned row) {
58   assert(row < nRow && "Invalid row");
59   return unknownFromIndex(rowUnknown[row]);
60 }
61 
62 unsigned SimplexBase::addZeroRow(bool makeRestricted) {
63   ++nRow;
64   // If the tableau is not big enough to accomodate the extra row, we extend it.
65   if (nRow >= tableau.getNumRows())
66     tableau.resizeVertically(nRow);
67   rowUnknown.push_back(~con.size());
68   con.emplace_back(Orientation::Row, makeRestricted, nRow - 1);
69   undoLog.push_back(UndoLogEntry::RemoveLastConstraint);
70 
71   // Zero out the new row.
72   tableau.fillRow(nRow - 1, 0);
73 
74   tableau(nRow - 1, 0) = 1;
75   return con.size() - 1;
76 }
77 
78 /// Add a new row to the tableau corresponding to the given constant term and
79 /// list of coefficients. The coefficients are specified as a vector of
80 /// (variable index, coefficient) pairs.
81 unsigned SimplexBase::addRow(ArrayRef<int64_t> coeffs, bool makeRestricted) {
82   assert(coeffs.size() == var.size() + 1 &&
83          "Incorrect number of coefficients!");
84 
85   addZeroRow(makeRestricted);
86   tableau(nRow - 1, 1) = coeffs.back();
87   if (usingBigM) {
88     // When the lexicographic pivot rule is used, instead of the variables
89     //
90     // x, y, z ...
91     //
92     // we internally use the variables
93     //
94     // M, M + x, M + y, M + z, ...
95     //
96     // where M is the big M parameter. As such, when the user tries to add
97     // a row ax + by + cz + d, we express it in terms of our internal variables
98     // as -(a + b + c)M + a(M + x) + b(M + y) + c(M + z) + d.
99     int64_t bigMCoeff = 0;
100     for (unsigned i = 0; i < coeffs.size() - 1; ++i)
101       bigMCoeff -= coeffs[i];
102     // The coefficient to the big M parameter is stored in column 2.
103     tableau(nRow - 1, 2) = bigMCoeff;
104   }
105 
106   // Process each given variable coefficient.
107   for (unsigned i = 0; i < var.size(); ++i) {
108     unsigned pos = var[i].pos;
109     if (coeffs[i] == 0)
110       continue;
111 
112     if (var[i].orientation == Orientation::Column) {
113       // If a variable is in column position at column col, then we just add the
114       // coefficient for that variable (scaled by the common row denominator) to
115       // the corresponding entry in the new row.
116       tableau(nRow - 1, pos) += coeffs[i] * tableau(nRow - 1, 0);
117       continue;
118     }
119 
120     // If the variable is in row position, we need to add that row to the new
121     // row, scaled by the coefficient for the variable, accounting for the two
122     // rows potentially having different denominators. The new denominator is
123     // the lcm of the two.
124     int64_t lcm = mlir::lcm(tableau(nRow - 1, 0), tableau(pos, 0));
125     int64_t nRowCoeff = lcm / tableau(nRow - 1, 0);
126     int64_t idxRowCoeff = coeffs[i] * (lcm / tableau(pos, 0));
127     tableau(nRow - 1, 0) = lcm;
128     for (unsigned col = 1; col < nCol; ++col)
129       tableau(nRow - 1, col) =
130           nRowCoeff * tableau(nRow - 1, col) + idxRowCoeff * tableau(pos, col);
131   }
132 
133   normalizeRow(nRow - 1);
134   // Push to undo log along with the index of the new constraint.
135   return con.size() - 1;
136 }
137 
138 /// Normalize the row by removing factors that are common between the
139 /// denominator and all the numerator coefficients.
140 void SimplexBase::normalizeRow(unsigned row) {
141   int64_t gcd = 0;
142   for (unsigned col = 0; col < nCol; ++col) {
143     gcd = llvm::greatestCommonDivisor(gcd, std::abs(tableau(row, col)));
144     // If the gcd becomes 1 then the row is already normalized.
145     if (gcd == 1)
146       return;
147   }
148 
149   // Note that the gcd can never become zero since the first element of the row,
150   // the denominator, is non-zero.
151   assert(gcd != 0);
152   for (unsigned col = 0; col < nCol; ++col)
153     tableau(row, col) /= gcd;
154 }
155 
156 namespace {
157 bool signMatchesDirection(int64_t elem, Direction direction) {
158   assert(elem != 0 && "elem should not be 0");
159   return direction == Direction::Up ? elem > 0 : elem < 0;
160 }
161 
162 Direction flippedDirection(Direction direction) {
163   return direction == Direction::Up ? Direction::Down : Simplex::Direction::Up;
164 }
165 } // namespace
166 
167 MaybeOptimum<SmallVector<Fraction, 8>> LexSimplex::findRationalLexMin() {
168   restoreRationalConsistency();
169   return getRationalSample();
170 }
171 
172 LogicalResult LexSimplexBase::addCut(unsigned row) {
173   int64_t denom = tableau(row, 0);
174   addZeroRow(/*makeRestricted=*/true);
175   tableau(nRow - 1, 0) = denom;
176   tableau(nRow - 1, 1) = -mod(-tableau(row, 1), denom);
177   tableau(nRow - 1, 2) = 0; // M has all factors in it.
178   for (unsigned col = 3; col < nCol; ++col)
179     tableau(nRow - 1, col) = mod(tableau(row, col), denom);
180   return moveRowUnknownToColumn(nRow - 1);
181 }
182 
183 Optional<unsigned> LexSimplex::maybeGetNonIntegralVarRow() const {
184   for (const Unknown &u : var) {
185     if (u.orientation == Orientation::Column)
186       continue;
187     // If the sample value is of the form (a/d)M + b/d, we need b to be
188     // divisible by d. We assume M is very large and contains all possible
189     // factors and is divisible by everything.
190     unsigned row = u.pos;
191     if (tableau(row, 1) % tableau(row, 0) != 0)
192       return row;
193   }
194   return {};
195 }
196 
197 MaybeOptimum<SmallVector<int64_t, 8>> LexSimplex::findIntegerLexMin() {
198   while (!empty) {
199     restoreRationalConsistency();
200     if (empty)
201       return OptimumKind::Empty;
202 
203     if (Optional<unsigned> maybeRow = maybeGetNonIntegralVarRow()) {
204       // Failure occurs when the polytope is integer empty.
205       if (failed(addCut(*maybeRow)))
206         return OptimumKind::Empty;
207       continue;
208     }
209 
210     MaybeOptimum<SmallVector<Fraction, 8>> sample = getRationalSample();
211     assert(!sample.isEmpty() && "If we reached here the sample should exist!");
212     if (sample.isUnbounded())
213       return OptimumKind::Unbounded;
214     return llvm::to_vector<8>(
215         llvm::map_range(*sample, std::mem_fn(&Fraction::getAsInteger)));
216   }
217 
218   // Polytope is integer empty.
219   return OptimumKind::Empty;
220 }
221 
222 bool LexSimplex::isSeparateInequality(ArrayRef<int64_t> coeffs) {
223   SimplexRollbackScopeExit scopeExit(*this);
224   addInequality(coeffs);
225   return findIntegerLexMin().isEmpty();
226 }
227 
228 bool LexSimplex::isRedundantInequality(ArrayRef<int64_t> coeffs) {
229   return isSeparateInequality(getComplementIneq(coeffs));
230 }
231 bool LexSimplex::rowIsViolated(unsigned row) const {
232   if (tableau(row, 2) < 0)
233     return true;
234   if (tableau(row, 2) == 0 && tableau(row, 1) < 0)
235     return true;
236   return false;
237 }
238 
239 Optional<unsigned> LexSimplex::maybeGetViolatedRow() const {
240   for (unsigned row = 0; row < nRow; ++row)
241     if (rowIsViolated(row))
242       return row;
243   return {};
244 }
245 
246 // We simply look for violated rows and keep trying to move them to column
247 // orientation, which always succeeds unless the constraints have no solution
248 // in which case we just give up and return.
249 void LexSimplex::restoreRationalConsistency() {
250   while (Optional<unsigned> maybeViolatedRow = maybeGetViolatedRow()) {
251     LogicalResult status = moveRowUnknownToColumn(*maybeViolatedRow);
252     if (failed(status))
253       return;
254   }
255 }
256 
257 // Move the row unknown to column orientation while preserving lexicopositivity
258 // of the basis transform.
259 //
260 // We only consider pivots where the pivot element is positive. Suppose no such
261 // pivot exists, i.e., some violated row has no positive coefficient for any
262 // basis unknown. The row can be represented as (s + c_1*u_1 + ... + c_n*u_n)/d,
263 // where d is the denominator, s is the sample value and the c_i are the basis
264 // coefficients. Since any feasible assignment of the basis satisfies u_i >= 0
265 // for all i, and we have s < 0 as well as c_i < 0 for all i, any feasible
266 // assignment would violate this row and therefore the constraints have no
267 // solution.
268 //
269 // We can preserve lexicopositivity by picking the pivot column with positive
270 // pivot element that makes the lexicographically smallest change to the sample
271 // point.
272 //
273 // Proof. Let
274 // x = (x_1, ... x_n) be the variables,
275 // z = (z_1, ... z_m) be the constraints,
276 // y = (y_1, ... y_n) be the current basis, and
277 // define w = (x_1, ... x_n, z_1, ... z_m) = B*y + s.
278 // B is basically the simplex tableau of our implementation except that instead
279 // of only describing the transform to get back the non-basis unknowns, it
280 // defines the values of all the unknowns in terms of the basis unknowns.
281 // Similarly, s is the column for the sample value.
282 //
283 // Our goal is to show that each column in B, restricted to the first n
284 // rows, is lexicopositive after the pivot if it is so before. This is
285 // equivalent to saying the columns in the whole matrix are lexicopositive;
286 // there must be some non-zero element in every column in the first n rows since
287 // the n variables cannot be spanned without using all the n basis unknowns.
288 //
289 // Consider a pivot where z_i replaces y_j in the basis. Recall the pivot
290 // transform for the tableau derived for SimplexBase::pivot:
291 //
292 //            pivot col    other col                   pivot col    other col
293 // pivot row     a             b       ->   pivot row     1/a         -b/a
294 // other row     c             d            other row     c/a        d - bc/a
295 //
296 // Similarly, a pivot results in B changing to B' and c to c'; the difference
297 // between the tableau and these matrices B and B' is that there is no special
298 // case for the pivot row, since it continues to represent the same unknown. The
299 // same formula applies for all rows:
300 //
301 // B'.col(j) = B.col(j) / B(i,j)
302 // B'.col(k) = B.col(k) - B(i,k) * B.col(j) / B(i,j) for k != j
303 // and similarly, s' = s - s_i * B.col(j) / B(i,j).
304 //
305 // Since the row is violated, we have s_i < 0, so the change in sample value
306 // when pivoting with column a is lexicographically smaller than that when
307 // pivoting with column b iff B.col(a) / B(i, a) is lexicographically smaller
308 // than B.col(b) / B(i, b).
309 //
310 // Since B(i, j) > 0, column j remains lexicopositive.
311 //
312 // For the other columns, suppose C.col(k) is not lexicopositive.
313 // This means that for some p, for all t < p,
314 // C(t,k) = 0 => B(t,k) = B(t,j) * B(i,k) / B(i,j) and
315 // C(t,k) < 0 => B(p,k) < B(t,j) * B(i,k) / B(i,j),
316 // which is in contradiction to the fact that B.col(j) / B(i,j) must be
317 // lexicographically smaller than B.col(k) / B(i,k), since it lexicographically
318 // minimizes the change in sample value.
319 LogicalResult LexSimplexBase::moveRowUnknownToColumn(unsigned row) {
320   Optional<unsigned> maybeColumn;
321   for (unsigned col = 3; col < nCol; ++col) {
322     if (tableau(row, col) <= 0)
323       continue;
324     maybeColumn =
325         !maybeColumn ? col : getLexMinPivotColumn(row, *maybeColumn, col);
326   }
327 
328   if (!maybeColumn) {
329     markEmpty();
330     return failure();
331   }
332 
333   pivot(row, *maybeColumn);
334   return success();
335 }
336 
337 unsigned LexSimplexBase::getLexMinPivotColumn(unsigned row, unsigned colA,
338                                               unsigned colB) const {
339   // A pivot causes the following change. (in the diagram the matrix elements
340   // are shown as rationals and there is no common denominator used)
341   //
342   //            pivot col    big M col      const col
343   // pivot row     a            p               b
344   // other row     c            q               d
345   //                        |
346   //                        v
347   //
348   //            pivot col    big M col      const col
349   // pivot row     1/a         -p/a           -b/a
350   // other row     c/a        q - pc/a       d - bc/a
351   //
352   // Let the sample value of the pivot row be s = pM + b before the pivot. Since
353   // the pivot row represents a violated constraint we know that s < 0.
354   //
355   // If the variable is a non-pivot column, its sample value is zero before and
356   // after the pivot.
357   //
358   // If the variable is the pivot column, then its sample value goes from 0 to
359   // (-p/a)M + (-b/a), i.e. 0 to -(pM + b)/a. Thus the change in the sample
360   // value is -s/a.
361   //
362   // If the variable is the pivot row, it sampel value goes from s to 0, for a
363   // change of -s.
364   //
365   // If the variable is a non-pivot row, its sample value changes from
366   // qM + d to qM + d + (-pc/a)M + (-bc/a). Thus the change in sample value
367   // is -(pM + b)(c/a) = -sc/a.
368   //
369   // Thus the change in sample value is either 0, -s/a, -s, or -sc/a. Here -s is
370   // fixed for all calls to this function since the row and tableau are fixed.
371   // The callee just wants to compare the return values with the return value of
372   // other invocations of the same function. So the -s is common for all
373   // comparisons involved and can be ignored, since -s is strictly positive.
374   //
375   // Thus we take away this common factor and just return 0, 1/a, 1, or c/a as
376   // appropriate. This allows us to run the entire algorithm without ever having
377   // to fix a value of M.
378   auto getSampleChangeCoeffForVar = [this, row](unsigned col,
379                                                 const Unknown &u) -> Fraction {
380     int64_t a = tableau(row, col);
381     if (u.orientation == Orientation::Column) {
382       // Pivot column case.
383       if (u.pos == col)
384         return {1, a};
385 
386       // Non-pivot column case.
387       return {0, 1};
388     }
389 
390     // Pivot row case.
391     if (u.pos == row)
392       return {1, 1};
393 
394     // Non-pivot row case.
395     int64_t c = tableau(u.pos, col);
396     return {c, a};
397   };
398 
399   for (const Unknown &u : var) {
400     Fraction changeA = getSampleChangeCoeffForVar(colA, u);
401     Fraction changeB = getSampleChangeCoeffForVar(colB, u);
402     if (changeA < changeB)
403       return colA;
404     if (changeA > changeB)
405       return colB;
406   }
407 
408   // If we reached here, both result in exactly the same changes, so it
409   // doesn't matter which we return.
410   return colA;
411 }
412 
413 /// Find a pivot to change the sample value of the row in the specified
414 /// direction. The returned pivot row will involve `row` if and only if the
415 /// unknown is unbounded in the specified direction.
416 ///
417 /// To increase (resp. decrease) the value of a row, we need to find a live
418 /// column with a non-zero coefficient. If the coefficient is positive, we need
419 /// to increase (decrease) the value of the column, and if the coefficient is
420 /// negative, we need to decrease (increase) the value of the column. Also,
421 /// we cannot decrease the sample value of restricted columns.
422 ///
423 /// If multiple columns are valid, we break ties by considering a lexicographic
424 /// ordering where we prefer unknowns with lower index.
425 Optional<SimplexBase::Pivot> Simplex::findPivot(int row,
426                                                 Direction direction) const {
427   Optional<unsigned> col;
428   for (unsigned j = 2; j < nCol; ++j) {
429     int64_t elem = tableau(row, j);
430     if (elem == 0)
431       continue;
432 
433     if (unknownFromColumn(j).restricted &&
434         !signMatchesDirection(elem, direction))
435       continue;
436     if (!col || colUnknown[j] < colUnknown[*col])
437       col = j;
438   }
439 
440   if (!col)
441     return {};
442 
443   Direction newDirection =
444       tableau(row, *col) < 0 ? flippedDirection(direction) : direction;
445   Optional<unsigned> maybePivotRow = findPivotRow(row, newDirection, *col);
446   return Pivot{maybePivotRow.getValueOr(row), *col};
447 }
448 
449 /// Swap the associated unknowns for the row and the column.
450 ///
451 /// First we swap the index associated with the row and column. Then we update
452 /// the unknowns to reflect their new position and orientation.
453 void SimplexBase::swapRowWithCol(unsigned row, unsigned col) {
454   std::swap(rowUnknown[row], colUnknown[col]);
455   Unknown &uCol = unknownFromColumn(col);
456   Unknown &uRow = unknownFromRow(row);
457   uCol.orientation = Orientation::Column;
458   uRow.orientation = Orientation::Row;
459   uCol.pos = col;
460   uRow.pos = row;
461 }
462 
463 void SimplexBase::pivot(Pivot pair) { pivot(pair.row, pair.column); }
464 
465 /// Pivot pivotRow and pivotCol.
466 ///
467 /// Let R be the pivot row unknown and let C be the pivot col unknown.
468 /// Since initially R = a*C + sum b_i * X_i
469 /// (where the sum is over the other column's unknowns, x_i)
470 /// C = (R - (sum b_i * X_i))/a
471 ///
472 /// Let u be some other row unknown.
473 /// u = c*C + sum d_i * X_i
474 /// So u = c*(R - sum b_i * X_i)/a + sum d_i * X_i
475 ///
476 /// This results in the following transform:
477 ///            pivot col    other col                   pivot col    other col
478 /// pivot row     a             b       ->   pivot row     1/a         -b/a
479 /// other row     c             d            other row     c/a        d - bc/a
480 ///
481 /// Taking into account the common denominators p and q:
482 ///
483 ///            pivot col    other col                    pivot col   other col
484 /// pivot row     a/p          b/p     ->   pivot row      p/a         -b/a
485 /// other row     c/q          d/q          other row     cp/aq    (da - bc)/aq
486 ///
487 /// The pivot row transform is accomplished be swapping a with the pivot row's
488 /// common denominator and negating the pivot row except for the pivot column
489 /// element.
490 void SimplexBase::pivot(unsigned pivotRow, unsigned pivotCol) {
491   assert(pivotCol >= getNumFixedCols() && "Refusing to pivot invalid column");
492 
493   swapRowWithCol(pivotRow, pivotCol);
494   std::swap(tableau(pivotRow, 0), tableau(pivotRow, pivotCol));
495   // We need to negate the whole pivot row except for the pivot column.
496   if (tableau(pivotRow, 0) < 0) {
497     // If the denominator is negative, we negate the row by simply negating the
498     // denominator.
499     tableau(pivotRow, 0) = -tableau(pivotRow, 0);
500     tableau(pivotRow, pivotCol) = -tableau(pivotRow, pivotCol);
501   } else {
502     for (unsigned col = 1; col < nCol; ++col) {
503       if (col == pivotCol)
504         continue;
505       tableau(pivotRow, col) = -tableau(pivotRow, col);
506     }
507   }
508   normalizeRow(pivotRow);
509 
510   for (unsigned row = 0; row < nRow; ++row) {
511     if (row == pivotRow)
512       continue;
513     if (tableau(row, pivotCol) == 0) // Nothing to do.
514       continue;
515     tableau(row, 0) *= tableau(pivotRow, 0);
516     for (unsigned j = 1; j < nCol; ++j) {
517       if (j == pivotCol)
518         continue;
519       // Add rather than subtract because the pivot row has been negated.
520       tableau(row, j) = tableau(row, j) * tableau(pivotRow, 0) +
521                         tableau(row, pivotCol) * tableau(pivotRow, j);
522     }
523     tableau(row, pivotCol) *= tableau(pivotRow, pivotCol);
524     normalizeRow(row);
525   }
526 }
527 
528 /// Perform pivots until the unknown has a non-negative sample value or until
529 /// no more upward pivots can be performed. Return success if we were able to
530 /// bring the row to a non-negative sample value, and failure otherwise.
531 LogicalResult Simplex::restoreRow(Unknown &u) {
532   assert(u.orientation == Orientation::Row &&
533          "unknown should be in row position");
534 
535   while (tableau(u.pos, 1) < 0) {
536     Optional<Pivot> maybePivot = findPivot(u.pos, Direction::Up);
537     if (!maybePivot)
538       break;
539 
540     pivot(*maybePivot);
541     if (u.orientation == Orientation::Column)
542       return success(); // the unknown is unbounded above.
543   }
544   return success(tableau(u.pos, 1) >= 0);
545 }
546 
547 /// Find a row that can be used to pivot the column in the specified direction.
548 /// This returns an empty optional if and only if the column is unbounded in the
549 /// specified direction (ignoring skipRow, if skipRow is set).
550 ///
551 /// If skipRow is set, this row is not considered, and (if it is restricted) its
552 /// restriction may be violated by the returned pivot. Usually, skipRow is set
553 /// because we don't want to move it to column position unless it is unbounded,
554 /// and we are either trying to increase the value of skipRow or explicitly
555 /// trying to make skipRow negative, so we are not concerned about this.
556 ///
557 /// If the direction is up (resp. down) and a restricted row has a negative
558 /// (positive) coefficient for the column, then this row imposes a bound on how
559 /// much the sample value of the column can change. Such a row with constant
560 /// term c and coefficient f for the column imposes a bound of c/|f| on the
561 /// change in sample value (in the specified direction). (note that c is
562 /// non-negative here since the row is restricted and the tableau is consistent)
563 ///
564 /// We iterate through the rows and pick the row which imposes the most
565 /// stringent bound, since pivoting with a row changes the row's sample value to
566 /// 0 and hence saturates the bound it imposes. We break ties between rows that
567 /// impose the same bound by considering a lexicographic ordering where we
568 /// prefer unknowns with lower index value.
569 Optional<unsigned> Simplex::findPivotRow(Optional<unsigned> skipRow,
570                                          Direction direction,
571                                          unsigned col) const {
572   Optional<unsigned> retRow;
573   // Initialize these to zero in order to silence a warning about retElem and
574   // retConst being used uninitialized in the initialization of `diff` below. In
575   // reality, these are always initialized when that line is reached since these
576   // are set whenever retRow is set.
577   int64_t retElem = 0, retConst = 0;
578   for (unsigned row = nRedundant; row < nRow; ++row) {
579     if (skipRow && row == *skipRow)
580       continue;
581     int64_t elem = tableau(row, col);
582     if (elem == 0)
583       continue;
584     if (!unknownFromRow(row).restricted)
585       continue;
586     if (signMatchesDirection(elem, direction))
587       continue;
588     int64_t constTerm = tableau(row, 1);
589 
590     if (!retRow) {
591       retRow = row;
592       retElem = elem;
593       retConst = constTerm;
594       continue;
595     }
596 
597     int64_t diff = retConst * elem - constTerm * retElem;
598     if ((diff == 0 && rowUnknown[row] < rowUnknown[*retRow]) ||
599         (diff != 0 && !signMatchesDirection(diff, direction))) {
600       retRow = row;
601       retElem = elem;
602       retConst = constTerm;
603     }
604   }
605   return retRow;
606 }
607 
608 bool SimplexBase::isEmpty() const { return empty; }
609 
610 void SimplexBase::swapRows(unsigned i, unsigned j) {
611   if (i == j)
612     return;
613   tableau.swapRows(i, j);
614   std::swap(rowUnknown[i], rowUnknown[j]);
615   unknownFromRow(i).pos = i;
616   unknownFromRow(j).pos = j;
617 }
618 
619 void SimplexBase::swapColumns(unsigned i, unsigned j) {
620   assert(i < nCol && j < nCol && "Invalid columns provided!");
621   if (i == j)
622     return;
623   tableau.swapColumns(i, j);
624   std::swap(colUnknown[i], colUnknown[j]);
625   unknownFromColumn(i).pos = i;
626   unknownFromColumn(j).pos = j;
627 }
628 
629 /// Mark this tableau empty and push an entry to the undo stack.
630 void SimplexBase::markEmpty() {
631   // If the set is already empty, then we shouldn't add another UnmarkEmpty log
632   // entry, since in that case the Simplex will be erroneously marked as
633   // non-empty when rolling back past this point.
634   if (empty)
635     return;
636   undoLog.push_back(UndoLogEntry::UnmarkEmpty);
637   empty = true;
638 }
639 
640 /// Add an inequality to the tableau. If coeffs is c_0, c_1, ... c_n, where n
641 /// is the current number of variables, then the corresponding inequality is
642 /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} >= 0.
643 ///
644 /// We add the inequality and mark it as restricted. We then try to make its
645 /// sample value non-negative. If this is not possible, the tableau has become
646 /// empty and we mark it as such.
647 void Simplex::addInequality(ArrayRef<int64_t> coeffs) {
648   unsigned conIndex = addRow(coeffs, /*makeRestricted=*/true);
649   LogicalResult result = restoreRow(con[conIndex]);
650   if (failed(result))
651     markEmpty();
652 }
653 
654 /// Add an equality to the tableau. If coeffs is c_0, c_1, ... c_n, where n
655 /// is the current number of variables, then the corresponding equality is
656 /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} == 0.
657 ///
658 /// We simply add two opposing inequalities, which force the expression to
659 /// be zero.
660 void SimplexBase::addEquality(ArrayRef<int64_t> coeffs) {
661   addInequality(coeffs);
662   SmallVector<int64_t, 8> negatedCoeffs;
663   for (int64_t coeff : coeffs)
664     negatedCoeffs.emplace_back(-coeff);
665   addInequality(negatedCoeffs);
666 }
667 
668 unsigned SimplexBase::getNumVariables() const { return var.size(); }
669 unsigned SimplexBase::getNumConstraints() const { return con.size(); }
670 
671 /// Return a snapshot of the current state. This is just the current size of the
672 /// undo log.
673 unsigned SimplexBase::getSnapshot() const { return undoLog.size(); }
674 
675 unsigned SimplexBase::getSnapshotBasis() {
676   SmallVector<int, 8> basis;
677   for (int index : colUnknown) {
678     if (index != nullIndex)
679       basis.push_back(index);
680   }
681   savedBases.push_back(std::move(basis));
682 
683   undoLog.emplace_back(UndoLogEntry::RestoreBasis);
684   return undoLog.size() - 1;
685 }
686 
687 void SimplexBase::removeLastConstraintRowOrientation() {
688   assert(con.back().orientation == Orientation::Row);
689 
690   // Move this unknown to the last row and remove the last row from the
691   // tableau.
692   swapRows(con.back().pos, nRow - 1);
693   // It is not strictly necessary to shrink the tableau, but for now we
694   // maintain the invariant that the tableau has exactly nRow rows.
695   tableau.resizeVertically(nRow - 1);
696   nRow--;
697   rowUnknown.pop_back();
698   con.pop_back();
699 }
700 
701 // This doesn't find a pivot row only if the column has zero
702 // coefficients for every row.
703 //
704 // If the unknown is a constraint, this can't happen, since it was added
705 // initially as a row. Such a row could never have been pivoted to a column. So
706 // a pivot row will always be found if we have a constraint.
707 //
708 // If we have a variable, then the column has zero coefficients for every row
709 // iff no constraints have been added with a non-zero coefficient for this row.
710 Optional<unsigned> SimplexBase::findAnyPivotRow(unsigned col) {
711   for (unsigned row = nRedundant; row < nRow; ++row)
712     if (tableau(row, col) != 0)
713       return row;
714   return {};
715 }
716 
717 // It's not valid to remove the constraint by deleting the column since this
718 // would result in an invalid basis.
719 void Simplex::undoLastConstraint() {
720   if (con.back().orientation == Orientation::Column) {
721     // We try to find any pivot row for this column that preserves tableau
722     // consistency (except possibly the column itself, which is going to be
723     // deallocated anyway).
724     //
725     // If no pivot row is found in either direction, then the unknown is
726     // unbounded in both directions and we are free to perform any pivot at
727     // all. To do this, we just need to find any row with a non-zero
728     // coefficient for the column. findAnyPivotRow will always be able to
729     // find such a row for a constraint.
730     unsigned column = con.back().pos;
731     if (Optional<unsigned> maybeRow = findPivotRow({}, Direction::Up, column)) {
732       pivot(*maybeRow, column);
733     } else if (Optional<unsigned> maybeRow =
734                    findPivotRow({}, Direction::Down, column)) {
735       pivot(*maybeRow, column);
736     } else {
737       Optional<unsigned> row = findAnyPivotRow(column);
738       assert(row.hasValue() && "Pivot should always exist for a constraint!");
739       pivot(*row, column);
740     }
741   }
742   removeLastConstraintRowOrientation();
743 }
744 
745 // It's not valid to remove the constraint by deleting the column since this
746 // would result in an invalid basis.
747 void LexSimplexBase::undoLastConstraint() {
748   if (con.back().orientation == Orientation::Column) {
749     // When removing the last constraint during a rollback, we just need to find
750     // any pivot at all, i.e., any row with non-zero coefficient for the
751     // column, because when rolling back a lexicographic simplex, we always
752     // end by restoring the exact basis that was present at the time of the
753     // snapshot, so what pivots we perform while undoing doesn't matter as
754     // long as we get the unknown to row orientation and remove it.
755     unsigned column = con.back().pos;
756     Optional<unsigned> row = findAnyPivotRow(column);
757     assert(row.hasValue() && "Pivot should always exist for a constraint!");
758     pivot(*row, column);
759   }
760   removeLastConstraintRowOrientation();
761 }
762 
763 void SimplexBase::undo(UndoLogEntry entry) {
764   if (entry == UndoLogEntry::RemoveLastConstraint) {
765     // Simplex and LexSimplex handle this differently, so we call out to a
766     // virtual function to handle this.
767     undoLastConstraint();
768   } else if (entry == UndoLogEntry::RemoveLastVariable) {
769     // Whenever we are rolling back the addition of a variable, it is guaranteed
770     // that the variable will be in column position.
771     //
772     // We can see this as follows: any constraint that depends on this variable
773     // was added after this variable was added, so the addition of such
774     // constraints should already have been rolled back by the time we get to
775     // rolling back the addition of the variable. Therefore, no constraint
776     // currently has a component along the variable, so the variable itself must
777     // be part of the basis.
778     assert(var.back().orientation == Orientation::Column &&
779            "Variable to be removed must be in column orientation!");
780 
781     // Move this variable to the last column and remove the column from the
782     // tableau.
783     swapColumns(var.back().pos, nCol - 1);
784     tableau.resizeHorizontally(nCol - 1);
785     var.pop_back();
786     colUnknown.pop_back();
787     nCol--;
788   } else if (entry == UndoLogEntry::UnmarkEmpty) {
789     empty = false;
790   } else if (entry == UndoLogEntry::UnmarkLastRedundant) {
791     nRedundant--;
792   } else if (entry == UndoLogEntry::RestoreBasis) {
793     assert(!savedBases.empty() && "No bases saved!");
794 
795     SmallVector<int, 8> basis = std::move(savedBases.back());
796     savedBases.pop_back();
797 
798     for (int index : basis) {
799       Unknown &u = unknownFromIndex(index);
800       if (u.orientation == Orientation::Column)
801         continue;
802       for (unsigned col = getNumFixedCols(); col < nCol; col++) {
803         assert(colUnknown[col] != nullIndex &&
804                "Column should not be a fixed column!");
805         if (std::find(basis.begin(), basis.end(), colUnknown[col]) !=
806             basis.end())
807           continue;
808         if (tableau(u.pos, col) == 0)
809           continue;
810         pivot(u.pos, col);
811         break;
812       }
813 
814       assert(u.orientation == Orientation::Column && "No pivot found!");
815     }
816   }
817 }
818 
819 /// Rollback to the specified snapshot.
820 ///
821 /// We undo all the log entries until the log size when the snapshot was taken
822 /// is reached.
823 void SimplexBase::rollback(unsigned snapshot) {
824   while (undoLog.size() > snapshot) {
825     undo(undoLog.back());
826     undoLog.pop_back();
827   }
828 }
829 
830 /// We add the usual floor division constraints:
831 /// `0 <= coeffs - denom*q <= denom - 1`, where `q` is the new division
832 /// variable.
833 ///
834 /// This constrains the remainder `coeffs - denom*q` to be in the
835 /// range `[0, denom - 1]`, which fixes the integer value of the quotient `q`.
836 void SimplexBase::addDivisionVariable(ArrayRef<int64_t> coeffs, int64_t denom) {
837   assert(denom != 0 && "Cannot divide by zero!\n");
838   appendVariable();
839 
840   SmallVector<int64_t, 8> ineq(coeffs.begin(), coeffs.end());
841   int64_t constTerm = ineq.back();
842   ineq.back() = -denom;
843   ineq.push_back(constTerm);
844   addInequality(ineq);
845 
846   for (int64_t &coeff : ineq)
847     coeff = -coeff;
848   ineq.back() += denom - 1;
849   addInequality(ineq);
850 }
851 
852 void SimplexBase::appendVariable(unsigned count) {
853   if (count == 0)
854     return;
855   var.reserve(var.size() + count);
856   colUnknown.reserve(colUnknown.size() + count);
857   for (unsigned i = 0; i < count; ++i) {
858     nCol++;
859     var.emplace_back(Orientation::Column, /*restricted=*/false,
860                      /*pos=*/nCol - 1);
861     colUnknown.push_back(var.size() - 1);
862   }
863   tableau.resizeHorizontally(nCol);
864   undoLog.insert(undoLog.end(), count, UndoLogEntry::RemoveLastVariable);
865 }
866 
867 /// Add all the constraints from the given IntegerRelation.
868 void SimplexBase::intersectIntegerRelation(const IntegerRelation &rel) {
869   assert(rel.getNumIds() == getNumVariables() &&
870          "IntegerRelation must have same dimensionality as simplex");
871   for (unsigned i = 0, e = rel.getNumInequalities(); i < e; ++i)
872     addInequality(rel.getInequality(i));
873   for (unsigned i = 0, e = rel.getNumEqualities(); i < e; ++i)
874     addEquality(rel.getEquality(i));
875 }
876 
877 MaybeOptimum<Fraction> Simplex::computeRowOptimum(Direction direction,
878                                                   unsigned row) {
879   // Keep trying to find a pivot for the row in the specified direction.
880   while (Optional<Pivot> maybePivot = findPivot(row, direction)) {
881     // If findPivot returns a pivot involving the row itself, then the optimum
882     // is unbounded, so we return None.
883     if (maybePivot->row == row)
884       return OptimumKind::Unbounded;
885     pivot(*maybePivot);
886   }
887 
888   // The row has reached its optimal sample value, which we return.
889   // The sample value is the entry in the constant column divided by the common
890   // denominator for this row.
891   return Fraction(tableau(row, 1), tableau(row, 0));
892 }
893 
894 /// Compute the optimum of the specified expression in the specified direction,
895 /// or None if it is unbounded.
896 MaybeOptimum<Fraction> Simplex::computeOptimum(Direction direction,
897                                                ArrayRef<int64_t> coeffs) {
898   if (empty)
899     return OptimumKind::Empty;
900 
901   SimplexRollbackScopeExit scopeExit(*this);
902   unsigned conIndex = addRow(coeffs);
903   unsigned row = con[conIndex].pos;
904   MaybeOptimum<Fraction> optimum = computeRowOptimum(direction, row);
905   return optimum;
906 }
907 
908 MaybeOptimum<Fraction> Simplex::computeOptimum(Direction direction,
909                                                Unknown &u) {
910   if (empty)
911     return OptimumKind::Empty;
912   if (u.orientation == Orientation::Column) {
913     unsigned column = u.pos;
914     Optional<unsigned> pivotRow = findPivotRow({}, direction, column);
915     // If no pivot is returned, the constraint is unbounded in the specified
916     // direction.
917     if (!pivotRow)
918       return OptimumKind::Unbounded;
919     pivot(*pivotRow, column);
920   }
921 
922   unsigned row = u.pos;
923   MaybeOptimum<Fraction> optimum = computeRowOptimum(direction, row);
924   if (u.restricted && direction == Direction::Down &&
925       (optimum.isUnbounded() || *optimum < Fraction(0, 1))) {
926     if (failed(restoreRow(u)))
927       llvm_unreachable("Could not restore row!");
928   }
929   return optimum;
930 }
931 
932 bool Simplex::isBoundedAlongConstraint(unsigned constraintIndex) {
933   assert(!empty && "It is not meaningful to ask whether a direction is bounded "
934                    "in an empty set.");
935   // The constraint's perpendicular is already bounded below, since it is a
936   // constraint. If it is also bounded above, we can return true.
937   return computeOptimum(Direction::Up, con[constraintIndex]).isBounded();
938 }
939 
940 /// Redundant constraints are those that are in row orientation and lie in
941 /// rows 0 to nRedundant - 1.
942 bool Simplex::isMarkedRedundant(unsigned constraintIndex) const {
943   const Unknown &u = con[constraintIndex];
944   return u.orientation == Orientation::Row && u.pos < nRedundant;
945 }
946 
947 /// Mark the specified row redundant.
948 ///
949 /// This is done by moving the unknown to the end of the block of redundant
950 /// rows (namely, to row nRedundant) and incrementing nRedundant to
951 /// accomodate the new redundant row.
952 void Simplex::markRowRedundant(Unknown &u) {
953   assert(u.orientation == Orientation::Row &&
954          "Unknown should be in row position!");
955   assert(u.pos >= nRedundant && "Unknown is already marked redundant!");
956   swapRows(u.pos, nRedundant);
957   ++nRedundant;
958   undoLog.emplace_back(UndoLogEntry::UnmarkLastRedundant);
959 }
960 
961 /// Find a subset of constraints that is redundant and mark them redundant.
962 void Simplex::detectRedundant() {
963   // It is not meaningful to talk about redundancy for empty sets.
964   if (empty)
965     return;
966 
967   // Iterate through the constraints and check for each one if it can attain
968   // negative sample values. If it can, it's not redundant. Otherwise, it is.
969   // We mark redundant constraints redundant.
970   //
971   // Constraints that get marked redundant in one iteration are not respected
972   // when checking constraints in later iterations. This prevents, for example,
973   // two identical constraints both being marked redundant since each is
974   // redundant given the other one. In this example, only the first of the
975   // constraints that is processed will get marked redundant, as it should be.
976   for (Unknown &u : con) {
977     if (u.orientation == Orientation::Column) {
978       unsigned column = u.pos;
979       Optional<unsigned> pivotRow = findPivotRow({}, Direction::Down, column);
980       // If no downward pivot is returned, the constraint is unbounded below
981       // and hence not redundant.
982       if (!pivotRow)
983         continue;
984       pivot(*pivotRow, column);
985     }
986 
987     unsigned row = u.pos;
988     MaybeOptimum<Fraction> minimum = computeRowOptimum(Direction::Down, row);
989     if (minimum.isUnbounded() || *minimum < Fraction(0, 1)) {
990       // Constraint is unbounded below or can attain negative sample values and
991       // hence is not redundant.
992       if (failed(restoreRow(u)))
993         llvm_unreachable("Could not restore non-redundant row!");
994       continue;
995     }
996 
997     markRowRedundant(u);
998   }
999 }
1000 
1001 bool Simplex::isUnbounded() {
1002   if (empty)
1003     return false;
1004 
1005   SmallVector<int64_t, 8> dir(var.size() + 1);
1006   for (unsigned i = 0; i < var.size(); ++i) {
1007     dir[i] = 1;
1008 
1009     if (computeOptimum(Direction::Up, dir).isUnbounded())
1010       return true;
1011 
1012     if (computeOptimum(Direction::Down, dir).isUnbounded())
1013       return true;
1014 
1015     dir[i] = 0;
1016   }
1017   return false;
1018 }
1019 
1020 /// Make a tableau to represent a pair of points in the original tableau.
1021 ///
1022 /// The product constraints and variables are stored as: first A's, then B's.
1023 ///
1024 /// The product tableau has row layout:
1025 ///   A's redundant rows, B's redundant rows, A's other rows, B's other rows.
1026 ///
1027 /// It has column layout:
1028 ///   denominator, constant, A's columns, B's columns.
1029 Simplex Simplex::makeProduct(const Simplex &a, const Simplex &b) {
1030   unsigned numVar = a.getNumVariables() + b.getNumVariables();
1031   unsigned numCon = a.getNumConstraints() + b.getNumConstraints();
1032   Simplex result(numVar);
1033 
1034   result.tableau.resizeVertically(numCon);
1035   result.empty = a.empty || b.empty;
1036 
1037   auto concat = [](ArrayRef<Unknown> v, ArrayRef<Unknown> w) {
1038     SmallVector<Unknown, 8> result;
1039     result.reserve(v.size() + w.size());
1040     result.insert(result.end(), v.begin(), v.end());
1041     result.insert(result.end(), w.begin(), w.end());
1042     return result;
1043   };
1044   result.con = concat(a.con, b.con);
1045   result.var = concat(a.var, b.var);
1046 
1047   auto indexFromBIndex = [&](int index) {
1048     return index >= 0 ? a.getNumVariables() + index
1049                       : ~(a.getNumConstraints() + ~index);
1050   };
1051 
1052   result.colUnknown.assign(2, nullIndex);
1053   for (unsigned i = 2; i < a.nCol; ++i) {
1054     result.colUnknown.push_back(a.colUnknown[i]);
1055     result.unknownFromIndex(result.colUnknown.back()).pos =
1056         result.colUnknown.size() - 1;
1057   }
1058   for (unsigned i = 2; i < b.nCol; ++i) {
1059     result.colUnknown.push_back(indexFromBIndex(b.colUnknown[i]));
1060     result.unknownFromIndex(result.colUnknown.back()).pos =
1061         result.colUnknown.size() - 1;
1062   }
1063 
1064   auto appendRowFromA = [&](unsigned row) {
1065     for (unsigned col = 0; col < a.nCol; ++col)
1066       result.tableau(result.nRow, col) = a.tableau(row, col);
1067     result.rowUnknown.push_back(a.rowUnknown[row]);
1068     result.unknownFromIndex(result.rowUnknown.back()).pos =
1069         result.rowUnknown.size() - 1;
1070     result.nRow++;
1071   };
1072 
1073   // Also fixes the corresponding entry in rowUnknown and var/con (as the case
1074   // may be).
1075   auto appendRowFromB = [&](unsigned row) {
1076     result.tableau(result.nRow, 0) = b.tableau(row, 0);
1077     result.tableau(result.nRow, 1) = b.tableau(row, 1);
1078 
1079     unsigned offset = a.nCol - 2;
1080     for (unsigned col = 2; col < b.nCol; ++col)
1081       result.tableau(result.nRow, offset + col) = b.tableau(row, col);
1082     result.rowUnknown.push_back(indexFromBIndex(b.rowUnknown[row]));
1083     result.unknownFromIndex(result.rowUnknown.back()).pos =
1084         result.rowUnknown.size() - 1;
1085     result.nRow++;
1086   };
1087 
1088   result.nRedundant = a.nRedundant + b.nRedundant;
1089   for (unsigned row = 0; row < a.nRedundant; ++row)
1090     appendRowFromA(row);
1091   for (unsigned row = 0; row < b.nRedundant; ++row)
1092     appendRowFromB(row);
1093   for (unsigned row = a.nRedundant; row < a.nRow; ++row)
1094     appendRowFromA(row);
1095   for (unsigned row = b.nRedundant; row < b.nRow; ++row)
1096     appendRowFromB(row);
1097 
1098   return result;
1099 }
1100 
1101 Optional<SmallVector<Fraction, 8>> Simplex::getRationalSample() const {
1102   if (empty)
1103     return {};
1104 
1105   SmallVector<Fraction, 8> sample;
1106   sample.reserve(var.size());
1107   // Push the sample value for each variable into the vector.
1108   for (const Unknown &u : var) {
1109     if (u.orientation == Orientation::Column) {
1110       // If the variable is in column position, its sample value is zero.
1111       sample.emplace_back(0, 1);
1112     } else {
1113       // If the variable is in row position, its sample value is the
1114       // entry in the constant column divided by the denominator.
1115       int64_t denom = tableau(u.pos, 0);
1116       sample.emplace_back(tableau(u.pos, 1), denom);
1117     }
1118   }
1119   return sample;
1120 }
1121 
1122 void LexSimplexBase::addInequality(ArrayRef<int64_t> coeffs) {
1123   addRow(coeffs, /*makeRestricted=*/true);
1124 }
1125 
1126 MaybeOptimum<SmallVector<Fraction, 8>> LexSimplex::getRationalSample() const {
1127   if (empty)
1128     return OptimumKind::Empty;
1129 
1130   SmallVector<Fraction, 8> sample;
1131   sample.reserve(var.size());
1132   // Push the sample value for each variable into the vector.
1133   for (const Unknown &u : var) {
1134     // When the big M parameter is being used, each variable x is represented
1135     // as M + x, so its sample value is finite if and only if it is of the
1136     // form 1*M + c. If the coefficient of M is not one then the sample value
1137     // is infinite, and we return an empty optional.
1138 
1139     if (u.orientation == Orientation::Column) {
1140       // If the variable is in column position, the sample value of M + x is
1141       // zero, so x = -M which is unbounded.
1142       return OptimumKind::Unbounded;
1143     }
1144 
1145     // If the variable is in row position, its sample value is the
1146     // entry in the constant column divided by the denominator.
1147     int64_t denom = tableau(u.pos, 0);
1148     if (usingBigM)
1149       if (tableau(u.pos, 2) != denom)
1150         return OptimumKind::Unbounded;
1151     sample.emplace_back(tableau(u.pos, 1), denom);
1152   }
1153   return sample;
1154 }
1155 
1156 Optional<SmallVector<int64_t, 8>> Simplex::getSamplePointIfIntegral() const {
1157   // If the tableau is empty, no sample point exists.
1158   if (empty)
1159     return {};
1160 
1161   // The value will always exist since the Simplex is non-empty.
1162   SmallVector<Fraction, 8> rationalSample = *getRationalSample();
1163   SmallVector<int64_t, 8> integerSample;
1164   integerSample.reserve(var.size());
1165   for (const Fraction &coord : rationalSample) {
1166     // If the sample is non-integral, return None.
1167     if (coord.num % coord.den != 0)
1168       return {};
1169     integerSample.push_back(coord.num / coord.den);
1170   }
1171   return integerSample;
1172 }
1173 
1174 /// Given a simplex for a polytope, construct a new simplex whose variables are
1175 /// identified with a pair of points (x, y) in the original polytope. Supports
1176 /// some operations needed for generalized basis reduction. In what follows,
1177 /// dotProduct(x, y) = x_1 * y_1 + x_2 * y_2 + ... x_n * y_n where n is the
1178 /// dimension of the original polytope.
1179 ///
1180 /// This supports adding equality constraints dotProduct(dir, x - y) == 0. It
1181 /// also supports rolling back this addition, by maintaining a snapshot stack
1182 /// that contains a snapshot of the Simplex's state for each equality, just
1183 /// before that equality was added.
1184 class presburger::GBRSimplex {
1185   using Orientation = Simplex::Orientation;
1186 
1187 public:
1188   GBRSimplex(const Simplex &originalSimplex)
1189       : simplex(Simplex::makeProduct(originalSimplex, originalSimplex)),
1190         simplexConstraintOffset(simplex.getNumConstraints()) {}
1191 
1192   /// Add an equality dotProduct(dir, x - y) == 0.
1193   /// First pushes a snapshot for the current simplex state to the stack so
1194   /// that this can be rolled back later.
1195   void addEqualityForDirection(ArrayRef<int64_t> dir) {
1196     assert(llvm::any_of(dir, [](int64_t x) { return x != 0; }) &&
1197            "Direction passed is the zero vector!");
1198     snapshotStack.push_back(simplex.getSnapshot());
1199     simplex.addEquality(getCoeffsForDirection(dir));
1200   }
1201   /// Compute max(dotProduct(dir, x - y)).
1202   Fraction computeWidth(ArrayRef<int64_t> dir) {
1203     MaybeOptimum<Fraction> maybeWidth =
1204         simplex.computeOptimum(Direction::Up, getCoeffsForDirection(dir));
1205     assert(maybeWidth.isBounded() && "Width should be bounded!");
1206     return *maybeWidth;
1207   }
1208 
1209   /// Compute max(dotProduct(dir, x - y)) and save the dual variables for only
1210   /// the direction equalities to `dual`.
1211   Fraction computeWidthAndDuals(ArrayRef<int64_t> dir,
1212                                 SmallVectorImpl<int64_t> &dual,
1213                                 int64_t &dualDenom) {
1214     // We can't just call into computeWidth or computeOptimum since we need to
1215     // access the state of the tableau after computing the optimum, and these
1216     // functions rollback the insertion of the objective function into the
1217     // tableau before returning. We instead add a row for the objective function
1218     // ourselves, call into computeOptimum, compute the duals from the tableau
1219     // state, and finally rollback the addition of the row before returning.
1220     SimplexRollbackScopeExit scopeExit(simplex);
1221     unsigned conIndex = simplex.addRow(getCoeffsForDirection(dir));
1222     unsigned row = simplex.con[conIndex].pos;
1223     MaybeOptimum<Fraction> maybeWidth =
1224         simplex.computeRowOptimum(Simplex::Direction::Up, row);
1225     assert(maybeWidth.isBounded() && "Width should be bounded!");
1226     dualDenom = simplex.tableau(row, 0);
1227     dual.clear();
1228 
1229     // The increment is i += 2 because equalities are added as two inequalities,
1230     // one positive and one negative. Each iteration processes one equality.
1231     for (unsigned i = simplexConstraintOffset; i < conIndex; i += 2) {
1232       // The dual variable for an inequality in column orientation is the
1233       // negative of its coefficient at the objective row. If the inequality is
1234       // in row orientation, the corresponding dual variable is zero.
1235       //
1236       // We want the dual for the original equality, which corresponds to two
1237       // inequalities: a positive inequality, which has the same coefficients as
1238       // the equality, and a negative equality, which has negated coefficients.
1239       //
1240       // Note that at most one of these inequalities can be in column
1241       // orientation because the column unknowns should form a basis and hence
1242       // must be linearly independent. If the positive inequality is in column
1243       // position, its dual is the dual corresponding to the equality. If the
1244       // negative inequality is in column position, the negation of its dual is
1245       // the dual corresponding to the equality. If neither is in column
1246       // position, then that means that this equality is redundant, and its dual
1247       // is zero.
1248       //
1249       // Note that it is NOT valid to perform pivots during the computation of
1250       // the duals. This entire dual computation must be performed on the same
1251       // tableau configuration.
1252       assert(!(simplex.con[i].orientation == Orientation::Column &&
1253                simplex.con[i + 1].orientation == Orientation::Column) &&
1254              "Both inequalities for the equality cannot be in column "
1255              "orientation!");
1256       if (simplex.con[i].orientation == Orientation::Column)
1257         dual.push_back(-simplex.tableau(row, simplex.con[i].pos));
1258       else if (simplex.con[i + 1].orientation == Orientation::Column)
1259         dual.push_back(simplex.tableau(row, simplex.con[i + 1].pos));
1260       else
1261         dual.push_back(0);
1262     }
1263     return *maybeWidth;
1264   }
1265 
1266   /// Remove the last equality that was added through addEqualityForDirection.
1267   ///
1268   /// We do this by rolling back to the snapshot at the top of the stack, which
1269   /// should be a snapshot taken just before the last equality was added.
1270   void removeLastEquality() {
1271     assert(!snapshotStack.empty() && "Snapshot stack is empty!");
1272     simplex.rollback(snapshotStack.back());
1273     snapshotStack.pop_back();
1274   }
1275 
1276 private:
1277   /// Returns coefficients of the expression 'dot_product(dir, x - y)',
1278   /// i.e.,   dir_1 * x_1 + dir_2 * x_2 + ... + dir_n * x_n
1279   ///       - dir_1 * y_1 - dir_2 * y_2 - ... - dir_n * y_n,
1280   /// where n is the dimension of the original polytope.
1281   SmallVector<int64_t, 8> getCoeffsForDirection(ArrayRef<int64_t> dir) {
1282     assert(2 * dir.size() == simplex.getNumVariables() &&
1283            "Direction vector has wrong dimensionality");
1284     SmallVector<int64_t, 8> coeffs(dir.begin(), dir.end());
1285     coeffs.reserve(2 * dir.size());
1286     for (int64_t coeff : dir)
1287       coeffs.push_back(-coeff);
1288     coeffs.push_back(0); // constant term
1289     return coeffs;
1290   }
1291 
1292   Simplex simplex;
1293   /// The first index of the equality constraints, the index immediately after
1294   /// the last constraint in the initial product simplex.
1295   unsigned simplexConstraintOffset;
1296   /// A stack of snapshots, used for rolling back.
1297   SmallVector<unsigned, 8> snapshotStack;
1298 };
1299 
1300 // Return a + scale*b;
1301 static SmallVector<int64_t, 8> scaleAndAdd(ArrayRef<int64_t> a, int64_t scale,
1302                                            ArrayRef<int64_t> b) {
1303   assert(a.size() == b.size());
1304   SmallVector<int64_t, 8> res;
1305   res.reserve(a.size());
1306   for (unsigned i = 0, e = a.size(); i < e; ++i)
1307     res.push_back(a[i] + scale * b[i]);
1308   return res;
1309 }
1310 
1311 /// Reduce the basis to try and find a direction in which the polytope is
1312 /// "thin". This only works for bounded polytopes.
1313 ///
1314 /// This is an implementation of the algorithm described in the paper
1315 /// "An Implementation of Generalized Basis Reduction for Integer Programming"
1316 /// by W. Cook, T. Rutherford, H. E. Scarf, D. Shallcross.
1317 ///
1318 /// Let b_{level}, b_{level + 1}, ... b_n be the current basis.
1319 /// Let width_i(v) = max <v, x - y> where x and y are points in the original
1320 /// polytope such that <b_j, x - y> = 0 is satisfied for all level <= j < i.
1321 ///
1322 /// In every iteration, we first replace b_{i+1} with b_{i+1} + u*b_i, where u
1323 /// is the integer such that width_i(b_{i+1} + u*b_i) is minimized. Let dual_i
1324 /// be the dual variable associated with the constraint <b_i, x - y> = 0 when
1325 /// computing width_{i+1}(b_{i+1}). It can be shown that dual_i is the
1326 /// minimizing value of u, if it were allowed to be fractional. Due to
1327 /// convexity, the minimizing integer value is either floor(dual_i) or
1328 /// ceil(dual_i), so we just need to check which of these gives a lower
1329 /// width_{i+1} value. If dual_i turned out to be an integer, then u = dual_i.
1330 ///
1331 /// Now if width_i(b_{i+1}) < 0.75 * width_i(b_i), we swap b_i and (the new)
1332 /// b_{i + 1} and decrement i (unless i = level, in which case we stay at the
1333 /// same i). Otherwise, we increment i.
1334 ///
1335 /// We keep f values and duals cached and invalidate them when necessary.
1336 /// Whenever possible, we use them instead of recomputing them. We implement the
1337 /// algorithm as follows.
1338 ///
1339 /// In an iteration at i we need to compute:
1340 ///   a) width_i(b_{i + 1})
1341 ///   b) width_i(b_i)
1342 ///   c) the integer u that minimizes width_i(b_{i + 1} + u*b_i)
1343 ///
1344 /// If width_i(b_i) is not already cached, we compute it.
1345 ///
1346 /// If the duals are not already cached, we compute width_{i+1}(b_{i+1}) and
1347 /// store the duals from this computation.
1348 ///
1349 /// We call updateBasisWithUAndGetFCandidate, which finds the minimizing value
1350 /// of u as explained before, caches the duals from this computation, sets
1351 /// b_{i+1} to b_{i+1} + u*b_i, and returns the new value of width_i(b_{i+1}).
1352 ///
1353 /// Now if width_i(b_{i+1}) < 0.75 * width_i(b_i), we swap b_i and b_{i+1} and
1354 /// decrement i, resulting in the basis
1355 /// ... b_{i - 1}, b_{i + 1} + u*b_i, b_i, b_{i+2}, ...
1356 /// with corresponding f values
1357 /// ... width_{i-1}(b_{i-1}), width_i(b_{i+1} + u*b_i), width_{i+1}(b_i), ...
1358 /// The values up to i - 1 remain unchanged. We have just gotten the middle
1359 /// value from updateBasisWithUAndGetFCandidate, so we can update that in the
1360 /// cache. The value at width_{i+1}(b_i) is unknown, so we evict this value from
1361 /// the cache. The iteration after decrementing needs exactly the duals from the
1362 /// computation of width_i(b_{i + 1} + u*b_i), so we keep these in the cache.
1363 ///
1364 /// When incrementing i, no cached f values get invalidated. However, the cached
1365 /// duals do get invalidated as the duals for the higher levels are different.
1366 void Simplex::reduceBasis(Matrix &basis, unsigned level) {
1367   const Fraction epsilon(3, 4);
1368 
1369   if (level == basis.getNumRows() - 1)
1370     return;
1371 
1372   GBRSimplex gbrSimplex(*this);
1373   SmallVector<Fraction, 8> width;
1374   SmallVector<int64_t, 8> dual;
1375   int64_t dualDenom;
1376 
1377   // Finds the value of u that minimizes width_i(b_{i+1} + u*b_i), caches the
1378   // duals from this computation, sets b_{i+1} to b_{i+1} + u*b_i, and returns
1379   // the new value of width_i(b_{i+1}).
1380   //
1381   // If dual_i is not an integer, the minimizing value must be either
1382   // floor(dual_i) or ceil(dual_i). We compute the expression for both and
1383   // choose the minimizing value.
1384   //
1385   // If dual_i is an integer, we don't need to perform these computations. We
1386   // know that in this case,
1387   //   a) u = dual_i.
1388   //   b) one can show that dual_j for j < i are the same duals we would have
1389   //      gotten from computing width_i(b_{i + 1} + u*b_i), so the correct duals
1390   //      are the ones already in the cache.
1391   //   c) width_i(b_{i+1} + u*b_i) = min_{alpha} width_i(b_{i+1} + alpha * b_i),
1392   //   which
1393   //      one can show is equal to width_{i+1}(b_{i+1}). The latter value must
1394   //      be in the cache, so we get it from there and return it.
1395   auto updateBasisWithUAndGetFCandidate = [&](unsigned i) -> Fraction {
1396     assert(i < level + dual.size() && "dual_i is not known!");
1397 
1398     int64_t u = floorDiv(dual[i - level], dualDenom);
1399     basis.addToRow(i, i + 1, u);
1400     if (dual[i - level] % dualDenom != 0) {
1401       SmallVector<int64_t, 8> candidateDual[2];
1402       int64_t candidateDualDenom[2];
1403       Fraction widthI[2];
1404 
1405       // Initially u is floor(dual) and basis reflects this.
1406       widthI[0] = gbrSimplex.computeWidthAndDuals(
1407           basis.getRow(i + 1), candidateDual[0], candidateDualDenom[0]);
1408 
1409       // Now try ceil(dual), i.e. floor(dual) + 1.
1410       ++u;
1411       basis.addToRow(i, i + 1, 1);
1412       widthI[1] = gbrSimplex.computeWidthAndDuals(
1413           basis.getRow(i + 1), candidateDual[1], candidateDualDenom[1]);
1414 
1415       unsigned j = widthI[0] < widthI[1] ? 0 : 1;
1416       if (j == 0)
1417         // Subtract 1 to go from u = ceil(dual) back to floor(dual).
1418         basis.addToRow(i, i + 1, -1);
1419 
1420       // width_i(b{i+1} + u*b_i) should be minimized at our value of u.
1421       // We assert that this holds by checking that the values of width_i at
1422       // u - 1 and u + 1 are greater than or equal to the value at u. If the
1423       // width is lesser at either of the adjacent values, then our computed
1424       // value of u is clearly not the minimizer. Otherwise by convexity the
1425       // computed value of u is really the minimizer.
1426 
1427       // Check the value at u - 1.
1428       assert(gbrSimplex.computeWidth(scaleAndAdd(
1429                  basis.getRow(i + 1), -1, basis.getRow(i))) >= widthI[j] &&
1430              "Computed u value does not minimize the width!");
1431       // Check the value at u + 1.
1432       assert(gbrSimplex.computeWidth(scaleAndAdd(
1433                  basis.getRow(i + 1), +1, basis.getRow(i))) >= widthI[j] &&
1434              "Computed u value does not minimize the width!");
1435 
1436       dual = std::move(candidateDual[j]);
1437       dualDenom = candidateDualDenom[j];
1438       return widthI[j];
1439     }
1440 
1441     assert(i + 1 - level < width.size() && "width_{i+1} wasn't saved");
1442     // f_i(b_{i+1} + dual*b_i) == width_{i+1}(b_{i+1}) when `dual` minimizes the
1443     // LHS. (note: the basis has already been updated, so b_{i+1} + dual*b_i in
1444     // the above expression is equal to basis.getRow(i+1) below.)
1445     assert(gbrSimplex.computeWidth(basis.getRow(i + 1)) ==
1446            width[i + 1 - level]);
1447     return width[i + 1 - level];
1448   };
1449 
1450   // In the ith iteration of the loop, gbrSimplex has constraints for directions
1451   // from `level` to i - 1.
1452   unsigned i = level;
1453   while (i < basis.getNumRows() - 1) {
1454     if (i >= level + width.size()) {
1455       // We don't even know the value of f_i(b_i), so let's find that first.
1456       // We have to do this first since later we assume that width already
1457       // contains values up to and including i.
1458 
1459       assert((i == 0 || i - 1 < level + width.size()) &&
1460              "We are at level i but we don't know the value of width_{i-1}");
1461 
1462       // We don't actually use these duals at all, but it doesn't matter
1463       // because this case should only occur when i is level, and there are no
1464       // duals in that case anyway.
1465       assert(i == level && "This case should only occur when i == level");
1466       width.push_back(
1467           gbrSimplex.computeWidthAndDuals(basis.getRow(i), dual, dualDenom));
1468     }
1469 
1470     if (i >= level + dual.size()) {
1471       assert(i + 1 >= level + width.size() &&
1472              "We don't know dual_i but we know width_{i+1}");
1473       // We don't know dual for our level, so let's find it.
1474       gbrSimplex.addEqualityForDirection(basis.getRow(i));
1475       width.push_back(gbrSimplex.computeWidthAndDuals(basis.getRow(i + 1), dual,
1476                                                       dualDenom));
1477       gbrSimplex.removeLastEquality();
1478     }
1479 
1480     // This variable stores width_i(b_{i+1} + u*b_i).
1481     Fraction widthICandidate = updateBasisWithUAndGetFCandidate(i);
1482     if (widthICandidate < epsilon * width[i - level]) {
1483       basis.swapRows(i, i + 1);
1484       width[i - level] = widthICandidate;
1485       // The values of width_{i+1}(b_{i+1}) and higher may change after the
1486       // swap, so we remove the cached values here.
1487       width.resize(i - level + 1);
1488       if (i == level) {
1489         dual.clear();
1490         continue;
1491       }
1492 
1493       gbrSimplex.removeLastEquality();
1494       i--;
1495       continue;
1496     }
1497 
1498     // Invalidate duals since the higher level needs to recompute its own duals.
1499     dual.clear();
1500     gbrSimplex.addEqualityForDirection(basis.getRow(i));
1501     i++;
1502   }
1503 }
1504 
1505 /// Search for an integer sample point using a branch and bound algorithm.
1506 ///
1507 /// Each row in the basis matrix is a vector, and the set of basis vectors
1508 /// should span the space. Initially this is the identity matrix,
1509 /// i.e., the basis vectors are just the variables.
1510 ///
1511 /// In every level, a value is assigned to the level-th basis vector, as
1512 /// follows. Compute the minimum and maximum rational values of this direction.
1513 /// If only one integer point lies in this range, constrain the variable to
1514 /// have this value and recurse to the next variable.
1515 ///
1516 /// If the range has multiple values, perform generalized basis reduction via
1517 /// reduceBasis and then compute the bounds again. Now we try constraining
1518 /// this direction in the first value in this range and "recurse" to the next
1519 /// level. If we fail to find a sample, we try assigning the direction the next
1520 /// value in this range, and so on.
1521 ///
1522 /// If no integer sample is found from any of the assignments, or if the range
1523 /// contains no integer value, then of course the polytope is empty for the
1524 /// current assignment of the values in previous levels, so we return to
1525 /// the previous level.
1526 ///
1527 /// If we reach the last level where all the variables have been assigned values
1528 /// already, then we simply return the current sample point if it is integral,
1529 /// and go back to the previous level otherwise.
1530 ///
1531 /// To avoid potentially arbitrarily large recursion depths leading to stack
1532 /// overflows, this algorithm is implemented iteratively.
1533 Optional<SmallVector<int64_t, 8>> Simplex::findIntegerSample() {
1534   if (empty)
1535     return {};
1536 
1537   unsigned nDims = var.size();
1538   Matrix basis = Matrix::identity(nDims);
1539 
1540   unsigned level = 0;
1541   // The snapshot just before constraining a direction to a value at each level.
1542   SmallVector<unsigned, 8> snapshotStack;
1543   // The maximum value in the range of the direction for each level.
1544   SmallVector<int64_t, 8> upperBoundStack;
1545   // The next value to try constraining the basis vector to at each level.
1546   SmallVector<int64_t, 8> nextValueStack;
1547 
1548   snapshotStack.reserve(basis.getNumRows());
1549   upperBoundStack.reserve(basis.getNumRows());
1550   nextValueStack.reserve(basis.getNumRows());
1551   while (level != -1u) {
1552     if (level == basis.getNumRows()) {
1553       // We've assigned values to all variables. Return if we have a sample,
1554       // or go back up to the previous level otherwise.
1555       if (auto maybeSample = getSamplePointIfIntegral())
1556         return maybeSample;
1557       level--;
1558       continue;
1559     }
1560 
1561     if (level >= upperBoundStack.size()) {
1562       // We haven't populated the stack values for this level yet, so we have
1563       // just come down a level ("recursed"). Find the lower and upper bounds.
1564       // If there is more than one integer point in the range, perform
1565       // generalized basis reduction.
1566       SmallVector<int64_t, 8> basisCoeffs =
1567           llvm::to_vector<8>(basis.getRow(level));
1568       basisCoeffs.push_back(0);
1569 
1570       MaybeOptimum<int64_t> minRoundedUp, maxRoundedDown;
1571       std::tie(minRoundedUp, maxRoundedDown) =
1572           computeIntegerBounds(basisCoeffs);
1573 
1574       // We don't have any integer values in the range.
1575       // Pop the stack and return up a level.
1576       if (minRoundedUp.isEmpty() || maxRoundedDown.isEmpty()) {
1577         assert((minRoundedUp.isEmpty() && maxRoundedDown.isEmpty()) &&
1578                "If one bound is empty, both should be.");
1579         snapshotStack.pop_back();
1580         nextValueStack.pop_back();
1581         upperBoundStack.pop_back();
1582         level--;
1583         continue;
1584       }
1585 
1586       // We already checked the empty case above.
1587       assert((minRoundedUp.isBounded() && maxRoundedDown.isBounded()) &&
1588              "Polyhedron should be bounded!");
1589 
1590       // Heuristic: if the sample point is integral at this point, just return
1591       // it.
1592       if (auto maybeSample = getSamplePointIfIntegral())
1593         return *maybeSample;
1594 
1595       if (*minRoundedUp < *maxRoundedDown) {
1596         reduceBasis(basis, level);
1597         basisCoeffs = llvm::to_vector<8>(basis.getRow(level));
1598         basisCoeffs.push_back(0);
1599         std::tie(minRoundedUp, maxRoundedDown) =
1600             computeIntegerBounds(basisCoeffs);
1601       }
1602 
1603       snapshotStack.push_back(getSnapshot());
1604       // The smallest value in the range is the next value to try.
1605       // The values in the optionals are guaranteed to exist since we know the
1606       // polytope is bounded.
1607       nextValueStack.push_back(*minRoundedUp);
1608       upperBoundStack.push_back(*maxRoundedDown);
1609     }
1610 
1611     assert((snapshotStack.size() - 1 == level &&
1612             nextValueStack.size() - 1 == level &&
1613             upperBoundStack.size() - 1 == level) &&
1614            "Mismatched variable stack sizes!");
1615 
1616     // Whether we "recursed" or "returned" from a lower level, we rollback
1617     // to the snapshot of the starting state at this level. (in the "recursed"
1618     // case this has no effect)
1619     rollback(snapshotStack.back());
1620     int64_t nextValue = nextValueStack.back();
1621     nextValueStack.back()++;
1622     if (nextValue > upperBoundStack.back()) {
1623       // We have exhausted the range and found no solution. Pop the stack and
1624       // return up a level.
1625       snapshotStack.pop_back();
1626       nextValueStack.pop_back();
1627       upperBoundStack.pop_back();
1628       level--;
1629       continue;
1630     }
1631 
1632     // Try the next value in the range and "recurse" into the next level.
1633     SmallVector<int64_t, 8> basisCoeffs(basis.getRow(level).begin(),
1634                                         basis.getRow(level).end());
1635     basisCoeffs.push_back(-nextValue);
1636     addEquality(basisCoeffs);
1637     level++;
1638   }
1639 
1640   return {};
1641 }
1642 
1643 /// Compute the minimum and maximum integer values the expression can take. We
1644 /// compute each separately.
1645 std::pair<MaybeOptimum<int64_t>, MaybeOptimum<int64_t>>
1646 Simplex::computeIntegerBounds(ArrayRef<int64_t> coeffs) {
1647   MaybeOptimum<int64_t> minRoundedUp(
1648       computeOptimum(Simplex::Direction::Down, coeffs).map(ceil));
1649   MaybeOptimum<int64_t> maxRoundedDown(
1650       computeOptimum(Simplex::Direction::Up, coeffs).map(floor));
1651   return {minRoundedUp, maxRoundedDown};
1652 }
1653 
1654 void SimplexBase::print(raw_ostream &os) const {
1655   os << "rows = " << nRow << ", columns = " << nCol << "\n";
1656   if (empty)
1657     os << "Simplex marked empty!\n";
1658   os << "var: ";
1659   for (unsigned i = 0; i < var.size(); ++i) {
1660     if (i > 0)
1661       os << ", ";
1662     var[i].print(os);
1663   }
1664   os << "\ncon: ";
1665   for (unsigned i = 0; i < con.size(); ++i) {
1666     if (i > 0)
1667       os << ", ";
1668     con[i].print(os);
1669   }
1670   os << '\n';
1671   for (unsigned row = 0; row < nRow; ++row) {
1672     if (row > 0)
1673       os << ", ";
1674     os << "r" << row << ": " << rowUnknown[row];
1675   }
1676   os << '\n';
1677   os << "c0: denom, c1: const";
1678   for (unsigned col = 2; col < nCol; ++col)
1679     os << ", c" << col << ": " << colUnknown[col];
1680   os << '\n';
1681   for (unsigned row = 0; row < nRow; ++row) {
1682     for (unsigned col = 0; col < nCol; ++col)
1683       os << tableau(row, col) << '\t';
1684     os << '\n';
1685   }
1686   os << '\n';
1687 }
1688 
1689 void SimplexBase::dump() const { print(llvm::errs()); }
1690 
1691 bool Simplex::isRationalSubsetOf(const IntegerRelation &rel) {
1692   if (isEmpty())
1693     return true;
1694 
1695   for (unsigned i = 0, e = rel.getNumInequalities(); i < e; ++i)
1696     if (findIneqType(rel.getInequality(i)) != IneqType::Redundant)
1697       return false;
1698 
1699   for (unsigned i = 0, e = rel.getNumEqualities(); i < e; ++i)
1700     if (!isRedundantEquality(rel.getEquality(i)))
1701       return false;
1702 
1703   return true;
1704 }
1705 
1706 /// Returns the type of the inequality with coefficients `coeffs`.
1707 /// Possible types are:
1708 /// Redundant   The inequality is satisfied by all points in the polytope
1709 /// Cut         The inequality is satisfied by some points, but not by others
1710 /// Separate    The inequality is not satisfied by any point
1711 ///
1712 /// Internally, this computes the minimum and the maximum the inequality with
1713 /// coefficients `coeffs` can take. If the minimum is >= 0, the inequality holds
1714 /// for all points in the polytope, so it is redundant.  If the minimum is <= 0
1715 /// and the maximum is >= 0, the points in between the minimum and the
1716 /// inequality do not satisfy it, the points in between the inequality and the
1717 /// maximum satisfy it. Hence, it is a cut inequality. If both are < 0, no
1718 /// points of the polytope satisfy the inequality, which means it is a separate
1719 /// inequality.
1720 Simplex::IneqType Simplex::findIneqType(ArrayRef<int64_t> coeffs) {
1721   MaybeOptimum<Fraction> minimum = computeOptimum(Direction::Down, coeffs);
1722   if (minimum.isBounded() && *minimum >= Fraction(0, 1)) {
1723     return IneqType::Redundant;
1724   }
1725   MaybeOptimum<Fraction> maximum = computeOptimum(Direction::Up, coeffs);
1726   if ((!minimum.isBounded() || *minimum <= Fraction(0, 1)) &&
1727       (!maximum.isBounded() || *maximum >= Fraction(0, 1))) {
1728     return IneqType::Cut;
1729   }
1730   return IneqType::Separate;
1731 }
1732 
1733 /// Checks whether the type of the inequality with coefficients `coeffs`
1734 /// is Redundant.
1735 bool Simplex::isRedundantInequality(ArrayRef<int64_t> coeffs) {
1736   assert(!empty &&
1737          "It is not meaningful to ask about redundancy in an empty set!");
1738   return findIneqType(coeffs) == IneqType::Redundant;
1739 }
1740 
1741 /// Check whether the equality given by `coeffs == 0` is redundant given
1742 /// the existing constraints. This is redundant when `coeffs` is already
1743 /// always zero under the existing constraints. `coeffs` is always zero
1744 /// when the minimum and maximum value that `coeffs` can take are both zero.
1745 bool Simplex::isRedundantEquality(ArrayRef<int64_t> coeffs) {
1746   assert(!empty &&
1747          "It is not meaningful to ask about redundancy in an empty set!");
1748   MaybeOptimum<Fraction> minimum = computeOptimum(Direction::Down, coeffs);
1749   MaybeOptimum<Fraction> maximum = computeOptimum(Direction::Up, coeffs);
1750   assert((!minimum.isEmpty() && !maximum.isEmpty()) &&
1751          "Optima should be non-empty for a non-empty set");
1752   return minimum.isBounded() && maximum.isBounded() &&
1753          *maximum == Fraction(0, 1) && *minimum == Fraction(0, 1);
1754 }
1755