isl_tab_pip.c: extract out context handling
[platform/upstream/isl.git] / isl_tab_pip.c
1 #include "isl_map_private.h"
2 #include "isl_seq.h"
3 #include "isl_tab.h"
4
5 /*
6  * The implementation of parametric integer linear programming in this file
7  * was inspired by the paper "Parametric Integer Programming" and the
8  * report "Solving systems of affine (in)equalities" by Paul Feautrier
9  * (and others).
10  *
11  * The strategy used for obtaining a feasible solution is different
12  * from the one used in isl_tab.c.  In particular, in isl_tab.c,
13  * upon finding a constraint that is not yet satisfied, we pivot
14  * in a row that increases the constant term of row holding the
15  * constraint, making sure the sample solution remains feasible
16  * for all the constraints it already satisfied.
17  * Here, we always pivot in the row holding the constraint,
18  * choosing a column that induces the lexicographically smallest
19  * increment to the sample solution.
20  *
21  * By starting out from a sample value that is lexicographically
22  * smaller than any integer point in the problem space, the first
23  * feasible integer sample point we find will also be the lexicographically
24  * smallest.  If all variables can be assumed to be non-negative,
25  * then the initial sample value may be chosen equal to zero.
26  * However, we will not make this assumption.  Instead, we apply
27  * the "big parameter" trick.  Any variable x is then not directly
28  * used in the tableau, but instead it its represented by another
29  * variable x' = M + x, where M is an arbitrarily large (positive)
30  * value.  x' is therefore always non-negative, whatever the value of x.
31  * Taking as initial smaple value x' = 0 corresponds to x = -M,
32  * which is always smaller than any possible value of x.
33  *
34  * We use the big parameter trick both in the main tableau and
35  * the context tableau, each of course having its own big parameter.
36  * Before doing any real work, we check if all the parameters
37  * happen to be non-negative.  If so, we drop the column corresponding
38  * to M from the initial context tableau.
39  */
40
41 struct isl_context;
42 struct isl_context_op {
43         /* detect nonnegative parameters in context and mark them in tab */
44         struct isl_tab *(*detect_nonnegative_parameters)(
45                         struct isl_context *context, struct isl_tab *tab);
46         /* return temporary reference to basic set representation of context */
47         struct isl_basic_set *(*peek_basic_set)(struct isl_context *context);
48         /* return temporary reference to tableau representation of context */
49         struct isl_tab *(*peek_tab)(struct isl_context *context);
50         /* add equality; check is 1 if eq may not be valid;
51          * update is 1 if we may want to call ineq_sign on context later.
52          */
53         void (*add_eq)(struct isl_context *context, isl_int *eq,
54                         int check, int update);
55         /* add inequality; check is 1 if ineq may not be valid;
56          * update is 1 if we may want to call ineq_sign on context later.
57          */
58         void (*add_ineq)(struct isl_context *context, isl_int *ineq,
59                         int check, int update);
60         /* check sign of ineq based on previous information.
61          * strict is 1 if saturation should be treated as a positive sign.
62          */
63         enum isl_tab_row_sign (*ineq_sign)(struct isl_context *context,
64                         isl_int *ineq, int strict);
65         /* check if inequality maintains feasibility */
66         int (*test_ineq)(struct isl_context *context, isl_int *ineq);
67         /* return index of a div that corresponds to "div" */
68         int (*get_div)(struct isl_context *context, struct isl_tab *tab,
69                         struct isl_vec *div);
70         /* add div "div" to context and return index and non-negativity */
71         int (*add_div)(struct isl_context *context, struct isl_vec *div,
72                         int *nonneg);
73         /* return row index of "best" split */
74         int (*best_split)(struct isl_context *context, struct isl_tab *tab);
75         /* check if context has already been determined to be empty */
76         int (*is_empty)(struct isl_context *context);
77         /* check if context is still usable */
78         int (*is_ok)(struct isl_context *context);
79         /* save a copy/snapshot of context */
80         void *(*save)(struct isl_context *context);
81         /* restore saved context */
82         void (*restore)(struct isl_context *context, void *);
83         /* invalidate context */
84         void (*invalidate)(struct isl_context *context);
85         /* free context */
86         void (*free)(struct isl_context *context);
87 };
88
89 struct isl_context {
90         struct isl_context_op *op;
91 };
92
93 struct isl_context_lex {
94         struct isl_context context;
95         struct isl_tab *tab;
96 };
97
98 /* isl_sol is an interface for constructing a solution to
99  * a parametric integer linear programming problem.
100  * Every time the algorithm reaches a state where a solution
101  * can be read off from the tableau (including cases where the tableau
102  * is empty), the function "add" is called on the isl_sol passed
103  * to find_solutions_main.
104  *
105  * The context tableau is owned by isl_sol and is updated incrementally.
106  *
107  * There are currently two implementations of this interface,
108  * isl_sol_map, which simply collects the solutions in an isl_map
109  * and (optionally) the parts of the context where there is no solution
110  * in an isl_set, and
111  * isl_sol_for, which calls a user-defined function for each part of
112  * the solution.
113  */
114 struct isl_sol {
115         struct isl_context *context;
116         struct isl_sol *(*add)(struct isl_sol *sol, struct isl_tab *tab);
117         void (*free)(struct isl_sol *sol);
118 };
119
120 static void sol_free(struct isl_sol *sol)
121 {
122         if (!sol)
123                 return;
124         sol->free(sol);
125 }
126
127 struct isl_sol_map {
128         struct isl_sol  sol;
129         struct isl_map  *map;
130         struct isl_set  *empty;
131         int             max;
132 };
133
134 static void sol_map_free(struct isl_sol_map *sol_map)
135 {
136         if (sol_map->sol.context)
137                 sol_map->sol.context->op->free(sol_map->sol.context);
138         isl_map_free(sol_map->map);
139         isl_set_free(sol_map->empty);
140         free(sol_map);
141 }
142
143 static void sol_map_free_wrap(struct isl_sol *sol)
144 {
145         sol_map_free((struct isl_sol_map *)sol);
146 }
147
148 static struct isl_sol_map *add_empty(struct isl_sol_map *sol)
149 {
150         struct isl_basic_set *bset;
151
152         if (!sol->empty)
153                 return sol;
154         sol->empty = isl_set_grow(sol->empty, 1);
155         bset = sol->sol.context->op->peek_basic_set(sol->sol.context);
156         bset = isl_basic_set_copy(bset);
157         bset = isl_basic_set_simplify(bset);
158         bset = isl_basic_set_finalize(bset);
159         sol->empty = isl_set_add(sol->empty, bset);
160         if (!sol->empty)
161                 goto error;
162         return sol;
163 error:
164         sol_map_free(sol);
165         return NULL;
166 }
167
168 /* Add the solution identified by the tableau and the context tableau.
169  *
170  * The layout of the variables is as follows.
171  *      tab->n_var is equal to the total number of variables in the input
172  *                      map (including divs that were copied from the context)
173  *                      + the number of extra divs constructed
174  *      Of these, the first tab->n_param and the last tab->n_div variables
175  *      correspond to the variables in the context, i.e.,
176  *              tab->n_param + tab->n_div = context_tab->n_var
177  *      tab->n_param is equal to the number of parameters and input
178  *                      dimensions in the input map
179  *      tab->n_div is equal to the number of divs in the context
180  *
181  * If there is no solution, then the basic set corresponding to the
182  * context tableau is added to the set "empty".
183  *
184  * Otherwise, a basic map is constructed with the same parameters
185  * and divs as the context, the dimensions of the context as input
186  * dimensions and a number of output dimensions that is equal to
187  * the number of output dimensions in the input map.
188  * The divs in the input map (if any) that do not correspond to any
189  * div in the context do not appear in the solution.
190  * The algorithm will make sure that they have an integer value,
191  * but these values themselves are of no interest.
192  *
193  * The constraints and divs of the context are simply copied
194  * fron context_tab->bset.
195  * To extract the value of the output variables, it should be noted
196  * that we always use a big parameter M and so the variable stored
197  * in the tableau is not an output variable x itself, but
198  *      x' = M + x (in case of minimization)
199  * or
200  *      x' = M - x (in case of maximization)
201  * If x' appears in a column, then its optimal value is zero,
202  * which means that the optimal value of x is an unbounded number
203  * (-M for minimization and M for maximization).
204  * We currently assume that the output dimensions in the original map
205  * are bounded, so this cannot occur.
206  * Similarly, when x' appears in a row, then the coefficient of M in that
207  * row is necessarily 1.
208  * If the row represents
209  *      d x' = c + d M + e(y)
210  * then, in case of minimization, an equality
211  *      c + e(y) - d x' = 0
212  * is added, and in case of maximization,
213  *      c + e(y) + d x' = 0
214  */
215 static struct isl_sol_map *sol_map_add(struct isl_sol_map *sol,
216         struct isl_tab *tab)
217 {
218         int i;
219         struct isl_basic_map *bmap = NULL;
220         isl_basic_set *context_bset;
221         unsigned n_eq;
222         unsigned n_ineq;
223         unsigned nparam;
224         unsigned total;
225         unsigned n_div;
226         unsigned n_out;
227         unsigned off;
228
229         if (!sol || !tab)
230                 goto error;
231
232         if (tab->empty)
233                 return add_empty(sol);
234
235         context_bset = sol->sol.context->op->peek_basic_set(sol->sol.context);
236         off = 2 + tab->M;
237         n_out = isl_map_dim(sol->map, isl_dim_out);
238         n_eq = context_bset->n_eq + n_out;
239         n_ineq = context_bset->n_ineq;
240         nparam = tab->n_param;
241         total = isl_map_dim(sol->map, isl_dim_all);
242         bmap = isl_basic_map_alloc_dim(isl_map_get_dim(sol->map),
243                                     tab->n_div, n_eq, 2 * tab->n_div + n_ineq);
244         if (!bmap)
245                 goto error;
246         n_div = tab->n_div;
247         if (tab->rational)
248                 ISL_F_SET(bmap, ISL_BASIC_MAP_RATIONAL);
249         for (i = 0; i < context_bset->n_div; ++i) {
250                 int k = isl_basic_map_alloc_div(bmap);
251                 if (k < 0)
252                         goto error;
253                 isl_seq_cpy(bmap->div[k],
254                             context_bset->div[i], 1 + 1 + nparam);
255                 isl_seq_clr(bmap->div[k] + 1 + 1 + nparam, total - nparam);
256                 isl_seq_cpy(bmap->div[k] + 1 + 1 + total,
257                             context_bset->div[i] + 1 + 1 + nparam, i);
258         }
259         for (i = 0; i < context_bset->n_eq; ++i) {
260                 int k = isl_basic_map_alloc_equality(bmap);
261                 if (k < 0)
262                         goto error;
263                 isl_seq_cpy(bmap->eq[k], context_bset->eq[i], 1 + nparam);
264                 isl_seq_clr(bmap->eq[k] + 1 + nparam, total - nparam);
265                 isl_seq_cpy(bmap->eq[k] + 1 + total,
266                             context_bset->eq[i] + 1 + nparam, n_div);
267         }
268         for (i = 0; i < context_bset->n_ineq; ++i) {
269                 int k = isl_basic_map_alloc_inequality(bmap);
270                 if (k < 0)
271                         goto error;
272                 isl_seq_cpy(bmap->ineq[k],
273                         context_bset->ineq[i], 1 + nparam);
274                 isl_seq_clr(bmap->ineq[k] + 1 + nparam, total - nparam);
275                 isl_seq_cpy(bmap->ineq[k] + 1 + total,
276                         context_bset->ineq[i] + 1 + nparam, n_div);
277         }
278         for (i = tab->n_param; i < total; ++i) {
279                 int k = isl_basic_map_alloc_equality(bmap);
280                 if (k < 0)
281                         goto error;
282                 isl_seq_clr(bmap->eq[k] + 1, isl_basic_map_total_dim(bmap));
283                 if (!tab->var[i].is_row) {
284                         /* no unbounded */
285                         isl_assert(bmap->ctx, !tab->M, goto error);
286                         isl_int_set_si(bmap->eq[k][0], 0);
287                         if (sol->max)
288                                 isl_int_set_si(bmap->eq[k][1 + i], 1);
289                         else
290                                 isl_int_set_si(bmap->eq[k][1 + i], -1);
291                 } else {
292                         int row, j;
293                         row = tab->var[i].index;
294                         /* no unbounded */
295                         if (tab->M)
296                                 isl_assert(bmap->ctx,
297                                         isl_int_eq(tab->mat->row[row][2],
298                                                    tab->mat->row[row][0]),
299                                         goto error);
300                         isl_int_set(bmap->eq[k][0], tab->mat->row[row][1]);
301                         for (j = 0; j < tab->n_param; ++j) {
302                                 int col;
303                                 if (tab->var[j].is_row)
304                                         continue;
305                                 col = tab->var[j].index;
306                                 isl_int_set(bmap->eq[k][1 + j],
307                                             tab->mat->row[row][off + col]);
308                         }
309                         for (j = 0; j < tab->n_div; ++j) {
310                                 int col;
311                                 if (tab->var[tab->n_var - tab->n_div+j].is_row)
312                                         continue;
313                                 col = tab->var[tab->n_var - tab->n_div+j].index;
314                                 isl_int_set(bmap->eq[k][1 + total + j],
315                                             tab->mat->row[row][off + col]);
316                         }
317                         if (sol->max)
318                                 isl_int_set(bmap->eq[k][1 + i],
319                                             tab->mat->row[row][0]);
320                         else
321                                 isl_int_neg(bmap->eq[k][1 + i],
322                                             tab->mat->row[row][0]);
323                 }
324         }
325         bmap = isl_basic_map_simplify(bmap);
326         bmap = isl_basic_map_finalize(bmap);
327         sol->map = isl_map_grow(sol->map, 1);
328         sol->map = isl_map_add(sol->map, bmap);
329         if (!sol->map)
330                 goto error;
331         return sol;
332 error:
333         isl_basic_map_free(bmap);
334         sol_free(&sol->sol);
335         return NULL;
336 }
337
338 static struct isl_sol *sol_map_add_wrap(struct isl_sol *sol,
339         struct isl_tab *tab)
340 {
341         return (struct isl_sol *)sol_map_add((struct isl_sol_map *)sol, tab);
342 }
343
344
345 /* Store the "parametric constant" of row "row" of tableau "tab" in "line",
346  * i.e., the constant term and the coefficients of all variables that
347  * appear in the context tableau.
348  * Note that the coefficient of the big parameter M is NOT copied.
349  * The context tableau may not have a big parameter and even when it
350  * does, it is a different big parameter.
351  */
352 static void get_row_parameter_line(struct isl_tab *tab, int row, isl_int *line)
353 {
354         int i;
355         unsigned off = 2 + tab->M;
356
357         isl_int_set(line[0], tab->mat->row[row][1]);
358         for (i = 0; i < tab->n_param; ++i) {
359                 if (tab->var[i].is_row)
360                         isl_int_set_si(line[1 + i], 0);
361                 else {
362                         int col = tab->var[i].index;
363                         isl_int_set(line[1 + i], tab->mat->row[row][off + col]);
364                 }
365         }
366         for (i = 0; i < tab->n_div; ++i) {
367                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
368                         isl_int_set_si(line[1 + tab->n_param + i], 0);
369                 else {
370                         int col = tab->var[tab->n_var - tab->n_div + i].index;
371                         isl_int_set(line[1 + tab->n_param + i],
372                                     tab->mat->row[row][off + col]);
373                 }
374         }
375 }
376
377 /* Check if rows "row1" and "row2" have identical "parametric constants",
378  * as explained above.
379  * In this case, we also insist that the coefficients of the big parameter
380  * be the same as the values of the constants will only be the same
381  * if these coefficients are also the same.
382  */
383 static int identical_parameter_line(struct isl_tab *tab, int row1, int row2)
384 {
385         int i;
386         unsigned off = 2 + tab->M;
387
388         if (isl_int_ne(tab->mat->row[row1][1], tab->mat->row[row2][1]))
389                 return 0;
390
391         if (tab->M && isl_int_ne(tab->mat->row[row1][2],
392                                  tab->mat->row[row2][2]))
393                 return 0;
394
395         for (i = 0; i < tab->n_param + tab->n_div; ++i) {
396                 int pos = i < tab->n_param ? i :
397                         tab->n_var - tab->n_div + i - tab->n_param;
398                 int col;
399
400                 if (tab->var[pos].is_row)
401                         continue;
402                 col = tab->var[pos].index;
403                 if (isl_int_ne(tab->mat->row[row1][off + col],
404                                tab->mat->row[row2][off + col]))
405                         return 0;
406         }
407         return 1;
408 }
409
410 /* Return an inequality that expresses that the "parametric constant"
411  * should be non-negative.
412  * This function is only called when the coefficient of the big parameter
413  * is equal to zero.
414  */
415 static struct isl_vec *get_row_parameter_ineq(struct isl_tab *tab, int row)
416 {
417         struct isl_vec *ineq;
418
419         ineq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_param + tab->n_div);
420         if (!ineq)
421                 return NULL;
422
423         get_row_parameter_line(tab, row, ineq->el);
424         if (ineq)
425                 ineq = isl_vec_normalize(ineq);
426
427         return ineq;
428 }
429
430 /* Return a integer division for use in a parametric cut based on the given row.
431  * In particular, let the parametric constant of the row be
432  *
433  *              \sum_i a_i y_i
434  *
435  * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
436  * The div returned is equal to
437  *
438  *              floor(\sum_i {-a_i} y_i) = floor((\sum_i (-a_i mod d) y_i)/d)
439  */
440 static struct isl_vec *get_row_parameter_div(struct isl_tab *tab, int row)
441 {
442         struct isl_vec *div;
443
444         div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
445         if (!div)
446                 return NULL;
447
448         isl_int_set(div->el[0], tab->mat->row[row][0]);
449         get_row_parameter_line(tab, row, div->el + 1);
450         div = isl_vec_normalize(div);
451         isl_seq_neg(div->el + 1, div->el + 1, div->size - 1);
452         isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
453
454         return div;
455 }
456
457 /* Return a integer division for use in transferring an integrality constraint
458  * to the context.
459  * In particular, let the parametric constant of the row be
460  *
461  *              \sum_i a_i y_i
462  *
463  * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
464  * The the returned div is equal to
465  *
466  *              floor(\sum_i {a_i} y_i) = floor((\sum_i (a_i mod d) y_i)/d)
467  */
468 static struct isl_vec *get_row_split_div(struct isl_tab *tab, int row)
469 {
470         struct isl_vec *div;
471
472         div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
473         if (!div)
474                 return NULL;
475
476         isl_int_set(div->el[0], tab->mat->row[row][0]);
477         get_row_parameter_line(tab, row, div->el + 1);
478         div = isl_vec_normalize(div);
479         isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
480
481         return div;
482 }
483
484 /* Construct and return an inequality that expresses an upper bound
485  * on the given div.
486  * In particular, if the div is given by
487  *
488  *      d = floor(e/m)
489  *
490  * then the inequality expresses
491  *
492  *      m d <= e
493  */
494 static struct isl_vec *ineq_for_div(struct isl_basic_set *bset, unsigned div)
495 {
496         unsigned total;
497         unsigned div_pos;
498         struct isl_vec *ineq;
499
500         if (!bset)
501                 return NULL;
502
503         total = isl_basic_set_total_dim(bset);
504         div_pos = 1 + total - bset->n_div + div;
505
506         ineq = isl_vec_alloc(bset->ctx, 1 + total);
507         if (!ineq)
508                 return NULL;
509
510         isl_seq_cpy(ineq->el, bset->div[div] + 1, 1 + total);
511         isl_int_neg(ineq->el[div_pos], bset->div[div][0]);
512         return ineq;
513 }
514
515 /* Given a row in the tableau and a div that was created
516  * using get_row_split_div and that been constrained to equality, i.e.,
517  *
518  *              d = floor(\sum_i {a_i} y_i) = \sum_i {a_i} y_i
519  *
520  * replace the expression "\sum_i {a_i} y_i" in the row by d,
521  * i.e., we subtract "\sum_i {a_i} y_i" and add 1 d.
522  * The coefficients of the non-parameters in the tableau have been
523  * verified to be integral.  We can therefore simply replace coefficient b
524  * by floor(b).  For the coefficients of the parameters we have
525  * floor(a_i) = a_i - {a_i}, while for the other coefficients, we have
526  * floor(b) = b.
527  */
528 static struct isl_tab *set_row_cst_to_div(struct isl_tab *tab, int row, int div)
529 {
530         int col;
531         unsigned off = 2 + tab->M;
532
533         isl_seq_fdiv_q(tab->mat->row[row] + 1, tab->mat->row[row] + 1,
534                         tab->mat->row[row][0], 1 + tab->M + tab->n_col);
535
536         isl_int_set_si(tab->mat->row[row][0], 1);
537
538         isl_assert(tab->mat->ctx,
539                 !tab->var[tab->n_var - tab->n_div + div].is_row, goto error);
540
541         col = tab->var[tab->n_var - tab->n_div + div].index;
542         isl_int_set_si(tab->mat->row[row][off + col], 1);
543
544         return tab;
545 error:
546         isl_tab_free(tab);
547         return NULL;
548 }
549
550 /* Check if the (parametric) constant of the given row is obviously
551  * negative, meaning that we don't need to consult the context tableau.
552  * If there is a big parameter and its coefficient is non-zero,
553  * then this coefficient determines the outcome.
554  * Otherwise, we check whether the constant is negative and
555  * all non-zero coefficients of parameters are negative and
556  * belong to non-negative parameters.
557  */
558 static int is_obviously_neg(struct isl_tab *tab, int row)
559 {
560         int i;
561         int col;
562         unsigned off = 2 + tab->M;
563
564         if (tab->M) {
565                 if (isl_int_is_pos(tab->mat->row[row][2]))
566                         return 0;
567                 if (isl_int_is_neg(tab->mat->row[row][2]))
568                         return 1;
569         }
570
571         if (isl_int_is_nonneg(tab->mat->row[row][1]))
572                 return 0;
573         for (i = 0; i < tab->n_param; ++i) {
574                 /* Eliminated parameter */
575                 if (tab->var[i].is_row)
576                         continue;
577                 col = tab->var[i].index;
578                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
579                         continue;
580                 if (!tab->var[i].is_nonneg)
581                         return 0;
582                 if (isl_int_is_pos(tab->mat->row[row][off + col]))
583                         return 0;
584         }
585         for (i = 0; i < tab->n_div; ++i) {
586                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
587                         continue;
588                 col = tab->var[tab->n_var - tab->n_div + i].index;
589                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
590                         continue;
591                 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
592                         return 0;
593                 if (isl_int_is_pos(tab->mat->row[row][off + col]))
594                         return 0;
595         }
596         return 1;
597 }
598
599 /* Check if the (parametric) constant of the given row is obviously
600  * non-negative, meaning that we don't need to consult the context tableau.
601  * If there is a big parameter and its coefficient is non-zero,
602  * then this coefficient determines the outcome.
603  * Otherwise, we check whether the constant is non-negative and
604  * all non-zero coefficients of parameters are positive and
605  * belong to non-negative parameters.
606  */
607 static int is_obviously_nonneg(struct isl_tab *tab, int row)
608 {
609         int i;
610         int col;
611         unsigned off = 2 + tab->M;
612
613         if (tab->M) {
614                 if (isl_int_is_pos(tab->mat->row[row][2]))
615                         return 1;
616                 if (isl_int_is_neg(tab->mat->row[row][2]))
617                         return 0;
618         }
619
620         if (isl_int_is_neg(tab->mat->row[row][1]))
621                 return 0;
622         for (i = 0; i < tab->n_param; ++i) {
623                 /* Eliminated parameter */
624                 if (tab->var[i].is_row)
625                         continue;
626                 col = tab->var[i].index;
627                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
628                         continue;
629                 if (!tab->var[i].is_nonneg)
630                         return 0;
631                 if (isl_int_is_neg(tab->mat->row[row][off + col]))
632                         return 0;
633         }
634         for (i = 0; i < tab->n_div; ++i) {
635                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
636                         continue;
637                 col = tab->var[tab->n_var - tab->n_div + i].index;
638                 if (isl_int_is_zero(tab->mat->row[row][off + col]))
639                         continue;
640                 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
641                         return 0;
642                 if (isl_int_is_neg(tab->mat->row[row][off + col]))
643                         return 0;
644         }
645         return 1;
646 }
647
648 /* Given a row r and two columns, return the column that would
649  * lead to the lexicographically smallest increment in the sample
650  * solution when leaving the basis in favor of the row.
651  * Pivoting with column c will increment the sample value by a non-negative
652  * constant times a_{V,c}/a_{r,c}, with a_{V,c} the elements of column c
653  * corresponding to the non-parametric variables.
654  * If variable v appears in a column c_v, the a_{v,c} = 1 iff c = c_v,
655  * with all other entries in this virtual row equal to zero.
656  * If variable v appears in a row, then a_{v,c} is the element in column c
657  * of that row.
658  *
659  * Let v be the first variable with a_{v,c1}/a_{r,c1} != a_{v,c2}/a_{r,c2}.
660  * Then if a_{v,c1}/a_{r,c1} < a_{v,c2}/a_{r,c2}, i.e.,
661  * a_{v,c2} a_{r,c1} - a_{v,c1} a_{r,c2} > 0, c1 results in the minimal
662  * increment.  Otherwise, it's c2.
663  */
664 static int lexmin_col_pair(struct isl_tab *tab,
665         int row, int col1, int col2, isl_int tmp)
666 {
667         int i;
668         isl_int *tr;
669
670         tr = tab->mat->row[row] + 2 + tab->M;
671
672         for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
673                 int s1, s2;
674                 isl_int *r;
675
676                 if (!tab->var[i].is_row) {
677                         if (tab->var[i].index == col1)
678                                 return col2;
679                         if (tab->var[i].index == col2)
680                                 return col1;
681                         continue;
682                 }
683
684                 if (tab->var[i].index == row)
685                         continue;
686
687                 r = tab->mat->row[tab->var[i].index] + 2 + tab->M;
688                 s1 = isl_int_sgn(r[col1]);
689                 s2 = isl_int_sgn(r[col2]);
690                 if (s1 == 0 && s2 == 0)
691                         continue;
692                 if (s1 < s2)
693                         return col1;
694                 if (s2 < s1)
695                         return col2;
696
697                 isl_int_mul(tmp, r[col2], tr[col1]);
698                 isl_int_submul(tmp, r[col1], tr[col2]);
699                 if (isl_int_is_pos(tmp))
700                         return col1;
701                 if (isl_int_is_neg(tmp))
702                         return col2;
703         }
704         return -1;
705 }
706
707 /* Given a row in the tableau, find and return the column that would
708  * result in the lexicographically smallest, but positive, increment
709  * in the sample point.
710  * If there is no such column, then return tab->n_col.
711  * If anything goes wrong, return -1.
712  */
713 static int lexmin_pivot_col(struct isl_tab *tab, int row)
714 {
715         int j;
716         int col = tab->n_col;
717         isl_int *tr;
718         isl_int tmp;
719
720         tr = tab->mat->row[row] + 2 + tab->M;
721
722         isl_int_init(tmp);
723
724         for (j = tab->n_dead; j < tab->n_col; ++j) {
725                 if (tab->col_var[j] >= 0 &&
726                     (tab->col_var[j] < tab->n_param  ||
727                     tab->col_var[j] >= tab->n_var - tab->n_div))
728                         continue;
729
730                 if (!isl_int_is_pos(tr[j]))
731                         continue;
732
733                 if (col == tab->n_col)
734                         col = j;
735                 else
736                         col = lexmin_col_pair(tab, row, col, j, tmp);
737                 isl_assert(tab->mat->ctx, col >= 0, goto error);
738         }
739
740         isl_int_clear(tmp);
741         return col;
742 error:
743         isl_int_clear(tmp);
744         return -1;
745 }
746
747 /* Return the first known violated constraint, i.e., a non-negative
748  * contraint that currently has an either obviously negative value
749  * or a previously determined to be negative value.
750  *
751  * If any constraint has a negative coefficient for the big parameter,
752  * if any, then we return one of these first.
753  */
754 static int first_neg(struct isl_tab *tab)
755 {
756         int row;
757
758         if (tab->M)
759                 for (row = tab->n_redundant; row < tab->n_row; ++row) {
760                         if (!isl_tab_var_from_row(tab, row)->is_nonneg)
761                                 continue;
762                         if (isl_int_is_neg(tab->mat->row[row][2]))
763                                 return row;
764                 }
765         for (row = tab->n_redundant; row < tab->n_row; ++row) {
766                 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
767                         continue;
768                 if (tab->row_sign) {
769                         if (tab->row_sign[row] == 0 &&
770                             is_obviously_neg(tab, row))
771                                 tab->row_sign[row] = isl_tab_row_neg;
772                         if (tab->row_sign[row] != isl_tab_row_neg)
773                                 continue;
774                 } else if (!is_obviously_neg(tab, row))
775                         continue;
776                 return row;
777         }
778         return -1;
779 }
780
781 /* Resolve all known or obviously violated constraints through pivoting.
782  * In particular, as long as we can find any violated constraint, we
783  * look for a pivoting column that would result in the lexicographicallly
784  * smallest increment in the sample point.  If there is no such column
785  * then the tableau is infeasible.
786  */
787 static struct isl_tab *restore_lexmin(struct isl_tab *tab)
788 {
789         int row, col;
790
791         if (!tab)
792                 return NULL;
793         if (tab->empty)
794                 return tab;
795         while ((row = first_neg(tab)) != -1) {
796                 col = lexmin_pivot_col(tab, row);
797                 if (col >= tab->n_col)
798                         return isl_tab_mark_empty(tab);
799                 if (col < 0)
800                         goto error;
801                 isl_tab_pivot(tab, row, col);
802         }
803         return tab;
804 error:
805         isl_tab_free(tab);
806         return NULL;
807 }
808
809 /* Given a row that represents an equality, look for an appropriate
810  * pivoting column.
811  * In particular, if there are any non-zero coefficients among
812  * the non-parameter variables, then we take the last of these
813  * variables.  Eliminating this variable in terms of the other
814  * variables and/or parameters does not influence the property
815  * that all column in the initial tableau are lexicographically
816  * positive.  The row corresponding to the eliminated variable
817  * will only have non-zero entries below the diagonal of the
818  * initial tableau.  That is, we transform
819  *
820  *              I                               I
821  *                1             into            a
822  *                  I                             I
823  *
824  * If there is no such non-parameter variable, then we are dealing with
825  * pure parameter equality and we pick any parameter with coefficient 1 or -1
826  * for elimination.  This will ensure that the eliminated parameter
827  * always has an integer value whenever all the other parameters are integral.
828  * If there is no such parameter then we return -1.
829  */
830 static int last_var_col_or_int_par_col(struct isl_tab *tab, int row)
831 {
832         unsigned off = 2 + tab->M;
833         int i;
834
835         for (i = tab->n_var - tab->n_div - 1; i >= 0 && i >= tab->n_param; --i) {
836                 int col;
837                 if (tab->var[i].is_row)
838                         continue;
839                 col = tab->var[i].index;
840                 if (col <= tab->n_dead)
841                         continue;
842                 if (!isl_int_is_zero(tab->mat->row[row][off + col]))
843                         return col;
844         }
845         for (i = tab->n_dead; i < tab->n_col; ++i) {
846                 if (isl_int_is_one(tab->mat->row[row][off + i]))
847                         return i;
848                 if (isl_int_is_negone(tab->mat->row[row][off + i]))
849                         return i;
850         }
851         return -1;
852 }
853
854 /* Add an equality that is known to be valid to the tableau.
855  * We first check if we can eliminate a variable or a parameter.
856  * If not, we add the equality as two inequalities.
857  * In this case, the equality was a pure parameter equality and there
858  * is no need to resolve any constraint violations.
859  */
860 static struct isl_tab *add_lexmin_valid_eq(struct isl_tab *tab, isl_int *eq)
861 {
862         int i;
863         int r;
864
865         if (!tab)
866                 return NULL;
867         r = isl_tab_add_row(tab, eq);
868         if (r < 0)
869                 goto error;
870
871         r = tab->con[r].index;
872         i = last_var_col_or_int_par_col(tab, r);
873         if (i < 0) {
874                 tab->con[r].is_nonneg = 1;
875                 isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]);
876                 isl_seq_neg(eq, eq, 1 + tab->n_var);
877                 r = isl_tab_add_row(tab, eq);
878                 if (r < 0)
879                         goto error;
880                 tab->con[r].is_nonneg = 1;
881                 isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]);
882         } else {
883                 isl_tab_pivot(tab, r, i);
884                 isl_tab_kill_col(tab, i);
885                 tab->n_eq++;
886
887                 tab = restore_lexmin(tab);
888         }
889
890         return tab;
891 error:
892         isl_tab_free(tab);
893         return NULL;
894 }
895
896 /* Check if the given row is a pure constant.
897  */
898 static int is_constant(struct isl_tab *tab, int row)
899 {
900         unsigned off = 2 + tab->M;
901
902         return isl_seq_first_non_zero(tab->mat->row[row] + off + tab->n_dead,
903                                         tab->n_col - tab->n_dead) == -1;
904 }
905
906 /* Add an equality that may or may not be valid to the tableau.
907  * If the resulting row is a pure constant, then it must be zero.
908  * Otherwise, the resulting tableau is empty.
909  *
910  * If the row is not a pure constant, then we add two inequalities,
911  * each time checking that they can be satisfied.
912  * In the end we try to use one of the two constraints to eliminate
913  * a column.
914  */
915 static struct isl_tab *add_lexmin_eq(struct isl_tab *tab, isl_int *eq)
916 {
917         int r1, r2;
918         int row;
919         struct isl_tab_undo *snap;
920
921         if (!tab)
922                 return NULL;
923         snap = isl_tab_snap(tab);
924         r1 = isl_tab_add_row(tab, eq);
925         if (r1 < 0)
926                 goto error;
927         tab->con[r1].is_nonneg = 1;
928         isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r1]);
929
930         row = tab->con[r1].index;
931         if (is_constant(tab, row)) {
932                 if (!isl_int_is_zero(tab->mat->row[row][1]) ||
933                     (tab->M && !isl_int_is_zero(tab->mat->row[row][2])))
934                         return isl_tab_mark_empty(tab);
935                 if (isl_tab_rollback(tab, snap) < 0)
936                         goto error;
937                 return tab;
938         }
939
940         tab = restore_lexmin(tab);
941         if (!tab || tab->empty)
942                 return tab;
943
944         isl_seq_neg(eq, eq, 1 + tab->n_var);
945
946         r2 = isl_tab_add_row(tab, eq);
947         if (r2 < 0)
948                 goto error;
949         tab->con[r2].is_nonneg = 1;
950         isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r2]);
951
952         tab = restore_lexmin(tab);
953         if (!tab || tab->empty)
954                 return tab;
955
956         if (!tab->con[r1].is_row)
957                 isl_tab_kill_col(tab, tab->con[r1].index);
958         else if (!tab->con[r2].is_row)
959                 isl_tab_kill_col(tab, tab->con[r2].index);
960         else if (isl_int_is_zero(tab->mat->row[tab->con[r1].index][1])) {
961                 unsigned off = 2 + tab->M;
962                 int i;
963                 int row = tab->con[r1].index;
964                 i = isl_seq_first_non_zero(tab->mat->row[row]+off+tab->n_dead,
965                                                 tab->n_col - tab->n_dead);
966                 if (i != -1) {
967                         isl_tab_pivot(tab, row, tab->n_dead + i);
968                         isl_tab_kill_col(tab, tab->n_dead + i);
969                 }
970         }
971
972         if (tab->bset) {
973                 tab->bset = isl_basic_set_add_ineq(tab->bset, eq);
974                 isl_tab_push(tab, isl_tab_undo_bset_ineq);
975                 isl_seq_neg(eq, eq, 1 + tab->n_var);
976                 tab->bset = isl_basic_set_add_ineq(tab->bset, eq);
977                 isl_seq_neg(eq, eq, 1 + tab->n_var);
978                 isl_tab_push(tab, isl_tab_undo_bset_ineq);
979                 if (!tab->bset)
980                         goto error;
981         }
982
983         return tab;
984 error:
985         isl_tab_free(tab);
986         return NULL;
987 }
988
989 /* Add an inequality to the tableau, resolving violations using
990  * restore_lexmin.
991  */
992 static struct isl_tab *add_lexmin_ineq(struct isl_tab *tab, isl_int *ineq)
993 {
994         int r;
995
996         if (!tab)
997                 return NULL;
998         if (tab->bset) {
999                 tab->bset = isl_basic_set_add_ineq(tab->bset, ineq);
1000                 isl_tab_push(tab, isl_tab_undo_bset_ineq);
1001                 if (!tab->bset)
1002                         goto error;
1003         }
1004         r = isl_tab_add_row(tab, ineq);
1005         if (r < 0)
1006                 goto error;
1007         tab->con[r].is_nonneg = 1;
1008         isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]);
1009         if (isl_tab_row_is_redundant(tab, tab->con[r].index)) {
1010                 isl_tab_mark_redundant(tab, tab->con[r].index);
1011                 return tab;
1012         }
1013
1014         tab = restore_lexmin(tab);
1015         if (tab && !tab->empty && tab->con[r].is_row &&
1016                  isl_tab_row_is_redundant(tab, tab->con[r].index))
1017                 isl_tab_mark_redundant(tab, tab->con[r].index);
1018         return tab;
1019 error:
1020         isl_tab_free(tab);
1021         return NULL;
1022 }
1023
1024 /* Check if the coefficients of the parameters are all integral.
1025  */
1026 static int integer_parameter(struct isl_tab *tab, int row)
1027 {
1028         int i;
1029         int col;
1030         unsigned off = 2 + tab->M;
1031
1032         for (i = 0; i < tab->n_param; ++i) {
1033                 /* Eliminated parameter */
1034                 if (tab->var[i].is_row)
1035                         continue;
1036                 col = tab->var[i].index;
1037                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1038                                                 tab->mat->row[row][0]))
1039                         return 0;
1040         }
1041         for (i = 0; i < tab->n_div; ++i) {
1042                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1043                         continue;
1044                 col = tab->var[tab->n_var - tab->n_div + i].index;
1045                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1046                                                 tab->mat->row[row][0]))
1047                         return 0;
1048         }
1049         return 1;
1050 }
1051
1052 /* Check if the coefficients of the non-parameter variables are all integral.
1053  */
1054 static int integer_variable(struct isl_tab *tab, int row)
1055 {
1056         int i;
1057         unsigned off = 2 + tab->M;
1058
1059         for (i = 0; i < tab->n_col; ++i) {
1060                 if (tab->col_var[i] >= 0 &&
1061                     (tab->col_var[i] < tab->n_param ||
1062                      tab->col_var[i] >= tab->n_var - tab->n_div))
1063                         continue;
1064                 if (!isl_int_is_divisible_by(tab->mat->row[row][off + i],
1065                                                 tab->mat->row[row][0]))
1066                         return 0;
1067         }
1068         return 1;
1069 }
1070
1071 /* Check if the constant term is integral.
1072  */
1073 static int integer_constant(struct isl_tab *tab, int row)
1074 {
1075         return isl_int_is_divisible_by(tab->mat->row[row][1],
1076                                         tab->mat->row[row][0]);
1077 }
1078
1079 #define I_CST   1 << 0
1080 #define I_PAR   1 << 1
1081 #define I_VAR   1 << 2
1082
1083 /* Check for first (non-parameter) variable that is non-integer and
1084  * therefore requires a cut.
1085  * For parametric tableaus, there are three parts in a row,
1086  * the constant, the coefficients of the parameters and the rest.
1087  * For each part, we check whether the coefficients in that part
1088  * are all integral and if so, set the corresponding flag in *f.
1089  * If the constant and the parameter part are integral, then the
1090  * current sample value is integral and no cut is required
1091  * (irrespective of whether the variable part is integral).
1092  */
1093 static int first_non_integer(struct isl_tab *tab, int *f)
1094 {
1095         int i;
1096
1097         for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
1098                 int flags = 0;
1099                 int row;
1100                 if (!tab->var[i].is_row)
1101                         continue;
1102                 row = tab->var[i].index;
1103                 if (integer_constant(tab, row))
1104                         ISL_FL_SET(flags, I_CST);
1105                 if (integer_parameter(tab, row))
1106                         ISL_FL_SET(flags, I_PAR);
1107                 if (ISL_FL_ISSET(flags, I_CST) && ISL_FL_ISSET(flags, I_PAR))
1108                         continue;
1109                 if (integer_variable(tab, row))
1110                         ISL_FL_SET(flags, I_VAR);
1111                 *f = flags;
1112                 return row;
1113         }
1114         return -1;
1115 }
1116
1117 /* Add a (non-parametric) cut to cut away the non-integral sample
1118  * value of the given row.
1119  *
1120  * If the row is given by
1121  *
1122  *      m r = f + \sum_i a_i y_i
1123  *
1124  * then the cut is
1125  *
1126  *      c = - {-f/m} + \sum_i {a_i/m} y_i >= 0
1127  *
1128  * The big parameter, if any, is ignored, since it is assumed to be big
1129  * enough to be divisible by any integer.
1130  * If the tableau is actually a parametric tableau, then this function
1131  * is only called when all coefficients of the parameters are integral.
1132  * The cut therefore has zero coefficients for the parameters.
1133  *
1134  * The current value is known to be negative, so row_sign, if it
1135  * exists, is set accordingly.
1136  *
1137  * Return the row of the cut or -1.
1138  */
1139 static int add_cut(struct isl_tab *tab, int row)
1140 {
1141         int i;
1142         int r;
1143         isl_int *r_row;
1144         unsigned off = 2 + tab->M;
1145
1146         if (isl_tab_extend_cons(tab, 1) < 0)
1147                 return -1;
1148         r = isl_tab_allocate_con(tab);
1149         if (r < 0)
1150                 return -1;
1151
1152         r_row = tab->mat->row[tab->con[r].index];
1153         isl_int_set(r_row[0], tab->mat->row[row][0]);
1154         isl_int_neg(r_row[1], tab->mat->row[row][1]);
1155         isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1156         isl_int_neg(r_row[1], r_row[1]);
1157         if (tab->M)
1158                 isl_int_set_si(r_row[2], 0);
1159         for (i = 0; i < tab->n_col; ++i)
1160                 isl_int_fdiv_r(r_row[off + i],
1161                         tab->mat->row[row][off + i], tab->mat->row[row][0]);
1162
1163         tab->con[r].is_nonneg = 1;
1164         isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]);
1165         if (tab->row_sign)
1166                 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1167
1168         return tab->con[r].index;
1169 }
1170
1171 /* Given a non-parametric tableau, add cuts until an integer
1172  * sample point is obtained or until the tableau is determined
1173  * to be integer infeasible.
1174  * As long as there is any non-integer value in the sample point,
1175  * we add an appropriate cut, if possible and resolve the violated
1176  * cut constraint using restore_lexmin.
1177  * If one of the corresponding rows is equal to an integral
1178  * combination of variables/constraints plus a non-integral constant,
1179  * then there is no way to obtain an integer point an we return
1180  * a tableau that is marked empty.
1181  */
1182 static struct isl_tab *cut_to_integer_lexmin(struct isl_tab *tab)
1183 {
1184         int row;
1185         int flags;
1186
1187         if (!tab)
1188                 return NULL;
1189         if (tab->empty)
1190                 return tab;
1191
1192         while ((row = first_non_integer(tab, &flags)) != -1) {
1193                 if (ISL_FL_ISSET(flags, I_VAR))
1194                         return isl_tab_mark_empty(tab);
1195                 row = add_cut(tab, row);
1196                 if (row < 0)
1197                         goto error;
1198                 tab = restore_lexmin(tab);
1199                 if (!tab || tab->empty)
1200                         break;
1201         }
1202         return tab;
1203 error:
1204         isl_tab_free(tab);
1205         return NULL;
1206 }
1207
1208 /* Check whether all the currently active samples also satisfy the inequality
1209  * "ineq" (treated as an equality if eq is set).
1210  * Remove those samples that do not.
1211  */
1212 static struct isl_tab *check_samples(struct isl_tab *tab, isl_int *ineq, int eq)
1213 {
1214         int i;
1215         isl_int v;
1216
1217         if (!tab)
1218                 return NULL;
1219
1220         isl_assert(tab->mat->ctx, tab->bset, goto error);
1221         isl_assert(tab->mat->ctx, tab->samples, goto error);
1222         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, goto error);
1223
1224         isl_int_init(v);
1225         for (i = tab->n_outside; i < tab->n_sample; ++i) {
1226                 int sgn;
1227                 isl_seq_inner_product(ineq, tab->samples->row[i],
1228                                         1 + tab->n_var, &v);
1229                 sgn = isl_int_sgn(v);
1230                 if (eq ? (sgn == 0) : (sgn >= 0))
1231                         continue;
1232                 tab = isl_tab_drop_sample(tab, i);
1233                 if (!tab)
1234                         break;
1235         }
1236         isl_int_clear(v);
1237
1238         return tab;
1239 error:
1240         isl_tab_free(tab);
1241         return NULL;
1242 }
1243
1244 /* Check whether the sample value of the tableau is finite,
1245  * i.e., either the tableau does not use a big parameter, or
1246  * all values of the variables are equal to the big parameter plus
1247  * some constant.  This constant is the actual sample value.
1248  */
1249 static int sample_is_finite(struct isl_tab *tab)
1250 {
1251         int i;
1252
1253         if (!tab->M)
1254                 return 1;
1255
1256         for (i = 0; i < tab->n_var; ++i) {
1257                 int row;
1258                 if (!tab->var[i].is_row)
1259                         return 0;
1260                 row = tab->var[i].index;
1261                 if (isl_int_ne(tab->mat->row[row][0], tab->mat->row[row][2]))
1262                         return 0;
1263         }
1264         return 1;
1265 }
1266
1267 /* Check if the context tableau of sol has any integer points.
1268  * Leave tab in empty state if no integer point can be found.
1269  * If an integer point can be found and if moreover it is finite,
1270  * then it is added to the list of sample values.
1271  *
1272  * This function is only called when none of the currently active sample
1273  * values satisfies the most recently added constraint.
1274  */
1275 static struct isl_tab *check_integer_feasible(struct isl_tab *tab)
1276 {
1277         struct isl_tab_undo *snap;
1278         int feasible;
1279
1280         if (!tab)
1281                 return NULL;
1282
1283         snap = isl_tab_snap(tab);
1284         isl_tab_push_basis(tab);
1285
1286         tab = cut_to_integer_lexmin(tab);
1287         if (!tab)
1288                 goto error;
1289
1290         if (!tab->empty && sample_is_finite(tab)) {
1291                 struct isl_vec *sample;
1292
1293                 sample = isl_tab_get_sample_value(tab);
1294
1295                 tab = isl_tab_add_sample(tab, sample);
1296         }
1297
1298         if (!tab->empty && isl_tab_rollback(tab, snap) < 0)
1299                 goto error;
1300
1301         return tab;
1302 error:
1303         isl_tab_free(tab);
1304         return NULL;
1305 }
1306
1307 /* Check if any of the currently active sample values satisfies
1308  * the inequality "ineq" (an equality if eq is set).
1309  */
1310 static int tab_has_valid_sample(struct isl_tab *tab, isl_int *ineq, int eq)
1311 {
1312         int i;
1313         isl_int v;
1314
1315         if (!tab)
1316                 return -1;
1317
1318         isl_assert(tab->mat->ctx, tab->bset, return -1);
1319         isl_assert(tab->mat->ctx, tab->samples, return -1);
1320         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, return -1);
1321
1322         isl_int_init(v);
1323         for (i = tab->n_outside; i < tab->n_sample; ++i) {
1324                 int sgn;
1325                 isl_seq_inner_product(ineq, tab->samples->row[i],
1326                                         1 + tab->n_var, &v);
1327                 sgn = isl_int_sgn(v);
1328                 if (eq ? (sgn == 0) : (sgn >= 0))
1329                         break;
1330         }
1331         isl_int_clear(v);
1332
1333         return i < tab->n_sample;
1334 }
1335
1336 /* For a div d = floor(f/m), add the constraints
1337  *
1338  *              f - m d >= 0
1339  *              -(f-(m-1)) + m d >= 0
1340  *
1341  * Note that the second constraint is the negation of
1342  *
1343  *              f - m d >= m
1344  */
1345 static void add_div_constraints(struct isl_context *context, unsigned div)
1346 {
1347         unsigned total;
1348         unsigned div_pos;
1349         struct isl_vec *ineq;
1350         struct isl_basic_set *bset;
1351
1352         bset = context->op->peek_basic_set(context);
1353         if (!bset)
1354                 goto error;
1355
1356         total = isl_basic_set_total_dim(bset);
1357         div_pos = 1 + total - bset->n_div + div;
1358
1359         ineq = ineq_for_div(bset, div);
1360         if (!ineq)
1361                 goto error;
1362
1363         context->op->add_ineq(context, ineq->el, 0, 0);
1364
1365         isl_seq_neg(ineq->el, bset->div[div] + 1, 1 + total);
1366         isl_int_set(ineq->el[div_pos], bset->div[div][0]);
1367         isl_int_add(ineq->el[0], ineq->el[0], ineq->el[div_pos]);
1368         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
1369
1370         context->op->add_ineq(context, ineq->el, 0, 0);
1371
1372         isl_vec_free(ineq);
1373
1374         return;
1375 error:
1376         context->op->invalidate(context);
1377 }
1378
1379 /* Add a div specifed by "div" to the tableau "tab" and return
1380  * the index of the new div.  *nonneg is set to 1 if the div
1381  * is obviously non-negative.
1382  */
1383 static int context_tab_add_div(struct isl_tab *tab, struct isl_vec *div,
1384         int *nonneg)
1385 {
1386         int i;
1387         int r;
1388         int k;
1389         struct isl_mat *samples;
1390
1391         for (i = 0; i < tab->n_var; ++i) {
1392                 if (isl_int_is_zero(div->el[2 + i]))
1393                         continue;
1394                 if (!tab->var[i].is_nonneg)
1395                         break;
1396         }
1397         *nonneg = i == tab->n_var;
1398
1399         if (isl_tab_extend_cons(tab, 3) < 0)
1400                 return -1;
1401         if (isl_tab_extend_vars(tab, 1) < 0)
1402                 return -1;
1403         r = isl_tab_allocate_var(tab);
1404         if (r < 0)
1405                 return -1;
1406         if (*nonneg)
1407                 tab->var[r].is_nonneg = 1;
1408         tab->var[r].frozen = 1;
1409
1410         samples = isl_mat_extend(tab->samples,
1411                         tab->n_sample, 1 + tab->n_var);
1412         tab->samples = samples;
1413         if (!samples)
1414                 return -1;
1415         for (i = tab->n_outside; i < samples->n_row; ++i) {
1416                 isl_seq_inner_product(div->el + 1, samples->row[i],
1417                         div->size - 1, &samples->row[i][samples->n_col - 1]);
1418                 isl_int_fdiv_q(samples->row[i][samples->n_col - 1],
1419                                samples->row[i][samples->n_col - 1], div->el[0]);
1420         }
1421
1422         tab->bset = isl_basic_set_extend_dim(tab->bset,
1423                 isl_basic_set_get_dim(tab->bset), 1, 0, 2);
1424         k = isl_basic_set_alloc_div(tab->bset);
1425         if (k < 0)
1426                 return -1;
1427         isl_seq_cpy(tab->bset->div[k], div->el, div->size);
1428         isl_tab_push(tab, isl_tab_undo_bset_div);
1429
1430         return k;
1431 }
1432
1433 /* Add a div specified by "div" to both the main tableau and
1434  * the context tableau.  In case of the main tableau, we only
1435  * need to add an extra div.  In the context tableau, we also
1436  * need to express the meaning of the div.
1437  * Return the index of the div or -1 if anything went wrong.
1438  */
1439 static int add_div(struct isl_tab *tab, struct isl_context *context,
1440         struct isl_vec *div)
1441 {
1442         int r;
1443         int k;
1444         int nonneg;
1445
1446         k = context->op->add_div(context, div, &nonneg);
1447         if (k < 0)
1448                 goto error;
1449
1450         add_div_constraints(context, k);
1451         if (!context->op->is_ok(context))
1452                 goto error;
1453
1454         if (isl_tab_extend_vars(tab, 1) < 0)
1455                 goto error;
1456         r = isl_tab_allocate_var(tab);
1457         if (r < 0)
1458                 goto error;
1459         if (nonneg)
1460                 tab->var[r].is_nonneg = 1;
1461         tab->var[r].frozen = 1;
1462         tab->n_div++;
1463
1464         return tab->n_div - 1;
1465 error:
1466         context->op->invalidate(context);
1467         return -1;
1468 }
1469
1470 static int find_div(struct isl_tab *tab, isl_int *div, isl_int denom)
1471 {
1472         int i;
1473         unsigned total = isl_basic_set_total_dim(tab->bset);
1474
1475         for (i = 0; i < tab->bset->n_div; ++i) {
1476                 if (isl_int_ne(tab->bset->div[i][0], denom))
1477                         continue;
1478                 if (!isl_seq_eq(tab->bset->div[i] + 1, div, total))
1479                         continue;
1480                 return i;
1481         }
1482         return -1;
1483 }
1484
1485 /* Return the index of a div that corresponds to "div".
1486  * We first check if we already have such a div and if not, we create one.
1487  */
1488 static int get_div(struct isl_tab *tab, struct isl_context *context,
1489         struct isl_vec *div)
1490 {
1491         int d;
1492         struct isl_tab *context_tab = context->op->peek_tab(context);
1493
1494         if (!context_tab)
1495                 return -1;
1496
1497         d = find_div(context_tab, div->el + 1, div->el[0]);
1498         if (d != -1)
1499                 return d;
1500
1501         return add_div(tab, context, div);
1502 }
1503
1504 /* Add a parametric cut to cut away the non-integral sample value
1505  * of the give row.
1506  * Let a_i be the coefficients of the constant term and the parameters
1507  * and let b_i be the coefficients of the variables or constraints
1508  * in basis of the tableau.
1509  * Let q be the div q = floor(\sum_i {-a_i} y_i).
1510  *
1511  * The cut is expressed as
1512  *
1513  *      c = \sum_i -{-a_i} y_i + \sum_i {b_i} x_i + q >= 0
1514  *
1515  * If q did not already exist in the context tableau, then it is added first.
1516  * If q is in a column of the main tableau then the "+ q" can be accomplished
1517  * by setting the corresponding entry to the denominator of the constraint.
1518  * If q happens to be in a row of the main tableau, then the corresponding
1519  * row needs to be added instead (taking care of the denominators).
1520  * Note that this is very unlikely, but perhaps not entirely impossible.
1521  *
1522  * The current value of the cut is known to be negative (or at least
1523  * non-positive), so row_sign is set accordingly.
1524  *
1525  * Return the row of the cut or -1.
1526  */
1527 static int add_parametric_cut(struct isl_tab *tab, int row,
1528         struct isl_context *context)
1529 {
1530         struct isl_vec *div;
1531         int d;
1532         int i;
1533         int r;
1534         isl_int *r_row;
1535         int col;
1536         unsigned off = 2 + tab->M;
1537
1538         if (!context)
1539                 return -1;
1540
1541         div = get_row_parameter_div(tab, row);
1542         if (!div)
1543                 return -1;
1544
1545         d = context->op->get_div(context, tab, div);
1546         if (d < 0)
1547                 return -1;
1548
1549         if (isl_tab_extend_cons(tab, 1) < 0)
1550                 return -1;
1551         r = isl_tab_allocate_con(tab);
1552         if (r < 0)
1553                 return -1;
1554
1555         r_row = tab->mat->row[tab->con[r].index];
1556         isl_int_set(r_row[0], tab->mat->row[row][0]);
1557         isl_int_neg(r_row[1], tab->mat->row[row][1]);
1558         isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1559         isl_int_neg(r_row[1], r_row[1]);
1560         if (tab->M)
1561                 isl_int_set_si(r_row[2], 0);
1562         for (i = 0; i < tab->n_param; ++i) {
1563                 if (tab->var[i].is_row)
1564                         continue;
1565                 col = tab->var[i].index;
1566                 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
1567                 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
1568                                 tab->mat->row[row][0]);
1569                 isl_int_neg(r_row[off + col], r_row[off + col]);
1570         }
1571         for (i = 0; i < tab->n_div; ++i) {
1572                 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1573                         continue;
1574                 col = tab->var[tab->n_var - tab->n_div + i].index;
1575                 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
1576                 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
1577                                 tab->mat->row[row][0]);
1578                 isl_int_neg(r_row[off + col], r_row[off + col]);
1579         }
1580         for (i = 0; i < tab->n_col; ++i) {
1581                 if (tab->col_var[i] >= 0 &&
1582                     (tab->col_var[i] < tab->n_param ||
1583                      tab->col_var[i] >= tab->n_var - tab->n_div))
1584                         continue;
1585                 isl_int_fdiv_r(r_row[off + i],
1586                         tab->mat->row[row][off + i], tab->mat->row[row][0]);
1587         }
1588         if (tab->var[tab->n_var - tab->n_div + d].is_row) {
1589                 isl_int gcd;
1590                 int d_row = tab->var[tab->n_var - tab->n_div + d].index;
1591                 isl_int_init(gcd);
1592                 isl_int_gcd(gcd, tab->mat->row[d_row][0], r_row[0]);
1593                 isl_int_divexact(r_row[0], r_row[0], gcd);
1594                 isl_int_divexact(gcd, tab->mat->row[d_row][0], gcd);
1595                 isl_seq_combine(r_row + 1, gcd, r_row + 1,
1596                                 r_row[0], tab->mat->row[d_row] + 1,
1597                                 off - 1 + tab->n_col);
1598                 isl_int_mul(r_row[0], r_row[0], tab->mat->row[d_row][0]);
1599                 isl_int_clear(gcd);
1600         } else {
1601                 col = tab->var[tab->n_var - tab->n_div + d].index;
1602                 isl_int_set(r_row[off + col], tab->mat->row[row][0]);
1603         }
1604
1605         tab->con[r].is_nonneg = 1;
1606         isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]);
1607         if (tab->row_sign)
1608                 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1609
1610         isl_vec_free(div);
1611
1612         return tab->con[r].index;
1613 }
1614
1615 /* Construct a tableau for bmap that can be used for computing
1616  * the lexicographic minimum (or maximum) of bmap.
1617  * If not NULL, then dom is the domain where the minimum
1618  * should be computed.  In this case, we set up a parametric
1619  * tableau with row signs (initialized to "unknown").
1620  * If M is set, then the tableau will use a big parameter.
1621  * If max is set, then a maximum should be computed instead of a minimum.
1622  * This means that for each variable x, the tableau will contain the variable
1623  * x' = M - x, rather than x' = M + x.  This in turn means that the coefficient
1624  * of the variables in all constraints are negated prior to adding them
1625  * to the tableau.
1626  */
1627 static struct isl_tab *tab_for_lexmin(struct isl_basic_map *bmap,
1628         struct isl_basic_set *dom, unsigned M, int max)
1629 {
1630         int i;
1631         struct isl_tab *tab;
1632
1633         tab = isl_tab_alloc(bmap->ctx, 2 * bmap->n_eq + bmap->n_ineq + 1,
1634                             isl_basic_map_total_dim(bmap), M);
1635         if (!tab)
1636                 return NULL;
1637
1638         tab->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
1639         if (dom) {
1640                 tab->n_param = isl_basic_set_total_dim(dom) - dom->n_div;
1641                 tab->n_div = dom->n_div;
1642                 tab->row_sign = isl_calloc_array(bmap->ctx,
1643                                         enum isl_tab_row_sign, tab->mat->n_row);
1644                 if (!tab->row_sign)
1645                         goto error;
1646         }
1647         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
1648                 return isl_tab_mark_empty(tab);
1649
1650         for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
1651                 tab->var[i].is_nonneg = 1;
1652                 tab->var[i].frozen = 1;
1653         }
1654         for (i = 0; i < bmap->n_eq; ++i) {
1655                 if (max)
1656                         isl_seq_neg(bmap->eq[i] + 1 + tab->n_param,
1657                                     bmap->eq[i] + 1 + tab->n_param,
1658                                     tab->n_var - tab->n_param - tab->n_div);
1659                 tab = add_lexmin_valid_eq(tab, bmap->eq[i]);
1660                 if (max)
1661                         isl_seq_neg(bmap->eq[i] + 1 + tab->n_param,
1662                                     bmap->eq[i] + 1 + tab->n_param,
1663                                     tab->n_var - tab->n_param - tab->n_div);
1664                 if (!tab || tab->empty)
1665                         return tab;
1666         }
1667         for (i = 0; i < bmap->n_ineq; ++i) {
1668                 if (max)
1669                         isl_seq_neg(bmap->ineq[i] + 1 + tab->n_param,
1670                                     bmap->ineq[i] + 1 + tab->n_param,
1671                                     tab->n_var - tab->n_param - tab->n_div);
1672                 tab = add_lexmin_ineq(tab, bmap->ineq[i]);
1673                 if (max)
1674                         isl_seq_neg(bmap->ineq[i] + 1 + tab->n_param,
1675                                     bmap->ineq[i] + 1 + tab->n_param,
1676                                     tab->n_var - tab->n_param - tab->n_div);
1677                 if (!tab || tab->empty)
1678                         return tab;
1679         }
1680         return tab;
1681 error:
1682         isl_tab_free(tab);
1683         return NULL;
1684 }
1685
1686 /* Given a main tableau where more than one row requires a split,
1687  * determine and return the "best" row to split on.
1688  *
1689  * Given two rows in the main tableau, if the inequality corresponding
1690  * to the first row is redundant with respect to that of the second row
1691  * in the current tableau, then it is better to split on the second row,
1692  * since in the positive part, both row will be positive.
1693  * (In the negative part a pivot will have to be performed and just about
1694  * anything can happen to the sign of the other row.)
1695  *
1696  * As a simple heuristic, we therefore select the row that makes the most
1697  * of the other rows redundant.
1698  *
1699  * Perhaps it would also be useful to look at the number of constraints
1700  * that conflict with any given constraint.
1701  */
1702 static int best_split(struct isl_tab *tab, struct isl_tab *context_tab)
1703 {
1704         struct isl_tab_undo *snap;
1705         int split;
1706         int row;
1707         int best = -1;
1708         int best_r;
1709
1710         if (isl_tab_extend_cons(context_tab, 2) < 0)
1711                 return -1;
1712
1713         snap = isl_tab_snap(context_tab);
1714
1715         for (split = tab->n_redundant; split < tab->n_row; ++split) {
1716                 struct isl_tab_undo *snap2;
1717                 struct isl_vec *ineq = NULL;
1718                 int r = 0;
1719
1720                 if (!isl_tab_var_from_row(tab, split)->is_nonneg)
1721                         continue;
1722                 if (tab->row_sign[split] != isl_tab_row_any)
1723                         continue;
1724
1725                 ineq = get_row_parameter_ineq(tab, split);
1726                 if (!ineq)
1727                         return -1;
1728                 context_tab = isl_tab_add_ineq(context_tab, ineq->el);
1729                 isl_vec_free(ineq);
1730
1731                 snap2 = isl_tab_snap(context_tab);
1732
1733                 for (row = tab->n_redundant; row < tab->n_row; ++row) {
1734                         struct isl_tab_var *var;
1735
1736                         if (row == split)
1737                                 continue;
1738                         if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1739                                 continue;
1740                         if (tab->row_sign[row] != isl_tab_row_any)
1741                                 continue;
1742
1743                         ineq = get_row_parameter_ineq(tab, row);
1744                         if (!ineq)
1745                                 return -1;
1746                         context_tab = isl_tab_add_ineq(context_tab, ineq->el);
1747                         isl_vec_free(ineq);
1748                         var = &context_tab->con[context_tab->n_con - 1];
1749                         if (!context_tab->empty &&
1750                             !isl_tab_min_at_most_neg_one(context_tab, var))
1751                                 r++;
1752                         if (isl_tab_rollback(context_tab, snap2) < 0)
1753                                 return -1;
1754                 }
1755                 if (best == -1 || r > best_r) {
1756                         best = split;
1757                         best_r = r;
1758                 }
1759                 if (isl_tab_rollback(context_tab, snap) < 0)
1760                         return -1;
1761         }
1762
1763         return best;
1764 }
1765
1766 static struct isl_basic_set *context_lex_peek_basic_set(
1767         struct isl_context *context)
1768 {
1769         struct isl_context_lex *clex = (struct isl_context_lex *)context;
1770         if (!clex->tab)
1771                 return NULL;
1772         return clex->tab->bset;
1773 }
1774
1775 static struct isl_tab *context_lex_peek_tab(struct isl_context *context)
1776 {
1777         struct isl_context_lex *clex = (struct isl_context_lex *)context;
1778         return clex->tab;
1779 }
1780
1781 static void context_lex_extend(struct isl_context *context, int n)
1782 {
1783         struct isl_context_lex *clex = (struct isl_context_lex *)context;
1784         if (!clex->tab)
1785                 return;
1786         if (isl_tab_extend_cons(clex->tab, n) >= 0)
1787                 return;
1788         isl_tab_free(clex->tab);
1789         clex->tab = NULL;
1790 }
1791
1792 static void context_lex_add_eq(struct isl_context *context, isl_int *eq,
1793                 int check, int update)
1794 {
1795         struct isl_context_lex *clex = (struct isl_context_lex *)context;
1796         if (isl_tab_extend_cons(clex->tab, 2) < 0)
1797                 goto error;
1798         clex->tab = add_lexmin_eq(clex->tab, eq);
1799         if (check) {
1800                 int v = tab_has_valid_sample(clex->tab, eq, 1);
1801                 if (v < 0)
1802                         goto error;
1803                 if (!v)
1804                         clex->tab = check_integer_feasible(clex->tab);
1805         }
1806         if (update)
1807                 clex->tab = check_samples(clex->tab, eq, 1);
1808         return;
1809 error:
1810         isl_tab_free(clex->tab);
1811         clex->tab = NULL;
1812 }
1813
1814 static void context_lex_add_ineq(struct isl_context *context, isl_int *ineq,
1815                 int check, int update)
1816 {
1817         struct isl_context_lex *clex = (struct isl_context_lex *)context;
1818         if (isl_tab_extend_cons(clex->tab, 1) < 0)
1819                 goto error;
1820         clex->tab = add_lexmin_ineq(clex->tab, ineq);
1821         if (check) {
1822                 int v = tab_has_valid_sample(clex->tab, ineq, 0);
1823                 if (v < 0)
1824                         goto error;
1825                 if (!v)
1826                         clex->tab = check_integer_feasible(clex->tab);
1827         }
1828         if (update)
1829                 clex->tab = check_samples(clex->tab, ineq, 0);
1830         return;
1831 error:
1832         isl_tab_free(clex->tab);
1833         clex->tab = NULL;
1834 }
1835
1836 /* Check which signs can be obtained by "ineq" on all the currently
1837  * active sample values.  See row_sign for more information.
1838  */
1839 static enum isl_tab_row_sign tab_ineq_sign(struct isl_tab *tab, isl_int *ineq,
1840         int strict)
1841 {
1842         int i;
1843         int sgn;
1844         isl_int tmp;
1845         int res = isl_tab_row_unknown;
1846
1847         isl_assert(tab->mat->ctx, tab->samples, return 0);
1848         isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, return 0);
1849
1850         isl_int_init(tmp);
1851         for (i = tab->n_outside; i < tab->n_sample; ++i) {
1852                 isl_seq_inner_product(tab->samples->row[i], ineq,
1853                                         1 + tab->n_var, &tmp);
1854                 sgn = isl_int_sgn(tmp);
1855                 if (sgn > 0 || (sgn == 0 && strict)) {
1856                         if (res == isl_tab_row_unknown)
1857                                 res = isl_tab_row_pos;
1858                         if (res == isl_tab_row_neg)
1859                                 res = isl_tab_row_any;
1860                 }
1861                 if (sgn < 0) {
1862                         if (res == isl_tab_row_unknown)
1863                                 res = isl_tab_row_neg;
1864                         if (res == isl_tab_row_pos)
1865                                 res = isl_tab_row_any;
1866                 }
1867                 if (res == isl_tab_row_any)
1868                         break;
1869         }
1870         isl_int_clear(tmp);
1871
1872         return res;
1873 }
1874
1875 static enum isl_tab_row_sign context_lex_ineq_sign(struct isl_context *context,
1876                         isl_int *ineq, int strict)
1877 {
1878         struct isl_context_lex *clex = (struct isl_context_lex *)context;
1879         return tab_ineq_sign(clex->tab, ineq, strict);
1880 }
1881
1882 /* Check whether "ineq" can be added to the tableau without rendering
1883  * it infeasible.
1884  */
1885 static int context_lex_test_ineq(struct isl_context *context, isl_int *ineq)
1886 {
1887         struct isl_context_lex *clex = (struct isl_context_lex *)context;
1888         struct isl_tab_undo *snap;
1889         int feasible;
1890
1891         if (!clex->tab)
1892                 return -1;
1893
1894         if (isl_tab_extend_cons(clex->tab, 1) < 0)
1895                 return -1;
1896
1897         snap = isl_tab_snap(clex->tab);
1898         isl_tab_push_basis(clex->tab);
1899         clex->tab = add_lexmin_ineq(clex->tab, ineq);
1900         clex->tab = check_integer_feasible(clex->tab);
1901         if (!clex->tab)
1902                 return -1;
1903         feasible = !clex->tab->empty;
1904         if (isl_tab_rollback(clex->tab, snap) < 0)
1905                 return -1;
1906
1907         return feasible;
1908 }
1909
1910 static int context_lex_get_div(struct isl_context *context, struct isl_tab *tab,
1911                 struct isl_vec *div)
1912 {
1913         return get_div(tab, context, div);
1914 }
1915
1916 static int context_lex_add_div(struct isl_context *context, struct isl_vec *div,
1917         int *nonneg)
1918 {
1919         struct isl_context_lex *clex = (struct isl_context_lex *)context;
1920         return context_tab_add_div(clex->tab, div, nonneg);
1921 }
1922
1923 static int context_lex_best_split(struct isl_context *context,
1924                 struct isl_tab *tab)
1925 {
1926         struct isl_context_lex *clex = (struct isl_context_lex *)context;
1927         struct isl_tab_undo *snap;
1928         int r;
1929
1930         snap = isl_tab_snap(clex->tab);
1931         isl_tab_push_basis(clex->tab);
1932         r = best_split(tab, clex->tab);
1933
1934         if (isl_tab_rollback(clex->tab, snap) < 0)
1935                 return -1;
1936
1937         return r;
1938 }
1939
1940 static int context_lex_is_empty(struct isl_context *context)
1941 {
1942         struct isl_context_lex *clex = (struct isl_context_lex *)context;
1943         if (!clex->tab)
1944                 return -1;
1945         return clex->tab->empty;
1946 }
1947
1948 static void *context_lex_save(struct isl_context *context)
1949 {
1950         struct isl_context_lex *clex = (struct isl_context_lex *)context;
1951         struct isl_tab_undo *snap;
1952
1953         snap = isl_tab_snap(clex->tab);
1954         isl_tab_push_basis(clex->tab);
1955         isl_tab_save_samples(clex->tab);
1956
1957         return snap;
1958 }
1959
1960 static void context_lex_restore(struct isl_context *context, void *save)
1961 {
1962         struct isl_context_lex *clex = (struct isl_context_lex *)context;
1963         if (isl_tab_rollback(clex->tab, (struct isl_tab_undo *)save) < 0) {
1964                 isl_tab_free(clex->tab);
1965                 clex->tab = NULL;
1966         }
1967 }
1968
1969 static int context_lex_is_ok(struct isl_context *context)
1970 {
1971         struct isl_context_lex *clex = (struct isl_context_lex *)context;
1972         return !!clex->tab;
1973 }
1974
1975 /* For each variable in the context tableau, check if the variable can
1976  * only attain non-negative values.  If so, mark the parameter as non-negative
1977  * in the main tableau.  This allows for a more direct identification of some
1978  * cases of violated constraints.
1979  */
1980 static struct isl_tab *tab_detect_nonnegative_parameters(struct isl_tab *tab,
1981         struct isl_tab *context_tab)
1982 {
1983         int i;
1984         struct isl_tab_undo *snap;
1985         struct isl_vec *ineq = NULL;
1986         struct isl_tab_var *var;
1987         int n;
1988
1989         if (context_tab->n_var == 0)
1990                 return tab;
1991
1992         ineq = isl_vec_alloc(tab->mat->ctx, 1 + context_tab->n_var);
1993         if (!ineq)
1994                 goto error;
1995
1996         if (isl_tab_extend_cons(context_tab, 1) < 0)
1997                 goto error;
1998
1999         snap = isl_tab_snap(context_tab);
2000
2001         n = 0;
2002         isl_seq_clr(ineq->el, ineq->size);
2003         for (i = 0; i < context_tab->n_var; ++i) {
2004                 isl_int_set_si(ineq->el[1 + i], 1);
2005                 context_tab = isl_tab_add_ineq(context_tab, ineq->el);
2006                 var = &context_tab->con[context_tab->n_con - 1];
2007                 if (!context_tab->empty &&
2008                     !isl_tab_min_at_most_neg_one(context_tab, var)) {
2009                         int j = i;
2010                         if (i >= tab->n_param)
2011                                 j = i - tab->n_param + tab->n_var - tab->n_div;
2012                         tab->var[j].is_nonneg = 1;
2013                         n++;
2014                 }
2015                 isl_int_set_si(ineq->el[1 + i], 0);
2016                 if (isl_tab_rollback(context_tab, snap) < 0)
2017                         goto error;
2018         }
2019
2020         if (context_tab->M && n == context_tab->n_var) {
2021                 context_tab->mat = isl_mat_drop_cols(context_tab->mat, 2, 1);
2022                 context_tab->M = 0;
2023         }
2024
2025         isl_vec_free(ineq);
2026         return tab;
2027 error:
2028         isl_vec_free(ineq);
2029         isl_tab_free(tab);
2030         return NULL;
2031 }
2032
2033 static struct isl_tab *context_lex_detect_nonnegative_parameters(
2034         struct isl_context *context, struct isl_tab *tab)
2035 {
2036         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2037         struct isl_tab_undo *snap;
2038
2039         snap = isl_tab_snap(clex->tab);
2040         isl_tab_push_basis(clex->tab);
2041
2042         tab = tab_detect_nonnegative_parameters(tab, clex->tab);
2043
2044         if (isl_tab_rollback(clex->tab, snap) < 0)
2045                 goto error;
2046
2047         return tab;
2048 error:
2049         isl_tab_free(tab);
2050         return NULL;
2051 }
2052
2053 static void context_lex_invalidate(struct isl_context *context)
2054 {
2055         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2056         isl_tab_free(clex->tab);
2057         clex->tab = NULL;
2058 }
2059
2060 static void context_lex_free(struct isl_context *context)
2061 {
2062         struct isl_context_lex *clex = (struct isl_context_lex *)context;
2063         isl_tab_free(clex->tab);
2064         free(clex);
2065 }
2066
2067 struct isl_context_op isl_context_lex_op = {
2068         context_lex_detect_nonnegative_parameters,
2069         context_lex_peek_basic_set,
2070         context_lex_peek_tab,
2071         context_lex_add_eq,
2072         context_lex_add_ineq,
2073         context_lex_ineq_sign,
2074         context_lex_test_ineq,
2075         context_lex_get_div,
2076         context_lex_add_div,
2077         context_lex_best_split,
2078         context_lex_is_empty,
2079         context_lex_is_ok,
2080         context_lex_save,
2081         context_lex_restore,
2082         context_lex_invalidate,
2083         context_lex_free,
2084 };
2085
2086 static struct isl_tab *context_tab_for_lexmin(struct isl_basic_set *bset)
2087 {
2088         struct isl_tab *tab;
2089
2090         bset = isl_basic_set_cow(bset);
2091         if (!bset)
2092                 return NULL;
2093         tab = tab_for_lexmin((struct isl_basic_map *)bset, NULL, 1, 0);
2094         if (!tab)
2095                 goto error;
2096         tab->bset = bset;
2097         tab = isl_tab_init_samples(tab);
2098         return tab;
2099 error:
2100         isl_basic_set_free(bset);
2101         return NULL;
2102 }
2103
2104 static struct isl_context *isl_context_lex_alloc(struct isl_basic_set *dom)
2105 {
2106         struct isl_context_lex *clex;
2107
2108         if (!dom)
2109                 return NULL;
2110
2111         clex = isl_alloc_type(dom->ctx, struct isl_context_lex);
2112         if (!clex)
2113                 return NULL;
2114
2115         clex->context.op = &isl_context_lex_op;
2116
2117         clex->tab = context_tab_for_lexmin(isl_basic_set_copy(dom));
2118         clex->tab = restore_lexmin(clex->tab);
2119         clex->tab = check_integer_feasible(clex->tab);
2120         if (!clex->tab)
2121                 goto error;
2122
2123         return &clex->context;
2124 error:
2125         clex->context.op->free(&clex->context);
2126         return NULL;
2127 }
2128
2129 /* Construct an isl_sol_map structure for accumulating the solution.
2130  * If track_empty is set, then we also keep track of the parts
2131  * of the context where there is no solution.
2132  * If max is set, then we are solving a maximization, rather than
2133  * a minimization problem, which means that the variables in the
2134  * tableau have value "M - x" rather than "M + x".
2135  */
2136 static struct isl_sol_map *sol_map_init(struct isl_basic_map *bmap,
2137         struct isl_basic_set *dom, int track_empty, int max)
2138 {
2139         struct isl_sol_map *sol_map;
2140
2141         sol_map = isl_calloc_type(bset->ctx, struct isl_sol_map);
2142         if (!sol_map)
2143                 goto error;
2144
2145         sol_map->max = max;
2146         sol_map->sol.add = &sol_map_add_wrap;
2147         sol_map->sol.free = &sol_map_free_wrap;
2148         sol_map->map = isl_map_alloc_dim(isl_basic_map_get_dim(bmap), 1,
2149                                             ISL_MAP_DISJOINT);
2150         if (!sol_map->map)
2151                 goto error;
2152
2153         sol_map->sol.context = isl_context_lex_alloc(dom);
2154         if (!sol_map->sol.context)
2155                 goto error;
2156
2157         if (track_empty) {
2158                 sol_map->empty = isl_set_alloc_dim(isl_basic_set_get_dim(dom),
2159                                                         1, ISL_SET_DISJOINT);
2160                 if (!sol_map->empty)
2161                         goto error;
2162         }
2163
2164         isl_basic_set_free(dom);
2165         return sol_map;
2166 error:
2167         isl_basic_set_free(dom);
2168         sol_map_free(sol_map);
2169         return NULL;
2170 }
2171
2172 /* Check whether all coefficients of (non-parameter) variables
2173  * are non-positive, meaning that no pivots can be performed on the row.
2174  */
2175 static int is_critical(struct isl_tab *tab, int row)
2176 {
2177         int j;
2178         unsigned off = 2 + tab->M;
2179
2180         for (j = tab->n_dead; j < tab->n_col; ++j) {
2181                 if (tab->col_var[j] >= 0 &&
2182                     (tab->col_var[j] < tab->n_param  ||
2183                     tab->col_var[j] >= tab->n_var - tab->n_div))
2184                         continue;
2185
2186                 if (isl_int_is_pos(tab->mat->row[row][off + j]))
2187                         return 0;
2188         }
2189
2190         return 1;
2191 }
2192
2193 /* Check whether the inequality represented by vec is strict over the integers,
2194  * i.e., there are no integer values satisfying the constraint with
2195  * equality.  This happens if the gcd of the coefficients is not a divisor
2196  * of the constant term.  If so, scale the constraint down by the gcd
2197  * of the coefficients.
2198  */
2199 static int is_strict(struct isl_vec *vec)
2200 {
2201         isl_int gcd;
2202         int strict = 0;
2203
2204         isl_int_init(gcd);
2205         isl_seq_gcd(vec->el + 1, vec->size - 1, &gcd);
2206         if (!isl_int_is_one(gcd)) {
2207                 strict = !isl_int_is_divisible_by(vec->el[0], gcd);
2208                 isl_int_fdiv_q(vec->el[0], vec->el[0], gcd);
2209                 isl_seq_scale_down(vec->el + 1, vec->el + 1, gcd, vec->size-1);
2210         }
2211         isl_int_clear(gcd);
2212
2213         return strict;
2214 }
2215
2216 /* Determine the sign of the given row of the main tableau.
2217  * The result is one of
2218  *      isl_tab_row_pos: always non-negative; no pivot needed
2219  *      isl_tab_row_neg: always non-positive; pivot
2220  *      isl_tab_row_any: can be both positive and negative; split
2221  *
2222  * We first handle some simple cases
2223  *      - the row sign may be known already
2224  *      - the row may be obviously non-negative
2225  *      - the parametric constant may be equal to that of another row
2226  *        for which we know the sign.  This sign will be either "pos" or
2227  *        "any".  If it had been "neg" then we would have pivoted before.
2228  *
2229  * If none of these cases hold, we check the value of the row for each
2230  * of the currently active samples.  Based on the signs of these values
2231  * we make an initial determination of the sign of the row.
2232  *
2233  *      all zero                        ->      unk(nown)
2234  *      all non-negative                ->      pos
2235  *      all non-positive                ->      neg
2236  *      both negative and positive      ->      all
2237  *
2238  * If we end up with "all", we are done.
2239  * Otherwise, we perform a check for positive and/or negative
2240  * values as follows.
2241  *
2242  *      samples        neg             unk             pos
2243  *      <0 ?                        Y        N      Y        N
2244  *                                          pos    any      pos
2245  *      >0 ?         Y      N    Y     N
2246  *                  any    neg  any   neg
2247  *
2248  * There is no special sign for "zero", because we can usually treat zero
2249  * as either non-negative or non-positive, whatever works out best.
2250  * However, if the row is "critical", meaning that pivoting is impossible
2251  * then we don't want to limp zero with the non-positive case, because
2252  * then we we would lose the solution for those values of the parameters
2253  * where the value of the row is zero.  Instead, we treat 0 as non-negative
2254  * ensuring a split if the row can attain both zero and negative values.
2255  * The same happens when the original constraint was one that could not
2256  * be satisfied with equality by any integer values of the parameters.
2257  * In this case, we normalize the constraint, but then a value of zero
2258  * for the normalized constraint is actually a positive value for the
2259  * original constraint, so again we need to treat zero as non-negative.
2260  * In both these cases, we have the following decision tree instead:
2261  *
2262  *      all non-negative                ->      pos
2263  *      all negative                    ->      neg
2264  *      both negative and non-negative  ->      all
2265  *
2266  *      samples        neg                             pos
2267  *      <0 ?                                        Y        N
2268  *                                                 any      pos
2269  *      >=0 ?        Y      N
2270  *                  any    neg
2271  */
2272 static enum isl_tab_row_sign row_sign(struct isl_tab *tab,
2273         struct isl_sol *sol, int row)
2274 {
2275         struct isl_vec *ineq = NULL;
2276         int res = isl_tab_row_unknown;
2277         int critical;
2278         int strict;
2279         int row2;
2280
2281         if (tab->row_sign[row] != isl_tab_row_unknown)
2282                 return tab->row_sign[row];
2283         if (is_obviously_nonneg(tab, row))
2284                 return isl_tab_row_pos;
2285         for (row2 = tab->n_redundant; row2 < tab->n_row; ++row2) {
2286                 if (tab->row_sign[row2] == isl_tab_row_unknown)
2287                         continue;
2288                 if (identical_parameter_line(tab, row, row2))
2289                         return tab->row_sign[row2];
2290         }
2291
2292         critical = is_critical(tab, row);
2293
2294         ineq = get_row_parameter_ineq(tab, row);
2295         if (!ineq)
2296                 goto error;
2297
2298         strict = is_strict(ineq);
2299
2300         res = sol->context->op->ineq_sign(sol->context, ineq->el,
2301                                           critical || strict);
2302
2303         if (res == isl_tab_row_unknown || res == isl_tab_row_pos) {
2304                 /* test for negative values */
2305                 int feasible;
2306                 isl_seq_neg(ineq->el, ineq->el, ineq->size);
2307                 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
2308
2309                 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
2310                 if (feasible < 0)
2311                         goto error;
2312                 if (!feasible)
2313                         res = isl_tab_row_pos;
2314                 else
2315                         res = (res == isl_tab_row_unknown) ? isl_tab_row_neg
2316                                                            : isl_tab_row_any;
2317                 if (res == isl_tab_row_neg) {
2318                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
2319                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
2320                 }
2321         }
2322
2323         if (res == isl_tab_row_neg) {
2324                 /* test for positive values */
2325                 int feasible;
2326                 if (!critical && !strict)
2327                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
2328
2329                 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
2330                 if (feasible < 0)
2331                         goto error;
2332                 if (feasible)
2333                         res = isl_tab_row_any;
2334         }
2335
2336         isl_vec_free(ineq);
2337         return res;
2338 error:
2339         isl_vec_free(ineq);
2340         return 0;
2341 }
2342
2343 static struct isl_sol *find_solutions(struct isl_sol *sol, struct isl_tab *tab);
2344
2345 /* Find solutions for values of the parameters that satisfy the given
2346  * inequality.
2347  *
2348  * We currently take a snapshot of the context tableau that is reset
2349  * when we return from this function, while we make a copy of the main
2350  * tableau, leaving the original main tableau untouched.
2351  * These are fairly arbitrary choices.  Making a copy also of the context
2352  * tableau would obviate the need to undo any changes made to it later,
2353  * while taking a snapshot of the main tableau could reduce memory usage.
2354  * If we were to switch to taking a snapshot of the main tableau,
2355  * we would have to keep in mind that we need to save the row signs
2356  * and that we need to do this before saving the current basis
2357  * such that the basis has been restore before we restore the row signs.
2358  */
2359 static struct isl_sol *find_in_pos(struct isl_sol *sol,
2360         struct isl_tab *tab, isl_int *ineq)
2361 {
2362         void *saved;
2363
2364         if (!sol->context)
2365                 goto error;
2366         saved = sol->context->op->save(sol->context);
2367
2368         tab = isl_tab_dup(tab);
2369         if (!tab)
2370                 goto error;
2371
2372         sol->context->op->add_ineq(sol->context, ineq, 0, 1);
2373
2374         sol = find_solutions(sol, tab);
2375
2376         sol->context->op->restore(sol->context, saved);
2377         return sol;
2378 error:
2379         sol_free(sol);
2380         return NULL;
2381 }
2382
2383 /* Record the absence of solutions for those values of the parameters
2384  * that do not satisfy the given inequality with equality.
2385  */
2386 static struct isl_sol *no_sol_in_strict(struct isl_sol *sol,
2387         struct isl_tab *tab, struct isl_vec *ineq)
2388 {
2389         int empty;
2390         void *saved;
2391
2392         if (!sol->context)
2393                 goto error;
2394         saved = sol->context->op->save(sol->context);
2395
2396         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
2397
2398         sol->context->op->add_ineq(sol->context, ineq->el, 1, 0);
2399         if (!sol->context)
2400                 goto error;
2401
2402         empty = tab->empty;
2403         tab->empty = 1;
2404         sol = sol->add(sol, tab);
2405         tab->empty = empty;
2406
2407         isl_int_add_ui(ineq->el[0], ineq->el[0], 1);
2408
2409         sol->context->op->restore(sol->context, saved);
2410         return sol;
2411 error:
2412         sol_free(sol);
2413         return NULL;
2414 }
2415
2416 /* Compute the lexicographic minimum of the set represented by the main
2417  * tableau "tab" within the context "sol->context_tab".
2418  * On entry the sample value of the main tableau is lexicographically
2419  * less than or equal to this lexicographic minimum.
2420  * Pivots are performed until a feasible point is found, which is then
2421  * necessarily equal to the minimum, or until the tableau is found to
2422  * be infeasible.  Some pivots may need to be performed for only some
2423  * feasible values of the context tableau.  If so, the context tableau
2424  * is split into a part where the pivot is needed and a part where it is not.
2425  *
2426  * Whenever we enter the main loop, the main tableau is such that no
2427  * "obvious" pivots need to be performed on it, where "obvious" means
2428  * that the given row can be seen to be negative without looking at
2429  * the context tableau.  In particular, for non-parametric problems,
2430  * no pivots need to be performed on the main tableau.
2431  * The caller of find_solutions is responsible for making this property
2432  * hold prior to the first iteration of the loop, while restore_lexmin
2433  * is called before every other iteration.
2434  *
2435  * Inside the main loop, we first examine the signs of the rows of
2436  * the main tableau within the context of the context tableau.
2437  * If we find a row that is always non-positive for all values of
2438  * the parameters satisfying the context tableau and negative for at
2439  * least one value of the parameters, we perform the appropriate pivot
2440  * and start over.  An exception is the case where no pivot can be
2441  * performed on the row.  In this case, we require that the sign of
2442  * the row is negative for all values of the parameters (rather than just
2443  * non-positive).  This special case is handled inside row_sign, which
2444  * will say that the row can have any sign if it determines that it can
2445  * attain both negative and zero values.
2446  *
2447  * If we can't find a row that always requires a pivot, but we can find
2448  * one or more rows that require a pivot for some values of the parameters
2449  * (i.e., the row can attain both positive and negative signs), then we split
2450  * the context tableau into two parts, one where we force the sign to be
2451  * non-negative and one where we force is to be negative.
2452  * The non-negative part is handled by a recursive call (through find_in_pos).
2453  * Upon returning from this call, we continue with the negative part and
2454  * perform the required pivot.
2455  *
2456  * If no such rows can be found, all rows are non-negative and we have
2457  * found a (rational) feasible point.  If we only wanted a rational point
2458  * then we are done.
2459  * Otherwise, we check if all values of the sample point of the tableau
2460  * are integral for the variables.  If so, we have found the minimal
2461  * integral point and we are done.
2462  * If the sample point is not integral, then we need to make a distinction
2463  * based on whether the constant term is non-integral or the coefficients
2464  * of the parameters.  Furthermore, in order to decide how to handle
2465  * the non-integrality, we also need to know whether the coefficients
2466  * of the other columns in the tableau are integral.  This leads
2467  * to the following table.  The first two rows do not correspond
2468  * to a non-integral sample point and are only mentioned for completeness.
2469  *
2470  *      constant        parameters      other
2471  *
2472  *      int             int             int     |
2473  *      int             int             rat     | -> no problem
2474  *
2475  *      rat             int             int       -> fail
2476  *
2477  *      rat             int             rat       -> cut
2478  *
2479  *      int             rat             rat     |
2480  *      rat             rat             rat     | -> parametric cut
2481  *
2482  *      int             rat             int     |
2483  *      rat             rat             int     | -> split context
2484  *
2485  * If the parametric constant is completely integral, then there is nothing
2486  * to be done.  If the constant term is non-integral, but all the other
2487  * coefficient are integral, then there is nothing that can be done
2488  * and the tableau has no integral solution.
2489  * If, on the other hand, one or more of the other columns have rational
2490  * coeffcients, but the parameter coefficients are all integral, then
2491  * we can perform a regular (non-parametric) cut.
2492  * Finally, if there is any parameter coefficient that is non-integral,
2493  * then we need to involve the context tableau.  There are two cases here.
2494  * If at least one other column has a rational coefficient, then we
2495  * can perform a parametric cut in the main tableau by adding a new
2496  * integer division in the context tableau.
2497  * If all other columns have integral coefficients, then we need to
2498  * enforce that the rational combination of parameters (c + \sum a_i y_i)/m
2499  * is always integral.  We do this by introducing an integer division
2500  * q = floor((c + \sum a_i y_i)/m) and stipulating that its argument should
2501  * always be integral in the context tableau, i.e., m q = c + \sum a_i y_i.
2502  * Since q is expressed in the tableau as
2503  *      c + \sum a_i y_i - m q >= 0
2504  *      -c - \sum a_i y_i + m q + m - 1 >= 0
2505  * it is sufficient to add the inequality
2506  *      -c - \sum a_i y_i + m q >= 0
2507  * In the part of the context where this inequality does not hold, the
2508  * main tableau is marked as being empty.
2509  */
2510 static struct isl_sol *find_solutions(struct isl_sol *sol, struct isl_tab *tab)
2511 {
2512         struct isl_context *context;
2513
2514         if (!tab || !sol)
2515                 goto error;
2516
2517         context = sol->context;
2518
2519         if (tab->empty)
2520                 goto done;
2521         if (context->op->is_empty(context))
2522                 goto done;
2523
2524         for (; tab && !tab->empty; tab = restore_lexmin(tab)) {
2525                 int flags;
2526                 int row;
2527                 int sgn;
2528                 int split = -1;
2529                 int n_split = 0;
2530
2531                 for (row = tab->n_redundant; row < tab->n_row; ++row) {
2532                         if (!isl_tab_var_from_row(tab, row)->is_nonneg)
2533                                 continue;
2534                         sgn = row_sign(tab, sol, row);
2535                         if (!sgn)
2536                                 goto error;
2537                         tab->row_sign[row] = sgn;
2538                         if (sgn == isl_tab_row_any)
2539                                 n_split++;
2540                         if (sgn == isl_tab_row_any && split == -1)
2541                                 split = row;
2542                         if (sgn == isl_tab_row_neg)
2543                                 break;
2544                 }
2545                 if (row < tab->n_row)
2546                         continue;
2547                 if (split != -1) {
2548                         struct isl_vec *ineq;
2549                         if (n_split != 1)
2550                                 split = context->op->best_split(context, tab);
2551                         if (split < 0)
2552                                 goto error;
2553                         ineq = get_row_parameter_ineq(tab, split);
2554                         if (!ineq)
2555                                 goto error;
2556                         is_strict(ineq);
2557                         for (row = tab->n_redundant; row < tab->n_row; ++row) {
2558                                 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
2559                                         continue;
2560                                 if (tab->row_sign[row] == isl_tab_row_any)
2561                                         tab->row_sign[row] = isl_tab_row_unknown;
2562                         }
2563                         tab->row_sign[split] = isl_tab_row_pos;
2564                         sol = find_in_pos(sol, tab, ineq->el);
2565                         tab->row_sign[split] = isl_tab_row_neg;
2566                         row = split;
2567                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
2568                         isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
2569                         context->op->add_ineq(context, ineq->el, 0, 1);
2570                         isl_vec_free(ineq);
2571                         if (!sol)
2572                                 goto error;
2573                         continue;
2574                 }
2575                 if (tab->rational)
2576                         break;
2577                 row = first_non_integer(tab, &flags);
2578                 if (row < 0)
2579                         break;
2580                 if (ISL_FL_ISSET(flags, I_PAR)) {
2581                         if (ISL_FL_ISSET(flags, I_VAR)) {
2582                                 tab = isl_tab_mark_empty(tab);
2583                                 break;
2584                         }
2585                         row = add_cut(tab, row);
2586                 } else if (ISL_FL_ISSET(flags, I_VAR)) {
2587                         struct isl_vec *div;
2588                         struct isl_vec *ineq;
2589                         int d;
2590                         div = get_row_split_div(tab, row);
2591                         if (!div)
2592                                 goto error;
2593                         d = context->op->get_div(context, tab, div);
2594                         isl_vec_free(div);
2595                         if (d < 0)
2596                                 goto error;
2597                         ineq = ineq_for_div(context->op->peek_basic_set(context), d);
2598                         sol = no_sol_in_strict(sol, tab, ineq);
2599                         isl_seq_neg(ineq->el, ineq->el, ineq->size);
2600                         context->op->add_ineq(context, ineq->el, 1, 1);
2601                         isl_vec_free(ineq);
2602                         if (!sol || !context->op->is_ok(context))
2603                                 goto error;
2604                         tab = set_row_cst_to_div(tab, row, d);
2605                 } else
2606                         row = add_parametric_cut(tab, row, context);
2607                 if (row < 0)
2608                         goto error;
2609         }
2610 done:
2611         sol = sol->add(sol, tab);
2612         isl_tab_free(tab);
2613         return sol;
2614 error:
2615         isl_tab_free(tab);
2616         sol_free(sol);
2617         return NULL;
2618 }
2619
2620 /* Compute the lexicographic minimum of the set represented by the main
2621  * tableau "tab" within the context "sol->context_tab".
2622  *
2623  * As a preprocessing step, we first transfer all the purely parametric
2624  * equalities from the main tableau to the context tableau, i.e.,
2625  * parameters that have been pivoted to a row.
2626  * These equalities are ignored by the main algorithm, because the
2627  * corresponding rows may not be marked as being non-negative.
2628  * In parts of the context where the added equality does not hold,
2629  * the main tableau is marked as being empty.
2630  */
2631 static struct isl_sol *find_solutions_main(struct isl_sol *sol,
2632         struct isl_tab *tab)
2633 {
2634         int row;
2635
2636         for (row = tab->n_redundant; row < tab->n_row; ++row) {
2637                 int p;
2638                 struct isl_vec *eq;
2639
2640                 if (tab->row_var[row] < 0)
2641                         continue;
2642                 if (tab->row_var[row] >= tab->n_param &&
2643                     tab->row_var[row] < tab->n_var - tab->n_div)
2644                         continue;
2645                 if (tab->row_var[row] < tab->n_param)
2646                         p = tab->row_var[row];
2647                 else
2648                         p = tab->row_var[row]
2649                                 + tab->n_param - (tab->n_var - tab->n_div);
2650
2651                 eq = isl_vec_alloc(tab->mat->ctx, 1+tab->n_param+tab->n_div);
2652                 get_row_parameter_line(tab, row, eq->el);
2653                 isl_int_neg(eq->el[1 + p], tab->mat->row[row][0]);
2654                 eq = isl_vec_normalize(eq);
2655
2656                 sol = no_sol_in_strict(sol, tab, eq);
2657
2658                 isl_seq_neg(eq->el, eq->el, eq->size);
2659                 sol = no_sol_in_strict(sol, tab, eq);
2660                 isl_seq_neg(eq->el, eq->el, eq->size);
2661
2662                 sol->context->op->add_eq(sol->context, eq->el, 1, 1);
2663
2664                 isl_vec_free(eq);
2665
2666                 isl_tab_mark_redundant(tab, row);
2667
2668                 if (sol->context->op->is_empty(sol->context))
2669                         break;
2670
2671                 row = tab->n_redundant - 1;
2672         }
2673
2674         return find_solutions(sol, tab);
2675 error:
2676         isl_tab_free(tab);
2677         sol_free(sol);
2678         return NULL;
2679 }
2680
2681 static struct isl_sol_map *sol_map_find_solutions(struct isl_sol_map *sol_map,
2682         struct isl_tab *tab)
2683 {
2684         return (struct isl_sol_map *)find_solutions_main(&sol_map->sol, tab);
2685 }
2686
2687 /* Check if integer division "div" of "dom" also occurs in "bmap".
2688  * If so, return its position within the divs.
2689  * If not, return -1.
2690  */
2691 static int find_context_div(struct isl_basic_map *bmap,
2692         struct isl_basic_set *dom, unsigned div)
2693 {
2694         int i;
2695         unsigned b_dim = isl_dim_total(bmap->dim);
2696         unsigned d_dim = isl_dim_total(dom->dim);
2697
2698         if (isl_int_is_zero(dom->div[div][0]))
2699                 return -1;
2700         if (isl_seq_first_non_zero(dom->div[div] + 2 + d_dim, dom->n_div) != -1)
2701                 return -1;
2702
2703         for (i = 0; i < bmap->n_div; ++i) {
2704                 if (isl_int_is_zero(bmap->div[i][0]))
2705                         continue;
2706                 if (isl_seq_first_non_zero(bmap->div[i] + 2 + d_dim,
2707                                            (b_dim - d_dim) + bmap->n_div) != -1)
2708                         continue;
2709                 if (isl_seq_eq(bmap->div[i], dom->div[div], 2 + d_dim))
2710                         return i;
2711         }
2712         return -1;
2713 }
2714
2715 /* The correspondence between the variables in the main tableau,
2716  * the context tableau, and the input map and domain is as follows.
2717  * The first n_param and the last n_div variables of the main tableau
2718  * form the variables of the context tableau.
2719  * In the basic map, these n_param variables correspond to the
2720  * parameters and the input dimensions.  In the domain, they correspond
2721  * to the parameters and the set dimensions.
2722  * The n_div variables correspond to the integer divisions in the domain.
2723  * To ensure that everything lines up, we may need to copy some of the
2724  * integer divisions of the domain to the map.  These have to be placed
2725  * in the same order as those in the context and they have to be placed
2726  * after any other integer divisions that the map may have.
2727  * This function performs the required reordering.
2728  */
2729 static struct isl_basic_map *align_context_divs(struct isl_basic_map *bmap,
2730         struct isl_basic_set *dom)
2731 {
2732         int i;
2733         int common = 0;
2734         int other;
2735
2736         for (i = 0; i < dom->n_div; ++i)
2737                 if (find_context_div(bmap, dom, i) != -1)
2738                         common++;
2739         other = bmap->n_div - common;
2740         if (dom->n_div - common > 0) {
2741                 bmap = isl_basic_map_extend_dim(bmap, isl_dim_copy(bmap->dim),
2742                                 dom->n_div - common, 0, 0);
2743                 if (!bmap)
2744                         return NULL;
2745         }
2746         for (i = 0; i < dom->n_div; ++i) {
2747                 int pos = find_context_div(bmap, dom, i);
2748                 if (pos < 0) {
2749                         pos = isl_basic_map_alloc_div(bmap);
2750                         if (pos < 0)
2751                                 goto error;
2752                         isl_int_set_si(bmap->div[pos][0], 0);
2753                 }
2754                 if (pos != other + i)
2755                         isl_basic_map_swap_div(bmap, pos, other + i);
2756         }
2757         return bmap;
2758 error:
2759         isl_basic_map_free(bmap);
2760         return NULL;
2761 }
2762
2763 /* Compute the lexicographic minimum (or maximum if "max" is set)
2764  * of "bmap" over the domain "dom" and return the result as a map.
2765  * If "empty" is not NULL, then *empty is assigned a set that
2766  * contains those parts of the domain where there is no solution.
2767  * If "bmap" is marked as rational (ISL_BASIC_MAP_RATIONAL),
2768  * then we compute the rational optimum.  Otherwise, we compute
2769  * the integral optimum.
2770  *
2771  * We perform some preprocessing.  As the PILP solver does not
2772  * handle implicit equalities very well, we first make sure all
2773  * the equalities are explicitly available.
2774  * We also make sure the divs in the domain are properly order,
2775  * because they will be added one by one in the given order
2776  * during the construction of the solution map.
2777  */
2778 struct isl_map *isl_tab_basic_map_partial_lexopt(
2779                 struct isl_basic_map *bmap, struct isl_basic_set *dom,
2780                 struct isl_set **empty, int max)
2781 {
2782         struct isl_tab *tab;
2783         struct isl_map *result = NULL;
2784         struct isl_sol_map *sol_map = NULL;
2785         struct isl_context *context;
2786
2787         if (empty)
2788                 *empty = NULL;
2789         if (!bmap || !dom)
2790                 goto error;
2791
2792         isl_assert(bmap->ctx,
2793             isl_basic_map_compatible_domain(bmap, dom), goto error);
2794
2795         bmap = isl_basic_map_detect_equalities(bmap);
2796
2797         if (dom->n_div) {
2798                 dom = isl_basic_set_order_divs(dom);
2799                 bmap = align_context_divs(bmap, dom);
2800         }
2801         sol_map = sol_map_init(bmap, dom, !!empty, max);
2802         if (!sol_map)
2803                 goto error;
2804
2805         context = sol_map->sol.context;
2806         if (isl_basic_set_fast_is_empty(context->op->peek_basic_set(context)))
2807                 /* nothing */;
2808         else if (isl_basic_map_fast_is_empty(bmap))
2809                 sol_map = add_empty(sol_map);
2810         else {
2811                 tab = tab_for_lexmin(bmap,
2812                                     context->op->peek_basic_set(context), 1, max);
2813                 tab = context->op->detect_nonnegative_parameters(context, tab);
2814                 sol_map = sol_map_find_solutions(sol_map, tab);
2815                 if (!sol_map)
2816                         goto error;
2817         }
2818
2819         result = isl_map_copy(sol_map->map);
2820         if (empty)
2821                 *empty = isl_set_copy(sol_map->empty);
2822         sol_map_free(sol_map);
2823         isl_basic_map_free(bmap);
2824         return result;
2825 error:
2826         sol_map_free(sol_map);
2827         isl_basic_map_free(bmap);
2828         return NULL;
2829 }
2830
2831 struct isl_sol_for {
2832         struct isl_sol  sol;
2833         int             (*fn)(__isl_take isl_basic_set *dom,
2834                                 __isl_take isl_mat *map, void *user);
2835         void            *user;
2836         int             max;
2837 };
2838
2839 static void sol_for_free(struct isl_sol_for *sol_for)
2840 {
2841         if (sol_for->sol.context)
2842                 sol_for->sol.context->op->free(sol_for->sol.context);
2843         free(sol_for);
2844 }
2845
2846 static void sol_for_free_wrap(struct isl_sol *sol)
2847 {
2848         sol_for_free((struct isl_sol_for *)sol);
2849 }
2850
2851 /* Add the solution identified by the tableau and the context tableau.
2852  *
2853  * See documentation of sol_map_add for more details.
2854  *
2855  * Instead of constructing a basic map, this function calls a user
2856  * defined function with the current context as a basic set and
2857  * an affine matrix reprenting the relation between the input and output.
2858  * The number of rows in this matrix is equal to one plus the number
2859  * of output variables.  The number of columns is equal to one plus
2860  * the total dimension of the context, i.e., the number of parameters,
2861  * input variables and divs.  Since some of the columns in the matrix
2862  * may refer to the divs, the basic set is not simplified.
2863  * (Simplification may reorder or remove divs.)
2864  */
2865 static struct isl_sol_for *sol_for_add(struct isl_sol_for *sol,
2866         struct isl_tab *tab)
2867 {
2868         struct isl_basic_set *bset;
2869         struct isl_mat *mat = NULL;
2870         unsigned n_out;
2871         unsigned off;
2872         int row, i;
2873
2874         if (!sol || !tab)
2875                 goto error;
2876
2877         if (tab->empty)
2878                 return sol;
2879
2880         off = 2 + tab->M;
2881
2882         n_out = tab->n_var - tab->n_param - tab->n_div;
2883         mat = isl_mat_alloc(tab->mat->ctx, 1 + n_out, 1 + tab->n_param + tab->n_div);
2884         if (!mat)
2885                 goto error;
2886
2887         isl_seq_clr(mat->row[0] + 1, mat->n_col - 1);
2888         isl_int_set_si(mat->row[0][0], 1);
2889         for (row = 0; row < n_out; ++row) {
2890                 int i = tab->n_param + row;
2891                 int r, j;
2892
2893                 isl_seq_clr(mat->row[1 + row], mat->n_col);
2894                 if (!tab->var[i].is_row)
2895                         continue;
2896
2897                 r = tab->var[i].index;
2898                 /* no unbounded */
2899                 if (tab->M)
2900                         isl_assert(mat->ctx, isl_int_eq(tab->mat->row[r][2],
2901                                                         tab->mat->row[r][0]),
2902                                     goto error);
2903                 isl_int_set(mat->row[1 + row][0], tab->mat->row[r][1]);
2904                 for (j = 0; j < tab->n_param; ++j) {
2905                         int col;
2906                         if (tab->var[j].is_row)
2907                                 continue;
2908                         col = tab->var[j].index;
2909                         isl_int_set(mat->row[1 + row][1 + j],
2910                                     tab->mat->row[r][off + col]);
2911                 }
2912                 for (j = 0; j < tab->n_div; ++j) {
2913                         int col;
2914                         if (tab->var[tab->n_var - tab->n_div+j].is_row)
2915                                 continue;
2916                         col = tab->var[tab->n_var - tab->n_div+j].index;
2917                         isl_int_set(mat->row[1 + row][1 + tab->n_param + j],
2918                                     tab->mat->row[r][off + col]);
2919                 }
2920                 if (!isl_int_is_one(tab->mat->row[r][0]))
2921                         isl_seq_scale_down(mat->row[1 + row], mat->row[1 + row],
2922                                             tab->mat->row[r][0], mat->n_col);
2923                 if (sol->max)
2924                         isl_seq_neg(mat->row[1 + row], mat->row[1 + row],
2925                                     mat->n_col);
2926         }
2927
2928         bset = sol->sol.context->op->peek_basic_set(sol->sol.context);
2929         bset = isl_basic_set_dup(bset);
2930         bset = isl_basic_set_finalize(bset);
2931
2932         if (sol->fn(bset, isl_mat_copy(mat), sol->user) < 0)
2933                 goto error;
2934
2935         isl_mat_free(mat);
2936         return sol;
2937 error:
2938         isl_mat_free(mat);
2939         sol_free(&sol->sol);
2940         return NULL;
2941 }
2942
2943 static struct isl_sol *sol_for_add_wrap(struct isl_sol *sol,
2944         struct isl_tab *tab)
2945 {
2946         return (struct isl_sol *)sol_for_add((struct isl_sol_for *)sol, tab);
2947 }
2948
2949 static struct isl_sol_for *sol_for_init(struct isl_basic_map *bmap, int max,
2950         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
2951                   void *user),
2952         void *user)
2953 {
2954         struct isl_sol_for *sol_for = NULL;
2955         struct isl_dim *dom_dim;
2956         struct isl_basic_set *dom = NULL;
2957
2958         sol_for = isl_calloc_type(bset->ctx, struct isl_sol_for);
2959         if (!sol_for)
2960                 goto error;
2961
2962         dom_dim = isl_dim_domain(isl_dim_copy(bmap->dim));
2963         dom = isl_basic_set_universe(dom_dim);
2964
2965         sol_for->fn = fn;
2966         sol_for->user = user;
2967         sol_for->max = max;
2968         sol_for->sol.add = &sol_for_add_wrap;
2969         sol_for->sol.free = &sol_for_free_wrap;
2970
2971         sol_for->sol.context = isl_context_lex_alloc(dom);
2972         if (!sol_for->sol.context)
2973                 goto error;
2974
2975         isl_basic_set_free(dom);
2976         return sol_for;
2977 error:
2978         isl_basic_set_free(dom);
2979         sol_for_free(sol_for);
2980         return NULL;
2981 }
2982
2983 static struct isl_sol_for *sol_for_find_solutions(struct isl_sol_for *sol_for,
2984         struct isl_tab *tab)
2985 {
2986         return (struct isl_sol_for *)find_solutions_main(&sol_for->sol, tab);
2987 }
2988
2989 int isl_basic_map_foreach_lexopt(__isl_keep isl_basic_map *bmap, int max,
2990         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
2991                   void *user),
2992         void *user)
2993 {
2994         struct isl_sol_for *sol_for = NULL;
2995
2996         bmap = isl_basic_map_copy(bmap);
2997         if (!bmap)
2998                 return -1;
2999
3000         bmap = isl_basic_map_detect_equalities(bmap);
3001         sol_for = sol_for_init(bmap, max, fn, user);
3002
3003         if (isl_basic_map_fast_is_empty(bmap))
3004                 /* nothing */;
3005         else {
3006                 struct isl_tab *tab;
3007                 struct isl_context *context = sol_for->sol.context;
3008                 tab = tab_for_lexmin(bmap,
3009                                 context->op->peek_basic_set(context), 1, max);
3010                 tab = context->op->detect_nonnegative_parameters(context, tab);
3011                 sol_for = sol_for_find_solutions(sol_for, tab);
3012                 if (!sol_for)
3013                         goto error;
3014         }
3015
3016         sol_for_free(sol_for);
3017         isl_basic_map_free(bmap);
3018         return 0;
3019 error:
3020         sol_for_free(sol_for);
3021         isl_basic_map_free(bmap);
3022         return -1;
3023 }
3024
3025 int isl_basic_map_foreach_lexmin(__isl_keep isl_basic_map *bmap,
3026         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
3027                   void *user),
3028         void *user)
3029 {
3030         return isl_basic_map_foreach_lexopt(bmap, 0, fn, user);
3031 }
3032
3033 int isl_basic_map_foreach_lexmax(__isl_keep isl_basic_map *bmap,
3034         int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_mat *map,
3035                   void *user),
3036         void *user)
3037 {
3038         return isl_basic_map_foreach_lexopt(bmap, 1, fn, user);
3039 }