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