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