isl_tab_pip.c: isl_context_alloc: add memory management annotation
[isl.git] / isl_tab_pip.c
blob5e041f45ff968a8295ef79be8cdf1852daced155
1 /*
2 * Copyright 2008-2009 Katholieke Universiteit Leuven
3 * Copyright 2010 INRIA Saclay
4 * Copyright 2016 Sven Verdoolaege
6 * Use of this software is governed by the MIT license
8 * Written by Sven Verdoolaege, K.U.Leuven, Departement
9 * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
10 * and INRIA Saclay - Ile-de-France, Parc Club Orsay Universite,
11 * ZAC des vignes, 4 rue Jacques Monod, 91893 Orsay, France
14 #include <isl_ctx_private.h>
15 #include "isl_map_private.h"
16 #include <isl_seq.h>
17 #include "isl_tab.h"
18 #include "isl_sample.h"
19 #include <isl_mat_private.h>
20 #include <isl_vec_private.h>
21 #include <isl_aff_private.h>
22 #include <isl_constraint_private.h>
23 #include <isl_options_private.h>
24 #include <isl_config.h>
27 * The implementation of parametric integer linear programming in this file
28 * was inspired by the paper "Parametric Integer Programming" and the
29 * report "Solving systems of affine (in)equalities" by Paul Feautrier
30 * (and others).
32 * The strategy used for obtaining a feasible solution is different
33 * from the one used in isl_tab.c. In particular, in isl_tab.c,
34 * upon finding a constraint that is not yet satisfied, we pivot
35 * in a row that increases the constant term of the row holding the
36 * constraint, making sure the sample solution remains feasible
37 * for all the constraints it already satisfied.
38 * Here, we always pivot in the row holding the constraint,
39 * choosing a column that induces the lexicographically smallest
40 * increment to the sample solution.
42 * By starting out from a sample value that is lexicographically
43 * smaller than any integer point in the problem space, the first
44 * feasible integer sample point we find will also be the lexicographically
45 * smallest. If all variables can be assumed to be non-negative,
46 * then the initial sample value may be chosen equal to zero.
47 * However, we will not make this assumption. Instead, we apply
48 * the "big parameter" trick. Any variable x is then not directly
49 * used in the tableau, but instead it is represented by another
50 * variable x' = M + x, where M is an arbitrarily large (positive)
51 * value. x' is therefore always non-negative, whatever the value of x.
52 * Taking as initial sample value x' = 0 corresponds to x = -M,
53 * which is always smaller than any possible value of x.
55 * The big parameter trick is used in the main tableau and
56 * also in the context tableau if isl_context_lex is used.
57 * In this case, each tableaus has its own big parameter.
58 * Before doing any real work, we check if all the parameters
59 * happen to be non-negative. If so, we drop the column corresponding
60 * to M from the initial context tableau.
61 * If isl_context_gbr is used, then the big parameter trick is only
62 * used in the main tableau.
65 struct isl_context;
66 struct isl_context_op {
67 /* detect nonnegative parameters in context and mark them in tab */
68 struct isl_tab *(*detect_nonnegative_parameters)(
69 struct isl_context *context, struct isl_tab *tab);
70 /* return temporary reference to basic set representation of context */
71 struct isl_basic_set *(*peek_basic_set)(struct isl_context *context);
72 /* return temporary reference to tableau representation of context */
73 struct isl_tab *(*peek_tab)(struct isl_context *context);
74 /* add equality; check is 1 if eq may not be valid;
75 * update is 1 if we may want to call ineq_sign on context later.
77 void (*add_eq)(struct isl_context *context, isl_int *eq,
78 int check, int update);
79 /* add inequality; check is 1 if ineq may not be valid;
80 * update is 1 if we may want to call ineq_sign on context later.
82 void (*add_ineq)(struct isl_context *context, isl_int *ineq,
83 int check, int update);
84 /* check sign of ineq based on previous information.
85 * strict is 1 if saturation should be treated as a positive sign.
87 enum isl_tab_row_sign (*ineq_sign)(struct isl_context *context,
88 isl_int *ineq, int strict);
89 /* check if inequality maintains feasibility */
90 int (*test_ineq)(struct isl_context *context, isl_int *ineq);
91 /* return index of a div that corresponds to "div" */
92 int (*get_div)(struct isl_context *context, struct isl_tab *tab,
93 struct isl_vec *div);
94 /* add div "div" to context and return non-negativity */
95 int (*add_div)(struct isl_context *context, struct isl_vec *div);
96 int (*detect_equalities)(struct isl_context *context,
97 struct isl_tab *tab);
98 /* return row index of "best" split */
99 int (*best_split)(struct isl_context *context, struct isl_tab *tab);
100 /* check if context has already been determined to be empty */
101 int (*is_empty)(struct isl_context *context);
102 /* check if context is still usable */
103 int (*is_ok)(struct isl_context *context);
104 /* save a copy/snapshot of context */
105 void *(*save)(struct isl_context *context);
106 /* restore saved context */
107 void (*restore)(struct isl_context *context, void *);
108 /* discard saved context */
109 void (*discard)(void *);
110 /* invalidate context */
111 void (*invalidate)(struct isl_context *context);
112 /* free context */
113 void (*free)(struct isl_context *context);
116 struct isl_context {
117 struct isl_context_op *op;
120 struct isl_context_lex {
121 struct isl_context context;
122 struct isl_tab *tab;
125 /* A stack (linked list) of solutions of subtrees of the search space.
127 * "M" describes the solution in terms of the dimensions of "dom".
128 * The number of columns of "M" is one more than the total number
129 * of dimensions of "dom".
131 * If "M" is NULL, then there is no solution on "dom".
133 struct isl_partial_sol {
134 int level;
135 struct isl_basic_set *dom;
136 struct isl_mat *M;
138 struct isl_partial_sol *next;
141 struct isl_sol;
142 struct isl_sol_callback {
143 struct isl_tab_callback callback;
144 struct isl_sol *sol;
147 /* isl_sol is an interface for constructing a solution to
148 * a parametric integer linear programming problem.
149 * Every time the algorithm reaches a state where a solution
150 * can be read off from the tableau (including cases where the tableau
151 * is empty), the function "add" is called on the isl_sol passed
152 * to find_solutions_main.
154 * The context tableau is owned by isl_sol and is updated incrementally.
156 * There are currently two implementations of this interface,
157 * isl_sol_map, which simply collects the solutions in an isl_map
158 * and (optionally) the parts of the context where there is no solution
159 * in an isl_set, and
160 * isl_sol_for, which calls a user-defined function for each part of
161 * the solution.
163 struct isl_sol {
164 int error;
165 int rational;
166 int level;
167 int max;
168 int n_out;
169 struct isl_context *context;
170 struct isl_partial_sol *partial;
171 void (*add)(struct isl_sol *sol,
172 struct isl_basic_set *dom, struct isl_mat *M);
173 void (*add_empty)(struct isl_sol *sol, struct isl_basic_set *bset);
174 void (*free)(struct isl_sol *sol);
175 struct isl_sol_callback dec_level;
178 static void sol_free(struct isl_sol *sol)
180 struct isl_partial_sol *partial, *next;
181 if (!sol)
182 return;
183 for (partial = sol->partial; partial; partial = next) {
184 next = partial->next;
185 isl_basic_set_free(partial->dom);
186 isl_mat_free(partial->M);
187 free(partial);
189 sol->free(sol);
192 /* Push a partial solution represented by a domain and mapping M
193 * onto the stack of partial solutions.
195 static void sol_push_sol(struct isl_sol *sol,
196 struct isl_basic_set *dom, struct isl_mat *M)
198 struct isl_partial_sol *partial;
200 if (sol->error || !dom)
201 goto error;
203 partial = isl_alloc_type(dom->ctx, struct isl_partial_sol);
204 if (!partial)
205 goto error;
207 partial->level = sol->level;
208 partial->dom = dom;
209 partial->M = M;
210 partial->next = sol->partial;
212 sol->partial = partial;
214 return;
215 error:
216 isl_basic_set_free(dom);
217 isl_mat_free(M);
218 sol->error = 1;
221 /* Pop one partial solution from the partial solution stack and
222 * pass it on to sol->add or sol->add_empty.
224 static void sol_pop_one(struct isl_sol *sol)
226 struct isl_partial_sol *partial;
228 partial = sol->partial;
229 sol->partial = partial->next;
231 if (partial->M)
232 sol->add(sol, partial->dom, partial->M);
233 else
234 sol->add_empty(sol, partial->dom);
235 free(partial);
238 /* Return a fresh copy of the domain represented by the context tableau.
240 static struct isl_basic_set *sol_domain(struct isl_sol *sol)
242 struct isl_basic_set *bset;
244 if (sol->error)
245 return NULL;
247 bset = isl_basic_set_dup(sol->context->op->peek_basic_set(sol->context));
248 bset = isl_basic_set_update_from_tab(bset,
249 sol->context->op->peek_tab(sol->context));
251 return bset;
254 /* Check whether two partial solutions have the same mapping, where n_div
255 * is the number of divs that the two partial solutions have in common.
257 static int same_solution(struct isl_partial_sol *s1, struct isl_partial_sol *s2,
258 unsigned n_div)
260 int i;
261 unsigned dim;
263 if (!s1->M != !s2->M)
264 return 0;
265 if (!s1->M)
266 return 1;
268 dim = isl_basic_set_total_dim(s1->dom) - s1->dom->n_div;
270 for (i = 0; i < s1->M->n_row; ++i) {
271 if (isl_seq_first_non_zero(s1->M->row[i]+1+dim+n_div,
272 s1->M->n_col-1-dim-n_div) != -1)
273 return 0;
274 if (isl_seq_first_non_zero(s2->M->row[i]+1+dim+n_div,
275 s2->M->n_col-1-dim-n_div) != -1)
276 return 0;
277 if (!isl_seq_eq(s1->M->row[i], s2->M->row[i], 1+dim+n_div))
278 return 0;
280 return 1;
283 /* Pop all solutions from the partial solution stack that were pushed onto
284 * the stack at levels that are deeper than the current level.
285 * If the two topmost elements on the stack have the same level
286 * and represent the same solution, then their domains are combined.
287 * This combined domain is the same as the current context domain
288 * as sol_pop is called each time we move back to a higher level.
289 * If the outer level (0) has been reached, then all partial solutions
290 * at the current level are also popped off.
292 static void sol_pop(struct isl_sol *sol)
294 struct isl_partial_sol *partial;
295 unsigned n_div;
297 if (sol->error)
298 return;
300 partial = sol->partial;
301 if (!partial)
302 return;
304 if (partial->level == 0 && sol->level == 0) {
305 for (partial = sol->partial; partial; partial = sol->partial)
306 sol_pop_one(sol);
307 return;
310 if (partial->level <= sol->level)
311 return;
313 if (partial->next && partial->next->level == partial->level) {
314 n_div = isl_basic_set_dim(
315 sol->context->op->peek_basic_set(sol->context),
316 isl_dim_div);
318 if (!same_solution(partial, partial->next, n_div)) {
319 sol_pop_one(sol);
320 sol_pop_one(sol);
321 } else {
322 struct isl_basic_set *bset;
323 isl_mat *M;
324 unsigned n;
326 n = isl_basic_set_dim(partial->next->dom, isl_dim_div);
327 n -= n_div;
328 bset = sol_domain(sol);
329 isl_basic_set_free(partial->next->dom);
330 partial->next->dom = bset;
331 M = partial->next->M;
332 if (M) {
333 M = isl_mat_drop_cols(M, M->n_col - n, n);
334 partial->next->M = M;
335 if (!M)
336 goto error;
338 partial->next->level = sol->level;
340 if (!bset)
341 goto error;
343 sol->partial = partial->next;
344 isl_basic_set_free(partial->dom);
345 isl_mat_free(partial->M);
346 free(partial);
348 } else
349 sol_pop_one(sol);
351 if (sol->level == 0) {
352 for (partial = sol->partial; partial; partial = sol->partial)
353 sol_pop_one(sol);
354 return;
357 if (0)
358 error: sol->error = 1;
361 static void sol_dec_level(struct isl_sol *sol)
363 if (sol->error)
364 return;
366 sol->level--;
368 sol_pop(sol);
371 static int sol_dec_level_wrap(struct isl_tab_callback *cb)
373 struct isl_sol_callback *callback = (struct isl_sol_callback *)cb;
375 sol_dec_level(callback->sol);
377 return callback->sol->error ? -1 : 0;
380 /* Move down to next level and push callback onto context tableau
381 * to decrease the level again when it gets rolled back across
382 * the current state. That is, dec_level will be called with
383 * the context tableau in the same state as it is when inc_level
384 * is called.
386 static void sol_inc_level(struct isl_sol *sol)
388 struct isl_tab *tab;
390 if (sol->error)
391 return;
393 sol->level++;
394 tab = sol->context->op->peek_tab(sol->context);
395 if (isl_tab_push_callback(tab, &sol->dec_level.callback) < 0)
396 sol->error = 1;
399 static void scale_rows(struct isl_mat *mat, isl_int m, int n_row)
401 int i;
403 if (isl_int_is_one(m))
404 return;
406 for (i = 0; i < n_row; ++i)
407 isl_seq_scale(mat->row[i], mat->row[i], m, mat->n_col);
410 /* Add the solution identified by the tableau and the context tableau.
412 * The layout of the variables is as follows.
413 * tab->n_var is equal to the total number of variables in the input
414 * map (including divs that were copied from the context)
415 * + the number of extra divs constructed
416 * Of these, the first tab->n_param and the last tab->n_div variables
417 * correspond to the variables in the context, i.e.,
418 * tab->n_param + tab->n_div = context_tab->n_var
419 * tab->n_param is equal to the number of parameters and input
420 * dimensions in the input map
421 * tab->n_div is equal to the number of divs in the context
423 * If there is no solution, then call add_empty with a basic set
424 * that corresponds to the context tableau. (If add_empty is NULL,
425 * then do nothing).
427 * If there is a solution, then first construct a matrix that maps
428 * all dimensions of the context to the output variables, i.e.,
429 * the output dimensions in the input map.
430 * The divs in the input map (if any) that do not correspond to any
431 * div in the context do not appear in the solution.
432 * The algorithm will make sure that they have an integer value,
433 * but these values themselves are of no interest.
434 * We have to be careful not to drop or rearrange any divs in the
435 * context because that would change the meaning of the matrix.
437 * To extract the value of the output variables, it should be noted
438 * that we always use a big parameter M in the main tableau and so
439 * the variable stored in this tableau is not an output variable x itself, but
440 * x' = M + x (in case of minimization)
441 * or
442 * x' = M - x (in case of maximization)
443 * If x' appears in a column, then its optimal value is zero,
444 * which means that the optimal value of x is an unbounded number
445 * (-M for minimization and M for maximization).
446 * We currently assume that the output dimensions in the original map
447 * are bounded, so this cannot occur.
448 * Similarly, when x' appears in a row, then the coefficient of M in that
449 * row is necessarily 1.
450 * If the row in the tableau represents
451 * d x' = c + d M + e(y)
452 * then, in case of minimization, the corresponding row in the matrix
453 * will be
454 * a c + a e(y)
455 * with a d = m, the (updated) common denominator of the matrix.
456 * In case of maximization, the row will be
457 * -a c - a e(y)
459 static void sol_add(struct isl_sol *sol, struct isl_tab *tab)
461 struct isl_basic_set *bset = NULL;
462 struct isl_mat *mat = NULL;
463 unsigned off;
464 int row;
465 isl_int m;
467 if (sol->error || !tab)
468 goto error;
470 if (tab->empty && !sol->add_empty)
471 return;
472 if (sol->context->op->is_empty(sol->context))
473 return;
475 bset = sol_domain(sol);
477 if (tab->empty) {
478 sol_push_sol(sol, bset, NULL);
479 return;
482 off = 2 + tab->M;
484 mat = isl_mat_alloc(tab->mat->ctx, 1 + sol->n_out,
485 1 + tab->n_param + tab->n_div);
486 if (!mat)
487 goto error;
489 isl_int_init(m);
491 isl_seq_clr(mat->row[0] + 1, mat->n_col - 1);
492 isl_int_set_si(mat->row[0][0], 1);
493 for (row = 0; row < sol->n_out; ++row) {
494 int i = tab->n_param + row;
495 int r, j;
497 isl_seq_clr(mat->row[1 + row], mat->n_col);
498 if (!tab->var[i].is_row) {
499 if (tab->M)
500 isl_die(mat->ctx, isl_error_invalid,
501 "unbounded optimum", goto error2);
502 continue;
505 r = tab->var[i].index;
506 if (tab->M &&
507 isl_int_ne(tab->mat->row[r][2], tab->mat->row[r][0]))
508 isl_die(mat->ctx, isl_error_invalid,
509 "unbounded optimum", goto error2);
510 isl_int_gcd(m, mat->row[0][0], tab->mat->row[r][0]);
511 isl_int_divexact(m, tab->mat->row[r][0], m);
512 scale_rows(mat, m, 1 + row);
513 isl_int_divexact(m, mat->row[0][0], tab->mat->row[r][0]);
514 isl_int_mul(mat->row[1 + row][0], m, tab->mat->row[r][1]);
515 for (j = 0; j < tab->n_param; ++j) {
516 int col;
517 if (tab->var[j].is_row)
518 continue;
519 col = tab->var[j].index;
520 isl_int_mul(mat->row[1 + row][1 + j], m,
521 tab->mat->row[r][off + col]);
523 for (j = 0; j < tab->n_div; ++j) {
524 int col;
525 if (tab->var[tab->n_var - tab->n_div+j].is_row)
526 continue;
527 col = tab->var[tab->n_var - tab->n_div+j].index;
528 isl_int_mul(mat->row[1 + row][1 + tab->n_param + j], m,
529 tab->mat->row[r][off + col]);
531 if (sol->max)
532 isl_seq_neg(mat->row[1 + row], mat->row[1 + row],
533 mat->n_col);
536 isl_int_clear(m);
538 sol_push_sol(sol, bset, mat);
539 return;
540 error2:
541 isl_int_clear(m);
542 error:
543 isl_basic_set_free(bset);
544 isl_mat_free(mat);
545 sol->error = 1;
548 struct isl_sol_map {
549 struct isl_sol sol;
550 struct isl_map *map;
551 struct isl_set *empty;
554 static void sol_map_free(struct isl_sol_map *sol_map)
556 if (!sol_map)
557 return;
558 if (sol_map->sol.context)
559 sol_map->sol.context->op->free(sol_map->sol.context);
560 isl_map_free(sol_map->map);
561 isl_set_free(sol_map->empty);
562 free(sol_map);
565 static void sol_map_free_wrap(struct isl_sol *sol)
567 sol_map_free((struct isl_sol_map *)sol);
570 /* This function is called for parts of the context where there is
571 * no solution, with "bset" corresponding to the context tableau.
572 * Simply add the basic set to the set "empty".
574 static void sol_map_add_empty(struct isl_sol_map *sol,
575 struct isl_basic_set *bset)
577 if (!bset || !sol->empty)
578 goto error;
580 sol->empty = isl_set_grow(sol->empty, 1);
581 bset = isl_basic_set_simplify(bset);
582 bset = isl_basic_set_finalize(bset);
583 sol->empty = isl_set_add_basic_set(sol->empty, isl_basic_set_copy(bset));
584 if (!sol->empty)
585 goto error;
586 isl_basic_set_free(bset);
587 return;
588 error:
589 isl_basic_set_free(bset);
590 sol->sol.error = 1;
593 static void sol_map_add_empty_wrap(struct isl_sol *sol,
594 struct isl_basic_set *bset)
596 sol_map_add_empty((struct isl_sol_map *)sol, bset);
599 /* Given a basic map "dom" that represents the context and an affine
600 * matrix "M" that maps the dimensions of the context to the
601 * output variables, construct a basic map with the same parameters
602 * and divs as the context, the dimensions of the context as input
603 * dimensions and a number of output dimensions that is equal to
604 * the number of output dimensions in the input map.
606 * The constraints and divs of the context are simply copied
607 * from "dom". For each row
608 * x = c + e(y)
609 * an equality
610 * c + e(y) - d x = 0
611 * is added, with d the common denominator of M.
613 static void sol_map_add(struct isl_sol_map *sol,
614 struct isl_basic_set *dom, struct isl_mat *M)
616 int i;
617 struct isl_basic_map *bmap = NULL;
618 unsigned n_eq;
619 unsigned n_ineq;
620 unsigned nparam;
621 unsigned total;
622 unsigned n_div;
623 unsigned n_out;
625 if (sol->sol.error || !dom || !M)
626 goto error;
628 n_out = sol->sol.n_out;
629 n_eq = dom->n_eq + n_out;
630 n_ineq = dom->n_ineq;
631 n_div = dom->n_div;
632 nparam = isl_basic_set_total_dim(dom) - n_div;
633 total = isl_map_dim(sol->map, isl_dim_all);
634 bmap = isl_basic_map_alloc_space(isl_map_get_space(sol->map),
635 n_div, n_eq, 2 * n_div + n_ineq);
636 if (!bmap)
637 goto error;
638 if (sol->sol.rational)
639 ISL_F_SET(bmap, ISL_BASIC_MAP_RATIONAL);
640 for (i = 0; i < dom->n_div; ++i) {
641 int k = isl_basic_map_alloc_div(bmap);
642 if (k < 0)
643 goto error;
644 isl_seq_cpy(bmap->div[k], dom->div[i], 1 + 1 + nparam);
645 isl_seq_clr(bmap->div[k] + 1 + 1 + nparam, total - nparam);
646 isl_seq_cpy(bmap->div[k] + 1 + 1 + total,
647 dom->div[i] + 1 + 1 + nparam, i);
649 for (i = 0; i < dom->n_eq; ++i) {
650 int k = isl_basic_map_alloc_equality(bmap);
651 if (k < 0)
652 goto error;
653 isl_seq_cpy(bmap->eq[k], dom->eq[i], 1 + nparam);
654 isl_seq_clr(bmap->eq[k] + 1 + nparam, total - nparam);
655 isl_seq_cpy(bmap->eq[k] + 1 + total,
656 dom->eq[i] + 1 + nparam, n_div);
658 for (i = 0; i < dom->n_ineq; ++i) {
659 int k = isl_basic_map_alloc_inequality(bmap);
660 if (k < 0)
661 goto error;
662 isl_seq_cpy(bmap->ineq[k], dom->ineq[i], 1 + nparam);
663 isl_seq_clr(bmap->ineq[k] + 1 + nparam, total - nparam);
664 isl_seq_cpy(bmap->ineq[k] + 1 + total,
665 dom->ineq[i] + 1 + nparam, n_div);
667 for (i = 0; i < M->n_row - 1; ++i) {
668 int k = isl_basic_map_alloc_equality(bmap);
669 if (k < 0)
670 goto error;
671 isl_seq_cpy(bmap->eq[k], M->row[1 + i], 1 + nparam);
672 isl_seq_clr(bmap->eq[k] + 1 + nparam, n_out);
673 isl_int_neg(bmap->eq[k][1 + nparam + i], M->row[0][0]);
674 isl_seq_cpy(bmap->eq[k] + 1 + nparam + n_out,
675 M->row[1 + i] + 1 + nparam, n_div);
677 bmap = isl_basic_map_simplify(bmap);
678 bmap = isl_basic_map_finalize(bmap);
679 sol->map = isl_map_grow(sol->map, 1);
680 sol->map = isl_map_add_basic_map(sol->map, bmap);
681 isl_basic_set_free(dom);
682 isl_mat_free(M);
683 if (!sol->map)
684 sol->sol.error = 1;
685 return;
686 error:
687 isl_basic_set_free(dom);
688 isl_mat_free(M);
689 isl_basic_map_free(bmap);
690 sol->sol.error = 1;
693 static void sol_map_add_wrap(struct isl_sol *sol,
694 struct isl_basic_set *dom, struct isl_mat *M)
696 sol_map_add((struct isl_sol_map *)sol, dom, M);
700 /* Store the "parametric constant" of row "row" of tableau "tab" in "line",
701 * i.e., the constant term and the coefficients of all variables that
702 * appear in the context tableau.
703 * Note that the coefficient of the big parameter M is NOT copied.
704 * The context tableau may not have a big parameter and even when it
705 * does, it is a different big parameter.
707 static void get_row_parameter_line(struct isl_tab *tab, int row, isl_int *line)
709 int i;
710 unsigned off = 2 + tab->M;
712 isl_int_set(line[0], tab->mat->row[row][1]);
713 for (i = 0; i < tab->n_param; ++i) {
714 if (tab->var[i].is_row)
715 isl_int_set_si(line[1 + i], 0);
716 else {
717 int col = tab->var[i].index;
718 isl_int_set(line[1 + i], tab->mat->row[row][off + col]);
721 for (i = 0; i < tab->n_div; ++i) {
722 if (tab->var[tab->n_var - tab->n_div + i].is_row)
723 isl_int_set_si(line[1 + tab->n_param + i], 0);
724 else {
725 int col = tab->var[tab->n_var - tab->n_div + i].index;
726 isl_int_set(line[1 + tab->n_param + i],
727 tab->mat->row[row][off + col]);
732 /* Check if rows "row1" and "row2" have identical "parametric constants",
733 * as explained above.
734 * In this case, we also insist that the coefficients of the big parameter
735 * be the same as the values of the constants will only be the same
736 * if these coefficients are also the same.
738 static int identical_parameter_line(struct isl_tab *tab, int row1, int row2)
740 int i;
741 unsigned off = 2 + tab->M;
743 if (isl_int_ne(tab->mat->row[row1][1], tab->mat->row[row2][1]))
744 return 0;
746 if (tab->M && isl_int_ne(tab->mat->row[row1][2],
747 tab->mat->row[row2][2]))
748 return 0;
750 for (i = 0; i < tab->n_param + tab->n_div; ++i) {
751 int pos = i < tab->n_param ? i :
752 tab->n_var - tab->n_div + i - tab->n_param;
753 int col;
755 if (tab->var[pos].is_row)
756 continue;
757 col = tab->var[pos].index;
758 if (isl_int_ne(tab->mat->row[row1][off + col],
759 tab->mat->row[row2][off + col]))
760 return 0;
762 return 1;
765 /* Return an inequality that expresses that the "parametric constant"
766 * should be non-negative.
767 * This function is only called when the coefficient of the big parameter
768 * is equal to zero.
770 static struct isl_vec *get_row_parameter_ineq(struct isl_tab *tab, int row)
772 struct isl_vec *ineq;
774 ineq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_param + tab->n_div);
775 if (!ineq)
776 return NULL;
778 get_row_parameter_line(tab, row, ineq->el);
779 if (ineq)
780 ineq = isl_vec_normalize(ineq);
782 return ineq;
785 /* Normalize a div expression of the form
787 * [(g*f(x) + c)/(g * m)]
789 * with c the constant term and f(x) the remaining coefficients, to
791 * [(f(x) + [c/g])/m]
793 static void normalize_div(__isl_keep isl_vec *div)
795 isl_ctx *ctx = isl_vec_get_ctx(div);
796 int len = div->size - 2;
798 isl_seq_gcd(div->el + 2, len, &ctx->normalize_gcd);
799 isl_int_gcd(ctx->normalize_gcd, ctx->normalize_gcd, div->el[0]);
801 if (isl_int_is_one(ctx->normalize_gcd))
802 return;
804 isl_int_divexact(div->el[0], div->el[0], ctx->normalize_gcd);
805 isl_int_fdiv_q(div->el[1], div->el[1], ctx->normalize_gcd);
806 isl_seq_scale_down(div->el + 2, div->el + 2, ctx->normalize_gcd, len);
809 /* Return a integer division for use in a parametric cut based on the given row.
810 * In particular, let the parametric constant of the row be
812 * \sum_i a_i y_i
814 * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
815 * The div returned is equal to
817 * floor(\sum_i {-a_i} y_i) = floor((\sum_i (-a_i mod d) y_i)/d)
819 static struct isl_vec *get_row_parameter_div(struct isl_tab *tab, int row)
821 struct isl_vec *div;
823 div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
824 if (!div)
825 return NULL;
827 isl_int_set(div->el[0], tab->mat->row[row][0]);
828 get_row_parameter_line(tab, row, div->el + 1);
829 isl_seq_neg(div->el + 1, div->el + 1, div->size - 1);
830 normalize_div(div);
831 isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
833 return div;
836 /* Return a integer division for use in transferring an integrality constraint
837 * to the context.
838 * In particular, let the parametric constant of the row be
840 * \sum_i a_i y_i
842 * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
843 * The the returned div is equal to
845 * floor(\sum_i {a_i} y_i) = floor((\sum_i (a_i mod d) y_i)/d)
847 static struct isl_vec *get_row_split_div(struct isl_tab *tab, int row)
849 struct isl_vec *div;
851 div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
852 if (!div)
853 return NULL;
855 isl_int_set(div->el[0], tab->mat->row[row][0]);
856 get_row_parameter_line(tab, row, div->el + 1);
857 normalize_div(div);
858 isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
860 return div;
863 /* Construct and return an inequality that expresses an upper bound
864 * on the given div.
865 * In particular, if the div is given by
867 * d = floor(e/m)
869 * then the inequality expresses
871 * m d <= e
873 static struct isl_vec *ineq_for_div(struct isl_basic_set *bset, unsigned div)
875 unsigned total;
876 unsigned div_pos;
877 struct isl_vec *ineq;
879 if (!bset)
880 return NULL;
882 total = isl_basic_set_total_dim(bset);
883 div_pos = 1 + total - bset->n_div + div;
885 ineq = isl_vec_alloc(bset->ctx, 1 + total);
886 if (!ineq)
887 return NULL;
889 isl_seq_cpy(ineq->el, bset->div[div] + 1, 1 + total);
890 isl_int_neg(ineq->el[div_pos], bset->div[div][0]);
891 return ineq;
894 /* Given a row in the tableau and a div that was created
895 * using get_row_split_div and that has been constrained to equality, i.e.,
897 * d = floor(\sum_i {a_i} y_i) = \sum_i {a_i} y_i
899 * replace the expression "\sum_i {a_i} y_i" in the row by d,
900 * i.e., we subtract "\sum_i {a_i} y_i" and add 1 d.
901 * The coefficients of the non-parameters in the tableau have been
902 * verified to be integral. We can therefore simply replace coefficient b
903 * by floor(b). For the coefficients of the parameters we have
904 * floor(a_i) = a_i - {a_i}, while for the other coefficients, we have
905 * floor(b) = b.
907 static struct isl_tab *set_row_cst_to_div(struct isl_tab *tab, int row, int div)
909 isl_seq_fdiv_q(tab->mat->row[row] + 1, tab->mat->row[row] + 1,
910 tab->mat->row[row][0], 1 + tab->M + tab->n_col);
912 isl_int_set_si(tab->mat->row[row][0], 1);
914 if (tab->var[tab->n_var - tab->n_div + div].is_row) {
915 int drow = tab->var[tab->n_var - tab->n_div + div].index;
917 isl_assert(tab->mat->ctx,
918 isl_int_is_one(tab->mat->row[drow][0]), goto error);
919 isl_seq_combine(tab->mat->row[row] + 1,
920 tab->mat->ctx->one, tab->mat->row[row] + 1,
921 tab->mat->ctx->one, tab->mat->row[drow] + 1,
922 1 + tab->M + tab->n_col);
923 } else {
924 int dcol = tab->var[tab->n_var - tab->n_div + div].index;
926 isl_int_add_ui(tab->mat->row[row][2 + tab->M + dcol],
927 tab->mat->row[row][2 + tab->M + dcol], 1);
930 return tab;
931 error:
932 isl_tab_free(tab);
933 return NULL;
936 /* Check if the (parametric) constant of the given row is obviously
937 * negative, meaning that we don't need to consult the context tableau.
938 * If there is a big parameter and its coefficient is non-zero,
939 * then this coefficient determines the outcome.
940 * Otherwise, we check whether the constant is negative and
941 * all non-zero coefficients of parameters are negative and
942 * belong to non-negative parameters.
944 static int is_obviously_neg(struct isl_tab *tab, int row)
946 int i;
947 int col;
948 unsigned off = 2 + tab->M;
950 if (tab->M) {
951 if (isl_int_is_pos(tab->mat->row[row][2]))
952 return 0;
953 if (isl_int_is_neg(tab->mat->row[row][2]))
954 return 1;
957 if (isl_int_is_nonneg(tab->mat->row[row][1]))
958 return 0;
959 for (i = 0; i < tab->n_param; ++i) {
960 /* Eliminated parameter */
961 if (tab->var[i].is_row)
962 continue;
963 col = tab->var[i].index;
964 if (isl_int_is_zero(tab->mat->row[row][off + col]))
965 continue;
966 if (!tab->var[i].is_nonneg)
967 return 0;
968 if (isl_int_is_pos(tab->mat->row[row][off + col]))
969 return 0;
971 for (i = 0; i < tab->n_div; ++i) {
972 if (tab->var[tab->n_var - tab->n_div + i].is_row)
973 continue;
974 col = tab->var[tab->n_var - tab->n_div + i].index;
975 if (isl_int_is_zero(tab->mat->row[row][off + col]))
976 continue;
977 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
978 return 0;
979 if (isl_int_is_pos(tab->mat->row[row][off + col]))
980 return 0;
982 return 1;
985 /* Check if the (parametric) constant of the given row is obviously
986 * non-negative, meaning that we don't need to consult the context tableau.
987 * If there is a big parameter and its coefficient is non-zero,
988 * then this coefficient determines the outcome.
989 * Otherwise, we check whether the constant is non-negative and
990 * all non-zero coefficients of parameters are positive and
991 * belong to non-negative parameters.
993 static int is_obviously_nonneg(struct isl_tab *tab, int row)
995 int i;
996 int col;
997 unsigned off = 2 + tab->M;
999 if (tab->M) {
1000 if (isl_int_is_pos(tab->mat->row[row][2]))
1001 return 1;
1002 if (isl_int_is_neg(tab->mat->row[row][2]))
1003 return 0;
1006 if (isl_int_is_neg(tab->mat->row[row][1]))
1007 return 0;
1008 for (i = 0; i < tab->n_param; ++i) {
1009 /* Eliminated parameter */
1010 if (tab->var[i].is_row)
1011 continue;
1012 col = tab->var[i].index;
1013 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1014 continue;
1015 if (!tab->var[i].is_nonneg)
1016 return 0;
1017 if (isl_int_is_neg(tab->mat->row[row][off + col]))
1018 return 0;
1020 for (i = 0; i < tab->n_div; ++i) {
1021 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1022 continue;
1023 col = tab->var[tab->n_var - tab->n_div + i].index;
1024 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1025 continue;
1026 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
1027 return 0;
1028 if (isl_int_is_neg(tab->mat->row[row][off + col]))
1029 return 0;
1031 return 1;
1034 /* Given a row r and two columns, return the column that would
1035 * lead to the lexicographically smallest increment in the sample
1036 * solution when leaving the basis in favor of the row.
1037 * Pivoting with column c will increment the sample value by a non-negative
1038 * constant times a_{V,c}/a_{r,c}, with a_{V,c} the elements of column c
1039 * corresponding to the non-parametric variables.
1040 * If variable v appears in a column c_v, the a_{v,c} = 1 iff c = c_v,
1041 * with all other entries in this virtual row equal to zero.
1042 * If variable v appears in a row, then a_{v,c} is the element in column c
1043 * of that row.
1045 * Let v be the first variable with a_{v,c1}/a_{r,c1} != a_{v,c2}/a_{r,c2}.
1046 * Then if a_{v,c1}/a_{r,c1} < a_{v,c2}/a_{r,c2}, i.e.,
1047 * a_{v,c2} a_{r,c1} - a_{v,c1} a_{r,c2} > 0, c1 results in the minimal
1048 * increment. Otherwise, it's c2.
1050 static int lexmin_col_pair(struct isl_tab *tab,
1051 int row, int col1, int col2, isl_int tmp)
1053 int i;
1054 isl_int *tr;
1056 tr = tab->mat->row[row] + 2 + tab->M;
1058 for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
1059 int s1, s2;
1060 isl_int *r;
1062 if (!tab->var[i].is_row) {
1063 if (tab->var[i].index == col1)
1064 return col2;
1065 if (tab->var[i].index == col2)
1066 return col1;
1067 continue;
1070 if (tab->var[i].index == row)
1071 continue;
1073 r = tab->mat->row[tab->var[i].index] + 2 + tab->M;
1074 s1 = isl_int_sgn(r[col1]);
1075 s2 = isl_int_sgn(r[col2]);
1076 if (s1 == 0 && s2 == 0)
1077 continue;
1078 if (s1 < s2)
1079 return col1;
1080 if (s2 < s1)
1081 return col2;
1083 isl_int_mul(tmp, r[col2], tr[col1]);
1084 isl_int_submul(tmp, r[col1], tr[col2]);
1085 if (isl_int_is_pos(tmp))
1086 return col1;
1087 if (isl_int_is_neg(tmp))
1088 return col2;
1090 return -1;
1093 /* Given a row in the tableau, find and return the column that would
1094 * result in the lexicographically smallest, but positive, increment
1095 * in the sample point.
1096 * If there is no such column, then return tab->n_col.
1097 * If anything goes wrong, return -1.
1099 static int lexmin_pivot_col(struct isl_tab *tab, int row)
1101 int j;
1102 int col = tab->n_col;
1103 isl_int *tr;
1104 isl_int tmp;
1106 tr = tab->mat->row[row] + 2 + tab->M;
1108 isl_int_init(tmp);
1110 for (j = tab->n_dead; j < tab->n_col; ++j) {
1111 if (tab->col_var[j] >= 0 &&
1112 (tab->col_var[j] < tab->n_param ||
1113 tab->col_var[j] >= tab->n_var - tab->n_div))
1114 continue;
1116 if (!isl_int_is_pos(tr[j]))
1117 continue;
1119 if (col == tab->n_col)
1120 col = j;
1121 else
1122 col = lexmin_col_pair(tab, row, col, j, tmp);
1123 isl_assert(tab->mat->ctx, col >= 0, goto error);
1126 isl_int_clear(tmp);
1127 return col;
1128 error:
1129 isl_int_clear(tmp);
1130 return -1;
1133 /* Return the first known violated constraint, i.e., a non-negative
1134 * constraint that currently has an either obviously negative value
1135 * or a previously determined to be negative value.
1137 * If any constraint has a negative coefficient for the big parameter,
1138 * if any, then we return one of these first.
1140 static int first_neg(struct isl_tab *tab)
1142 int row;
1144 if (tab->M)
1145 for (row = tab->n_redundant; row < tab->n_row; ++row) {
1146 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1147 continue;
1148 if (!isl_int_is_neg(tab->mat->row[row][2]))
1149 continue;
1150 if (tab->row_sign)
1151 tab->row_sign[row] = isl_tab_row_neg;
1152 return row;
1154 for (row = tab->n_redundant; row < tab->n_row; ++row) {
1155 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1156 continue;
1157 if (tab->row_sign) {
1158 if (tab->row_sign[row] == 0 &&
1159 is_obviously_neg(tab, row))
1160 tab->row_sign[row] = isl_tab_row_neg;
1161 if (tab->row_sign[row] != isl_tab_row_neg)
1162 continue;
1163 } else if (!is_obviously_neg(tab, row))
1164 continue;
1165 return row;
1167 return -1;
1170 /* Check whether the invariant that all columns are lexico-positive
1171 * is satisfied. This function is not called from the current code
1172 * but is useful during debugging.
1174 static void check_lexpos(struct isl_tab *tab) __attribute__ ((unused));
1175 static void check_lexpos(struct isl_tab *tab)
1177 unsigned off = 2 + tab->M;
1178 int col;
1179 int var;
1180 int row;
1182 for (col = tab->n_dead; col < tab->n_col; ++col) {
1183 if (tab->col_var[col] >= 0 &&
1184 (tab->col_var[col] < tab->n_param ||
1185 tab->col_var[col] >= tab->n_var - tab->n_div))
1186 continue;
1187 for (var = tab->n_param; var < tab->n_var - tab->n_div; ++var) {
1188 if (!tab->var[var].is_row) {
1189 if (tab->var[var].index == col)
1190 break;
1191 else
1192 continue;
1194 row = tab->var[var].index;
1195 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1196 continue;
1197 if (isl_int_is_pos(tab->mat->row[row][off + col]))
1198 break;
1199 fprintf(stderr, "lexneg column %d (row %d)\n",
1200 col, row);
1202 if (var >= tab->n_var - tab->n_div)
1203 fprintf(stderr, "zero column %d\n", col);
1207 /* Report to the caller that the given constraint is part of an encountered
1208 * conflict.
1210 static int report_conflicting_constraint(struct isl_tab *tab, int con)
1212 return tab->conflict(con, tab->conflict_user);
1215 /* Given a conflicting row in the tableau, report all constraints
1216 * involved in the row to the caller. That is, the row itself
1217 * (if it represents a constraint) and all constraint columns with
1218 * non-zero (and therefore negative) coefficients.
1220 static int report_conflict(struct isl_tab *tab, int row)
1222 int j;
1223 isl_int *tr;
1225 if (!tab->conflict)
1226 return 0;
1228 if (tab->row_var[row] < 0 &&
1229 report_conflicting_constraint(tab, ~tab->row_var[row]) < 0)
1230 return -1;
1232 tr = tab->mat->row[row] + 2 + tab->M;
1234 for (j = tab->n_dead; j < tab->n_col; ++j) {
1235 if (tab->col_var[j] >= 0 &&
1236 (tab->col_var[j] < tab->n_param ||
1237 tab->col_var[j] >= tab->n_var - tab->n_div))
1238 continue;
1240 if (!isl_int_is_neg(tr[j]))
1241 continue;
1243 if (tab->col_var[j] < 0 &&
1244 report_conflicting_constraint(tab, ~tab->col_var[j]) < 0)
1245 return -1;
1248 return 0;
1251 /* Resolve all known or obviously violated constraints through pivoting.
1252 * In particular, as long as we can find any violated constraint, we
1253 * look for a pivoting column that would result in the lexicographically
1254 * smallest increment in the sample point. If there is no such column
1255 * then the tableau is infeasible.
1257 static int restore_lexmin(struct isl_tab *tab) WARN_UNUSED;
1258 static int restore_lexmin(struct isl_tab *tab)
1260 int row, col;
1262 if (!tab)
1263 return -1;
1264 if (tab->empty)
1265 return 0;
1266 while ((row = first_neg(tab)) != -1) {
1267 col = lexmin_pivot_col(tab, row);
1268 if (col >= tab->n_col) {
1269 if (report_conflict(tab, row) < 0)
1270 return -1;
1271 if (isl_tab_mark_empty(tab) < 0)
1272 return -1;
1273 return 0;
1275 if (col < 0)
1276 return -1;
1277 if (isl_tab_pivot(tab, row, col) < 0)
1278 return -1;
1280 return 0;
1283 /* Given a row that represents an equality, look for an appropriate
1284 * pivoting column.
1285 * In particular, if there are any non-zero coefficients among
1286 * the non-parameter variables, then we take the last of these
1287 * variables. Eliminating this variable in terms of the other
1288 * variables and/or parameters does not influence the property
1289 * that all column in the initial tableau are lexicographically
1290 * positive. The row corresponding to the eliminated variable
1291 * will only have non-zero entries below the diagonal of the
1292 * initial tableau. That is, we transform
1294 * I I
1295 * 1 into a
1296 * I I
1298 * If there is no such non-parameter variable, then we are dealing with
1299 * pure parameter equality and we pick any parameter with coefficient 1 or -1
1300 * for elimination. This will ensure that the eliminated parameter
1301 * always has an integer value whenever all the other parameters are integral.
1302 * If there is no such parameter then we return -1.
1304 static int last_var_col_or_int_par_col(struct isl_tab *tab, int row)
1306 unsigned off = 2 + tab->M;
1307 int i;
1309 for (i = tab->n_var - tab->n_div - 1; i >= 0 && i >= tab->n_param; --i) {
1310 int col;
1311 if (tab->var[i].is_row)
1312 continue;
1313 col = tab->var[i].index;
1314 if (col <= tab->n_dead)
1315 continue;
1316 if (!isl_int_is_zero(tab->mat->row[row][off + col]))
1317 return col;
1319 for (i = tab->n_dead; i < tab->n_col; ++i) {
1320 if (isl_int_is_one(tab->mat->row[row][off + i]))
1321 return i;
1322 if (isl_int_is_negone(tab->mat->row[row][off + i]))
1323 return i;
1325 return -1;
1328 /* Add an equality that is known to be valid to the tableau.
1329 * We first check if we can eliminate a variable or a parameter.
1330 * If not, we add the equality as two inequalities.
1331 * In this case, the equality was a pure parameter equality and there
1332 * is no need to resolve any constraint violations.
1334 * This function assumes that at least two more rows and at least
1335 * two more elements in the constraint array are available in the tableau.
1337 static struct isl_tab *add_lexmin_valid_eq(struct isl_tab *tab, isl_int *eq)
1339 int i;
1340 int r;
1342 if (!tab)
1343 return NULL;
1344 r = isl_tab_add_row(tab, eq);
1345 if (r < 0)
1346 goto error;
1348 r = tab->con[r].index;
1349 i = last_var_col_or_int_par_col(tab, r);
1350 if (i < 0) {
1351 tab->con[r].is_nonneg = 1;
1352 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1353 goto error;
1354 isl_seq_neg(eq, eq, 1 + tab->n_var);
1355 r = isl_tab_add_row(tab, eq);
1356 if (r < 0)
1357 goto error;
1358 tab->con[r].is_nonneg = 1;
1359 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1360 goto error;
1361 } else {
1362 if (isl_tab_pivot(tab, r, i) < 0)
1363 goto error;
1364 if (isl_tab_kill_col(tab, i) < 0)
1365 goto error;
1366 tab->n_eq++;
1369 return tab;
1370 error:
1371 isl_tab_free(tab);
1372 return NULL;
1375 /* Check if the given row is a pure constant.
1377 static int is_constant(struct isl_tab *tab, int row)
1379 unsigned off = 2 + tab->M;
1381 return isl_seq_first_non_zero(tab->mat->row[row] + off + tab->n_dead,
1382 tab->n_col - tab->n_dead) == -1;
1385 /* Add an equality that may or may not be valid to the tableau.
1386 * If the resulting row is a pure constant, then it must be zero.
1387 * Otherwise, the resulting tableau is empty.
1389 * If the row is not a pure constant, then we add two inequalities,
1390 * each time checking that they can be satisfied.
1391 * In the end we try to use one of the two constraints to eliminate
1392 * a column.
1394 * This function assumes that at least two more rows and at least
1395 * two more elements in the constraint array are available in the tableau.
1397 static int add_lexmin_eq(struct isl_tab *tab, isl_int *eq) WARN_UNUSED;
1398 static int add_lexmin_eq(struct isl_tab *tab, isl_int *eq)
1400 int r1, r2;
1401 int row;
1402 struct isl_tab_undo *snap;
1404 if (!tab)
1405 return -1;
1406 snap = isl_tab_snap(tab);
1407 r1 = isl_tab_add_row(tab, eq);
1408 if (r1 < 0)
1409 return -1;
1410 tab->con[r1].is_nonneg = 1;
1411 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r1]) < 0)
1412 return -1;
1414 row = tab->con[r1].index;
1415 if (is_constant(tab, row)) {
1416 if (!isl_int_is_zero(tab->mat->row[row][1]) ||
1417 (tab->M && !isl_int_is_zero(tab->mat->row[row][2]))) {
1418 if (isl_tab_mark_empty(tab) < 0)
1419 return -1;
1420 return 0;
1422 if (isl_tab_rollback(tab, snap) < 0)
1423 return -1;
1424 return 0;
1427 if (restore_lexmin(tab) < 0)
1428 return -1;
1429 if (tab->empty)
1430 return 0;
1432 isl_seq_neg(eq, eq, 1 + tab->n_var);
1434 r2 = isl_tab_add_row(tab, eq);
1435 if (r2 < 0)
1436 return -1;
1437 tab->con[r2].is_nonneg = 1;
1438 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r2]) < 0)
1439 return -1;
1441 if (restore_lexmin(tab) < 0)
1442 return -1;
1443 if (tab->empty)
1444 return 0;
1446 if (!tab->con[r1].is_row) {
1447 if (isl_tab_kill_col(tab, tab->con[r1].index) < 0)
1448 return -1;
1449 } else if (!tab->con[r2].is_row) {
1450 if (isl_tab_kill_col(tab, tab->con[r2].index) < 0)
1451 return -1;
1454 if (tab->bmap) {
1455 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1456 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1457 return -1;
1458 isl_seq_neg(eq, eq, 1 + tab->n_var);
1459 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1460 isl_seq_neg(eq, eq, 1 + tab->n_var);
1461 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1462 return -1;
1463 if (!tab->bmap)
1464 return -1;
1467 return 0;
1470 /* Add an inequality to the tableau, resolving violations using
1471 * restore_lexmin.
1473 * This function assumes that at least one more row and at least
1474 * one more element in the constraint array are available in the tableau.
1476 static struct isl_tab *add_lexmin_ineq(struct isl_tab *tab, isl_int *ineq)
1478 int r;
1480 if (!tab)
1481 return NULL;
1482 if (tab->bmap) {
1483 tab->bmap = isl_basic_map_add_ineq(tab->bmap, ineq);
1484 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1485 goto error;
1486 if (!tab->bmap)
1487 goto error;
1489 r = isl_tab_add_row(tab, ineq);
1490 if (r < 0)
1491 goto error;
1492 tab->con[r].is_nonneg = 1;
1493 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1494 goto error;
1495 if (isl_tab_row_is_redundant(tab, tab->con[r].index)) {
1496 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1497 goto error;
1498 return tab;
1501 if (restore_lexmin(tab) < 0)
1502 goto error;
1503 if (!tab->empty && tab->con[r].is_row &&
1504 isl_tab_row_is_redundant(tab, tab->con[r].index))
1505 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1506 goto error;
1507 return tab;
1508 error:
1509 isl_tab_free(tab);
1510 return NULL;
1513 /* Check if the coefficients of the parameters are all integral.
1515 static int integer_parameter(struct isl_tab *tab, int row)
1517 int i;
1518 int col;
1519 unsigned off = 2 + tab->M;
1521 for (i = 0; i < tab->n_param; ++i) {
1522 /* Eliminated parameter */
1523 if (tab->var[i].is_row)
1524 continue;
1525 col = tab->var[i].index;
1526 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1527 tab->mat->row[row][0]))
1528 return 0;
1530 for (i = 0; i < tab->n_div; ++i) {
1531 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1532 continue;
1533 col = tab->var[tab->n_var - tab->n_div + i].index;
1534 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1535 tab->mat->row[row][0]))
1536 return 0;
1538 return 1;
1541 /* Check if the coefficients of the non-parameter variables are all integral.
1543 static int integer_variable(struct isl_tab *tab, int row)
1545 int i;
1546 unsigned off = 2 + tab->M;
1548 for (i = tab->n_dead; i < tab->n_col; ++i) {
1549 if (tab->col_var[i] >= 0 &&
1550 (tab->col_var[i] < tab->n_param ||
1551 tab->col_var[i] >= tab->n_var - tab->n_div))
1552 continue;
1553 if (!isl_int_is_divisible_by(tab->mat->row[row][off + i],
1554 tab->mat->row[row][0]))
1555 return 0;
1557 return 1;
1560 /* Check if the constant term is integral.
1562 static int integer_constant(struct isl_tab *tab, int row)
1564 return isl_int_is_divisible_by(tab->mat->row[row][1],
1565 tab->mat->row[row][0]);
1568 #define I_CST 1 << 0
1569 #define I_PAR 1 << 1
1570 #define I_VAR 1 << 2
1572 /* Check for next (non-parameter) variable after "var" (first if var == -1)
1573 * that is non-integer and therefore requires a cut and return
1574 * the index of the variable.
1575 * For parametric tableaus, there are three parts in a row,
1576 * the constant, the coefficients of the parameters and the rest.
1577 * For each part, we check whether the coefficients in that part
1578 * are all integral and if so, set the corresponding flag in *f.
1579 * If the constant and the parameter part are integral, then the
1580 * current sample value is integral and no cut is required
1581 * (irrespective of whether the variable part is integral).
1583 static int next_non_integer_var(struct isl_tab *tab, int var, int *f)
1585 var = var < 0 ? tab->n_param : var + 1;
1587 for (; var < tab->n_var - tab->n_div; ++var) {
1588 int flags = 0;
1589 int row;
1590 if (!tab->var[var].is_row)
1591 continue;
1592 row = tab->var[var].index;
1593 if (integer_constant(tab, row))
1594 ISL_FL_SET(flags, I_CST);
1595 if (integer_parameter(tab, row))
1596 ISL_FL_SET(flags, I_PAR);
1597 if (ISL_FL_ISSET(flags, I_CST) && ISL_FL_ISSET(flags, I_PAR))
1598 continue;
1599 if (integer_variable(tab, row))
1600 ISL_FL_SET(flags, I_VAR);
1601 *f = flags;
1602 return var;
1604 return -1;
1607 /* Check for first (non-parameter) variable that is non-integer and
1608 * therefore requires a cut and return the corresponding row.
1609 * For parametric tableaus, there are three parts in a row,
1610 * the constant, the coefficients of the parameters and the rest.
1611 * For each part, we check whether the coefficients in that part
1612 * are all integral and if so, set the corresponding flag in *f.
1613 * If the constant and the parameter part are integral, then the
1614 * current sample value is integral and no cut is required
1615 * (irrespective of whether the variable part is integral).
1617 static int first_non_integer_row(struct isl_tab *tab, int *f)
1619 int var = next_non_integer_var(tab, -1, f);
1621 return var < 0 ? -1 : tab->var[var].index;
1624 /* Add a (non-parametric) cut to cut away the non-integral sample
1625 * value of the given row.
1627 * If the row is given by
1629 * m r = f + \sum_i a_i y_i
1631 * then the cut is
1633 * c = - {-f/m} + \sum_i {a_i/m} y_i >= 0
1635 * The big parameter, if any, is ignored, since it is assumed to be big
1636 * enough to be divisible by any integer.
1637 * If the tableau is actually a parametric tableau, then this function
1638 * is only called when all coefficients of the parameters are integral.
1639 * The cut therefore has zero coefficients for the parameters.
1641 * The current value is known to be negative, so row_sign, if it
1642 * exists, is set accordingly.
1644 * Return the row of the cut or -1.
1646 static int add_cut(struct isl_tab *tab, int row)
1648 int i;
1649 int r;
1650 isl_int *r_row;
1651 unsigned off = 2 + tab->M;
1653 if (isl_tab_extend_cons(tab, 1) < 0)
1654 return -1;
1655 r = isl_tab_allocate_con(tab);
1656 if (r < 0)
1657 return -1;
1659 r_row = tab->mat->row[tab->con[r].index];
1660 isl_int_set(r_row[0], tab->mat->row[row][0]);
1661 isl_int_neg(r_row[1], tab->mat->row[row][1]);
1662 isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1663 isl_int_neg(r_row[1], r_row[1]);
1664 if (tab->M)
1665 isl_int_set_si(r_row[2], 0);
1666 for (i = 0; i < tab->n_col; ++i)
1667 isl_int_fdiv_r(r_row[off + i],
1668 tab->mat->row[row][off + i], tab->mat->row[row][0]);
1670 tab->con[r].is_nonneg = 1;
1671 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1672 return -1;
1673 if (tab->row_sign)
1674 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1676 return tab->con[r].index;
1679 #define CUT_ALL 1
1680 #define CUT_ONE 0
1682 /* Given a non-parametric tableau, add cuts until an integer
1683 * sample point is obtained or until the tableau is determined
1684 * to be integer infeasible.
1685 * As long as there is any non-integer value in the sample point,
1686 * we add appropriate cuts, if possible, for each of these
1687 * non-integer values and then resolve the violated
1688 * cut constraints using restore_lexmin.
1689 * If one of the corresponding rows is equal to an integral
1690 * combination of variables/constraints plus a non-integral constant,
1691 * then there is no way to obtain an integer point and we return
1692 * a tableau that is marked empty.
1693 * The parameter cutting_strategy controls the strategy used when adding cuts
1694 * to remove non-integer points. CUT_ALL adds all possible cuts
1695 * before continuing the search. CUT_ONE adds only one cut at a time.
1697 static struct isl_tab *cut_to_integer_lexmin(struct isl_tab *tab,
1698 int cutting_strategy)
1700 int var;
1701 int row;
1702 int flags;
1704 if (!tab)
1705 return NULL;
1706 if (tab->empty)
1707 return tab;
1709 while ((var = next_non_integer_var(tab, -1, &flags)) != -1) {
1710 do {
1711 if (ISL_FL_ISSET(flags, I_VAR)) {
1712 if (isl_tab_mark_empty(tab) < 0)
1713 goto error;
1714 return tab;
1716 row = tab->var[var].index;
1717 row = add_cut(tab, row);
1718 if (row < 0)
1719 goto error;
1720 if (cutting_strategy == CUT_ONE)
1721 break;
1722 } while ((var = next_non_integer_var(tab, var, &flags)) != -1);
1723 if (restore_lexmin(tab) < 0)
1724 goto error;
1725 if (tab->empty)
1726 break;
1728 return tab;
1729 error:
1730 isl_tab_free(tab);
1731 return NULL;
1734 /* Check whether all the currently active samples also satisfy the inequality
1735 * "ineq" (treated as an equality if eq is set).
1736 * Remove those samples that do not.
1738 static struct isl_tab *check_samples(struct isl_tab *tab, isl_int *ineq, int eq)
1740 int i;
1741 isl_int v;
1743 if (!tab)
1744 return NULL;
1746 isl_assert(tab->mat->ctx, tab->bmap, goto error);
1747 isl_assert(tab->mat->ctx, tab->samples, goto error);
1748 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, goto error);
1750 isl_int_init(v);
1751 for (i = tab->n_outside; i < tab->n_sample; ++i) {
1752 int sgn;
1753 isl_seq_inner_product(ineq, tab->samples->row[i],
1754 1 + tab->n_var, &v);
1755 sgn = isl_int_sgn(v);
1756 if (eq ? (sgn == 0) : (sgn >= 0))
1757 continue;
1758 tab = isl_tab_drop_sample(tab, i);
1759 if (!tab)
1760 break;
1762 isl_int_clear(v);
1764 return tab;
1765 error:
1766 isl_tab_free(tab);
1767 return NULL;
1770 /* Check whether the sample value of the tableau is finite,
1771 * i.e., either the tableau does not use a big parameter, or
1772 * all values of the variables are equal to the big parameter plus
1773 * some constant. This constant is the actual sample value.
1775 static int sample_is_finite(struct isl_tab *tab)
1777 int i;
1779 if (!tab->M)
1780 return 1;
1782 for (i = 0; i < tab->n_var; ++i) {
1783 int row;
1784 if (!tab->var[i].is_row)
1785 return 0;
1786 row = tab->var[i].index;
1787 if (isl_int_ne(tab->mat->row[row][0], tab->mat->row[row][2]))
1788 return 0;
1790 return 1;
1793 /* Check if the context tableau of sol has any integer points.
1794 * Leave tab in empty state if no integer point can be found.
1795 * If an integer point can be found and if moreover it is finite,
1796 * then it is added to the list of sample values.
1798 * This function is only called when none of the currently active sample
1799 * values satisfies the most recently added constraint.
1801 static struct isl_tab *check_integer_feasible(struct isl_tab *tab)
1803 struct isl_tab_undo *snap;
1805 if (!tab)
1806 return NULL;
1808 snap = isl_tab_snap(tab);
1809 if (isl_tab_push_basis(tab) < 0)
1810 goto error;
1812 tab = cut_to_integer_lexmin(tab, CUT_ALL);
1813 if (!tab)
1814 goto error;
1816 if (!tab->empty && sample_is_finite(tab)) {
1817 struct isl_vec *sample;
1819 sample = isl_tab_get_sample_value(tab);
1821 if (isl_tab_add_sample(tab, sample) < 0)
1822 goto error;
1825 if (!tab->empty && isl_tab_rollback(tab, snap) < 0)
1826 goto error;
1828 return tab;
1829 error:
1830 isl_tab_free(tab);
1831 return NULL;
1834 /* Check if any of the currently active sample values satisfies
1835 * the inequality "ineq" (an equality if eq is set).
1837 static int tab_has_valid_sample(struct isl_tab *tab, isl_int *ineq, int eq)
1839 int i;
1840 isl_int v;
1842 if (!tab)
1843 return -1;
1845 isl_assert(tab->mat->ctx, tab->bmap, return -1);
1846 isl_assert(tab->mat->ctx, tab->samples, return -1);
1847 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, return -1);
1849 isl_int_init(v);
1850 for (i = tab->n_outside; i < tab->n_sample; ++i) {
1851 int sgn;
1852 isl_seq_inner_product(ineq, tab->samples->row[i],
1853 1 + tab->n_var, &v);
1854 sgn = isl_int_sgn(v);
1855 if (eq ? (sgn == 0) : (sgn >= 0))
1856 break;
1858 isl_int_clear(v);
1860 return i < tab->n_sample;
1863 /* Add a div specified by "div" to the tableau "tab" and return
1864 * 1 if the div is obviously non-negative.
1866 static int context_tab_add_div(struct isl_tab *tab, struct isl_vec *div,
1867 int (*add_ineq)(void *user, isl_int *), void *user)
1869 int i;
1870 int r;
1871 struct isl_mat *samples;
1872 int nonneg;
1874 r = isl_tab_add_div(tab, div, add_ineq, user);
1875 if (r < 0)
1876 return -1;
1877 nonneg = tab->var[r].is_nonneg;
1878 tab->var[r].frozen = 1;
1880 samples = isl_mat_extend(tab->samples,
1881 tab->n_sample, 1 + tab->n_var);
1882 tab->samples = samples;
1883 if (!samples)
1884 return -1;
1885 for (i = tab->n_outside; i < samples->n_row; ++i) {
1886 isl_seq_inner_product(div->el + 1, samples->row[i],
1887 div->size - 1, &samples->row[i][samples->n_col - 1]);
1888 isl_int_fdiv_q(samples->row[i][samples->n_col - 1],
1889 samples->row[i][samples->n_col - 1], div->el[0]);
1892 return nonneg;
1895 /* Add a div specified by "div" to both the main tableau and
1896 * the context tableau. In case of the main tableau, we only
1897 * need to add an extra div. In the context tableau, we also
1898 * need to express the meaning of the div.
1899 * Return the index of the div or -1 if anything went wrong.
1901 static int add_div(struct isl_tab *tab, struct isl_context *context,
1902 struct isl_vec *div)
1904 int r;
1905 int nonneg;
1907 if ((nonneg = context->op->add_div(context, div)) < 0)
1908 goto error;
1910 if (!context->op->is_ok(context))
1911 goto error;
1913 if (isl_tab_extend_vars(tab, 1) < 0)
1914 goto error;
1915 r = isl_tab_allocate_var(tab);
1916 if (r < 0)
1917 goto error;
1918 if (nonneg)
1919 tab->var[r].is_nonneg = 1;
1920 tab->var[r].frozen = 1;
1921 tab->n_div++;
1923 return tab->n_div - 1;
1924 error:
1925 context->op->invalidate(context);
1926 return -1;
1929 static int find_div(struct isl_tab *tab, isl_int *div, isl_int denom)
1931 int i;
1932 unsigned total = isl_basic_map_total_dim(tab->bmap);
1934 for (i = 0; i < tab->bmap->n_div; ++i) {
1935 if (isl_int_ne(tab->bmap->div[i][0], denom))
1936 continue;
1937 if (!isl_seq_eq(tab->bmap->div[i] + 1, div, 1 + total))
1938 continue;
1939 return i;
1941 return -1;
1944 /* Return the index of a div that corresponds to "div".
1945 * We first check if we already have such a div and if not, we create one.
1947 static int get_div(struct isl_tab *tab, struct isl_context *context,
1948 struct isl_vec *div)
1950 int d;
1951 struct isl_tab *context_tab = context->op->peek_tab(context);
1953 if (!context_tab)
1954 return -1;
1956 d = find_div(context_tab, div->el + 1, div->el[0]);
1957 if (d != -1)
1958 return d;
1960 return add_div(tab, context, div);
1963 /* Add a parametric cut to cut away the non-integral sample value
1964 * of the give row.
1965 * Let a_i be the coefficients of the constant term and the parameters
1966 * and let b_i be the coefficients of the variables or constraints
1967 * in basis of the tableau.
1968 * Let q be the div q = floor(\sum_i {-a_i} y_i).
1970 * The cut is expressed as
1972 * c = \sum_i -{-a_i} y_i + \sum_i {b_i} x_i + q >= 0
1974 * If q did not already exist in the context tableau, then it is added first.
1975 * If q is in a column of the main tableau then the "+ q" can be accomplished
1976 * by setting the corresponding entry to the denominator of the constraint.
1977 * If q happens to be in a row of the main tableau, then the corresponding
1978 * row needs to be added instead (taking care of the denominators).
1979 * Note that this is very unlikely, but perhaps not entirely impossible.
1981 * The current value of the cut is known to be negative (or at least
1982 * non-positive), so row_sign is set accordingly.
1984 * Return the row of the cut or -1.
1986 static int add_parametric_cut(struct isl_tab *tab, int row,
1987 struct isl_context *context)
1989 struct isl_vec *div;
1990 int d;
1991 int i;
1992 int r;
1993 isl_int *r_row;
1994 int col;
1995 int n;
1996 unsigned off = 2 + tab->M;
1998 if (!context)
1999 return -1;
2001 div = get_row_parameter_div(tab, row);
2002 if (!div)
2003 return -1;
2005 n = tab->n_div;
2006 d = context->op->get_div(context, tab, div);
2007 isl_vec_free(div);
2008 if (d < 0)
2009 return -1;
2011 if (isl_tab_extend_cons(tab, 1) < 0)
2012 return -1;
2013 r = isl_tab_allocate_con(tab);
2014 if (r < 0)
2015 return -1;
2017 r_row = tab->mat->row[tab->con[r].index];
2018 isl_int_set(r_row[0], tab->mat->row[row][0]);
2019 isl_int_neg(r_row[1], tab->mat->row[row][1]);
2020 isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
2021 isl_int_neg(r_row[1], r_row[1]);
2022 if (tab->M)
2023 isl_int_set_si(r_row[2], 0);
2024 for (i = 0; i < tab->n_param; ++i) {
2025 if (tab->var[i].is_row)
2026 continue;
2027 col = tab->var[i].index;
2028 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
2029 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
2030 tab->mat->row[row][0]);
2031 isl_int_neg(r_row[off + col], r_row[off + col]);
2033 for (i = 0; i < tab->n_div; ++i) {
2034 if (tab->var[tab->n_var - tab->n_div + i].is_row)
2035 continue;
2036 col = tab->var[tab->n_var - tab->n_div + i].index;
2037 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
2038 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
2039 tab->mat->row[row][0]);
2040 isl_int_neg(r_row[off + col], r_row[off + col]);
2042 for (i = 0; i < tab->n_col; ++i) {
2043 if (tab->col_var[i] >= 0 &&
2044 (tab->col_var[i] < tab->n_param ||
2045 tab->col_var[i] >= tab->n_var - tab->n_div))
2046 continue;
2047 isl_int_fdiv_r(r_row[off + i],
2048 tab->mat->row[row][off + i], tab->mat->row[row][0]);
2050 if (tab->var[tab->n_var - tab->n_div + d].is_row) {
2051 isl_int gcd;
2052 int d_row = tab->var[tab->n_var - tab->n_div + d].index;
2053 isl_int_init(gcd);
2054 isl_int_gcd(gcd, tab->mat->row[d_row][0], r_row[0]);
2055 isl_int_divexact(r_row[0], r_row[0], gcd);
2056 isl_int_divexact(gcd, tab->mat->row[d_row][0], gcd);
2057 isl_seq_combine(r_row + 1, gcd, r_row + 1,
2058 r_row[0], tab->mat->row[d_row] + 1,
2059 off - 1 + tab->n_col);
2060 isl_int_mul(r_row[0], r_row[0], tab->mat->row[d_row][0]);
2061 isl_int_clear(gcd);
2062 } else {
2063 col = tab->var[tab->n_var - tab->n_div + d].index;
2064 isl_int_set(r_row[off + col], tab->mat->row[row][0]);
2067 tab->con[r].is_nonneg = 1;
2068 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
2069 return -1;
2070 if (tab->row_sign)
2071 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
2073 row = tab->con[r].index;
2075 if (d >= n && context->op->detect_equalities(context, tab) < 0)
2076 return -1;
2078 return row;
2081 /* Construct a tableau for bmap that can be used for computing
2082 * the lexicographic minimum (or maximum) of bmap.
2083 * If not NULL, then dom is the domain where the minimum
2084 * should be computed. In this case, we set up a parametric
2085 * tableau with row signs (initialized to "unknown").
2086 * If M is set, then the tableau will use a big parameter.
2087 * If max is set, then a maximum should be computed instead of a minimum.
2088 * This means that for each variable x, the tableau will contain the variable
2089 * x' = M - x, rather than x' = M + x. This in turn means that the coefficient
2090 * of the variables in all constraints are negated prior to adding them
2091 * to the tableau.
2093 static struct isl_tab *tab_for_lexmin(struct isl_basic_map *bmap,
2094 struct isl_basic_set *dom, unsigned M, int max)
2096 int i;
2097 struct isl_tab *tab;
2098 unsigned n_var;
2099 unsigned o_var;
2101 tab = isl_tab_alloc(bmap->ctx, 2 * bmap->n_eq + bmap->n_ineq + 1,
2102 isl_basic_map_total_dim(bmap), M);
2103 if (!tab)
2104 return NULL;
2106 tab->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
2107 if (dom) {
2108 tab->n_param = isl_basic_set_total_dim(dom) - dom->n_div;
2109 tab->n_div = dom->n_div;
2110 tab->row_sign = isl_calloc_array(bmap->ctx,
2111 enum isl_tab_row_sign, tab->mat->n_row);
2112 if (tab->mat->n_row && !tab->row_sign)
2113 goto error;
2115 if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY)) {
2116 if (isl_tab_mark_empty(tab) < 0)
2117 goto error;
2118 return tab;
2121 for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
2122 tab->var[i].is_nonneg = 1;
2123 tab->var[i].frozen = 1;
2125 o_var = 1 + tab->n_param;
2126 n_var = tab->n_var - tab->n_param - tab->n_div;
2127 for (i = 0; i < bmap->n_eq; ++i) {
2128 if (max)
2129 isl_seq_neg(bmap->eq[i] + o_var,
2130 bmap->eq[i] + o_var, n_var);
2131 tab = add_lexmin_valid_eq(tab, bmap->eq[i]);
2132 if (max)
2133 isl_seq_neg(bmap->eq[i] + o_var,
2134 bmap->eq[i] + o_var, n_var);
2135 if (!tab || tab->empty)
2136 return tab;
2138 if (bmap->n_eq && restore_lexmin(tab) < 0)
2139 goto error;
2140 for (i = 0; i < bmap->n_ineq; ++i) {
2141 if (max)
2142 isl_seq_neg(bmap->ineq[i] + o_var,
2143 bmap->ineq[i] + o_var, n_var);
2144 tab = add_lexmin_ineq(tab, bmap->ineq[i]);
2145 if (max)
2146 isl_seq_neg(bmap->ineq[i] + o_var,
2147 bmap->ineq[i] + o_var, n_var);
2148 if (!tab || tab->empty)
2149 return tab;
2151 return tab;
2152 error:
2153 isl_tab_free(tab);
2154 return NULL;
2157 /* Given a main tableau where more than one row requires a split,
2158 * determine and return the "best" row to split on.
2160 * Given two rows in the main tableau, if the inequality corresponding
2161 * to the first row is redundant with respect to that of the second row
2162 * in the current tableau, then it is better to split on the second row,
2163 * since in the positive part, both rows will be positive.
2164 * (In the negative part a pivot will have to be performed and just about
2165 * anything can happen to the sign of the other row.)
2167 * As a simple heuristic, we therefore select the row that makes the most
2168 * of the other rows redundant.
2170 * Perhaps it would also be useful to look at the number of constraints
2171 * that conflict with any given constraint.
2173 * best is the best row so far (-1 when we have not found any row yet).
2174 * best_r is the number of other rows made redundant by row best.
2175 * When best is still -1, bset_r is meaningless, but it is initialized
2176 * to some arbitrary value (0) anyway. Without this redundant initialization
2177 * valgrind may warn about uninitialized memory accesses when isl
2178 * is compiled with some versions of gcc.
2180 static int best_split(struct isl_tab *tab, struct isl_tab *context_tab)
2182 struct isl_tab_undo *snap;
2183 int split;
2184 int row;
2185 int best = -1;
2186 int best_r = 0;
2188 if (isl_tab_extend_cons(context_tab, 2) < 0)
2189 return -1;
2191 snap = isl_tab_snap(context_tab);
2193 for (split = tab->n_redundant; split < tab->n_row; ++split) {
2194 struct isl_tab_undo *snap2;
2195 struct isl_vec *ineq = NULL;
2196 int r = 0;
2197 int ok;
2199 if (!isl_tab_var_from_row(tab, split)->is_nonneg)
2200 continue;
2201 if (tab->row_sign[split] != isl_tab_row_any)
2202 continue;
2204 ineq = get_row_parameter_ineq(tab, split);
2205 if (!ineq)
2206 return -1;
2207 ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2208 isl_vec_free(ineq);
2209 if (!ok)
2210 return -1;
2212 snap2 = isl_tab_snap(context_tab);
2214 for (row = tab->n_redundant; row < tab->n_row; ++row) {
2215 struct isl_tab_var *var;
2217 if (row == split)
2218 continue;
2219 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
2220 continue;
2221 if (tab->row_sign[row] != isl_tab_row_any)
2222 continue;
2224 ineq = get_row_parameter_ineq(tab, row);
2225 if (!ineq)
2226 return -1;
2227 ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2228 isl_vec_free(ineq);
2229 if (!ok)
2230 return -1;
2231 var = &context_tab->con[context_tab->n_con - 1];
2232 if (!context_tab->empty &&
2233 !isl_tab_min_at_most_neg_one(context_tab, var))
2234 r++;
2235 if (isl_tab_rollback(context_tab, snap2) < 0)
2236 return -1;
2238 if (best == -1 || r > best_r) {
2239 best = split;
2240 best_r = r;
2242 if (isl_tab_rollback(context_tab, snap) < 0)
2243 return -1;
2246 return best;
2249 static struct isl_basic_set *context_lex_peek_basic_set(
2250 struct isl_context *context)
2252 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2253 if (!clex->tab)
2254 return NULL;
2255 return isl_tab_peek_bset(clex->tab);
2258 static struct isl_tab *context_lex_peek_tab(struct isl_context *context)
2260 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2261 return clex->tab;
2264 static void context_lex_add_eq(struct isl_context *context, isl_int *eq,
2265 int check, int update)
2267 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2268 if (isl_tab_extend_cons(clex->tab, 2) < 0)
2269 goto error;
2270 if (add_lexmin_eq(clex->tab, eq) < 0)
2271 goto error;
2272 if (check) {
2273 int v = tab_has_valid_sample(clex->tab, eq, 1);
2274 if (v < 0)
2275 goto error;
2276 if (!v)
2277 clex->tab = check_integer_feasible(clex->tab);
2279 if (update)
2280 clex->tab = check_samples(clex->tab, eq, 1);
2281 return;
2282 error:
2283 isl_tab_free(clex->tab);
2284 clex->tab = NULL;
2287 static void context_lex_add_ineq(struct isl_context *context, isl_int *ineq,
2288 int check, int update)
2290 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2291 if (isl_tab_extend_cons(clex->tab, 1) < 0)
2292 goto error;
2293 clex->tab = add_lexmin_ineq(clex->tab, ineq);
2294 if (check) {
2295 int v = tab_has_valid_sample(clex->tab, ineq, 0);
2296 if (v < 0)
2297 goto error;
2298 if (!v)
2299 clex->tab = check_integer_feasible(clex->tab);
2301 if (update)
2302 clex->tab = check_samples(clex->tab, ineq, 0);
2303 return;
2304 error:
2305 isl_tab_free(clex->tab);
2306 clex->tab = NULL;
2309 static int context_lex_add_ineq_wrap(void *user, isl_int *ineq)
2311 struct isl_context *context = (struct isl_context *)user;
2312 context_lex_add_ineq(context, ineq, 0, 0);
2313 return context->op->is_ok(context) ? 0 : -1;
2316 /* Check which signs can be obtained by "ineq" on all the currently
2317 * active sample values. See row_sign for more information.
2319 static enum isl_tab_row_sign tab_ineq_sign(struct isl_tab *tab, isl_int *ineq,
2320 int strict)
2322 int i;
2323 int sgn;
2324 isl_int tmp;
2325 enum isl_tab_row_sign res = isl_tab_row_unknown;
2327 isl_assert(tab->mat->ctx, tab->samples, return isl_tab_row_unknown);
2328 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var,
2329 return isl_tab_row_unknown);
2331 isl_int_init(tmp);
2332 for (i = tab->n_outside; i < tab->n_sample; ++i) {
2333 isl_seq_inner_product(tab->samples->row[i], ineq,
2334 1 + tab->n_var, &tmp);
2335 sgn = isl_int_sgn(tmp);
2336 if (sgn > 0 || (sgn == 0 && strict)) {
2337 if (res == isl_tab_row_unknown)
2338 res = isl_tab_row_pos;
2339 if (res == isl_tab_row_neg)
2340 res = isl_tab_row_any;
2342 if (sgn < 0) {
2343 if (res == isl_tab_row_unknown)
2344 res = isl_tab_row_neg;
2345 if (res == isl_tab_row_pos)
2346 res = isl_tab_row_any;
2348 if (res == isl_tab_row_any)
2349 break;
2351 isl_int_clear(tmp);
2353 return res;
2356 static enum isl_tab_row_sign context_lex_ineq_sign(struct isl_context *context,
2357 isl_int *ineq, int strict)
2359 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2360 return tab_ineq_sign(clex->tab, ineq, strict);
2363 /* Check whether "ineq" can be added to the tableau without rendering
2364 * it infeasible.
2366 static int context_lex_test_ineq(struct isl_context *context, isl_int *ineq)
2368 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2369 struct isl_tab_undo *snap;
2370 int feasible;
2372 if (!clex->tab)
2373 return -1;
2375 if (isl_tab_extend_cons(clex->tab, 1) < 0)
2376 return -1;
2378 snap = isl_tab_snap(clex->tab);
2379 if (isl_tab_push_basis(clex->tab) < 0)
2380 return -1;
2381 clex->tab = add_lexmin_ineq(clex->tab, ineq);
2382 clex->tab = check_integer_feasible(clex->tab);
2383 if (!clex->tab)
2384 return -1;
2385 feasible = !clex->tab->empty;
2386 if (isl_tab_rollback(clex->tab, snap) < 0)
2387 return -1;
2389 return feasible;
2392 static int context_lex_get_div(struct isl_context *context, struct isl_tab *tab,
2393 struct isl_vec *div)
2395 return get_div(tab, context, div);
2398 /* Add a div specified by "div" to the context tableau and return
2399 * 1 if the div is obviously non-negative.
2400 * context_tab_add_div will always return 1, because all variables
2401 * in a isl_context_lex tableau are non-negative.
2402 * However, if we are using a big parameter in the context, then this only
2403 * reflects the non-negativity of the variable used to _encode_ the
2404 * div, i.e., div' = M + div, so we can't draw any conclusions.
2406 static int context_lex_add_div(struct isl_context *context, struct isl_vec *div)
2408 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2409 int nonneg;
2410 nonneg = context_tab_add_div(clex->tab, div,
2411 context_lex_add_ineq_wrap, context);
2412 if (nonneg < 0)
2413 return -1;
2414 if (clex->tab->M)
2415 return 0;
2416 return nonneg;
2419 static int context_lex_detect_equalities(struct isl_context *context,
2420 struct isl_tab *tab)
2422 return 0;
2425 static int context_lex_best_split(struct isl_context *context,
2426 struct isl_tab *tab)
2428 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2429 struct isl_tab_undo *snap;
2430 int r;
2432 snap = isl_tab_snap(clex->tab);
2433 if (isl_tab_push_basis(clex->tab) < 0)
2434 return -1;
2435 r = best_split(tab, clex->tab);
2437 if (r >= 0 && isl_tab_rollback(clex->tab, snap) < 0)
2438 return -1;
2440 return r;
2443 static int context_lex_is_empty(struct isl_context *context)
2445 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2446 if (!clex->tab)
2447 return -1;
2448 return clex->tab->empty;
2451 static void *context_lex_save(struct isl_context *context)
2453 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2454 struct isl_tab_undo *snap;
2456 snap = isl_tab_snap(clex->tab);
2457 if (isl_tab_push_basis(clex->tab) < 0)
2458 return NULL;
2459 if (isl_tab_save_samples(clex->tab) < 0)
2460 return NULL;
2462 return snap;
2465 static void context_lex_restore(struct isl_context *context, void *save)
2467 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2468 if (isl_tab_rollback(clex->tab, (struct isl_tab_undo *)save) < 0) {
2469 isl_tab_free(clex->tab);
2470 clex->tab = NULL;
2474 static void context_lex_discard(void *save)
2478 static int context_lex_is_ok(struct isl_context *context)
2480 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2481 return !!clex->tab;
2484 /* For each variable in the context tableau, check if the variable can
2485 * only attain non-negative values. If so, mark the parameter as non-negative
2486 * in the main tableau. This allows for a more direct identification of some
2487 * cases of violated constraints.
2489 static struct isl_tab *tab_detect_nonnegative_parameters(struct isl_tab *tab,
2490 struct isl_tab *context_tab)
2492 int i;
2493 struct isl_tab_undo *snap;
2494 struct isl_vec *ineq = NULL;
2495 struct isl_tab_var *var;
2496 int n;
2498 if (context_tab->n_var == 0)
2499 return tab;
2501 ineq = isl_vec_alloc(tab->mat->ctx, 1 + context_tab->n_var);
2502 if (!ineq)
2503 goto error;
2505 if (isl_tab_extend_cons(context_tab, 1) < 0)
2506 goto error;
2508 snap = isl_tab_snap(context_tab);
2510 n = 0;
2511 isl_seq_clr(ineq->el, ineq->size);
2512 for (i = 0; i < context_tab->n_var; ++i) {
2513 isl_int_set_si(ineq->el[1 + i], 1);
2514 if (isl_tab_add_ineq(context_tab, ineq->el) < 0)
2515 goto error;
2516 var = &context_tab->con[context_tab->n_con - 1];
2517 if (!context_tab->empty &&
2518 !isl_tab_min_at_most_neg_one(context_tab, var)) {
2519 int j = i;
2520 if (i >= tab->n_param)
2521 j = i - tab->n_param + tab->n_var - tab->n_div;
2522 tab->var[j].is_nonneg = 1;
2523 n++;
2525 isl_int_set_si(ineq->el[1 + i], 0);
2526 if (isl_tab_rollback(context_tab, snap) < 0)
2527 goto error;
2530 if (context_tab->M && n == context_tab->n_var) {
2531 context_tab->mat = isl_mat_drop_cols(context_tab->mat, 2, 1);
2532 context_tab->M = 0;
2535 isl_vec_free(ineq);
2536 return tab;
2537 error:
2538 isl_vec_free(ineq);
2539 isl_tab_free(tab);
2540 return NULL;
2543 static struct isl_tab *context_lex_detect_nonnegative_parameters(
2544 struct isl_context *context, struct isl_tab *tab)
2546 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2547 struct isl_tab_undo *snap;
2549 if (!tab)
2550 return NULL;
2552 snap = isl_tab_snap(clex->tab);
2553 if (isl_tab_push_basis(clex->tab) < 0)
2554 goto error;
2556 tab = tab_detect_nonnegative_parameters(tab, clex->tab);
2558 if (isl_tab_rollback(clex->tab, snap) < 0)
2559 goto error;
2561 return tab;
2562 error:
2563 isl_tab_free(tab);
2564 return NULL;
2567 static void context_lex_invalidate(struct isl_context *context)
2569 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2570 isl_tab_free(clex->tab);
2571 clex->tab = NULL;
2574 static void context_lex_free(struct isl_context *context)
2576 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2577 isl_tab_free(clex->tab);
2578 free(clex);
2581 struct isl_context_op isl_context_lex_op = {
2582 context_lex_detect_nonnegative_parameters,
2583 context_lex_peek_basic_set,
2584 context_lex_peek_tab,
2585 context_lex_add_eq,
2586 context_lex_add_ineq,
2587 context_lex_ineq_sign,
2588 context_lex_test_ineq,
2589 context_lex_get_div,
2590 context_lex_add_div,
2591 context_lex_detect_equalities,
2592 context_lex_best_split,
2593 context_lex_is_empty,
2594 context_lex_is_ok,
2595 context_lex_save,
2596 context_lex_restore,
2597 context_lex_discard,
2598 context_lex_invalidate,
2599 context_lex_free,
2602 static struct isl_tab *context_tab_for_lexmin(struct isl_basic_set *bset)
2604 struct isl_tab *tab;
2606 if (!bset)
2607 return NULL;
2608 tab = tab_for_lexmin((struct isl_basic_map *)bset, NULL, 1, 0);
2609 if (!tab)
2610 goto error;
2611 if (isl_tab_track_bset(tab, bset) < 0)
2612 goto error;
2613 tab = isl_tab_init_samples(tab);
2614 return tab;
2615 error:
2616 isl_basic_set_free(bset);
2617 return NULL;
2620 static struct isl_context *isl_context_lex_alloc(struct isl_basic_set *dom)
2622 struct isl_context_lex *clex;
2624 if (!dom)
2625 return NULL;
2627 clex = isl_alloc_type(dom->ctx, struct isl_context_lex);
2628 if (!clex)
2629 return NULL;
2631 clex->context.op = &isl_context_lex_op;
2633 clex->tab = context_tab_for_lexmin(isl_basic_set_copy(dom));
2634 if (restore_lexmin(clex->tab) < 0)
2635 goto error;
2636 clex->tab = check_integer_feasible(clex->tab);
2637 if (!clex->tab)
2638 goto error;
2640 return &clex->context;
2641 error:
2642 clex->context.op->free(&clex->context);
2643 return NULL;
2646 /* Representation of the context when using generalized basis reduction.
2648 * "shifted" contains the offsets of the unit hypercubes that lie inside the
2649 * context. Any rational point in "shifted" can therefore be rounded
2650 * up to an integer point in the context.
2651 * If the context is constrained by any equality, then "shifted" is not used
2652 * as it would be empty.
2654 struct isl_context_gbr {
2655 struct isl_context context;
2656 struct isl_tab *tab;
2657 struct isl_tab *shifted;
2658 struct isl_tab *cone;
2661 static struct isl_tab *context_gbr_detect_nonnegative_parameters(
2662 struct isl_context *context, struct isl_tab *tab)
2664 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2665 if (!tab)
2666 return NULL;
2667 return tab_detect_nonnegative_parameters(tab, cgbr->tab);
2670 static struct isl_basic_set *context_gbr_peek_basic_set(
2671 struct isl_context *context)
2673 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2674 if (!cgbr->tab)
2675 return NULL;
2676 return isl_tab_peek_bset(cgbr->tab);
2679 static struct isl_tab *context_gbr_peek_tab(struct isl_context *context)
2681 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2682 return cgbr->tab;
2685 /* Initialize the "shifted" tableau of the context, which
2686 * contains the constraints of the original tableau shifted
2687 * by the sum of all negative coefficients. This ensures
2688 * that any rational point in the shifted tableau can
2689 * be rounded up to yield an integer point in the original tableau.
2691 static void gbr_init_shifted(struct isl_context_gbr *cgbr)
2693 int i, j;
2694 struct isl_vec *cst;
2695 struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
2696 unsigned dim = isl_basic_set_total_dim(bset);
2698 cst = isl_vec_alloc(cgbr->tab->mat->ctx, bset->n_ineq);
2699 if (!cst)
2700 return;
2702 for (i = 0; i < bset->n_ineq; ++i) {
2703 isl_int_set(cst->el[i], bset->ineq[i][0]);
2704 for (j = 0; j < dim; ++j) {
2705 if (!isl_int_is_neg(bset->ineq[i][1 + j]))
2706 continue;
2707 isl_int_add(bset->ineq[i][0], bset->ineq[i][0],
2708 bset->ineq[i][1 + j]);
2712 cgbr->shifted = isl_tab_from_basic_set(bset, 0);
2714 for (i = 0; i < bset->n_ineq; ++i)
2715 isl_int_set(bset->ineq[i][0], cst->el[i]);
2717 isl_vec_free(cst);
2720 /* Check if the shifted tableau is non-empty, and if so
2721 * use the sample point to construct an integer point
2722 * of the context tableau.
2724 static struct isl_vec *gbr_get_shifted_sample(struct isl_context_gbr *cgbr)
2726 struct isl_vec *sample;
2728 if (!cgbr->shifted)
2729 gbr_init_shifted(cgbr);
2730 if (!cgbr->shifted)
2731 return NULL;
2732 if (cgbr->shifted->empty)
2733 return isl_vec_alloc(cgbr->tab->mat->ctx, 0);
2735 sample = isl_tab_get_sample_value(cgbr->shifted);
2736 sample = isl_vec_ceil(sample);
2738 return sample;
2741 static struct isl_basic_set *drop_constant_terms(struct isl_basic_set *bset)
2743 int i;
2745 if (!bset)
2746 return NULL;
2748 for (i = 0; i < bset->n_eq; ++i)
2749 isl_int_set_si(bset->eq[i][0], 0);
2751 for (i = 0; i < bset->n_ineq; ++i)
2752 isl_int_set_si(bset->ineq[i][0], 0);
2754 return bset;
2757 static int use_shifted(struct isl_context_gbr *cgbr)
2759 if (!cgbr->tab)
2760 return 0;
2761 return cgbr->tab->bmap->n_eq == 0 && cgbr->tab->bmap->n_div == 0;
2764 static struct isl_vec *gbr_get_sample(struct isl_context_gbr *cgbr)
2766 struct isl_basic_set *bset;
2767 struct isl_basic_set *cone;
2769 if (isl_tab_sample_is_integer(cgbr->tab))
2770 return isl_tab_get_sample_value(cgbr->tab);
2772 if (use_shifted(cgbr)) {
2773 struct isl_vec *sample;
2775 sample = gbr_get_shifted_sample(cgbr);
2776 if (!sample || sample->size > 0)
2777 return sample;
2779 isl_vec_free(sample);
2782 if (!cgbr->cone) {
2783 bset = isl_tab_peek_bset(cgbr->tab);
2784 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
2785 if (!cgbr->cone)
2786 return NULL;
2787 if (isl_tab_track_bset(cgbr->cone,
2788 isl_basic_set_copy(bset)) < 0)
2789 return NULL;
2791 if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
2792 return NULL;
2794 if (cgbr->cone->n_dead == cgbr->cone->n_col) {
2795 struct isl_vec *sample;
2796 struct isl_tab_undo *snap;
2798 if (cgbr->tab->basis) {
2799 if (cgbr->tab->basis->n_col != 1 + cgbr->tab->n_var) {
2800 isl_mat_free(cgbr->tab->basis);
2801 cgbr->tab->basis = NULL;
2803 cgbr->tab->n_zero = 0;
2804 cgbr->tab->n_unbounded = 0;
2807 snap = isl_tab_snap(cgbr->tab);
2809 sample = isl_tab_sample(cgbr->tab);
2811 if (!sample || isl_tab_rollback(cgbr->tab, snap) < 0) {
2812 isl_vec_free(sample);
2813 return NULL;
2816 return sample;
2819 cone = isl_basic_set_dup(isl_tab_peek_bset(cgbr->cone));
2820 cone = drop_constant_terms(cone);
2821 cone = isl_basic_set_update_from_tab(cone, cgbr->cone);
2822 cone = isl_basic_set_underlying_set(cone);
2823 cone = isl_basic_set_gauss(cone, NULL);
2825 bset = isl_basic_set_dup(isl_tab_peek_bset(cgbr->tab));
2826 bset = isl_basic_set_update_from_tab(bset, cgbr->tab);
2827 bset = isl_basic_set_underlying_set(bset);
2828 bset = isl_basic_set_gauss(bset, NULL);
2830 return isl_basic_set_sample_with_cone(bset, cone);
2833 static void check_gbr_integer_feasible(struct isl_context_gbr *cgbr)
2835 struct isl_vec *sample;
2837 if (!cgbr->tab)
2838 return;
2840 if (cgbr->tab->empty)
2841 return;
2843 sample = gbr_get_sample(cgbr);
2844 if (!sample)
2845 goto error;
2847 if (sample->size == 0) {
2848 isl_vec_free(sample);
2849 if (isl_tab_mark_empty(cgbr->tab) < 0)
2850 goto error;
2851 return;
2854 if (isl_tab_add_sample(cgbr->tab, sample) < 0)
2855 goto error;
2857 return;
2858 error:
2859 isl_tab_free(cgbr->tab);
2860 cgbr->tab = NULL;
2863 static struct isl_tab *add_gbr_eq(struct isl_tab *tab, isl_int *eq)
2865 if (!tab)
2866 return NULL;
2868 if (isl_tab_extend_cons(tab, 2) < 0)
2869 goto error;
2871 if (isl_tab_add_eq(tab, eq) < 0)
2872 goto error;
2874 return tab;
2875 error:
2876 isl_tab_free(tab);
2877 return NULL;
2880 /* Add the equality described by "eq" to the context.
2881 * If "check" is set, then we check if the context is empty after
2882 * adding the equality.
2883 * If "update" is set, then we check if the samples are still valid.
2885 * We do not explicitly add shifted copies of the equality to
2886 * cgbr->shifted since they would conflict with each other.
2887 * Instead, we directly mark cgbr->shifted empty.
2889 static void context_gbr_add_eq(struct isl_context *context, isl_int *eq,
2890 int check, int update)
2892 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2894 cgbr->tab = add_gbr_eq(cgbr->tab, eq);
2896 if (cgbr->shifted && !cgbr->shifted->empty && use_shifted(cgbr)) {
2897 if (isl_tab_mark_empty(cgbr->shifted) < 0)
2898 goto error;
2901 if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
2902 if (isl_tab_extend_cons(cgbr->cone, 2) < 0)
2903 goto error;
2904 if (isl_tab_add_eq(cgbr->cone, eq) < 0)
2905 goto error;
2908 if (check) {
2909 int v = tab_has_valid_sample(cgbr->tab, eq, 1);
2910 if (v < 0)
2911 goto error;
2912 if (!v)
2913 check_gbr_integer_feasible(cgbr);
2915 if (update)
2916 cgbr->tab = check_samples(cgbr->tab, eq, 1);
2917 return;
2918 error:
2919 isl_tab_free(cgbr->tab);
2920 cgbr->tab = NULL;
2923 static void add_gbr_ineq(struct isl_context_gbr *cgbr, isl_int *ineq)
2925 if (!cgbr->tab)
2926 return;
2928 if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
2929 goto error;
2931 if (isl_tab_add_ineq(cgbr->tab, ineq) < 0)
2932 goto error;
2934 if (cgbr->shifted && !cgbr->shifted->empty && use_shifted(cgbr)) {
2935 int i;
2936 unsigned dim;
2937 dim = isl_basic_map_total_dim(cgbr->tab->bmap);
2939 if (isl_tab_extend_cons(cgbr->shifted, 1) < 0)
2940 goto error;
2942 for (i = 0; i < dim; ++i) {
2943 if (!isl_int_is_neg(ineq[1 + i]))
2944 continue;
2945 isl_int_add(ineq[0], ineq[0], ineq[1 + i]);
2948 if (isl_tab_add_ineq(cgbr->shifted, ineq) < 0)
2949 goto error;
2951 for (i = 0; i < dim; ++i) {
2952 if (!isl_int_is_neg(ineq[1 + i]))
2953 continue;
2954 isl_int_sub(ineq[0], ineq[0], ineq[1 + i]);
2958 if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
2959 if (isl_tab_extend_cons(cgbr->cone, 1) < 0)
2960 goto error;
2961 if (isl_tab_add_ineq(cgbr->cone, ineq) < 0)
2962 goto error;
2965 return;
2966 error:
2967 isl_tab_free(cgbr->tab);
2968 cgbr->tab = NULL;
2971 static void context_gbr_add_ineq(struct isl_context *context, isl_int *ineq,
2972 int check, int update)
2974 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2976 add_gbr_ineq(cgbr, ineq);
2977 if (!cgbr->tab)
2978 return;
2980 if (check) {
2981 int v = tab_has_valid_sample(cgbr->tab, ineq, 0);
2982 if (v < 0)
2983 goto error;
2984 if (!v)
2985 check_gbr_integer_feasible(cgbr);
2987 if (update)
2988 cgbr->tab = check_samples(cgbr->tab, ineq, 0);
2989 return;
2990 error:
2991 isl_tab_free(cgbr->tab);
2992 cgbr->tab = NULL;
2995 static int context_gbr_add_ineq_wrap(void *user, isl_int *ineq)
2997 struct isl_context *context = (struct isl_context *)user;
2998 context_gbr_add_ineq(context, ineq, 0, 0);
2999 return context->op->is_ok(context) ? 0 : -1;
3002 static enum isl_tab_row_sign context_gbr_ineq_sign(struct isl_context *context,
3003 isl_int *ineq, int strict)
3005 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3006 return tab_ineq_sign(cgbr->tab, ineq, strict);
3009 /* Check whether "ineq" can be added to the tableau without rendering
3010 * it infeasible.
3012 static int context_gbr_test_ineq(struct isl_context *context, isl_int *ineq)
3014 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3015 struct isl_tab_undo *snap;
3016 struct isl_tab_undo *shifted_snap = NULL;
3017 struct isl_tab_undo *cone_snap = NULL;
3018 int feasible;
3020 if (!cgbr->tab)
3021 return -1;
3023 if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
3024 return -1;
3026 snap = isl_tab_snap(cgbr->tab);
3027 if (cgbr->shifted)
3028 shifted_snap = isl_tab_snap(cgbr->shifted);
3029 if (cgbr->cone)
3030 cone_snap = isl_tab_snap(cgbr->cone);
3031 add_gbr_ineq(cgbr, ineq);
3032 check_gbr_integer_feasible(cgbr);
3033 if (!cgbr->tab)
3034 return -1;
3035 feasible = !cgbr->tab->empty;
3036 if (isl_tab_rollback(cgbr->tab, snap) < 0)
3037 return -1;
3038 if (shifted_snap) {
3039 if (isl_tab_rollback(cgbr->shifted, shifted_snap))
3040 return -1;
3041 } else if (cgbr->shifted) {
3042 isl_tab_free(cgbr->shifted);
3043 cgbr->shifted = NULL;
3045 if (cone_snap) {
3046 if (isl_tab_rollback(cgbr->cone, cone_snap))
3047 return -1;
3048 } else if (cgbr->cone) {
3049 isl_tab_free(cgbr->cone);
3050 cgbr->cone = NULL;
3053 return feasible;
3056 /* Return the column of the last of the variables associated to
3057 * a column that has a non-zero coefficient.
3058 * This function is called in a context where only coefficients
3059 * of parameters or divs can be non-zero.
3061 static int last_non_zero_var_col(struct isl_tab *tab, isl_int *p)
3063 int i;
3064 int col;
3066 if (tab->n_var == 0)
3067 return -1;
3069 for (i = tab->n_var - 1; i >= 0; --i) {
3070 if (i >= tab->n_param && i < tab->n_var - tab->n_div)
3071 continue;
3072 if (tab->var[i].is_row)
3073 continue;
3074 col = tab->var[i].index;
3075 if (!isl_int_is_zero(p[col]))
3076 return col;
3079 return -1;
3082 /* Look through all the recently added equalities in the context
3083 * to see if we can propagate any of them to the main tableau.
3085 * The newly added equalities in the context are encoded as pairs
3086 * of inequalities starting at inequality "first".
3088 * We tentatively add each of these equalities to the main tableau
3089 * and if this happens to result in a row with a final coefficient
3090 * that is one or negative one, we use it to kill a column
3091 * in the main tableau. Otherwise, we discard the tentatively
3092 * added row.
3093 * This tentative addition of equality constraints turns
3094 * on the undo facility of the tableau. Turn it off again
3095 * at the end, assuming it was turned off to begin with.
3097 * Return 0 on success and -1 on failure.
3099 static int propagate_equalities(struct isl_context_gbr *cgbr,
3100 struct isl_tab *tab, unsigned first)
3102 int i;
3103 struct isl_vec *eq = NULL;
3104 isl_bool needs_undo;
3106 needs_undo = isl_tab_need_undo(tab);
3107 if (needs_undo < 0)
3108 goto error;
3109 eq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_var);
3110 if (!eq)
3111 goto error;
3113 if (isl_tab_extend_cons(tab, (cgbr->tab->bmap->n_ineq - first)/2) < 0)
3114 goto error;
3116 isl_seq_clr(eq->el + 1 + tab->n_param,
3117 tab->n_var - tab->n_param - tab->n_div);
3118 for (i = first; i < cgbr->tab->bmap->n_ineq; i += 2) {
3119 int j;
3120 int r;
3121 struct isl_tab_undo *snap;
3122 snap = isl_tab_snap(tab);
3124 isl_seq_cpy(eq->el, cgbr->tab->bmap->ineq[i], 1 + tab->n_param);
3125 isl_seq_cpy(eq->el + 1 + tab->n_var - tab->n_div,
3126 cgbr->tab->bmap->ineq[i] + 1 + tab->n_param,
3127 tab->n_div);
3129 r = isl_tab_add_row(tab, eq->el);
3130 if (r < 0)
3131 goto error;
3132 r = tab->con[r].index;
3133 j = last_non_zero_var_col(tab, tab->mat->row[r] + 2 + tab->M);
3134 if (j < 0 || j < tab->n_dead ||
3135 !isl_int_is_one(tab->mat->row[r][0]) ||
3136 (!isl_int_is_one(tab->mat->row[r][2 + tab->M + j]) &&
3137 !isl_int_is_negone(tab->mat->row[r][2 + tab->M + j]))) {
3138 if (isl_tab_rollback(tab, snap) < 0)
3139 goto error;
3140 continue;
3142 if (isl_tab_pivot(tab, r, j) < 0)
3143 goto error;
3144 if (isl_tab_kill_col(tab, j) < 0)
3145 goto error;
3147 if (restore_lexmin(tab) < 0)
3148 goto error;
3151 if (!needs_undo)
3152 isl_tab_clear_undo(tab);
3153 isl_vec_free(eq);
3155 return 0;
3156 error:
3157 isl_vec_free(eq);
3158 isl_tab_free(cgbr->tab);
3159 cgbr->tab = NULL;
3160 return -1;
3163 static int context_gbr_detect_equalities(struct isl_context *context,
3164 struct isl_tab *tab)
3166 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3167 unsigned n_ineq;
3169 if (!cgbr->cone) {
3170 struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
3171 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
3172 if (!cgbr->cone)
3173 goto error;
3174 if (isl_tab_track_bset(cgbr->cone,
3175 isl_basic_set_copy(bset)) < 0)
3176 goto error;
3178 if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
3179 goto error;
3181 n_ineq = cgbr->tab->bmap->n_ineq;
3182 cgbr->tab = isl_tab_detect_equalities(cgbr->tab, cgbr->cone);
3183 if (!cgbr->tab)
3184 return -1;
3185 if (cgbr->tab->bmap->n_ineq > n_ineq &&
3186 propagate_equalities(cgbr, tab, n_ineq) < 0)
3187 return -1;
3189 return 0;
3190 error:
3191 isl_tab_free(cgbr->tab);
3192 cgbr->tab = NULL;
3193 return -1;
3196 static int context_gbr_get_div(struct isl_context *context, struct isl_tab *tab,
3197 struct isl_vec *div)
3199 return get_div(tab, context, div);
3202 static int context_gbr_add_div(struct isl_context *context, struct isl_vec *div)
3204 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3205 if (cgbr->cone) {
3206 int k;
3208 if (isl_tab_extend_cons(cgbr->cone, 3) < 0)
3209 return -1;
3210 if (isl_tab_extend_vars(cgbr->cone, 1) < 0)
3211 return -1;
3212 if (isl_tab_allocate_var(cgbr->cone) <0)
3213 return -1;
3215 cgbr->cone->bmap = isl_basic_map_extend_space(cgbr->cone->bmap,
3216 isl_basic_map_get_space(cgbr->cone->bmap), 1, 0, 2);
3217 k = isl_basic_map_alloc_div(cgbr->cone->bmap);
3218 if (k < 0)
3219 return -1;
3220 isl_seq_cpy(cgbr->cone->bmap->div[k], div->el, div->size);
3221 if (isl_tab_push(cgbr->cone, isl_tab_undo_bmap_div) < 0)
3222 return -1;
3224 return context_tab_add_div(cgbr->tab, div,
3225 context_gbr_add_ineq_wrap, context);
3228 static int context_gbr_best_split(struct isl_context *context,
3229 struct isl_tab *tab)
3231 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3232 struct isl_tab_undo *snap;
3233 int r;
3235 snap = isl_tab_snap(cgbr->tab);
3236 r = best_split(tab, cgbr->tab);
3238 if (r >= 0 && isl_tab_rollback(cgbr->tab, snap) < 0)
3239 return -1;
3241 return r;
3244 static int context_gbr_is_empty(struct isl_context *context)
3246 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3247 if (!cgbr->tab)
3248 return -1;
3249 return cgbr->tab->empty;
3252 struct isl_gbr_tab_undo {
3253 struct isl_tab_undo *tab_snap;
3254 struct isl_tab_undo *shifted_snap;
3255 struct isl_tab_undo *cone_snap;
3258 static void *context_gbr_save(struct isl_context *context)
3260 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3261 struct isl_gbr_tab_undo *snap;
3263 if (!cgbr->tab)
3264 return NULL;
3266 snap = isl_alloc_type(cgbr->tab->mat->ctx, struct isl_gbr_tab_undo);
3267 if (!snap)
3268 return NULL;
3270 snap->tab_snap = isl_tab_snap(cgbr->tab);
3271 if (isl_tab_save_samples(cgbr->tab) < 0)
3272 goto error;
3274 if (cgbr->shifted)
3275 snap->shifted_snap = isl_tab_snap(cgbr->shifted);
3276 else
3277 snap->shifted_snap = NULL;
3279 if (cgbr->cone)
3280 snap->cone_snap = isl_tab_snap(cgbr->cone);
3281 else
3282 snap->cone_snap = NULL;
3284 return snap;
3285 error:
3286 free(snap);
3287 return NULL;
3290 static void context_gbr_restore(struct isl_context *context, void *save)
3292 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3293 struct isl_gbr_tab_undo *snap = (struct isl_gbr_tab_undo *)save;
3294 if (!snap)
3295 goto error;
3296 if (isl_tab_rollback(cgbr->tab, snap->tab_snap) < 0)
3297 goto error;
3299 if (snap->shifted_snap) {
3300 if (isl_tab_rollback(cgbr->shifted, snap->shifted_snap) < 0)
3301 goto error;
3302 } else if (cgbr->shifted) {
3303 isl_tab_free(cgbr->shifted);
3304 cgbr->shifted = NULL;
3307 if (snap->cone_snap) {
3308 if (isl_tab_rollback(cgbr->cone, snap->cone_snap) < 0)
3309 goto error;
3310 } else if (cgbr->cone) {
3311 isl_tab_free(cgbr->cone);
3312 cgbr->cone = NULL;
3315 free(snap);
3317 return;
3318 error:
3319 free(snap);
3320 isl_tab_free(cgbr->tab);
3321 cgbr->tab = NULL;
3324 static void context_gbr_discard(void *save)
3326 struct isl_gbr_tab_undo *snap = (struct isl_gbr_tab_undo *)save;
3327 free(snap);
3330 static int context_gbr_is_ok(struct isl_context *context)
3332 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3333 return !!cgbr->tab;
3336 static void context_gbr_invalidate(struct isl_context *context)
3338 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3339 isl_tab_free(cgbr->tab);
3340 cgbr->tab = NULL;
3343 static void context_gbr_free(struct isl_context *context)
3345 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3346 isl_tab_free(cgbr->tab);
3347 isl_tab_free(cgbr->shifted);
3348 isl_tab_free(cgbr->cone);
3349 free(cgbr);
3352 struct isl_context_op isl_context_gbr_op = {
3353 context_gbr_detect_nonnegative_parameters,
3354 context_gbr_peek_basic_set,
3355 context_gbr_peek_tab,
3356 context_gbr_add_eq,
3357 context_gbr_add_ineq,
3358 context_gbr_ineq_sign,
3359 context_gbr_test_ineq,
3360 context_gbr_get_div,
3361 context_gbr_add_div,
3362 context_gbr_detect_equalities,
3363 context_gbr_best_split,
3364 context_gbr_is_empty,
3365 context_gbr_is_ok,
3366 context_gbr_save,
3367 context_gbr_restore,
3368 context_gbr_discard,
3369 context_gbr_invalidate,
3370 context_gbr_free,
3373 static struct isl_context *isl_context_gbr_alloc(struct isl_basic_set *dom)
3375 struct isl_context_gbr *cgbr;
3377 if (!dom)
3378 return NULL;
3380 cgbr = isl_calloc_type(dom->ctx, struct isl_context_gbr);
3381 if (!cgbr)
3382 return NULL;
3384 cgbr->context.op = &isl_context_gbr_op;
3386 cgbr->shifted = NULL;
3387 cgbr->cone = NULL;
3388 cgbr->tab = isl_tab_from_basic_set(dom, 1);
3389 cgbr->tab = isl_tab_init_samples(cgbr->tab);
3390 if (!cgbr->tab)
3391 goto error;
3392 check_gbr_integer_feasible(cgbr);
3394 return &cgbr->context;
3395 error:
3396 cgbr->context.op->free(&cgbr->context);
3397 return NULL;
3400 static struct isl_context *isl_context_alloc(__isl_keep isl_basic_set *dom)
3402 if (!dom)
3403 return NULL;
3405 if (dom->ctx->opt->context == ISL_CONTEXT_LEXMIN)
3406 return isl_context_lex_alloc(dom);
3407 else
3408 return isl_context_gbr_alloc(dom);
3411 /* Construct an isl_sol_map structure for accumulating the solution.
3412 * If track_empty is set, then we also keep track of the parts
3413 * of the context where there is no solution.
3414 * If max is set, then we are solving a maximization, rather than
3415 * a minimization problem, which means that the variables in the
3416 * tableau have value "M - x" rather than "M + x".
3418 static struct isl_sol *sol_map_init(struct isl_basic_map *bmap,
3419 struct isl_basic_set *dom, int track_empty, int max)
3421 struct isl_sol_map *sol_map = NULL;
3423 if (!bmap)
3424 goto error;
3426 sol_map = isl_calloc_type(bmap->ctx, struct isl_sol_map);
3427 if (!sol_map)
3428 goto error;
3430 sol_map->sol.rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
3431 sol_map->sol.dec_level.callback.run = &sol_dec_level_wrap;
3432 sol_map->sol.dec_level.sol = &sol_map->sol;
3433 sol_map->sol.max = max;
3434 sol_map->sol.n_out = isl_basic_map_dim(bmap, isl_dim_out);
3435 sol_map->sol.add = &sol_map_add_wrap;
3436 sol_map->sol.add_empty = track_empty ? &sol_map_add_empty_wrap : NULL;
3437 sol_map->sol.free = &sol_map_free_wrap;
3438 sol_map->map = isl_map_alloc_space(isl_basic_map_get_space(bmap), 1,
3439 ISL_MAP_DISJOINT);
3440 if (!sol_map->map)
3441 goto error;
3443 sol_map->sol.context = isl_context_alloc(dom);
3444 if (!sol_map->sol.context)
3445 goto error;
3447 if (track_empty) {
3448 sol_map->empty = isl_set_alloc_space(isl_basic_set_get_space(dom),
3449 1, ISL_SET_DISJOINT);
3450 if (!sol_map->empty)
3451 goto error;
3454 isl_basic_set_free(dom);
3455 return &sol_map->sol;
3456 error:
3457 isl_basic_set_free(dom);
3458 sol_map_free(sol_map);
3459 return NULL;
3462 /* Check whether all coefficients of (non-parameter) variables
3463 * are non-positive, meaning that no pivots can be performed on the row.
3465 static int is_critical(struct isl_tab *tab, int row)
3467 int j;
3468 unsigned off = 2 + tab->M;
3470 for (j = tab->n_dead; j < tab->n_col; ++j) {
3471 if (tab->col_var[j] >= 0 &&
3472 (tab->col_var[j] < tab->n_param ||
3473 tab->col_var[j] >= tab->n_var - tab->n_div))
3474 continue;
3476 if (isl_int_is_pos(tab->mat->row[row][off + j]))
3477 return 0;
3480 return 1;
3483 /* Check whether the inequality represented by vec is strict over the integers,
3484 * i.e., there are no integer values satisfying the constraint with
3485 * equality. This happens if the gcd of the coefficients is not a divisor
3486 * of the constant term. If so, scale the constraint down by the gcd
3487 * of the coefficients.
3489 static int is_strict(struct isl_vec *vec)
3491 isl_int gcd;
3492 int strict = 0;
3494 isl_int_init(gcd);
3495 isl_seq_gcd(vec->el + 1, vec->size - 1, &gcd);
3496 if (!isl_int_is_one(gcd)) {
3497 strict = !isl_int_is_divisible_by(vec->el[0], gcd);
3498 isl_int_fdiv_q(vec->el[0], vec->el[0], gcd);
3499 isl_seq_scale_down(vec->el + 1, vec->el + 1, gcd, vec->size-1);
3501 isl_int_clear(gcd);
3503 return strict;
3506 /* Determine the sign of the given row of the main tableau.
3507 * The result is one of
3508 * isl_tab_row_pos: always non-negative; no pivot needed
3509 * isl_tab_row_neg: always non-positive; pivot
3510 * isl_tab_row_any: can be both positive and negative; split
3512 * We first handle some simple cases
3513 * - the row sign may be known already
3514 * - the row may be obviously non-negative
3515 * - the parametric constant may be equal to that of another row
3516 * for which we know the sign. This sign will be either "pos" or
3517 * "any". If it had been "neg" then we would have pivoted before.
3519 * If none of these cases hold, we check the value of the row for each
3520 * of the currently active samples. Based on the signs of these values
3521 * we make an initial determination of the sign of the row.
3523 * all zero -> unk(nown)
3524 * all non-negative -> pos
3525 * all non-positive -> neg
3526 * both negative and positive -> all
3528 * If we end up with "all", we are done.
3529 * Otherwise, we perform a check for positive and/or negative
3530 * values as follows.
3532 * samples neg unk pos
3533 * <0 ? Y N Y N
3534 * pos any pos
3535 * >0 ? Y N Y N
3536 * any neg any neg
3538 * There is no special sign for "zero", because we can usually treat zero
3539 * as either non-negative or non-positive, whatever works out best.
3540 * However, if the row is "critical", meaning that pivoting is impossible
3541 * then we don't want to limp zero with the non-positive case, because
3542 * then we we would lose the solution for those values of the parameters
3543 * where the value of the row is zero. Instead, we treat 0 as non-negative
3544 * ensuring a split if the row can attain both zero and negative values.
3545 * The same happens when the original constraint was one that could not
3546 * be satisfied with equality by any integer values of the parameters.
3547 * In this case, we normalize the constraint, but then a value of zero
3548 * for the normalized constraint is actually a positive value for the
3549 * original constraint, so again we need to treat zero as non-negative.
3550 * In both these cases, we have the following decision tree instead:
3552 * all non-negative -> pos
3553 * all negative -> neg
3554 * both negative and non-negative -> all
3556 * samples neg pos
3557 * <0 ? Y N
3558 * any pos
3559 * >=0 ? Y N
3560 * any neg
3562 static enum isl_tab_row_sign row_sign(struct isl_tab *tab,
3563 struct isl_sol *sol, int row)
3565 struct isl_vec *ineq = NULL;
3566 enum isl_tab_row_sign res = isl_tab_row_unknown;
3567 int critical;
3568 int strict;
3569 int row2;
3571 if (tab->row_sign[row] != isl_tab_row_unknown)
3572 return tab->row_sign[row];
3573 if (is_obviously_nonneg(tab, row))
3574 return isl_tab_row_pos;
3575 for (row2 = tab->n_redundant; row2 < tab->n_row; ++row2) {
3576 if (tab->row_sign[row2] == isl_tab_row_unknown)
3577 continue;
3578 if (identical_parameter_line(tab, row, row2))
3579 return tab->row_sign[row2];
3582 critical = is_critical(tab, row);
3584 ineq = get_row_parameter_ineq(tab, row);
3585 if (!ineq)
3586 goto error;
3588 strict = is_strict(ineq);
3590 res = sol->context->op->ineq_sign(sol->context, ineq->el,
3591 critical || strict);
3593 if (res == isl_tab_row_unknown || res == isl_tab_row_pos) {
3594 /* test for negative values */
3595 int feasible;
3596 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3597 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3599 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3600 if (feasible < 0)
3601 goto error;
3602 if (!feasible)
3603 res = isl_tab_row_pos;
3604 else
3605 res = (res == isl_tab_row_unknown) ? isl_tab_row_neg
3606 : isl_tab_row_any;
3607 if (res == isl_tab_row_neg) {
3608 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3609 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3613 if (res == isl_tab_row_neg) {
3614 /* test for positive values */
3615 int feasible;
3616 if (!critical && !strict)
3617 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3619 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3620 if (feasible < 0)
3621 goto error;
3622 if (feasible)
3623 res = isl_tab_row_any;
3626 isl_vec_free(ineq);
3627 return res;
3628 error:
3629 isl_vec_free(ineq);
3630 return isl_tab_row_unknown;
3633 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab);
3635 /* Find solutions for values of the parameters that satisfy the given
3636 * inequality.
3638 * We currently take a snapshot of the context tableau that is reset
3639 * when we return from this function, while we make a copy of the main
3640 * tableau, leaving the original main tableau untouched.
3641 * These are fairly arbitrary choices. Making a copy also of the context
3642 * tableau would obviate the need to undo any changes made to it later,
3643 * while taking a snapshot of the main tableau could reduce memory usage.
3644 * If we were to switch to taking a snapshot of the main tableau,
3645 * we would have to keep in mind that we need to save the row signs
3646 * and that we need to do this before saving the current basis
3647 * such that the basis has been restore before we restore the row signs.
3649 static void find_in_pos(struct isl_sol *sol, struct isl_tab *tab, isl_int *ineq)
3651 void *saved;
3653 if (!sol->context)
3654 goto error;
3655 saved = sol->context->op->save(sol->context);
3657 tab = isl_tab_dup(tab);
3658 if (!tab)
3659 goto error;
3661 sol->context->op->add_ineq(sol->context, ineq, 0, 1);
3663 find_solutions(sol, tab);
3665 if (!sol->error)
3666 sol->context->op->restore(sol->context, saved);
3667 else
3668 sol->context->op->discard(saved);
3669 return;
3670 error:
3671 sol->error = 1;
3674 /* Record the absence of solutions for those values of the parameters
3675 * that do not satisfy the given inequality with equality.
3677 static void no_sol_in_strict(struct isl_sol *sol,
3678 struct isl_tab *tab, struct isl_vec *ineq)
3680 int empty;
3681 void *saved;
3683 if (!sol->context || sol->error)
3684 goto error;
3685 saved = sol->context->op->save(sol->context);
3687 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3689 sol->context->op->add_ineq(sol->context, ineq->el, 1, 0);
3690 if (!sol->context)
3691 goto error;
3693 empty = tab->empty;
3694 tab->empty = 1;
3695 sol_add(sol, tab);
3696 tab->empty = empty;
3698 isl_int_add_ui(ineq->el[0], ineq->el[0], 1);
3700 sol->context->op->restore(sol->context, saved);
3701 return;
3702 error:
3703 sol->error = 1;
3706 /* Reset all row variables that are marked to have a sign that may
3707 * be both positive and negative to have an unknown sign.
3709 static void reset_any_to_unknown(struct isl_tab *tab)
3711 int row;
3713 for (row = tab->n_redundant; row < tab->n_row; ++row) {
3714 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
3715 continue;
3716 if (tab->row_sign[row] == isl_tab_row_any)
3717 tab->row_sign[row] = isl_tab_row_unknown;
3721 /* Compute the lexicographic minimum of the set represented by the main
3722 * tableau "tab" within the context "sol->context_tab".
3723 * On entry the sample value of the main tableau is lexicographically
3724 * less than or equal to this lexicographic minimum.
3725 * Pivots are performed until a feasible point is found, which is then
3726 * necessarily equal to the minimum, or until the tableau is found to
3727 * be infeasible. Some pivots may need to be performed for only some
3728 * feasible values of the context tableau. If so, the context tableau
3729 * is split into a part where the pivot is needed and a part where it is not.
3731 * Whenever we enter the main loop, the main tableau is such that no
3732 * "obvious" pivots need to be performed on it, where "obvious" means
3733 * that the given row can be seen to be negative without looking at
3734 * the context tableau. In particular, for non-parametric problems,
3735 * no pivots need to be performed on the main tableau.
3736 * The caller of find_solutions is responsible for making this property
3737 * hold prior to the first iteration of the loop, while restore_lexmin
3738 * is called before every other iteration.
3740 * Inside the main loop, we first examine the signs of the rows of
3741 * the main tableau within the context of the context tableau.
3742 * If we find a row that is always non-positive for all values of
3743 * the parameters satisfying the context tableau and negative for at
3744 * least one value of the parameters, we perform the appropriate pivot
3745 * and start over. An exception is the case where no pivot can be
3746 * performed on the row. In this case, we require that the sign of
3747 * the row is negative for all values of the parameters (rather than just
3748 * non-positive). This special case is handled inside row_sign, which
3749 * will say that the row can have any sign if it determines that it can
3750 * attain both negative and zero values.
3752 * If we can't find a row that always requires a pivot, but we can find
3753 * one or more rows that require a pivot for some values of the parameters
3754 * (i.e., the row can attain both positive and negative signs), then we split
3755 * the context tableau into two parts, one where we force the sign to be
3756 * non-negative and one where we force is to be negative.
3757 * The non-negative part is handled by a recursive call (through find_in_pos).
3758 * Upon returning from this call, we continue with the negative part and
3759 * perform the required pivot.
3761 * If no such rows can be found, all rows are non-negative and we have
3762 * found a (rational) feasible point. If we only wanted a rational point
3763 * then we are done.
3764 * Otherwise, we check if all values of the sample point of the tableau
3765 * are integral for the variables. If so, we have found the minimal
3766 * integral point and we are done.
3767 * If the sample point is not integral, then we need to make a distinction
3768 * based on whether the constant term is non-integral or the coefficients
3769 * of the parameters. Furthermore, in order to decide how to handle
3770 * the non-integrality, we also need to know whether the coefficients
3771 * of the other columns in the tableau are integral. This leads
3772 * to the following table. The first two rows do not correspond
3773 * to a non-integral sample point and are only mentioned for completeness.
3775 * constant parameters other
3777 * int int int |
3778 * int int rat | -> no problem
3780 * rat int int -> fail
3782 * rat int rat -> cut
3784 * int rat rat |
3785 * rat rat rat | -> parametric cut
3787 * int rat int |
3788 * rat rat int | -> split context
3790 * If the parametric constant is completely integral, then there is nothing
3791 * to be done. If the constant term is non-integral, but all the other
3792 * coefficient are integral, then there is nothing that can be done
3793 * and the tableau has no integral solution.
3794 * If, on the other hand, one or more of the other columns have rational
3795 * coefficients, but the parameter coefficients are all integral, then
3796 * we can perform a regular (non-parametric) cut.
3797 * Finally, if there is any parameter coefficient that is non-integral,
3798 * then we need to involve the context tableau. There are two cases here.
3799 * If at least one other column has a rational coefficient, then we
3800 * can perform a parametric cut in the main tableau by adding a new
3801 * integer division in the context tableau.
3802 * If all other columns have integral coefficients, then we need to
3803 * enforce that the rational combination of parameters (c + \sum a_i y_i)/m
3804 * is always integral. We do this by introducing an integer division
3805 * q = floor((c + \sum a_i y_i)/m) and stipulating that its argument should
3806 * always be integral in the context tableau, i.e., m q = c + \sum a_i y_i.
3807 * Since q is expressed in the tableau as
3808 * c + \sum a_i y_i - m q >= 0
3809 * -c - \sum a_i y_i + m q + m - 1 >= 0
3810 * it is sufficient to add the inequality
3811 * -c - \sum a_i y_i + m q >= 0
3812 * In the part of the context where this inequality does not hold, the
3813 * main tableau is marked as being empty.
3815 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab)
3817 struct isl_context *context;
3818 int r;
3820 if (!tab || sol->error)
3821 goto error;
3823 context = sol->context;
3825 if (tab->empty)
3826 goto done;
3827 if (context->op->is_empty(context))
3828 goto done;
3830 for (r = 0; r >= 0 && tab && !tab->empty; r = restore_lexmin(tab)) {
3831 int flags;
3832 int row;
3833 enum isl_tab_row_sign sgn;
3834 int split = -1;
3835 int n_split = 0;
3837 for (row = tab->n_redundant; row < tab->n_row; ++row) {
3838 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
3839 continue;
3840 sgn = row_sign(tab, sol, row);
3841 if (!sgn)
3842 goto error;
3843 tab->row_sign[row] = sgn;
3844 if (sgn == isl_tab_row_any)
3845 n_split++;
3846 if (sgn == isl_tab_row_any && split == -1)
3847 split = row;
3848 if (sgn == isl_tab_row_neg)
3849 break;
3851 if (row < tab->n_row)
3852 continue;
3853 if (split != -1) {
3854 struct isl_vec *ineq;
3855 if (n_split != 1)
3856 split = context->op->best_split(context, tab);
3857 if (split < 0)
3858 goto error;
3859 ineq = get_row_parameter_ineq(tab, split);
3860 if (!ineq)
3861 goto error;
3862 is_strict(ineq);
3863 reset_any_to_unknown(tab);
3864 tab->row_sign[split] = isl_tab_row_pos;
3865 sol_inc_level(sol);
3866 find_in_pos(sol, tab, ineq->el);
3867 tab->row_sign[split] = isl_tab_row_neg;
3868 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3869 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3870 if (!sol->error)
3871 context->op->add_ineq(context, ineq->el, 0, 1);
3872 isl_vec_free(ineq);
3873 if (sol->error)
3874 goto error;
3875 continue;
3877 if (tab->rational)
3878 break;
3879 row = first_non_integer_row(tab, &flags);
3880 if (row < 0)
3881 break;
3882 if (ISL_FL_ISSET(flags, I_PAR)) {
3883 if (ISL_FL_ISSET(flags, I_VAR)) {
3884 if (isl_tab_mark_empty(tab) < 0)
3885 goto error;
3886 break;
3888 row = add_cut(tab, row);
3889 } else if (ISL_FL_ISSET(flags, I_VAR)) {
3890 struct isl_vec *div;
3891 struct isl_vec *ineq;
3892 int d;
3893 div = get_row_split_div(tab, row);
3894 if (!div)
3895 goto error;
3896 d = context->op->get_div(context, tab, div);
3897 isl_vec_free(div);
3898 if (d < 0)
3899 goto error;
3900 ineq = ineq_for_div(context->op->peek_basic_set(context), d);
3901 if (!ineq)
3902 goto error;
3903 sol_inc_level(sol);
3904 no_sol_in_strict(sol, tab, ineq);
3905 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3906 context->op->add_ineq(context, ineq->el, 1, 1);
3907 isl_vec_free(ineq);
3908 if (sol->error || !context->op->is_ok(context))
3909 goto error;
3910 tab = set_row_cst_to_div(tab, row, d);
3911 if (context->op->is_empty(context))
3912 break;
3913 } else
3914 row = add_parametric_cut(tab, row, context);
3915 if (row < 0)
3916 goto error;
3918 if (r < 0)
3919 goto error;
3920 done:
3921 sol_add(sol, tab);
3922 isl_tab_free(tab);
3923 return;
3924 error:
3925 isl_tab_free(tab);
3926 sol->error = 1;
3929 /* Does "sol" contain a pair of partial solutions that could potentially
3930 * be merged?
3932 * We currently only check that "sol" is not in an error state
3933 * and that there are at least two partial solutions of which the final two
3934 * are defined at the same level.
3936 static int sol_has_mergeable_solutions(struct isl_sol *sol)
3938 if (sol->error)
3939 return 0;
3940 if (!sol->partial)
3941 return 0;
3942 if (!sol->partial->next)
3943 return 0;
3944 return sol->partial->level == sol->partial->next->level;
3947 /* Compute the lexicographic minimum of the set represented by the main
3948 * tableau "tab" within the context "sol->context_tab".
3950 * As a preprocessing step, we first transfer all the purely parametric
3951 * equalities from the main tableau to the context tableau, i.e.,
3952 * parameters that have been pivoted to a row.
3953 * These equalities are ignored by the main algorithm, because the
3954 * corresponding rows may not be marked as being non-negative.
3955 * In parts of the context where the added equality does not hold,
3956 * the main tableau is marked as being empty.
3958 * Before we embark on the actual computation, we save a copy
3959 * of the context. When we return, we check if there are any
3960 * partial solutions that can potentially be merged. If so,
3961 * we perform a rollback to the initial state of the context.
3962 * The merging of partial solutions happens inside calls to
3963 * sol_dec_level that are pushed onto the undo stack of the context.
3964 * If there are no partial solutions that can potentially be merged
3965 * then the rollback is skipped as it would just be wasted effort.
3967 static void find_solutions_main(struct isl_sol *sol, struct isl_tab *tab)
3969 int row;
3970 void *saved;
3972 if (!tab)
3973 goto error;
3975 sol->level = 0;
3977 for (row = tab->n_redundant; row < tab->n_row; ++row) {
3978 int p;
3979 struct isl_vec *eq;
3981 if (tab->row_var[row] < 0)
3982 continue;
3983 if (tab->row_var[row] >= tab->n_param &&
3984 tab->row_var[row] < tab->n_var - tab->n_div)
3985 continue;
3986 if (tab->row_var[row] < tab->n_param)
3987 p = tab->row_var[row];
3988 else
3989 p = tab->row_var[row]
3990 + tab->n_param - (tab->n_var - tab->n_div);
3992 eq = isl_vec_alloc(tab->mat->ctx, 1+tab->n_param+tab->n_div);
3993 if (!eq)
3994 goto error;
3995 get_row_parameter_line(tab, row, eq->el);
3996 isl_int_neg(eq->el[1 + p], tab->mat->row[row][0]);
3997 eq = isl_vec_normalize(eq);
3999 sol_inc_level(sol);
4000 no_sol_in_strict(sol, tab, eq);
4002 isl_seq_neg(eq->el, eq->el, eq->size);
4003 sol_inc_level(sol);
4004 no_sol_in_strict(sol, tab, eq);
4005 isl_seq_neg(eq->el, eq->el, eq->size);
4007 sol->context->op->add_eq(sol->context, eq->el, 1, 1);
4009 isl_vec_free(eq);
4011 if (isl_tab_mark_redundant(tab, row) < 0)
4012 goto error;
4014 if (sol->context->op->is_empty(sol->context))
4015 break;
4017 row = tab->n_redundant - 1;
4020 saved = sol->context->op->save(sol->context);
4022 find_solutions(sol, tab);
4024 if (sol_has_mergeable_solutions(sol))
4025 sol->context->op->restore(sol->context, saved);
4026 else
4027 sol->context->op->discard(saved);
4029 sol->level = 0;
4030 sol_pop(sol);
4032 return;
4033 error:
4034 isl_tab_free(tab);
4035 sol->error = 1;
4038 /* Check if integer division "div" of "dom" also occurs in "bmap".
4039 * If so, return its position within the divs.
4040 * If not, return -1.
4042 static int find_context_div(struct isl_basic_map *bmap,
4043 struct isl_basic_set *dom, unsigned div)
4045 int i;
4046 unsigned b_dim = isl_space_dim(bmap->dim, isl_dim_all);
4047 unsigned d_dim = isl_space_dim(dom->dim, isl_dim_all);
4049 if (isl_int_is_zero(dom->div[div][0]))
4050 return -1;
4051 if (isl_seq_first_non_zero(dom->div[div] + 2 + d_dim, dom->n_div) != -1)
4052 return -1;
4054 for (i = 0; i < bmap->n_div; ++i) {
4055 if (isl_int_is_zero(bmap->div[i][0]))
4056 continue;
4057 if (isl_seq_first_non_zero(bmap->div[i] + 2 + d_dim,
4058 (b_dim - d_dim) + bmap->n_div) != -1)
4059 continue;
4060 if (isl_seq_eq(bmap->div[i], dom->div[div], 2 + d_dim))
4061 return i;
4063 return -1;
4066 /* The correspondence between the variables in the main tableau,
4067 * the context tableau, and the input map and domain is as follows.
4068 * The first n_param and the last n_div variables of the main tableau
4069 * form the variables of the context tableau.
4070 * In the basic map, these n_param variables correspond to the
4071 * parameters and the input dimensions. In the domain, they correspond
4072 * to the parameters and the set dimensions.
4073 * The n_div variables correspond to the integer divisions in the domain.
4074 * To ensure that everything lines up, we may need to copy some of the
4075 * integer divisions of the domain to the map. These have to be placed
4076 * in the same order as those in the context and they have to be placed
4077 * after any other integer divisions that the map may have.
4078 * This function performs the required reordering.
4080 static struct isl_basic_map *align_context_divs(struct isl_basic_map *bmap,
4081 struct isl_basic_set *dom)
4083 int i;
4084 int common = 0;
4085 int other;
4087 for (i = 0; i < dom->n_div; ++i)
4088 if (find_context_div(bmap, dom, i) != -1)
4089 common++;
4090 other = bmap->n_div - common;
4091 if (dom->n_div - common > 0) {
4092 bmap = isl_basic_map_extend_space(bmap, isl_space_copy(bmap->dim),
4093 dom->n_div - common, 0, 0);
4094 if (!bmap)
4095 return NULL;
4097 for (i = 0; i < dom->n_div; ++i) {
4098 int pos = find_context_div(bmap, dom, i);
4099 if (pos < 0) {
4100 pos = isl_basic_map_alloc_div(bmap);
4101 if (pos < 0)
4102 goto error;
4103 isl_int_set_si(bmap->div[pos][0], 0);
4105 if (pos != other + i)
4106 isl_basic_map_swap_div(bmap, pos, other + i);
4108 return bmap;
4109 error:
4110 isl_basic_map_free(bmap);
4111 return NULL;
4114 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
4115 * some obvious symmetries.
4117 * We make sure the divs in the domain are properly ordered,
4118 * because they will be added one by one in the given order
4119 * during the construction of the solution map.
4121 static struct isl_sol *basic_map_partial_lexopt_base(
4122 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4123 __isl_give isl_set **empty, int max,
4124 struct isl_sol *(*init)(__isl_keep isl_basic_map *bmap,
4125 __isl_take isl_basic_set *dom, int track_empty, int max))
4127 struct isl_tab *tab;
4128 struct isl_sol *sol = NULL;
4129 struct isl_context *context;
4131 if (dom->n_div) {
4132 dom = isl_basic_set_order_divs(dom);
4133 bmap = align_context_divs(bmap, dom);
4135 sol = init(bmap, dom, !!empty, max);
4136 if (!sol)
4137 goto error;
4139 context = sol->context;
4140 if (isl_basic_set_plain_is_empty(context->op->peek_basic_set(context)))
4141 /* nothing */;
4142 else if (isl_basic_map_plain_is_empty(bmap)) {
4143 if (sol->add_empty)
4144 sol->add_empty(sol,
4145 isl_basic_set_copy(context->op->peek_basic_set(context)));
4146 } else {
4147 tab = tab_for_lexmin(bmap,
4148 context->op->peek_basic_set(context), 1, max);
4149 tab = context->op->detect_nonnegative_parameters(context, tab);
4150 find_solutions_main(sol, tab);
4152 if (sol->error)
4153 goto error;
4155 isl_basic_map_free(bmap);
4156 return sol;
4157 error:
4158 sol_free(sol);
4159 isl_basic_map_free(bmap);
4160 return NULL;
4163 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
4164 * some obvious symmetries.
4166 * We call basic_map_partial_lexopt_base and extract the results.
4168 static __isl_give isl_map *basic_map_partial_lexopt_base_map(
4169 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4170 __isl_give isl_set **empty, int max)
4172 isl_map *result = NULL;
4173 struct isl_sol *sol;
4174 struct isl_sol_map *sol_map;
4176 sol = basic_map_partial_lexopt_base(bmap, dom, empty, max,
4177 &sol_map_init);
4178 if (!sol)
4179 return NULL;
4180 sol_map = (struct isl_sol_map *) sol;
4182 result = isl_map_copy(sol_map->map);
4183 if (empty)
4184 *empty = isl_set_copy(sol_map->empty);
4185 sol_free(&sol_map->sol);
4186 return result;
4189 /* Return a count of the number of occurrences of the "n" first
4190 * variables in the inequality constraints of "bmap".
4192 static __isl_give int *count_occurrences(__isl_keep isl_basic_map *bmap,
4193 int n)
4195 int i, j;
4196 isl_ctx *ctx;
4197 int *occurrences;
4199 if (!bmap)
4200 return NULL;
4201 ctx = isl_basic_map_get_ctx(bmap);
4202 occurrences = isl_calloc_array(ctx, int, n);
4203 if (!occurrences)
4204 return NULL;
4206 for (i = 0; i < bmap->n_ineq; ++i) {
4207 for (j = 0; j < n; ++j) {
4208 if (!isl_int_is_zero(bmap->ineq[i][1 + j]))
4209 occurrences[j]++;
4213 return occurrences;
4216 /* Do all of the "n" variables with non-zero coefficients in "c"
4217 * occur in exactly a single constraint.
4218 * "occurrences" is an array of length "n" containing the number
4219 * of occurrences of each of the variables in the inequality constraints.
4221 static int single_occurrence(int n, isl_int *c, int *occurrences)
4223 int i;
4225 for (i = 0; i < n; ++i) {
4226 if (isl_int_is_zero(c[i]))
4227 continue;
4228 if (occurrences[i] != 1)
4229 return 0;
4232 return 1;
4235 /* Do all of the "n" initial variables that occur in inequality constraint
4236 * "ineq" of "bmap" only occur in that constraint?
4238 static int all_single_occurrence(__isl_keep isl_basic_map *bmap, int ineq,
4239 int n)
4241 int i, j;
4243 for (i = 0; i < n; ++i) {
4244 if (isl_int_is_zero(bmap->ineq[ineq][1 + i]))
4245 continue;
4246 for (j = 0; j < bmap->n_ineq; ++j) {
4247 if (j == ineq)
4248 continue;
4249 if (!isl_int_is_zero(bmap->ineq[j][1 + i]))
4250 return 0;
4254 return 1;
4257 /* Structure used during detection of parallel constraints.
4258 * n_in: number of "input" variables: isl_dim_param + isl_dim_in
4259 * n_out: number of "output" variables: isl_dim_out + isl_dim_div
4260 * val: the coefficients of the output variables
4262 struct isl_constraint_equal_info {
4263 isl_basic_map *bmap;
4264 unsigned n_in;
4265 unsigned n_out;
4266 isl_int *val;
4269 /* Check whether the coefficients of the output variables
4270 * of the constraint in "entry" are equal to info->val.
4272 static int constraint_equal(const void *entry, const void *val)
4274 isl_int **row = (isl_int **)entry;
4275 const struct isl_constraint_equal_info *info = val;
4277 return isl_seq_eq((*row) + 1 + info->n_in, info->val, info->n_out);
4280 /* Check whether "bmap" has a pair of constraints that have
4281 * the same coefficients for the output variables.
4282 * Note that the coefficients of the existentially quantified
4283 * variables need to be zero since the existentially quantified
4284 * of the result are usually not the same as those of the input.
4285 * Furthermore, check that each of the input variables that occur
4286 * in those constraints does not occur in any other constraint.
4287 * If so, return 1 and return the row indices of the two constraints
4288 * in *first and *second.
4290 static int parallel_constraints(__isl_keep isl_basic_map *bmap,
4291 int *first, int *second)
4293 int i;
4294 isl_ctx *ctx;
4295 int *occurrences = NULL;
4296 struct isl_hash_table *table = NULL;
4297 struct isl_hash_table_entry *entry;
4298 struct isl_constraint_equal_info info;
4299 unsigned n_out;
4300 unsigned n_div;
4302 ctx = isl_basic_map_get_ctx(bmap);
4303 table = isl_hash_table_alloc(ctx, bmap->n_ineq);
4304 if (!table)
4305 goto error;
4307 info.n_in = isl_basic_map_dim(bmap, isl_dim_param) +
4308 isl_basic_map_dim(bmap, isl_dim_in);
4309 occurrences = count_occurrences(bmap, info.n_in);
4310 if (info.n_in && !occurrences)
4311 goto error;
4312 info.bmap = bmap;
4313 n_out = isl_basic_map_dim(bmap, isl_dim_out);
4314 n_div = isl_basic_map_dim(bmap, isl_dim_div);
4315 info.n_out = n_out + n_div;
4316 for (i = 0; i < bmap->n_ineq; ++i) {
4317 uint32_t hash;
4319 info.val = bmap->ineq[i] + 1 + info.n_in;
4320 if (isl_seq_first_non_zero(info.val, n_out) < 0)
4321 continue;
4322 if (isl_seq_first_non_zero(info.val + n_out, n_div) >= 0)
4323 continue;
4324 if (!single_occurrence(info.n_in, bmap->ineq[i] + 1,
4325 occurrences))
4326 continue;
4327 hash = isl_seq_get_hash(info.val, info.n_out);
4328 entry = isl_hash_table_find(ctx, table, hash,
4329 constraint_equal, &info, 1);
4330 if (!entry)
4331 goto error;
4332 if (entry->data)
4333 break;
4334 entry->data = &bmap->ineq[i];
4337 if (i < bmap->n_ineq) {
4338 *first = ((isl_int **)entry->data) - bmap->ineq;
4339 *second = i;
4342 isl_hash_table_free(ctx, table);
4343 free(occurrences);
4345 return i < bmap->n_ineq;
4346 error:
4347 isl_hash_table_free(ctx, table);
4348 free(occurrences);
4349 return -1;
4352 /* Given a set of upper bounds in "var", add constraints to "bset"
4353 * that make the i-th bound smallest.
4355 * In particular, if there are n bounds b_i, then add the constraints
4357 * b_i <= b_j for j > i
4358 * b_i < b_j for j < i
4360 static __isl_give isl_basic_set *select_minimum(__isl_take isl_basic_set *bset,
4361 __isl_keep isl_mat *var, int i)
4363 isl_ctx *ctx;
4364 int j, k;
4366 ctx = isl_mat_get_ctx(var);
4368 for (j = 0; j < var->n_row; ++j) {
4369 if (j == i)
4370 continue;
4371 k = isl_basic_set_alloc_inequality(bset);
4372 if (k < 0)
4373 goto error;
4374 isl_seq_combine(bset->ineq[k], ctx->one, var->row[j],
4375 ctx->negone, var->row[i], var->n_col);
4376 isl_int_set_si(bset->ineq[k][var->n_col], 0);
4377 if (j < i)
4378 isl_int_sub_ui(bset->ineq[k][0], bset->ineq[k][0], 1);
4381 bset = isl_basic_set_finalize(bset);
4383 return bset;
4384 error:
4385 isl_basic_set_free(bset);
4386 return NULL;
4389 /* Given a set of upper bounds on the last "input" variable m,
4390 * construct a set that assigns the minimal upper bound to m, i.e.,
4391 * construct a set that divides the space into cells where one
4392 * of the upper bounds is smaller than all the others and assign
4393 * this upper bound to m.
4395 * In particular, if there are n bounds b_i, then the result
4396 * consists of n basic sets, each one of the form
4398 * m = b_i
4399 * b_i <= b_j for j > i
4400 * b_i < b_j for j < i
4402 static __isl_give isl_set *set_minimum(__isl_take isl_space *dim,
4403 __isl_take isl_mat *var)
4405 int i, k;
4406 isl_basic_set *bset = NULL;
4407 isl_set *set = NULL;
4409 if (!dim || !var)
4410 goto error;
4412 set = isl_set_alloc_space(isl_space_copy(dim),
4413 var->n_row, ISL_SET_DISJOINT);
4415 for (i = 0; i < var->n_row; ++i) {
4416 bset = isl_basic_set_alloc_space(isl_space_copy(dim), 0,
4417 1, var->n_row - 1);
4418 k = isl_basic_set_alloc_equality(bset);
4419 if (k < 0)
4420 goto error;
4421 isl_seq_cpy(bset->eq[k], var->row[i], var->n_col);
4422 isl_int_set_si(bset->eq[k][var->n_col], -1);
4423 bset = select_minimum(bset, var, i);
4424 set = isl_set_add_basic_set(set, bset);
4427 isl_space_free(dim);
4428 isl_mat_free(var);
4429 return set;
4430 error:
4431 isl_basic_set_free(bset);
4432 isl_set_free(set);
4433 isl_space_free(dim);
4434 isl_mat_free(var);
4435 return NULL;
4438 /* Given that the last input variable of "bmap" represents the minimum
4439 * of the bounds in "cst", check whether we need to split the domain
4440 * based on which bound attains the minimum.
4442 * A split is needed when the minimum appears in an integer division
4443 * or in an equality. Otherwise, it is only needed if it appears in
4444 * an upper bound that is different from the upper bounds on which it
4445 * is defined.
4447 static int need_split_basic_map(__isl_keep isl_basic_map *bmap,
4448 __isl_keep isl_mat *cst)
4450 int i, j;
4451 unsigned total;
4452 unsigned pos;
4454 pos = cst->n_col - 1;
4455 total = isl_basic_map_dim(bmap, isl_dim_all);
4457 for (i = 0; i < bmap->n_div; ++i)
4458 if (!isl_int_is_zero(bmap->div[i][2 + pos]))
4459 return 1;
4461 for (i = 0; i < bmap->n_eq; ++i)
4462 if (!isl_int_is_zero(bmap->eq[i][1 + pos]))
4463 return 1;
4465 for (i = 0; i < bmap->n_ineq; ++i) {
4466 if (isl_int_is_nonneg(bmap->ineq[i][1 + pos]))
4467 continue;
4468 if (!isl_int_is_negone(bmap->ineq[i][1 + pos]))
4469 return 1;
4470 if (isl_seq_first_non_zero(bmap->ineq[i] + 1 + pos + 1,
4471 total - pos - 1) >= 0)
4472 return 1;
4474 for (j = 0; j < cst->n_row; ++j)
4475 if (isl_seq_eq(bmap->ineq[i], cst->row[j], cst->n_col))
4476 break;
4477 if (j >= cst->n_row)
4478 return 1;
4481 return 0;
4484 /* Given that the last set variable of "bset" represents the minimum
4485 * of the bounds in "cst", check whether we need to split the domain
4486 * based on which bound attains the minimum.
4488 * We simply call need_split_basic_map here. This is safe because
4489 * the position of the minimum is computed from "cst" and not
4490 * from "bmap".
4492 static int need_split_basic_set(__isl_keep isl_basic_set *bset,
4493 __isl_keep isl_mat *cst)
4495 return need_split_basic_map((isl_basic_map *)bset, cst);
4498 /* Given that the last set variable of "set" represents the minimum
4499 * of the bounds in "cst", check whether we need to split the domain
4500 * based on which bound attains the minimum.
4502 static int need_split_set(__isl_keep isl_set *set, __isl_keep isl_mat *cst)
4504 int i;
4506 for (i = 0; i < set->n; ++i)
4507 if (need_split_basic_set(set->p[i], cst))
4508 return 1;
4510 return 0;
4513 /* Given a set of which the last set variable is the minimum
4514 * of the bounds in "cst", split each basic set in the set
4515 * in pieces where one of the bounds is (strictly) smaller than the others.
4516 * This subdivision is given in "min_expr".
4517 * The variable is subsequently projected out.
4519 * We only do the split when it is needed.
4520 * For example if the last input variable m = min(a,b) and the only
4521 * constraints in the given basic set are lower bounds on m,
4522 * i.e., l <= m = min(a,b), then we can simply project out m
4523 * to obtain l <= a and l <= b, without having to split on whether
4524 * m is equal to a or b.
4526 static __isl_give isl_set *split(__isl_take isl_set *empty,
4527 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4529 int n_in;
4530 int i;
4531 isl_space *dim;
4532 isl_set *res;
4534 if (!empty || !min_expr || !cst)
4535 goto error;
4537 n_in = isl_set_dim(empty, isl_dim_set);
4538 dim = isl_set_get_space(empty);
4539 dim = isl_space_drop_dims(dim, isl_dim_set, n_in - 1, 1);
4540 res = isl_set_empty(dim);
4542 for (i = 0; i < empty->n; ++i) {
4543 isl_set *set;
4545 set = isl_set_from_basic_set(isl_basic_set_copy(empty->p[i]));
4546 if (need_split_basic_set(empty->p[i], cst))
4547 set = isl_set_intersect(set, isl_set_copy(min_expr));
4548 set = isl_set_remove_dims(set, isl_dim_set, n_in - 1, 1);
4550 res = isl_set_union_disjoint(res, set);
4553 isl_set_free(empty);
4554 isl_set_free(min_expr);
4555 isl_mat_free(cst);
4556 return res;
4557 error:
4558 isl_set_free(empty);
4559 isl_set_free(min_expr);
4560 isl_mat_free(cst);
4561 return NULL;
4564 /* Given a map of which the last input variable is the minimum
4565 * of the bounds in "cst", split each basic set in the set
4566 * in pieces where one of the bounds is (strictly) smaller than the others.
4567 * This subdivision is given in "min_expr".
4568 * The variable is subsequently projected out.
4570 * The implementation is essentially the same as that of "split".
4572 static __isl_give isl_map *split_domain(__isl_take isl_map *opt,
4573 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4575 int n_in;
4576 int i;
4577 isl_space *dim;
4578 isl_map *res;
4580 if (!opt || !min_expr || !cst)
4581 goto error;
4583 n_in = isl_map_dim(opt, isl_dim_in);
4584 dim = isl_map_get_space(opt);
4585 dim = isl_space_drop_dims(dim, isl_dim_in, n_in - 1, 1);
4586 res = isl_map_empty(dim);
4588 for (i = 0; i < opt->n; ++i) {
4589 isl_map *map;
4591 map = isl_map_from_basic_map(isl_basic_map_copy(opt->p[i]));
4592 if (need_split_basic_map(opt->p[i], cst))
4593 map = isl_map_intersect_domain(map,
4594 isl_set_copy(min_expr));
4595 map = isl_map_remove_dims(map, isl_dim_in, n_in - 1, 1);
4597 res = isl_map_union_disjoint(res, map);
4600 isl_map_free(opt);
4601 isl_set_free(min_expr);
4602 isl_mat_free(cst);
4603 return res;
4604 error:
4605 isl_map_free(opt);
4606 isl_set_free(min_expr);
4607 isl_mat_free(cst);
4608 return NULL;
4611 static __isl_give isl_map *basic_map_partial_lexopt(
4612 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4613 __isl_give isl_set **empty, int max);
4615 union isl_lex_res {
4616 void *p;
4617 isl_map *map;
4618 isl_pw_multi_aff *pma;
4621 /* This function is called from basic_map_partial_lexopt_symm.
4622 * The last variable of "bmap" and "dom" corresponds to the minimum
4623 * of the bounds in "cst". "map_space" is the space of the original
4624 * input relation (of basic_map_partial_lexopt_symm) and "set_space"
4625 * is the space of the original domain.
4627 * We recursively call basic_map_partial_lexopt and then plug in
4628 * the definition of the minimum in the result.
4630 static __isl_give union isl_lex_res basic_map_partial_lexopt_symm_map_core(
4631 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4632 __isl_give isl_set **empty, int max, __isl_take isl_mat *cst,
4633 __isl_take isl_space *map_space, __isl_take isl_space *set_space)
4635 isl_map *opt;
4636 isl_set *min_expr;
4637 union isl_lex_res res;
4639 min_expr = set_minimum(isl_basic_set_get_space(dom), isl_mat_copy(cst));
4641 opt = basic_map_partial_lexopt(bmap, dom, empty, max);
4643 if (empty) {
4644 *empty = split(*empty,
4645 isl_set_copy(min_expr), isl_mat_copy(cst));
4646 *empty = isl_set_reset_space(*empty, set_space);
4649 opt = split_domain(opt, min_expr, cst);
4650 opt = isl_map_reset_space(opt, map_space);
4652 res.map = opt;
4653 return res;
4656 /* Given a basic map with at least two parallel constraints (as found
4657 * by the function parallel_constraints), first look for more constraints
4658 * parallel to the two constraint and replace the found list of parallel
4659 * constraints by a single constraint with as "input" part the minimum
4660 * of the input parts of the list of constraints. Then, recursively call
4661 * basic_map_partial_lexopt (possibly finding more parallel constraints)
4662 * and plug in the definition of the minimum in the result.
4664 * As in parallel_constraints, only inequality constraints that only
4665 * involve input variables that do not occur in any other inequality
4666 * constraints are considered.
4668 * More specifically, given a set of constraints
4670 * a x + b_i(p) >= 0
4672 * Replace this set by a single constraint
4674 * a x + u >= 0
4676 * with u a new parameter with constraints
4678 * u <= b_i(p)
4680 * Any solution to the new system is also a solution for the original system
4681 * since
4683 * a x >= -u >= -b_i(p)
4685 * Moreover, m = min_i(b_i(p)) satisfies the constraints on u and can
4686 * therefore be plugged into the solution.
4688 static union isl_lex_res basic_map_partial_lexopt_symm(
4689 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4690 __isl_give isl_set **empty, int max, int first, int second,
4691 __isl_give union isl_lex_res (*core)(__isl_take isl_basic_map *bmap,
4692 __isl_take isl_basic_set *dom,
4693 __isl_give isl_set **empty,
4694 int max, __isl_take isl_mat *cst,
4695 __isl_take isl_space *map_space,
4696 __isl_take isl_space *set_space))
4698 int i, n, k;
4699 int *list = NULL;
4700 unsigned n_in, n_out, n_div;
4701 isl_ctx *ctx;
4702 isl_vec *var = NULL;
4703 isl_mat *cst = NULL;
4704 isl_space *map_space, *set_space;
4705 union isl_lex_res res;
4707 map_space = isl_basic_map_get_space(bmap);
4708 set_space = empty ? isl_basic_set_get_space(dom) : NULL;
4710 n_in = isl_basic_map_dim(bmap, isl_dim_param) +
4711 isl_basic_map_dim(bmap, isl_dim_in);
4712 n_out = isl_basic_map_dim(bmap, isl_dim_all) - n_in;
4714 ctx = isl_basic_map_get_ctx(bmap);
4715 list = isl_alloc_array(ctx, int, bmap->n_ineq);
4716 var = isl_vec_alloc(ctx, n_out);
4717 if ((bmap->n_ineq && !list) || (n_out && !var))
4718 goto error;
4720 list[0] = first;
4721 list[1] = second;
4722 isl_seq_cpy(var->el, bmap->ineq[first] + 1 + n_in, n_out);
4723 for (i = second + 1, n = 2; i < bmap->n_ineq; ++i) {
4724 if (isl_seq_eq(var->el, bmap->ineq[i] + 1 + n_in, n_out) &&
4725 all_single_occurrence(bmap, i, n_in))
4726 list[n++] = i;
4729 cst = isl_mat_alloc(ctx, n, 1 + n_in);
4730 if (!cst)
4731 goto error;
4733 for (i = 0; i < n; ++i)
4734 isl_seq_cpy(cst->row[i], bmap->ineq[list[i]], 1 + n_in);
4736 bmap = isl_basic_map_cow(bmap);
4737 if (!bmap)
4738 goto error;
4739 for (i = n - 1; i >= 0; --i)
4740 if (isl_basic_map_drop_inequality(bmap, list[i]) < 0)
4741 goto error;
4743 bmap = isl_basic_map_add_dims(bmap, isl_dim_in, 1);
4744 bmap = isl_basic_map_extend_constraints(bmap, 0, 1);
4745 k = isl_basic_map_alloc_inequality(bmap);
4746 if (k < 0)
4747 goto error;
4748 isl_seq_clr(bmap->ineq[k], 1 + n_in);
4749 isl_int_set_si(bmap->ineq[k][1 + n_in], 1);
4750 isl_seq_cpy(bmap->ineq[k] + 1 + n_in + 1, var->el, n_out);
4751 bmap = isl_basic_map_finalize(bmap);
4753 n_div = isl_basic_set_dim(dom, isl_dim_div);
4754 dom = isl_basic_set_add_dims(dom, isl_dim_set, 1);
4755 dom = isl_basic_set_extend_constraints(dom, 0, n);
4756 for (i = 0; i < n; ++i) {
4757 k = isl_basic_set_alloc_inequality(dom);
4758 if (k < 0)
4759 goto error;
4760 isl_seq_cpy(dom->ineq[k], cst->row[i], 1 + n_in);
4761 isl_int_set_si(dom->ineq[k][1 + n_in], -1);
4762 isl_seq_clr(dom->ineq[k] + 1 + n_in + 1, n_div);
4765 isl_vec_free(var);
4766 free(list);
4768 return core(bmap, dom, empty, max, cst, map_space, set_space);
4769 error:
4770 isl_space_free(map_space);
4771 isl_space_free(set_space);
4772 isl_mat_free(cst);
4773 isl_vec_free(var);
4774 free(list);
4775 isl_basic_set_free(dom);
4776 isl_basic_map_free(bmap);
4777 res.p = NULL;
4778 return res;
4781 static __isl_give isl_map *basic_map_partial_lexopt_symm_map(
4782 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4783 __isl_give isl_set **empty, int max, int first, int second)
4785 return basic_map_partial_lexopt_symm(bmap, dom, empty, max,
4786 first, second, &basic_map_partial_lexopt_symm_map_core).map;
4789 /* Recursive part of isl_tab_basic_map_partial_lexopt, after detecting
4790 * equalities and removing redundant constraints.
4792 * We first check if there are any parallel constraints (left).
4793 * If not, we are in the base case.
4794 * If there are parallel constraints, we replace them by a single
4795 * constraint in basic_map_partial_lexopt_symm and then call
4796 * this function recursively to look for more parallel constraints.
4798 static __isl_give isl_map *basic_map_partial_lexopt(
4799 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4800 __isl_give isl_set **empty, int max)
4802 int par = 0;
4803 int first, second;
4805 if (!bmap)
4806 goto error;
4808 if (bmap->ctx->opt->pip_symmetry)
4809 par = parallel_constraints(bmap, &first, &second);
4810 if (par < 0)
4811 goto error;
4812 if (!par)
4813 return basic_map_partial_lexopt_base_map(bmap, dom, empty, max);
4815 return basic_map_partial_lexopt_symm_map(bmap, dom, empty, max,
4816 first, second);
4817 error:
4818 isl_basic_set_free(dom);
4819 isl_basic_map_free(bmap);
4820 return NULL;
4823 /* Compute the lexicographic minimum (or maximum if "max" is set)
4824 * of "bmap" over the domain "dom" and return the result as a map.
4825 * If "empty" is not NULL, then *empty is assigned a set that
4826 * contains those parts of the domain where there is no solution.
4827 * If "bmap" is marked as rational (ISL_BASIC_MAP_RATIONAL),
4828 * then we compute the rational optimum. Otherwise, we compute
4829 * the integral optimum.
4831 * We perform some preprocessing. As the PILP solver does not
4832 * handle implicit equalities very well, we first make sure all
4833 * the equalities are explicitly available.
4835 * We also add context constraints to the basic map and remove
4836 * redundant constraints. This is only needed because of the
4837 * way we handle simple symmetries. In particular, we currently look
4838 * for symmetries on the constraints, before we set up the main tableau.
4839 * It is then no good to look for symmetries on possibly redundant constraints.
4841 struct isl_map *isl_tab_basic_map_partial_lexopt(
4842 struct isl_basic_map *bmap, struct isl_basic_set *dom,
4843 struct isl_set **empty, int max)
4845 if (empty)
4846 *empty = NULL;
4847 if (!bmap || !dom)
4848 goto error;
4850 isl_assert(bmap->ctx,
4851 isl_basic_map_compatible_domain(bmap, dom), goto error);
4853 if (isl_basic_set_dim(dom, isl_dim_all) == 0)
4854 return basic_map_partial_lexopt(bmap, dom, empty, max);
4856 bmap = isl_basic_map_intersect_domain(bmap, isl_basic_set_copy(dom));
4857 bmap = isl_basic_map_detect_equalities(bmap);
4858 bmap = isl_basic_map_remove_redundancies(bmap);
4860 return basic_map_partial_lexopt(bmap, dom, empty, max);
4861 error:
4862 isl_basic_set_free(dom);
4863 isl_basic_map_free(bmap);
4864 return NULL;
4867 struct isl_sol_for {
4868 struct isl_sol sol;
4869 int (*fn)(__isl_take isl_basic_set *dom,
4870 __isl_take isl_aff_list *list, void *user);
4871 void *user;
4874 static void sol_for_free(struct isl_sol_for *sol_for)
4876 if (!sol_for)
4877 return;
4878 if (sol_for->sol.context)
4879 sol_for->sol.context->op->free(sol_for->sol.context);
4880 free(sol_for);
4883 static void sol_for_free_wrap(struct isl_sol *sol)
4885 sol_for_free((struct isl_sol_for *)sol);
4888 /* Add the solution identified by the tableau and the context tableau.
4890 * See documentation of sol_add for more details.
4892 * Instead of constructing a basic map, this function calls a user
4893 * defined function with the current context as a basic set and
4894 * a list of affine expressions representing the relation between
4895 * the input and output. The space over which the affine expressions
4896 * are defined is the same as that of the domain. The number of
4897 * affine expressions in the list is equal to the number of output variables.
4899 static void sol_for_add(struct isl_sol_for *sol,
4900 struct isl_basic_set *dom, struct isl_mat *M)
4902 int i;
4903 isl_ctx *ctx;
4904 isl_local_space *ls;
4905 isl_aff *aff;
4906 isl_aff_list *list;
4908 if (sol->sol.error || !dom || !M)
4909 goto error;
4911 ctx = isl_basic_set_get_ctx(dom);
4912 ls = isl_basic_set_get_local_space(dom);
4913 list = isl_aff_list_alloc(ctx, M->n_row - 1);
4914 for (i = 1; i < M->n_row; ++i) {
4915 aff = isl_aff_alloc(isl_local_space_copy(ls));
4916 if (aff) {
4917 isl_int_set(aff->v->el[0], M->row[0][0]);
4918 isl_seq_cpy(aff->v->el + 1, M->row[i], M->n_col);
4920 aff = isl_aff_normalize(aff);
4921 list = isl_aff_list_add(list, aff);
4923 isl_local_space_free(ls);
4925 dom = isl_basic_set_finalize(dom);
4927 if (sol->fn(isl_basic_set_copy(dom), list, sol->user) < 0)
4928 goto error;
4930 isl_basic_set_free(dom);
4931 isl_mat_free(M);
4932 return;
4933 error:
4934 isl_basic_set_free(dom);
4935 isl_mat_free(M);
4936 sol->sol.error = 1;
4939 static void sol_for_add_wrap(struct isl_sol *sol,
4940 struct isl_basic_set *dom, struct isl_mat *M)
4942 sol_for_add((struct isl_sol_for *)sol, dom, M);
4945 static struct isl_sol_for *sol_for_init(struct isl_basic_map *bmap, int max,
4946 int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_aff_list *list,
4947 void *user),
4948 void *user)
4950 struct isl_sol_for *sol_for = NULL;
4951 isl_space *dom_dim;
4952 struct isl_basic_set *dom = NULL;
4954 sol_for = isl_calloc_type(bmap->ctx, struct isl_sol_for);
4955 if (!sol_for)
4956 goto error;
4958 dom_dim = isl_space_domain(isl_space_copy(bmap->dim));
4959 dom = isl_basic_set_universe(dom_dim);
4961 sol_for->sol.rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
4962 sol_for->sol.dec_level.callback.run = &sol_dec_level_wrap;
4963 sol_for->sol.dec_level.sol = &sol_for->sol;
4964 sol_for->fn = fn;
4965 sol_for->user = user;
4966 sol_for->sol.max = max;
4967 sol_for->sol.n_out = isl_basic_map_dim(bmap, isl_dim_out);
4968 sol_for->sol.add = &sol_for_add_wrap;
4969 sol_for->sol.add_empty = NULL;
4970 sol_for->sol.free = &sol_for_free_wrap;
4972 sol_for->sol.context = isl_context_alloc(dom);
4973 if (!sol_for->sol.context)
4974 goto error;
4976 isl_basic_set_free(dom);
4977 return sol_for;
4978 error:
4979 isl_basic_set_free(dom);
4980 sol_for_free(sol_for);
4981 return NULL;
4984 static void sol_for_find_solutions(struct isl_sol_for *sol_for,
4985 struct isl_tab *tab)
4987 find_solutions_main(&sol_for->sol, tab);
4990 int isl_basic_map_foreach_lexopt(__isl_keep isl_basic_map *bmap, int max,
4991 int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_aff_list *list,
4992 void *user),
4993 void *user)
4995 struct isl_sol_for *sol_for = NULL;
4997 bmap = isl_basic_map_copy(bmap);
4998 bmap = isl_basic_map_detect_equalities(bmap);
4999 if (!bmap)
5000 return -1;
5002 sol_for = sol_for_init(bmap, max, fn, user);
5003 if (!sol_for)
5004 goto error;
5006 if (isl_basic_map_plain_is_empty(bmap))
5007 /* nothing */;
5008 else {
5009 struct isl_tab *tab;
5010 struct isl_context *context = sol_for->sol.context;
5011 tab = tab_for_lexmin(bmap,
5012 context->op->peek_basic_set(context), 1, max);
5013 tab = context->op->detect_nonnegative_parameters(context, tab);
5014 sol_for_find_solutions(sol_for, tab);
5015 if (sol_for->sol.error)
5016 goto error;
5019 sol_free(&sol_for->sol);
5020 isl_basic_map_free(bmap);
5021 return 0;
5022 error:
5023 sol_free(&sol_for->sol);
5024 isl_basic_map_free(bmap);
5025 return -1;
5028 int isl_basic_set_foreach_lexopt(__isl_keep isl_basic_set *bset, int max,
5029 int (*fn)(__isl_take isl_basic_set *dom, __isl_take isl_aff_list *list,
5030 void *user),
5031 void *user)
5033 return isl_basic_map_foreach_lexopt(bset, max, fn, user);
5036 /* Check if the given sequence of len variables starting at pos
5037 * represents a trivial (i.e., zero) solution.
5038 * The variables are assumed to be non-negative and to come in pairs,
5039 * with each pair representing a variable of unrestricted sign.
5040 * The solution is trivial if each such pair in the sequence consists
5041 * of two identical values, meaning that the variable being represented
5042 * has value zero.
5044 static int region_is_trivial(struct isl_tab *tab, int pos, int len)
5046 int i;
5048 if (len == 0)
5049 return 0;
5051 for (i = 0; i < len; i += 2) {
5052 int neg_row;
5053 int pos_row;
5055 neg_row = tab->var[pos + i].is_row ?
5056 tab->var[pos + i].index : -1;
5057 pos_row = tab->var[pos + i + 1].is_row ?
5058 tab->var[pos + i + 1].index : -1;
5060 if ((neg_row < 0 ||
5061 isl_int_is_zero(tab->mat->row[neg_row][1])) &&
5062 (pos_row < 0 ||
5063 isl_int_is_zero(tab->mat->row[pos_row][1])))
5064 continue;
5066 if (neg_row < 0 || pos_row < 0)
5067 return 0;
5068 if (isl_int_ne(tab->mat->row[neg_row][1],
5069 tab->mat->row[pos_row][1]))
5070 return 0;
5073 return 1;
5076 /* Return the index of the first trivial region or -1 if all regions
5077 * are non-trivial.
5079 static int first_trivial_region(struct isl_tab *tab,
5080 int n_region, struct isl_region *region)
5082 int i;
5084 for (i = 0; i < n_region; ++i) {
5085 if (region_is_trivial(tab, region[i].pos, region[i].len))
5086 return i;
5089 return -1;
5092 /* Check if the solution is optimal, i.e., whether the first
5093 * n_op entries are zero.
5095 static int is_optimal(__isl_keep isl_vec *sol, int n_op)
5097 int i;
5099 for (i = 0; i < n_op; ++i)
5100 if (!isl_int_is_zero(sol->el[1 + i]))
5101 return 0;
5102 return 1;
5105 /* Add constraints to "tab" that ensure that any solution is significantly
5106 * better than that represented by "sol". That is, find the first
5107 * relevant (within first n_op) non-zero coefficient and force it (along
5108 * with all previous coefficients) to be zero.
5109 * If the solution is already optimal (all relevant coefficients are zero),
5110 * then just mark the table as empty.
5112 * This function assumes that at least 2 * n_op more rows and at least
5113 * 2 * n_op more elements in the constraint array are available in the tableau.
5115 static int force_better_solution(struct isl_tab *tab,
5116 __isl_keep isl_vec *sol, int n_op)
5118 int i;
5119 isl_ctx *ctx;
5120 isl_vec *v = NULL;
5122 if (!sol)
5123 return -1;
5125 for (i = 0; i < n_op; ++i)
5126 if (!isl_int_is_zero(sol->el[1 + i]))
5127 break;
5129 if (i == n_op) {
5130 if (isl_tab_mark_empty(tab) < 0)
5131 return -1;
5132 return 0;
5135 ctx = isl_vec_get_ctx(sol);
5136 v = isl_vec_alloc(ctx, 1 + tab->n_var);
5137 if (!v)
5138 return -1;
5140 for (; i >= 0; --i) {
5141 v = isl_vec_clr(v);
5142 isl_int_set_si(v->el[1 + i], -1);
5143 if (add_lexmin_eq(tab, v->el) < 0)
5144 goto error;
5147 isl_vec_free(v);
5148 return 0;
5149 error:
5150 isl_vec_free(v);
5151 return -1;
5154 struct isl_trivial {
5155 int update;
5156 int region;
5157 int side;
5158 struct isl_tab_undo *snap;
5161 /* Return the lexicographically smallest non-trivial solution of the
5162 * given ILP problem.
5164 * All variables are assumed to be non-negative.
5166 * n_op is the number of initial coordinates to optimize.
5167 * That is, once a solution has been found, we will only continue looking
5168 * for solution that result in significantly better values for those
5169 * initial coordinates. That is, we only continue looking for solutions
5170 * that increase the number of initial zeros in this sequence.
5172 * A solution is non-trivial, if it is non-trivial on each of the
5173 * specified regions. Each region represents a sequence of pairs
5174 * of variables. A solution is non-trivial on such a region if
5175 * at least one of these pairs consists of different values, i.e.,
5176 * such that the non-negative variable represented by the pair is non-zero.
5178 * Whenever a conflict is encountered, all constraints involved are
5179 * reported to the caller through a call to "conflict".
5181 * We perform a simple branch-and-bound backtracking search.
5182 * Each level in the search represents initially trivial region that is forced
5183 * to be non-trivial.
5184 * At each level we consider n cases, where n is the length of the region.
5185 * In terms of the n/2 variables of unrestricted signs being encoded by
5186 * the region, we consider the cases
5187 * x_0 >= 1
5188 * x_0 <= -1
5189 * x_0 = 0 and x_1 >= 1
5190 * x_0 = 0 and x_1 <= -1
5191 * x_0 = 0 and x_1 = 0 and x_2 >= 1
5192 * x_0 = 0 and x_1 = 0 and x_2 <= -1
5193 * ...
5194 * The cases are considered in this order, assuming that each pair
5195 * x_i_a x_i_b represents the value x_i_b - x_i_a.
5196 * That is, x_0 >= 1 is enforced by adding the constraint
5197 * x_0_b - x_0_a >= 1
5199 __isl_give isl_vec *isl_tab_basic_set_non_trivial_lexmin(
5200 __isl_take isl_basic_set *bset, int n_op, int n_region,
5201 struct isl_region *region,
5202 int (*conflict)(int con, void *user), void *user)
5204 int i, j;
5205 int r;
5206 isl_ctx *ctx;
5207 isl_vec *v = NULL;
5208 isl_vec *sol = NULL;
5209 struct isl_tab *tab;
5210 struct isl_trivial *triv = NULL;
5211 int level, init;
5213 if (!bset)
5214 return NULL;
5216 ctx = isl_basic_set_get_ctx(bset);
5217 sol = isl_vec_alloc(ctx, 0);
5219 tab = tab_for_lexmin(bset, NULL, 0, 0);
5220 if (!tab)
5221 goto error;
5222 tab->conflict = conflict;
5223 tab->conflict_user = user;
5225 v = isl_vec_alloc(ctx, 1 + tab->n_var);
5226 triv = isl_calloc_array(ctx, struct isl_trivial, n_region);
5227 if (!v || (n_region && !triv))
5228 goto error;
5230 level = 0;
5231 init = 1;
5233 while (level >= 0) {
5234 int side, base;
5236 if (init) {
5237 tab = cut_to_integer_lexmin(tab, CUT_ONE);
5238 if (!tab)
5239 goto error;
5240 if (tab->empty)
5241 goto backtrack;
5242 r = first_trivial_region(tab, n_region, region);
5243 if (r < 0) {
5244 for (i = 0; i < level; ++i)
5245 triv[i].update = 1;
5246 isl_vec_free(sol);
5247 sol = isl_tab_get_sample_value(tab);
5248 if (!sol)
5249 goto error;
5250 if (is_optimal(sol, n_op))
5251 break;
5252 goto backtrack;
5254 if (level >= n_region)
5255 isl_die(ctx, isl_error_internal,
5256 "nesting level too deep", goto error);
5257 if (isl_tab_extend_cons(tab,
5258 2 * region[r].len + 2 * n_op) < 0)
5259 goto error;
5260 triv[level].region = r;
5261 triv[level].side = 0;
5264 r = triv[level].region;
5265 side = triv[level].side;
5266 base = 2 * (side/2);
5268 if (side >= region[r].len) {
5269 backtrack:
5270 level--;
5271 init = 0;
5272 if (level >= 0)
5273 if (isl_tab_rollback(tab, triv[level].snap) < 0)
5274 goto error;
5275 continue;
5278 if (triv[level].update) {
5279 if (force_better_solution(tab, sol, n_op) < 0)
5280 goto error;
5281 triv[level].update = 0;
5284 if (side == base && base >= 2) {
5285 for (j = base - 2; j < base; ++j) {
5286 v = isl_vec_clr(v);
5287 isl_int_set_si(v->el[1 + region[r].pos + j], 1);
5288 if (add_lexmin_eq(tab, v->el) < 0)
5289 goto error;
5293 triv[level].snap = isl_tab_snap(tab);
5294 if (isl_tab_push_basis(tab) < 0)
5295 goto error;
5297 v = isl_vec_clr(v);
5298 isl_int_set_si(v->el[0], -1);
5299 isl_int_set_si(v->el[1 + region[r].pos + side], -1);
5300 isl_int_set_si(v->el[1 + region[r].pos + (side ^ 1)], 1);
5301 tab = add_lexmin_ineq(tab, v->el);
5303 triv[level].side++;
5304 level++;
5305 init = 1;
5308 free(triv);
5309 isl_vec_free(v);
5310 isl_tab_free(tab);
5311 isl_basic_set_free(bset);
5313 return sol;
5314 error:
5315 free(triv);
5316 isl_vec_free(v);
5317 isl_tab_free(tab);
5318 isl_basic_set_free(bset);
5319 isl_vec_free(sol);
5320 return NULL;
5323 /* Wrapper for a tableau that is used for computing
5324 * the lexicographically smallest rational point of a non-negative set.
5325 * This point is represented by the sample value of "tab",
5326 * unless "tab" is empty.
5328 struct isl_tab_lexmin {
5329 isl_ctx *ctx;
5330 struct isl_tab *tab;
5333 /* Free "tl" and return NULL.
5335 __isl_null isl_tab_lexmin *isl_tab_lexmin_free(__isl_take isl_tab_lexmin *tl)
5337 if (!tl)
5338 return NULL;
5339 isl_ctx_deref(tl->ctx);
5340 isl_tab_free(tl->tab);
5341 free(tl);
5343 return NULL;
5346 /* Construct an isl_tab_lexmin for computing
5347 * the lexicographically smallest rational point in "bset",
5348 * assuming that all variables are non-negative.
5350 __isl_give isl_tab_lexmin *isl_tab_lexmin_from_basic_set(
5351 __isl_take isl_basic_set *bset)
5353 isl_ctx *ctx;
5354 isl_tab_lexmin *tl;
5356 if (!bset)
5357 return NULL;
5359 ctx = isl_basic_set_get_ctx(bset);
5360 tl = isl_calloc_type(ctx, struct isl_tab_lexmin);
5361 if (!tl)
5362 goto error;
5363 tl->ctx = ctx;
5364 isl_ctx_ref(ctx);
5365 tl->tab = tab_for_lexmin(bset, NULL, 0, 0);
5366 isl_basic_set_free(bset);
5367 if (!tl->tab)
5368 return isl_tab_lexmin_free(tl);
5369 return tl;
5370 error:
5371 isl_basic_set_free(bset);
5372 isl_tab_lexmin_free(tl);
5373 return NULL;
5376 /* Return the dimension of the set represented by "tl".
5378 int isl_tab_lexmin_dim(__isl_keep isl_tab_lexmin *tl)
5380 return tl ? tl->tab->n_var : -1;
5383 /* Add the equality with coefficients "eq" to "tl", updating the optimal
5384 * solution if needed.
5385 * The equality is added as two opposite inequality constraints.
5387 __isl_give isl_tab_lexmin *isl_tab_lexmin_add_eq(__isl_take isl_tab_lexmin *tl,
5388 isl_int *eq)
5390 unsigned n_var;
5392 if (!tl || !eq)
5393 return isl_tab_lexmin_free(tl);
5395 if (isl_tab_extend_cons(tl->tab, 2) < 0)
5396 return isl_tab_lexmin_free(tl);
5397 n_var = tl->tab->n_var;
5398 isl_seq_neg(eq, eq, 1 + n_var);
5399 tl->tab = add_lexmin_ineq(tl->tab, eq);
5400 isl_seq_neg(eq, eq, 1 + n_var);
5401 tl->tab = add_lexmin_ineq(tl->tab, eq);
5403 if (!tl->tab)
5404 return isl_tab_lexmin_free(tl);
5406 return tl;
5409 /* Return the lexicographically smallest rational point in the basic set
5410 * from which "tl" was constructed.
5411 * If the original input was empty, then return a zero-length vector.
5413 __isl_give isl_vec *isl_tab_lexmin_get_solution(__isl_keep isl_tab_lexmin *tl)
5415 if (!tl)
5416 return NULL;
5417 if (tl->tab->empty)
5418 return isl_vec_alloc(tl->ctx, 0);
5419 else
5420 return isl_tab_get_sample_value(tl->tab);
5423 /* Return the lexicographically smallest rational point in "bset",
5424 * assuming that all variables are non-negative.
5425 * If "bset" is empty, then return a zero-length vector.
5427 __isl_give isl_vec *isl_tab_basic_set_non_neg_lexmin(
5428 __isl_take isl_basic_set *bset)
5430 isl_tab_lexmin *tl;
5431 isl_vec *sol;
5433 tl = isl_tab_lexmin_from_basic_set(bset);
5434 sol = isl_tab_lexmin_get_solution(tl);
5435 isl_tab_lexmin_free(tl);
5436 return sol;
5439 struct isl_sol_pma {
5440 struct isl_sol sol;
5441 isl_pw_multi_aff *pma;
5442 isl_set *empty;
5445 static void sol_pma_free(struct isl_sol_pma *sol_pma)
5447 if (!sol_pma)
5448 return;
5449 if (sol_pma->sol.context)
5450 sol_pma->sol.context->op->free(sol_pma->sol.context);
5451 isl_pw_multi_aff_free(sol_pma->pma);
5452 isl_set_free(sol_pma->empty);
5453 free(sol_pma);
5456 /* This function is called for parts of the context where there is
5457 * no solution, with "bset" corresponding to the context tableau.
5458 * Simply add the basic set to the set "empty".
5460 static void sol_pma_add_empty(struct isl_sol_pma *sol,
5461 __isl_take isl_basic_set *bset)
5463 if (!bset || !sol->empty)
5464 goto error;
5466 sol->empty = isl_set_grow(sol->empty, 1);
5467 bset = isl_basic_set_simplify(bset);
5468 bset = isl_basic_set_finalize(bset);
5469 sol->empty = isl_set_add_basic_set(sol->empty, bset);
5470 if (!sol->empty)
5471 sol->sol.error = 1;
5472 return;
5473 error:
5474 isl_basic_set_free(bset);
5475 sol->sol.error = 1;
5478 /* Return the equality constraint in "bset" that defines existentially
5479 * quantified variable "pos" in terms of earlier dimensions.
5480 * The equality constraint is guaranteed to exist by the caller.
5481 * If "c" is not NULL, then it is the result of a previous call
5482 * to this function for the same variable, so simply return the input "c"
5483 * in that case.
5485 static __isl_give isl_constraint *get_equality(__isl_keep isl_basic_set *bset,
5486 int pos, __isl_take isl_constraint *c)
5488 int r;
5490 if (c)
5491 return c;
5492 r = isl_basic_set_has_defining_equality(bset, isl_dim_div, pos, &c);
5493 if (r < 0)
5494 return NULL;
5495 if (!r)
5496 isl_die(isl_basic_set_get_ctx(bset), isl_error_internal,
5497 "unexpected missing equality", return NULL);
5498 return c;
5501 /* Given a set "dom", of which only the first "n_known" existentially
5502 * quantified variables have a known explicit representation, and
5503 * a matrix "M", the rows of which are defined in terms of the dimensions
5504 * of "dom", eliminate all references to the existentially quantified
5505 * variables without a known explicit representation from "M"
5506 * by exploiting the equality constraints of "dom".
5508 * In particular, for each of those existentially quantified variables,
5509 * if there are non-zero entries in the corresponding column of "M",
5510 * then look for an equality constraint of "dom" that defines that variable
5511 * in terms of earlier variables and use it to clear the entries.
5513 * In particular, if the equality is of the form
5515 * f() + a alpha = 0
5517 * while the matrix entry is b/d (with d the global denominator of "M"),
5518 * then first scale the matrix such that the entry becomes b'/d' with
5519 * b' a multiple of a. Do this by multiplying the entire matrix
5520 * by abs(a/gcd(a,b)). Then subtract the equality multiplied by b'/a
5521 * from the row of "M" to clear the entry.
5523 static __isl_give isl_mat *eliminate_unknown_divs(__isl_take isl_mat *M,
5524 __isl_keep isl_basic_set *dom, int n_known)
5526 int i, j, n_div, off;
5527 isl_int t;
5528 isl_constraint *c = NULL;
5530 if (!M)
5531 return NULL;
5533 n_div = isl_basic_set_dim(dom, isl_dim_div);
5534 off = M->n_col - n_div;
5536 isl_int_init(t);
5537 for (i = n_div - 1; i >= n_known; --i) {
5538 for (j = 1; j < M->n_row; ++j) {
5539 if (isl_int_is_zero(M->row[j][off + i]))
5540 continue;
5541 c = get_equality(dom, i, c);
5542 if (!c)
5543 goto error;
5544 isl_int_gcd(t, M->row[j][off + i], c->v->el[off + i]);
5545 isl_int_divexact(t, c->v->el[off + i], t);
5546 isl_int_abs(t, t);
5547 M = isl_mat_scale(M, t);
5548 M = isl_mat_cow(M);
5549 if (!M)
5550 goto error;
5551 isl_int_divexact(t,
5552 M->row[j][off + i], c->v->el[off + i]);
5553 isl_seq_submul(M->row[j], t, c->v->el, M->n_col);
5555 c = isl_constraint_free(c);
5557 isl_int_clear(t);
5559 return M;
5560 error:
5561 isl_int_clear(t);
5562 isl_constraint_free(c);
5563 isl_mat_free(M);
5564 return NULL;
5567 /* Return the index of the last known div of "bset" after "start" and
5568 * up to (but not including) "end".
5569 * Return "start" if there is no such known div.
5571 static int last_known_div_after(__isl_keep isl_basic_set *bset,
5572 int start, int end)
5574 for (end = end - 1; end > start; --end) {
5575 if (isl_basic_set_div_is_known(bset, end))
5576 return end;
5579 return start;
5582 /* Set the affine expressions in "ma" according to the rows in "M", which
5583 * are defined over the local space "ls".
5584 * The matrix "M" may have extra (zero) columns beyond the number
5585 * of variables in "ls".
5587 static __isl_give isl_multi_aff *set_from_affine_matrix(
5588 __isl_take isl_multi_aff *ma, __isl_take isl_local_space *ls,
5589 __isl_take isl_mat *M)
5591 int i, dim;
5592 isl_aff *aff;
5594 dim = isl_local_space_dim(ls, isl_dim_all);
5595 for (i = 1; i < M->n_row; ++i) {
5596 aff = isl_aff_alloc(isl_local_space_copy(ls));
5597 if (aff) {
5598 isl_int_set(aff->v->el[0], M->row[0][0]);
5599 isl_seq_cpy(aff->v->el + 1, M->row[i], 1 + dim);
5601 aff = isl_aff_normalize(aff);
5602 ma = isl_multi_aff_set_aff(ma, i - 1, aff);
5604 isl_local_space_free(ls);
5605 isl_mat_free(M);
5607 return ma;
5610 /* Given a basic map "dom" that represents the context and an affine
5611 * matrix "M" that maps the dimensions of the context to the
5612 * output variables, construct an isl_pw_multi_aff with a single
5613 * cell corresponding to "dom" and affine expressions copied from "M".
5615 * Note that the description of the initial context may have involved
5616 * existentially quantified variables, in which case they also appear
5617 * in "dom". These need to be removed before creating the affine
5618 * expression because an affine expression cannot be defined in terms
5619 * of existentially quantified variables without a known representation.
5620 * In particular, they are first moved to the end in both "dom" and "M" and
5621 * then ignored in "M". In principle, the final columns of "M"
5622 * (i.e., those that will be ignored) should be zero at this stage
5623 * because align_context_divs adds the existentially quantified
5624 * variables of the context to the main tableau without any constraints.
5625 * The computed minimal value can therefore not depend on these variables.
5626 * However, additional integer divisions that get added for parametric cuts
5627 * get added to the end and they may happen to be equal to some affine
5628 * expression involving the original existentially quantified variables.
5629 * These equality constraints are then propagated to the main tableau
5630 * such that the computed minimum can in fact depend on those existentially
5631 * quantified variables. This dependence can however be removed again
5632 * by exploiting the equality constraints in "dom".
5633 * eliminate_unknown_divs takes care of this.
5635 static void sol_pma_add(struct isl_sol_pma *sol,
5636 __isl_take isl_basic_set *dom, __isl_take isl_mat *M)
5638 isl_local_space *ls;
5639 isl_multi_aff *maff;
5640 isl_pw_multi_aff *pma;
5641 int n_div, n_known, end, off;
5643 n_div = isl_basic_set_dim(dom, isl_dim_div);
5644 off = M->n_col - n_div;
5645 end = n_div;
5646 for (n_known = 0; n_known < end; ++n_known) {
5647 if (isl_basic_set_div_is_known(dom, n_known))
5648 continue;
5649 end = last_known_div_after(dom, n_known, end);
5650 if (end == n_known)
5651 break;
5652 isl_basic_set_swap_div(dom, n_known, end);
5653 M = isl_mat_swap_cols(M, off + n_known, off + end);
5655 dom = isl_basic_set_gauss(dom, NULL);
5656 if (n_known < n_div)
5657 M = eliminate_unknown_divs(M, dom, n_known);
5659 maff = isl_multi_aff_alloc(isl_pw_multi_aff_get_space(sol->pma));
5660 ls = isl_basic_set_get_local_space(dom);
5661 ls = isl_local_space_drop_dims(ls, isl_dim_div,
5662 n_known, n_div - n_known);
5663 maff = set_from_affine_matrix(maff, ls, M);
5664 dom = isl_basic_set_simplify(dom);
5665 dom = isl_basic_set_finalize(dom);
5666 pma = isl_pw_multi_aff_alloc(isl_set_from_basic_set(dom), maff);
5667 sol->pma = isl_pw_multi_aff_add_disjoint(sol->pma, pma);
5668 if (!sol->pma)
5669 sol->sol.error = 1;
5672 static void sol_pma_free_wrap(struct isl_sol *sol)
5674 sol_pma_free((struct isl_sol_pma *)sol);
5677 static void sol_pma_add_empty_wrap(struct isl_sol *sol,
5678 __isl_take isl_basic_set *bset)
5680 sol_pma_add_empty((struct isl_sol_pma *)sol, bset);
5683 static void sol_pma_add_wrap(struct isl_sol *sol,
5684 __isl_take isl_basic_set *dom, __isl_take isl_mat *M)
5686 sol_pma_add((struct isl_sol_pma *)sol, dom, M);
5689 /* Construct an isl_sol_pma structure for accumulating the solution.
5690 * If track_empty is set, then we also keep track of the parts
5691 * of the context where there is no solution.
5692 * If max is set, then we are solving a maximization, rather than
5693 * a minimization problem, which means that the variables in the
5694 * tableau have value "M - x" rather than "M + x".
5696 static struct isl_sol *sol_pma_init(__isl_keep isl_basic_map *bmap,
5697 __isl_take isl_basic_set *dom, int track_empty, int max)
5699 struct isl_sol_pma *sol_pma = NULL;
5701 if (!bmap)
5702 goto error;
5704 sol_pma = isl_calloc_type(bmap->ctx, struct isl_sol_pma);
5705 if (!sol_pma)
5706 goto error;
5708 sol_pma->sol.rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
5709 sol_pma->sol.dec_level.callback.run = &sol_dec_level_wrap;
5710 sol_pma->sol.dec_level.sol = &sol_pma->sol;
5711 sol_pma->sol.max = max;
5712 sol_pma->sol.n_out = isl_basic_map_dim(bmap, isl_dim_out);
5713 sol_pma->sol.add = &sol_pma_add_wrap;
5714 sol_pma->sol.add_empty = track_empty ? &sol_pma_add_empty_wrap : NULL;
5715 sol_pma->sol.free = &sol_pma_free_wrap;
5716 sol_pma->pma = isl_pw_multi_aff_empty(isl_basic_map_get_space(bmap));
5717 if (!sol_pma->pma)
5718 goto error;
5720 sol_pma->sol.context = isl_context_alloc(dom);
5721 if (!sol_pma->sol.context)
5722 goto error;
5724 if (track_empty) {
5725 sol_pma->empty = isl_set_alloc_space(isl_basic_set_get_space(dom),
5726 1, ISL_SET_DISJOINT);
5727 if (!sol_pma->empty)
5728 goto error;
5731 isl_basic_set_free(dom);
5732 return &sol_pma->sol;
5733 error:
5734 isl_basic_set_free(dom);
5735 sol_pma_free(sol_pma);
5736 return NULL;
5739 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
5740 * some obvious symmetries.
5742 * We call basic_map_partial_lexopt_base and extract the results.
5744 static __isl_give isl_pw_multi_aff *basic_map_partial_lexopt_base_pma(
5745 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5746 __isl_give isl_set **empty, int max)
5748 isl_pw_multi_aff *result = NULL;
5749 struct isl_sol *sol;
5750 struct isl_sol_pma *sol_pma;
5752 sol = basic_map_partial_lexopt_base(bmap, dom, empty, max,
5753 &sol_pma_init);
5754 if (!sol)
5755 return NULL;
5756 sol_pma = (struct isl_sol_pma *) sol;
5758 result = isl_pw_multi_aff_copy(sol_pma->pma);
5759 if (empty)
5760 *empty = isl_set_copy(sol_pma->empty);
5761 sol_free(&sol_pma->sol);
5762 return result;
5765 /* Given that the last input variable of "maff" represents the minimum
5766 * of some bounds, check whether we need to plug in the expression
5767 * of the minimum.
5769 * In particular, check if the last input variable appears in any
5770 * of the expressions in "maff".
5772 static int need_substitution(__isl_keep isl_multi_aff *maff)
5774 int i;
5775 unsigned pos;
5777 pos = isl_multi_aff_dim(maff, isl_dim_in) - 1;
5779 for (i = 0; i < maff->n; ++i)
5780 if (isl_aff_involves_dims(maff->p[i], isl_dim_in, pos, 1))
5781 return 1;
5783 return 0;
5786 /* Given a set of upper bounds on the last "input" variable m,
5787 * construct a piecewise affine expression that selects
5788 * the minimal upper bound to m, i.e.,
5789 * divide the space into cells where one
5790 * of the upper bounds is smaller than all the others and select
5791 * this upper bound on that cell.
5793 * In particular, if there are n bounds b_i, then the result
5794 * consists of n cell, each one of the form
5796 * b_i <= b_j for j > i
5797 * b_i < b_j for j < i
5799 * The affine expression on this cell is
5801 * b_i
5803 static __isl_give isl_pw_aff *set_minimum_pa(__isl_take isl_space *space,
5804 __isl_take isl_mat *var)
5806 int i;
5807 isl_aff *aff = NULL;
5808 isl_basic_set *bset = NULL;
5809 isl_pw_aff *paff = NULL;
5810 isl_space *pw_space;
5811 isl_local_space *ls = NULL;
5813 if (!space || !var)
5814 goto error;
5816 ls = isl_local_space_from_space(isl_space_copy(space));
5817 pw_space = isl_space_copy(space);
5818 pw_space = isl_space_from_domain(pw_space);
5819 pw_space = isl_space_add_dims(pw_space, isl_dim_out, 1);
5820 paff = isl_pw_aff_alloc_size(pw_space, var->n_row);
5822 for (i = 0; i < var->n_row; ++i) {
5823 isl_pw_aff *paff_i;
5825 aff = isl_aff_alloc(isl_local_space_copy(ls));
5826 bset = isl_basic_set_alloc_space(isl_space_copy(space), 0,
5827 0, var->n_row - 1);
5828 if (!aff || !bset)
5829 goto error;
5830 isl_int_set_si(aff->v->el[0], 1);
5831 isl_seq_cpy(aff->v->el + 1, var->row[i], var->n_col);
5832 isl_int_set_si(aff->v->el[1 + var->n_col], 0);
5833 bset = select_minimum(bset, var, i);
5834 paff_i = isl_pw_aff_alloc(isl_set_from_basic_set(bset), aff);
5835 paff = isl_pw_aff_add_disjoint(paff, paff_i);
5838 isl_local_space_free(ls);
5839 isl_space_free(space);
5840 isl_mat_free(var);
5841 return paff;
5842 error:
5843 isl_aff_free(aff);
5844 isl_basic_set_free(bset);
5845 isl_pw_aff_free(paff);
5846 isl_local_space_free(ls);
5847 isl_space_free(space);
5848 isl_mat_free(var);
5849 return NULL;
5852 /* Given a piecewise multi-affine expression of which the last input variable
5853 * is the minimum of the bounds in "cst", plug in the value of the minimum.
5854 * This minimum expression is given in "min_expr_pa".
5855 * The set "min_expr" contains the same information, but in the form of a set.
5856 * The variable is subsequently projected out.
5858 * The implementation is similar to those of "split" and "split_domain".
5859 * If the variable appears in a given expression, then minimum expression
5860 * is plugged in. Otherwise, if the variable appears in the constraints
5861 * and a split is required, then the domain is split. Otherwise, no split
5862 * is performed.
5864 static __isl_give isl_pw_multi_aff *split_domain_pma(
5865 __isl_take isl_pw_multi_aff *opt, __isl_take isl_pw_aff *min_expr_pa,
5866 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
5868 int n_in;
5869 int i;
5870 isl_space *space;
5871 isl_pw_multi_aff *res;
5873 if (!opt || !min_expr || !cst)
5874 goto error;
5876 n_in = isl_pw_multi_aff_dim(opt, isl_dim_in);
5877 space = isl_pw_multi_aff_get_space(opt);
5878 space = isl_space_drop_dims(space, isl_dim_in, n_in - 1, 1);
5879 res = isl_pw_multi_aff_empty(space);
5881 for (i = 0; i < opt->n; ++i) {
5882 isl_pw_multi_aff *pma;
5884 pma = isl_pw_multi_aff_alloc(isl_set_copy(opt->p[i].set),
5885 isl_multi_aff_copy(opt->p[i].maff));
5886 if (need_substitution(opt->p[i].maff))
5887 pma = isl_pw_multi_aff_substitute(pma,
5888 isl_dim_in, n_in - 1, min_expr_pa);
5889 else if (need_split_set(opt->p[i].set, cst))
5890 pma = isl_pw_multi_aff_intersect_domain(pma,
5891 isl_set_copy(min_expr));
5892 pma = isl_pw_multi_aff_project_out(pma,
5893 isl_dim_in, n_in - 1, 1);
5895 res = isl_pw_multi_aff_add_disjoint(res, pma);
5898 isl_pw_multi_aff_free(opt);
5899 isl_pw_aff_free(min_expr_pa);
5900 isl_set_free(min_expr);
5901 isl_mat_free(cst);
5902 return res;
5903 error:
5904 isl_pw_multi_aff_free(opt);
5905 isl_pw_aff_free(min_expr_pa);
5906 isl_set_free(min_expr);
5907 isl_mat_free(cst);
5908 return NULL;
5911 static __isl_give isl_pw_multi_aff *basic_map_partial_lexopt_pma(
5912 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5913 __isl_give isl_set **empty, int max);
5915 /* This function is called from basic_map_partial_lexopt_symm.
5916 * The last variable of "bmap" and "dom" corresponds to the minimum
5917 * of the bounds in "cst". "map_space" is the space of the original
5918 * input relation (of basic_map_partial_lexopt_symm) and "set_space"
5919 * is the space of the original domain.
5921 * We recursively call basic_map_partial_lexopt and then plug in
5922 * the definition of the minimum in the result.
5924 static __isl_give union isl_lex_res basic_map_partial_lexopt_symm_pma_core(
5925 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5926 __isl_give isl_set **empty, int max, __isl_take isl_mat *cst,
5927 __isl_take isl_space *map_space, __isl_take isl_space *set_space)
5929 isl_pw_multi_aff *opt;
5930 isl_pw_aff *min_expr_pa;
5931 isl_set *min_expr;
5932 union isl_lex_res res;
5934 min_expr = set_minimum(isl_basic_set_get_space(dom), isl_mat_copy(cst));
5935 min_expr_pa = set_minimum_pa(isl_basic_set_get_space(dom),
5936 isl_mat_copy(cst));
5938 opt = basic_map_partial_lexopt_pma(bmap, dom, empty, max);
5940 if (empty) {
5941 *empty = split(*empty,
5942 isl_set_copy(min_expr), isl_mat_copy(cst));
5943 *empty = isl_set_reset_space(*empty, set_space);
5946 opt = split_domain_pma(opt, min_expr_pa, min_expr, cst);
5947 opt = isl_pw_multi_aff_reset_space(opt, map_space);
5949 res.pma = opt;
5950 return res;
5953 static __isl_give isl_pw_multi_aff *basic_map_partial_lexopt_symm_pma(
5954 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5955 __isl_give isl_set **empty, int max, int first, int second)
5957 return basic_map_partial_lexopt_symm(bmap, dom, empty, max,
5958 first, second, &basic_map_partial_lexopt_symm_pma_core).pma;
5961 /* Recursive part of isl_basic_map_partial_lexopt_pw_multi_aff, after detecting
5962 * equalities and removing redundant constraints.
5964 * We first check if there are any parallel constraints (left).
5965 * If not, we are in the base case.
5966 * If there are parallel constraints, we replace them by a single
5967 * constraint in basic_map_partial_lexopt_symm_pma and then call
5968 * this function recursively to look for more parallel constraints.
5970 static __isl_give isl_pw_multi_aff *basic_map_partial_lexopt_pma(
5971 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5972 __isl_give isl_set **empty, int max)
5974 int par = 0;
5975 int first, second;
5977 if (!bmap)
5978 goto error;
5980 if (bmap->ctx->opt->pip_symmetry)
5981 par = parallel_constraints(bmap, &first, &second);
5982 if (par < 0)
5983 goto error;
5984 if (!par)
5985 return basic_map_partial_lexopt_base_pma(bmap, dom, empty, max);
5987 return basic_map_partial_lexopt_symm_pma(bmap, dom, empty, max,
5988 first, second);
5989 error:
5990 isl_basic_set_free(dom);
5991 isl_basic_map_free(bmap);
5992 return NULL;
5995 /* Compute the lexicographic minimum (or maximum if "max" is set)
5996 * of "bmap" over the domain "dom" and return the result as a piecewise
5997 * multi-affine expression.
5998 * If "empty" is not NULL, then *empty is assigned a set that
5999 * contains those parts of the domain where there is no solution.
6000 * If "bmap" is marked as rational (ISL_BASIC_MAP_RATIONAL),
6001 * then we compute the rational optimum. Otherwise, we compute
6002 * the integral optimum.
6004 * We perform some preprocessing. As the PILP solver does not
6005 * handle implicit equalities very well, we first make sure all
6006 * the equalities are explicitly available.
6008 * We also add context constraints to the basic map and remove
6009 * redundant constraints. This is only needed because of the
6010 * way we handle simple symmetries. In particular, we currently look
6011 * for symmetries on the constraints, before we set up the main tableau.
6012 * It is then no good to look for symmetries on possibly redundant constraints.
6014 __isl_give isl_pw_multi_aff *isl_basic_map_partial_lexopt_pw_multi_aff(
6015 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
6016 __isl_give isl_set **empty, int max)
6018 if (empty)
6019 *empty = NULL;
6020 if (!bmap || !dom)
6021 goto error;
6023 isl_assert(bmap->ctx,
6024 isl_basic_map_compatible_domain(bmap, dom), goto error);
6026 if (isl_basic_set_dim(dom, isl_dim_all) == 0)
6027 return basic_map_partial_lexopt_pma(bmap, dom, empty, max);
6029 bmap = isl_basic_map_intersect_domain(bmap, isl_basic_set_copy(dom));
6030 bmap = isl_basic_map_detect_equalities(bmap);
6031 bmap = isl_basic_map_remove_redundancies(bmap);
6033 return basic_map_partial_lexopt_pma(bmap, dom, empty, max);
6034 error:
6035 isl_basic_set_free(dom);
6036 isl_basic_map_free(bmap);
6037 return NULL;