1 //===- IntegerPolyhedron.cpp - Tests for IntegerPolyhedron 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 "./Utils.h"
10 #include "mlir/Analysis/Presburger/IntegerRelation.h"
11 #include "mlir/Analysis/Presburger/PWMAFunction.h"
12 #include "mlir/Analysis/Presburger/Simplex.h"
13 
14 #include <gmock/gmock.h>
15 #include <gtest/gtest.h>
16 
17 #include <numeric>
18 
19 using namespace mlir;
20 using namespace presburger;
21 
22 using testing::ElementsAre;
23 
24 enum class TestFunction { Sample, Empty };
25 
26 /// Construct a IntegerPolyhedron from a set of inequality and
27 /// equality constraints.
28 static IntegerPolyhedron
makeSetFromConstraints(unsigned ids,ArrayRef<SmallVector<int64_t,4>> ineqs,ArrayRef<SmallVector<int64_t,4>> eqs,unsigned syms=0)29 makeSetFromConstraints(unsigned ids, ArrayRef<SmallVector<int64_t, 4>> ineqs,
30                        ArrayRef<SmallVector<int64_t, 4>> eqs,
31                        unsigned syms = 0) {
32   IntegerPolyhedron set(
33       ineqs.size(), eqs.size(), ids + 1,
34       PresburgerSpace::getSetSpace(ids - syms, syms, /*numLocals=*/0));
35   for (const auto &eq : eqs)
36     set.addEquality(eq);
37   for (const auto &ineq : ineqs)
38     set.addInequality(ineq);
39   return set;
40 }
41 
dump(ArrayRef<int64_t> vec)42 static void dump(ArrayRef<int64_t> vec) {
43   for (int64_t x : vec)
44     llvm::errs() << x << ' ';
45   llvm::errs() << '\n';
46 }
47 
48 /// If fn is TestFunction::Sample (default):
49 ///
50 ///   If hasSample is true, check that findIntegerSample returns a valid sample
51 ///   for the IntegerPolyhedron poly. Also check that getIntegerLexmin finds a
52 ///   non-empty lexmin.
53 ///
54 ///   If hasSample is false, check that findIntegerSample returns None and
55 ///   findIntegerLexMin returns Empty.
56 ///
57 /// If fn is TestFunction::Empty, check that isIntegerEmpty returns the
58 /// opposite of hasSample.
checkSample(bool hasSample,const IntegerPolyhedron & poly,TestFunction fn=TestFunction::Sample)59 static void checkSample(bool hasSample, const IntegerPolyhedron &poly,
60                         TestFunction fn = TestFunction::Sample) {
61   Optional<SmallVector<int64_t, 8>> maybeSample;
62   MaybeOptimum<SmallVector<int64_t, 8>> maybeLexMin;
63   switch (fn) {
64   case TestFunction::Sample:
65     maybeSample = poly.findIntegerSample();
66     maybeLexMin = poly.findIntegerLexMin();
67 
68     if (!hasSample) {
69       EXPECT_FALSE(maybeSample.has_value());
70       if (maybeSample.has_value()) {
71         llvm::errs() << "findIntegerSample gave sample: ";
72         dump(*maybeSample);
73       }
74 
75       EXPECT_TRUE(maybeLexMin.isEmpty());
76       if (maybeLexMin.isBounded()) {
77         llvm::errs() << "findIntegerLexMin gave sample: ";
78         dump(*maybeLexMin);
79       }
80     } else {
81       ASSERT_TRUE(maybeSample.has_value());
82       EXPECT_TRUE(poly.containsPoint(*maybeSample));
83 
84       ASSERT_FALSE(maybeLexMin.isEmpty());
85       if (maybeLexMin.isUnbounded()) {
86         EXPECT_TRUE(Simplex(poly).isUnbounded());
87       }
88       if (maybeLexMin.isBounded()) {
89         EXPECT_TRUE(poly.containsPoint(*maybeLexMin));
90       }
91     }
92     break;
93   case TestFunction::Empty:
94     EXPECT_EQ(!hasSample, poly.isIntegerEmpty());
95     break;
96   }
97 }
98 
99 /// Check sampling for all the permutations of the dimensions for the given
100 /// constraint set. Since the GBR algorithm progresses dimension-wise, different
101 /// orderings may cause the algorithm to proceed differently. At least some of
102 ///.these permutations should make it past the heuristics and test the
103 /// implementation of the GBR algorithm itself.
104 /// Use TestFunction fn to test.
checkPermutationsSample(bool hasSample,unsigned nDim,ArrayRef<SmallVector<int64_t,4>> ineqs,ArrayRef<SmallVector<int64_t,4>> eqs,TestFunction fn=TestFunction::Sample)105 static void checkPermutationsSample(bool hasSample, unsigned nDim,
106                                     ArrayRef<SmallVector<int64_t, 4>> ineqs,
107                                     ArrayRef<SmallVector<int64_t, 4>> eqs,
108                                     TestFunction fn = TestFunction::Sample) {
109   SmallVector<unsigned, 4> perm(nDim);
110   std::iota(perm.begin(), perm.end(), 0);
111   auto permute = [&perm](ArrayRef<int64_t> coeffs) {
112     SmallVector<int64_t, 4> permuted;
113     for (unsigned id : perm)
114       permuted.push_back(coeffs[id]);
115     permuted.push_back(coeffs.back());
116     return permuted;
117   };
118   do {
119     SmallVector<SmallVector<int64_t, 4>, 4> permutedIneqs, permutedEqs;
120     for (const auto &ineq : ineqs)
121       permutedIneqs.push_back(permute(ineq));
122     for (const auto &eq : eqs)
123       permutedEqs.push_back(permute(eq));
124 
125     checkSample(hasSample,
126                 makeSetFromConstraints(nDim, permutedIneqs, permutedEqs), fn);
127   } while (std::next_permutation(perm.begin(), perm.end()));
128 }
129 
TEST(IntegerPolyhedronTest,removeInequality)130 TEST(IntegerPolyhedronTest, removeInequality) {
131   IntegerPolyhedron set =
132       makeSetFromConstraints(1, {{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}}, {});
133 
134   set.removeInequalityRange(0, 0);
135   EXPECT_EQ(set.getNumInequalities(), 5u);
136 
137   set.removeInequalityRange(1, 3);
138   EXPECT_EQ(set.getNumInequalities(), 3u);
139   EXPECT_THAT(set.getInequality(0), ElementsAre(0, 0));
140   EXPECT_THAT(set.getInequality(1), ElementsAre(3, 3));
141   EXPECT_THAT(set.getInequality(2), ElementsAre(4, 4));
142 
143   set.removeInequality(1);
144   EXPECT_EQ(set.getNumInequalities(), 2u);
145   EXPECT_THAT(set.getInequality(0), ElementsAre(0, 0));
146   EXPECT_THAT(set.getInequality(1), ElementsAre(4, 4));
147 }
148 
TEST(IntegerPolyhedronTest,removeEquality)149 TEST(IntegerPolyhedronTest, removeEquality) {
150   IntegerPolyhedron set =
151       makeSetFromConstraints(1, {}, {{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}});
152 
153   set.removeEqualityRange(0, 0);
154   EXPECT_EQ(set.getNumEqualities(), 5u);
155 
156   set.removeEqualityRange(1, 3);
157   EXPECT_EQ(set.getNumEqualities(), 3u);
158   EXPECT_THAT(set.getEquality(0), ElementsAre(0, 0));
159   EXPECT_THAT(set.getEquality(1), ElementsAre(3, 3));
160   EXPECT_THAT(set.getEquality(2), ElementsAre(4, 4));
161 
162   set.removeEquality(1);
163   EXPECT_EQ(set.getNumEqualities(), 2u);
164   EXPECT_THAT(set.getEquality(0), ElementsAre(0, 0));
165   EXPECT_THAT(set.getEquality(1), ElementsAre(4, 4));
166 }
167 
TEST(IntegerPolyhedronTest,clearConstraints)168 TEST(IntegerPolyhedronTest, clearConstraints) {
169   IntegerPolyhedron set = makeSetFromConstraints(1, {}, {});
170 
171   set.addInequality({1, 0});
172   EXPECT_EQ(set.atIneq(0, 0), 1);
173   EXPECT_EQ(set.atIneq(0, 1), 0);
174 
175   set.clearConstraints();
176 
177   set.addInequality({1, 0});
178   EXPECT_EQ(set.atIneq(0, 0), 1);
179   EXPECT_EQ(set.atIneq(0, 1), 0);
180 }
181 
TEST(IntegerPolyhedronTest,removeIdRange)182 TEST(IntegerPolyhedronTest, removeIdRange) {
183   IntegerPolyhedron set(PresburgerSpace::getSetSpace(3, 2, 1));
184 
185   set.addInequality({10, 11, 12, 20, 21, 30, 40});
186   set.removeVar(VarKind::Symbol, 1);
187   EXPECT_THAT(set.getInequality(0),
188               testing::ElementsAre(10, 11, 12, 20, 30, 40));
189 
190   set.removeVarRange(VarKind::SetDim, 0, 2);
191   EXPECT_THAT(set.getInequality(0), testing::ElementsAre(12, 20, 30, 40));
192 
193   set.removeVarRange(VarKind::Local, 1, 1);
194   EXPECT_THAT(set.getInequality(0), testing::ElementsAre(12, 20, 30, 40));
195 
196   set.removeVarRange(VarKind::Local, 0, 1);
197   EXPECT_THAT(set.getInequality(0), testing::ElementsAre(12, 20, 40));
198 }
199 
TEST(IntegerPolyhedronTest,FindSampleTest)200 TEST(IntegerPolyhedronTest, FindSampleTest) {
201   // Bounded sets with only inequalities.
202   // 0 <= 7x <= 5
203   checkSample(true, parsePoly("(x) : (7 * x >= 0, -7 * x + 5 >= 0)"));
204 
205   // 1 <= 5x and 5x <= 4 (no solution).
206   checkSample(false, parsePoly("(x) : (5 * x - 1 >= 0, -5 * x + 4 >= 0)"));
207 
208   // 1 <= 5x and 5x <= 9 (solution: x = 1).
209   checkSample(true, parsePoly("(x) : (5 * x - 1 >= 0, -5 * x + 9 >= 0)"));
210 
211   // Bounded sets with equalities.
212   // x >= 8 and 40 >= y and x = y.
213   checkSample(true,
214               parsePoly("(x,y) : (x - 8 >= 0, -y + 40 >= 0, x - y == 0)"));
215 
216   // x <= 10 and y <= 10 and 10 <= z and x + 2y = 3z.
217   // solution: x = y = z = 10.
218   checkSample(true, parsePoly("(x,y,z) : (-x + 10 >= 0, -y + 10 >= 0, "
219                               "z - 10 >= 0, x + 2 * y - 3 * z == 0)"));
220 
221   // x <= 10 and y <= 10 and 11 <= z and x + 2y = 3z.
222   // This implies x + 2y >= 33 and x + 2y <= 30, which has no solution.
223   checkSample(false, parsePoly("(x,y,z) : (-x + 10 >= 0, -y + 10 >= 0, "
224                                "z - 11 >= 0, x + 2 * y - 3 * z == 0)"));
225 
226   // 0 <= r and r <= 3 and 4q + r = 7.
227   // Solution: q = 1, r = 3.
228   checkSample(true,
229               parsePoly("(q,r) : (r >= 0, -r + 3 >= 0, 4 * q + r - 7 == 0)"));
230 
231   // 4q + r = 7 and r = 0.
232   // Solution: q = 1, r = 3.
233   checkSample(false, parsePoly("(q,r) : (4 * q + r - 7 == 0, r == 0)"));
234 
235   // The next two sets are large sets that should take a long time to sample
236   // with a naive branch and bound algorithm but can be sampled efficiently with
237   // the GBR algorithm.
238   //
239   // This is a triangle with vertices at (1/3, 0), (2/3, 0) and (10000, 10000).
240   checkSample(true, parsePoly("(x,y) : (y >= 0, "
241                               "300000 * x - 299999 * y - 100000 >= 0, "
242                               "-300000 * x + 299998 * y + 200000 >= 0)"));
243 
244   // This is a tetrahedron with vertices at
245   // (1/3, 0, 0), (2/3, 0, 0), (2/3, 0, 10000), and (10000, 10000, 10000).
246   // The first three points form a triangular base on the xz plane with the
247   // apex at the fourth point, which is the only integer point.
248   checkPermutationsSample(
249       true, 3,
250       {
251           {0, 1, 0, 0},  // y >= 0
252           {0, -1, 1, 0}, // z >= y
253           {300000, -299998, -1,
254            -100000},                    // -300000x + 299998y + 100000 + z <= 0.
255           {-150000, 149999, 0, 100000}, // -150000x + 149999y + 100000 >= 0.
256       },
257       {});
258 
259   // Same thing with some spurious extra dimensions equated to constants.
260   checkSample(
261       true,
262       parsePoly("(a,b,c,d,e) : (b + d - e >= 0, -b + c - d + e >= 0, "
263                 "300000 * a - 299998 * b - c - 9 * d + 21 * e - 112000 >= 0, "
264                 "-150000 * a + 149999 * b - 15 * d + 47 * e + 68000 >= 0, "
265                 "d - e == 0, d + e - 2000 == 0)"));
266 
267   // This is a tetrahedron with vertices at
268   // (1/3, 0, 0), (2/3, 0, 0), (2/3, 0, 100), (100, 100 - 1/3, 100).
269   checkPermutationsSample(false, 3,
270                           {
271                               {0, 1, 0, 0},
272                               {0, -300, 299, 0},
273                               {300 * 299, -89400, -299, -100 * 299},
274                               {-897, 894, 0, 598},
275                           },
276                           {});
277 
278   // Two tests involving equalities that are integer empty but not rational
279   // empty.
280 
281   // This is a line segment from (0, 1/3) to (100, 100 + 1/3).
282   checkSample(
283       false,
284       parsePoly("(x,y) : (x >= 0, -x + 100 >= 0, 3 * x - 3 * y + 1 == 0)"));
285 
286   // A thin parallelogram. 0 <= x <= 100 and x + 1/3 <= y <= x + 2/3.
287   checkSample(false,
288               parsePoly("(x,y) : (x >= 0, -x + 100 >= 0, "
289                         "3 * x - 3 * y + 2 >= 0, -3 * x + 3 * y - 1 >= 0)"));
290 
291   checkSample(true, parsePoly("(x,y) : (2 * x >= 0, -2 * x + 99 >= 0, "
292                               "2 * y >= 0, -2 * y + 99 >= 0)"));
293 
294   // 2D cone with apex at (10000, 10000) and
295   // edges passing through (1/3, 0) and (2/3, 0).
296   checkSample(true, parsePoly("(x,y) : (300000 * x - 299999 * y - 100000 >= 0, "
297                               "-300000 * x + 299998 * y + 200000 >= 0)"));
298 
299   // Cartesian product of a tetrahedron and a 2D cone.
300   // The tetrahedron has vertices at
301   // (1/3, 0, 0), (2/3, 0, 0), (2/3, 0, 10000), and (10000, 10000, 10000).
302   // The first three points form a triangular base on the xz plane with the
303   // apex at the fourth point, which is the only integer point.
304   // The cone has apex at (10000, 10000) and
305   // edges passing through (1/3, 0) and (2/3, 0).
306   checkPermutationsSample(
307       true /* not empty */, 5,
308       {
309           // Tetrahedron contraints:
310           {0, 1, 0, 0, 0, 0},  // y >= 0
311           {0, -1, 1, 0, 0, 0}, // z >= y
312                                // -300000x + 299998y + 100000 + z <= 0.
313           {300000, -299998, -1, 0, 0, -100000},
314           // -150000x + 149999y + 100000 >= 0.
315           {-150000, 149999, 0, 0, 0, 100000},
316 
317           // Triangle constraints:
318           // 300000p - 299999q >= 100000
319           {0, 0, 0, 300000, -299999, -100000},
320           // -300000p + 299998q + 200000 >= 0
321           {0, 0, 0, -300000, 299998, 200000},
322       },
323       {});
324 
325   // Cartesian product of same tetrahedron as above and {(p, q) : 1/3 <= p <=
326   // 2/3}. Since the second set is empty, the whole set is too.
327   checkPermutationsSample(
328       false /* empty */, 5,
329       {
330           // Tetrahedron contraints:
331           {0, 1, 0, 0, 0, 0},  // y >= 0
332           {0, -1, 1, 0, 0, 0}, // z >= y
333                                // -300000x + 299998y + 100000 + z <= 0.
334           {300000, -299998, -1, 0, 0, -100000},
335           // -150000x + 149999y + 100000 >= 0.
336           {-150000, 149999, 0, 0, 0, 100000},
337 
338           // Second set constraints:
339           // 3p >= 1
340           {0, 0, 0, 3, 0, -1},
341           // 3p <= 2
342           {0, 0, 0, -3, 0, 2},
343       },
344       {});
345 
346   // Cartesian product of same tetrahedron as above and
347   // {(p, q, r) : 1 <= p <= 2 and p = 3q + 3r}.
348   // Since the second set is empty, the whole set is too.
349   checkPermutationsSample(
350       false /* empty */, 5,
351       {
352           // Tetrahedron contraints:
353           {0, 1, 0, 0, 0, 0, 0},  // y >= 0
354           {0, -1, 1, 0, 0, 0, 0}, // z >= y
355                                   // -300000x + 299998y + 100000 + z <= 0.
356           {300000, -299998, -1, 0, 0, 0, -100000},
357           // -150000x + 149999y + 100000 >= 0.
358           {-150000, 149999, 0, 0, 0, 0, 100000},
359 
360           // Second set constraints:
361           // p >= 1
362           {0, 0, 0, 1, 0, 0, -1},
363           // p <= 2
364           {0, 0, 0, -1, 0, 0, 2},
365       },
366       {
367           {0, 0, 0, 1, -3, -3, 0}, // p = 3q + 3r
368       });
369 
370   // Cartesian product of a tetrahedron and a 2D cone.
371   // The tetrahedron is empty and has vertices at
372   // (1/3, 0, 0), (2/3, 0, 0), (2/3, 0, 100), and (100, 100 - 1/3, 100).
373   // The cone has apex at (10000, 10000) and
374   // edges passing through (1/3, 0) and (2/3, 0).
375   // Since the tetrahedron is empty, the Cartesian product is too.
376   checkPermutationsSample(false /* empty */, 5,
377                           {
378                               // Tetrahedron contraints:
379                               {0, 1, 0, 0, 0, 0},
380                               {0, -300, 299, 0, 0, 0},
381                               {300 * 299, -89400, -299, 0, 0, -100 * 299},
382                               {-897, 894, 0, 0, 0, 598},
383 
384                               // Triangle constraints:
385                               // 300000p - 299999q >= 100000
386                               {0, 0, 0, 300000, -299999, -100000},
387                               // -300000p + 299998q + 200000 >= 0
388                               {0, 0, 0, -300000, 299998, 200000},
389                           },
390                           {});
391 
392   // Cartesian product of same tetrahedron as above and
393   // {(p, q) : 1/3 <= p <= 2/3}.
394   checkPermutationsSample(false /* empty */, 5,
395                           {
396                               // Tetrahedron contraints:
397                               {0, 1, 0, 0, 0, 0},
398                               {0, -300, 299, 0, 0, 0},
399                               {300 * 299, -89400, -299, 0, 0, -100 * 299},
400                               {-897, 894, 0, 0, 0, 598},
401 
402                               // Second set constraints:
403                               // 3p >= 1
404                               {0, 0, 0, 3, 0, -1},
405                               // 3p <= 2
406                               {0, 0, 0, -3, 0, 2},
407                           },
408                           {});
409 
410   checkSample(true, parsePoly("(x, y, z) : (2 * x - 1 >= 0, x - y - 1 == 0, "
411                               "y - z == 0)"));
412 
413   // Regression tests for the computation of dual coefficients.
414   checkSample(false, parsePoly("(x, y, z) : ("
415                                "6*x - 4*y + 9*z + 2 >= 0,"
416                                "x + 5*y + z + 5 >= 0,"
417                                "-4*x + y + 2*z - 1 >= 0,"
418                                "-3*x - 2*y - 7*z - 1 >= 0,"
419                                "-7*x - 5*y - 9*z - 1 >= 0)"));
420   checkSample(true, parsePoly("(x, y, z) : ("
421                               "3*x + 3*y + 3 >= 0,"
422                               "-4*x - 8*y - z + 4 >= 0,"
423                               "-7*x - 4*y + z + 1 >= 0,"
424                               "2*x - 7*y - 8*z - 7 >= 0,"
425                               "9*x + 8*y - 9*z - 7 >= 0)"));
426 }
427 
TEST(IntegerPolyhedronTest,IsIntegerEmptyTest)428 TEST(IntegerPolyhedronTest, IsIntegerEmptyTest) {
429   // 1 <= 5x and 5x <= 4 (no solution).
430   EXPECT_TRUE(
431       parsePoly("(x) : (5 * x - 1 >= 0, -5 * x + 4 >= 0)").isIntegerEmpty());
432   // 1 <= 5x and 5x <= 9 (solution: x = 1).
433   EXPECT_FALSE(
434       parsePoly("(x) : (5 * x - 1 >= 0, -5 * x + 9 >= 0)").isIntegerEmpty());
435 
436   // Unbounded sets.
437   EXPECT_TRUE(parsePoly("(x,y,z) : (2 * y - 1 >= 0, -2 * y + 1 >= 0, "
438                         "2 * z - 1 >= 0, 2 * x - 1 == 0)")
439                   .isIntegerEmpty());
440 
441   EXPECT_FALSE(parsePoly("(x,y,z) : (2 * x - 1 >= 0, -3 * x + 3 >= 0, "
442                          "5 * z - 6 >= 0, -7 * z + 17 >= 0, 3 * y - 2 >= 0)")
443                    .isIntegerEmpty());
444 
445   EXPECT_FALSE(
446       parsePoly("(x,y,z) : (2 * x - 1 >= 0, x - y - 1 == 0, y - z == 0)")
447           .isIntegerEmpty());
448 
449   // IntegerPolyhedron::isEmpty() does not detect the following sets to be
450   // empty.
451 
452   // 3x + 7y = 1 and 0 <= x, y <= 10.
453   // Since x and y are non-negative, 3x + 7y can never be 1.
454   EXPECT_TRUE(parsePoly("(x,y) : (x >= 0, -x + 10 >= 0, y >= 0, -y + 10 >= 0, "
455                         "3 * x + 7 * y - 1 == 0)")
456                   .isIntegerEmpty());
457 
458   // 2x = 3y and y = x - 1 and x + y = 6z + 2 and 0 <= x, y <= 100.
459   // Substituting y = x - 1 in 3y = 2x, we obtain x = 3 and hence y = 2.
460   // Since x + y = 5 cannot be equal to 6z + 2 for any z, the set is empty.
461   EXPECT_TRUE(
462       parsePoly("(x,y,z) : (x >= 0, -x + 100 >= 0, y >= 0, -y + 100 >= 0, "
463                 "2 * x - 3 * y == 0, x - y - 1 == 0, x + y - 6 * z - 2 == 0)")
464           .isIntegerEmpty());
465 
466   // 2x = 3y and y = x - 1 + 6z and x + y = 6q + 2 and 0 <= x, y <= 100.
467   // 2x = 3y implies x is a multiple of 3 and y is even.
468   // Now y = x - 1 + 6z implies y = 2 mod 3. In fact, since y is even, we have
469   // y = 2 mod 6. Then since x = y + 1 + 6z, we have x = 3 mod 6, implying
470   // x + y = 5 mod 6, which contradicts x + y = 6q + 2, so the set is empty.
471   EXPECT_TRUE(
472       parsePoly(
473           "(x,y,z,q) : (x >= 0, -x + 100 >= 0, y >= 0, -y + 100 >= 0, "
474           "2 * x - 3 * y == 0, x - y + 6 * z - 1 == 0, x + y - 6 * q - 2 == 0)")
475           .isIntegerEmpty());
476 
477   // Set with symbols.
478   EXPECT_FALSE(parsePoly("(x)[s] : (x + s >= 0, x - s == 0)").isIntegerEmpty());
479 }
480 
TEST(IntegerPolyhedronTest,removeRedundantConstraintsTest)481 TEST(IntegerPolyhedronTest, removeRedundantConstraintsTest) {
482   IntegerPolyhedron poly =
483       parsePoly("(x) : (x - 2 >= 0, -x + 2 >= 0, x - 2 == 0)");
484   poly.removeRedundantConstraints();
485 
486   // Both inequalities are redundant given the equality. Both have been removed.
487   EXPECT_EQ(poly.getNumInequalities(), 0u);
488   EXPECT_EQ(poly.getNumEqualities(), 1u);
489 
490   IntegerPolyhedron poly2 =
491       parsePoly("(x,y) : (x - 3 >= 0, y - 2 >= 0, x - y == 0)");
492   poly2.removeRedundantConstraints();
493 
494   // The second inequality is redundant and should have been removed. The
495   // remaining inequality should be the first one.
496   EXPECT_EQ(poly2.getNumInequalities(), 1u);
497   EXPECT_THAT(poly2.getInequality(0), ElementsAre(1, 0, -3));
498   EXPECT_EQ(poly2.getNumEqualities(), 1u);
499 
500   IntegerPolyhedron poly3 =
501       parsePoly("(x,y,z) : (x - y == 0, x - z == 0, y - z == 0)");
502   poly3.removeRedundantConstraints();
503 
504   // One of the three equalities can be removed.
505   EXPECT_EQ(poly3.getNumInequalities(), 0u);
506   EXPECT_EQ(poly3.getNumEqualities(), 2u);
507 
508   IntegerPolyhedron poly4 =
509       parsePoly("(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q) : ("
510                 "b - 1 >= 0,"
511                 "-b + 500 >= 0,"
512                 "-16 * d + f >= 0,"
513                 "f - 1 >= 0,"
514                 "-f + 998 >= 0,"
515                 "16 * d - f + 15 >= 0,"
516                 "-16 * e + g >= 0,"
517                 "g - 1 >= 0,"
518                 "-g + 998 >= 0,"
519                 "16 * e - g + 15 >= 0,"
520                 "h >= 0,"
521                 "-h + 1 >= 0,"
522                 "j - 1 >= 0,"
523                 "-j + 500 >= 0,"
524                 "-f + 16 * l + 15 >= 0,"
525                 "f - 16 * l >= 0,"
526                 "-16 * m + o >= 0,"
527                 "o - 1 >= 0,"
528                 "-o + 998 >= 0,"
529                 "16 * m - o + 15 >= 0,"
530                 "p >= 0,"
531                 "-p + 1 >= 0,"
532                 "-g - h + 8 * q + 8 >= 0,"
533                 "-o - p + 8 * q + 8 >= 0,"
534                 "o + p - 8 * q - 1 >= 0,"
535                 "g + h - 8 * q - 1 >= 0,"
536                 "-f + n >= 0,"
537                 "f - n >= 0,"
538                 "k - 10 >= 0,"
539                 "-k + 10 >= 0,"
540                 "i - 13 >= 0,"
541                 "-i + 13 >= 0,"
542                 "c - 10 >= 0,"
543                 "-c + 10 >= 0,"
544                 "a - 13 >= 0,"
545                 "-a + 13 >= 0"
546                 ")");
547 
548   // The above is a large set of constraints without any redundant constraints,
549   // as verified by the Fourier-Motzkin based removeRedundantInequalities.
550   unsigned nIneq = poly4.getNumInequalities();
551   unsigned nEq = poly4.getNumEqualities();
552   poly4.removeRedundantInequalities();
553   ASSERT_EQ(poly4.getNumInequalities(), nIneq);
554   ASSERT_EQ(poly4.getNumEqualities(), nEq);
555   // Now we test that removeRedundantConstraints does not find any constraints
556   // to be redundant either.
557   poly4.removeRedundantConstraints();
558   EXPECT_EQ(poly4.getNumInequalities(), nIneq);
559   EXPECT_EQ(poly4.getNumEqualities(), nEq);
560 
561   IntegerPolyhedron poly5 = parsePoly(
562       "(x,y) : (128 * x + 127 >= 0, -x + 7 >= 0, -128 * x + y >= 0, y >= 0)");
563   // 128x + 127 >= 0  implies that 128x >= 0, since x has to be an integer.
564   // (This should be caught by GCDTightenInqualities().)
565   // So -128x + y >= 0 and 128x + 127 >= 0 imply y >= 0 since we have
566   // y >= 128x >= 0.
567   poly5.removeRedundantConstraints();
568   EXPECT_EQ(poly5.getNumInequalities(), 3u);
569   SmallVector<int64_t, 8> redundantConstraint = {0, 1, 0};
570   for (unsigned i = 0; i < 3; ++i) {
571     // Ensure that the removed constraint was the redundant constraint [3].
572     EXPECT_NE(poly5.getInequality(i), ArrayRef<int64_t>(redundantConstraint));
573   }
574 }
575 
TEST(IntegerPolyhedronTest,addConstantUpperBound)576 TEST(IntegerPolyhedronTest, addConstantUpperBound) {
577   IntegerPolyhedron poly(PresburgerSpace::getSetSpace(2));
578   poly.addBound(IntegerPolyhedron::UB, 0, 1);
579   EXPECT_EQ(poly.atIneq(0, 0), -1);
580   EXPECT_EQ(poly.atIneq(0, 1), 0);
581   EXPECT_EQ(poly.atIneq(0, 2), 1);
582 
583   poly.addBound(IntegerPolyhedron::UB, {1, 2, 3}, 1);
584   EXPECT_EQ(poly.atIneq(1, 0), -1);
585   EXPECT_EQ(poly.atIneq(1, 1), -2);
586   EXPECT_EQ(poly.atIneq(1, 2), -2);
587 }
588 
TEST(IntegerPolyhedronTest,addConstantLowerBound)589 TEST(IntegerPolyhedronTest, addConstantLowerBound) {
590   IntegerPolyhedron poly(PresburgerSpace::getSetSpace(2));
591   poly.addBound(IntegerPolyhedron::LB, 0, 1);
592   EXPECT_EQ(poly.atIneq(0, 0), 1);
593   EXPECT_EQ(poly.atIneq(0, 1), 0);
594   EXPECT_EQ(poly.atIneq(0, 2), -1);
595 
596   poly.addBound(IntegerPolyhedron::LB, {1, 2, 3}, 1);
597   EXPECT_EQ(poly.atIneq(1, 0), 1);
598   EXPECT_EQ(poly.atIneq(1, 1), 2);
599   EXPECT_EQ(poly.atIneq(1, 2), 2);
600 }
601 
602 /// Check if the expected division representation of local variables matches the
603 /// computed representation. The expected division representation is given as
604 /// a vector of expressions set in `expectedDividends` and the corressponding
605 /// denominator in `expectedDenominators`. The `denominators` and `dividends`
606 /// obtained through `getLocalRepr` function is verified against the
607 /// `expectedDenominators` and `expectedDividends` respectively.
checkDivisionRepresentation(IntegerPolyhedron & poly,const std::vector<SmallVector<int64_t,8>> & expectedDividends,ArrayRef<unsigned> expectedDenominators)608 static void checkDivisionRepresentation(
609     IntegerPolyhedron &poly,
610     const std::vector<SmallVector<int64_t, 8>> &expectedDividends,
611     ArrayRef<unsigned> expectedDenominators) {
612   DivisionRepr divs = poly.getLocalReprs();
613 
614   // Check that the `denominators` and `expectedDenominators` match.
615   EXPECT_TRUE(expectedDenominators == divs.getDenoms());
616 
617   // Check that the `dividends` and `expectedDividends` match. If the
618   // denominator for a division is zero, we ignore its dividend.
619   EXPECT_TRUE(divs.getNumDivs() == expectedDividends.size());
620   for (unsigned i = 0, e = divs.getNumDivs(); i < e; ++i) {
621     if (divs.hasRepr(i)) {
622       for (unsigned j = 0, f = divs.getNumVars() + 1; j < f; ++j) {
623         EXPECT_TRUE(expectedDividends[i][j] == divs.getDividend(i)[j]);
624       }
625     }
626   }
627 }
628 
TEST(IntegerPolyhedronTest,computeLocalReprSimple)629 TEST(IntegerPolyhedronTest, computeLocalReprSimple) {
630   IntegerPolyhedron poly(PresburgerSpace::getSetSpace(1));
631 
632   poly.addLocalFloorDiv({1, 4}, 10);
633   poly.addLocalFloorDiv({1, 0, 100}, 10);
634 
635   std::vector<SmallVector<int64_t, 8>> divisions = {{1, 0, 0, 4},
636                                                     {1, 0, 0, 100}};
637   SmallVector<unsigned, 8> denoms = {10, 10};
638 
639   // Check if floordivs can be computed when no other inequalities exist
640   // and floor divs do not depend on each other.
641   checkDivisionRepresentation(poly, divisions, denoms);
642 }
643 
TEST(IntegerPolyhedronTest,computeLocalReprConstantFloorDiv)644 TEST(IntegerPolyhedronTest, computeLocalReprConstantFloorDiv) {
645   IntegerPolyhedron poly(PresburgerSpace::getSetSpace(4));
646 
647   poly.addInequality({1, 0, 3, 1, 2});
648   poly.addInequality({1, 2, -8, 1, 10});
649   poly.addEquality({1, 2, -4, 1, 10});
650 
651   poly.addLocalFloorDiv({0, 0, 0, 0, 100}, 30);
652   poly.addLocalFloorDiv({0, 0, 0, 0, 0, 206}, 101);
653 
654   std::vector<SmallVector<int64_t, 8>> divisions = {{0, 0, 0, 0, 0, 0, 3},
655                                                     {0, 0, 0, 0, 0, 0, 2}};
656   SmallVector<unsigned, 8> denoms = {1, 1};
657 
658   // Check if floordivs with constant numerator can be computed.
659   checkDivisionRepresentation(poly, divisions, denoms);
660 }
661 
TEST(IntegerPolyhedronTest,computeLocalReprRecursive)662 TEST(IntegerPolyhedronTest, computeLocalReprRecursive) {
663   IntegerPolyhedron poly(PresburgerSpace::getSetSpace(4));
664   poly.addInequality({1, 0, 3, 1, 2});
665   poly.addInequality({1, 2, -8, 1, 10});
666   poly.addEquality({1, 2, -4, 1, 10});
667 
668   poly.addLocalFloorDiv({0, -2, 7, 2, 10}, 3);
669   poly.addLocalFloorDiv({3, 0, 9, 2, 2, 10}, 5);
670   poly.addLocalFloorDiv({0, 1, -123, 2, 0, -4, 10}, 3);
671 
672   poly.addInequality({1, 2, -2, 1, -5, 0, 6, 100});
673   poly.addInequality({1, 2, -8, 1, 3, 7, 0, -9});
674 
675   std::vector<SmallVector<int64_t, 8>> divisions = {
676       {0, -2, 7, 2, 0, 0, 0, 10},
677       {3, 0, 9, 2, 2, 0, 0, 10},
678       {0, 1, -123, 2, 0, -4, 0, 10}};
679 
680   SmallVector<unsigned, 8> denoms = {3, 5, 3};
681 
682   // Check if floordivs which may depend on other floordivs can be computed.
683   checkDivisionRepresentation(poly, divisions, denoms);
684 }
685 
TEST(IntegerPolyhedronTest,computeLocalReprTightUpperBound)686 TEST(IntegerPolyhedronTest, computeLocalReprTightUpperBound) {
687   {
688     IntegerPolyhedron poly = parsePoly("(i) : (i mod 3 - 1 >= 0)");
689 
690     // The set formed by the poly is:
691     //        3q - i + 2 >= 0             <-- Division lower bound
692     //       -3q + i - 1 >= 0
693     //       -3q + i     >= 0             <-- Division upper bound
694     // We remove redundant constraints to get the set:
695     //        3q - i + 2 >= 0             <-- Division lower bound
696     //       -3q + i - 1 >= 0             <-- Tighter division upper bound
697     // thus, making the upper bound tighter.
698     poly.removeRedundantConstraints();
699 
700     std::vector<SmallVector<int64_t, 8>> divisions = {{1, 0, 0}};
701     SmallVector<unsigned, 8> denoms = {3};
702 
703     // Check if the divisions can be computed even with a tighter upper bound.
704     checkDivisionRepresentation(poly, divisions, denoms);
705   }
706 
707   {
708     IntegerPolyhedron poly =
709         parsePoly("(i, j, q) : (4*q - i - j + 2 >= 0, -4*q + i + j >= 0)");
710     // Convert `q` to a local variable.
711     poly.convertToLocal(VarKind::SetDim, 2, 3);
712 
713     std::vector<SmallVector<int64_t, 8>> divisions = {{1, 1, 0, 1}};
714     SmallVector<unsigned, 8> denoms = {4};
715 
716     // Check if the divisions can be computed even with a tighter upper bound.
717     checkDivisionRepresentation(poly, divisions, denoms);
718   }
719 }
720 
TEST(IntegerPolyhedronTest,computeLocalReprFromEquality)721 TEST(IntegerPolyhedronTest, computeLocalReprFromEquality) {
722   {
723     IntegerPolyhedron poly = parsePoly("(i, j, q) : (-4*q + i + j == 0)");
724     // Convert `q` to a local variable.
725     poly.convertToLocal(VarKind::SetDim, 2, 3);
726 
727     std::vector<SmallVector<int64_t, 8>> divisions = {{1, 1, 0, 0}};
728     SmallVector<unsigned, 8> denoms = {4};
729 
730     checkDivisionRepresentation(poly, divisions, denoms);
731   }
732   {
733     IntegerPolyhedron poly = parsePoly("(i, j, q) : (4*q - i - j == 0)");
734     // Convert `q` to a local variable.
735     poly.convertToLocal(VarKind::SetDim, 2, 3);
736 
737     std::vector<SmallVector<int64_t, 8>> divisions = {{1, 1, 0, 0}};
738     SmallVector<unsigned, 8> denoms = {4};
739 
740     checkDivisionRepresentation(poly, divisions, denoms);
741   }
742   {
743     IntegerPolyhedron poly = parsePoly("(i, j, q) : (3*q + i + j - 2 == 0)");
744     // Convert `q` to a local variable.
745     poly.convertToLocal(VarKind::SetDim, 2, 3);
746 
747     std::vector<SmallVector<int64_t, 8>> divisions = {{-1, -1, 0, 2}};
748     SmallVector<unsigned, 8> denoms = {3};
749 
750     checkDivisionRepresentation(poly, divisions, denoms);
751   }
752 }
753 
TEST(IntegerPolyhedronTest,computeLocalReprFromEqualityAndInequality)754 TEST(IntegerPolyhedronTest, computeLocalReprFromEqualityAndInequality) {
755   {
756     IntegerPolyhedron poly =
757         parsePoly("(i, j, q, k) : (-3*k + i + j == 0, 4*q - "
758                   "i - j + 2 >= 0, -4*q + i + j >= 0)");
759     // Convert `q` and `k` to local variables.
760     poly.convertToLocal(VarKind::SetDim, 2, 4);
761 
762     std::vector<SmallVector<int64_t, 8>> divisions = {{1, 1, 0, 0, 1},
763                                                       {1, 1, 0, 0, 0}};
764     SmallVector<unsigned, 8> denoms = {4, 3};
765 
766     checkDivisionRepresentation(poly, divisions, denoms);
767   }
768 }
769 
TEST(IntegerPolyhedronTest,computeLocalReprNoRepr)770 TEST(IntegerPolyhedronTest, computeLocalReprNoRepr) {
771   IntegerPolyhedron poly =
772       parsePoly("(x, q) : (x - 3 * q >= 0, -x + 3 * q + 3 >= 0)");
773   // Convert q to a local variable.
774   poly.convertToLocal(VarKind::SetDim, 1, 2);
775 
776   std::vector<SmallVector<int64_t, 8>> divisions = {{0, 0, 0}};
777   SmallVector<unsigned, 8> denoms = {0};
778 
779   // Check that no division is computed.
780   checkDivisionRepresentation(poly, divisions, denoms);
781 }
782 
TEST(IntegerPolyhedronTest,computeLocalReprNegConstNormalize)783 TEST(IntegerPolyhedronTest, computeLocalReprNegConstNormalize) {
784   IntegerPolyhedron poly =
785       parsePoly("(x, q) : (-1 - 3*x - 6 * q >= 0, 6 + 3*x + 6*q >= 0)");
786   // Convert q to a local variable.
787   poly.convertToLocal(VarKind::SetDim, 1, 2);
788 
789   // q = floor((-1/3 - x)/2)
790   //   = floor((1/3) + (-1 - x)/2)
791   //   = floor((-1 - x)/2).
792   std::vector<SmallVector<int64_t, 8>> divisions = {{-1, 0, -1}};
793   SmallVector<unsigned, 8> denoms = {2};
794   checkDivisionRepresentation(poly, divisions, denoms);
795 }
796 
TEST(IntegerPolyhedronTest,simplifyLocalsTest)797 TEST(IntegerPolyhedronTest, simplifyLocalsTest) {
798   // (x) : (exists y: 2x + y = 1 and y = 2).
799   IntegerPolyhedron poly(PresburgerSpace::getSetSpace(1, 0, 1));
800   poly.addEquality({2, 1, -1});
801   poly.addEquality({0, 1, -2});
802 
803   EXPECT_TRUE(poly.isEmpty());
804 
805   // (x) : (exists y, z, w: 3x + y = 1 and 2y = z and 3y = w and z = w).
806   IntegerPolyhedron poly2(PresburgerSpace::getSetSpace(1, 0, 3));
807   poly2.addEquality({3, 1, 0, 0, -1});
808   poly2.addEquality({0, 2, -1, 0, 0});
809   poly2.addEquality({0, 3, 0, -1, 0});
810   poly2.addEquality({0, 0, 1, -1, 0});
811 
812   EXPECT_TRUE(poly2.isEmpty());
813 
814   // (x) : (exists y: x >= y + 1 and 2x + y = 0 and y >= -1).
815   IntegerPolyhedron poly3(PresburgerSpace::getSetSpace(1, 0, 1));
816   poly3.addInequality({1, -1, -1});
817   poly3.addInequality({0, 1, 1});
818   poly3.addEquality({2, 1, 0});
819 
820   EXPECT_TRUE(poly3.isEmpty());
821 }
822 
TEST(IntegerPolyhedronTest,mergeDivisionsSimple)823 TEST(IntegerPolyhedronTest, mergeDivisionsSimple) {
824   {
825     // (x) : (exists z, y  = [x / 2] : x = 3y and x + z + 1 >= 0).
826     IntegerPolyhedron poly1(PresburgerSpace::getSetSpace(1, 0, 1));
827     poly1.addLocalFloorDiv({1, 0, 0}, 2); // y = [x / 2].
828     poly1.addEquality({1, 0, -3, 0});     // x = 3y.
829     poly1.addInequality({1, 1, 0, 1});    // x + z + 1 >= 0.
830 
831     // (x) : (exists y = [x / 2], z : x = 5y).
832     IntegerPolyhedron poly2(PresburgerSpace::getSetSpace(1));
833     poly2.addLocalFloorDiv({1, 0}, 2); // y = [x / 2].
834     poly2.addEquality({1, -5, 0});     // x = 5y.
835     poly2.appendVar(VarKind::Local);   // Add local id z.
836 
837     poly1.mergeLocalVars(poly2);
838 
839     // Local space should be same.
840     EXPECT_EQ(poly1.getNumLocalVars(), poly2.getNumLocalVars());
841 
842     // 1 division should be matched + 2 unmatched local ids.
843     EXPECT_EQ(poly1.getNumLocalVars(), 3u);
844     EXPECT_EQ(poly2.getNumLocalVars(), 3u);
845   }
846 
847   {
848     // (x) : (exists z = [x / 5], y = [x / 2] : x = 3y).
849     IntegerPolyhedron poly1(PresburgerSpace::getSetSpace(1));
850     poly1.addLocalFloorDiv({1, 0}, 5);    // z = [x / 5].
851     poly1.addLocalFloorDiv({1, 0, 0}, 2); // y = [x / 2].
852     poly1.addEquality({1, 0, -3, 0});     // x = 3y.
853 
854     // (x) : (exists y = [x / 2], z = [x / 5]: x = 5z).
855     IntegerPolyhedron poly2(PresburgerSpace::getSetSpace(1));
856     poly2.addLocalFloorDiv({1, 0}, 2);    // y = [x / 2].
857     poly2.addLocalFloorDiv({1, 0, 0}, 5); // z = [x / 5].
858     poly2.addEquality({1, 0, -5, 0});     // x = 5z.
859 
860     poly1.mergeLocalVars(poly2);
861 
862     // Local space should be same.
863     EXPECT_EQ(poly1.getNumLocalVars(), poly2.getNumLocalVars());
864 
865     // 2 divisions should be matched.
866     EXPECT_EQ(poly1.getNumLocalVars(), 2u);
867     EXPECT_EQ(poly2.getNumLocalVars(), 2u);
868   }
869 
870   {
871     // Division Normalization test.
872     // (x) : (exists z, y  = [x / 2] : x = 3y and x + z + 1 >= 0).
873     IntegerPolyhedron poly1(PresburgerSpace::getSetSpace(1, 0, 1));
874     // This division would be normalized.
875     poly1.addLocalFloorDiv({3, 0, 0}, 6); // y = [3x / 6] -> [x/2].
876     poly1.addEquality({1, 0, -3, 0});     // x = 3z.
877     poly1.addInequality({1, 1, 0, 1});    // x + y + 1 >= 0.
878 
879     // (x) : (exists y = [x / 2], z : x = 5y).
880     IntegerPolyhedron poly2(PresburgerSpace::getSetSpace(1));
881     poly2.addLocalFloorDiv({1, 0}, 2); // y = [x / 2].
882     poly2.addEquality({1, -5, 0});     // x = 5y.
883     poly2.appendVar(VarKind::Local);   // Add local id z.
884 
885     poly1.mergeLocalVars(poly2);
886 
887     // Local space should be same.
888     EXPECT_EQ(poly1.getNumLocalVars(), poly2.getNumLocalVars());
889 
890     // One division should be matched + 2 unmatched local ids.
891     EXPECT_EQ(poly1.getNumLocalVars(), 3u);
892     EXPECT_EQ(poly2.getNumLocalVars(), 3u);
893   }
894 }
895 
TEST(IntegerPolyhedronTest,mergeDivisionsNestedDivsions)896 TEST(IntegerPolyhedronTest, mergeDivisionsNestedDivsions) {
897   {
898     // (x) : (exists y = [x / 2], z = [x + y / 3]: y + z >= x).
899     IntegerPolyhedron poly1(PresburgerSpace::getSetSpace(1));
900     poly1.addLocalFloorDiv({1, 0}, 2);    // y = [x / 2].
901     poly1.addLocalFloorDiv({1, 1, 0}, 3); // z = [x + y / 3].
902     poly1.addInequality({-1, 1, 1, 0});   // y + z >= x.
903 
904     // (x) : (exists y = [x / 2], z = [x + y / 3]: y + z <= x).
905     IntegerPolyhedron poly2(PresburgerSpace::getSetSpace(1));
906     poly2.addLocalFloorDiv({1, 0}, 2);    // y = [x / 2].
907     poly2.addLocalFloorDiv({1, 1, 0}, 3); // z = [x + y / 3].
908     poly2.addInequality({1, -1, -1, 0});  // y + z <= x.
909 
910     poly1.mergeLocalVars(poly2);
911 
912     // Local space should be same.
913     EXPECT_EQ(poly1.getNumLocalVars(), poly2.getNumLocalVars());
914 
915     // 2 divisions should be matched.
916     EXPECT_EQ(poly1.getNumLocalVars(), 2u);
917     EXPECT_EQ(poly2.getNumLocalVars(), 2u);
918   }
919 
920   {
921     // (x) : (exists y = [x / 2], z = [x + y / 3], w = [z + 1 / 5]: y + z >= x).
922     IntegerPolyhedron poly1(PresburgerSpace::getSetSpace(1));
923     poly1.addLocalFloorDiv({1, 0}, 2);       // y = [x / 2].
924     poly1.addLocalFloorDiv({1, 1, 0}, 3);    // z = [x + y / 3].
925     poly1.addLocalFloorDiv({0, 0, 1, 1}, 5); // w = [z + 1 / 5].
926     poly1.addInequality({-1, 1, 1, 0, 0});   // y + z >= x.
927 
928     // (x) : (exists y = [x / 2], z = [x + y / 3], w = [z + 1 / 5]: y + z <= x).
929     IntegerPolyhedron poly2(PresburgerSpace::getSetSpace(1));
930     poly2.addLocalFloorDiv({1, 0}, 2);       // y = [x / 2].
931     poly2.addLocalFloorDiv({1, 1, 0}, 3);    // z = [x + y / 3].
932     poly2.addLocalFloorDiv({0, 0, 1, 1}, 5); // w = [z + 1 / 5].
933     poly2.addInequality({1, -1, -1, 0, 0});  // y + z <= x.
934 
935     poly1.mergeLocalVars(poly2);
936 
937     // Local space should be same.
938     EXPECT_EQ(poly1.getNumLocalVars(), poly2.getNumLocalVars());
939 
940     // 3 divisions should be matched.
941     EXPECT_EQ(poly1.getNumLocalVars(), 3u);
942     EXPECT_EQ(poly2.getNumLocalVars(), 3u);
943   }
944   {
945     // (x) : (exists y = [x / 2], z = [x + y / 3]: y + z >= x).
946     IntegerPolyhedron poly1(PresburgerSpace::getSetSpace(1));
947     poly1.addLocalFloorDiv({2, 0}, 4);    // y = [2x / 4] -> [x / 2].
948     poly1.addLocalFloorDiv({1, 1, 0}, 3); // z = [x + y / 3].
949     poly1.addInequality({-1, 1, 1, 0});   // y + z >= x.
950 
951     // (x) : (exists y = [x / 2], z = [x + y / 3]: y + z <= x).
952     IntegerPolyhedron poly2(PresburgerSpace::getSetSpace(1));
953     poly2.addLocalFloorDiv({1, 0}, 2); // y = [x / 2].
954     // This division would be normalized.
955     poly2.addLocalFloorDiv({3, 3, 0}, 9); // z = [3x + 3y / 9] -> [x + y / 3].
956     poly2.addInequality({1, -1, -1, 0});  // y + z <= x.
957 
958     poly1.mergeLocalVars(poly2);
959 
960     // Local space should be same.
961     EXPECT_EQ(poly1.getNumLocalVars(), poly2.getNumLocalVars());
962 
963     // 2 divisions should be matched.
964     EXPECT_EQ(poly1.getNumLocalVars(), 2u);
965     EXPECT_EQ(poly2.getNumLocalVars(), 2u);
966   }
967 }
968 
TEST(IntegerPolyhedronTest,mergeDivisionsConstants)969 TEST(IntegerPolyhedronTest, mergeDivisionsConstants) {
970   {
971     // (x) : (exists y = [x + 1 / 3], z = [x + 2 / 3]: y + z >= x).
972     IntegerPolyhedron poly1(PresburgerSpace::getSetSpace(1));
973     poly1.addLocalFloorDiv({1, 1}, 2);    // y = [x + 1 / 2].
974     poly1.addLocalFloorDiv({1, 0, 2}, 3); // z = [x + 2 / 3].
975     poly1.addInequality({-1, 1, 1, 0});   // y + z >= x.
976 
977     // (x) : (exists y = [x + 1 / 3], z = [x + 2 / 3]: y + z <= x).
978     IntegerPolyhedron poly2(PresburgerSpace::getSetSpace(1));
979     poly2.addLocalFloorDiv({1, 1}, 2);    // y = [x + 1 / 2].
980     poly2.addLocalFloorDiv({1, 0, 2}, 3); // z = [x + 2 / 3].
981     poly2.addInequality({1, -1, -1, 0});  // y + z <= x.
982 
983     poly1.mergeLocalVars(poly2);
984 
985     // Local space should be same.
986     EXPECT_EQ(poly1.getNumLocalVars(), poly2.getNumLocalVars());
987 
988     // 2 divisions should be matched.
989     EXPECT_EQ(poly1.getNumLocalVars(), 2u);
990     EXPECT_EQ(poly2.getNumLocalVars(), 2u);
991   }
992   {
993     // (x) : (exists y = [x + 1 / 3], z = [x + 2 / 3]: y + z >= x).
994     IntegerPolyhedron poly1(PresburgerSpace::getSetSpace(1));
995     poly1.addLocalFloorDiv({1, 1}, 2); // y = [x + 1 / 2].
996     // Normalization test.
997     poly1.addLocalFloorDiv({3, 0, 6}, 9); // z = [3x + 6 / 9] -> [x + 2 / 3].
998     poly1.addInequality({-1, 1, 1, 0});   // y + z >= x.
999 
1000     // (x) : (exists y = [x + 1 / 3], z = [x + 2 / 3]: y + z <= x).
1001     IntegerPolyhedron poly2(PresburgerSpace::getSetSpace(1));
1002     // Normalization test.
1003     poly2.addLocalFloorDiv({2, 2}, 4);    // y = [2x + 2 / 4] -> [x + 1 / 2].
1004     poly2.addLocalFloorDiv({1, 0, 2}, 3); // z = [x + 2 / 3].
1005     poly2.addInequality({1, -1, -1, 0});  // y + z <= x.
1006 
1007     poly1.mergeLocalVars(poly2);
1008 
1009     // Local space should be same.
1010     EXPECT_EQ(poly1.getNumLocalVars(), poly2.getNumLocalVars());
1011 
1012     // 2 divisions should be matched.
1013     EXPECT_EQ(poly1.getNumLocalVars(), 2u);
1014     EXPECT_EQ(poly2.getNumLocalVars(), 2u);
1015   }
1016 }
1017 
TEST(IntegerPolyhedronTest,mergeDivisionsDuplicateInSameSet)1018 TEST(IntegerPolyhedronTest, mergeDivisionsDuplicateInSameSet) {
1019   // (x) : (exists y = [x + 1 / 3], z = [x + 1 / 3]: y + z >= x).
1020   IntegerPolyhedron poly1(PresburgerSpace::getSetSpace(1));
1021   poly1.addLocalFloorDiv({1, 1}, 3);    // y = [x + 1 / 2].
1022   poly1.addLocalFloorDiv({1, 0, 1}, 3); // z = [x + 1 / 3].
1023   poly1.addInequality({-1, 1, 1, 0});   // y + z >= x.
1024 
1025   // (x) : (exists y = [x + 1 / 3], z = [x + 2 / 3]: y + z <= x).
1026   IntegerPolyhedron poly2(PresburgerSpace::getSetSpace(1));
1027   poly2.addLocalFloorDiv({1, 1}, 3);    // y = [x + 1 / 3].
1028   poly2.addLocalFloorDiv({1, 0, 2}, 3); // z = [x + 2 / 3].
1029   poly2.addInequality({1, -1, -1, 0});  // y + z <= x.
1030 
1031   poly1.mergeLocalVars(poly2);
1032 
1033   // Local space should be same.
1034   EXPECT_EQ(poly1.getNumLocalVars(), poly2.getNumLocalVars());
1035 
1036   // 1 divisions should be matched.
1037   EXPECT_EQ(poly1.getNumLocalVars(), 3u);
1038   EXPECT_EQ(poly2.getNumLocalVars(), 3u);
1039 }
1040 
TEST(IntegerPolyhedronTest,negativeDividends)1041 TEST(IntegerPolyhedronTest, negativeDividends) {
1042   // (x) : (exists y = [-x + 1 / 2], z = [-x - 2 / 3]: y + z >= x).
1043   IntegerPolyhedron poly1(PresburgerSpace::getSetSpace(1));
1044   poly1.addLocalFloorDiv({-1, 1}, 2); // y = [x + 1 / 2].
1045   // Normalization test with negative dividends
1046   poly1.addLocalFloorDiv({-3, 0, -6}, 9); // z = [3x + 6 / 9] -> [x + 2 / 3].
1047   poly1.addInequality({-1, 1, 1, 0});     // y + z >= x.
1048 
1049   // (x) : (exists y = [x + 1 / 3], z = [x + 2 / 3]: y + z <= x).
1050   IntegerPolyhedron poly2(PresburgerSpace::getSetSpace(1));
1051   // Normalization test.
1052   poly2.addLocalFloorDiv({-2, 2}, 4);     // y = [-2x + 2 / 4] -> [-x + 1 / 2].
1053   poly2.addLocalFloorDiv({-1, 0, -2}, 3); // z = [-x - 2 / 3].
1054   poly2.addInequality({1, -1, -1, 0});    // y + z <= x.
1055 
1056   poly1.mergeLocalVars(poly2);
1057 
1058   // Merging triggers normalization.
1059   std::vector<SmallVector<int64_t, 8>> divisions = {{-1, 0, 0, 1},
1060                                                     {-1, 0, 0, -2}};
1061   SmallVector<unsigned, 8> denoms = {2, 3};
1062   checkDivisionRepresentation(poly1, divisions, denoms);
1063 }
1064 
expectRationalLexMin(const IntegerPolyhedron & poly,ArrayRef<Fraction> min)1065 void expectRationalLexMin(const IntegerPolyhedron &poly,
1066                           ArrayRef<Fraction> min) {
1067   auto lexMin = poly.findRationalLexMin();
1068   ASSERT_TRUE(lexMin.isBounded());
1069   EXPECT_EQ(ArrayRef<Fraction>(*lexMin), min);
1070 }
1071 
expectNoRationalLexMin(OptimumKind kind,const IntegerPolyhedron & poly)1072 void expectNoRationalLexMin(OptimumKind kind, const IntegerPolyhedron &poly) {
1073   ASSERT_NE(kind, OptimumKind::Bounded)
1074       << "Use expectRationalLexMin for bounded min";
1075   EXPECT_EQ(poly.findRationalLexMin().getKind(), kind);
1076 }
1077 
TEST(IntegerPolyhedronTest,findRationalLexMin)1078 TEST(IntegerPolyhedronTest, findRationalLexMin) {
1079   expectRationalLexMin(
1080       parsePoly("(x, y, z) : (x + 10 >= 0, y + 40 >= 0, z + 30 >= 0)"),
1081       {{-10, 1}, {-40, 1}, {-30, 1}});
1082   expectRationalLexMin(
1083       parsePoly(
1084           "(x, y, z) : (2*x + 7 >= 0, 3*y - 5 >= 0, 8*z + 10 >= 0, 9*z >= 0)"),
1085       {{-7, 2}, {5, 3}, {0, 1}});
1086   expectRationalLexMin(parsePoly("(x, y) : (3*x + 2*y + 10 >= 0, -3*y + 10 >= "
1087                                  "0, 4*x - 7*y - 10 >= 0)"),
1088                        {{-50, 29}, {-70, 29}});
1089 
1090   // Test with some locals. This is basically x >= 11, 0 <= x - 2e <= 1.
1091   // It'll just choose x = 11, e = 5.5 since it's rational lexmin.
1092   expectRationalLexMin(
1093       parsePoly(
1094           "(x, y) : (x - 2*(x floordiv 2) == 0, y - 2*x >= 0, x - 11 >= 0)"),
1095       {{11, 1}, {22, 1}});
1096 
1097   expectRationalLexMin(parsePoly("(x, y) : (3*x + 2*y + 10 >= 0,"
1098                                  "-4*x + 7*y + 10 >= 0, -3*y + 10 >= 0)"),
1099                        {{-50, 9}, {10, 3}});
1100 
1101   // Cartesian product of above with itself.
1102   expectRationalLexMin(
1103       parsePoly("(x, y, z, w) : (3*x + 2*y + 10 >= 0, -4*x + 7*y + 10 >= 0,"
1104                 "-3*y + 10 >= 0, 3*z + 2*w + 10 >= 0, -4*z + 7*w + 10 >= 0,"
1105                 "-3*w + 10 >= 0)"),
1106       {{-50, 9}, {10, 3}, {-50, 9}, {10, 3}});
1107 
1108   // Same as above but for the constraints on z and w, we express "10" in terms
1109   // of x and y. We know that x and y still have to take the values
1110   // -50/9 and 10/3 since their constraints are the same and their values are
1111   // minimized first. Accordingly, the values -9x - 12y,  -9x - 0y - 10,
1112   // and -9x - 15y + 10 are all equal to 10.
1113   expectRationalLexMin(
1114       parsePoly(
1115           "(x, y, z, w) : (3*x + 2*y + 10 >= 0, -4*x + 7*y + 10 >= 0, "
1116           "-3*y + 10 >= 0, 3*z + 2*w - 9*x - 12*y >= 0,"
1117           "-4*z + 7*w + - 9*x - 9*y - 10 >= 0, -3*w - 9*x - 15*y + 10 >= 0)"),
1118       {{-50, 9}, {10, 3}, {-50, 9}, {10, 3}});
1119 
1120   // Same as above with one constraint removed, making the lexmin unbounded.
1121   expectNoRationalLexMin(
1122       OptimumKind::Unbounded,
1123       parsePoly("(x, y, z, w) : (3*x + 2*y + 10 >= 0, -4*x + 7*y + 10 >= 0,"
1124                 "-3*y + 10 >= 0, 3*z + 2*w - 9*x - 12*y >= 0,"
1125                 "-4*z + 7*w + - 9*x - 9*y - 10>= 0)"));
1126 
1127   // Again, the lexmin is unbounded.
1128   expectNoRationalLexMin(
1129       OptimumKind::Unbounded,
1130       parsePoly("(x, y, z) : (2*x + 5*y + 8*z - 10 >= 0,"
1131                 "2*x + 10*y + 8*z - 10 >= 0, 2*x + 5*y + 10*z - 10 >= 0)"));
1132 
1133   // The set is empty.
1134   expectNoRationalLexMin(OptimumKind::Empty,
1135                          parsePoly("(x) : (2*x >= 0, -x - 1 >= 0)"));
1136 }
1137 
expectIntegerLexMin(const IntegerPolyhedron & poly,ArrayRef<int64_t> min)1138 void expectIntegerLexMin(const IntegerPolyhedron &poly, ArrayRef<int64_t> min) {
1139   auto lexMin = poly.findIntegerLexMin();
1140   ASSERT_TRUE(lexMin.isBounded());
1141   EXPECT_EQ(ArrayRef<int64_t>(*lexMin), min);
1142 }
1143 
expectNoIntegerLexMin(OptimumKind kind,const IntegerPolyhedron & poly)1144 void expectNoIntegerLexMin(OptimumKind kind, const IntegerPolyhedron &poly) {
1145   ASSERT_NE(kind, OptimumKind::Bounded)
1146       << "Use expectRationalLexMin for bounded min";
1147   EXPECT_EQ(poly.findRationalLexMin().getKind(), kind);
1148 }
1149 
TEST(IntegerPolyhedronTest,findIntegerLexMin)1150 TEST(IntegerPolyhedronTest, findIntegerLexMin) {
1151   expectIntegerLexMin(parsePoly("(x, y, z) : (2*x + 13 >= 0, 4*y - 3*x - 2  >= "
1152                                 "0, 11*z + 5*y - 3*x + 7 >= 0)"),
1153                       {-6, -4, 0});
1154   // Similar to above but no lower bound on z.
1155   expectNoIntegerLexMin(OptimumKind::Unbounded,
1156                         parsePoly("(x, y, z) : (2*x + 13 >= 0, 4*y - 3*x - 2  "
1157                                   ">= 0, -11*z + 5*y - 3*x + 7 >= 0)"));
1158 }
1159 
expectSymbolicIntegerLexMin(StringRef polyStr,ArrayRef<std::pair<StringRef,SmallVector<SmallVector<int64_t,8>,8>>> expectedLexminRepr,ArrayRef<StringRef> expectedUnboundedDomainRepr)1160 void expectSymbolicIntegerLexMin(
1161     StringRef polyStr,
1162     ArrayRef<std::pair<StringRef, SmallVector<SmallVector<int64_t, 8>, 8>>>
1163         expectedLexminRepr,
1164     ArrayRef<StringRef> expectedUnboundedDomainRepr) {
1165   IntegerPolyhedron poly = parsePoly(polyStr);
1166 
1167   ASSERT_NE(poly.getNumDimVars(), 0u);
1168   ASSERT_NE(poly.getNumSymbolVars(), 0u);
1169 
1170   PWMAFunction expectedLexmin =
1171       parsePWMAF(/*numInputs=*/poly.getNumSymbolVars(),
1172                  /*numOutputs=*/poly.getNumDimVars(), expectedLexminRepr,
1173                  /*numSymbols=*/poly.getNumSymbolVars());
1174 
1175   PresburgerSet expectedUnboundedDomain = parsePresburgerSetFromPolyStrings(
1176       /*numDims=*/0, expectedUnboundedDomainRepr, poly.getNumSymbolVars());
1177 
1178   SymbolicLexMin result = poly.findSymbolicIntegerLexMin();
1179 
1180   EXPECT_TRUE(result.lexmin.isEqual(expectedLexmin));
1181   if (!result.lexmin.isEqual(expectedLexmin)) {
1182     llvm::errs() << "got:\n";
1183     result.lexmin.dump();
1184     llvm::errs() << "expected:\n";
1185     expectedLexmin.dump();
1186   }
1187 
1188   EXPECT_TRUE(result.unboundedDomain.isEqual(expectedUnboundedDomain));
1189   if (!result.unboundedDomain.isEqual(expectedUnboundedDomain))
1190     result.unboundedDomain.dump();
1191 }
1192 
expectSymbolicIntegerLexMin(StringRef polyStr,ArrayRef<std::pair<StringRef,SmallVector<SmallVector<int64_t,8>,8>>> result)1193 void expectSymbolicIntegerLexMin(
1194     StringRef polyStr,
1195     ArrayRef<std::pair<StringRef, SmallVector<SmallVector<int64_t, 8>, 8>>>
1196         result) {
1197   expectSymbolicIntegerLexMin(polyStr, result, {});
1198 }
1199 
TEST(IntegerPolyhedronTest,findSymbolicIntegerLexMin)1200 TEST(IntegerPolyhedronTest, findSymbolicIntegerLexMin) {
1201   expectSymbolicIntegerLexMin("(x)[a] : (x - a >= 0)",
1202                               {
1203                                   {"()[a] : ()", {{1, 0}}}, // a
1204                               });
1205 
1206   expectSymbolicIntegerLexMin(
1207       "(x)[a, b] : (x - a >= 0, x - b >= 0)",
1208       {
1209           {"()[a, b] : (a - b >= 0)", {{1, 0, 0}}},     // a
1210           {"()[a, b] : (b - a - 1 >= 0)", {{0, 1, 0}}}, // b
1211       });
1212 
1213   expectSymbolicIntegerLexMin(
1214       "(x)[a, b, c] : (x -a >= 0, x - b >= 0, x - c >= 0)",
1215       {
1216           {"()[a, b, c] : (a - b >= 0, a - c >= 0)", {{1, 0, 0, 0}}},     // a
1217           {"()[a, b, c] : (b - a - 1 >= 0, b - c >= 0)", {{0, 1, 0, 0}}}, // b
1218           {"()[a, b, c] : (c - a - 1 >= 0, c - b - 1 >= 0)",
1219            {{0, 0, 1, 0}}}, // c
1220       });
1221 
1222   expectSymbolicIntegerLexMin("(x, y)[a] : (x - a >= 0, x + y >= 0)",
1223                               {
1224                                   {"()[a] : ()", {{1, 0}, {-1, 0}}}, // (a, -a)
1225                               });
1226 
1227   expectSymbolicIntegerLexMin(
1228       "(x, y)[a] : (x - a >= 0, x + y >= 0, y >= 0)",
1229       {
1230           {"()[a] : (a >= 0)", {{1, 0}, {0, 0}}},       // (a, 0)
1231           {"()[a] : (-a - 1 >= 0)", {{1, 0}, {-1, 0}}}, // (a, -a)
1232       });
1233 
1234   expectSymbolicIntegerLexMin(
1235       "(x, y)[a, b, c] : (x - a >= 0, y - b >= 0, c - x - y >= 0)",
1236       {
1237           {"()[a, b, c] : (c - a - b >= 0)",
1238            {{1, 0, 0, 0}, {0, 1, 0, 0}}}, // (a, b)
1239       });
1240 
1241   expectSymbolicIntegerLexMin(
1242       "(x, y, z)[a, b, c] : (c - z >= 0, b - y >= 0, x + y + z - a == 0)",
1243       {
1244           {"()[a, b, c] : ()",
1245            {{1, -1, -1, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}}}, // (a - b - c, b, c)
1246       });
1247 
1248   expectSymbolicIntegerLexMin(
1249       "(x)[a, b] : (a >= 0, b >= 0, x >= 0, a + b + x - 1 >= 0)",
1250       {
1251           {"()[a, b] : (a >= 0, b >= 0, a + b - 1 >= 0)", {{0, 0, 0}}}, // 0
1252           {"()[a, b] : (a == 0, b == 0)", {{0, 0, 1}}},                 // 1
1253       });
1254 
1255   expectSymbolicIntegerLexMin(
1256       "(x)[a, b] : (1 - a >= 0, a >= 0, 1 - b >= 0, b >= 0, 1 - x >= 0, x >= "
1257       "0, a + b + x - 1 >= 0)",
1258       {
1259           {"()[a, b] : (1 - a >= 0, a >= 0, 1 - b >= 0, b >= 0, a + b - 1 >= "
1260            "0)",
1261            {{0, 0, 0}}},                                // 0
1262           {"()[a, b] : (a == 0, b == 0)", {{0, 0, 1}}}, // 1
1263       });
1264 
1265   expectSymbolicIntegerLexMin(
1266       "(x, y, z)[a, b] : (x - a == 0, y - b == 0, x >= 0, y >= 0, z >= 0, x + "
1267       "y + z - 1 >= 0)",
1268       {
1269           {"()[a, b] : (a >= 0, b >= 0, 1 - a - b >= 0)",
1270            {{1, 0, 0}, {0, 1, 0}, {-1, -1, 1}}}, // (a, b, 1 - a - b)
1271           {"()[a, b] : (a >= 0, b >= 0, a + b - 2 >= 0)",
1272            {{1, 0, 0}, {0, 1, 0}, {0, 0, 0}}}, // (a, b, 0)
1273       });
1274 
1275   expectSymbolicIntegerLexMin("(x)[a, b] : (x - a == 0, x - b >= 0)",
1276                               {
1277                                   {"()[a, b] : (a - b >= 0)", {{1, 0, 0}}}, // a
1278                               });
1279 
1280   expectSymbolicIntegerLexMin(
1281       "(q)[a] : (a - 1 - 3*q == 0, q >= 0)",
1282       {
1283           {"()[a] : (a - 1 - 3*(a floordiv 3) == 0, a >= 0)",
1284            {{0, 1, 0}}}, // a floordiv 3
1285       });
1286 
1287   expectSymbolicIntegerLexMin(
1288       "(r, q)[a] : (a - r - 3*q == 0, q >= 0, 1 - r >= 0, r >= 0)",
1289       {
1290           {"()[a] : (a - 0 - 3*(a floordiv 3) == 0, a >= 0)",
1291            {{0, 0, 0}, {0, 1, 0}}}, // (0, a floordiv 3)
1292           {"()[a] : (a - 1 - 3*(a floordiv 3) == 0, a >= 0)",
1293            {{0, 0, 1}, {0, 1, 0}}}, // (1 a floordiv 3)
1294       });
1295 
1296   expectSymbolicIntegerLexMin(
1297       "(r, q)[a] : (a - r - 3*q == 0, q >= 0, 2 - r >= 0, r - 1 >= 0)",
1298       {
1299           {"()[a] : (a - 1 - 3*(a floordiv 3) == 0, a >= 0)",
1300            {{0, 0, 1}, {0, 1, 0}}}, // (1, a floordiv 3)
1301           {"()[a] : (a - 2 - 3*(a floordiv 3) == 0, a >= 0)",
1302            {{0, 0, 2}, {0, 1, 0}}}, // (2, a floordiv 3)
1303       });
1304 
1305   expectSymbolicIntegerLexMin(
1306       "(r, q)[a] : (a - r - 3*q == 0, q >= 0, r >= 0)",
1307       {
1308           {"()[a] : (a - 3*(a floordiv 3) == 0, a >= 0)",
1309            {{0, 0, 0}, {0, 1, 0}}}, // (0, a floordiv 3)
1310           {"()[a] : (a - 1 - 3*(a floordiv 3) == 0, a >= 0)",
1311            {{0, 0, 1}, {0, 1, 0}}}, // (1, a floordiv 3)
1312           {"()[a] : (a - 2 - 3*(a floordiv 3) == 0, a >= 0)",
1313            {{0, 0, 2}, {0, 1, 0}}}, // (2, a floordiv 3)
1314       });
1315 
1316   expectSymbolicIntegerLexMin(
1317       "(x, y, z, w)[g] : ("
1318       // x, y, z, w are boolean variables.
1319       "1 - x >= 0, x >= 0, 1 - y >= 0, y >= 0,"
1320       "1 - z >= 0, z >= 0, 1 - w >= 0, w >= 0,"
1321       // We have some constraints on them:
1322       "x + y + z - 1 >= 0,"             // x or y or z
1323       "x + y + w - 1 >= 0,"             // x or y or w
1324       "1 - x + 1 - y + 1 - w - 1 >= 0," // ~x or ~y or ~w
1325       // What's the lexmin solution using exactly g true vars?
1326       "g - x - y - z - w == 0)",
1327       {
1328           {"()[g] : (g - 1 == 0)",
1329            {{0, 0}, {0, 1}, {0, 0}, {0, 0}}}, // (0, 1, 0, 0)
1330           {"()[g] : (g - 2 == 0)",
1331            {{0, 0}, {0, 0}, {0, 1}, {0, 1}}}, // (0, 0, 1, 1)
1332           {"()[g] : (g - 3 == 0)",
1333            {{0, 0}, {0, 1}, {0, 1}, {0, 1}}}, // (0, 1, 1, 1)
1334       });
1335 
1336   // Bezout's lemma: if a, b are constants,
1337   // the set of values that ax + by can take is all multiples of gcd(a, b).
1338   expectSymbolicIntegerLexMin(
1339       // If (x, y) is a solution for a given [a, r], then so is (x - 5, y + 2).
1340       // So the lexmin is unbounded if it exists.
1341       "(x, y)[a, r] : (a >= 0, r - a + 14*x + 35*y == 0)", {},
1342       // According to Bezout's lemma, 14x + 35y can take on all multiples
1343       // of 7 and no other values. So the solution exists iff r - a is a
1344       // multiple of 7.
1345       {"()[a, r] : (a >= 0, r - a - 7*((r - a) floordiv 7) == 0)"});
1346 
1347   // The lexmins are unbounded.
1348   expectSymbolicIntegerLexMin("(x, y)[a] : (9*x - 4*y - 2*a >= 0)", {},
1349                               {"()[a] : ()"});
1350 
1351   // Test cases adapted from isl.
1352   expectSymbolicIntegerLexMin(
1353       // a = 2b - 2(c - b), c - b >= 0.
1354       // So b is minimized when c = b.
1355       "(b, c)[a] : (a - 4*b + 2*c == 0, c - b >= 0)",
1356       {
1357           {"()[a] : (a - 2*(a floordiv 2) == 0)",
1358            {{0, 1, 0}, {0, 1, 0}}}, // (a floordiv 2, a floordiv 2)
1359       });
1360 
1361   expectSymbolicIntegerLexMin(
1362       // 0 <= b <= 255, 1 <= a - 512b <= 509,
1363       // b + 8 >= 1 + 16*(b + 8 floordiv 16) // i.e. b % 16 != 8
1364       "(b)[a] : (255 - b >= 0, b >= 0, a - 512*b - 1 >= 0, 512*b -a + 509 >= "
1365       "0, b + 7 - 16*((8 + b) floordiv 16) >= 0)",
1366       {
1367           {"()[a] : (255 - (a floordiv 512) >= 0, a >= 0, a - 512*(a floordiv "
1368            "512) - 1 >= 0, 512*(a floordiv 512) - a + 509 >= 0, (a floordiv "
1369            "512) + 7 - 16*((8 + (a floordiv 512)) floordiv 16) >= 0)",
1370            {{0, 1, 0, 0}}}, // (a floordiv 2, a floordiv 2)
1371       });
1372 
1373   expectSymbolicIntegerLexMin(
1374       "(a, b)[K, N, x, y] : (N - K - 2 >= 0, K + 4 - N >= 0, x - 4 >= 0, x + 6 "
1375       "- 2*N >= 0, K+N - x - 1 >= 0, a - N + 1 >= 0, K+N-1-a >= 0,a + 6 - b - "
1376       "N >= 0, 2*N - 4 - a >= 0,"
1377       "2*N - 3*K + a - b >= 0, 4*N - K + 1 - 3*b >= 0, b - N >= 0, a - x - 1 "
1378       ">= 0)",
1379       {{
1380           "()[K, N, x, y] : (x + 6 - 2*N >= 0, 2*N - 5 - x >= 0, x + 1 -3*K + "
1381           "N "
1382           ">= 0, N + K - 2 - x >= 0, x - 4 >= 0)",
1383           {{0, 0, 1, 0, 1}, {0, 1, 0, 0, 0}} // (1 + x, N)
1384       }});
1385 }
1386 
1387 static void
expectComputedVolumeIsValidOverapprox(const IntegerPolyhedron & poly,Optional<uint64_t> trueVolume,Optional<uint64_t> resultBound)1388 expectComputedVolumeIsValidOverapprox(const IntegerPolyhedron &poly,
1389                                       Optional<uint64_t> trueVolume,
1390                                       Optional<uint64_t> resultBound) {
1391   expectComputedVolumeIsValidOverapprox(poly.computeVolume(), trueVolume,
1392                                         resultBound);
1393 }
1394 
TEST(IntegerPolyhedronTest,computeVolume)1395 TEST(IntegerPolyhedronTest, computeVolume) {
1396   // 0 <= x <= 3 + 1/3, -5.5 <= y <= 2 + 3/5, 3 <= z <= 1.75.
1397   // i.e. 0 <= x <= 3, -5 <= y <= 2, 3 <= z <= 3 + 1/4.
1398   // So volume is 4 * 8 * 1 = 32.
1399   expectComputedVolumeIsValidOverapprox(
1400       parsePoly("(x, y, z) : (x >= 0, -3*x + 10 >= 0, 2*y + 11 >= 0,"
1401                 "-5*y + 13 >= 0, z - 3 >= 0, -4*z + 13 >= 0)"),
1402       /*trueVolume=*/32ull, /*resultBound=*/32ull);
1403 
1404   // Same as above but y has bounds 2 + 1/5 <= y <= 2 + 3/5. So the volume is
1405   // zero.
1406   expectComputedVolumeIsValidOverapprox(
1407       parsePoly("(x, y, z) : (x >= 0, -3*x + 10 >= 0, 5*y - 11 >= 0,"
1408                 "-5*y + 13 >= 0, z - 3 >= 0, -4*z + 13 >= 0)"),
1409       /*trueVolume=*/0ull, /*resultBound=*/0ull);
1410 
1411   // Now x is unbounded below but y still has no integer values.
1412   expectComputedVolumeIsValidOverapprox(
1413       parsePoly("(x, y, z) : (-3*x + 10 >= 0, 5*y - 11 >= 0,"
1414                 "-5*y + 13 >= 0, z - 3 >= 0, -4*z + 13 >= 0)"),
1415       /*trueVolume=*/0ull, /*resultBound=*/0ull);
1416 
1417   // A diamond shape, 0 <= x + y <= 10, 0 <= x - y <= 10,
1418   // with vertices at (0, 0), (5, 5), (5, 5), (10, 0).
1419   // x and y can take 11 possible values so result computed is 11*11 = 121.
1420   expectComputedVolumeIsValidOverapprox(
1421       parsePoly("(x, y) : (x + y >= 0, -x - y + 10 >= 0, x - y >= 0,"
1422                 "-x + y + 10 >= 0)"),
1423       /*trueVolume=*/61ull, /*resultBound=*/121ull);
1424 
1425   // Effectively the same diamond as above; constrain the variables to be even
1426   // and double the constant terms of the constraints. The algorithm can't
1427   // eliminate locals exactly, so the result is an overapproximation by
1428   // computing that x and y can take 21 possible values so result is 21*21 =
1429   // 441.
1430   expectComputedVolumeIsValidOverapprox(
1431       parsePoly("(x, y) : (x + y >= 0, -x - y + 20 >= 0, x - y >= 0,"
1432                 " -x + y + 20 >= 0, x - 2*(x floordiv 2) == 0,"
1433                 "y - 2*(y floordiv 2) == 0)"),
1434       /*trueVolume=*/61ull, /*resultBound=*/441ull);
1435 
1436   // Unbounded polytope.
1437   expectComputedVolumeIsValidOverapprox(
1438       parsePoly("(x, y) : (2*x - y >= 0, y - 3*x >= 0)"),
1439       /*trueVolume=*/{}, /*resultBound=*/{});
1440 }
1441 
TEST(IntegerPolyhedronTest,containsPointNoLocal)1442 TEST(IntegerPolyhedronTest, containsPointNoLocal) {
1443   IntegerPolyhedron poly1 = parsePoly("(x) : ((x floordiv 2) - x == 0)");
1444   EXPECT_TRUE(poly1.containsPointNoLocal({0}));
1445   EXPECT_FALSE(poly1.containsPointNoLocal({1}));
1446 
1447   IntegerPolyhedron poly2 = parsePoly(
1448       "(x) : (x - 2*(x floordiv 2) == 0, x - 4*(x floordiv 4) - 2 == 0)");
1449   EXPECT_TRUE(poly2.containsPointNoLocal({6}));
1450   EXPECT_FALSE(poly2.containsPointNoLocal({4}));
1451 
1452   IntegerPolyhedron poly3 = parsePoly("(x, y) : (2*x - y >= 0, y - 3*x >= 0)");
1453   EXPECT_TRUE(poly3.containsPointNoLocal({0, 0}));
1454   EXPECT_FALSE(poly3.containsPointNoLocal({1, 0}));
1455 }
1456 
TEST(IntegerPolyhedronTest,truncateEqualityRegressionTest)1457 TEST(IntegerPolyhedronTest, truncateEqualityRegressionTest) {
1458   // IntegerRelation::truncate was truncating inequalities to the number of
1459   // equalities.
1460   IntegerRelation set(PresburgerSpace::getSetSpace(1));
1461   IntegerRelation::CountsSnapshot snapshot = set.getCounts();
1462   set.addEquality({1, 0});
1463   set.truncate(snapshot);
1464   EXPECT_EQ(set.getNumEqualities(), 0u);
1465 }
1466