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