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