isl_tab_pip: keep cache of partial solutions
[platform/upstream/isl.git] / isl_tab_pip.c
1 #include "isl_map_private.h"
2 #include "isl_seq.h"
3 #include "isl_tab.h"
4 #include "isl_sample.h"
5
6 /*
7  * The implementation of parametric integer linear programming in this file
8  * was inspired by the paper "Parametric Integer Programming" and the
9  * report "Solving systems of affine (in)equalities" by Paul Feautrier
10  * (and others).
11  *
12  * The strategy used for obtaining a feasible solution is different
13  * from the one used in isl_tab.c.  In particular, in isl_tab.c,
14  * upon finding a constraint that is not yet satisfied, we pivot
15  * in a row that increases the constant term of row holding the
16  * constraint, making sure the sample solution remains feasible
17  * for all the constraints it already satisfied.
18  * Here, we always pivot in the row holding the constraint,
19  * choosing a column that induces the lexicographically smallest
20  * increment to the sample solution.
21  *
22  * By starting out from a sample value that is lexicographically
23  * smaller than any integer point in the problem space, the first
24  * feasible integer sample point we find will also be the lexicographically
25  * smallest.  If all variables can be assumed to be non-negative,
26  * then the initial sample value may be chosen equal to zero.
27  * However, we will not make this assumption.  Instead, we apply
28  * the "big parameter" trick.  Any variable x is then not directly
29  * used in the tableau, but instead it its represented by another
30  * variable x' = M + x, where M is an arbitrarily large (positive)
31  * value.  x' is therefore always non-negative, whatever the value of x.
32  * Taking as initial smaple value x' = 0 corresponds to x = -M,
33  * which is always smaller than any possible value of x.
34  *
35  * The big parameter trick is used in the main tableau and
36  * also in the context tableau if isl_context_lex is used.
37  * In this case, each tableaus has its own big parameter.
38  * Before doing any real work, we check if all the parameters
39  * happen to be non-negative.  If so, we drop the column corresponding
40  * to M from the initial context tableau.
41  * If isl_context_gbr is used, then the big parameter trick is only
42  * used in the main tableau.
43  */
44
45 struct isl_context;
46 struct isl_context_op {
47         /* detect nonnegative parameters in context and mark them in tab */
48         struct isl_tab *(*detect_nonnegative_parameters)(
49                         struct isl_context *context, struct isl_tab *tab);
50         /* return temporary reference to basic set representation of context */
51         struct isl_basic_set *(*peek_basic_set)(struct isl_context *context);
52         /* return temporary reference to tableau representation of context */
53         struct isl_tab *(*peek_tab)(struct isl_context *context);
54         /* add equality; check is 1 if eq may not be valid;
55          * update is 1 if we may want to call ineq_sign on context later.
56          */
57         void (*add_eq)(struct isl_context *context, isl_int *eq,
58                         int check, int update);
59         /* add inequality; check is 1 if ineq may not be valid;
60          * update is 1 if we may want to call ineq_sign on context later.
61          */
62         void (*add_ineq)(struct isl_context *context, isl_int *ineq,
63                         int check, int update);
64         /* check sign of ineq based on previous information.
65          * strict is 1 if saturation should be treated as a positive sign.
66          */
67         enum isl_tab_row_sign (*ineq_sign)(struct isl_context *context,
68                         isl_int *ineq, int strict);
69         /* check if inequality maintains feasibility */
70         int (*test_ineq)(struct isl_context *context, isl_int *ineq);
71         /* return index of a div that corresponds to "div" */
72         int (*get_div)(struct isl_context *context, struct isl_tab *tab,
73                         struct isl_vec *div);
74         /* add div "div" to context and return index and non-negativity */
75         int (*add_div)(struct isl_context *context, struct isl_vec *div,
76                         int *nonneg);
77         int (*detect_equalities)(struct isl_context *context,
78                         struct isl_tab *tab);
79         /* return row index of "best" split */
80         int (*best_split)(struct isl_context *context, struct isl_tab *tab);
81         /* check if context has already been determined to be empty */
82         int (*is_empty)(struct isl_context *context);
83         /* check if context is still usable */
84         int (*is_ok)(struct isl_context *context);
85         /* save a copy/snapshot of context */
86         void *(*save)(struct isl_context *context);
87         /* restore saved context */
88         void (*restore)(struct isl_context *context, void *);
89         /* invalidate context */
90         void (*invalidate)(struct isl_context *context);
91         /* free context */
92         void (*free)(struct isl_context *context);
93 };
94
95 struct isl_context {
96         struct isl_context_op *op;
97 };
98
99 struct isl_context_lex {
100         struct isl_context context;
101         struct isl_tab *tab;
102 };
103
104 struct isl_partial_sol {
105         int level;
106         struct isl_basic_set *dom;
107         struct isl_mat *M;
108
109         struct isl_partial_sol *next;
110 };
111
112 struct isl_sol;
113 struct isl_sol_callback {
114         struct isl_tab_callback callback;
115         struct isl_sol *sol;
116 };
117
118 /* isl_sol is an interface for constructing a solution to
119  * a parametric integer linear programming problem.
120  * Every time the algorithm reaches a state where a solution
121  * can be read off from the tableau (including cases where the tableau
122  * is empty), the function "add" is called on the isl_sol passed
123  * to find_solutions_main.
124  *
125  * The context tableau is owned by isl_sol and is updated incrementally.
126  *
127  * There are currently two implementations of this interface,
128  * isl_sol_map, which simply collects the solutions in an isl_map
129  * and (optionally) the parts of the context where there is no solution
130  * in an isl_set, and
131  * isl_sol_for, which calls a user-defined function for each part of
132  * the solution.
133  */
134 struct isl_sol {
135         int error;
136         int rational;
137         int level;
138         int max;
139         int n_out;
140         struct isl_context *context;
141         struct isl_partial_sol *partial;
142         void (*add)(struct isl_sol *sol,
143                             struct isl_basic_set *dom, struct isl_mat *M);
144         void (*add_empty)(struct isl_sol *sol, struct isl_basic_set *bset);
145         void (*free)(struct isl_sol *sol);
146         struct isl_sol_callback dec_level;
147 };
148
149 static void sol_free(struct isl_sol *sol)
150 {
151         struct isl_partial_sol *partial, *next;
152         if (!sol)
153                 return;
154         for (partial = sol->partial; partial; partial = next) {
155                 next = partial->next;
156                 isl_basic_set_free(partial->dom);
157                 isl_mat_free(partial->M);
158                 free(partial);
159         }
160         sol->free(sol);
161 }
162
163 /* Push a partial solution represented by a domain and mapping M
164  * onto the stack of partial solutions.
165  */
166 static void sol_push_sol(struct isl_sol *sol,
167         struct isl_basic_set *dom, struct isl_mat *M)
168 {
169         struct isl_partial_sol *partial;
170
171         if (sol->error || !dom)
172                 goto error;
173
174         partial = isl_alloc_type(dom->ctx, struct isl_partial_sol);
175         if (!partial)
176                 goto error;
177
178         partial->level = sol->level;
179         partial->dom = dom;
180         partial->M = M;
181         partial->next = sol->partial;
182
183         sol->partial = partial;
184
185         return;
186 error:
187         isl_basic_set_free(dom);
188         sol->error = 1;
189 }
190
191 /* Pop one partial solution from the partial solution stack and
192  * pass it on to sol->add or sol->add_empty.
193  */
194 static void sol_pop_one(struct isl_sol *sol)
195 {
196         struct isl_partial_sol *partial;
197
198         partial = sol->partial;
199         sol->partial = partial->next;
200
201         if (partial->M)
202                 sol->add(sol, partial->dom, partial->M);
203         else
204                 sol->add_empty(sol, partial->dom);
205         free(partial);
206 }
207
208 /* Return a fresh copy of the domain represented by the context tableau.
209  */
210 static struct isl_basic_set *sol_domain(struct isl_sol *sol)
211 {
212         struct isl_basic_set *bset;
213
214         if (sol->error)
215                 return NULL;
216
217         bset = isl_basic_set_dup(sol->context->op->peek_basic_set(sol->context));
218         bset = isl_basic_set_update_from_tab(bset,
219                         sol->context->op->peek_tab(sol->context));
220
221         return bset;
222 }
223
224 /* Check whether two partial solutions have the same mapping, where n_div
225  * is the number of divs that the two partial solutions have in common.
226  */
227 static int same_solution(struct isl_partial_sol *s1, struct isl_partial_sol *s2,
228         unsigned n_div)
229 {
230         int i;
231         unsigned dim;
232
233         if (!s1->M != !s2->M)
234                 return 0;
235         if (!s1->M)
236                 return 1;
237
238         dim = isl_basic_set_total_dim(s1->dom) - s1->dom->n_div;
239
240         for (i = 0; i < s1->M->n_row; ++i) {
241                 if (isl_seq_first_non_zero(s1->M->row[i]+1+dim+n_div,
242                                             s1->M->n_col-1-dim-n_div) != -1)
243                         return 0;
244                 if (isl_seq_first_non_zero(s2->M->row[i]+1+dim+n_div,
245                                             s2->M->n_col-1-dim-n_div) != -1)
246                         return 0;
247                 if (!isl_seq_eq(s1->M->row[i], s2->M->row[i], 1+dim+n_div))
248                         return 0;
249         }
250         return 1;
251 }
252
253 /* Pop all solutions from the partial solution stack that were pushed onto
254  * the stack at levels that are deeper than the current level.
255  * If the two topmost elements on the stack have the same level
256  * and represent the same solution, then their domains are combined.
257  * This combined domain is the same as the current context domain
258  * as sol_pop is called each time we move back to a higher level.
259  */
260 static void sol_pop(struct isl_sol *sol)
261 {
262         struct isl_partial_sol *partial;
263         unsigned n_div;
264
265         if (sol->error)
266                 return;
267
268         if (sol->level == 0) {
269                 for (partial = sol->partial; partial; partial = sol->partial)
270                         sol_pop_one(sol);
271                 return;
272         }
273
274         partial = sol->partial;
275         if (!partial)
276                 return;
277
278         if (partial->level <= sol->level)
279                 return;
280
281         if (partial->next && partial->next->level == partial->level) {
282                 n_div = isl_basic_set_dim(
283                                 sol->context->op->peek_basic_set(sol->context),
284                                 isl_dim_div);
285
286                 if (!same_solution(partial, partial->next, n_div)) {
287                         sol_pop_one(sol);
288                         sol_pop_one(sol);
289                 } else {
290                         struct isl_basic_set *bset;
291
292                         bset = sol_domain(sol);
293
294                         isl_basic_set_free(partial->next->dom);
295                         partial->next->dom = bset;
296                         partial->next->level = sol->level;
297
298                         sol->partial = partial->next;
299                         isl_basic_set_free(partial->dom);
300                         isl_mat_free(partial->M);
301                         free(partial);
302                 }
303         } else
304                 sol_pop_one(sol);
305 }
306
307 static void sol_dec_level(struct isl_sol *sol)
308 {
309         if (sol->error)
310                 return;
311
312         sol->level--;
313
314         sol_pop(sol);
315 }
316
317 static int sol_dec_level_wrap(struct isl_tab_callback *cb)
318 {
319         struct isl_sol_callback *callback = (struct isl_sol_callback *)cb;
320
321         sol_dec_level(callback->sol);
322
323         return callback->sol->error ? -1 : 0;
324 }
325
326 /* Move down to next level and push callback onto context tableau
327  * to decrease the level again when it gets rolled back across
328  * the current state.  That is, dec_level will be called with
329  * the context tableau in the same state as it is when inc_level
330  * is called.
331  */
332 static void sol_inc_level(struct isl_sol *sol)
333 {
334         struct isl_tab *tab;
335
336         if (sol->error)
337                 return;
338
339         sol->level++;
340         tab = sol->context->op->peek_tab(sol->context);
341         if (isl_tab_push_callback(tab, &sol->dec_level.callback) < 0)
342                 sol->error = 1;
343 }
344
345 static void scale_rows(struct isl_mat *mat, isl_int m, int n_row)
346 {
347         int i;
348
349         if (isl_int_is_one(m))
350                 return;
351
352         for (i = 0; i < n_row; ++i)
353                 isl_seq_scale(mat->row[i], mat->row[i], m, mat->n_col);
354 }
355
356 /* Add the solution identified by the tableau and the context tableau.
357  *
358  * The layout of the variables is as follows.
359  *      tab->n_var is equal to the total number of variables in the input
360  *                      map (including divs that were copied from the context)
361  *                      + the number of extra divs constructed
362  *      Of these, the first tab->n_param and the last tab->n_div variables
363  *      correspond to the variables in the context, i.e.,
364  *              tab->n_param + tab->n_div = context_tab->n_var
365  *      tab->n_param is equal to the number of parameters and input
366  *                      dimensions in the input map
367  *      tab->n_div is equal to the number of divs in the context
368  *
369  * If there is no solution, then call add_empty with a basic set
370  * that corresponds to the context tableau.  (If add_empty is NULL,
371  * then do nothing).
372  *
373  * If there is a solution, then first construct a matrix that maps
374  * all dimensions of the context to the output variables, i.e.,
375  * the output dimensions in the input map.
376  * The divs in the input map (if any) that do not correspond to any
377  * div in the context do not appear in the solution.
378  * The algorithm will make sure that they have an integer value,
379  * but these values themselves are of no interest.
380  * We have to be careful not to drop or rearrange any divs in the
381  * context because that would change the meaning of the matrix.
382  *
383  * To extract the value of the output variables, it should be noted
384  * that we always use a big parameter M in the main tableau and so
385  * the variable stored in this tableau is not an output variable x itself, but
386  *      x' = M + x (in case of minimization)
387  * or
388  *      x' = M - x (in case of maximization)
389  * If x' appears in a column, then its optimal value is zero,
390  * which means that the optimal value of x is an unbounded number
391  * (-M for minimization and M for maximization).
392  * We currently assume that the output dimensions in the original map
393  * are bounded, so this cannot occur.
394  * Similarly, when x' appears in a row, then the coefficient of M in that
395  * row is necessarily 1.
396  * If the row in the tableau represents
397  *      d x' = c + d M + e(y)
398  * then, in case of minimization, the corresponding row in the matrix
399  * will be
400  *      a c + a e(y)
401  * with a d = m, the (updated) common denominator of the matrix.
402  * In case of maximization, the row will be
403  *      -a c - a e(y)
404  */
405 static void sol_add(struct isl_sol *sol, struct isl_tab *tab)
406 {
407         struct isl_basic_set *bset = NULL;
408         struct isl_mat *mat = NULL;
409         unsigned off;
410         int row, i;
411         isl_int m;
412
413         if (sol->error || !tab)
414                 goto error;
415
416         if (tab->empty && !sol->add_empty)
417                 return;
418
419         bset = sol_domain(sol);
420
421         if (tab->empty) {
422                 sol_push_sol(sol, bset, NULL);
423                 return;
424         }
425
426         off = 2 + tab->M;
427
428         mat = isl_mat_alloc(tab->mat->ctx, 1 + sol->n_out,
429                                             1 + tab->n_param + tab->n_div);
430         if (!mat)
431                 goto error;
432
433         isl_int_init(m);
434
435         isl_seq_clr(mat->row[0] + 1, mat->n_col - 1);
436         isl_int_set_si(mat->row[0][0], 1);
437         for (row = 0; row < sol->n_out; ++row) {
438                 int i = tab->n_param + row;
439                 int r, j;
440
441                 isl_seq_clr(mat->row[1 + row], mat->n_col);
442                 if (!tab->var[i].is_row) {
443                         /* no unbounded */
444                         isl_assert(mat->ctx, !tab->M, goto error2);
445                         continue;
446                 }
447
448                 r = tab->var[i].index;
449                 /* no unbounded */
450                 if (tab->M)
451                         isl_assert(mat->ctx, isl_int_eq(tab->mat->row[r][2],
452                                                         tab->mat->row[r][0]),
453                                     goto error2);
454                 isl_int_gcd(m, mat->row[0][0], tab->mat->row[r][0]);
455                 isl_int_divexact(m, tab->mat->row[r][0], m);
456                 scale_rows(mat, m, 1 + row);
457                 isl_int_divexact(m, mat->row[0][0], tab->mat->row[r][0]);
458                 isl_int_mul(mat->row[1 + row][0], m, tab->mat->row[r][1]);
459                 for (j = 0; j < tab->n_param; ++j) {
460                         int col;
461                         if (tab->var[j].is_row)
462                                 continue;
463                         col = tab->var[j].index;
464                         isl_int_mul(mat->row[1 + row][1 + j], m,
465                                     tab->mat->row[r][off + col]);
466                 }
467                 for (j = 0; j < tab->n_div; ++j) {
468                         int col;
469                         if (tab->var[tab->n_var - tab->n_div+j].is_row)
470                                 continue;
471                         col = tab->var[tab->n_var - tab->n_div+j].index;
472                         isl_int_mul(mat->row[1 + row][1 + tab->n_param + j], m,
473                                     tab->mat->row[r][off + col]);
474                 }
475                 if (sol->max)
476                         isl_seq_neg(mat->row[1 + row], mat->row[1 + row],
477                                     mat->n_col);
478         }
479
480         isl_int_clear(m);
481
482         sol_push_sol(sol, bset, mat);
483         return;
484 error2:
485         isl_int_clear(m);
486 error:
487         isl_basic_set_free(bset);
488         isl_mat_free(mat);
489         sol_free(sol);
490 }
491
492 struct isl_sol_map {
493         struct isl_sol  sol;
494         struct isl_map  *map;
495         struct isl_set  *empty;
496 };
497
498 static void sol_map_free(struct isl_sol_map *sol_map)
499 {
500         if (sol_map->sol.context)
501                 sol_map->sol.context->op->free(sol_map->sol.context);
502         isl_map_free(sol_map->map);
503         isl_set_free(sol_map->empty);
504         free(sol_map);
505 }
506
507 static void sol_map_free_wrap(struct isl_sol *sol)
508 {
509         sol_map_free((struct isl_sol_map *)sol);
510 }
511
512 /* This function is called for parts of the context where there is
513  * no solution, with "bset" corresponding to the context tableau.
514  * Simply add the basic set to the set "empty".
515  */
516 static void sol_map_add_empty(struct isl_sol_map *sol,
517         struct isl_basic_set *bset)
518 {
519         if (!bset)
520                 goto error;
521         isl_assert(bset->ctx, sol->empty, goto error);
522
523         sol->empty = isl_set_grow(sol->empty, 1);
524         bset = isl_basic_set_simplify(bset);
525         bset = isl_basic_set_finalize(bset);
526         sol->empty = isl_set_add(sol->empty, isl_basic_set_copy(bset));
527         if (!sol->empty)
528                 goto error;
529         isl_basic_set_free(bset);
530         return;
531 error:
532         isl_basic_set_free(bset);
533         sol->sol.error = 1;
534 }
535
536 static void sol_map_add_empty_wrap(struct isl_sol *sol,
537         struct isl_basic_set *bset)
538 {
539         sol_map_add_empty((struct isl_sol_map *)sol, bset);
540 }
541
542 /* Given a basic map "dom" that represents the context and an affine
543  * matrix "M" that maps the dimensions of the context to the
544  * output variables, construct a basic map with the same parameters
545  * and divs as the context, the dimensions of the context as input
546  * dimensions and a number of output dimensions that is equal to
547  * the number of output dimensions in the input map.
548  *
549  * The constraints and divs of the context are simply copied
550  * from "dom".  For each row
551  *      x = c + e(y)
552  * an equality
553  *      c + e(y) - d x = 0
554  * is added, with d the common denominator of M.
555  */
556 static void sol_map_add(struct isl_sol_map *sol,
557         struct isl_basic_set *dom, struct isl_mat *M)
558 {
559         int i;
560         struct isl_basic_map *bmap = NULL;
561         isl_basic_set *context_bset;
562         unsigned n_eq;
563         unsigned n_ineq;
564         unsigned nparam;
565         unsigned total;
566         unsigned n_div;
567         unsigned n_out;
568
569         if (sol->sol.error || !dom || !M)
570                 goto error;
571
572         n_out = sol->sol.n_out;
573         n_eq = dom->n_eq + n_out;
574         n_ineq = dom->n_ineq;
575         n_div = dom->n_div;
576         nparam = isl_basic_set_total_dim(dom) - n_div;
577         total = isl_map_dim(sol->map, isl_dim_all);
578         bmap = isl_basic_map_alloc_dim(isl_map_get_dim(sol->map),
579                                         n_div, n_eq, 2 * n_div + n_ineq);
580         if (!bmap)
581                 goto error;
582         if (sol->sol.rational)
583                 ISL_F_SET(bmap, ISL_BASIC_MAP_RATIONAL);
584         for (i = 0; i < dom->n_div; ++i) {
585                 int k = isl_basic_map_alloc_div(bmap);
586                 if (k < 0)
587                         goto error;
588                 isl_seq_cpy(bmap->div[k], dom->div[i], 1 + 1 + nparam);
589                 isl_seq_clr(bmap->div[k] + 1 + 1 + nparam, total - nparam);
590                 isl_seq_cpy(bmap->div[k] + 1 + 1 + total,
591                             dom->div[i] + 1 + 1 + nparam, i);
592         }
593         for (i = 0; i < dom->n_eq; ++i) {
594                 int k = isl_basic_map_alloc_equality(bmap);
595                 if (k < 0)
596                         goto error;
597                 isl_seq_cpy(bmap->eq[k], dom->eq[i], 1 + nparam);
598                 isl_seq_clr(bmap->eq[k] + 1 + nparam, total - nparam);
599                 isl_seq_cpy(bmap->eq[k] + 1 + total,
600                             dom->eq[i] + 1 + nparam, n_div);
601         }
602         for (i = 0; i < dom->n_ineq; ++i) {
603                 int k = isl_basic_map_alloc_inequality(bmap);
604                 if (k < 0)
605                         goto error;
606                 isl_seq_cpy(bmap->ineq[k], dom->ineq[i], 1 + nparam);
607                 isl_seq_clr(bmap->ineq[k] + 1 + nparam, total - nparam);
608                 isl_seq_cpy(bmap->ineq[k] + 1 + total,
609                         dom->ineq[i] + 1 + nparam, n_div);
610         }
611         for (i = 0; i < M->n_row - 1; ++i) {
612                 int k = isl_basic_map_alloc_equality(bmap);
613                 if (k < 0)
614                         goto error;
615                 isl_seq_cpy(bmap->eq[k], M->row[1 + i], 1 + nparam);
616                 isl_seq_clr(bmap->eq[k] + 1 + nparam, n_out);
617                 isl_int_neg(bmap->eq[k][1 + nparam + i], M->row[0][0]);
618                 isl_seq_cpy(bmap->eq[k] + 1 + nparam + n_out,
619                             M->row[1 + i] + 1 + nparam, n_div);
620         }
621         bmap = isl_basic_map_simplify(bmap);
622         bmap = isl_basic_map_finalize(bmap);
623         sol->map = isl_map_grow(sol->map, 1);
624         sol->map = isl_map_add(sol->map, bmap);
625         if (!sol->map)
626                 goto error;
627         isl_basic_set_free(dom);
628         isl_mat_free(M);
629         return;
630 error:
631         isl_basic_set_free(dom);
632         isl_mat_free(M);
633         isl_basic_map_free(bmap);
634         sol->sol.error = 1;
635 }
636
637 static void sol_map_add_wrap(struct isl_sol *sol,
638         struct isl_basic_set *dom, struct isl_mat *M)
639 {
640         sol_map_add((struct isl_sol_map *)sol, dom, M);
641 }
642
643
644 /* Store the "parametric constant" of row "row" of tableau "tab" in "line",
645  * i.e., the constant term and the coefficients of all variables that
646  * appear in the context tableau.
647  * Note that the coefficient of the big parameter M is NOT copied.
648  * The context tableau may not have a big parameter and even when it
649  * does, it is a different big parameter.
650  */
651 static void get_row_parameter_line(struct isl_tab *tab, int row, isl_int *line)
652 {
653         int i;
654         unsigned off = 2 + tab->M;
655
656         isl_int_set(line[0], tab->mat->row[row][1]);
657         for (i = 0; i < tab->n_param; ++i) {
658                 if (tab->var[i].is_row)
659                         isl_int_set_si(line[1 + i], 0);
660                 else {
661                         int col = tab->var[i].index;
662                         isl_int_set(line[1 + i], tab->mat->row[row][off + col]);
663                 }
664         }
665         for (i = 0; i < tab->n_div; ++i) {
666                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
667                         isl_int_set_si(line[1 + tab->n_param + i], 0);
668                 else {
669                         int col = tab->var[tab->n_var - tab->n_div + i].index;
670                         isl_int_set(line[1 + tab->n_param + i],
671                                     tab->mat->row[row][off + col]);
672                 }
673         }
674 }
675
676 /* Check if rows "row1" and "row2" have identical "parametric constants",
677  * as explained above.
678  * In this case, we also insist that the coefficients of the big parameter
679  * be the same as the values of the constants will only be the same
680  * if these coefficients are also the same.
681  */
682 static int identical_parameter_line(struct isl_tab *tab, int row1, int row2)
683 {
684         int i;
685         unsigned off = 2 + tab->M;
686
687         if (isl_int_ne(tab->mat->row[row1][1], tab->mat->row[row2][1]))
688                 return 0;
689
690         if (tab->M && isl_int_ne(tab->mat->row[row1][2],
691                                  tab->mat->row[row2][2]))
692                 return 0;
693
694         for (i = 0; i < tab->n_param + tab->n_div; ++i) {
695                 int pos = i < tab->n_param ? i :
696                         tab->n_var - tab->n_div + i - tab->n_param;
697                 int col;
698
699                 if (tab->var[pos].is_row)
700                         continue;
701                 col = tab->var[pos].index;
702                 if (isl_int_ne(tab->mat->row[row1][off + col],
703                                tab->mat->row[row2][off + col]))
704                         return 0;
705         }
706         return 1;
707 }
708
709 /* Return an inequality that expresses that the "parametric constant"
710  * should be non-negative.
711  * This function is only called when the coefficient of the big parameter
712  * is equal to zero.
713  */
714 static struct isl_vec *get_row_parameter_ineq(struct isl_tab *tab, int row)
715 {
716         struct isl_vec *ineq;
717
718         ineq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_param + tab->n_div);
719         if (!ineq)
720                 return NULL;
721
722         get_row_parameter_line(tab, row, ineq->el);
723         if (ineq)
724                 ineq = isl_vec_normalize(ineq);
725
726         return ineq;
727 }
728
729 /* Return a integer division for use in a parametric cut based on the given row.
730  * In particular, let the parametric constant of the row be
731  *
732  *              \sum_i a_i y_i
733  *
734  * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
735  * The div returned is equal to
736  *
737  *              floor(\sum_i {-a_i} y_i) = floor((\sum_i (-a_i mod d) y_i)/d)
738  */
739 static struct isl_vec *get_row_parameter_div(struct isl_tab *tab, int row)
740 {
741         struct isl_vec *div;
742
743         div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
744         if (!div)
745                 return NULL;
746
747         isl_int_set(div->el[0], tab->mat->row[row][0]);
748         get_row_parameter_line(tab, row, div->el + 1);
749         div = isl_vec_normalize(div);
750         isl_seq_neg(div->el + 1, div->el + 1, div->size - 1);
751         isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
752
753         return div;
754 }
755
756 /* Return a integer division for use in transferring an integrality constraint
757  * to the context.
758  * In particular, let the parametric constant of the row be
759  *
760  *              \sum_i a_i y_i
761  *
762  * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
763  * The the returned div is equal to
764  *
765  *              floor(\sum_i {a_i} y_i) = floor((\sum_i (a_i mod d) y_i)/d)
766  */
767 static struct isl_vec *get_row_split_div(struct isl_tab *tab, int row)
768 {
769         struct isl_vec *div;
770
771         div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
772         if (!div)
773                 return NULL;
774
775         isl_int_set(div->el[0], tab->mat->row[row][0]);
776         get_row_parameter_line(tab, row, div->el + 1);
777         div = isl_vec_normalize(div);
778         isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
779
780         return div;
781 }
782
783 /* Construct and return an inequality that expresses an upper bound
784  * on the given div.
785  * In particular, if the div is given by
786  *
787  *      d = floor(e/m)
788  *
789  * then the inequality expresses
790  *
791  *      m d <= e
792  */
793 static struct isl_vec *ineq_for_div(struct isl_basic_set *bset, unsigned div)
794 {
795         unsigned total;
796         unsigned div_pos;
797         struct isl_vec *ineq;
798
799         if (!bset)
800                 return NULL;
801
802         total = isl_basic_set_total_dim(bset);
803         div_pos = 1 + total - bset->n_div + div;
804
805         ineq = isl_vec_alloc(bset->ctx, 1 + total);
806         if (!ineq)
807                 return NULL;
808
809         isl_seq_cpy(ineq->el, bset->div[div] + 1, 1 + total);
810         isl_int_neg(ineq->el[div_pos], bset->div[div][0]);
811         return ineq;
812 }
813
814 /* Given a row in the tableau and a div that was created
815  * using get_row_split_div and that been constrained to equality, i.e.,
816  *
817  *              d = floor(\sum_i {a_i} y_i) = \sum_i {a_i} y_i
818  *
819  * replace the expression "\sum_i {a_i} y_i" in the row by d,
820  * i.e., we subtract "\sum_i {a_i} y_i" and add 1 d.
821  * The coefficients of the non-parameters in the tableau have been
822  * verified to be integral.  We can therefore simply replace coefficient b
823  * by floor(b).  For the coefficients of the parameters we have
824  * floor(a_i) = a_i - {a_i}, while for the other coefficients, we have
825  * floor(b) = b.
826  */
827 static struct isl_tab *set_row_cst_to_div(struct isl_tab *tab, int row, int div)
828 {
829         isl_seq_fdiv_q(tab->mat->row[row] + 1, tab->mat->row[row] + 1,
830                         tab->mat->row[row][0], 1 + tab->M + tab->n_col);
831
832         isl_int_set_si(tab->mat->row[row][0], 1);
833
834         if (tab->var[tab->n_var - tab->n_div + div].is_row) {
835                 int drow = tab->var[tab->n_var - tab->n_div + div].index;
836
837                 isl_assert(tab->mat->ctx,
838                         isl_int_is_one(tab->mat->row[drow][0]), goto error);
839                 isl_seq_combine(tab->mat->row[row] + 1,
840                         tab->mat->ctx->one, tab->mat->row[row] + 1,
841                         tab->mat->ctx->one, tab->mat->row[drow] + 1,
842                         1 + tab->M + tab->n_col);
843         } else {
844                 int dcol = tab->var[tab->n_var - tab->n_div + div].index;
845
846                 isl_int_set_si(tab->mat->row[row][2 + tab->M + dcol], 1);
847         }
848
849         return tab;
850 error:
851         isl_tab_free(tab);
852         return NULL;
853 }
854
855 /* Check if the (parametric) constant of the given row is obviously
856  * negative, meaning that we don't need to consult the context tableau.
857  * If there is a big parameter and its coefficient is non-zero,
858  * then this coefficient determines the outcome.
859  * Otherwise, we check whether the constant is negative and
860  * all non-zero coefficients of parameters are negative and
861  * belong to non-negative parameters.
862  */
863 static int is_obviously_neg(struct isl_tab *tab, int row)
864 {
865         int i;
866         int col;
867         unsigned off = 2 + tab->M;
868
869         if (tab->M) {
870                 if (isl_int_is_pos(tab->mat->row[row][2]))
871                         return 0;
872                 if (isl_int_is_neg(tab->mat->row[row][2]))
873                         return 1;
874         }
875
876         if (isl_int_is_nonneg(tab->mat->row[row][1]))
877                 return 0;
878         for (i = 0; i < tab->n_param; ++i) {
879                 /* Eliminated parameter */
880                 if (tab->var[i].is_row)
881                         continue;
882                 col = tab->var[i].index;
883                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
884                         continue;
885                 if (!tab->var[i].is_nonneg)
886                         return 0;
887                 if (isl_int_is_pos(tab->mat->row[row][off + col]))
888                         return 0;
889         }
890         for (i = 0; i < tab->n_div; ++i) {
891                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
892                         continue;
893                 col = tab->var[tab->n_var - tab->n_div + i].index;
894                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
895                         continue;
896                 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
897                         return 0;
898                 if (isl_int_is_pos(tab->mat->row[row][off + col]))
899                         return 0;
900         }
901         return 1;
902 }
903
904 /* Check if the (parametric) constant of the given row is obviously
905  * non-negative, meaning that we don't need to consult the context tableau.
906  * If there is a big parameter and its coefficient is non-zero,
907  * then this coefficient determines the outcome.
908  * Otherwise, we check whether the constant is non-negative and
909  * all non-zero coefficients of parameters are positive and
910  * belong to non-negative parameters.
911  */
912 static int is_obviously_nonneg(struct isl_tab *tab, int row)
913 {
914         int i;
915         int col;
916         unsigned off = 2 + tab->M;
917
918         if (tab->M) {
919                 if (isl_int_is_pos(tab->mat->row[row][2]))
920                         return 1;
921                 if (isl_int_is_neg(tab->mat->row[row][2]))
922                         return 0;
923         }
924
925         if (isl_int_is_neg(tab->mat->row[row][1]))
926                 return 0;
927         for (i = 0; i < tab->n_param; ++i) {
928                 /* Eliminated parameter */
929                 if (tab->var[i].is_row)
930                         continue;
931                 col = tab->var[i].index;
932                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
933                         continue;
934                 if (!tab->var[i].is_nonneg)
935                         return 0;
936                 if (isl_int_is_neg(tab->mat->row[row][off + col]))
937                         return 0;
938         }
939         for (i = 0; i < tab->n_div; ++i) {
940                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
941                         continue;
942                 col = tab->var[tab->n_var - tab->n_div + i].index;
943                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
944                         continue;
945                 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
946                         return 0;
947                 if (isl_int_is_neg(tab->mat->row[row][off + col]))
948                         return 0;
949         }
950         return 1;
951 }
952
953 /* Given a row r and two columns, return the column that would
954  * lead to the lexicographically smallest increment in the sample
955  * solution when leaving the basis in favor of the row.
956  * Pivoting with column c will increment the sample value by a non-negative
957  * constant times a_{V,c}/a_{r,c}, with a_{V,c} the elements of column c
958  * corresponding to the non-parametric variables.
959  * If variable v appears in a column c_v, the a_{v,c} = 1 iff c = c_v,
960  * with all other entries in this virtual row equal to zero.
961  * If variable v appears in a row, then a_{v,c} is the element in column c
962  * of that row.
963  *
964  * Let v be the first variable with a_{v,c1}/a_{r,c1} != a_{v,c2}/a_{r,c2}.
965  * Then if a_{v,c1}/a_{r,c1} < a_{v,c2}/a_{r,c2}, i.e.,
966  * a_{v,c2} a_{r,c1} - a_{v,c1} a_{r,c2} > 0, c1 results in the minimal
967  * increment.  Otherwise, it's c2.
968  */
969 static int lexmin_col_pair(struct isl_tab *tab,
970         int row, int col1, int col2, isl_int tmp)
971 {
972         int i;
973         isl_int *tr;
974
975         tr = tab->mat->row[row] + 2 + tab->M;
976
977         for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
978                 int s1, s2;
979                 isl_int *r;
980
981                 if (!tab->var[i].is_row) {
982                         if (tab->var[i].index == col1)
983                                 return col2;
984                         if (tab->var[i].index == col2)
985                                 return col1;
986                         continue;
987                 }
988
989                 if (tab->var[i].index == row)
990                         continue;
991
992                 r = tab->mat->row[tab->var[i].index] + 2 + tab->M;
993                 s1 = isl_int_sgn(r[col1]);
994                 s2 = isl_int_sgn(r[col2]);
995                 if (s1 == 0 && s2 == 0)
996                         continue;
997                 if (s1 < s2)
998                         return col1;
999                 if (s2 < s1)
1000                         return col2;
1001
1002                 isl_int_mul(tmp, r[col2], tr[col1]);
1003                 isl_int_submul(tmp, r[col1], tr[col2]);
1004                 if (isl_int_is_pos(tmp))
1005                         return col1;
1006                 if (isl_int_is_neg(tmp))
1007                         return col2;
1008         }
1009         return -1;
1010 }
1011
1012 /* Given a row in the tableau, find and return the column that would
1013  * result in the lexicographically smallest, but positive, increment
1014  * in the sample point.
1015  * If there is no such column, then return tab->n_col.
1016  * If anything goes wrong, return -1.
1017  */
1018 static int lexmin_pivot_col(struct isl_tab *tab, int row)
1019 {
1020         int j;
1021         int col = tab->n_col;
1022         isl_int *tr;
1023         isl_int tmp;
1024
1025         tr = tab->mat->row[row] + 2 + tab->M;
1026
1027         isl_int_init(tmp);
1028
1029         for (j = tab->n_dead; j < tab->n_col; ++j) {
1030                 if (tab->col_var[j] >= 0 &&
1031                     (tab->col_var[j] < tab->n_param  ||
1032                     tab->col_var[j] >= tab->n_var - tab->n_div))
1033                         continue;
1034
1035                 if (!isl_int_is_pos(tr[j]))
1036                         continue;
1037
1038                 if (col == tab->n_col)
1039                         col = j;
1040                 else
1041                         col = lexmin_col_pair(tab, row, col, j, tmp);
1042                 isl_assert(tab->mat->ctx, col >= 0, goto error);
1043         }
1044
1045         isl_int_clear(tmp);
1046         return col;
1047 error:
1048         isl_int_clear(tmp);
1049         return -1;
1050 }
1051
1052 /* Return the first known violated constraint, i.e., a non-negative
1053  * contraint that currently has an either obviously negative value
1054  * or a previously determined to be negative value.
1055  *
1056  * If any constraint has a negative coefficient for the big parameter,
1057  * if any, then we return one of these first.
1058  */
1059 static int first_neg(struct isl_tab *tab)
1060 {
1061         int row;
1062
1063         if (tab->M)
1064                 for (row = tab->n_redundant; row < tab->n_row; ++row) {
1065                         if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1066                                 continue;
1067                         if (isl_int_is_neg(tab->mat->row[row][2]))
1068                                 return row;
1069                 }
1070         for (row = tab->n_redundant; row < tab->n_row; ++row) {
1071                 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1072                         continue;
1073                 if (tab->row_sign) {
1074                         if (tab->row_sign[row] == 0 &&
1075                             is_obviously_neg(tab, row))
1076                                 tab->row_sign[row] = isl_tab_row_neg;
1077                         if (tab->row_sign[row] != isl_tab_row_neg)
1078                                 continue;
1079                 } else if (!is_obviously_neg(tab, row))
1080                         continue;
1081                 return row;
1082         }
1083         return -1;
1084 }
1085
1086 /* Resolve all known or obviously violated constraints through pivoting.
1087  * In particular, as long as we can find any violated constraint, we
1088  * look for a pivoting column that would result in the lexicographicallly
1089  * smallest increment in the sample point.  If there is no such column
1090  * then the tableau is infeasible.
1091  */
1092 static struct isl_tab *restore_lexmin(struct isl_tab *tab) WARN_UNUSED;
1093 static struct isl_tab *restore_lexmin(struct isl_tab *tab)
1094 {
1095         int row, col;
1096
1097         if (!tab)
1098                 return NULL;
1099         if (tab->empty)
1100                 return tab;
1101         while ((row = first_neg(tab)) != -1) {
1102                 col = lexmin_pivot_col(tab, row);
1103                 if (col >= tab->n_col)
1104                         return isl_tab_mark_empty(tab);
1105                 if (col < 0)
1106                         goto error;
1107                 if (isl_tab_pivot(tab, row, col) < 0)
1108                         goto error;
1109         }
1110         return tab;
1111 error:
1112         isl_tab_free(tab);
1113         return NULL;
1114 }
1115
1116 /* Given a row that represents an equality, look for an appropriate
1117  * pivoting column.
1118  * In particular, if there are any non-zero coefficients among
1119  * the non-parameter variables, then we take the last of these
1120  * variables.  Eliminating this variable in terms of the other
1121  * variables and/or parameters does not influence the property
1122  * that all column in the initial tableau are lexicographically
1123  * positive.  The row corresponding to the eliminated variable
1124  * will only have non-zero entries below the diagonal of the
1125  * initial tableau.  That is, we transform
1126  *
1127  *              I                               I
1128  *                1             into            a
1129  *                  I                             I
1130  *
1131  * If there is no such non-parameter variable, then we are dealing with
1132  * pure parameter equality and we pick any parameter with coefficient 1 or -1
1133  * for elimination.  This will ensure that the eliminated parameter
1134  * always has an integer value whenever all the other parameters are integral.
1135  * If there is no such parameter then we return -1.
1136  */
1137 static int last_var_col_or_int_par_col(struct isl_tab *tab, int row)
1138 {
1139         unsigned off = 2 + tab->M;
1140         int i;
1141
1142         for (i = tab->n_var - tab->n_div - 1; i >= 0 && i >= tab->n_param; --i) {
1143                 int col;
1144                 if (tab->var[i].is_row)
1145                         continue;
1146                 col = tab->var[i].index;
1147                 if (col <= tab->n_dead)
1148                         continue;
1149                 if (!isl_int_is_zero(tab->mat->row[row][off + col]))
1150                         return col;
1151         }
1152         for (i = tab->n_dead; i < tab->n_col; ++i) {
1153                 if (isl_int_is_one(tab->mat->row[row][off + i]))
1154                         return i;
1155                 if (isl_int_is_negone(tab->mat->row[row][off + i]))
1156                         return i;
1157         }
1158         return -1;
1159 }
1160
1161 /* Add an equality that is known to be valid to the tableau.
1162  * We first check if we can eliminate a variable or a parameter.
1163  * If not, we add the equality as two inequalities.
1164  * In this case, the equality was a pure parameter equality and there
1165  * is no need to resolve any constraint violations.
1166  */
1167 static struct isl_tab *add_lexmin_valid_eq(struct isl_tab *tab, isl_int *eq)
1168 {
1169         int i;
1170         int r;
1171
1172         if (!tab)
1173                 return NULL;
1174         r = isl_tab_add_row(tab, eq);
1175         if (r < 0)
1176                 goto error;
1177
1178         r = tab->con[r].index;
1179         i = last_var_col_or_int_par_col(tab, r);
1180         if (i < 0) {
1181                 tab->con[r].is_nonneg = 1;
1182                 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1183                         goto error;
1184                 isl_seq_neg(eq, eq, 1 + tab->n_var);
1185                 r = isl_tab_add_row(tab, eq);
1186                 if (r < 0)
1187                         goto error;
1188                 tab->con[r].is_nonneg = 1;
1189                 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1190                         goto error;
1191         } else {
1192                 if (isl_tab_pivot(tab, r, i) < 0)
1193                         goto error;
1194                 if (isl_tab_kill_col(tab, i) < 0)
1195                         goto error;
1196                 tab->n_eq++;
1197
1198                 tab = restore_lexmin(tab);
1199         }
1200
1201         return tab;
1202 error:
1203         isl_tab_free(tab);
1204         return NULL;
1205 }
1206
1207 /* Check if the given row is a pure constant.
1208  */
1209 static int is_constant(struct isl_tab *tab, int row)
1210 {
1211         unsigned off = 2 + tab->M;
1212
1213         return isl_seq_first_non_zero(tab->mat->row[row] + off + tab->n_dead,
1214                                         tab->n_col - tab->n_dead) == -1;
1215 }
1216
1217 /* Add an equality that may or may not be valid to the tableau.
1218  * If the resulting row is a pure constant, then it must be zero.
1219  * Otherwise, the resulting tableau is empty.
1220  *
1221  * If the row is not a pure constant, then we add two inequalities,
1222  * each time checking that they can be satisfied.
1223  * In the end we try to use one of the two constraints to eliminate
1224  * a column.
1225  */
1226 static struct isl_tab *add_lexmin_eq(struct isl_tab *tab, isl_int *eq) WARN_UNUSED;
1227 static struct isl_tab *add_lexmin_eq(struct isl_tab *tab, isl_int *eq)
1228 {
1229         int r1, r2;
1230         int row;
1231         struct isl_tab_undo *snap;
1232
1233         if (!tab)
1234                 return NULL;
1235         snap = isl_tab_snap(tab);
1236         r1 = isl_tab_add_row(tab, eq);
1237         if (r1 < 0)
1238                 goto error;
1239         tab->con[r1].is_nonneg = 1;
1240         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r1]) < 0)
1241                 goto error;
1242
1243         row = tab->con[r1].index;
1244         if (is_constant(tab, row)) {
1245                 if (!isl_int_is_zero(tab->mat->row[row][1]) ||
1246                     (tab->M && !isl_int_is_zero(tab->mat->row[row][2])))
1247                         return isl_tab_mark_empty(tab);
1248                 if (isl_tab_rollback(tab, snap) < 0)
1249                         goto error;
1250                 return tab;
1251         }
1252
1253         tab = restore_lexmin(tab);
1254         if (!tab || tab->empty)
1255                 return tab;
1256
1257         isl_seq_neg(eq, eq, 1 + tab->n_var);
1258
1259         r2 = isl_tab_add_row(tab, eq);
1260         if (r2 < 0)
1261                 goto error;
1262         tab->con[r2].is_nonneg = 1;
1263         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r2]) < 0)
1264                 goto error;
1265
1266         tab = restore_lexmin(tab);
1267         if (!tab || tab->empty)
1268                 return tab;
1269
1270         if (!tab->con[r1].is_row) {
1271                 if (isl_tab_kill_col(tab, tab->con[r1].index) < 0)
1272                         goto error;
1273         } else if (!tab->con[r2].is_row) {
1274                 if (isl_tab_kill_col(tab, tab->con[r2].index) < 0)
1275                         goto error;
1276         } else if (isl_int_is_zero(tab->mat->row[tab->con[r1].index][1])) {
1277                 unsigned off = 2 + tab->M;
1278                 int i;
1279                 int row = tab->con[r1].index;
1280                 i = isl_seq_first_non_zero(tab->mat->row[row]+off+tab->n_dead,
1281                                                 tab->n_col - tab->n_dead);
1282                 if (i != -1) {
1283                         if (isl_tab_pivot(tab, row, tab->n_dead + i) < 0)
1284                                 goto error;
1285                         if (isl_tab_kill_col(tab, tab->n_dead + i) < 0)
1286                                 goto error;
1287                 }
1288         }
1289
1290         if (tab->bset) {
1291                 tab->bset = isl_basic_set_add_ineq(tab->bset, eq);
1292                 if (isl_tab_push(tab, isl_tab_undo_bset_ineq) < 0)
1293                         goto error;
1294                 isl_seq_neg(eq, eq, 1 + tab->n_var);
1295                 tab->bset = isl_basic_set_add_ineq(tab->bset, eq);
1296                 isl_seq_neg(eq, eq, 1 + tab->n_var);
1297                 if (isl_tab_push(tab, isl_tab_undo_bset_ineq) < 0)
1298                         goto error;
1299                 if (!tab->bset)
1300                         goto error;
1301         }
1302
1303         return tab;
1304 error:
1305         isl_tab_free(tab);
1306         return NULL;
1307 }
1308
1309 /* Add an inequality to the tableau, resolving violations using
1310  * restore_lexmin.
1311  */
1312 static struct isl_tab *add_lexmin_ineq(struct isl_tab *tab, isl_int *ineq)
1313 {
1314         int r;
1315
1316         if (!tab)
1317                 return NULL;
1318         if (tab->bset) {
1319                 tab->bset = isl_basic_set_add_ineq(tab->bset, ineq);
1320                 if (isl_tab_push(tab, isl_tab_undo_bset_ineq) < 0)
1321                         goto error;
1322                 if (!tab->bset)
1323                         goto error;
1324         }
1325         r = isl_tab_add_row(tab, ineq);
1326         if (r < 0)
1327                 goto error;
1328         tab->con[r].is_nonneg = 1;
1329         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1330                 goto error;
1331         if (isl_tab_row_is_redundant(tab, tab->con[r].index)) {
1332                 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1333                         goto error;
1334                 return tab;
1335         }
1336
1337         tab = restore_lexmin(tab);
1338         if (tab && !tab->empty && tab->con[r].is_row &&
1339                  isl_tab_row_is_redundant(tab, tab->con[r].index))
1340                 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1341                         goto error;
1342         return tab;
1343 error:
1344         isl_tab_free(tab);
1345         return NULL;
1346 }
1347
1348 /* Check if the coefficients of the parameters are all integral.
1349  */
1350 static int integer_parameter(struct isl_tab *tab, int row)
1351 {
1352         int i;
1353         int col;
1354         unsigned off = 2 + tab->M;
1355
1356         for (i = 0; i < tab->n_param; ++i) {
1357                 /* Eliminated parameter */
1358                 if (tab->var[i].is_row)
1359                         continue;
1360                 col = tab->var[i].index;
1361                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1362                                                 tab->mat->row[row][0]))
1363                         return 0;
1364         }
1365         for (i = 0; i < tab->n_div; ++i) {
1366                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1367                         continue;
1368                 col = tab->var[tab->n_var - tab->n_div + i].index;
1369                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1370                                                 tab->mat->row[row][0]))
1371                         return 0;
1372         }
1373         return 1;
1374 }
1375
1376 /* Check if the coefficients of the non-parameter variables are all integral.
1377  */
1378 static int integer_variable(struct isl_tab *tab, int row)
1379 {
1380         int i;
1381         unsigned off = 2 + tab->M;
1382
1383         for (i = 0; i < tab->n_col; ++i) {
1384                 if (tab->col_var[i] >= 0 &&
1385                     (tab->col_var[i] < tab->n_param ||
1386                      tab->col_var[i] >= tab->n_var - tab->n_div))
1387                         continue;
1388                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + i],
1389                                                 tab->mat->row[row][0]))
1390                         return 0;
1391         }
1392         return 1;
1393 }
1394
1395 /* Check if the constant term is integral.
1396  */
1397 static int integer_constant(struct isl_tab *tab, int row)
1398 {
1399         return isl_int_is_divisible_by(tab->mat->row[row][1],
1400                                         tab->mat->row[row][0]);
1401 }
1402
1403 #define I_CST   1 << 0
1404 #define I_PAR   1 << 1
1405 #define I_VAR   1 << 2
1406
1407 /* Check for first (non-parameter) variable that is non-integer and
1408  * therefore requires a cut.
1409  * For parametric tableaus, there are three parts in a row,
1410  * the constant, the coefficients of the parameters and the rest.
1411  * For each part, we check whether the coefficients in that part
1412  * are all integral and if so, set the corresponding flag in *f.
1413  * If the constant and the parameter part are integral, then the
1414  * current sample value is integral and no cut is required
1415  * (irrespective of whether the variable part is integral).
1416  */
1417 static int first_non_integer(struct isl_tab *tab, int *f)
1418 {
1419         int i;
1420
1421         for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
1422                 int flags = 0;
1423                 int row;
1424                 if (!tab->var[i].is_row)
1425                         continue;
1426                 row = tab->var[i].index;
1427                 if (integer_constant(tab, row))
1428                         ISL_FL_SET(flags, I_CST);
1429                 if (integer_parameter(tab, row))
1430                         ISL_FL_SET(flags, I_PAR);
1431                 if (ISL_FL_ISSET(flags, I_CST) && ISL_FL_ISSET(flags, I_PAR))
1432                         continue;
1433                 if (integer_variable(tab, row))
1434                         ISL_FL_SET(flags, I_VAR);
1435                 *f = flags;
1436                 return row;
1437         }
1438         return -1;
1439 }
1440
1441 /* Add a (non-parametric) cut to cut away the non-integral sample
1442  * value of the given row.
1443  *
1444  * If the row is given by
1445  *
1446  *      m r = f + \sum_i a_i y_i
1447  *
1448  * then the cut is
1449  *
1450  *      c = - {-f/m} + \sum_i {a_i/m} y_i >= 0
1451  *
1452  * The big parameter, if any, is ignored, since it is assumed to be big
1453  * enough to be divisible by any integer.
1454  * If the tableau is actually a parametric tableau, then this function
1455  * is only called when all coefficients of the parameters are integral.
1456  * The cut therefore has zero coefficients for the parameters.
1457  *
1458  * The current value is known to be negative, so row_sign, if it
1459  * exists, is set accordingly.
1460  *
1461  * Return the row of the cut or -1.
1462  */
1463 static int add_cut(struct isl_tab *tab, int row)
1464 {
1465         int i;
1466         int r;
1467         isl_int *r_row;
1468         unsigned off = 2 + tab->M;
1469
1470         if (isl_tab_extend_cons(tab, 1) < 0)
1471                 return -1;
1472         r = isl_tab_allocate_con(tab);
1473         if (r < 0)
1474                 return -1;
1475
1476         r_row = tab->mat->row[tab->con[r].index];
1477         isl_int_set(r_row[0], tab->mat->row[row][0]);
1478         isl_int_neg(r_row[1], tab->mat->row[row][1]);
1479         isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1480         isl_int_neg(r_row[1], r_row[1]);
1481         if (tab->M)
1482                 isl_int_set_si(r_row[2], 0);
1483         for (i = 0; i < tab->n_col; ++i)
1484                 isl_int_fdiv_r(r_row[off + i],
1485                         tab->mat->row[row][off + i], tab->mat->row[row][0]);
1486
1487         tab->con[r].is_nonneg = 1;
1488         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1489                 return -1;
1490         if (tab->row_sign)
1491                 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1492
1493         return tab->con[r].index;
1494 }
1495
1496 /* Given a non-parametric tableau, add cuts until an integer
1497  * sample point is obtained or until the tableau is determined
1498  * to be integer infeasible.
1499  * As long as there is any non-integer value in the sample point,
1500  * we add an appropriate cut, if possible and resolve the violated
1501  * cut constraint using restore_lexmin.
1502  * If one of the corresponding rows is equal to an integral
1503  * combination of variables/constraints plus a non-integral constant,
1504  * then there is no way to obtain an integer point an we return
1505  * a tableau that is marked empty.
1506  */
1507 static struct isl_tab *cut_to_integer_lexmin(struct isl_tab *tab)
1508 {
1509         int row;
1510         int flags;
1511
1512         if (!tab)
1513                 return NULL;
1514         if (tab->empty)
1515                 return tab;
1516
1517         while ((row = first_non_integer(tab, &flags)) != -1) {
1518                 if (ISL_FL_ISSET(flags, I_VAR))
1519                         return isl_tab_mark_empty(tab);
1520                 row = add_cut(tab, row);
1521                 if (row < 0)
1522                         goto error;
1523                 tab = restore_lexmin(tab);
1524                 if (!tab || tab->empty)
1525                         break;
1526         }
1527         return tab;
1528 error:
1529         isl_tab_free(tab);
1530         return NULL;
1531 }
1532
1533 /* Check whether all the currently active samples also satisfy the inequality
1534  * "ineq" (treated as an equality if eq is set).
1535  * Remove those samples that do not.
1536  */
1537 static struct isl_tab *check_samples(struct isl_tab *tab, isl_int *ineq, int eq)
1538 {
1539         int i;
1540         isl_int v;
1541
1542         if (!tab)
1543                 return NULL;
1544
1545         isl_assert(tab->mat->ctx, tab->bset, goto error);
1546         isl_assert(tab->mat->ctx, tab->samples, goto error);
1547         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, goto error);
1548
1549         isl_int_init(v);
1550         for (i = tab->n_outside; i < tab->n_sample; ++i) {
1551                 int sgn;
1552                 isl_seq_inner_product(ineq, tab->samples->row[i],
1553                                         1 + tab->n_var, &v);
1554                 sgn = isl_int_sgn(v);
1555                 if (eq ? (sgn == 0) : (sgn >= 0))
1556                         continue;
1557                 tab = isl_tab_drop_sample(tab, i);
1558                 if (!tab)
1559                         break;
1560         }
1561         isl_int_clear(v);
1562
1563         return tab;
1564 error:
1565         isl_tab_free(tab);
1566         return NULL;
1567 }
1568
1569 /* Check whether the sample value of the tableau is finite,
1570  * i.e., either the tableau does not use a big parameter, or
1571  * all values of the variables are equal to the big parameter plus
1572  * some constant.  This constant is the actual sample value.
1573  */
1574 static int sample_is_finite(struct isl_tab *tab)
1575 {
1576         int i;
1577
1578         if (!tab->M)
1579                 return 1;
1580
1581         for (i = 0; i < tab->n_var; ++i) {
1582                 int row;
1583                 if (!tab->var[i].is_row)
1584                         return 0;
1585                 row = tab->var[i].index;
1586                 if (isl_int_ne(tab->mat->row[row][0], tab->mat->row[row][2]))
1587                         return 0;
1588         }
1589         return 1;
1590 }
1591
1592 /* Check if the context tableau of sol has any integer points.
1593  * Leave tab in empty state if no integer point can be found.
1594  * If an integer point can be found and if moreover it is finite,
1595  * then it is added to the list of sample values.
1596  *
1597  * This function is only called when none of the currently active sample
1598  * values satisfies the most recently added constraint.
1599  */
1600 static struct isl_tab *check_integer_feasible(struct isl_tab *tab)
1601 {
1602         struct isl_tab_undo *snap;
1603         int feasible;
1604
1605         if (!tab)
1606                 return NULL;
1607
1608         snap = isl_tab_snap(tab);
1609         if (isl_tab_push_basis(tab) < 0)
1610                 goto error;
1611
1612         tab = cut_to_integer_lexmin(tab);
1613         if (!tab)
1614                 goto error;
1615
1616         if (!tab->empty && sample_is_finite(tab)) {
1617                 struct isl_vec *sample;
1618
1619                 sample = isl_tab_get_sample_value(tab);
1620
1621                 tab = isl_tab_add_sample(tab, sample);
1622         }
1623
1624         if (!tab->empty && isl_tab_rollback(tab, snap) < 0)
1625                 goto error;
1626
1627         return tab;
1628 error:
1629         isl_tab_free(tab);
1630         return NULL;
1631 }
1632
1633 /* Check if any of the currently active sample values satisfies
1634  * the inequality "ineq" (an equality if eq is set).
1635  */
1636 static int tab_has_valid_sample(struct isl_tab *tab, isl_int *ineq, int eq)
1637 {
1638         int i;
1639         isl_int v;
1640
1641         if (!tab)
1642                 return -1;
1643
1644         isl_assert(tab->mat->ctx, tab->bset, return -1);
1645         isl_assert(tab->mat->ctx, tab->samples, return -1);
1646         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, return -1);
1647
1648         isl_int_init(v);
1649         for (i = tab->n_outside; i < tab->n_sample; ++i) {
1650                 int sgn;
1651                 isl_seq_inner_product(ineq, tab->samples->row[i],
1652                                         1 + tab->n_var, &v);
1653                 sgn = isl_int_sgn(v);
1654                 if (eq ? (sgn == 0) : (sgn >= 0))
1655                         break;
1656         }
1657         isl_int_clear(v);
1658
1659         return i < tab->n_sample;
1660 }
1661
1662 /* For a div d = floor(f/m), add the constraints
1663  *
1664  *              f - m d >= 0
1665  *              -(f-(m-1)) + m d >= 0
1666  *
1667  * Note that the second constraint is the negation of
1668  *
1669  *              f - m d >= m
1670  */
1671 static void add_div_constraints(struct isl_context *context, unsigned div)
1672 {
1673         unsigned total;
1674         unsigned div_pos;
1675         struct isl_vec *ineq;
1676         struct isl_basic_set *bset;
1677
1678         bset = context->op->peek_basic_set(context);
1679         if (!bset)
1680                 goto error;
1681
1682         total = isl_basic_set_total_dim(bset);
1683         div_pos = 1 + total - bset->n_div + div;
1684
1685         ineq = ineq_for_div(bset, div);
1686         if (!ineq)
1687                 goto error;
1688
1689         context->op->add_ineq(context, ineq->el, 0, 0);
1690
1691         isl_seq_neg(ineq->el, bset->div[div] + 1, 1 + total);
1692         isl_int_set(ineq->el[div_pos], bset->div[div][0]);
1693         isl_int_add(ineq->el[0], ineq->el[0], ineq->el[div_pos]);
1694         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
1695
1696         context->op->add_ineq(context, ineq->el, 0, 0);
1697
1698         isl_vec_free(ineq);
1699
1700         return;
1701 error:
1702         context->op->invalidate(context);
1703 }
1704
1705 /* Add a div specifed by "div" to the tableau "tab" and return
1706  * the index of the new div.  *nonneg is set to 1 if the div
1707  * is obviously non-negative.
1708  */
1709 static int context_tab_add_div(struct isl_tab *tab, struct isl_vec *div,
1710         int *nonneg)
1711 {
1712         int i;
1713         int r;
1714         int k;
1715         struct isl_mat *samples;
1716
1717         for (i = 0; i < tab->n_var; ++i) {
1718                 if (isl_int_is_zero(div->el[2 + i]))
1719                         continue;
1720                 if (!tab->var[i].is_nonneg)
1721                         break;
1722         }
1723         *nonneg = i == tab->n_var;
1724
1725         if (isl_tab_extend_cons(tab, 3) < 0)
1726                 return -1;
1727         if (isl_tab_extend_vars(tab, 1) < 0)
1728                 return -1;
1729         r = isl_tab_allocate_var(tab);
1730         if (r < 0)
1731                 return -1;
1732         if (*nonneg)
1733                 tab->var[r].is_nonneg = 1;
1734         tab->var[r].frozen = 1;
1735
1736         samples = isl_mat_extend(tab->samples,
1737                         tab->n_sample, 1 + tab->n_var);
1738         tab->samples = samples;
1739         if (!samples)
1740                 return -1;
1741         for (i = tab->n_outside; i < samples->n_row; ++i) {
1742                 isl_seq_inner_product(div->el + 1, samples->row[i],
1743                         div->size - 1, &samples->row[i][samples->n_col - 1]);
1744                 isl_int_fdiv_q(samples->row[i][samples->n_col - 1],
1745                                samples->row[i][samples->n_col - 1], div->el[0]);
1746         }
1747
1748         tab->bset = isl_basic_set_extend_dim(tab->bset,
1749                 isl_basic_set_get_dim(tab->bset), 1, 0, 2);
1750         k = isl_basic_set_alloc_div(tab->bset);
1751         if (k < 0)
1752                 return -1;
1753         isl_seq_cpy(tab->bset->div[k], div->el, div->size);
1754         if (isl_tab_push(tab, isl_tab_undo_bset_div) < 0)
1755                 return -1;
1756
1757         return k;
1758 }
1759
1760 /* Add a div specified by "div" to both the main tableau and
1761  * the context tableau.  In case of the main tableau, we only
1762  * need to add an extra div.  In the context tableau, we also
1763  * need to express the meaning of the div.
1764  * Return the index of the div or -1 if anything went wrong.
1765  */
1766 static int add_div(struct isl_tab *tab, struct isl_context *context,
1767         struct isl_vec *div)
1768 {
1769         int r;
1770         int k;
1771         int nonneg;
1772
1773         k = context->op->add_div(context, div, &nonneg);
1774         if (k < 0)
1775                 goto error;
1776
1777         add_div_constraints(context, k);
1778         if (!context->op->is_ok(context))
1779                 goto error;
1780
1781         if (isl_tab_extend_vars(tab, 1) < 0)
1782                 goto error;
1783         r = isl_tab_allocate_var(tab);
1784         if (r < 0)
1785                 goto error;
1786         if (nonneg)
1787                 tab->var[r].is_nonneg = 1;
1788         tab->var[r].frozen = 1;
1789         tab->n_div++;
1790
1791         return tab->n_div - 1;
1792 error:
1793         context->op->invalidate(context);
1794         return -1;
1795 }
1796
1797 static int find_div(struct isl_tab *tab, isl_int *div, isl_int denom)
1798 {
1799         int i;
1800         unsigned total = isl_basic_set_total_dim(tab->bset);
1801
1802         for (i = 0; i < tab->bset->n_div; ++i) {
1803                 if (isl_int_ne(tab->bset->div[i][0], denom))
1804                         continue;
1805                 if (!isl_seq_eq(tab->bset->div[i] + 1, div, total))
1806                         continue;
1807                 return i;
1808         }
1809         return -1;
1810 }
1811
1812 /* Return the index of a div that corresponds to "div".
1813  * We first check if we already have such a div and if not, we create one.
1814  */
1815 static int get_div(struct isl_tab *tab, struct isl_context *context,
1816         struct isl_vec *div)
1817 {
1818         int d;
1819         struct isl_tab *context_tab = context->op->peek_tab(context);
1820
1821         if (!context_tab)
1822                 return -1;
1823
1824         d = find_div(context_tab, div->el + 1, div->el[0]);
1825         if (d != -1)
1826                 return d;
1827
1828         return add_div(tab, context, div);
1829 }
1830
1831 /* Add a parametric cut to cut away the non-integral sample value
1832  * of the give row.
1833  * Let a_i be the coefficients of the constant term and the parameters
1834  * and let b_i be the coefficients of the variables or constraints
1835  * in basis of the tableau.
1836  * Let q be the div q = floor(\sum_i {-a_i} y_i).
1837  *
1838  * The cut is expressed as
1839  *
1840  *      c = \sum_i -{-a_i} y_i + \sum_i {b_i} x_i + q >= 0
1841  *
1842  * If q did not already exist in the context tableau, then it is added first.
1843  * If q is in a column of the main tableau then the "+ q" can be accomplished
1844  * by setting the corresponding entry to the denominator of the constraint.
1845  * If q happens to be in a row of the main tableau, then the corresponding
1846  * row needs to be added instead (taking care of the denominators).
1847  * Note that this is very unlikely, but perhaps not entirely impossible.
1848  *
1849  * The current value of the cut is known to be negative (or at least
1850  * non-positive), so row_sign is set accordingly.
1851  *
1852  * Return the row of the cut or -1.
1853  */
1854 static int add_parametric_cut(struct isl_tab *tab, int row,
1855         struct isl_context *context)
1856 {
1857         struct isl_vec *div;
1858         int d;
1859         int i;
1860         int r;
1861         isl_int *r_row;
1862         int col;
1863         int n;
1864         unsigned off = 2 + tab->M;
1865
1866         if (!context)
1867                 return -1;
1868
1869         div = get_row_parameter_div(tab, row);
1870         if (!div)
1871                 return -1;
1872
1873         n = tab->n_div;
1874         d = context->op->get_div(context, tab, div);
1875         if (d < 0)
1876                 return -1;
1877
1878         if (isl_tab_extend_cons(tab, 1) < 0)
1879                 return -1;
1880         r = isl_tab_allocate_con(tab);
1881         if (r < 0)
1882                 return -1;
1883
1884         r_row = tab->mat->row[tab->con[r].index];
1885         isl_int_set(r_row[0], tab->mat->row[row][0]);
1886         isl_int_neg(r_row[1], tab->mat->row[row][1]);
1887         isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1888         isl_int_neg(r_row[1], r_row[1]);
1889         if (tab->M)
1890                 isl_int_set_si(r_row[2], 0);
1891         for (i = 0; i < tab->n_param; ++i) {
1892                 if (tab->var[i].is_row)
1893                         continue;
1894                 col = tab->var[i].index;
1895                 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
1896                 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
1897                                 tab->mat->row[row][0]);
1898                 isl_int_neg(r_row[off + col], r_row[off + col]);
1899         }
1900         for (i = 0; i < tab->n_div; ++i) {
1901                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1902                         continue;
1903                 col = tab->var[tab->n_var - tab->n_div + i].index;
1904                 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
1905                 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
1906                                 tab->mat->row[row][0]);
1907                 isl_int_neg(r_row[off + col], r_row[off + col]);
1908         }
1909         for (i = 0; i < tab->n_col; ++i) {
1910                 if (tab->col_var[i] >= 0 &&
1911                     (tab->col_var[i] < tab->n_param ||
1912                      tab->col_var[i] >= tab->n_var - tab->n_div))
1913                         continue;
1914                 isl_int_fdiv_r(r_row[off + i],
1915                         tab->mat->row[row][off + i], tab->mat->row[row][0]);
1916         }
1917         if (tab->var[tab->n_var - tab->n_div + d].is_row) {
1918                 isl_int gcd;
1919                 int d_row = tab->var[tab->n_var - tab->n_div + d].index;
1920                 isl_int_init(gcd);
1921                 isl_int_gcd(gcd, tab->mat->row[d_row][0], r_row[0]);
1922                 isl_int_divexact(r_row[0], r_row[0], gcd);
1923                 isl_int_divexact(gcd, tab->mat->row[d_row][0], gcd);
1924                 isl_seq_combine(r_row + 1, gcd, r_row + 1,
1925                                 r_row[0], tab->mat->row[d_row] + 1,
1926                                 off - 1 + tab->n_col);
1927                 isl_int_mul(r_row[0], r_row[0], tab->mat->row[d_row][0]);
1928                 isl_int_clear(gcd);
1929         } else {
1930                 col = tab->var[tab->n_var - tab->n_div + d].index;
1931                 isl_int_set(r_row[off + col], tab->mat->row[row][0]);
1932         }
1933
1934         tab->con[r].is_nonneg = 1;
1935         if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1936                 return -1;
1937         if (tab->row_sign)
1938                 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1939
1940         isl_vec_free(div);
1941
1942         row = tab->con[r].index;
1943
1944         if (d >= n && context->op->detect_equalities(context, tab) < 0)
1945                 return -1;
1946
1947         return row;
1948 }
1949
1950 /* Construct a tableau for bmap that can be used for computing
1951  * the lexicographic minimum (or maximum) of bmap.
1952  * If not NULL, then dom is the domain where the minimum
1953  * should be computed.  In this case, we set up a parametric
1954  * tableau with row signs (initialized to "unknown").
1955  * If M is set, then the tableau will use a big parameter.
1956  * If max is set, then a maximum should be computed instead of a minimum.
1957  * This means that for each variable x, the tableau will contain the variable
1958  * x' = M - x, rather than x' = M + x.  This in turn means that the coefficient
1959  * of the variables in all constraints are negated prior to adding them
1960  * to the tableau.
1961  */
1962 static struct isl_tab *tab_for_lexmin(struct isl_basic_map *bmap,
1963         struct isl_basic_set *dom, unsigned M, int max)
1964 {
1965         int i;
1966         struct isl_tab *tab;
1967
1968         tab = isl_tab_alloc(bmap->ctx, 2 * bmap->n_eq + bmap->n_ineq + 1,
1969                             isl_basic_map_total_dim(bmap), M);
1970         if (!tab)
1971                 return NULL;
1972
1973         tab->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
1974         if (dom) {
1975                 tab->n_param = isl_basic_set_total_dim(dom) - dom->n_div;
1976                 tab->n_div = dom->n_div;
1977                 tab->row_sign = isl_calloc_array(bmap->ctx,
1978                                         enum isl_tab_row_sign, tab->mat->n_row);
1979                 if (!tab->row_sign)
1980                         goto error;
1981         }
1982         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
1983                 return isl_tab_mark_empty(tab);
1984
1985         for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
1986                 tab->var[i].is_nonneg = 1;
1987                 tab->var[i].frozen = 1;
1988         }
1989         for (i = 0; i < bmap->n_eq; ++i) {
1990                 if (max)
1991                         isl_seq_neg(bmap->eq[i] + 1 + tab->n_param,
1992                                     bmap->eq[i] + 1 + tab->n_param,
1993                                     tab->n_var - tab->n_param - tab->n_div);
1994                 tab = add_lexmin_valid_eq(tab, bmap->eq[i]);
1995                 if (max)
1996                         isl_seq_neg(bmap->eq[i] + 1 + tab->n_param,
1997                                     bmap->eq[i] + 1 + tab->n_param,
1998                                     tab->n_var - tab->n_param - tab->n_div);
1999                 if (!tab || tab->empty)
2000                         return tab;
2001         }
2002         for (i = 0; i < bmap->n_ineq; ++i) {
2003                 if (max)
2004                         isl_seq_neg(bmap->ineq[i] + 1 + tab->n_param,
2005                                     bmap->ineq[i] + 1 + tab->n_param,
2006                                     tab->n_var - tab->n_param - tab->n_div);
2007                 tab = add_lexmin_ineq(tab, bmap->ineq[i]);
2008                 if (max)
2009                         isl_seq_neg(bmap->ineq[i] + 1 + tab->n_param,
2010                                     bmap->ineq[i] + 1 + tab->n_param,
2011                                     tab->n_var - tab->n_param - tab->n_div);
2012                 if (!tab || tab->empty)
2013                         return tab;
2014         }
2015         return tab;
2016 error:
2017         isl_tab_free(tab);
2018         return NULL;
2019 }
2020
2021 /* Given a main tableau where more than one row requires a split,
2022  * determine and return the "best" row to split on.
2023  *
2024  * Given two rows in the main tableau, if the inequality corresponding
2025  * to the first row is redundant with respect to that of the second row
2026  * in the current tableau, then it is better to split on the second row,
2027  * since in the positive part, both row will be positive.
2028  * (In the negative part a pivot will have to be performed and just about
2029  * anything can happen to the sign of the other row.)
2030  *
2031  * As a simple heuristic, we therefore select the row that makes the most
2032  * of the other rows redundant.
2033  *
2034  * Perhaps it would also be useful to look at the number of constraints
2035  * that conflict with any given constraint.
2036  */
2037 static int best_split(struct isl_tab *tab, struct isl_tab *context_tab)
2038 {
2039         struct isl_tab_undo *snap;
2040         int split;
2041         int row;
2042         int best = -1;
2043         int best_r;
2044
2045         if (isl_tab_extend_cons(context_tab, 2) < 0)
2046                 return -1;
2047
2048         snap = isl_tab_snap(context_tab);
2049
2050         for (split = tab->n_redundant; split < tab->n_row; ++split) {
2051                 struct isl_tab_undo *snap2;
2052                 struct isl_vec *ineq = NULL;
2053                 int r = 0;
2054
2055                 if (!isl_tab_var_from_row(tab, split)->is_nonneg)
2056                         continue;
2057                 if (tab->row_sign[split] != isl_tab_row_any)
2058                         continue;
2059
2060                 ineq = get_row_parameter_ineq(tab, split);
2061                 if (!ineq)
2062                         return -1;
2063                 context_tab = isl_tab_add_ineq(context_tab, ineq->el);
2064                 isl_vec_free(ineq);
2065
2066                 snap2 = isl_tab_snap(context_tab);
2067
2068                 for (row = tab->n_redundant; row < tab->n_row; ++row) {
2069                         struct isl_tab_var *var;
2070
2071                         if (row == split)
2072                                 continue;
2073                         if (!isl_tab_var_from_row(tab, row)->is_nonneg)
2074                                 continue;
2075                         if (tab->row_sign[row] != isl_tab_row_any)
2076                                 continue;
2077
2078                         ineq = get_row_parameter_ineq(tab, row);
2079                         if (!ineq)
2080                                 return -1;
2081                         context_tab = isl_tab_add_ineq(context_tab, ineq->el);
2082                         isl_vec_free(ineq);
2083                         var = &context_tab->con[context_tab->n_con - 1];
2084                         if (!context_tab->empty &&
2085                             !isl_tab_min_at_most_neg_one(context_tab, var))
2086                                 r++;
2087                         if (isl_tab_rollback(context_tab, snap2) < 0)
2088                                 return -1;
2089                 }
2090                 if (best == -1 || r > best_r) {
2091                         best = split;
2092                         best_r = r;
2093                 }
2094                 if (isl_tab_rollback(context_tab, snap) < 0)
2095                         return -1;
2096         }
2097
2098         return best;
2099 }
2100
2101 static struct isl_basic_set *context_lex_peek_basic_set(
2102         struct isl_context *context)
2103 {
2104         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2105         if (!clex->tab)
2106                 return NULL;
2107         return clex->tab->bset;
2108 }
2109
2110 static struct isl_tab *context_lex_peek_tab(struct isl_context *context)
2111 {
2112         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2113         return clex->tab;
2114 }
2115
2116 static void context_lex_extend(struct isl_context *context, int n)
2117 {
2118         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2119         if (!clex->tab)
2120                 return;
2121         if (isl_tab_extend_cons(clex->tab, n) >= 0)
2122                 return;
2123         isl_tab_free(clex->tab);
2124         clex->tab = NULL;
2125 }
2126
2127 static void context_lex_add_eq(struct isl_context *context, isl_int *eq,
2128                 int check, int update)
2129 {
2130         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2131         if (isl_tab_extend_cons(clex->tab, 2) < 0)
2132                 goto error;
2133         clex->tab = add_lexmin_eq(clex->tab, eq);
2134         if (check) {
2135                 int v = tab_has_valid_sample(clex->tab, eq, 1);
2136                 if (v < 0)
2137                         goto error;
2138                 if (!v)
2139                         clex->tab = check_integer_feasible(clex->tab);
2140         }
2141         if (update)
2142                 clex->tab = check_samples(clex->tab, eq, 1);
2143         return;
2144 error:
2145         isl_tab_free(clex->tab);
2146         clex->tab = NULL;
2147 }
2148
2149 static void context_lex_add_ineq(struct isl_context *context, isl_int *ineq,
2150                 int check, int update)
2151 {
2152         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2153         if (isl_tab_extend_cons(clex->tab, 1) < 0)
2154                 goto error;
2155         clex->tab = add_lexmin_ineq(clex->tab, ineq);
2156         if (check) {
2157                 int v = tab_has_valid_sample(clex->tab, ineq, 0);
2158                 if (v < 0)
2159                         goto error;
2160                 if (!v)
2161                         clex->tab = check_integer_feasible(clex->tab);
2162         }
2163         if (update)
2164                 clex->tab = check_samples(clex->tab, ineq, 0);
2165         return;
2166 error:
2167         isl_tab_free(clex->tab);
2168         clex->tab = NULL;
2169 }
2170
2171 /* Check which signs can be obtained by "ineq" on all the currently
2172  * active sample values.  See row_sign for more information.
2173  */
2174 static enum isl_tab_row_sign tab_ineq_sign(struct isl_tab *tab, isl_int *ineq,
2175         int strict)
2176 {
2177         int i;
2178         int sgn;
2179         isl_int tmp;
2180         int res = isl_tab_row_unknown;
2181
2182         isl_assert(tab->mat->ctx, tab->samples, return 0);
2183         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, return 0);
2184
2185         isl_int_init(tmp);
2186         for (i = tab->n_outside; i < tab->n_sample; ++i) {
2187                 isl_seq_inner_product(tab->samples->row[i], ineq,
2188                                         1 + tab->n_var, &tmp);
2189                 sgn = isl_int_sgn(tmp);
2190                 if (sgn > 0 || (sgn == 0 && strict)) {
2191                         if (res == isl_tab_row_unknown)
2192                                 res = isl_tab_row_pos;
2193                         if (res == isl_tab_row_neg)
2194                                 res = isl_tab_row_any;
2195                 }
2196                 if (sgn < 0) {
2197                         if (res == isl_tab_row_unknown)
2198                                 res = isl_tab_row_neg;
2199                         if (res == isl_tab_row_pos)
2200                                 res = isl_tab_row_any;
2201                 }
2202                 if (res == isl_tab_row_any)
2203                         break;
2204         }
2205         isl_int_clear(tmp);
2206
2207         return res;
2208 }
2209
2210 static enum isl_tab_row_sign context_lex_ineq_sign(struct isl_context *context,
2211                         isl_int *ineq, int strict)
2212 {
2213         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2214         return tab_ineq_sign(clex->tab, ineq, strict);
2215 }
2216
2217 /* Check whether "ineq" can be added to the tableau without rendering
2218  * it infeasible.
2219  */
2220 static int context_lex_test_ineq(struct isl_context *context, isl_int *ineq)
2221 {
2222         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2223         struct isl_tab_undo *snap;
2224         int feasible;
2225
2226         if (!clex->tab)
2227                 return -1;
2228
2229         if (isl_tab_extend_cons(clex->tab, 1) < 0)
2230                 return -1;
2231
2232         snap = isl_tab_snap(clex->tab);
2233         if (isl_tab_push_basis(clex->tab) < 0)
2234                 return -1;
2235         clex->tab = add_lexmin_ineq(clex->tab, ineq);
2236         clex->tab = check_integer_feasible(clex->tab);
2237         if (!clex->tab)
2238                 return -1;
2239         feasible = !clex->tab->empty;
2240         if (isl_tab_rollback(clex->tab, snap) < 0)
2241                 return -1;
2242
2243         return feasible;
2244 }
2245
2246 static int context_lex_get_div(struct isl_context *context, struct isl_tab *tab,
2247                 struct isl_vec *div)
2248 {
2249         return get_div(tab, context, div);
2250 }
2251
2252 static int context_lex_add_div(struct isl_context *context, struct isl_vec *div,
2253         int *nonneg)
2254 {
2255         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2256         return context_tab_add_div(clex->tab, div, nonneg);
2257 }
2258
2259 static int context_lex_detect_equalities(struct isl_context *context,
2260                 struct isl_tab *tab)
2261 {
2262         return 0;
2263 }
2264
2265 static int context_lex_best_split(struct isl_context *context,
2266                 struct isl_tab *tab)
2267 {
2268         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2269         struct isl_tab_undo *snap;
2270         int r;
2271
2272         snap = isl_tab_snap(clex->tab);
2273         if (isl_tab_push_basis(clex->tab) < 0)
2274                 return -1;
2275         r = best_split(tab, clex->tab);
2276
2277         if (isl_tab_rollback(clex->tab, snap) < 0)
2278                 return -1;
2279
2280         return r;
2281 }
2282
2283 static int context_lex_is_empty(struct isl_context *context)
2284 {
2285         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2286         if (!clex->tab)
2287                 return -1;
2288         return clex->tab->empty;
2289 }
2290
2291 static void *context_lex_save(struct isl_context *context)
2292 {
2293         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2294         struct isl_tab_undo *snap;
2295
2296         snap = isl_tab_snap(clex->tab);
2297         if (isl_tab_push_basis(clex->tab) < 0)
2298                 return NULL;
2299         if (isl_tab_save_samples(clex->tab) < 0)
2300                 return NULL;
2301
2302         return snap;
2303 }
2304
2305 static void context_lex_restore(struct isl_context *context, void *save)
2306 {
2307         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2308         if (isl_tab_rollback(clex->tab, (struct isl_tab_undo *)save) < 0) {
2309                 isl_tab_free(clex->tab);
2310                 clex->tab = NULL;
2311         }
2312 }
2313
2314 static int context_lex_is_ok(struct isl_context *context)
2315 {
2316         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2317         return !!clex->tab;
2318 }
2319
2320 /* For each variable in the context tableau, check if the variable can
2321  * only attain non-negative values.  If so, mark the parameter as non-negative
2322  * in the main tableau.  This allows for a more direct identification of some
2323  * cases of violated constraints.
2324  */
2325 static struct isl_tab *tab_detect_nonnegative_parameters(struct isl_tab *tab,
2326         struct isl_tab *context_tab)
2327 {
2328         int i;
2329         struct isl_tab_undo *snap;
2330         struct isl_vec *ineq = NULL;
2331         struct isl_tab_var *var;
2332         int n;
2333
2334         if (context_tab->n_var == 0)
2335                 return tab;
2336
2337         ineq = isl_vec_alloc(tab->mat->ctx, 1 + context_tab->n_var);
2338         if (!ineq)
2339                 goto error;
2340
2341         if (isl_tab_extend_cons(context_tab, 1) < 0)
2342                 goto error;
2343
2344         snap = isl_tab_snap(context_tab);
2345
2346         n = 0;
2347         isl_seq_clr(ineq->el, ineq->size);
2348         for (i = 0; i < context_tab->n_var; ++i) {
2349                 isl_int_set_si(ineq->el[1 + i], 1);
2350                 context_tab = isl_tab_add_ineq(context_tab, ineq->el);
2351                 var = &context_tab->con[context_tab->n_con - 1];
2352                 if (!context_tab->empty &&
2353                     !isl_tab_min_at_most_neg_one(context_tab, var)) {
2354                         int j = i;
2355                         if (i >= tab->n_param)
2356                                 j = i - tab->n_param + tab->n_var - tab->n_div;
2357                         tab->var[j].is_nonneg = 1;
2358                         n++;
2359                 }
2360                 isl_int_set_si(ineq->el[1 + i], 0);
2361                 if (isl_tab_rollback(context_tab, snap) < 0)
2362                         goto error;
2363         }
2364
2365         if (context_tab->M && n == context_tab->n_var) {
2366                 context_tab->mat = isl_mat_drop_cols(context_tab->mat, 2, 1);
2367                 context_tab->M = 0;
2368         }
2369
2370         isl_vec_free(ineq);
2371         return tab;
2372 error:
2373         isl_vec_free(ineq);
2374         isl_tab_free(tab);
2375         return NULL;
2376 }
2377
2378 static struct isl_tab *context_lex_detect_nonnegative_parameters(
2379         struct isl_context *context, struct isl_tab *tab)
2380 {
2381         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2382         struct isl_tab_undo *snap;
2383
2384         snap = isl_tab_snap(clex->tab);
2385         if (isl_tab_push_basis(clex->tab) < 0)
2386                 goto error;
2387
2388         tab = tab_detect_nonnegative_parameters(tab, clex->tab);
2389
2390         if (isl_tab_rollback(clex->tab, snap) < 0)
2391                 goto error;
2392
2393         return tab;
2394 error:
2395         isl_tab_free(tab);
2396         return NULL;
2397 }
2398
2399 static void context_lex_invalidate(struct isl_context *context)
2400 {
2401         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2402         isl_tab_free(clex->tab);
2403         clex->tab = NULL;
2404 }
2405
2406 static void context_lex_free(struct isl_context *context)
2407 {
2408         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2409         isl_tab_free(clex->tab);
2410         free(clex);
2411 }
2412
2413 struct isl_context_op isl_context_lex_op = {
2414         context_lex_detect_nonnegative_parameters,
2415         context_lex_peek_basic_set,
2416         context_lex_peek_tab,
2417         context_lex_add_eq,
2418         context_lex_add_ineq,
2419         context_lex_ineq_sign,
2420         context_lex_test_ineq,
2421         context_lex_get_div,
2422         context_lex_add_div,
2423         context_lex_detect_equalities,
2424         context_lex_best_split,
2425         context_lex_is_empty,
2426         context_lex_is_ok,
2427         context_lex_save,
2428         context_lex_restore,
2429         context_lex_invalidate,
2430         context_lex_free,
2431 };
2432
2433 static struct isl_tab *context_tab_for_lexmin(struct isl_basic_set *bset)
2434 {
2435         struct isl_tab *tab;
2436
2437         bset = isl_basic_set_cow(bset);
2438         if (!bset)
2439                 return NULL;
2440         tab = tab_for_lexmin((struct isl_basic_map *)bset, NULL, 1, 0);
2441         if (!tab)
2442                 goto error;
2443         tab->bset = bset;
2444         tab = isl_tab_init_samples(tab);
2445         return tab;
2446 error:
2447         isl_basic_set_free(bset);
2448         return NULL;
2449 }
2450
2451 static struct isl_context *isl_context_lex_alloc(struct isl_basic_set *dom)
2452 {
2453         struct isl_context_lex *clex;
2454
2455         if (!dom)
2456                 return NULL;
2457
2458         clex = isl_alloc_type(dom->ctx, struct isl_context_lex);
2459         if (!clex)
2460                 return NULL;
2461
2462         clex->context.op = &isl_context_lex_op;
2463
2464         clex->tab = context_tab_for_lexmin(isl_basic_set_copy(dom));
2465         clex->tab = restore_lexmin(clex->tab);
2466         clex->tab = check_integer_feasible(clex->tab);
2467         if (!clex->tab)
2468                 goto error;
2469
2470         return &clex->context;
2471 error:
2472         clex->context.op->free(&clex->context);
2473         return NULL;
2474 }
2475
2476 struct isl_context_gbr {
2477         struct isl_context context;
2478         struct isl_tab *tab;
2479         struct isl_tab *shifted;
2480         struct isl_tab *cone;
2481 };
2482
2483 static struct isl_tab *context_gbr_detect_nonnegative_parameters(
2484         struct isl_context *context, struct isl_tab *tab)
2485 {
2486         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2487         return tab_detect_nonnegative_parameters(tab, cgbr->tab);
2488 }
2489
2490 static struct isl_basic_set *context_gbr_peek_basic_set(
2491         struct isl_context *context)
2492 {
2493         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2494         if (!cgbr->tab)
2495                 return NULL;
2496         return cgbr->tab->bset;
2497 }
2498
2499 static struct isl_tab *context_gbr_peek_tab(struct isl_context *context)
2500 {
2501         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2502         return cgbr->tab;
2503 }
2504
2505 /* Initialize the "shifted" tableau of the context, which
2506  * contains the constraints of the original tableau shifted
2507  * by the sum of all negative coefficients.  This ensures
2508  * that any rational point in the shifted tableau can
2509  * be rounded up to yield an integer point in the original tableau.
2510  */
2511 static void gbr_init_shifted(struct isl_context_gbr *cgbr)
2512 {
2513         int i, j;
2514         struct isl_vec *cst;
2515         struct isl_basic_set *bset = cgbr->tab->bset;
2516         unsigned dim = isl_basic_set_total_dim(bset);
2517
2518         cst = isl_vec_alloc(cgbr->tab->mat->ctx, bset->n_ineq);
2519         if (!cst)
2520                 return;
2521
2522         for (i = 0; i < bset->n_ineq; ++i) {
2523                 isl_int_set(cst->el[i], bset->ineq[i][0]);
2524                 for (j = 0; j < dim; ++j) {
2525                         if (!isl_int_is_neg(bset->ineq[i][1 + j]))
2526                                 continue;
2527                         isl_int_add(bset->ineq[i][0], bset->ineq[i][0],
2528                                     bset->ineq[i][1 + j]);
2529                 }
2530         }
2531
2532         cgbr->shifted = isl_tab_from_basic_set(bset);
2533
2534         for (i = 0; i < bset->n_ineq; ++i)
2535                 isl_int_set(bset->ineq[i][0], cst->el[i]);
2536
2537         isl_vec_free(cst);
2538 }
2539
2540 /* Check if the shifted tableau is non-empty, and if so
2541  * use the sample point to construct an integer point
2542  * of the context tableau.
2543  */
2544 static struct isl_vec *gbr_get_shifted_sample(struct isl_context_gbr *cgbr)
2545 {
2546         struct isl_vec *sample;
2547
2548         if (!cgbr->shifted)
2549                 gbr_init_shifted(cgbr);
2550         if (!cgbr->shifted)
2551                 return NULL;
2552         if (cgbr->shifted->empty)
2553                 return isl_vec_alloc(cgbr->tab->mat->ctx, 0);
2554
2555         sample = isl_tab_get_sample_value(cgbr->shifted);
2556         sample = isl_vec_ceil(sample);
2557
2558         return sample;
2559 }
2560
2561 static struct isl_basic_set *drop_constant_terms(struct isl_basic_set *bset)
2562 {
2563         int i;
2564
2565         if (!bset)
2566                 return NULL;
2567
2568         for (i = 0; i < bset->n_eq; ++i)
2569                 isl_int_set_si(bset->eq[i][0], 0);
2570
2571         for (i = 0; i < bset->n_ineq; ++i)
2572                 isl_int_set_si(bset->ineq[i][0], 0);
2573
2574         return bset;
2575 }
2576
2577 static int use_shifted(struct isl_context_gbr *cgbr)
2578 {
2579         return cgbr->tab->bset->n_eq == 0 && cgbr->tab->bset->n_div == 0;
2580 }
2581
2582 static struct isl_vec *gbr_get_sample(struct isl_context_gbr *cgbr)
2583 {
2584         struct isl_basic_set *bset;
2585         struct isl_basic_set *cone;
2586
2587         if (isl_tab_sample_is_integer(cgbr->tab))
2588                 return isl_tab_get_sample_value(cgbr->tab);
2589
2590         if (use_shifted(cgbr)) {
2591                 struct isl_vec *sample;
2592
2593                 sample = gbr_get_shifted_sample(cgbr);
2594                 if (!sample || sample->size > 0)
2595                         return sample;
2596
2597                 isl_vec_free(sample);
2598         }
2599
2600         if (!cgbr->cone) {
2601                 cgbr->cone = isl_tab_from_recession_cone(cgbr->tab->bset);
2602                 if (!cgbr->cone)
2603                         return NULL;
2604                 cgbr->cone->bset = isl_basic_set_dup(cgbr->tab->bset);
2605         }
2606         cgbr->cone = isl_tab_detect_implicit_equalities(cgbr->cone);
2607         if (!cgbr->cone)
2608                 return NULL;
2609
2610         if (cgbr->cone->n_dead == cgbr->cone->n_col) {
2611                 struct isl_vec *sample;
2612                 struct isl_tab_undo *snap;
2613
2614                 if (cgbr->tab->basis) {
2615                         if (cgbr->tab->basis->n_col != 1 + cgbr->tab->n_var) {
2616                                 isl_mat_free(cgbr->tab->basis);
2617                                 cgbr->tab->basis = NULL;
2618                         } else {
2619                                 cgbr->tab->n_zero = 0;
2620                                 cgbr->tab->n_unbounded = 0;
2621                         }
2622                 }
2623
2624                 snap = isl_tab_snap(cgbr->tab);
2625
2626                 sample = isl_tab_sample(cgbr->tab);
2627
2628                 if (isl_tab_rollback(cgbr->tab, snap) < 0) {
2629                         isl_vec_free(sample);
2630                         return NULL;
2631                 }
2632
2633                 return sample;
2634         }
2635
2636         cone = isl_basic_set_dup(cgbr->cone->bset);
2637         cone = drop_constant_terms(cone);
2638         cone = isl_basic_set_update_from_tab(cone, cgbr->cone);
2639         cone = isl_basic_set_underlying_set(cone);
2640         cone = isl_basic_set_gauss(cone, NULL);
2641
2642         bset = isl_basic_set_dup(cgbr->tab->bset);
2643         bset = isl_basic_set_update_from_tab(bset, cgbr->tab);
2644         bset = isl_basic_set_underlying_set(bset);
2645         bset = isl_basic_set_gauss(bset, NULL);
2646
2647         return isl_basic_set_sample_with_cone(bset, cone);
2648 }
2649
2650 static void check_gbr_integer_feasible(struct isl_context_gbr *cgbr)
2651 {
2652         struct isl_vec *sample;
2653
2654         if (!cgbr->tab)
2655                 return;
2656
2657         if (cgbr->tab->empty)
2658                 return;
2659
2660         sample = gbr_get_sample(cgbr);
2661         if (!sample)
2662                 goto error;
2663
2664         if (sample->size == 0) {
2665                 isl_vec_free(sample);
2666                 cgbr->tab = isl_tab_mark_empty(cgbr->tab);
2667                 return;
2668         }
2669
2670         cgbr->tab = isl_tab_add_sample(cgbr->tab, sample);
2671
2672         return;
2673 error:
2674         isl_tab_free(cgbr->tab);
2675         cgbr->tab = NULL;
2676 }
2677
2678 static struct isl_tab *add_gbr_eq(struct isl_tab *tab, isl_int *eq)
2679 {
2680         int r;
2681
2682         if (!tab)
2683                 return NULL;
2684
2685         if (isl_tab_extend_cons(tab, 2) < 0)
2686                 goto error;
2687
2688         tab = isl_tab_add_eq(tab, eq);
2689
2690         return tab;
2691 error:
2692         isl_tab_free(tab);
2693         return NULL;
2694 }
2695
2696 static void context_gbr_add_eq(struct isl_context *context, isl_int *eq,
2697                 int check, int update)
2698 {
2699         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2700
2701         cgbr->tab = add_gbr_eq(cgbr->tab, eq);
2702
2703         if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
2704                 if (isl_tab_extend_cons(cgbr->cone, 2) < 0)
2705                         goto error;
2706                 cgbr->cone = isl_tab_add_eq(cgbr->cone, eq);
2707         }
2708
2709         if (check) {
2710                 int v = tab_has_valid_sample(cgbr->tab, eq, 1);
2711                 if (v < 0)
2712                         goto error;
2713                 if (!v)
2714                         check_gbr_integer_feasible(cgbr);
2715         }
2716         if (update)
2717                 cgbr->tab = check_samples(cgbr->tab, eq, 1);
2718         return;
2719 error:
2720         isl_tab_free(cgbr->tab);
2721         cgbr->tab = NULL;
2722 }
2723
2724 static void add_gbr_ineq(struct isl_context_gbr *cgbr, isl_int *ineq)
2725 {
2726         if (!cgbr->tab)
2727                 return;
2728
2729         if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
2730                 goto error;
2731
2732         cgbr->tab = isl_tab_add_ineq(cgbr->tab, ineq);
2733
2734         if (cgbr->shifted && !cgbr->shifted->empty && use_shifted(cgbr)) {
2735                 int i;
2736                 unsigned dim;
2737                 dim = isl_basic_set_total_dim(cgbr->tab->bset);
2738
2739                 if (isl_tab_extend_cons(cgbr->shifted, 1) < 0)
2740                         goto error;
2741
2742                 for (i = 0; i < dim; ++i) {
2743                         if (!isl_int_is_neg(ineq[1 + i]))
2744                                 continue;
2745                         isl_int_add(ineq[0], ineq[0], ineq[1 + i]);
2746                 }
2747
2748                 cgbr->shifted = isl_tab_add_ineq(cgbr->shifted, ineq);
2749
2750                 for (i = 0; i < dim; ++i) {
2751                         if (!isl_int_is_neg(ineq[1 + i]))
2752                                 continue;
2753                         isl_int_sub(ineq[0], ineq[0], ineq[1 + i]);
2754                 }
2755         }
2756
2757         if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
2758                 if (isl_tab_extend_cons(cgbr->cone, 1) < 0)
2759                         goto error;
2760                 cgbr->cone = isl_tab_add_ineq(cgbr->cone, ineq);
2761         }
2762
2763         return;
2764 error:
2765         isl_tab_free(cgbr->tab);
2766         cgbr->tab = NULL;
2767 }
2768
2769 static void context_gbr_add_ineq(struct isl_context *context, isl_int *ineq,
2770                 int check, int update)
2771 {
2772         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2773
2774         add_gbr_ineq(cgbr, ineq);
2775         if (!cgbr->tab)
2776                 return;
2777
2778         if (check) {
2779                 int v = tab_has_valid_sample(cgbr->tab, ineq, 0);
2780                 if (v < 0)
2781                         goto error;
2782                 if (!v)
2783                         check_gbr_integer_feasible(cgbr);
2784         }
2785         if (update)
2786                 cgbr->tab = check_samples(cgbr->tab, ineq, 0);
2787         return;
2788 error:
2789         isl_tab_free(cgbr->tab);
2790         cgbr->tab = NULL;
2791 }
2792
2793 static enum isl_tab_row_sign context_gbr_ineq_sign(struct isl_context *context,
2794                         isl_int *ineq, int strict)
2795 {
2796         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2797         return tab_ineq_sign(cgbr->tab, ineq, strict);
2798 }
2799
2800 /* Check whether "ineq" can be added to the tableau without rendering
2801  * it infeasible.
2802  */
2803 static int context_gbr_test_ineq(struct isl_context *context, isl_int *ineq)
2804 {
2805         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2806         struct isl_tab_undo *snap;
2807         struct isl_tab_undo *shifted_snap = NULL;
2808         struct isl_tab_undo *cone_snap = NULL;
2809         int feasible;
2810
2811         if (!cgbr->tab)
2812                 return -1;
2813
2814         if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
2815                 return -1;
2816
2817         snap = isl_tab_snap(cgbr->tab);
2818         if (cgbr->shifted)
2819                 shifted_snap = isl_tab_snap(cgbr->shifted);
2820         if (cgbr->cone)
2821                 cone_snap = isl_tab_snap(cgbr->cone);
2822         add_gbr_ineq(cgbr, ineq);
2823         check_gbr_integer_feasible(cgbr);
2824         if (!cgbr->tab)
2825                 return -1;
2826         feasible = !cgbr->tab->empty;
2827         if (isl_tab_rollback(cgbr->tab, snap) < 0)
2828                 return -1;
2829         if (shifted_snap) {
2830                 if (isl_tab_rollback(cgbr->shifted, shifted_snap))
2831                         return -1;
2832         } else if (cgbr->shifted) {
2833                 isl_tab_free(cgbr->shifted);
2834                 cgbr->shifted = NULL;
2835         }
2836         if (cone_snap) {
2837                 if (isl_tab_rollback(cgbr->cone, cone_snap))
2838                         return -1;
2839         } else if (cgbr->cone) {
2840                 isl_tab_free(cgbr->cone);
2841                 cgbr->cone = NULL;
2842         }
2843
2844         return feasible;
2845 }
2846
2847 /* Return the column of the last of the variables associated to
2848  * a column that has a non-zero coefficient.
2849  * This function is called in a context where only coefficients
2850  * of parameters or divs can be non-zero.
2851  */
2852 static int last_non_zero_var_col(struct isl_tab *tab, isl_int *p)
2853 {
2854         int i;
2855         int col;
2856         unsigned dim = tab->n_var - tab->n_param - tab->n_div;
2857
2858         if (tab->n_var == 0)
2859                 return -1;
2860
2861         for (i = tab->n_var - 1; i >= 0; --i) {
2862                 if (i >= tab->n_param && i < tab->n_var - tab->n_div)
2863                         continue;
2864                 if (tab->var[i].is_row)
2865                         continue;
2866                 col = tab->var[i].index;
2867                 if (!isl_int_is_zero(p[col]))
2868                         return col;
2869         }
2870
2871         return -1;
2872 }
2873
2874 /* Look through all the recently added equalities in the context
2875  * to see if we can propagate any of them to the main tableau.
2876  *
2877  * The newly added equalities in the context are encoded as pairs
2878  * of inequalities starting at inequality "first".
2879  *
2880  * We tentatively add each of these equalities to the main tableau
2881  * and if this happens to result in a row with a final coefficient
2882  * that is one or negative one, we use it to kill a column
2883  * in the main tableau.  Otherwise, we discard the tentatively
2884  * added row.
2885  */
2886 static void propagate_equalities(struct isl_context_gbr *cgbr,
2887         struct isl_tab *tab, unsigned first)
2888 {
2889         int i;
2890         struct isl_vec *eq = NULL;
2891
2892         eq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_var);
2893         if (!eq)
2894                 goto error;
2895
2896         if (isl_tab_extend_cons(tab, (cgbr->tab->bset->n_ineq - first)/2) < 0)
2897                 goto error;
2898
2899         isl_seq_clr(eq->el + 1 + tab->n_param,
2900                     tab->n_var - tab->n_param - tab->n_div);
2901         for (i = first; i < cgbr->tab->bset->n_ineq; i += 2) {
2902                 int j;
2903                 int r;
2904                 struct isl_tab_undo *snap;
2905                 snap = isl_tab_snap(tab);
2906
2907                 isl_seq_cpy(eq->el, cgbr->tab->bset->ineq[i], 1 + tab->n_param);
2908                 isl_seq_cpy(eq->el + 1 + tab->n_var - tab->n_div,
2909                             cgbr->tab->bset->ineq[i] + 1 + tab->n_param,
2910                             tab->n_div);
2911
2912                 r = isl_tab_add_row(tab, eq->el);
2913                 if (r < 0)
2914                         goto error;
2915                 r = tab->con[r].index;
2916                 j = last_non_zero_var_col(tab, tab->mat->row[r] + 2 + tab->M);
2917                 if (j < 0 || j < tab->n_dead ||
2918                     !isl_int_is_one(tab->mat->row[r][0]) ||
2919                     (!isl_int_is_one(tab->mat->row[r][2 + tab->M + j]) &&
2920                      !isl_int_is_negone(tab->mat->row[r][2 + tab->M + j]))) {
2921                         if (isl_tab_rollback(tab, snap) < 0)
2922                                 goto error;
2923                         continue;
2924                 }
2925                 if (isl_tab_pivot(tab, r, j) < 0)
2926                         goto error;
2927                 if (isl_tab_kill_col(tab, j) < 0)
2928                         goto error;
2929
2930                 tab = restore_lexmin(tab);
2931         }
2932
2933         isl_vec_free(eq);
2934
2935         return;
2936 error:
2937         isl_vec_free(eq);
2938         isl_tab_free(cgbr->tab);
2939         cgbr->tab = NULL;
2940 }
2941
2942 static int context_gbr_detect_equalities(struct isl_context *context,
2943         struct isl_tab *tab)
2944 {
2945         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2946         struct isl_ctx *ctx;
2947         int i;
2948         enum isl_lp_result res;
2949         unsigned n_ineq;
2950
2951         ctx = cgbr->tab->mat->ctx;
2952
2953         if (!cgbr->cone) {
2954                 cgbr->cone = isl_tab_from_recession_cone(cgbr->tab->bset);
2955                 if (!cgbr->cone)
2956                         goto error;
2957                 cgbr->cone->bset = isl_basic_set_dup(cgbr->tab->bset);
2958         }
2959         cgbr->cone = isl_tab_detect_implicit_equalities(cgbr->cone);
2960
2961         n_ineq = cgbr->tab->bset->n_ineq;
2962         cgbr->tab = isl_tab_detect_equalities(cgbr->tab, cgbr->cone);
2963         if (cgbr->tab && cgbr->tab->bset->n_ineq > n_ineq)
2964                 propagate_equalities(cgbr, tab, n_ineq);
2965
2966         return 0;
2967 error:
2968         isl_tab_free(cgbr->tab);
2969         cgbr->tab = NULL;
2970         return -1;
2971 }
2972
2973 static int context_gbr_get_div(struct isl_context *context, struct isl_tab *tab,
2974                 struct isl_vec *div)
2975 {
2976         return get_div(tab, context, div);
2977 }
2978
2979 static int context_gbr_add_div(struct isl_context *context, struct isl_vec *div,
2980         int *nonneg)
2981 {
2982         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2983         if (cgbr->cone) {
2984                 int k;
2985
2986                 if (isl_tab_extend_cons(cgbr->cone, 3) < 0)
2987                         return -1;
2988                 if (isl_tab_extend_vars(cgbr->cone, 1) < 0)
2989                         return -1;
2990                 if (isl_tab_allocate_var(cgbr->cone) <0)
2991                         return -1;
2992
2993                 cgbr->cone->bset = isl_basic_set_extend_dim(cgbr->cone->bset,
2994                         isl_basic_set_get_dim(cgbr->cone->bset), 1, 0, 2);
2995                 k = isl_basic_set_alloc_div(cgbr->cone->bset);
2996                 if (k < 0)
2997                         return -1;
2998                 isl_seq_cpy(cgbr->cone->bset->div[k], div->el, div->size);
2999                 if (isl_tab_push(cgbr->cone, isl_tab_undo_bset_div) < 0)
3000                         return -1;
3001         }
3002         return context_tab_add_div(cgbr->tab, div, nonneg);
3003 }
3004
3005 static int context_gbr_best_split(struct isl_context *context,
3006                 struct isl_tab *tab)
3007 {
3008         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3009         struct isl_tab_undo *snap;
3010         int r;
3011
3012         snap = isl_tab_snap(cgbr->tab);
3013         r = best_split(tab, cgbr->tab);
3014
3015         if (isl_tab_rollback(cgbr->tab, snap) < 0)
3016                 return -1;
3017
3018         return r;
3019 }
3020
3021 static int context_gbr_is_empty(struct isl_context *context)
3022 {
3023         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3024         if (!cgbr->tab)
3025                 return -1;
3026         return cgbr->tab->empty;
3027 }
3028
3029 struct isl_gbr_tab_undo {
3030         struct isl_tab_undo *tab_snap;
3031         struct isl_tab_undo *shifted_snap;
3032         struct isl_tab_undo *cone_snap;
3033 };
3034
3035 static void *context_gbr_save(struct isl_context *context)
3036 {
3037         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3038         struct isl_gbr_tab_undo *snap;
3039
3040         snap = isl_alloc_type(cgbr->tab->mat->ctx, struct isl_gbr_tab_undo);
3041         if (!snap)
3042                 return NULL;
3043
3044         snap->tab_snap = isl_tab_snap(cgbr->tab);
3045         if (isl_tab_save_samples(cgbr->tab) < 0)
3046                 goto error;
3047
3048         if (cgbr->shifted)
3049                 snap->shifted_snap = isl_tab_snap(cgbr->shifted);
3050         else
3051                 snap->shifted_snap = NULL;
3052
3053         if (cgbr->cone)
3054                 snap->cone_snap = isl_tab_snap(cgbr->cone);
3055         else
3056                 snap->cone_snap = NULL;
3057
3058         return snap;
3059 error:
3060         free(snap);
3061         return NULL;
3062 }
3063
3064 static void context_gbr_restore(struct isl_context *context, void *save)
3065 {
3066         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3067         struct isl_gbr_tab_undo *snap = (struct isl_gbr_tab_undo *)save;
3068         if (!snap)
3069                 goto error;
3070         if (isl_tab_rollback(cgbr->tab, snap->tab_snap) < 0) {
3071                 isl_tab_free(cgbr->tab);
3072                 cgbr->tab = NULL;
3073         }
3074
3075         if (snap->shifted_snap) {
3076                 if (isl_tab_rollback(cgbr->shifted, snap->shifted_snap) < 0)
3077                         goto error;
3078         } else if (cgbr->shifted) {
3079                 isl_tab_free(cgbr->shifted);
3080                 cgbr->shifted = NULL;
3081         }
3082
3083         if (snap->cone_snap) {
3084                 if (isl_tab_rollback(cgbr->cone, snap->cone_snap) < 0)
3085                         goto error;
3086         } else if (cgbr->cone) {
3087                 isl_tab_free(cgbr->cone);
3088                 cgbr->cone = NULL;
3089         }
3090
3091         free(snap);
3092
3093         return;
3094 error:
3095         free(snap);
3096         isl_tab_free(cgbr->tab);
3097         cgbr->tab = NULL;
3098 }
3099
3100 static int context_gbr_is_ok(struct isl_context *context)
3101 {
3102         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3103         return !!cgbr->tab;
3104 }
3105
3106 static void context_gbr_invalidate(struct isl_context *context)
3107 {
3108         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3109         isl_tab_free(cgbr->tab);
3110         cgbr->tab = NULL;
3111 }
3112
3113 static void context_gbr_free(struct isl_context *context)
3114 {
3115         struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3116         isl_tab_free(cgbr->tab);
3117         isl_tab_free(cgbr->shifted);
3118         isl_tab_free(cgbr->cone);
3119         free(cgbr);
3120 }
3121
3122 struct isl_context_op isl_context_gbr_op = {
3123         context_gbr_detect_nonnegative_parameters,
3124         context_gbr_peek_basic_set,
3125         context_gbr_peek_tab,
3126         context_gbr_add_eq,
3127         context_gbr_add_ineq,
3128         context_gbr_ineq_sign,
3129         context_gbr_test_ineq,
3130         context_gbr_get_div,
3131         context_gbr_add_div,
3132         context_gbr_detect_equalities,
3133         context_gbr_best_split,
3134         context_gbr_is_empty,
3135         context_gbr_is_ok,
3136         context_gbr_save,
3137         context_gbr_restore,
3138         context_gbr_invalidate,
3139         context_gbr_free,
3140 };
3141
3142 static struct isl_context *isl_context_gbr_alloc(struct isl_basic_set *dom)
3143 {
3144         struct isl_context_gbr *cgbr;
3145
3146         if (!dom)
3147                 return NULL;
3148
3149         cgbr = isl_calloc_type(dom->ctx, struct isl_context_gbr);
3150         if (!cgbr)
3151                 return NULL;
3152
3153         cgbr->context.op = &isl_context_gbr_op;
3154
3155         cgbr->shifted = NULL;
3156         cgbr->cone = NULL;
3157         cgbr->tab = isl_tab_from_basic_set(dom);
3158         cgbr->tab = isl_tab_init_samples(cgbr->tab);
3159         if (!cgbr->tab)
3160                 goto error;
3161         cgbr->tab->bset = isl_basic_set_cow(isl_basic_set_copy(dom));
3162         if (!cgbr->tab->bset)
3163                 goto error;
3164         check_gbr_integer_feasible(cgbr);
3165
3166         return &cgbr->context;
3167 error:
3168         cgbr->context.op->free(&cgbr->context);
3169         return NULL;
3170 }
3171
3172 static struct isl_context *isl_context_alloc(struct isl_basic_set *dom)
3173 {
3174         if (!dom)
3175                 return NULL;
3176
3177         if (dom->ctx->context == ISL_CONTEXT_LEXMIN)
3178                 return isl_context_lex_alloc(dom);
3179         else
3180                 return isl_context_gbr_alloc(dom);
3181 }
3182
3183 /* Construct an isl_sol_map structure for accumulating the solution.
3184  * If track_empty is set, then we also keep track of the parts
3185  * of the context where there is no solution.
3186  * If max is set, then we are solving a maximization, rather than
3187  * a minimization problem, which means that the variables in the
3188  * tableau have value "M - x" rather than "M + x".
3189  */
3190 static struct isl_sol_map *sol_map_init(struct isl_basic_map *bmap,
3191         struct isl_basic_set *dom, int track_empty, int max)
3192 {
3193         struct isl_sol_map *sol_map;
3194
3195         sol_map = isl_calloc_type(bset->ctx, struct isl_sol_map);
3196         if (!sol_map)
3197                 goto error;
3198
3199         sol_map->sol.rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
3200         sol_map->sol.dec_level.callback.run = &sol_dec_level_wrap;
3201         sol_map->sol.dec_level.sol = &sol_map->sol;
3202         sol_map->sol.max = max;
3203         sol_map->sol.n_out = isl_basic_map_dim(bmap, isl_dim_out);
3204         sol_map->sol.add = &sol_map_add_wrap;
3205         sol_map->sol.add_empty = track_empty ? &sol_map_add_empty_wrap : NULL;
3206         sol_map->sol.free = &sol_map_free_wrap;
3207         sol_map->map = isl_map_alloc_dim(isl_basic_map_get_dim(bmap), 1,
3208                                             ISL_MAP_DISJOINT);
3209         if (!sol_map->map)
3210                 goto error;
3211
3212         sol_map->sol.context = isl_context_alloc(dom);
3213         if (!sol_map->sol.context)
3214                 goto error;
3215
3216         if (track_empty) {
3217                 sol_map->empty = isl_set_alloc_dim(isl_basic_set_get_dim(dom),
3218                                                         1, ISL_SET_DISJOINT);
3219                 if (!sol_map->empty)
3220                         goto error;
3221         }
3222
3223         isl_basic_set_free(dom);
3224         return sol_map;
3225 error:
3226         isl_basic_set_free(dom);
3227         sol_map_free(sol_map);
3228         return NULL;
3229 }
3230
3231 /* Check whether all coefficients of (non-parameter) variables
3232  * are non-positive, meaning that no pivots can be performed on the row.
3233  */
3234 static int is_critical(struct isl_tab *tab, int row)
3235 {
3236         int j;
3237         unsigned off = 2 + tab->M;
3238
3239         for (j = tab->n_dead; j < tab->n_col; ++j) {
3240                 if (tab->col_var[j] >= 0 &&
3241                     (tab->col_var[j] < tab->n_param  ||
3242                     tab->col_var[j] >= tab->n_var - tab->n_div))
3243                         continue;
3244
3245                 if (isl_int_is_pos(tab->mat->row[row][off + j]))
3246                         return 0;
3247         }
3248
3249         return 1;
3250 }
3251
3252 /* Check whether the inequality represented by vec is strict over the integers,
3253  * i.e., there are no integer values satisfying the constraint with
3254  * equality.  This happens if the gcd of the coefficients is not a divisor
3255  * of the constant term.  If so, scale the constraint down by the gcd
3256  * of the coefficients.
3257  */
3258 static int is_strict(struct isl_vec *vec)
3259 {
3260         isl_int gcd;
3261         int strict = 0;
3262
3263         isl_int_init(gcd);
3264         isl_seq_gcd(vec->el + 1, vec->size - 1, &gcd);
3265         if (!isl_int_is_one(gcd)) {
3266                 strict = !isl_int_is_divisible_by(vec->el[0], gcd);
3267                 isl_int_fdiv_q(vec->el[0], vec->el[0], gcd);
3268                 isl_seq_scale_down(vec->el + 1, vec->el + 1, gcd, vec->size-1);
3269         }
3270         isl_int_clear(gcd);
3271
3272         return strict;
3273 }
3274
3275 /* Determine the sign of the given row of the main tableau.
3276  * The result is one of
3277  *      isl_tab_row_pos: always non-negative; no pivot needed
3278  *      isl_tab_row_neg: always non-positive; pivot
3279  *      isl_tab_row_any: can be both positive and negative; split
3280  *
3281  * We first handle some simple cases
3282  *      - the row sign may be known already
3283  *      - the row may be obviously non-negative
3284  *      - the parametric constant may be equal to that of another row
3285  *        for which we know the sign.  This sign will be either "pos" or
3286  *        "any".  If it had been "neg" then we would have pivoted before.
3287  *
3288  * If none of these cases hold, we check the value of the row for each
3289  * of the currently active samples.  Based on the signs of these values
3290  * we make an initial determination of the sign of the row.
3291  *
3292  *      all zero                        ->      unk(nown)
3293  *      all non-negative                ->      pos
3294  *      all non-positive                ->      neg
3295  *      both negative and positive      ->      all
3296  *
3297  * If we end up with "all", we are done.
3298  * Otherwise, we perform a check for positive and/or negative
3299  * values as follows.
3300  *
3301  *      samples        neg             unk             pos
3302  *      <0 ?                        Y        N      Y        N
3303  *                                          pos    any      pos
3304  *      >0 ?         Y      N    Y     N
3305  *                  any    neg  any   neg
3306  *
3307  * There is no special sign for "zero", because we can usually treat zero
3308  * as either non-negative or non-positive, whatever works out best.
3309  * However, if the row is "critical", meaning that pivoting is impossible
3310  * then we don't want to limp zero with the non-positive case, because
3311  * then we we would lose the solution for those values of the parameters
3312  * where the value of the row is zero.  Instead, we treat 0 as non-negative
3313  * ensuring a split if the row can attain both zero and negative values.
3314  * The same happens when the original constraint was one that could not
3315  * be satisfied with equality by any integer values of the parameters.
3316  * In this case, we normalize the constraint, but then a value of zero
3317  * for the normalized constraint is actually a positive value for the
3318  * original constraint, so again we need to treat zero as non-negative.
3319  * In both these cases, we have the following decision tree instead:
3320  *
3321  *      all non-negative                ->      pos
3322  *      all negative                    ->      neg
3323  *      both negative and non-negative  ->      all
3324  *
3325  *      samples        neg                             pos
3326  *      <0 ?                                        Y        N
3327  *                                                 any      pos
3328  *      >=0 ?        Y      N
3329  *                  any    neg
3330  */
3331 static enum isl_tab_row_sign row_sign(struct isl_tab *tab,
3332         struct isl_sol *sol, int row)
3333 {
3334         struct isl_vec *ineq = NULL;
3335         int res = isl_tab_row_unknown;
3336         int critical;
3337         int strict;
3338         int row2;
3339
3340         if (tab->row_sign[row] != isl_tab_row_unknown)
3341                 return tab->row_sign[row];
3342         if (is_obviously_nonneg(tab, row))
3343                 return isl_tab_row_pos;
3344         for (row2 = tab->n_redundant; row2 < tab->n_row; ++row2) {
3345                 if (tab->row_sign[row2] == isl_tab_row_unknown)
3346                         continue;
3347                 if (identical_parameter_line(tab, row, row2))
3348                         return tab->row_sign[row2];
3349         }
3350
3351         critical = is_critical(tab, row);
3352
3353         ineq = get_row_parameter_ineq(tab, row);
3354         if (!ineq)
3355                 goto error;
3356
3357         strict = is_strict(ineq);
3358
3359         res = sol->context->op->ineq_sign(sol->context, ineq->el,
3360                                           critical || strict);
3361
3362         if (res == isl_tab_row_unknown || res == isl_tab_row_pos) {
3363                 /* test for negative values */
3364                 int feasible;
3365                 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3366                 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3367
3368                 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3369                 if (feasible < 0)
3370                         goto error;
3371                 if (!feasible)
3372                         res = isl_tab_row_pos;
3373                 else
3374                         res = (res == isl_tab_row_unknown) ? isl_tab_row_neg
3375                                                            : isl_tab_row_any;
3376                 if (res == isl_tab_row_neg) {
3377                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
3378                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3379                 }
3380         }
3381
3382         if (res == isl_tab_row_neg) {
3383                 /* test for positive values */
3384                 int feasible;
3385                 if (!critical && !strict)
3386                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3387
3388                 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3389                 if (feasible < 0)
3390                         goto error;
3391                 if (feasible)
3392                         res = isl_tab_row_any;
3393         }
3394
3395         isl_vec_free(ineq);
3396         return res;
3397 error:
3398         isl_vec_free(ineq);
3399         return 0;
3400 }
3401
3402 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab);
3403
3404 /* Find solutions for values of the parameters that satisfy the given
3405  * inequality.
3406  *
3407  * We currently take a snapshot of the context tableau that is reset
3408  * when we return from this function, while we make a copy of the main
3409  * tableau, leaving the original main tableau untouched.
3410  * These are fairly arbitrary choices.  Making a copy also of the context
3411  * tableau would obviate the need to undo any changes made to it later,
3412  * while taking a snapshot of the main tableau could reduce memory usage.
3413  * If we were to switch to taking a snapshot of the main tableau,
3414  * we would have to keep in mind that we need to save the row signs
3415  * and that we need to do this before saving the current basis
3416  * such that the basis has been restore before we restore the row signs.
3417  */
3418 static void find_in_pos(struct isl_sol *sol, struct isl_tab *tab, isl_int *ineq)
3419 {
3420         void *saved;
3421
3422         if (!sol->context)
3423                 goto error;
3424         saved = sol->context->op->save(sol->context);
3425
3426         tab = isl_tab_dup(tab);
3427         if (!tab)
3428                 goto error;
3429
3430         sol->context->op->add_ineq(sol->context, ineq, 0, 1);
3431
3432         find_solutions(sol, tab);
3433
3434         sol->context->op->restore(sol->context, saved);
3435         return;
3436 error:
3437         sol->error = 1;
3438 }
3439
3440 /* Record the absence of solutions for those values of the parameters
3441  * that do not satisfy the given inequality with equality.
3442  */
3443 static void no_sol_in_strict(struct isl_sol *sol,
3444         struct isl_tab *tab, struct isl_vec *ineq)
3445 {
3446         int empty;
3447         void *saved;
3448
3449         if (!sol->context)
3450                 goto error;
3451         saved = sol->context->op->save(sol->context);
3452
3453         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3454
3455         sol->context->op->add_ineq(sol->context, ineq->el, 1, 0);
3456         if (!sol->context)
3457                 goto error;
3458
3459         empty = tab->empty;
3460         tab->empty = 1;
3461         sol_add(sol, tab);
3462         tab->empty = empty;
3463
3464         isl_int_add_ui(ineq->el[0], ineq->el[0], 1);
3465
3466         sol->context->op->restore(sol->context, saved);
3467         return;
3468 error:
3469         sol->error = 1;
3470 }
3471
3472 /* Compute the lexicographic minimum of the set represented by the main
3473  * tableau "tab" within the context "sol->context_tab".
3474  * On entry the sample value of the main tableau is lexicographically
3475  * less than or equal to this lexicographic minimum.
3476  * Pivots are performed until a feasible point is found, which is then
3477  * necessarily equal to the minimum, or until the tableau is found to
3478  * be infeasible.  Some pivots may need to be performed for only some
3479  * feasible values of the context tableau.  If so, the context tableau
3480  * is split into a part where the pivot is needed and a part where it is not.
3481  *
3482  * Whenever we enter the main loop, the main tableau is such that no
3483  * "obvious" pivots need to be performed on it, where "obvious" means
3484  * that the given row can be seen to be negative without looking at
3485  * the context tableau.  In particular, for non-parametric problems,
3486  * no pivots need to be performed on the main tableau.
3487  * The caller of find_solutions is responsible for making this property
3488  * hold prior to the first iteration of the loop, while restore_lexmin
3489  * is called before every other iteration.
3490  *
3491  * Inside the main loop, we first examine the signs of the rows of
3492  * the main tableau within the context of the context tableau.
3493  * If we find a row that is always non-positive for all values of
3494  * the parameters satisfying the context tableau and negative for at
3495  * least one value of the parameters, we perform the appropriate pivot
3496  * and start over.  An exception is the case where no pivot can be
3497  * performed on the row.  In this case, we require that the sign of
3498  * the row is negative for all values of the parameters (rather than just
3499  * non-positive).  This special case is handled inside row_sign, which
3500  * will say that the row can have any sign if it determines that it can
3501  * attain both negative and zero values.
3502  *
3503  * If we can't find a row that always requires a pivot, but we can find
3504  * one or more rows that require a pivot for some values of the parameters
3505  * (i.e., the row can attain both positive and negative signs), then we split
3506  * the context tableau into two parts, one where we force the sign to be
3507  * non-negative and one where we force is to be negative.
3508  * The non-negative part is handled by a recursive call (through find_in_pos).
3509  * Upon returning from this call, we continue with the negative part and
3510  * perform the required pivot.
3511  *
3512  * If no such rows can be found, all rows are non-negative and we have
3513  * found a (rational) feasible point.  If we only wanted a rational point
3514  * then we are done.
3515  * Otherwise, we check if all values of the sample point of the tableau
3516  * are integral for the variables.  If so, we have found the minimal
3517  * integral point and we are done.
3518  * If the sample point is not integral, then we need to make a distinction
3519  * based on whether the constant term is non-integral or the coefficients
3520  * of the parameters.  Furthermore, in order to decide how to handle
3521  * the non-integrality, we also need to know whether the coefficients
3522  * of the other columns in the tableau are integral.  This leads
3523  * to the following table.  The first two rows do not correspond
3524  * to a non-integral sample point and are only mentioned for completeness.
3525  *
3526  *      constant        parameters      other
3527  *
3528  *      int             int             int     |
3529  *      int             int             rat     | -> no problem
3530  *
3531  *      rat             int             int       -> fail
3532  *
3533  *      rat             int             rat       -> cut
3534  *
3535  *      int             rat             rat     |
3536  *      rat             rat             rat     | -> parametric cut
3537  *
3538  *      int             rat             int     |
3539  *      rat             rat             int     | -> split context
3540  *
3541  * If the parametric constant is completely integral, then there is nothing
3542  * to be done.  If the constant term is non-integral, but all the other
3543  * coefficient are integral, then there is nothing that can be done
3544  * and the tableau has no integral solution.
3545  * If, on the other hand, one or more of the other columns have rational
3546  * coeffcients, but the parameter coefficients are all integral, then
3547  * we can perform a regular (non-parametric) cut.
3548  * Finally, if there is any parameter coefficient that is non-integral,
3549  * then we need to involve the context tableau.  There are two cases here.
3550  * If at least one other column has a rational coefficient, then we
3551  * can perform a parametric cut in the main tableau by adding a new
3552  * integer division in the context tableau.
3553  * If all other columns have integral coefficients, then we need to
3554  * enforce that the rational combination of parameters (c + \sum a_i y_i)/m
3555  * is always integral.  We do this by introducing an integer division
3556  * q = floor((c + \sum a_i y_i)/m) and stipulating that its argument should
3557  * always be integral in the context tableau, i.e., m q = c + \sum a_i y_i.
3558  * Since q is expressed in the tableau as
3559  *      c + \sum a_i y_i - m q >= 0
3560  *      -c - \sum a_i y_i + m q + m - 1 >= 0
3561  * it is sufficient to add the inequality
3562  *      -c - \sum a_i y_i + m q >= 0
3563  * In the part of the context where this inequality does not hold, the
3564  * main tableau is marked as being empty.
3565  */
3566 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab)
3567 {
3568         struct isl_context *context;
3569
3570         if (!tab || sol->error)
3571                 goto error;
3572
3573         context = sol->context;
3574
3575         if (tab->empty)
3576                 goto done;
3577         if (context->op->is_empty(context))
3578                 goto done;
3579
3580         for (; tab && !tab->empty; tab = restore_lexmin(tab)) {
3581                 int flags;
3582                 int row;
3583                 int sgn;
3584                 int split = -1;
3585                 int n_split = 0;
3586
3587                 for (row = tab->n_redundant; row < tab->n_row; ++row) {
3588                         if (!isl_tab_var_from_row(tab, row)->is_nonneg)
3589                                 continue;
3590                         sgn = row_sign(tab, sol, row);
3591                         if (!sgn)
3592                                 goto error;
3593                         tab->row_sign[row] = sgn;
3594                         if (sgn == isl_tab_row_any)
3595                                 n_split++;
3596                         if (sgn == isl_tab_row_any && split == -1)
3597                                 split = row;
3598                         if (sgn == isl_tab_row_neg)
3599                                 break;
3600                 }
3601                 if (row < tab->n_row)
3602                         continue;
3603                 if (split != -1) {
3604                         struct isl_vec *ineq;
3605                         if (n_split != 1)
3606                                 split = context->op->best_split(context, tab);
3607                         if (split < 0)
3608                                 goto error;
3609                         ineq = get_row_parameter_ineq(tab, split);
3610                         if (!ineq)
3611                                 goto error;
3612                         is_strict(ineq);
3613                         for (row = tab->n_redundant; row < tab->n_row; ++row) {
3614                                 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
3615                                         continue;
3616                                 if (tab->row_sign[row] == isl_tab_row_any)
3617                                         tab->row_sign[row] = isl_tab_row_unknown;
3618                         }
3619                         tab->row_sign[split] = isl_tab_row_pos;
3620                         sol_inc_level(sol);
3621                         find_in_pos(sol, tab, ineq->el);
3622                         tab->row_sign[split] = isl_tab_row_neg;
3623                         row = split;
3624                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
3625                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3626                         context->op->add_ineq(context, ineq->el, 0, 1);
3627                         isl_vec_free(ineq);
3628                         if (sol->error)
3629                                 goto error;
3630                         continue;
3631                 }
3632                 if (tab->rational)
3633                         break;
3634                 row = first_non_integer(tab, &flags);
3635                 if (row < 0)
3636                         break;
3637                 if (ISL_FL_ISSET(flags, I_PAR)) {
3638                         if (ISL_FL_ISSET(flags, I_VAR)) {
3639                                 tab = isl_tab_mark_empty(tab);
3640                                 break;
3641                         }
3642                         row = add_cut(tab, row);
3643                 } else if (ISL_FL_ISSET(flags, I_VAR)) {
3644                         struct isl_vec *div;
3645                         struct isl_vec *ineq;
3646                         int d;
3647                         div = get_row_split_div(tab, row);
3648                         if (!div)
3649                                 goto error;
3650                         d = context->op->get_div(context, tab, div);
3651                         isl_vec_free(div);
3652                         if (d < 0)
3653                                 goto error;
3654                         ineq = ineq_for_div(context->op->peek_basic_set(context), d);
3655                         sol_inc_level(sol);
3656                         no_sol_in_strict(sol, tab, ineq);
3657                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
3658                         context->op->add_ineq(context, ineq->el, 1, 1);
3659                         isl_vec_free(ineq);
3660                         if (sol->error || !context->op->is_ok(context))
3661                                 goto error;
3662                         tab = set_row_cst_to_div(tab, row, d);
3663                 } else
3664                         row = add_parametric_cut(tab, row, context);
3665                 if (row < 0)
3666                         goto error;
3667         }
3668 done:
3669         sol_add(sol, tab);
3670         isl_tab_free(tab);
3671         return;
3672 error:
3673         isl_tab_free(tab);
3674         sol_free(sol);
3675 }
3676
3677 /* Compute the lexicographic minimum of the set represented by the main
3678  * tableau "tab" within the context "sol->context_tab".
3679  *
3680  * As a preprocessing step, we first transfer all the purely parametric
3681  * equalities from the main tableau to the context tableau, i.e.,
3682  * parameters that have been pivoted to a row.
3683  * These equalities are ignored by the main algorithm, because the
3684  * corresponding rows may not be marked as being non-negative.
3685  * In parts of the context where the added equality does not hold,
3686  * the main tableau is marked as being empty.
3687  */
3688 static void find_solutions_main(struct isl_sol *sol, struct isl_tab *tab)
3689 {
3690         int row;
3691
3692         sol->level = 0;
3693
3694         for (row = tab->n_redundant; row < tab->n_row; ++row) {
3695                 int p;
3696                 struct isl_vec *eq;
3697
3698                 if (tab->row_var[row] < 0)
3699                         continue;
3700                 if (tab->row_var[row] >= tab->n_param &&
3701                     tab->row_var[row] < tab->n_var - tab->n_div)
3702                         continue;
3703                 if (tab->row_var[row] < tab->n_param)
3704                         p = tab->row_var[row];
3705                 else
3706                         p = tab->row_var[row]
3707                                 + tab->n_param - (tab->n_var - tab->n_div);
3708
3709                 eq = isl_vec_alloc(tab->mat->ctx, 1+tab->n_param+tab->n_div);
3710                 get_row_parameter_line(tab, row, eq->el);
3711                 isl_int_neg(eq->el[1 + p], tab->mat->row[row][0]);
3712                 eq = isl_vec_normalize(eq);
3713
3714                 sol_inc_level(sol);
3715                 no_sol_in_strict(sol, tab, eq);
3716
3717                 isl_seq_neg(eq->el, eq->el, eq->size);
3718                 sol_inc_level(sol);
3719                 no_sol_in_strict(sol, tab, eq);
3720                 isl_seq_neg(eq->el, eq->el, eq->size);
3721
3722                 sol->context->op->add_eq(sol->context, eq->el, 1, 1);
3723
3724                 isl_vec_free(eq);
3725
3726                 if (isl_tab_mark_redundant(tab, row) < 0)
3727                         goto error;
3728
3729                 if (sol->context->op->is_empty(sol->context))
3730                         break;
3731
3732                 row = tab->n_redundant - 1;
3733         }
3734
3735         find_solutions(sol, tab);
3736
3737         sol->level = 0;
3738         sol_pop(sol);
3739
3740         return;
3741 error:
3742         isl_tab_free(tab);
3743         sol_free(sol);
3744 }
3745
3746 static void sol_map_find_solutions(struct isl_sol_map *sol_map,
3747         struct isl_tab *tab)
3748 {
3749         find_solutions_main(&sol_map->sol, tab);
3750 }
3751
3752 /* Check if integer division "div" of "dom" also occurs in "bmap".
3753  * If so, return its position within the divs.
3754  * If not, return -1.
3755  */
3756 static int find_context_div(struct isl_basic_map *bmap,
3757         struct isl_basic_set *dom, unsigned div)
3758 {
3759         int i;
3760         unsigned b_dim = isl_dim_total(bmap->dim);
3761         unsigned d_dim = isl_dim_total(dom->dim);
3762
3763         if (isl_int_is_zero(dom->div[div][0]))
3764                 return -1;
3765         if (isl_seq_first_non_zero(dom->div[div] + 2 + d_dim, dom->n_div) != -1)
3766                 return -1;
3767
3768         for (i = 0; i < bmap->n_div; ++i) {
3769                 if (isl_int_is_zero(bmap->div[i][0]))
3770                         continue;
3771                 if (isl_seq_first_non_zero(bmap->div[i] + 2 + d_dim,
3772                                            (b_dim - d_dim) + bmap->n_div) != -1)
3773                         continue;
3774                 if (isl_seq_eq(bmap->div[i], dom->div[div], 2 + d_dim))
3775                         return i;
3776         }
3777         return -1;
3778 }
3779
3780 /* The correspondence between the variables in the main tableau,
3781  * the context tableau, and the input map and domain is as follows.
3782  * The first n_param and the last n_div variables of the main tableau
3783  * form the variables of the context tableau.
3784  * In the basic map, these n_param variables correspond to the
3785  * parameters and the input dimensions.  In the domain, they correspond
3786  * to the parameters and the set dimensions.
3787  * The n_div variables correspond to the integer divisions in the domain.
3788  * To ensure that everything lines up, we may need to copy some of the
3789  * integer divisions of the domain to the map.  These have to be placed
3790  * in the same order as those in the context and they have to be placed
3791  * after any other integer divisions that the map may have.
3792  * This function performs the required reordering.
3793  */
3794 static struct isl_basic_map *align_context_divs(struct isl_basic_map *bmap,
3795         struct isl_basic_set *dom)
3796 {
3797         int i;
3798         int common = 0;
3799         int other;
3800
3801         for (i = 0; i < dom->n_div; ++i)
3802                 if (find_context_div(bmap, dom, i) != -1)
3803                         common++;
3804         other = bmap->n_div - common;
3805         if (dom->n_div - common > 0) {
3806                 bmap = isl_basic_map_extend_dim(bmap, isl_dim_copy(bmap->dim),
3807                                 dom->n_div - common, 0, 0);
3808                 if (!bmap)
3809                         return NULL;
3810         }
3811         for (i = 0; i < dom->n_div; ++i) {
3812                 int pos = find_context_div(bmap, dom, i);
3813                 if (pos < 0) {
3814                         pos = isl_basic_map_alloc_div(bmap);
3815                         if (pos < 0)
3816                                 goto error;
3817                         isl_int_set_si(bmap->div[pos][0], 0);
3818                 }
3819                 if (pos != other + i)
3820                         isl_basic_map_swap_div(bmap, pos, other + i);
3821         }
3822         return bmap;
3823 error:
3824         isl_basic_map_free(bmap);
3825         return NULL;
3826 }
3827
3828 /* Compute the lexicographic minimum (or maximum if "max" is set)
3829  * of "bmap" over the domain "dom" and return the result as a map.
3830  * If "empty" is not NULL, then *empty is assigned a set that
3831  * contains those parts of the domain where there is no solution.
3832  * If "bmap" is marked as rational (ISL_BASIC_MAP_RATIONAL),
3833  * then we compute the rational optimum.  Otherwise, we compute
3834  * the integral optimum.
3835  *
3836  * We perform some preprocessing.  As the PILP solver does not
3837  * handle implicit equalities very well, we first make sure all
3838  * the equalities are explicitly available.
3839  * We also make sure the divs in the domain are properly order,
3840  * because they will be added one by one in the given order
3841  * during the construction of the solution map.
3842  */
3843 struct isl_map *isl_tab_basic_map_partial_lexopt(
3844                 struct isl_basic_map *bmap, struct isl_basic_set *dom,
3845                 struct isl_set **empty, int max)
3846 {
3847         struct isl_tab *tab;
3848         struct isl_map *result = NULL;
3849         struct isl_sol_map *sol_map = NULL;
3850         struct isl_context *context;
3851
3852         if (empty)
3853                 *empty = NULL;
3854         if (!bmap || !dom)
3855                 goto error;
3856
3857         isl_assert(bmap->ctx,
3858             isl_basic_map_compatible_domain(bmap, dom), goto error);
3859
3860         bmap = isl_basic_map_detect_equalities(bmap);
3861
3862         if (dom->n_div) {
3863                 dom = isl_basic_set_order_divs(dom);
3864                 bmap = align_context_divs(bmap, dom);
3865         }
3866         sol_map = sol_map_init(bmap, dom, !!empty, max);
3867         if (!sol_map)
3868                 goto error;
3869
3870         context = sol_map->sol.context;
3871         if (isl_basic_set_fast_is_empty(context->op->peek_basic_set(context)))
3872                 /* nothing */;
3873         else if (isl_basic_map_fast_is_empty(bmap))
3874                 sol_map_add_empty(sol_map,
3875                     isl_basic_set_dup(context->op->peek_basic_set(context)));
3876         else {
3877                 tab = tab_for_lexmin(bmap,
3878                                     context->op->peek_basic_set(context), 1, max);
3879                 tab = context->op->detect_nonnegative_parameters(context, tab);
3880                 sol_map_find_solutions(sol_map, tab);
3881         }
3882         if (sol_map->sol.error)
3883                 goto error;
3884
3885         result = isl_map_copy(sol_map->map);
3886         if (empty)
3887                 *empty = isl_set_copy(sol_map->empty);
3888         sol_free(&sol_map->sol);
3889         isl_basic_map_free(bmap);
3890         return result;
3891 error:
3892         sol_free(&sol_map->sol);
3893         isl_basic_map_free(bmap);
3894         return NULL;
3895 }
3896
3897 struct isl_sol_for {
3898         struct isl_sol  sol;
3899         int             (*fn)(__isl_take isl_basic_set *dom,
3900                                 __isl_take isl_mat *map, void *user);
3901         void            *user;
3902 };
3903
3904 static void sol_for_free(struct isl_sol_for *sol_for)
3905 {
3906         if (sol_for->sol.context)
3907                 sol_for->sol.context->op->free(sol_for->sol.context);
3908         free(sol_for);
3909 }
3910
3911 static void sol_for_free_wrap(struct isl_sol *sol)
3912 {
3913         sol_for_free((struct isl_sol_for *)sol);
3914 }
3915
3916 /* Add the solution identified by the tableau and the context tableau.
3917  *
3918  * See documentation of sol_add for more details.
3919  *
3920  * Instead of constructing a basic map, this function calls a user
3921  * defined function with the current context as a basic set and
3922  * an affine matrix reprenting the relation between the input and output.
3923  * The number of rows in this matrix is equal to one plus the number
3924  * of output variables.  The number of columns is equal to one plus
3925  * the total dimension of the context, i.e., the number of parameters,
3926  * input variables and divs.  Since some of the columns in the matrix
3927  * may refer to the divs, the basic set is not simplified.
3928  * (Simplification may reorder or remove divs.)
3929  */
3930 static void sol_for_add(struct isl_sol_for *sol,
3931         struct isl_basic_set *dom, struct isl_mat *M)
3932 {
3933         if (sol->sol.error || !dom || !M)
3934                 goto error;
3935
3936         dom = isl_basic_set_simplify(dom);
3937         dom = isl_basic_set_finalize(dom);
3938
3939         if (sol->fn(isl_basic_set_copy(dom), isl_mat_copy(M), sol->user) < 0)
3940                 goto error;
3941
3942         isl_basic_set_free(dom);
3943         isl_mat_free(M);
3944         return;
3945 error:
3946         isl_basic_set_free(dom);
3947         isl_mat_free(M);
3948         sol->sol.error = 1;
3949 }
3950
3951 static void sol_for_add_wrap(struct isl_sol *sol,
3952         struct isl_basic_set *dom, struct isl_mat *M)
3953 {
3954         sol_for_add((struct isl_sol_for *)sol, dom, M);
3955 }
3956
3957 static struct isl_sol_for *sol_for_init(struct isl_basic_map *bmap, int max,
3958         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
3959                   void *user),
3960         void *user)
3961 {
3962         struct isl_sol_for *sol_for = NULL;
3963         struct isl_dim *dom_dim;
3964         struct isl_basic_set *dom = NULL;
3965
3966         sol_for = isl_calloc_type(bset->ctx, struct isl_sol_for);
3967         if (!sol_for)
3968                 goto error;
3969
3970         dom_dim = isl_dim_domain(isl_dim_copy(bmap->dim));
3971         dom = isl_basic_set_universe(dom_dim);
3972
3973         sol_for->sol.rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
3974         sol_for->sol.dec_level.callback.run = &sol_dec_level_wrap;
3975         sol_for->sol.dec_level.sol = &sol_for->sol;
3976         sol_for->fn = fn;
3977         sol_for->user = user;
3978         sol_for->sol.max = max;
3979         sol_for->sol.n_out = isl_basic_map_dim(bmap, isl_dim_out);
3980         sol_for->sol.add = &sol_for_add_wrap;
3981         sol_for->sol.add_empty = NULL;
3982         sol_for->sol.free = &sol_for_free_wrap;
3983
3984         sol_for->sol.context = isl_context_alloc(dom);
3985         if (!sol_for->sol.context)
3986                 goto error;
3987
3988         isl_basic_set_free(dom);
3989         return sol_for;
3990 error:
3991         isl_basic_set_free(dom);
3992         sol_for_free(sol_for);
3993         return NULL;
3994 }
3995
3996 static void sol_for_find_solutions(struct isl_sol_for *sol_for,
3997         struct isl_tab *tab)
3998 {
3999         find_solutions_main(&sol_for->sol, tab);
4000 }
4001
4002 int isl_basic_map_foreach_lexopt(__isl_keep isl_basic_map *bmap, int max,
4003         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
4004                   void *user),
4005         void *user)
4006 {
4007         struct isl_sol_for *sol_for = NULL;
4008
4009         bmap = isl_basic_map_copy(bmap);
4010         if (!bmap)
4011                 return -1;
4012
4013         bmap = isl_basic_map_detect_equalities(bmap);
4014         sol_for = sol_for_init(bmap, max, fn, user);
4015
4016         if (isl_basic_map_fast_is_empty(bmap))
4017                 /* nothing */;
4018         else {
4019                 struct isl_tab *tab;
4020                 struct isl_context *context = sol_for->sol.context;
4021                 tab = tab_for_lexmin(bmap,
4022                                 context->op->peek_basic_set(context), 1, max);
4023                 tab = context->op->detect_nonnegative_parameters(context, tab);
4024                 sol_for_find_solutions(sol_for, tab);
4025                 if (sol_for->sol.error)
4026                         goto error;
4027         }
4028
4029         sol_free(&sol_for->sol);
4030         isl_basic_map_free(bmap);
4031         return 0;
4032 error:
4033         sol_free(&sol_for->sol);
4034         isl_basic_map_free(bmap);
4035         return -1;
4036 }
4037
4038 int isl_basic_map_foreach_lexmin(__isl_keep isl_basic_map *bmap,
4039         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
4040                   void *user),
4041         void *user)
4042 {
4043         return isl_basic_map_foreach_lexopt(bmap, 0, fn, user);
4044 }
4045
4046 int isl_basic_map_foreach_lexmax(__isl_keep isl_basic_map *bmap,
4047         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
4048                   void *user),
4049         void *user)
4050 {
4051         return isl_basic_map_foreach_lexopt(bmap, 1, fn, user);
4052 }