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