rename isl_basic_map_convex_hull to isl_basic_map_remove_redundancies
[platform/upstream/isl.git] / isl_convex_hull.c
1 /*
2  * Copyright 2008-2009 Katholieke Universiteit Leuven
3  *
4  * Use of this software is governed by the GNU LGPLv2.1 license
5  *
6  * Written by Sven Verdoolaege, K.U.Leuven, Departement
7  * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
8  */
9
10 #include "isl_lp.h"
11 #include "isl_map.h"
12 #include "isl_map_private.h"
13 #include "isl_mat.h"
14 #include "isl_set.h"
15 #include "isl_seq.h"
16 #include "isl_equalities.h"
17 #include "isl_tab.h"
18
19 static struct isl_basic_set *uset_convex_hull_wrap_bounded(struct isl_set *set);
20
21 static void swap_ineq(struct isl_basic_map *bmap, unsigned i, unsigned j)
22 {
23         isl_int *t;
24
25         if (i != j) {
26                 t = bmap->ineq[i];
27                 bmap->ineq[i] = bmap->ineq[j];
28                 bmap->ineq[j] = t;
29         }
30 }
31
32 /* Return 1 if constraint c is redundant with respect to the constraints
33  * in bmap.  If c is a lower [upper] bound in some variable and bmap
34  * does not have a lower [upper] bound in that variable, then c cannot
35  * be redundant and we do not need solve any lp.
36  */
37 int isl_basic_map_constraint_is_redundant(struct isl_basic_map **bmap,
38         isl_int *c, isl_int *opt_n, isl_int *opt_d)
39 {
40         enum isl_lp_result res;
41         unsigned total;
42         int i, j;
43
44         if (!bmap)
45                 return -1;
46
47         total = isl_basic_map_total_dim(*bmap);
48         for (i = 0; i < total; ++i) {
49                 int sign;
50                 if (isl_int_is_zero(c[1+i]))
51                         continue;
52                 sign = isl_int_sgn(c[1+i]);
53                 for (j = 0; j < (*bmap)->n_ineq; ++j)
54                         if (sign == isl_int_sgn((*bmap)->ineq[j][1+i]))
55                                 break;
56                 if (j == (*bmap)->n_ineq)
57                         break;
58         }
59         if (i < total)
60                 return 0;
61
62         res = isl_basic_map_solve_lp(*bmap, 0, c, (*bmap)->ctx->one,
63                                         opt_n, opt_d, NULL);
64         if (res == isl_lp_unbounded)
65                 return 0;
66         if (res == isl_lp_error)
67                 return -1;
68         if (res == isl_lp_empty) {
69                 *bmap = isl_basic_map_set_to_empty(*bmap);
70                 return 0;
71         }
72         return !isl_int_is_neg(*opt_n);
73 }
74
75 int isl_basic_set_constraint_is_redundant(struct isl_basic_set **bset,
76         isl_int *c, isl_int *opt_n, isl_int *opt_d)
77 {
78         return isl_basic_map_constraint_is_redundant(
79                         (struct isl_basic_map **)bset, c, opt_n, opt_d);
80 }
81
82 /* Remove redundant
83  * constraints.  If the minimal value along the normal of a constraint
84  * is the same if the constraint is removed, then the constraint is redundant.
85  *
86  * Alternatively, we could have intersected the basic map with the
87  * corresponding equality and the checked if the dimension was that
88  * of a facet.
89  */
90 __isl_give isl_basic_map *isl_basic_map_remove_redundancies(
91         __isl_take isl_basic_map *bmap)
92 {
93         struct isl_tab *tab;
94
95         if (!bmap)
96                 return NULL;
97
98         bmap = isl_basic_map_gauss(bmap, NULL);
99         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
100                 return bmap;
101         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_NO_REDUNDANT))
102                 return bmap;
103         if (bmap->n_ineq <= 1)
104                 return bmap;
105
106         tab = isl_tab_from_basic_map(bmap);
107         if (isl_tab_detect_implicit_equalities(tab) < 0)
108                 goto error;
109         if (isl_tab_detect_redundant(tab) < 0)
110                 goto error;
111         bmap = isl_basic_map_update_from_tab(bmap, tab);
112         isl_tab_free(tab);
113         ISL_F_SET(bmap, ISL_BASIC_MAP_NO_IMPLICIT);
114         ISL_F_SET(bmap, ISL_BASIC_MAP_NO_REDUNDANT);
115         return bmap;
116 error:
117         isl_tab_free(tab);
118         isl_basic_map_free(bmap);
119         return NULL;
120 }
121
122 __isl_give isl_basic_set *isl_basic_set_remove_redundancies(
123         __isl_take isl_basic_set *bset)
124 {
125         return (struct isl_basic_set *)
126                 isl_basic_map_remove_redundancies((struct isl_basic_map *)bset);
127 }
128
129 /* Check if the set set is bound in the direction of the affine
130  * constraint c and if so, set the constant term such that the
131  * resulting constraint is a bounding constraint for the set.
132  */
133 static int uset_is_bound(struct isl_set *set, isl_int *c, unsigned len)
134 {
135         int first;
136         int j;
137         isl_int opt;
138         isl_int opt_denom;
139
140         isl_int_init(opt);
141         isl_int_init(opt_denom);
142         first = 1;
143         for (j = 0; j < set->n; ++j) {
144                 enum isl_lp_result res;
145
146                 if (ISL_F_ISSET(set->p[j], ISL_BASIC_SET_EMPTY))
147                         continue;
148
149                 res = isl_basic_set_solve_lp(set->p[j],
150                                 0, c, set->ctx->one, &opt, &opt_denom, NULL);
151                 if (res == isl_lp_unbounded)
152                         break;
153                 if (res == isl_lp_error)
154                         goto error;
155                 if (res == isl_lp_empty) {
156                         set->p[j] = isl_basic_set_set_to_empty(set->p[j]);
157                         if (!set->p[j])
158                                 goto error;
159                         continue;
160                 }
161                 if (first || isl_int_is_neg(opt)) {
162                         if (!isl_int_is_one(opt_denom))
163                                 isl_seq_scale(c, c, opt_denom, len);
164                         isl_int_sub(c[0], c[0], opt);
165                 }
166                 first = 0;
167         }
168         isl_int_clear(opt);
169         isl_int_clear(opt_denom);
170         return j >= set->n;
171 error:
172         isl_int_clear(opt);
173         isl_int_clear(opt_denom);
174         return -1;
175 }
176
177 struct isl_basic_set *isl_basic_set_set_rational(struct isl_basic_set *bset)
178 {
179         if (!bset)
180                 return NULL;
181
182         if (ISL_F_ISSET(bset, ISL_BASIC_MAP_RATIONAL))
183                 return bset;
184
185         bset = isl_basic_set_cow(bset);
186         if (!bset)
187                 return NULL;
188
189         ISL_F_SET(bset, ISL_BASIC_MAP_RATIONAL);
190
191         return isl_basic_set_finalize(bset);
192 }
193
194 static struct isl_set *isl_set_set_rational(struct isl_set *set)
195 {
196         int i;
197
198         set = isl_set_cow(set);
199         if (!set)
200                 return NULL;
201         for (i = 0; i < set->n; ++i) {
202                 set->p[i] = isl_basic_set_set_rational(set->p[i]);
203                 if (!set->p[i])
204                         goto error;
205         }
206         return set;
207 error:
208         isl_set_free(set);
209         return NULL;
210 }
211
212 static struct isl_basic_set *isl_basic_set_add_equality(
213         struct isl_basic_set *bset, isl_int *c)
214 {
215         int i;
216         unsigned dim;
217
218         if (!bset)
219                 return NULL;
220
221         if (ISL_F_ISSET(bset, ISL_BASIC_SET_EMPTY))
222                 return bset;
223
224         isl_assert(bset->ctx, isl_basic_set_n_param(bset) == 0, goto error);
225         isl_assert(bset->ctx, bset->n_div == 0, goto error);
226         dim = isl_basic_set_n_dim(bset);
227         bset = isl_basic_set_cow(bset);
228         bset = isl_basic_set_extend(bset, 0, dim, 0, 1, 0);
229         i = isl_basic_set_alloc_equality(bset);
230         if (i < 0)
231                 goto error;
232         isl_seq_cpy(bset->eq[i], c, 1 + dim);
233         return bset;
234 error:
235         isl_basic_set_free(bset);
236         return NULL;
237 }
238
239 static struct isl_set *isl_set_add_basic_set_equality(struct isl_set *set, isl_int *c)
240 {
241         int i;
242
243         set = isl_set_cow(set);
244         if (!set)
245                 return NULL;
246         for (i = 0; i < set->n; ++i) {
247                 set->p[i] = isl_basic_set_add_equality(set->p[i], c);
248                 if (!set->p[i])
249                         goto error;
250         }
251         return set;
252 error:
253         isl_set_free(set);
254         return NULL;
255 }
256
257 /* Given a union of basic sets, construct the constraints for wrapping
258  * a facet around one of its ridges.
259  * In particular, if each of n the d-dimensional basic sets i in "set"
260  * contains the origin, satisfies the constraints x_1 >= 0 and x_2 >= 0
261  * and is defined by the constraints
262  *                                  [ 1 ]
263  *                              A_i [ x ]  >= 0
264  *
265  * then the resulting set is of dimension n*(1+d) and has as constraints
266  *
267  *                                  [ a_i ]
268  *                              A_i [ x_i ] >= 0
269  *
270  *                                    a_i   >= 0
271  *
272  *                      \sum_i x_{i,1} = 1
273  */
274 static struct isl_basic_set *wrap_constraints(struct isl_set *set)
275 {
276         struct isl_basic_set *lp;
277         unsigned n_eq;
278         unsigned n_ineq;
279         int i, j, k;
280         unsigned dim, lp_dim;
281
282         if (!set)
283                 return NULL;
284
285         dim = 1 + isl_set_n_dim(set);
286         n_eq = 1;
287         n_ineq = set->n;
288         for (i = 0; i < set->n; ++i) {
289                 n_eq += set->p[i]->n_eq;
290                 n_ineq += set->p[i]->n_ineq;
291         }
292         lp = isl_basic_set_alloc(set->ctx, 0, dim * set->n, 0, n_eq, n_ineq);
293         if (!lp)
294                 return NULL;
295         lp_dim = isl_basic_set_n_dim(lp);
296         k = isl_basic_set_alloc_equality(lp);
297         isl_int_set_si(lp->eq[k][0], -1);
298         for (i = 0; i < set->n; ++i) {
299                 isl_int_set_si(lp->eq[k][1+dim*i], 0);
300                 isl_int_set_si(lp->eq[k][1+dim*i+1], 1);
301                 isl_seq_clr(lp->eq[k]+1+dim*i+2, dim-2);
302         }
303         for (i = 0; i < set->n; ++i) {
304                 k = isl_basic_set_alloc_inequality(lp);
305                 isl_seq_clr(lp->ineq[k], 1+lp_dim);
306                 isl_int_set_si(lp->ineq[k][1+dim*i], 1);
307
308                 for (j = 0; j < set->p[i]->n_eq; ++j) {
309                         k = isl_basic_set_alloc_equality(lp);
310                         isl_seq_clr(lp->eq[k], 1+dim*i);
311                         isl_seq_cpy(lp->eq[k]+1+dim*i, set->p[i]->eq[j], dim);
312                         isl_seq_clr(lp->eq[k]+1+dim*(i+1), dim*(set->n-i-1));
313                 }
314
315                 for (j = 0; j < set->p[i]->n_ineq; ++j) {
316                         k = isl_basic_set_alloc_inequality(lp);
317                         isl_seq_clr(lp->ineq[k], 1+dim*i);
318                         isl_seq_cpy(lp->ineq[k]+1+dim*i, set->p[i]->ineq[j], dim);
319                         isl_seq_clr(lp->ineq[k]+1+dim*(i+1), dim*(set->n-i-1));
320                 }
321         }
322         return lp;
323 }
324
325 /* Given a facet "facet" of the convex hull of "set" and a facet "ridge"
326  * of that facet, compute the other facet of the convex hull that contains
327  * the ridge.
328  *
329  * We first transform the set such that the facet constraint becomes
330  *
331  *                      x_1 >= 0
332  *
333  * I.e., the facet lies in
334  *
335  *                      x_1 = 0
336  *
337  * and on that facet, the constraint that defines the ridge is
338  *
339  *                      x_2 >= 0
340  *
341  * (This transformation is not strictly needed, all that is needed is
342  * that the ridge contains the origin.)
343  *
344  * Since the ridge contains the origin, the cone of the convex hull
345  * will be of the form
346  *
347  *                      x_1 >= 0
348  *                      x_2 >= a x_1
349  *
350  * with this second constraint defining the new facet.
351  * The constant a is obtained by settting x_1 in the cone of the
352  * convex hull to 1 and minimizing x_2.
353  * Now, each element in the cone of the convex hull is the sum
354  * of elements in the cones of the basic sets.
355  * If a_i is the dilation factor of basic set i, then the problem
356  * we need to solve is
357  *
358  *                      min \sum_i x_{i,2}
359  *                      st
360  *                              \sum_i x_{i,1} = 1
361  *                                  a_i   >= 0
362  *                                [ a_i ]
363  *                              A [ x_i ] >= 0
364  *
365  * with
366  *                                  [  1  ]
367  *                              A_i [ x_i ] >= 0
368  *
369  * the constraints of each (transformed) basic set.
370  * If a = n/d, then the constraint defining the new facet (in the transformed
371  * space) is
372  *
373  *                      -n x_1 + d x_2 >= 0
374  *
375  * In the original space, we need to take the same combination of the
376  * corresponding constraints "facet" and "ridge".
377  *
378  * If a = -infty = "-1/0", then we just return the original facet constraint.
379  * This means that the facet is unbounded, but has a bounded intersection
380  * with the union of sets.
381  */
382 isl_int *isl_set_wrap_facet(__isl_keep isl_set *set,
383         isl_int *facet, isl_int *ridge)
384 {
385         int i;
386         isl_ctx *ctx;
387         struct isl_mat *T = NULL;
388         struct isl_basic_set *lp = NULL;
389         struct isl_vec *obj;
390         enum isl_lp_result res;
391         isl_int num, den;
392         unsigned dim;
393
394         if (!set)
395                 return NULL;
396         ctx = set->ctx;
397         set = isl_set_copy(set);
398         set = isl_set_set_rational(set);
399
400         dim = 1 + isl_set_n_dim(set);
401         T = isl_mat_alloc(ctx, 3, dim);
402         if (!T)
403                 goto error;
404         isl_int_set_si(T->row[0][0], 1);
405         isl_seq_clr(T->row[0]+1, dim - 1);
406         isl_seq_cpy(T->row[1], facet, dim);
407         isl_seq_cpy(T->row[2], ridge, dim);
408         T = isl_mat_right_inverse(T);
409         set = isl_set_preimage(set, T);
410         T = NULL;
411         if (!set)
412                 goto error;
413         lp = wrap_constraints(set);
414         obj = isl_vec_alloc(ctx, 1 + dim*set->n);
415         if (!obj)
416                 goto error;
417         isl_int_set_si(obj->block.data[0], 0);
418         for (i = 0; i < set->n; ++i) {
419                 isl_seq_clr(obj->block.data + 1 + dim*i, 2);
420                 isl_int_set_si(obj->block.data[1 + dim*i+2], 1);
421                 isl_seq_clr(obj->block.data + 1 + dim*i+3, dim-3);
422         }
423         isl_int_init(num);
424         isl_int_init(den);
425         res = isl_basic_set_solve_lp(lp, 0,
426                             obj->block.data, ctx->one, &num, &den, NULL);
427         if (res == isl_lp_ok) {
428                 isl_int_neg(num, num);
429                 isl_seq_combine(facet, num, facet, den, ridge, dim);
430         }
431         isl_int_clear(num);
432         isl_int_clear(den);
433         isl_vec_free(obj);
434         isl_basic_set_free(lp);
435         isl_set_free(set);
436         if (res == isl_lp_error)
437                 return NULL;
438         isl_assert(ctx, res == isl_lp_ok || res == isl_lp_unbounded, 
439                    return NULL);
440         return facet;
441 error:
442         isl_basic_set_free(lp);
443         isl_mat_free(T);
444         isl_set_free(set);
445         return NULL;
446 }
447
448 /* Compute the constraint of a facet of "set".
449  *
450  * We first compute the intersection with a bounding constraint
451  * that is orthogonal to one of the coordinate axes.
452  * If the affine hull of this intersection has only one equality,
453  * we have found a facet.
454  * Otherwise, we wrap the current bounding constraint around
455  * one of the equalities of the face (one that is not equal to
456  * the current bounding constraint).
457  * This process continues until we have found a facet.
458  * The dimension of the intersection increases by at least
459  * one on each iteration, so termination is guaranteed.
460  */
461 static __isl_give isl_mat *initial_facet_constraint(__isl_keep isl_set *set)
462 {
463         struct isl_set *slice = NULL;
464         struct isl_basic_set *face = NULL;
465         int i;
466         unsigned dim = isl_set_n_dim(set);
467         int is_bound;
468         isl_mat *bounds;
469
470         isl_assert(set->ctx, set->n > 0, goto error);
471         bounds = isl_mat_alloc(set->ctx, 1, 1 + dim);
472         if (!bounds)
473                 return NULL;
474
475         isl_seq_clr(bounds->row[0], dim);
476         isl_int_set_si(bounds->row[0][1 + dim - 1], 1);
477         is_bound = uset_is_bound(set, bounds->row[0], 1 + dim);
478         isl_assert(set->ctx, is_bound == 1, goto error);
479         isl_seq_normalize(set->ctx, bounds->row[0], 1 + dim);
480         bounds->n_row = 1;
481
482         for (;;) {
483                 slice = isl_set_copy(set);
484                 slice = isl_set_add_basic_set_equality(slice, bounds->row[0]);
485                 face = isl_set_affine_hull(slice);
486                 if (!face)
487                         goto error;
488                 if (face->n_eq == 1) {
489                         isl_basic_set_free(face);
490                         break;
491                 }
492                 for (i = 0; i < face->n_eq; ++i)
493                         if (!isl_seq_eq(bounds->row[0], face->eq[i], 1 + dim) &&
494                             !isl_seq_is_neg(bounds->row[0],
495                                                 face->eq[i], 1 + dim))
496                                 break;
497                 isl_assert(set->ctx, i < face->n_eq, goto error);
498                 if (!isl_set_wrap_facet(set, bounds->row[0], face->eq[i]))
499                         goto error;
500                 isl_seq_normalize(set->ctx, bounds->row[0], bounds->n_col);
501                 isl_basic_set_free(face);
502         }
503
504         return bounds;
505 error:
506         isl_basic_set_free(face);
507         isl_mat_free(bounds);
508         return NULL;
509 }
510
511 /* Given the bounding constraint "c" of a facet of the convex hull of "set",
512  * compute a hyperplane description of the facet, i.e., compute the facets
513  * of the facet.
514  *
515  * We compute an affine transformation that transforms the constraint
516  *
517  *                        [ 1 ]
518  *                      c [ x ] = 0
519  *
520  * to the constraint
521  *
522  *                         z_1  = 0
523  *
524  * by computing the right inverse U of a matrix that starts with the rows
525  *
526  *                      [ 1 0 ]
527  *                      [  c  ]
528  *
529  * Then
530  *                      [ 1 ]     [ 1 ]
531  *                      [ x ] = U [ z ]
532  * and
533  *                      [ 1 ]     [ 1 ]
534  *                      [ z ] = Q [ x ]
535  *
536  * with Q = U^{-1}
537  * Since z_1 is zero, we can drop this variable as well as the corresponding
538  * column of U to obtain
539  *
540  *                      [ 1 ]      [ 1  ]
541  *                      [ x ] = U' [ z' ]
542  * and
543  *                      [ 1  ]      [ 1 ]
544  *                      [ z' ] = Q' [ x ]
545  *
546  * with Q' equal to Q, but without the corresponding row.
547  * After computing the facets of the facet in the z' space,
548  * we convert them back to the x space through Q.
549  */
550 static struct isl_basic_set *compute_facet(struct isl_set *set, isl_int *c)
551 {
552         struct isl_mat *m, *U, *Q;
553         struct isl_basic_set *facet = NULL;
554         struct isl_ctx *ctx;
555         unsigned dim;
556
557         ctx = set->ctx;
558         set = isl_set_copy(set);
559         dim = isl_set_n_dim(set);
560         m = isl_mat_alloc(set->ctx, 2, 1 + dim);
561         if (!m)
562                 goto error;
563         isl_int_set_si(m->row[0][0], 1);
564         isl_seq_clr(m->row[0]+1, dim);
565         isl_seq_cpy(m->row[1], c, 1+dim);
566         U = isl_mat_right_inverse(m);
567         Q = isl_mat_right_inverse(isl_mat_copy(U));
568         U = isl_mat_drop_cols(U, 1, 1);
569         Q = isl_mat_drop_rows(Q, 1, 1);
570         set = isl_set_preimage(set, U);
571         facet = uset_convex_hull_wrap_bounded(set);
572         facet = isl_basic_set_preimage(facet, Q);
573         if (facet)
574                 isl_assert(ctx, facet->n_eq == 0, goto error);
575         return facet;
576 error:
577         isl_basic_set_free(facet);
578         isl_set_free(set);
579         return NULL;
580 }
581
582 /* Given an initial facet constraint, compute the remaining facets.
583  * We do this by running through all facets found so far and computing
584  * the adjacent facets through wrapping, adding those facets that we
585  * hadn't already found before.
586  *
587  * For each facet we have found so far, we first compute its facets
588  * in the resulting convex hull.  That is, we compute the ridges
589  * of the resulting convex hull contained in the facet.
590  * We also compute the corresponding facet in the current approximation
591  * of the convex hull.  There is no need to wrap around the ridges
592  * in this facet since that would result in a facet that is already
593  * present in the current approximation.
594  *
595  * This function can still be significantly optimized by checking which of
596  * the facets of the basic sets are also facets of the convex hull and
597  * using all the facets so far to help in constructing the facets of the
598  * facets
599  * and/or
600  * using the technique in section "3.1 Ridge Generation" of
601  * "Extended Convex Hull" by Fukuda et al.
602  */
603 static struct isl_basic_set *extend(struct isl_basic_set *hull,
604         struct isl_set *set)
605 {
606         int i, j, f;
607         int k;
608         struct isl_basic_set *facet = NULL;
609         struct isl_basic_set *hull_facet = NULL;
610         unsigned dim;
611
612         if (!hull)
613                 return NULL;
614
615         isl_assert(set->ctx, set->n > 0, goto error);
616
617         dim = isl_set_n_dim(set);
618
619         for (i = 0; i < hull->n_ineq; ++i) {
620                 facet = compute_facet(set, hull->ineq[i]);
621                 facet = isl_basic_set_add_equality(facet, hull->ineq[i]);
622                 facet = isl_basic_set_gauss(facet, NULL);
623                 facet = isl_basic_set_normalize_constraints(facet);
624                 hull_facet = isl_basic_set_copy(hull);
625                 hull_facet = isl_basic_set_add_equality(hull_facet, hull->ineq[i]);
626                 hull_facet = isl_basic_set_gauss(hull_facet, NULL);
627                 hull_facet = isl_basic_set_normalize_constraints(hull_facet);
628                 if (!facet || !hull_facet)
629                         goto error;
630                 hull = isl_basic_set_cow(hull);
631                 hull = isl_basic_set_extend_dim(hull,
632                         isl_dim_copy(hull->dim), 0, 0, facet->n_ineq);
633                 if (!hull)
634                         goto error;
635                 for (j = 0; j < facet->n_ineq; ++j) {
636                         for (f = 0; f < hull_facet->n_ineq; ++f)
637                                 if (isl_seq_eq(facet->ineq[j],
638                                                 hull_facet->ineq[f], 1 + dim))
639                                         break;
640                         if (f < hull_facet->n_ineq)
641                                 continue;
642                         k = isl_basic_set_alloc_inequality(hull);
643                         if (k < 0)
644                                 goto error;
645                         isl_seq_cpy(hull->ineq[k], hull->ineq[i], 1+dim);
646                         if (!isl_set_wrap_facet(set, hull->ineq[k], facet->ineq[j]))
647                                 goto error;
648                 }
649                 isl_basic_set_free(hull_facet);
650                 isl_basic_set_free(facet);
651         }
652         hull = isl_basic_set_simplify(hull);
653         hull = isl_basic_set_finalize(hull);
654         return hull;
655 error:
656         isl_basic_set_free(hull_facet);
657         isl_basic_set_free(facet);
658         isl_basic_set_free(hull);
659         return NULL;
660 }
661
662 /* Special case for computing the convex hull of a one dimensional set.
663  * We simply collect the lower and upper bounds of each basic set
664  * and the biggest of those.
665  */
666 static struct isl_basic_set *convex_hull_1d(struct isl_set *set)
667 {
668         struct isl_mat *c = NULL;
669         isl_int *lower = NULL;
670         isl_int *upper = NULL;
671         int i, j, k;
672         isl_int a, b;
673         struct isl_basic_set *hull;
674
675         for (i = 0; i < set->n; ++i) {
676                 set->p[i] = isl_basic_set_simplify(set->p[i]);
677                 if (!set->p[i])
678                         goto error;
679         }
680         set = isl_set_remove_empty_parts(set);
681         if (!set)
682                 goto error;
683         isl_assert(set->ctx, set->n > 0, goto error);
684         c = isl_mat_alloc(set->ctx, 2, 2);
685         if (!c)
686                 goto error;
687
688         if (set->p[0]->n_eq > 0) {
689                 isl_assert(set->ctx, set->p[0]->n_eq == 1, goto error);
690                 lower = c->row[0];
691                 upper = c->row[1];
692                 if (isl_int_is_pos(set->p[0]->eq[0][1])) {
693                         isl_seq_cpy(lower, set->p[0]->eq[0], 2);
694                         isl_seq_neg(upper, set->p[0]->eq[0], 2);
695                 } else {
696                         isl_seq_neg(lower, set->p[0]->eq[0], 2);
697                         isl_seq_cpy(upper, set->p[0]->eq[0], 2);
698                 }
699         } else {
700                 for (j = 0; j < set->p[0]->n_ineq; ++j) {
701                         if (isl_int_is_pos(set->p[0]->ineq[j][1])) {
702                                 lower = c->row[0];
703                                 isl_seq_cpy(lower, set->p[0]->ineq[j], 2);
704                         } else {
705                                 upper = c->row[1];
706                                 isl_seq_cpy(upper, set->p[0]->ineq[j], 2);
707                         }
708                 }
709         }
710
711         isl_int_init(a);
712         isl_int_init(b);
713         for (i = 0; i < set->n; ++i) {
714                 struct isl_basic_set *bset = set->p[i];
715                 int has_lower = 0;
716                 int has_upper = 0;
717
718                 for (j = 0; j < bset->n_eq; ++j) {
719                         has_lower = 1;
720                         has_upper = 1;
721                         if (lower) {
722                                 isl_int_mul(a, lower[0], bset->eq[j][1]);
723                                 isl_int_mul(b, lower[1], bset->eq[j][0]);
724                                 if (isl_int_lt(a, b) && isl_int_is_pos(bset->eq[j][1]))
725                                         isl_seq_cpy(lower, bset->eq[j], 2);
726                                 if (isl_int_gt(a, b) && isl_int_is_neg(bset->eq[j][1]))
727                                         isl_seq_neg(lower, bset->eq[j], 2);
728                         }
729                         if (upper) {
730                                 isl_int_mul(a, upper[0], bset->eq[j][1]);
731                                 isl_int_mul(b, upper[1], bset->eq[j][0]);
732                                 if (isl_int_lt(a, b) && isl_int_is_pos(bset->eq[j][1]))
733                                         isl_seq_neg(upper, bset->eq[j], 2);
734                                 if (isl_int_gt(a, b) && isl_int_is_neg(bset->eq[j][1]))
735                                         isl_seq_cpy(upper, bset->eq[j], 2);
736                         }
737                 }
738                 for (j = 0; j < bset->n_ineq; ++j) {
739                         if (isl_int_is_pos(bset->ineq[j][1]))
740                                 has_lower = 1;
741                         if (isl_int_is_neg(bset->ineq[j][1]))
742                                 has_upper = 1;
743                         if (lower && isl_int_is_pos(bset->ineq[j][1])) {
744                                 isl_int_mul(a, lower[0], bset->ineq[j][1]);
745                                 isl_int_mul(b, lower[1], bset->ineq[j][0]);
746                                 if (isl_int_lt(a, b))
747                                         isl_seq_cpy(lower, bset->ineq[j], 2);
748                         }
749                         if (upper && isl_int_is_neg(bset->ineq[j][1])) {
750                                 isl_int_mul(a, upper[0], bset->ineq[j][1]);
751                                 isl_int_mul(b, upper[1], bset->ineq[j][0]);
752                                 if (isl_int_gt(a, b))
753                                         isl_seq_cpy(upper, bset->ineq[j], 2);
754                         }
755                 }
756                 if (!has_lower)
757                         lower = NULL;
758                 if (!has_upper)
759                         upper = NULL;
760         }
761         isl_int_clear(a);
762         isl_int_clear(b);
763
764         hull = isl_basic_set_alloc(set->ctx, 0, 1, 0, 0, 2);
765         hull = isl_basic_set_set_rational(hull);
766         if (!hull)
767                 goto error;
768         if (lower) {
769                 k = isl_basic_set_alloc_inequality(hull);
770                 isl_seq_cpy(hull->ineq[k], lower, 2);
771         }
772         if (upper) {
773                 k = isl_basic_set_alloc_inequality(hull);
774                 isl_seq_cpy(hull->ineq[k], upper, 2);
775         }
776         hull = isl_basic_set_finalize(hull);
777         isl_set_free(set);
778         isl_mat_free(c);
779         return hull;
780 error:
781         isl_set_free(set);
782         isl_mat_free(c);
783         return NULL;
784 }
785
786 /* Project out final n dimensions using Fourier-Motzkin */
787 static struct isl_set *set_project_out(struct isl_ctx *ctx,
788         struct isl_set *set, unsigned n)
789 {
790         return isl_set_remove_dims(set, isl_set_n_dim(set) - n, n);
791 }
792
793 static struct isl_basic_set *convex_hull_0d(struct isl_set *set)
794 {
795         struct isl_basic_set *convex_hull;
796
797         if (!set)
798                 return NULL;
799
800         if (isl_set_is_empty(set))
801                 convex_hull = isl_basic_set_empty(isl_dim_copy(set->dim));
802         else
803                 convex_hull = isl_basic_set_universe(isl_dim_copy(set->dim));
804         isl_set_free(set);
805         return convex_hull;
806 }
807
808 /* Compute the convex hull of a pair of basic sets without any parameters or
809  * integer divisions using Fourier-Motzkin elimination.
810  * The convex hull is the set of all points that can be written as
811  * the sum of points from both basic sets (in homogeneous coordinates).
812  * We set up the constraints in a space with dimensions for each of
813  * the three sets and then project out the dimensions corresponding
814  * to the two original basic sets, retaining only those corresponding
815  * to the convex hull.
816  */
817 static struct isl_basic_set *convex_hull_pair_elim(struct isl_basic_set *bset1,
818         struct isl_basic_set *bset2)
819 {
820         int i, j, k;
821         struct isl_basic_set *bset[2];
822         struct isl_basic_set *hull = NULL;
823         unsigned dim;
824
825         if (!bset1 || !bset2)
826                 goto error;
827
828         dim = isl_basic_set_n_dim(bset1);
829         hull = isl_basic_set_alloc(bset1->ctx, 0, 2 + 3 * dim, 0,
830                                 1 + dim + bset1->n_eq + bset2->n_eq,
831                                 2 + bset1->n_ineq + bset2->n_ineq);
832         bset[0] = bset1;
833         bset[1] = bset2;
834         for (i = 0; i < 2; ++i) {
835                 for (j = 0; j < bset[i]->n_eq; ++j) {
836                         k = isl_basic_set_alloc_equality(hull);
837                         if (k < 0)
838                                 goto error;
839                         isl_seq_clr(hull->eq[k], (i+1) * (1+dim));
840                         isl_seq_clr(hull->eq[k]+(i+2)*(1+dim), (1-i)*(1+dim));
841                         isl_seq_cpy(hull->eq[k]+(i+1)*(1+dim), bset[i]->eq[j],
842                                         1+dim);
843                 }
844                 for (j = 0; j < bset[i]->n_ineq; ++j) {
845                         k = isl_basic_set_alloc_inequality(hull);
846                         if (k < 0)
847                                 goto error;
848                         isl_seq_clr(hull->ineq[k], (i+1) * (1+dim));
849                         isl_seq_clr(hull->ineq[k]+(i+2)*(1+dim), (1-i)*(1+dim));
850                         isl_seq_cpy(hull->ineq[k]+(i+1)*(1+dim),
851                                         bset[i]->ineq[j], 1+dim);
852                 }
853                 k = isl_basic_set_alloc_inequality(hull);
854                 if (k < 0)
855                         goto error;
856                 isl_seq_clr(hull->ineq[k], 1+2+3*dim);
857                 isl_int_set_si(hull->ineq[k][(i+1)*(1+dim)], 1);
858         }
859         for (j = 0; j < 1+dim; ++j) {
860                 k = isl_basic_set_alloc_equality(hull);
861                 if (k < 0)
862                         goto error;
863                 isl_seq_clr(hull->eq[k], 1+2+3*dim);
864                 isl_int_set_si(hull->eq[k][j], -1);
865                 isl_int_set_si(hull->eq[k][1+dim+j], 1);
866                 isl_int_set_si(hull->eq[k][2*(1+dim)+j], 1);
867         }
868         hull = isl_basic_set_set_rational(hull);
869         hull = isl_basic_set_remove_dims(hull, dim, 2*(1+dim));
870         hull = isl_basic_set_remove_redundancies(hull);
871         isl_basic_set_free(bset1);
872         isl_basic_set_free(bset2);
873         return hull;
874 error:
875         isl_basic_set_free(bset1);
876         isl_basic_set_free(bset2);
877         isl_basic_set_free(hull);
878         return NULL;
879 }
880
881 /* Is the set bounded for each value of the parameters?
882  */
883 int isl_basic_set_is_bounded(__isl_keep isl_basic_set *bset)
884 {
885         struct isl_tab *tab;
886         int bounded;
887
888         if (!bset)
889                 return -1;
890         if (isl_basic_set_fast_is_empty(bset))
891                 return 1;
892
893         tab = isl_tab_from_recession_cone(bset, 1);
894         bounded = isl_tab_cone_is_bounded(tab);
895         isl_tab_free(tab);
896         return bounded;
897 }
898
899 /* Is the set bounded for each value of the parameters?
900  */
901 int isl_set_is_bounded(__isl_keep isl_set *set)
902 {
903         int i;
904
905         if (!set)
906                 return -1;
907
908         for (i = 0; i < set->n; ++i) {
909                 int bounded = isl_basic_set_is_bounded(set->p[i]);
910                 if (!bounded || bounded < 0)
911                         return bounded;
912         }
913         return 1;
914 }
915
916 /* Compute the lineality space of the convex hull of bset1 and bset2.
917  *
918  * We first compute the intersection of the recession cone of bset1
919  * with the negative of the recession cone of bset2 and then compute
920  * the linear hull of the resulting cone.
921  */
922 static struct isl_basic_set *induced_lineality_space(
923         struct isl_basic_set *bset1, struct isl_basic_set *bset2)
924 {
925         int i, k;
926         struct isl_basic_set *lin = NULL;
927         unsigned dim;
928
929         if (!bset1 || !bset2)
930                 goto error;
931
932         dim = isl_basic_set_total_dim(bset1);
933         lin = isl_basic_set_alloc_dim(isl_basic_set_get_dim(bset1), 0,
934                                         bset1->n_eq + bset2->n_eq,
935                                         bset1->n_ineq + bset2->n_ineq);
936         lin = isl_basic_set_set_rational(lin);
937         if (!lin)
938                 goto error;
939         for (i = 0; i < bset1->n_eq; ++i) {
940                 k = isl_basic_set_alloc_equality(lin);
941                 if (k < 0)
942                         goto error;
943                 isl_int_set_si(lin->eq[k][0], 0);
944                 isl_seq_cpy(lin->eq[k] + 1, bset1->eq[i] + 1, dim);
945         }
946         for (i = 0; i < bset1->n_ineq; ++i) {
947                 k = isl_basic_set_alloc_inequality(lin);
948                 if (k < 0)
949                         goto error;
950                 isl_int_set_si(lin->ineq[k][0], 0);
951                 isl_seq_cpy(lin->ineq[k] + 1, bset1->ineq[i] + 1, dim);
952         }
953         for (i = 0; i < bset2->n_eq; ++i) {
954                 k = isl_basic_set_alloc_equality(lin);
955                 if (k < 0)
956                         goto error;
957                 isl_int_set_si(lin->eq[k][0], 0);
958                 isl_seq_neg(lin->eq[k] + 1, bset2->eq[i] + 1, dim);
959         }
960         for (i = 0; i < bset2->n_ineq; ++i) {
961                 k = isl_basic_set_alloc_inequality(lin);
962                 if (k < 0)
963                         goto error;
964                 isl_int_set_si(lin->ineq[k][0], 0);
965                 isl_seq_neg(lin->ineq[k] + 1, bset2->ineq[i] + 1, dim);
966         }
967
968         isl_basic_set_free(bset1);
969         isl_basic_set_free(bset2);
970         return isl_basic_set_affine_hull(lin);
971 error:
972         isl_basic_set_free(lin);
973         isl_basic_set_free(bset1);
974         isl_basic_set_free(bset2);
975         return NULL;
976 }
977
978 static struct isl_basic_set *uset_convex_hull(struct isl_set *set);
979
980 /* Given a set and a linear space "lin" of dimension n > 0,
981  * project the linear space from the set, compute the convex hull
982  * and then map the set back to the original space.
983  *
984  * Let
985  *
986  *      M x = 0
987  *
988  * describe the linear space.  We first compute the Hermite normal
989  * form H = M U of M = H Q, to obtain
990  *
991  *      H Q x = 0
992  *
993  * The last n rows of H will be zero, so the last n variables of x' = Q x
994  * are the one we want to project out.  We do this by transforming each
995  * basic set A x >= b to A U x' >= b and then removing the last n dimensions.
996  * After computing the convex hull in x'_1, i.e., A' x'_1 >= b',
997  * we transform the hull back to the original space as A' Q_1 x >= b',
998  * with Q_1 all but the last n rows of Q.
999  */
1000 static struct isl_basic_set *modulo_lineality(struct isl_set *set,
1001         struct isl_basic_set *lin)
1002 {
1003         unsigned total = isl_basic_set_total_dim(lin);
1004         unsigned lin_dim;
1005         struct isl_basic_set *hull;
1006         struct isl_mat *M, *U, *Q;
1007
1008         if (!set || !lin)
1009                 goto error;
1010         lin_dim = total - lin->n_eq;
1011         M = isl_mat_sub_alloc(set->ctx, lin->eq, 0, lin->n_eq, 1, total);
1012         M = isl_mat_left_hermite(M, 0, &U, &Q);
1013         if (!M)
1014                 goto error;
1015         isl_mat_free(M);
1016         isl_basic_set_free(lin);
1017
1018         Q = isl_mat_drop_rows(Q, Q->n_row - lin_dim, lin_dim);
1019
1020         U = isl_mat_lin_to_aff(U);
1021         Q = isl_mat_lin_to_aff(Q);
1022
1023         set = isl_set_preimage(set, U);
1024         set = isl_set_remove_dims(set, total - lin_dim, lin_dim);
1025         hull = uset_convex_hull(set);
1026         hull = isl_basic_set_preimage(hull, Q);
1027
1028         return hull;
1029 error:
1030         isl_basic_set_free(lin);
1031         isl_set_free(set);
1032         return NULL;
1033 }
1034
1035 /* Given two polyhedra with as constraints h_{ij} x >= 0 in homegeneous space,
1036  * set up an LP for solving
1037  *
1038  *      \sum_j \alpha_{1j} h_{1j} = \sum_j \alpha_{2j} h_{2j}
1039  *
1040  * \alpha{i0} corresponds to the (implicit) positivity constraint 1 >= 0
1041  * The next \alpha{ij} correspond to the equalities and come in pairs.
1042  * The final \alpha{ij} correspond to the inequalities.
1043  */
1044 static struct isl_basic_set *valid_direction_lp(
1045         struct isl_basic_set *bset1, struct isl_basic_set *bset2)
1046 {
1047         struct isl_dim *dim;
1048         struct isl_basic_set *lp;
1049         unsigned d;
1050         int n;
1051         int i, j, k;
1052
1053         if (!bset1 || !bset2)
1054                 goto error;
1055         d = 1 + isl_basic_set_total_dim(bset1);
1056         n = 2 +
1057             2 * bset1->n_eq + bset1->n_ineq + 2 * bset2->n_eq + bset2->n_ineq;
1058         dim = isl_dim_set_alloc(bset1->ctx, 0, n);
1059         lp = isl_basic_set_alloc_dim(dim, 0, d, n);
1060         if (!lp)
1061                 goto error;
1062         for (i = 0; i < n; ++i) {
1063                 k = isl_basic_set_alloc_inequality(lp);
1064                 if (k < 0)
1065                         goto error;
1066                 isl_seq_clr(lp->ineq[k] + 1, n);
1067                 isl_int_set_si(lp->ineq[k][0], -1);
1068                 isl_int_set_si(lp->ineq[k][1 + i], 1);
1069         }
1070         for (i = 0; i < d; ++i) {
1071                 k = isl_basic_set_alloc_equality(lp);
1072                 if (k < 0)
1073                         goto error;
1074                 n = 0;
1075                 isl_int_set_si(lp->eq[k][n++], 0);
1076                 /* positivity constraint 1 >= 0 */
1077                 isl_int_set_si(lp->eq[k][n++], i == 0);
1078                 for (j = 0; j < bset1->n_eq; ++j) {
1079                         isl_int_set(lp->eq[k][n++], bset1->eq[j][i]);
1080                         isl_int_neg(lp->eq[k][n++], bset1->eq[j][i]);
1081                 }
1082                 for (j = 0; j < bset1->n_ineq; ++j)
1083                         isl_int_set(lp->eq[k][n++], bset1->ineq[j][i]);
1084                 /* positivity constraint 1 >= 0 */
1085                 isl_int_set_si(lp->eq[k][n++], -(i == 0));
1086                 for (j = 0; j < bset2->n_eq; ++j) {
1087                         isl_int_neg(lp->eq[k][n++], bset2->eq[j][i]);
1088                         isl_int_set(lp->eq[k][n++], bset2->eq[j][i]);
1089                 }
1090                 for (j = 0; j < bset2->n_ineq; ++j)
1091                         isl_int_neg(lp->eq[k][n++], bset2->ineq[j][i]);
1092         }
1093         lp = isl_basic_set_gauss(lp, NULL);
1094         isl_basic_set_free(bset1);
1095         isl_basic_set_free(bset2);
1096         return lp;
1097 error:
1098         isl_basic_set_free(bset1);
1099         isl_basic_set_free(bset2);
1100         return NULL;
1101 }
1102
1103 /* Compute a vector s in the homogeneous space such that <s, r> > 0
1104  * for all rays in the homogeneous space of the two cones that correspond
1105  * to the input polyhedra bset1 and bset2.
1106  *
1107  * We compute s as a vector that satisfies
1108  *
1109  *      s = \sum_j \alpha_{ij} h_{ij}   for i = 1,2                     (*)
1110  *
1111  * with h_{ij} the normals of the facets of polyhedron i
1112  * (including the "positivity constraint" 1 >= 0) and \alpha_{ij}
1113  * strictly positive numbers.  For simplicity we impose \alpha_{ij} >= 1.
1114  * We first set up an LP with as variables the \alpha{ij}.
1115  * In this formulation, for each polyhedron i,
1116  * the first constraint is the positivity constraint, followed by pairs
1117  * of variables for the equalities, followed by variables for the inequalities.
1118  * We then simply pick a feasible solution and compute s using (*).
1119  *
1120  * Note that we simply pick any valid direction and make no attempt
1121  * to pick a "good" or even the "best" valid direction.
1122  */
1123 static struct isl_vec *valid_direction(
1124         struct isl_basic_set *bset1, struct isl_basic_set *bset2)
1125 {
1126         struct isl_basic_set *lp;
1127         struct isl_tab *tab;
1128         struct isl_vec *sample = NULL;
1129         struct isl_vec *dir;
1130         unsigned d;
1131         int i;
1132         int n;
1133
1134         if (!bset1 || !bset2)
1135                 goto error;
1136         lp = valid_direction_lp(isl_basic_set_copy(bset1),
1137                                 isl_basic_set_copy(bset2));
1138         tab = isl_tab_from_basic_set(lp);
1139         sample = isl_tab_get_sample_value(tab);
1140         isl_tab_free(tab);
1141         isl_basic_set_free(lp);
1142         if (!sample)
1143                 goto error;
1144         d = isl_basic_set_total_dim(bset1);
1145         dir = isl_vec_alloc(bset1->ctx, 1 + d);
1146         if (!dir)
1147                 goto error;
1148         isl_seq_clr(dir->block.data + 1, dir->size - 1);
1149         n = 1;
1150         /* positivity constraint 1 >= 0 */
1151         isl_int_set(dir->block.data[0], sample->block.data[n++]);
1152         for (i = 0; i < bset1->n_eq; ++i) {
1153                 isl_int_sub(sample->block.data[n],
1154                             sample->block.data[n], sample->block.data[n+1]);
1155                 isl_seq_combine(dir->block.data,
1156                                 bset1->ctx->one, dir->block.data,
1157                                 sample->block.data[n], bset1->eq[i], 1 + d);
1158
1159                 n += 2;
1160         }
1161         for (i = 0; i < bset1->n_ineq; ++i)
1162                 isl_seq_combine(dir->block.data,
1163                                 bset1->ctx->one, dir->block.data,
1164                                 sample->block.data[n++], bset1->ineq[i], 1 + d);
1165         isl_vec_free(sample);
1166         isl_seq_normalize(bset1->ctx, dir->el, dir->size);
1167         isl_basic_set_free(bset1);
1168         isl_basic_set_free(bset2);
1169         return dir;
1170 error:
1171         isl_vec_free(sample);
1172         isl_basic_set_free(bset1);
1173         isl_basic_set_free(bset2);
1174         return NULL;
1175 }
1176
1177 /* Given a polyhedron b_i + A_i x >= 0 and a map T = S^{-1},
1178  * compute b_i' + A_i' x' >= 0, with
1179  *
1180  *      [ b_i A_i ]        [ y' ]                             [ y' ]
1181  *      [  1   0  ] S^{-1} [ x' ] >= 0  or      [ b_i' A_i' ] [ x' ] >= 0
1182  *
1183  * In particular, add the "positivity constraint" and then perform
1184  * the mapping.
1185  */
1186 static struct isl_basic_set *homogeneous_map(struct isl_basic_set *bset,
1187         struct isl_mat *T)
1188 {
1189         int k;
1190
1191         if (!bset)
1192                 goto error;
1193         bset = isl_basic_set_extend_constraints(bset, 0, 1);
1194         k = isl_basic_set_alloc_inequality(bset);
1195         if (k < 0)
1196                 goto error;
1197         isl_seq_clr(bset->ineq[k] + 1, isl_basic_set_total_dim(bset));
1198         isl_int_set_si(bset->ineq[k][0], 1);
1199         bset = isl_basic_set_preimage(bset, T);
1200         return bset;
1201 error:
1202         isl_mat_free(T);
1203         isl_basic_set_free(bset);
1204         return NULL;
1205 }
1206
1207 /* Compute the convex hull of a pair of basic sets without any parameters or
1208  * integer divisions, where the convex hull is known to be pointed,
1209  * but the basic sets may be unbounded.
1210  *
1211  * We turn this problem into the computation of a convex hull of a pair
1212  * _bounded_ polyhedra by "changing the direction of the homogeneous
1213  * dimension".  This idea is due to Matthias Koeppe.
1214  *
1215  * Consider the cones in homogeneous space that correspond to the
1216  * input polyhedra.  The rays of these cones are also rays of the
1217  * polyhedra if the coordinate that corresponds to the homogeneous
1218  * dimension is zero.  That is, if the inner product of the rays
1219  * with the homogeneous direction is zero.
1220  * The cones in the homogeneous space can also be considered to
1221  * correspond to other pairs of polyhedra by chosing a different
1222  * homogeneous direction.  To ensure that both of these polyhedra
1223  * are bounded, we need to make sure that all rays of the cones
1224  * correspond to vertices and not to rays.
1225  * Let s be a direction such that <s, r> > 0 for all rays r of both cones.
1226  * Then using s as a homogeneous direction, we obtain a pair of polytopes.
1227  * The vector s is computed in valid_direction.
1228  *
1229  * Note that we need to consider _all_ rays of the cones and not just
1230  * the rays that correspond to rays in the polyhedra.  If we were to
1231  * only consider those rays and turn them into vertices, then we
1232  * may inadvertently turn some vertices into rays.
1233  *
1234  * The standard homogeneous direction is the unit vector in the 0th coordinate.
1235  * We therefore transform the two polyhedra such that the selected
1236  * direction is mapped onto this standard direction and then proceed
1237  * with the normal computation.
1238  * Let S be a non-singular square matrix with s as its first row,
1239  * then we want to map the polyhedra to the space
1240  *
1241  *      [ y' ]     [ y ]                [ y ]          [ y' ]
1242  *      [ x' ] = S [ x ]        i.e.,   [ x ] = S^{-1} [ x' ]
1243  *
1244  * We take S to be the unimodular completion of s to limit the growth
1245  * of the coefficients in the following computations.
1246  *
1247  * Let b_i + A_i x >= 0 be the constraints of polyhedron i.
1248  * We first move to the homogeneous dimension
1249  *
1250  *      b_i y + A_i x >= 0              [ b_i A_i ] [ y ]    [ 0 ]
1251  *          y         >= 0      or      [  1   0  ] [ x ] >= [ 0 ]
1252  *
1253  * Then we change directoin
1254  *
1255  *      [ b_i A_i ]        [ y' ]                             [ y' ]
1256  *      [  1   0  ] S^{-1} [ x' ] >= 0  or      [ b_i' A_i' ] [ x' ] >= 0
1257  *
1258  * Then we compute the convex hull of the polytopes b_i' + A_i' x' >= 0
1259  * resulting in b' + A' x' >= 0, which we then convert back
1260  *
1261  *                  [ y ]                       [ y ]
1262  *      [ b' A' ] S [ x ] >= 0  or      [ b A ] [ x ] >= 0
1263  *
1264  * The polyhedron b + A x >= 0 is then the convex hull of the input polyhedra.
1265  */
1266 static struct isl_basic_set *convex_hull_pair_pointed(
1267         struct isl_basic_set *bset1, struct isl_basic_set *bset2)
1268 {
1269         struct isl_ctx *ctx = NULL;
1270         struct isl_vec *dir = NULL;
1271         struct isl_mat *T = NULL;
1272         struct isl_mat *T2 = NULL;
1273         struct isl_basic_set *hull;
1274         struct isl_set *set;
1275
1276         if (!bset1 || !bset2)
1277                 goto error;
1278         ctx = bset1->ctx;
1279         dir = valid_direction(isl_basic_set_copy(bset1),
1280                                 isl_basic_set_copy(bset2));
1281         if (!dir)
1282                 goto error;
1283         T = isl_mat_alloc(bset1->ctx, dir->size, dir->size);
1284         if (!T)
1285                 goto error;
1286         isl_seq_cpy(T->row[0], dir->block.data, dir->size);
1287         T = isl_mat_unimodular_complete(T, 1);
1288         T2 = isl_mat_right_inverse(isl_mat_copy(T));
1289
1290         bset1 = homogeneous_map(bset1, isl_mat_copy(T2));
1291         bset2 = homogeneous_map(bset2, T2);
1292         set = isl_set_alloc_dim(isl_basic_set_get_dim(bset1), 2, 0);
1293         set = isl_set_add_basic_set(set, bset1);
1294         set = isl_set_add_basic_set(set, bset2);
1295         hull = uset_convex_hull(set);
1296         hull = isl_basic_set_preimage(hull, T);
1297          
1298         isl_vec_free(dir);
1299
1300         return hull;
1301 error:
1302         isl_vec_free(dir);
1303         isl_basic_set_free(bset1);
1304         isl_basic_set_free(bset2);
1305         return NULL;
1306 }
1307
1308 static struct isl_basic_set *uset_convex_hull_wrap(struct isl_set *set);
1309 static struct isl_basic_set *modulo_affine_hull(
1310         struct isl_set *set, struct isl_basic_set *affine_hull);
1311
1312 /* Compute the convex hull of a pair of basic sets without any parameters or
1313  * integer divisions.
1314  *
1315  * This function is called from uset_convex_hull_unbounded, which
1316  * means that the complete convex hull is unbounded.  Some pairs
1317  * of basic sets may still be bounded, though.
1318  * They may even lie inside a lower dimensional space, in which
1319  * case they need to be handled inside their affine hull since
1320  * the main algorithm assumes that the result is full-dimensional.
1321  *
1322  * If the convex hull of the two basic sets would have a non-trivial
1323  * lineality space, we first project out this lineality space.
1324  */
1325 static struct isl_basic_set *convex_hull_pair(struct isl_basic_set *bset1,
1326         struct isl_basic_set *bset2)
1327 {
1328         isl_basic_set *lin, *aff;
1329         int bounded1, bounded2;
1330
1331         aff = isl_set_affine_hull(isl_basic_set_union(isl_basic_set_copy(bset1),
1332                                                     isl_basic_set_copy(bset2)));
1333         if (!aff)
1334                 goto error;
1335         if (aff->n_eq != 0) 
1336                 return modulo_affine_hull(isl_basic_set_union(bset1, bset2), aff);
1337         isl_basic_set_free(aff);
1338
1339         bounded1 = isl_basic_set_is_bounded(bset1);
1340         bounded2 = isl_basic_set_is_bounded(bset2);
1341
1342         if (bounded1 < 0 || bounded2 < 0)
1343                 goto error;
1344
1345         if (bounded1 && bounded2)
1346                 uset_convex_hull_wrap(isl_basic_set_union(bset1, bset2));
1347
1348         if (bounded1 || bounded2)
1349                 return convex_hull_pair_pointed(bset1, bset2);
1350
1351         lin = induced_lineality_space(isl_basic_set_copy(bset1),
1352                                       isl_basic_set_copy(bset2));
1353         if (!lin)
1354                 goto error;
1355         if (isl_basic_set_is_universe(lin)) {
1356                 isl_basic_set_free(bset1);
1357                 isl_basic_set_free(bset2);
1358                 return lin;
1359         }
1360         if (lin->n_eq < isl_basic_set_total_dim(lin)) {
1361                 struct isl_set *set;
1362                 set = isl_set_alloc_dim(isl_basic_set_get_dim(bset1), 2, 0);
1363                 set = isl_set_add_basic_set(set, bset1);
1364                 set = isl_set_add_basic_set(set, bset2);
1365                 return modulo_lineality(set, lin);
1366         }
1367         isl_basic_set_free(lin);
1368
1369         return convex_hull_pair_pointed(bset1, bset2);
1370 error:
1371         isl_basic_set_free(bset1);
1372         isl_basic_set_free(bset2);
1373         return NULL;
1374 }
1375
1376 /* Compute the lineality space of a basic set.
1377  * We currently do not allow the basic set to have any divs.
1378  * We basically just drop the constants and turn every inequality
1379  * into an equality.
1380  */
1381 struct isl_basic_set *isl_basic_set_lineality_space(struct isl_basic_set *bset)
1382 {
1383         int i, k;
1384         struct isl_basic_set *lin = NULL;
1385         unsigned dim;
1386
1387         if (!bset)
1388                 goto error;
1389         isl_assert(bset->ctx, bset->n_div == 0, goto error);
1390         dim = isl_basic_set_total_dim(bset);
1391
1392         lin = isl_basic_set_alloc_dim(isl_basic_set_get_dim(bset), 0, dim, 0);
1393         if (!lin)
1394                 goto error;
1395         for (i = 0; i < bset->n_eq; ++i) {
1396                 k = isl_basic_set_alloc_equality(lin);
1397                 if (k < 0)
1398                         goto error;
1399                 isl_int_set_si(lin->eq[k][0], 0);
1400                 isl_seq_cpy(lin->eq[k] + 1, bset->eq[i] + 1, dim);
1401         }
1402         lin = isl_basic_set_gauss(lin, NULL);
1403         if (!lin)
1404                 goto error;
1405         for (i = 0; i < bset->n_ineq && lin->n_eq < dim; ++i) {
1406                 k = isl_basic_set_alloc_equality(lin);
1407                 if (k < 0)
1408                         goto error;
1409                 isl_int_set_si(lin->eq[k][0], 0);
1410                 isl_seq_cpy(lin->eq[k] + 1, bset->ineq[i] + 1, dim);
1411                 lin = isl_basic_set_gauss(lin, NULL);
1412                 if (!lin)
1413                         goto error;
1414         }
1415         isl_basic_set_free(bset);
1416         return lin;
1417 error:
1418         isl_basic_set_free(lin);
1419         isl_basic_set_free(bset);
1420         return NULL;
1421 }
1422
1423 /* Compute the (linear) hull of the lineality spaces of the basic sets in the
1424  * "underlying" set "set".
1425  */
1426 static struct isl_basic_set *uset_combined_lineality_space(struct isl_set *set)
1427 {
1428         int i;
1429         struct isl_set *lin = NULL;
1430
1431         if (!set)
1432                 return NULL;
1433         if (set->n == 0) {
1434                 struct isl_dim *dim = isl_set_get_dim(set);
1435                 isl_set_free(set);
1436                 return isl_basic_set_empty(dim);
1437         }
1438
1439         lin = isl_set_alloc_dim(isl_set_get_dim(set), set->n, 0);
1440         for (i = 0; i < set->n; ++i)
1441                 lin = isl_set_add_basic_set(lin,
1442                     isl_basic_set_lineality_space(isl_basic_set_copy(set->p[i])));
1443         isl_set_free(set);
1444         return isl_set_affine_hull(lin);
1445 }
1446
1447 /* Compute the convex hull of a set without any parameters or
1448  * integer divisions.
1449  * In each step, we combined two basic sets until only one
1450  * basic set is left.
1451  * The input basic sets are assumed not to have a non-trivial
1452  * lineality space.  If any of the intermediate results has
1453  * a non-trivial lineality space, it is projected out.
1454  */
1455 static struct isl_basic_set *uset_convex_hull_unbounded(struct isl_set *set)
1456 {
1457         struct isl_basic_set *convex_hull = NULL;
1458
1459         convex_hull = isl_set_copy_basic_set(set);
1460         set = isl_set_drop_basic_set(set, convex_hull);
1461         if (!set)
1462                 goto error;
1463         while (set->n > 0) {
1464                 struct isl_basic_set *t;
1465                 t = isl_set_copy_basic_set(set);
1466                 if (!t)
1467                         goto error;
1468                 set = isl_set_drop_basic_set(set, t);
1469                 if (!set)
1470                         goto error;
1471                 convex_hull = convex_hull_pair(convex_hull, t);
1472                 if (set->n == 0)
1473                         break;
1474                 t = isl_basic_set_lineality_space(isl_basic_set_copy(convex_hull));
1475                 if (!t)
1476                         goto error;
1477                 if (isl_basic_set_is_universe(t)) {
1478                         isl_basic_set_free(convex_hull);
1479                         convex_hull = t;
1480                         break;
1481                 }
1482                 if (t->n_eq < isl_basic_set_total_dim(t)) {
1483                         set = isl_set_add_basic_set(set, convex_hull);
1484                         return modulo_lineality(set, t);
1485                 }
1486                 isl_basic_set_free(t);
1487         }
1488         isl_set_free(set);
1489         return convex_hull;
1490 error:
1491         isl_set_free(set);
1492         isl_basic_set_free(convex_hull);
1493         return NULL;
1494 }
1495
1496 /* Compute an initial hull for wrapping containing a single initial
1497  * facet.
1498  * This function assumes that the given set is bounded.
1499  */
1500 static struct isl_basic_set *initial_hull(struct isl_basic_set *hull,
1501         struct isl_set *set)
1502 {
1503         struct isl_mat *bounds = NULL;
1504         unsigned dim;
1505         int k;
1506
1507         if (!hull)
1508                 goto error;
1509         bounds = initial_facet_constraint(set);
1510         if (!bounds)
1511                 goto error;
1512         k = isl_basic_set_alloc_inequality(hull);
1513         if (k < 0)
1514                 goto error;
1515         dim = isl_set_n_dim(set);
1516         isl_assert(set->ctx, 1 + dim == bounds->n_col, goto error);
1517         isl_seq_cpy(hull->ineq[k], bounds->row[0], bounds->n_col);
1518         isl_mat_free(bounds);
1519
1520         return hull;
1521 error:
1522         isl_basic_set_free(hull);
1523         isl_mat_free(bounds);
1524         return NULL;
1525 }
1526
1527 struct max_constraint {
1528         struct isl_mat *c;
1529         int             count;
1530         int             ineq;
1531 };
1532
1533 static int max_constraint_equal(const void *entry, const void *val)
1534 {
1535         struct max_constraint *a = (struct max_constraint *)entry;
1536         isl_int *b = (isl_int *)val;
1537
1538         return isl_seq_eq(a->c->row[0] + 1, b, a->c->n_col - 1);
1539 }
1540
1541 static void update_constraint(struct isl_ctx *ctx, struct isl_hash_table *table,
1542         isl_int *con, unsigned len, int n, int ineq)
1543 {
1544         struct isl_hash_table_entry *entry;
1545         struct max_constraint *c;
1546         uint32_t c_hash;
1547
1548         c_hash = isl_seq_get_hash(con + 1, len);
1549         entry = isl_hash_table_find(ctx, table, c_hash, max_constraint_equal,
1550                         con + 1, 0);
1551         if (!entry)
1552                 return;
1553         c = entry->data;
1554         if (c->count < n) {
1555                 isl_hash_table_remove(ctx, table, entry);
1556                 return;
1557         }
1558         c->count++;
1559         if (isl_int_gt(c->c->row[0][0], con[0]))
1560                 return;
1561         if (isl_int_eq(c->c->row[0][0], con[0])) {
1562                 if (ineq)
1563                         c->ineq = ineq;
1564                 return;
1565         }
1566         c->c = isl_mat_cow(c->c);
1567         isl_int_set(c->c->row[0][0], con[0]);
1568         c->ineq = ineq;
1569 }
1570
1571 /* Check whether the constraint hash table "table" constains the constraint
1572  * "con".
1573  */
1574 static int has_constraint(struct isl_ctx *ctx, struct isl_hash_table *table,
1575         isl_int *con, unsigned len, int n)
1576 {
1577         struct isl_hash_table_entry *entry;
1578         struct max_constraint *c;
1579         uint32_t c_hash;
1580
1581         c_hash = isl_seq_get_hash(con + 1, len);
1582         entry = isl_hash_table_find(ctx, table, c_hash, max_constraint_equal,
1583                         con + 1, 0);
1584         if (!entry)
1585                 return 0;
1586         c = entry->data;
1587         if (c->count < n)
1588                 return 0;
1589         return isl_int_eq(c->c->row[0][0], con[0]);
1590 }
1591
1592 /* Check for inequality constraints of a basic set without equalities
1593  * such that the same or more stringent copies of the constraint appear
1594  * in all of the basic sets.  Such constraints are necessarily facet
1595  * constraints of the convex hull.
1596  *
1597  * If the resulting basic set is by chance identical to one of
1598  * the basic sets in "set", then we know that this basic set contains
1599  * all other basic sets and is therefore the convex hull of set.
1600  * In this case we set *is_hull to 1.
1601  */
1602 static struct isl_basic_set *common_constraints(struct isl_basic_set *hull,
1603         struct isl_set *set, int *is_hull)
1604 {
1605         int i, j, s, n;
1606         int min_constraints;
1607         int best;
1608         struct max_constraint *constraints = NULL;
1609         struct isl_hash_table *table = NULL;
1610         unsigned total;
1611
1612         *is_hull = 0;
1613
1614         for (i = 0; i < set->n; ++i)
1615                 if (set->p[i]->n_eq == 0)
1616                         break;
1617         if (i >= set->n)
1618                 return hull;
1619         min_constraints = set->p[i]->n_ineq;
1620         best = i;
1621         for (i = best + 1; i < set->n; ++i) {
1622                 if (set->p[i]->n_eq != 0)
1623                         continue;
1624                 if (set->p[i]->n_ineq >= min_constraints)
1625                         continue;
1626                 min_constraints = set->p[i]->n_ineq;
1627                 best = i;
1628         }
1629         constraints = isl_calloc_array(hull->ctx, struct max_constraint,
1630                                         min_constraints);
1631         if (!constraints)
1632                 return hull;
1633         table = isl_alloc_type(hull->ctx, struct isl_hash_table);
1634         if (isl_hash_table_init(hull->ctx, table, min_constraints))
1635                 goto error;
1636
1637         total = isl_dim_total(set->dim);
1638         for (i = 0; i < set->p[best]->n_ineq; ++i) {
1639                 constraints[i].c = isl_mat_sub_alloc(hull->ctx,
1640                         set->p[best]->ineq + i, 0, 1, 0, 1 + total);
1641                 if (!constraints[i].c)
1642                         goto error;
1643                 constraints[i].ineq = 1;
1644         }
1645         for (i = 0; i < min_constraints; ++i) {
1646                 struct isl_hash_table_entry *entry;
1647                 uint32_t c_hash;
1648                 c_hash = isl_seq_get_hash(constraints[i].c->row[0] + 1, total);
1649                 entry = isl_hash_table_find(hull->ctx, table, c_hash,
1650                         max_constraint_equal, constraints[i].c->row[0] + 1, 1);
1651                 if (!entry)
1652                         goto error;
1653                 isl_assert(hull->ctx, !entry->data, goto error);
1654                 entry->data = &constraints[i];
1655         }
1656
1657         n = 0;
1658         for (s = 0; s < set->n; ++s) {
1659                 if (s == best)
1660                         continue;
1661
1662                 for (i = 0; i < set->p[s]->n_eq; ++i) {
1663                         isl_int *eq = set->p[s]->eq[i];
1664                         for (j = 0; j < 2; ++j) {
1665                                 isl_seq_neg(eq, eq, 1 + total);
1666                                 update_constraint(hull->ctx, table,
1667                                                             eq, total, n, 0);
1668                         }
1669                 }
1670                 for (i = 0; i < set->p[s]->n_ineq; ++i) {
1671                         isl_int *ineq = set->p[s]->ineq[i];
1672                         update_constraint(hull->ctx, table, ineq, total, n,
1673                                 set->p[s]->n_eq == 0);
1674                 }
1675                 ++n;
1676         }
1677
1678         for (i = 0; i < min_constraints; ++i) {
1679                 if (constraints[i].count < n)
1680                         continue;
1681                 if (!constraints[i].ineq)
1682                         continue;
1683                 j = isl_basic_set_alloc_inequality(hull);
1684                 if (j < 0)
1685                         goto error;
1686                 isl_seq_cpy(hull->ineq[j], constraints[i].c->row[0], 1 + total);
1687         }
1688
1689         for (s = 0; s < set->n; ++s) {
1690                 if (set->p[s]->n_eq)
1691                         continue;
1692                 if (set->p[s]->n_ineq != hull->n_ineq)
1693                         continue;
1694                 for (i = 0; i < set->p[s]->n_ineq; ++i) {
1695                         isl_int *ineq = set->p[s]->ineq[i];
1696                         if (!has_constraint(hull->ctx, table, ineq, total, n))
1697                                 break;
1698                 }
1699                 if (i == set->p[s]->n_ineq)
1700                         *is_hull = 1;
1701         }
1702
1703         isl_hash_table_clear(table);
1704         for (i = 0; i < min_constraints; ++i)
1705                 isl_mat_free(constraints[i].c);
1706         free(constraints);
1707         free(table);
1708         return hull;
1709 error:
1710         isl_hash_table_clear(table);
1711         free(table);
1712         if (constraints)
1713                 for (i = 0; i < min_constraints; ++i)
1714                         isl_mat_free(constraints[i].c);
1715         free(constraints);
1716         return hull;
1717 }
1718
1719 /* Create a template for the convex hull of "set" and fill it up
1720  * obvious facet constraints, if any.  If the result happens to
1721  * be the convex hull of "set" then *is_hull is set to 1.
1722  */
1723 static struct isl_basic_set *proto_hull(struct isl_set *set, int *is_hull)
1724 {
1725         struct isl_basic_set *hull;
1726         unsigned n_ineq;
1727         int i;
1728
1729         n_ineq = 1;
1730         for (i = 0; i < set->n; ++i) {
1731                 n_ineq += set->p[i]->n_eq;
1732                 n_ineq += set->p[i]->n_ineq;
1733         }
1734         hull = isl_basic_set_alloc_dim(isl_dim_copy(set->dim), 0, 0, n_ineq);
1735         hull = isl_basic_set_set_rational(hull);
1736         if (!hull)
1737                 return NULL;
1738         return common_constraints(hull, set, is_hull);
1739 }
1740
1741 static struct isl_basic_set *uset_convex_hull_wrap(struct isl_set *set)
1742 {
1743         struct isl_basic_set *hull;
1744         int is_hull;
1745
1746         hull = proto_hull(set, &is_hull);
1747         if (hull && !is_hull) {
1748                 if (hull->n_ineq == 0)
1749                         hull = initial_hull(hull, set);
1750                 hull = extend(hull, set);
1751         }
1752         isl_set_free(set);
1753
1754         return hull;
1755 }
1756
1757 /* Compute the convex hull of a set without any parameters or
1758  * integer divisions.  Depending on whether the set is bounded,
1759  * we pass control to the wrapping based convex hull or
1760  * the Fourier-Motzkin elimination based convex hull.
1761  * We also handle a few special cases before checking the boundedness.
1762  */
1763 static struct isl_basic_set *uset_convex_hull(struct isl_set *set)
1764 {
1765         struct isl_basic_set *convex_hull = NULL;
1766         struct isl_basic_set *lin;
1767
1768         if (isl_set_n_dim(set) == 0)
1769                 return convex_hull_0d(set);
1770
1771         set = isl_set_coalesce(set);
1772         set = isl_set_set_rational(set);
1773
1774         if (!set)
1775                 goto error;
1776         if (!set)
1777                 return NULL;
1778         if (set->n == 1) {
1779                 convex_hull = isl_basic_set_copy(set->p[0]);
1780                 isl_set_free(set);
1781                 return convex_hull;
1782         }
1783         if (isl_set_n_dim(set) == 1)
1784                 return convex_hull_1d(set);
1785
1786         if (isl_set_is_bounded(set))
1787                 return uset_convex_hull_wrap(set);
1788
1789         lin = uset_combined_lineality_space(isl_set_copy(set));
1790         if (!lin)
1791                 goto error;
1792         if (isl_basic_set_is_universe(lin)) {
1793                 isl_set_free(set);
1794                 return lin;
1795         }
1796         if (lin->n_eq < isl_basic_set_total_dim(lin))
1797                 return modulo_lineality(set, lin);
1798         isl_basic_set_free(lin);
1799
1800         return uset_convex_hull_unbounded(set);
1801 error:
1802         isl_set_free(set);
1803         isl_basic_set_free(convex_hull);
1804         return NULL;
1805 }
1806
1807 /* This is the core procedure, where "set" is a "pure" set, i.e.,
1808  * without parameters or divs and where the convex hull of set is
1809  * known to be full-dimensional.
1810  */
1811 static struct isl_basic_set *uset_convex_hull_wrap_bounded(struct isl_set *set)
1812 {
1813         struct isl_basic_set *convex_hull = NULL;
1814
1815         if (!set)
1816                 goto error;
1817
1818         if (isl_set_n_dim(set) == 0) {
1819                 convex_hull = isl_basic_set_universe(isl_dim_copy(set->dim));
1820                 isl_set_free(set);
1821                 convex_hull = isl_basic_set_set_rational(convex_hull);
1822                 return convex_hull;
1823         }
1824
1825         set = isl_set_set_rational(set);
1826         set = isl_set_coalesce(set);
1827         if (!set)
1828                 goto error;
1829         if (set->n == 1) {
1830                 convex_hull = isl_basic_set_copy(set->p[0]);
1831                 isl_set_free(set);
1832                 return convex_hull;
1833         }
1834         if (isl_set_n_dim(set) == 1)
1835                 return convex_hull_1d(set);
1836
1837         return uset_convex_hull_wrap(set);
1838 error:
1839         isl_set_free(set);
1840         return NULL;
1841 }
1842
1843 /* Compute the convex hull of set "set" with affine hull "affine_hull",
1844  * We first remove the equalities (transforming the set), compute the
1845  * convex hull of the transformed set and then add the equalities back
1846  * (after performing the inverse transformation.
1847  */
1848 static struct isl_basic_set *modulo_affine_hull(
1849         struct isl_set *set, struct isl_basic_set *affine_hull)
1850 {
1851         struct isl_mat *T;
1852         struct isl_mat *T2;
1853         struct isl_basic_set *dummy;
1854         struct isl_basic_set *convex_hull;
1855
1856         dummy = isl_basic_set_remove_equalities(
1857                         isl_basic_set_copy(affine_hull), &T, &T2);
1858         if (!dummy)
1859                 goto error;
1860         isl_basic_set_free(dummy);
1861         set = isl_set_preimage(set, T);
1862         convex_hull = uset_convex_hull(set);
1863         convex_hull = isl_basic_set_preimage(convex_hull, T2);
1864         convex_hull = isl_basic_set_intersect(convex_hull, affine_hull);
1865         return convex_hull;
1866 error:
1867         isl_basic_set_free(affine_hull);
1868         isl_set_free(set);
1869         return NULL;
1870 }
1871
1872 /* Compute the convex hull of a map.
1873  *
1874  * The implementation was inspired by "Extended Convex Hull" by Fukuda et al.,
1875  * specifically, the wrapping of facets to obtain new facets.
1876  */
1877 struct isl_basic_map *isl_map_convex_hull(struct isl_map *map)
1878 {
1879         struct isl_basic_set *bset;
1880         struct isl_basic_map *model = NULL;
1881         struct isl_basic_set *affine_hull = NULL;
1882         struct isl_basic_map *convex_hull = NULL;
1883         struct isl_set *set = NULL;
1884         struct isl_ctx *ctx;
1885
1886         if (!map)
1887                 goto error;
1888
1889         ctx = map->ctx;
1890         if (map->n == 0) {
1891                 convex_hull = isl_basic_map_empty_like_map(map);
1892                 isl_map_free(map);
1893                 return convex_hull;
1894         }
1895
1896         map = isl_map_detect_equalities(map);
1897         map = isl_map_align_divs(map);
1898         if (!map)
1899                 goto error;
1900         model = isl_basic_map_copy(map->p[0]);
1901         set = isl_map_underlying_set(map);
1902         if (!set)
1903                 goto error;
1904
1905         affine_hull = isl_set_affine_hull(isl_set_copy(set));
1906         if (!affine_hull)
1907                 goto error;
1908         if (affine_hull->n_eq != 0)
1909                 bset = modulo_affine_hull(set, affine_hull);
1910         else {
1911                 isl_basic_set_free(affine_hull);
1912                 bset = uset_convex_hull(set);
1913         }
1914
1915         convex_hull = isl_basic_map_overlying_set(bset, model);
1916         if (!convex_hull)
1917                 return NULL;
1918
1919         ISL_F_SET(convex_hull, ISL_BASIC_MAP_NO_IMPLICIT);
1920         ISL_F_SET(convex_hull, ISL_BASIC_MAP_ALL_EQUALITIES);
1921         ISL_F_CLR(convex_hull, ISL_BASIC_MAP_RATIONAL);
1922         return convex_hull;
1923 error:
1924         isl_set_free(set);
1925         isl_basic_map_free(model);
1926         return NULL;
1927 }
1928
1929 struct isl_basic_set *isl_set_convex_hull(struct isl_set *set)
1930 {
1931         return (struct isl_basic_set *)
1932                 isl_map_convex_hull((struct isl_map *)set);
1933 }
1934
1935 struct sh_data_entry {
1936         struct isl_hash_table   *table;
1937         struct isl_tab          *tab;
1938 };
1939
1940 /* Holds the data needed during the simple hull computation.
1941  * In particular,
1942  *      n               the number of basic sets in the original set
1943  *      hull_table      a hash table of already computed constraints
1944  *                      in the simple hull
1945  *      p               for each basic set,
1946  *              table           a hash table of the constraints
1947  *              tab             the tableau corresponding to the basic set
1948  */
1949 struct sh_data {
1950         struct isl_ctx          *ctx;
1951         unsigned                n;
1952         struct isl_hash_table   *hull_table;
1953         struct sh_data_entry    p[1];
1954 };
1955
1956 static void sh_data_free(struct sh_data *data)
1957 {
1958         int i;
1959
1960         if (!data)
1961                 return;
1962         isl_hash_table_free(data->ctx, data->hull_table);
1963         for (i = 0; i < data->n; ++i) {
1964                 isl_hash_table_free(data->ctx, data->p[i].table);
1965                 isl_tab_free(data->p[i].tab);
1966         }
1967         free(data);
1968 }
1969
1970 struct ineq_cmp_data {
1971         unsigned        len;
1972         isl_int         *p;
1973 };
1974
1975 static int has_ineq(const void *entry, const void *val)
1976 {
1977         isl_int *row = (isl_int *)entry;
1978         struct ineq_cmp_data *v = (struct ineq_cmp_data *)val;
1979
1980         return isl_seq_eq(row + 1, v->p + 1, v->len) ||
1981                isl_seq_is_neg(row + 1, v->p + 1, v->len);
1982 }
1983
1984 static int hash_ineq(struct isl_ctx *ctx, struct isl_hash_table *table,
1985                         isl_int *ineq, unsigned len)
1986 {
1987         uint32_t c_hash;
1988         struct ineq_cmp_data v;
1989         struct isl_hash_table_entry *entry;
1990
1991         v.len = len;
1992         v.p = ineq;
1993         c_hash = isl_seq_get_hash(ineq + 1, len);
1994         entry = isl_hash_table_find(ctx, table, c_hash, has_ineq, &v, 1);
1995         if (!entry)
1996                 return - 1;
1997         entry->data = ineq;
1998         return 0;
1999 }
2000
2001 /* Fill hash table "table" with the constraints of "bset".
2002  * Equalities are added as two inequalities.
2003  * The value in the hash table is a pointer to the (in)equality of "bset".
2004  */
2005 static int hash_basic_set(struct isl_hash_table *table,
2006                                 struct isl_basic_set *bset)
2007 {
2008         int i, j;
2009         unsigned dim = isl_basic_set_total_dim(bset);
2010
2011         for (i = 0; i < bset->n_eq; ++i) {
2012                 for (j = 0; j < 2; ++j) {
2013                         isl_seq_neg(bset->eq[i], bset->eq[i], 1 + dim);
2014                         if (hash_ineq(bset->ctx, table, bset->eq[i], dim) < 0)
2015                                 return -1;
2016                 }
2017         }
2018         for (i = 0; i < bset->n_ineq; ++i) {
2019                 if (hash_ineq(bset->ctx, table, bset->ineq[i], dim) < 0)
2020                         return -1;
2021         }
2022         return 0;
2023 }
2024
2025 static struct sh_data *sh_data_alloc(struct isl_set *set, unsigned n_ineq)
2026 {
2027         struct sh_data *data;
2028         int i;
2029
2030         data = isl_calloc(set->ctx, struct sh_data,
2031                 sizeof(struct sh_data) +
2032                 (set->n - 1) * sizeof(struct sh_data_entry));
2033         if (!data)
2034                 return NULL;
2035         data->ctx = set->ctx;
2036         data->n = set->n;
2037         data->hull_table = isl_hash_table_alloc(set->ctx, n_ineq);
2038         if (!data->hull_table)
2039                 goto error;
2040         for (i = 0; i < set->n; ++i) {
2041                 data->p[i].table = isl_hash_table_alloc(set->ctx,
2042                                     2 * set->p[i]->n_eq + set->p[i]->n_ineq);
2043                 if (!data->p[i].table)
2044                         goto error;
2045                 if (hash_basic_set(data->p[i].table, set->p[i]) < 0)
2046                         goto error;
2047         }
2048         return data;
2049 error:
2050         sh_data_free(data);
2051         return NULL;
2052 }
2053
2054 /* Check if inequality "ineq" is a bound for basic set "j" or if
2055  * it can be relaxed (by increasing the constant term) to become
2056  * a bound for that basic set.  In the latter case, the constant
2057  * term is updated.
2058  * Return 1 if "ineq" is a bound
2059  *        0 if "ineq" may attain arbitrarily small values on basic set "j"
2060  *       -1 if some error occurred
2061  */
2062 static int is_bound(struct sh_data *data, struct isl_set *set, int j,
2063                         isl_int *ineq)
2064 {
2065         enum isl_lp_result res;
2066         isl_int opt;
2067
2068         if (!data->p[j].tab) {
2069                 data->p[j].tab = isl_tab_from_basic_set(set->p[j]);
2070                 if (!data->p[j].tab)
2071                         return -1;
2072         }
2073
2074         isl_int_init(opt);
2075
2076         res = isl_tab_min(data->p[j].tab, ineq, data->ctx->one,
2077                                 &opt, NULL, 0);
2078         if (res == isl_lp_ok && isl_int_is_neg(opt))
2079                 isl_int_sub(ineq[0], ineq[0], opt);
2080
2081         isl_int_clear(opt);
2082
2083         return (res == isl_lp_ok || res == isl_lp_empty) ? 1 :
2084                res == isl_lp_unbounded ? 0 : -1;
2085 }
2086
2087 /* Check if inequality "ineq" from basic set "i" can be relaxed to
2088  * become a bound on the whole set.  If so, add the (relaxed) inequality
2089  * to "hull".
2090  *
2091  * We first check if "hull" already contains a translate of the inequality.
2092  * If so, we are done.
2093  * Then, we check if any of the previous basic sets contains a translate
2094  * of the inequality.  If so, then we have already considered this
2095  * inequality and we are done.
2096  * Otherwise, for each basic set other than "i", we check if the inequality
2097  * is a bound on the basic set.
2098  * For previous basic sets, we know that they do not contain a translate
2099  * of the inequality, so we directly call is_bound.
2100  * For following basic sets, we first check if a translate of the
2101  * inequality appears in its description and if so directly update
2102  * the inequality accordingly.
2103  */
2104 static struct isl_basic_set *add_bound(struct isl_basic_set *hull,
2105         struct sh_data *data, struct isl_set *set, int i, isl_int *ineq)
2106 {
2107         uint32_t c_hash;
2108         struct ineq_cmp_data v;
2109         struct isl_hash_table_entry *entry;
2110         int j, k;
2111
2112         if (!hull)
2113                 return NULL;
2114
2115         v.len = isl_basic_set_total_dim(hull);
2116         v.p = ineq;
2117         c_hash = isl_seq_get_hash(ineq + 1, v.len);
2118
2119         entry = isl_hash_table_find(hull->ctx, data->hull_table, c_hash,
2120                                         has_ineq, &v, 0);
2121         if (entry)
2122                 return hull;
2123
2124         for (j = 0; j < i; ++j) {
2125                 entry = isl_hash_table_find(hull->ctx, data->p[j].table,
2126                                                 c_hash, has_ineq, &v, 0);
2127                 if (entry)
2128                         break;
2129         }
2130         if (j < i)
2131                 return hull;
2132
2133         k = isl_basic_set_alloc_inequality(hull);
2134         isl_seq_cpy(hull->ineq[k], ineq, 1 + v.len);
2135         if (k < 0)
2136                 goto error;
2137
2138         for (j = 0; j < i; ++j) {
2139                 int bound;
2140                 bound = is_bound(data, set, j, hull->ineq[k]);
2141                 if (bound < 0)
2142                         goto error;
2143                 if (!bound)
2144                         break;
2145         }
2146         if (j < i) {
2147                 isl_basic_set_free_inequality(hull, 1);
2148                 return hull;
2149         }
2150
2151         for (j = i + 1; j < set->n; ++j) {
2152                 int bound, neg;
2153                 isl_int *ineq_j;
2154                 entry = isl_hash_table_find(hull->ctx, data->p[j].table,
2155                                                 c_hash, has_ineq, &v, 0);
2156                 if (entry) {
2157                         ineq_j = entry->data;
2158                         neg = isl_seq_is_neg(ineq_j + 1,
2159                                              hull->ineq[k] + 1, v.len);
2160                         if (neg)
2161                                 isl_int_neg(ineq_j[0], ineq_j[0]);
2162                         if (isl_int_gt(ineq_j[0], hull->ineq[k][0]))
2163                                 isl_int_set(hull->ineq[k][0], ineq_j[0]);
2164                         if (neg)
2165                                 isl_int_neg(ineq_j[0], ineq_j[0]);
2166                         continue;
2167                 }
2168                 bound = is_bound(data, set, j, hull->ineq[k]);
2169                 if (bound < 0)
2170                         goto error;
2171                 if (!bound)
2172                         break;
2173         }
2174         if (j < set->n) {
2175                 isl_basic_set_free_inequality(hull, 1);
2176                 return hull;
2177         }
2178
2179         entry = isl_hash_table_find(hull->ctx, data->hull_table, c_hash,
2180                                         has_ineq, &v, 1);
2181         if (!entry)
2182                 goto error;
2183         entry->data = hull->ineq[k];
2184
2185         return hull;
2186 error:
2187         isl_basic_set_free(hull);
2188         return NULL;
2189 }
2190
2191 /* Check if any inequality from basic set "i" can be relaxed to
2192  * become a bound on the whole set.  If so, add the (relaxed) inequality
2193  * to "hull".
2194  */
2195 static struct isl_basic_set *add_bounds(struct isl_basic_set *bset,
2196         struct sh_data *data, struct isl_set *set, int i)
2197 {
2198         int j, k;
2199         unsigned dim = isl_basic_set_total_dim(bset);
2200
2201         for (j = 0; j < set->p[i]->n_eq; ++j) {
2202                 for (k = 0; k < 2; ++k) {
2203                         isl_seq_neg(set->p[i]->eq[j], set->p[i]->eq[j], 1+dim);
2204                         bset = add_bound(bset, data, set, i, set->p[i]->eq[j]);
2205                 }
2206         }
2207         for (j = 0; j < set->p[i]->n_ineq; ++j)
2208                 bset = add_bound(bset, data, set, i, set->p[i]->ineq[j]);
2209         return bset;
2210 }
2211
2212 /* Compute a superset of the convex hull of set that is described
2213  * by only translates of the constraints in the constituents of set.
2214  */
2215 static struct isl_basic_set *uset_simple_hull(struct isl_set *set)
2216 {
2217         struct sh_data *data = NULL;
2218         struct isl_basic_set *hull = NULL;
2219         unsigned n_ineq;
2220         int i;
2221
2222         if (!set)
2223                 return NULL;
2224
2225         n_ineq = 0;
2226         for (i = 0; i < set->n; ++i) {
2227                 if (!set->p[i])
2228                         goto error;
2229                 n_ineq += 2 * set->p[i]->n_eq + set->p[i]->n_ineq;
2230         }
2231
2232         hull = isl_basic_set_alloc_dim(isl_dim_copy(set->dim), 0, 0, n_ineq);
2233         if (!hull)
2234                 goto error;
2235
2236         data = sh_data_alloc(set, n_ineq);
2237         if (!data)
2238                 goto error;
2239
2240         for (i = 0; i < set->n; ++i)
2241                 hull = add_bounds(hull, data, set, i);
2242
2243         sh_data_free(data);
2244         isl_set_free(set);
2245
2246         return hull;
2247 error:
2248         sh_data_free(data);
2249         isl_basic_set_free(hull);
2250         isl_set_free(set);
2251         return NULL;
2252 }
2253
2254 /* Compute a superset of the convex hull of map that is described
2255  * by only translates of the constraints in the constituents of map.
2256  */
2257 struct isl_basic_map *isl_map_simple_hull(struct isl_map *map)
2258 {
2259         struct isl_set *set = NULL;
2260         struct isl_basic_map *model = NULL;
2261         struct isl_basic_map *hull;
2262         struct isl_basic_map *affine_hull;
2263         struct isl_basic_set *bset = NULL;
2264
2265         if (!map)
2266                 return NULL;
2267         if (map->n == 0) {
2268                 hull = isl_basic_map_empty_like_map(map);
2269                 isl_map_free(map);
2270                 return hull;
2271         }
2272         if (map->n == 1) {
2273                 hull = isl_basic_map_copy(map->p[0]);
2274                 isl_map_free(map);
2275                 return hull;
2276         }
2277
2278         map = isl_map_detect_equalities(map);
2279         affine_hull = isl_map_affine_hull(isl_map_copy(map));
2280         map = isl_map_align_divs(map);
2281         model = isl_basic_map_copy(map->p[0]);
2282
2283         set = isl_map_underlying_set(map);
2284
2285         bset = uset_simple_hull(set);
2286
2287         hull = isl_basic_map_overlying_set(bset, model);
2288
2289         hull = isl_basic_map_intersect(hull, affine_hull);
2290         hull = isl_basic_map_remove_redundancies(hull);
2291         ISL_F_SET(hull, ISL_BASIC_MAP_NO_IMPLICIT);
2292         ISL_F_SET(hull, ISL_BASIC_MAP_ALL_EQUALITIES);
2293
2294         return hull;
2295 }
2296
2297 struct isl_basic_set *isl_set_simple_hull(struct isl_set *set)
2298 {
2299         return (struct isl_basic_set *)
2300                 isl_map_simple_hull((struct isl_map *)set);
2301 }
2302
2303 /* Given a set "set", return parametric bounds on the dimension "dim".
2304  */
2305 static struct isl_basic_set *set_bounds(struct isl_set *set, int dim)
2306 {
2307         unsigned set_dim = isl_set_dim(set, isl_dim_set);
2308         set = isl_set_copy(set);
2309         set = isl_set_eliminate_dims(set, dim + 1, set_dim - (dim + 1));
2310         set = isl_set_eliminate_dims(set, 0, dim);
2311         return isl_set_convex_hull(set);
2312 }
2313
2314 /* Computes a "simple hull" and then check if each dimension in the
2315  * resulting hull is bounded by a symbolic constant.  If not, the
2316  * hull is intersected with the corresponding bounds on the whole set.
2317  */
2318 struct isl_basic_set *isl_set_bounded_simple_hull(struct isl_set *set)
2319 {
2320         int i, j;
2321         struct isl_basic_set *hull;
2322         unsigned nparam, left;
2323         int removed_divs = 0;
2324
2325         hull = isl_set_simple_hull(isl_set_copy(set));
2326         if (!hull)
2327                 goto error;
2328
2329         nparam = isl_basic_set_dim(hull, isl_dim_param);
2330         for (i = 0; i < isl_basic_set_dim(hull, isl_dim_set); ++i) {
2331                 int lower = 0, upper = 0;
2332                 struct isl_basic_set *bounds;
2333
2334                 left = isl_basic_set_total_dim(hull) - nparam - i - 1;
2335                 for (j = 0; j < hull->n_eq; ++j) {
2336                         if (isl_int_is_zero(hull->eq[j][1 + nparam + i]))
2337                                 continue;
2338                         if (isl_seq_first_non_zero(hull->eq[j]+1+nparam+i+1,
2339                                                     left) == -1)
2340                                 break;
2341                 }
2342                 if (j < hull->n_eq)
2343                         continue;
2344
2345                 for (j = 0; j < hull->n_ineq; ++j) {
2346                         if (isl_int_is_zero(hull->ineq[j][1 + nparam + i]))
2347                                 continue;
2348                         if (isl_seq_first_non_zero(hull->ineq[j]+1+nparam+i+1,
2349                                                     left) != -1 ||
2350                             isl_seq_first_non_zero(hull->ineq[j]+1+nparam,
2351                                                     i) != -1)
2352                                 continue;
2353                         if (isl_int_is_pos(hull->ineq[j][1 + nparam + i]))
2354                                 lower = 1;
2355                         else
2356                                 upper = 1;
2357                         if (lower && upper)
2358                                 break;
2359                 }
2360
2361                 if (lower && upper)
2362                         continue;
2363
2364                 if (!removed_divs) {
2365                         set = isl_set_remove_divs(set);
2366                         if (!set)
2367                                 goto error;
2368                         removed_divs = 1;
2369                 }
2370                 bounds = set_bounds(set, i);
2371                 hull = isl_basic_set_intersect(hull, bounds);
2372                 if (!hull)
2373                         goto error;
2374         }
2375
2376         isl_set_free(set);
2377         return hull;
2378 error:
2379         isl_set_free(set);
2380         return NULL;
2381 }