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