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