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