isl_basic_set_opt: avoid invalid access on error path
[platform/upstream/isl.git] / isl_map_simplify.c
1 /*
2  * Copyright 2008-2009 Katholieke Universiteit Leuven
3  * Copyright 2012      Ecole Normale Superieure
4  *
5  * Use of this software is governed by the MIT license
6  *
7  * Written by Sven Verdoolaege, K.U.Leuven, Departement
8  * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
9  * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
10  */
11
12 #include <strings.h>
13 #include <isl_ctx_private.h>
14 #include <isl_map_private.h>
15 #include "isl_equalities.h"
16 #include <isl/map.h>
17 #include <isl/seq.h>
18 #include "isl_tab.h"
19 #include <isl_space_private.h>
20 #include <isl_mat_private.h>
21
22 static void swap_equality(struct isl_basic_map *bmap, int a, int b)
23 {
24         isl_int *t = bmap->eq[a];
25         bmap->eq[a] = bmap->eq[b];
26         bmap->eq[b] = t;
27 }
28
29 static void swap_inequality(struct isl_basic_map *bmap, int a, int b)
30 {
31         if (a != b) {
32                 isl_int *t = bmap->ineq[a];
33                 bmap->ineq[a] = bmap->ineq[b];
34                 bmap->ineq[b] = t;
35         }
36 }
37
38 static void constraint_drop_vars(isl_int *c, unsigned n, unsigned rem)
39 {
40         isl_seq_cpy(c, c + n, rem);
41         isl_seq_clr(c + rem, n);
42 }
43
44 /* Drop n dimensions starting at first.
45  *
46  * In principle, this frees up some extra variables as the number
47  * of columns remains constant, but we would have to extend
48  * the div array too as the number of rows in this array is assumed
49  * to be equal to extra.
50  */
51 struct isl_basic_set *isl_basic_set_drop_dims(
52                 struct isl_basic_set *bset, unsigned first, unsigned n)
53 {
54         int i;
55
56         if (!bset)
57                 goto error;
58
59         isl_assert(bset->ctx, first + n <= bset->dim->n_out, goto error);
60
61         if (n == 0 && !isl_space_get_tuple_name(bset->dim, isl_dim_set))
62                 return bset;
63
64         bset = isl_basic_set_cow(bset);
65         if (!bset)
66                 return NULL;
67
68         for (i = 0; i < bset->n_eq; ++i)
69                 constraint_drop_vars(bset->eq[i]+1+bset->dim->nparam+first, n,
70                                      (bset->dim->n_out-first-n)+bset->extra);
71
72         for (i = 0; i < bset->n_ineq; ++i)
73                 constraint_drop_vars(bset->ineq[i]+1+bset->dim->nparam+first, n,
74                                      (bset->dim->n_out-first-n)+bset->extra);
75
76         for (i = 0; i < bset->n_div; ++i)
77                 constraint_drop_vars(bset->div[i]+1+1+bset->dim->nparam+first, n,
78                                      (bset->dim->n_out-first-n)+bset->extra);
79
80         bset->dim = isl_space_drop_outputs(bset->dim, first, n);
81         if (!bset->dim)
82                 goto error;
83
84         ISL_F_CLR(bset, ISL_BASIC_SET_NORMALIZED);
85         bset = isl_basic_set_simplify(bset);
86         return isl_basic_set_finalize(bset);
87 error:
88         isl_basic_set_free(bset);
89         return NULL;
90 }
91
92 struct isl_set *isl_set_drop_dims(
93                 struct isl_set *set, unsigned first, unsigned n)
94 {
95         int i;
96
97         if (!set)
98                 goto error;
99
100         isl_assert(set->ctx, first + n <= set->dim->n_out, goto error);
101
102         if (n == 0 && !isl_space_get_tuple_name(set->dim, isl_dim_set))
103                 return set;
104         set = isl_set_cow(set);
105         if (!set)
106                 goto error;
107         set->dim = isl_space_drop_outputs(set->dim, first, n);
108         if (!set->dim)
109                 goto error;
110
111         for (i = 0; i < set->n; ++i) {
112                 set->p[i] = isl_basic_set_drop_dims(set->p[i], first, n);
113                 if (!set->p[i])
114                         goto error;
115         }
116
117         ISL_F_CLR(set, ISL_SET_NORMALIZED);
118         return set;
119 error:
120         isl_set_free(set);
121         return NULL;
122 }
123
124 /* Move "n" divs starting at "first" to the end of the list of divs.
125  */
126 static struct isl_basic_map *move_divs_last(struct isl_basic_map *bmap,
127         unsigned first, unsigned n)
128 {
129         isl_int **div;
130         int i;
131
132         if (first + n == bmap->n_div)
133                 return bmap;
134
135         div = isl_alloc_array(bmap->ctx, isl_int *, n);
136         if (!div)
137                 goto error;
138         for (i = 0; i < n; ++i)
139                 div[i] = bmap->div[first + i];
140         for (i = 0; i < bmap->n_div - first - n; ++i)
141                 bmap->div[first + i] = bmap->div[first + n + i];
142         for (i = 0; i < n; ++i)
143                 bmap->div[bmap->n_div - n + i] = div[i];
144         free(div);
145         return bmap;
146 error:
147         isl_basic_map_free(bmap);
148         return NULL;
149 }
150
151 /* Drop "n" dimensions of type "type" starting at "first".
152  *
153  * In principle, this frees up some extra variables as the number
154  * of columns remains constant, but we would have to extend
155  * the div array too as the number of rows in this array is assumed
156  * to be equal to extra.
157  */
158 struct isl_basic_map *isl_basic_map_drop(struct isl_basic_map *bmap,
159         enum isl_dim_type type, unsigned first, unsigned n)
160 {
161         int i;
162         unsigned dim;
163         unsigned offset;
164         unsigned left;
165
166         if (!bmap)
167                 goto error;
168
169         dim = isl_basic_map_dim(bmap, type);
170         isl_assert(bmap->ctx, first + n <= dim, goto error);
171
172         if (n == 0 && !isl_space_is_named_or_nested(bmap->dim, type))
173                 return bmap;
174
175         bmap = isl_basic_map_cow(bmap);
176         if (!bmap)
177                 return NULL;
178
179         offset = isl_basic_map_offset(bmap, type) + first;
180         left = isl_basic_map_total_dim(bmap) - (offset - 1) - n;
181         for (i = 0; i < bmap->n_eq; ++i)
182                 constraint_drop_vars(bmap->eq[i]+offset, n, left);
183
184         for (i = 0; i < bmap->n_ineq; ++i)
185                 constraint_drop_vars(bmap->ineq[i]+offset, n, left);
186
187         for (i = 0; i < bmap->n_div; ++i)
188                 constraint_drop_vars(bmap->div[i]+1+offset, n, left);
189
190         if (type == isl_dim_div) {
191                 bmap = move_divs_last(bmap, first, n);
192                 if (!bmap)
193                         goto error;
194                 isl_basic_map_free_div(bmap, n);
195         } else
196                 bmap->dim = isl_space_drop_dims(bmap->dim, type, first, n);
197         if (!bmap->dim)
198                 goto error;
199
200         ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
201         bmap = isl_basic_map_simplify(bmap);
202         return isl_basic_map_finalize(bmap);
203 error:
204         isl_basic_map_free(bmap);
205         return NULL;
206 }
207
208 __isl_give isl_basic_set *isl_basic_set_drop(__isl_take isl_basic_set *bset,
209         enum isl_dim_type type, unsigned first, unsigned n)
210 {
211         return (isl_basic_set *)isl_basic_map_drop((isl_basic_map *)bset,
212                                                         type, first, n);
213 }
214
215 struct isl_basic_map *isl_basic_map_drop_inputs(
216                 struct isl_basic_map *bmap, unsigned first, unsigned n)
217 {
218         return isl_basic_map_drop(bmap, isl_dim_in, first, n);
219 }
220
221 struct isl_map *isl_map_drop(struct isl_map *map,
222         enum isl_dim_type type, unsigned first, unsigned n)
223 {
224         int i;
225
226         if (!map)
227                 goto error;
228
229         isl_assert(map->ctx, first + n <= isl_map_dim(map, type), goto error);
230
231         if (n == 0 && !isl_space_get_tuple_name(map->dim, type))
232                 return map;
233         map = isl_map_cow(map);
234         if (!map)
235                 goto error;
236         map->dim = isl_space_drop_dims(map->dim, type, first, n);
237         if (!map->dim)
238                 goto error;
239
240         for (i = 0; i < map->n; ++i) {
241                 map->p[i] = isl_basic_map_drop(map->p[i], type, first, n);
242                 if (!map->p[i])
243                         goto error;
244         }
245         ISL_F_CLR(map, ISL_MAP_NORMALIZED);
246
247         return map;
248 error:
249         isl_map_free(map);
250         return NULL;
251 }
252
253 struct isl_set *isl_set_drop(struct isl_set *set,
254         enum isl_dim_type type, unsigned first, unsigned n)
255 {
256         return (isl_set *)isl_map_drop((isl_map *)set, type, first, n);
257 }
258
259 struct isl_map *isl_map_drop_inputs(
260                 struct isl_map *map, unsigned first, unsigned n)
261 {
262         return isl_map_drop(map, isl_dim_in, first, n);
263 }
264
265 /*
266  * We don't cow, as the div is assumed to be redundant.
267  */
268 static struct isl_basic_map *isl_basic_map_drop_div(
269                 struct isl_basic_map *bmap, unsigned div)
270 {
271         int i;
272         unsigned pos;
273
274         if (!bmap)
275                 goto error;
276
277         pos = 1 + isl_space_dim(bmap->dim, isl_dim_all) + div;
278
279         isl_assert(bmap->ctx, div < bmap->n_div, goto error);
280
281         for (i = 0; i < bmap->n_eq; ++i)
282                 constraint_drop_vars(bmap->eq[i]+pos, 1, bmap->extra-div-1);
283
284         for (i = 0; i < bmap->n_ineq; ++i) {
285                 if (!isl_int_is_zero(bmap->ineq[i][pos])) {
286                         isl_basic_map_drop_inequality(bmap, i);
287                         --i;
288                         continue;
289                 }
290                 constraint_drop_vars(bmap->ineq[i]+pos, 1, bmap->extra-div-1);
291         }
292
293         for (i = 0; i < bmap->n_div; ++i)
294                 constraint_drop_vars(bmap->div[i]+1+pos, 1, bmap->extra-div-1);
295
296         if (div != bmap->n_div - 1) {
297                 int j;
298                 isl_int *t = bmap->div[div];
299
300                 for (j = div; j < bmap->n_div - 1; ++j)
301                         bmap->div[j] = bmap->div[j+1];
302
303                 bmap->div[bmap->n_div - 1] = t;
304         }
305         ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
306         isl_basic_map_free_div(bmap, 1);
307
308         return bmap;
309 error:
310         isl_basic_map_free(bmap);
311         return NULL;
312 }
313
314 struct isl_basic_map *isl_basic_map_normalize_constraints(
315         struct isl_basic_map *bmap)
316 {
317         int i;
318         isl_int gcd;
319         unsigned total = isl_basic_map_total_dim(bmap);
320
321         if (!bmap)
322                 return NULL;
323
324         isl_int_init(gcd);
325         for (i = bmap->n_eq - 1; i >= 0; --i) {
326                 isl_seq_gcd(bmap->eq[i]+1, total, &gcd);
327                 if (isl_int_is_zero(gcd)) {
328                         if (!isl_int_is_zero(bmap->eq[i][0])) {
329                                 bmap = isl_basic_map_set_to_empty(bmap);
330                                 break;
331                         }
332                         isl_basic_map_drop_equality(bmap, i);
333                         continue;
334                 }
335                 if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL))
336                         isl_int_gcd(gcd, gcd, bmap->eq[i][0]);
337                 if (isl_int_is_one(gcd))
338                         continue;
339                 if (!isl_int_is_divisible_by(bmap->eq[i][0], gcd)) {
340                         bmap = isl_basic_map_set_to_empty(bmap);
341                         break;
342                 }
343                 isl_seq_scale_down(bmap->eq[i], bmap->eq[i], gcd, 1+total);
344         }
345
346         for (i = bmap->n_ineq - 1; i >= 0; --i) {
347                 isl_seq_gcd(bmap->ineq[i]+1, total, &gcd);
348                 if (isl_int_is_zero(gcd)) {
349                         if (isl_int_is_neg(bmap->ineq[i][0])) {
350                                 bmap = isl_basic_map_set_to_empty(bmap);
351                                 break;
352                         }
353                         isl_basic_map_drop_inequality(bmap, i);
354                         continue;
355                 }
356                 if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL))
357                         isl_int_gcd(gcd, gcd, bmap->ineq[i][0]);
358                 if (isl_int_is_one(gcd))
359                         continue;
360                 isl_int_fdiv_q(bmap->ineq[i][0], bmap->ineq[i][0], gcd);
361                 isl_seq_scale_down(bmap->ineq[i]+1, bmap->ineq[i]+1, gcd, total);
362         }
363         isl_int_clear(gcd);
364
365         return bmap;
366 }
367
368 struct isl_basic_set *isl_basic_set_normalize_constraints(
369         struct isl_basic_set *bset)
370 {
371         return (struct isl_basic_set *)isl_basic_map_normalize_constraints(
372                 (struct isl_basic_map *)bset);
373 }
374
375 /* Remove any common factor in numerator and denominator of the div expression,
376  * not taking into account the constant term.
377  * That is, if the div is of the form
378  *
379  *      floor((a + m f(x))/(m d))
380  *
381  * then replace it by
382  *
383  *      floor((floor(a/m) + f(x))/d)
384  *
385  * The difference {a/m}/d in the argument satisfies 0 <= {a/m}/d < 1/d
386  * and can therefore not influence the result of the floor.
387  */
388 static void normalize_div_expression(__isl_keep isl_basic_map *bmap, int div)
389 {
390         unsigned total = isl_basic_map_total_dim(bmap);
391         isl_ctx *ctx = bmap->ctx;
392
393         if (isl_int_is_zero(bmap->div[div][0]))
394                 return;
395         isl_seq_gcd(bmap->div[div] + 2, total, &ctx->normalize_gcd);
396         isl_int_gcd(ctx->normalize_gcd, ctx->normalize_gcd, bmap->div[div][0]);
397         if (isl_int_is_one(ctx->normalize_gcd))
398                 return;
399         isl_int_fdiv_q(bmap->div[div][1], bmap->div[div][1],
400                         ctx->normalize_gcd);
401         isl_int_divexact(bmap->div[div][0], bmap->div[div][0],
402                         ctx->normalize_gcd);
403         isl_seq_scale_down(bmap->div[div] + 2, bmap->div[div] + 2,
404                         ctx->normalize_gcd, total);
405 }
406
407 /* Remove any common factor in numerator and denominator of a div expression,
408  * not taking into account the constant term.
409  * That is, look for any div of the form
410  *
411  *      floor((a + m f(x))/(m d))
412  *
413  * and replace it by
414  *
415  *      floor((floor(a/m) + f(x))/d)
416  *
417  * The difference {a/m}/d in the argument satisfies 0 <= {a/m}/d < 1/d
418  * and can therefore not influence the result of the floor.
419  */
420 static __isl_give isl_basic_map *normalize_div_expressions(
421         __isl_take isl_basic_map *bmap)
422 {
423         int i;
424
425         if (!bmap)
426                 return NULL;
427         if (bmap->n_div == 0)
428                 return bmap;
429
430         for (i = 0; i < bmap->n_div; ++i)
431                 normalize_div_expression(bmap, i);
432
433         return bmap;
434 }
435
436 /* Assumes divs have been ordered if keep_divs is set.
437  */
438 static void eliminate_var_using_equality(struct isl_basic_map *bmap,
439         unsigned pos, isl_int *eq, int keep_divs, int *progress)
440 {
441         unsigned total;
442         unsigned space_total;
443         int k;
444         int last_div;
445
446         total = isl_basic_map_total_dim(bmap);
447         space_total = isl_space_dim(bmap->dim, isl_dim_all);
448         last_div = isl_seq_last_non_zero(eq + 1 + space_total, bmap->n_div);
449         for (k = 0; k < bmap->n_eq; ++k) {
450                 if (bmap->eq[k] == eq)
451                         continue;
452                 if (isl_int_is_zero(bmap->eq[k][1+pos]))
453                         continue;
454                 if (progress)
455                         *progress = 1;
456                 isl_seq_elim(bmap->eq[k], eq, 1+pos, 1+total, NULL);
457                 isl_seq_normalize(bmap->ctx, bmap->eq[k], 1 + total);
458         }
459
460         for (k = 0; k < bmap->n_ineq; ++k) {
461                 if (isl_int_is_zero(bmap->ineq[k][1+pos]))
462                         continue;
463                 if (progress)
464                         *progress = 1;
465                 isl_seq_elim(bmap->ineq[k], eq, 1+pos, 1+total, NULL);
466                 isl_seq_normalize(bmap->ctx, bmap->ineq[k], 1 + total);
467                 ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
468         }
469
470         for (k = 0; k < bmap->n_div; ++k) {
471                 if (isl_int_is_zero(bmap->div[k][0]))
472                         continue;
473                 if (isl_int_is_zero(bmap->div[k][1+1+pos]))
474                         continue;
475                 if (progress)
476                         *progress = 1;
477                 /* We need to be careful about circular definitions,
478                  * so for now we just remove the definition of div k
479                  * if the equality contains any divs.
480                  * If keep_divs is set, then the divs have been ordered
481                  * and we can keep the definition as long as the result
482                  * is still ordered.
483                  */
484                 if (last_div == -1 || (keep_divs && last_div < k)) {
485                         isl_seq_elim(bmap->div[k]+1, eq,
486                                         1+pos, 1+total, &bmap->div[k][0]);
487                         normalize_div_expression(bmap, k);
488                 } else
489                         isl_seq_clr(bmap->div[k], 1 + total);
490                 ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
491         }
492 }
493
494 /* Assumes divs have been ordered if keep_divs is set.
495  */
496 static void eliminate_div(struct isl_basic_map *bmap, isl_int *eq,
497         unsigned div, int keep_divs)
498 {
499         unsigned pos = isl_space_dim(bmap->dim, isl_dim_all) + div;
500
501         eliminate_var_using_equality(bmap, pos, eq, keep_divs, NULL);
502
503         isl_basic_map_drop_div(bmap, div);
504 }
505
506 /* Check if elimination of div "div" using equality "eq" would not
507  * result in a div depending on a later div.
508  */
509 static int ok_to_eliminate_div(struct isl_basic_map *bmap, isl_int *eq,
510         unsigned div)
511 {
512         int k;
513         int last_div;
514         unsigned space_total = isl_space_dim(bmap->dim, isl_dim_all);
515         unsigned pos = space_total + div;
516
517         last_div = isl_seq_last_non_zero(eq + 1 + space_total, bmap->n_div);
518         if (last_div < 0 || last_div <= div)
519                 return 1;
520
521         for (k = 0; k <= last_div; ++k) {
522                 if (isl_int_is_zero(bmap->div[k][0]))
523                         return 1;
524                 if (!isl_int_is_zero(bmap->div[k][1 + 1 + pos]))
525                         return 0;
526         }
527
528         return 1;
529 }
530
531 /* Elimininate divs based on equalities
532  */
533 static struct isl_basic_map *eliminate_divs_eq(
534                 struct isl_basic_map *bmap, int *progress)
535 {
536         int d;
537         int i;
538         int modified = 0;
539         unsigned off;
540
541         bmap = isl_basic_map_order_divs(bmap);
542
543         if (!bmap)
544                 return NULL;
545
546         off = 1 + isl_space_dim(bmap->dim, isl_dim_all);
547
548         for (d = bmap->n_div - 1; d >= 0 ; --d) {
549                 for (i = 0; i < bmap->n_eq; ++i) {
550                         if (!isl_int_is_one(bmap->eq[i][off + d]) &&
551                             !isl_int_is_negone(bmap->eq[i][off + d]))
552                                 continue;
553                         if (!ok_to_eliminate_div(bmap, bmap->eq[i], d))
554                                 continue;
555                         modified = 1;
556                         *progress = 1;
557                         eliminate_div(bmap, bmap->eq[i], d, 1);
558                         isl_basic_map_drop_equality(bmap, i);
559                         break;
560                 }
561         }
562         if (modified)
563                 return eliminate_divs_eq(bmap, progress);
564         return bmap;
565 }
566
567 /* Elimininate divs based on inequalities
568  */
569 static struct isl_basic_map *eliminate_divs_ineq(
570                 struct isl_basic_map *bmap, int *progress)
571 {
572         int d;
573         int i;
574         unsigned off;
575         struct isl_ctx *ctx;
576
577         if (!bmap)
578                 return NULL;
579
580         ctx = bmap->ctx;
581         off = 1 + isl_space_dim(bmap->dim, isl_dim_all);
582
583         for (d = bmap->n_div - 1; d >= 0 ; --d) {
584                 for (i = 0; i < bmap->n_eq; ++i)
585                         if (!isl_int_is_zero(bmap->eq[i][off + d]))
586                                 break;
587                 if (i < bmap->n_eq)
588                         continue;
589                 for (i = 0; i < bmap->n_ineq; ++i)
590                         if (isl_int_abs_gt(bmap->ineq[i][off + d], ctx->one))
591                                 break;
592                 if (i < bmap->n_ineq)
593                         continue;
594                 *progress = 1;
595                 bmap = isl_basic_map_eliminate_vars(bmap, (off-1)+d, 1);
596                 if (!bmap || ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
597                         break;
598                 bmap = isl_basic_map_drop_div(bmap, d);
599                 if (!bmap)
600                         break;
601         }
602         return bmap;
603 }
604
605 struct isl_basic_map *isl_basic_map_gauss(
606         struct isl_basic_map *bmap, int *progress)
607 {
608         int k;
609         int done;
610         int last_var;
611         unsigned total_var;
612         unsigned total;
613
614         bmap = isl_basic_map_order_divs(bmap);
615
616         if (!bmap)
617                 return NULL;
618
619         total = isl_basic_map_total_dim(bmap);
620         total_var = total - bmap->n_div;
621
622         last_var = total - 1;
623         for (done = 0; done < bmap->n_eq; ++done) {
624                 for (; last_var >= 0; --last_var) {
625                         for (k = done; k < bmap->n_eq; ++k)
626                                 if (!isl_int_is_zero(bmap->eq[k][1+last_var]))
627                                         break;
628                         if (k < bmap->n_eq)
629                                 break;
630                 }
631                 if (last_var < 0)
632                         break;
633                 if (k != done)
634                         swap_equality(bmap, k, done);
635                 if (isl_int_is_neg(bmap->eq[done][1+last_var]))
636                         isl_seq_neg(bmap->eq[done], bmap->eq[done], 1+total);
637
638                 eliminate_var_using_equality(bmap, last_var, bmap->eq[done], 1,
639                                                 progress);
640
641                 if (last_var >= total_var &&
642                     isl_int_is_zero(bmap->div[last_var - total_var][0])) {
643                         unsigned div = last_var - total_var;
644                         isl_seq_neg(bmap->div[div]+1, bmap->eq[done], 1+total);
645                         isl_int_set_si(bmap->div[div][1+1+last_var], 0);
646                         isl_int_set(bmap->div[div][0],
647                                     bmap->eq[done][1+last_var]);
648                         if (progress)
649                                 *progress = 1;
650                         ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
651                 }
652         }
653         if (done == bmap->n_eq)
654                 return bmap;
655         for (k = done; k < bmap->n_eq; ++k) {
656                 if (isl_int_is_zero(bmap->eq[k][0]))
657                         continue;
658                 return isl_basic_map_set_to_empty(bmap);
659         }
660         isl_basic_map_free_equality(bmap, bmap->n_eq-done);
661         return bmap;
662 }
663
664 struct isl_basic_set *isl_basic_set_gauss(
665         struct isl_basic_set *bset, int *progress)
666 {
667         return (struct isl_basic_set*)isl_basic_map_gauss(
668                         (struct isl_basic_map *)bset, progress);
669 }
670
671
672 static unsigned int round_up(unsigned int v)
673 {
674         int old_v = v;
675
676         while (v) {
677                 old_v = v;
678                 v ^= v & -v;
679         }
680         return old_v << 1;
681 }
682
683 static int hash_index(isl_int ***index, unsigned int size, int bits,
684                         struct isl_basic_map *bmap, int k)
685 {
686         int h;
687         unsigned total = isl_basic_map_total_dim(bmap);
688         uint32_t hash = isl_seq_get_hash_bits(bmap->ineq[k]+1, total, bits);
689         for (h = hash; index[h]; h = (h+1) % size)
690                 if (&bmap->ineq[k] != index[h] &&
691                     isl_seq_eq(bmap->ineq[k]+1, index[h][0]+1, total))
692                         break;
693         return h;
694 }
695
696 static int set_hash_index(isl_int ***index, unsigned int size, int bits,
697                           struct isl_basic_set *bset, int k)
698 {
699         return hash_index(index, size, bits, (struct isl_basic_map *)bset, k);
700 }
701
702 /* If we can eliminate more than one div, then we need to make
703  * sure we do it from last div to first div, in order not to
704  * change the position of the other divs that still need to
705  * be removed.
706  */
707 static struct isl_basic_map *remove_duplicate_divs(
708         struct isl_basic_map *bmap, int *progress)
709 {
710         unsigned int size;
711         int *index;
712         int *elim_for;
713         int k, l, h;
714         int bits;
715         struct isl_blk eq;
716         unsigned total_var;
717         unsigned total;
718         struct isl_ctx *ctx;
719
720         bmap = isl_basic_map_order_divs(bmap);
721         if (!bmap || bmap->n_div <= 1)
722                 return bmap;
723
724         total_var = isl_space_dim(bmap->dim, isl_dim_all);
725         total = total_var + bmap->n_div;
726
727         ctx = bmap->ctx;
728         for (k = bmap->n_div - 1; k >= 0; --k)
729                 if (!isl_int_is_zero(bmap->div[k][0]))
730                         break;
731         if (k <= 0)
732                 return bmap;
733
734         elim_for = isl_calloc_array(ctx, int, bmap->n_div);
735         size = round_up(4 * bmap->n_div / 3 - 1);
736         bits = ffs(size) - 1;
737         index = isl_calloc_array(ctx, int, size);
738         if (!index)
739                 return bmap;
740         eq = isl_blk_alloc(ctx, 1+total);
741         if (isl_blk_is_error(eq))
742                 goto out;
743
744         isl_seq_clr(eq.data, 1+total);
745         index[isl_seq_get_hash_bits(bmap->div[k], 2+total, bits)] = k + 1;
746         for (--k; k >= 0; --k) {
747                 uint32_t hash;
748
749                 if (isl_int_is_zero(bmap->div[k][0]))
750                         continue;
751
752                 hash = isl_seq_get_hash_bits(bmap->div[k], 2+total, bits);
753                 for (h = hash; index[h]; h = (h+1) % size)
754                         if (isl_seq_eq(bmap->div[k],
755                                        bmap->div[index[h]-1], 2+total))
756                                 break;
757                 if (index[h]) {
758                         *progress = 1;
759                         l = index[h] - 1;
760                         elim_for[l] = k + 1;
761                 }
762                 index[h] = k+1;
763         }
764         for (l = bmap->n_div - 1; l >= 0; --l) {
765                 if (!elim_for[l])
766                         continue;
767                 k = elim_for[l] - 1;
768                 isl_int_set_si(eq.data[1+total_var+k], -1);
769                 isl_int_set_si(eq.data[1+total_var+l], 1);
770                 eliminate_div(bmap, eq.data, l, 1);
771                 isl_int_set_si(eq.data[1+total_var+k], 0);
772                 isl_int_set_si(eq.data[1+total_var+l], 0);
773         }
774
775         isl_blk_free(ctx, eq);
776 out:
777         free(index);
778         free(elim_for);
779         return bmap;
780 }
781
782 static int n_pure_div_eq(struct isl_basic_map *bmap)
783 {
784         int i, j;
785         unsigned total;
786
787         total = isl_space_dim(bmap->dim, isl_dim_all);
788         for (i = 0, j = bmap->n_div-1; i < bmap->n_eq; ++i) {
789                 while (j >= 0 && isl_int_is_zero(bmap->eq[i][1 + total + j]))
790                         --j;
791                 if (j < 0)
792                         break;
793                 if (isl_seq_first_non_zero(bmap->eq[i] + 1 + total, j) != -1)
794                         return 0;
795         }
796         return i;
797 }
798
799 /* Normalize divs that appear in equalities.
800  *
801  * In particular, we assume that bmap contains some equalities
802  * of the form
803  *
804  *      a x = m * e_i
805  *
806  * and we want to replace the set of e_i by a minimal set and
807  * such that the new e_i have a canonical representation in terms
808  * of the vector x.
809  * If any of the equalities involves more than one divs, then
810  * we currently simply bail out.
811  *
812  * Let us first additionally assume that all equalities involve
813  * a div.  The equalities then express modulo constraints on the
814  * remaining variables and we can use "parameter compression"
815  * to find a minimal set of constraints.  The result is a transformation
816  *
817  *      x = T(x') = x_0 + G x'
818  *
819  * with G a lower-triangular matrix with all elements below the diagonal
820  * non-negative and smaller than the diagonal element on the same row.
821  * We first normalize x_0 by making the same property hold in the affine
822  * T matrix.
823  * The rows i of G with a 1 on the diagonal do not impose any modulo
824  * constraint and simply express x_i = x'_i.
825  * For each of the remaining rows i, we introduce a div and a corresponding
826  * equality.  In particular
827  *
828  *      g_ii e_j = x_i - g_i(x')
829  *
830  * where each x'_k is replaced either by x_k (if g_kk = 1) or the
831  * corresponding div (if g_kk != 1).
832  *
833  * If there are any equalities not involving any div, then we
834  * first apply a variable compression on the variables x:
835  *
836  *      x = C x''       x'' = C_2 x
837  *
838  * and perform the above parameter compression on A C instead of on A.
839  * The resulting compression is then of the form
840  *
841  *      x'' = T(x') = x_0 + G x'
842  *
843  * and in constructing the new divs and the corresponding equalities,
844  * we have to replace each x'', i.e., the x'_k with (g_kk = 1),
845  * by the corresponding row from C_2.
846  */
847 static struct isl_basic_map *normalize_divs(
848         struct isl_basic_map *bmap, int *progress)
849 {
850         int i, j, k;
851         int total;
852         int div_eq;
853         struct isl_mat *B;
854         struct isl_vec *d;
855         struct isl_mat *T = NULL;
856         struct isl_mat *C = NULL;
857         struct isl_mat *C2 = NULL;
858         isl_int v;
859         int *pos;
860         int dropped, needed;
861
862         if (!bmap)
863                 return NULL;
864
865         if (bmap->n_div == 0)
866                 return bmap;
867
868         if (bmap->n_eq == 0)
869                 return bmap;
870
871         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_NORMALIZED_DIVS))
872                 return bmap;
873
874         total = isl_space_dim(bmap->dim, isl_dim_all);
875         div_eq = n_pure_div_eq(bmap);
876         if (div_eq == 0)
877                 return bmap;
878
879         if (div_eq < bmap->n_eq) {
880                 B = isl_mat_sub_alloc6(bmap->ctx, bmap->eq, div_eq,
881                                         bmap->n_eq - div_eq, 0, 1 + total);
882                 C = isl_mat_variable_compression(B, &C2);
883                 if (!C || !C2)
884                         goto error;
885                 if (C->n_col == 0) {
886                         bmap = isl_basic_map_set_to_empty(bmap);
887                         isl_mat_free(C);
888                         isl_mat_free(C2);
889                         goto done;
890                 }
891         }
892
893         d = isl_vec_alloc(bmap->ctx, div_eq);
894         if (!d)
895                 goto error;
896         for (i = 0, j = bmap->n_div-1; i < div_eq; ++i) {
897                 while (j >= 0 && isl_int_is_zero(bmap->eq[i][1 + total + j]))
898                         --j;
899                 isl_int_set(d->block.data[i], bmap->eq[i][1 + total + j]);
900         }
901         B = isl_mat_sub_alloc6(bmap->ctx, bmap->eq, 0, div_eq, 0, 1 + total);
902
903         if (C) {
904                 B = isl_mat_product(B, C);
905                 C = NULL;
906         }
907
908         T = isl_mat_parameter_compression(B, d);
909         if (!T)
910                 goto error;
911         if (T->n_col == 0) {
912                 bmap = isl_basic_map_set_to_empty(bmap);
913                 isl_mat_free(C2);
914                 isl_mat_free(T);
915                 goto done;
916         }
917         isl_int_init(v);
918         for (i = 0; i < T->n_row - 1; ++i) {
919                 isl_int_fdiv_q(v, T->row[1 + i][0], T->row[1 + i][1 + i]);
920                 if (isl_int_is_zero(v))
921                         continue;
922                 isl_mat_col_submul(T, 0, v, 1 + i);
923         }
924         isl_int_clear(v);
925         pos = isl_alloc_array(bmap->ctx, int, T->n_row);
926         if (!pos)
927                 goto error;
928         /* We have to be careful because dropping equalities may reorder them */
929         dropped = 0;
930         for (j = bmap->n_div - 1; j >= 0; --j) {
931                 for (i = 0; i < bmap->n_eq; ++i)
932                         if (!isl_int_is_zero(bmap->eq[i][1 + total + j]))
933                                 break;
934                 if (i < bmap->n_eq) {
935                         bmap = isl_basic_map_drop_div(bmap, j);
936                         isl_basic_map_drop_equality(bmap, i);
937                         ++dropped;
938                 }
939         }
940         pos[0] = 0;
941         needed = 0;
942         for (i = 1; i < T->n_row; ++i) {
943                 if (isl_int_is_one(T->row[i][i]))
944                         pos[i] = i;
945                 else
946                         needed++;
947         }
948         if (needed > dropped) {
949                 bmap = isl_basic_map_extend_space(bmap, isl_space_copy(bmap->dim),
950                                 needed, needed, 0);
951                 if (!bmap)
952                         goto error;
953         }
954         for (i = 1; i < T->n_row; ++i) {
955                 if (isl_int_is_one(T->row[i][i]))
956                         continue;
957                 k = isl_basic_map_alloc_div(bmap);
958                 pos[i] = 1 + total + k;
959                 isl_seq_clr(bmap->div[k] + 1, 1 + total + bmap->n_div);
960                 isl_int_set(bmap->div[k][0], T->row[i][i]);
961                 if (C2)
962                         isl_seq_cpy(bmap->div[k] + 1, C2->row[i], 1 + total);
963                 else
964                         isl_int_set_si(bmap->div[k][1 + i], 1);
965                 for (j = 0; j < i; ++j) {
966                         if (isl_int_is_zero(T->row[i][j]))
967                                 continue;
968                         if (pos[j] < T->n_row && C2)
969                                 isl_seq_submul(bmap->div[k] + 1, T->row[i][j],
970                                                 C2->row[pos[j]], 1 + total);
971                         else
972                                 isl_int_neg(bmap->div[k][1 + pos[j]],
973                                                                 T->row[i][j]);
974                 }
975                 j = isl_basic_map_alloc_equality(bmap);
976                 isl_seq_neg(bmap->eq[j], bmap->div[k]+1, 1+total+bmap->n_div);
977                 isl_int_set(bmap->eq[j][pos[i]], bmap->div[k][0]);
978         }
979         free(pos);
980         isl_mat_free(C2);
981         isl_mat_free(T);
982
983         if (progress)
984                 *progress = 1;
985 done:
986         ISL_F_SET(bmap, ISL_BASIC_MAP_NORMALIZED_DIVS);
987
988         return bmap;
989 error:
990         isl_mat_free(C);
991         isl_mat_free(C2);
992         isl_mat_free(T);
993         return bmap;
994 }
995
996 static struct isl_basic_map *set_div_from_lower_bound(
997         struct isl_basic_map *bmap, int div, int ineq)
998 {
999         unsigned total = 1 + isl_space_dim(bmap->dim, isl_dim_all);
1000
1001         isl_seq_neg(bmap->div[div] + 1, bmap->ineq[ineq], total + bmap->n_div);
1002         isl_int_set(bmap->div[div][0], bmap->ineq[ineq][total + div]);
1003         isl_int_add(bmap->div[div][1], bmap->div[div][1], bmap->div[div][0]);
1004         isl_int_sub_ui(bmap->div[div][1], bmap->div[div][1], 1);
1005         isl_int_set_si(bmap->div[div][1 + total + div], 0);
1006
1007         return bmap;
1008 }
1009
1010 /* Check whether it is ok to define a div based on an inequality.
1011  * To avoid the introduction of circular definitions of divs, we
1012  * do not allow such a definition if the resulting expression would refer to
1013  * any other undefined divs or if any known div is defined in
1014  * terms of the unknown div.
1015  */
1016 static int ok_to_set_div_from_bound(struct isl_basic_map *bmap,
1017         int div, int ineq)
1018 {
1019         int j;
1020         unsigned total = 1 + isl_space_dim(bmap->dim, isl_dim_all);
1021
1022         /* Not defined in terms of unknown divs */
1023         for (j = 0; j < bmap->n_div; ++j) {
1024                 if (div == j)
1025                         continue;
1026                 if (isl_int_is_zero(bmap->ineq[ineq][total + j]))
1027                         continue;
1028                 if (isl_int_is_zero(bmap->div[j][0]))
1029                         return 0;
1030         }
1031
1032         /* No other div defined in terms of this one => avoid loops */
1033         for (j = 0; j < bmap->n_div; ++j) {
1034                 if (div == j)
1035                         continue;
1036                 if (isl_int_is_zero(bmap->div[j][0]))
1037                         continue;
1038                 if (!isl_int_is_zero(bmap->div[j][1 + total + div]))
1039                         return 0;
1040         }
1041
1042         return 1;
1043 }
1044
1045 /* Given two constraints "k" and "l" that are opposite to each other,
1046  * except for the constant term, check if we can use them
1047  * to obtain an expression for one of the hitherto unknown divs.
1048  * "sum" is the sum of the constant terms of the constraints.
1049  * If this sum is strictly smaller than the coefficient of one
1050  * of the divs, then this pair can be used define the div.
1051  * To avoid the introduction of circular definitions of divs, we
1052  * do not use the pair if the resulting expression would refer to
1053  * any other undefined divs or if any known div is defined in
1054  * terms of the unknown div.
1055  */
1056 static struct isl_basic_map *check_for_div_constraints(
1057         struct isl_basic_map *bmap, int k, int l, isl_int sum, int *progress)
1058 {
1059         int i;
1060         unsigned total = 1 + isl_space_dim(bmap->dim, isl_dim_all);
1061
1062         for (i = 0; i < bmap->n_div; ++i) {
1063                 if (!isl_int_is_zero(bmap->div[i][0]))
1064                         continue;
1065                 if (isl_int_is_zero(bmap->ineq[k][total + i]))
1066                         continue;
1067                 if (isl_int_abs_ge(sum, bmap->ineq[k][total + i]))
1068                         continue;
1069                 if (!ok_to_set_div_from_bound(bmap, i, k))
1070                         break;
1071                 if (isl_int_is_pos(bmap->ineq[k][total + i]))
1072                         bmap = set_div_from_lower_bound(bmap, i, k);
1073                 else
1074                         bmap = set_div_from_lower_bound(bmap, i, l);
1075                 if (progress)
1076                         *progress = 1;
1077                 break;
1078         }
1079         return bmap;
1080 }
1081
1082 static struct isl_basic_map *remove_duplicate_constraints(
1083         struct isl_basic_map *bmap, int *progress, int detect_divs)
1084 {
1085         unsigned int size;
1086         isl_int ***index;
1087         int k, l, h;
1088         int bits;
1089         unsigned total = isl_basic_map_total_dim(bmap);
1090         isl_int sum;
1091         isl_ctx *ctx;
1092
1093         if (!bmap || bmap->n_ineq <= 1)
1094                 return bmap;
1095
1096         size = round_up(4 * (bmap->n_ineq+1) / 3 - 1);
1097         bits = ffs(size) - 1;
1098         ctx = isl_basic_map_get_ctx(bmap);
1099         index = isl_calloc_array(ctx, isl_int **, size);
1100         if (!index)
1101                 return bmap;
1102
1103         index[isl_seq_get_hash_bits(bmap->ineq[0]+1, total, bits)] = &bmap->ineq[0];
1104         for (k = 1; k < bmap->n_ineq; ++k) {
1105                 h = hash_index(index, size, bits, bmap, k);
1106                 if (!index[h]) {
1107                         index[h] = &bmap->ineq[k];
1108                         continue;
1109                 }
1110                 if (progress)
1111                         *progress = 1;
1112                 l = index[h] - &bmap->ineq[0];
1113                 if (isl_int_lt(bmap->ineq[k][0], bmap->ineq[l][0]))
1114                         swap_inequality(bmap, k, l);
1115                 isl_basic_map_drop_inequality(bmap, k);
1116                 --k;
1117         }
1118         isl_int_init(sum);
1119         for (k = 0; k < bmap->n_ineq-1; ++k) {
1120                 isl_seq_neg(bmap->ineq[k]+1, bmap->ineq[k]+1, total);
1121                 h = hash_index(index, size, bits, bmap, k);
1122                 isl_seq_neg(bmap->ineq[k]+1, bmap->ineq[k]+1, total);
1123                 if (!index[h])
1124                         continue;
1125                 l = index[h] - &bmap->ineq[0];
1126                 isl_int_add(sum, bmap->ineq[k][0], bmap->ineq[l][0]);
1127                 if (isl_int_is_pos(sum)) {
1128                         if (detect_divs)
1129                                 bmap = check_for_div_constraints(bmap, k, l,
1130                                                                  sum, progress);
1131                         continue;
1132                 }
1133                 if (isl_int_is_zero(sum)) {
1134                         /* We need to break out of the loop after these
1135                          * changes since the contents of the hash
1136                          * will no longer be valid.
1137                          * Plus, we probably we want to regauss first.
1138                          */
1139                         if (progress)
1140                                 *progress = 1;
1141                         isl_basic_map_drop_inequality(bmap, l);
1142                         isl_basic_map_inequality_to_equality(bmap, k);
1143                 } else
1144                         bmap = isl_basic_map_set_to_empty(bmap);
1145                 break;
1146         }
1147         isl_int_clear(sum);
1148
1149         free(index);
1150         return bmap;
1151 }
1152
1153
1154 /* Eliminate knowns divs from constraints where they appear with
1155  * a (positive or negative) unit coefficient.
1156  *
1157  * That is, replace
1158  *
1159  *      floor(e/m) + f >= 0
1160  *
1161  * by
1162  *
1163  *      e + m f >= 0
1164  *
1165  * and
1166  *
1167  *      -floor(e/m) + f >= 0
1168  *
1169  * by
1170  *
1171  *      -e + m f + m - 1 >= 0
1172  *
1173  * The first conversion is valid because floor(e/m) >= -f is equivalent
1174  * to e/m >= -f because -f is an integral expression.
1175  * The second conversion follows from the fact that
1176  *
1177  *      -floor(e/m) = ceil(-e/m) = floor((-e + m - 1)/m)
1178  *
1179  *
1180  * We skip integral divs, i.e., those with denominator 1, as we would
1181  * risk eliminating the div from the div constraints.  We do not need
1182  * to handle those divs here anyway since the div constraints will turn
1183  * out to form an equality and this equality can then be use to eliminate
1184  * the div from all constraints.
1185  */
1186 static __isl_give isl_basic_map *eliminate_unit_divs(
1187         __isl_take isl_basic_map *bmap, int *progress)
1188 {
1189         int i, j;
1190         isl_ctx *ctx;
1191         unsigned total;
1192
1193         if (!bmap)
1194                 return NULL;
1195
1196         ctx = isl_basic_map_get_ctx(bmap);
1197         total = 1 + isl_space_dim(bmap->dim, isl_dim_all);
1198
1199         for (i = 0; i < bmap->n_div; ++i) {
1200                 if (isl_int_is_zero(bmap->div[i][0]))
1201                         continue;
1202                 if (isl_int_is_one(bmap->div[i][0]))
1203                         continue;
1204                 for (j = 0; j < bmap->n_ineq; ++j) {
1205                         int s;
1206
1207                         if (!isl_int_is_one(bmap->ineq[j][total + i]) &&
1208                             !isl_int_is_negone(bmap->ineq[j][total + i]))
1209                                 continue;
1210
1211                         *progress = 1;
1212
1213                         s = isl_int_sgn(bmap->ineq[j][total + i]);
1214                         isl_int_set_si(bmap->ineq[j][total + i], 0);
1215                         if (s < 0)
1216                                 isl_seq_combine(bmap->ineq[j],
1217                                         ctx->negone, bmap->div[i] + 1,
1218                                         bmap->div[i][0], bmap->ineq[j],
1219                                         total + bmap->n_div);
1220                         else
1221                                 isl_seq_combine(bmap->ineq[j],
1222                                         ctx->one, bmap->div[i] + 1,
1223                                         bmap->div[i][0], bmap->ineq[j],
1224                                         total + bmap->n_div);
1225                         if (s < 0) {
1226                                 isl_int_add(bmap->ineq[j][0],
1227                                         bmap->ineq[j][0], bmap->div[i][0]);
1228                                 isl_int_sub_ui(bmap->ineq[j][0],
1229                                         bmap->ineq[j][0], 1);
1230                         }
1231                 }
1232         }
1233
1234         return bmap;
1235 }
1236
1237 struct isl_basic_map *isl_basic_map_simplify(struct isl_basic_map *bmap)
1238 {
1239         int progress = 1;
1240         if (!bmap)
1241                 return NULL;
1242         while (progress) {
1243                 progress = 0;
1244                 if (!bmap)
1245                         break;
1246                 if (isl_basic_map_plain_is_empty(bmap))
1247                         break;
1248                 bmap = isl_basic_map_normalize_constraints(bmap);
1249                 bmap = normalize_div_expressions(bmap);
1250                 bmap = remove_duplicate_divs(bmap, &progress);
1251                 bmap = eliminate_unit_divs(bmap, &progress);
1252                 bmap = eliminate_divs_eq(bmap, &progress);
1253                 bmap = eliminate_divs_ineq(bmap, &progress);
1254                 bmap = isl_basic_map_gauss(bmap, &progress);
1255                 /* requires equalities in normal form */
1256                 bmap = normalize_divs(bmap, &progress);
1257                 bmap = remove_duplicate_constraints(bmap, &progress, 1);
1258         }
1259         return bmap;
1260 }
1261
1262 struct isl_basic_set *isl_basic_set_simplify(struct isl_basic_set *bset)
1263 {
1264         return (struct isl_basic_set *)
1265                 isl_basic_map_simplify((struct isl_basic_map *)bset);
1266 }
1267
1268
1269 int isl_basic_map_is_div_constraint(__isl_keep isl_basic_map *bmap,
1270         isl_int *constraint, unsigned div)
1271 {
1272         unsigned pos;
1273
1274         if (!bmap)
1275                 return -1;
1276
1277         pos = 1 + isl_space_dim(bmap->dim, isl_dim_all) + div;
1278
1279         if (isl_int_eq(constraint[pos], bmap->div[div][0])) {
1280                 int neg;
1281                 isl_int_sub(bmap->div[div][1],
1282                                 bmap->div[div][1], bmap->div[div][0]);
1283                 isl_int_add_ui(bmap->div[div][1], bmap->div[div][1], 1);
1284                 neg = isl_seq_is_neg(constraint, bmap->div[div]+1, pos);
1285                 isl_int_sub_ui(bmap->div[div][1], bmap->div[div][1], 1);
1286                 isl_int_add(bmap->div[div][1],
1287                                 bmap->div[div][1], bmap->div[div][0]);
1288                 if (!neg)
1289                         return 0;
1290                 if (isl_seq_first_non_zero(constraint+pos+1,
1291                                             bmap->n_div-div-1) != -1)
1292                         return 0;
1293         } else if (isl_int_abs_eq(constraint[pos], bmap->div[div][0])) {
1294                 if (!isl_seq_eq(constraint, bmap->div[div]+1, pos))
1295                         return 0;
1296                 if (isl_seq_first_non_zero(constraint+pos+1,
1297                                             bmap->n_div-div-1) != -1)
1298                         return 0;
1299         } else
1300                 return 0;
1301
1302         return 1;
1303 }
1304
1305 int isl_basic_set_is_div_constraint(__isl_keep isl_basic_set *bset,
1306         isl_int *constraint, unsigned div)
1307 {
1308         return isl_basic_map_is_div_constraint(bset, constraint, div);
1309 }
1310
1311
1312 /* If the only constraints a div d=floor(f/m)
1313  * appears in are its two defining constraints
1314  *
1315  *      f - m d >=0
1316  *      -(f - (m - 1)) + m d >= 0
1317  *
1318  * then it can safely be removed.
1319  */
1320 static int div_is_redundant(struct isl_basic_map *bmap, int div)
1321 {
1322         int i;
1323         unsigned pos = 1 + isl_space_dim(bmap->dim, isl_dim_all) + div;
1324
1325         for (i = 0; i < bmap->n_eq; ++i)
1326                 if (!isl_int_is_zero(bmap->eq[i][pos]))
1327                         return 0;
1328
1329         for (i = 0; i < bmap->n_ineq; ++i) {
1330                 if (isl_int_is_zero(bmap->ineq[i][pos]))
1331                         continue;
1332                 if (!isl_basic_map_is_div_constraint(bmap, bmap->ineq[i], div))
1333                         return 0;
1334         }
1335
1336         for (i = 0; i < bmap->n_div; ++i) {
1337                 if (isl_int_is_zero(bmap->div[i][0]))
1338                         continue;
1339                 if (!isl_int_is_zero(bmap->div[i][1+pos]))
1340                         return 0;
1341         }
1342
1343         return 1;
1344 }
1345
1346 /*
1347  * Remove divs that don't occur in any of the constraints or other divs.
1348  * These can arise when dropping some of the variables in a quast
1349  * returned by piplib.
1350  */
1351 static struct isl_basic_map *remove_redundant_divs(struct isl_basic_map *bmap)
1352 {
1353         int i;
1354
1355         if (!bmap)
1356                 return NULL;
1357
1358         for (i = bmap->n_div-1; i >= 0; --i) {
1359                 if (!div_is_redundant(bmap, i))
1360                         continue;
1361                 bmap = isl_basic_map_drop_div(bmap, i);
1362         }
1363         return bmap;
1364 }
1365
1366 struct isl_basic_map *isl_basic_map_finalize(struct isl_basic_map *bmap)
1367 {
1368         bmap = remove_redundant_divs(bmap);
1369         if (!bmap)
1370                 return NULL;
1371         ISL_F_SET(bmap, ISL_BASIC_SET_FINAL);
1372         return bmap;
1373 }
1374
1375 struct isl_basic_set *isl_basic_set_finalize(struct isl_basic_set *bset)
1376 {
1377         return (struct isl_basic_set *)
1378                 isl_basic_map_finalize((struct isl_basic_map *)bset);
1379 }
1380
1381 struct isl_set *isl_set_finalize(struct isl_set *set)
1382 {
1383         int i;
1384
1385         if (!set)
1386                 return NULL;
1387         for (i = 0; i < set->n; ++i) {
1388                 set->p[i] = isl_basic_set_finalize(set->p[i]);
1389                 if (!set->p[i])
1390                         goto error;
1391         }
1392         return set;
1393 error:
1394         isl_set_free(set);
1395         return NULL;
1396 }
1397
1398 struct isl_map *isl_map_finalize(struct isl_map *map)
1399 {
1400         int i;
1401
1402         if (!map)
1403                 return NULL;
1404         for (i = 0; i < map->n; ++i) {
1405                 map->p[i] = isl_basic_map_finalize(map->p[i]);
1406                 if (!map->p[i])
1407                         goto error;
1408         }
1409         ISL_F_CLR(map, ISL_MAP_NORMALIZED);
1410         return map;
1411 error:
1412         isl_map_free(map);
1413         return NULL;
1414 }
1415
1416
1417 /* Remove definition of any div that is defined in terms of the given variable.
1418  * The div itself is not removed.  Functions such as
1419  * eliminate_divs_ineq depend on the other divs remaining in place.
1420  */
1421 static struct isl_basic_map *remove_dependent_vars(struct isl_basic_map *bmap,
1422                                                                         int pos)
1423 {
1424         int i;
1425
1426         if (!bmap)
1427                 return NULL;
1428
1429         for (i = 0; i < bmap->n_div; ++i) {
1430                 if (isl_int_is_zero(bmap->div[i][0]))
1431                         continue;
1432                 if (isl_int_is_zero(bmap->div[i][1+1+pos]))
1433                         continue;
1434                 isl_int_set_si(bmap->div[i][0], 0);
1435         }
1436         return bmap;
1437 }
1438
1439 /* Eliminate the specified variables from the constraints using
1440  * Fourier-Motzkin.  The variables themselves are not removed.
1441  */
1442 struct isl_basic_map *isl_basic_map_eliminate_vars(
1443         struct isl_basic_map *bmap, unsigned pos, unsigned n)
1444 {
1445         int d;
1446         int i, j, k;
1447         unsigned total;
1448         int need_gauss = 0;
1449
1450         if (n == 0)
1451                 return bmap;
1452         if (!bmap)
1453                 return NULL;
1454         total = isl_basic_map_total_dim(bmap);
1455
1456         bmap = isl_basic_map_cow(bmap);
1457         for (d = pos + n - 1; d >= 0 && d >= pos; --d)
1458                 bmap = remove_dependent_vars(bmap, d);
1459         if (!bmap)
1460                 return NULL;
1461
1462         for (d = pos + n - 1;
1463              d >= 0 && d >= total - bmap->n_div && d >= pos; --d)
1464                 isl_seq_clr(bmap->div[d-(total-bmap->n_div)], 2+total);
1465         for (d = pos + n - 1; d >= 0 && d >= pos; --d) {
1466                 int n_lower, n_upper;
1467                 if (!bmap)
1468                         return NULL;
1469                 for (i = 0; i < bmap->n_eq; ++i) {
1470                         if (isl_int_is_zero(bmap->eq[i][1+d]))
1471                                 continue;
1472                         eliminate_var_using_equality(bmap, d, bmap->eq[i], 0, NULL);
1473                         isl_basic_map_drop_equality(bmap, i);
1474                         need_gauss = 1;
1475                         break;
1476                 }
1477                 if (i < bmap->n_eq)
1478                         continue;
1479                 n_lower = 0;
1480                 n_upper = 0;
1481                 for (i = 0; i < bmap->n_ineq; ++i) {
1482                         if (isl_int_is_pos(bmap->ineq[i][1+d]))
1483                                 n_lower++;
1484                         else if (isl_int_is_neg(bmap->ineq[i][1+d]))
1485                                 n_upper++;
1486                 }
1487                 bmap = isl_basic_map_extend_constraints(bmap,
1488                                 0, n_lower * n_upper);
1489                 if (!bmap)
1490                         goto error;
1491                 for (i = bmap->n_ineq - 1; i >= 0; --i) {
1492                         int last;
1493                         if (isl_int_is_zero(bmap->ineq[i][1+d]))
1494                                 continue;
1495                         last = -1;
1496                         for (j = 0; j < i; ++j) {
1497                                 if (isl_int_is_zero(bmap->ineq[j][1+d]))
1498                                         continue;
1499                                 last = j;
1500                                 if (isl_int_sgn(bmap->ineq[i][1+d]) ==
1501                                     isl_int_sgn(bmap->ineq[j][1+d]))
1502                                         continue;
1503                                 k = isl_basic_map_alloc_inequality(bmap);
1504                                 if (k < 0)
1505                                         goto error;
1506                                 isl_seq_cpy(bmap->ineq[k], bmap->ineq[i],
1507                                                 1+total);
1508                                 isl_seq_elim(bmap->ineq[k], bmap->ineq[j],
1509                                                 1+d, 1+total, NULL);
1510                         }
1511                         isl_basic_map_drop_inequality(bmap, i);
1512                         i = last + 1;
1513                 }
1514                 if (n_lower > 0 && n_upper > 0) {
1515                         bmap = isl_basic_map_normalize_constraints(bmap);
1516                         bmap = remove_duplicate_constraints(bmap, NULL, 0);
1517                         bmap = isl_basic_map_gauss(bmap, NULL);
1518                         bmap = isl_basic_map_remove_redundancies(bmap);
1519                         need_gauss = 0;
1520                         if (!bmap)
1521                                 goto error;
1522                         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
1523                                 break;
1524                 }
1525         }
1526         ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
1527         if (need_gauss)
1528                 bmap = isl_basic_map_gauss(bmap, NULL);
1529         return bmap;
1530 error:
1531         isl_basic_map_free(bmap);
1532         return NULL;
1533 }
1534
1535 struct isl_basic_set *isl_basic_set_eliminate_vars(
1536         struct isl_basic_set *bset, unsigned pos, unsigned n)
1537 {
1538         return (struct isl_basic_set *)isl_basic_map_eliminate_vars(
1539                         (struct isl_basic_map *)bset, pos, n);
1540 }
1541
1542 /* Eliminate the specified n dimensions starting at first from the
1543  * constraints, without removing the dimensions from the space.
1544  * If the set is rational, the dimensions are eliminated using Fourier-Motzkin.
1545  * Otherwise, they are projected out and the original space is restored.
1546  */
1547 __isl_give isl_basic_map *isl_basic_map_eliminate(
1548         __isl_take isl_basic_map *bmap,
1549         enum isl_dim_type type, unsigned first, unsigned n)
1550 {
1551         isl_space *space;
1552
1553         if (!bmap)
1554                 return NULL;
1555         if (n == 0)
1556                 return bmap;
1557
1558         if (first + n > isl_basic_map_dim(bmap, type) || first + n < first)
1559                 isl_die(bmap->ctx, isl_error_invalid,
1560                         "index out of bounds", goto error);
1561
1562         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL)) {
1563                 first += isl_basic_map_offset(bmap, type) - 1;
1564                 bmap = isl_basic_map_eliminate_vars(bmap, first, n);
1565                 return isl_basic_map_finalize(bmap);
1566         }
1567
1568         space = isl_basic_map_get_space(bmap);
1569         bmap = isl_basic_map_project_out(bmap, type, first, n);
1570         bmap = isl_basic_map_insert_dims(bmap, type, first, n);
1571         bmap = isl_basic_map_reset_space(bmap, space);
1572         return bmap;
1573 error:
1574         isl_basic_map_free(bmap);
1575         return NULL;
1576 }
1577
1578 __isl_give isl_basic_set *isl_basic_set_eliminate(
1579         __isl_take isl_basic_set *bset,
1580         enum isl_dim_type type, unsigned first, unsigned n)
1581 {
1582         return isl_basic_map_eliminate(bset, type, first, n);
1583 }
1584
1585 /* Don't assume equalities are in order, because align_divs
1586  * may have changed the order of the divs.
1587  */
1588 static void compute_elimination_index(struct isl_basic_map *bmap, int *elim)
1589 {
1590         int d, i;
1591         unsigned total;
1592
1593         total = isl_space_dim(bmap->dim, isl_dim_all);
1594         for (d = 0; d < total; ++d)
1595                 elim[d] = -1;
1596         for (i = 0; i < bmap->n_eq; ++i) {
1597                 for (d = total - 1; d >= 0; --d) {
1598                         if (isl_int_is_zero(bmap->eq[i][1+d]))
1599                                 continue;
1600                         elim[d] = i;
1601                         break;
1602                 }
1603         }
1604 }
1605
1606 static void set_compute_elimination_index(struct isl_basic_set *bset, int *elim)
1607 {
1608         compute_elimination_index((struct isl_basic_map *)bset, elim);
1609 }
1610
1611 static int reduced_using_equalities(isl_int *dst, isl_int *src,
1612         struct isl_basic_map *bmap, int *elim)
1613 {
1614         int d;
1615         int copied = 0;
1616         unsigned total;
1617
1618         total = isl_space_dim(bmap->dim, isl_dim_all);
1619         for (d = total - 1; d >= 0; --d) {
1620                 if (isl_int_is_zero(src[1+d]))
1621                         continue;
1622                 if (elim[d] == -1)
1623                         continue;
1624                 if (!copied) {
1625                         isl_seq_cpy(dst, src, 1 + total);
1626                         copied = 1;
1627                 }
1628                 isl_seq_elim(dst, bmap->eq[elim[d]], 1 + d, 1 + total, NULL);
1629         }
1630         return copied;
1631 }
1632
1633 static int set_reduced_using_equalities(isl_int *dst, isl_int *src,
1634         struct isl_basic_set *bset, int *elim)
1635 {
1636         return reduced_using_equalities(dst, src,
1637                                         (struct isl_basic_map *)bset, elim);
1638 }
1639
1640 static struct isl_basic_set *isl_basic_set_reduce_using_equalities(
1641         struct isl_basic_set *bset, struct isl_basic_set *context)
1642 {
1643         int i;
1644         int *elim;
1645
1646         if (!bset || !context)
1647                 goto error;
1648
1649         if (context->n_eq == 0) {
1650                 isl_basic_set_free(context);
1651                 return bset;
1652         }
1653
1654         bset = isl_basic_set_cow(bset);
1655         if (!bset)
1656                 goto error;
1657
1658         elim = isl_alloc_array(bset->ctx, int, isl_basic_set_n_dim(bset));
1659         if (!elim)
1660                 goto error;
1661         set_compute_elimination_index(context, elim);
1662         for (i = 0; i < bset->n_eq; ++i)
1663                 set_reduced_using_equalities(bset->eq[i], bset->eq[i],
1664                                                         context, elim);
1665         for (i = 0; i < bset->n_ineq; ++i)
1666                 set_reduced_using_equalities(bset->ineq[i], bset->ineq[i],
1667                                                         context, elim);
1668         isl_basic_set_free(context);
1669         free(elim);
1670         bset = isl_basic_set_simplify(bset);
1671         bset = isl_basic_set_finalize(bset);
1672         return bset;
1673 error:
1674         isl_basic_set_free(bset);
1675         isl_basic_set_free(context);
1676         return NULL;
1677 }
1678
1679 static struct isl_basic_set *remove_shifted_constraints(
1680         struct isl_basic_set *bset, struct isl_basic_set *context)
1681 {
1682         unsigned int size;
1683         isl_int ***index;
1684         int bits;
1685         int k, h, l;
1686         isl_ctx *ctx;
1687
1688         if (!bset)
1689                 return NULL;
1690
1691         size = round_up(4 * (context->n_ineq+1) / 3 - 1);
1692         bits = ffs(size) - 1;
1693         ctx = isl_basic_set_get_ctx(bset);
1694         index = isl_calloc_array(ctx, isl_int **, size);
1695         if (!index)
1696                 return bset;
1697
1698         for (k = 0; k < context->n_ineq; ++k) {
1699                 h = set_hash_index(index, size, bits, context, k);
1700                 index[h] = &context->ineq[k];
1701         }
1702         for (k = 0; k < bset->n_ineq; ++k) {
1703                 h = set_hash_index(index, size, bits, bset, k);
1704                 if (!index[h])
1705                         continue;
1706                 l = index[h] - &context->ineq[0];
1707                 if (isl_int_lt(bset->ineq[k][0], context->ineq[l][0]))
1708                         continue;
1709                 bset = isl_basic_set_cow(bset);
1710                 if (!bset)
1711                         goto error;
1712                 isl_basic_set_drop_inequality(bset, k);
1713                 --k;
1714         }
1715         free(index);
1716         return bset;
1717 error:
1718         free(index);
1719         return bset;
1720 }
1721
1722 /* Does the (linear part of a) constraint "c" involve any of the "len"
1723  * "relevant" dimensions?
1724  */
1725 static int is_related(isl_int *c, int len, int *relevant)
1726 {
1727         int i;
1728
1729         for (i = 0; i < len; ++i) {
1730                 if (!relevant[i])
1731                         continue;
1732                 if (!isl_int_is_zero(c[i]))
1733                         return 1;
1734         }
1735
1736         return 0;
1737 }
1738
1739 /* Drop constraints from "bset" that do not involve any of
1740  * the dimensions marked "relevant".
1741  */
1742 static __isl_give isl_basic_set *drop_unrelated_constraints(
1743         __isl_take isl_basic_set *bset, int *relevant)
1744 {
1745         int i, dim;
1746
1747         dim = isl_basic_set_dim(bset, isl_dim_set);
1748         for (i = 0; i < dim; ++i)
1749                 if (!relevant[i])
1750                         break;
1751         if (i >= dim)
1752                 return bset;
1753
1754         for (i = bset->n_eq - 1; i >= 0; --i)
1755                 if (!is_related(bset->eq[i] + 1, dim, relevant))
1756                         isl_basic_set_drop_equality(bset, i);
1757
1758         for (i = bset->n_ineq - 1; i >= 0; --i)
1759                 if (!is_related(bset->ineq[i] + 1, dim, relevant))
1760                         isl_basic_set_drop_inequality(bset, i);
1761
1762         return bset;
1763 }
1764
1765 /* Update the groups in "group" based on the (linear part of a) constraint "c".
1766  *
1767  * In particular, for any variable involved in the constraint,
1768  * find the actual group id from before and replace the group
1769  * of the corresponding variable by the minimal group of all
1770  * the variables involved in the constraint considered so far
1771  * (if this minimum is smaller) or replace the minimum by this group
1772  * (if the minimum is larger).
1773  *
1774  * At the end, all the variables in "c" will (indirectly) point
1775  * to the minimal of the groups that they referred to originally.
1776  */
1777 static void update_groups(int dim, int *group, isl_int *c)
1778 {
1779         int j;
1780         int min = dim;
1781
1782         for (j = 0; j < dim; ++j) {
1783                 if (isl_int_is_zero(c[j]))
1784                         continue;
1785                 while (group[j] >= 0 && group[group[j]] != group[j])
1786                         group[j] = group[group[j]];
1787                 if (group[j] == min)
1788                         continue;
1789                 if (group[j] < min) {
1790                         if (min >= 0 && min < dim)
1791                                 group[min] = group[j];
1792                         min = group[j];
1793                 } else
1794                         group[group[j]] = min;
1795         }
1796 }
1797
1798 /* Drop constraints from "context" that are irrelevant for computing
1799  * the gist of "bset".
1800  *
1801  * In particular, drop constraints in variables that are not related
1802  * to any of the variables involved in the constraints of "bset"
1803  * in the sense that there is no sequence of constraints that connects them.
1804  *
1805  * We construct groups of variables that collect variables that
1806  * (indirectly) appear in some common constraint of "context".
1807  * Each group is identified by the first variable in the group,
1808  * except for the special group of variables that appear in "bset"
1809  * (or are related to those variables), which is identified by -1.
1810  * If group[i] is equal to i (or -1), then the group of i is i (or -1),
1811  * otherwise the group of i is the group of group[i].
1812  *
1813  * We first initialize the -1 group with the variables that appear in "bset".
1814  * Then we initialize groups for the remaining variables.
1815  * Then we iterate over the constraints of "context" and update the
1816  * group of the variables in the constraint by the smallest group.
1817  * Finally, we resolve indirect references to groups by running over
1818  * the variables.
1819  *
1820  * After computing the groups, we drop constraints that do not involve
1821  * any variables in the -1 group.
1822  */
1823 static __isl_give isl_basic_set *drop_irrelevant_constraints(
1824         __isl_take isl_basic_set *context, __isl_keep isl_basic_set *bset)
1825 {
1826         isl_ctx *ctx;
1827         int *group;
1828         int dim;
1829         int i, j;
1830         int last;
1831
1832         if (!context || !bset)
1833                 return isl_basic_set_free(context);
1834
1835         dim = isl_basic_set_dim(bset, isl_dim_set);
1836         ctx = isl_basic_set_get_ctx(bset);
1837         group = isl_calloc_array(ctx, int, dim);
1838
1839         if (!group)
1840                 goto error;
1841
1842         for (i = 0; i < dim; ++i) {
1843                 for (j = 0; j < bset->n_eq; ++j)
1844                         if (!isl_int_is_zero(bset->eq[j][1 + i]))
1845                                 break;
1846                 if (j < bset->n_eq) {
1847                         group[i] = -1;
1848                         continue;
1849                 }
1850                 for (j = 0; j < bset->n_ineq; ++j)
1851                         if (!isl_int_is_zero(bset->ineq[j][1 + i]))
1852                                 break;
1853                 if (j < bset->n_ineq)
1854                         group[i] = -1;
1855         }
1856
1857         last = -1;
1858         for (i = 0; i < dim; ++i)
1859                 if (group[i] >= 0)
1860                         last = group[i] = i;
1861         if (last < 0) {
1862                 free(group);
1863                 return context;
1864         }
1865
1866         for (i = 0; i < context->n_eq; ++i)
1867                 update_groups(dim, group, context->eq[i] + 1);
1868         for (i = 0; i < context->n_ineq; ++i)
1869                 update_groups(dim, group, context->ineq[i] + 1);
1870
1871         for (i = 0; i < dim; ++i)
1872                 if (group[i] >= 0)
1873                         group[i] = group[group[i]];
1874
1875         for (i = 0; i < dim; ++i)
1876                 group[i] = group[i] == -1;
1877
1878         context = drop_unrelated_constraints(context, group);
1879
1880         free(group);
1881         return context;
1882 error:
1883         free(group);
1884         return isl_basic_set_free(context);
1885 }
1886
1887 /* Remove all information from bset that is redundant in the context
1888  * of context.  Both bset and context are assumed to be full-dimensional.
1889  *
1890  * We first remove the inequalities from "bset"
1891  * that are obviously redundant with respect to some inequality in "context".
1892  * Then we remove those constraints from "context" that have become
1893  * irrelevant for computing the gist of "bset".
1894  * Note that this removal of constraints cannot be replaced by
1895  * a factorization because factors in "bset" may still be connected
1896  * to each other through constraints in "context".
1897  *
1898  * If there are any inequalities left, we construct a tableau for
1899  * the context and then add the inequalities of "bset".
1900  * Before adding these inequalities, we freeze all constraints such that
1901  * they won't be considered redundant in terms of the constraints of "bset".
1902  * Then we detect all redundant constraints (among the
1903  * constraints that weren't frozen), first by checking for redundancy in the
1904  * the tableau and then by checking if replacing a constraint by its negation
1905  * would lead to an empty set.  This last step is fairly expensive
1906  * and could be optimized by more reuse of the tableau.
1907  * Finally, we update bset according to the results.
1908  */
1909 static __isl_give isl_basic_set *uset_gist_full(__isl_take isl_basic_set *bset,
1910         __isl_take isl_basic_set *context)
1911 {
1912         int i, k;
1913         isl_basic_set *combined = NULL;
1914         struct isl_tab *tab = NULL;
1915         unsigned context_ineq;
1916         unsigned total;
1917
1918         if (!bset || !context)
1919                 goto error;
1920
1921         if (isl_basic_set_is_universe(bset)) {
1922                 isl_basic_set_free(context);
1923                 return bset;
1924         }
1925
1926         if (isl_basic_set_is_universe(context)) {
1927                 isl_basic_set_free(context);
1928                 return bset;
1929         }
1930
1931         bset = remove_shifted_constraints(bset, context);
1932         if (!bset)
1933                 goto error;
1934         if (bset->n_ineq == 0)
1935                 goto done;
1936
1937         context = drop_irrelevant_constraints(context, bset);
1938         if (!context)
1939                 goto error;
1940         if (isl_basic_set_is_universe(context)) {
1941                 isl_basic_set_free(context);
1942                 return bset;
1943         }
1944
1945         context_ineq = context->n_ineq;
1946         combined = isl_basic_set_cow(isl_basic_set_copy(context));
1947         combined = isl_basic_set_extend_constraints(combined, 0, bset->n_ineq);
1948         tab = isl_tab_from_basic_set(combined, 0);
1949         for (i = 0; i < context_ineq; ++i)
1950                 if (isl_tab_freeze_constraint(tab, i) < 0)
1951                         goto error;
1952         tab = isl_tab_extend(tab, bset->n_ineq);
1953         for (i = 0; i < bset->n_ineq; ++i)
1954                 if (isl_tab_add_ineq(tab, bset->ineq[i]) < 0)
1955                         goto error;
1956         bset = isl_basic_set_add_constraints(combined, bset, 0);
1957         combined = NULL;
1958         if (!bset)
1959                 goto error;
1960         if (isl_tab_detect_redundant(tab) < 0)
1961                 goto error;
1962         total = isl_basic_set_total_dim(bset);
1963         for (i = context_ineq; i < bset->n_ineq; ++i) {
1964                 int is_empty;
1965                 if (tab->con[i].is_redundant)
1966                         continue;
1967                 tab->con[i].is_redundant = 1;
1968                 combined = isl_basic_set_dup(bset);
1969                 combined = isl_basic_set_update_from_tab(combined, tab);
1970                 combined = isl_basic_set_extend_constraints(combined, 0, 1);
1971                 k = isl_basic_set_alloc_inequality(combined);
1972                 if (k < 0)
1973                         goto error;
1974                 isl_seq_neg(combined->ineq[k], bset->ineq[i], 1 + total);
1975                 isl_int_sub_ui(combined->ineq[k][0], combined->ineq[k][0], 1);
1976                 is_empty = isl_basic_set_is_empty(combined);
1977                 if (is_empty < 0)
1978                         goto error;
1979                 isl_basic_set_free(combined);
1980                 combined = NULL;
1981                 if (!is_empty)
1982                         tab->con[i].is_redundant = 0;
1983         }
1984         for (i = 0; i < context_ineq; ++i)
1985                 tab->con[i].is_redundant = 1;
1986         bset = isl_basic_set_update_from_tab(bset, tab);
1987         if (bset) {
1988                 ISL_F_SET(bset, ISL_BASIC_SET_NO_IMPLICIT);
1989                 ISL_F_SET(bset, ISL_BASIC_SET_NO_REDUNDANT);
1990         }
1991
1992         isl_tab_free(tab);
1993 done:
1994         bset = isl_basic_set_simplify(bset);
1995         bset = isl_basic_set_finalize(bset);
1996         isl_basic_set_free(context);
1997         return bset;
1998 error:
1999         isl_tab_free(tab);
2000         isl_basic_set_free(combined);
2001         isl_basic_set_free(context);
2002         isl_basic_set_free(bset);
2003         return NULL;
2004 }
2005
2006 /* Remove all information from bset that is redundant in the context
2007  * of context.  In particular, equalities that are linear combinations
2008  * of those in context are removed.  Then the inequalities that are
2009  * redundant in the context of the equalities and inequalities of
2010  * context are removed.
2011  *
2012  * First of all, we drop those constraints from "context"
2013  * that are irrelevant for computing the gist of "bset".
2014  * Alternatively, we could factorize the intersection of "context" and "bset".
2015  *
2016  * We first compute the integer affine hull of the intersection,
2017  * compute the gist inside this affine hull and then add back
2018  * those equalities that are not implied by the context.
2019  *
2020  * If two constraints are mutually redundant, then uset_gist_full
2021  * will remove the second of those constraints.  We therefore first
2022  * sort the constraints so that constraints not involving existentially
2023  * quantified variables are given precedence over those that do.
2024  * We have to perform this sorting before the variable compression,
2025  * because that may effect the order of the variables.
2026  */
2027 static __isl_give isl_basic_set *uset_gist(__isl_take isl_basic_set *bset,
2028         __isl_take isl_basic_set *context)
2029 {
2030         isl_mat *eq;
2031         isl_mat *T, *T2;
2032         isl_basic_set *aff;
2033         isl_basic_set *aff_context;
2034         unsigned total;
2035
2036         if (!bset || !context)
2037                 goto error;
2038
2039         context = drop_irrelevant_constraints(context, bset);
2040
2041         bset = isl_basic_set_intersect(bset, isl_basic_set_copy(context));
2042         if (isl_basic_set_plain_is_empty(bset)) {
2043                 isl_basic_set_free(context);
2044                 return bset;
2045         }
2046         bset = isl_basic_set_sort_constraints(bset);
2047         aff = isl_basic_set_affine_hull(isl_basic_set_copy(bset));
2048         if (!aff)
2049                 goto error;
2050         if (isl_basic_set_plain_is_empty(aff)) {
2051                 isl_basic_set_free(aff);
2052                 isl_basic_set_free(context);
2053                 return bset;
2054         }
2055         if (aff->n_eq == 0) {
2056                 isl_basic_set_free(aff);
2057                 return uset_gist_full(bset, context);
2058         }
2059         total = isl_basic_set_total_dim(bset);
2060         eq = isl_mat_sub_alloc6(bset->ctx, aff->eq, 0, aff->n_eq, 0, 1 + total);
2061         eq = isl_mat_cow(eq);
2062         T = isl_mat_variable_compression(eq, &T2);
2063         if (T && T->n_col == 0) {
2064                 isl_mat_free(T);
2065                 isl_mat_free(T2);
2066                 isl_basic_set_free(context);
2067                 isl_basic_set_free(aff);
2068                 return isl_basic_set_set_to_empty(bset);
2069         }
2070
2071         aff_context = isl_basic_set_affine_hull(isl_basic_set_copy(context));
2072
2073         bset = isl_basic_set_preimage(bset, isl_mat_copy(T));
2074         context = isl_basic_set_preimage(context, T);
2075
2076         bset = uset_gist_full(bset, context);
2077         bset = isl_basic_set_preimage(bset, T2);
2078         bset = isl_basic_set_intersect(bset, aff);
2079         bset = isl_basic_set_reduce_using_equalities(bset, aff_context);
2080
2081         if (bset) {
2082                 ISL_F_SET(bset, ISL_BASIC_SET_NO_IMPLICIT);
2083                 ISL_F_SET(bset, ISL_BASIC_SET_NO_REDUNDANT);
2084         }
2085
2086         return bset;
2087 error:
2088         isl_basic_set_free(bset);
2089         isl_basic_set_free(context);
2090         return NULL;
2091 }
2092
2093 /* Normalize the divs in "bmap" in the context of the equalities in "context".
2094  * We simply add the equalities in context to bmap and then do a regular
2095  * div normalizations.  Better results can be obtained by normalizing
2096  * only the divs in bmap than do not also appear in context.
2097  * We need to be careful to reduce the divs using the equalities
2098  * so that later calls to isl_basic_map_overlying_set wouldn't introduce
2099  * spurious constraints.
2100  */
2101 static struct isl_basic_map *normalize_divs_in_context(
2102         struct isl_basic_map *bmap, struct isl_basic_map *context)
2103 {
2104         int i;
2105         unsigned total_context;
2106         int div_eq;
2107
2108         div_eq = n_pure_div_eq(bmap);
2109         if (div_eq == 0)
2110                 return bmap;
2111
2112         if (context->n_div > 0)
2113                 bmap = isl_basic_map_align_divs(bmap, context);
2114
2115         total_context = isl_basic_map_total_dim(context);
2116         bmap = isl_basic_map_extend_constraints(bmap, context->n_eq, 0);
2117         for (i = 0; i < context->n_eq; ++i) {
2118                 int k;
2119                 k = isl_basic_map_alloc_equality(bmap);
2120                 if (k < 0)
2121                         return isl_basic_map_free(bmap);
2122                 isl_seq_cpy(bmap->eq[k], context->eq[i], 1 + total_context);
2123                 isl_seq_clr(bmap->eq[k] + 1 + total_context,
2124                                 isl_basic_map_total_dim(bmap) - total_context);
2125         }
2126         bmap = isl_basic_map_gauss(bmap, NULL);
2127         bmap = normalize_divs(bmap, NULL);
2128         bmap = isl_basic_map_gauss(bmap, NULL);
2129         return bmap;
2130 }
2131
2132 struct isl_basic_map *isl_basic_map_gist(struct isl_basic_map *bmap,
2133         struct isl_basic_map *context)
2134 {
2135         struct isl_basic_set *bset;
2136
2137         if (!bmap || !context)
2138                 goto error;
2139
2140         if (isl_basic_map_is_universe(bmap)) {
2141                 isl_basic_map_free(context);
2142                 return bmap;
2143         }
2144         if (isl_basic_map_plain_is_empty(context)) {
2145                 isl_basic_map_free(bmap);
2146                 return context;
2147         }
2148         if (isl_basic_map_plain_is_empty(bmap)) {
2149                 isl_basic_map_free(context);
2150                 return bmap;
2151         }
2152
2153         bmap = isl_basic_map_remove_redundancies(bmap);
2154         context = isl_basic_map_remove_redundancies(context);
2155
2156         if (context->n_eq)
2157                 bmap = normalize_divs_in_context(bmap, context);
2158
2159         context = isl_basic_map_align_divs(context, bmap);
2160         bmap = isl_basic_map_align_divs(bmap, context);
2161
2162         bset = uset_gist(isl_basic_map_underlying_set(isl_basic_map_copy(bmap)),
2163                          isl_basic_map_underlying_set(context));
2164
2165         return isl_basic_map_overlying_set(bset, bmap);
2166 error:
2167         isl_basic_map_free(bmap);
2168         isl_basic_map_free(context);
2169         return NULL;
2170 }
2171
2172 /*
2173  * Assumes context has no implicit divs.
2174  */
2175 __isl_give isl_map *isl_map_gist_basic_map(__isl_take isl_map *map,
2176         __isl_take isl_basic_map *context)
2177 {
2178         int i;
2179
2180         if (!map || !context)
2181                 goto error;;
2182
2183         if (isl_basic_map_plain_is_empty(context)) {
2184                 isl_map_free(map);
2185                 return isl_map_from_basic_map(context);
2186         }
2187
2188         context = isl_basic_map_remove_redundancies(context);
2189         map = isl_map_cow(map);
2190         if (!map || !context)
2191                 goto error;;
2192         isl_assert(map->ctx, isl_space_is_equal(map->dim, context->dim), goto error);
2193         map = isl_map_compute_divs(map);
2194         if (!map)
2195                 goto error;
2196         for (i = 0; i < map->n; ++i)
2197                 context = isl_basic_map_align_divs(context, map->p[i]);
2198         for (i = map->n - 1; i >= 0; --i) {
2199                 map->p[i] = isl_basic_map_gist(map->p[i],
2200                                                 isl_basic_map_copy(context));
2201                 if (!map->p[i])
2202                         goto error;
2203                 if (isl_basic_map_plain_is_empty(map->p[i])) {
2204                         isl_basic_map_free(map->p[i]);
2205                         if (i != map->n - 1)
2206                                 map->p[i] = map->p[map->n - 1];
2207                         map->n--;
2208                 }
2209         }
2210         isl_basic_map_free(context);
2211         ISL_F_CLR(map, ISL_MAP_NORMALIZED);
2212         return map;
2213 error:
2214         isl_map_free(map);
2215         isl_basic_map_free(context);
2216         return NULL;
2217 }
2218
2219 /* Return a map that has the same intersection with "context" as "map"
2220  * and that as "simple" as possible.
2221  *
2222  * If "map" is already the universe, then we cannot make it any simpler.
2223  * Similarly, if "context" is the universe, then we cannot exploit it
2224  * to simplify "map"
2225  * If "map" and "context" are identical to each other, then we can
2226  * return the corresponding universe.
2227  *
2228  * If none of these cases apply, we have to work a bit harder.
2229  */
2230 static __isl_give isl_map *map_gist(__isl_take isl_map *map,
2231         __isl_take isl_map *context)
2232 {
2233         int equal;
2234         int is_universe;
2235
2236         is_universe = isl_map_plain_is_universe(map);
2237         if (is_universe >= 0 && !is_universe)
2238                 is_universe = isl_map_plain_is_universe(context);
2239         if (is_universe < 0)
2240                 goto error;
2241         if (is_universe) {
2242                 isl_map_free(context);
2243                 return map;
2244         }
2245
2246         equal = isl_map_plain_is_equal(map, context);
2247         if (equal < 0)
2248                 goto error;
2249         if (equal) {
2250                 isl_map *res = isl_map_universe(isl_map_get_space(map));
2251                 isl_map_free(map);
2252                 isl_map_free(context);
2253                 return res;
2254         }
2255
2256         context = isl_map_compute_divs(context);
2257         return isl_map_gist_basic_map(map, isl_map_simple_hull(context));
2258 error:
2259         isl_map_free(map);
2260         isl_map_free(context);
2261         return NULL;
2262 }
2263
2264 __isl_give isl_map *isl_map_gist(__isl_take isl_map *map,
2265         __isl_take isl_map *context)
2266 {
2267         return isl_map_align_params_map_map_and(map, context, &map_gist);
2268 }
2269
2270 struct isl_basic_set *isl_basic_set_gist(struct isl_basic_set *bset,
2271                                                 struct isl_basic_set *context)
2272 {
2273         return (struct isl_basic_set *)isl_basic_map_gist(
2274                 (struct isl_basic_map *)bset, (struct isl_basic_map *)context);
2275 }
2276
2277 __isl_give isl_set *isl_set_gist_basic_set(__isl_take isl_set *set,
2278         __isl_take isl_basic_set *context)
2279 {
2280         return (struct isl_set *)isl_map_gist_basic_map((struct isl_map *)set,
2281                                         (struct isl_basic_map *)context);
2282 }
2283
2284 __isl_give isl_set *isl_set_gist_params_basic_set(__isl_take isl_set *set,
2285         __isl_take isl_basic_set *context)
2286 {
2287         isl_space *space = isl_set_get_space(set);
2288         isl_basic_set *dom_context = isl_basic_set_universe(space);
2289         dom_context = isl_basic_set_intersect_params(dom_context, context);
2290         return isl_set_gist_basic_set(set, dom_context);
2291 }
2292
2293 __isl_give isl_set *isl_set_gist(__isl_take isl_set *set,
2294         __isl_take isl_set *context)
2295 {
2296         return (struct isl_set *)isl_map_gist((struct isl_map *)set,
2297                                         (struct isl_map *)context);
2298 }
2299
2300 __isl_give isl_map *isl_map_gist_domain(__isl_take isl_map *map,
2301         __isl_take isl_set *context)
2302 {
2303         isl_map *map_context = isl_map_universe(isl_map_get_space(map));
2304         map_context = isl_map_intersect_domain(map_context, context);
2305         return isl_map_gist(map, map_context);
2306 }
2307
2308 __isl_give isl_map *isl_map_gist_range(__isl_take isl_map *map,
2309         __isl_take isl_set *context)
2310 {
2311         isl_map *map_context = isl_map_universe(isl_map_get_space(map));
2312         map_context = isl_map_intersect_range(map_context, context);
2313         return isl_map_gist(map, map_context);
2314 }
2315
2316 __isl_give isl_map *isl_map_gist_params(__isl_take isl_map *map,
2317         __isl_take isl_set *context)
2318 {
2319         isl_map *map_context = isl_map_universe(isl_map_get_space(map));
2320         map_context = isl_map_intersect_params(map_context, context);
2321         return isl_map_gist(map, map_context);
2322 }
2323
2324 __isl_give isl_set *isl_set_gist_params(__isl_take isl_set *set,
2325         __isl_take isl_set *context)
2326 {
2327         return isl_map_gist_params(set, context);
2328 }
2329
2330 /* Quick check to see if two basic maps are disjoint.
2331  * In particular, we reduce the equalities and inequalities of
2332  * one basic map in the context of the equalities of the other
2333  * basic map and check if we get a contradiction.
2334  */
2335 int isl_basic_map_plain_is_disjoint(__isl_keep isl_basic_map *bmap1,
2336         __isl_keep isl_basic_map *bmap2)
2337 {
2338         struct isl_vec *v = NULL;
2339         int *elim = NULL;
2340         unsigned total;
2341         int i;
2342
2343         if (!bmap1 || !bmap2)
2344                 return -1;
2345         isl_assert(bmap1->ctx, isl_space_is_equal(bmap1->dim, bmap2->dim),
2346                         return -1);
2347         if (bmap1->n_div || bmap2->n_div)
2348                 return 0;
2349         if (!bmap1->n_eq && !bmap2->n_eq)
2350                 return 0;
2351
2352         total = isl_space_dim(bmap1->dim, isl_dim_all);
2353         if (total == 0)
2354                 return 0;
2355         v = isl_vec_alloc(bmap1->ctx, 1 + total);
2356         if (!v)
2357                 goto error;
2358         elim = isl_alloc_array(bmap1->ctx, int, total);
2359         if (!elim)
2360                 goto error;
2361         compute_elimination_index(bmap1, elim);
2362         for (i = 0; i < bmap2->n_eq; ++i) {
2363                 int reduced;
2364                 reduced = reduced_using_equalities(v->block.data, bmap2->eq[i],
2365                                                         bmap1, elim);
2366                 if (reduced && !isl_int_is_zero(v->block.data[0]) &&
2367                     isl_seq_first_non_zero(v->block.data + 1, total) == -1)
2368                         goto disjoint;
2369         }
2370         for (i = 0; i < bmap2->n_ineq; ++i) {
2371                 int reduced;
2372                 reduced = reduced_using_equalities(v->block.data,
2373                                                 bmap2->ineq[i], bmap1, elim);
2374                 if (reduced && isl_int_is_neg(v->block.data[0]) &&
2375                     isl_seq_first_non_zero(v->block.data + 1, total) == -1)
2376                         goto disjoint;
2377         }
2378         compute_elimination_index(bmap2, elim);
2379         for (i = 0; i < bmap1->n_ineq; ++i) {
2380                 int reduced;
2381                 reduced = reduced_using_equalities(v->block.data,
2382                                                 bmap1->ineq[i], bmap2, elim);
2383                 if (reduced && isl_int_is_neg(v->block.data[0]) &&
2384                     isl_seq_first_non_zero(v->block.data + 1, total) == -1)
2385                         goto disjoint;
2386         }
2387         isl_vec_free(v);
2388         free(elim);
2389         return 0;
2390 disjoint:
2391         isl_vec_free(v);
2392         free(elim);
2393         return 1;
2394 error:
2395         isl_vec_free(v);
2396         free(elim);
2397         return -1;
2398 }
2399
2400 int isl_basic_set_plain_is_disjoint(__isl_keep isl_basic_set *bset1,
2401         __isl_keep isl_basic_set *bset2)
2402 {
2403         return isl_basic_map_plain_is_disjoint((struct isl_basic_map *)bset1,
2404                                               (struct isl_basic_map *)bset2);
2405 }
2406
2407 /* Are "map1" and "map2" obviously disjoint?
2408  *
2409  * If one of them is empty or if they live in different spaces (ignoring
2410  * parameters), then they are clearly disjoint.
2411  *
2412  * If they have different parameters, then we skip any further tests.
2413  *
2414  * If they are obviously equal, but not obviously empty, then we will
2415  * not be able to detect if they are disjoint.
2416  *
2417  * Otherwise we check if each basic map in "map1" is obviously disjoint
2418  * from each basic map in "map2".
2419  */
2420 int isl_map_plain_is_disjoint(__isl_keep isl_map *map1,
2421         __isl_keep isl_map *map2)
2422 {
2423         int i, j;
2424         int disjoint;
2425         int intersect;
2426         int match;
2427
2428         if (!map1 || !map2)
2429                 return -1;
2430
2431         disjoint = isl_map_plain_is_empty(map1);
2432         if (disjoint < 0 || disjoint)
2433                 return disjoint;
2434
2435         disjoint = isl_map_plain_is_empty(map2);
2436         if (disjoint < 0 || disjoint)
2437                 return disjoint;
2438
2439         match = isl_space_tuple_match(map1->dim, isl_dim_in,
2440                                 map2->dim, isl_dim_in);
2441         if (match < 0 || !match)
2442                 return match < 0 ? -1 : 1;
2443
2444         match = isl_space_tuple_match(map1->dim, isl_dim_out,
2445                                 map2->dim, isl_dim_out);
2446         if (match < 0 || !match)
2447                 return match < 0 ? -1 : 1;
2448
2449         match = isl_space_match(map1->dim, isl_dim_param,
2450                                 map2->dim, isl_dim_param);
2451         if (match < 0 || !match)
2452                 return match < 0 ? -1 : 0;
2453
2454         intersect = isl_map_plain_is_equal(map1, map2);
2455         if (intersect < 0 || intersect)
2456                 return intersect < 0 ? -1 : 0;
2457
2458         for (i = 0; i < map1->n; ++i) {
2459                 for (j = 0; j < map2->n; ++j) {
2460                         int d = isl_basic_map_plain_is_disjoint(map1->p[i],
2461                                                                map2->p[j]);
2462                         if (d != 1)
2463                                 return d;
2464                 }
2465         }
2466         return 1;
2467 }
2468
2469 /* Are "map1" and "map2" disjoint?
2470  *
2471  * They are disjoint if they are "obviously disjoint" or if one of them
2472  * is empty.  Otherwise, they are not disjoint if one of them is universal.
2473  * If none of these cases apply, we compute the intersection and see if
2474  * the result is empty.
2475  */
2476 int isl_map_is_disjoint(__isl_keep isl_map *map1, __isl_keep isl_map *map2)
2477 {
2478         int disjoint;
2479         int intersect;
2480         isl_map *test;
2481
2482         disjoint = isl_map_plain_is_disjoint(map1, map2);
2483         if (disjoint < 0 || disjoint)
2484                 return disjoint;
2485
2486         disjoint = isl_map_is_empty(map1);
2487         if (disjoint < 0 || disjoint)
2488                 return disjoint;
2489
2490         disjoint = isl_map_is_empty(map2);
2491         if (disjoint < 0 || disjoint)
2492                 return disjoint;
2493
2494         intersect = isl_map_plain_is_universe(map1);
2495         if (intersect < 0 || intersect)
2496                 return intersect < 0 ? -1 : 0;
2497
2498         intersect = isl_map_plain_is_universe(map2);
2499         if (intersect < 0 || intersect)
2500                 return intersect < 0 ? -1 : 0;
2501
2502         test = isl_map_intersect(isl_map_copy(map1), isl_map_copy(map2));
2503         disjoint = isl_map_is_empty(test);
2504         isl_map_free(test);
2505
2506         return disjoint;
2507 }
2508
2509 int isl_set_plain_is_disjoint(__isl_keep isl_set *set1,
2510         __isl_keep isl_set *set2)
2511 {
2512         return isl_map_plain_is_disjoint((struct isl_map *)set1,
2513                                         (struct isl_map *)set2);
2514 }
2515
2516 /* Are "set1" and "set2" disjoint?
2517  */
2518 int isl_set_is_disjoint(__isl_keep isl_set *set1, __isl_keep isl_set *set2)
2519 {
2520         return isl_map_is_disjoint(set1, set2);
2521 }
2522
2523 int isl_set_fast_is_disjoint(__isl_keep isl_set *set1, __isl_keep isl_set *set2)
2524 {
2525         return isl_set_plain_is_disjoint(set1, set2);
2526 }
2527
2528 /* Check if we can combine a given div with lower bound l and upper
2529  * bound u with some other div and if so return that other div.
2530  * Otherwise return -1.
2531  *
2532  * We first check that
2533  *      - the bounds are opposites of each other (except for the constant
2534  *        term)
2535  *      - the bounds do not reference any other div
2536  *      - no div is defined in terms of this div
2537  *
2538  * Let m be the size of the range allowed on the div by the bounds.
2539  * That is, the bounds are of the form
2540  *
2541  *      e <= a <= e + m - 1
2542  *
2543  * with e some expression in the other variables.
2544  * We look for another div b such that no third div is defined in terms
2545  * of this second div b and such that in any constraint that contains
2546  * a (except for the given lower and upper bound), also contains b
2547  * with a coefficient that is m times that of b.
2548  * That is, all constraints (execpt for the lower and upper bound)
2549  * are of the form
2550  *
2551  *      e + f (a + m b) >= 0
2552  *
2553  * If so, we return b so that "a + m b" can be replaced by
2554  * a single div "c = a + m b".
2555  */
2556 static int div_find_coalesce(struct isl_basic_map *bmap, int *pairs,
2557         unsigned div, unsigned l, unsigned u)
2558 {
2559         int i, j;
2560         unsigned dim;
2561         int coalesce = -1;
2562
2563         if (bmap->n_div <= 1)
2564                 return -1;
2565         dim = isl_space_dim(bmap->dim, isl_dim_all);
2566         if (isl_seq_first_non_zero(bmap->ineq[l] + 1 + dim, div) != -1)
2567                 return -1;
2568         if (isl_seq_first_non_zero(bmap->ineq[l] + 1 + dim + div + 1,
2569                                    bmap->n_div - div - 1) != -1)
2570                 return -1;
2571         if (!isl_seq_is_neg(bmap->ineq[l] + 1, bmap->ineq[u] + 1,
2572                             dim + bmap->n_div))
2573                 return -1;
2574
2575         for (i = 0; i < bmap->n_div; ++i) {
2576                 if (isl_int_is_zero(bmap->div[i][0]))
2577                         continue;
2578                 if (!isl_int_is_zero(bmap->div[i][1 + 1 + dim + div]))
2579                         return -1;
2580         }
2581
2582         isl_int_add(bmap->ineq[l][0], bmap->ineq[l][0], bmap->ineq[u][0]);
2583         if (isl_int_is_neg(bmap->ineq[l][0])) {
2584                 isl_int_sub(bmap->ineq[l][0],
2585                             bmap->ineq[l][0], bmap->ineq[u][0]);
2586                 bmap = isl_basic_map_copy(bmap);
2587                 bmap = isl_basic_map_set_to_empty(bmap);
2588                 isl_basic_map_free(bmap);
2589                 return -1;
2590         }
2591         isl_int_add_ui(bmap->ineq[l][0], bmap->ineq[l][0], 1);
2592         for (i = 0; i < bmap->n_div; ++i) {
2593                 if (i == div)
2594                         continue;
2595                 if (!pairs[i])
2596                         continue;
2597                 for (j = 0; j < bmap->n_div; ++j) {
2598                         if (isl_int_is_zero(bmap->div[j][0]))
2599                                 continue;
2600                         if (!isl_int_is_zero(bmap->div[j][1 + 1 + dim + i]))
2601                                 break;
2602                 }
2603                 if (j < bmap->n_div)
2604                         continue;
2605                 for (j = 0; j < bmap->n_ineq; ++j) {
2606                         int valid;
2607                         if (j == l || j == u)
2608                                 continue;
2609                         if (isl_int_is_zero(bmap->ineq[j][1 + dim + div]))
2610                                 continue;
2611                         if (isl_int_is_zero(bmap->ineq[j][1 + dim + i]))
2612                                 break;
2613                         isl_int_mul(bmap->ineq[j][1 + dim + div],
2614                                     bmap->ineq[j][1 + dim + div],
2615                                     bmap->ineq[l][0]);
2616                         valid = isl_int_eq(bmap->ineq[j][1 + dim + div],
2617                                            bmap->ineq[j][1 + dim + i]);
2618                         isl_int_divexact(bmap->ineq[j][1 + dim + div],
2619                                          bmap->ineq[j][1 + dim + div],
2620                                          bmap->ineq[l][0]);
2621                         if (!valid)
2622                                 break;
2623                 }
2624                 if (j < bmap->n_ineq)
2625                         continue;
2626                 coalesce = i;
2627                 break;
2628         }
2629         isl_int_sub_ui(bmap->ineq[l][0], bmap->ineq[l][0], 1);
2630         isl_int_sub(bmap->ineq[l][0], bmap->ineq[l][0], bmap->ineq[u][0]);
2631         return coalesce;
2632 }
2633
2634 /* Given a lower and an upper bound on div i, construct an inequality
2635  * that when nonnegative ensures that this pair of bounds always allows
2636  * for an integer value of the given div.
2637  * The lower bound is inequality l, while the upper bound is inequality u.
2638  * The constructed inequality is stored in ineq.
2639  * g, fl, fu are temporary scalars.
2640  *
2641  * Let the upper bound be
2642  *
2643  *      -n_u a + e_u >= 0
2644  *
2645  * and the lower bound
2646  *
2647  *      n_l a + e_l >= 0
2648  *
2649  * Let n_u = f_u g and n_l = f_l g, with g = gcd(n_u, n_l).
2650  * We have
2651  *
2652  *      - f_u e_l <= f_u f_l g a <= f_l e_u
2653  *
2654  * Since all variables are integer valued, this is equivalent to
2655  *
2656  *      - f_u e_l - (f_u - 1) <= f_u f_l g a <= f_l e_u + (f_l - 1)
2657  *
2658  * If this interval is at least f_u f_l g, then it contains at least
2659  * one integer value for a.
2660  * That is, the test constraint is
2661  *
2662  *      f_l e_u + f_u e_l + f_l - 1 + f_u - 1 + 1 >= f_u f_l g
2663  */
2664 static void construct_test_ineq(struct isl_basic_map *bmap, int i,
2665         int l, int u, isl_int *ineq, isl_int g, isl_int fl, isl_int fu)
2666 {
2667         unsigned dim;
2668         dim = isl_space_dim(bmap->dim, isl_dim_all);
2669
2670         isl_int_gcd(g, bmap->ineq[l][1 + dim + i], bmap->ineq[u][1 + dim + i]);
2671         isl_int_divexact(fl, bmap->ineq[l][1 + dim + i], g);
2672         isl_int_divexact(fu, bmap->ineq[u][1 + dim + i], g);
2673         isl_int_neg(fu, fu);
2674         isl_seq_combine(ineq, fl, bmap->ineq[u], fu, bmap->ineq[l],
2675                         1 + dim + bmap->n_div);
2676         isl_int_add(ineq[0], ineq[0], fl);
2677         isl_int_add(ineq[0], ineq[0], fu);
2678         isl_int_sub_ui(ineq[0], ineq[0], 1);
2679         isl_int_mul(g, g, fl);
2680         isl_int_mul(g, g, fu);
2681         isl_int_sub(ineq[0], ineq[0], g);
2682 }
2683
2684 /* Remove more kinds of divs that are not strictly needed.
2685  * In particular, if all pairs of lower and upper bounds on a div
2686  * are such that they allow at least one integer value of the div,
2687  * the we can eliminate the div using Fourier-Motzkin without
2688  * introducing any spurious solutions.
2689  */
2690 static struct isl_basic_map *drop_more_redundant_divs(
2691         struct isl_basic_map *bmap, int *pairs, int n)
2692 {
2693         struct isl_tab *tab = NULL;
2694         struct isl_vec *vec = NULL;
2695         unsigned dim;
2696         int remove = -1;
2697         isl_int g, fl, fu;
2698
2699         isl_int_init(g);
2700         isl_int_init(fl);
2701         isl_int_init(fu);
2702
2703         if (!bmap)
2704                 goto error;
2705
2706         dim = isl_space_dim(bmap->dim, isl_dim_all);
2707         vec = isl_vec_alloc(bmap->ctx, 1 + dim + bmap->n_div);
2708         if (!vec)
2709                 goto error;
2710
2711         tab = isl_tab_from_basic_map(bmap, 0);
2712
2713         while (n > 0) {
2714                 int i, l, u;
2715                 int best = -1;
2716                 enum isl_lp_result res;
2717
2718                 for (i = 0; i < bmap->n_div; ++i) {
2719                         if (!pairs[i])
2720                                 continue;
2721                         if (best >= 0 && pairs[best] <= pairs[i])
2722                                 continue;
2723                         best = i;
2724                 }
2725
2726                 i = best;
2727                 for (l = 0; l < bmap->n_ineq; ++l) {
2728                         if (!isl_int_is_pos(bmap->ineq[l][1 + dim + i]))
2729                                 continue;
2730                         for (u = 0; u < bmap->n_ineq; ++u) {
2731                                 if (!isl_int_is_neg(bmap->ineq[u][1 + dim + i]))
2732                                         continue;
2733                                 construct_test_ineq(bmap, i, l, u,
2734                                                     vec->el, g, fl, fu);
2735                                 res = isl_tab_min(tab, vec->el,
2736                                                   bmap->ctx->one, &g, NULL, 0);
2737                                 if (res == isl_lp_error)
2738                                         goto error;
2739                                 if (res == isl_lp_empty) {
2740                                         bmap = isl_basic_map_set_to_empty(bmap);
2741                                         break;
2742                                 }
2743                                 if (res != isl_lp_ok || isl_int_is_neg(g))
2744                                         break;
2745                         }
2746                         if (u < bmap->n_ineq)
2747                                 break;
2748                 }
2749                 if (l == bmap->n_ineq) {
2750                         remove = i;
2751                         break;
2752                 }
2753                 pairs[i] = 0;
2754                 --n;
2755         }
2756
2757         isl_tab_free(tab);
2758         isl_vec_free(vec);
2759
2760         isl_int_clear(g);
2761         isl_int_clear(fl);
2762         isl_int_clear(fu);
2763
2764         free(pairs);
2765
2766         if (remove < 0)
2767                 return bmap;
2768
2769         bmap = isl_basic_map_remove_dims(bmap, isl_dim_div, remove, 1);
2770         return isl_basic_map_drop_redundant_divs(bmap);
2771 error:
2772         free(pairs);
2773         isl_basic_map_free(bmap);
2774         isl_tab_free(tab);
2775         isl_vec_free(vec);
2776         isl_int_clear(g);
2777         isl_int_clear(fl);
2778         isl_int_clear(fu);
2779         return NULL;
2780 }
2781
2782 /* Given a pair of divs div1 and div2 such that, expect for the lower bound l
2783  * and the upper bound u, div1 always occurs together with div2 in the form 
2784  * (div1 + m div2), where m is the constant range on the variable div1
2785  * allowed by l and u, replace the pair div1 and div2 by a single
2786  * div that is equal to div1 + m div2.
2787  *
2788  * The new div will appear in the location that contains div2.
2789  * We need to modify all constraints that contain
2790  * div2 = (div - div1) / m
2791  * (If a constraint does not contain div2, it will also not contain div1.)
2792  * If the constraint also contains div1, then we know they appear
2793  * as f (div1 + m div2) and we can simply replace (div1 + m div2) by div,
2794  * i.e., the coefficient of div is f.
2795  *
2796  * Otherwise, we first need to introduce div1 into the constraint.
2797  * Let the l be
2798  *
2799  *      div1 + f >=0
2800  *
2801  * and u
2802  *
2803  *      -div1 + f' >= 0
2804  *
2805  * A lower bound on div2
2806  *
2807  *      n div2 + t >= 0
2808  *
2809  * can be replaced by
2810  *
2811  *      (n * (m div 2 + div1) + m t + n f)/g >= 0
2812  *
2813  * with g = gcd(m,n).
2814  * An upper bound
2815  *
2816  *      -n div2 + t >= 0
2817  *
2818  * can be replaced by
2819  *
2820  *      (-n * (m div2 + div1) + m t + n f')/g >= 0
2821  *
2822  * These constraint are those that we would obtain from eliminating
2823  * div1 using Fourier-Motzkin.
2824  *
2825  * After all constraints have been modified, we drop the lower and upper
2826  * bound and then drop div1.
2827  */
2828 static struct isl_basic_map *coalesce_divs(struct isl_basic_map *bmap,
2829         unsigned div1, unsigned div2, unsigned l, unsigned u)
2830 {
2831         isl_int a;
2832         isl_int b;
2833         isl_int m;
2834         unsigned dim, total;
2835         int i;
2836
2837         dim = isl_space_dim(bmap->dim, isl_dim_all);
2838         total = 1 + dim + bmap->n_div;
2839
2840         isl_int_init(a);
2841         isl_int_init(b);
2842         isl_int_init(m);
2843         isl_int_add(m, bmap->ineq[l][0], bmap->ineq[u][0]);
2844         isl_int_add_ui(m, m, 1);
2845
2846         for (i = 0; i < bmap->n_ineq; ++i) {
2847                 if (i == l || i == u)
2848                         continue;
2849                 if (isl_int_is_zero(bmap->ineq[i][1 + dim + div2]))
2850                         continue;
2851                 if (isl_int_is_zero(bmap->ineq[i][1 + dim + div1])) {
2852                         isl_int_gcd(b, m, bmap->ineq[i][1 + dim + div2]);
2853                         isl_int_divexact(a, m, b);
2854                         isl_int_divexact(b, bmap->ineq[i][1 + dim + div2], b);
2855                         if (isl_int_is_pos(b)) {
2856                                 isl_seq_combine(bmap->ineq[i], a, bmap->ineq[i],
2857                                                 b, bmap->ineq[l], total);
2858                         } else {
2859                                 isl_int_neg(b, b);
2860                                 isl_seq_combine(bmap->ineq[i], a, bmap->ineq[i],
2861                                                 b, bmap->ineq[u], total);
2862                         }
2863                 }
2864                 isl_int_set(bmap->ineq[i][1 + dim + div2],
2865                             bmap->ineq[i][1 + dim + div1]);
2866                 isl_int_set_si(bmap->ineq[i][1 + dim + div1], 0);
2867         }
2868
2869         isl_int_clear(a);
2870         isl_int_clear(b);
2871         isl_int_clear(m);
2872         if (l > u) {
2873                 isl_basic_map_drop_inequality(bmap, l);
2874                 isl_basic_map_drop_inequality(bmap, u);
2875         } else {
2876                 isl_basic_map_drop_inequality(bmap, u);
2877                 isl_basic_map_drop_inequality(bmap, l);
2878         }
2879         bmap = isl_basic_map_drop_div(bmap, div1);
2880         return bmap;
2881 }
2882
2883 /* First check if we can coalesce any pair of divs and
2884  * then continue with dropping more redundant divs.
2885  *
2886  * We loop over all pairs of lower and upper bounds on a div
2887  * with coefficient 1 and -1, respectively, check if there
2888  * is any other div "c" with which we can coalesce the div
2889  * and if so, perform the coalescing.
2890  */
2891 static struct isl_basic_map *coalesce_or_drop_more_redundant_divs(
2892         struct isl_basic_map *bmap, int *pairs, int n)
2893 {
2894         int i, l, u;
2895         unsigned dim;
2896
2897         dim = isl_space_dim(bmap->dim, isl_dim_all);
2898
2899         for (i = 0; i < bmap->n_div; ++i) {
2900                 if (!pairs[i])
2901                         continue;
2902                 for (l = 0; l < bmap->n_ineq; ++l) {
2903                         if (!isl_int_is_one(bmap->ineq[l][1 + dim + i]))
2904                                 continue;
2905                         for (u = 0; u < bmap->n_ineq; ++u) {
2906                                 int c;
2907
2908                                 if (!isl_int_is_negone(bmap->ineq[u][1+dim+i]))
2909                                         continue;
2910                                 c = div_find_coalesce(bmap, pairs, i, l, u);
2911                                 if (c < 0)
2912                                         continue;
2913                                 free(pairs);
2914                                 bmap = coalesce_divs(bmap, i, c, l, u);
2915                                 return isl_basic_map_drop_redundant_divs(bmap);
2916                         }
2917                 }
2918         }
2919
2920         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
2921                 return bmap;
2922
2923         return drop_more_redundant_divs(bmap, pairs, n);
2924 }
2925
2926 /* Remove divs that are not strictly needed.
2927  * In particular, if a div only occurs positively (or negatively)
2928  * in constraints, then it can simply be dropped.
2929  * Also, if a div occurs in only two constraints and if moreover
2930  * those two constraints are opposite to each other, except for the constant
2931  * term and if the sum of the constant terms is such that for any value
2932  * of the other values, there is always at least one integer value of the
2933  * div, i.e., if one plus this sum is greater than or equal to
2934  * the (absolute value) of the coefficent of the div in the constraints,
2935  * then we can also simply drop the div.
2936  *
2937  * We skip divs that appear in equalities or in the definition of other divs.
2938  * Divs that appear in the definition of other divs usually occur in at least
2939  * 4 constraints, but the constraints may have been simplified.
2940  *
2941  * If any divs are left after these simple checks then we move on
2942  * to more complicated cases in drop_more_redundant_divs.
2943  */
2944 struct isl_basic_map *isl_basic_map_drop_redundant_divs(
2945         struct isl_basic_map *bmap)
2946 {
2947         int i, j;
2948         unsigned off;
2949         int *pairs = NULL;
2950         int n = 0;
2951
2952         if (!bmap)
2953                 goto error;
2954
2955         off = isl_space_dim(bmap->dim, isl_dim_all);
2956         pairs = isl_calloc_array(bmap->ctx, int, bmap->n_div);
2957         if (!pairs)
2958                 goto error;
2959
2960         for (i = 0; i < bmap->n_div; ++i) {
2961                 int pos, neg;
2962                 int last_pos, last_neg;
2963                 int redundant;
2964                 int defined;
2965
2966                 defined = !isl_int_is_zero(bmap->div[i][0]);
2967                 for (j = i; j < bmap->n_div; ++j)
2968                         if (!isl_int_is_zero(bmap->div[j][1 + 1 + off + i]))
2969                                 break;
2970                 if (j < bmap->n_div)
2971                         continue;
2972                 for (j = 0; j < bmap->n_eq; ++j)
2973                         if (!isl_int_is_zero(bmap->eq[j][1 + off + i]))
2974                                 break;
2975                 if (j < bmap->n_eq)
2976                         continue;
2977                 ++n;
2978                 pos = neg = 0;
2979                 for (j = 0; j < bmap->n_ineq; ++j) {
2980                         if (isl_int_is_pos(bmap->ineq[j][1 + off + i])) {
2981                                 last_pos = j;
2982                                 ++pos;
2983                         }
2984                         if (isl_int_is_neg(bmap->ineq[j][1 + off + i])) {
2985                                 last_neg = j;
2986                                 ++neg;
2987                         }
2988                 }
2989                 pairs[i] = pos * neg;
2990                 if (pairs[i] == 0) {
2991                         for (j = bmap->n_ineq - 1; j >= 0; --j)
2992                                 if (!isl_int_is_zero(bmap->ineq[j][1+off+i]))
2993                                         isl_basic_map_drop_inequality(bmap, j);
2994                         bmap = isl_basic_map_drop_div(bmap, i);
2995                         free(pairs);
2996                         return isl_basic_map_drop_redundant_divs(bmap);
2997                 }
2998                 if (pairs[i] != 1)
2999                         continue;
3000                 if (!isl_seq_is_neg(bmap->ineq[last_pos] + 1,
3001                                     bmap->ineq[last_neg] + 1,
3002                                     off + bmap->n_div))
3003                         continue;
3004
3005                 isl_int_add(bmap->ineq[last_pos][0],
3006                             bmap->ineq[last_pos][0], bmap->ineq[last_neg][0]);
3007                 isl_int_add_ui(bmap->ineq[last_pos][0],
3008                                bmap->ineq[last_pos][0], 1);
3009                 redundant = isl_int_ge(bmap->ineq[last_pos][0],
3010                                 bmap->ineq[last_pos][1+off+i]);
3011                 isl_int_sub_ui(bmap->ineq[last_pos][0],
3012                                bmap->ineq[last_pos][0], 1);
3013                 isl_int_sub(bmap->ineq[last_pos][0],
3014                             bmap->ineq[last_pos][0], bmap->ineq[last_neg][0]);
3015                 if (!redundant) {
3016                         if (defined ||
3017                             !ok_to_set_div_from_bound(bmap, i, last_pos)) {
3018                                 pairs[i] = 0;
3019                                 --n;
3020                                 continue;
3021                         }
3022                         bmap = set_div_from_lower_bound(bmap, i, last_pos);
3023                         bmap = isl_basic_map_simplify(bmap);
3024                         free(pairs);
3025                         return isl_basic_map_drop_redundant_divs(bmap);
3026                 }
3027                 if (last_pos > last_neg) {
3028                         isl_basic_map_drop_inequality(bmap, last_pos);
3029                         isl_basic_map_drop_inequality(bmap, last_neg);
3030                 } else {
3031                         isl_basic_map_drop_inequality(bmap, last_neg);
3032                         isl_basic_map_drop_inequality(bmap, last_pos);
3033                 }
3034                 bmap = isl_basic_map_drop_div(bmap, i);
3035                 free(pairs);
3036                 return isl_basic_map_drop_redundant_divs(bmap);
3037         }
3038
3039         if (n > 0)
3040                 return coalesce_or_drop_more_redundant_divs(bmap, pairs, n);
3041
3042         free(pairs);
3043         return bmap;
3044 error:
3045         free(pairs);
3046         isl_basic_map_free(bmap);
3047         return NULL;
3048 }
3049
3050 struct isl_basic_set *isl_basic_set_drop_redundant_divs(
3051         struct isl_basic_set *bset)
3052 {
3053         return (struct isl_basic_set *)
3054             isl_basic_map_drop_redundant_divs((struct isl_basic_map *)bset);
3055 }
3056
3057 struct isl_map *isl_map_drop_redundant_divs(struct isl_map *map)
3058 {
3059         int i;
3060
3061         if (!map)
3062                 return NULL;
3063         for (i = 0; i < map->n; ++i) {
3064                 map->p[i] = isl_basic_map_drop_redundant_divs(map->p[i]);
3065                 if (!map->p[i])
3066                         goto error;
3067         }
3068         ISL_F_CLR(map, ISL_MAP_NORMALIZED);
3069         return map;
3070 error:
3071         isl_map_free(map);
3072         return NULL;
3073 }
3074
3075 struct isl_set *isl_set_drop_redundant_divs(struct isl_set *set)
3076 {
3077         return (struct isl_set *)
3078             isl_map_drop_redundant_divs((struct isl_map *)set);
3079 }