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