isl_basic_map_domain_product: use isl_basic_map_get_space
[isl.git] / isl_tab_pip.c
blob8bc6ad8e249e3e04982b318d185ce8a7b566c1c1
1 /*
2 * Copyright 2008-2009 Katholieke Universiteit Leuven
3 * Copyright 2010 INRIA Saclay
4 * Copyright 2016-2017 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>
26 #include <bset_to_bmap.c>
29 * The implementation of parametric integer linear programming in this file
30 * was inspired by the paper "Parametric Integer Programming" and the
31 * report "Solving systems of affine (in)equalities" by Paul Feautrier
32 * (and others).
34 * The strategy used for obtaining a feasible solution is different
35 * from the one used in isl_tab.c. In particular, in isl_tab.c,
36 * upon finding a constraint that is not yet satisfied, we pivot
37 * in a row that increases the constant term of the row holding the
38 * constraint, making sure the sample solution remains feasible
39 * for all the constraints it already satisfied.
40 * Here, we always pivot in the row holding the constraint,
41 * choosing a column that induces the lexicographically smallest
42 * increment to the sample solution.
44 * By starting out from a sample value that is lexicographically
45 * smaller than any integer point in the problem space, the first
46 * feasible integer sample point we find will also be the lexicographically
47 * smallest. If all variables can be assumed to be non-negative,
48 * then the initial sample value may be chosen equal to zero.
49 * However, we will not make this assumption. Instead, we apply
50 * the "big parameter" trick. Any variable x is then not directly
51 * used in the tableau, but instead it is represented by another
52 * variable x' = M + x, where M is an arbitrarily large (positive)
53 * value. x' is therefore always non-negative, whatever the value of x.
54 * Taking as initial sample value x' = 0 corresponds to x = -M,
55 * which is always smaller than any possible value of x.
57 * The big parameter trick is used in the main tableau and
58 * also in the context tableau if isl_context_lex is used.
59 * In this case, each tableaus has its own big parameter.
60 * Before doing any real work, we check if all the parameters
61 * happen to be non-negative. If so, we drop the column corresponding
62 * to M from the initial context tableau.
63 * If isl_context_gbr is used, then the big parameter trick is only
64 * used in the main tableau.
67 struct isl_context;
68 struct isl_context_op {
69 /* detect nonnegative parameters in context and mark them in tab */
70 struct isl_tab *(*detect_nonnegative_parameters)(
71 struct isl_context *context, struct isl_tab *tab);
72 /* return temporary reference to basic set representation of context */
73 struct isl_basic_set *(*peek_basic_set)(struct isl_context *context);
74 /* return temporary reference to tableau representation of context */
75 struct isl_tab *(*peek_tab)(struct isl_context *context);
76 /* add equality; check is 1 if eq may not be valid;
77 * update is 1 if we may want to call ineq_sign on context later.
79 void (*add_eq)(struct isl_context *context, isl_int *eq,
80 int check, int update);
81 /* add inequality; check is 1 if ineq may not be valid;
82 * update is 1 if we may want to call ineq_sign on context later.
84 void (*add_ineq)(struct isl_context *context, isl_int *ineq,
85 int check, int update);
86 /* check sign of ineq based on previous information.
87 * strict is 1 if saturation should be treated as a positive sign.
89 enum isl_tab_row_sign (*ineq_sign)(struct isl_context *context,
90 isl_int *ineq, int strict);
91 /* check if inequality maintains feasibility */
92 int (*test_ineq)(struct isl_context *context, isl_int *ineq);
93 /* return index of a div that corresponds to "div" */
94 int (*get_div)(struct isl_context *context, struct isl_tab *tab,
95 struct isl_vec *div);
96 /* insert div "div" to context at "pos" and return non-negativity */
97 isl_bool (*insert_div)(struct isl_context *context, int pos,
98 __isl_keep isl_vec *div);
99 int (*detect_equalities)(struct isl_context *context,
100 struct isl_tab *tab);
101 /* return row index of "best" split */
102 int (*best_split)(struct isl_context *context, struct isl_tab *tab);
103 /* check if context has already been determined to be empty */
104 int (*is_empty)(struct isl_context *context);
105 /* check if context is still usable */
106 int (*is_ok)(struct isl_context *context);
107 /* save a copy/snapshot of context */
108 void *(*save)(struct isl_context *context);
109 /* restore saved context */
110 void (*restore)(struct isl_context *context, void *);
111 /* discard saved context */
112 void (*discard)(void *);
113 /* invalidate context */
114 void (*invalidate)(struct isl_context *context);
115 /* free context */
116 __isl_null struct isl_context *(*free)(struct isl_context *context);
119 /* Shared parts of context representation.
121 * "n_unknown" is the number of final unknown integer divisions
122 * in the input domain.
124 struct isl_context {
125 struct isl_context_op *op;
126 int n_unknown;
129 struct isl_context_lex {
130 struct isl_context context;
131 struct isl_tab *tab;
134 /* A stack (linked list) of solutions of subtrees of the search space.
136 * "ma" describes the solution as a function of "dom".
137 * In particular, the domain space of "ma" is equal to the space of "dom".
139 * If "ma" is NULL, then there is no solution on "dom".
141 struct isl_partial_sol {
142 int level;
143 struct isl_basic_set *dom;
144 isl_multi_aff *ma;
146 struct isl_partial_sol *next;
149 struct isl_sol;
150 struct isl_sol_callback {
151 struct isl_tab_callback callback;
152 struct isl_sol *sol;
155 /* isl_sol is an interface for constructing a solution to
156 * a parametric integer linear programming problem.
157 * Every time the algorithm reaches a state where a solution
158 * can be read off from the tableau, the function "add" is called
159 * on the isl_sol passed to find_solutions_main. In a state where
160 * the tableau is empty, "add_empty" is called instead.
161 * "free" is called to free the implementation specific fields, if any.
163 * "error" is set if some error has occurred. This flag invalidates
164 * the remainder of the data structure.
165 * If "rational" is set, then a rational optimization is being performed.
166 * "level" is the current level in the tree with nodes for each
167 * split in the context.
168 * If "max" is set, then a maximization problem is being solved, rather than
169 * a minimization problem, which means that the variables in the
170 * tableau have value "M - x" rather than "M + x".
171 * "n_out" is the number of output dimensions in the input.
172 * "space" is the space in which the solution (and also the input) lives.
174 * The context tableau is owned by isl_sol and is updated incrementally.
176 * There are currently two implementations of this interface,
177 * isl_sol_map, which simply collects the solutions in an isl_map
178 * and (optionally) the parts of the context where there is no solution
179 * in an isl_set, and
180 * isl_sol_pma, which collects an isl_pw_multi_aff instead.
182 struct isl_sol {
183 int error;
184 int rational;
185 int level;
186 int max;
187 int n_out;
188 isl_space *space;
189 struct isl_context *context;
190 struct isl_partial_sol *partial;
191 void (*add)(struct isl_sol *sol,
192 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma);
193 void (*add_empty)(struct isl_sol *sol, struct isl_basic_set *bset);
194 void (*free)(struct isl_sol *sol);
195 struct isl_sol_callback dec_level;
198 static void sol_free(struct isl_sol *sol)
200 struct isl_partial_sol *partial, *next;
201 if (!sol)
202 return;
203 for (partial = sol->partial; partial; partial = next) {
204 next = partial->next;
205 isl_basic_set_free(partial->dom);
206 isl_multi_aff_free(partial->ma);
207 free(partial);
209 isl_space_free(sol->space);
210 if (sol->context)
211 sol->context->op->free(sol->context);
212 sol->free(sol);
213 free(sol);
216 /* Push a partial solution represented by a domain and function "ma"
217 * onto the stack of partial solutions.
218 * If "ma" is NULL, then "dom" represents a part of the domain
219 * with no solution.
221 static void sol_push_sol(struct isl_sol *sol,
222 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
224 struct isl_partial_sol *partial;
226 if (sol->error || !dom)
227 goto error;
229 partial = isl_alloc_type(dom->ctx, struct isl_partial_sol);
230 if (!partial)
231 goto error;
233 partial->level = sol->level;
234 partial->dom = dom;
235 partial->ma = ma;
236 partial->next = sol->partial;
238 sol->partial = partial;
240 return;
241 error:
242 isl_basic_set_free(dom);
243 isl_multi_aff_free(ma);
244 sol->error = 1;
247 /* Check that the final columns of "M", starting at "first", are zero.
249 static isl_stat check_final_columns_are_zero(__isl_keep isl_mat *M,
250 unsigned first)
252 int i;
253 unsigned rows, cols, n;
255 if (!M)
256 return isl_stat_error;
257 rows = isl_mat_rows(M);
258 cols = isl_mat_cols(M);
259 n = cols - first;
260 for (i = 0; i < rows; ++i)
261 if (isl_seq_first_non_zero(M->row[i] + first, n) != -1)
262 isl_die(isl_mat_get_ctx(M), isl_error_internal,
263 "final columns should be zero",
264 return isl_stat_error);
265 return isl_stat_ok;
268 /* Set the affine expressions in "ma" according to the rows in "M", which
269 * are defined over the local space "ls".
270 * The matrix "M" may have extra (zero) columns beyond the number
271 * of variables in "ls".
273 static __isl_give isl_multi_aff *set_from_affine_matrix(
274 __isl_take isl_multi_aff *ma, __isl_take isl_local_space *ls,
275 __isl_take isl_mat *M)
277 int i, dim;
278 isl_aff *aff;
280 if (!ma || !ls || !M)
281 goto error;
283 dim = isl_local_space_dim(ls, isl_dim_all);
284 if (check_final_columns_are_zero(M, 1 + dim) < 0)
285 goto error;
286 for (i = 1; i < M->n_row; ++i) {
287 aff = isl_aff_alloc(isl_local_space_copy(ls));
288 if (aff) {
289 isl_int_set(aff->v->el[0], M->row[0][0]);
290 isl_seq_cpy(aff->v->el + 1, M->row[i], 1 + dim);
292 aff = isl_aff_normalize(aff);
293 ma = isl_multi_aff_set_aff(ma, i - 1, aff);
295 isl_local_space_free(ls);
296 isl_mat_free(M);
298 return ma;
299 error:
300 isl_local_space_free(ls);
301 isl_mat_free(M);
302 isl_multi_aff_free(ma);
303 return NULL;
306 /* Push a partial solution represented by a domain and mapping M
307 * onto the stack of partial solutions.
309 * The affine matrix "M" maps the dimensions of the context
310 * to the output variables. Convert it into an isl_multi_aff and
311 * then call sol_push_sol.
313 * Note that the description of the initial context may have involved
314 * existentially quantified variables, in which case they also appear
315 * in "dom". These need to be removed before creating the affine
316 * expression because an affine expression cannot be defined in terms
317 * of existentially quantified variables without a known representation.
318 * Since newly added integer divisions are inserted before these
319 * existentially quantified variables, they are still in the final
320 * positions and the corresponding final columns of "M" are zero
321 * because align_context_divs adds the existentially quantified
322 * variables of the context to the main tableau without any constraints and
323 * any equality constraints that are added later on can only serve
324 * to eliminate these existentially quantified variables.
326 static void sol_push_sol_mat(struct isl_sol *sol,
327 __isl_take isl_basic_set *dom, __isl_take isl_mat *M)
329 isl_local_space *ls;
330 isl_multi_aff *ma;
331 int n_div, n_known;
333 n_div = isl_basic_set_dim(dom, isl_dim_div);
334 n_known = n_div - sol->context->n_unknown;
336 ma = isl_multi_aff_alloc(isl_space_copy(sol->space));
337 ls = isl_basic_set_get_local_space(dom);
338 ls = isl_local_space_drop_dims(ls, isl_dim_div,
339 n_known, n_div - n_known);
340 ma = set_from_affine_matrix(ma, ls, M);
342 if (!ma)
343 dom = isl_basic_set_free(dom);
344 sol_push_sol(sol, dom, ma);
347 /* Pop one partial solution from the partial solution stack and
348 * pass it on to sol->add or sol->add_empty.
350 static void sol_pop_one(struct isl_sol *sol)
352 struct isl_partial_sol *partial;
354 partial = sol->partial;
355 sol->partial = partial->next;
357 if (partial->ma)
358 sol->add(sol, partial->dom, partial->ma);
359 else
360 sol->add_empty(sol, partial->dom);
361 free(partial);
364 /* Return a fresh copy of the domain represented by the context tableau.
366 static struct isl_basic_set *sol_domain(struct isl_sol *sol)
368 struct isl_basic_set *bset;
370 if (sol->error)
371 return NULL;
373 bset = isl_basic_set_dup(sol->context->op->peek_basic_set(sol->context));
374 bset = isl_basic_set_update_from_tab(bset,
375 sol->context->op->peek_tab(sol->context));
377 return bset;
380 /* Check whether two partial solutions have the same affine expressions.
382 static isl_bool same_solution(struct isl_partial_sol *s1,
383 struct isl_partial_sol *s2)
385 if (!s1->ma != !s2->ma)
386 return isl_bool_false;
387 if (!s1->ma)
388 return isl_bool_true;
390 return isl_multi_aff_plain_is_equal(s1->ma, s2->ma);
393 /* Swap the initial two partial solutions in "sol".
395 * That is, go from
397 * sol->partial = p1; p1->next = p2; p2->next = p3
399 * to
401 * sol->partial = p2; p2->next = p1; p1->next = p3
403 static void swap_initial(struct isl_sol *sol)
405 struct isl_partial_sol *partial;
407 partial = sol->partial;
408 sol->partial = partial->next;
409 partial->next = partial->next->next;
410 sol->partial->next = partial;
413 /* Combine the initial two partial solution of "sol" into
414 * a partial solution with the current context domain of "sol" and
415 * the function description of the second partial solution in the list.
416 * The level of the new partial solution is set to the current level.
418 * That is, the first two partial solutions (D1,M1) and (D2,M2) are
419 * replaced by (D,M2), where D is the domain of "sol", which is assumed
420 * to be the union of D1 and D2, while M1 is assumed to be equal to M2
421 * (at least on D1).
423 static isl_stat combine_initial_into_second(struct isl_sol *sol)
425 struct isl_partial_sol *partial;
426 isl_basic_set *bset;
428 partial = sol->partial;
430 bset = sol_domain(sol);
431 isl_basic_set_free(partial->next->dom);
432 partial->next->dom = bset;
433 partial->next->level = sol->level;
435 if (!bset)
436 return isl_stat_error;
438 sol->partial = partial->next;
439 isl_basic_set_free(partial->dom);
440 isl_multi_aff_free(partial->ma);
441 free(partial);
443 return isl_stat_ok;
446 /* Are "ma1" and "ma2" equal to each other on "dom"?
448 * Combine "ma1" and "ma2" with "dom" and check if the results are the same.
449 * "dom" may have existentially quantified variables. Eliminate them first
450 * as otherwise they would have to be eliminated twice, in a more complicated
451 * context.
453 static isl_bool equal_on_domain(__isl_keep isl_multi_aff *ma1,
454 __isl_keep isl_multi_aff *ma2, __isl_keep isl_basic_set *dom)
456 isl_set *set;
457 isl_pw_multi_aff *pma1, *pma2;
458 isl_bool equal;
460 set = isl_basic_set_compute_divs(isl_basic_set_copy(dom));
461 pma1 = isl_pw_multi_aff_alloc(isl_set_copy(set),
462 isl_multi_aff_copy(ma1));
463 pma2 = isl_pw_multi_aff_alloc(set, isl_multi_aff_copy(ma2));
464 equal = isl_pw_multi_aff_is_equal(pma1, pma2);
465 isl_pw_multi_aff_free(pma1);
466 isl_pw_multi_aff_free(pma2);
468 return equal;
471 /* The initial two partial solutions of "sol" are known to be at
472 * the same level.
473 * If they represent the same solution (on different parts of the domain),
474 * then combine them into a single solution at the current level.
475 * Otherwise, pop them both.
477 * Even if the two partial solution are not obviously the same,
478 * one may still be a simplification of the other over its own domain.
479 * Also check if the two sets of affine functions are equal when
480 * restricted to one of the domains. If so, combine the two
481 * using the set of affine functions on the other domain.
482 * That is, for two partial solutions (D1,M1) and (D2,M2),
483 * if M1 = M2 on D1, then the pair of partial solutions can
484 * be replaced by (D1+D2,M2) and similarly when M1 = M2 on D2.
486 static isl_stat combine_initial_if_equal(struct isl_sol *sol)
488 struct isl_partial_sol *partial;
489 isl_bool same;
491 partial = sol->partial;
493 same = same_solution(partial, partial->next);
494 if (same < 0)
495 return isl_stat_error;
496 if (same)
497 return combine_initial_into_second(sol);
498 if (partial->ma && partial->next->ma) {
499 same = equal_on_domain(partial->ma, partial->next->ma,
500 partial->dom);
501 if (same < 0)
502 return isl_stat_error;
503 if (same)
504 return combine_initial_into_second(sol);
505 same = equal_on_domain(partial->ma, partial->next->ma,
506 partial->next->dom);
507 if (same) {
508 swap_initial(sol);
509 return combine_initial_into_second(sol);
513 sol_pop_one(sol);
514 sol_pop_one(sol);
516 return isl_stat_ok;
519 /* Pop all solutions from the partial solution stack that were pushed onto
520 * the stack at levels that are deeper than the current level.
521 * If the two topmost elements on the stack have the same level
522 * and represent the same solution, then their domains are combined.
523 * This combined domain is the same as the current context domain
524 * as sol_pop is called each time we move back to a higher level.
525 * If the outer level (0) has been reached, then all partial solutions
526 * at the current level are also popped off.
528 static void sol_pop(struct isl_sol *sol)
530 struct isl_partial_sol *partial;
532 if (sol->error)
533 return;
535 partial = sol->partial;
536 if (!partial)
537 return;
539 if (partial->level == 0 && sol->level == 0) {
540 for (partial = sol->partial; partial; partial = sol->partial)
541 sol_pop_one(sol);
542 return;
545 if (partial->level <= sol->level)
546 return;
548 if (partial->next && partial->next->level == partial->level) {
549 if (combine_initial_if_equal(sol) < 0)
550 goto error;
551 } else
552 sol_pop_one(sol);
554 if (sol->level == 0) {
555 for (partial = sol->partial; partial; partial = sol->partial)
556 sol_pop_one(sol);
557 return;
560 if (0)
561 error: sol->error = 1;
564 static void sol_dec_level(struct isl_sol *sol)
566 if (sol->error)
567 return;
569 sol->level--;
571 sol_pop(sol);
574 static isl_stat sol_dec_level_wrap(struct isl_tab_callback *cb)
576 struct isl_sol_callback *callback = (struct isl_sol_callback *)cb;
578 sol_dec_level(callback->sol);
580 return callback->sol->error ? isl_stat_error : isl_stat_ok;
583 /* Move down to next level and push callback onto context tableau
584 * to decrease the level again when it gets rolled back across
585 * the current state. That is, dec_level will be called with
586 * the context tableau in the same state as it is when inc_level
587 * is called.
589 static void sol_inc_level(struct isl_sol *sol)
591 struct isl_tab *tab;
593 if (sol->error)
594 return;
596 sol->level++;
597 tab = sol->context->op->peek_tab(sol->context);
598 if (isl_tab_push_callback(tab, &sol->dec_level.callback) < 0)
599 sol->error = 1;
602 static void scale_rows(struct isl_mat *mat, isl_int m, int n_row)
604 int i;
606 if (isl_int_is_one(m))
607 return;
609 for (i = 0; i < n_row; ++i)
610 isl_seq_scale(mat->row[i], mat->row[i], m, mat->n_col);
613 /* Add the solution identified by the tableau and the context tableau.
615 * The layout of the variables is as follows.
616 * tab->n_var is equal to the total number of variables in the input
617 * map (including divs that were copied from the context)
618 * + the number of extra divs constructed
619 * Of these, the first tab->n_param and the last tab->n_div variables
620 * correspond to the variables in the context, i.e.,
621 * tab->n_param + tab->n_div = context_tab->n_var
622 * tab->n_param is equal to the number of parameters and input
623 * dimensions in the input map
624 * tab->n_div is equal to the number of divs in the context
626 * If there is no solution, then call add_empty with a basic set
627 * that corresponds to the context tableau. (If add_empty is NULL,
628 * then do nothing).
630 * If there is a solution, then first construct a matrix that maps
631 * all dimensions of the context to the output variables, i.e.,
632 * the output dimensions in the input map.
633 * The divs in the input map (if any) that do not correspond to any
634 * div in the context do not appear in the solution.
635 * The algorithm will make sure that they have an integer value,
636 * but these values themselves are of no interest.
637 * We have to be careful not to drop or rearrange any divs in the
638 * context because that would change the meaning of the matrix.
640 * To extract the value of the output variables, it should be noted
641 * that we always use a big parameter M in the main tableau and so
642 * the variable stored in this tableau is not an output variable x itself, but
643 * x' = M + x (in case of minimization)
644 * or
645 * x' = M - x (in case of maximization)
646 * If x' appears in a column, then its optimal value is zero,
647 * which means that the optimal value of x is an unbounded number
648 * (-M for minimization and M for maximization).
649 * We currently assume that the output dimensions in the original map
650 * are bounded, so this cannot occur.
651 * Similarly, when x' appears in a row, then the coefficient of M in that
652 * row is necessarily 1.
653 * If the row in the tableau represents
654 * d x' = c + d M + e(y)
655 * then, in case of minimization, the corresponding row in the matrix
656 * will be
657 * a c + a e(y)
658 * with a d = m, the (updated) common denominator of the matrix.
659 * In case of maximization, the row will be
660 * -a c - a e(y)
662 static void sol_add(struct isl_sol *sol, struct isl_tab *tab)
664 struct isl_basic_set *bset = NULL;
665 struct isl_mat *mat = NULL;
666 unsigned off;
667 int row;
668 isl_int m;
670 if (sol->error || !tab)
671 goto error;
673 if (tab->empty && !sol->add_empty)
674 return;
675 if (sol->context->op->is_empty(sol->context))
676 return;
678 bset = sol_domain(sol);
680 if (tab->empty) {
681 sol_push_sol(sol, bset, NULL);
682 return;
685 off = 2 + tab->M;
687 mat = isl_mat_alloc(tab->mat->ctx, 1 + sol->n_out,
688 1 + tab->n_param + tab->n_div);
689 if (!mat)
690 goto error;
692 isl_int_init(m);
694 isl_seq_clr(mat->row[0] + 1, mat->n_col - 1);
695 isl_int_set_si(mat->row[0][0], 1);
696 for (row = 0; row < sol->n_out; ++row) {
697 int i = tab->n_param + row;
698 int r, j;
700 isl_seq_clr(mat->row[1 + row], mat->n_col);
701 if (!tab->var[i].is_row) {
702 if (tab->M)
703 isl_die(mat->ctx, isl_error_invalid,
704 "unbounded optimum", goto error2);
705 continue;
708 r = tab->var[i].index;
709 if (tab->M &&
710 isl_int_ne(tab->mat->row[r][2], tab->mat->row[r][0]))
711 isl_die(mat->ctx, isl_error_invalid,
712 "unbounded optimum", goto error2);
713 isl_int_gcd(m, mat->row[0][0], tab->mat->row[r][0]);
714 isl_int_divexact(m, tab->mat->row[r][0], m);
715 scale_rows(mat, m, 1 + row);
716 isl_int_divexact(m, mat->row[0][0], tab->mat->row[r][0]);
717 isl_int_mul(mat->row[1 + row][0], m, tab->mat->row[r][1]);
718 for (j = 0; j < tab->n_param; ++j) {
719 int col;
720 if (tab->var[j].is_row)
721 continue;
722 col = tab->var[j].index;
723 isl_int_mul(mat->row[1 + row][1 + j], m,
724 tab->mat->row[r][off + col]);
726 for (j = 0; j < tab->n_div; ++j) {
727 int col;
728 if (tab->var[tab->n_var - tab->n_div+j].is_row)
729 continue;
730 col = tab->var[tab->n_var - tab->n_div+j].index;
731 isl_int_mul(mat->row[1 + row][1 + tab->n_param + j], m,
732 tab->mat->row[r][off + col]);
734 if (sol->max)
735 isl_seq_neg(mat->row[1 + row], mat->row[1 + row],
736 mat->n_col);
739 isl_int_clear(m);
741 sol_push_sol_mat(sol, bset, mat);
742 return;
743 error2:
744 isl_int_clear(m);
745 error:
746 isl_basic_set_free(bset);
747 isl_mat_free(mat);
748 sol->error = 1;
751 struct isl_sol_map {
752 struct isl_sol sol;
753 struct isl_map *map;
754 struct isl_set *empty;
757 static void sol_map_free(struct isl_sol *sol)
759 struct isl_sol_map *sol_map = (struct isl_sol_map *) sol;
760 isl_map_free(sol_map->map);
761 isl_set_free(sol_map->empty);
764 /* This function is called for parts of the context where there is
765 * no solution, with "bset" corresponding to the context tableau.
766 * Simply add the basic set to the set "empty".
768 static void sol_map_add_empty(struct isl_sol_map *sol,
769 struct isl_basic_set *bset)
771 if (!bset || !sol->empty)
772 goto error;
774 sol->empty = isl_set_grow(sol->empty, 1);
775 bset = isl_basic_set_simplify(bset);
776 bset = isl_basic_set_finalize(bset);
777 sol->empty = isl_set_add_basic_set(sol->empty, isl_basic_set_copy(bset));
778 if (!sol->empty)
779 goto error;
780 isl_basic_set_free(bset);
781 return;
782 error:
783 isl_basic_set_free(bset);
784 sol->sol.error = 1;
787 static void sol_map_add_empty_wrap(struct isl_sol *sol,
788 struct isl_basic_set *bset)
790 sol_map_add_empty((struct isl_sol_map *)sol, bset);
793 /* Given a basic set "dom" that represents the context and a tuple of
794 * affine expressions "ma" defined over this domain, construct a basic map
795 * that expresses this function on the domain.
797 static void sol_map_add(struct isl_sol_map *sol,
798 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
800 isl_basic_map *bmap;
802 if (sol->sol.error || !dom || !ma)
803 goto error;
805 bmap = isl_basic_map_from_multi_aff2(ma, sol->sol.rational);
806 bmap = isl_basic_map_intersect_domain(bmap, dom);
807 sol->map = isl_map_grow(sol->map, 1);
808 sol->map = isl_map_add_basic_map(sol->map, bmap);
809 if (!sol->map)
810 sol->sol.error = 1;
811 return;
812 error:
813 isl_basic_set_free(dom);
814 isl_multi_aff_free(ma);
815 sol->sol.error = 1;
818 static void sol_map_add_wrap(struct isl_sol *sol,
819 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
821 sol_map_add((struct isl_sol_map *)sol, dom, ma);
825 /* Store the "parametric constant" of row "row" of tableau "tab" in "line",
826 * i.e., the constant term and the coefficients of all variables that
827 * appear in the context tableau.
828 * Note that the coefficient of the big parameter M is NOT copied.
829 * The context tableau may not have a big parameter and even when it
830 * does, it is a different big parameter.
832 static void get_row_parameter_line(struct isl_tab *tab, int row, isl_int *line)
834 int i;
835 unsigned off = 2 + tab->M;
837 isl_int_set(line[0], tab->mat->row[row][1]);
838 for (i = 0; i < tab->n_param; ++i) {
839 if (tab->var[i].is_row)
840 isl_int_set_si(line[1 + i], 0);
841 else {
842 int col = tab->var[i].index;
843 isl_int_set(line[1 + i], tab->mat->row[row][off + col]);
846 for (i = 0; i < tab->n_div; ++i) {
847 if (tab->var[tab->n_var - tab->n_div + i].is_row)
848 isl_int_set_si(line[1 + tab->n_param + i], 0);
849 else {
850 int col = tab->var[tab->n_var - tab->n_div + i].index;
851 isl_int_set(line[1 + tab->n_param + i],
852 tab->mat->row[row][off + col]);
857 /* Check if rows "row1" and "row2" have identical "parametric constants",
858 * as explained above.
859 * In this case, we also insist that the coefficients of the big parameter
860 * be the same as the values of the constants will only be the same
861 * if these coefficients are also the same.
863 static int identical_parameter_line(struct isl_tab *tab, int row1, int row2)
865 int i;
866 unsigned off = 2 + tab->M;
868 if (isl_int_ne(tab->mat->row[row1][1], tab->mat->row[row2][1]))
869 return 0;
871 if (tab->M && isl_int_ne(tab->mat->row[row1][2],
872 tab->mat->row[row2][2]))
873 return 0;
875 for (i = 0; i < tab->n_param + tab->n_div; ++i) {
876 int pos = i < tab->n_param ? i :
877 tab->n_var - tab->n_div + i - tab->n_param;
878 int col;
880 if (tab->var[pos].is_row)
881 continue;
882 col = tab->var[pos].index;
883 if (isl_int_ne(tab->mat->row[row1][off + col],
884 tab->mat->row[row2][off + col]))
885 return 0;
887 return 1;
890 /* Return an inequality that expresses that the "parametric constant"
891 * should be non-negative.
892 * This function is only called when the coefficient of the big parameter
893 * is equal to zero.
895 static struct isl_vec *get_row_parameter_ineq(struct isl_tab *tab, int row)
897 struct isl_vec *ineq;
899 ineq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_param + tab->n_div);
900 if (!ineq)
901 return NULL;
903 get_row_parameter_line(tab, row, ineq->el);
904 if (ineq)
905 ineq = isl_vec_normalize(ineq);
907 return ineq;
910 /* Normalize a div expression of the form
912 * [(g*f(x) + c)/(g * m)]
914 * with c the constant term and f(x) the remaining coefficients, to
916 * [(f(x) + [c/g])/m]
918 static void normalize_div(__isl_keep isl_vec *div)
920 isl_ctx *ctx = isl_vec_get_ctx(div);
921 int len = div->size - 2;
923 isl_seq_gcd(div->el + 2, len, &ctx->normalize_gcd);
924 isl_int_gcd(ctx->normalize_gcd, ctx->normalize_gcd, div->el[0]);
926 if (isl_int_is_one(ctx->normalize_gcd))
927 return;
929 isl_int_divexact(div->el[0], div->el[0], ctx->normalize_gcd);
930 isl_int_fdiv_q(div->el[1], div->el[1], ctx->normalize_gcd);
931 isl_seq_scale_down(div->el + 2, div->el + 2, ctx->normalize_gcd, len);
934 /* Return an integer division for use in a parametric cut based
935 * on the given row.
936 * In particular, let the parametric constant of the row be
938 * \sum_i a_i y_i
940 * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
941 * The div returned is equal to
943 * floor(\sum_i {-a_i} y_i) = floor((\sum_i (-a_i mod d) y_i)/d)
945 static struct isl_vec *get_row_parameter_div(struct isl_tab *tab, int row)
947 struct isl_vec *div;
949 div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
950 if (!div)
951 return NULL;
953 isl_int_set(div->el[0], tab->mat->row[row][0]);
954 get_row_parameter_line(tab, row, div->el + 1);
955 isl_seq_neg(div->el + 1, div->el + 1, div->size - 1);
956 normalize_div(div);
957 isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
959 return div;
962 /* Return an integer division for use in transferring an integrality constraint
963 * to the context.
964 * In particular, let the parametric constant of the row be
966 * \sum_i a_i y_i
968 * where y_0 = 1, but none of the y_i corresponds to the big parameter M.
969 * The the returned div is equal to
971 * floor(\sum_i {a_i} y_i) = floor((\sum_i (a_i mod d) y_i)/d)
973 static struct isl_vec *get_row_split_div(struct isl_tab *tab, int row)
975 struct isl_vec *div;
977 div = isl_vec_alloc(tab->mat->ctx, 1 + 1 + tab->n_param + tab->n_div);
978 if (!div)
979 return NULL;
981 isl_int_set(div->el[0], tab->mat->row[row][0]);
982 get_row_parameter_line(tab, row, div->el + 1);
983 normalize_div(div);
984 isl_seq_fdiv_r(div->el + 1, div->el + 1, div->el[0], div->size - 1);
986 return div;
989 /* Construct and return an inequality that expresses an upper bound
990 * on the given div.
991 * In particular, if the div is given by
993 * d = floor(e/m)
995 * then the inequality expresses
997 * m d <= e
999 static __isl_give isl_vec *ineq_for_div(__isl_keep isl_basic_set *bset,
1000 unsigned div)
1002 unsigned total;
1003 unsigned div_pos;
1004 struct isl_vec *ineq;
1006 if (!bset)
1007 return NULL;
1009 total = isl_basic_set_total_dim(bset);
1010 div_pos = 1 + total - bset->n_div + div;
1012 ineq = isl_vec_alloc(bset->ctx, 1 + total);
1013 if (!ineq)
1014 return NULL;
1016 isl_seq_cpy(ineq->el, bset->div[div] + 1, 1 + total);
1017 isl_int_neg(ineq->el[div_pos], bset->div[div][0]);
1018 return ineq;
1021 /* Given a row in the tableau and a div that was created
1022 * using get_row_split_div and that has been constrained to equality, i.e.,
1024 * d = floor(\sum_i {a_i} y_i) = \sum_i {a_i} y_i
1026 * replace the expression "\sum_i {a_i} y_i" in the row by d,
1027 * i.e., we subtract "\sum_i {a_i} y_i" and add 1 d.
1028 * The coefficients of the non-parameters in the tableau have been
1029 * verified to be integral. We can therefore simply replace coefficient b
1030 * by floor(b). For the coefficients of the parameters we have
1031 * floor(a_i) = a_i - {a_i}, while for the other coefficients, we have
1032 * floor(b) = b.
1034 static struct isl_tab *set_row_cst_to_div(struct isl_tab *tab, int row, int div)
1036 isl_seq_fdiv_q(tab->mat->row[row] + 1, tab->mat->row[row] + 1,
1037 tab->mat->row[row][0], 1 + tab->M + tab->n_col);
1039 isl_int_set_si(tab->mat->row[row][0], 1);
1041 if (tab->var[tab->n_var - tab->n_div + div].is_row) {
1042 int drow = tab->var[tab->n_var - tab->n_div + div].index;
1044 isl_assert(tab->mat->ctx,
1045 isl_int_is_one(tab->mat->row[drow][0]), goto error);
1046 isl_seq_combine(tab->mat->row[row] + 1,
1047 tab->mat->ctx->one, tab->mat->row[row] + 1,
1048 tab->mat->ctx->one, tab->mat->row[drow] + 1,
1049 1 + tab->M + tab->n_col);
1050 } else {
1051 int dcol = tab->var[tab->n_var - tab->n_div + div].index;
1053 isl_int_add_ui(tab->mat->row[row][2 + tab->M + dcol],
1054 tab->mat->row[row][2 + tab->M + dcol], 1);
1057 return tab;
1058 error:
1059 isl_tab_free(tab);
1060 return NULL;
1063 /* Check if the (parametric) constant of the given row is obviously
1064 * negative, meaning that we don't need to consult the context tableau.
1065 * If there is a big parameter and its coefficient is non-zero,
1066 * then this coefficient determines the outcome.
1067 * Otherwise, we check whether the constant is negative and
1068 * all non-zero coefficients of parameters are negative and
1069 * belong to non-negative parameters.
1071 static int is_obviously_neg(struct isl_tab *tab, int row)
1073 int i;
1074 int col;
1075 unsigned off = 2 + tab->M;
1077 if (tab->M) {
1078 if (isl_int_is_pos(tab->mat->row[row][2]))
1079 return 0;
1080 if (isl_int_is_neg(tab->mat->row[row][2]))
1081 return 1;
1084 if (isl_int_is_nonneg(tab->mat->row[row][1]))
1085 return 0;
1086 for (i = 0; i < tab->n_param; ++i) {
1087 /* Eliminated parameter */
1088 if (tab->var[i].is_row)
1089 continue;
1090 col = tab->var[i].index;
1091 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1092 continue;
1093 if (!tab->var[i].is_nonneg)
1094 return 0;
1095 if (isl_int_is_pos(tab->mat->row[row][off + col]))
1096 return 0;
1098 for (i = 0; i < tab->n_div; ++i) {
1099 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1100 continue;
1101 col = tab->var[tab->n_var - tab->n_div + i].index;
1102 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1103 continue;
1104 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
1105 return 0;
1106 if (isl_int_is_pos(tab->mat->row[row][off + col]))
1107 return 0;
1109 return 1;
1112 /* Check if the (parametric) constant of the given row is obviously
1113 * non-negative, meaning that we don't need to consult the context tableau.
1114 * If there is a big parameter and its coefficient is non-zero,
1115 * then this coefficient determines the outcome.
1116 * Otherwise, we check whether the constant is non-negative and
1117 * all non-zero coefficients of parameters are positive and
1118 * belong to non-negative parameters.
1120 static int is_obviously_nonneg(struct isl_tab *tab, int row)
1122 int i;
1123 int col;
1124 unsigned off = 2 + tab->M;
1126 if (tab->M) {
1127 if (isl_int_is_pos(tab->mat->row[row][2]))
1128 return 1;
1129 if (isl_int_is_neg(tab->mat->row[row][2]))
1130 return 0;
1133 if (isl_int_is_neg(tab->mat->row[row][1]))
1134 return 0;
1135 for (i = 0; i < tab->n_param; ++i) {
1136 /* Eliminated parameter */
1137 if (tab->var[i].is_row)
1138 continue;
1139 col = tab->var[i].index;
1140 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1141 continue;
1142 if (!tab->var[i].is_nonneg)
1143 return 0;
1144 if (isl_int_is_neg(tab->mat->row[row][off + col]))
1145 return 0;
1147 for (i = 0; i < tab->n_div; ++i) {
1148 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1149 continue;
1150 col = tab->var[tab->n_var - tab->n_div + i].index;
1151 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1152 continue;
1153 if (!tab->var[tab->n_var - tab->n_div + i].is_nonneg)
1154 return 0;
1155 if (isl_int_is_neg(tab->mat->row[row][off + col]))
1156 return 0;
1158 return 1;
1161 /* Given a row r and two columns, return the column that would
1162 * lead to the lexicographically smallest increment in the sample
1163 * solution when leaving the basis in favor of the row.
1164 * Pivoting with column c will increment the sample value by a non-negative
1165 * constant times a_{V,c}/a_{r,c}, with a_{V,c} the elements of column c
1166 * corresponding to the non-parametric variables.
1167 * If variable v appears in a column c_v, then a_{v,c} = 1 iff c = c_v,
1168 * with all other entries in this virtual row equal to zero.
1169 * If variable v appears in a row, then a_{v,c} is the element in column c
1170 * of that row.
1172 * Let v be the first variable with a_{v,c1}/a_{r,c1} != a_{v,c2}/a_{r,c2}.
1173 * Then if a_{v,c1}/a_{r,c1} < a_{v,c2}/a_{r,c2}, i.e.,
1174 * a_{v,c2} a_{r,c1} - a_{v,c1} a_{r,c2} > 0, c1 results in the minimal
1175 * increment. Otherwise, it's c2.
1177 static int lexmin_col_pair(struct isl_tab *tab,
1178 int row, int col1, int col2, isl_int tmp)
1180 int i;
1181 isl_int *tr;
1183 tr = tab->mat->row[row] + 2 + tab->M;
1185 for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
1186 int s1, s2;
1187 isl_int *r;
1189 if (!tab->var[i].is_row) {
1190 if (tab->var[i].index == col1)
1191 return col2;
1192 if (tab->var[i].index == col2)
1193 return col1;
1194 continue;
1197 if (tab->var[i].index == row)
1198 continue;
1200 r = tab->mat->row[tab->var[i].index] + 2 + tab->M;
1201 s1 = isl_int_sgn(r[col1]);
1202 s2 = isl_int_sgn(r[col2]);
1203 if (s1 == 0 && s2 == 0)
1204 continue;
1205 if (s1 < s2)
1206 return col1;
1207 if (s2 < s1)
1208 return col2;
1210 isl_int_mul(tmp, r[col2], tr[col1]);
1211 isl_int_submul(tmp, r[col1], tr[col2]);
1212 if (isl_int_is_pos(tmp))
1213 return col1;
1214 if (isl_int_is_neg(tmp))
1215 return col2;
1217 return -1;
1220 /* Does the index into the tab->var or tab->con array "index"
1221 * correspond to a variable in the context tableau?
1222 * In particular, it needs to be an index into the tab->var array and
1223 * it needs to refer to either one of the first tab->n_param variables or
1224 * one of the last tab->n_div variables.
1226 static int is_parameter_var(struct isl_tab *tab, int index)
1228 if (index < 0)
1229 return 0;
1230 if (index < tab->n_param)
1231 return 1;
1232 if (index >= tab->n_var - tab->n_div)
1233 return 1;
1234 return 0;
1237 /* Does column "col" of "tab" refer to a variable in the context tableau?
1239 static int col_is_parameter_var(struct isl_tab *tab, int col)
1241 return is_parameter_var(tab, tab->col_var[col]);
1244 /* Does row "row" of "tab" refer to a variable in the context tableau?
1246 static int row_is_parameter_var(struct isl_tab *tab, int row)
1248 return is_parameter_var(tab, tab->row_var[row]);
1251 /* Given a row in the tableau, find and return the column that would
1252 * result in the lexicographically smallest, but positive, increment
1253 * in the sample point.
1254 * If there is no such column, then return tab->n_col.
1255 * If anything goes wrong, return -1.
1257 static int lexmin_pivot_col(struct isl_tab *tab, int row)
1259 int j;
1260 int col = tab->n_col;
1261 isl_int *tr;
1262 isl_int tmp;
1264 tr = tab->mat->row[row] + 2 + tab->M;
1266 isl_int_init(tmp);
1268 for (j = tab->n_dead; j < tab->n_col; ++j) {
1269 if (col_is_parameter_var(tab, j))
1270 continue;
1272 if (!isl_int_is_pos(tr[j]))
1273 continue;
1275 if (col == tab->n_col)
1276 col = j;
1277 else
1278 col = lexmin_col_pair(tab, row, col, j, tmp);
1279 isl_assert(tab->mat->ctx, col >= 0, goto error);
1282 isl_int_clear(tmp);
1283 return col;
1284 error:
1285 isl_int_clear(tmp);
1286 return -1;
1289 /* Return the first known violated constraint, i.e., a non-negative
1290 * constraint that currently has an either obviously negative value
1291 * or a previously determined to be negative value.
1293 * If any constraint has a negative coefficient for the big parameter,
1294 * if any, then we return one of these first.
1296 static int first_neg(struct isl_tab *tab)
1298 int row;
1300 if (tab->M)
1301 for (row = tab->n_redundant; row < tab->n_row; ++row) {
1302 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1303 continue;
1304 if (!isl_int_is_neg(tab->mat->row[row][2]))
1305 continue;
1306 if (tab->row_sign)
1307 tab->row_sign[row] = isl_tab_row_neg;
1308 return row;
1310 for (row = tab->n_redundant; row < tab->n_row; ++row) {
1311 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
1312 continue;
1313 if (tab->row_sign) {
1314 if (tab->row_sign[row] == 0 &&
1315 is_obviously_neg(tab, row))
1316 tab->row_sign[row] = isl_tab_row_neg;
1317 if (tab->row_sign[row] != isl_tab_row_neg)
1318 continue;
1319 } else if (!is_obviously_neg(tab, row))
1320 continue;
1321 return row;
1323 return -1;
1326 /* Check whether the invariant that all columns are lexico-positive
1327 * is satisfied. This function is not called from the current code
1328 * but is useful during debugging.
1330 static void check_lexpos(struct isl_tab *tab) __attribute__ ((unused));
1331 static void check_lexpos(struct isl_tab *tab)
1333 unsigned off = 2 + tab->M;
1334 int col;
1335 int var;
1336 int row;
1338 for (col = tab->n_dead; col < tab->n_col; ++col) {
1339 if (col_is_parameter_var(tab, col))
1340 continue;
1341 for (var = tab->n_param; var < tab->n_var - tab->n_div; ++var) {
1342 if (!tab->var[var].is_row) {
1343 if (tab->var[var].index == col)
1344 break;
1345 else
1346 continue;
1348 row = tab->var[var].index;
1349 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1350 continue;
1351 if (isl_int_is_pos(tab->mat->row[row][off + col]))
1352 break;
1353 fprintf(stderr, "lexneg column %d (row %d)\n",
1354 col, row);
1356 if (var >= tab->n_var - tab->n_div)
1357 fprintf(stderr, "zero column %d\n", col);
1361 /* Report to the caller that the given constraint is part of an encountered
1362 * conflict.
1364 static int report_conflicting_constraint(struct isl_tab *tab, int con)
1366 return tab->conflict(con, tab->conflict_user);
1369 /* Given a conflicting row in the tableau, report all constraints
1370 * involved in the row to the caller. That is, the row itself
1371 * (if it represents a constraint) and all constraint columns with
1372 * non-zero (and therefore negative) coefficients.
1374 static int report_conflict(struct isl_tab *tab, int row)
1376 int j;
1377 isl_int *tr;
1379 if (!tab->conflict)
1380 return 0;
1382 if (tab->row_var[row] < 0 &&
1383 report_conflicting_constraint(tab, ~tab->row_var[row]) < 0)
1384 return -1;
1386 tr = tab->mat->row[row] + 2 + tab->M;
1388 for (j = tab->n_dead; j < tab->n_col; ++j) {
1389 if (col_is_parameter_var(tab, j))
1390 continue;
1392 if (!isl_int_is_neg(tr[j]))
1393 continue;
1395 if (tab->col_var[j] < 0 &&
1396 report_conflicting_constraint(tab, ~tab->col_var[j]) < 0)
1397 return -1;
1400 return 0;
1403 /* Resolve all known or obviously violated constraints through pivoting.
1404 * In particular, as long as we can find any violated constraint, we
1405 * look for a pivoting column that would result in the lexicographically
1406 * smallest increment in the sample point. If there is no such column
1407 * then the tableau is infeasible.
1409 static int restore_lexmin(struct isl_tab *tab) WARN_UNUSED;
1410 static int restore_lexmin(struct isl_tab *tab)
1412 int row, col;
1414 if (!tab)
1415 return -1;
1416 if (tab->empty)
1417 return 0;
1418 while ((row = first_neg(tab)) != -1) {
1419 col = lexmin_pivot_col(tab, row);
1420 if (col >= tab->n_col) {
1421 if (report_conflict(tab, row) < 0)
1422 return -1;
1423 if (isl_tab_mark_empty(tab) < 0)
1424 return -1;
1425 return 0;
1427 if (col < 0)
1428 return -1;
1429 if (isl_tab_pivot(tab, row, col) < 0)
1430 return -1;
1432 return 0;
1435 /* Given a row that represents an equality, look for an appropriate
1436 * pivoting column.
1437 * In particular, if there are any non-zero coefficients among
1438 * the non-parameter variables, then we take the last of these
1439 * variables. Eliminating this variable in terms of the other
1440 * variables and/or parameters does not influence the property
1441 * that all column in the initial tableau are lexicographically
1442 * positive. The row corresponding to the eliminated variable
1443 * will only have non-zero entries below the diagonal of the
1444 * initial tableau. That is, we transform
1446 * I I
1447 * 1 into a
1448 * I I
1450 * If there is no such non-parameter variable, then we are dealing with
1451 * pure parameter equality and we pick any parameter with coefficient 1 or -1
1452 * for elimination. This will ensure that the eliminated parameter
1453 * always has an integer value whenever all the other parameters are integral.
1454 * If there is no such parameter then we return -1.
1456 static int last_var_col_or_int_par_col(struct isl_tab *tab, int row)
1458 unsigned off = 2 + tab->M;
1459 int i;
1461 for (i = tab->n_var - tab->n_div - 1; i >= 0 && i >= tab->n_param; --i) {
1462 int col;
1463 if (tab->var[i].is_row)
1464 continue;
1465 col = tab->var[i].index;
1466 if (col <= tab->n_dead)
1467 continue;
1468 if (!isl_int_is_zero(tab->mat->row[row][off + col]))
1469 return col;
1471 for (i = tab->n_dead; i < tab->n_col; ++i) {
1472 if (isl_int_is_one(tab->mat->row[row][off + i]))
1473 return i;
1474 if (isl_int_is_negone(tab->mat->row[row][off + i]))
1475 return i;
1477 return -1;
1480 /* Add an equality that is known to be valid to the tableau.
1481 * We first check if we can eliminate a variable or a parameter.
1482 * If not, we add the equality as two inequalities.
1483 * In this case, the equality was a pure parameter equality and there
1484 * is no need to resolve any constraint violations.
1486 * This function assumes that at least two more rows and at least
1487 * two more elements in the constraint array are available in the tableau.
1489 static struct isl_tab *add_lexmin_valid_eq(struct isl_tab *tab, isl_int *eq)
1491 int i;
1492 int r;
1494 if (!tab)
1495 return NULL;
1496 r = isl_tab_add_row(tab, eq);
1497 if (r < 0)
1498 goto error;
1500 r = tab->con[r].index;
1501 i = last_var_col_or_int_par_col(tab, r);
1502 if (i < 0) {
1503 tab->con[r].is_nonneg = 1;
1504 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1505 goto error;
1506 isl_seq_neg(eq, eq, 1 + tab->n_var);
1507 r = isl_tab_add_row(tab, eq);
1508 if (r < 0)
1509 goto error;
1510 tab->con[r].is_nonneg = 1;
1511 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1512 goto error;
1513 } else {
1514 if (isl_tab_pivot(tab, r, i) < 0)
1515 goto error;
1516 if (isl_tab_kill_col(tab, i) < 0)
1517 goto error;
1518 tab->n_eq++;
1521 return tab;
1522 error:
1523 isl_tab_free(tab);
1524 return NULL;
1527 /* Check if the given row is a pure constant.
1529 static int is_constant(struct isl_tab *tab, int row)
1531 unsigned off = 2 + tab->M;
1533 return isl_seq_first_non_zero(tab->mat->row[row] + off + tab->n_dead,
1534 tab->n_col - tab->n_dead) == -1;
1537 /* Is the given row a parametric constant?
1538 * That is, does it only involve variables that also appear in the context?
1540 static int is_parametric_constant(struct isl_tab *tab, int row)
1542 unsigned off = 2 + tab->M;
1543 int col;
1545 for (col = tab->n_dead; col < tab->n_col; ++col) {
1546 if (col_is_parameter_var(tab, col))
1547 continue;
1548 if (isl_int_is_zero(tab->mat->row[row][off + col]))
1549 continue;
1550 return 0;
1553 return 1;
1556 /* Add an equality that may or may not be valid to the tableau.
1557 * If the resulting row is a pure constant, then it must be zero.
1558 * Otherwise, the resulting tableau is empty.
1560 * If the row is not a pure constant, then we add two inequalities,
1561 * each time checking that they can be satisfied.
1562 * In the end we try to use one of the two constraints to eliminate
1563 * a column.
1565 * This function assumes that at least two more rows and at least
1566 * two more elements in the constraint array are available in the tableau.
1568 static int add_lexmin_eq(struct isl_tab *tab, isl_int *eq) WARN_UNUSED;
1569 static int add_lexmin_eq(struct isl_tab *tab, isl_int *eq)
1571 int r1, r2;
1572 int row;
1573 struct isl_tab_undo *snap;
1575 if (!tab)
1576 return -1;
1577 snap = isl_tab_snap(tab);
1578 r1 = isl_tab_add_row(tab, eq);
1579 if (r1 < 0)
1580 return -1;
1581 tab->con[r1].is_nonneg = 1;
1582 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r1]) < 0)
1583 return -1;
1585 row = tab->con[r1].index;
1586 if (is_constant(tab, row)) {
1587 if (!isl_int_is_zero(tab->mat->row[row][1]) ||
1588 (tab->M && !isl_int_is_zero(tab->mat->row[row][2]))) {
1589 if (isl_tab_mark_empty(tab) < 0)
1590 return -1;
1591 return 0;
1593 if (isl_tab_rollback(tab, snap) < 0)
1594 return -1;
1595 return 0;
1598 if (restore_lexmin(tab) < 0)
1599 return -1;
1600 if (tab->empty)
1601 return 0;
1603 isl_seq_neg(eq, eq, 1 + tab->n_var);
1605 r2 = isl_tab_add_row(tab, eq);
1606 if (r2 < 0)
1607 return -1;
1608 tab->con[r2].is_nonneg = 1;
1609 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r2]) < 0)
1610 return -1;
1612 if (restore_lexmin(tab) < 0)
1613 return -1;
1614 if (tab->empty)
1615 return 0;
1617 if (!tab->con[r1].is_row) {
1618 if (isl_tab_kill_col(tab, tab->con[r1].index) < 0)
1619 return -1;
1620 } else if (!tab->con[r2].is_row) {
1621 if (isl_tab_kill_col(tab, tab->con[r2].index) < 0)
1622 return -1;
1625 if (tab->bmap) {
1626 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1627 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1628 return -1;
1629 isl_seq_neg(eq, eq, 1 + tab->n_var);
1630 tab->bmap = isl_basic_map_add_ineq(tab->bmap, eq);
1631 isl_seq_neg(eq, eq, 1 + tab->n_var);
1632 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1633 return -1;
1634 if (!tab->bmap)
1635 return -1;
1638 return 0;
1641 /* Add an inequality to the tableau, resolving violations using
1642 * restore_lexmin.
1644 * This function assumes that at least one more row and at least
1645 * one more element in the constraint array are available in the tableau.
1647 static struct isl_tab *add_lexmin_ineq(struct isl_tab *tab, isl_int *ineq)
1649 int r;
1651 if (!tab)
1652 return NULL;
1653 if (tab->bmap) {
1654 tab->bmap = isl_basic_map_add_ineq(tab->bmap, ineq);
1655 if (isl_tab_push(tab, isl_tab_undo_bmap_ineq) < 0)
1656 goto error;
1657 if (!tab->bmap)
1658 goto error;
1660 r = isl_tab_add_row(tab, ineq);
1661 if (r < 0)
1662 goto error;
1663 tab->con[r].is_nonneg = 1;
1664 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1665 goto error;
1666 if (isl_tab_row_is_redundant(tab, tab->con[r].index)) {
1667 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1668 goto error;
1669 return tab;
1672 if (restore_lexmin(tab) < 0)
1673 goto error;
1674 if (!tab->empty && tab->con[r].is_row &&
1675 isl_tab_row_is_redundant(tab, tab->con[r].index))
1676 if (isl_tab_mark_redundant(tab, tab->con[r].index) < 0)
1677 goto error;
1678 return tab;
1679 error:
1680 isl_tab_free(tab);
1681 return NULL;
1684 /* Check if the coefficients of the parameters are all integral.
1686 static int integer_parameter(struct isl_tab *tab, int row)
1688 int i;
1689 int col;
1690 unsigned off = 2 + tab->M;
1692 for (i = 0; i < tab->n_param; ++i) {
1693 /* Eliminated parameter */
1694 if (tab->var[i].is_row)
1695 continue;
1696 col = tab->var[i].index;
1697 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1698 tab->mat->row[row][0]))
1699 return 0;
1701 for (i = 0; i < tab->n_div; ++i) {
1702 if (tab->var[tab->n_var - tab->n_div + i].is_row)
1703 continue;
1704 col = tab->var[tab->n_var - tab->n_div + i].index;
1705 if (!isl_int_is_divisible_by(tab->mat->row[row][off + col],
1706 tab->mat->row[row][0]))
1707 return 0;
1709 return 1;
1712 /* Check if the coefficients of the non-parameter variables are all integral.
1714 static int integer_variable(struct isl_tab *tab, int row)
1716 int i;
1717 unsigned off = 2 + tab->M;
1719 for (i = tab->n_dead; i < tab->n_col; ++i) {
1720 if (col_is_parameter_var(tab, i))
1721 continue;
1722 if (!isl_int_is_divisible_by(tab->mat->row[row][off + i],
1723 tab->mat->row[row][0]))
1724 return 0;
1726 return 1;
1729 /* Check if the constant term is integral.
1731 static int integer_constant(struct isl_tab *tab, int row)
1733 return isl_int_is_divisible_by(tab->mat->row[row][1],
1734 tab->mat->row[row][0]);
1737 #define I_CST 1 << 0
1738 #define I_PAR 1 << 1
1739 #define I_VAR 1 << 2
1741 /* Check for next (non-parameter) variable after "var" (first if var == -1)
1742 * that is non-integer and therefore requires a cut and return
1743 * the index of the variable.
1744 * For parametric tableaus, there are three parts in a row,
1745 * the constant, the coefficients of the parameters and the rest.
1746 * For each part, we check whether the coefficients in that part
1747 * are all integral and if so, set the corresponding flag in *f.
1748 * If the constant and the parameter part are integral, then the
1749 * current sample value is integral and no cut is required
1750 * (irrespective of whether the variable part is integral).
1752 static int next_non_integer_var(struct isl_tab *tab, int var, int *f)
1754 var = var < 0 ? tab->n_param : var + 1;
1756 for (; var < tab->n_var - tab->n_div; ++var) {
1757 int flags = 0;
1758 int row;
1759 if (!tab->var[var].is_row)
1760 continue;
1761 row = tab->var[var].index;
1762 if (integer_constant(tab, row))
1763 ISL_FL_SET(flags, I_CST);
1764 if (integer_parameter(tab, row))
1765 ISL_FL_SET(flags, I_PAR);
1766 if (ISL_FL_ISSET(flags, I_CST) && ISL_FL_ISSET(flags, I_PAR))
1767 continue;
1768 if (integer_variable(tab, row))
1769 ISL_FL_SET(flags, I_VAR);
1770 *f = flags;
1771 return var;
1773 return -1;
1776 /* Check for first (non-parameter) variable that is non-integer and
1777 * therefore requires a cut and return the corresponding row.
1778 * For parametric tableaus, there are three parts in a row,
1779 * the constant, the coefficients of the parameters and the rest.
1780 * For each part, we check whether the coefficients in that part
1781 * are all integral and if so, set the corresponding flag in *f.
1782 * If the constant and the parameter part are integral, then the
1783 * current sample value is integral and no cut is required
1784 * (irrespective of whether the variable part is integral).
1786 static int first_non_integer_row(struct isl_tab *tab, int *f)
1788 int var = next_non_integer_var(tab, -1, f);
1790 return var < 0 ? -1 : tab->var[var].index;
1793 /* Add a (non-parametric) cut to cut away the non-integral sample
1794 * value of the given row.
1796 * If the row is given by
1798 * m r = f + \sum_i a_i y_i
1800 * then the cut is
1802 * c = - {-f/m} + \sum_i {a_i/m} y_i >= 0
1804 * The big parameter, if any, is ignored, since it is assumed to be big
1805 * enough to be divisible by any integer.
1806 * If the tableau is actually a parametric tableau, then this function
1807 * is only called when all coefficients of the parameters are integral.
1808 * The cut therefore has zero coefficients for the parameters.
1810 * The current value is known to be negative, so row_sign, if it
1811 * exists, is set accordingly.
1813 * Return the row of the cut or -1.
1815 static int add_cut(struct isl_tab *tab, int row)
1817 int i;
1818 int r;
1819 isl_int *r_row;
1820 unsigned off = 2 + tab->M;
1822 if (isl_tab_extend_cons(tab, 1) < 0)
1823 return -1;
1824 r = isl_tab_allocate_con(tab);
1825 if (r < 0)
1826 return -1;
1828 r_row = tab->mat->row[tab->con[r].index];
1829 isl_int_set(r_row[0], tab->mat->row[row][0]);
1830 isl_int_neg(r_row[1], tab->mat->row[row][1]);
1831 isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
1832 isl_int_neg(r_row[1], r_row[1]);
1833 if (tab->M)
1834 isl_int_set_si(r_row[2], 0);
1835 for (i = 0; i < tab->n_col; ++i)
1836 isl_int_fdiv_r(r_row[off + i],
1837 tab->mat->row[row][off + i], tab->mat->row[row][0]);
1839 tab->con[r].is_nonneg = 1;
1840 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
1841 return -1;
1842 if (tab->row_sign)
1843 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
1845 return tab->con[r].index;
1848 #define CUT_ALL 1
1849 #define CUT_ONE 0
1851 /* Given a non-parametric tableau, add cuts until an integer
1852 * sample point is obtained or until the tableau is determined
1853 * to be integer infeasible.
1854 * As long as there is any non-integer value in the sample point,
1855 * we add appropriate cuts, if possible, for each of these
1856 * non-integer values and then resolve the violated
1857 * cut constraints using restore_lexmin.
1858 * If one of the corresponding rows is equal to an integral
1859 * combination of variables/constraints plus a non-integral constant,
1860 * then there is no way to obtain an integer point and we return
1861 * a tableau that is marked empty.
1862 * The parameter cutting_strategy controls the strategy used when adding cuts
1863 * to remove non-integer points. CUT_ALL adds all possible cuts
1864 * before continuing the search. CUT_ONE adds only one cut at a time.
1866 static struct isl_tab *cut_to_integer_lexmin(struct isl_tab *tab,
1867 int cutting_strategy)
1869 int var;
1870 int row;
1871 int flags;
1873 if (!tab)
1874 return NULL;
1875 if (tab->empty)
1876 return tab;
1878 while ((var = next_non_integer_var(tab, -1, &flags)) != -1) {
1879 do {
1880 if (ISL_FL_ISSET(flags, I_VAR)) {
1881 if (isl_tab_mark_empty(tab) < 0)
1882 goto error;
1883 return tab;
1885 row = tab->var[var].index;
1886 row = add_cut(tab, row);
1887 if (row < 0)
1888 goto error;
1889 if (cutting_strategy == CUT_ONE)
1890 break;
1891 } while ((var = next_non_integer_var(tab, var, &flags)) != -1);
1892 if (restore_lexmin(tab) < 0)
1893 goto error;
1894 if (tab->empty)
1895 break;
1897 return tab;
1898 error:
1899 isl_tab_free(tab);
1900 return NULL;
1903 /* Check whether all the currently active samples also satisfy the inequality
1904 * "ineq" (treated as an equality if eq is set).
1905 * Remove those samples that do not.
1907 static struct isl_tab *check_samples(struct isl_tab *tab, isl_int *ineq, int eq)
1909 int i;
1910 isl_int v;
1912 if (!tab)
1913 return NULL;
1915 isl_assert(tab->mat->ctx, tab->bmap, goto error);
1916 isl_assert(tab->mat->ctx, tab->samples, goto error);
1917 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, goto error);
1919 isl_int_init(v);
1920 for (i = tab->n_outside; i < tab->n_sample; ++i) {
1921 int sgn;
1922 isl_seq_inner_product(ineq, tab->samples->row[i],
1923 1 + tab->n_var, &v);
1924 sgn = isl_int_sgn(v);
1925 if (eq ? (sgn == 0) : (sgn >= 0))
1926 continue;
1927 tab = isl_tab_drop_sample(tab, i);
1928 if (!tab)
1929 break;
1931 isl_int_clear(v);
1933 return tab;
1934 error:
1935 isl_tab_free(tab);
1936 return NULL;
1939 /* Check whether the sample value of the tableau is finite,
1940 * i.e., either the tableau does not use a big parameter, or
1941 * all values of the variables are equal to the big parameter plus
1942 * some constant. This constant is the actual sample value.
1944 static int sample_is_finite(struct isl_tab *tab)
1946 int i;
1948 if (!tab->M)
1949 return 1;
1951 for (i = 0; i < tab->n_var; ++i) {
1952 int row;
1953 if (!tab->var[i].is_row)
1954 return 0;
1955 row = tab->var[i].index;
1956 if (isl_int_ne(tab->mat->row[row][0], tab->mat->row[row][2]))
1957 return 0;
1959 return 1;
1962 /* Check if the context tableau of sol has any integer points.
1963 * Leave tab in empty state if no integer point can be found.
1964 * If an integer point can be found and if moreover it is finite,
1965 * then it is added to the list of sample values.
1967 * This function is only called when none of the currently active sample
1968 * values satisfies the most recently added constraint.
1970 static struct isl_tab *check_integer_feasible(struct isl_tab *tab)
1972 struct isl_tab_undo *snap;
1974 if (!tab)
1975 return NULL;
1977 snap = isl_tab_snap(tab);
1978 if (isl_tab_push_basis(tab) < 0)
1979 goto error;
1981 tab = cut_to_integer_lexmin(tab, CUT_ALL);
1982 if (!tab)
1983 goto error;
1985 if (!tab->empty && sample_is_finite(tab)) {
1986 struct isl_vec *sample;
1988 sample = isl_tab_get_sample_value(tab);
1990 if (isl_tab_add_sample(tab, sample) < 0)
1991 goto error;
1994 if (!tab->empty && isl_tab_rollback(tab, snap) < 0)
1995 goto error;
1997 return tab;
1998 error:
1999 isl_tab_free(tab);
2000 return NULL;
2003 /* Check if any of the currently active sample values satisfies
2004 * the inequality "ineq" (an equality if eq is set).
2006 static int tab_has_valid_sample(struct isl_tab *tab, isl_int *ineq, int eq)
2008 int i;
2009 isl_int v;
2011 if (!tab)
2012 return -1;
2014 isl_assert(tab->mat->ctx, tab->bmap, return -1);
2015 isl_assert(tab->mat->ctx, tab->samples, return -1);
2016 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var, return -1);
2018 isl_int_init(v);
2019 for (i = tab->n_outside; i < tab->n_sample; ++i) {
2020 int sgn;
2021 isl_seq_inner_product(ineq, tab->samples->row[i],
2022 1 + tab->n_var, &v);
2023 sgn = isl_int_sgn(v);
2024 if (eq ? (sgn == 0) : (sgn >= 0))
2025 break;
2027 isl_int_clear(v);
2029 return i < tab->n_sample;
2032 /* Insert a div specified by "div" to the tableau "tab" at position "pos" and
2033 * return isl_bool_true if the div is obviously non-negative.
2035 static isl_bool context_tab_insert_div(struct isl_tab *tab, int pos,
2036 __isl_keep isl_vec *div,
2037 isl_stat (*add_ineq)(void *user, isl_int *), void *user)
2039 int i;
2040 int r;
2041 struct isl_mat *samples;
2042 int nonneg;
2044 r = isl_tab_insert_div(tab, pos, div, add_ineq, user);
2045 if (r < 0)
2046 return isl_bool_error;
2047 nonneg = tab->var[r].is_nonneg;
2048 tab->var[r].frozen = 1;
2050 samples = isl_mat_extend(tab->samples,
2051 tab->n_sample, 1 + tab->n_var);
2052 tab->samples = samples;
2053 if (!samples)
2054 return isl_bool_error;
2055 for (i = tab->n_outside; i < samples->n_row; ++i) {
2056 isl_seq_inner_product(div->el + 1, samples->row[i],
2057 div->size - 1, &samples->row[i][samples->n_col - 1]);
2058 isl_int_fdiv_q(samples->row[i][samples->n_col - 1],
2059 samples->row[i][samples->n_col - 1], div->el[0]);
2061 tab->samples = isl_mat_move_cols(tab->samples, 1 + pos,
2062 1 + tab->n_var - 1, 1);
2063 if (!tab->samples)
2064 return isl_bool_error;
2066 return nonneg;
2069 /* Add a div specified by "div" to both the main tableau and
2070 * the context tableau. In case of the main tableau, we only
2071 * need to add an extra div. In the context tableau, we also
2072 * need to express the meaning of the div.
2073 * Return the index of the div or -1 if anything went wrong.
2075 * The new integer division is added before any unknown integer
2076 * divisions in the context to ensure that it does not get
2077 * equated to some linear combination involving unknown integer
2078 * divisions.
2080 static int add_div(struct isl_tab *tab, struct isl_context *context,
2081 __isl_keep isl_vec *div)
2083 int r;
2084 int pos;
2085 isl_bool nonneg;
2086 struct isl_tab *context_tab = context->op->peek_tab(context);
2088 if (!tab || !context_tab)
2089 goto error;
2091 pos = context_tab->n_var - context->n_unknown;
2092 if ((nonneg = context->op->insert_div(context, pos, div)) < 0)
2093 goto error;
2095 if (!context->op->is_ok(context))
2096 goto error;
2098 pos = tab->n_var - context->n_unknown;
2099 if (isl_tab_extend_vars(tab, 1) < 0)
2100 goto error;
2101 r = isl_tab_insert_var(tab, pos);
2102 if (r < 0)
2103 goto error;
2104 if (nonneg)
2105 tab->var[r].is_nonneg = 1;
2106 tab->var[r].frozen = 1;
2107 tab->n_div++;
2109 return tab->n_div - 1 - context->n_unknown;
2110 error:
2111 context->op->invalidate(context);
2112 return -1;
2115 /* Return the position of the integer division that is equal to div/denom
2116 * if there is one. Otherwise, return a position beyond the integer divisions.
2118 static int find_div(struct isl_tab *tab, isl_int *div, isl_int denom)
2120 int i;
2121 unsigned total = isl_basic_map_total_dim(tab->bmap);
2122 unsigned n_div;
2124 n_div = isl_basic_map_dim(tab->bmap, isl_dim_div);
2125 for (i = 0; i < n_div; ++i) {
2126 if (isl_int_ne(tab->bmap->div[i][0], denom))
2127 continue;
2128 if (!isl_seq_eq(tab->bmap->div[i] + 1, div, 1 + total))
2129 continue;
2130 return i;
2132 return n_div;
2135 /* Return the index of a div that corresponds to "div".
2136 * We first check if we already have such a div and if not, we create one.
2138 static int get_div(struct isl_tab *tab, struct isl_context *context,
2139 struct isl_vec *div)
2141 int d;
2142 struct isl_tab *context_tab = context->op->peek_tab(context);
2143 unsigned n_div;
2145 if (!context_tab)
2146 return -1;
2148 n_div = isl_basic_map_dim(context_tab->bmap, isl_dim_div);
2149 d = find_div(context_tab, div->el + 1, div->el[0]);
2150 if (d < 0)
2151 return -1;
2152 if (d < n_div)
2153 return d;
2155 return add_div(tab, context, div);
2158 /* Add a parametric cut to cut away the non-integral sample value
2159 * of the given row.
2160 * Let a_i be the coefficients of the constant term and the parameters
2161 * and let b_i be the coefficients of the variables or constraints
2162 * in basis of the tableau.
2163 * Let q be the div q = floor(\sum_i {-a_i} y_i).
2165 * The cut is expressed as
2167 * c = \sum_i -{-a_i} y_i + \sum_i {b_i} x_i + q >= 0
2169 * If q did not already exist in the context tableau, then it is added first.
2170 * If q is in a column of the main tableau then the "+ q" can be accomplished
2171 * by setting the corresponding entry to the denominator of the constraint.
2172 * If q happens to be in a row of the main tableau, then the corresponding
2173 * row needs to be added instead (taking care of the denominators).
2174 * Note that this is very unlikely, but perhaps not entirely impossible.
2176 * The current value of the cut is known to be negative (or at least
2177 * non-positive), so row_sign is set accordingly.
2179 * Return the row of the cut or -1.
2181 static int add_parametric_cut(struct isl_tab *tab, int row,
2182 struct isl_context *context)
2184 struct isl_vec *div;
2185 int d;
2186 int i;
2187 int r;
2188 isl_int *r_row;
2189 int col;
2190 int n;
2191 unsigned off = 2 + tab->M;
2193 if (!context)
2194 return -1;
2196 div = get_row_parameter_div(tab, row);
2197 if (!div)
2198 return -1;
2200 n = tab->n_div - context->n_unknown;
2201 d = context->op->get_div(context, tab, div);
2202 isl_vec_free(div);
2203 if (d < 0)
2204 return -1;
2206 if (isl_tab_extend_cons(tab, 1) < 0)
2207 return -1;
2208 r = isl_tab_allocate_con(tab);
2209 if (r < 0)
2210 return -1;
2212 r_row = tab->mat->row[tab->con[r].index];
2213 isl_int_set(r_row[0], tab->mat->row[row][0]);
2214 isl_int_neg(r_row[1], tab->mat->row[row][1]);
2215 isl_int_fdiv_r(r_row[1], r_row[1], tab->mat->row[row][0]);
2216 isl_int_neg(r_row[1], r_row[1]);
2217 if (tab->M)
2218 isl_int_set_si(r_row[2], 0);
2219 for (i = 0; i < tab->n_param; ++i) {
2220 if (tab->var[i].is_row)
2221 continue;
2222 col = tab->var[i].index;
2223 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
2224 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
2225 tab->mat->row[row][0]);
2226 isl_int_neg(r_row[off + col], r_row[off + col]);
2228 for (i = 0; i < tab->n_div; ++i) {
2229 if (tab->var[tab->n_var - tab->n_div + i].is_row)
2230 continue;
2231 col = tab->var[tab->n_var - tab->n_div + i].index;
2232 isl_int_neg(r_row[off + col], tab->mat->row[row][off + col]);
2233 isl_int_fdiv_r(r_row[off + col], r_row[off + col],
2234 tab->mat->row[row][0]);
2235 isl_int_neg(r_row[off + col], r_row[off + col]);
2237 for (i = 0; i < tab->n_col; ++i) {
2238 if (tab->col_var[i] >= 0 &&
2239 (tab->col_var[i] < tab->n_param ||
2240 tab->col_var[i] >= tab->n_var - tab->n_div))
2241 continue;
2242 isl_int_fdiv_r(r_row[off + i],
2243 tab->mat->row[row][off + i], tab->mat->row[row][0]);
2245 if (tab->var[tab->n_var - tab->n_div + d].is_row) {
2246 isl_int gcd;
2247 int d_row = tab->var[tab->n_var - tab->n_div + d].index;
2248 isl_int_init(gcd);
2249 isl_int_gcd(gcd, tab->mat->row[d_row][0], r_row[0]);
2250 isl_int_divexact(r_row[0], r_row[0], gcd);
2251 isl_int_divexact(gcd, tab->mat->row[d_row][0], gcd);
2252 isl_seq_combine(r_row + 1, gcd, r_row + 1,
2253 r_row[0], tab->mat->row[d_row] + 1,
2254 off - 1 + tab->n_col);
2255 isl_int_mul(r_row[0], r_row[0], tab->mat->row[d_row][0]);
2256 isl_int_clear(gcd);
2257 } else {
2258 col = tab->var[tab->n_var - tab->n_div + d].index;
2259 isl_int_set(r_row[off + col], tab->mat->row[row][0]);
2262 tab->con[r].is_nonneg = 1;
2263 if (isl_tab_push_var(tab, isl_tab_undo_nonneg, &tab->con[r]) < 0)
2264 return -1;
2265 if (tab->row_sign)
2266 tab->row_sign[tab->con[r].index] = isl_tab_row_neg;
2268 row = tab->con[r].index;
2270 if (d >= n && context->op->detect_equalities(context, tab) < 0)
2271 return -1;
2273 return row;
2276 /* Construct a tableau for bmap that can be used for computing
2277 * the lexicographic minimum (or maximum) of bmap.
2278 * If not NULL, then dom is the domain where the minimum
2279 * should be computed. In this case, we set up a parametric
2280 * tableau with row signs (initialized to "unknown").
2281 * If M is set, then the tableau will use a big parameter.
2282 * If max is set, then a maximum should be computed instead of a minimum.
2283 * This means that for each variable x, the tableau will contain the variable
2284 * x' = M - x, rather than x' = M + x. This in turn means that the coefficient
2285 * of the variables in all constraints are negated prior to adding them
2286 * to the tableau.
2288 static __isl_give struct isl_tab *tab_for_lexmin(__isl_keep isl_basic_map *bmap,
2289 __isl_keep isl_basic_set *dom, unsigned M, int max)
2291 int i;
2292 struct isl_tab *tab;
2293 unsigned n_var;
2294 unsigned o_var;
2296 tab = isl_tab_alloc(bmap->ctx, 2 * bmap->n_eq + bmap->n_ineq + 1,
2297 isl_basic_map_total_dim(bmap), M);
2298 if (!tab)
2299 return NULL;
2301 tab->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
2302 if (dom) {
2303 tab->n_param = isl_basic_set_total_dim(dom) - dom->n_div;
2304 tab->n_div = dom->n_div;
2305 tab->row_sign = isl_calloc_array(bmap->ctx,
2306 enum isl_tab_row_sign, tab->mat->n_row);
2307 if (tab->mat->n_row && !tab->row_sign)
2308 goto error;
2310 if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY)) {
2311 if (isl_tab_mark_empty(tab) < 0)
2312 goto error;
2313 return tab;
2316 for (i = tab->n_param; i < tab->n_var - tab->n_div; ++i) {
2317 tab->var[i].is_nonneg = 1;
2318 tab->var[i].frozen = 1;
2320 o_var = 1 + tab->n_param;
2321 n_var = tab->n_var - tab->n_param - tab->n_div;
2322 for (i = 0; i < bmap->n_eq; ++i) {
2323 if (max)
2324 isl_seq_neg(bmap->eq[i] + o_var,
2325 bmap->eq[i] + o_var, n_var);
2326 tab = add_lexmin_valid_eq(tab, bmap->eq[i]);
2327 if (max)
2328 isl_seq_neg(bmap->eq[i] + o_var,
2329 bmap->eq[i] + o_var, n_var);
2330 if (!tab || tab->empty)
2331 return tab;
2333 if (bmap->n_eq && restore_lexmin(tab) < 0)
2334 goto error;
2335 for (i = 0; i < bmap->n_ineq; ++i) {
2336 if (max)
2337 isl_seq_neg(bmap->ineq[i] + o_var,
2338 bmap->ineq[i] + o_var, n_var);
2339 tab = add_lexmin_ineq(tab, bmap->ineq[i]);
2340 if (max)
2341 isl_seq_neg(bmap->ineq[i] + o_var,
2342 bmap->ineq[i] + o_var, n_var);
2343 if (!tab || tab->empty)
2344 return tab;
2346 return tab;
2347 error:
2348 isl_tab_free(tab);
2349 return NULL;
2352 /* Given a main tableau where more than one row requires a split,
2353 * determine and return the "best" row to split on.
2355 * If any of the rows requiring a split only involves
2356 * variables that also appear in the context tableau,
2357 * then the negative part is guaranteed not to have a solution.
2358 * It is therefore best to split on any of these rows first.
2360 * Otherwise,
2361 * given two rows in the main tableau, if the inequality corresponding
2362 * to the first row is redundant with respect to that of the second row
2363 * in the current tableau, then it is better to split on the second row,
2364 * since in the positive part, both rows will be positive.
2365 * (In the negative part a pivot will have to be performed and just about
2366 * anything can happen to the sign of the other row.)
2368 * As a simple heuristic, we therefore select the row that makes the most
2369 * of the other rows redundant.
2371 * Perhaps it would also be useful to look at the number of constraints
2372 * that conflict with any given constraint.
2374 * best is the best row so far (-1 when we have not found any row yet).
2375 * best_r is the number of other rows made redundant by row best.
2376 * When best is still -1, bset_r is meaningless, but it is initialized
2377 * to some arbitrary value (0) anyway. Without this redundant initialization
2378 * valgrind may warn about uninitialized memory accesses when isl
2379 * is compiled with some versions of gcc.
2381 static int best_split(struct isl_tab *tab, struct isl_tab *context_tab)
2383 struct isl_tab_undo *snap;
2384 int split;
2385 int row;
2386 int best = -1;
2387 int best_r = 0;
2389 if (isl_tab_extend_cons(context_tab, 2) < 0)
2390 return -1;
2392 snap = isl_tab_snap(context_tab);
2394 for (split = tab->n_redundant; split < tab->n_row; ++split) {
2395 struct isl_tab_undo *snap2;
2396 struct isl_vec *ineq = NULL;
2397 int r = 0;
2398 int ok;
2400 if (!isl_tab_var_from_row(tab, split)->is_nonneg)
2401 continue;
2402 if (tab->row_sign[split] != isl_tab_row_any)
2403 continue;
2405 if (is_parametric_constant(tab, split))
2406 return split;
2408 ineq = get_row_parameter_ineq(tab, split);
2409 if (!ineq)
2410 return -1;
2411 ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2412 isl_vec_free(ineq);
2413 if (!ok)
2414 return -1;
2416 snap2 = isl_tab_snap(context_tab);
2418 for (row = tab->n_redundant; row < tab->n_row; ++row) {
2419 struct isl_tab_var *var;
2421 if (row == split)
2422 continue;
2423 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
2424 continue;
2425 if (tab->row_sign[row] != isl_tab_row_any)
2426 continue;
2428 ineq = get_row_parameter_ineq(tab, row);
2429 if (!ineq)
2430 return -1;
2431 ok = isl_tab_add_ineq(context_tab, ineq->el) >= 0;
2432 isl_vec_free(ineq);
2433 if (!ok)
2434 return -1;
2435 var = &context_tab->con[context_tab->n_con - 1];
2436 if (!context_tab->empty &&
2437 !isl_tab_min_at_most_neg_one(context_tab, var))
2438 r++;
2439 if (isl_tab_rollback(context_tab, snap2) < 0)
2440 return -1;
2442 if (best == -1 || r > best_r) {
2443 best = split;
2444 best_r = r;
2446 if (isl_tab_rollback(context_tab, snap) < 0)
2447 return -1;
2450 return best;
2453 static struct isl_basic_set *context_lex_peek_basic_set(
2454 struct isl_context *context)
2456 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2457 if (!clex->tab)
2458 return NULL;
2459 return isl_tab_peek_bset(clex->tab);
2462 static struct isl_tab *context_lex_peek_tab(struct isl_context *context)
2464 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2465 return clex->tab;
2468 static void context_lex_add_eq(struct isl_context *context, isl_int *eq,
2469 int check, int update)
2471 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2472 if (isl_tab_extend_cons(clex->tab, 2) < 0)
2473 goto error;
2474 if (add_lexmin_eq(clex->tab, eq) < 0)
2475 goto error;
2476 if (check) {
2477 int v = tab_has_valid_sample(clex->tab, eq, 1);
2478 if (v < 0)
2479 goto error;
2480 if (!v)
2481 clex->tab = check_integer_feasible(clex->tab);
2483 if (update)
2484 clex->tab = check_samples(clex->tab, eq, 1);
2485 return;
2486 error:
2487 isl_tab_free(clex->tab);
2488 clex->tab = NULL;
2491 static void context_lex_add_ineq(struct isl_context *context, isl_int *ineq,
2492 int check, int update)
2494 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2495 if (isl_tab_extend_cons(clex->tab, 1) < 0)
2496 goto error;
2497 clex->tab = add_lexmin_ineq(clex->tab, ineq);
2498 if (check) {
2499 int v = tab_has_valid_sample(clex->tab, ineq, 0);
2500 if (v < 0)
2501 goto error;
2502 if (!v)
2503 clex->tab = check_integer_feasible(clex->tab);
2505 if (update)
2506 clex->tab = check_samples(clex->tab, ineq, 0);
2507 return;
2508 error:
2509 isl_tab_free(clex->tab);
2510 clex->tab = NULL;
2513 static isl_stat context_lex_add_ineq_wrap(void *user, isl_int *ineq)
2515 struct isl_context *context = (struct isl_context *)user;
2516 context_lex_add_ineq(context, ineq, 0, 0);
2517 return context->op->is_ok(context) ? isl_stat_ok : isl_stat_error;
2520 /* Check which signs can be obtained by "ineq" on all the currently
2521 * active sample values. See row_sign for more information.
2523 static enum isl_tab_row_sign tab_ineq_sign(struct isl_tab *tab, isl_int *ineq,
2524 int strict)
2526 int i;
2527 int sgn;
2528 isl_int tmp;
2529 enum isl_tab_row_sign res = isl_tab_row_unknown;
2531 isl_assert(tab->mat->ctx, tab->samples, return isl_tab_row_unknown);
2532 isl_assert(tab->mat->ctx, tab->samples->n_col == 1 + tab->n_var,
2533 return isl_tab_row_unknown);
2535 isl_int_init(tmp);
2536 for (i = tab->n_outside; i < tab->n_sample; ++i) {
2537 isl_seq_inner_product(tab->samples->row[i], ineq,
2538 1 + tab->n_var, &tmp);
2539 sgn = isl_int_sgn(tmp);
2540 if (sgn > 0 || (sgn == 0 && strict)) {
2541 if (res == isl_tab_row_unknown)
2542 res = isl_tab_row_pos;
2543 if (res == isl_tab_row_neg)
2544 res = isl_tab_row_any;
2546 if (sgn < 0) {
2547 if (res == isl_tab_row_unknown)
2548 res = isl_tab_row_neg;
2549 if (res == isl_tab_row_pos)
2550 res = isl_tab_row_any;
2552 if (res == isl_tab_row_any)
2553 break;
2555 isl_int_clear(tmp);
2557 return res;
2560 static enum isl_tab_row_sign context_lex_ineq_sign(struct isl_context *context,
2561 isl_int *ineq, int strict)
2563 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2564 return tab_ineq_sign(clex->tab, ineq, strict);
2567 /* Check whether "ineq" can be added to the tableau without rendering
2568 * it infeasible.
2570 static int context_lex_test_ineq(struct isl_context *context, isl_int *ineq)
2572 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2573 struct isl_tab_undo *snap;
2574 int feasible;
2576 if (!clex->tab)
2577 return -1;
2579 if (isl_tab_extend_cons(clex->tab, 1) < 0)
2580 return -1;
2582 snap = isl_tab_snap(clex->tab);
2583 if (isl_tab_push_basis(clex->tab) < 0)
2584 return -1;
2585 clex->tab = add_lexmin_ineq(clex->tab, ineq);
2586 clex->tab = check_integer_feasible(clex->tab);
2587 if (!clex->tab)
2588 return -1;
2589 feasible = !clex->tab->empty;
2590 if (isl_tab_rollback(clex->tab, snap) < 0)
2591 return -1;
2593 return feasible;
2596 static int context_lex_get_div(struct isl_context *context, struct isl_tab *tab,
2597 struct isl_vec *div)
2599 return get_div(tab, context, div);
2602 /* Insert a div specified by "div" to the context tableau at position "pos" and
2603 * return isl_bool_true if the div is obviously non-negative.
2604 * context_tab_add_div will always return isl_bool_true, because all variables
2605 * in a isl_context_lex tableau are non-negative.
2606 * However, if we are using a big parameter in the context, then this only
2607 * reflects the non-negativity of the variable used to _encode_ the
2608 * div, i.e., div' = M + div, so we can't draw any conclusions.
2610 static isl_bool context_lex_insert_div(struct isl_context *context, int pos,
2611 __isl_keep isl_vec *div)
2613 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2614 isl_bool nonneg;
2615 nonneg = context_tab_insert_div(clex->tab, pos, div,
2616 context_lex_add_ineq_wrap, context);
2617 if (nonneg < 0)
2618 return isl_bool_error;
2619 if (clex->tab->M)
2620 return isl_bool_false;
2621 return nonneg;
2624 static int context_lex_detect_equalities(struct isl_context *context,
2625 struct isl_tab *tab)
2627 return 0;
2630 static int context_lex_best_split(struct isl_context *context,
2631 struct isl_tab *tab)
2633 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2634 struct isl_tab_undo *snap;
2635 int r;
2637 snap = isl_tab_snap(clex->tab);
2638 if (isl_tab_push_basis(clex->tab) < 0)
2639 return -1;
2640 r = best_split(tab, clex->tab);
2642 if (r >= 0 && isl_tab_rollback(clex->tab, snap) < 0)
2643 return -1;
2645 return r;
2648 static int context_lex_is_empty(struct isl_context *context)
2650 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2651 if (!clex->tab)
2652 return -1;
2653 return clex->tab->empty;
2656 static void *context_lex_save(struct isl_context *context)
2658 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2659 struct isl_tab_undo *snap;
2661 snap = isl_tab_snap(clex->tab);
2662 if (isl_tab_push_basis(clex->tab) < 0)
2663 return NULL;
2664 if (isl_tab_save_samples(clex->tab) < 0)
2665 return NULL;
2667 return snap;
2670 static void context_lex_restore(struct isl_context *context, void *save)
2672 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2673 if (isl_tab_rollback(clex->tab, (struct isl_tab_undo *)save) < 0) {
2674 isl_tab_free(clex->tab);
2675 clex->tab = NULL;
2679 static void context_lex_discard(void *save)
2683 static int context_lex_is_ok(struct isl_context *context)
2685 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2686 return !!clex->tab;
2689 /* For each variable in the context tableau, check if the variable can
2690 * only attain non-negative values. If so, mark the parameter as non-negative
2691 * in the main tableau. This allows for a more direct identification of some
2692 * cases of violated constraints.
2694 static struct isl_tab *tab_detect_nonnegative_parameters(struct isl_tab *tab,
2695 struct isl_tab *context_tab)
2697 int i;
2698 struct isl_tab_undo *snap;
2699 struct isl_vec *ineq = NULL;
2700 struct isl_tab_var *var;
2701 int n;
2703 if (context_tab->n_var == 0)
2704 return tab;
2706 ineq = isl_vec_alloc(tab->mat->ctx, 1 + context_tab->n_var);
2707 if (!ineq)
2708 goto error;
2710 if (isl_tab_extend_cons(context_tab, 1) < 0)
2711 goto error;
2713 snap = isl_tab_snap(context_tab);
2715 n = 0;
2716 isl_seq_clr(ineq->el, ineq->size);
2717 for (i = 0; i < context_tab->n_var; ++i) {
2718 isl_int_set_si(ineq->el[1 + i], 1);
2719 if (isl_tab_add_ineq(context_tab, ineq->el) < 0)
2720 goto error;
2721 var = &context_tab->con[context_tab->n_con - 1];
2722 if (!context_tab->empty &&
2723 !isl_tab_min_at_most_neg_one(context_tab, var)) {
2724 int j = i;
2725 if (i >= tab->n_param)
2726 j = i - tab->n_param + tab->n_var - tab->n_div;
2727 tab->var[j].is_nonneg = 1;
2728 n++;
2730 isl_int_set_si(ineq->el[1 + i], 0);
2731 if (isl_tab_rollback(context_tab, snap) < 0)
2732 goto error;
2735 if (context_tab->M && n == context_tab->n_var) {
2736 context_tab->mat = isl_mat_drop_cols(context_tab->mat, 2, 1);
2737 context_tab->M = 0;
2740 isl_vec_free(ineq);
2741 return tab;
2742 error:
2743 isl_vec_free(ineq);
2744 isl_tab_free(tab);
2745 return NULL;
2748 static struct isl_tab *context_lex_detect_nonnegative_parameters(
2749 struct isl_context *context, struct isl_tab *tab)
2751 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2752 struct isl_tab_undo *snap;
2754 if (!tab)
2755 return NULL;
2757 snap = isl_tab_snap(clex->tab);
2758 if (isl_tab_push_basis(clex->tab) < 0)
2759 goto error;
2761 tab = tab_detect_nonnegative_parameters(tab, clex->tab);
2763 if (isl_tab_rollback(clex->tab, snap) < 0)
2764 goto error;
2766 return tab;
2767 error:
2768 isl_tab_free(tab);
2769 return NULL;
2772 static void context_lex_invalidate(struct isl_context *context)
2774 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2775 isl_tab_free(clex->tab);
2776 clex->tab = NULL;
2779 static __isl_null struct isl_context *context_lex_free(
2780 struct isl_context *context)
2782 struct isl_context_lex *clex = (struct isl_context_lex *)context;
2783 isl_tab_free(clex->tab);
2784 free(clex);
2786 return NULL;
2789 struct isl_context_op isl_context_lex_op = {
2790 context_lex_detect_nonnegative_parameters,
2791 context_lex_peek_basic_set,
2792 context_lex_peek_tab,
2793 context_lex_add_eq,
2794 context_lex_add_ineq,
2795 context_lex_ineq_sign,
2796 context_lex_test_ineq,
2797 context_lex_get_div,
2798 context_lex_insert_div,
2799 context_lex_detect_equalities,
2800 context_lex_best_split,
2801 context_lex_is_empty,
2802 context_lex_is_ok,
2803 context_lex_save,
2804 context_lex_restore,
2805 context_lex_discard,
2806 context_lex_invalidate,
2807 context_lex_free,
2810 static struct isl_tab *context_tab_for_lexmin(__isl_take isl_basic_set *bset)
2812 struct isl_tab *tab;
2814 if (!bset)
2815 return NULL;
2816 tab = tab_for_lexmin(bset_to_bmap(bset), NULL, 1, 0);
2817 if (isl_tab_track_bset(tab, bset) < 0)
2818 goto error;
2819 tab = isl_tab_init_samples(tab);
2820 return tab;
2821 error:
2822 isl_tab_free(tab);
2823 return NULL;
2826 static struct isl_context *isl_context_lex_alloc(struct isl_basic_set *dom)
2828 struct isl_context_lex *clex;
2830 if (!dom)
2831 return NULL;
2833 clex = isl_alloc_type(dom->ctx, struct isl_context_lex);
2834 if (!clex)
2835 return NULL;
2837 clex->context.op = &isl_context_lex_op;
2839 clex->tab = context_tab_for_lexmin(isl_basic_set_copy(dom));
2840 if (restore_lexmin(clex->tab) < 0)
2841 goto error;
2842 clex->tab = check_integer_feasible(clex->tab);
2843 if (!clex->tab)
2844 goto error;
2846 return &clex->context;
2847 error:
2848 clex->context.op->free(&clex->context);
2849 return NULL;
2852 /* Representation of the context when using generalized basis reduction.
2854 * "shifted" contains the offsets of the unit hypercubes that lie inside the
2855 * context. Any rational point in "shifted" can therefore be rounded
2856 * up to an integer point in the context.
2857 * If the context is constrained by any equality, then "shifted" is not used
2858 * as it would be empty.
2860 struct isl_context_gbr {
2861 struct isl_context context;
2862 struct isl_tab *tab;
2863 struct isl_tab *shifted;
2864 struct isl_tab *cone;
2867 static struct isl_tab *context_gbr_detect_nonnegative_parameters(
2868 struct isl_context *context, struct isl_tab *tab)
2870 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2871 if (!tab)
2872 return NULL;
2873 return tab_detect_nonnegative_parameters(tab, cgbr->tab);
2876 static struct isl_basic_set *context_gbr_peek_basic_set(
2877 struct isl_context *context)
2879 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2880 if (!cgbr->tab)
2881 return NULL;
2882 return isl_tab_peek_bset(cgbr->tab);
2885 static struct isl_tab *context_gbr_peek_tab(struct isl_context *context)
2887 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
2888 return cgbr->tab;
2891 /* Initialize the "shifted" tableau of the context, which
2892 * contains the constraints of the original tableau shifted
2893 * by the sum of all negative coefficients. This ensures
2894 * that any rational point in the shifted tableau can
2895 * be rounded up to yield an integer point in the original tableau.
2897 static void gbr_init_shifted(struct isl_context_gbr *cgbr)
2899 int i, j;
2900 struct isl_vec *cst;
2901 struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
2902 unsigned dim = isl_basic_set_total_dim(bset);
2904 cst = isl_vec_alloc(cgbr->tab->mat->ctx, bset->n_ineq);
2905 if (!cst)
2906 return;
2908 for (i = 0; i < bset->n_ineq; ++i) {
2909 isl_int_set(cst->el[i], bset->ineq[i][0]);
2910 for (j = 0; j < dim; ++j) {
2911 if (!isl_int_is_neg(bset->ineq[i][1 + j]))
2912 continue;
2913 isl_int_add(bset->ineq[i][0], bset->ineq[i][0],
2914 bset->ineq[i][1 + j]);
2918 cgbr->shifted = isl_tab_from_basic_set(bset, 0);
2920 for (i = 0; i < bset->n_ineq; ++i)
2921 isl_int_set(bset->ineq[i][0], cst->el[i]);
2923 isl_vec_free(cst);
2926 /* Check if the shifted tableau is non-empty, and if so
2927 * use the sample point to construct an integer point
2928 * of the context tableau.
2930 static struct isl_vec *gbr_get_shifted_sample(struct isl_context_gbr *cgbr)
2932 struct isl_vec *sample;
2934 if (!cgbr->shifted)
2935 gbr_init_shifted(cgbr);
2936 if (!cgbr->shifted)
2937 return NULL;
2938 if (cgbr->shifted->empty)
2939 return isl_vec_alloc(cgbr->tab->mat->ctx, 0);
2941 sample = isl_tab_get_sample_value(cgbr->shifted);
2942 sample = isl_vec_ceil(sample);
2944 return sample;
2947 static __isl_give isl_basic_set *drop_constant_terms(
2948 __isl_take isl_basic_set *bset)
2950 int i;
2952 if (!bset)
2953 return NULL;
2955 for (i = 0; i < bset->n_eq; ++i)
2956 isl_int_set_si(bset->eq[i][0], 0);
2958 for (i = 0; i < bset->n_ineq; ++i)
2959 isl_int_set_si(bset->ineq[i][0], 0);
2961 return bset;
2964 static int use_shifted(struct isl_context_gbr *cgbr)
2966 if (!cgbr->tab)
2967 return 0;
2968 return cgbr->tab->bmap->n_eq == 0 && cgbr->tab->bmap->n_div == 0;
2971 static struct isl_vec *gbr_get_sample(struct isl_context_gbr *cgbr)
2973 struct isl_basic_set *bset;
2974 struct isl_basic_set *cone;
2976 if (isl_tab_sample_is_integer(cgbr->tab))
2977 return isl_tab_get_sample_value(cgbr->tab);
2979 if (use_shifted(cgbr)) {
2980 struct isl_vec *sample;
2982 sample = gbr_get_shifted_sample(cgbr);
2983 if (!sample || sample->size > 0)
2984 return sample;
2986 isl_vec_free(sample);
2989 if (!cgbr->cone) {
2990 bset = isl_tab_peek_bset(cgbr->tab);
2991 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
2992 if (!cgbr->cone)
2993 return NULL;
2994 if (isl_tab_track_bset(cgbr->cone,
2995 isl_basic_set_copy(bset)) < 0)
2996 return NULL;
2998 if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
2999 return NULL;
3001 if (cgbr->cone->n_dead == cgbr->cone->n_col) {
3002 struct isl_vec *sample;
3003 struct isl_tab_undo *snap;
3005 if (cgbr->tab->basis) {
3006 if (cgbr->tab->basis->n_col != 1 + cgbr->tab->n_var) {
3007 isl_mat_free(cgbr->tab->basis);
3008 cgbr->tab->basis = NULL;
3010 cgbr->tab->n_zero = 0;
3011 cgbr->tab->n_unbounded = 0;
3014 snap = isl_tab_snap(cgbr->tab);
3016 sample = isl_tab_sample(cgbr->tab);
3018 if (!sample || isl_tab_rollback(cgbr->tab, snap) < 0) {
3019 isl_vec_free(sample);
3020 return NULL;
3023 return sample;
3026 cone = isl_basic_set_dup(isl_tab_peek_bset(cgbr->cone));
3027 cone = drop_constant_terms(cone);
3028 cone = isl_basic_set_update_from_tab(cone, cgbr->cone);
3029 cone = isl_basic_set_underlying_set(cone);
3030 cone = isl_basic_set_gauss(cone, NULL);
3032 bset = isl_basic_set_dup(isl_tab_peek_bset(cgbr->tab));
3033 bset = isl_basic_set_update_from_tab(bset, cgbr->tab);
3034 bset = isl_basic_set_underlying_set(bset);
3035 bset = isl_basic_set_gauss(bset, NULL);
3037 return isl_basic_set_sample_with_cone(bset, cone);
3040 static void check_gbr_integer_feasible(struct isl_context_gbr *cgbr)
3042 struct isl_vec *sample;
3044 if (!cgbr->tab)
3045 return;
3047 if (cgbr->tab->empty)
3048 return;
3050 sample = gbr_get_sample(cgbr);
3051 if (!sample)
3052 goto error;
3054 if (sample->size == 0) {
3055 isl_vec_free(sample);
3056 if (isl_tab_mark_empty(cgbr->tab) < 0)
3057 goto error;
3058 return;
3061 if (isl_tab_add_sample(cgbr->tab, sample) < 0)
3062 goto error;
3064 return;
3065 error:
3066 isl_tab_free(cgbr->tab);
3067 cgbr->tab = NULL;
3070 static struct isl_tab *add_gbr_eq(struct isl_tab *tab, isl_int *eq)
3072 if (!tab)
3073 return NULL;
3075 if (isl_tab_extend_cons(tab, 2) < 0)
3076 goto error;
3078 if (isl_tab_add_eq(tab, eq) < 0)
3079 goto error;
3081 return tab;
3082 error:
3083 isl_tab_free(tab);
3084 return NULL;
3087 /* Add the equality described by "eq" to the context.
3088 * If "check" is set, then we check if the context is empty after
3089 * adding the equality.
3090 * If "update" is set, then we check if the samples are still valid.
3092 * We do not explicitly add shifted copies of the equality to
3093 * cgbr->shifted since they would conflict with each other.
3094 * Instead, we directly mark cgbr->shifted empty.
3096 static void context_gbr_add_eq(struct isl_context *context, isl_int *eq,
3097 int check, int update)
3099 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3101 cgbr->tab = add_gbr_eq(cgbr->tab, eq);
3103 if (cgbr->shifted && !cgbr->shifted->empty && use_shifted(cgbr)) {
3104 if (isl_tab_mark_empty(cgbr->shifted) < 0)
3105 goto error;
3108 if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
3109 if (isl_tab_extend_cons(cgbr->cone, 2) < 0)
3110 goto error;
3111 if (isl_tab_add_eq(cgbr->cone, eq) < 0)
3112 goto error;
3115 if (check) {
3116 int v = tab_has_valid_sample(cgbr->tab, eq, 1);
3117 if (v < 0)
3118 goto error;
3119 if (!v)
3120 check_gbr_integer_feasible(cgbr);
3122 if (update)
3123 cgbr->tab = check_samples(cgbr->tab, eq, 1);
3124 return;
3125 error:
3126 isl_tab_free(cgbr->tab);
3127 cgbr->tab = NULL;
3130 static void add_gbr_ineq(struct isl_context_gbr *cgbr, isl_int *ineq)
3132 if (!cgbr->tab)
3133 return;
3135 if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
3136 goto error;
3138 if (isl_tab_add_ineq(cgbr->tab, ineq) < 0)
3139 goto error;
3141 if (cgbr->shifted && !cgbr->shifted->empty && use_shifted(cgbr)) {
3142 int i;
3143 unsigned dim;
3144 dim = isl_basic_map_total_dim(cgbr->tab->bmap);
3146 if (isl_tab_extend_cons(cgbr->shifted, 1) < 0)
3147 goto error;
3149 for (i = 0; i < dim; ++i) {
3150 if (!isl_int_is_neg(ineq[1 + i]))
3151 continue;
3152 isl_int_add(ineq[0], ineq[0], ineq[1 + i]);
3155 if (isl_tab_add_ineq(cgbr->shifted, ineq) < 0)
3156 goto error;
3158 for (i = 0; i < dim; ++i) {
3159 if (!isl_int_is_neg(ineq[1 + i]))
3160 continue;
3161 isl_int_sub(ineq[0], ineq[0], ineq[1 + i]);
3165 if (cgbr->cone && cgbr->cone->n_col != cgbr->cone->n_dead) {
3166 if (isl_tab_extend_cons(cgbr->cone, 1) < 0)
3167 goto error;
3168 if (isl_tab_add_ineq(cgbr->cone, ineq) < 0)
3169 goto error;
3172 return;
3173 error:
3174 isl_tab_free(cgbr->tab);
3175 cgbr->tab = NULL;
3178 static void context_gbr_add_ineq(struct isl_context *context, isl_int *ineq,
3179 int check, int update)
3181 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3183 add_gbr_ineq(cgbr, ineq);
3184 if (!cgbr->tab)
3185 return;
3187 if (check) {
3188 int v = tab_has_valid_sample(cgbr->tab, ineq, 0);
3189 if (v < 0)
3190 goto error;
3191 if (!v)
3192 check_gbr_integer_feasible(cgbr);
3194 if (update)
3195 cgbr->tab = check_samples(cgbr->tab, ineq, 0);
3196 return;
3197 error:
3198 isl_tab_free(cgbr->tab);
3199 cgbr->tab = NULL;
3202 static isl_stat context_gbr_add_ineq_wrap(void *user, isl_int *ineq)
3204 struct isl_context *context = (struct isl_context *)user;
3205 context_gbr_add_ineq(context, ineq, 0, 0);
3206 return context->op->is_ok(context) ? isl_stat_ok : isl_stat_error;
3209 static enum isl_tab_row_sign context_gbr_ineq_sign(struct isl_context *context,
3210 isl_int *ineq, int strict)
3212 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3213 return tab_ineq_sign(cgbr->tab, ineq, strict);
3216 /* Check whether "ineq" can be added to the tableau without rendering
3217 * it infeasible.
3219 static int context_gbr_test_ineq(struct isl_context *context, isl_int *ineq)
3221 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3222 struct isl_tab_undo *snap;
3223 struct isl_tab_undo *shifted_snap = NULL;
3224 struct isl_tab_undo *cone_snap = NULL;
3225 int feasible;
3227 if (!cgbr->tab)
3228 return -1;
3230 if (isl_tab_extend_cons(cgbr->tab, 1) < 0)
3231 return -1;
3233 snap = isl_tab_snap(cgbr->tab);
3234 if (cgbr->shifted)
3235 shifted_snap = isl_tab_snap(cgbr->shifted);
3236 if (cgbr->cone)
3237 cone_snap = isl_tab_snap(cgbr->cone);
3238 add_gbr_ineq(cgbr, ineq);
3239 check_gbr_integer_feasible(cgbr);
3240 if (!cgbr->tab)
3241 return -1;
3242 feasible = !cgbr->tab->empty;
3243 if (isl_tab_rollback(cgbr->tab, snap) < 0)
3244 return -1;
3245 if (shifted_snap) {
3246 if (isl_tab_rollback(cgbr->shifted, shifted_snap))
3247 return -1;
3248 } else if (cgbr->shifted) {
3249 isl_tab_free(cgbr->shifted);
3250 cgbr->shifted = NULL;
3252 if (cone_snap) {
3253 if (isl_tab_rollback(cgbr->cone, cone_snap))
3254 return -1;
3255 } else if (cgbr->cone) {
3256 isl_tab_free(cgbr->cone);
3257 cgbr->cone = NULL;
3260 return feasible;
3263 /* Return the column of the last of the variables associated to
3264 * a column that has a non-zero coefficient.
3265 * This function is called in a context where only coefficients
3266 * of parameters or divs can be non-zero.
3268 static int last_non_zero_var_col(struct isl_tab *tab, isl_int *p)
3270 int i;
3271 int col;
3273 if (tab->n_var == 0)
3274 return -1;
3276 for (i = tab->n_var - 1; i >= 0; --i) {
3277 if (i >= tab->n_param && i < tab->n_var - tab->n_div)
3278 continue;
3279 if (tab->var[i].is_row)
3280 continue;
3281 col = tab->var[i].index;
3282 if (!isl_int_is_zero(p[col]))
3283 return col;
3286 return -1;
3289 /* Look through all the recently added equalities in the context
3290 * to see if we can propagate any of them to the main tableau.
3292 * The newly added equalities in the context are encoded as pairs
3293 * of inequalities starting at inequality "first".
3295 * We tentatively add each of these equalities to the main tableau
3296 * and if this happens to result in a row with a final coefficient
3297 * that is one or negative one, we use it to kill a column
3298 * in the main tableau. Otherwise, we discard the tentatively
3299 * added row.
3300 * This tentative addition of equality constraints turns
3301 * on the undo facility of the tableau. Turn it off again
3302 * at the end, assuming it was turned off to begin with.
3304 * Return 0 on success and -1 on failure.
3306 static int propagate_equalities(struct isl_context_gbr *cgbr,
3307 struct isl_tab *tab, unsigned first)
3309 int i;
3310 struct isl_vec *eq = NULL;
3311 isl_bool needs_undo;
3313 needs_undo = isl_tab_need_undo(tab);
3314 if (needs_undo < 0)
3315 goto error;
3316 eq = isl_vec_alloc(tab->mat->ctx, 1 + tab->n_var);
3317 if (!eq)
3318 goto error;
3320 if (isl_tab_extend_cons(tab, (cgbr->tab->bmap->n_ineq - first)/2) < 0)
3321 goto error;
3323 isl_seq_clr(eq->el + 1 + tab->n_param,
3324 tab->n_var - tab->n_param - tab->n_div);
3325 for (i = first; i < cgbr->tab->bmap->n_ineq; i += 2) {
3326 int j;
3327 int r;
3328 struct isl_tab_undo *snap;
3329 snap = isl_tab_snap(tab);
3331 isl_seq_cpy(eq->el, cgbr->tab->bmap->ineq[i], 1 + tab->n_param);
3332 isl_seq_cpy(eq->el + 1 + tab->n_var - tab->n_div,
3333 cgbr->tab->bmap->ineq[i] + 1 + tab->n_param,
3334 tab->n_div);
3336 r = isl_tab_add_row(tab, eq->el);
3337 if (r < 0)
3338 goto error;
3339 r = tab->con[r].index;
3340 j = last_non_zero_var_col(tab, tab->mat->row[r] + 2 + tab->M);
3341 if (j < 0 || j < tab->n_dead ||
3342 !isl_int_is_one(tab->mat->row[r][0]) ||
3343 (!isl_int_is_one(tab->mat->row[r][2 + tab->M + j]) &&
3344 !isl_int_is_negone(tab->mat->row[r][2 + tab->M + j]))) {
3345 if (isl_tab_rollback(tab, snap) < 0)
3346 goto error;
3347 continue;
3349 if (isl_tab_pivot(tab, r, j) < 0)
3350 goto error;
3351 if (isl_tab_kill_col(tab, j) < 0)
3352 goto error;
3354 if (restore_lexmin(tab) < 0)
3355 goto error;
3358 if (!needs_undo)
3359 isl_tab_clear_undo(tab);
3360 isl_vec_free(eq);
3362 return 0;
3363 error:
3364 isl_vec_free(eq);
3365 isl_tab_free(cgbr->tab);
3366 cgbr->tab = NULL;
3367 return -1;
3370 static int context_gbr_detect_equalities(struct isl_context *context,
3371 struct isl_tab *tab)
3373 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3374 unsigned n_ineq;
3376 if (!cgbr->cone) {
3377 struct isl_basic_set *bset = isl_tab_peek_bset(cgbr->tab);
3378 cgbr->cone = isl_tab_from_recession_cone(bset, 0);
3379 if (!cgbr->cone)
3380 goto error;
3381 if (isl_tab_track_bset(cgbr->cone,
3382 isl_basic_set_copy(bset)) < 0)
3383 goto error;
3385 if (isl_tab_detect_implicit_equalities(cgbr->cone) < 0)
3386 goto error;
3388 n_ineq = cgbr->tab->bmap->n_ineq;
3389 cgbr->tab = isl_tab_detect_equalities(cgbr->tab, cgbr->cone);
3390 if (!cgbr->tab)
3391 return -1;
3392 if (cgbr->tab->bmap->n_ineq > n_ineq &&
3393 propagate_equalities(cgbr, tab, n_ineq) < 0)
3394 return -1;
3396 return 0;
3397 error:
3398 isl_tab_free(cgbr->tab);
3399 cgbr->tab = NULL;
3400 return -1;
3403 static int context_gbr_get_div(struct isl_context *context, struct isl_tab *tab,
3404 struct isl_vec *div)
3406 return get_div(tab, context, div);
3409 static isl_bool context_gbr_insert_div(struct isl_context *context, int pos,
3410 __isl_keep isl_vec *div)
3412 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3413 if (cgbr->cone) {
3414 int r, n_div, o_div;
3416 n_div = isl_basic_map_dim(cgbr->cone->bmap, isl_dim_div);
3417 o_div = cgbr->cone->n_var - n_div;
3419 if (isl_tab_extend_cons(cgbr->cone, 3) < 0)
3420 return isl_bool_error;
3421 if (isl_tab_extend_vars(cgbr->cone, 1) < 0)
3422 return isl_bool_error;
3423 if ((r = isl_tab_insert_var(cgbr->cone, pos)) <0)
3424 return isl_bool_error;
3426 cgbr->cone->bmap = isl_basic_map_insert_div(cgbr->cone->bmap,
3427 r - o_div, div);
3428 if (!cgbr->cone->bmap)
3429 return isl_bool_error;
3430 if (isl_tab_push_var(cgbr->cone, isl_tab_undo_bmap_div,
3431 &cgbr->cone->var[r]) < 0)
3432 return isl_bool_error;
3434 return context_tab_insert_div(cgbr->tab, pos, div,
3435 context_gbr_add_ineq_wrap, context);
3438 static int context_gbr_best_split(struct isl_context *context,
3439 struct isl_tab *tab)
3441 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3442 struct isl_tab_undo *snap;
3443 int r;
3445 snap = isl_tab_snap(cgbr->tab);
3446 r = best_split(tab, cgbr->tab);
3448 if (r >= 0 && isl_tab_rollback(cgbr->tab, snap) < 0)
3449 return -1;
3451 return r;
3454 static int context_gbr_is_empty(struct isl_context *context)
3456 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3457 if (!cgbr->tab)
3458 return -1;
3459 return cgbr->tab->empty;
3462 struct isl_gbr_tab_undo {
3463 struct isl_tab_undo *tab_snap;
3464 struct isl_tab_undo *shifted_snap;
3465 struct isl_tab_undo *cone_snap;
3468 static void *context_gbr_save(struct isl_context *context)
3470 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3471 struct isl_gbr_tab_undo *snap;
3473 if (!cgbr->tab)
3474 return NULL;
3476 snap = isl_alloc_type(cgbr->tab->mat->ctx, struct isl_gbr_tab_undo);
3477 if (!snap)
3478 return NULL;
3480 snap->tab_snap = isl_tab_snap(cgbr->tab);
3481 if (isl_tab_save_samples(cgbr->tab) < 0)
3482 goto error;
3484 if (cgbr->shifted)
3485 snap->shifted_snap = isl_tab_snap(cgbr->shifted);
3486 else
3487 snap->shifted_snap = NULL;
3489 if (cgbr->cone)
3490 snap->cone_snap = isl_tab_snap(cgbr->cone);
3491 else
3492 snap->cone_snap = NULL;
3494 return snap;
3495 error:
3496 free(snap);
3497 return NULL;
3500 static void context_gbr_restore(struct isl_context *context, void *save)
3502 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3503 struct isl_gbr_tab_undo *snap = (struct isl_gbr_tab_undo *)save;
3504 if (!snap)
3505 goto error;
3506 if (isl_tab_rollback(cgbr->tab, snap->tab_snap) < 0)
3507 goto error;
3509 if (snap->shifted_snap) {
3510 if (isl_tab_rollback(cgbr->shifted, snap->shifted_snap) < 0)
3511 goto error;
3512 } else if (cgbr->shifted) {
3513 isl_tab_free(cgbr->shifted);
3514 cgbr->shifted = NULL;
3517 if (snap->cone_snap) {
3518 if (isl_tab_rollback(cgbr->cone, snap->cone_snap) < 0)
3519 goto error;
3520 } else if (cgbr->cone) {
3521 isl_tab_free(cgbr->cone);
3522 cgbr->cone = NULL;
3525 free(snap);
3527 return;
3528 error:
3529 free(snap);
3530 isl_tab_free(cgbr->tab);
3531 cgbr->tab = NULL;
3534 static void context_gbr_discard(void *save)
3536 struct isl_gbr_tab_undo *snap = (struct isl_gbr_tab_undo *)save;
3537 free(snap);
3540 static int context_gbr_is_ok(struct isl_context *context)
3542 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3543 return !!cgbr->tab;
3546 static void context_gbr_invalidate(struct isl_context *context)
3548 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3549 isl_tab_free(cgbr->tab);
3550 cgbr->tab = NULL;
3553 static __isl_null struct isl_context *context_gbr_free(
3554 struct isl_context *context)
3556 struct isl_context_gbr *cgbr = (struct isl_context_gbr *)context;
3557 isl_tab_free(cgbr->tab);
3558 isl_tab_free(cgbr->shifted);
3559 isl_tab_free(cgbr->cone);
3560 free(cgbr);
3562 return NULL;
3565 struct isl_context_op isl_context_gbr_op = {
3566 context_gbr_detect_nonnegative_parameters,
3567 context_gbr_peek_basic_set,
3568 context_gbr_peek_tab,
3569 context_gbr_add_eq,
3570 context_gbr_add_ineq,
3571 context_gbr_ineq_sign,
3572 context_gbr_test_ineq,
3573 context_gbr_get_div,
3574 context_gbr_insert_div,
3575 context_gbr_detect_equalities,
3576 context_gbr_best_split,
3577 context_gbr_is_empty,
3578 context_gbr_is_ok,
3579 context_gbr_save,
3580 context_gbr_restore,
3581 context_gbr_discard,
3582 context_gbr_invalidate,
3583 context_gbr_free,
3586 static struct isl_context *isl_context_gbr_alloc(__isl_keep isl_basic_set *dom)
3588 struct isl_context_gbr *cgbr;
3590 if (!dom)
3591 return NULL;
3593 cgbr = isl_calloc_type(dom->ctx, struct isl_context_gbr);
3594 if (!cgbr)
3595 return NULL;
3597 cgbr->context.op = &isl_context_gbr_op;
3599 cgbr->shifted = NULL;
3600 cgbr->cone = NULL;
3601 cgbr->tab = isl_tab_from_basic_set(dom, 1);
3602 cgbr->tab = isl_tab_init_samples(cgbr->tab);
3603 if (!cgbr->tab)
3604 goto error;
3605 check_gbr_integer_feasible(cgbr);
3607 return &cgbr->context;
3608 error:
3609 cgbr->context.op->free(&cgbr->context);
3610 return NULL;
3613 /* Allocate a context corresponding to "dom".
3614 * The representation specific fields are initialized by
3615 * isl_context_lex_alloc or isl_context_gbr_alloc.
3616 * The shared "n_unknown" field is initialized to the number
3617 * of final unknown integer divisions in "dom".
3619 static struct isl_context *isl_context_alloc(__isl_keep isl_basic_set *dom)
3621 struct isl_context *context;
3622 int first;
3624 if (!dom)
3625 return NULL;
3627 if (dom->ctx->opt->context == ISL_CONTEXT_LEXMIN)
3628 context = isl_context_lex_alloc(dom);
3629 else
3630 context = isl_context_gbr_alloc(dom);
3632 if (!context)
3633 return NULL;
3635 first = isl_basic_set_first_unknown_div(dom);
3636 if (first < 0)
3637 return context->op->free(context);
3638 context->n_unknown = isl_basic_set_dim(dom, isl_dim_div) - first;
3640 return context;
3643 /* Initialize some common fields of "sol", which keeps track
3644 * of the solution of an optimization problem on "bmap" over
3645 * the domain "dom".
3646 * If "max" is set, then a maximization problem is being solved, rather than
3647 * a minimization problem, which means that the variables in the
3648 * tableau have value "M - x" rather than "M + x".
3650 static isl_stat sol_init(struct isl_sol *sol, __isl_keep isl_basic_map *bmap,
3651 __isl_keep isl_basic_set *dom, int max)
3653 sol->rational = ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL);
3654 sol->dec_level.callback.run = &sol_dec_level_wrap;
3655 sol->dec_level.sol = sol;
3656 sol->max = max;
3657 sol->n_out = isl_basic_map_dim(bmap, isl_dim_out);
3658 sol->space = isl_basic_map_get_space(bmap);
3660 sol->context = isl_context_alloc(dom);
3661 if (!sol->space || !sol->context)
3662 return isl_stat_error;
3664 return isl_stat_ok;
3667 /* Construct an isl_sol_map structure for accumulating the solution.
3668 * If track_empty is set, then we also keep track of the parts
3669 * of the context where there is no solution.
3670 * If max is set, then we are solving a maximization, rather than
3671 * a minimization problem, which means that the variables in the
3672 * tableau have value "M - x" rather than "M + x".
3674 static struct isl_sol *sol_map_init(__isl_keep isl_basic_map *bmap,
3675 __isl_take isl_basic_set *dom, int track_empty, int max)
3677 struct isl_sol_map *sol_map = NULL;
3678 isl_space *space;
3680 if (!bmap)
3681 goto error;
3683 sol_map = isl_calloc_type(bmap->ctx, struct isl_sol_map);
3684 if (!sol_map)
3685 goto error;
3687 sol_map->sol.free = &sol_map_free;
3688 if (sol_init(&sol_map->sol, bmap, dom, max) < 0)
3689 goto error;
3690 sol_map->sol.add = &sol_map_add_wrap;
3691 sol_map->sol.add_empty = track_empty ? &sol_map_add_empty_wrap : NULL;
3692 space = isl_space_copy(sol_map->sol.space);
3693 sol_map->map = isl_map_alloc_space(space, 1, ISL_MAP_DISJOINT);
3694 if (!sol_map->map)
3695 goto error;
3697 if (track_empty) {
3698 sol_map->empty = isl_set_alloc_space(isl_basic_set_get_space(dom),
3699 1, ISL_SET_DISJOINT);
3700 if (!sol_map->empty)
3701 goto error;
3704 isl_basic_set_free(dom);
3705 return &sol_map->sol;
3706 error:
3707 isl_basic_set_free(dom);
3708 sol_free(&sol_map->sol);
3709 return NULL;
3712 /* Check whether all coefficients of (non-parameter) variables
3713 * are non-positive, meaning that no pivots can be performed on the row.
3715 static int is_critical(struct isl_tab *tab, int row)
3717 int j;
3718 unsigned off = 2 + tab->M;
3720 for (j = tab->n_dead; j < tab->n_col; ++j) {
3721 if (col_is_parameter_var(tab, j))
3722 continue;
3724 if (isl_int_is_pos(tab->mat->row[row][off + j]))
3725 return 0;
3728 return 1;
3731 /* Check whether the inequality represented by vec is strict over the integers,
3732 * i.e., there are no integer values satisfying the constraint with
3733 * equality. This happens if the gcd of the coefficients is not a divisor
3734 * of the constant term. If so, scale the constraint down by the gcd
3735 * of the coefficients.
3737 static int is_strict(struct isl_vec *vec)
3739 isl_int gcd;
3740 int strict = 0;
3742 isl_int_init(gcd);
3743 isl_seq_gcd(vec->el + 1, vec->size - 1, &gcd);
3744 if (!isl_int_is_one(gcd)) {
3745 strict = !isl_int_is_divisible_by(vec->el[0], gcd);
3746 isl_int_fdiv_q(vec->el[0], vec->el[0], gcd);
3747 isl_seq_scale_down(vec->el + 1, vec->el + 1, gcd, vec->size-1);
3749 isl_int_clear(gcd);
3751 return strict;
3754 /* Determine the sign of the given row of the main tableau.
3755 * The result is one of
3756 * isl_tab_row_pos: always non-negative; no pivot needed
3757 * isl_tab_row_neg: always non-positive; pivot
3758 * isl_tab_row_any: can be both positive and negative; split
3760 * We first handle some simple cases
3761 * - the row sign may be known already
3762 * - the row may be obviously non-negative
3763 * - the parametric constant may be equal to that of another row
3764 * for which we know the sign. This sign will be either "pos" or
3765 * "any". If it had been "neg" then we would have pivoted before.
3767 * If none of these cases hold, we check the value of the row for each
3768 * of the currently active samples. Based on the signs of these values
3769 * we make an initial determination of the sign of the row.
3771 * all zero -> unk(nown)
3772 * all non-negative -> pos
3773 * all non-positive -> neg
3774 * both negative and positive -> all
3776 * If we end up with "all", we are done.
3777 * Otherwise, we perform a check for positive and/or negative
3778 * values as follows.
3780 * samples neg unk pos
3781 * <0 ? Y N Y N
3782 * pos any pos
3783 * >0 ? Y N Y N
3784 * any neg any neg
3786 * There is no special sign for "zero", because we can usually treat zero
3787 * as either non-negative or non-positive, whatever works out best.
3788 * However, if the row is "critical", meaning that pivoting is impossible
3789 * then we don't want to limp zero with the non-positive case, because
3790 * then we we would lose the solution for those values of the parameters
3791 * where the value of the row is zero. Instead, we treat 0 as non-negative
3792 * ensuring a split if the row can attain both zero and negative values.
3793 * The same happens when the original constraint was one that could not
3794 * be satisfied with equality by any integer values of the parameters.
3795 * In this case, we normalize the constraint, but then a value of zero
3796 * for the normalized constraint is actually a positive value for the
3797 * original constraint, so again we need to treat zero as non-negative.
3798 * In both these cases, we have the following decision tree instead:
3800 * all non-negative -> pos
3801 * all negative -> neg
3802 * both negative and non-negative -> all
3804 * samples neg pos
3805 * <0 ? Y N
3806 * any pos
3807 * >=0 ? Y N
3808 * any neg
3810 static enum isl_tab_row_sign row_sign(struct isl_tab *tab,
3811 struct isl_sol *sol, int row)
3813 struct isl_vec *ineq = NULL;
3814 enum isl_tab_row_sign res = isl_tab_row_unknown;
3815 int critical;
3816 int strict;
3817 int row2;
3819 if (tab->row_sign[row] != isl_tab_row_unknown)
3820 return tab->row_sign[row];
3821 if (is_obviously_nonneg(tab, row))
3822 return isl_tab_row_pos;
3823 for (row2 = tab->n_redundant; row2 < tab->n_row; ++row2) {
3824 if (tab->row_sign[row2] == isl_tab_row_unknown)
3825 continue;
3826 if (identical_parameter_line(tab, row, row2))
3827 return tab->row_sign[row2];
3830 critical = is_critical(tab, row);
3832 ineq = get_row_parameter_ineq(tab, row);
3833 if (!ineq)
3834 goto error;
3836 strict = is_strict(ineq);
3838 res = sol->context->op->ineq_sign(sol->context, ineq->el,
3839 critical || strict);
3841 if (res == isl_tab_row_unknown || res == isl_tab_row_pos) {
3842 /* test for negative values */
3843 int feasible;
3844 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3845 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3847 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3848 if (feasible < 0)
3849 goto error;
3850 if (!feasible)
3851 res = isl_tab_row_pos;
3852 else
3853 res = (res == isl_tab_row_unknown) ? isl_tab_row_neg
3854 : isl_tab_row_any;
3855 if (res == isl_tab_row_neg) {
3856 isl_seq_neg(ineq->el, ineq->el, ineq->size);
3857 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3861 if (res == isl_tab_row_neg) {
3862 /* test for positive values */
3863 int feasible;
3864 if (!critical && !strict)
3865 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3867 feasible = sol->context->op->test_ineq(sol->context, ineq->el);
3868 if (feasible < 0)
3869 goto error;
3870 if (feasible)
3871 res = isl_tab_row_any;
3874 isl_vec_free(ineq);
3875 return res;
3876 error:
3877 isl_vec_free(ineq);
3878 return isl_tab_row_unknown;
3881 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab);
3883 /* Find solutions for values of the parameters that satisfy the given
3884 * inequality.
3886 * We currently take a snapshot of the context tableau that is reset
3887 * when we return from this function, while we make a copy of the main
3888 * tableau, leaving the original main tableau untouched.
3889 * These are fairly arbitrary choices. Making a copy also of the context
3890 * tableau would obviate the need to undo any changes made to it later,
3891 * while taking a snapshot of the main tableau could reduce memory usage.
3892 * If we were to switch to taking a snapshot of the main tableau,
3893 * we would have to keep in mind that we need to save the row signs
3894 * and that we need to do this before saving the current basis
3895 * such that the basis has been restore before we restore the row signs.
3897 static void find_in_pos(struct isl_sol *sol, struct isl_tab *tab, isl_int *ineq)
3899 void *saved;
3901 if (!sol->context)
3902 goto error;
3903 saved = sol->context->op->save(sol->context);
3905 tab = isl_tab_dup(tab);
3906 if (!tab)
3907 goto error;
3909 sol->context->op->add_ineq(sol->context, ineq, 0, 1);
3911 find_solutions(sol, tab);
3913 if (!sol->error)
3914 sol->context->op->restore(sol->context, saved);
3915 else
3916 sol->context->op->discard(saved);
3917 return;
3918 error:
3919 sol->error = 1;
3922 /* Record the absence of solutions for those values of the parameters
3923 * that do not satisfy the given inequality with equality.
3925 static void no_sol_in_strict(struct isl_sol *sol,
3926 struct isl_tab *tab, struct isl_vec *ineq)
3928 int empty;
3929 void *saved;
3931 if (!sol->context || sol->error)
3932 goto error;
3933 saved = sol->context->op->save(sol->context);
3935 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
3937 sol->context->op->add_ineq(sol->context, ineq->el, 1, 0);
3938 if (!sol->context)
3939 goto error;
3941 empty = tab->empty;
3942 tab->empty = 1;
3943 sol_add(sol, tab);
3944 tab->empty = empty;
3946 isl_int_add_ui(ineq->el[0], ineq->el[0], 1);
3948 sol->context->op->restore(sol->context, saved);
3949 return;
3950 error:
3951 sol->error = 1;
3954 /* Reset all row variables that are marked to have a sign that may
3955 * be both positive and negative to have an unknown sign.
3957 static void reset_any_to_unknown(struct isl_tab *tab)
3959 int row;
3961 for (row = tab->n_redundant; row < tab->n_row; ++row) {
3962 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
3963 continue;
3964 if (tab->row_sign[row] == isl_tab_row_any)
3965 tab->row_sign[row] = isl_tab_row_unknown;
3969 /* Compute the lexicographic minimum of the set represented by the main
3970 * tableau "tab" within the context "sol->context_tab".
3971 * On entry the sample value of the main tableau is lexicographically
3972 * less than or equal to this lexicographic minimum.
3973 * Pivots are performed until a feasible point is found, which is then
3974 * necessarily equal to the minimum, or until the tableau is found to
3975 * be infeasible. Some pivots may need to be performed for only some
3976 * feasible values of the context tableau. If so, the context tableau
3977 * is split into a part where the pivot is needed and a part where it is not.
3979 * Whenever we enter the main loop, the main tableau is such that no
3980 * "obvious" pivots need to be performed on it, where "obvious" means
3981 * that the given row can be seen to be negative without looking at
3982 * the context tableau. In particular, for non-parametric problems,
3983 * no pivots need to be performed on the main tableau.
3984 * The caller of find_solutions is responsible for making this property
3985 * hold prior to the first iteration of the loop, while restore_lexmin
3986 * is called before every other iteration.
3988 * Inside the main loop, we first examine the signs of the rows of
3989 * the main tableau within the context of the context tableau.
3990 * If we find a row that is always non-positive for all values of
3991 * the parameters satisfying the context tableau and negative for at
3992 * least one value of the parameters, we perform the appropriate pivot
3993 * and start over. An exception is the case where no pivot can be
3994 * performed on the row. In this case, we require that the sign of
3995 * the row is negative for all values of the parameters (rather than just
3996 * non-positive). This special case is handled inside row_sign, which
3997 * will say that the row can have any sign if it determines that it can
3998 * attain both negative and zero values.
4000 * If we can't find a row that always requires a pivot, but we can find
4001 * one or more rows that require a pivot for some values of the parameters
4002 * (i.e., the row can attain both positive and negative signs), then we split
4003 * the context tableau into two parts, one where we force the sign to be
4004 * non-negative and one where we force is to be negative.
4005 * The non-negative part is handled by a recursive call (through find_in_pos).
4006 * Upon returning from this call, we continue with the negative part and
4007 * perform the required pivot.
4009 * If no such rows can be found, all rows are non-negative and we have
4010 * found a (rational) feasible point. If we only wanted a rational point
4011 * then we are done.
4012 * Otherwise, we check if all values of the sample point of the tableau
4013 * are integral for the variables. If so, we have found the minimal
4014 * integral point and we are done.
4015 * If the sample point is not integral, then we need to make a distinction
4016 * based on whether the constant term is non-integral or the coefficients
4017 * of the parameters. Furthermore, in order to decide how to handle
4018 * the non-integrality, we also need to know whether the coefficients
4019 * of the other columns in the tableau are integral. This leads
4020 * to the following table. The first two rows do not correspond
4021 * to a non-integral sample point and are only mentioned for completeness.
4023 * constant parameters other
4025 * int int int |
4026 * int int rat | -> no problem
4028 * rat int int -> fail
4030 * rat int rat -> cut
4032 * int rat rat |
4033 * rat rat rat | -> parametric cut
4035 * int rat int |
4036 * rat rat int | -> split context
4038 * If the parametric constant is completely integral, then there is nothing
4039 * to be done. If the constant term is non-integral, but all the other
4040 * coefficient are integral, then there is nothing that can be done
4041 * and the tableau has no integral solution.
4042 * If, on the other hand, one or more of the other columns have rational
4043 * coefficients, but the parameter coefficients are all integral, then
4044 * we can perform a regular (non-parametric) cut.
4045 * Finally, if there is any parameter coefficient that is non-integral,
4046 * then we need to involve the context tableau. There are two cases here.
4047 * If at least one other column has a rational coefficient, then we
4048 * can perform a parametric cut in the main tableau by adding a new
4049 * integer division in the context tableau.
4050 * If all other columns have integral coefficients, then we need to
4051 * enforce that the rational combination of parameters (c + \sum a_i y_i)/m
4052 * is always integral. We do this by introducing an integer division
4053 * q = floor((c + \sum a_i y_i)/m) and stipulating that its argument should
4054 * always be integral in the context tableau, i.e., m q = c + \sum a_i y_i.
4055 * Since q is expressed in the tableau as
4056 * c + \sum a_i y_i - m q >= 0
4057 * -c - \sum a_i y_i + m q + m - 1 >= 0
4058 * it is sufficient to add the inequality
4059 * -c - \sum a_i y_i + m q >= 0
4060 * In the part of the context where this inequality does not hold, the
4061 * main tableau is marked as being empty.
4063 static void find_solutions(struct isl_sol *sol, struct isl_tab *tab)
4065 struct isl_context *context;
4066 int r;
4068 if (!tab || sol->error)
4069 goto error;
4071 context = sol->context;
4073 if (tab->empty)
4074 goto done;
4075 if (context->op->is_empty(context))
4076 goto done;
4078 for (r = 0; r >= 0 && tab && !tab->empty; r = restore_lexmin(tab)) {
4079 int flags;
4080 int row;
4081 enum isl_tab_row_sign sgn;
4082 int split = -1;
4083 int n_split = 0;
4085 for (row = tab->n_redundant; row < tab->n_row; ++row) {
4086 if (!isl_tab_var_from_row(tab, row)->is_nonneg)
4087 continue;
4088 sgn = row_sign(tab, sol, row);
4089 if (!sgn)
4090 goto error;
4091 tab->row_sign[row] = sgn;
4092 if (sgn == isl_tab_row_any)
4093 n_split++;
4094 if (sgn == isl_tab_row_any && split == -1)
4095 split = row;
4096 if (sgn == isl_tab_row_neg)
4097 break;
4099 if (row < tab->n_row)
4100 continue;
4101 if (split != -1) {
4102 struct isl_vec *ineq;
4103 if (n_split != 1)
4104 split = context->op->best_split(context, tab);
4105 if (split < 0)
4106 goto error;
4107 ineq = get_row_parameter_ineq(tab, split);
4108 if (!ineq)
4109 goto error;
4110 is_strict(ineq);
4111 reset_any_to_unknown(tab);
4112 tab->row_sign[split] = isl_tab_row_pos;
4113 sol_inc_level(sol);
4114 find_in_pos(sol, tab, ineq->el);
4115 tab->row_sign[split] = isl_tab_row_neg;
4116 isl_seq_neg(ineq->el, ineq->el, ineq->size);
4117 isl_int_sub_ui(ineq->el[0], ineq->el[0], 1);
4118 if (!sol->error)
4119 context->op->add_ineq(context, ineq->el, 0, 1);
4120 isl_vec_free(ineq);
4121 if (sol->error)
4122 goto error;
4123 continue;
4125 if (tab->rational)
4126 break;
4127 row = first_non_integer_row(tab, &flags);
4128 if (row < 0)
4129 break;
4130 if (ISL_FL_ISSET(flags, I_PAR)) {
4131 if (ISL_FL_ISSET(flags, I_VAR)) {
4132 if (isl_tab_mark_empty(tab) < 0)
4133 goto error;
4134 break;
4136 row = add_cut(tab, row);
4137 } else if (ISL_FL_ISSET(flags, I_VAR)) {
4138 struct isl_vec *div;
4139 struct isl_vec *ineq;
4140 int d;
4141 div = get_row_split_div(tab, row);
4142 if (!div)
4143 goto error;
4144 d = context->op->get_div(context, tab, div);
4145 isl_vec_free(div);
4146 if (d < 0)
4147 goto error;
4148 ineq = ineq_for_div(context->op->peek_basic_set(context), d);
4149 if (!ineq)
4150 goto error;
4151 sol_inc_level(sol);
4152 no_sol_in_strict(sol, tab, ineq);
4153 isl_seq_neg(ineq->el, ineq->el, ineq->size);
4154 context->op->add_ineq(context, ineq->el, 1, 1);
4155 isl_vec_free(ineq);
4156 if (sol->error || !context->op->is_ok(context))
4157 goto error;
4158 tab = set_row_cst_to_div(tab, row, d);
4159 if (context->op->is_empty(context))
4160 break;
4161 } else
4162 row = add_parametric_cut(tab, row, context);
4163 if (row < 0)
4164 goto error;
4166 if (r < 0)
4167 goto error;
4168 done:
4169 sol_add(sol, tab);
4170 isl_tab_free(tab);
4171 return;
4172 error:
4173 isl_tab_free(tab);
4174 sol->error = 1;
4177 /* Does "sol" contain a pair of partial solutions that could potentially
4178 * be merged?
4180 * We currently only check that "sol" is not in an error state
4181 * and that there are at least two partial solutions of which the final two
4182 * are defined at the same level.
4184 static int sol_has_mergeable_solutions(struct isl_sol *sol)
4186 if (sol->error)
4187 return 0;
4188 if (!sol->partial)
4189 return 0;
4190 if (!sol->partial->next)
4191 return 0;
4192 return sol->partial->level == sol->partial->next->level;
4195 /* Compute the lexicographic minimum of the set represented by the main
4196 * tableau "tab" within the context "sol->context_tab".
4198 * As a preprocessing step, we first transfer all the purely parametric
4199 * equalities from the main tableau to the context tableau, i.e.,
4200 * parameters that have been pivoted to a row.
4201 * These equalities are ignored by the main algorithm, because the
4202 * corresponding rows may not be marked as being non-negative.
4203 * In parts of the context where the added equality does not hold,
4204 * the main tableau is marked as being empty.
4206 * Before we embark on the actual computation, we save a copy
4207 * of the context. When we return, we check if there are any
4208 * partial solutions that can potentially be merged. If so,
4209 * we perform a rollback to the initial state of the context.
4210 * The merging of partial solutions happens inside calls to
4211 * sol_dec_level that are pushed onto the undo stack of the context.
4212 * If there are no partial solutions that can potentially be merged
4213 * then the rollback is skipped as it would just be wasted effort.
4215 static void find_solutions_main(struct isl_sol *sol, struct isl_tab *tab)
4217 int row;
4218 void *saved;
4220 if (!tab)
4221 goto error;
4223 sol->level = 0;
4225 for (row = tab->n_redundant; row < tab->n_row; ++row) {
4226 int p;
4227 struct isl_vec *eq;
4229 if (!row_is_parameter_var(tab, row))
4230 continue;
4231 if (tab->row_var[row] < tab->n_param)
4232 p = tab->row_var[row];
4233 else
4234 p = tab->row_var[row]
4235 + tab->n_param - (tab->n_var - tab->n_div);
4237 eq = isl_vec_alloc(tab->mat->ctx, 1+tab->n_param+tab->n_div);
4238 if (!eq)
4239 goto error;
4240 get_row_parameter_line(tab, row, eq->el);
4241 isl_int_neg(eq->el[1 + p], tab->mat->row[row][0]);
4242 eq = isl_vec_normalize(eq);
4244 sol_inc_level(sol);
4245 no_sol_in_strict(sol, tab, eq);
4247 isl_seq_neg(eq->el, eq->el, eq->size);
4248 sol_inc_level(sol);
4249 no_sol_in_strict(sol, tab, eq);
4250 isl_seq_neg(eq->el, eq->el, eq->size);
4252 sol->context->op->add_eq(sol->context, eq->el, 1, 1);
4254 isl_vec_free(eq);
4256 if (isl_tab_mark_redundant(tab, row) < 0)
4257 goto error;
4259 if (sol->context->op->is_empty(sol->context))
4260 break;
4262 row = tab->n_redundant - 1;
4265 saved = sol->context->op->save(sol->context);
4267 find_solutions(sol, tab);
4269 if (sol_has_mergeable_solutions(sol))
4270 sol->context->op->restore(sol->context, saved);
4271 else
4272 sol->context->op->discard(saved);
4274 sol->level = 0;
4275 sol_pop(sol);
4277 return;
4278 error:
4279 isl_tab_free(tab);
4280 sol->error = 1;
4283 /* Check if integer division "div" of "dom" also occurs in "bmap".
4284 * If so, return its position within the divs.
4285 * Otherwise, return a position beyond the integer divisions.
4287 static int find_context_div(__isl_keep isl_basic_map *bmap,
4288 __isl_keep isl_basic_set *dom, unsigned div)
4290 int i;
4291 int b_v_div, d_v_div;
4292 unsigned n_div;
4294 b_v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
4295 d_v_div = isl_basic_set_var_offset(dom, isl_dim_div);
4296 if (b_v_div < 0 || d_v_div < 0)
4297 return -1;
4298 n_div = isl_basic_map_dim(bmap, isl_dim_div);
4300 if (isl_int_is_zero(dom->div[div][0]))
4301 return n_div;
4302 if (isl_seq_first_non_zero(dom->div[div] + 2 + d_v_div,
4303 dom->n_div) != -1)
4304 return n_div;
4306 for (i = 0; i < n_div; ++i) {
4307 if (isl_int_is_zero(bmap->div[i][0]))
4308 continue;
4309 if (isl_seq_first_non_zero(bmap->div[i] + 2 + d_v_div,
4310 (b_v_div - d_v_div) + n_div) != -1)
4311 continue;
4312 if (isl_seq_eq(bmap->div[i], dom->div[div], 2 + d_v_div))
4313 return i;
4315 return n_div;
4318 /* The correspondence between the variables in the main tableau,
4319 * the context tableau, and the input map and domain is as follows.
4320 * The first n_param and the last n_div variables of the main tableau
4321 * form the variables of the context tableau.
4322 * In the basic map, these n_param variables correspond to the
4323 * parameters and the input dimensions. In the domain, they correspond
4324 * to the parameters and the set dimensions.
4325 * The n_div variables correspond to the integer divisions in the domain.
4326 * To ensure that everything lines up, we may need to copy some of the
4327 * integer divisions of the domain to the map. These have to be placed
4328 * in the same order as those in the context and they have to be placed
4329 * after any other integer divisions that the map may have.
4330 * This function performs the required reordering.
4332 static __isl_give isl_basic_map *align_context_divs(
4333 __isl_take isl_basic_map *bmap, __isl_keep isl_basic_set *dom)
4335 int i;
4336 int common = 0;
4337 int other;
4338 unsigned bmap_n_div;
4340 bmap_n_div = isl_basic_map_dim(bmap, isl_dim_div);
4342 for (i = 0; i < dom->n_div; ++i) {
4343 int pos;
4345 pos = find_context_div(bmap, dom, i);
4346 if (pos < 0)
4347 return isl_basic_map_free(bmap);
4348 if (pos < bmap_n_div)
4349 common++;
4351 other = bmap_n_div - common;
4352 if (dom->n_div - common > 0) {
4353 bmap = isl_basic_map_extend_space(bmap, isl_space_copy(bmap->dim),
4354 dom->n_div - common, 0, 0);
4355 if (!bmap)
4356 return NULL;
4358 for (i = 0; i < dom->n_div; ++i) {
4359 int pos = find_context_div(bmap, dom, i);
4360 if (pos < 0)
4361 bmap = isl_basic_map_free(bmap);
4362 if (pos >= bmap_n_div) {
4363 pos = isl_basic_map_alloc_div(bmap);
4364 if (pos < 0)
4365 goto error;
4366 isl_int_set_si(bmap->div[pos][0], 0);
4367 bmap_n_div++;
4369 if (pos != other + i)
4370 bmap = isl_basic_map_swap_div(bmap, pos, other + i);
4372 return bmap;
4373 error:
4374 isl_basic_map_free(bmap);
4375 return NULL;
4378 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
4379 * some obvious symmetries.
4381 * We make sure the divs in the domain are properly ordered,
4382 * because they will be added one by one in the given order
4383 * during the construction of the solution map.
4384 * Furthermore, make sure that the known integer divisions
4385 * appear before any unknown integer division because the solution
4386 * may depend on the known integer divisions, while anything that
4387 * depends on any variable starting from the first unknown integer
4388 * division is ignored in sol_pma_add.
4390 static struct isl_sol *basic_map_partial_lexopt_base_sol(
4391 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4392 __isl_give isl_set **empty, int max,
4393 struct isl_sol *(*init)(__isl_keep isl_basic_map *bmap,
4394 __isl_take isl_basic_set *dom, int track_empty, int max))
4396 struct isl_tab *tab;
4397 struct isl_sol *sol = NULL;
4398 struct isl_context *context;
4400 if (dom->n_div) {
4401 dom = isl_basic_set_sort_divs(dom);
4402 bmap = align_context_divs(bmap, dom);
4404 sol = init(bmap, dom, !!empty, max);
4405 if (!sol)
4406 goto error;
4408 context = sol->context;
4409 if (isl_basic_set_plain_is_empty(context->op->peek_basic_set(context)))
4410 /* nothing */;
4411 else if (isl_basic_map_plain_is_empty(bmap)) {
4412 if (sol->add_empty)
4413 sol->add_empty(sol,
4414 isl_basic_set_copy(context->op->peek_basic_set(context)));
4415 } else {
4416 tab = tab_for_lexmin(bmap,
4417 context->op->peek_basic_set(context), 1, max);
4418 tab = context->op->detect_nonnegative_parameters(context, tab);
4419 find_solutions_main(sol, tab);
4421 if (sol->error)
4422 goto error;
4424 isl_basic_map_free(bmap);
4425 return sol;
4426 error:
4427 sol_free(sol);
4428 isl_basic_map_free(bmap);
4429 return NULL;
4432 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
4433 * some obvious symmetries.
4435 * We call basic_map_partial_lexopt_base_sol and extract the results.
4437 static __isl_give isl_map *basic_map_partial_lexopt_base(
4438 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4439 __isl_give isl_set **empty, int max)
4441 isl_map *result = NULL;
4442 struct isl_sol *sol;
4443 struct isl_sol_map *sol_map;
4445 sol = basic_map_partial_lexopt_base_sol(bmap, dom, empty, max,
4446 &sol_map_init);
4447 if (!sol)
4448 return NULL;
4449 sol_map = (struct isl_sol_map *) sol;
4451 result = isl_map_copy(sol_map->map);
4452 if (empty)
4453 *empty = isl_set_copy(sol_map->empty);
4454 sol_free(&sol_map->sol);
4455 return result;
4458 /* Return a count of the number of occurrences of the "n" first
4459 * variables in the inequality constraints of "bmap".
4461 static __isl_give int *count_occurrences(__isl_keep isl_basic_map *bmap,
4462 int n)
4464 int i, j;
4465 isl_ctx *ctx;
4466 int *occurrences;
4468 if (!bmap)
4469 return NULL;
4470 ctx = isl_basic_map_get_ctx(bmap);
4471 occurrences = isl_calloc_array(ctx, int, n);
4472 if (!occurrences)
4473 return NULL;
4475 for (i = 0; i < bmap->n_ineq; ++i) {
4476 for (j = 0; j < n; ++j) {
4477 if (!isl_int_is_zero(bmap->ineq[i][1 + j]))
4478 occurrences[j]++;
4482 return occurrences;
4485 /* Do all of the "n" variables with non-zero coefficients in "c"
4486 * occur in exactly a single constraint.
4487 * "occurrences" is an array of length "n" containing the number
4488 * of occurrences of each of the variables in the inequality constraints.
4490 static int single_occurrence(int n, isl_int *c, int *occurrences)
4492 int i;
4494 for (i = 0; i < n; ++i) {
4495 if (isl_int_is_zero(c[i]))
4496 continue;
4497 if (occurrences[i] != 1)
4498 return 0;
4501 return 1;
4504 /* Do all of the "n" initial variables that occur in inequality constraint
4505 * "ineq" of "bmap" only occur in that constraint?
4507 static int all_single_occurrence(__isl_keep isl_basic_map *bmap, int ineq,
4508 int n)
4510 int i, j;
4512 for (i = 0; i < n; ++i) {
4513 if (isl_int_is_zero(bmap->ineq[ineq][1 + i]))
4514 continue;
4515 for (j = 0; j < bmap->n_ineq; ++j) {
4516 if (j == ineq)
4517 continue;
4518 if (!isl_int_is_zero(bmap->ineq[j][1 + i]))
4519 return 0;
4523 return 1;
4526 /* Structure used during detection of parallel constraints.
4527 * n_in: number of "input" variables: isl_dim_param + isl_dim_in
4528 * n_out: number of "output" variables: isl_dim_out + isl_dim_div
4529 * val: the coefficients of the output variables
4531 struct isl_constraint_equal_info {
4532 unsigned n_in;
4533 unsigned n_out;
4534 isl_int *val;
4537 /* Check whether the coefficients of the output variables
4538 * of the constraint in "entry" are equal to info->val.
4540 static int constraint_equal(const void *entry, const void *val)
4542 isl_int **row = (isl_int **)entry;
4543 const struct isl_constraint_equal_info *info = val;
4545 return isl_seq_eq((*row) + 1 + info->n_in, info->val, info->n_out);
4548 /* Check whether "bmap" has a pair of constraints that have
4549 * the same coefficients for the output variables.
4550 * Note that the coefficients of the existentially quantified
4551 * variables need to be zero since the existentially quantified
4552 * of the result are usually not the same as those of the input.
4553 * Furthermore, check that each of the input variables that occur
4554 * in those constraints does not occur in any other constraint.
4555 * If so, return true and return the row indices of the two constraints
4556 * in *first and *second.
4558 static isl_bool parallel_constraints(__isl_keep isl_basic_map *bmap,
4559 int *first, int *second)
4561 int i;
4562 isl_ctx *ctx;
4563 int *occurrences = NULL;
4564 struct isl_hash_table *table = NULL;
4565 struct isl_hash_table_entry *entry;
4566 struct isl_constraint_equal_info info;
4567 unsigned n_out;
4568 unsigned n_div;
4570 ctx = isl_basic_map_get_ctx(bmap);
4571 table = isl_hash_table_alloc(ctx, bmap->n_ineq);
4572 if (!table)
4573 goto error;
4575 info.n_in = isl_basic_map_dim(bmap, isl_dim_param) +
4576 isl_basic_map_dim(bmap, isl_dim_in);
4577 occurrences = count_occurrences(bmap, info.n_in);
4578 if (info.n_in && !occurrences)
4579 goto error;
4580 n_out = isl_basic_map_dim(bmap, isl_dim_out);
4581 n_div = isl_basic_map_dim(bmap, isl_dim_div);
4582 info.n_out = n_out + n_div;
4583 for (i = 0; i < bmap->n_ineq; ++i) {
4584 uint32_t hash;
4586 info.val = bmap->ineq[i] + 1 + info.n_in;
4587 if (isl_seq_first_non_zero(info.val, n_out) < 0)
4588 continue;
4589 if (isl_seq_first_non_zero(info.val + n_out, n_div) >= 0)
4590 continue;
4591 if (!single_occurrence(info.n_in, bmap->ineq[i] + 1,
4592 occurrences))
4593 continue;
4594 hash = isl_seq_get_hash(info.val, info.n_out);
4595 entry = isl_hash_table_find(ctx, table, hash,
4596 constraint_equal, &info, 1);
4597 if (!entry)
4598 goto error;
4599 if (entry->data)
4600 break;
4601 entry->data = &bmap->ineq[i];
4604 if (i < bmap->n_ineq) {
4605 *first = ((isl_int **)entry->data) - bmap->ineq;
4606 *second = i;
4609 isl_hash_table_free(ctx, table);
4610 free(occurrences);
4612 return i < bmap->n_ineq;
4613 error:
4614 isl_hash_table_free(ctx, table);
4615 free(occurrences);
4616 return isl_bool_error;
4619 /* Given a set of upper bounds in "var", add constraints to "bset"
4620 * that make the i-th bound smallest.
4622 * In particular, if there are n bounds b_i, then add the constraints
4624 * b_i <= b_j for j > i
4625 * b_i < b_j for j < i
4627 static __isl_give isl_basic_set *select_minimum(__isl_take isl_basic_set *bset,
4628 __isl_keep isl_mat *var, int i)
4630 isl_ctx *ctx;
4631 int j, k;
4633 ctx = isl_mat_get_ctx(var);
4635 for (j = 0; j < var->n_row; ++j) {
4636 if (j == i)
4637 continue;
4638 k = isl_basic_set_alloc_inequality(bset);
4639 if (k < 0)
4640 goto error;
4641 isl_seq_combine(bset->ineq[k], ctx->one, var->row[j],
4642 ctx->negone, var->row[i], var->n_col);
4643 isl_int_set_si(bset->ineq[k][var->n_col], 0);
4644 if (j < i)
4645 isl_int_sub_ui(bset->ineq[k][0], bset->ineq[k][0], 1);
4648 bset = isl_basic_set_finalize(bset);
4650 return bset;
4651 error:
4652 isl_basic_set_free(bset);
4653 return NULL;
4656 /* Given a set of upper bounds on the last "input" variable m,
4657 * construct a set that assigns the minimal upper bound to m, i.e.,
4658 * construct a set that divides the space into cells where one
4659 * of the upper bounds is smaller than all the others and assign
4660 * this upper bound to m.
4662 * In particular, if there are n bounds b_i, then the result
4663 * consists of n basic sets, each one of the form
4665 * m = b_i
4666 * b_i <= b_j for j > i
4667 * b_i < b_j for j < i
4669 static __isl_give isl_set *set_minimum(__isl_take isl_space *space,
4670 __isl_take isl_mat *var)
4672 int i, k;
4673 isl_basic_set *bset = NULL;
4674 isl_set *set = NULL;
4676 if (!space || !var)
4677 goto error;
4679 set = isl_set_alloc_space(isl_space_copy(space),
4680 var->n_row, ISL_SET_DISJOINT);
4682 for (i = 0; i < var->n_row; ++i) {
4683 bset = isl_basic_set_alloc_space(isl_space_copy(space), 0,
4684 1, var->n_row - 1);
4685 k = isl_basic_set_alloc_equality(bset);
4686 if (k < 0)
4687 goto error;
4688 isl_seq_cpy(bset->eq[k], var->row[i], var->n_col);
4689 isl_int_set_si(bset->eq[k][var->n_col], -1);
4690 bset = select_minimum(bset, var, i);
4691 set = isl_set_add_basic_set(set, bset);
4694 isl_space_free(space);
4695 isl_mat_free(var);
4696 return set;
4697 error:
4698 isl_basic_set_free(bset);
4699 isl_set_free(set);
4700 isl_space_free(space);
4701 isl_mat_free(var);
4702 return NULL;
4705 /* Given that the last input variable of "bmap" represents the minimum
4706 * of the bounds in "cst", check whether we need to split the domain
4707 * based on which bound attains the minimum.
4709 * A split is needed when the minimum appears in an integer division
4710 * or in an equality. Otherwise, it is only needed if it appears in
4711 * an upper bound that is different from the upper bounds on which it
4712 * is defined.
4714 static isl_bool need_split_basic_map(__isl_keep isl_basic_map *bmap,
4715 __isl_keep isl_mat *cst)
4717 int i, j;
4718 unsigned total;
4719 unsigned pos;
4721 pos = cst->n_col - 1;
4722 total = isl_basic_map_dim(bmap, isl_dim_all);
4724 for (i = 0; i < bmap->n_div; ++i)
4725 if (!isl_int_is_zero(bmap->div[i][2 + pos]))
4726 return isl_bool_true;
4728 for (i = 0; i < bmap->n_eq; ++i)
4729 if (!isl_int_is_zero(bmap->eq[i][1 + pos]))
4730 return isl_bool_true;
4732 for (i = 0; i < bmap->n_ineq; ++i) {
4733 if (isl_int_is_nonneg(bmap->ineq[i][1 + pos]))
4734 continue;
4735 if (!isl_int_is_negone(bmap->ineq[i][1 + pos]))
4736 return isl_bool_true;
4737 if (isl_seq_first_non_zero(bmap->ineq[i] + 1 + pos + 1,
4738 total - pos - 1) >= 0)
4739 return isl_bool_true;
4741 for (j = 0; j < cst->n_row; ++j)
4742 if (isl_seq_eq(bmap->ineq[i], cst->row[j], cst->n_col))
4743 break;
4744 if (j >= cst->n_row)
4745 return isl_bool_true;
4748 return isl_bool_false;
4751 /* Given that the last set variable of "bset" represents the minimum
4752 * of the bounds in "cst", check whether we need to split the domain
4753 * based on which bound attains the minimum.
4755 * We simply call need_split_basic_map here. This is safe because
4756 * the position of the minimum is computed from "cst" and not
4757 * from "bmap".
4759 static isl_bool need_split_basic_set(__isl_keep isl_basic_set *bset,
4760 __isl_keep isl_mat *cst)
4762 return need_split_basic_map(bset_to_bmap(bset), cst);
4765 /* Given that the last set variable of "set" represents the minimum
4766 * of the bounds in "cst", check whether we need to split the domain
4767 * based on which bound attains the minimum.
4769 static isl_bool need_split_set(__isl_keep isl_set *set, __isl_keep isl_mat *cst)
4771 int i;
4773 for (i = 0; i < set->n; ++i) {
4774 isl_bool split;
4776 split = need_split_basic_set(set->p[i], cst);
4777 if (split < 0 || split)
4778 return split;
4781 return isl_bool_false;
4784 /* Given a map of which the last input variable is the minimum
4785 * of the bounds in "cst", split each basic set in the set
4786 * in pieces where one of the bounds is (strictly) smaller than the others.
4787 * This subdivision is given in "min_expr".
4788 * The variable is subsequently projected out.
4790 * We only do the split when it is needed.
4791 * For example if the last input variable m = min(a,b) and the only
4792 * constraints in the given basic set are lower bounds on m,
4793 * i.e., l <= m = min(a,b), then we can simply project out m
4794 * to obtain l <= a and l <= b, without having to split on whether
4795 * m is equal to a or b.
4797 static __isl_give isl_map *split_domain(__isl_take isl_map *opt,
4798 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4800 int n_in;
4801 int i;
4802 isl_space *space;
4803 isl_map *res;
4805 if (!opt || !min_expr || !cst)
4806 goto error;
4808 n_in = isl_map_dim(opt, isl_dim_in);
4809 space = isl_map_get_space(opt);
4810 space = isl_space_drop_dims(space, isl_dim_in, n_in - 1, 1);
4811 res = isl_map_empty(space);
4813 for (i = 0; i < opt->n; ++i) {
4814 isl_map *map;
4815 isl_bool split;
4817 map = isl_map_from_basic_map(isl_basic_map_copy(opt->p[i]));
4818 split = need_split_basic_map(opt->p[i], cst);
4819 if (split < 0)
4820 map = isl_map_free(map);
4821 else if (split)
4822 map = isl_map_intersect_domain(map,
4823 isl_set_copy(min_expr));
4824 map = isl_map_remove_dims(map, isl_dim_in, n_in - 1, 1);
4826 res = isl_map_union_disjoint(res, map);
4829 isl_map_free(opt);
4830 isl_set_free(min_expr);
4831 isl_mat_free(cst);
4832 return res;
4833 error:
4834 isl_map_free(opt);
4835 isl_set_free(min_expr);
4836 isl_mat_free(cst);
4837 return NULL;
4840 /* Given a set of which the last set variable is the minimum
4841 * of the bounds in "cst", split each basic set in the set
4842 * in pieces where one of the bounds is (strictly) smaller than the others.
4843 * This subdivision is given in "min_expr".
4844 * The variable is subsequently projected out.
4846 static __isl_give isl_set *split(__isl_take isl_set *empty,
4847 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
4849 isl_map *map;
4851 map = isl_map_from_domain(empty);
4852 map = split_domain(map, min_expr, cst);
4853 empty = isl_map_domain(map);
4855 return empty;
4858 static __isl_give isl_map *basic_map_partial_lexopt(
4859 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4860 __isl_give isl_set **empty, int max);
4862 /* This function is called from basic_map_partial_lexopt_symm.
4863 * The last variable of "bmap" and "dom" corresponds to the minimum
4864 * of the bounds in "cst". "map_space" is the space of the original
4865 * input relation (of basic_map_partial_lexopt_symm) and "set_space"
4866 * is the space of the original domain.
4868 * We recursively call basic_map_partial_lexopt and then plug in
4869 * the definition of the minimum in the result.
4871 static __isl_give isl_map *basic_map_partial_lexopt_symm_core(
4872 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
4873 __isl_give isl_set **empty, int max, __isl_take isl_mat *cst,
4874 __isl_take isl_space *map_space, __isl_take isl_space *set_space)
4876 isl_map *opt;
4877 isl_set *min_expr;
4879 min_expr = set_minimum(isl_basic_set_get_space(dom), isl_mat_copy(cst));
4881 opt = basic_map_partial_lexopt(bmap, dom, empty, max);
4883 if (empty) {
4884 *empty = split(*empty,
4885 isl_set_copy(min_expr), isl_mat_copy(cst));
4886 *empty = isl_set_reset_space(*empty, set_space);
4889 opt = split_domain(opt, min_expr, cst);
4890 opt = isl_map_reset_space(opt, map_space);
4892 return opt;
4895 /* Extract a domain from "bmap" for the purpose of computing
4896 * a lexicographic optimum.
4898 * This function is only called when the caller wants to compute a full
4899 * lexicographic optimum, i.e., without specifying a domain. In this case,
4900 * the caller is not interested in the part of the domain space where
4901 * there is no solution and the domain can be initialized to those constraints
4902 * of "bmap" that only involve the parameters and the input dimensions.
4903 * This relieves the parametric programming engine from detecting those
4904 * inequalities and transferring them to the context. More importantly,
4905 * it ensures that those inequalities are transferred first and not
4906 * intermixed with inequalities that actually split the domain.
4908 * If the caller does not require the absence of existentially quantified
4909 * variables in the result (i.e., if ISL_OPT_QE is not set in "flags"),
4910 * then the actual domain of "bmap" can be used. This ensures that
4911 * the domain does not need to be split at all just to separate out
4912 * pieces of the domain that do not have a solution from piece that do.
4913 * This domain cannot be used in general because it may involve
4914 * (unknown) existentially quantified variables which will then also
4915 * appear in the solution.
4917 static __isl_give isl_basic_set *extract_domain(__isl_keep isl_basic_map *bmap,
4918 unsigned flags)
4920 int n_div;
4921 int n_out;
4923 n_div = isl_basic_map_dim(bmap, isl_dim_div);
4924 n_out = isl_basic_map_dim(bmap, isl_dim_out);
4925 bmap = isl_basic_map_copy(bmap);
4926 if (ISL_FL_ISSET(flags, ISL_OPT_QE)) {
4927 bmap = isl_basic_map_drop_constraints_involving_dims(bmap,
4928 isl_dim_div, 0, n_div);
4929 bmap = isl_basic_map_drop_constraints_involving_dims(bmap,
4930 isl_dim_out, 0, n_out);
4932 return isl_basic_map_domain(bmap);
4935 #undef TYPE
4936 #define TYPE isl_map
4937 #undef SUFFIX
4938 #define SUFFIX
4939 #include "isl_tab_lexopt_templ.c"
4941 /* Extract the subsequence of the sample value of "tab"
4942 * starting at "pos" and of length "len".
4944 static __isl_give isl_vec *extract_sample_sequence(struct isl_tab *tab,
4945 int pos, int len)
4947 int i;
4948 isl_ctx *ctx;
4949 isl_vec *v;
4951 ctx = isl_tab_get_ctx(tab);
4952 v = isl_vec_alloc(ctx, len);
4953 if (!v)
4954 return NULL;
4955 for (i = 0; i < len; ++i) {
4956 if (!tab->var[pos + i].is_row) {
4957 isl_int_set_si(v->el[i], 0);
4958 } else {
4959 int row;
4961 row = tab->var[pos + i].index;
4962 isl_int_divexact(v->el[i], tab->mat->row[row][1],
4963 tab->mat->row[row][0]);
4967 return v;
4970 /* Check if the sequence of variables starting at "pos"
4971 * represents a trivial solution according to "trivial".
4972 * That is, is the result of applying "trivial" to this sequence
4973 * equal to the zero vector?
4975 static isl_bool region_is_trivial(struct isl_tab *tab, int pos,
4976 __isl_keep isl_mat *trivial)
4978 int n, len;
4979 isl_vec *v;
4980 isl_bool is_trivial;
4982 if (!trivial)
4983 return isl_bool_error;
4985 n = isl_mat_rows(trivial);
4986 if (n == 0)
4987 return isl_bool_false;
4989 len = isl_mat_cols(trivial);
4990 v = extract_sample_sequence(tab, pos, len);
4991 v = isl_mat_vec_product(isl_mat_copy(trivial), v);
4992 is_trivial = isl_vec_is_zero(v);
4993 isl_vec_free(v);
4995 return is_trivial;
4998 /* Global internal data for isl_tab_basic_set_non_trivial_lexmin.
5000 * "n_op" is the number of initial coordinates to optimize,
5001 * as passed to isl_tab_basic_set_non_trivial_lexmin.
5002 * "region" is the "n_region"-sized array of regions passed
5003 * to isl_tab_basic_set_non_trivial_lexmin.
5005 * "tab" is the tableau that corresponds to the ILP problem.
5006 * "local" is an array of local data structure, one for each
5007 * (potential) level of the backtracking procedure of
5008 * isl_tab_basic_set_non_trivial_lexmin.
5009 * "v" is a pre-allocated vector that can be used for adding
5010 * constraints to the tableau.
5012 * "sol" contains the best solution found so far.
5013 * It is initialized to a vector of size zero.
5015 struct isl_lexmin_data {
5016 int n_op;
5017 int n_region;
5018 struct isl_trivial_region *region;
5020 struct isl_tab *tab;
5021 struct isl_local_region *local;
5022 isl_vec *v;
5024 isl_vec *sol;
5027 /* Return the index of the first trivial region, "n_region" if all regions
5028 * are non-trivial or -1 in case of error.
5030 static int first_trivial_region(struct isl_lexmin_data *data)
5032 int i;
5034 for (i = 0; i < data->n_region; ++i) {
5035 isl_bool trivial;
5036 trivial = region_is_trivial(data->tab, data->region[i].pos,
5037 data->region[i].trivial);
5038 if (trivial < 0)
5039 return -1;
5040 if (trivial)
5041 return i;
5044 return data->n_region;
5047 /* Check if the solution is optimal, i.e., whether the first
5048 * n_op entries are zero.
5050 static int is_optimal(__isl_keep isl_vec *sol, int n_op)
5052 int i;
5054 for (i = 0; i < n_op; ++i)
5055 if (!isl_int_is_zero(sol->el[1 + i]))
5056 return 0;
5057 return 1;
5060 /* Add constraints to "tab" that ensure that any solution is significantly
5061 * better than that represented by "sol". That is, find the first
5062 * relevant (within first n_op) non-zero coefficient and force it (along
5063 * with all previous coefficients) to be zero.
5064 * If the solution is already optimal (all relevant coefficients are zero),
5065 * then just mark the table as empty.
5066 * "n_zero" is the number of coefficients that have been forced zero
5067 * by previous calls to this function at the same level.
5068 * Return the updated number of forced zero coefficients or -1 on error.
5070 * This function assumes that at least 2 * (n_op - n_zero) more rows and
5071 * at least 2 * (n_op - n_zero) more elements in the constraint array
5072 * are available in the tableau.
5074 static int force_better_solution(struct isl_tab *tab,
5075 __isl_keep isl_vec *sol, int n_op, int n_zero)
5077 int i, n;
5078 isl_ctx *ctx;
5079 isl_vec *v = NULL;
5081 if (!sol)
5082 return -1;
5084 for (i = n_zero; i < n_op; ++i)
5085 if (!isl_int_is_zero(sol->el[1 + i]))
5086 break;
5088 if (i == n_op) {
5089 if (isl_tab_mark_empty(tab) < 0)
5090 return -1;
5091 return n_op;
5094 ctx = isl_vec_get_ctx(sol);
5095 v = isl_vec_alloc(ctx, 1 + tab->n_var);
5096 if (!v)
5097 return -1;
5099 n = i + 1;
5100 for (; i >= n_zero; --i) {
5101 v = isl_vec_clr(v);
5102 isl_int_set_si(v->el[1 + i], -1);
5103 if (add_lexmin_eq(tab, v->el) < 0)
5104 goto error;
5107 isl_vec_free(v);
5108 return n;
5109 error:
5110 isl_vec_free(v);
5111 return -1;
5114 /* Fix triviality direction "dir" of the given region to zero.
5116 * This function assumes that at least two more rows and at least
5117 * two more elements in the constraint array are available in the tableau.
5119 static isl_stat fix_zero(struct isl_tab *tab, struct isl_trivial_region *region,
5120 int dir, struct isl_lexmin_data *data)
5122 int len;
5124 data->v = isl_vec_clr(data->v);
5125 if (!data->v)
5126 return isl_stat_error;
5127 len = isl_mat_cols(region->trivial);
5128 isl_seq_cpy(data->v->el + 1 + region->pos, region->trivial->row[dir],
5129 len);
5130 if (add_lexmin_eq(tab, data->v->el) < 0)
5131 return isl_stat_error;
5133 return isl_stat_ok;
5136 /* This function selects case "side" for non-triviality region "region",
5137 * assuming all the equality constraints have been imposed already.
5138 * In particular, the triviality direction side/2 is made positive
5139 * if side is even and made negative if side is odd.
5141 * This function assumes that at least one more row and at least
5142 * one more element in the constraint array are available in the tableau.
5144 static struct isl_tab *pos_neg(struct isl_tab *tab,
5145 struct isl_trivial_region *region,
5146 int side, struct isl_lexmin_data *data)
5148 int len;
5150 data->v = isl_vec_clr(data->v);
5151 if (!data->v)
5152 goto error;
5153 isl_int_set_si(data->v->el[0], -1);
5154 len = isl_mat_cols(region->trivial);
5155 if (side % 2 == 0)
5156 isl_seq_cpy(data->v->el + 1 + region->pos,
5157 region->trivial->row[side / 2], len);
5158 else
5159 isl_seq_neg(data->v->el + 1 + region->pos,
5160 region->trivial->row[side / 2], len);
5161 return add_lexmin_ineq(tab, data->v->el);
5162 error:
5163 isl_tab_free(tab);
5164 return NULL;
5167 /* Local data at each level of the backtracking procedure of
5168 * isl_tab_basic_set_non_trivial_lexmin.
5170 * "update" is set if a solution has been found in the current case
5171 * of this level, such that a better solution needs to be enforced
5172 * in the next case.
5173 * "n_zero" is the number of initial coordinates that have already
5174 * been forced to be zero at this level.
5175 * "region" is the non-triviality region considered at this level.
5176 * "side" is the index of the current case at this level.
5177 * "n" is the number of triviality directions.
5178 * "snap" is a snapshot of the tableau holding a state that needs
5179 * to be satisfied by all subsequent cases.
5181 struct isl_local_region {
5182 int update;
5183 int n_zero;
5184 int region;
5185 int side;
5186 int n;
5187 struct isl_tab_undo *snap;
5190 /* Initialize the global data structure "data" used while solving
5191 * the ILP problem "bset".
5193 static isl_stat init_lexmin_data(struct isl_lexmin_data *data,
5194 __isl_keep isl_basic_set *bset)
5196 isl_ctx *ctx;
5198 ctx = isl_basic_set_get_ctx(bset);
5200 data->tab = tab_for_lexmin(bset, NULL, 0, 0);
5201 if (!data->tab)
5202 return isl_stat_error;
5204 data->v = isl_vec_alloc(ctx, 1 + data->tab->n_var);
5205 if (!data->v)
5206 return isl_stat_error;
5207 data->local = isl_calloc_array(ctx, struct isl_local_region,
5208 data->n_region);
5209 if (data->n_region && !data->local)
5210 return isl_stat_error;
5212 data->sol = isl_vec_alloc(ctx, 0);
5214 return isl_stat_ok;
5217 /* Mark all outer levels as requiring a better solution
5218 * in the next cases.
5220 static void update_outer_levels(struct isl_lexmin_data *data, int level)
5222 int i;
5224 for (i = 0; i < level; ++i)
5225 data->local[i].update = 1;
5228 /* Initialize "local" to refer to region "region" and
5229 * to initiate processing at this level.
5231 static isl_stat init_local_region(struct isl_local_region *local, int region,
5232 struct isl_lexmin_data *data)
5234 local->n = isl_mat_rows(data->region[region].trivial);
5235 local->region = region;
5236 local->side = 0;
5237 local->update = 0;
5238 local->n_zero = 0;
5240 return isl_stat_ok;
5243 /* What to do next after entering a level of the backtracking procedure.
5245 * error: some error has occurred; abort
5246 * done: an optimal solution has been found; stop search
5247 * backtrack: backtrack to the previous level
5248 * handle: add the constraints for the current level and
5249 * move to the next level
5251 enum isl_next {
5252 isl_next_error = -1,
5253 isl_next_done,
5254 isl_next_backtrack,
5255 isl_next_handle,
5258 /* Have all cases of the current region been considered?
5259 * If there are n directions, then there are 2n cases.
5261 * The constraints in the current tableau are imposed
5262 * in all subsequent cases. This means that if the current
5263 * tableau is empty, then none of those cases should be considered
5264 * anymore and all cases have effectively been considered.
5266 static int finished_all_cases(struct isl_local_region *local,
5267 struct isl_lexmin_data *data)
5269 if (data->tab->empty)
5270 return 1;
5271 return local->side >= 2 * local->n;
5274 /* Enter level "level" of the backtracking search and figure out
5275 * what to do next. "init" is set if the level was entered
5276 * from a higher level and needs to be initialized.
5277 * Otherwise, the level is entered as a result of backtracking and
5278 * the tableau needs to be restored to a position that can
5279 * be used for the next case at this level.
5280 * The snapshot is assumed to have been saved in the previous case,
5281 * before the constraints specific to that case were added.
5283 * In the initialization case, the local region is initialized
5284 * to point to the first violated region.
5285 * If the constraints of all regions are satisfied by the current
5286 * sample of the tableau, then tell the caller to continue looking
5287 * for a better solution or to stop searching if an optimal solution
5288 * has been found.
5290 * If the tableau is empty or if all cases at the current level
5291 * have been considered, then the caller needs to backtrack as well.
5293 static enum isl_next enter_level(int level, int init,
5294 struct isl_lexmin_data *data)
5296 struct isl_local_region *local = &data->local[level];
5298 if (init) {
5299 int r;
5301 data->tab = cut_to_integer_lexmin(data->tab, CUT_ONE);
5302 if (!data->tab)
5303 return isl_next_error;
5304 if (data->tab->empty)
5305 return isl_next_backtrack;
5306 r = first_trivial_region(data);
5307 if (r < 0)
5308 return isl_next_error;
5309 if (r == data->n_region) {
5310 update_outer_levels(data, level);
5311 isl_vec_free(data->sol);
5312 data->sol = isl_tab_get_sample_value(data->tab);
5313 if (!data->sol)
5314 return isl_next_error;
5315 if (is_optimal(data->sol, data->n_op))
5316 return isl_next_done;
5317 return isl_next_backtrack;
5319 if (level >= data->n_region)
5320 isl_die(isl_vec_get_ctx(data->v), isl_error_internal,
5321 "nesting level too deep",
5322 return isl_next_error);
5323 if (init_local_region(local, r, data) < 0)
5324 return isl_next_error;
5325 if (isl_tab_extend_cons(data->tab,
5326 2 * local->n + 2 * data->n_op) < 0)
5327 return isl_next_error;
5328 } else {
5329 if (isl_tab_rollback(data->tab, local->snap) < 0)
5330 return isl_next_error;
5333 if (finished_all_cases(local, data))
5334 return isl_next_backtrack;
5335 return isl_next_handle;
5338 /* If a solution has been found in the previous case at this level
5339 * (marked by local->update being set), then add constraints
5340 * that enforce a better solution in the present and all following cases.
5341 * The constraints only need to be imposed once because they are
5342 * included in the snapshot (taken in pick_side) that will be used in
5343 * subsequent cases.
5345 static isl_stat better_next_side(struct isl_local_region *local,
5346 struct isl_lexmin_data *data)
5348 if (!local->update)
5349 return isl_stat_ok;
5351 local->n_zero = force_better_solution(data->tab,
5352 data->sol, data->n_op, local->n_zero);
5353 if (local->n_zero < 0)
5354 return isl_stat_error;
5356 local->update = 0;
5358 return isl_stat_ok;
5361 /* Add constraints to data->tab that select the current case (local->side)
5362 * at the current level.
5364 * If the linear combinations v should not be zero, then the cases are
5365 * v_0 >= 1
5366 * v_0 <= -1
5367 * v_0 = 0 and v_1 >= 1
5368 * v_0 = 0 and v_1 <= -1
5369 * v_0 = 0 and v_1 = 0 and v_2 >= 1
5370 * v_0 = 0 and v_1 = 0 and v_2 <= -1
5371 * ...
5372 * in this order.
5374 * A snapshot is taken after the equality constraint (if any) has been added
5375 * such that the next case can start off from this position.
5376 * The rollback to this position is performed in enter_level.
5378 static isl_stat pick_side(struct isl_local_region *local,
5379 struct isl_lexmin_data *data)
5381 struct isl_trivial_region *region;
5382 int side, base;
5384 region = &data->region[local->region];
5385 side = local->side;
5386 base = 2 * (side/2);
5388 if (side == base && base >= 2 &&
5389 fix_zero(data->tab, region, base / 2 - 1, data) < 0)
5390 return isl_stat_error;
5392 local->snap = isl_tab_snap(data->tab);
5393 if (isl_tab_push_basis(data->tab) < 0)
5394 return isl_stat_error;
5396 data->tab = pos_neg(data->tab, region, side, data);
5397 if (!data->tab)
5398 return isl_stat_error;
5399 return isl_stat_ok;
5402 /* Free the memory associated to "data".
5404 static void clear_lexmin_data(struct isl_lexmin_data *data)
5406 free(data->local);
5407 isl_vec_free(data->v);
5408 isl_tab_free(data->tab);
5411 /* Return the lexicographically smallest non-trivial solution of the
5412 * given ILP problem.
5414 * All variables are assumed to be non-negative.
5416 * n_op is the number of initial coordinates to optimize.
5417 * That is, once a solution has been found, we will only continue looking
5418 * for solutions that result in significantly better values for those
5419 * initial coordinates. That is, we only continue looking for solutions
5420 * that increase the number of initial zeros in this sequence.
5422 * A solution is non-trivial, if it is non-trivial on each of the
5423 * specified regions. Each region represents a sequence of
5424 * triviality directions on a sequence of variables that starts
5425 * at a given position. A solution is non-trivial on such a region if
5426 * at least one of the triviality directions is non-zero
5427 * on that sequence of variables.
5429 * Whenever a conflict is encountered, all constraints involved are
5430 * reported to the caller through a call to "conflict".
5432 * We perform a simple branch-and-bound backtracking search.
5433 * Each level in the search represents an initially trivial region
5434 * that is forced to be non-trivial.
5435 * At each level we consider 2 * n cases, where n
5436 * is the number of triviality directions.
5437 * In terms of those n directions v_i, we consider the cases
5438 * v_0 >= 1
5439 * v_0 <= -1
5440 * v_0 = 0 and v_1 >= 1
5441 * v_0 = 0 and v_1 <= -1
5442 * v_0 = 0 and v_1 = 0 and v_2 >= 1
5443 * v_0 = 0 and v_1 = 0 and v_2 <= -1
5444 * ...
5445 * in this order.
5447 __isl_give isl_vec *isl_tab_basic_set_non_trivial_lexmin(
5448 __isl_take isl_basic_set *bset, int n_op, int n_region,
5449 struct isl_trivial_region *region,
5450 int (*conflict)(int con, void *user), void *user)
5452 struct isl_lexmin_data data = { n_op, n_region, region };
5453 int level, init;
5455 if (!bset)
5456 return NULL;
5458 if (init_lexmin_data(&data, bset) < 0)
5459 goto error;
5460 data.tab->conflict = conflict;
5461 data.tab->conflict_user = user;
5463 level = 0;
5464 init = 1;
5466 while (level >= 0) {
5467 enum isl_next next;
5468 struct isl_local_region *local = &data.local[level];
5470 next = enter_level(level, init, &data);
5471 if (next < 0)
5472 goto error;
5473 if (next == isl_next_done)
5474 break;
5475 if (next == isl_next_backtrack) {
5476 level--;
5477 init = 0;
5478 continue;
5481 if (better_next_side(local, &data) < 0)
5482 goto error;
5483 if (pick_side(local, &data) < 0)
5484 goto error;
5486 local->side++;
5487 level++;
5488 init = 1;
5491 clear_lexmin_data(&data);
5492 isl_basic_set_free(bset);
5494 return data.sol;
5495 error:
5496 clear_lexmin_data(&data);
5497 isl_basic_set_free(bset);
5498 isl_vec_free(data.sol);
5499 return NULL;
5502 /* Wrapper for a tableau that is used for computing
5503 * the lexicographically smallest rational point of a non-negative set.
5504 * This point is represented by the sample value of "tab",
5505 * unless "tab" is empty.
5507 struct isl_tab_lexmin {
5508 isl_ctx *ctx;
5509 struct isl_tab *tab;
5512 /* Free "tl" and return NULL.
5514 __isl_null isl_tab_lexmin *isl_tab_lexmin_free(__isl_take isl_tab_lexmin *tl)
5516 if (!tl)
5517 return NULL;
5518 isl_ctx_deref(tl->ctx);
5519 isl_tab_free(tl->tab);
5520 free(tl);
5522 return NULL;
5525 /* Construct an isl_tab_lexmin for computing
5526 * the lexicographically smallest rational point in "bset",
5527 * assuming that all variables are non-negative.
5529 __isl_give isl_tab_lexmin *isl_tab_lexmin_from_basic_set(
5530 __isl_take isl_basic_set *bset)
5532 isl_ctx *ctx;
5533 isl_tab_lexmin *tl;
5535 if (!bset)
5536 return NULL;
5538 ctx = isl_basic_set_get_ctx(bset);
5539 tl = isl_calloc_type(ctx, struct isl_tab_lexmin);
5540 if (!tl)
5541 goto error;
5542 tl->ctx = ctx;
5543 isl_ctx_ref(ctx);
5544 tl->tab = tab_for_lexmin(bset, NULL, 0, 0);
5545 isl_basic_set_free(bset);
5546 if (!tl->tab)
5547 return isl_tab_lexmin_free(tl);
5548 return tl;
5549 error:
5550 isl_basic_set_free(bset);
5551 isl_tab_lexmin_free(tl);
5552 return NULL;
5555 /* Return the dimension of the set represented by "tl".
5557 int isl_tab_lexmin_dim(__isl_keep isl_tab_lexmin *tl)
5559 return tl ? tl->tab->n_var : -1;
5562 /* Add the equality with coefficients "eq" to "tl", updating the optimal
5563 * solution if needed.
5564 * The equality is added as two opposite inequality constraints.
5566 __isl_give isl_tab_lexmin *isl_tab_lexmin_add_eq(__isl_take isl_tab_lexmin *tl,
5567 isl_int *eq)
5569 unsigned n_var;
5571 if (!tl || !eq)
5572 return isl_tab_lexmin_free(tl);
5574 if (isl_tab_extend_cons(tl->tab, 2) < 0)
5575 return isl_tab_lexmin_free(tl);
5576 n_var = tl->tab->n_var;
5577 isl_seq_neg(eq, eq, 1 + n_var);
5578 tl->tab = add_lexmin_ineq(tl->tab, eq);
5579 isl_seq_neg(eq, eq, 1 + n_var);
5580 tl->tab = add_lexmin_ineq(tl->tab, eq);
5582 if (!tl->tab)
5583 return isl_tab_lexmin_free(tl);
5585 return tl;
5588 /* Add cuts to "tl" until the sample value reaches an integer value or
5589 * until the result becomes empty.
5591 __isl_give isl_tab_lexmin *isl_tab_lexmin_cut_to_integer(
5592 __isl_take isl_tab_lexmin *tl)
5594 if (!tl)
5595 return NULL;
5596 tl->tab = cut_to_integer_lexmin(tl->tab, CUT_ONE);
5597 if (!tl->tab)
5598 return isl_tab_lexmin_free(tl);
5599 return tl;
5602 /* Return the lexicographically smallest rational point in the basic set
5603 * from which "tl" was constructed.
5604 * If the original input was empty, then return a zero-length vector.
5606 __isl_give isl_vec *isl_tab_lexmin_get_solution(__isl_keep isl_tab_lexmin *tl)
5608 if (!tl)
5609 return NULL;
5610 if (tl->tab->empty)
5611 return isl_vec_alloc(tl->ctx, 0);
5612 else
5613 return isl_tab_get_sample_value(tl->tab);
5616 struct isl_sol_pma {
5617 struct isl_sol sol;
5618 isl_pw_multi_aff *pma;
5619 isl_set *empty;
5622 static void sol_pma_free(struct isl_sol *sol)
5624 struct isl_sol_pma *sol_pma = (struct isl_sol_pma *) sol;
5625 isl_pw_multi_aff_free(sol_pma->pma);
5626 isl_set_free(sol_pma->empty);
5629 /* This function is called for parts of the context where there is
5630 * no solution, with "bset" corresponding to the context tableau.
5631 * Simply add the basic set to the set "empty".
5633 static void sol_pma_add_empty(struct isl_sol_pma *sol,
5634 __isl_take isl_basic_set *bset)
5636 if (!bset || !sol->empty)
5637 goto error;
5639 sol->empty = isl_set_grow(sol->empty, 1);
5640 bset = isl_basic_set_simplify(bset);
5641 bset = isl_basic_set_finalize(bset);
5642 sol->empty = isl_set_add_basic_set(sol->empty, bset);
5643 if (!sol->empty)
5644 sol->sol.error = 1;
5645 return;
5646 error:
5647 isl_basic_set_free(bset);
5648 sol->sol.error = 1;
5651 /* Given a basic set "dom" that represents the context and a tuple of
5652 * affine expressions "maff" defined over this domain, construct
5653 * an isl_pw_multi_aff with a single cell corresponding to "dom" and
5654 * the affine expressions in "maff".
5656 static void sol_pma_add(struct isl_sol_pma *sol,
5657 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *maff)
5659 isl_pw_multi_aff *pma;
5661 dom = isl_basic_set_simplify(dom);
5662 dom = isl_basic_set_finalize(dom);
5663 pma = isl_pw_multi_aff_alloc(isl_set_from_basic_set(dom), maff);
5664 sol->pma = isl_pw_multi_aff_add_disjoint(sol->pma, pma);
5665 if (!sol->pma)
5666 sol->sol.error = 1;
5669 static void sol_pma_add_empty_wrap(struct isl_sol *sol,
5670 __isl_take isl_basic_set *bset)
5672 sol_pma_add_empty((struct isl_sol_pma *)sol, bset);
5675 static void sol_pma_add_wrap(struct isl_sol *sol,
5676 __isl_take isl_basic_set *dom, __isl_take isl_multi_aff *ma)
5678 sol_pma_add((struct isl_sol_pma *)sol, dom, ma);
5681 /* Construct an isl_sol_pma structure for accumulating the solution.
5682 * If track_empty is set, then we also keep track of the parts
5683 * of the context where there is no solution.
5684 * If max is set, then we are solving a maximization, rather than
5685 * a minimization problem, which means that the variables in the
5686 * tableau have value "M - x" rather than "M + x".
5688 static struct isl_sol *sol_pma_init(__isl_keep isl_basic_map *bmap,
5689 __isl_take isl_basic_set *dom, int track_empty, int max)
5691 struct isl_sol_pma *sol_pma = NULL;
5692 isl_space *space;
5694 if (!bmap)
5695 goto error;
5697 sol_pma = isl_calloc_type(bmap->ctx, struct isl_sol_pma);
5698 if (!sol_pma)
5699 goto error;
5701 sol_pma->sol.free = &sol_pma_free;
5702 if (sol_init(&sol_pma->sol, bmap, dom, max) < 0)
5703 goto error;
5704 sol_pma->sol.add = &sol_pma_add_wrap;
5705 sol_pma->sol.add_empty = track_empty ? &sol_pma_add_empty_wrap : NULL;
5706 space = isl_space_copy(sol_pma->sol.space);
5707 sol_pma->pma = isl_pw_multi_aff_empty(space);
5708 if (!sol_pma->pma)
5709 goto error;
5711 if (track_empty) {
5712 sol_pma->empty = isl_set_alloc_space(isl_basic_set_get_space(dom),
5713 1, ISL_SET_DISJOINT);
5714 if (!sol_pma->empty)
5715 goto error;
5718 isl_basic_set_free(dom);
5719 return &sol_pma->sol;
5720 error:
5721 isl_basic_set_free(dom);
5722 sol_free(&sol_pma->sol);
5723 return NULL;
5726 /* Base case of isl_tab_basic_map_partial_lexopt, after removing
5727 * some obvious symmetries.
5729 * We call basic_map_partial_lexopt_base_sol and extract the results.
5731 static __isl_give isl_pw_multi_aff *basic_map_partial_lexopt_base_pw_multi_aff(
5732 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5733 __isl_give isl_set **empty, int max)
5735 isl_pw_multi_aff *result = NULL;
5736 struct isl_sol *sol;
5737 struct isl_sol_pma *sol_pma;
5739 sol = basic_map_partial_lexopt_base_sol(bmap, dom, empty, max,
5740 &sol_pma_init);
5741 if (!sol)
5742 return NULL;
5743 sol_pma = (struct isl_sol_pma *) sol;
5745 result = isl_pw_multi_aff_copy(sol_pma->pma);
5746 if (empty)
5747 *empty = isl_set_copy(sol_pma->empty);
5748 sol_free(&sol_pma->sol);
5749 return result;
5752 /* Given that the last input variable of "maff" represents the minimum
5753 * of some bounds, check whether we need to plug in the expression
5754 * of the minimum.
5756 * In particular, check if the last input variable appears in any
5757 * of the expressions in "maff".
5759 static isl_bool need_substitution(__isl_keep isl_multi_aff *maff)
5761 int i;
5762 unsigned pos;
5764 pos = isl_multi_aff_dim(maff, isl_dim_in) - 1;
5766 for (i = 0; i < maff->n; ++i) {
5767 isl_bool involves;
5769 involves = isl_aff_involves_dims(maff->u.p[i],
5770 isl_dim_in, pos, 1);
5771 if (involves < 0 || involves)
5772 return involves;
5775 return isl_bool_false;
5778 /* Given a set of upper bounds on the last "input" variable m,
5779 * construct a piecewise affine expression that selects
5780 * the minimal upper bound to m, i.e.,
5781 * divide the space into cells where one
5782 * of the upper bounds is smaller than all the others and select
5783 * this upper bound on that cell.
5785 * In particular, if there are n bounds b_i, then the result
5786 * consists of n cell, each one of the form
5788 * b_i <= b_j for j > i
5789 * b_i < b_j for j < i
5791 * The affine expression on this cell is
5793 * b_i
5795 static __isl_give isl_pw_aff *set_minimum_pa(__isl_take isl_space *space,
5796 __isl_take isl_mat *var)
5798 int i;
5799 isl_aff *aff = NULL;
5800 isl_basic_set *bset = NULL;
5801 isl_pw_aff *paff = NULL;
5802 isl_space *pw_space;
5803 isl_local_space *ls = NULL;
5805 if (!space || !var)
5806 goto error;
5808 ls = isl_local_space_from_space(isl_space_copy(space));
5809 pw_space = isl_space_copy(space);
5810 pw_space = isl_space_from_domain(pw_space);
5811 pw_space = isl_space_add_dims(pw_space, isl_dim_out, 1);
5812 paff = isl_pw_aff_alloc_size(pw_space, var->n_row);
5814 for (i = 0; i < var->n_row; ++i) {
5815 isl_pw_aff *paff_i;
5817 aff = isl_aff_alloc(isl_local_space_copy(ls));
5818 bset = isl_basic_set_alloc_space(isl_space_copy(space), 0,
5819 0, var->n_row - 1);
5820 if (!aff || !bset)
5821 goto error;
5822 isl_int_set_si(aff->v->el[0], 1);
5823 isl_seq_cpy(aff->v->el + 1, var->row[i], var->n_col);
5824 isl_int_set_si(aff->v->el[1 + var->n_col], 0);
5825 bset = select_minimum(bset, var, i);
5826 paff_i = isl_pw_aff_alloc(isl_set_from_basic_set(bset), aff);
5827 paff = isl_pw_aff_add_disjoint(paff, paff_i);
5830 isl_local_space_free(ls);
5831 isl_space_free(space);
5832 isl_mat_free(var);
5833 return paff;
5834 error:
5835 isl_aff_free(aff);
5836 isl_basic_set_free(bset);
5837 isl_pw_aff_free(paff);
5838 isl_local_space_free(ls);
5839 isl_space_free(space);
5840 isl_mat_free(var);
5841 return NULL;
5844 /* Given a piecewise multi-affine expression of which the last input variable
5845 * is the minimum of the bounds in "cst", plug in the value of the minimum.
5846 * This minimum expression is given in "min_expr_pa".
5847 * The set "min_expr" contains the same information, but in the form of a set.
5848 * The variable is subsequently projected out.
5850 * The implementation is similar to those of "split" and "split_domain".
5851 * If the variable appears in a given expression, then minimum expression
5852 * is plugged in. Otherwise, if the variable appears in the constraints
5853 * and a split is required, then the domain is split. Otherwise, no split
5854 * is performed.
5856 static __isl_give isl_pw_multi_aff *split_domain_pma(
5857 __isl_take isl_pw_multi_aff *opt, __isl_take isl_pw_aff *min_expr_pa,
5858 __isl_take isl_set *min_expr, __isl_take isl_mat *cst)
5860 int n_in;
5861 int i;
5862 isl_space *space;
5863 isl_pw_multi_aff *res;
5865 if (!opt || !min_expr || !cst)
5866 goto error;
5868 n_in = isl_pw_multi_aff_dim(opt, isl_dim_in);
5869 space = isl_pw_multi_aff_get_space(opt);
5870 space = isl_space_drop_dims(space, isl_dim_in, n_in - 1, 1);
5871 res = isl_pw_multi_aff_empty(space);
5873 for (i = 0; i < opt->n; ++i) {
5874 isl_bool subs;
5875 isl_pw_multi_aff *pma;
5877 pma = isl_pw_multi_aff_alloc(isl_set_copy(opt->p[i].set),
5878 isl_multi_aff_copy(opt->p[i].maff));
5879 subs = need_substitution(opt->p[i].maff);
5880 if (subs < 0) {
5881 pma = isl_pw_multi_aff_free(pma);
5882 } else if (subs) {
5883 pma = isl_pw_multi_aff_substitute(pma,
5884 isl_dim_in, n_in - 1, min_expr_pa);
5885 } else {
5886 isl_bool split;
5887 split = need_split_set(opt->p[i].set, cst);
5888 if (split < 0)
5889 pma = isl_pw_multi_aff_free(pma);
5890 else if (split)
5891 pma = isl_pw_multi_aff_intersect_domain(pma,
5892 isl_set_copy(min_expr));
5894 pma = isl_pw_multi_aff_project_out(pma,
5895 isl_dim_in, n_in - 1, 1);
5897 res = isl_pw_multi_aff_add_disjoint(res, pma);
5900 isl_pw_multi_aff_free(opt);
5901 isl_pw_aff_free(min_expr_pa);
5902 isl_set_free(min_expr);
5903 isl_mat_free(cst);
5904 return res;
5905 error:
5906 isl_pw_multi_aff_free(opt);
5907 isl_pw_aff_free(min_expr_pa);
5908 isl_set_free(min_expr);
5909 isl_mat_free(cst);
5910 return NULL;
5913 static __isl_give isl_pw_multi_aff *basic_map_partial_lexopt_pw_multi_aff(
5914 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5915 __isl_give isl_set **empty, int max);
5917 /* This function is called from basic_map_partial_lexopt_symm.
5918 * The last variable of "bmap" and "dom" corresponds to the minimum
5919 * of the bounds in "cst". "map_space" is the space of the original
5920 * input relation (of basic_map_partial_lexopt_symm) and "set_space"
5921 * is the space of the original domain.
5923 * We recursively call basic_map_partial_lexopt and then plug in
5924 * the definition of the minimum in the result.
5926 static __isl_give isl_pw_multi_aff *
5927 basic_map_partial_lexopt_symm_core_pw_multi_aff(
5928 __isl_take isl_basic_map *bmap, __isl_take isl_basic_set *dom,
5929 __isl_give isl_set **empty, int max, __isl_take isl_mat *cst,
5930 __isl_take isl_space *map_space, __isl_take isl_space *set_space)
5932 isl_pw_multi_aff *opt;
5933 isl_pw_aff *min_expr_pa;
5934 isl_set *min_expr;
5936 min_expr = set_minimum(isl_basic_set_get_space(dom), isl_mat_copy(cst));
5937 min_expr_pa = set_minimum_pa(isl_basic_set_get_space(dom),
5938 isl_mat_copy(cst));
5940 opt = basic_map_partial_lexopt_pw_multi_aff(bmap, dom, empty, max);
5942 if (empty) {
5943 *empty = split(*empty,
5944 isl_set_copy(min_expr), isl_mat_copy(cst));
5945 *empty = isl_set_reset_space(*empty, set_space);
5948 opt = split_domain_pma(opt, min_expr_pa, min_expr, cst);
5949 opt = isl_pw_multi_aff_reset_space(opt, map_space);
5951 return opt;
5954 #undef TYPE
5955 #define TYPE isl_pw_multi_aff
5956 #undef SUFFIX
5957 #define SUFFIX _pw_multi_aff
5958 #include "isl_tab_lexopt_templ.c"