02a6e34b2f494fe4eb867f5491d2b1c7d3e44e4e
[platform/upstream/isl.git] / isl_convex_hull.c
1 #include "isl_lp.h"
2 #include "isl_map.h"
3 #include "isl_map_private.h"
4 #include "isl_mat.h"
5 #include "isl_set.h"
6 #include "isl_seq.h"
7 #include "isl_equalities.h"
8 #include "isl_tab.h"
9
10 static struct isl_basic_set *uset_convex_hull_wrap_bounded(struct isl_set *set);
11
12 static void swap_ineq(struct isl_basic_map *bmap, unsigned i, unsigned j)
13 {
14         isl_int *t;
15
16         if (i != j) {
17                 t = bmap->ineq[i];
18                 bmap->ineq[i] = bmap->ineq[j];
19                 bmap->ineq[j] = t;
20         }
21 }
22
23 /* Return 1 if constraint c is redundant with respect to the constraints
24  * in bmap.  If c is a lower [upper] bound in some variable and bmap
25  * does not have a lower [upper] bound in that variable, then c cannot
26  * be redundant and we do not need solve any lp.
27  */
28 int isl_basic_map_constraint_is_redundant(struct isl_basic_map **bmap,
29         isl_int *c, isl_int *opt_n, isl_int *opt_d)
30 {
31         enum isl_lp_result res;
32         unsigned total;
33         int i, j;
34
35         if (!bmap)
36                 return -1;
37
38         total = isl_basic_map_total_dim(*bmap);
39         for (i = 0; i < total; ++i) {
40                 int sign;
41                 if (isl_int_is_zero(c[1+i]))
42                         continue;
43                 sign = isl_int_sgn(c[1+i]);
44                 for (j = 0; j < (*bmap)->n_ineq; ++j)
45                         if (sign == isl_int_sgn((*bmap)->ineq[j][1+i]))
46                                 break;
47                 if (j == (*bmap)->n_ineq)
48                         break;
49         }
50         if (i < total)
51                 return 0;
52
53         res = isl_solve_lp(*bmap, 0, c, (*bmap)->ctx->one, opt_n, opt_d);
54         if (res == isl_lp_unbounded)
55                 return 0;
56         if (res == isl_lp_error)
57                 return -1;
58         if (res == isl_lp_empty) {
59                 *bmap = isl_basic_map_set_to_empty(*bmap);
60                 return 0;
61         }
62         return !isl_int_is_neg(*opt_n);
63 }
64
65 int isl_basic_set_constraint_is_redundant(struct isl_basic_set **bset,
66         isl_int *c, isl_int *opt_n, isl_int *opt_d)
67 {
68         return isl_basic_map_constraint_is_redundant(
69                         (struct isl_basic_map **)bset, c, opt_n, opt_d);
70 }
71
72 /* Compute the convex hull of a basic map, by removing the redundant
73  * constraints.  If the minimal value along the normal of a constraint
74  * is the same if the constraint is removed, then the constraint is redundant.
75  *
76  * Alternatively, we could have intersected the basic map with the
77  * corresponding equality and the checked if the dimension was that
78  * of a facet.
79  */
80 struct isl_basic_map *isl_basic_map_convex_hull(struct isl_basic_map *bmap)
81 {
82         struct isl_tab *tab;
83
84         if (!bmap)
85                 return NULL;
86
87         bmap = isl_basic_map_gauss(bmap, NULL);
88         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
89                 return bmap;
90         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_NO_REDUNDANT))
91                 return bmap;
92         if (bmap->n_ineq <= 1)
93                 return bmap;
94
95         tab = isl_tab_from_basic_map(bmap);
96         tab = isl_tab_detect_equalities(bmap->ctx, tab);
97         tab = isl_tab_detect_redundant(bmap->ctx, tab);
98         bmap = isl_basic_map_update_from_tab(bmap, tab);
99         isl_tab_free(bmap->ctx, tab);
100         ISL_F_SET(bmap, ISL_BASIC_MAP_NO_IMPLICIT);
101         ISL_F_SET(bmap, ISL_BASIC_MAP_NO_REDUNDANT);
102         return bmap;
103 }
104
105 struct isl_basic_set *isl_basic_set_convex_hull(struct isl_basic_set *bset)
106 {
107         return (struct isl_basic_set *)
108                 isl_basic_map_convex_hull((struct isl_basic_map *)bset);
109 }
110
111 /* Check if the set set is bound in the direction of the affine
112  * constraint c and if so, set the constant term such that the
113  * resulting constraint is a bounding constraint for the set.
114  */
115 static int uset_is_bound(struct isl_ctx *ctx, struct isl_set *set,
116         isl_int *c, unsigned len)
117 {
118         int first;
119         int j;
120         isl_int opt;
121         isl_int opt_denom;
122
123         isl_int_init(opt);
124         isl_int_init(opt_denom);
125         first = 1;
126         for (j = 0; j < set->n; ++j) {
127                 enum isl_lp_result res;
128
129                 if (ISL_F_ISSET(set->p[j], ISL_BASIC_SET_EMPTY))
130                         continue;
131
132                 res = isl_solve_lp((struct isl_basic_map*)set->p[j],
133                                 0, c, ctx->one, &opt, &opt_denom);
134                 if (res == isl_lp_unbounded)
135                         break;
136                 if (res == isl_lp_error)
137                         goto error;
138                 if (res == isl_lp_empty) {
139                         set->p[j] = isl_basic_set_set_to_empty(set->p[j]);
140                         if (!set->p[j])
141                                 goto error;
142                         continue;
143                 }
144                 if (!isl_int_is_one(opt_denom))
145                         isl_seq_scale(c, c, opt_denom, len);
146                 if (first || isl_int_is_neg(opt))
147                         isl_int_sub(c[0], c[0], opt);
148                 first = 0;
149         }
150         isl_int_clear(opt);
151         isl_int_clear(opt_denom);
152         return j >= set->n;
153 error:
154         isl_int_clear(opt);
155         isl_int_clear(opt_denom);
156         return -1;
157 }
158
159 /* Check if "c" is a direction that is independent of the previously found "n"
160  * bounds in "dirs".
161  * If so, add it to the list, with the negative of the lower bound
162  * in the constant position, i.e., such that c corresponds to a bounding
163  * hyperplane (but not necessarily a facet).
164  * Assumes set "set" is bounded.
165  */
166 static int is_independent_bound(struct isl_ctx *ctx,
167         struct isl_set *set, isl_int *c,
168         struct isl_mat *dirs, int n)
169 {
170         int is_bound;
171         int i = 0;
172
173         isl_seq_cpy(dirs->row[n]+1, c+1, dirs->n_col-1);
174         if (n != 0) {
175                 int pos = isl_seq_first_non_zero(dirs->row[n]+1, dirs->n_col-1);
176                 if (pos < 0)
177                         return 0;
178                 for (i = 0; i < n; ++i) {
179                         int pos_i;
180                         pos_i = isl_seq_first_non_zero(dirs->row[i]+1, dirs->n_col-1);
181                         if (pos_i < pos)
182                                 continue;
183                         if (pos_i > pos)
184                                 break;
185                         isl_seq_elim(dirs->row[n]+1, dirs->row[i]+1, pos,
186                                         dirs->n_col-1, NULL);
187                         pos = isl_seq_first_non_zero(dirs->row[n]+1, dirs->n_col-1);
188                         if (pos < 0)
189                                 return 0;
190                 }
191         }
192
193         is_bound = uset_is_bound(ctx, set, dirs->row[n], dirs->n_col);
194         if (is_bound != 1)
195                 return is_bound;
196         if (i < n) {
197                 int k;
198                 isl_int *t = dirs->row[n];
199                 for (k = n; k > i; --k)
200                         dirs->row[k] = dirs->row[k-1];
201                 dirs->row[i] = t;
202         }
203         return 1;
204 }
205
206 /* Compute and return a maximal set of linearly independent bounds
207  * on the set "set", based on the constraints of the basic sets
208  * in "set".
209  */
210 static struct isl_mat *independent_bounds(struct isl_ctx *ctx,
211         struct isl_set *set)
212 {
213         int i, j, n;
214         struct isl_mat *dirs = NULL;
215         unsigned dim = isl_set_n_dim(set);
216
217         dirs = isl_mat_alloc(ctx, dim, 1+dim);
218         if (!dirs)
219                 goto error;
220
221         n = 0;
222         for (i = 0; n < dim && i < set->n; ++i) {
223                 int f;
224                 struct isl_basic_set *bset = set->p[i];
225
226                 for (j = 0; n < dim && j < bset->n_eq; ++j) {
227                         f = is_independent_bound(ctx, set, bset->eq[j],
228                                                 dirs, n);
229                         if (f < 0)
230                                 goto error;
231                         if (f)
232                                 ++n;
233                 }
234                 for (j = 0; n < dim && j < bset->n_ineq; ++j) {
235                         f = is_independent_bound(ctx, set, bset->ineq[j],
236                                                 dirs, n);
237                         if (f < 0)
238                                 goto error;
239                         if (f)
240                                 ++n;
241                 }
242         }
243         dirs->n_row = n;
244         return dirs;
245 error:
246         isl_mat_free(ctx, dirs);
247         return NULL;
248 }
249
250 static struct isl_basic_set *isl_basic_set_set_rational(
251         struct isl_basic_set *bset)
252 {
253         if (!bset)
254                 return NULL;
255
256         if (ISL_F_ISSET(bset, ISL_BASIC_MAP_RATIONAL))
257                 return bset;
258
259         bset = isl_basic_set_cow(bset);
260         if (!bset)
261                 return NULL;
262
263         ISL_F_SET(bset, ISL_BASIC_MAP_RATIONAL);
264
265         return isl_basic_set_finalize(bset);
266 }
267
268 static struct isl_set *isl_set_set_rational(struct isl_set *set)
269 {
270         int i;
271
272         set = isl_set_cow(set);
273         if (!set)
274                 return NULL;
275         for (i = 0; i < set->n; ++i) {
276                 set->p[i] = isl_basic_set_set_rational(set->p[i]);
277                 if (!set->p[i])
278                         goto error;
279         }
280         return set;
281 error:
282         isl_set_free(set);
283         return NULL;
284 }
285
286 static struct isl_basic_set *isl_basic_set_add_equality(struct isl_ctx *ctx,
287         struct isl_basic_set *bset, isl_int *c)
288 {
289         int i;
290         unsigned total;
291         unsigned dim;
292
293         if (ISL_F_ISSET(bset, ISL_BASIC_SET_EMPTY))
294                 return bset;
295
296         isl_assert(ctx, isl_basic_set_n_param(bset) == 0, goto error);
297         isl_assert(ctx, bset->n_div == 0, goto error);
298         dim = isl_basic_set_n_dim(bset);
299         bset = isl_basic_set_extend(bset, 0, dim, 0, 1, 0);
300         i = isl_basic_set_alloc_equality(bset);
301         if (i < 0)
302                 goto error;
303         isl_seq_cpy(bset->eq[i], c, 1 + dim);
304         return bset;
305 error:
306         isl_basic_set_free(bset);
307         return NULL;
308 }
309
310 static struct isl_set *isl_set_add_equality(struct isl_ctx *ctx,
311         struct isl_set *set, isl_int *c)
312 {
313         int i;
314
315         set = isl_set_cow(set);
316         if (!set)
317                 return NULL;
318         for (i = 0; i < set->n; ++i) {
319                 set->p[i] = isl_basic_set_add_equality(ctx, set->p[i], c);
320                 if (!set->p[i])
321                         goto error;
322         }
323         return set;
324 error:
325         isl_set_free(set);
326         return NULL;
327 }
328
329 /* Given a union of basic sets, construct the constraints for wrapping
330  * a facet around one of its ridges.
331  * In particular, if each of n the d-dimensional basic sets i in "set"
332  * contains the origin, satisfies the constraints x_1 >= 0 and x_2 >= 0
333  * and is defined by the constraints
334  *                                  [ 1 ]
335  *                              A_i [ x ]  >= 0
336  *
337  * then the resulting set is of dimension n*(1+d) and has as contraints
338  *
339  *                                  [ a_i ]
340  *                              A_i [ x_i ] >= 0
341  *
342  *                                    a_i   >= 0
343  *
344  *                      \sum_i x_{i,1} = 1
345  */
346 static struct isl_basic_set *wrap_constraints(struct isl_set *set)
347 {
348         struct isl_basic_set *lp;
349         unsigned n_eq;
350         unsigned n_ineq;
351         int i, j, k;
352         unsigned dim, lp_dim;
353
354         if (!set)
355                 return NULL;
356
357         dim = 1 + isl_set_n_dim(set);
358         n_eq = 1;
359         n_ineq = set->n;
360         for (i = 0; i < set->n; ++i) {
361                 n_eq += set->p[i]->n_eq;
362                 n_ineq += set->p[i]->n_ineq;
363         }
364         lp = isl_basic_set_alloc(set->ctx, 0, dim * set->n, 0, n_eq, n_ineq);
365         if (!lp)
366                 return NULL;
367         lp_dim = isl_basic_set_n_dim(lp);
368         k = isl_basic_set_alloc_equality(lp);
369         isl_int_set_si(lp->eq[k][0], -1);
370         for (i = 0; i < set->n; ++i) {
371                 isl_int_set_si(lp->eq[k][1+dim*i], 0);
372                 isl_int_set_si(lp->eq[k][1+dim*i+1], 1);
373                 isl_seq_clr(lp->eq[k]+1+dim*i+2, dim-2);
374         }
375         for (i = 0; i < set->n; ++i) {
376                 k = isl_basic_set_alloc_inequality(lp);
377                 isl_seq_clr(lp->ineq[k], 1+lp_dim);
378                 isl_int_set_si(lp->ineq[k][1+dim*i], 1);
379
380                 for (j = 0; j < set->p[i]->n_eq; ++j) {
381                         k = isl_basic_set_alloc_equality(lp);
382                         isl_seq_clr(lp->eq[k], 1+dim*i);
383                         isl_seq_cpy(lp->eq[k]+1+dim*i, set->p[i]->eq[j], dim);
384                         isl_seq_clr(lp->eq[k]+1+dim*(i+1), dim*(set->n-i-1));
385                 }
386
387                 for (j = 0; j < set->p[i]->n_ineq; ++j) {
388                         k = isl_basic_set_alloc_inequality(lp);
389                         isl_seq_clr(lp->ineq[k], 1+dim*i);
390                         isl_seq_cpy(lp->ineq[k]+1+dim*i, set->p[i]->ineq[j], dim);
391                         isl_seq_clr(lp->ineq[k]+1+dim*(i+1), dim*(set->n-i-1));
392                 }
393         }
394         return lp;
395 }
396
397 /* Given a facet "facet" of the convex hull of "set" and a facet "ridge"
398  * of that facet, compute the other facet of the convex hull that contains
399  * the ridge.
400  *
401  * We first transform the set such that the facet constraint becomes
402  *
403  *                      x_1 >= 0
404  *
405  * I.e., the facet lies in
406  *
407  *                      x_1 = 0
408  *
409  * and on that facet, the constraint that defines the ridge is
410  *
411  *                      x_2 >= 0
412  *
413  * (This transformation is not strictly needed, all that is needed is
414  * that the ridge contains the origin.)
415  *
416  * Since the ridge contains the origin, the cone of the convex hull
417  * will be of the form
418  *
419  *                      x_1 >= 0
420  *                      x_2 >= a x_1
421  *
422  * with this second constraint defining the new facet.
423  * The constant a is obtained by settting x_1 in the cone of the
424  * convex hull to 1 and minimizing x_2.
425  * Now, each element in the cone of the convex hull is the sum
426  * of elements in the cones of the basic sets.
427  * If a_i is the dilation factor of basic set i, then the problem
428  * we need to solve is
429  *
430  *                      min \sum_i x_{i,2}
431  *                      st
432  *                              \sum_i x_{i,1} = 1
433  *                                  a_i   >= 0
434  *                                [ a_i ]
435  *                              A [ x_i ] >= 0
436  *
437  * with
438  *                                  [  1  ]
439  *                              A_i [ x_i ] >= 0
440  *
441  * the constraints of each (transformed) basic set.
442  * If a = n/d, then the constraint defining the new facet (in the transformed
443  * space) is
444  *
445  *                      -n x_1 + d x_2 >= 0
446  *
447  * In the original space, we need to take the same combination of the
448  * corresponding constraints "facet" and "ridge".
449  *
450  * If a = -infty = "-1/0", then we just return the original facet constraint.
451  * This means that the facet is unbounded, but has a bounded intersection
452  * with the union of sets.
453  */
454 static isl_int *wrap_facet(struct isl_set *set, isl_int *facet, isl_int *ridge)
455 {
456         int i;
457         struct isl_mat *T = NULL;
458         struct isl_basic_set *lp = NULL;
459         struct isl_vec *obj;
460         enum isl_lp_result res;
461         isl_int num, den;
462         unsigned dim;
463
464         set = isl_set_copy(set);
465
466         dim = 1 + isl_set_n_dim(set);
467         T = isl_mat_alloc(set->ctx, 3, dim);
468         if (!T)
469                 goto error;
470         isl_int_set_si(T->row[0][0], 1);
471         isl_seq_clr(T->row[0]+1, dim - 1);
472         isl_seq_cpy(T->row[1], facet, dim);
473         isl_seq_cpy(T->row[2], ridge, dim);
474         T = isl_mat_right_inverse(set->ctx, T);
475         set = isl_set_preimage(set, T);
476         T = NULL;
477         if (!set)
478                 goto error;
479         lp = wrap_constraints(set);
480         obj = isl_vec_alloc(set->ctx, 1 + dim*set->n);
481         if (!obj)
482                 goto error;
483         isl_int_set_si(obj->block.data[0], 0);
484         for (i = 0; i < set->n; ++i) {
485                 isl_seq_clr(obj->block.data + 1 + dim*i, 2);
486                 isl_int_set_si(obj->block.data[1 + dim*i+2], 1);
487                 isl_seq_clr(obj->block.data + 1 + dim*i+3, dim-3);
488         }
489         isl_int_init(num);
490         isl_int_init(den);
491         res = isl_solve_lp((struct isl_basic_map *)lp, 0,
492                                     obj->block.data, set->ctx->one, &num, &den);
493         if (res == isl_lp_ok) {
494                 isl_int_neg(num, num);
495                 isl_seq_combine(facet, num, facet, den, ridge, dim);
496         }
497         isl_int_clear(num);
498         isl_int_clear(den);
499         isl_vec_free(set->ctx, obj);
500         isl_basic_set_free(lp);
501         isl_set_free(set);
502         isl_assert(set->ctx, res == isl_lp_ok || res == isl_lp_unbounded, 
503                    return NULL);
504         return facet;
505 error:
506         isl_basic_set_free(lp);
507         isl_mat_free(set->ctx, T);
508         isl_set_free(set);
509         return NULL;
510 }
511
512 /* Given a set of d linearly independent bounding constraints of the
513  * convex hull of "set", compute the constraint of a facet of "set".
514  *
515  * We first compute the intersection with the first bounding hyperplane
516  * and remove the component corresponding to this hyperplane from
517  * other bounds (in homogeneous space).
518  * We then wrap around one of the remaining bounding constraints
519  * and continue the process until all bounding constraints have been
520  * taken into account.
521  * The resulting linear combination of the bounding constraints will
522  * correspond to a facet of the convex hull.
523  */
524 static struct isl_mat *initial_facet_constraint(struct isl_ctx *ctx,
525         struct isl_set *set, struct isl_mat *bounds)
526 {
527         struct isl_set *slice = NULL;
528         struct isl_basic_set *face = NULL;
529         struct isl_mat *m, *U, *Q;
530         int i;
531         unsigned dim = isl_set_n_dim(set);
532
533         isl_assert(ctx, set->n > 0, goto error);
534         isl_assert(ctx, bounds->n_row == dim, goto error);
535
536         while (bounds->n_row > 1) {
537                 slice = isl_set_copy(set);
538                 slice = isl_set_add_equality(ctx, slice, bounds->row[0]);
539                 face = isl_set_affine_hull(slice);
540                 if (!face)
541                         goto error;
542                 if (face->n_eq == 1) {
543                         isl_basic_set_free(face);
544                         break;
545                 }
546                 m = isl_mat_alloc(ctx, 1 + face->n_eq, 1 + dim);
547                 if (!m)
548                         goto error;
549                 isl_int_set_si(m->row[0][0], 1);
550                 isl_seq_clr(m->row[0]+1, dim);
551                 for (i = 0; i < face->n_eq; ++i)
552                         isl_seq_cpy(m->row[1 + i], face->eq[i], 1 + dim);
553                 U = isl_mat_right_inverse(ctx, m);
554                 Q = isl_mat_right_inverse(ctx, isl_mat_copy(ctx, U));
555                 U = isl_mat_drop_cols(ctx, U, 1 + face->n_eq,
556                                                 dim - face->n_eq);
557                 Q = isl_mat_drop_rows(ctx, Q, 1 + face->n_eq,
558                                                 dim - face->n_eq);
559                 U = isl_mat_drop_cols(ctx, U, 0, 1);
560                 Q = isl_mat_drop_rows(ctx, Q, 0, 1);
561                 bounds = isl_mat_product(ctx, bounds, U);
562                 bounds = isl_mat_product(ctx, bounds, Q);
563                 while (isl_seq_first_non_zero(bounds->row[bounds->n_row-1],
564                                               bounds->n_col) == -1) {
565                         bounds->n_row--;
566                         isl_assert(ctx, bounds->n_row > 1, goto error);
567                 }
568                 if (!wrap_facet(set, bounds->row[0],
569                                           bounds->row[bounds->n_row-1]))
570                         goto error;
571                 isl_basic_set_free(face);
572                 bounds->n_row--;
573         }
574         return bounds;
575 error:
576         isl_basic_set_free(face);
577         isl_mat_free(ctx, bounds);
578         return NULL;
579 }
580
581 /* Given the bounding constraint "c" of a facet of the convex hull of "set",
582  * compute a hyperplane description of the facet, i.e., compute the facets
583  * of the facet.
584  *
585  * We compute an affine transformation that transforms the constraint
586  *
587  *                        [ 1 ]
588  *                      c [ x ] = 0
589  *
590  * to the constraint
591  *
592  *                         z_1  = 0
593  *
594  * by computing the right inverse U of a matrix that starts with the rows
595  *
596  *                      [ 1 0 ]
597  *                      [  c  ]
598  *
599  * Then
600  *                      [ 1 ]     [ 1 ]
601  *                      [ x ] = U [ z ]
602  * and
603  *                      [ 1 ]     [ 1 ]
604  *                      [ z ] = Q [ x ]
605  *
606  * with Q = U^{-1}
607  * Since z_1 is zero, we can drop this variable as well as the corresponding
608  * column of U to obtain
609  *
610  *                      [ 1 ]      [ 1  ]
611  *                      [ x ] = U' [ z' ]
612  * and
613  *                      [ 1  ]      [ 1 ]
614  *                      [ z' ] = Q' [ x ]
615  *
616  * with Q' equal to Q, but without the corresponding row.
617  * After computing the facets of the facet in the z' space,
618  * we convert them back to the x space through Q.
619  */
620 static struct isl_basic_set *compute_facet(struct isl_set *set, isl_int *c)
621 {
622         struct isl_mat *m, *U, *Q;
623         struct isl_basic_set *facet = NULL;
624         struct isl_ctx *ctx;
625         unsigned dim;
626
627         ctx = set->ctx;
628         set = isl_set_copy(set);
629         dim = isl_set_n_dim(set);
630         m = isl_mat_alloc(set->ctx, 2, 1 + dim);
631         if (!m)
632                 goto error;
633         isl_int_set_si(m->row[0][0], 1);
634         isl_seq_clr(m->row[0]+1, dim);
635         isl_seq_cpy(m->row[1], c, 1+dim);
636         U = isl_mat_right_inverse(set->ctx, m);
637         Q = isl_mat_right_inverse(set->ctx, isl_mat_copy(set->ctx, U));
638         U = isl_mat_drop_cols(set->ctx, U, 1, 1);
639         Q = isl_mat_drop_rows(set->ctx, Q, 1, 1);
640         set = isl_set_preimage(set, U);
641         facet = uset_convex_hull_wrap_bounded(set);
642         facet = isl_basic_set_preimage(facet, Q);
643         isl_assert(ctx, facet->n_eq == 0, goto error);
644         return facet;
645 error:
646         isl_basic_set_free(facet);
647         isl_set_free(set);
648         return NULL;
649 }
650
651 /* Given an initial facet constraint, compute the remaining facets.
652  * We do this by running through all facets found so far and computing
653  * the adjacent facets through wrapping, adding those facets that we
654  * hadn't already found before.
655  *
656  * For each facet we have found so far, we first compute its facets
657  * in the resulting convex hull.  That is, we compute the ridges
658  * of the resulting convex hull contained in the facet.
659  * We also compute the corresponding facet in the current approximation
660  * of the convex hull.  There is no need to wrap around the ridges
661  * in this facet since that would result in a facet that is already
662  * present in the current approximation.
663  *
664  * This function can still be significantly optimized by checking which of
665  * the facets of the basic sets are also facets of the convex hull and
666  * using all the facets so far to help in constructing the facets of the
667  * facets
668  * and/or
669  * using the technique in section "3.1 Ridge Generation" of
670  * "Extended Convex Hull" by Fukuda et al.
671  */
672 static struct isl_basic_set *extend(struct isl_basic_set *hull,
673         struct isl_set *set)
674 {
675         int i, j, f;
676         int k;
677         struct isl_basic_set *facet = NULL;
678         struct isl_basic_set *hull_facet = NULL;
679         unsigned total;
680         unsigned dim;
681
682         isl_assert(set->ctx, set->n > 0, goto error);
683
684         dim = isl_set_n_dim(set);
685
686         for (i = 0; i < hull->n_ineq; ++i) {
687                 facet = compute_facet(set, hull->ineq[i]);
688                 facet = isl_basic_set_add_equality(facet->ctx, facet, hull->ineq[i]);
689                 facet = isl_basic_set_gauss(facet, NULL);
690                 facet = isl_basic_set_normalize_constraints(facet);
691                 hull_facet = isl_basic_set_copy(hull);
692                 hull_facet = isl_basic_set_add_equality(hull_facet->ctx, hull_facet, hull->ineq[i]);
693                 hull_facet = isl_basic_set_gauss(hull_facet, NULL);
694                 hull_facet = isl_basic_set_normalize_constraints(hull_facet);
695                 if (!facet)
696                         goto error;
697                 if (facet->n_ineq + hull->n_ineq > hull->c_size)
698                         hull = isl_basic_set_extend_dim(hull,
699                                 isl_dim_copy(hull->dim), 0, 0, facet->n_ineq);
700                 for (j = 0; j < facet->n_ineq; ++j) {
701                         for (f = 0; f < hull_facet->n_ineq; ++f)
702                                 if (isl_seq_eq(facet->ineq[j],
703                                                 hull_facet->ineq[f], 1 + dim))
704                                         break;
705                         if (f < hull_facet->n_ineq)
706                                 continue;
707                         k = isl_basic_set_alloc_inequality(hull);
708                         if (k < 0)
709                                 goto error;
710                         isl_seq_cpy(hull->ineq[k], hull->ineq[i], 1+dim);
711                         if (!wrap_facet(set, hull->ineq[k], facet->ineq[j]))
712                                 goto error;
713                 }
714                 isl_basic_set_free(hull_facet);
715                 isl_basic_set_free(facet);
716         }
717         hull = isl_basic_set_simplify(hull);
718         hull = isl_basic_set_finalize(hull);
719         return hull;
720 error:
721         isl_basic_set_free(hull_facet);
722         isl_basic_set_free(facet);
723         isl_basic_set_free(hull);
724         return NULL;
725 }
726
727 /* Special case for computing the convex hull of a one dimensional set.
728  * We simply collect the lower and upper bounds of each basic set
729  * and the biggest of those.
730  */
731 static struct isl_basic_set *convex_hull_1d(struct isl_ctx *ctx,
732         struct isl_set *set)
733 {
734         struct isl_mat *c = NULL;
735         isl_int *lower = NULL;
736         isl_int *upper = NULL;
737         int i, j, k;
738         isl_int a, b;
739         struct isl_basic_set *hull;
740
741         for (i = 0; i < set->n; ++i) {
742                 set->p[i] = isl_basic_set_simplify(set->p[i]);
743                 if (!set->p[i])
744                         goto error;
745         }
746         set = isl_set_remove_empty_parts(set);
747         if (!set)
748                 goto error;
749         isl_assert(ctx, set->n > 0, goto error);
750         c = isl_mat_alloc(ctx, 2, 2);
751         if (!c)
752                 goto error;
753
754         if (set->p[0]->n_eq > 0) {
755                 isl_assert(ctx, set->p[0]->n_eq == 1, goto error);
756                 lower = c->row[0];
757                 upper = c->row[1];
758                 if (isl_int_is_pos(set->p[0]->eq[0][1])) {
759                         isl_seq_cpy(lower, set->p[0]->eq[0], 2);
760                         isl_seq_neg(upper, set->p[0]->eq[0], 2);
761                 } else {
762                         isl_seq_neg(lower, set->p[0]->eq[0], 2);
763                         isl_seq_cpy(upper, set->p[0]->eq[0], 2);
764                 }
765         } else {
766                 for (j = 0; j < set->p[0]->n_ineq; ++j) {
767                         if (isl_int_is_pos(set->p[0]->ineq[j][1])) {
768                                 lower = c->row[0];
769                                 isl_seq_cpy(lower, set->p[0]->ineq[j], 2);
770                         } else {
771                                 upper = c->row[1];
772                                 isl_seq_cpy(upper, set->p[0]->ineq[j], 2);
773                         }
774                 }
775         }
776
777         isl_int_init(a);
778         isl_int_init(b);
779         for (i = 0; i < set->n; ++i) {
780                 struct isl_basic_set *bset = set->p[i];
781                 int has_lower = 0;
782                 int has_upper = 0;
783
784                 for (j = 0; j < bset->n_eq; ++j) {
785                         has_lower = 1;
786                         has_upper = 1;
787                         if (lower) {
788                                 isl_int_mul(a, lower[0], bset->eq[j][1]);
789                                 isl_int_mul(b, lower[1], bset->eq[j][0]);
790                                 if (isl_int_lt(a, b) && isl_int_is_pos(bset->eq[j][1]))
791                                         isl_seq_cpy(lower, bset->eq[j], 2);
792                                 if (isl_int_gt(a, b) && isl_int_is_neg(bset->eq[j][1]))
793                                         isl_seq_neg(lower, bset->eq[j], 2);
794                         }
795                         if (upper) {
796                                 isl_int_mul(a, upper[0], bset->eq[j][1]);
797                                 isl_int_mul(b, upper[1], bset->eq[j][0]);
798                                 if (isl_int_lt(a, b) && isl_int_is_pos(bset->eq[j][1]))
799                                         isl_seq_neg(upper, bset->eq[j], 2);
800                                 if (isl_int_gt(a, b) && isl_int_is_neg(bset->eq[j][1]))
801                                         isl_seq_cpy(upper, bset->eq[j], 2);
802                         }
803                 }
804                 for (j = 0; j < bset->n_ineq; ++j) {
805                         if (isl_int_is_pos(bset->ineq[j][1]))
806                                 has_lower = 1;
807                         if (isl_int_is_neg(bset->ineq[j][1]))
808                                 has_upper = 1;
809                         if (lower && isl_int_is_pos(bset->ineq[j][1])) {
810                                 isl_int_mul(a, lower[0], bset->ineq[j][1]);
811                                 isl_int_mul(b, lower[1], bset->ineq[j][0]);
812                                 if (isl_int_lt(a, b))
813                                         isl_seq_cpy(lower, bset->ineq[j], 2);
814                         }
815                         if (upper && isl_int_is_neg(bset->ineq[j][1])) {
816                                 isl_int_mul(a, upper[0], bset->ineq[j][1]);
817                                 isl_int_mul(b, upper[1], bset->ineq[j][0]);
818                                 if (isl_int_gt(a, b))
819                                         isl_seq_cpy(upper, bset->ineq[j], 2);
820                         }
821                 }
822                 if (!has_lower)
823                         lower = NULL;
824                 if (!has_upper)
825                         upper = NULL;
826         }
827         isl_int_clear(a);
828         isl_int_clear(b);
829
830         hull = isl_basic_set_alloc(ctx, 0, 1, 0, 0, 2);
831         hull = isl_basic_set_set_rational(hull);
832         if (!hull)
833                 goto error;
834         if (lower) {
835                 k = isl_basic_set_alloc_inequality(hull);
836                 isl_seq_cpy(hull->ineq[k], lower, 2);
837         }
838         if (upper) {
839                 k = isl_basic_set_alloc_inequality(hull);
840                 isl_seq_cpy(hull->ineq[k], upper, 2);
841         }
842         hull = isl_basic_set_finalize(hull);
843         isl_set_free(set);
844         isl_mat_free(ctx, c);
845         return hull;
846 error:
847         isl_set_free(set);
848         isl_mat_free(ctx, c);
849         return NULL;
850 }
851
852 /* Project out final n dimensions using Fourier-Motzkin */
853 static struct isl_set *set_project_out(struct isl_ctx *ctx,
854         struct isl_set *set, unsigned n)
855 {
856         return isl_set_remove_dims(set, isl_set_n_dim(set) - n, n);
857 }
858
859 static struct isl_basic_set *convex_hull_0d(struct isl_set *set)
860 {
861         struct isl_basic_set *convex_hull;
862
863         if (!set)
864                 return NULL;
865
866         if (isl_set_is_empty(set))
867                 convex_hull = isl_basic_set_empty(isl_dim_copy(set->dim));
868         else
869                 convex_hull = isl_basic_set_universe(isl_dim_copy(set->dim));
870         isl_set_free(set);
871         return convex_hull;
872 }
873
874 /* Compute the convex hull of a pair of basic sets without any parameters or
875  * integer divisions using Fourier-Motzkin elimination.
876  * The convex hull is the set of all points that can be written as
877  * the sum of points from both basic sets (in homogeneous coordinates).
878  * We set up the constraints in a space with dimensions for each of
879  * the three sets and then project out the dimensions corresponding
880  * to the two original basic sets, retaining only those corresponding
881  * to the convex hull.
882  */
883 static struct isl_basic_set *convex_hull_pair(struct isl_basic_set *bset1,
884         struct isl_basic_set *bset2)
885 {
886         int i, j, k;
887         struct isl_basic_set *bset[2];
888         struct isl_basic_set *hull = NULL;
889         unsigned dim;
890
891         if (!bset1 || !bset2)
892                 goto error;
893
894         dim = isl_basic_set_n_dim(bset1);
895         hull = isl_basic_set_alloc(bset1->ctx, 0, 2 + 3 * dim, 0,
896                                 1 + dim + bset1->n_eq + bset2->n_eq,
897                                 2 + bset1->n_ineq + bset2->n_ineq);
898         bset[0] = bset1;
899         bset[1] = bset2;
900         for (i = 0; i < 2; ++i) {
901                 for (j = 0; j < bset[i]->n_eq; ++j) {
902                         k = isl_basic_set_alloc_equality(hull);
903                         if (k < 0)
904                                 goto error;
905                         isl_seq_clr(hull->eq[k], (i+1) * (1+dim));
906                         isl_seq_clr(hull->eq[k]+(i+2)*(1+dim), (1-i)*(1+dim));
907                         isl_seq_cpy(hull->eq[k]+(i+1)*(1+dim), bset[i]->eq[j],
908                                         1+dim);
909                 }
910                 for (j = 0; j < bset[i]->n_ineq; ++j) {
911                         k = isl_basic_set_alloc_inequality(hull);
912                         if (k < 0)
913                                 goto error;
914                         isl_seq_clr(hull->ineq[k], (i+1) * (1+dim));
915                         isl_seq_clr(hull->ineq[k]+(i+2)*(1+dim), (1-i)*(1+dim));
916                         isl_seq_cpy(hull->ineq[k]+(i+1)*(1+dim),
917                                         bset[i]->ineq[j], 1+dim);
918                 }
919                 k = isl_basic_set_alloc_inequality(hull);
920                 if (k < 0)
921                         goto error;
922                 isl_seq_clr(hull->ineq[k], 1+2+3*dim);
923                 isl_int_set_si(hull->ineq[k][(i+1)*(1+dim)], 1);
924         }
925         for (j = 0; j < 1+dim; ++j) {
926                 k = isl_basic_set_alloc_equality(hull);
927                 if (k < 0)
928                         goto error;
929                 isl_seq_clr(hull->eq[k], 1+2+3*dim);
930                 isl_int_set_si(hull->eq[k][j], -1);
931                 isl_int_set_si(hull->eq[k][1+dim+j], 1);
932                 isl_int_set_si(hull->eq[k][2*(1+dim)+j], 1);
933         }
934         hull = isl_basic_set_set_rational(hull);
935         hull = isl_basic_set_remove_dims(hull, dim, 2*(1+dim));
936         hull = isl_basic_set_convex_hull(hull);
937         isl_basic_set_free(bset1);
938         isl_basic_set_free(bset2);
939         return hull;
940 error:
941         isl_basic_set_free(bset1);
942         isl_basic_set_free(bset2);
943         isl_basic_set_free(hull);
944         return NULL;
945 }
946
947 /* Compute the convex hull of a set without any parameters or
948  * integer divisions using Fourier-Motzkin elimination.
949  * In each step, we combined two basic sets until only one
950  * basic set is left.
951  */
952 static struct isl_basic_set *uset_convex_hull_elim(struct isl_set *set)
953 {
954         struct isl_basic_set *convex_hull = NULL;
955
956         convex_hull = isl_set_copy_basic_set(set);
957         set = isl_set_drop_basic_set(set, convex_hull);
958         if (!set)
959                 goto error;
960         while (set->n > 0) {
961                 struct isl_basic_set *t;
962                 t = isl_set_copy_basic_set(set);
963                 if (!t)
964                         goto error;
965                 set = isl_set_drop_basic_set(set, t);
966                 if (!set)
967                         goto error;
968                 convex_hull = convex_hull_pair(convex_hull, t);
969         }
970         isl_set_free(set);
971         return convex_hull;
972 error:
973         isl_set_free(set);
974         isl_basic_set_free(convex_hull);
975         return NULL;
976 }
977
978 /* Compute an initial hull for wrapping containing a single initial
979  * facet by first computing bounds on the set and then using these
980  * bounds to construct an initial facet.
981  * This function is a remnant of an older implementation where the
982  * bounds were also used to check whether the set was bounded.
983  * Since this function will now only be called when we know the
984  * set to be bounded, the initial facet should probably be constructed 
985  * by simply using the coordinate directions instead.
986  */
987 static struct isl_basic_set *initial_hull(struct isl_basic_set *hull,
988         struct isl_set *set)
989 {
990         struct isl_mat *bounds = NULL;
991         unsigned dim;
992         int k;
993
994         if (!hull)
995                 goto error;
996         bounds = independent_bounds(set->ctx, set);
997         if (!bounds)
998                 goto error;
999         isl_assert(set->ctx, bounds->n_row == isl_set_n_dim(set), goto error);
1000         bounds = initial_facet_constraint(set->ctx, set, bounds);
1001         if (!bounds)
1002                 goto error;
1003         k = isl_basic_set_alloc_inequality(hull);
1004         if (k < 0)
1005                 goto error;
1006         dim = isl_set_n_dim(set);
1007         isl_assert(set->ctx, 1 + dim == bounds->n_col, goto error);
1008         isl_seq_cpy(hull->ineq[k], bounds->row[0], bounds->n_col);
1009         isl_mat_free(set->ctx, bounds);
1010
1011         return hull;
1012 error:
1013         isl_basic_set_free(hull);
1014         isl_mat_free(set->ctx, bounds);
1015         return NULL;
1016 }
1017
1018 struct max_constraint {
1019         struct isl_mat *c;
1020         int             count;
1021         int             ineq;
1022 };
1023
1024 static int max_constraint_equal(const void *entry, const void *val)
1025 {
1026         struct max_constraint *a = (struct max_constraint *)entry;
1027         isl_int *b = (isl_int *)val;
1028
1029         return isl_seq_eq(a->c->row[0] + 1, b, a->c->n_col - 1);
1030 }
1031
1032 static void update_constraint(struct isl_ctx *ctx, struct isl_hash_table *table,
1033         isl_int *con, unsigned len, int n, int ineq)
1034 {
1035         struct isl_hash_table_entry *entry;
1036         struct max_constraint *c;
1037         uint32_t c_hash;
1038
1039         c_hash = isl_seq_hash(con + 1, len, isl_hash_init());
1040         entry = isl_hash_table_find(ctx, table, c_hash, max_constraint_equal,
1041                         con + 1, 0);
1042         if (!entry)
1043                 return;
1044         c = entry->data;
1045         if (c->count < n) {
1046                 isl_hash_table_remove(ctx, table, entry);
1047                 return;
1048         }
1049         c->count++;
1050         if (isl_int_gt(c->c->row[0][0], con[0]))
1051                 return;
1052         if (isl_int_eq(c->c->row[0][0], con[0])) {
1053                 if (ineq)
1054                         c->ineq = ineq;
1055                 return;
1056         }
1057         c->c = isl_mat_cow(ctx, c->c);
1058         isl_int_set(c->c->row[0][0], con[0]);
1059         c->ineq = ineq;
1060 }
1061
1062 /* Check whether the constraint hash table "table" constains the constraint
1063  * "con".
1064  */
1065 static int has_constraint(struct isl_ctx *ctx, struct isl_hash_table *table,
1066         isl_int *con, unsigned len, int n)
1067 {
1068         struct isl_hash_table_entry *entry;
1069         struct max_constraint *c;
1070         uint32_t c_hash;
1071
1072         c_hash = isl_seq_hash(con + 1, len, isl_hash_init());
1073         entry = isl_hash_table_find(ctx, table, c_hash, max_constraint_equal,
1074                         con + 1, 0);
1075         if (!entry)
1076                 return 0;
1077         c = entry->data;
1078         if (c->count < n)
1079                 return 0;
1080         return isl_int_eq(c->c->row[0][0], con[0]);
1081 }
1082
1083 /* Check for inequality constraints of a basic set without equalities
1084  * such that the same or more stringent copies of the constraint appear
1085  * in all of the basic sets.  Such constraints are necessarily facet
1086  * constraints of the convex hull.
1087  *
1088  * If the resulting basic set is by chance identical to one of
1089  * the basic sets in "set", then we know that this basic set contains
1090  * all other basic sets and is therefore the convex hull of set.
1091  * In this case we set *is_hull to 1.
1092  */
1093 static struct isl_basic_set *common_constraints(struct isl_basic_set *hull,
1094         struct isl_set *set, int *is_hull)
1095 {
1096         int i, j, s, n;
1097         int min_constraints;
1098         int best;
1099         struct max_constraint *constraints = NULL;
1100         struct isl_hash_table *table = NULL;
1101         unsigned total;
1102
1103         *is_hull = 0;
1104
1105         for (i = 0; i < set->n; ++i)
1106                 if (set->p[i]->n_eq == 0)
1107                         break;
1108         if (i >= set->n)
1109                 return hull;
1110         min_constraints = set->p[i]->n_ineq;
1111         best = i;
1112         for (i = best + 1; i < set->n; ++i) {
1113                 if (set->p[i]->n_eq != 0)
1114                         continue;
1115                 if (set->p[i]->n_ineq >= min_constraints)
1116                         continue;
1117                 min_constraints = set->p[i]->n_ineq;
1118                 best = i;
1119         }
1120         constraints = isl_calloc_array(hull->ctx, struct max_constraint,
1121                                         min_constraints);
1122         if (!constraints)
1123                 return hull;
1124         table = isl_alloc_type(hull->ctx, struct isl_hash_table);
1125         if (isl_hash_table_init(hull->ctx, table, min_constraints))
1126                 goto error;
1127
1128         total = isl_dim_total(set->dim);
1129         for (i = 0; i < set->p[best]->n_ineq; ++i) {
1130                 constraints[i].c = isl_mat_sub_alloc(hull->ctx,
1131                         set->p[best]->ineq + i, 0, 1, 0, 1 + total);
1132                 if (!constraints[i].c)
1133                         goto error;
1134                 constraints[i].ineq = 1;
1135         }
1136         for (i = 0; i < min_constraints; ++i) {
1137                 struct isl_hash_table_entry *entry;
1138                 uint32_t c_hash;
1139                 c_hash = isl_seq_hash(constraints[i].c->row[0] + 1, total,
1140                                         isl_hash_init());
1141                 entry = isl_hash_table_find(hull->ctx, table, c_hash,
1142                         max_constraint_equal, constraints[i].c->row[0] + 1, 1);
1143                 if (!entry)
1144                         goto error;
1145                 isl_assert(hull->ctx, !entry->data, goto error);
1146                 entry->data = &constraints[i];
1147         }
1148
1149         n = 0;
1150         for (s = 0; s < set->n; ++s) {
1151                 if (s == best)
1152                         continue;
1153
1154                 for (i = 0; i < set->p[s]->n_eq; ++i) {
1155                         isl_int *eq = set->p[s]->eq[i];
1156                         for (j = 0; j < 2; ++j) {
1157                                 isl_seq_neg(eq, eq, 1 + total);
1158                                 update_constraint(hull->ctx, table,
1159                                                             eq, total, n, 0);
1160                         }
1161                 }
1162                 for (i = 0; i < set->p[s]->n_ineq; ++i) {
1163                         isl_int *ineq = set->p[s]->ineq[i];
1164                         update_constraint(hull->ctx, table, ineq, total, n,
1165                                 set->p[s]->n_eq == 0);
1166                 }
1167                 ++n;
1168         }
1169
1170         for (i = 0; i < min_constraints; ++i) {
1171                 if (constraints[i].count < n)
1172                         continue;
1173                 if (!constraints[i].ineq)
1174                         continue;
1175                 j = isl_basic_set_alloc_inequality(hull);
1176                 if (j < 0)
1177                         goto error;
1178                 isl_seq_cpy(hull->ineq[j], constraints[i].c->row[0], 1 + total);
1179         }
1180
1181         for (s = 0; s < set->n; ++s) {
1182                 if (set->p[s]->n_eq)
1183                         continue;
1184                 if (set->p[s]->n_ineq != hull->n_ineq)
1185                         continue;
1186                 for (i = 0; i < set->p[s]->n_ineq; ++i) {
1187                         isl_int *ineq = set->p[s]->ineq[i];
1188                         if (!has_constraint(hull->ctx, table, ineq, total, n))
1189                                 break;
1190                 }
1191                 if (i == set->p[s]->n_ineq)
1192                         *is_hull = 1;
1193         }
1194
1195         isl_hash_table_clear(table);
1196         for (i = 0; i < min_constraints; ++i)
1197                 isl_mat_free(hull->ctx, constraints[i].c);
1198         free(constraints);
1199         free(table);
1200         return hull;
1201 error:
1202         isl_hash_table_clear(table);
1203         free(table);
1204         if (constraints)
1205                 for (i = 0; i < min_constraints; ++i)
1206                         isl_mat_free(hull->ctx, constraints[i].c);
1207         free(constraints);
1208         return hull;
1209 }
1210
1211 /* Create a template for the convex hull of "set" and fill it up
1212  * obvious facet constraints, if any.  If the result happens to
1213  * be the convex hull of "set" then *is_hull is set to 1.
1214  */
1215 static struct isl_basic_set *proto_hull(struct isl_set *set, int *is_hull)
1216 {
1217         struct isl_basic_set *hull;
1218         unsigned n_ineq;
1219         int i;
1220
1221         n_ineq = 1;
1222         for (i = 0; i < set->n; ++i) {
1223                 n_ineq += set->p[i]->n_eq;
1224                 n_ineq += set->p[i]->n_ineq;
1225         }
1226         hull = isl_basic_set_alloc_dim(isl_dim_copy(set->dim), 0, 0, n_ineq);
1227         hull = isl_basic_set_set_rational(hull);
1228         if (!hull)
1229                 return NULL;
1230         return common_constraints(hull, set, is_hull);
1231 }
1232
1233 static struct isl_basic_set *uset_convex_hull_wrap(struct isl_set *set)
1234 {
1235         struct isl_basic_set *hull;
1236         int is_hull;
1237
1238         hull = proto_hull(set, &is_hull);
1239         if (hull && !is_hull) {
1240                 if (hull->n_ineq == 0)
1241                         hull = initial_hull(hull, set);
1242                 hull = extend(hull, set);
1243         }
1244         isl_set_free(set);
1245
1246         return hull;
1247 }
1248
1249 static int isl_basic_set_is_bounded(struct isl_basic_set *bset)
1250 {
1251         struct isl_tab *tab;
1252         int bounded;
1253
1254         tab = isl_tab_from_recession_cone((struct isl_basic_map *)bset);
1255         bounded = isl_tab_cone_is_bounded(bset->ctx, tab);
1256         isl_tab_free(bset->ctx, tab);
1257         return bounded;
1258 }
1259
1260 static int isl_set_is_bounded(struct isl_set *set)
1261 {
1262         int i;
1263
1264         for (i = 0; i < set->n; ++i) {
1265                 int bounded = isl_basic_set_is_bounded(set->p[i]);
1266                 if (!bounded || bounded < 0)
1267                         return bounded;
1268         }
1269         return 1;
1270 }
1271
1272 /* Compute the convex hull of a set without any parameters or
1273  * integer divisions.  Depending on whether the set is bounded,
1274  * we pass control to the wrapping based convex hull or
1275  * the Fourier-Motzkin elimination based convex hull.
1276  * We also handle a few special cases before checking the boundedness.
1277  */
1278 static struct isl_basic_set *uset_convex_hull(struct isl_set *set)
1279 {
1280         int i;
1281         struct isl_basic_set *convex_hull = NULL;
1282
1283         if (isl_set_n_dim(set) == 0)
1284                 return convex_hull_0d(set);
1285
1286         set = isl_set_set_rational(set);
1287
1288         if (!set)
1289                 goto error;
1290         set = isl_set_normalize(set);
1291         if (!set)
1292                 return NULL;
1293         if (set->n == 1) {
1294                 convex_hull = isl_basic_set_copy(set->p[0]);
1295                 isl_set_free(set);
1296                 return convex_hull;
1297         }
1298         if (isl_set_n_dim(set) == 1)
1299                 return convex_hull_1d(set->ctx, set);
1300
1301         if (!isl_set_is_bounded(set))
1302                 return uset_convex_hull_elim(set);
1303
1304         return uset_convex_hull_wrap(set);
1305 error:
1306         isl_set_free(set);
1307         isl_basic_set_free(convex_hull);
1308         return NULL;
1309 }
1310
1311 /* This is the core procedure, where "set" is a "pure" set, i.e.,
1312  * without parameters or divs and where the convex hull of set is
1313  * known to be full-dimensional.
1314  */
1315 static struct isl_basic_set *uset_convex_hull_wrap_bounded(struct isl_set *set)
1316 {
1317         int i;
1318         struct isl_basic_set *convex_hull = NULL;
1319
1320         if (isl_set_n_dim(set) == 0) {
1321                 convex_hull = isl_basic_set_universe(isl_dim_copy(set->dim));
1322                 isl_set_free(set);
1323                 convex_hull = isl_basic_set_set_rational(convex_hull);
1324                 return convex_hull;
1325         }
1326
1327         set = isl_set_set_rational(set);
1328
1329         if (!set)
1330                 goto error;
1331         set = isl_set_normalize(set);
1332         if (!set)
1333                 goto error;
1334         if (set->n == 1) {
1335                 convex_hull = isl_basic_set_copy(set->p[0]);
1336                 isl_set_free(set);
1337                 return convex_hull;
1338         }
1339         if (isl_set_n_dim(set) == 1)
1340                 return convex_hull_1d(set->ctx, set);
1341
1342         return uset_convex_hull_wrap(set);
1343 error:
1344         isl_set_free(set);
1345         return NULL;
1346 }
1347
1348 /* Compute the convex hull of set "set" with affine hull "affine_hull",
1349  * We first remove the equalities (transforming the set), compute the
1350  * convex hull of the transformed set and then add the equalities back
1351  * (after performing the inverse transformation.
1352  */
1353 static struct isl_basic_set *modulo_affine_hull(struct isl_ctx *ctx,
1354         struct isl_set *set, struct isl_basic_set *affine_hull)
1355 {
1356         struct isl_mat *T;
1357         struct isl_mat *T2;
1358         struct isl_basic_set *dummy;
1359         struct isl_basic_set *convex_hull;
1360
1361         dummy = isl_basic_set_remove_equalities(
1362                         isl_basic_set_copy(affine_hull), &T, &T2);
1363         if (!dummy)
1364                 goto error;
1365         isl_basic_set_free(dummy);
1366         set = isl_set_preimage(set, T);
1367         convex_hull = uset_convex_hull(set);
1368         convex_hull = isl_basic_set_preimage(convex_hull, T2);
1369         convex_hull = isl_basic_set_intersect(convex_hull, affine_hull);
1370         return convex_hull;
1371 error:
1372         isl_basic_set_free(affine_hull);
1373         isl_set_free(set);
1374         return NULL;
1375 }
1376
1377 /* Compute the convex hull of a map.
1378  *
1379  * The implementation was inspired by "Extended Convex Hull" by Fukuda et al.,
1380  * specifically, the wrapping of facets to obtain new facets.
1381  */
1382 struct isl_basic_map *isl_map_convex_hull(struct isl_map *map)
1383 {
1384         struct isl_basic_set *bset;
1385         struct isl_basic_map *model = NULL;
1386         struct isl_basic_set *affine_hull = NULL;
1387         struct isl_basic_map *convex_hull = NULL;
1388         struct isl_set *set = NULL;
1389         struct isl_ctx *ctx;
1390
1391         if (!map)
1392                 goto error;
1393
1394         ctx = map->ctx;
1395         if (map->n == 0) {
1396                 convex_hull = isl_basic_map_empty_like_map(map);
1397                 isl_map_free(map);
1398                 return convex_hull;
1399         }
1400
1401         map = isl_map_align_divs(map);
1402         model = isl_basic_map_copy(map->p[0]);
1403         set = isl_map_underlying_set(map);
1404         if (!set)
1405                 goto error;
1406
1407         affine_hull = isl_set_affine_hull(isl_set_copy(set));
1408         if (!affine_hull)
1409                 goto error;
1410         if (affine_hull->n_eq != 0)
1411                 bset = modulo_affine_hull(ctx, set, affine_hull);
1412         else {
1413                 isl_basic_set_free(affine_hull);
1414                 bset = uset_convex_hull(set);
1415         }
1416
1417         convex_hull = isl_basic_map_overlying_set(bset, model);
1418
1419         ISL_F_CLR(convex_hull, ISL_BASIC_MAP_RATIONAL);
1420         return convex_hull;
1421 error:
1422         isl_set_free(set);
1423         isl_basic_map_free(model);
1424         return NULL;
1425 }
1426
1427 struct isl_basic_set *isl_set_convex_hull(struct isl_set *set)
1428 {
1429         return (struct isl_basic_set *)
1430                 isl_map_convex_hull((struct isl_map *)set);
1431 }
1432
1433 struct sh_data_entry {
1434         struct isl_hash_table   *table;
1435         struct isl_tab          *tab;
1436 };
1437
1438 /* Holds the data needed during the simple hull computation.
1439  * In particular,
1440  *      n               the number of basic sets in the original set
1441  *      hull_table      a hash table of already computed constraints
1442  *                      in the simple hull
1443  *      p               for each basic set,
1444  *              table           a hash table of the constraints
1445  *              tab             the tableau corresponding to the basic set
1446  */
1447 struct sh_data {
1448         struct isl_ctx          *ctx;
1449         unsigned                n;
1450         struct isl_hash_table   *hull_table;
1451         struct sh_data_entry    p[0];
1452 };
1453
1454 static void sh_data_free(struct sh_data *data)
1455 {
1456         int i;
1457
1458         if (!data)
1459                 return;
1460         isl_hash_table_free(data->ctx, data->hull_table);
1461         for (i = 0; i < data->n; ++i) {
1462                 isl_hash_table_free(data->ctx, data->p[i].table);
1463                 isl_tab_free(data->ctx, data->p[i].tab);
1464         }
1465         free(data);
1466 }
1467
1468 struct ineq_cmp_data {
1469         unsigned        len;
1470         isl_int         *p;
1471 };
1472
1473 static int has_ineq(const void *entry, const void *val)
1474 {
1475         isl_int *row = (isl_int *)entry;
1476         struct ineq_cmp_data *v = (struct ineq_cmp_data *)val;
1477
1478         return isl_seq_eq(row + 1, v->p + 1, v->len) ||
1479                isl_seq_is_neg(row + 1, v->p + 1, v->len);
1480 }
1481
1482 static int hash_ineq(struct isl_ctx *ctx, struct isl_hash_table *table,
1483                         isl_int *ineq, unsigned len)
1484 {
1485         uint32_t c_hash;
1486         struct ineq_cmp_data v;
1487         struct isl_hash_table_entry *entry;
1488
1489         v.len = len;
1490         v.p = ineq;
1491         c_hash = isl_seq_hash(ineq + 1, len, isl_hash_init());
1492         entry = isl_hash_table_find(ctx, table, c_hash, has_ineq, &v, 1);
1493         if (!entry)
1494                 return - 1;
1495         entry->data = ineq;
1496         return 0;
1497 }
1498
1499 /* Fill hash table "table" with the constraints of "bset".
1500  * Equalities are added as two inequalities.
1501  * The value in the hash table is a pointer to the (in)equality of "bset".
1502  */
1503 static int hash_basic_set(struct isl_hash_table *table,
1504                                 struct isl_basic_set *bset)
1505 {
1506         int i, j;
1507         unsigned dim = isl_basic_set_total_dim(bset);
1508
1509         for (i = 0; i < bset->n_eq; ++i) {
1510                 for (j = 0; j < 2; ++j) {
1511                         isl_seq_neg(bset->eq[i], bset->eq[i], 1 + dim);
1512                         if (hash_ineq(bset->ctx, table, bset->eq[i], dim) < 0)
1513                                 return -1;
1514                 }
1515         }
1516         for (i = 0; i < bset->n_ineq; ++i) {
1517                 if (hash_ineq(bset->ctx, table, bset->ineq[i], dim) < 0)
1518                         return -1;
1519         }
1520         return 0;
1521 }
1522
1523 static struct sh_data *sh_data_alloc(struct isl_set *set, unsigned n_ineq)
1524 {
1525         struct sh_data *data;
1526         int i;
1527
1528         data = isl_calloc(set->ctx, struct sh_data,
1529                 sizeof(struct sh_data) + set->n * sizeof(struct sh_data_entry));
1530         if (!data)
1531                 return NULL;
1532         data->ctx = set->ctx;
1533         data->n = set->n;
1534         data->hull_table = isl_hash_table_alloc(set->ctx, n_ineq);
1535         if (!data->hull_table)
1536                 goto error;
1537         for (i = 0; i < set->n; ++i) {
1538                 data->p[i].table = isl_hash_table_alloc(set->ctx,
1539                                     2 * set->p[i]->n_eq + set->p[i]->n_ineq);
1540                 if (!data->p[i].table)
1541                         goto error;
1542                 if (hash_basic_set(data->p[i].table, set->p[i]) < 0)
1543                         goto error;
1544         }
1545         return data;
1546 error:
1547         sh_data_free(data);
1548         return NULL;
1549 }
1550
1551 /* Check if inequality "ineq" is a bound for basic set "j" or if
1552  * it can be relaxed (by increasing the constant term) to become
1553  * a bound for that basic set.  In the latter case, the constant
1554  * term is updated.
1555  * Return 1 if "ineq" is a bound
1556  *        0 if "ineq" may attain arbitrarily small values on basic set "j"
1557  *       -1 if some error occurred
1558  */
1559 static int is_bound(struct sh_data *data, struct isl_set *set, int j,
1560                         isl_int *ineq)
1561 {
1562         enum isl_lp_result res;
1563         isl_int opt;
1564
1565         if (!data->p[j].tab) {
1566                 data->p[j].tab = isl_tab_from_basic_set(set->p[j]);
1567                 if (!data->p[j].tab)
1568                         return -1;
1569         }
1570
1571         isl_int_init(opt);
1572
1573         res = isl_tab_min(data->ctx, data->p[j].tab, ineq, data->ctx->one,
1574                                 &opt, NULL);
1575         if (res == isl_lp_ok && isl_int_is_neg(opt))
1576                 isl_int_sub(ineq[0], ineq[0], opt);
1577
1578         isl_int_clear(opt);
1579
1580         return res == isl_lp_ok ? 1 :
1581                res == isl_lp_unbounded ? 0 : -1;
1582 }
1583
1584 /* Check if inequality "ineq" from basic set "i" can be relaxed to
1585  * become a bound on the whole set.  If so, add the (relaxed) inequality
1586  * to "hull".
1587  *
1588  * We first check if "hull" already contains a translate of the inequality.
1589  * If so, we are done.
1590  * Then, we check if any of the previous basic sets contains a translate
1591  * of the inequality.  If so, then we have already considered this
1592  * inequality and we are done.
1593  * Otherwise, for each basic set other than "i", we check if the inequality
1594  * is a bound on the basic set.
1595  * For previous basic sets, we know that they do not contain a translate
1596  * of the inequality, so we directly call is_bound.
1597  * For following basic sets, we first check if a translate of the
1598  * inequality appears in its description and if so directly update
1599  * the inequality accordingly.
1600  */
1601 static struct isl_basic_set *add_bound(struct isl_basic_set *hull,
1602         struct sh_data *data, struct isl_set *set, int i, isl_int *ineq)
1603 {
1604         uint32_t c_hash;
1605         struct ineq_cmp_data v;
1606         struct isl_hash_table_entry *entry;
1607         int j, k;
1608
1609         if (!hull)
1610                 return NULL;
1611
1612         v.len = isl_basic_set_total_dim(hull);
1613         v.p = ineq;
1614         c_hash = isl_seq_hash(ineq + 1, v.len, isl_hash_init());
1615
1616         entry = isl_hash_table_find(hull->ctx, data->hull_table, c_hash,
1617                                         has_ineq, &v, 0);
1618         if (entry)
1619                 return hull;
1620
1621         for (j = 0; j < i; ++j) {
1622                 entry = isl_hash_table_find(hull->ctx, data->p[j].table,
1623                                                 c_hash, has_ineq, &v, 0);
1624                 if (entry)
1625                         break;
1626         }
1627         if (j < i)
1628                 return hull;
1629
1630         k = isl_basic_set_alloc_inequality(hull);
1631         isl_seq_cpy(hull->ineq[k], ineq, 1 + v.len);
1632         if (k < 0)
1633                 goto error;
1634
1635         for (j = 0; j < i; ++j) {
1636                 int bound;
1637                 bound = is_bound(data, set, j, hull->ineq[k]);
1638                 if (bound < 0)
1639                         goto error;
1640                 if (!bound)
1641                         break;
1642         }
1643         if (j < i) {
1644                 isl_basic_set_free_inequality(hull, 1);
1645                 return hull;
1646         }
1647
1648         for (j = i + 1; j < set->n; ++j) {
1649                 int bound, neg;
1650                 isl_int *ineq_j;
1651                 entry = isl_hash_table_find(hull->ctx, data->p[j].table,
1652                                                 c_hash, has_ineq, &v, 0);
1653                 if (entry) {
1654                         ineq_j = entry->data;
1655                         neg = isl_seq_is_neg(ineq_j + 1,
1656                                              hull->ineq[k] + 1, v.len);
1657                         if (neg)
1658                                 isl_int_neg(ineq_j[0], ineq_j[0]);
1659                         if (isl_int_gt(ineq_j[0], hull->ineq[k][0]))
1660                                 isl_int_set(hull->ineq[k][0], ineq_j[0]);
1661                         if (neg)
1662                                 isl_int_neg(ineq_j[0], ineq_j[0]);
1663                         continue;
1664                 }
1665                 bound = is_bound(data, set, j, hull->ineq[k]);
1666                 if (bound < 0)
1667                         goto error;
1668                 if (!bound)
1669                         break;
1670         }
1671         if (j < set->n) {
1672                 isl_basic_set_free_inequality(hull, 1);
1673                 return hull;
1674         }
1675
1676         entry = isl_hash_table_find(hull->ctx, data->hull_table, c_hash,
1677                                         has_ineq, &v, 1);
1678         if (!entry)
1679                 goto error;
1680         entry->data = hull->ineq[k];
1681
1682         return hull;
1683 error:
1684         isl_basic_set_free(hull);
1685         return NULL;
1686 }
1687
1688 /* Check if any inequality from basic set "i" can be relaxed to
1689  * become a bound on the whole set.  If so, add the (relaxed) inequality
1690  * to "hull".
1691  */
1692 static struct isl_basic_set *add_bounds(struct isl_basic_set *bset,
1693         struct sh_data *data, struct isl_set *set, int i)
1694 {
1695         int j, k;
1696         unsigned dim = isl_basic_set_total_dim(bset);
1697
1698         for (j = 0; j < set->p[i]->n_eq; ++j) {
1699                 for (k = 0; k < 2; ++k) {
1700                         isl_seq_neg(set->p[i]->eq[j], set->p[i]->eq[j], 1+dim);
1701                         add_bound(bset, data, set, i, set->p[i]->eq[j]);
1702                 }
1703         }
1704         for (j = 0; j < set->p[i]->n_ineq; ++j)
1705                 add_bound(bset, data, set, i, set->p[i]->ineq[j]);
1706         return bset;
1707 }
1708
1709 /* Compute a superset of the convex hull of set that is described
1710  * by only translates of the constraints in the constituents of set.
1711  */
1712 static struct isl_basic_set *uset_simple_hull(struct isl_set *set)
1713 {
1714         struct sh_data *data = NULL;
1715         struct isl_basic_set *hull = NULL;
1716         unsigned n_ineq;
1717         int i, j;
1718
1719         if (!set)
1720                 return NULL;
1721
1722         n_ineq = 0;
1723         for (i = 0; i < set->n; ++i) {
1724                 if (!set->p[i])
1725                         goto error;
1726                 n_ineq += 2 * set->p[i]->n_eq + set->p[i]->n_ineq;
1727         }
1728
1729         hull = isl_set_affine_hull(isl_set_copy(set));
1730         if (!hull)
1731                 goto error;
1732         hull = isl_basic_set_extend_dim(hull, isl_dim_copy(hull->dim),
1733                                         0, 0, n_ineq);
1734         if (!hull)
1735                 goto error;
1736
1737         data = sh_data_alloc(set, n_ineq);
1738         if (!data)
1739                 goto error;
1740         if (hash_basic_set(data->hull_table, hull) < 0)
1741                 goto error;
1742
1743         for (i = 0; i < set->n; ++i)
1744                 hull = add_bounds(hull, data, set, i);
1745
1746         hull = isl_basic_set_convex_hull(hull);
1747
1748         sh_data_free(data);
1749         isl_set_free(set);
1750
1751         return hull;
1752 error:
1753         sh_data_free(data);
1754         isl_basic_set_free(hull);
1755         isl_set_free(set);
1756         return NULL;
1757 }
1758
1759 /* Compute a superset of the convex hull of map that is described
1760  * by only translates of the constraints in the constituents of map.
1761  */
1762 struct isl_basic_map *isl_map_simple_hull(struct isl_map *map)
1763 {
1764         struct isl_set *set = NULL;
1765         struct isl_basic_map *model = NULL;
1766         struct isl_basic_map *hull;
1767         struct isl_basic_set *bset = NULL;
1768
1769         if (!map)
1770                 return NULL;
1771         if (map->n == 0) {
1772                 hull = isl_basic_map_empty_like_map(map);
1773                 isl_map_free(map);
1774                 return hull;
1775         }
1776         if (map->n == 1) {
1777                 hull = isl_basic_map_copy(map->p[0]);
1778                 isl_map_free(map);
1779                 return hull;
1780         }
1781
1782         map = isl_map_align_divs(map);
1783         model = isl_basic_map_copy(map->p[0]);
1784
1785         set = isl_map_underlying_set(map);
1786
1787         bset = uset_simple_hull(set);
1788
1789         hull = isl_basic_map_overlying_set(bset, model);
1790
1791         return hull;
1792 }
1793
1794 struct isl_basic_set *isl_set_simple_hull(struct isl_set *set)
1795 {
1796         return (struct isl_basic_set *)
1797                 isl_map_simple_hull((struct isl_map *)set);
1798 }