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