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