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