isl_map_simple_hull: compute affine hull before aligning divs
[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 contraints
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  * If a = -infty = "-1/0", then we just return the original facet constraint.
452  * This means that the facet is unbounded, but has a bounded intersection
453  * with the union of sets.
454  */
455 static isl_int *wrap_facet(struct isl_set *set, isl_int *facet, isl_int *ridge)
456 {
457         int i;
458         struct isl_mat *T = NULL;
459         struct isl_basic_set *lp = NULL;
460         struct isl_vec *obj;
461         enum isl_lp_result res;
462         isl_int num, den;
463         unsigned dim;
464
465         set = isl_set_copy(set);
466
467         dim = 1 + isl_set_n_dim(set);
468         T = isl_mat_alloc(set->ctx, 3, dim);
469         if (!T)
470                 goto error;
471         isl_int_set_si(T->row[0][0], 1);
472         isl_seq_clr(T->row[0]+1, dim - 1);
473         isl_seq_cpy(T->row[1], facet, dim);
474         isl_seq_cpy(T->row[2], ridge, dim);
475         T = isl_mat_right_inverse(set->ctx, T);
476         set = isl_set_preimage(set, T);
477         T = NULL;
478         if (!set)
479                 goto error;
480         lp = wrap_constraints(set);
481         obj = isl_vec_alloc(set->ctx, 1 + dim*set->n);
482         if (!obj)
483                 goto error;
484         isl_int_set_si(obj->block.data[0], 0);
485         for (i = 0; i < set->n; ++i) {
486                 isl_seq_clr(obj->block.data + 1 + dim*i, 2);
487                 isl_int_set_si(obj->block.data[1 + dim*i+2], 1);
488                 isl_seq_clr(obj->block.data + 1 + dim*i+3, dim-3);
489         }
490         isl_int_init(num);
491         isl_int_init(den);
492         res = isl_solve_lp((struct isl_basic_map *)lp, 0,
493                                     obj->block.data, set->ctx->one, &num, &den);
494         if (res == isl_lp_ok) {
495                 isl_int_neg(num, num);
496                 isl_seq_combine(facet, num, facet, den, ridge, dim);
497         }
498         isl_int_clear(num);
499         isl_int_clear(den);
500         isl_vec_free(set->ctx, obj);
501         isl_basic_set_free(lp);
502         isl_set_free(set);
503         isl_assert(set->ctx, res == isl_lp_ok || res == isl_lp_unbounded, 
504                    return NULL);
505         return facet;
506 error:
507         isl_basic_set_free(lp);
508         isl_mat_free(set->ctx, T);
509         isl_set_free(set);
510         return NULL;
511 }
512
513 /* Given a set of d linearly independent bounding constraints of the
514  * convex hull of "set", compute the constraint of a facet of "set".
515  *
516  * We first compute the intersection with the first bounding hyperplane
517  * and remove the component corresponding to this hyperplane from
518  * other bounds (in homogeneous space).
519  * We then wrap around one of the remaining bounding constraints
520  * and continue the process until all bounding constraints have been
521  * taken into account.
522  * The resulting linear combination of the bounding constraints will
523  * correspond to a facet of the convex hull.
524  */
525 static struct isl_mat *initial_facet_constraint(struct isl_ctx *ctx,
526         struct isl_set *set, struct isl_mat *bounds)
527 {
528         struct isl_set *slice = NULL;
529         struct isl_basic_set *face = NULL;
530         struct isl_mat *m, *U, *Q;
531         int i;
532         unsigned dim = isl_set_n_dim(set);
533
534         isl_assert(ctx, set->n > 0, goto error);
535         isl_assert(ctx, bounds->n_row == dim, goto error);
536
537         while (bounds->n_row > 1) {
538                 slice = isl_set_copy(set);
539                 slice = isl_set_add_equality(ctx, slice, bounds->row[0]);
540                 face = isl_set_affine_hull(slice);
541                 if (!face)
542                         goto error;
543                 if (face->n_eq == 1) {
544                         isl_basic_set_free(face);
545                         break;
546                 }
547                 m = isl_mat_alloc(ctx, 1 + face->n_eq, 1 + dim);
548                 if (!m)
549                         goto error;
550                 isl_int_set_si(m->row[0][0], 1);
551                 isl_seq_clr(m->row[0]+1, dim);
552                 for (i = 0; i < face->n_eq; ++i)
553                         isl_seq_cpy(m->row[1 + i], face->eq[i], 1 + dim);
554                 U = isl_mat_right_inverse(ctx, m);
555                 Q = isl_mat_right_inverse(ctx, isl_mat_copy(ctx, U));
556                 U = isl_mat_drop_cols(ctx, U, 1 + face->n_eq,
557                                                 dim - face->n_eq);
558                 Q = isl_mat_drop_rows(ctx, Q, 1 + face->n_eq,
559                                                 dim - face->n_eq);
560                 U = isl_mat_drop_cols(ctx, U, 0, 1);
561                 Q = isl_mat_drop_rows(ctx, Q, 0, 1);
562                 bounds = isl_mat_product(ctx, bounds, U);
563                 bounds = isl_mat_product(ctx, bounds, Q);
564                 while (isl_seq_first_non_zero(bounds->row[bounds->n_row-1],
565                                               bounds->n_col) == -1) {
566                         bounds->n_row--;
567                         isl_assert(ctx, bounds->n_row > 1, goto error);
568                 }
569                 if (!wrap_facet(set, bounds->row[0],
570                                           bounds->row[bounds->n_row-1]))
571                         goto error;
572                 isl_basic_set_free(face);
573                 bounds->n_row--;
574         }
575         return bounds;
576 error:
577         isl_basic_set_free(face);
578         isl_mat_free(ctx, bounds);
579         return NULL;
580 }
581
582 /* Given the bounding constraint "c" of a facet of the convex hull of "set",
583  * compute a hyperplane description of the facet, i.e., compute the facets
584  * of the facet.
585  *
586  * We compute an affine transformation that transforms the constraint
587  *
588  *                        [ 1 ]
589  *                      c [ x ] = 0
590  *
591  * to the constraint
592  *
593  *                         z_1  = 0
594  *
595  * by computing the right inverse U of a matrix that starts with the rows
596  *
597  *                      [ 1 0 ]
598  *                      [  c  ]
599  *
600  * Then
601  *                      [ 1 ]     [ 1 ]
602  *                      [ x ] = U [ z ]
603  * and
604  *                      [ 1 ]     [ 1 ]
605  *                      [ z ] = Q [ x ]
606  *
607  * with Q = U^{-1}
608  * Since z_1 is zero, we can drop this variable as well as the corresponding
609  * column of U to obtain
610  *
611  *                      [ 1 ]      [ 1  ]
612  *                      [ x ] = U' [ z' ]
613  * and
614  *                      [ 1  ]      [ 1 ]
615  *                      [ z' ] = Q' [ x ]
616  *
617  * with Q' equal to Q, but without the corresponding row.
618  * After computing the facets of the facet in the z' space,
619  * we convert them back to the x space through Q.
620  */
621 static struct isl_basic_set *compute_facet(struct isl_set *set, isl_int *c)
622 {
623         struct isl_mat *m, *U, *Q;
624         struct isl_basic_set *facet = NULL;
625         struct isl_ctx *ctx;
626         unsigned dim;
627
628         ctx = set->ctx;
629         set = isl_set_copy(set);
630         dim = isl_set_n_dim(set);
631         m = isl_mat_alloc(set->ctx, 2, 1 + dim);
632         if (!m)
633                 goto error;
634         isl_int_set_si(m->row[0][0], 1);
635         isl_seq_clr(m->row[0]+1, dim);
636         isl_seq_cpy(m->row[1], c, 1+dim);
637         U = isl_mat_right_inverse(set->ctx, m);
638         Q = isl_mat_right_inverse(set->ctx, isl_mat_copy(set->ctx, U));
639         U = isl_mat_drop_cols(set->ctx, U, 1, 1);
640         Q = isl_mat_drop_rows(set->ctx, Q, 1, 1);
641         set = isl_set_preimage(set, U);
642         facet = uset_convex_hull_wrap_bounded(set);
643         facet = isl_basic_set_preimage(facet, Q);
644         isl_assert(ctx, facet->n_eq == 0, goto error);
645         return facet;
646 error:
647         isl_basic_set_free(facet);
648         isl_set_free(set);
649         return NULL;
650 }
651
652 /* Given an initial facet constraint, compute the remaining facets.
653  * We do this by running through all facets found so far and computing
654  * the adjacent facets through wrapping, adding those facets that we
655  * hadn't already found before.
656  *
657  * For each facet we have found so far, we first compute its facets
658  * in the resulting convex hull.  That is, we compute the ridges
659  * of the resulting convex hull contained in the facet.
660  * We also compute the corresponding facet in the current approximation
661  * of the convex hull.  There is no need to wrap around the ridges
662  * in this facet since that would result in a facet that is already
663  * present in the current approximation.
664  *
665  * This function can still be significantly optimized by checking which of
666  * the facets of the basic sets are also facets of the convex hull and
667  * using all the facets so far to help in constructing the facets of the
668  * facets
669  * and/or
670  * using the technique in section "3.1 Ridge Generation" of
671  * "Extended Convex Hull" by Fukuda et al.
672  */
673 static struct isl_basic_set *extend(struct isl_basic_set *hull,
674         struct isl_set *set)
675 {
676         int i, j, f;
677         int k;
678         struct isl_basic_set *facet = NULL;
679         struct isl_basic_set *hull_facet = NULL;
680         unsigned total;
681         unsigned dim;
682
683         isl_assert(set->ctx, set->n > 0, goto error);
684
685         dim = isl_set_n_dim(set);
686
687         for (i = 0; i < hull->n_ineq; ++i) {
688                 facet = compute_facet(set, hull->ineq[i]);
689                 facet = isl_basic_set_add_equality(facet->ctx, facet, hull->ineq[i]);
690                 facet = isl_basic_set_gauss(facet, NULL);
691                 facet = isl_basic_set_normalize_constraints(facet);
692                 hull_facet = isl_basic_set_copy(hull);
693                 hull_facet = isl_basic_set_add_equality(hull_facet->ctx, hull_facet, hull->ineq[i]);
694                 hull_facet = isl_basic_set_gauss(hull_facet, NULL);
695                 hull_facet = isl_basic_set_normalize_constraints(hull_facet);
696                 if (!facet)
697                         goto error;
698                 hull = isl_basic_set_cow(hull);
699                 hull = isl_basic_set_extend_dim(hull,
700                         isl_dim_copy(hull->dim), 0, 0, facet->n_ineq);
701                 for (j = 0; j < facet->n_ineq; ++j) {
702                         for (f = 0; f < hull_facet->n_ineq; ++f)
703                                 if (isl_seq_eq(facet->ineq[j],
704                                                 hull_facet->ineq[f], 1 + dim))
705                                         break;
706                         if (f < hull_facet->n_ineq)
707                                 continue;
708                         k = isl_basic_set_alloc_inequality(hull);
709                         if (k < 0)
710                                 goto error;
711                         isl_seq_cpy(hull->ineq[k], hull->ineq[i], 1+dim);
712                         if (!wrap_facet(set, hull->ineq[k], facet->ineq[j]))
713                                 goto error;
714                 }
715                 isl_basic_set_free(hull_facet);
716                 isl_basic_set_free(facet);
717         }
718         hull = isl_basic_set_simplify(hull);
719         hull = isl_basic_set_finalize(hull);
720         return hull;
721 error:
722         isl_basic_set_free(hull_facet);
723         isl_basic_set_free(facet);
724         isl_basic_set_free(hull);
725         return NULL;
726 }
727
728 /* Special case for computing the convex hull of a one dimensional set.
729  * We simply collect the lower and upper bounds of each basic set
730  * and the biggest of those.
731  */
732 static struct isl_basic_set *convex_hull_1d(struct isl_ctx *ctx,
733         struct isl_set *set)
734 {
735         struct isl_mat *c = NULL;
736         isl_int *lower = NULL;
737         isl_int *upper = NULL;
738         int i, j, k;
739         isl_int a, b;
740         struct isl_basic_set *hull;
741
742         for (i = 0; i < set->n; ++i) {
743                 set->p[i] = isl_basic_set_simplify(set->p[i]);
744                 if (!set->p[i])
745                         goto error;
746         }
747         set = isl_set_remove_empty_parts(set);
748         if (!set)
749                 goto error;
750         isl_assert(ctx, set->n > 0, goto error);
751         c = isl_mat_alloc(ctx, 2, 2);
752         if (!c)
753                 goto error;
754
755         if (set->p[0]->n_eq > 0) {
756                 isl_assert(ctx, set->p[0]->n_eq == 1, goto error);
757                 lower = c->row[0];
758                 upper = c->row[1];
759                 if (isl_int_is_pos(set->p[0]->eq[0][1])) {
760                         isl_seq_cpy(lower, set->p[0]->eq[0], 2);
761                         isl_seq_neg(upper, set->p[0]->eq[0], 2);
762                 } else {
763                         isl_seq_neg(lower, set->p[0]->eq[0], 2);
764                         isl_seq_cpy(upper, set->p[0]->eq[0], 2);
765                 }
766         } else {
767                 for (j = 0; j < set->p[0]->n_ineq; ++j) {
768                         if (isl_int_is_pos(set->p[0]->ineq[j][1])) {
769                                 lower = c->row[0];
770                                 isl_seq_cpy(lower, set->p[0]->ineq[j], 2);
771                         } else {
772                                 upper = c->row[1];
773                                 isl_seq_cpy(upper, set->p[0]->ineq[j], 2);
774                         }
775                 }
776         }
777
778         isl_int_init(a);
779         isl_int_init(b);
780         for (i = 0; i < set->n; ++i) {
781                 struct isl_basic_set *bset = set->p[i];
782                 int has_lower = 0;
783                 int has_upper = 0;
784
785                 for (j = 0; j < bset->n_eq; ++j) {
786                         has_lower = 1;
787                         has_upper = 1;
788                         if (lower) {
789                                 isl_int_mul(a, lower[0], bset->eq[j][1]);
790                                 isl_int_mul(b, lower[1], bset->eq[j][0]);
791                                 if (isl_int_lt(a, b) && isl_int_is_pos(bset->eq[j][1]))
792                                         isl_seq_cpy(lower, bset->eq[j], 2);
793                                 if (isl_int_gt(a, b) && isl_int_is_neg(bset->eq[j][1]))
794                                         isl_seq_neg(lower, bset->eq[j], 2);
795                         }
796                         if (upper) {
797                                 isl_int_mul(a, upper[0], bset->eq[j][1]);
798                                 isl_int_mul(b, upper[1], bset->eq[j][0]);
799                                 if (isl_int_lt(a, b) && isl_int_is_pos(bset->eq[j][1]))
800                                         isl_seq_neg(upper, bset->eq[j], 2);
801                                 if (isl_int_gt(a, b) && isl_int_is_neg(bset->eq[j][1]))
802                                         isl_seq_cpy(upper, bset->eq[j], 2);
803                         }
804                 }
805                 for (j = 0; j < bset->n_ineq; ++j) {
806                         if (isl_int_is_pos(bset->ineq[j][1]))
807                                 has_lower = 1;
808                         if (isl_int_is_neg(bset->ineq[j][1]))
809                                 has_upper = 1;
810                         if (lower && isl_int_is_pos(bset->ineq[j][1])) {
811                                 isl_int_mul(a, lower[0], bset->ineq[j][1]);
812                                 isl_int_mul(b, lower[1], bset->ineq[j][0]);
813                                 if (isl_int_lt(a, b))
814                                         isl_seq_cpy(lower, bset->ineq[j], 2);
815                         }
816                         if (upper && isl_int_is_neg(bset->ineq[j][1])) {
817                                 isl_int_mul(a, upper[0], bset->ineq[j][1]);
818                                 isl_int_mul(b, upper[1], bset->ineq[j][0]);
819                                 if (isl_int_gt(a, b))
820                                         isl_seq_cpy(upper, bset->ineq[j], 2);
821                         }
822                 }
823                 if (!has_lower)
824                         lower = NULL;
825                 if (!has_upper)
826                         upper = NULL;
827         }
828         isl_int_clear(a);
829         isl_int_clear(b);
830
831         hull = isl_basic_set_alloc(ctx, 0, 1, 0, 0, 2);
832         hull = isl_basic_set_set_rational(hull);
833         if (!hull)
834                 goto error;
835         if (lower) {
836                 k = isl_basic_set_alloc_inequality(hull);
837                 isl_seq_cpy(hull->ineq[k], lower, 2);
838         }
839         if (upper) {
840                 k = isl_basic_set_alloc_inequality(hull);
841                 isl_seq_cpy(hull->ineq[k], upper, 2);
842         }
843         hull = isl_basic_set_finalize(hull);
844         isl_set_free(set);
845         isl_mat_free(ctx, c);
846         return hull;
847 error:
848         isl_set_free(set);
849         isl_mat_free(ctx, c);
850         return NULL;
851 }
852
853 /* Project out final n dimensions using Fourier-Motzkin */
854 static struct isl_set *set_project_out(struct isl_ctx *ctx,
855         struct isl_set *set, unsigned n)
856 {
857         return isl_set_remove_dims(set, isl_set_n_dim(set) - n, n);
858 }
859
860 static struct isl_basic_set *convex_hull_0d(struct isl_set *set)
861 {
862         struct isl_basic_set *convex_hull;
863
864         if (!set)
865                 return NULL;
866
867         if (isl_set_is_empty(set))
868                 convex_hull = isl_basic_set_empty(isl_dim_copy(set->dim));
869         else
870                 convex_hull = isl_basic_set_universe(isl_dim_copy(set->dim));
871         isl_set_free(set);
872         return convex_hull;
873 }
874
875 /* Compute the convex hull of a pair of basic sets without any parameters or
876  * integer divisions using Fourier-Motzkin elimination.
877  * The convex hull is the set of all points that can be written as
878  * the sum of points from both basic sets (in homogeneous coordinates).
879  * We set up the constraints in a space with dimensions for each of
880  * the three sets and then project out the dimensions corresponding
881  * to the two original basic sets, retaining only those corresponding
882  * to the convex hull.
883  */
884 static struct isl_basic_set *convex_hull_pair(struct isl_basic_set *bset1,
885         struct isl_basic_set *bset2)
886 {
887         int i, j, k;
888         struct isl_basic_set *bset[2];
889         struct isl_basic_set *hull = NULL;
890         unsigned dim;
891
892         if (!bset1 || !bset2)
893                 goto error;
894
895         dim = isl_basic_set_n_dim(bset1);
896         hull = isl_basic_set_alloc(bset1->ctx, 0, 2 + 3 * dim, 0,
897                                 1 + dim + bset1->n_eq + bset2->n_eq,
898                                 2 + bset1->n_ineq + bset2->n_ineq);
899         bset[0] = bset1;
900         bset[1] = bset2;
901         for (i = 0; i < 2; ++i) {
902                 for (j = 0; j < bset[i]->n_eq; ++j) {
903                         k = isl_basic_set_alloc_equality(hull);
904                         if (k < 0)
905                                 goto error;
906                         isl_seq_clr(hull->eq[k], (i+1) * (1+dim));
907                         isl_seq_clr(hull->eq[k]+(i+2)*(1+dim), (1-i)*(1+dim));
908                         isl_seq_cpy(hull->eq[k]+(i+1)*(1+dim), bset[i]->eq[j],
909                                         1+dim);
910                 }
911                 for (j = 0; j < bset[i]->n_ineq; ++j) {
912                         k = isl_basic_set_alloc_inequality(hull);
913                         if (k < 0)
914                                 goto error;
915                         isl_seq_clr(hull->ineq[k], (i+1) * (1+dim));
916                         isl_seq_clr(hull->ineq[k]+(i+2)*(1+dim), (1-i)*(1+dim));
917                         isl_seq_cpy(hull->ineq[k]+(i+1)*(1+dim),
918                                         bset[i]->ineq[j], 1+dim);
919                 }
920                 k = isl_basic_set_alloc_inequality(hull);
921                 if (k < 0)
922                         goto error;
923                 isl_seq_clr(hull->ineq[k], 1+2+3*dim);
924                 isl_int_set_si(hull->ineq[k][(i+1)*(1+dim)], 1);
925         }
926         for (j = 0; j < 1+dim; ++j) {
927                 k = isl_basic_set_alloc_equality(hull);
928                 if (k < 0)
929                         goto error;
930                 isl_seq_clr(hull->eq[k], 1+2+3*dim);
931                 isl_int_set_si(hull->eq[k][j], -1);
932                 isl_int_set_si(hull->eq[k][1+dim+j], 1);
933                 isl_int_set_si(hull->eq[k][2*(1+dim)+j], 1);
934         }
935         hull = isl_basic_set_set_rational(hull);
936         hull = isl_basic_set_remove_dims(hull, dim, 2*(1+dim));
937         hull = isl_basic_set_convex_hull(hull);
938         isl_basic_set_free(bset1);
939         isl_basic_set_free(bset2);
940         return hull;
941 error:
942         isl_basic_set_free(bset1);
943         isl_basic_set_free(bset2);
944         isl_basic_set_free(hull);
945         return NULL;
946 }
947
948 /* Compute the convex hull of a set without any parameters or
949  * integer divisions using Fourier-Motzkin elimination.
950  * In each step, we combined two basic sets until only one
951  * basic set is left.
952  */
953 static struct isl_basic_set *uset_convex_hull_elim(struct isl_set *set)
954 {
955         struct isl_basic_set *convex_hull = NULL;
956
957         convex_hull = isl_set_copy_basic_set(set);
958         set = isl_set_drop_basic_set(set, convex_hull);
959         if (!set)
960                 goto error;
961         while (set->n > 0) {
962                 struct isl_basic_set *t;
963                 t = isl_set_copy_basic_set(set);
964                 if (!t)
965                         goto error;
966                 set = isl_set_drop_basic_set(set, t);
967                 if (!set)
968                         goto error;
969                 convex_hull = convex_hull_pair(convex_hull, t);
970         }
971         isl_set_free(set);
972         return convex_hull;
973 error:
974         isl_set_free(set);
975         isl_basic_set_free(convex_hull);
976         return NULL;
977 }
978
979 /* Compute an initial hull for wrapping containing a single initial
980  * facet by first computing bounds on the set and then using these
981  * bounds to construct an initial facet.
982  * This function is a remnant of an older implementation where the
983  * bounds were also used to check whether the set was bounded.
984  * Since this function will now only be called when we know the
985  * set to be bounded, the initial facet should probably be constructed 
986  * by simply using the coordinate directions instead.
987  */
988 static struct isl_basic_set *initial_hull(struct isl_basic_set *hull,
989         struct isl_set *set)
990 {
991         struct isl_mat *bounds = NULL;
992         unsigned dim;
993         int k;
994
995         if (!hull)
996                 goto error;
997         bounds = independent_bounds(set->ctx, set);
998         if (!bounds)
999                 goto error;
1000         isl_assert(set->ctx, bounds->n_row == isl_set_n_dim(set), goto error);
1001         bounds = initial_facet_constraint(set->ctx, set, bounds);
1002         if (!bounds)
1003                 goto error;
1004         k = isl_basic_set_alloc_inequality(hull);
1005         if (k < 0)
1006                 goto error;
1007         dim = isl_set_n_dim(set);
1008         isl_assert(set->ctx, 1 + dim == bounds->n_col, goto error);
1009         isl_seq_cpy(hull->ineq[k], bounds->row[0], bounds->n_col);
1010         isl_mat_free(set->ctx, bounds);
1011
1012         return hull;
1013 error:
1014         isl_basic_set_free(hull);
1015         isl_mat_free(set->ctx, bounds);
1016         return NULL;
1017 }
1018
1019 struct max_constraint {
1020         struct isl_mat *c;
1021         int             count;
1022         int             ineq;
1023 };
1024
1025 static int max_constraint_equal(const void *entry, const void *val)
1026 {
1027         struct max_constraint *a = (struct max_constraint *)entry;
1028         isl_int *b = (isl_int *)val;
1029
1030         return isl_seq_eq(a->c->row[0] + 1, b, a->c->n_col - 1);
1031 }
1032
1033 static void update_constraint(struct isl_ctx *ctx, struct isl_hash_table *table,
1034         isl_int *con, unsigned len, int n, int ineq)
1035 {
1036         struct isl_hash_table_entry *entry;
1037         struct max_constraint *c;
1038         uint32_t c_hash;
1039
1040         c_hash = isl_seq_hash(con + 1, len, isl_hash_init());
1041         entry = isl_hash_table_find(ctx, table, c_hash, max_constraint_equal,
1042                         con + 1, 0);
1043         if (!entry)
1044                 return;
1045         c = entry->data;
1046         if (c->count < n) {
1047                 isl_hash_table_remove(ctx, table, entry);
1048                 return;
1049         }
1050         c->count++;
1051         if (isl_int_gt(c->c->row[0][0], con[0]))
1052                 return;
1053         if (isl_int_eq(c->c->row[0][0], con[0])) {
1054                 if (ineq)
1055                         c->ineq = ineq;
1056                 return;
1057         }
1058         c->c = isl_mat_cow(ctx, c->c);
1059         isl_int_set(c->c->row[0][0], con[0]);
1060         c->ineq = ineq;
1061 }
1062
1063 /* Check whether the constraint hash table "table" constains the constraint
1064  * "con".
1065  */
1066 static int has_constraint(struct isl_ctx *ctx, struct isl_hash_table *table,
1067         isl_int *con, unsigned len, int n)
1068 {
1069         struct isl_hash_table_entry *entry;
1070         struct max_constraint *c;
1071         uint32_t c_hash;
1072
1073         c_hash = isl_seq_hash(con + 1, len, isl_hash_init());
1074         entry = isl_hash_table_find(ctx, table, c_hash, max_constraint_equal,
1075                         con + 1, 0);
1076         if (!entry)
1077                 return 0;
1078         c = entry->data;
1079         if (c->count < n)
1080                 return 0;
1081         return isl_int_eq(c->c->row[0][0], con[0]);
1082 }
1083
1084 /* Check for inequality constraints of a basic set without equalities
1085  * such that the same or more stringent copies of the constraint appear
1086  * in all of the basic sets.  Such constraints are necessarily facet
1087  * constraints of the convex hull.
1088  *
1089  * If the resulting basic set is by chance identical to one of
1090  * the basic sets in "set", then we know that this basic set contains
1091  * all other basic sets and is therefore the convex hull of set.
1092  * In this case we set *is_hull to 1.
1093  */
1094 static struct isl_basic_set *common_constraints(struct isl_basic_set *hull,
1095         struct isl_set *set, int *is_hull)
1096 {
1097         int i, j, s, n;
1098         int min_constraints;
1099         int best;
1100         struct max_constraint *constraints = NULL;
1101         struct isl_hash_table *table = NULL;
1102         unsigned total;
1103
1104         *is_hull = 0;
1105
1106         for (i = 0; i < set->n; ++i)
1107                 if (set->p[i]->n_eq == 0)
1108                         break;
1109         if (i >= set->n)
1110                 return hull;
1111         min_constraints = set->p[i]->n_ineq;
1112         best = i;
1113         for (i = best + 1; i < set->n; ++i) {
1114                 if (set->p[i]->n_eq != 0)
1115                         continue;
1116                 if (set->p[i]->n_ineq >= min_constraints)
1117                         continue;
1118                 min_constraints = set->p[i]->n_ineq;
1119                 best = i;
1120         }
1121         constraints = isl_calloc_array(hull->ctx, struct max_constraint,
1122                                         min_constraints);
1123         if (!constraints)
1124                 return hull;
1125         table = isl_alloc_type(hull->ctx, struct isl_hash_table);
1126         if (isl_hash_table_init(hull->ctx, table, min_constraints))
1127                 goto error;
1128
1129         total = isl_dim_total(set->dim);
1130         for (i = 0; i < set->p[best]->n_ineq; ++i) {
1131                 constraints[i].c = isl_mat_sub_alloc(hull->ctx,
1132                         set->p[best]->ineq + i, 0, 1, 0, 1 + total);
1133                 if (!constraints[i].c)
1134                         goto error;
1135                 constraints[i].ineq = 1;
1136         }
1137         for (i = 0; i < min_constraints; ++i) {
1138                 struct isl_hash_table_entry *entry;
1139                 uint32_t c_hash;
1140                 c_hash = isl_seq_hash(constraints[i].c->row[0] + 1, total,
1141                                         isl_hash_init());
1142                 entry = isl_hash_table_find(hull->ctx, table, c_hash,
1143                         max_constraint_equal, constraints[i].c->row[0] + 1, 1);
1144                 if (!entry)
1145                         goto error;
1146                 isl_assert(hull->ctx, !entry->data, goto error);
1147                 entry->data = &constraints[i];
1148         }
1149
1150         n = 0;
1151         for (s = 0; s < set->n; ++s) {
1152                 if (s == best)
1153                         continue;
1154
1155                 for (i = 0; i < set->p[s]->n_eq; ++i) {
1156                         isl_int *eq = set->p[s]->eq[i];
1157                         for (j = 0; j < 2; ++j) {
1158                                 isl_seq_neg(eq, eq, 1 + total);
1159                                 update_constraint(hull->ctx, table,
1160                                                             eq, total, n, 0);
1161                         }
1162                 }
1163                 for (i = 0; i < set->p[s]->n_ineq; ++i) {
1164                         isl_int *ineq = set->p[s]->ineq[i];
1165                         update_constraint(hull->ctx, table, ineq, total, n,
1166                                 set->p[s]->n_eq == 0);
1167                 }
1168                 ++n;
1169         }
1170
1171         for (i = 0; i < min_constraints; ++i) {
1172                 if (constraints[i].count < n)
1173                         continue;
1174                 if (!constraints[i].ineq)
1175                         continue;
1176                 j = isl_basic_set_alloc_inequality(hull);
1177                 if (j < 0)
1178                         goto error;
1179                 isl_seq_cpy(hull->ineq[j], constraints[i].c->row[0], 1 + total);
1180         }
1181
1182         for (s = 0; s < set->n; ++s) {
1183                 if (set->p[s]->n_eq)
1184                         continue;
1185                 if (set->p[s]->n_ineq != hull->n_ineq)
1186                         continue;
1187                 for (i = 0; i < set->p[s]->n_ineq; ++i) {
1188                         isl_int *ineq = set->p[s]->ineq[i];
1189                         if (!has_constraint(hull->ctx, table, ineq, total, n))
1190                                 break;
1191                 }
1192                 if (i == set->p[s]->n_ineq)
1193                         *is_hull = 1;
1194         }
1195
1196         isl_hash_table_clear(table);
1197         for (i = 0; i < min_constraints; ++i)
1198                 isl_mat_free(hull->ctx, constraints[i].c);
1199         free(constraints);
1200         free(table);
1201         return hull;
1202 error:
1203         isl_hash_table_clear(table);
1204         free(table);
1205         if (constraints)
1206                 for (i = 0; i < min_constraints; ++i)
1207                         isl_mat_free(hull->ctx, constraints[i].c);
1208         free(constraints);
1209         return hull;
1210 }
1211
1212 /* Create a template for the convex hull of "set" and fill it up
1213  * obvious facet constraints, if any.  If the result happens to
1214  * be the convex hull of "set" then *is_hull is set to 1.
1215  */
1216 static struct isl_basic_set *proto_hull(struct isl_set *set, int *is_hull)
1217 {
1218         struct isl_basic_set *hull;
1219         unsigned n_ineq;
1220         int i;
1221
1222         n_ineq = 1;
1223         for (i = 0; i < set->n; ++i) {
1224                 n_ineq += set->p[i]->n_eq;
1225                 n_ineq += set->p[i]->n_ineq;
1226         }
1227         hull = isl_basic_set_alloc_dim(isl_dim_copy(set->dim), 0, 0, n_ineq);
1228         hull = isl_basic_set_set_rational(hull);
1229         if (!hull)
1230                 return NULL;
1231         return common_constraints(hull, set, is_hull);
1232 }
1233
1234 static struct isl_basic_set *uset_convex_hull_wrap(struct isl_set *set)
1235 {
1236         struct isl_basic_set *hull;
1237         int is_hull;
1238
1239         hull = proto_hull(set, &is_hull);
1240         if (hull && !is_hull) {
1241                 if (hull->n_ineq == 0)
1242                         hull = initial_hull(hull, set);
1243                 hull = extend(hull, set);
1244         }
1245         isl_set_free(set);
1246
1247         return hull;
1248 }
1249
1250 static int isl_basic_set_is_bounded(struct isl_basic_set *bset)
1251 {
1252         struct isl_tab *tab;
1253         int bounded;
1254
1255         tab = isl_tab_from_recession_cone((struct isl_basic_map *)bset);
1256         bounded = isl_tab_cone_is_bounded(bset->ctx, tab);
1257         isl_tab_free(bset->ctx, tab);
1258         return bounded;
1259 }
1260
1261 static int isl_set_is_bounded(struct isl_set *set)
1262 {
1263         int i;
1264
1265         for (i = 0; i < set->n; ++i) {
1266                 int bounded = isl_basic_set_is_bounded(set->p[i]);
1267                 if (!bounded || bounded < 0)
1268                         return bounded;
1269         }
1270         return 1;
1271 }
1272
1273 /* Compute the convex hull of a set without any parameters or
1274  * integer divisions.  Depending on whether the set is bounded,
1275  * we pass control to the wrapping based convex hull or
1276  * the Fourier-Motzkin elimination based convex hull.
1277  * We also handle a few special cases before checking the boundedness.
1278  */
1279 static struct isl_basic_set *uset_convex_hull(struct isl_set *set)
1280 {
1281         int i;
1282         struct isl_basic_set *convex_hull = NULL;
1283
1284         if (isl_set_n_dim(set) == 0)
1285                 return convex_hull_0d(set);
1286
1287         set = isl_set_set_rational(set);
1288
1289         if (!set)
1290                 goto error;
1291         set = isl_set_normalize(set);
1292         if (!set)
1293                 return NULL;
1294         if (set->n == 1) {
1295                 convex_hull = isl_basic_set_copy(set->p[0]);
1296                 isl_set_free(set);
1297                 return convex_hull;
1298         }
1299         if (isl_set_n_dim(set) == 1)
1300                 return convex_hull_1d(set->ctx, set);
1301
1302         if (!isl_set_is_bounded(set))
1303                 return uset_convex_hull_elim(set);
1304
1305         return uset_convex_hull_wrap(set);
1306 error:
1307         isl_set_free(set);
1308         isl_basic_set_free(convex_hull);
1309         return NULL;
1310 }
1311
1312 /* This is the core procedure, where "set" is a "pure" set, i.e.,
1313  * without parameters or divs and where the convex hull of set is
1314  * known to be full-dimensional.
1315  */
1316 static struct isl_basic_set *uset_convex_hull_wrap_bounded(struct isl_set *set)
1317 {
1318         int i;
1319         struct isl_basic_set *convex_hull = NULL;
1320
1321         if (isl_set_n_dim(set) == 0) {
1322                 convex_hull = isl_basic_set_universe(isl_dim_copy(set->dim));
1323                 isl_set_free(set);
1324                 convex_hull = isl_basic_set_set_rational(convex_hull);
1325                 return convex_hull;
1326         }
1327
1328         set = isl_set_set_rational(set);
1329
1330         if (!set)
1331                 goto error;
1332         set = isl_set_normalize(set);
1333         if (!set)
1334                 goto error;
1335         if (set->n == 1) {
1336                 convex_hull = isl_basic_set_copy(set->p[0]);
1337                 isl_set_free(set);
1338                 return convex_hull;
1339         }
1340         if (isl_set_n_dim(set) == 1)
1341                 return convex_hull_1d(set->ctx, set);
1342
1343         return uset_convex_hull_wrap(set);
1344 error:
1345         isl_set_free(set);
1346         return NULL;
1347 }
1348
1349 /* Compute the convex hull of set "set" with affine hull "affine_hull",
1350  * We first remove the equalities (transforming the set), compute the
1351  * convex hull of the transformed set and then add the equalities back
1352  * (after performing the inverse transformation.
1353  */
1354 static struct isl_basic_set *modulo_affine_hull(struct isl_ctx *ctx,
1355         struct isl_set *set, struct isl_basic_set *affine_hull)
1356 {
1357         struct isl_mat *T;
1358         struct isl_mat *T2;
1359         struct isl_basic_set *dummy;
1360         struct isl_basic_set *convex_hull;
1361
1362         dummy = isl_basic_set_remove_equalities(
1363                         isl_basic_set_copy(affine_hull), &T, &T2);
1364         if (!dummy)
1365                 goto error;
1366         isl_basic_set_free(dummy);
1367         set = isl_set_preimage(set, T);
1368         convex_hull = uset_convex_hull(set);
1369         convex_hull = isl_basic_set_preimage(convex_hull, T2);
1370         convex_hull = isl_basic_set_intersect(convex_hull, affine_hull);
1371         return convex_hull;
1372 error:
1373         isl_basic_set_free(affine_hull);
1374         isl_set_free(set);
1375         return NULL;
1376 }
1377
1378 /* Compute the convex hull of a map.
1379  *
1380  * The implementation was inspired by "Extended Convex Hull" by Fukuda et al.,
1381  * specifically, the wrapping of facets to obtain new facets.
1382  */
1383 struct isl_basic_map *isl_map_convex_hull(struct isl_map *map)
1384 {
1385         struct isl_basic_set *bset;
1386         struct isl_basic_map *model = NULL;
1387         struct isl_basic_set *affine_hull = NULL;
1388         struct isl_basic_map *convex_hull = NULL;
1389         struct isl_set *set = NULL;
1390         struct isl_ctx *ctx;
1391
1392         if (!map)
1393                 goto error;
1394
1395         ctx = map->ctx;
1396         if (map->n == 0) {
1397                 convex_hull = isl_basic_map_empty_like_map(map);
1398                 isl_map_free(map);
1399                 return convex_hull;
1400         }
1401
1402         map = isl_map_align_divs(map);
1403         model = isl_basic_map_copy(map->p[0]);
1404         set = isl_map_underlying_set(map);
1405         if (!set)
1406                 goto error;
1407
1408         affine_hull = isl_set_affine_hull(isl_set_copy(set));
1409         if (!affine_hull)
1410                 goto error;
1411         if (affine_hull->n_eq != 0)
1412                 bset = modulo_affine_hull(ctx, set, affine_hull);
1413         else {
1414                 isl_basic_set_free(affine_hull);
1415                 bset = uset_convex_hull(set);
1416         }
1417
1418         convex_hull = isl_basic_map_overlying_set(bset, model);
1419
1420         ISL_F_CLR(convex_hull, ISL_BASIC_MAP_RATIONAL);
1421         return convex_hull;
1422 error:
1423         isl_set_free(set);
1424         isl_basic_map_free(model);
1425         return NULL;
1426 }
1427
1428 struct isl_basic_set *isl_set_convex_hull(struct isl_set *set)
1429 {
1430         return (struct isl_basic_set *)
1431                 isl_map_convex_hull((struct isl_map *)set);
1432 }
1433
1434 struct sh_data_entry {
1435         struct isl_hash_table   *table;
1436         struct isl_tab          *tab;
1437 };
1438
1439 /* Holds the data needed during the simple hull computation.
1440  * In particular,
1441  *      n               the number of basic sets in the original set
1442  *      hull_table      a hash table of already computed constraints
1443  *                      in the simple hull
1444  *      p               for each basic set,
1445  *              table           a hash table of the constraints
1446  *              tab             the tableau corresponding to the basic set
1447  */
1448 struct sh_data {
1449         struct isl_ctx          *ctx;
1450         unsigned                n;
1451         struct isl_hash_table   *hull_table;
1452         struct sh_data_entry    p[0];
1453 };
1454
1455 static void sh_data_free(struct sh_data *data)
1456 {
1457         int i;
1458
1459         if (!data)
1460                 return;
1461         isl_hash_table_free(data->ctx, data->hull_table);
1462         for (i = 0; i < data->n; ++i) {
1463                 isl_hash_table_free(data->ctx, data->p[i].table);
1464                 isl_tab_free(data->ctx, data->p[i].tab);
1465         }
1466         free(data);
1467 }
1468
1469 struct ineq_cmp_data {
1470         unsigned        len;
1471         isl_int         *p;
1472 };
1473
1474 static int has_ineq(const void *entry, const void *val)
1475 {
1476         isl_int *row = (isl_int *)entry;
1477         struct ineq_cmp_data *v = (struct ineq_cmp_data *)val;
1478
1479         return isl_seq_eq(row + 1, v->p + 1, v->len) ||
1480                isl_seq_is_neg(row + 1, v->p + 1, v->len);
1481 }
1482
1483 static int hash_ineq(struct isl_ctx *ctx, struct isl_hash_table *table,
1484                         isl_int *ineq, unsigned len)
1485 {
1486         uint32_t c_hash;
1487         struct ineq_cmp_data v;
1488         struct isl_hash_table_entry *entry;
1489
1490         v.len = len;
1491         v.p = ineq;
1492         c_hash = isl_seq_hash(ineq + 1, len, isl_hash_init());
1493         entry = isl_hash_table_find(ctx, table, c_hash, has_ineq, &v, 1);
1494         if (!entry)
1495                 return - 1;
1496         entry->data = ineq;
1497         return 0;
1498 }
1499
1500 /* Fill hash table "table" with the constraints of "bset".
1501  * Equalities are added as two inequalities.
1502  * The value in the hash table is a pointer to the (in)equality of "bset".
1503  */
1504 static int hash_basic_set(struct isl_hash_table *table,
1505                                 struct isl_basic_set *bset)
1506 {
1507         int i, j;
1508         unsigned dim = isl_basic_set_total_dim(bset);
1509
1510         for (i = 0; i < bset->n_eq; ++i) {
1511                 for (j = 0; j < 2; ++j) {
1512                         isl_seq_neg(bset->eq[i], bset->eq[i], 1 + dim);
1513                         if (hash_ineq(bset->ctx, table, bset->eq[i], dim) < 0)
1514                                 return -1;
1515                 }
1516         }
1517         for (i = 0; i < bset->n_ineq; ++i) {
1518                 if (hash_ineq(bset->ctx, table, bset->ineq[i], dim) < 0)
1519                         return -1;
1520         }
1521         return 0;
1522 }
1523
1524 static struct sh_data *sh_data_alloc(struct isl_set *set, unsigned n_ineq)
1525 {
1526         struct sh_data *data;
1527         int i;
1528
1529         data = isl_calloc(set->ctx, struct sh_data,
1530                 sizeof(struct sh_data) + set->n * sizeof(struct sh_data_entry));
1531         if (!data)
1532                 return NULL;
1533         data->ctx = set->ctx;
1534         data->n = set->n;
1535         data->hull_table = isl_hash_table_alloc(set->ctx, n_ineq);
1536         if (!data->hull_table)
1537                 goto error;
1538         for (i = 0; i < set->n; ++i) {
1539                 data->p[i].table = isl_hash_table_alloc(set->ctx,
1540                                     2 * set->p[i]->n_eq + set->p[i]->n_ineq);
1541                 if (!data->p[i].table)
1542                         goto error;
1543                 if (hash_basic_set(data->p[i].table, set->p[i]) < 0)
1544                         goto error;
1545         }
1546         return data;
1547 error:
1548         sh_data_free(data);
1549         return NULL;
1550 }
1551
1552 /* Check if inequality "ineq" is a bound for basic set "j" or if
1553  * it can be relaxed (by increasing the constant term) to become
1554  * a bound for that basic set.  In the latter case, the constant
1555  * term is updated.
1556  * Return 1 if "ineq" is a bound
1557  *        0 if "ineq" may attain arbitrarily small values on basic set "j"
1558  *       -1 if some error occurred
1559  */
1560 static int is_bound(struct sh_data *data, struct isl_set *set, int j,
1561                         isl_int *ineq)
1562 {
1563         enum isl_lp_result res;
1564         isl_int opt;
1565
1566         if (!data->p[j].tab) {
1567                 data->p[j].tab = isl_tab_from_basic_set(set->p[j]);
1568                 if (!data->p[j].tab)
1569                         return -1;
1570         }
1571
1572         isl_int_init(opt);
1573
1574         res = isl_tab_min(data->ctx, data->p[j].tab, ineq, data->ctx->one,
1575                                 &opt, NULL);
1576         if (res == isl_lp_ok && isl_int_is_neg(opt))
1577                 isl_int_sub(ineq[0], ineq[0], opt);
1578
1579         isl_int_clear(opt);
1580
1581         return res == isl_lp_ok ? 1 :
1582                res == isl_lp_unbounded ? 0 : -1;
1583 }
1584
1585 /* Check if inequality "ineq" from basic set "i" can be relaxed to
1586  * become a bound on the whole set.  If so, add the (relaxed) inequality
1587  * to "hull".
1588  *
1589  * We first check if "hull" already contains a translate of the inequality.
1590  * If so, we are done.
1591  * Then, we check if any of the previous basic sets contains a translate
1592  * of the inequality.  If so, then we have already considered this
1593  * inequality and we are done.
1594  * Otherwise, for each basic set other than "i", we check if the inequality
1595  * is a bound on the basic set.
1596  * For previous basic sets, we know that they do not contain a translate
1597  * of the inequality, so we directly call is_bound.
1598  * For following basic sets, we first check if a translate of the
1599  * inequality appears in its description and if so directly update
1600  * the inequality accordingly.
1601  */
1602 static struct isl_basic_set *add_bound(struct isl_basic_set *hull,
1603         struct sh_data *data, struct isl_set *set, int i, isl_int *ineq)
1604 {
1605         uint32_t c_hash;
1606         struct ineq_cmp_data v;
1607         struct isl_hash_table_entry *entry;
1608         int j, k;
1609
1610         if (!hull)
1611                 return NULL;
1612
1613         v.len = isl_basic_set_total_dim(hull);
1614         v.p = ineq;
1615         c_hash = isl_seq_hash(ineq + 1, v.len, isl_hash_init());
1616
1617         entry = isl_hash_table_find(hull->ctx, data->hull_table, c_hash,
1618                                         has_ineq, &v, 0);
1619         if (entry)
1620                 return hull;
1621
1622         for (j = 0; j < i; ++j) {
1623                 entry = isl_hash_table_find(hull->ctx, data->p[j].table,
1624                                                 c_hash, has_ineq, &v, 0);
1625                 if (entry)
1626                         break;
1627         }
1628         if (j < i)
1629                 return hull;
1630
1631         k = isl_basic_set_alloc_inequality(hull);
1632         isl_seq_cpy(hull->ineq[k], ineq, 1 + v.len);
1633         if (k < 0)
1634                 goto error;
1635
1636         for (j = 0; j < i; ++j) {
1637                 int bound;
1638                 bound = is_bound(data, set, j, hull->ineq[k]);
1639                 if (bound < 0)
1640                         goto error;
1641                 if (!bound)
1642                         break;
1643         }
1644         if (j < i) {
1645                 isl_basic_set_free_inequality(hull, 1);
1646                 return hull;
1647         }
1648
1649         for (j = i + 1; j < set->n; ++j) {
1650                 int bound, neg;
1651                 isl_int *ineq_j;
1652                 entry = isl_hash_table_find(hull->ctx, data->p[j].table,
1653                                                 c_hash, has_ineq, &v, 0);
1654                 if (entry) {
1655                         ineq_j = entry->data;
1656                         neg = isl_seq_is_neg(ineq_j + 1,
1657                                              hull->ineq[k] + 1, v.len);
1658                         if (neg)
1659                                 isl_int_neg(ineq_j[0], ineq_j[0]);
1660                         if (isl_int_gt(ineq_j[0], hull->ineq[k][0]))
1661                                 isl_int_set(hull->ineq[k][0], ineq_j[0]);
1662                         if (neg)
1663                                 isl_int_neg(ineq_j[0], ineq_j[0]);
1664                         continue;
1665                 }
1666                 bound = is_bound(data, set, j, hull->ineq[k]);
1667                 if (bound < 0)
1668                         goto error;
1669                 if (!bound)
1670                         break;
1671         }
1672         if (j < set->n) {
1673                 isl_basic_set_free_inequality(hull, 1);
1674                 return hull;
1675         }
1676
1677         entry = isl_hash_table_find(hull->ctx, data->hull_table, c_hash,
1678                                         has_ineq, &v, 1);
1679         if (!entry)
1680                 goto error;
1681         entry->data = hull->ineq[k];
1682
1683         return hull;
1684 error:
1685         isl_basic_set_free(hull);
1686         return NULL;
1687 }
1688
1689 /* Check if any inequality from basic set "i" can be relaxed to
1690  * become a bound on the whole set.  If so, add the (relaxed) inequality
1691  * to "hull".
1692  */
1693 static struct isl_basic_set *add_bounds(struct isl_basic_set *bset,
1694         struct sh_data *data, struct isl_set *set, int i)
1695 {
1696         int j, k;
1697         unsigned dim = isl_basic_set_total_dim(bset);
1698
1699         for (j = 0; j < set->p[i]->n_eq; ++j) {
1700                 for (k = 0; k < 2; ++k) {
1701                         isl_seq_neg(set->p[i]->eq[j], set->p[i]->eq[j], 1+dim);
1702                         add_bound(bset, data, set, i, set->p[i]->eq[j]);
1703                 }
1704         }
1705         for (j = 0; j < set->p[i]->n_ineq; ++j)
1706                 add_bound(bset, data, set, i, set->p[i]->ineq[j]);
1707         return bset;
1708 }
1709
1710 /* Compute a superset of the convex hull of set that is described
1711  * by only translates of the constraints in the constituents of set.
1712  */
1713 static struct isl_basic_set *uset_simple_hull(struct isl_set *set)
1714 {
1715         struct sh_data *data = NULL;
1716         struct isl_basic_set *hull = NULL;
1717         unsigned n_ineq;
1718         int i, j;
1719
1720         if (!set)
1721                 return NULL;
1722
1723         n_ineq = 0;
1724         for (i = 0; i < set->n; ++i) {
1725                 if (!set->p[i])
1726                         goto error;
1727                 n_ineq += 2 * set->p[i]->n_eq + set->p[i]->n_ineq;
1728         }
1729
1730         hull = isl_basic_set_alloc_dim(isl_dim_copy(set->dim), 0, 0, n_ineq);
1731         if (!hull)
1732                 goto error;
1733
1734         data = sh_data_alloc(set, n_ineq);
1735         if (!data)
1736                 goto error;
1737
1738         for (i = 0; i < set->n; ++i)
1739                 hull = add_bounds(hull, data, set, i);
1740
1741         sh_data_free(data);
1742         isl_set_free(set);
1743
1744         return hull;
1745 error:
1746         sh_data_free(data);
1747         isl_basic_set_free(hull);
1748         isl_set_free(set);
1749         return NULL;
1750 }
1751
1752 /* Compute a superset of the convex hull of map that is described
1753  * by only translates of the constraints in the constituents of map.
1754  */
1755 struct isl_basic_map *isl_map_simple_hull(struct isl_map *map)
1756 {
1757         struct isl_set *set = NULL;
1758         struct isl_basic_map *model = NULL;
1759         struct isl_basic_map *hull;
1760         struct isl_basic_map *affine_hull;
1761         struct isl_basic_set *bset = NULL;
1762
1763         if (!map)
1764                 return NULL;
1765         if (map->n == 0) {
1766                 hull = isl_basic_map_empty_like_map(map);
1767                 isl_map_free(map);
1768                 return hull;
1769         }
1770         if (map->n == 1) {
1771                 hull = isl_basic_map_copy(map->p[0]);
1772                 isl_map_free(map);
1773                 return hull;
1774         }
1775
1776         map = isl_map_detect_equalities(map);
1777         affine_hull = isl_map_affine_hull(isl_map_copy(map));
1778         map = isl_map_align_divs(map);
1779         model = isl_basic_map_copy(map->p[0]);
1780
1781         set = isl_map_underlying_set(map);
1782
1783         bset = uset_simple_hull(set);
1784
1785         hull = isl_basic_map_overlying_set(bset, model);
1786
1787         hull = isl_basic_map_intersect(hull, affine_hull);
1788         hull = isl_basic_map_convex_hull(hull);
1789         ISL_F_SET(hull, ISL_BASIC_MAP_NO_IMPLICIT);
1790         ISL_F_SET(hull, ISL_BASIC_MAP_ALL_EQUALITIES);
1791
1792         return hull;
1793 }
1794
1795 struct isl_basic_set *isl_set_simple_hull(struct isl_set *set)
1796 {
1797         return (struct isl_basic_set *)
1798                 isl_map_simple_hull((struct isl_map *)set);
1799 }
1800
1801 /* Given a set "set", return parametric bounds on the dimension "dim".
1802  */
1803 static struct isl_basic_set *set_bounds(struct isl_set *set, int dim)
1804 {
1805         unsigned set_dim = isl_set_dim(set, isl_dim_set);
1806         set = isl_set_copy(set);
1807         set = isl_set_eliminate_dims(set, dim + 1, set_dim - (dim + 1));
1808         set = isl_set_eliminate_dims(set, 0, dim);
1809         return isl_set_convex_hull(set);
1810 }
1811
1812 /* Computes a "simple hull" and then check if each dimension in the
1813  * resulting hull is bounded by a symbolic constant.  If not, the
1814  * hull is intersected with the corresponding bounds on the whole set.
1815  */
1816 struct isl_basic_set *isl_set_bounded_simple_hull(struct isl_set *set)
1817 {
1818         int i, j;
1819         struct isl_basic_set *hull;
1820         unsigned nparam, left;
1821         int removed_divs = 0;
1822
1823         hull = isl_set_simple_hull(isl_set_copy(set));
1824         if (!hull)
1825                 goto error;
1826
1827         nparam = isl_basic_set_dim(hull, isl_dim_param);
1828         for (i = 0; i < isl_basic_set_dim(hull, isl_dim_set); ++i) {
1829                 int lower = 0, upper = 0;
1830                 struct isl_basic_set *bounds;
1831
1832                 left = isl_basic_set_total_dim(hull) - nparam - i - 1;
1833                 for (j = 0; j < hull->n_eq; ++j) {
1834                         if (isl_int_is_zero(hull->eq[j][1 + nparam + i]))
1835                                 continue;
1836                         if (isl_seq_first_non_zero(hull->eq[j]+1+nparam+i+1,
1837                                                     left) == -1)
1838                                 break;
1839                 }
1840                 if (j < hull->n_eq)
1841                         continue;
1842
1843                 for (j = 0; j < hull->n_ineq; ++j) {
1844                         if (isl_int_is_zero(hull->ineq[j][1 + nparam + i]))
1845                                 continue;
1846                         if (isl_seq_first_non_zero(hull->ineq[j]+1+nparam+i+1,
1847                                                     left) != -1 ||
1848                             isl_seq_first_non_zero(hull->ineq[j]+1+nparam,
1849                                                     i) != -1)
1850                                 continue;
1851                         if (isl_int_is_pos(hull->ineq[j][1 + nparam + i]))
1852                                 lower = 1;
1853                         else
1854                                 upper = 1;
1855                         if (lower && upper)
1856                                 break;
1857                 }
1858
1859                 if (lower && upper)
1860                         continue;
1861
1862                 if (!removed_divs) {
1863                         set = isl_set_remove_divs(set);
1864                         if (!set)
1865                                 goto error;
1866                         removed_divs = 1;
1867                 }
1868                 bounds = set_bounds(set, i);
1869                 hull = isl_basic_set_intersect(hull, bounds);
1870                 if (!hull)
1871                         goto error;
1872         }
1873
1874         isl_set_free(set);
1875         return hull;
1876 error:
1877         isl_set_free(set);
1878         return NULL;
1879 }