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