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