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