1 //===- PresburgerRelation.cpp - MLIR PresburgerRelation 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/PresburgerRelation.h"
10 #include "mlir/Analysis/Presburger/Simplex.h"
11 #include "mlir/Analysis/Presburger/Utils.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/ScopeExit.h"
14 #include "llvm/ADT/SmallBitVector.h"
15 
16 using namespace mlir;
17 using namespace presburger;
18 
19 PresburgerRelation::PresburgerRelation(const IntegerRelation &disjunct)
20     : space(disjunct.getSpaceWithoutLocals()) {
21   unionInPlace(disjunct);
22 }
23 
24 unsigned PresburgerRelation::getNumDisjuncts() const {
25   return disjuncts.size();
26 }
27 
28 ArrayRef<IntegerRelation> PresburgerRelation::getAllDisjuncts() const {
29   return disjuncts;
30 }
31 
32 const IntegerRelation &PresburgerRelation::getDisjunct(unsigned index) const {
33   assert(index < disjuncts.size() && "index out of bounds!");
34   return disjuncts[index];
35 }
36 
37 /// Mutate this set, turning it into the union of this set and the given
38 /// IntegerRelation.
39 void PresburgerRelation::unionInPlace(const IntegerRelation &disjunct) {
40   assert(space.isCompatible(disjunct.getSpace()) && "Spaces should match");
41   disjuncts.push_back(disjunct);
42 }
43 
44 /// Mutate this set, turning it into the union of this set and the given set.
45 ///
46 /// This is accomplished by simply adding all the disjuncts of the given set
47 /// to this set.
48 void PresburgerRelation::unionInPlace(const PresburgerRelation &set) {
49   assert(space.isCompatible(set.getSpace()) && "Spaces should match");
50   for (const IntegerRelation &disjunct : set.disjuncts)
51     unionInPlace(disjunct);
52 }
53 
54 /// Return the union of this set and the given set.
55 PresburgerRelation
56 PresburgerRelation::unionSet(const PresburgerRelation &set) const {
57   assert(space.isCompatible(set.getSpace()) && "Spaces should match");
58   PresburgerRelation result = *this;
59   result.unionInPlace(set);
60   return result;
61 }
62 
63 /// A point is contained in the union iff any of the parts contain the point.
64 bool PresburgerRelation::containsPoint(ArrayRef<int64_t> point) const {
65   return llvm::any_of(disjuncts, [&](const IntegerRelation &disjunct) {
66     return (disjunct.containsPoint(point));
67   });
68 }
69 
70 PresburgerRelation
71 PresburgerRelation::getUniverse(const PresburgerSpace &space) {
72   PresburgerRelation result(space);
73   result.unionInPlace(IntegerRelation::getUniverse(space));
74   return result;
75 }
76 
77 PresburgerRelation PresburgerRelation::getEmpty(const PresburgerSpace &space) {
78   return PresburgerRelation(space);
79 }
80 
81 // Return the intersection of this set with the given set.
82 //
83 // We directly compute (S_1 or S_2 ...) and (T_1 or T_2 ...)
84 // as (S_1 and T_1) or (S_1 and T_2) or ...
85 //
86 // If S_i or T_j have local variables, then S_i and T_j contains the local
87 // variables of both.
88 PresburgerRelation
89 PresburgerRelation::intersect(const PresburgerRelation &set) const {
90   assert(space.isCompatible(set.getSpace()) && "Spaces should match");
91 
92   PresburgerRelation result(getSpace());
93   for (const IntegerRelation &csA : disjuncts) {
94     for (const IntegerRelation &csB : set.disjuncts) {
95       IntegerRelation intersection = csA.intersect(csB);
96       if (!intersection.isEmpty())
97         result.unionInPlace(intersection);
98     }
99   }
100   return result;
101 }
102 
103 /// Return the coefficients of the ineq in `rel` specified by  `idx`.
104 /// `idx` can refer not only to an actual inequality of `rel`, but also
105 /// to either of the inequalities that make up an equality in `rel`.
106 ///
107 /// When 0 <= idx < rel.getNumInequalities(), this returns the coeffs of the
108 /// idx-th inequality of `rel`.
109 ///
110 /// Otherwise, it is then considered to index into the ineqs corresponding to
111 /// eqs of `rel`, and it must hold that
112 ///
113 /// 0 <= idx - rel.getNumInequalities() < 2*getNumEqualities().
114 ///
115 /// For every eq `coeffs == 0` there are two possible ineqs to index into.
116 /// The first is coeffs >= 0 and the second is coeffs <= 0.
117 static SmallVector<int64_t, 8> getIneqCoeffsFromIdx(const IntegerRelation &rel,
118                                                     unsigned idx) {
119   assert(idx < rel.getNumInequalities() + 2 * rel.getNumEqualities() &&
120          "idx out of bounds!");
121   if (idx < rel.getNumInequalities())
122     return llvm::to_vector<8>(rel.getInequality(idx));
123 
124   idx -= rel.getNumInequalities();
125   ArrayRef<int64_t> eqCoeffs = rel.getEquality(idx / 2);
126 
127   if (idx % 2 == 0)
128     return llvm::to_vector<8>(eqCoeffs);
129   return getNegatedCoeffs(eqCoeffs);
130 }
131 
132 /// Return the set difference b \ s.
133 ///
134 /// In the following, U denotes union, /\ denotes intersection, \ denotes set
135 /// difference and ~ denotes complement.
136 ///
137 /// Let s = (U_i s_i). We want  b \ (U_i s_i).
138 ///
139 /// Let s_i = /\_j s_ij, where each s_ij is a single inequality. To compute
140 /// b \ s_i = b /\ ~s_i, we partition s_i based on the first violated
141 /// inequality: ~s_i = (~s_i1) U (s_i1 /\ ~s_i2) U (s_i1 /\ s_i2 /\ ~s_i3) U ...
142 /// And the required result is (b /\ ~s_i1) U (b /\ s_i1 /\ ~s_i2) U ...
143 /// We recurse by subtracting U_{j > i} S_j from each of these parts and
144 /// returning the union of the results. Each equality is handled as a
145 /// conjunction of two inequalities.
146 ///
147 /// Note that the same approach works even if an inequality involves a floor
148 /// division. For example, the complement of x <= 7*floor(x/7) is still
149 /// x > 7*floor(x/7). Since b \ s_i contains the inequalities of both b and s_i
150 /// (or the complements of those inequalities), b \ s_i may contain the
151 /// divisions present in both b and s_i. Therefore, we need to add the local
152 /// division variables of both b and s_i to each part in the result. This means
153 /// adding the local variables of both b and s_i, as well as the corresponding
154 /// division inequalities to each part. Since the division inequalities are
155 /// added to each part, we can skip the parts where the complement of any
156 /// division inequality is added, as these parts will become empty anyway.
157 ///
158 /// As a heuristic, we try adding all the constraints and check if simplex
159 /// says that the intersection is empty. If it is, then subtracting this
160 /// disjuncts is a no-op and we just skip it. Also, in the process we find out
161 /// that some constraints are redundant. These redundant constraints are
162 /// ignored.
163 ///
164 static PresburgerRelation getSetDifference(IntegerRelation b,
165                                            const PresburgerRelation &s) {
166   assert(b.getSpace().isCompatible(s.getSpace()) && "Spaces should match");
167   if (b.isEmptyByGCDTest())
168     return PresburgerRelation::getEmpty(b.getSpaceWithoutLocals());
169 
170   // Remove duplicate divs up front here to avoid existing
171   // divs disappearing in the call to mergeLocalIds below.
172   b.removeDuplicateDivs();
173 
174   PresburgerRelation result =
175       PresburgerRelation::getEmpty(b.getSpaceWithoutLocals());
176   Simplex simplex(b);
177 
178   // This algorithm is more naturally expressed recursively, but we implement
179   // it iteratively here to avoid issues with stack sizes.
180   //
181   // Each level of the recursion has five stack variables.
182   struct Frame {
183     // A snapshot of the simplex state to rollback to.
184     unsigned simplexSnapshot;
185     // A CountsSnapshot of `b` to rollback to.
186     IntegerRelation::CountsSnapshot bCounts;
187     // The IntegerRelation currently being operated on.
188     IntegerRelation sI;
189     // A list of indexes (see getIneqCoeffsFromIdx) of inequalities to be
190     // processed.
191     SmallVector<unsigned, 8> ineqsToProcess;
192     // The index of the last inequality that was processed at this level.
193     // This is empty when we are coming to this level for the first time.
194     Optional<unsigned> lastIneqProcessed;
195   };
196   SmallVector<Frame, 2> frames;
197 
198   // When we "recurse", we ensure the current frame is stored in `frames` and
199   // increment `level`. When we return, we decrement `level`.
200   unsigned level = 1;
201   while (level > 0) {
202     if (level - 1 >= s.getNumDisjuncts()) {
203       // No more parts to subtract; add to the result and return.
204       result.unionInPlace(b);
205       level = frames.size();
206       continue;
207     }
208 
209     if (level > frames.size()) {
210       // No frame for this level yet, so we have just recursed into this level.
211       IntegerRelation sI = s.getDisjunct(level - 1);
212       // Remove the duplicate divs up front to avoid them possibly disappearing
213       // in the call to mergeLocalIds below.
214       sI.removeDuplicateDivs();
215 
216       // Below, we append some additional constraints and ids to b. We want to
217       // rollback b to its initial state before returning, which we will do by
218       // removing all constraints beyond the original number of inequalities
219       // and equalities, so we store these counts first.
220       IntegerRelation::CountsSnapshot initBCounts = b.getCounts();
221       // Similarly, we also want to rollback simplex to its original state.
222       unsigned initialSnapshot = simplex.getSnapshot();
223 
224       // Find out which inequalities of sI correspond to division inequalities
225       // for the local variables of sI.
226       std::vector<MaybeLocalRepr> repr(sI.getNumLocalIds());
227       sI.getLocalReprs(repr);
228 
229       // Add sI's locals to b, after b's locals. Only those locals of sI which
230       // do not already exist in b will be added. (i.e., duplicate divisions
231       // will not be added.) Also add b's locals to sI, in such a way that both
232       // have the same locals in the same order in the end.
233       b.mergeLocalIds(sI);
234 
235       // Mark which inequalities of sI are division inequalities and add all
236       // such inequalities to b.
237       llvm::SmallBitVector canIgnoreIneq(sI.getNumInequalities() +
238                                          2 * sI.getNumEqualities());
239       for (MaybeLocalRepr &maybeInequality : repr) {
240         assert(
241             maybeInequality.kind == ReprKind::Inequality &&
242             "Subtraction is not supported when a representation of the local "
243             "variables of the subtrahend cannot be found!");
244         unsigned lb = maybeInequality.repr.inequalityPair.lowerBoundIdx;
245         unsigned ub = maybeInequality.repr.inequalityPair.upperBoundIdx;
246 
247         b.addInequality(sI.getInequality(lb));
248         b.addInequality(sI.getInequality(ub));
249 
250         assert(lb != ub &&
251                "Upper and lower bounds must be different inequalities!");
252         canIgnoreIneq[lb] = true;
253         canIgnoreIneq[ub] = true;
254       }
255 
256       unsigned offset = simplex.getNumConstraints();
257       unsigned numLocalsAdded =
258           b.getNumLocalIds() - initBCounts.getSpace().getNumLocalIds();
259       simplex.appendVariable(numLocalsAdded);
260 
261       unsigned snapshotBeforeIntersect = simplex.getSnapshot();
262       simplex.intersectIntegerRelation(sI);
263 
264       if (simplex.isEmpty()) {
265         // b /\ s_i is empty, so b \ s_i = b. We move directly to i + 1.
266         // We are ignoring level i completely, so we restore the state
267         // *before* going to the next level.
268         b.truncate(initBCounts);
269         simplex.rollback(initialSnapshot);
270         // Recurse. We haven't processed any inequalities and
271         // we don't need to process anything when we return.
272         //
273         // TODO: consider supporting tail recursion directly if this becomes
274         // relevant for performance.
275         frames.push_back(Frame{initialSnapshot, initBCounts, sI,
276                                /*ineqsToProcess=*/{},
277                                /*lastIneqProcessed=*/{}});
278         ++level;
279         continue;
280       }
281 
282       simplex.detectRedundant();
283 
284       // Equalities are added to simplex as a pair of inequalities.
285       unsigned totalNewSimplexInequalities =
286           2 * sI.getNumEqualities() + sI.getNumInequalities();
287       for (unsigned j = 0; j < totalNewSimplexInequalities; j++)
288         canIgnoreIneq[j] = simplex.isMarkedRedundant(offset + j);
289       simplex.rollback(snapshotBeforeIntersect);
290 
291       SmallVector<unsigned, 8> ineqsToProcess(totalNewSimplexInequalities);
292       for (unsigned i = 0; i < totalNewSimplexInequalities; ++i)
293         if (!canIgnoreIneq[i])
294           ineqsToProcess.push_back(i);
295 
296       if (ineqsToProcess.empty()) {
297         // Nothing to process; return. (we have no frame to pop.)
298         level = frames.size();
299         continue;
300       }
301 
302       unsigned simplexSnapshot = simplex.getSnapshot();
303       IntegerRelation::CountsSnapshot bCounts = b.getCounts();
304       frames.push_back(Frame{simplexSnapshot, bCounts, sI, ineqsToProcess,
305                              /*lastIneqProcessed=*/llvm::None});
306       // We have completed the initial setup for this level.
307       // Fallthrough to the main recursive part below.
308     }
309 
310     // For each inequality ineq, we first recurse with the part where ineq
311     // is not satisfied, and then add ineq to b and simplex because
312     // ineq must be satisfied by all later parts.
313     if (level == frames.size()) {
314       Frame &frame = frames.back();
315       if (frame.lastIneqProcessed) {
316         // Let the current value of b be b' and
317         // let the initial value of b when we first came to this level be b.
318         //
319         // b' is equal to b /\ s_i1 /\ s_i2 /\ ... /\ s_i{j-1} /\ ~s_ij.
320         // We had previously recursed with the part where s_ij was not
321         // satisfied; all further parts satisfy s_ij, so we rollback to the
322         // state before adding this complement constraint, and add s_ij to b.
323         simplex.rollback(frame.simplexSnapshot);
324         b.truncate(frame.bCounts);
325         SmallVector<int64_t, 8> ineq =
326             getIneqCoeffsFromIdx(frame.sI, *frame.lastIneqProcessed);
327         b.addInequality(ineq);
328         simplex.addInequality(ineq);
329       }
330 
331       if (frame.ineqsToProcess.empty()) {
332         // No ineqs left to process; pop this level's frame and return.
333         frames.pop_back();
334         level = frames.size();
335         continue;
336       }
337 
338       // "Recurse" with the part where the ineq is not satisfied.
339       frame.bCounts = b.getCounts();
340       frame.simplexSnapshot = simplex.getSnapshot();
341 
342       unsigned idx = frame.ineqsToProcess.back();
343       SmallVector<int64_t, 8> ineq =
344           getComplementIneq(getIneqCoeffsFromIdx(frame.sI, idx));
345       b.addInequality(ineq);
346       simplex.addInequality(ineq);
347 
348       frame.ineqsToProcess.pop_back();
349       frame.lastIneqProcessed = idx;
350       ++level;
351       continue;
352     }
353   }
354 
355   return result;
356 }
357 
358 /// Return the complement of this set.
359 PresburgerRelation PresburgerRelation::complement() const {
360   return getSetDifference(IntegerRelation::getUniverse(getSpace()), *this);
361 }
362 
363 /// Return the result of subtract the given set from this set, i.e.,
364 /// return `this \ set`.
365 PresburgerRelation
366 PresburgerRelation::subtract(const PresburgerRelation &set) const {
367   assert(space.isCompatible(set.getSpace()) && "Spaces should match");
368   PresburgerRelation result(getSpace());
369   // We compute (U_i t_i) \ (U_i set_i) as U_i (t_i \ V_i set_i).
370   for (const IntegerRelation &disjunct : disjuncts)
371     result.unionInPlace(getSetDifference(disjunct, set));
372   return result;
373 }
374 
375 /// T is a subset of S iff T \ S is empty, since if T \ S contains a
376 /// point then this is a point that is contained in T but not S, and
377 /// if T contains a point that is not in S, this also lies in T \ S.
378 bool PresburgerRelation::isSubsetOf(const PresburgerRelation &set) const {
379   return this->subtract(set).isIntegerEmpty();
380 }
381 
382 /// Two sets are equal iff they are subsets of each other.
383 bool PresburgerRelation::isEqual(const PresburgerRelation &set) const {
384   assert(space.isCompatible(set.getSpace()) && "Spaces should match");
385   return this->isSubsetOf(set) && set.isSubsetOf(*this);
386 }
387 
388 /// Return true if all the sets in the union are known to be integer empty,
389 /// false otherwise.
390 bool PresburgerRelation::isIntegerEmpty() const {
391   // The set is empty iff all of the disjuncts are empty.
392   return llvm::all_of(disjuncts, std::mem_fn(&IntegerRelation::isIntegerEmpty));
393 }
394 
395 bool PresburgerRelation::findIntegerSample(SmallVectorImpl<int64_t> &sample) {
396   // A sample exists iff any of the disjuncts contains a sample.
397   for (const IntegerRelation &disjunct : disjuncts) {
398     if (Optional<SmallVector<int64_t, 8>> opt = disjunct.findIntegerSample()) {
399       sample = std::move(*opt);
400       return true;
401     }
402   }
403   return false;
404 }
405 
406 Optional<uint64_t> PresburgerRelation::computeVolume() const {
407   assert(getNumSymbolIds() == 0 && "Symbols are not yet supported!");
408   // The sum of the volumes of the disjuncts is a valid overapproximation of the
409   // volume of their union, even if they overlap.
410   uint64_t result = 0;
411   for (const IntegerRelation &disjunct : disjuncts) {
412     Optional<uint64_t> volume = disjunct.computeVolume();
413     if (!volume)
414       return {};
415     result += *volume;
416   }
417   return result;
418 }
419 
420 /// The SetCoalescer class contains all functionality concerning the coalesce
421 /// heuristic. It is built from a `PresburgerRelation` and has the `coalesce()`
422 /// function as its main API. The coalesce heuristic simplifies the
423 /// representation of a PresburgerRelation. In particular, it removes all
424 /// disjuncts which are subsets of other disjuncts in the union and it combines
425 /// sets that overlap and can be combined in a convex way.
426 class presburger::SetCoalescer {
427 
428 public:
429   /// Simplifies the representation of a PresburgerSet.
430   PresburgerRelation coalesce();
431 
432   /// Construct a SetCoalescer from a PresburgerSet.
433   SetCoalescer(const PresburgerRelation &s);
434 
435 private:
436   /// The space of the set the SetCoalescer is coalescing.
437   PresburgerSpace space;
438 
439   /// The current list of `IntegerRelation`s that the currently coalesced set is
440   /// the union of.
441   SmallVector<IntegerRelation, 2> disjuncts;
442   /// The list of `Simplex`s constructed from the elements of `disjuncts`.
443   SmallVector<Simplex, 2> simplices;
444 
445   /// The list of all inversed equalities during typing. This ensures that
446   /// the constraints exist even after the typing function has concluded.
447   SmallVector<SmallVector<int64_t, 2>, 2> negEqs;
448 
449   /// `redundantIneqsA` is the inequalities of `a` that are redundant for `b`
450   /// (similarly for `cuttingIneqsA`, `redundantIneqsB`, and `cuttingIneqsB`).
451   SmallVector<ArrayRef<int64_t>, 2> redundantIneqsA;
452   SmallVector<ArrayRef<int64_t>, 2> cuttingIneqsA;
453 
454   SmallVector<ArrayRef<int64_t>, 2> redundantIneqsB;
455   SmallVector<ArrayRef<int64_t>, 2> cuttingIneqsB;
456 
457   /// Given a Simplex `simp` and one of its inequalities `ineq`, check
458   /// that the facet of `simp` where `ineq` holds as an equality is contained
459   /// within `a`.
460   bool isFacetContained(ArrayRef<int64_t> ineq, Simplex &simp);
461 
462   /// Removes redundant constraints from `disjunct`, adds it to `disjuncts` and
463   /// removes the disjuncts at position `i` and `j`. Updates `simplices` to
464   /// reflect the changes. `i` and `j` cannot be equal.
465   void addCoalescedDisjunct(unsigned i, unsigned j,
466                             const IntegerRelation &disjunct);
467 
468   /// Checks whether `a` and `b` can be combined in a convex sense, if there
469   /// exist cutting inequalities.
470   ///
471   /// An example of this case:
472   ///    ___________        ___________
473   ///   /   /  |   /       /          /
474   ///   \   \  |  /   ==>  \         /
475   ///    \   \ | /          \       /
476   ///     \___\|/            \_____/
477   ///
478   ///
479   LogicalResult coalescePairCutCase(unsigned i, unsigned j);
480 
481   /// Types the inequality `ineq` according to its `IneqType` for `simp` into
482   /// `redundantIneqsB` and `cuttingIneqsB`. Returns success, if no separate
483   /// inequalities were encountered. Otherwise, returns failure.
484   LogicalResult typeInequality(ArrayRef<int64_t> ineq, Simplex &simp);
485 
486   /// Types the equality `eq`, i.e. for `eq` == 0, types both `eq` >= 0 and
487   /// -`eq` >= 0 according to their `IneqType` for `simp` into
488   /// `redundantIneqsB` and `cuttingIneqsB`. Returns success, if no separate
489   /// inequalities were encountered. Otherwise, returns failure.
490   LogicalResult typeEquality(ArrayRef<int64_t> eq, Simplex &simp);
491 
492   /// Replaces the element at position `i` with the last element and erases
493   /// the last element for both `disjuncts` and `simplices`.
494   void eraseDisjunct(unsigned i);
495 
496   /// Attempts to coalesce the two IntegerRelations at position `i` and `j`
497   /// in `disjuncts` in-place. Returns whether the disjuncts were
498   /// successfully coalesced. The simplices in `simplices` need to be the ones
499   /// constructed from `disjuncts`. At this point, there are no empty
500   /// disjuncts in `disjuncts` left.
501   LogicalResult coalescePair(unsigned i, unsigned j);
502 };
503 
504 /// Constructs a `SetCoalescer` from a `PresburgerRelation`. Only adds non-empty
505 /// `IntegerRelation`s to the `disjuncts` vector.
506 SetCoalescer::SetCoalescer(const PresburgerRelation &s) : space(s.getSpace()) {
507 
508   disjuncts = s.disjuncts;
509 
510   simplices.reserve(s.getNumDisjuncts());
511   // Note that disjuncts.size() changes during the loop.
512   for (unsigned i = 0; i < disjuncts.size();) {
513     disjuncts[i].removeRedundantConstraints();
514     Simplex simp(disjuncts[i]);
515     if (simp.isEmpty()) {
516       disjuncts[i] = disjuncts[disjuncts.size() - 1];
517       disjuncts.pop_back();
518       continue;
519     }
520     ++i;
521     simplices.push_back(simp);
522   }
523 }
524 
525 /// Simplifies the representation of a PresburgerSet.
526 PresburgerRelation SetCoalescer::coalesce() {
527   // For all tuples of IntegerRelations, check whether they can be
528   // coalesced. When coalescing is successful, the contained IntegerRelation
529   // is swapped with the last element of `disjuncts` and subsequently erased
530   // and similarly for simplices.
531   for (unsigned i = 0; i < disjuncts.size();) {
532 
533     // TODO: This does some comparisons two times (index 0 with 1 and index 1
534     // with 0).
535     bool broken = false;
536     for (unsigned j = 0, e = disjuncts.size(); j < e; ++j) {
537       negEqs.clear();
538       redundantIneqsA.clear();
539       redundantIneqsB.clear();
540       cuttingIneqsA.clear();
541       cuttingIneqsB.clear();
542       if (i == j)
543         continue;
544       if (coalescePair(i, j).succeeded()) {
545         broken = true;
546         break;
547       }
548     }
549 
550     // Only if the inner loop was not broken, i is incremented. This is
551     // required as otherwise, if a coalescing occurs, the IntegerRelation
552     // now at position i is not compared.
553     if (!broken)
554       ++i;
555   }
556 
557   PresburgerRelation newSet = PresburgerRelation::getEmpty(space);
558   for (unsigned i = 0, e = disjuncts.size(); i < e; ++i)
559     newSet.unionInPlace(disjuncts[i]);
560 
561   return newSet;
562 }
563 
564 /// Given a Simplex `simp` and one of its inequalities `ineq`, check
565 /// that all inequalities of `cuttingIneqsB` are redundant for the facet of
566 /// `simp` where `ineq` holds as an equality is contained within `a`.
567 bool SetCoalescer::isFacetContained(ArrayRef<int64_t> ineq, Simplex &simp) {
568   SimplexRollbackScopeExit scopeExit(simp);
569   simp.addEquality(ineq);
570   return llvm::all_of(cuttingIneqsB, [&simp](ArrayRef<int64_t> curr) {
571     return simp.isRedundantInequality(curr);
572   });
573 }
574 
575 void SetCoalescer::addCoalescedDisjunct(unsigned i, unsigned j,
576                                         const IntegerRelation &disjunct) {
577   assert(i != j && "The indices must refer to different disjuncts");
578   unsigned n = disjuncts.size();
579   if (j == n - 1) {
580     // This case needs special handling since position `n` - 1 is removed
581     // from the vector, hence the `IntegerRelation` at position `n` - 2 is
582     // lost otherwise.
583     disjuncts[i] = disjuncts[n - 2];
584     disjuncts.pop_back();
585     disjuncts[n - 2] = disjunct;
586     disjuncts[n - 2].removeRedundantConstraints();
587 
588     simplices[i] = simplices[n - 2];
589     simplices.pop_back();
590     simplices[n - 2] = Simplex(disjuncts[n - 2]);
591 
592   } else {
593     // Other possible edge cases are correct since for `j` or `i` == `n` -
594     // 2, the `IntegerRelation` at position `n` - 2 should be lost. The
595     // case `i` == `n` - 1 makes the first following statement a noop.
596     // Hence, in this case the same thing is done as above, but with `j`
597     // rather than `i`.
598     disjuncts[i] = disjuncts[n - 1];
599     disjuncts[j] = disjuncts[n - 2];
600     disjuncts.pop_back();
601     disjuncts[n - 2] = disjunct;
602     disjuncts[n - 2].removeRedundantConstraints();
603 
604     simplices[i] = simplices[n - 1];
605     simplices[j] = simplices[n - 2];
606     simplices.pop_back();
607     simplices[n - 2] = Simplex(disjuncts[n - 2]);
608   }
609 }
610 
611 /// Given two polyhedra `a` and `b` at positions `i` and `j` in
612 /// `disjuncts` and `redundantIneqsA` being the inequalities of `a` that
613 /// are redundant for `b` (similarly for `cuttingIneqsA`, `redundantIneqsB`,
614 /// and `cuttingIneqsB`), Checks whether the facets of all cutting
615 /// inequalites of `a` are contained in `b`. If so, a new polyhedron
616 /// consisting of all redundant inequalites of `a` and `b` and all
617 /// equalities of both is created.
618 ///
619 /// An example of this case:
620 ///    ___________        ___________
621 ///   /   /  |   /       /          /
622 ///   \   \  |  /   ==>  \         /
623 ///    \   \ | /          \       /
624 ///     \___\|/            \_____/
625 ///
626 ///
627 LogicalResult SetCoalescer::coalescePairCutCase(unsigned i, unsigned j) {
628   /// All inequalities of `b` need to be redundant. We already know that the
629   /// redundant ones are, so only the cutting ones remain to be checked.
630   Simplex &simp = simplices[i];
631   IntegerRelation &disjunct = disjuncts[i];
632   if (llvm::any_of(cuttingIneqsA, [this, &simp](ArrayRef<int64_t> curr) {
633         return !isFacetContained(curr, simp);
634       }))
635     return failure();
636   IntegerRelation newSet(disjunct.getSpace());
637 
638   for (ArrayRef<int64_t> curr : redundantIneqsA)
639     newSet.addInequality(curr);
640 
641   for (ArrayRef<int64_t> curr : redundantIneqsB)
642     newSet.addInequality(curr);
643 
644   addCoalescedDisjunct(i, j, newSet);
645   return success();
646 }
647 
648 LogicalResult SetCoalescer::typeInequality(ArrayRef<int64_t> ineq,
649                                            Simplex &simp) {
650   Simplex::IneqType type = simp.findIneqType(ineq);
651   if (type == Simplex::IneqType::Redundant)
652     redundantIneqsB.push_back(ineq);
653   else if (type == Simplex::IneqType::Cut)
654     cuttingIneqsB.push_back(ineq);
655   else
656     return failure();
657   return success();
658 }
659 
660 LogicalResult SetCoalescer::typeEquality(ArrayRef<int64_t> eq, Simplex &simp) {
661   if (typeInequality(eq, simp).failed())
662     return failure();
663   negEqs.push_back(getNegatedCoeffs(eq));
664   ArrayRef<int64_t> inv(negEqs.back());
665   if (typeInequality(inv, simp).failed())
666     return failure();
667   return success();
668 }
669 
670 void SetCoalescer::eraseDisjunct(unsigned i) {
671   assert(simplices.size() == disjuncts.size() &&
672          "simplices and disjuncts must be equally as long");
673   disjuncts[i] = disjuncts.back();
674   disjuncts.pop_back();
675   simplices[i] = simplices.back();
676   simplices.pop_back();
677 }
678 
679 LogicalResult SetCoalescer::coalescePair(unsigned i, unsigned j) {
680 
681   IntegerRelation &a = disjuncts[i];
682   IntegerRelation &b = disjuncts[j];
683   /// Handling of local ids is not yet implemented, so these cases are
684   /// skipped.
685   /// TODO: implement local id support.
686   if (a.getNumLocalIds() != 0 || b.getNumLocalIds() != 0)
687     return failure();
688   Simplex &simpA = simplices[i];
689   Simplex &simpB = simplices[j];
690 
691   // Organize all inequalities and equalities of `a` according to their type
692   // for `b` into `redundantIneqsA` and `cuttingIneqsA` (and vice versa for
693   // all inequalities of `b` according to their type in `a`). If a separate
694   // inequality is encountered during typing, the two IntegerRelations
695   // cannot be coalesced.
696   for (int k = 0, e = a.getNumInequalities(); k < e; ++k)
697     if (typeInequality(a.getInequality(k), simpB).failed())
698       return failure();
699 
700   for (int k = 0, e = a.getNumEqualities(); k < e; ++k)
701     if (typeEquality(a.getEquality(k), simpB).failed())
702       return failure();
703 
704   std::swap(redundantIneqsA, redundantIneqsB);
705   std::swap(cuttingIneqsA, cuttingIneqsB);
706 
707   for (int k = 0, e = b.getNumInequalities(); k < e; ++k)
708     if (typeInequality(b.getInequality(k), simpA).failed())
709       return failure();
710 
711   for (int k = 0, e = b.getNumEqualities(); k < e; ++k)
712     if (typeEquality(b.getEquality(k), simpA).failed())
713       return failure();
714 
715   // If there are no cutting inequalities of `a`, `b` is contained
716   // within `a`.
717   if (cuttingIneqsA.empty()) {
718     eraseDisjunct(j);
719     return success();
720   }
721 
722   // Try to apply the cut case
723   if (coalescePairCutCase(i, j).succeeded())
724     return success();
725 
726   // Swap the vectors to compare the pair (j,i) instead of (i,j).
727   std::swap(redundantIneqsA, redundantIneqsB);
728   std::swap(cuttingIneqsA, cuttingIneqsB);
729 
730   // If there are no cutting inequalities of `a`, `b` is contained
731   // within `a`.
732   if (cuttingIneqsA.empty()) {
733     eraseDisjunct(i);
734     return success();
735   }
736 
737   // Try to apply the cut case
738   if (coalescePairCutCase(j, i).succeeded())
739     return success();
740 
741   return failure();
742 }
743 
744 PresburgerRelation PresburgerRelation::coalesce() const {
745   return SetCoalescer(*this).coalesce();
746 }
747 
748 void PresburgerRelation::print(raw_ostream &os) const {
749   os << "Number of Disjuncts: " << getNumDisjuncts() << "\n";
750   for (const IntegerRelation &disjunct : disjuncts) {
751     disjunct.print(os);
752     os << '\n';
753   }
754 }
755 
756 void PresburgerRelation::dump() const { print(llvm::errs()); }
757 
758 PresburgerSet PresburgerSet::getUniverse(const PresburgerSpace &space) {
759   PresburgerSet result(space);
760   result.unionInPlace(IntegerPolyhedron::getUniverse(space));
761   return result;
762 }
763 
764 PresburgerSet PresburgerSet::getEmpty(const PresburgerSpace &space) {
765   return PresburgerSet(space);
766 }
767 
768 PresburgerSet::PresburgerSet(const IntegerPolyhedron &disjunct)
769     : PresburgerRelation(disjunct) {}
770 
771 PresburgerSet::PresburgerSet(const PresburgerRelation &set)
772     : PresburgerRelation(set) {}
773 
774 PresburgerSet PresburgerSet::unionSet(const PresburgerRelation &set) const {
775   return PresburgerSet(PresburgerRelation::unionSet(set));
776 }
777 
778 PresburgerSet PresburgerSet::intersect(const PresburgerRelation &set) const {
779   return PresburgerSet(PresburgerRelation::intersect(set));
780 }
781 
782 PresburgerSet PresburgerSet::complement() const {
783   return PresburgerSet(PresburgerRelation::complement());
784 }
785 
786 PresburgerSet PresburgerSet::subtract(const PresburgerRelation &set) const {
787   return PresburgerSet(PresburgerRelation::subtract(set));
788 }
789 
790 PresburgerSet PresburgerSet::coalesce() const {
791   return PresburgerSet(PresburgerRelation::coalesce());
792 }
793