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