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