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