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