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