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