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