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