isl_map_coalesce: allow wrapping in sets that stick out in different directions
[platform/upstream/isl.git] / isl_coalesce.c
1 /*
2  * Copyright 2008-2009 Katholieke Universiteit Leuven
3  * Copyright 2010      INRIA Saclay
4  *
5  * Use of this software is governed by the GNU LGPLv2.1 license
6  *
7  * Written by Sven Verdoolaege, K.U.Leuven, Departement
8  * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
9  * and INRIA Saclay - Ile-de-France, Parc Club Orsay Universite,
10  * ZAC des vignes, 4 rue Jacques Monod, 91893 Orsay, France 
11  */
12
13 #include "isl_map_private.h"
14 #include "isl_seq.h"
15 #include "isl_tab.h"
16
17 #define STATUS_ERROR            -1
18 #define STATUS_REDUNDANT         1
19 #define STATUS_VALID             2
20 #define STATUS_SEPARATE          3
21 #define STATUS_CUT               4
22 #define STATUS_ADJ_EQ            5
23 #define STATUS_ADJ_INEQ          6
24
25 static int status_in(isl_int *ineq, struct isl_tab *tab)
26 {
27         enum isl_ineq_type type = isl_tab_ineq_type(tab, ineq);
28         switch (type) {
29         case isl_ineq_error:            return STATUS_ERROR;
30         case isl_ineq_redundant:        return STATUS_VALID;
31         case isl_ineq_separate:         return STATUS_SEPARATE;
32         case isl_ineq_cut:              return STATUS_CUT;
33         case isl_ineq_adj_eq:           return STATUS_ADJ_EQ;
34         case isl_ineq_adj_ineq:         return STATUS_ADJ_INEQ;
35         }
36 }
37
38 /* Compute the position of the equalities of basic map "i"
39  * with respect to basic map "j".
40  * The resulting array has twice as many entries as the number
41  * of equalities corresponding to the two inequalties to which
42  * each equality corresponds.
43  */
44 static int *eq_status_in(struct isl_map *map, int i, int j,
45         struct isl_tab **tabs)
46 {
47         int k, l;
48         int *eq = isl_calloc_array(map->ctx, int, 2 * map->p[i]->n_eq);
49         unsigned dim;
50
51         dim = isl_basic_map_total_dim(map->p[i]);
52         for (k = 0; k < map->p[i]->n_eq; ++k) {
53                 for (l = 0; l < 2; ++l) {
54                         isl_seq_neg(map->p[i]->eq[k], map->p[i]->eq[k], 1+dim);
55                         eq[2 * k + l] = status_in(map->p[i]->eq[k], tabs[j]);
56                         if (eq[2 * k + l] == STATUS_ERROR)
57                                 goto error;
58                 }
59                 if (eq[2 * k] == STATUS_SEPARATE ||
60                     eq[2 * k + 1] == STATUS_SEPARATE)
61                         break;
62         }
63
64         return eq;
65 error:
66         free(eq);
67         return NULL;
68 }
69
70 /* Compute the position of the inequalities of basic map "i"
71  * with respect to basic map "j".
72  */
73 static int *ineq_status_in(struct isl_map *map, int i, int j,
74         struct isl_tab **tabs)
75 {
76         int k;
77         unsigned n_eq = map->p[i]->n_eq;
78         int *ineq = isl_calloc_array(map->ctx, int, map->p[i]->n_ineq);
79
80         for (k = 0; k < map->p[i]->n_ineq; ++k) {
81                 if (isl_tab_is_redundant(tabs[i], n_eq + k)) {
82                         ineq[k] = STATUS_REDUNDANT;
83                         continue;
84                 }
85                 ineq[k] = status_in(map->p[i]->ineq[k], tabs[j]);
86                 if (ineq[k] == STATUS_ERROR)
87                         goto error;
88                 if (ineq[k] == STATUS_SEPARATE)
89                         break;
90         }
91
92         return ineq;
93 error:
94         free(ineq);
95         return NULL;
96 }
97
98 static int any(int *con, unsigned len, int status)
99 {
100         int i;
101
102         for (i = 0; i < len ; ++i)
103                 if (con[i] == status)
104                         return 1;
105         return 0;
106 }
107
108 static int count(int *con, unsigned len, int status)
109 {
110         int i;
111         int c = 0;
112
113         for (i = 0; i < len ; ++i)
114                 if (con[i] == status)
115                         c++;
116         return c;
117 }
118
119 static int all(int *con, unsigned len, int status)
120 {
121         int i;
122
123         for (i = 0; i < len ; ++i) {
124                 if (con[i] == STATUS_REDUNDANT)
125                         continue;
126                 if (con[i] != status)
127                         return 0;
128         }
129         return 1;
130 }
131
132 static void drop(struct isl_map *map, int i, struct isl_tab **tabs)
133 {
134         isl_basic_map_free(map->p[i]);
135         isl_tab_free(tabs[i]);
136
137         if (i != map->n - 1) {
138                 map->p[i] = map->p[map->n - 1];
139                 tabs[i] = tabs[map->n - 1];
140         }
141         tabs[map->n - 1] = NULL;
142         map->n--;
143 }
144
145 /* Replace the pair of basic maps i and j by the basic map bounded
146  * by the valid constraints in both basic maps and the constraint
147  * in extra (if not NULL).
148  */
149 static int fuse(struct isl_map *map, int i, int j,
150         struct isl_tab **tabs, int *eq_i, int *ineq_i, int *eq_j, int *ineq_j,
151         __isl_keep isl_mat *extra)
152 {
153         int k, l;
154         struct isl_basic_map *fused = NULL;
155         struct isl_tab *fused_tab = NULL;
156         unsigned total = isl_basic_map_total_dim(map->p[i]);
157         unsigned extra_rows = extra ? extra->n_row : 0;
158
159         fused = isl_basic_map_alloc_dim(isl_dim_copy(map->p[i]->dim),
160                         map->p[i]->n_div,
161                         map->p[i]->n_eq + map->p[j]->n_eq,
162                         map->p[i]->n_ineq + map->p[j]->n_ineq + extra_rows);
163         if (!fused)
164                 goto error;
165
166         for (k = 0; k < map->p[i]->n_eq; ++k) {
167                 if (eq_i && (eq_i[2 * k] != STATUS_VALID ||
168                              eq_i[2 * k + 1] != STATUS_VALID))
169                         continue;
170                 l = isl_basic_map_alloc_equality(fused);
171                 if (l < 0)
172                         goto error;
173                 isl_seq_cpy(fused->eq[l], map->p[i]->eq[k], 1 + total);
174         }
175
176         for (k = 0; k < map->p[j]->n_eq; ++k) {
177                 if (eq_j && (eq_j[2 * k] != STATUS_VALID ||
178                              eq_j[2 * k + 1] != STATUS_VALID))
179                         continue;
180                 l = isl_basic_map_alloc_equality(fused);
181                 if (l < 0)
182                         goto error;
183                 isl_seq_cpy(fused->eq[l], map->p[j]->eq[k], 1 + total);
184         }
185
186         for (k = 0; k < map->p[i]->n_ineq; ++k) {
187                 if (ineq_i[k] != STATUS_VALID)
188                         continue;
189                 l = isl_basic_map_alloc_inequality(fused);
190                 if (l < 0)
191                         goto error;
192                 isl_seq_cpy(fused->ineq[l], map->p[i]->ineq[k], 1 + total);
193         }
194
195         for (k = 0; k < map->p[j]->n_ineq; ++k) {
196                 if (ineq_j[k] != STATUS_VALID)
197                         continue;
198                 l = isl_basic_map_alloc_inequality(fused);
199                 if (l < 0)
200                         goto error;
201                 isl_seq_cpy(fused->ineq[l], map->p[j]->ineq[k], 1 + total);
202         }
203
204         for (k = 0; k < map->p[i]->n_div; ++k) {
205                 int l = isl_basic_map_alloc_div(fused);
206                 if (l < 0)
207                         goto error;
208                 isl_seq_cpy(fused->div[l], map->p[i]->div[k], 1 + 1 + total);
209         }
210
211         for (k = 0; k < extra_rows; ++k) {
212                 l = isl_basic_map_alloc_inequality(fused);
213                 if (l < 0)
214                         goto error;
215                 isl_seq_cpy(fused->ineq[l], extra->row[k], 1 + total);
216         }
217
218         fused = isl_basic_map_gauss(fused, NULL);
219         ISL_F_SET(fused, ISL_BASIC_MAP_FINAL);
220         if (ISL_F_ISSET(map->p[i], ISL_BASIC_MAP_RATIONAL) &&
221             ISL_F_ISSET(map->p[j], ISL_BASIC_MAP_RATIONAL))
222                 ISL_F_SET(fused, ISL_BASIC_MAP_RATIONAL);
223
224         fused_tab = isl_tab_from_basic_map(fused);
225         if (isl_tab_detect_redundant(fused_tab) < 0)
226                 goto error;
227
228         isl_basic_map_free(map->p[i]);
229         map->p[i] = fused;
230         isl_tab_free(tabs[i]);
231         tabs[i] = fused_tab;
232         drop(map, j, tabs);
233
234         return 1;
235 error:
236         isl_tab_free(fused_tab);
237         isl_basic_map_free(fused);
238         return -1;
239 }
240
241 /* Given a pair of basic maps i and j such that all constraints are either
242  * "valid" or "cut", check if the facets corresponding to the "cut"
243  * constraints of i lie entirely within basic map j.
244  * If so, replace the pair by the basic map consisting of the valid
245  * constraints in both basic maps.
246  *
247  * To see that we are not introducing any extra points, call the
248  * two basic maps A and B and the resulting map U and let x
249  * be an element of U \setminus ( A \cup B ).
250  * Then there is a pair of cut constraints c_1 and c_2 in A and B such that x
251  * violates them.  Let X be the intersection of U with the opposites
252  * of these constraints.  Then x \in X.
253  * The facet corresponding to c_1 contains the corresponding facet of A.
254  * This facet is entirely contained in B, so c_2 is valid on the facet.
255  * However, since it is also (part of) a facet of X, -c_2 is also valid
256  * on the facet.  This means c_2 is saturated on the facet, so c_1 and
257  * c_2 must be opposites of each other, but then x could not violate
258  * both of them.
259  */
260 static int check_facets(struct isl_map *map, int i, int j,
261         struct isl_tab **tabs, int *ineq_i, int *ineq_j)
262 {
263         int k, l;
264         struct isl_tab_undo *snap;
265         unsigned n_eq = map->p[i]->n_eq;
266
267         snap = isl_tab_snap(tabs[i]);
268
269         for (k = 0; k < map->p[i]->n_ineq; ++k) {
270                 if (ineq_i[k] != STATUS_CUT)
271                         continue;
272                 tabs[i] = isl_tab_select_facet(tabs[i], n_eq + k);
273                 for (l = 0; l < map->p[j]->n_ineq; ++l) {
274                         int stat;
275                         if (ineq_j[l] != STATUS_CUT)
276                                 continue;
277                         stat = status_in(map->p[j]->ineq[l], tabs[i]);
278                         if (stat != STATUS_VALID)
279                                 break;
280                 }
281                 if (isl_tab_rollback(tabs[i], snap) < 0)
282                         return -1;
283                 if (l < map->p[j]->n_ineq)
284                         break;
285         }
286
287         if (k < map->p[i]->n_ineq)
288                 /* BAD CUT PAIR */
289                 return 0;
290         return fuse(map, i, j, tabs, NULL, ineq_i, NULL, ineq_j, NULL);
291 }
292
293 /* Both basic maps have at least one inequality with and adjacent
294  * (but opposite) inequality in the other basic map.
295  * Check that there are no cut constraints and that there is only
296  * a single pair of adjacent inequalities.
297  * If so, we can replace the pair by a single basic map described
298  * by all but the pair of adjacent inequalities.
299  * Any additional points introduced lie strictly between the two
300  * adjacent hyperplanes and can therefore be integral.
301  *
302  *        ____                    _____
303  *       /    ||\                /     \
304  *      /     || \              /       \
305  *      \     ||  \     =>      \        \
306  *       \    ||  /              \       /
307  *        \___||_/                \_____/
308  *
309  * The test for a single pair of adjancent inequalities is important
310  * for avoiding the combination of two basic maps like the following
311  *
312  *       /|
313  *      / |
314  *     /__|
315  *         _____
316  *         |   |
317  *         |   |
318  *         |___|
319  */
320 static int check_adj_ineq(struct isl_map *map, int i, int j,
321         struct isl_tab **tabs, int *ineq_i, int *ineq_j)
322 {
323         int changed = 0;
324
325         if (any(ineq_i, map->p[i]->n_ineq, STATUS_CUT) ||
326             any(ineq_j, map->p[j]->n_ineq, STATUS_CUT))
327                 /* ADJ INEQ CUT */
328                 ;
329         else if (count(ineq_i, map->p[i]->n_ineq, STATUS_ADJ_INEQ) == 1 &&
330                  count(ineq_j, map->p[j]->n_ineq, STATUS_ADJ_INEQ) == 1)
331                 changed = fuse(map, i, j, tabs, NULL, ineq_i, NULL, ineq_j, NULL);
332         /* else ADJ INEQ TOO MANY */
333
334         return changed;
335 }
336
337 /* Check if basic map "i" contains the basic map represented
338  * by the tableau "tab".
339  */
340 static int contains(struct isl_map *map, int i, int *ineq_i,
341         struct isl_tab *tab)
342 {
343         int k, l;
344         unsigned dim;
345
346         dim = isl_basic_map_total_dim(map->p[i]);
347         for (k = 0; k < map->p[i]->n_eq; ++k) {
348                 for (l = 0; l < 2; ++l) {
349                         int stat;
350                         isl_seq_neg(map->p[i]->eq[k], map->p[i]->eq[k], 1+dim);
351                         stat = status_in(map->p[i]->eq[k], tab);
352                         if (stat != STATUS_VALID)
353                                 return 0;
354                 }
355         }
356
357         for (k = 0; k < map->p[i]->n_ineq; ++k) {
358                 int stat;
359                 if (ineq_i[k] == STATUS_REDUNDANT)
360                         continue;
361                 stat = status_in(map->p[i]->ineq[k], tab);
362                 if (stat != STATUS_VALID)
363                         return 0;
364         }
365         return 1;
366 }
367
368 /* Basic map "i" has an inequality "k" that is adjacent to some equality
369  * of basic map "j".  All the other inequalities are valid for "j".
370  * Check if basic map "j" forms an extension of basic map "i".
371  *
372  * In particular, we relax constraint "k", compute the corresponding
373  * facet and check whether it is included in the other basic map.
374  * If so, we know that relaxing the constraint extends the basic
375  * map with exactly the other basic map (we already know that this
376  * other basic map is included in the extension, because there
377  * were no "cut" inequalities in "i") and we can replace the
378  * two basic maps by thie extension.
379  *        ____                    _____
380  *       /    ||                 /     |
381  *      /     ||                /      |
382  *      \     ||        =>      \      |
383  *       \    ||                 \     |
384  *        \___||                  \____|
385  */
386 static int is_extension(struct isl_map *map, int i, int j, int k,
387         struct isl_tab **tabs, int *eq_i, int *ineq_i, int *eq_j, int *ineq_j)
388 {
389         int changed = 0;
390         int super;
391         struct isl_tab_undo *snap, *snap2;
392         unsigned n_eq = map->p[i]->n_eq;
393
394         snap = isl_tab_snap(tabs[i]);
395         tabs[i] = isl_tab_relax(tabs[i], n_eq + k);
396         snap2 = isl_tab_snap(tabs[i]);
397         tabs[i] = isl_tab_select_facet(tabs[i], n_eq + k);
398         super = contains(map, j, ineq_j, tabs[i]);
399         if (super) {
400                 if (isl_tab_rollback(tabs[i], snap2) < 0)
401                         return -1;
402                 map->p[i] = isl_basic_map_cow(map->p[i]);
403                 if (!map->p[i])
404                         return -1;
405                 isl_int_add_ui(map->p[i]->ineq[k][0], map->p[i]->ineq[k][0], 1);
406                 ISL_F_SET(map->p[i], ISL_BASIC_MAP_FINAL);
407                 drop(map, j, tabs);
408                 changed = 1;
409         } else
410                 if (isl_tab_rollback(tabs[i], snap) < 0)
411                         return -1;
412
413         return changed;
414 }
415
416 /* For each non-redundant constraint in "bmap" (as determined by "tab"),
417  * wrap the constraint around "bound" such that it includes the whole
418  * set "set" and append the resulting constraint to "wraps".
419  * "wraps" is assumed to have been pre-allocated to the appropriate size.
420  * wraps->n_row is the number of actual wrapped constraints that have
421  * been added.
422  * If any of the wrapping problems results in a constraint that is
423  * identical to "bound", then this means that "set" is unbounded in such
424  * way that no wrapping is possible.  If this happens then wraps->n_row
425  * is reset to zero.
426  */
427 static int add_wraps(__isl_keep isl_mat *wraps, __isl_keep isl_basic_map *bmap,
428         struct isl_tab *tab, isl_int *bound, __isl_keep isl_set *set)
429 {
430         int l;
431         int w;
432         unsigned total = isl_basic_map_total_dim(bmap);
433
434         w = wraps->n_row;
435
436         for (l = 0; l < bmap->n_ineq; ++l) {
437                 if (isl_seq_is_neg(bound, bmap->ineq[l], 1 + total))
438                         continue;
439                 if (isl_seq_eq(bound, bmap->ineq[l], 1 + total))
440                         continue;
441                 if (isl_tab_is_redundant(tab, bmap->n_eq + l))
442                         continue;
443
444                 isl_seq_cpy(wraps->row[w], bound, 1 + total);
445                 if (!isl_set_wrap_facet(set, wraps->row[w], bmap->ineq[l]))
446                         return -1;
447                 if (isl_seq_eq(wraps->row[w], bound, 1 + total))
448                         goto unbounded;
449                 ++w;
450         }
451         for (l = 0; l < bmap->n_eq; ++l) {
452                 if (isl_seq_is_neg(bound, bmap->eq[l], 1 + total))
453                         continue;
454                 if (isl_seq_eq(bound, bmap->eq[l], 1 + total))
455                         continue;
456
457                 isl_seq_cpy(wraps->row[w], bound, 1 + total);
458                 isl_seq_neg(wraps->row[w + 1], bmap->eq[l], 1 + total);
459                 if (!isl_set_wrap_facet(set, wraps->row[w], wraps->row[w + 1]))
460                         return -1;
461                 if (isl_seq_eq(wraps->row[w], bound, 1 + total))
462                         goto unbounded;
463                 ++w;
464
465                 isl_seq_cpy(wraps->row[w], bound, 1 + total);
466                 if (!isl_set_wrap_facet(set, wraps->row[w], bmap->eq[l]))
467                         return -1;
468                 if (isl_seq_eq(wraps->row[w], bound, 1 + total))
469                         goto unbounded;
470                 ++w;
471         }
472
473         wraps->n_row = w;
474         return 0;
475 unbounded:
476         wraps->n_row = 0;
477         return 0;
478 }
479
480 /* Check if the constraints in "wraps" from "first" until the last
481  * are all valid for the basic set represented by "tab".
482  * If not, wraps->n_row is set to zero.
483  */
484 static int check_wraps(__isl_keep isl_mat *wraps, int first,
485         struct isl_tab *tab)
486 {
487         int i;
488
489         for (i = first; i < wraps->n_row; ++i) {
490                 enum isl_ineq_type type;
491                 type = isl_tab_ineq_type(tab, wraps->row[i]);
492                 if (type == isl_ineq_error)
493                         return -1;
494                 if (type == isl_ineq_redundant)
495                         continue;
496                 wraps->n_row = 0;
497                 return 0;
498         }
499
500         return 0;
501 }
502
503 /* Return a set that corresponds to the non-redudant constraints
504  * (as recorded in tab) of bmap.
505  *
506  * It's important to remove the redundant constraints as some
507  * of the other constraints may have been modified after the
508  * constraints were marked redundant.
509  * In particular, a constraint may have been relaxed.
510  * Redundant constraints are ignored when a constraint is relaxed
511  * and should therefore continue to be ignored ever after.
512  * Otherwise, the relaxation might be thwarted by some of
513  * these constraints.
514  */
515 static __isl_give isl_set *set_from_updated_bmap(__isl_keep isl_basic_map *bmap,
516         struct isl_tab *tab)
517 {
518         bmap = isl_basic_map_copy(bmap);
519         bmap = isl_basic_map_cow(bmap);
520         bmap = isl_basic_map_update_from_tab(bmap, tab);
521         return isl_set_from_basic_set(isl_basic_map_underlying_set(bmap));
522 }
523
524 /* Given a basic set i with a constraint k that is adjacent to either the
525  * whole of basic set j or a facet of basic set j, check if we can wrap
526  * both the facet corresponding to k and the facet of j (or the whole of j)
527  * around their ridges to include the other set.
528  * If so, replace the pair of basic sets by their union.
529  *
530  * All constraints of i (except k) are assumed to be valid for j.
531  *
532  * However, the constraints of j may not be valid for i and so
533  * we have to check that the wrapping constraints for j are valid for i.
534  *
535  * In the case where j has a facet adjacent to i, tab[j] is assumed
536  * to have been restricted to this facet, so that the non-redundant
537  * constraints in tab[j] are the ridges of the facet.
538  * Note that for the purpose of wrapping, it does not matter whether
539  * we wrap the ridges of i around the whole of j or just around
540  * the facet since all the other constraints are assumed to be valid for j.
541  * In practice, we wrap to include the whole of j.
542  *        ____                    _____
543  *       /    |                  /     \
544  *      /     ||                /      |
545  *      \     ||        =>      \      |
546  *       \    ||                 \     |
547  *        \___||                  \____|
548  *
549  */
550 static int can_wrap_in_facet(struct isl_map *map, int i, int j, int k,
551         struct isl_tab **tabs, int *eq_i, int *ineq_i, int *eq_j, int *ineq_j)
552 {
553         int changed = 0;
554         struct isl_mat *wraps = NULL;
555         struct isl_set *set_i = NULL;
556         struct isl_set *set_j = NULL;
557         struct isl_vec *bound = NULL;
558         unsigned total = isl_basic_map_total_dim(map->p[i]);
559         struct isl_tab_undo *snap;
560         int n;
561
562         set_i = set_from_updated_bmap(map->p[i], tabs[i]);
563         set_j = set_from_updated_bmap(map->p[j], tabs[j]);
564         wraps = isl_mat_alloc(map->ctx, 2 * (map->p[i]->n_eq + map->p[j]->n_eq) +
565                                         map->p[i]->n_ineq + map->p[j]->n_ineq,
566                                         1 + total);
567         bound = isl_vec_alloc(map->ctx, 1 + total);
568         if (!set_i || !set_j || !wraps || !bound)
569                 goto error;
570
571         isl_seq_cpy(bound->el, map->p[i]->ineq[k], 1 + total);
572         isl_int_add_ui(bound->el[0], bound->el[0], 1);
573
574         isl_seq_cpy(wraps->row[0], bound->el, 1 + total);
575         wraps->n_row = 1;
576
577         if (add_wraps(wraps, map->p[j], tabs[j], bound->el, set_i) < 0)
578                 goto error;
579         if (!wraps->n_row)
580                 goto unbounded;
581
582         snap = isl_tab_snap(tabs[i]);
583
584         tabs[i] = isl_tab_select_facet(tabs[i], map->p[i]->n_eq + k);
585         if (isl_tab_detect_redundant(tabs[i]) < 0)
586                 goto error;
587
588         isl_seq_neg(bound->el, map->p[i]->ineq[k], 1 + total);
589
590         n = wraps->n_row;
591         if (add_wraps(wraps, map->p[i], tabs[i], bound->el, set_j) < 0)
592                 goto error;
593
594         if (isl_tab_rollback(tabs[i], snap) < 0)
595                 goto error;
596         if (check_wraps(wraps, n, tabs[i]) < 0)
597                 goto error;
598         if (!wraps->n_row)
599                 goto unbounded;
600
601         changed = fuse(map, i, j, tabs, eq_i, ineq_i, eq_j, ineq_j, wraps);
602
603 unbounded:
604         isl_mat_free(wraps);
605
606         isl_set_free(set_i);
607         isl_set_free(set_j);
608
609         isl_vec_free(bound);
610
611         return changed;
612 error:
613         isl_vec_free(bound);
614         isl_mat_free(wraps);
615         isl_set_free(set_i);
616         isl_set_free(set_j);
617         return -1;
618 }
619
620 /* Set the is_redundant property of the "n" constraints in "cuts",
621  * except "k" to "v".
622  * This is a fairly tricky operation as it bypasses isl_tab.c.
623  * The reason we want to temporarily mark some constraints redundant
624  * is that we want to ignore them in add_wraps.
625  *
626  * Initially all cut constraints are non-redundant, but the
627  * selection of a facet right before the call to this function
628  * may have made some of them redundant.
629  * Likewise, the same constraints are marked non-redundant
630  * in the second call to this function, before they are officially
631  * made non-redundant again in the subsequent rollback.
632  */
633 static void set_is_redundant(struct isl_tab *tab, unsigned n_eq,
634         int *cuts, int n, int k, int v)
635 {
636         int l;
637
638         for (l = 0; l < n; ++l) {
639                 if (l == k)
640                         continue;
641                 tab->con[n_eq + cuts[l]].is_redundant = v;
642         }
643 }
644
645 /* Given a pair of basic maps i and j such that j stick out
646  * of i at n cut constraints, each time by at most one,
647  * try to compute wrapping constraints and replace the two
648  * basic maps by a single basic map.
649  * The other constraints of i are assumed to be valid for j.
650  *
651  * The facets of i corresponding to the cut constraints are
652  * wrapped around their ridges, except those ridges determined
653  * by any of the other cut constraints.
654  * The intersections of cut constraints need to be ignored
655  * as the result of wrapping on cur constraint around another
656  * would result in a constraint cutting the union.
657  * In each case, the facets are wrapped to include the union
658  * of the two basic maps.
659  *
660  * The pieces of j that lie at an offset of exactly one from
661  * one of the cut constraints of i are wrapped around their edges.
662  * Here, there is no need to ignore intersections because we
663  * are wrapping around the union of the two basic maps.
664  *
665  * If any wrapping fails, i.e., if we cannot wrap to touch
666  * the union, then we give up.
667  * Otherwise, the pair of basic maps is replaced by their union.
668  */
669 static int wrap_in_facets(struct isl_map *map, int i, int j,
670         int *cuts, int n, struct isl_tab **tabs,
671         int *eq_i, int *ineq_i, int *eq_j, int *ineq_j)
672 {
673         int changed = 0;
674         isl_mat *wraps = NULL;
675         isl_set *set = NULL;
676         isl_vec *bound = NULL;
677         unsigned total = isl_basic_map_total_dim(map->p[i]);
678         int max_wrap;
679         int k;
680         struct isl_tab_undo *snap_i, *snap_j;
681
682         if (isl_tab_extend_cons(tabs[j], 1) < 0)
683                 goto error;
684
685         max_wrap = 2 * (map->p[i]->n_eq + map->p[j]->n_eq) +
686                     map->p[i]->n_ineq + map->p[j]->n_ineq;
687         max_wrap *= n;
688
689         set = isl_set_union(set_from_updated_bmap(map->p[i], tabs[i]),
690                             set_from_updated_bmap(map->p[j], tabs[j]));
691         wraps = isl_mat_alloc(map->ctx, max_wrap, 1 + total);
692         bound = isl_vec_alloc(map->ctx, 1 + total);
693         if (!set || !wraps || !bound)
694                 goto error;
695
696         snap_i = isl_tab_snap(tabs[i]);
697         snap_j = isl_tab_snap(tabs[j]);
698
699         wraps->n_row = 0;
700
701         for (k = 0; k < n; ++k) {
702                 tabs[i] = isl_tab_select_facet(tabs[i],
703                                                 map->p[i]->n_eq + cuts[k]);
704                 if (isl_tab_detect_redundant(tabs[i]) < 0)
705                         goto error;
706                 set_is_redundant(tabs[i], map->p[i]->n_eq, cuts, n, k, 1);
707
708                 isl_seq_neg(bound->el, map->p[i]->ineq[cuts[k]], 1 + total);
709                 if (add_wraps(wraps, map->p[i], tabs[i], bound->el, set) < 0)
710                         goto error;
711
712                 set_is_redundant(tabs[i], map->p[i]->n_eq, cuts, n, k, 0);
713                 if (isl_tab_rollback(tabs[i], snap_i) < 0)
714                         goto error;
715
716                 if (!wraps->n_row)
717                         break;
718
719                 isl_seq_cpy(bound->el, map->p[i]->ineq[cuts[k]], 1 + total);
720                 isl_int_add_ui(bound->el[0], bound->el[0], 1);
721                 tabs[j] = isl_tab_add_eq(tabs[j], bound->el);
722                 if (isl_tab_detect_redundant(tabs[j]) < 0)
723                         goto error;
724
725                 if (!tabs[j]->empty &&
726                     add_wraps(wraps, map->p[j], tabs[j], bound->el, set) < 0)
727                         goto error;
728
729                 if (isl_tab_rollback(tabs[j], snap_j) < 0)
730                         goto error;
731
732                 if (!wraps->n_row)
733                         break;
734         }
735
736         if (k == n)
737                 changed = fuse(map, i, j, tabs,
738                                 eq_i, ineq_i, eq_j, ineq_j, wraps);
739
740         isl_vec_free(bound);
741         isl_mat_free(wraps);
742         isl_set_free(set);
743
744         return changed;
745 error:
746         isl_vec_free(bound);
747         isl_mat_free(wraps);
748         isl_set_free(set);
749         return -1;
750 }
751
752 /* Given two basic sets i and j such that i has not cut equalities,
753  * check if relaxing all the cut inequalities of i by one turns
754  * them into valid constraint for j and check if we can wrap in
755  * the bits that are sticking out.
756  * If so, replace the pair by their union.
757  *
758  * We first check if all relaxed cut inequalities of i are valid for j
759  * and then try to wrap in the intersections of the relaxed cut inequalities
760  * with j.
761  *
762  * During this wrapping, we consider the points of j that lie at a distance
763  * of exactly 1 from i.  In particular, we ignore the points that lie in
764  * between this lower-dimensional space and the basic map i.
765  * We can therefore only apply this to integer maps.
766  *        ____                    _____
767  *       / ___|_                 /     \
768  *      / |    |                /      |
769  *      \ |    |        =>      \      |
770  *       \|____|                 \     |
771  *        \___|                   \____/
772  *
773  *       _____                   ______
774  *      | ____|_                |      \
775  *      | |     |               |       |
776  *      | |     |       =>      |       |
777  *      |_|     |               |       |
778  *        |_____|                \______|
779  *
780  *       _______
781  *      |       |
782  *      |  |\   |
783  *      |  | \  |
784  *      |  |  \ |
785  *      |  |   \|
786  *      |  |    \
787  *      |  |_____\
788  *      |       |
789  *      |_______|
790  *
791  * Wrapping can fail if the result of wrapping one of the facets
792  * around its edges does not produce any new facet constraint.
793  * In particular, this happens when we try to wrap in unbounded sets.
794  *
795  *       _______________________________________________________________________
796  *      |
797  *      |  ___
798  *      | |   |
799  *      |_|   |_________________________________________________________________
800  *        |___|
801  *
802  * The following is not an acceptable result of coalescing the above two
803  * sets as it includes extra integer points.
804  *       _______________________________________________________________________
805  *      |
806  *      |     
807  *      |      
808  *      |
809  *       \______________________________________________________________________
810  */
811 static int can_wrap_in_set(struct isl_map *map, int i, int j,
812         struct isl_tab **tabs, int *eq_i, int *ineq_i, int *eq_j, int *ineq_j)
813 {
814         int changed = 0;
815         int k, l, m;
816         unsigned total = isl_basic_map_total_dim(map->p[i]);
817         struct isl_tab_undo *snap;
818         int n;
819         int *cuts = NULL;
820
821         if (ISL_F_ISSET(map->p[i], ISL_BASIC_MAP_RATIONAL) ||
822             ISL_F_ISSET(map->p[j], ISL_BASIC_MAP_RATIONAL))
823                 return 0;
824
825         n = count(ineq_i, map->p[i]->n_ineq, STATUS_CUT);
826         if (n == 0)
827                 return 0;
828
829         cuts = isl_alloc_array(map->ctx, int, n);
830         if (!cuts)
831                 return -1;
832
833         for (k = 0, m = 0; m < n; ++k) {
834                 enum isl_ineq_type type;
835
836                 if (ineq_i[k] != STATUS_CUT)
837                         continue;
838
839                 isl_int_add_ui(map->p[i]->ineq[k][0], map->p[i]->ineq[k][0], 1);
840                 type = isl_tab_ineq_type(tabs[j], map->p[i]->ineq[k]);
841                 isl_int_sub_ui(map->p[i]->ineq[k][0], map->p[i]->ineq[k][0], 1);
842                 if (type == isl_ineq_error)
843                         goto error;
844                 if (type != isl_ineq_redundant)
845                         break;
846                 cuts[m] = k;
847                 ++m;
848         }
849
850         if (m == n)
851                 changed = wrap_in_facets(map, i, j, cuts, n, tabs,
852                                          eq_i, ineq_i, eq_j, ineq_j);
853
854         free(cuts);
855
856         return changed;
857 error:
858         free(cuts);
859         return -1;
860 }
861
862 /* Check if either i or j has a single cut constraint that can
863  * be used to wrap in (a facet of) the other basic set.
864  * if so, replace the pair by their union.
865  */
866 static int check_wrap(struct isl_map *map, int i, int j,
867         struct isl_tab **tabs, int *eq_i, int *ineq_i, int *eq_j, int *ineq_j)
868 {
869         int changed = 0;
870
871         if (!any(eq_i, 2 * map->p[i]->n_eq, STATUS_CUT))
872                 changed = can_wrap_in_set(map, i, j, tabs,
873                                             eq_i, ineq_i, eq_j, ineq_j);
874         if (changed)
875                 return changed;
876
877         if (!any(eq_j, 2 * map->p[j]->n_eq, STATUS_CUT))
878                 changed = can_wrap_in_set(map, j, i, tabs,
879                                             eq_j, ineq_j, eq_i, ineq_i);
880         return changed;
881 }
882
883 /* At least one of the basic maps has an equality that is adjacent
884  * to inequality.  Make sure that only one of the basic maps has
885  * such an equality and that the other basic map has exactly one
886  * inequality adjacent to an equality.
887  * We call the basic map that has the inequality "i" and the basic
888  * map that has the equality "j".
889  * If "i" has any "cut" (in)equality, then relaxing the inequality
890  * by one would not result in a basic map that contains the other
891  * basic map.
892  */
893 static int check_adj_eq(struct isl_map *map, int i, int j,
894         struct isl_tab **tabs, int *eq_i, int *ineq_i, int *eq_j, int *ineq_j)
895 {
896         int changed = 0;
897         int k;
898
899         if (any(eq_i, 2 * map->p[i]->n_eq, STATUS_ADJ_INEQ) &&
900             any(eq_j, 2 * map->p[j]->n_eq, STATUS_ADJ_INEQ))
901                 /* ADJ EQ TOO MANY */
902                 return 0;
903
904         if (any(eq_i, 2 * map->p[i]->n_eq, STATUS_ADJ_INEQ))
905                 return check_adj_eq(map, j, i, tabs,
906                                         eq_j, ineq_j, eq_i, ineq_i);
907
908         /* j has an equality adjacent to an inequality in i */
909
910         if (any(eq_i, 2 * map->p[i]->n_eq, STATUS_CUT))
911                 return 0;
912         if (any(ineq_i, map->p[i]->n_ineq, STATUS_CUT))
913                 /* ADJ EQ CUT */
914                 return 0;
915         if (count(eq_j, 2 * map->p[j]->n_eq, STATUS_ADJ_INEQ) != 1 ||
916             count(ineq_i, map->p[i]->n_ineq, STATUS_ADJ_EQ) != 1 ||
917             any(ineq_j, map->p[j]->n_ineq, STATUS_ADJ_EQ) ||
918             any(ineq_i, map->p[i]->n_ineq, STATUS_ADJ_INEQ) ||
919             any(ineq_j, map->p[j]->n_ineq, STATUS_ADJ_INEQ))
920                 /* ADJ EQ TOO MANY */
921                 return 0;
922
923         for (k = 0; k < map->p[i]->n_ineq ; ++k)
924                 if (ineq_i[k] == STATUS_ADJ_EQ)
925                         break;
926
927         changed = is_extension(map, i, j, k, tabs, eq_i, ineq_i, eq_j, ineq_j);
928         if (changed)
929                 return changed;
930
931         changed = can_wrap_in_facet(map, i, j, k, tabs, eq_i, ineq_i, eq_j, ineq_j);
932
933         return changed;
934 }
935
936 /* Check if the union of the given pair of basic maps
937  * can be represented by a single basic map.
938  * If so, replace the pair by the single basic map and return 1.
939  * Otherwise, return 0;
940  *
941  * We first check the effect of each constraint of one basic map
942  * on the other basic map.
943  * The constraint may be
944  *      redundant       the constraint is redundant in its own
945  *                      basic map and should be ignore and removed
946  *                      in the end
947  *      valid           all (integer) points of the other basic map
948  *                      satisfy the constraint
949  *      separate        no (integer) point of the other basic map
950  *                      satisfies the constraint
951  *      cut             some but not all points of the other basic map
952  *                      satisfy the constraint
953  *      adj_eq          the given constraint is adjacent (on the outside)
954  *                      to an equality of the other basic map
955  *      adj_ineq        the given constraint is adjacent (on the outside)
956  *                      to an inequality of the other basic map
957  *
958  * We consider six cases in which we can replace the pair by a single
959  * basic map.  We ignore all "redundant" constraints.
960  *
961  *      1. all constraints of one basic map are valid
962  *              => the other basic map is a subset and can be removed
963  *
964  *      2. all constraints of both basic maps are either "valid" or "cut"
965  *         and the facets corresponding to the "cut" constraints
966  *         of one of the basic maps lies entirely inside the other basic map
967  *              => the pair can be replaced by a basic map consisting
968  *                 of the valid constraints in both basic maps
969  *
970  *      3. there is a single pair of adjacent inequalities
971  *         (all other constraints are "valid")
972  *              => the pair can be replaced by a basic map consisting
973  *                 of the valid constraints in both basic maps
974  *
975  *      4. there is a single adjacent pair of an inequality and an equality,
976  *         the other constraints of the basic map containing the inequality are
977  *         "valid".  Moreover, if the inequality the basic map is relaxed
978  *         and then turned into an equality, then resulting facet lies
979  *         entirely inside the other basic map
980  *              => the pair can be replaced by the basic map containing
981  *                 the inequality, with the inequality relaxed.
982  *
983  *      5. there is a single adjacent pair of an inequality and an equality,
984  *         the other constraints of the basic map containing the inequality are
985  *         "valid".  Moreover, the facets corresponding to both
986  *         the inequality and the equality can be wrapped around their
987  *         ridges to include the other basic map
988  *              => the pair can be replaced by a basic map consisting
989  *                 of the valid constraints in both basic maps together
990  *                 with all wrapping constraints
991  *
992  *      6. one of the basic maps extends beyond the other by at most one.
993  *         Moreover, the facets corresponding to the cut constraints and
994  *         the pieces of the other basic map at offset one from these cut
995  *         constraints can be wrapped around their ridges to include
996  *         the unione of the two basic maps
997  *              => the pair can be replaced by a basic map consisting
998  *                 of the valid constraints in both basic maps together
999  *                 with all wrapping constraints
1000  *
1001  * Throughout the computation, we maintain a collection of tableaus
1002  * corresponding to the basic maps.  When the basic maps are dropped
1003  * or combined, the tableaus are modified accordingly.
1004  */
1005 static int coalesce_pair(struct isl_map *map, int i, int j,
1006         struct isl_tab **tabs)
1007 {
1008         int changed = 0;
1009         int *eq_i = NULL;
1010         int *eq_j = NULL;
1011         int *ineq_i = NULL;
1012         int *ineq_j = NULL;
1013
1014         eq_i = eq_status_in(map, i, j, tabs);
1015         if (any(eq_i, 2 * map->p[i]->n_eq, STATUS_ERROR))
1016                 goto error;
1017         if (any(eq_i, 2 * map->p[i]->n_eq, STATUS_SEPARATE))
1018                 goto done;
1019
1020         eq_j = eq_status_in(map, j, i, tabs);
1021         if (any(eq_j, 2 * map->p[j]->n_eq, STATUS_ERROR))
1022                 goto error;
1023         if (any(eq_j, 2 * map->p[j]->n_eq, STATUS_SEPARATE))
1024                 goto done;
1025
1026         ineq_i = ineq_status_in(map, i, j, tabs);
1027         if (any(ineq_i, map->p[i]->n_ineq, STATUS_ERROR))
1028                 goto error;
1029         if (any(ineq_i, map->p[i]->n_ineq, STATUS_SEPARATE))
1030                 goto done;
1031
1032         ineq_j = ineq_status_in(map, j, i, tabs);
1033         if (any(ineq_j, map->p[j]->n_ineq, STATUS_ERROR))
1034                 goto error;
1035         if (any(ineq_j, map->p[j]->n_ineq, STATUS_SEPARATE))
1036                 goto done;
1037
1038         if (all(eq_i, 2 * map->p[i]->n_eq, STATUS_VALID) &&
1039             all(ineq_i, map->p[i]->n_ineq, STATUS_VALID)) {
1040                 drop(map, j, tabs);
1041                 changed = 1;
1042         } else if (all(eq_j, 2 * map->p[j]->n_eq, STATUS_VALID) &&
1043                    all(ineq_j, map->p[j]->n_ineq, STATUS_VALID)) {
1044                 drop(map, i, tabs);
1045                 changed = 1;
1046         } else if (any(eq_i, 2 * map->p[i]->n_eq, STATUS_ADJ_EQ) ||
1047                    any(eq_j, 2 * map->p[j]->n_eq, STATUS_ADJ_EQ)) {
1048                 /* ADJ EQ PAIR */
1049         } else if (any(eq_i, 2 * map->p[i]->n_eq, STATUS_ADJ_INEQ) ||
1050                    any(eq_j, 2 * map->p[j]->n_eq, STATUS_ADJ_INEQ)) {
1051                 changed = check_adj_eq(map, i, j, tabs,
1052                                         eq_i, ineq_i, eq_j, ineq_j);
1053         } else if (any(ineq_i, map->p[i]->n_ineq, STATUS_ADJ_EQ) ||
1054                    any(ineq_j, map->p[j]->n_ineq, STATUS_ADJ_EQ)) {
1055                 /* Can't happen */
1056                 /* BAD ADJ INEQ */
1057         } else if (any(ineq_i, map->p[i]->n_ineq, STATUS_ADJ_INEQ) ||
1058                    any(ineq_j, map->p[j]->n_ineq, STATUS_ADJ_INEQ)) {
1059                 if (!any(eq_i, 2 * map->p[i]->n_eq, STATUS_CUT) &&
1060                     !any(eq_j, 2 * map->p[j]->n_eq, STATUS_CUT))
1061                         changed = check_adj_ineq(map, i, j, tabs,
1062                                                  ineq_i, ineq_j);
1063         } else {
1064                 if (!any(eq_i, 2 * map->p[i]->n_eq, STATUS_CUT) &&
1065                     !any(eq_j, 2 * map->p[j]->n_eq, STATUS_CUT))
1066                         changed = check_facets(map, i, j, tabs, ineq_i, ineq_j);
1067                 if (!changed)
1068                         changed = check_wrap(map, i, j, tabs,
1069                                                 eq_i, ineq_i, eq_j, ineq_j);
1070         }
1071
1072 done:
1073         free(eq_i);
1074         free(eq_j);
1075         free(ineq_i);
1076         free(ineq_j);
1077         return changed;
1078 error:
1079         free(eq_i);
1080         free(eq_j);
1081         free(ineq_i);
1082         free(ineq_j);
1083         return -1;
1084 }
1085
1086 static struct isl_map *coalesce(struct isl_map *map, struct isl_tab **tabs)
1087 {
1088         int i, j;
1089
1090         for (i = map->n - 2; i >= 0; --i)
1091 restart:
1092                 for (j = i + 1; j < map->n; ++j) {
1093                         int changed;
1094                         changed = coalesce_pair(map, i, j, tabs);
1095                         if (changed < 0)
1096                                 goto error;
1097                         if (changed)
1098                                 goto restart;
1099                 }
1100         return map;
1101 error:
1102         isl_map_free(map);
1103         return NULL;
1104 }
1105
1106 /* For each pair of basic maps in the map, check if the union of the two
1107  * can be represented by a single basic map.
1108  * If so, replace the pair by the single basic map and start over.
1109  */
1110 struct isl_map *isl_map_coalesce(struct isl_map *map)
1111 {
1112         int i;
1113         unsigned n;
1114         struct isl_tab **tabs = NULL;
1115
1116         if (!map)
1117                 return NULL;
1118
1119         if (map->n <= 1)
1120                 return map;
1121
1122         map = isl_map_align_divs(map);
1123
1124         tabs = isl_calloc_array(map->ctx, struct isl_tab *, map->n);
1125         if (!tabs)
1126                 goto error;
1127
1128         n = map->n;
1129         for (i = 0; i < map->n; ++i) {
1130                 tabs[i] = isl_tab_from_basic_map(map->p[i]);
1131                 if (!tabs[i])
1132                         goto error;
1133                 if (!ISL_F_ISSET(map->p[i], ISL_BASIC_MAP_NO_IMPLICIT))
1134                         tabs[i] = isl_tab_detect_implicit_equalities(tabs[i]);
1135                 if (!ISL_F_ISSET(map->p[i], ISL_BASIC_MAP_NO_REDUNDANT))
1136                         if (isl_tab_detect_redundant(tabs[i]) < 0)
1137                                 goto error;
1138         }
1139         for (i = map->n - 1; i >= 0; --i)
1140                 if (tabs[i]->empty)
1141                         drop(map, i, tabs);
1142
1143         map = coalesce(map, tabs);
1144
1145         if (map)
1146                 for (i = 0; i < map->n; ++i) {
1147                         map->p[i] = isl_basic_map_update_from_tab(map->p[i],
1148                                                                     tabs[i]);
1149                         map->p[i] = isl_basic_map_finalize(map->p[i]);
1150                         if (!map->p[i])
1151                                 goto error;
1152                         ISL_F_SET(map->p[i], ISL_BASIC_MAP_NO_IMPLICIT);
1153                         ISL_F_SET(map->p[i], ISL_BASIC_MAP_NO_REDUNDANT);
1154                 }
1155
1156         for (i = 0; i < n; ++i)
1157                 isl_tab_free(tabs[i]);
1158
1159         free(tabs);
1160
1161         return map;
1162 error:
1163         if (tabs)
1164                 for (i = 0; i < n; ++i)
1165                         isl_tab_free(tabs[i]);
1166         free(tabs);
1167         return NULL;
1168 }
1169
1170 /* For each pair of basic sets in the set, check if the union of the two
1171  * can be represented by a single basic set.
1172  * If so, replace the pair by the single basic set and start over.
1173  */
1174 struct isl_set *isl_set_coalesce(struct isl_set *set)
1175 {
1176         return (struct isl_set *)isl_map_coalesce((struct isl_map *)set);
1177 }