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