1 /*
2  * Copyright 2008-2009 Katholieke Universiteit Leuven
3  * Copyright 2012-2013 Ecole Normale Superieure
4  * Copyright 2014-2015 INRIA Rocquencourt
5  * Copyright 2016      Sven Verdoolaege
6  *
7  * Use of this software is governed by the MIT license
8  *
9  * Written by Sven Verdoolaege, K.U.Leuven, Departement
10  * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
11  * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
12  * and Inria Paris - Rocquencourt, Domaine de Voluceau - Rocquencourt,
13  * B.P. 105 - 78153 Le Chesnay, France
14  */
15 
16 #include <isl_ctx_private.h>
17 #include <isl_map_private.h>
18 #include "isl_equalities.h"
19 #include <isl/map.h>
20 #include <isl_seq.h>
21 #include "isl_tab.h"
22 #include <isl_space_private.h>
23 #include <isl_mat_private.h>
24 #include <isl_vec_private.h>
25 
26 #include <bset_to_bmap.c>
27 #include <bset_from_bmap.c>
28 #include <set_to_map.c>
29 #include <set_from_map.c>
30 
swap_equality(__isl_keep isl_basic_map * bmap,int a,int b)31 static void swap_equality(__isl_keep isl_basic_map *bmap, int a, int b)
32 {
33 	isl_int *t = bmap->eq[a];
34 	bmap->eq[a] = bmap->eq[b];
35 	bmap->eq[b] = t;
36 }
37 
swap_inequality(__isl_keep isl_basic_map * bmap,int a,int b)38 static void swap_inequality(__isl_keep isl_basic_map *bmap, int a, int b)
39 {
40 	if (a != b) {
41 		isl_int *t = bmap->ineq[a];
42 		bmap->ineq[a] = bmap->ineq[b];
43 		bmap->ineq[b] = t;
44 	}
45 }
46 
isl_basic_map_normalize_constraints(__isl_take isl_basic_map * bmap)47 __isl_give isl_basic_map *isl_basic_map_normalize_constraints(
48 	__isl_take isl_basic_map *bmap)
49 {
50 	int i;
51 	isl_int gcd;
52 	isl_size total = isl_basic_map_dim(bmap, isl_dim_all);
53 
54 	if (total < 0)
55 		return isl_basic_map_free(bmap);
56 
57 	isl_int_init(gcd);
58 	for (i = bmap->n_eq - 1; i >= 0; --i) {
59 		isl_seq_gcd(bmap->eq[i]+1, total, &gcd);
60 		if (isl_int_is_zero(gcd)) {
61 			if (!isl_int_is_zero(bmap->eq[i][0])) {
62 				bmap = isl_basic_map_set_to_empty(bmap);
63 				break;
64 			}
65 			if (isl_basic_map_drop_equality(bmap, i) < 0)
66 				goto error;
67 			continue;
68 		}
69 		if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL))
70 			isl_int_gcd(gcd, gcd, bmap->eq[i][0]);
71 		if (isl_int_is_one(gcd))
72 			continue;
73 		if (!isl_int_is_divisible_by(bmap->eq[i][0], gcd)) {
74 			bmap = isl_basic_map_set_to_empty(bmap);
75 			break;
76 		}
77 		isl_seq_scale_down(bmap->eq[i], bmap->eq[i], gcd, 1+total);
78 	}
79 
80 	for (i = bmap->n_ineq - 1; i >= 0; --i) {
81 		isl_seq_gcd(bmap->ineq[i]+1, total, &gcd);
82 		if (isl_int_is_zero(gcd)) {
83 			if (isl_int_is_neg(bmap->ineq[i][0])) {
84 				bmap = isl_basic_map_set_to_empty(bmap);
85 				break;
86 			}
87 			if (isl_basic_map_drop_inequality(bmap, i) < 0)
88 				goto error;
89 			continue;
90 		}
91 		if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL))
92 			isl_int_gcd(gcd, gcd, bmap->ineq[i][0]);
93 		if (isl_int_is_one(gcd))
94 			continue;
95 		isl_int_fdiv_q(bmap->ineq[i][0], bmap->ineq[i][0], gcd);
96 		isl_seq_scale_down(bmap->ineq[i]+1, bmap->ineq[i]+1, gcd, total);
97 	}
98 	isl_int_clear(gcd);
99 
100 	return bmap;
101 error:
102 	isl_int_clear(gcd);
103 	isl_basic_map_free(bmap);
104 	return NULL;
105 }
106 
isl_basic_set_normalize_constraints(__isl_take isl_basic_set * bset)107 __isl_give isl_basic_set *isl_basic_set_normalize_constraints(
108 	__isl_take isl_basic_set *bset)
109 {
110 	isl_basic_map *bmap = bset_to_bmap(bset);
111 	return bset_from_bmap(isl_basic_map_normalize_constraints(bmap));
112 }
113 
114 /* Reduce the coefficient of the variable at position "pos"
115  * in integer division "div", such that it lies in the half-open
116  * interval (1/2,1/2], extracting any excess value from this integer division.
117  * "pos" is as determined by isl_basic_map_offset, i.e., pos == 0
118  * corresponds to the constant term.
119  *
120  * That is, the integer division is of the form
121  *
122  *	floor((... + (c * d + r) * x_pos + ...)/d)
123  *
124  * with -d < 2 * r <= d.
125  * Replace it by
126  *
127  *	floor((... + r * x_pos + ...)/d) + c * x_pos
128  *
129  * If 2 * ((c * d + r) % d) <= d, then c = floor((c * d + r)/d).
130  * Otherwise, c = floor((c * d + r)/d) + 1.
131  *
132  * This is the same normalization that is performed by isl_aff_floor.
133  */
reduce_coefficient_in_div(__isl_take isl_basic_map * bmap,int div,int pos)134 static __isl_give isl_basic_map *reduce_coefficient_in_div(
135 	__isl_take isl_basic_map *bmap, int div, int pos)
136 {
137 	isl_int shift;
138 	int add_one;
139 
140 	isl_int_init(shift);
141 	isl_int_fdiv_r(shift, bmap->div[div][1 + pos], bmap->div[div][0]);
142 	isl_int_mul_ui(shift, shift, 2);
143 	add_one = isl_int_gt(shift, bmap->div[div][0]);
144 	isl_int_fdiv_q(shift, bmap->div[div][1 + pos], bmap->div[div][0]);
145 	if (add_one)
146 		isl_int_add_ui(shift, shift, 1);
147 	isl_int_neg(shift, shift);
148 	bmap = isl_basic_map_shift_div(bmap, div, pos, shift);
149 	isl_int_clear(shift);
150 
151 	return bmap;
152 }
153 
154 /* Does the coefficient of the variable at position "pos"
155  * in integer division "div" need to be reduced?
156  * That is, does it lie outside the half-open interval (1/2,1/2]?
157  * The coefficient c/d lies outside this interval if abs(2 * c) >= d and
158  * 2 * c != d.
159  */
needs_reduction(__isl_keep isl_basic_map * bmap,int div,int pos)160 static isl_bool needs_reduction(__isl_keep isl_basic_map *bmap, int div,
161 	int pos)
162 {
163 	isl_bool r;
164 
165 	if (isl_int_is_zero(bmap->div[div][1 + pos]))
166 		return isl_bool_false;
167 
168 	isl_int_mul_ui(bmap->div[div][1 + pos], bmap->div[div][1 + pos], 2);
169 	r = isl_int_abs_ge(bmap->div[div][1 + pos], bmap->div[div][0]) &&
170 	    !isl_int_eq(bmap->div[div][1 + pos], bmap->div[div][0]);
171 	isl_int_divexact_ui(bmap->div[div][1 + pos],
172 			    bmap->div[div][1 + pos], 2);
173 
174 	return r;
175 }
176 
177 /* Reduce the coefficients (including the constant term) of
178  * integer division "div", if needed.
179  * In particular, make sure all coefficients lie in
180  * the half-open interval (1/2,1/2].
181  */
reduce_div_coefficients_of_div(__isl_take isl_basic_map * bmap,int div)182 static __isl_give isl_basic_map *reduce_div_coefficients_of_div(
183 	__isl_take isl_basic_map *bmap, int div)
184 {
185 	int i;
186 	isl_size total;
187 
188 	total = isl_basic_map_dim(bmap, isl_dim_all);
189 	if (total < 0)
190 		return isl_basic_map_free(bmap);
191 	for (i = 0; i < 1 + total; ++i) {
192 		isl_bool reduce;
193 
194 		reduce = needs_reduction(bmap, div, i);
195 		if (reduce < 0)
196 			return isl_basic_map_free(bmap);
197 		if (!reduce)
198 			continue;
199 		bmap = reduce_coefficient_in_div(bmap, div, i);
200 		if (!bmap)
201 			break;
202 	}
203 
204 	return bmap;
205 }
206 
207 /* Reduce the coefficients (including the constant term) of
208  * the known integer divisions, if needed
209  * In particular, make sure all coefficients lie in
210  * the half-open interval (1/2,1/2].
211  */
reduce_div_coefficients(__isl_take isl_basic_map * bmap)212 static __isl_give isl_basic_map *reduce_div_coefficients(
213 	__isl_take isl_basic_map *bmap)
214 {
215 	int i;
216 
217 	if (!bmap)
218 		return NULL;
219 	if (bmap->n_div == 0)
220 		return bmap;
221 
222 	for (i = 0; i < bmap->n_div; ++i) {
223 		if (isl_int_is_zero(bmap->div[i][0]))
224 			continue;
225 		bmap = reduce_div_coefficients_of_div(bmap, i);
226 		if (!bmap)
227 			break;
228 	}
229 
230 	return bmap;
231 }
232 
233 /* Remove any common factor in numerator and denominator of the div expression,
234  * not taking into account the constant term.
235  * That is, if the div is of the form
236  *
237  *	floor((a + m f(x))/(m d))
238  *
239  * then replace it by
240  *
241  *	floor((floor(a/m) + f(x))/d)
242  *
243  * The difference {a/m}/d in the argument satisfies 0 <= {a/m}/d < 1/d
244  * and can therefore not influence the result of the floor.
245  */
normalize_div_expression(__isl_take isl_basic_map * bmap,int div)246 static __isl_give isl_basic_map *normalize_div_expression(
247 	__isl_take isl_basic_map *bmap, int div)
248 {
249 	isl_size total = isl_basic_map_dim(bmap, isl_dim_all);
250 	isl_ctx *ctx = bmap->ctx;
251 
252 	if (total < 0)
253 		return isl_basic_map_free(bmap);
254 	if (isl_int_is_zero(bmap->div[div][0]))
255 		return bmap;
256 	isl_seq_gcd(bmap->div[div] + 2, total, &ctx->normalize_gcd);
257 	isl_int_gcd(ctx->normalize_gcd, ctx->normalize_gcd, bmap->div[div][0]);
258 	if (isl_int_is_one(ctx->normalize_gcd))
259 		return bmap;
260 	isl_int_fdiv_q(bmap->div[div][1], bmap->div[div][1],
261 			ctx->normalize_gcd);
262 	isl_int_divexact(bmap->div[div][0], bmap->div[div][0],
263 			ctx->normalize_gcd);
264 	isl_seq_scale_down(bmap->div[div] + 2, bmap->div[div] + 2,
265 			ctx->normalize_gcd, total);
266 
267 	return bmap;
268 }
269 
270 /* Remove any common factor in numerator and denominator of a div expression,
271  * not taking into account the constant term.
272  * That is, look for any div of the form
273  *
274  *	floor((a + m f(x))/(m d))
275  *
276  * and replace it by
277  *
278  *	floor((floor(a/m) + f(x))/d)
279  *
280  * The difference {a/m}/d in the argument satisfies 0 <= {a/m}/d < 1/d
281  * and can therefore not influence the result of the floor.
282  */
normalize_div_expressions(__isl_take isl_basic_map * bmap)283 static __isl_give isl_basic_map *normalize_div_expressions(
284 	__isl_take isl_basic_map *bmap)
285 {
286 	int i;
287 
288 	if (!bmap)
289 		return NULL;
290 	if (bmap->n_div == 0)
291 		return bmap;
292 
293 	for (i = 0; i < bmap->n_div; ++i)
294 		bmap = normalize_div_expression(bmap, i);
295 
296 	return bmap;
297 }
298 
299 /* Assumes divs have been ordered if keep_divs is set.
300  */
eliminate_var_using_equality(__isl_take isl_basic_map * bmap,unsigned pos,isl_int * eq,int keep_divs,int * progress)301 static __isl_give isl_basic_map *eliminate_var_using_equality(
302 	__isl_take isl_basic_map *bmap,
303 	unsigned pos, isl_int *eq, int keep_divs, int *progress)
304 {
305 	isl_size total;
306 	isl_size v_div;
307 	int k;
308 	int last_div;
309 
310 	total = isl_basic_map_dim(bmap, isl_dim_all);
311 	v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
312 	if (total < 0 || v_div < 0)
313 		return isl_basic_map_free(bmap);
314 	last_div = isl_seq_last_non_zero(eq + 1 + v_div, bmap->n_div);
315 	for (k = 0; k < bmap->n_eq; ++k) {
316 		if (bmap->eq[k] == eq)
317 			continue;
318 		if (isl_int_is_zero(bmap->eq[k][1+pos]))
319 			continue;
320 		if (progress)
321 			*progress = 1;
322 		isl_seq_elim(bmap->eq[k], eq, 1+pos, 1+total, NULL);
323 		isl_seq_normalize(bmap->ctx, bmap->eq[k], 1 + total);
324 	}
325 
326 	for (k = 0; k < bmap->n_ineq; ++k) {
327 		if (isl_int_is_zero(bmap->ineq[k][1+pos]))
328 			continue;
329 		if (progress)
330 			*progress = 1;
331 		isl_seq_elim(bmap->ineq[k], eq, 1+pos, 1+total, NULL);
332 		isl_seq_normalize(bmap->ctx, bmap->ineq[k], 1 + total);
333 		ISL_F_CLR(bmap, ISL_BASIC_MAP_NO_REDUNDANT);
334 		ISL_F_CLR(bmap, ISL_BASIC_MAP_SORTED);
335 	}
336 
337 	for (k = 0; k < bmap->n_div; ++k) {
338 		if (isl_int_is_zero(bmap->div[k][0]))
339 			continue;
340 		if (isl_int_is_zero(bmap->div[k][1+1+pos]))
341 			continue;
342 		if (progress)
343 			*progress = 1;
344 		/* We need to be careful about circular definitions,
345 		 * so for now we just remove the definition of div k
346 		 * if the equality contains any divs.
347 		 * If keep_divs is set, then the divs have been ordered
348 		 * and we can keep the definition as long as the result
349 		 * is still ordered.
350 		 */
351 		if (last_div == -1 || (keep_divs && last_div < k)) {
352 			isl_seq_elim(bmap->div[k]+1, eq,
353 					1+pos, 1+total, &bmap->div[k][0]);
354 			bmap = normalize_div_expression(bmap, k);
355 			if (!bmap)
356 				return NULL;
357 		} else
358 			isl_seq_clr(bmap->div[k], 1 + total);
359 	}
360 
361 	return bmap;
362 }
363 
364 /* Assumes divs have been ordered if keep_divs is set.
365  */
eliminate_div(__isl_take isl_basic_map * bmap,isl_int * eq,unsigned div,int keep_divs)366 static __isl_give isl_basic_map *eliminate_div(__isl_take isl_basic_map *bmap,
367 	isl_int *eq, unsigned div, int keep_divs)
368 {
369 	isl_size v_div;
370 	unsigned pos;
371 
372 	v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
373 	if (v_div < 0)
374 		return isl_basic_map_free(bmap);
375 	pos = v_div + div;
376 	bmap = eliminate_var_using_equality(bmap, pos, eq, keep_divs, NULL);
377 
378 	bmap = isl_basic_map_drop_div(bmap, div);
379 
380 	return bmap;
381 }
382 
383 /* Check if elimination of div "div" using equality "eq" would not
384  * result in a div depending on a later div.
385  */
ok_to_eliminate_div(__isl_keep isl_basic_map * bmap,isl_int * eq,unsigned div)386 static isl_bool ok_to_eliminate_div(__isl_keep isl_basic_map *bmap, isl_int *eq,
387 	unsigned div)
388 {
389 	int k;
390 	int last_div;
391 	isl_size v_div;
392 	unsigned pos;
393 
394 	v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
395 	if (v_div < 0)
396 		return isl_bool_error;
397 	pos = v_div + div;
398 
399 	last_div = isl_seq_last_non_zero(eq + 1 + v_div, bmap->n_div);
400 	if (last_div < 0 || last_div <= div)
401 		return isl_bool_true;
402 
403 	for (k = 0; k <= last_div; ++k) {
404 		if (isl_int_is_zero(bmap->div[k][0]))
405 			continue;
406 		if (!isl_int_is_zero(bmap->div[k][1 + 1 + pos]))
407 			return isl_bool_false;
408 	}
409 
410 	return isl_bool_true;
411 }
412 
413 /* Eliminate divs based on equalities
414  */
eliminate_divs_eq(__isl_take isl_basic_map * bmap,int * progress)415 static __isl_give isl_basic_map *eliminate_divs_eq(
416 	__isl_take isl_basic_map *bmap, int *progress)
417 {
418 	int d;
419 	int i;
420 	int modified = 0;
421 	unsigned off;
422 
423 	bmap = isl_basic_map_order_divs(bmap);
424 
425 	if (!bmap)
426 		return NULL;
427 
428 	off = isl_basic_map_offset(bmap, isl_dim_div);
429 
430 	for (d = bmap->n_div - 1; d >= 0 ; --d) {
431 		for (i = 0; i < bmap->n_eq; ++i) {
432 			isl_bool ok;
433 
434 			if (!isl_int_is_one(bmap->eq[i][off + d]) &&
435 			    !isl_int_is_negone(bmap->eq[i][off + d]))
436 				continue;
437 			ok = ok_to_eliminate_div(bmap, bmap->eq[i], d);
438 			if (ok < 0)
439 				return isl_basic_map_free(bmap);
440 			if (!ok)
441 				continue;
442 			modified = 1;
443 			*progress = 1;
444 			bmap = eliminate_div(bmap, bmap->eq[i], d, 1);
445 			if (isl_basic_map_drop_equality(bmap, i) < 0)
446 				return isl_basic_map_free(bmap);
447 			break;
448 		}
449 	}
450 	if (modified)
451 		return eliminate_divs_eq(bmap, progress);
452 	return bmap;
453 }
454 
455 /* Eliminate divs based on inequalities
456  */
eliminate_divs_ineq(__isl_take isl_basic_map * bmap,int * progress)457 static __isl_give isl_basic_map *eliminate_divs_ineq(
458 	__isl_take isl_basic_map *bmap, int *progress)
459 {
460 	int d;
461 	int i;
462 	unsigned off;
463 	struct isl_ctx *ctx;
464 
465 	if (!bmap)
466 		return NULL;
467 
468 	ctx = bmap->ctx;
469 	off = isl_basic_map_offset(bmap, isl_dim_div);
470 
471 	for (d = bmap->n_div - 1; d >= 0 ; --d) {
472 		for (i = 0; i < bmap->n_eq; ++i)
473 			if (!isl_int_is_zero(bmap->eq[i][off + d]))
474 				break;
475 		if (i < bmap->n_eq)
476 			continue;
477 		for (i = 0; i < bmap->n_ineq; ++i)
478 			if (isl_int_abs_gt(bmap->ineq[i][off + d], ctx->one))
479 				break;
480 		if (i < bmap->n_ineq)
481 			continue;
482 		*progress = 1;
483 		bmap = isl_basic_map_eliminate_vars(bmap, (off-1)+d, 1);
484 		if (!bmap || ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
485 			break;
486 		bmap = isl_basic_map_drop_div(bmap, d);
487 		if (!bmap)
488 			break;
489 	}
490 	return bmap;
491 }
492 
493 /* Does the equality constraint at position "eq" in "bmap" involve
494  * any local variables in the range [first, first + n)
495  * that are not marked as having an explicit representation?
496  */
bmap_eq_involves_unknown_divs(__isl_keep isl_basic_map * bmap,int eq,unsigned first,unsigned n)497 static isl_bool bmap_eq_involves_unknown_divs(__isl_keep isl_basic_map *bmap,
498 	int eq, unsigned first, unsigned n)
499 {
500 	unsigned o_div;
501 	int i;
502 
503 	if (!bmap)
504 		return isl_bool_error;
505 
506 	o_div = isl_basic_map_offset(bmap, isl_dim_div);
507 	for (i = 0; i < n; ++i) {
508 		isl_bool unknown;
509 
510 		if (isl_int_is_zero(bmap->eq[eq][o_div + first + i]))
511 			continue;
512 		unknown = isl_basic_map_div_is_marked_unknown(bmap, first + i);
513 		if (unknown < 0)
514 			return isl_bool_error;
515 		if (unknown)
516 			return isl_bool_true;
517 	}
518 
519 	return isl_bool_false;
520 }
521 
522 /* The last local variable involved in the equality constraint
523  * at position "eq" in "bmap" is the local variable at position "div".
524  * It can therefore be used to extract an explicit representation
525  * for that variable.
526  * Do so unless the local variable already has an explicit representation or
527  * the explicit representation would involve any other local variables
528  * that in turn do not have an explicit representation.
529  * An equality constraint involving local variables without an explicit
530  * representation can be used in isl_basic_map_drop_redundant_divs
531  * to separate out an independent local variable.  Introducing
532  * an explicit representation here would block this transformation,
533  * while the partial explicit representation in itself is not very useful.
534  * Set *progress if anything is changed.
535  *
536  * The equality constraint is of the form
537  *
538  *	f(x) + n e >= 0
539  *
540  * with n a positive number.  The explicit representation derived from
541  * this constraint is
542  *
543  *	floor((-f(x))/n)
544  */
set_div_from_eq(__isl_take isl_basic_map * bmap,int div,int eq,int * progress)545 static __isl_give isl_basic_map *set_div_from_eq(__isl_take isl_basic_map *bmap,
546 	int div, int eq, int *progress)
547 {
548 	isl_size total;
549 	unsigned o_div;
550 	isl_bool involves;
551 
552 	if (!bmap)
553 		return NULL;
554 
555 	if (!isl_int_is_zero(bmap->div[div][0]))
556 		return bmap;
557 
558 	involves = bmap_eq_involves_unknown_divs(bmap, eq, 0, div);
559 	if (involves < 0)
560 		return isl_basic_map_free(bmap);
561 	if (involves)
562 		return bmap;
563 
564 	total = isl_basic_map_dim(bmap, isl_dim_all);
565 	if (total < 0)
566 		return isl_basic_map_free(bmap);
567 	o_div = isl_basic_map_offset(bmap, isl_dim_div);
568 	isl_seq_neg(bmap->div[div] + 1, bmap->eq[eq], 1 + total);
569 	isl_int_set_si(bmap->div[div][1 + o_div + div], 0);
570 	isl_int_set(bmap->div[div][0], bmap->eq[eq][o_div + div]);
571 	if (progress)
572 		*progress = 1;
573 
574 	return bmap;
575 }
576 
577 /* Perform fangcheng (Gaussian elimination) on the equality
578  * constraints of "bmap".
579  * That is, put them into row-echelon form, starting from the last column
580  * backward and use them to eliminate the corresponding coefficients
581  * from all constraints.
582  *
583  * If "progress" is not NULL, then it gets set if the elimination
584  * results in any changes.
585  * The elimination process may result in some equality constraints
586  * getting interchanged or removed.
587  * If "swap" or "drop" are not NULL, then they get called when
588  * two equality constraints get interchanged or
589  * when a number of final equality constraints get removed.
590  * As a special case, if the input turns out to be empty,
591  * then drop gets called with the number of removed equality
592  * constraints set to the total number of equality constraints.
593  * If "swap" or "drop" are not NULL, then the local variables (if any)
594  * are assumed to be in a valid order.
595  */
isl_basic_map_gauss5(__isl_take isl_basic_map * bmap,int * progress,isl_stat (* swap)(unsigned a,unsigned b,void * user),isl_stat (* drop)(unsigned n,void * user),void * user)596 __isl_give isl_basic_map *isl_basic_map_gauss5(__isl_take isl_basic_map *bmap,
597 	int *progress,
598 	isl_stat (*swap)(unsigned a, unsigned b, void *user),
599 	isl_stat (*drop)(unsigned n, void *user), void *user)
600 {
601 	int k;
602 	int done;
603 	int last_var;
604 	unsigned total_var;
605 	isl_size total;
606 	unsigned n_drop;
607 
608 	if (!swap && !drop)
609 		bmap = isl_basic_map_order_divs(bmap);
610 
611 	total = isl_basic_map_dim(bmap, isl_dim_all);
612 	if (total < 0)
613 		return isl_basic_map_free(bmap);
614 
615 	total_var = total - bmap->n_div;
616 
617 	last_var = total - 1;
618 	for (done = 0; done < bmap->n_eq; ++done) {
619 		for (; last_var >= 0; --last_var) {
620 			for (k = done; k < bmap->n_eq; ++k)
621 				if (!isl_int_is_zero(bmap->eq[k][1+last_var]))
622 					break;
623 			if (k < bmap->n_eq)
624 				break;
625 		}
626 		if (last_var < 0)
627 			break;
628 		if (k != done) {
629 			swap_equality(bmap, k, done);
630 			if (swap && swap(k, done, user) < 0)
631 				return isl_basic_map_free(bmap);
632 		}
633 		if (isl_int_is_neg(bmap->eq[done][1+last_var]))
634 			isl_seq_neg(bmap->eq[done], bmap->eq[done], 1+total);
635 
636 		bmap = eliminate_var_using_equality(bmap, last_var,
637 						bmap->eq[done], 1, progress);
638 
639 		if (last_var >= total_var)
640 			bmap = set_div_from_eq(bmap, last_var - total_var,
641 						done, progress);
642 		if (!bmap)
643 			return NULL;
644 	}
645 	if (done == bmap->n_eq)
646 		return bmap;
647 	for (k = done; k < bmap->n_eq; ++k) {
648 		if (isl_int_is_zero(bmap->eq[k][0]))
649 			continue;
650 		if (drop && drop(bmap->n_eq, user) < 0)
651 			return isl_basic_map_free(bmap);
652 		return isl_basic_map_set_to_empty(bmap);
653 	}
654 	n_drop = bmap->n_eq - done;
655 	bmap = isl_basic_map_free_equality(bmap, n_drop);
656 	if (drop && drop(n_drop, user) < 0)
657 		return isl_basic_map_free(bmap);
658 	return bmap;
659 }
660 
isl_basic_map_gauss(__isl_take isl_basic_map * bmap,int * progress)661 __isl_give isl_basic_map *isl_basic_map_gauss(__isl_take isl_basic_map *bmap,
662 	int *progress)
663 {
664 	return isl_basic_map_gauss5(bmap, progress, NULL, NULL, NULL);
665 }
666 
isl_basic_set_gauss(__isl_take isl_basic_set * bset,int * progress)667 __isl_give isl_basic_set *isl_basic_set_gauss(
668 	__isl_take isl_basic_set *bset, int *progress)
669 {
670 	return bset_from_bmap(isl_basic_map_gauss(bset_to_bmap(bset),
671 							progress));
672 }
673 
674 
round_up(unsigned int v)675 static unsigned int round_up(unsigned int v)
676 {
677 	int old_v = v;
678 
679 	while (v) {
680 		old_v = v;
681 		v ^= v & -v;
682 	}
683 	return old_v << 1;
684 }
685 
686 /* Hash table of inequalities in a basic map.
687  * "index" is an array of addresses of inequalities in the basic map, some
688  * of which are NULL.  The inequalities are hashed on the coefficients
689  * except the constant term.
690  * "size" is the number of elements in the array and is always a power of two
691  * "bits" is the number of bits need to represent an index into the array.
692  * "total" is the total dimension of the basic map.
693  */
694 struct isl_constraint_index {
695 	unsigned int size;
696 	int bits;
697 	isl_int ***index;
698 	isl_size total;
699 };
700 
701 /* Fill in the "ci" data structure for holding the inequalities of "bmap".
702  */
create_constraint_index(struct isl_constraint_index * ci,__isl_keep isl_basic_map * bmap)703 static isl_stat create_constraint_index(struct isl_constraint_index *ci,
704 	__isl_keep isl_basic_map *bmap)
705 {
706 	isl_ctx *ctx;
707 
708 	ci->index = NULL;
709 	if (!bmap)
710 		return isl_stat_error;
711 	ci->total = isl_basic_map_dim(bmap, isl_dim_all);
712 	if (ci->total < 0)
713 		return isl_stat_error;
714 	if (bmap->n_ineq == 0)
715 		return isl_stat_ok;
716 	ci->size = round_up(4 * (bmap->n_ineq + 1) / 3 - 1);
717 	ci->bits = ffs(ci->size) - 1;
718 	ctx = isl_basic_map_get_ctx(bmap);
719 	ci->index = isl_calloc_array(ctx, isl_int **, ci->size);
720 	if (!ci->index)
721 		return isl_stat_error;
722 
723 	return isl_stat_ok;
724 }
725 
726 /* Free the memory allocated by create_constraint_index.
727  */
constraint_index_free(struct isl_constraint_index * ci)728 static void constraint_index_free(struct isl_constraint_index *ci)
729 {
730 	free(ci->index);
731 }
732 
733 /* Return the position in ci->index that contains the address of
734  * an inequality that is equal to *ineq up to the constant term,
735  * provided this address is not identical to "ineq".
736  * If there is no such inequality, then return the position where
737  * such an inequality should be inserted.
738  */
hash_index_ineq(struct isl_constraint_index * ci,isl_int ** ineq)739 static int hash_index_ineq(struct isl_constraint_index *ci, isl_int **ineq)
740 {
741 	int h;
742 	uint32_t hash = isl_seq_get_hash_bits((*ineq) + 1, ci->total, ci->bits);
743 	for (h = hash; ci->index[h]; h = (h+1) % ci->size)
744 		if (ineq != ci->index[h] &&
745 		    isl_seq_eq((*ineq) + 1, ci->index[h][0]+1, ci->total))
746 			break;
747 	return h;
748 }
749 
750 /* Return the position in ci->index that contains the address of
751  * an inequality that is equal to the k'th inequality of "bmap"
752  * up to the constant term, provided it does not point to the very
753  * same inequality.
754  * If there is no such inequality, then return the position where
755  * such an inequality should be inserted.
756  */
hash_index(struct isl_constraint_index * ci,__isl_keep isl_basic_map * bmap,int k)757 static int hash_index(struct isl_constraint_index *ci,
758 	__isl_keep isl_basic_map *bmap, int k)
759 {
760 	return hash_index_ineq(ci, &bmap->ineq[k]);
761 }
762 
set_hash_index(struct isl_constraint_index * ci,__isl_keep isl_basic_set * bset,int k)763 static int set_hash_index(struct isl_constraint_index *ci,
764 	__isl_keep isl_basic_set *bset, int k)
765 {
766 	return hash_index(ci, bset, k);
767 }
768 
769 /* Fill in the "ci" data structure with the inequalities of "bset".
770  */
setup_constraint_index(struct isl_constraint_index * ci,__isl_keep isl_basic_set * bset)771 static isl_stat setup_constraint_index(struct isl_constraint_index *ci,
772 	__isl_keep isl_basic_set *bset)
773 {
774 	int k, h;
775 
776 	if (create_constraint_index(ci, bset) < 0)
777 		return isl_stat_error;
778 
779 	for (k = 0; k < bset->n_ineq; ++k) {
780 		h = set_hash_index(ci, bset, k);
781 		ci->index[h] = &bset->ineq[k];
782 	}
783 
784 	return isl_stat_ok;
785 }
786 
787 /* Is the inequality ineq (obviously) redundant with respect
788  * to the constraints in "ci"?
789  *
790  * Look for an inequality in "ci" with the same coefficients and then
791  * check if the contant term of "ineq" is greater than or equal
792  * to the constant term of that inequality.  If so, "ineq" is clearly
793  * redundant.
794  *
795  * Note that hash_index_ineq ignores a stored constraint if it has
796  * the same address as the passed inequality.  It is ok to pass
797  * the address of a local variable here since it will never be
798  * the same as the address of a constraint in "ci".
799  */
constraint_index_is_redundant(struct isl_constraint_index * ci,isl_int * ineq)800 static isl_bool constraint_index_is_redundant(struct isl_constraint_index *ci,
801 	isl_int *ineq)
802 {
803 	int h;
804 
805 	h = hash_index_ineq(ci, &ineq);
806 	if (!ci->index[h])
807 		return isl_bool_false;
808 	return isl_int_ge(ineq[0], (*ci->index[h])[0]);
809 }
810 
811 /* If we can eliminate more than one div, then we need to make
812  * sure we do it from last div to first div, in order not to
813  * change the position of the other divs that still need to
814  * be removed.
815  */
remove_duplicate_divs(__isl_take isl_basic_map * bmap,int * progress)816 static __isl_give isl_basic_map *remove_duplicate_divs(
817 	__isl_take isl_basic_map *bmap, int *progress)
818 {
819 	unsigned int size;
820 	int *index;
821 	int *elim_for;
822 	int k, l, h;
823 	int bits;
824 	struct isl_blk eq;
825 	isl_size v_div;
826 	unsigned total;
827 	struct isl_ctx *ctx;
828 
829 	bmap = isl_basic_map_order_divs(bmap);
830 	if (!bmap || bmap->n_div <= 1)
831 		return bmap;
832 
833 	v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
834 	if (v_div < 0)
835 		return isl_basic_map_free(bmap);
836 	total = v_div + bmap->n_div;
837 
838 	ctx = bmap->ctx;
839 	for (k = bmap->n_div - 1; k >= 0; --k)
840 		if (!isl_int_is_zero(bmap->div[k][0]))
841 			break;
842 	if (k <= 0)
843 		return bmap;
844 
845 	size = round_up(4 * bmap->n_div / 3 - 1);
846 	if (size == 0)
847 		return bmap;
848 	elim_for = isl_calloc_array(ctx, int, bmap->n_div);
849 	bits = ffs(size) - 1;
850 	index = isl_calloc_array(ctx, int, size);
851 	if (!elim_for || !index)
852 		goto out;
853 	eq = isl_blk_alloc(ctx, 1+total);
854 	if (isl_blk_is_error(eq))
855 		goto out;
856 
857 	isl_seq_clr(eq.data, 1+total);
858 	index[isl_seq_get_hash_bits(bmap->div[k], 2+total, bits)] = k + 1;
859 	for (--k; k >= 0; --k) {
860 		uint32_t hash;
861 
862 		if (isl_int_is_zero(bmap->div[k][0]))
863 			continue;
864 
865 		hash = isl_seq_get_hash_bits(bmap->div[k], 2+total, bits);
866 		for (h = hash; index[h]; h = (h+1) % size)
867 			if (isl_seq_eq(bmap->div[k],
868 				       bmap->div[index[h]-1], 2+total))
869 				break;
870 		if (index[h]) {
871 			*progress = 1;
872 			l = index[h] - 1;
873 			elim_for[l] = k + 1;
874 		}
875 		index[h] = k+1;
876 	}
877 	for (l = bmap->n_div - 1; l >= 0; --l) {
878 		if (!elim_for[l])
879 			continue;
880 		k = elim_for[l] - 1;
881 		isl_int_set_si(eq.data[1 + v_div + k], -1);
882 		isl_int_set_si(eq.data[1 + v_div + l], 1);
883 		bmap = eliminate_div(bmap, eq.data, l, 1);
884 		if (!bmap)
885 			break;
886 		isl_int_set_si(eq.data[1 + v_div + k], 0);
887 		isl_int_set_si(eq.data[1 + v_div + l], 0);
888 	}
889 
890 	isl_blk_free(ctx, eq);
891 out:
892 	free(index);
893 	free(elim_for);
894 	return bmap;
895 }
896 
n_pure_div_eq(__isl_keep isl_basic_map * bmap)897 static int n_pure_div_eq(__isl_keep isl_basic_map *bmap)
898 {
899 	int i, j;
900 	isl_size v_div;
901 
902 	v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
903 	if (v_div < 0)
904 		return -1;
905 	for (i = 0, j = bmap->n_div-1; i < bmap->n_eq; ++i) {
906 		while (j >= 0 && isl_int_is_zero(bmap->eq[i][1 + v_div + j]))
907 			--j;
908 		if (j < 0)
909 			break;
910 		if (isl_seq_first_non_zero(bmap->eq[i] + 1 + v_div, j) != -1)
911 			return 0;
912 	}
913 	return i;
914 }
915 
916 /* Normalize divs that appear in equalities.
917  *
918  * In particular, we assume that bmap contains some equalities
919  * of the form
920  *
921  *	a x = m * e_i
922  *
923  * and we want to replace the set of e_i by a minimal set and
924  * such that the new e_i have a canonical representation in terms
925  * of the vector x.
926  * If any of the equalities involves more than one divs, then
927  * we currently simply bail out.
928  *
929  * Let us first additionally assume that all equalities involve
930  * a div.  The equalities then express modulo constraints on the
931  * remaining variables and we can use "parameter compression"
932  * to find a minimal set of constraints.  The result is a transformation
933  *
934  *	x = T(x') = x_0 + G x'
935  *
936  * with G a lower-triangular matrix with all elements below the diagonal
937  * non-negative and smaller than the diagonal element on the same row.
938  * We first normalize x_0 by making the same property hold in the affine
939  * T matrix.
940  * The rows i of G with a 1 on the diagonal do not impose any modulo
941  * constraint and simply express x_i = x'_i.
942  * For each of the remaining rows i, we introduce a div and a corresponding
943  * equality.  In particular
944  *
945  *	g_ii e_j = x_i - g_i(x')
946  *
947  * where each x'_k is replaced either by x_k (if g_kk = 1) or the
948  * corresponding div (if g_kk != 1).
949  *
950  * If there are any equalities not involving any div, then we
951  * first apply a variable compression on the variables x:
952  *
953  *	x = C x''	x'' = C_2 x
954  *
955  * and perform the above parameter compression on A C instead of on A.
956  * The resulting compression is then of the form
957  *
958  *	x'' = T(x') = x_0 + G x'
959  *
960  * and in constructing the new divs and the corresponding equalities,
961  * we have to replace each x'', i.e., the x'_k with (g_kk = 1),
962  * by the corresponding row from C_2.
963  */
normalize_divs(__isl_take isl_basic_map * bmap,int * progress)964 static __isl_give isl_basic_map *normalize_divs(__isl_take isl_basic_map *bmap,
965 	int *progress)
966 {
967 	int i, j, k;
968 	isl_size v_div;
969 	int div_eq;
970 	struct isl_mat *B;
971 	struct isl_vec *d;
972 	struct isl_mat *T = NULL;
973 	struct isl_mat *C = NULL;
974 	struct isl_mat *C2 = NULL;
975 	isl_int v;
976 	int *pos = NULL;
977 	int dropped, needed;
978 
979 	if (!bmap)
980 		return NULL;
981 
982 	if (bmap->n_div == 0)
983 		return bmap;
984 
985 	if (bmap->n_eq == 0)
986 		return bmap;
987 
988 	if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_NORMALIZED_DIVS))
989 		return bmap;
990 
991 	v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
992 	div_eq = n_pure_div_eq(bmap);
993 	if (v_div < 0 || div_eq < 0)
994 		return isl_basic_map_free(bmap);
995 	if (div_eq == 0)
996 		return bmap;
997 
998 	if (div_eq < bmap->n_eq) {
999 		B = isl_mat_sub_alloc6(bmap->ctx, bmap->eq, div_eq,
1000 					bmap->n_eq - div_eq, 0, 1 + v_div);
1001 		C = isl_mat_variable_compression(B, &C2);
1002 		if (!C || !C2)
1003 			goto error;
1004 		if (C->n_col == 0) {
1005 			bmap = isl_basic_map_set_to_empty(bmap);
1006 			isl_mat_free(C);
1007 			isl_mat_free(C2);
1008 			goto done;
1009 		}
1010 	}
1011 
1012 	d = isl_vec_alloc(bmap->ctx, div_eq);
1013 	if (!d)
1014 		goto error;
1015 	for (i = 0, j = bmap->n_div-1; i < div_eq; ++i) {
1016 		while (j >= 0 && isl_int_is_zero(bmap->eq[i][1 + v_div + j]))
1017 			--j;
1018 		isl_int_set(d->block.data[i], bmap->eq[i][1 + v_div + j]);
1019 	}
1020 	B = isl_mat_sub_alloc6(bmap->ctx, bmap->eq, 0, div_eq, 0, 1 + v_div);
1021 
1022 	if (C) {
1023 		B = isl_mat_product(B, C);
1024 		C = NULL;
1025 	}
1026 
1027 	T = isl_mat_parameter_compression(B, d);
1028 	if (!T)
1029 		goto error;
1030 	if (T->n_col == 0) {
1031 		bmap = isl_basic_map_set_to_empty(bmap);
1032 		isl_mat_free(C2);
1033 		isl_mat_free(T);
1034 		goto done;
1035 	}
1036 	isl_int_init(v);
1037 	for (i = 0; i < T->n_row - 1; ++i) {
1038 		isl_int_fdiv_q(v, T->row[1 + i][0], T->row[1 + i][1 + i]);
1039 		if (isl_int_is_zero(v))
1040 			continue;
1041 		isl_mat_col_submul(T, 0, v, 1 + i);
1042 	}
1043 	isl_int_clear(v);
1044 	pos = isl_alloc_array(bmap->ctx, int, T->n_row);
1045 	if (!pos)
1046 		goto error;
1047 	/* We have to be careful because dropping equalities may reorder them */
1048 	dropped = 0;
1049 	for (j = bmap->n_div - 1; j >= 0; --j) {
1050 		for (i = 0; i < bmap->n_eq; ++i)
1051 			if (!isl_int_is_zero(bmap->eq[i][1 + v_div + j]))
1052 				break;
1053 		if (i < bmap->n_eq) {
1054 			bmap = isl_basic_map_drop_div(bmap, j);
1055 			if (isl_basic_map_drop_equality(bmap, i) < 0)
1056 				goto error;
1057 			++dropped;
1058 		}
1059 	}
1060 	pos[0] = 0;
1061 	needed = 0;
1062 	for (i = 1; i < T->n_row; ++i) {
1063 		if (isl_int_is_one(T->row[i][i]))
1064 			pos[i] = i;
1065 		else
1066 			needed++;
1067 	}
1068 	if (needed > dropped) {
1069 		bmap = isl_basic_map_extend(bmap, needed, needed, 0);
1070 		if (!bmap)
1071 			goto error;
1072 	}
1073 	for (i = 1; i < T->n_row; ++i) {
1074 		if (isl_int_is_one(T->row[i][i]))
1075 			continue;
1076 		k = isl_basic_map_alloc_div(bmap);
1077 		pos[i] = 1 + v_div + k;
1078 		isl_seq_clr(bmap->div[k] + 1, 1 + v_div + bmap->n_div);
1079 		isl_int_set(bmap->div[k][0], T->row[i][i]);
1080 		if (C2)
1081 			isl_seq_cpy(bmap->div[k] + 1, C2->row[i], 1 + v_div);
1082 		else
1083 			isl_int_set_si(bmap->div[k][1 + i], 1);
1084 		for (j = 0; j < i; ++j) {
1085 			if (isl_int_is_zero(T->row[i][j]))
1086 				continue;
1087 			if (pos[j] < T->n_row && C2)
1088 				isl_seq_submul(bmap->div[k] + 1, T->row[i][j],
1089 						C2->row[pos[j]], 1 + v_div);
1090 			else
1091 				isl_int_neg(bmap->div[k][1 + pos[j]],
1092 								T->row[i][j]);
1093 		}
1094 		j = isl_basic_map_alloc_equality(bmap);
1095 		isl_seq_neg(bmap->eq[j], bmap->div[k]+1, 1+v_div+bmap->n_div);
1096 		isl_int_set(bmap->eq[j][pos[i]], bmap->div[k][0]);
1097 	}
1098 	free(pos);
1099 	isl_mat_free(C2);
1100 	isl_mat_free(T);
1101 
1102 	if (progress)
1103 		*progress = 1;
1104 done:
1105 	ISL_F_SET(bmap, ISL_BASIC_MAP_NORMALIZED_DIVS);
1106 
1107 	return bmap;
1108 error:
1109 	free(pos);
1110 	isl_mat_free(C);
1111 	isl_mat_free(C2);
1112 	isl_mat_free(T);
1113 	isl_basic_map_free(bmap);
1114 	return NULL;
1115 }
1116 
set_div_from_lower_bound(__isl_take isl_basic_map * bmap,int div,int ineq)1117 static __isl_give isl_basic_map *set_div_from_lower_bound(
1118 	__isl_take isl_basic_map *bmap, int div, int ineq)
1119 {
1120 	unsigned total = isl_basic_map_offset(bmap, isl_dim_div);
1121 
1122 	isl_seq_neg(bmap->div[div] + 1, bmap->ineq[ineq], total + bmap->n_div);
1123 	isl_int_set(bmap->div[div][0], bmap->ineq[ineq][total + div]);
1124 	isl_int_add(bmap->div[div][1], bmap->div[div][1], bmap->div[div][0]);
1125 	isl_int_sub_ui(bmap->div[div][1], bmap->div[div][1], 1);
1126 	isl_int_set_si(bmap->div[div][1 + total + div], 0);
1127 
1128 	return bmap;
1129 }
1130 
1131 /* Check whether it is ok to define a div based on an inequality.
1132  * To avoid the introduction of circular definitions of divs, we
1133  * do not allow such a definition if the resulting expression would refer to
1134  * any other undefined divs or if any known div is defined in
1135  * terms of the unknown div.
1136  */
ok_to_set_div_from_bound(__isl_keep isl_basic_map * bmap,int div,int ineq)1137 static isl_bool ok_to_set_div_from_bound(__isl_keep isl_basic_map *bmap,
1138 	int div, int ineq)
1139 {
1140 	int j;
1141 	unsigned total = isl_basic_map_offset(bmap, isl_dim_div);
1142 
1143 	/* Not defined in terms of unknown divs */
1144 	for (j = 0; j < bmap->n_div; ++j) {
1145 		if (div == j)
1146 			continue;
1147 		if (isl_int_is_zero(bmap->ineq[ineq][total + j]))
1148 			continue;
1149 		if (isl_int_is_zero(bmap->div[j][0]))
1150 			return isl_bool_false;
1151 	}
1152 
1153 	/* No other div defined in terms of this one => avoid loops */
1154 	for (j = 0; j < bmap->n_div; ++j) {
1155 		if (div == j)
1156 			continue;
1157 		if (isl_int_is_zero(bmap->div[j][0]))
1158 			continue;
1159 		if (!isl_int_is_zero(bmap->div[j][1 + total + div]))
1160 			return isl_bool_false;
1161 	}
1162 
1163 	return isl_bool_true;
1164 }
1165 
1166 /* Would an expression for div "div" based on inequality "ineq" of "bmap"
1167  * be a better expression than the current one?
1168  *
1169  * If we do not have any expression yet, then any expression would be better.
1170  * Otherwise we check if the last variable involved in the inequality
1171  * (disregarding the div that it would define) is in an earlier position
1172  * than the last variable involved in the current div expression.
1173  */
better_div_constraint(__isl_keep isl_basic_map * bmap,int div,int ineq)1174 static isl_bool better_div_constraint(__isl_keep isl_basic_map *bmap,
1175 	int div, int ineq)
1176 {
1177 	unsigned total = isl_basic_map_offset(bmap, isl_dim_div);
1178 	int last_div;
1179 	int last_ineq;
1180 
1181 	if (isl_int_is_zero(bmap->div[div][0]))
1182 		return isl_bool_true;
1183 
1184 	if (isl_seq_last_non_zero(bmap->ineq[ineq] + total + div + 1,
1185 				  bmap->n_div - (div + 1)) >= 0)
1186 		return isl_bool_false;
1187 
1188 	last_ineq = isl_seq_last_non_zero(bmap->ineq[ineq], total + div);
1189 	last_div = isl_seq_last_non_zero(bmap->div[div] + 1,
1190 					 total + bmap->n_div);
1191 
1192 	return last_ineq < last_div;
1193 }
1194 
1195 /* Given two constraints "k" and "l" that are opposite to each other,
1196  * except for the constant term, check if we can use them
1197  * to obtain an expression for one of the hitherto unknown divs or
1198  * a "better" expression for a div for which we already have an expression.
1199  * "sum" is the sum of the constant terms of the constraints.
1200  * If this sum is strictly smaller than the coefficient of one
1201  * of the divs, then this pair can be used define the div.
1202  * To avoid the introduction of circular definitions of divs, we
1203  * do not use the pair if the resulting expression would refer to
1204  * any other undefined divs or if any known div is defined in
1205  * terms of the unknown div.
1206  */
check_for_div_constraints(__isl_take isl_basic_map * bmap,int k,int l,isl_int sum,int * progress)1207 static __isl_give isl_basic_map *check_for_div_constraints(
1208 	__isl_take isl_basic_map *bmap, int k, int l, isl_int sum,
1209 	int *progress)
1210 {
1211 	int i;
1212 	unsigned total = isl_basic_map_offset(bmap, isl_dim_div);
1213 
1214 	for (i = 0; i < bmap->n_div; ++i) {
1215 		isl_bool set_div;
1216 
1217 		if (isl_int_is_zero(bmap->ineq[k][total + i]))
1218 			continue;
1219 		if (isl_int_abs_ge(sum, bmap->ineq[k][total + i]))
1220 			continue;
1221 		set_div = better_div_constraint(bmap, i, k);
1222 		if (set_div >= 0 && set_div)
1223 			set_div = ok_to_set_div_from_bound(bmap, i, k);
1224 		if (set_div < 0)
1225 			return isl_basic_map_free(bmap);
1226 		if (!set_div)
1227 			break;
1228 		if (isl_int_is_pos(bmap->ineq[k][total + i]))
1229 			bmap = set_div_from_lower_bound(bmap, i, k);
1230 		else
1231 			bmap = set_div_from_lower_bound(bmap, i, l);
1232 		if (progress)
1233 			*progress = 1;
1234 		break;
1235 	}
1236 	return bmap;
1237 }
1238 
isl_basic_map_remove_duplicate_constraints(__isl_take isl_basic_map * bmap,int * progress,int detect_divs)1239 __isl_give isl_basic_map *isl_basic_map_remove_duplicate_constraints(
1240 	__isl_take isl_basic_map *bmap, int *progress, int detect_divs)
1241 {
1242 	struct isl_constraint_index ci;
1243 	int k, l, h;
1244 	isl_size total = isl_basic_map_dim(bmap, isl_dim_all);
1245 	isl_int sum;
1246 
1247 	if (total < 0 || bmap->n_ineq <= 1)
1248 		return bmap;
1249 
1250 	if (create_constraint_index(&ci, bmap) < 0)
1251 		return bmap;
1252 
1253 	h = isl_seq_get_hash_bits(bmap->ineq[0] + 1, total, ci.bits);
1254 	ci.index[h] = &bmap->ineq[0];
1255 	for (k = 1; k < bmap->n_ineq; ++k) {
1256 		h = hash_index(&ci, bmap, k);
1257 		if (!ci.index[h]) {
1258 			ci.index[h] = &bmap->ineq[k];
1259 			continue;
1260 		}
1261 		if (progress)
1262 			*progress = 1;
1263 		l = ci.index[h] - &bmap->ineq[0];
1264 		if (isl_int_lt(bmap->ineq[k][0], bmap->ineq[l][0]))
1265 			swap_inequality(bmap, k, l);
1266 		isl_basic_map_drop_inequality(bmap, k);
1267 		--k;
1268 	}
1269 	isl_int_init(sum);
1270 	for (k = 0; bmap && k < bmap->n_ineq-1; ++k) {
1271 		isl_seq_neg(bmap->ineq[k]+1, bmap->ineq[k]+1, total);
1272 		h = hash_index(&ci, bmap, k);
1273 		isl_seq_neg(bmap->ineq[k]+1, bmap->ineq[k]+1, total);
1274 		if (!ci.index[h])
1275 			continue;
1276 		l = ci.index[h] - &bmap->ineq[0];
1277 		isl_int_add(sum, bmap->ineq[k][0], bmap->ineq[l][0]);
1278 		if (isl_int_is_pos(sum)) {
1279 			if (detect_divs)
1280 				bmap = check_for_div_constraints(bmap, k, l,
1281 								 sum, progress);
1282 			continue;
1283 		}
1284 		if (isl_int_is_zero(sum)) {
1285 			/* We need to break out of the loop after these
1286 			 * changes since the contents of the hash
1287 			 * will no longer be valid.
1288 			 * Plus, we probably we want to regauss first.
1289 			 */
1290 			if (progress)
1291 				*progress = 1;
1292 			isl_basic_map_drop_inequality(bmap, l);
1293 			isl_basic_map_inequality_to_equality(bmap, k);
1294 		} else
1295 			bmap = isl_basic_map_set_to_empty(bmap);
1296 		break;
1297 	}
1298 	isl_int_clear(sum);
1299 
1300 	constraint_index_free(&ci);
1301 	return bmap;
1302 }
1303 
1304 /* Detect all pairs of inequalities that form an equality.
1305  *
1306  * isl_basic_map_remove_duplicate_constraints detects at most one such pair.
1307  * Call it repeatedly while it is making progress.
1308  */
isl_basic_map_detect_inequality_pairs(__isl_take isl_basic_map * bmap,int * progress)1309 __isl_give isl_basic_map *isl_basic_map_detect_inequality_pairs(
1310 	__isl_take isl_basic_map *bmap, int *progress)
1311 {
1312 	int duplicate;
1313 
1314 	do {
1315 		duplicate = 0;
1316 		bmap = isl_basic_map_remove_duplicate_constraints(bmap,
1317 								&duplicate, 0);
1318 		if (progress && duplicate)
1319 			*progress = 1;
1320 	} while (duplicate);
1321 
1322 	return bmap;
1323 }
1324 
1325 /* Given a known integer division "div" that is not integral
1326  * (with denominator 1), eliminate it from the constraints in "bmap"
1327  * where it appears with a (positive or negative) unit coefficient.
1328  * If "progress" is not NULL, then it gets set if the elimination
1329  * results in any changes.
1330  *
1331  * That is, replace
1332  *
1333  *	floor(e/m) + f >= 0
1334  *
1335  * by
1336  *
1337  *	e + m f >= 0
1338  *
1339  * and
1340  *
1341  *	-floor(e/m) + f >= 0
1342  *
1343  * by
1344  *
1345  *	-e + m f + m - 1 >= 0
1346  *
1347  * The first conversion is valid because floor(e/m) >= -f is equivalent
1348  * to e/m >= -f because -f is an integral expression.
1349  * The second conversion follows from the fact that
1350  *
1351  *	-floor(e/m) = ceil(-e/m) = floor((-e + m - 1)/m)
1352  *
1353  *
1354  * Note that one of the div constraints may have been eliminated
1355  * due to being redundant with respect to the constraint that is
1356  * being modified by this function.  The modified constraint may
1357  * no longer imply this div constraint, so we add it back to make
1358  * sure we do not lose any information.
1359  */
eliminate_unit_div(__isl_take isl_basic_map * bmap,int div,int * progress)1360 static __isl_give isl_basic_map *eliminate_unit_div(
1361 	__isl_take isl_basic_map *bmap, int div, int *progress)
1362 {
1363 	int j;
1364 	isl_size v_div, dim;
1365 	isl_ctx *ctx;
1366 
1367 	v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
1368 	dim = isl_basic_map_dim(bmap, isl_dim_all);
1369 	if (v_div < 0 || dim < 0)
1370 		return isl_basic_map_free(bmap);
1371 
1372 	ctx = isl_basic_map_get_ctx(bmap);
1373 
1374 	for (j = 0; j < bmap->n_ineq; ++j) {
1375 		int s;
1376 
1377 		if (!isl_int_is_one(bmap->ineq[j][1 + v_div + div]) &&
1378 		    !isl_int_is_negone(bmap->ineq[j][1 + v_div + div]))
1379 			continue;
1380 
1381 		if (progress)
1382 			*progress = 1;
1383 
1384 		s = isl_int_sgn(bmap->ineq[j][1 + v_div + div]);
1385 		isl_int_set_si(bmap->ineq[j][1 + v_div + div], 0);
1386 		if (s < 0)
1387 			isl_seq_combine(bmap->ineq[j],
1388 				ctx->negone, bmap->div[div] + 1,
1389 				bmap->div[div][0], bmap->ineq[j], 1 + dim);
1390 		else
1391 			isl_seq_combine(bmap->ineq[j],
1392 				ctx->one, bmap->div[div] + 1,
1393 				bmap->div[div][0], bmap->ineq[j], 1 + dim);
1394 		if (s < 0) {
1395 			isl_int_add(bmap->ineq[j][0],
1396 				bmap->ineq[j][0], bmap->div[div][0]);
1397 			isl_int_sub_ui(bmap->ineq[j][0],
1398 				bmap->ineq[j][0], 1);
1399 		}
1400 
1401 		bmap = isl_basic_map_extend_constraints(bmap, 0, 1);
1402 		bmap = isl_basic_map_add_div_constraint(bmap, div, s);
1403 		if (!bmap)
1404 			return NULL;
1405 	}
1406 
1407 	return bmap;
1408 }
1409 
1410 /* Eliminate selected known divs from constraints where they appear with
1411  * a (positive or negative) unit coefficient.
1412  * In particular, only handle those for which "select" returns isl_bool_true.
1413  * If "progress" is not NULL, then it gets set if the elimination
1414  * results in any changes.
1415  *
1416  * We skip integral divs, i.e., those with denominator 1, as we would
1417  * risk eliminating the div from the div constraints.  We do not need
1418  * to handle those divs here anyway since the div constraints will turn
1419  * out to form an equality and this equality can then be used to eliminate
1420  * the div from all constraints.
1421  */
eliminate_selected_unit_divs(__isl_take isl_basic_map * bmap,isl_bool (* select)(__isl_keep isl_basic_map * bmap,int div),int * progress)1422 static __isl_give isl_basic_map *eliminate_selected_unit_divs(
1423 	__isl_take isl_basic_map *bmap,
1424 	isl_bool (*select)(__isl_keep isl_basic_map *bmap, int div),
1425 	int *progress)
1426 {
1427 	int i;
1428 
1429 	if (!bmap)
1430 		return NULL;
1431 
1432 	for (i = 0; i < bmap->n_div; ++i) {
1433 		isl_bool selected;
1434 
1435 		if (isl_int_is_zero(bmap->div[i][0]))
1436 			continue;
1437 		if (isl_int_is_one(bmap->div[i][0]))
1438 			continue;
1439 		selected = select(bmap, i);
1440 		if (selected < 0)
1441 			return isl_basic_map_free(bmap);
1442 		if (!selected)
1443 			continue;
1444 		bmap = eliminate_unit_div(bmap, i, progress);
1445 		if (!bmap)
1446 			return NULL;
1447 	}
1448 
1449 	return bmap;
1450 }
1451 
1452 /* eliminate_selected_unit_divs callback that selects every
1453  * integer division.
1454  */
is_any_div(__isl_keep isl_basic_map * bmap,int div)1455 static isl_bool is_any_div(__isl_keep isl_basic_map *bmap, int div)
1456 {
1457 	return isl_bool_true;
1458 }
1459 
1460 /* Eliminate known divs from constraints where they appear with
1461  * a (positive or negative) unit coefficient.
1462  * If "progress" is not NULL, then it gets set if the elimination
1463  * results in any changes.
1464  */
eliminate_unit_divs(__isl_take isl_basic_map * bmap,int * progress)1465 static __isl_give isl_basic_map *eliminate_unit_divs(
1466 	__isl_take isl_basic_map *bmap, int *progress)
1467 {
1468 	return eliminate_selected_unit_divs(bmap, &is_any_div, progress);
1469 }
1470 
1471 /* eliminate_selected_unit_divs callback that selects
1472  * integer divisions that only appear with
1473  * a (positive or negative) unit coefficient
1474  * (outside their div constraints).
1475  */
is_pure_unit_div(__isl_keep isl_basic_map * bmap,int div)1476 static isl_bool is_pure_unit_div(__isl_keep isl_basic_map *bmap, int div)
1477 {
1478 	int i;
1479 	isl_size v_div, n_ineq;
1480 
1481 	v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
1482 	n_ineq = isl_basic_map_n_inequality(bmap);
1483 	if (v_div < 0 || n_ineq < 0)
1484 		return isl_bool_error;
1485 
1486 	for (i = 0; i < n_ineq; ++i) {
1487 		isl_bool skip;
1488 
1489 		if (isl_int_is_zero(bmap->ineq[i][1 + v_div + div]))
1490 			continue;
1491 		skip = isl_basic_map_is_div_constraint(bmap,
1492 							bmap->ineq[i], div);
1493 		if (skip < 0)
1494 			return isl_bool_error;
1495 		if (skip)
1496 			continue;
1497 		if (!isl_int_is_one(bmap->ineq[i][1 + v_div + div]) &&
1498 		    !isl_int_is_negone(bmap->ineq[i][1 + v_div + div]))
1499 			return isl_bool_false;
1500 	}
1501 
1502 	return isl_bool_true;
1503 }
1504 
1505 /* Eliminate known divs from constraints where they appear with
1506  * a (positive or negative) unit coefficient,
1507  * but only if they do not appear in any other constraints
1508  * (other than the div constraints).
1509  */
isl_basic_map_eliminate_pure_unit_divs(__isl_take isl_basic_map * bmap)1510 __isl_give isl_basic_map *isl_basic_map_eliminate_pure_unit_divs(
1511 	__isl_take isl_basic_map *bmap)
1512 {
1513 	return eliminate_selected_unit_divs(bmap, &is_pure_unit_div, NULL);
1514 }
1515 
isl_basic_map_simplify(__isl_take isl_basic_map * bmap)1516 __isl_give isl_basic_map *isl_basic_map_simplify(__isl_take isl_basic_map *bmap)
1517 {
1518 	int progress = 1;
1519 	if (!bmap)
1520 		return NULL;
1521 	while (progress) {
1522 		isl_bool empty;
1523 
1524 		progress = 0;
1525 		empty = isl_basic_map_plain_is_empty(bmap);
1526 		if (empty < 0)
1527 			return isl_basic_map_free(bmap);
1528 		if (empty)
1529 			break;
1530 		bmap = isl_basic_map_normalize_constraints(bmap);
1531 		bmap = reduce_div_coefficients(bmap);
1532 		bmap = normalize_div_expressions(bmap);
1533 		bmap = remove_duplicate_divs(bmap, &progress);
1534 		bmap = eliminate_unit_divs(bmap, &progress);
1535 		bmap = eliminate_divs_eq(bmap, &progress);
1536 		bmap = eliminate_divs_ineq(bmap, &progress);
1537 		bmap = isl_basic_map_gauss(bmap, &progress);
1538 		/* requires equalities in normal form */
1539 		bmap = normalize_divs(bmap, &progress);
1540 		bmap = isl_basic_map_remove_duplicate_constraints(bmap,
1541 								&progress, 1);
1542 		if (bmap && progress)
1543 			ISL_F_CLR(bmap, ISL_BASIC_MAP_REDUCED_COEFFICIENTS);
1544 	}
1545 	return bmap;
1546 }
1547 
isl_basic_set_simplify(__isl_take isl_basic_set * bset)1548 __isl_give isl_basic_set *isl_basic_set_simplify(
1549 	__isl_take isl_basic_set *bset)
1550 {
1551 	return bset_from_bmap(isl_basic_map_simplify(bset_to_bmap(bset)));
1552 }
1553 
1554 
isl_basic_map_is_div_constraint(__isl_keep isl_basic_map * bmap,isl_int * constraint,unsigned div)1555 isl_bool isl_basic_map_is_div_constraint(__isl_keep isl_basic_map *bmap,
1556 	isl_int *constraint, unsigned div)
1557 {
1558 	unsigned pos;
1559 
1560 	if (!bmap)
1561 		return isl_bool_error;
1562 
1563 	pos = isl_basic_map_offset(bmap, isl_dim_div) + div;
1564 
1565 	if (isl_int_eq(constraint[pos], bmap->div[div][0])) {
1566 		int neg;
1567 		isl_int_sub(bmap->div[div][1],
1568 				bmap->div[div][1], bmap->div[div][0]);
1569 		isl_int_add_ui(bmap->div[div][1], bmap->div[div][1], 1);
1570 		neg = isl_seq_is_neg(constraint, bmap->div[div]+1, pos);
1571 		isl_int_sub_ui(bmap->div[div][1], bmap->div[div][1], 1);
1572 		isl_int_add(bmap->div[div][1],
1573 				bmap->div[div][1], bmap->div[div][0]);
1574 		if (!neg)
1575 			return isl_bool_false;
1576 		if (isl_seq_first_non_zero(constraint+pos+1,
1577 					    bmap->n_div-div-1) != -1)
1578 			return isl_bool_false;
1579 	} else if (isl_int_abs_eq(constraint[pos], bmap->div[div][0])) {
1580 		if (!isl_seq_eq(constraint, bmap->div[div]+1, pos))
1581 			return isl_bool_false;
1582 		if (isl_seq_first_non_zero(constraint+pos+1,
1583 					    bmap->n_div-div-1) != -1)
1584 			return isl_bool_false;
1585 	} else
1586 		return isl_bool_false;
1587 
1588 	return isl_bool_true;
1589 }
1590 
1591 /* If the only constraints a div d=floor(f/m)
1592  * appears in are its two defining constraints
1593  *
1594  *	f - m d >=0
1595  *	-(f - (m - 1)) + m d >= 0
1596  *
1597  * then it can safely be removed.
1598  */
div_is_redundant(__isl_keep isl_basic_map * bmap,int div)1599 static isl_bool div_is_redundant(__isl_keep isl_basic_map *bmap, int div)
1600 {
1601 	int i;
1602 	isl_size v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
1603 	unsigned pos = 1 + v_div + div;
1604 
1605 	if (v_div < 0)
1606 		return isl_bool_error;
1607 
1608 	for (i = 0; i < bmap->n_eq; ++i)
1609 		if (!isl_int_is_zero(bmap->eq[i][pos]))
1610 			return isl_bool_false;
1611 
1612 	for (i = 0; i < bmap->n_ineq; ++i) {
1613 		isl_bool red;
1614 
1615 		if (isl_int_is_zero(bmap->ineq[i][pos]))
1616 			continue;
1617 		red = isl_basic_map_is_div_constraint(bmap, bmap->ineq[i], div);
1618 		if (red < 0 || !red)
1619 			return red;
1620 	}
1621 
1622 	for (i = 0; i < bmap->n_div; ++i) {
1623 		if (isl_int_is_zero(bmap->div[i][0]))
1624 			continue;
1625 		if (!isl_int_is_zero(bmap->div[i][1+pos]))
1626 			return isl_bool_false;
1627 	}
1628 
1629 	return isl_bool_true;
1630 }
1631 
1632 /*
1633  * Remove divs that don't occur in any of the constraints or other divs.
1634  * These can arise when dropping constraints from a basic map or
1635  * when the divs of a basic map have been temporarily aligned
1636  * with the divs of another basic map.
1637  */
remove_redundant_divs(__isl_take isl_basic_map * bmap)1638 static __isl_give isl_basic_map *remove_redundant_divs(
1639 	__isl_take isl_basic_map *bmap)
1640 {
1641 	int i;
1642 	isl_size v_div;
1643 
1644 	v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
1645 	if (v_div < 0)
1646 		return isl_basic_map_free(bmap);
1647 
1648 	for (i = bmap->n_div-1; i >= 0; --i) {
1649 		isl_bool redundant;
1650 
1651 		redundant = div_is_redundant(bmap, i);
1652 		if (redundant < 0)
1653 			return isl_basic_map_free(bmap);
1654 		if (!redundant)
1655 			continue;
1656 		bmap = isl_basic_map_drop_constraints_involving(bmap,
1657 								v_div + i, 1);
1658 		bmap = isl_basic_map_drop_div(bmap, i);
1659 	}
1660 	return bmap;
1661 }
1662 
1663 /* Mark "bmap" as final, without checking for obviously redundant
1664  * integer divisions.  This function should be used when "bmap"
1665  * is known not to involve any such integer divisions.
1666  */
isl_basic_map_mark_final(__isl_take isl_basic_map * bmap)1667 __isl_give isl_basic_map *isl_basic_map_mark_final(
1668 	__isl_take isl_basic_map *bmap)
1669 {
1670 	if (!bmap)
1671 		return NULL;
1672 	ISL_F_SET(bmap, ISL_BASIC_SET_FINAL);
1673 	return bmap;
1674 }
1675 
1676 /* Mark "bmap" as final, after removing obviously redundant integer divisions.
1677  */
isl_basic_map_finalize(__isl_take isl_basic_map * bmap)1678 __isl_give isl_basic_map *isl_basic_map_finalize(__isl_take isl_basic_map *bmap)
1679 {
1680 	bmap = remove_redundant_divs(bmap);
1681 	bmap = isl_basic_map_mark_final(bmap);
1682 	return bmap;
1683 }
1684 
isl_basic_set_finalize(__isl_take isl_basic_set * bset)1685 __isl_give isl_basic_set *isl_basic_set_finalize(
1686 	__isl_take isl_basic_set *bset)
1687 {
1688 	return bset_from_bmap(isl_basic_map_finalize(bset_to_bmap(bset)));
1689 }
1690 
1691 /* Remove definition of any div that is defined in terms of the given variable.
1692  * The div itself is not removed.  Functions such as
1693  * eliminate_divs_ineq depend on the other divs remaining in place.
1694  */
remove_dependent_vars(__isl_take isl_basic_map * bmap,int pos)1695 static __isl_give isl_basic_map *remove_dependent_vars(
1696 	__isl_take isl_basic_map *bmap, int pos)
1697 {
1698 	int i;
1699 
1700 	if (!bmap)
1701 		return NULL;
1702 
1703 	for (i = 0; i < bmap->n_div; ++i) {
1704 		if (isl_int_is_zero(bmap->div[i][0]))
1705 			continue;
1706 		if (isl_int_is_zero(bmap->div[i][1+1+pos]))
1707 			continue;
1708 		bmap = isl_basic_map_mark_div_unknown(bmap, i);
1709 		if (!bmap)
1710 			return NULL;
1711 	}
1712 	return bmap;
1713 }
1714 
1715 /* Eliminate the specified variables from the constraints using
1716  * Fourier-Motzkin.  The variables themselves are not removed.
1717  */
isl_basic_map_eliminate_vars(__isl_take isl_basic_map * bmap,unsigned pos,unsigned n)1718 __isl_give isl_basic_map *isl_basic_map_eliminate_vars(
1719 	__isl_take isl_basic_map *bmap, unsigned pos, unsigned n)
1720 {
1721 	int d;
1722 	int i, j, k;
1723 	isl_size total;
1724 	int need_gauss = 0;
1725 
1726 	if (n == 0)
1727 		return bmap;
1728 	total = isl_basic_map_dim(bmap, isl_dim_all);
1729 	if (total < 0)
1730 		return isl_basic_map_free(bmap);
1731 
1732 	bmap = isl_basic_map_cow(bmap);
1733 	for (d = pos + n - 1; d >= 0 && d >= pos; --d)
1734 		bmap = remove_dependent_vars(bmap, d);
1735 	if (!bmap)
1736 		return NULL;
1737 
1738 	for (d = pos + n - 1;
1739 	     d >= 0 && d >= total - bmap->n_div && d >= pos; --d)
1740 		isl_seq_clr(bmap->div[d-(total-bmap->n_div)], 2+total);
1741 	for (d = pos + n - 1; d >= 0 && d >= pos; --d) {
1742 		int n_lower, n_upper;
1743 		if (!bmap)
1744 			return NULL;
1745 		for (i = 0; i < bmap->n_eq; ++i) {
1746 			if (isl_int_is_zero(bmap->eq[i][1+d]))
1747 				continue;
1748 			bmap = eliminate_var_using_equality(bmap, d,
1749 							bmap->eq[i], 0, NULL);
1750 			if (isl_basic_map_drop_equality(bmap, i) < 0)
1751 				return isl_basic_map_free(bmap);
1752 			need_gauss = 1;
1753 			break;
1754 		}
1755 		if (i < bmap->n_eq)
1756 			continue;
1757 		n_lower = 0;
1758 		n_upper = 0;
1759 		for (i = 0; i < bmap->n_ineq; ++i) {
1760 			if (isl_int_is_pos(bmap->ineq[i][1+d]))
1761 				n_lower++;
1762 			else if (isl_int_is_neg(bmap->ineq[i][1+d]))
1763 				n_upper++;
1764 		}
1765 		bmap = isl_basic_map_extend_constraints(bmap,
1766 				0, n_lower * n_upper);
1767 		if (!bmap)
1768 			goto error;
1769 		for (i = bmap->n_ineq - 1; i >= 0; --i) {
1770 			int last;
1771 			if (isl_int_is_zero(bmap->ineq[i][1+d]))
1772 				continue;
1773 			last = -1;
1774 			for (j = 0; j < i; ++j) {
1775 				if (isl_int_is_zero(bmap->ineq[j][1+d]))
1776 					continue;
1777 				last = j;
1778 				if (isl_int_sgn(bmap->ineq[i][1+d]) ==
1779 				    isl_int_sgn(bmap->ineq[j][1+d]))
1780 					continue;
1781 				k = isl_basic_map_alloc_inequality(bmap);
1782 				if (k < 0)
1783 					goto error;
1784 				isl_seq_cpy(bmap->ineq[k], bmap->ineq[i],
1785 						1+total);
1786 				isl_seq_elim(bmap->ineq[k], bmap->ineq[j],
1787 						1+d, 1+total, NULL);
1788 			}
1789 			isl_basic_map_drop_inequality(bmap, i);
1790 			i = last + 1;
1791 		}
1792 		if (n_lower > 0 && n_upper > 0) {
1793 			bmap = isl_basic_map_normalize_constraints(bmap);
1794 			bmap = isl_basic_map_remove_duplicate_constraints(bmap,
1795 								    NULL, 0);
1796 			bmap = isl_basic_map_gauss(bmap, NULL);
1797 			bmap = isl_basic_map_remove_redundancies(bmap);
1798 			need_gauss = 0;
1799 			if (!bmap)
1800 				goto error;
1801 			if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
1802 				break;
1803 		}
1804 	}
1805 	if (need_gauss)
1806 		bmap = isl_basic_map_gauss(bmap, NULL);
1807 	return bmap;
1808 error:
1809 	isl_basic_map_free(bmap);
1810 	return NULL;
1811 }
1812 
isl_basic_set_eliminate_vars(__isl_take isl_basic_set * bset,unsigned pos,unsigned n)1813 __isl_give isl_basic_set *isl_basic_set_eliminate_vars(
1814 	__isl_take isl_basic_set *bset, unsigned pos, unsigned n)
1815 {
1816 	return bset_from_bmap(isl_basic_map_eliminate_vars(bset_to_bmap(bset),
1817 								pos, n));
1818 }
1819 
1820 /* Eliminate the specified n dimensions starting at first from the
1821  * constraints, without removing the dimensions from the space.
1822  * If the set is rational, the dimensions are eliminated using Fourier-Motzkin.
1823  * Otherwise, they are projected out and the original space is restored.
1824  */
isl_basic_map_eliminate(__isl_take isl_basic_map * bmap,enum isl_dim_type type,unsigned first,unsigned n)1825 __isl_give isl_basic_map *isl_basic_map_eliminate(
1826 	__isl_take isl_basic_map *bmap,
1827 	enum isl_dim_type type, unsigned first, unsigned n)
1828 {
1829 	isl_space *space;
1830 
1831 	if (!bmap)
1832 		return NULL;
1833 	if (n == 0)
1834 		return bmap;
1835 
1836 	if (isl_basic_map_check_range(bmap, type, first, n) < 0)
1837 		return isl_basic_map_free(bmap);
1838 
1839 	if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL)) {
1840 		first += isl_basic_map_offset(bmap, type) - 1;
1841 		bmap = isl_basic_map_eliminate_vars(bmap, first, n);
1842 		return isl_basic_map_finalize(bmap);
1843 	}
1844 
1845 	space = isl_basic_map_get_space(bmap);
1846 	bmap = isl_basic_map_project_out(bmap, type, first, n);
1847 	bmap = isl_basic_map_insert_dims(bmap, type, first, n);
1848 	bmap = isl_basic_map_reset_space(bmap, space);
1849 	return bmap;
1850 }
1851 
isl_basic_set_eliminate(__isl_take isl_basic_set * bset,enum isl_dim_type type,unsigned first,unsigned n)1852 __isl_give isl_basic_set *isl_basic_set_eliminate(
1853 	__isl_take isl_basic_set *bset,
1854 	enum isl_dim_type type, unsigned first, unsigned n)
1855 {
1856 	return isl_basic_map_eliminate(bset, type, first, n);
1857 }
1858 
1859 /* Remove all constraints from "bmap" that reference any unknown local
1860  * variables (directly or indirectly).
1861  *
1862  * Dropping all constraints on a local variable will make it redundant,
1863  * so it will get removed implicitly by
1864  * isl_basic_map_drop_constraints_involving_dims.  Some other local
1865  * variables may also end up becoming redundant if they only appear
1866  * in constraints together with the unknown local variable.
1867  * Therefore, start over after calling
1868  * isl_basic_map_drop_constraints_involving_dims.
1869  */
isl_basic_map_drop_constraints_involving_unknown_divs(__isl_take isl_basic_map * bmap)1870 __isl_give isl_basic_map *isl_basic_map_drop_constraints_involving_unknown_divs(
1871 	__isl_take isl_basic_map *bmap)
1872 {
1873 	isl_bool known;
1874 	isl_size n_div;
1875 	int i, o_div;
1876 
1877 	known = isl_basic_map_divs_known(bmap);
1878 	if (known < 0)
1879 		return isl_basic_map_free(bmap);
1880 	if (known)
1881 		return bmap;
1882 
1883 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
1884 	if (n_div < 0)
1885 		return isl_basic_map_free(bmap);
1886 	o_div = isl_basic_map_offset(bmap, isl_dim_div) - 1;
1887 
1888 	for (i = 0; i < n_div; ++i) {
1889 		known = isl_basic_map_div_is_known(bmap, i);
1890 		if (known < 0)
1891 			return isl_basic_map_free(bmap);
1892 		if (known)
1893 			continue;
1894 		bmap = remove_dependent_vars(bmap, o_div + i);
1895 		bmap = isl_basic_map_drop_constraints_involving_dims(bmap,
1896 							    isl_dim_div, i, 1);
1897 		n_div = isl_basic_map_dim(bmap, isl_dim_div);
1898 		if (n_div < 0)
1899 			return isl_basic_map_free(bmap);
1900 		i = -1;
1901 	}
1902 
1903 	return bmap;
1904 }
1905 
1906 /* Remove all constraints from "bset" that reference any unknown local
1907  * variables (directly or indirectly).
1908  */
isl_basic_set_drop_constraints_involving_unknown_divs(__isl_take isl_basic_set * bset)1909 __isl_give isl_basic_set *isl_basic_set_drop_constraints_involving_unknown_divs(
1910 	__isl_take isl_basic_set *bset)
1911 {
1912 	isl_basic_map *bmap;
1913 
1914 	bmap = bset_to_bmap(bset);
1915 	bmap = isl_basic_map_drop_constraints_involving_unknown_divs(bmap);
1916 	return bset_from_bmap(bmap);
1917 }
1918 
1919 /* Remove all constraints from "map" that reference any unknown local
1920  * variables (directly or indirectly).
1921  *
1922  * Since constraints may get dropped from the basic maps,
1923  * they may no longer be disjoint from each other.
1924  */
isl_map_drop_constraints_involving_unknown_divs(__isl_take isl_map * map)1925 __isl_give isl_map *isl_map_drop_constraints_involving_unknown_divs(
1926 	__isl_take isl_map *map)
1927 {
1928 	int i;
1929 	isl_bool known;
1930 
1931 	known = isl_map_divs_known(map);
1932 	if (known < 0)
1933 		return isl_map_free(map);
1934 	if (known)
1935 		return map;
1936 
1937 	map = isl_map_cow(map);
1938 	if (!map)
1939 		return NULL;
1940 
1941 	for (i = 0; i < map->n; ++i) {
1942 		map->p[i] =
1943 		    isl_basic_map_drop_constraints_involving_unknown_divs(
1944 								    map->p[i]);
1945 		if (!map->p[i])
1946 			return isl_map_free(map);
1947 	}
1948 
1949 	if (map->n > 1)
1950 		ISL_F_CLR(map, ISL_MAP_DISJOINT);
1951 
1952 	return map;
1953 }
1954 
1955 /* Don't assume equalities are in order, because align_divs
1956  * may have changed the order of the divs.
1957  */
compute_elimination_index(__isl_keep isl_basic_map * bmap,int * elim,unsigned len)1958 static void compute_elimination_index(__isl_keep isl_basic_map *bmap, int *elim,
1959 	unsigned len)
1960 {
1961 	int d, i;
1962 
1963 	for (d = 0; d < len; ++d)
1964 		elim[d] = -1;
1965 	for (i = 0; i < bmap->n_eq; ++i) {
1966 		for (d = len - 1; d >= 0; --d) {
1967 			if (isl_int_is_zero(bmap->eq[i][1+d]))
1968 				continue;
1969 			elim[d] = i;
1970 			break;
1971 		}
1972 	}
1973 }
1974 
set_compute_elimination_index(__isl_keep isl_basic_set * bset,int * elim,unsigned len)1975 static void set_compute_elimination_index(__isl_keep isl_basic_set *bset,
1976 	int *elim, unsigned len)
1977 {
1978 	compute_elimination_index(bset_to_bmap(bset), elim, len);
1979 }
1980 
reduced_using_equalities(isl_int * dst,isl_int * src,__isl_keep isl_basic_map * bmap,int * elim,unsigned total)1981 static int reduced_using_equalities(isl_int *dst, isl_int *src,
1982 	__isl_keep isl_basic_map *bmap, int *elim, unsigned total)
1983 {
1984 	int d;
1985 	int copied = 0;
1986 
1987 	for (d = total - 1; d >= 0; --d) {
1988 		if (isl_int_is_zero(src[1+d]))
1989 			continue;
1990 		if (elim[d] == -1)
1991 			continue;
1992 		if (!copied) {
1993 			isl_seq_cpy(dst, src, 1 + total);
1994 			copied = 1;
1995 		}
1996 		isl_seq_elim(dst, bmap->eq[elim[d]], 1 + d, 1 + total, NULL);
1997 	}
1998 	return copied;
1999 }
2000 
set_reduced_using_equalities(isl_int * dst,isl_int * src,__isl_keep isl_basic_set * bset,int * elim,unsigned total)2001 static int set_reduced_using_equalities(isl_int *dst, isl_int *src,
2002 	__isl_keep isl_basic_set *bset, int *elim, unsigned total)
2003 {
2004 	return reduced_using_equalities(dst, src,
2005 					bset_to_bmap(bset), elim, total);
2006 }
2007 
isl_basic_set_reduce_using_equalities(__isl_take isl_basic_set * bset,__isl_take isl_basic_set * context)2008 static __isl_give isl_basic_set *isl_basic_set_reduce_using_equalities(
2009 	__isl_take isl_basic_set *bset, __isl_take isl_basic_set *context)
2010 {
2011 	int i;
2012 	int *elim;
2013 	isl_size dim;
2014 
2015 	if (!bset || !context)
2016 		goto error;
2017 
2018 	if (context->n_eq == 0) {
2019 		isl_basic_set_free(context);
2020 		return bset;
2021 	}
2022 
2023 	bset = isl_basic_set_cow(bset);
2024 	dim = isl_basic_set_dim(bset, isl_dim_set);
2025 	if (dim < 0)
2026 		goto error;
2027 
2028 	elim = isl_alloc_array(bset->ctx, int, dim);
2029 	if (!elim)
2030 		goto error;
2031 	set_compute_elimination_index(context, elim, dim);
2032 	for (i = 0; i < bset->n_eq; ++i)
2033 		set_reduced_using_equalities(bset->eq[i], bset->eq[i],
2034 							context, elim, dim);
2035 	for (i = 0; i < bset->n_ineq; ++i)
2036 		set_reduced_using_equalities(bset->ineq[i], bset->ineq[i],
2037 							context, elim, dim);
2038 	isl_basic_set_free(context);
2039 	free(elim);
2040 	bset = isl_basic_set_simplify(bset);
2041 	bset = isl_basic_set_finalize(bset);
2042 	return bset;
2043 error:
2044 	isl_basic_set_free(bset);
2045 	isl_basic_set_free(context);
2046 	return NULL;
2047 }
2048 
2049 /* For each inequality in "ineq" that is a shifted (more relaxed)
2050  * copy of an inequality in "context", mark the corresponding entry
2051  * in "row" with -1.
2052  * If an inequality only has a non-negative constant term, then
2053  * mark it as well.
2054  */
mark_shifted_constraints(__isl_keep isl_mat * ineq,__isl_keep isl_basic_set * context,int * row)2055 static isl_stat mark_shifted_constraints(__isl_keep isl_mat *ineq,
2056 	__isl_keep isl_basic_set *context, int *row)
2057 {
2058 	struct isl_constraint_index ci;
2059 	isl_size n_ineq, cols;
2060 	unsigned total;
2061 	int k;
2062 
2063 	if (!ineq || !context)
2064 		return isl_stat_error;
2065 	if (context->n_ineq == 0)
2066 		return isl_stat_ok;
2067 	if (setup_constraint_index(&ci, context) < 0)
2068 		return isl_stat_error;
2069 
2070 	n_ineq = isl_mat_rows(ineq);
2071 	cols = isl_mat_cols(ineq);
2072 	if (n_ineq < 0 || cols < 0)
2073 		return isl_stat_error;
2074 	total = cols - 1;
2075 	for (k = 0; k < n_ineq; ++k) {
2076 		int l;
2077 		isl_bool redundant;
2078 
2079 		l = isl_seq_first_non_zero(ineq->row[k] + 1, total);
2080 		if (l < 0 && isl_int_is_nonneg(ineq->row[k][0])) {
2081 			row[k] = -1;
2082 			continue;
2083 		}
2084 		redundant = constraint_index_is_redundant(&ci, ineq->row[k]);
2085 		if (redundant < 0)
2086 			goto error;
2087 		if (!redundant)
2088 			continue;
2089 		row[k] = -1;
2090 	}
2091 	constraint_index_free(&ci);
2092 	return isl_stat_ok;
2093 error:
2094 	constraint_index_free(&ci);
2095 	return isl_stat_error;
2096 }
2097 
remove_shifted_constraints(__isl_take isl_basic_set * bset,__isl_keep isl_basic_set * context)2098 static __isl_give isl_basic_set *remove_shifted_constraints(
2099 	__isl_take isl_basic_set *bset, __isl_keep isl_basic_set *context)
2100 {
2101 	struct isl_constraint_index ci;
2102 	int k;
2103 
2104 	if (!bset || !context)
2105 		return bset;
2106 
2107 	if (context->n_ineq == 0)
2108 		return bset;
2109 	if (setup_constraint_index(&ci, context) < 0)
2110 		return bset;
2111 
2112 	for (k = 0; k < bset->n_ineq; ++k) {
2113 		isl_bool redundant;
2114 
2115 		redundant = constraint_index_is_redundant(&ci, bset->ineq[k]);
2116 		if (redundant < 0)
2117 			goto error;
2118 		if (!redundant)
2119 			continue;
2120 		bset = isl_basic_set_cow(bset);
2121 		if (!bset)
2122 			goto error;
2123 		isl_basic_set_drop_inequality(bset, k);
2124 		--k;
2125 	}
2126 	constraint_index_free(&ci);
2127 	return bset;
2128 error:
2129 	constraint_index_free(&ci);
2130 	return bset;
2131 }
2132 
2133 /* Remove constraints from "bmap" that are identical to constraints
2134  * in "context" or that are more relaxed (greater constant term).
2135  *
2136  * We perform the test for shifted copies on the pure constraints
2137  * in remove_shifted_constraints.
2138  */
isl_basic_map_remove_shifted_constraints(__isl_take isl_basic_map * bmap,__isl_take isl_basic_map * context)2139 static __isl_give isl_basic_map *isl_basic_map_remove_shifted_constraints(
2140 	__isl_take isl_basic_map *bmap, __isl_take isl_basic_map *context)
2141 {
2142 	isl_basic_set *bset, *bset_context;
2143 
2144 	if (!bmap || !context)
2145 		goto error;
2146 
2147 	if (bmap->n_ineq == 0 || context->n_ineq == 0) {
2148 		isl_basic_map_free(context);
2149 		return bmap;
2150 	}
2151 
2152 	context = isl_basic_map_align_divs(context, bmap);
2153 	bmap = isl_basic_map_align_divs(bmap, context);
2154 
2155 	bset = isl_basic_map_underlying_set(isl_basic_map_copy(bmap));
2156 	bset_context = isl_basic_map_underlying_set(context);
2157 	bset = remove_shifted_constraints(bset, bset_context);
2158 	isl_basic_set_free(bset_context);
2159 
2160 	bmap = isl_basic_map_overlying_set(bset, bmap);
2161 
2162 	return bmap;
2163 error:
2164 	isl_basic_map_free(bmap);
2165 	isl_basic_map_free(context);
2166 	return NULL;
2167 }
2168 
2169 /* Does the (linear part of a) constraint "c" involve any of the "len"
2170  * "relevant" dimensions?
2171  */
is_related(isl_int * c,int len,int * relevant)2172 static int is_related(isl_int *c, int len, int *relevant)
2173 {
2174 	int i;
2175 
2176 	for (i = 0; i < len; ++i) {
2177 		if (!relevant[i])
2178 			continue;
2179 		if (!isl_int_is_zero(c[i]))
2180 			return 1;
2181 	}
2182 
2183 	return 0;
2184 }
2185 
2186 /* Drop constraints from "bmap" that do not involve any of
2187  * the dimensions marked "relevant".
2188  */
drop_unrelated_constraints(__isl_take isl_basic_map * bmap,int * relevant)2189 static __isl_give isl_basic_map *drop_unrelated_constraints(
2190 	__isl_take isl_basic_map *bmap, int *relevant)
2191 {
2192 	int i;
2193 	isl_size dim;
2194 
2195 	dim = isl_basic_map_dim(bmap, isl_dim_all);
2196 	if (dim < 0)
2197 		return isl_basic_map_free(bmap);
2198 	for (i = 0; i < dim; ++i)
2199 		if (!relevant[i])
2200 			break;
2201 	if (i >= dim)
2202 		return bmap;
2203 
2204 	for (i = bmap->n_eq - 1; i >= 0; --i)
2205 		if (!is_related(bmap->eq[i] + 1, dim, relevant)) {
2206 			bmap = isl_basic_map_cow(bmap);
2207 			if (isl_basic_map_drop_equality(bmap, i) < 0)
2208 				return isl_basic_map_free(bmap);
2209 		}
2210 
2211 	for (i = bmap->n_ineq - 1; i >= 0; --i)
2212 		if (!is_related(bmap->ineq[i] + 1, dim, relevant)) {
2213 			bmap = isl_basic_map_cow(bmap);
2214 			if (isl_basic_map_drop_inequality(bmap, i) < 0)
2215 				return isl_basic_map_free(bmap);
2216 		}
2217 
2218 	return bmap;
2219 }
2220 
2221 /* Update the groups in "group" based on the (linear part of a) constraint "c".
2222  *
2223  * In particular, for any variable involved in the constraint,
2224  * find the actual group id from before and replace the group
2225  * of the corresponding variable by the minimal group of all
2226  * the variables involved in the constraint considered so far
2227  * (if this minimum is smaller) or replace the minimum by this group
2228  * (if the minimum is larger).
2229  *
2230  * At the end, all the variables in "c" will (indirectly) point
2231  * to the minimal of the groups that they referred to originally.
2232  */
update_groups(int dim,int * group,isl_int * c)2233 static void update_groups(int dim, int *group, isl_int *c)
2234 {
2235 	int j;
2236 	int min = dim;
2237 
2238 	for (j = 0; j < dim; ++j) {
2239 		if (isl_int_is_zero(c[j]))
2240 			continue;
2241 		while (group[j] >= 0 && group[group[j]] != group[j])
2242 			group[j] = group[group[j]];
2243 		if (group[j] == min)
2244 			continue;
2245 		if (group[j] < min) {
2246 			if (min >= 0 && min < dim)
2247 				group[min] = group[j];
2248 			min = group[j];
2249 		} else
2250 			group[group[j]] = min;
2251 	}
2252 }
2253 
2254 /* Allocate an array of groups of variables, one for each variable
2255  * in "context", initialized to zero.
2256  */
alloc_groups(__isl_keep isl_basic_set * context)2257 static int *alloc_groups(__isl_keep isl_basic_set *context)
2258 {
2259 	isl_ctx *ctx;
2260 	isl_size dim;
2261 
2262 	dim = isl_basic_set_dim(context, isl_dim_set);
2263 	if (dim < 0)
2264 		return NULL;
2265 	ctx = isl_basic_set_get_ctx(context);
2266 	return isl_calloc_array(ctx, int, dim);
2267 }
2268 
2269 /* Drop constraints from "bmap" that only involve variables that are
2270  * not related to any of the variables marked with a "-1" in "group".
2271  *
2272  * We construct groups of variables that collect variables that
2273  * (indirectly) appear in some common constraint of "bmap".
2274  * Each group is identified by the first variable in the group,
2275  * except for the special group of variables that was already identified
2276  * in the input as -1 (or are related to those variables).
2277  * If group[i] is equal to i (or -1), then the group of i is i (or -1),
2278  * otherwise the group of i is the group of group[i].
2279  *
2280  * We first initialize groups for the remaining variables.
2281  * Then we iterate over the constraints of "bmap" and update the
2282  * group of the variables in the constraint by the smallest group.
2283  * Finally, we resolve indirect references to groups by running over
2284  * the variables.
2285  *
2286  * After computing the groups, we drop constraints that do not involve
2287  * any variables in the -1 group.
2288  */
isl_basic_map_drop_unrelated_constraints(__isl_take isl_basic_map * bmap,__isl_take int * group)2289 __isl_give isl_basic_map *isl_basic_map_drop_unrelated_constraints(
2290 	__isl_take isl_basic_map *bmap, __isl_take int *group)
2291 {
2292 	isl_size dim;
2293 	int i;
2294 	int last;
2295 
2296 	dim = isl_basic_map_dim(bmap, isl_dim_all);
2297 	if (dim < 0)
2298 		return isl_basic_map_free(bmap);
2299 
2300 	last = -1;
2301 	for (i = 0; i < dim; ++i)
2302 		if (group[i] >= 0)
2303 			last = group[i] = i;
2304 	if (last < 0) {
2305 		free(group);
2306 		return bmap;
2307 	}
2308 
2309 	for (i = 0; i < bmap->n_eq; ++i)
2310 		update_groups(dim, group, bmap->eq[i] + 1);
2311 	for (i = 0; i < bmap->n_ineq; ++i)
2312 		update_groups(dim, group, bmap->ineq[i] + 1);
2313 
2314 	for (i = 0; i < dim; ++i)
2315 		if (group[i] >= 0)
2316 			group[i] = group[group[i]];
2317 
2318 	for (i = 0; i < dim; ++i)
2319 		group[i] = group[i] == -1;
2320 
2321 	bmap = drop_unrelated_constraints(bmap, group);
2322 
2323 	free(group);
2324 	return bmap;
2325 }
2326 
2327 /* Drop constraints from "context" that are irrelevant for computing
2328  * the gist of "bset".
2329  *
2330  * In particular, drop constraints in variables that are not related
2331  * to any of the variables involved in the constraints of "bset"
2332  * in the sense that there is no sequence of constraints that connects them.
2333  *
2334  * We first mark all variables that appear in "bset" as belonging
2335  * to a "-1" group and then continue with group_and_drop_irrelevant_constraints.
2336  */
drop_irrelevant_constraints(__isl_take isl_basic_set * context,__isl_keep isl_basic_set * bset)2337 static __isl_give isl_basic_set *drop_irrelevant_constraints(
2338 	__isl_take isl_basic_set *context, __isl_keep isl_basic_set *bset)
2339 {
2340 	int *group;
2341 	isl_size dim;
2342 	int i, j;
2343 
2344 	dim = isl_basic_set_dim(bset, isl_dim_set);
2345 	if (!context || dim < 0)
2346 		return isl_basic_set_free(context);
2347 
2348 	group = alloc_groups(context);
2349 
2350 	if (!group)
2351 		return isl_basic_set_free(context);
2352 
2353 	for (i = 0; i < dim; ++i) {
2354 		for (j = 0; j < bset->n_eq; ++j)
2355 			if (!isl_int_is_zero(bset->eq[j][1 + i]))
2356 				break;
2357 		if (j < bset->n_eq) {
2358 			group[i] = -1;
2359 			continue;
2360 		}
2361 		for (j = 0; j < bset->n_ineq; ++j)
2362 			if (!isl_int_is_zero(bset->ineq[j][1 + i]))
2363 				break;
2364 		if (j < bset->n_ineq)
2365 			group[i] = -1;
2366 	}
2367 
2368 	return isl_basic_map_drop_unrelated_constraints(context, group);
2369 }
2370 
2371 /* Drop constraints from "context" that are irrelevant for computing
2372  * the gist of the inequalities "ineq".
2373  * Inequalities in "ineq" for which the corresponding element of row
2374  * is set to -1 have already been marked for removal and should be ignored.
2375  *
2376  * In particular, drop constraints in variables that are not related
2377  * to any of the variables involved in "ineq"
2378  * in the sense that there is no sequence of constraints that connects them.
2379  *
2380  * We first mark all variables that appear in "bset" as belonging
2381  * to a "-1" group and then continue with group_and_drop_irrelevant_constraints.
2382  */
drop_irrelevant_constraints_marked(__isl_take isl_basic_set * context,__isl_keep isl_mat * ineq,int * row)2383 static __isl_give isl_basic_set *drop_irrelevant_constraints_marked(
2384 	__isl_take isl_basic_set *context, __isl_keep isl_mat *ineq, int *row)
2385 {
2386 	int *group;
2387 	isl_size dim;
2388 	int i, j;
2389 	isl_size n;
2390 
2391 	dim = isl_basic_set_dim(context, isl_dim_set);
2392 	n = isl_mat_rows(ineq);
2393 	if (dim < 0 || n < 0)
2394 		return isl_basic_set_free(context);
2395 
2396 	group = alloc_groups(context);
2397 
2398 	if (!group)
2399 		return isl_basic_set_free(context);
2400 
2401 	for (i = 0; i < dim; ++i) {
2402 		for (j = 0; j < n; ++j) {
2403 			if (row[j] < 0)
2404 				continue;
2405 			if (!isl_int_is_zero(ineq->row[j][1 + i]))
2406 				break;
2407 		}
2408 		if (j < n)
2409 			group[i] = -1;
2410 	}
2411 
2412 	return isl_basic_map_drop_unrelated_constraints(context, group);
2413 }
2414 
2415 /* Do all "n" entries of "row" contain a negative value?
2416  */
all_neg(int * row,int n)2417 static int all_neg(int *row, int n)
2418 {
2419 	int i;
2420 
2421 	for (i = 0; i < n; ++i)
2422 		if (row[i] >= 0)
2423 			return 0;
2424 
2425 	return 1;
2426 }
2427 
2428 /* Update the inequalities in "bset" based on the information in "row"
2429  * and "tab".
2430  *
2431  * In particular, the array "row" contains either -1, meaning that
2432  * the corresponding inequality of "bset" is redundant, or the index
2433  * of an inequality in "tab".
2434  *
2435  * If the row entry is -1, then drop the inequality.
2436  * Otherwise, if the constraint is marked redundant in the tableau,
2437  * then drop the inequality.  Similarly, if it is marked as an equality
2438  * in the tableau, then turn the inequality into an equality and
2439  * perform Gaussian elimination.
2440  */
update_ineq(__isl_take isl_basic_set * bset,__isl_keep int * row,struct isl_tab * tab)2441 static __isl_give isl_basic_set *update_ineq(__isl_take isl_basic_set *bset,
2442 	__isl_keep int *row, struct isl_tab *tab)
2443 {
2444 	int i;
2445 	unsigned n_ineq;
2446 	unsigned n_eq;
2447 	int found_equality = 0;
2448 
2449 	if (!bset)
2450 		return NULL;
2451 	if (tab && tab->empty)
2452 		return isl_basic_set_set_to_empty(bset);
2453 
2454 	n_ineq = bset->n_ineq;
2455 	for (i = n_ineq - 1; i >= 0; --i) {
2456 		if (row[i] < 0) {
2457 			if (isl_basic_set_drop_inequality(bset, i) < 0)
2458 				return isl_basic_set_free(bset);
2459 			continue;
2460 		}
2461 		if (!tab)
2462 			continue;
2463 		n_eq = tab->n_eq;
2464 		if (isl_tab_is_equality(tab, n_eq + row[i])) {
2465 			isl_basic_map_inequality_to_equality(bset, i);
2466 			found_equality = 1;
2467 		} else if (isl_tab_is_redundant(tab, n_eq + row[i])) {
2468 			if (isl_basic_set_drop_inequality(bset, i) < 0)
2469 				return isl_basic_set_free(bset);
2470 		}
2471 	}
2472 
2473 	if (found_equality)
2474 		bset = isl_basic_set_gauss(bset, NULL);
2475 	bset = isl_basic_set_finalize(bset);
2476 	return bset;
2477 }
2478 
2479 /* Update the inequalities in "bset" based on the information in "row"
2480  * and "tab" and free all arguments (other than "bset").
2481  */
update_ineq_free(__isl_take isl_basic_set * bset,__isl_take isl_mat * ineq,__isl_take isl_basic_set * context,__isl_take int * row,struct isl_tab * tab)2482 static __isl_give isl_basic_set *update_ineq_free(
2483 	__isl_take isl_basic_set *bset, __isl_take isl_mat *ineq,
2484 	__isl_take isl_basic_set *context, __isl_take int *row,
2485 	struct isl_tab *tab)
2486 {
2487 	isl_mat_free(ineq);
2488 	isl_basic_set_free(context);
2489 
2490 	bset = update_ineq(bset, row, tab);
2491 
2492 	free(row);
2493 	isl_tab_free(tab);
2494 	return bset;
2495 }
2496 
2497 /* Remove all information from bset that is redundant in the context
2498  * of context.
2499  * "ineq" contains the (possibly transformed) inequalities of "bset",
2500  * in the same order.
2501  * The (explicit) equalities of "bset" are assumed to have been taken
2502  * into account by the transformation such that only the inequalities
2503  * are relevant.
2504  * "context" is assumed not to be empty.
2505  *
2506  * "row" keeps track of the constraint index of a "bset" inequality in "tab".
2507  * A value of -1 means that the inequality is obviously redundant and may
2508  * not even appear in  "tab".
2509  *
2510  * We first mark the inequalities of "bset"
2511  * that are obviously redundant with respect to some inequality in "context".
2512  * Then we remove those constraints from "context" that have become
2513  * irrelevant for computing the gist of "bset".
2514  * Note that this removal of constraints cannot be replaced by
2515  * a factorization because factors in "bset" may still be connected
2516  * to each other through constraints in "context".
2517  *
2518  * If there are any inequalities left, we construct a tableau for
2519  * the context and then add the inequalities of "bset".
2520  * Before adding these inequalities, we freeze all constraints such that
2521  * they won't be considered redundant in terms of the constraints of "bset".
2522  * Then we detect all redundant constraints (among the
2523  * constraints that weren't frozen), first by checking for redundancy in the
2524  * the tableau and then by checking if replacing a constraint by its negation
2525  * would lead to an empty set.  This last step is fairly expensive
2526  * and could be optimized by more reuse of the tableau.
2527  * Finally, we update bset according to the results.
2528  */
uset_gist_full(__isl_take isl_basic_set * bset,__isl_take isl_mat * ineq,__isl_take isl_basic_set * context)2529 static __isl_give isl_basic_set *uset_gist_full(__isl_take isl_basic_set *bset,
2530 	__isl_take isl_mat *ineq, __isl_take isl_basic_set *context)
2531 {
2532 	int i, r;
2533 	int *row = NULL;
2534 	isl_ctx *ctx;
2535 	isl_basic_set *combined = NULL;
2536 	struct isl_tab *tab = NULL;
2537 	unsigned n_eq, context_ineq;
2538 
2539 	if (!bset || !ineq || !context)
2540 		goto error;
2541 
2542 	if (bset->n_ineq == 0 || isl_basic_set_plain_is_universe(context)) {
2543 		isl_basic_set_free(context);
2544 		isl_mat_free(ineq);
2545 		return bset;
2546 	}
2547 
2548 	ctx = isl_basic_set_get_ctx(context);
2549 	row = isl_calloc_array(ctx, int, bset->n_ineq);
2550 	if (!row)
2551 		goto error;
2552 
2553 	if (mark_shifted_constraints(ineq, context, row) < 0)
2554 		goto error;
2555 	if (all_neg(row, bset->n_ineq))
2556 		return update_ineq_free(bset, ineq, context, row, NULL);
2557 
2558 	context = drop_irrelevant_constraints_marked(context, ineq, row);
2559 	if (!context)
2560 		goto error;
2561 	if (isl_basic_set_plain_is_universe(context))
2562 		return update_ineq_free(bset, ineq, context, row, NULL);
2563 
2564 	n_eq = context->n_eq;
2565 	context_ineq = context->n_ineq;
2566 	combined = isl_basic_set_cow(isl_basic_set_copy(context));
2567 	combined = isl_basic_set_extend_constraints(combined, 0, bset->n_ineq);
2568 	tab = isl_tab_from_basic_set(combined, 0);
2569 	for (i = 0; i < context_ineq; ++i)
2570 		if (isl_tab_freeze_constraint(tab, n_eq + i) < 0)
2571 			goto error;
2572 	if (isl_tab_extend_cons(tab, bset->n_ineq) < 0)
2573 		goto error;
2574 	r = context_ineq;
2575 	for (i = 0; i < bset->n_ineq; ++i) {
2576 		if (row[i] < 0)
2577 			continue;
2578 		combined = isl_basic_set_add_ineq(combined, ineq->row[i]);
2579 		if (isl_tab_add_ineq(tab, ineq->row[i]) < 0)
2580 			goto error;
2581 		row[i] = r++;
2582 	}
2583 	if (isl_tab_detect_implicit_equalities(tab) < 0)
2584 		goto error;
2585 	if (isl_tab_detect_redundant(tab) < 0)
2586 		goto error;
2587 	for (i = bset->n_ineq - 1; i >= 0; --i) {
2588 		isl_basic_set *test;
2589 		int is_empty;
2590 
2591 		if (row[i] < 0)
2592 			continue;
2593 		r = row[i];
2594 		if (tab->con[n_eq + r].is_redundant)
2595 			continue;
2596 		test = isl_basic_set_dup(combined);
2597 		test = isl_inequality_negate(test, r);
2598 		test = isl_basic_set_update_from_tab(test, tab);
2599 		is_empty = isl_basic_set_is_empty(test);
2600 		isl_basic_set_free(test);
2601 		if (is_empty < 0)
2602 			goto error;
2603 		if (is_empty)
2604 			tab->con[n_eq + r].is_redundant = 1;
2605 	}
2606 	bset = update_ineq_free(bset, ineq, context, row, tab);
2607 	if (bset) {
2608 		ISL_F_SET(bset, ISL_BASIC_SET_NO_IMPLICIT);
2609 		ISL_F_SET(bset, ISL_BASIC_SET_NO_REDUNDANT);
2610 	}
2611 
2612 	isl_basic_set_free(combined);
2613 	return bset;
2614 error:
2615 	free(row);
2616 	isl_mat_free(ineq);
2617 	isl_tab_free(tab);
2618 	isl_basic_set_free(combined);
2619 	isl_basic_set_free(context);
2620 	isl_basic_set_free(bset);
2621 	return NULL;
2622 }
2623 
2624 /* Extract the inequalities of "bset" as an isl_mat.
2625  */
extract_ineq(__isl_keep isl_basic_set * bset)2626 static __isl_give isl_mat *extract_ineq(__isl_keep isl_basic_set *bset)
2627 {
2628 	isl_size total;
2629 	isl_ctx *ctx;
2630 	isl_mat *ineq;
2631 
2632 	total = isl_basic_set_dim(bset, isl_dim_all);
2633 	if (total < 0)
2634 		return NULL;
2635 
2636 	ctx = isl_basic_set_get_ctx(bset);
2637 	ineq = isl_mat_sub_alloc6(ctx, bset->ineq, 0, bset->n_ineq,
2638 				    0, 1 + total);
2639 
2640 	return ineq;
2641 }
2642 
2643 /* Remove all information from "bset" that is redundant in the context
2644  * of "context", for the case where both "bset" and "context" are
2645  * full-dimensional.
2646  */
uset_gist_uncompressed(__isl_take isl_basic_set * bset,__isl_take isl_basic_set * context)2647 static __isl_give isl_basic_set *uset_gist_uncompressed(
2648 	__isl_take isl_basic_set *bset, __isl_take isl_basic_set *context)
2649 {
2650 	isl_mat *ineq;
2651 
2652 	ineq = extract_ineq(bset);
2653 	return uset_gist_full(bset, ineq, context);
2654 }
2655 
2656 /* Replace "bset" by an empty basic set in the same space.
2657  */
replace_by_empty(__isl_take isl_basic_set * bset)2658 static __isl_give isl_basic_set *replace_by_empty(
2659 	__isl_take isl_basic_set *bset)
2660 {
2661 	isl_space *space;
2662 
2663 	space = isl_basic_set_get_space(bset);
2664 	isl_basic_set_free(bset);
2665 	return isl_basic_set_empty(space);
2666 }
2667 
2668 /* Remove all information from "bset" that is redundant in the context
2669  * of "context", for the case where the combined equalities of
2670  * "bset" and "context" allow for a compression that can be obtained
2671  * by preapplication of "T".
2672  * If the compression of "context" is empty, meaning that "bset" and
2673  * "context" do not intersect, then return the empty set.
2674  *
2675  * "bset" itself is not transformed by "T".  Instead, the inequalities
2676  * are extracted from "bset" and those are transformed by "T".
2677  * uset_gist_full then determines which of the transformed inequalities
2678  * are redundant with respect to the transformed "context" and removes
2679  * the corresponding inequalities from "bset".
2680  *
2681  * After preapplying "T" to the inequalities, any common factor is
2682  * removed from the coefficients.  If this results in a tightening
2683  * of the constant term, then the same tightening is applied to
2684  * the corresponding untransformed inequality in "bset".
2685  * That is, if after plugging in T, a constraint f(x) >= 0 is of the form
2686  *
2687  *	g f'(x) + r >= 0
2688  *
2689  * with 0 <= r < g, then it is equivalent to
2690  *
2691  *	f'(x) >= 0
2692  *
2693  * This means that f(x) >= 0 is equivalent to f(x) - r >= 0 in the affine
2694  * subspace compressed by T since the latter would be transformed to
2695  *
2696  *	g f'(x) >= 0
2697  */
uset_gist_compressed(__isl_take isl_basic_set * bset,__isl_take isl_basic_set * context,__isl_take isl_mat * T)2698 static __isl_give isl_basic_set *uset_gist_compressed(
2699 	__isl_take isl_basic_set *bset, __isl_take isl_basic_set *context,
2700 	__isl_take isl_mat *T)
2701 {
2702 	isl_ctx *ctx;
2703 	isl_mat *ineq;
2704 	int i;
2705 	isl_size n_row, n_col;
2706 	isl_int rem;
2707 
2708 	ineq = extract_ineq(bset);
2709 	ineq = isl_mat_product(ineq, isl_mat_copy(T));
2710 	context = isl_basic_set_preimage(context, T);
2711 
2712 	if (!ineq || !context)
2713 		goto error;
2714 	if (isl_basic_set_plain_is_empty(context)) {
2715 		isl_mat_free(ineq);
2716 		isl_basic_set_free(context);
2717 		return replace_by_empty(bset);
2718 	}
2719 
2720 	ctx = isl_mat_get_ctx(ineq);
2721 	n_row = isl_mat_rows(ineq);
2722 	n_col = isl_mat_cols(ineq);
2723 	if (n_row < 0 || n_col < 0)
2724 		goto error;
2725 	isl_int_init(rem);
2726 	for (i = 0; i < n_row; ++i) {
2727 		isl_seq_gcd(ineq->row[i] + 1, n_col - 1, &ctx->normalize_gcd);
2728 		if (isl_int_is_zero(ctx->normalize_gcd))
2729 			continue;
2730 		if (isl_int_is_one(ctx->normalize_gcd))
2731 			continue;
2732 		isl_seq_scale_down(ineq->row[i] + 1, ineq->row[i] + 1,
2733 				    ctx->normalize_gcd, n_col - 1);
2734 		isl_int_fdiv_r(rem, ineq->row[i][0], ctx->normalize_gcd);
2735 		isl_int_fdiv_q(ineq->row[i][0],
2736 				ineq->row[i][0], ctx->normalize_gcd);
2737 		if (isl_int_is_zero(rem))
2738 			continue;
2739 		bset = isl_basic_set_cow(bset);
2740 		if (!bset)
2741 			break;
2742 		isl_int_sub(bset->ineq[i][0], bset->ineq[i][0], rem);
2743 	}
2744 	isl_int_clear(rem);
2745 
2746 	return uset_gist_full(bset, ineq, context);
2747 error:
2748 	isl_mat_free(ineq);
2749 	isl_basic_set_free(context);
2750 	isl_basic_set_free(bset);
2751 	return NULL;
2752 }
2753 
2754 /* Project "bset" onto the variables that are involved in "template".
2755  */
project_onto_involved(__isl_take isl_basic_set * bset,__isl_keep isl_basic_set * template)2756 static __isl_give isl_basic_set *project_onto_involved(
2757 	__isl_take isl_basic_set *bset, __isl_keep isl_basic_set *template)
2758 {
2759 	int i;
2760 	isl_size n;
2761 
2762 	n = isl_basic_set_dim(template, isl_dim_set);
2763 	if (n < 0 || !template)
2764 		return isl_basic_set_free(bset);
2765 
2766 	for (i = 0; i < n; ++i) {
2767 		isl_bool involved;
2768 
2769 		involved = isl_basic_set_involves_dims(template,
2770 							isl_dim_set, i, 1);
2771 		if (involved < 0)
2772 			return isl_basic_set_free(bset);
2773 		if (involved)
2774 			continue;
2775 		bset = isl_basic_set_eliminate_vars(bset, i, 1);
2776 	}
2777 
2778 	return bset;
2779 }
2780 
2781 /* Remove all information from bset that is redundant in the context
2782  * of context.  In particular, equalities that are linear combinations
2783  * of those in context are removed.  Then the inequalities that are
2784  * redundant in the context of the equalities and inequalities of
2785  * context are removed.
2786  *
2787  * First of all, we drop those constraints from "context"
2788  * that are irrelevant for computing the gist of "bset".
2789  * Alternatively, we could factorize the intersection of "context" and "bset".
2790  *
2791  * We first compute the intersection of the integer affine hulls
2792  * of "bset" and "context",
2793  * compute the gist inside this intersection and then reduce
2794  * the constraints with respect to the equalities of the context
2795  * that only involve variables already involved in the input.
2796  * If the intersection of the affine hulls turns out to be empty,
2797  * then return the empty set.
2798  *
2799  * If two constraints are mutually redundant, then uset_gist_full
2800  * will remove the second of those constraints.  We therefore first
2801  * sort the constraints so that constraints not involving existentially
2802  * quantified variables are given precedence over those that do.
2803  * We have to perform this sorting before the variable compression,
2804  * because that may effect the order of the variables.
2805  */
uset_gist(__isl_take isl_basic_set * bset,__isl_take isl_basic_set * context)2806 static __isl_give isl_basic_set *uset_gist(__isl_take isl_basic_set *bset,
2807 	__isl_take isl_basic_set *context)
2808 {
2809 	isl_mat *eq;
2810 	isl_mat *T;
2811 	isl_basic_set *aff;
2812 	isl_basic_set *aff_context;
2813 	isl_size total;
2814 
2815 	total = isl_basic_set_dim(bset, isl_dim_all);
2816 	if (total < 0 || !context)
2817 		goto error;
2818 
2819 	context = drop_irrelevant_constraints(context, bset);
2820 
2821 	bset = isl_basic_set_detect_equalities(bset);
2822 	aff = isl_basic_set_copy(bset);
2823 	aff = isl_basic_set_plain_affine_hull(aff);
2824 	context = isl_basic_set_detect_equalities(context);
2825 	aff_context = isl_basic_set_copy(context);
2826 	aff_context = isl_basic_set_plain_affine_hull(aff_context);
2827 	aff = isl_basic_set_intersect(aff, aff_context);
2828 	if (!aff)
2829 		goto error;
2830 	if (isl_basic_set_plain_is_empty(aff)) {
2831 		isl_basic_set_free(bset);
2832 		isl_basic_set_free(context);
2833 		return aff;
2834 	}
2835 	bset = isl_basic_set_sort_constraints(bset);
2836 	if (aff->n_eq == 0) {
2837 		isl_basic_set_free(aff);
2838 		return uset_gist_uncompressed(bset, context);
2839 	}
2840 	eq = isl_mat_sub_alloc6(bset->ctx, aff->eq, 0, aff->n_eq, 0, 1 + total);
2841 	eq = isl_mat_cow(eq);
2842 	T = isl_mat_variable_compression(eq, NULL);
2843 	isl_basic_set_free(aff);
2844 	if (T && T->n_col == 0) {
2845 		isl_mat_free(T);
2846 		isl_basic_set_free(context);
2847 		return replace_by_empty(bset);
2848 	}
2849 
2850 	aff_context = isl_basic_set_affine_hull(isl_basic_set_copy(context));
2851 	aff_context = project_onto_involved(aff_context, bset);
2852 
2853 	bset = uset_gist_compressed(bset, context, T);
2854 	bset = isl_basic_set_reduce_using_equalities(bset, aff_context);
2855 
2856 	if (bset) {
2857 		ISL_F_SET(bset, ISL_BASIC_SET_NO_IMPLICIT);
2858 		ISL_F_SET(bset, ISL_BASIC_SET_NO_REDUNDANT);
2859 	}
2860 
2861 	return bset;
2862 error:
2863 	isl_basic_set_free(bset);
2864 	isl_basic_set_free(context);
2865 	return NULL;
2866 }
2867 
2868 /* Return the number of equality constraints in "bmap" that involve
2869  * local variables.  This function assumes that Gaussian elimination
2870  * has been applied to the equality constraints.
2871  */
n_div_eq(__isl_keep isl_basic_map * bmap)2872 static int n_div_eq(__isl_keep isl_basic_map *bmap)
2873 {
2874 	int i;
2875 	isl_size total, n_div;
2876 
2877 	if (!bmap)
2878 		return -1;
2879 
2880 	if (bmap->n_eq == 0)
2881 		return 0;
2882 
2883 	total = isl_basic_map_dim(bmap, isl_dim_all);
2884 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
2885 	if (total < 0 || n_div < 0)
2886 		return -1;
2887 	total -= n_div;
2888 
2889 	for (i = 0; i < bmap->n_eq; ++i)
2890 		if (isl_seq_first_non_zero(bmap->eq[i] + 1 + total,
2891 					    n_div) == -1)
2892 			return i;
2893 
2894 	return bmap->n_eq;
2895 }
2896 
2897 /* Construct a basic map in "space" defined by the equality constraints in "eq".
2898  * The constraints are assumed not to involve any local variables.
2899  */
basic_map_from_equalities(__isl_take isl_space * space,__isl_take isl_mat * eq)2900 static __isl_give isl_basic_map *basic_map_from_equalities(
2901 	__isl_take isl_space *space, __isl_take isl_mat *eq)
2902 {
2903 	int i, k;
2904 	isl_size total;
2905 	isl_basic_map *bmap = NULL;
2906 
2907 	total = isl_space_dim(space, isl_dim_all);
2908 	if (total < 0 || !eq)
2909 		goto error;
2910 
2911 	if (1 + total != eq->n_col)
2912 		isl_die(isl_space_get_ctx(space), isl_error_internal,
2913 			"unexpected number of columns", goto error);
2914 
2915 	bmap = isl_basic_map_alloc_space(isl_space_copy(space),
2916 					    0, eq->n_row, 0);
2917 	for (i = 0; i < eq->n_row; ++i) {
2918 		k = isl_basic_map_alloc_equality(bmap);
2919 		if (k < 0)
2920 			goto error;
2921 		isl_seq_cpy(bmap->eq[k], eq->row[i], eq->n_col);
2922 	}
2923 
2924 	isl_space_free(space);
2925 	isl_mat_free(eq);
2926 	return bmap;
2927 error:
2928 	isl_space_free(space);
2929 	isl_mat_free(eq);
2930 	isl_basic_map_free(bmap);
2931 	return NULL;
2932 }
2933 
2934 /* Construct and return a variable compression based on the equality
2935  * constraints in "bmap1" and "bmap2" that do not involve the local variables.
2936  * "n1" is the number of (initial) equality constraints in "bmap1"
2937  * that do involve local variables.
2938  * "n2" is the number of (initial) equality constraints in "bmap2"
2939  * that do involve local variables.
2940  * "total" is the total number of other variables.
2941  * This function assumes that Gaussian elimination
2942  * has been applied to the equality constraints in both "bmap1" and "bmap2"
2943  * such that the equality constraints not involving local variables
2944  * are those that start at "n1" or "n2".
2945  *
2946  * If either of "bmap1" and "bmap2" does not have such equality constraints,
2947  * then simply compute the compression based on the equality constraints
2948  * in the other basic map.
2949  * Otherwise, combine the equality constraints from both into a new
2950  * basic map such that Gaussian elimination can be applied to this combination
2951  * and then construct a variable compression from the resulting
2952  * equality constraints.
2953  */
combined_variable_compression(__isl_keep isl_basic_map * bmap1,int n1,__isl_keep isl_basic_map * bmap2,int n2,int total)2954 static __isl_give isl_mat *combined_variable_compression(
2955 	__isl_keep isl_basic_map *bmap1, int n1,
2956 	__isl_keep isl_basic_map *bmap2, int n2, int total)
2957 {
2958 	isl_ctx *ctx;
2959 	isl_mat *E1, *E2, *V;
2960 	isl_basic_map *bmap;
2961 
2962 	ctx = isl_basic_map_get_ctx(bmap1);
2963 	if (bmap1->n_eq == n1) {
2964 		E2 = isl_mat_sub_alloc6(ctx, bmap2->eq,
2965 					n2, bmap2->n_eq - n2, 0, 1 + total);
2966 		return isl_mat_variable_compression(E2, NULL);
2967 	}
2968 	if (bmap2->n_eq == n2) {
2969 		E1 = isl_mat_sub_alloc6(ctx, bmap1->eq,
2970 					n1, bmap1->n_eq - n1, 0, 1 + total);
2971 		return isl_mat_variable_compression(E1, NULL);
2972 	}
2973 	E1 = isl_mat_sub_alloc6(ctx, bmap1->eq,
2974 				n1, bmap1->n_eq - n1, 0, 1 + total);
2975 	E2 = isl_mat_sub_alloc6(ctx, bmap2->eq,
2976 				n2, bmap2->n_eq - n2, 0, 1 + total);
2977 	E1 = isl_mat_concat(E1, E2);
2978 	bmap = basic_map_from_equalities(isl_basic_map_get_space(bmap1), E1);
2979 	bmap = isl_basic_map_gauss(bmap, NULL);
2980 	if (!bmap)
2981 		return NULL;
2982 	E1 = isl_mat_sub_alloc6(ctx, bmap->eq, 0, bmap->n_eq, 0, 1 + total);
2983 	V = isl_mat_variable_compression(E1, NULL);
2984 	isl_basic_map_free(bmap);
2985 
2986 	return V;
2987 }
2988 
2989 /* Extract the stride constraints from "bmap", compressed
2990  * with respect to both the stride constraints in "context" and
2991  * the remaining equality constraints in both "bmap" and "context".
2992  * "bmap_n_eq" is the number of (initial) stride constraints in "bmap".
2993  * "context_n_eq" is the number of (initial) stride constraints in "context".
2994  *
2995  * Let x be all variables in "bmap" (and "context") other than the local
2996  * variables.  First compute a variable compression
2997  *
2998  *	x = V x'
2999  *
3000  * based on the non-stride equality constraints in "bmap" and "context".
3001  * Consider the stride constraints of "context",
3002  *
3003  *	A(x) + B(y) = 0
3004  *
3005  * with y the local variables and plug in the variable compression,
3006  * resulting in
3007  *
3008  *	A(V x') + B(y) = 0
3009  *
3010  * Use these constraints to compute a parameter compression on x'
3011  *
3012  *	x' = T x''
3013  *
3014  * Now consider the stride constraints of "bmap"
3015  *
3016  *	C(x) + D(y) = 0
3017  *
3018  * and plug in x = V*T x''.
3019  * That is, return A = [C*V*T D].
3020  */
extract_compressed_stride_constraints(__isl_keep isl_basic_map * bmap,int bmap_n_eq,__isl_keep isl_basic_map * context,int context_n_eq)3021 static __isl_give isl_mat *extract_compressed_stride_constraints(
3022 	__isl_keep isl_basic_map *bmap, int bmap_n_eq,
3023 	__isl_keep isl_basic_map *context, int context_n_eq)
3024 {
3025 	isl_size total, n_div;
3026 	isl_ctx *ctx;
3027 	isl_mat *A, *B, *T, *V;
3028 
3029 	total = isl_basic_map_dim(context, isl_dim_all);
3030 	n_div = isl_basic_map_dim(context, isl_dim_div);
3031 	if (total < 0 || n_div < 0)
3032 		return NULL;
3033 	total -= n_div;
3034 
3035 	ctx = isl_basic_map_get_ctx(bmap);
3036 
3037 	V = combined_variable_compression(bmap, bmap_n_eq,
3038 						context, context_n_eq, total);
3039 
3040 	A = isl_mat_sub_alloc6(ctx, context->eq, 0, context_n_eq, 0, 1 + total);
3041 	B = isl_mat_sub_alloc6(ctx, context->eq,
3042 				0, context_n_eq, 1 + total, n_div);
3043 	A = isl_mat_product(A, isl_mat_copy(V));
3044 	T = isl_mat_parameter_compression_ext(A, B);
3045 	T = isl_mat_product(V, T);
3046 
3047 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
3048 	if (n_div < 0)
3049 		T = isl_mat_free(T);
3050 	else
3051 		T = isl_mat_diagonal(T, isl_mat_identity(ctx, n_div));
3052 
3053 	A = isl_mat_sub_alloc6(ctx, bmap->eq,
3054 				0, bmap_n_eq, 0, 1 + total + n_div);
3055 	A = isl_mat_product(A, T);
3056 
3057 	return A;
3058 }
3059 
3060 /* Remove the prime factors from *g that have an exponent that
3061  * is strictly smaller than the exponent in "c".
3062  * All exponents in *g are known to be smaller than or equal
3063  * to those in "c".
3064  *
3065  * That is, if *g is equal to
3066  *
3067  *	p_1^{e_1} p_2^{e_2} ... p_n^{e_n}
3068  *
3069  * and "c" is equal to
3070  *
3071  *	p_1^{f_1} p_2^{f_2} ... p_n^{f_n}
3072  *
3073  * then update *g to
3074  *
3075  *	p_1^{e_1 * (e_1 = f_1)} p_2^{e_2 * (e_2 = f_2)} ...
3076  *		p_n^{e_n * (e_n = f_n)}
3077  *
3078  * If e_i = f_i, then c / *g does not have any p_i factors and therefore
3079  * neither does the gcd of *g and c / *g.
3080  * If e_i < f_i, then the gcd of *g and c / *g has a positive
3081  * power min(e_i, s_i) of p_i with s_i = f_i - e_i among its factors.
3082  * Dividing *g by this gcd therefore strictly reduces the exponent
3083  * of the prime factors that need to be removed, while leaving the
3084  * other prime factors untouched.
3085  * Repeating this process until gcd(*g, c / *g) = 1 therefore
3086  * removes all undesired factors, without removing any others.
3087  */
remove_incomplete_powers(isl_int * g,isl_int c)3088 static void remove_incomplete_powers(isl_int *g, isl_int c)
3089 {
3090 	isl_int t;
3091 
3092 	isl_int_init(t);
3093 	for (;;) {
3094 		isl_int_divexact(t, c, *g);
3095 		isl_int_gcd(t, t, *g);
3096 		if (isl_int_is_one(t))
3097 			break;
3098 		isl_int_divexact(*g, *g, t);
3099 	}
3100 	isl_int_clear(t);
3101 }
3102 
3103 /* Reduce the "n" stride constraints in "bmap" based on a copy "A"
3104  * of the same stride constraints in a compressed space that exploits
3105  * all equalities in the context and the other equalities in "bmap".
3106  *
3107  * If the stride constraints of "bmap" are of the form
3108  *
3109  *	C(x) + D(y) = 0
3110  *
3111  * then A is of the form
3112  *
3113  *	B(x') + D(y) = 0
3114  *
3115  * If any of these constraints involves only a single local variable y,
3116  * then the constraint appears as
3117  *
3118  *	f(x) + m y_i = 0
3119  *
3120  * in "bmap" and as
3121  *
3122  *	h(x') + m y_i = 0
3123  *
3124  * in "A".
3125  *
3126  * Let g be the gcd of m and the coefficients of h.
3127  * Then, in particular, g is a divisor of the coefficients of h and
3128  *
3129  *	f(x) = h(x')
3130  *
3131  * is known to be a multiple of g.
3132  * If some prime factor in m appears with the same exponent in g,
3133  * then it can be removed from m because f(x) is already known
3134  * to be a multiple of g and therefore in particular of this power
3135  * of the prime factors.
3136  * Prime factors that appear with a smaller exponent in g cannot
3137  * be removed from m.
3138  * Let g' be the divisor of g containing all prime factors that
3139  * appear with the same exponent in m and g, then
3140  *
3141  *	f(x) + m y_i = 0
3142  *
3143  * can be replaced by
3144  *
3145  *	f(x) + m/g' y_i' = 0
3146  *
3147  * Note that (if g' != 1) this changes the explicit representation
3148  * of y_i to that of y_i', so the integer division at position i
3149  * is marked unknown and later recomputed by a call to
3150  * isl_basic_map_gauss.
3151  */
reduce_stride_constraints(__isl_take isl_basic_map * bmap,int n,__isl_keep isl_mat * A)3152 static __isl_give isl_basic_map *reduce_stride_constraints(
3153 	__isl_take isl_basic_map *bmap, int n, __isl_keep isl_mat *A)
3154 {
3155 	int i;
3156 	isl_size total, n_div;
3157 	int any = 0;
3158 	isl_int gcd;
3159 
3160 	total = isl_basic_map_dim(bmap, isl_dim_all);
3161 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
3162 	if (total < 0 || n_div < 0 || !A)
3163 		return isl_basic_map_free(bmap);
3164 	total -= n_div;
3165 
3166 	isl_int_init(gcd);
3167 	for (i = 0; i < n; ++i) {
3168 		int div;
3169 
3170 		div = isl_seq_first_non_zero(bmap->eq[i] + 1 + total, n_div);
3171 		if (div < 0)
3172 			isl_die(isl_basic_map_get_ctx(bmap), isl_error_internal,
3173 				"equality constraints modified unexpectedly",
3174 				goto error);
3175 		if (isl_seq_first_non_zero(bmap->eq[i] + 1 + total + div + 1,
3176 						n_div - div - 1) != -1)
3177 			continue;
3178 		if (isl_mat_row_gcd(A, i, &gcd) < 0)
3179 			goto error;
3180 		if (isl_int_is_one(gcd))
3181 			continue;
3182 		remove_incomplete_powers(&gcd, bmap->eq[i][1 + total + div]);
3183 		if (isl_int_is_one(gcd))
3184 			continue;
3185 		isl_int_divexact(bmap->eq[i][1 + total + div],
3186 				bmap->eq[i][1 + total + div], gcd);
3187 		bmap = isl_basic_map_mark_div_unknown(bmap, div);
3188 		if (!bmap)
3189 			goto error;
3190 		any = 1;
3191 	}
3192 	isl_int_clear(gcd);
3193 
3194 	if (any)
3195 		bmap = isl_basic_map_gauss(bmap, NULL);
3196 
3197 	return bmap;
3198 error:
3199 	isl_int_clear(gcd);
3200 	isl_basic_map_free(bmap);
3201 	return NULL;
3202 }
3203 
3204 /* Simplify the stride constraints in "bmap" based on
3205  * the remaining equality constraints in "bmap" and all equality
3206  * constraints in "context".
3207  * Only do this if both "bmap" and "context" have stride constraints.
3208  *
3209  * First extract a copy of the stride constraints in "bmap" in a compressed
3210  * space exploiting all the other equality constraints and then
3211  * use this compressed copy to simplify the original stride constraints.
3212  */
gist_strides(__isl_take isl_basic_map * bmap,__isl_keep isl_basic_map * context)3213 static __isl_give isl_basic_map *gist_strides(__isl_take isl_basic_map *bmap,
3214 	__isl_keep isl_basic_map *context)
3215 {
3216 	int bmap_n_eq, context_n_eq;
3217 	isl_mat *A;
3218 
3219 	if (!bmap || !context)
3220 		return isl_basic_map_free(bmap);
3221 
3222 	bmap_n_eq = n_div_eq(bmap);
3223 	context_n_eq = n_div_eq(context);
3224 
3225 	if (bmap_n_eq < 0 || context_n_eq < 0)
3226 		return isl_basic_map_free(bmap);
3227 	if (bmap_n_eq == 0 || context_n_eq == 0)
3228 		return bmap;
3229 
3230 	A = extract_compressed_stride_constraints(bmap, bmap_n_eq,
3231 						    context, context_n_eq);
3232 	bmap = reduce_stride_constraints(bmap, bmap_n_eq, A);
3233 
3234 	isl_mat_free(A);
3235 
3236 	return bmap;
3237 }
3238 
3239 /* Return a basic map that has the same intersection with "context" as "bmap"
3240  * and that is as "simple" as possible.
3241  *
3242  * The core computation is performed on the pure constraints.
3243  * When we add back the meaning of the integer divisions, we need
3244  * to (re)introduce the div constraints.  If we happen to have
3245  * discovered that some of these integer divisions are equal to
3246  * some affine combination of other variables, then these div
3247  * constraints may end up getting simplified in terms of the equalities,
3248  * resulting in extra inequalities on the other variables that
3249  * may have been removed already or that may not even have been
3250  * part of the input.  We try and remove those constraints of
3251  * this form that are most obviously redundant with respect to
3252  * the context.  We also remove those div constraints that are
3253  * redundant with respect to the other constraints in the result.
3254  *
3255  * The stride constraints among the equality constraints in "bmap" are
3256  * also simplified with respecting to the other equality constraints
3257  * in "bmap" and with respect to all equality constraints in "context".
3258  */
isl_basic_map_gist(__isl_take isl_basic_map * bmap,__isl_take isl_basic_map * context)3259 __isl_give isl_basic_map *isl_basic_map_gist(__isl_take isl_basic_map *bmap,
3260 	__isl_take isl_basic_map *context)
3261 {
3262 	isl_basic_set *bset, *eq;
3263 	isl_basic_map *eq_bmap;
3264 	isl_size total, n_div, n_div_bmap;
3265 	unsigned extra, n_eq, n_ineq;
3266 
3267 	if (!bmap || !context)
3268 		goto error;
3269 
3270 	if (isl_basic_map_plain_is_universe(bmap)) {
3271 		isl_basic_map_free(context);
3272 		return bmap;
3273 	}
3274 	if (isl_basic_map_plain_is_empty(context)) {
3275 		isl_space *space = isl_basic_map_get_space(bmap);
3276 		isl_basic_map_free(bmap);
3277 		isl_basic_map_free(context);
3278 		return isl_basic_map_universe(space);
3279 	}
3280 	if (isl_basic_map_plain_is_empty(bmap)) {
3281 		isl_basic_map_free(context);
3282 		return bmap;
3283 	}
3284 
3285 	bmap = isl_basic_map_remove_redundancies(bmap);
3286 	context = isl_basic_map_remove_redundancies(context);
3287 	context = isl_basic_map_align_divs(context, bmap);
3288 
3289 	n_div = isl_basic_map_dim(context, isl_dim_div);
3290 	total = isl_basic_map_dim(bmap, isl_dim_all);
3291 	n_div_bmap = isl_basic_map_dim(bmap, isl_dim_div);
3292 	if (n_div < 0 || total < 0 || n_div_bmap < 0)
3293 		goto error;
3294 	extra = n_div - n_div_bmap;
3295 
3296 	bset = isl_basic_map_underlying_set(isl_basic_map_copy(bmap));
3297 	bset = isl_basic_set_add_dims(bset, isl_dim_set, extra);
3298 	bset = uset_gist(bset,
3299 		    isl_basic_map_underlying_set(isl_basic_map_copy(context)));
3300 	bset = isl_basic_set_project_out(bset, isl_dim_set, total, extra);
3301 
3302 	if (!bset || bset->n_eq == 0 || n_div == 0 ||
3303 	    isl_basic_set_plain_is_empty(bset)) {
3304 		isl_basic_map_free(context);
3305 		return isl_basic_map_overlying_set(bset, bmap);
3306 	}
3307 
3308 	n_eq = bset->n_eq;
3309 	n_ineq = bset->n_ineq;
3310 	eq = isl_basic_set_copy(bset);
3311 	eq = isl_basic_set_cow(eq);
3312 	eq = isl_basic_set_free_inequality(eq, n_ineq);
3313 	bset = isl_basic_set_free_equality(bset, n_eq);
3314 
3315 	eq_bmap = isl_basic_map_overlying_set(eq, isl_basic_map_copy(bmap));
3316 	eq_bmap = gist_strides(eq_bmap, context);
3317 	eq_bmap = isl_basic_map_remove_shifted_constraints(eq_bmap, context);
3318 	bmap = isl_basic_map_overlying_set(bset, bmap);
3319 	bmap = isl_basic_map_intersect(bmap, eq_bmap);
3320 	bmap = isl_basic_map_remove_redundancies(bmap);
3321 
3322 	return bmap;
3323 error:
3324 	isl_basic_map_free(bmap);
3325 	isl_basic_map_free(context);
3326 	return NULL;
3327 }
3328 
3329 /*
3330  * Assumes context has no implicit divs.
3331  */
isl_map_gist_basic_map(__isl_take isl_map * map,__isl_take isl_basic_map * context)3332 __isl_give isl_map *isl_map_gist_basic_map(__isl_take isl_map *map,
3333 	__isl_take isl_basic_map *context)
3334 {
3335 	int i;
3336 
3337 	if (!map || !context)
3338 		goto error;
3339 
3340 	if (isl_basic_map_plain_is_empty(context)) {
3341 		isl_space *space = isl_map_get_space(map);
3342 		isl_map_free(map);
3343 		isl_basic_map_free(context);
3344 		return isl_map_universe(space);
3345 	}
3346 
3347 	context = isl_basic_map_remove_redundancies(context);
3348 	map = isl_map_cow(map);
3349 	if (isl_map_basic_map_check_equal_space(map, context) < 0)
3350 		goto error;
3351 	map = isl_map_compute_divs(map);
3352 	if (!map)
3353 		goto error;
3354 	for (i = map->n - 1; i >= 0; --i) {
3355 		map->p[i] = isl_basic_map_gist(map->p[i],
3356 						isl_basic_map_copy(context));
3357 		if (!map->p[i])
3358 			goto error;
3359 		if (isl_basic_map_plain_is_empty(map->p[i])) {
3360 			isl_basic_map_free(map->p[i]);
3361 			if (i != map->n - 1)
3362 				map->p[i] = map->p[map->n - 1];
3363 			map->n--;
3364 		}
3365 	}
3366 	isl_basic_map_free(context);
3367 	ISL_F_CLR(map, ISL_MAP_NORMALIZED);
3368 	return map;
3369 error:
3370 	isl_map_free(map);
3371 	isl_basic_map_free(context);
3372 	return NULL;
3373 }
3374 
3375 /* Drop all inequalities from "bmap" that also appear in "context".
3376  * "context" is assumed to have only known local variables and
3377  * the initial local variables of "bmap" are assumed to be the same
3378  * as those of "context".
3379  * The constraints of both "bmap" and "context" are assumed
3380  * to have been sorted using isl_basic_map_sort_constraints.
3381  *
3382  * Run through the inequality constraints of "bmap" and "context"
3383  * in sorted order.
3384  * If a constraint of "bmap" involves variables not in "context",
3385  * then it cannot appear in "context".
3386  * If a matching constraint is found, it is removed from "bmap".
3387  */
drop_inequalities(__isl_take isl_basic_map * bmap,__isl_keep isl_basic_map * context)3388 static __isl_give isl_basic_map *drop_inequalities(
3389 	__isl_take isl_basic_map *bmap, __isl_keep isl_basic_map *context)
3390 {
3391 	int i1, i2;
3392 	isl_size total, bmap_total;
3393 	unsigned extra;
3394 
3395 	total = isl_basic_map_dim(context, isl_dim_all);
3396 	bmap_total = isl_basic_map_dim(bmap, isl_dim_all);
3397 	if (total < 0 || bmap_total < 0)
3398 		return isl_basic_map_free(bmap);
3399 
3400 	extra = bmap_total - total;
3401 
3402 	i1 = bmap->n_ineq - 1;
3403 	i2 = context->n_ineq - 1;
3404 	while (bmap && i1 >= 0 && i2 >= 0) {
3405 		int cmp;
3406 
3407 		if (isl_seq_first_non_zero(bmap->ineq[i1] + 1 + total,
3408 					    extra) != -1) {
3409 			--i1;
3410 			continue;
3411 		}
3412 		cmp = isl_basic_map_constraint_cmp(context, bmap->ineq[i1],
3413 							context->ineq[i2]);
3414 		if (cmp < 0) {
3415 			--i2;
3416 			continue;
3417 		}
3418 		if (cmp > 0) {
3419 			--i1;
3420 			continue;
3421 		}
3422 		if (isl_int_eq(bmap->ineq[i1][0], context->ineq[i2][0])) {
3423 			bmap = isl_basic_map_cow(bmap);
3424 			if (isl_basic_map_drop_inequality(bmap, i1) < 0)
3425 				bmap = isl_basic_map_free(bmap);
3426 		}
3427 		--i1;
3428 		--i2;
3429 	}
3430 
3431 	return bmap;
3432 }
3433 
3434 /* Drop all equalities from "bmap" that also appear in "context".
3435  * "context" is assumed to have only known local variables and
3436  * the initial local variables of "bmap" are assumed to be the same
3437  * as those of "context".
3438  *
3439  * Run through the equality constraints of "bmap" and "context"
3440  * in sorted order.
3441  * If a constraint of "bmap" involves variables not in "context",
3442  * then it cannot appear in "context".
3443  * If a matching constraint is found, it is removed from "bmap".
3444  */
drop_equalities(__isl_take isl_basic_map * bmap,__isl_keep isl_basic_map * context)3445 static __isl_give isl_basic_map *drop_equalities(
3446 	__isl_take isl_basic_map *bmap, __isl_keep isl_basic_map *context)
3447 {
3448 	int i1, i2;
3449 	isl_size total, bmap_total;
3450 	unsigned extra;
3451 
3452 	total = isl_basic_map_dim(context, isl_dim_all);
3453 	bmap_total = isl_basic_map_dim(bmap, isl_dim_all);
3454 	if (total < 0 || bmap_total < 0)
3455 		return isl_basic_map_free(bmap);
3456 
3457 	extra = bmap_total - total;
3458 
3459 	i1 = bmap->n_eq - 1;
3460 	i2 = context->n_eq - 1;
3461 
3462 	while (bmap && i1 >= 0 && i2 >= 0) {
3463 		int last1, last2;
3464 
3465 		if (isl_seq_first_non_zero(bmap->eq[i1] + 1 + total,
3466 					    extra) != -1)
3467 			break;
3468 		last1 = isl_seq_last_non_zero(bmap->eq[i1] + 1, total);
3469 		last2 = isl_seq_last_non_zero(context->eq[i2] + 1, total);
3470 		if (last1 > last2) {
3471 			--i2;
3472 			continue;
3473 		}
3474 		if (last1 < last2) {
3475 			--i1;
3476 			continue;
3477 		}
3478 		if (isl_seq_eq(bmap->eq[i1], context->eq[i2], 1 + total)) {
3479 			bmap = isl_basic_map_cow(bmap);
3480 			if (isl_basic_map_drop_equality(bmap, i1) < 0)
3481 				bmap = isl_basic_map_free(bmap);
3482 		}
3483 		--i1;
3484 		--i2;
3485 	}
3486 
3487 	return bmap;
3488 }
3489 
3490 /* Remove the constraints in "context" from "bmap".
3491  * "context" is assumed to have explicit representations
3492  * for all local variables.
3493  *
3494  * First align the divs of "bmap" to those of "context" and
3495  * sort the constraints.  Then drop all constraints from "bmap"
3496  * that appear in "context".
3497  */
isl_basic_map_plain_gist(__isl_take isl_basic_map * bmap,__isl_take isl_basic_map * context)3498 __isl_give isl_basic_map *isl_basic_map_plain_gist(
3499 	__isl_take isl_basic_map *bmap, __isl_take isl_basic_map *context)
3500 {
3501 	isl_bool done, known;
3502 
3503 	done = isl_basic_map_plain_is_universe(context);
3504 	if (done == isl_bool_false)
3505 		done = isl_basic_map_plain_is_universe(bmap);
3506 	if (done == isl_bool_false)
3507 		done = isl_basic_map_plain_is_empty(context);
3508 	if (done == isl_bool_false)
3509 		done = isl_basic_map_plain_is_empty(bmap);
3510 	if (done < 0)
3511 		goto error;
3512 	if (done) {
3513 		isl_basic_map_free(context);
3514 		return bmap;
3515 	}
3516 	known = isl_basic_map_divs_known(context);
3517 	if (known < 0)
3518 		goto error;
3519 	if (!known)
3520 		isl_die(isl_basic_map_get_ctx(bmap), isl_error_invalid,
3521 			"context has unknown divs", goto error);
3522 
3523 	bmap = isl_basic_map_align_divs(bmap, context);
3524 	bmap = isl_basic_map_gauss(bmap, NULL);
3525 	bmap = isl_basic_map_sort_constraints(bmap);
3526 	context = isl_basic_map_sort_constraints(context);
3527 
3528 	bmap = drop_inequalities(bmap, context);
3529 	bmap = drop_equalities(bmap, context);
3530 
3531 	isl_basic_map_free(context);
3532 	bmap = isl_basic_map_finalize(bmap);
3533 	return bmap;
3534 error:
3535 	isl_basic_map_free(bmap);
3536 	isl_basic_map_free(context);
3537 	return NULL;
3538 }
3539 
3540 /* Replace "map" by the disjunct at position "pos" and free "context".
3541  */
replace_by_disjunct(__isl_take isl_map * map,int pos,__isl_take isl_basic_map * context)3542 static __isl_give isl_map *replace_by_disjunct(__isl_take isl_map *map,
3543 	int pos, __isl_take isl_basic_map *context)
3544 {
3545 	isl_basic_map *bmap;
3546 
3547 	bmap = isl_basic_map_copy(map->p[pos]);
3548 	isl_map_free(map);
3549 	isl_basic_map_free(context);
3550 	return isl_map_from_basic_map(bmap);
3551 }
3552 
3553 /* Remove the constraints in "context" from "map".
3554  * If any of the disjuncts in the result turns out to be the universe,
3555  * then return this universe.
3556  * "context" is assumed to have explicit representations
3557  * for all local variables.
3558  */
isl_map_plain_gist_basic_map(__isl_take isl_map * map,__isl_take isl_basic_map * context)3559 __isl_give isl_map *isl_map_plain_gist_basic_map(__isl_take isl_map *map,
3560 	__isl_take isl_basic_map *context)
3561 {
3562 	int i;
3563 	isl_bool univ, known;
3564 
3565 	univ = isl_basic_map_plain_is_universe(context);
3566 	if (univ < 0)
3567 		goto error;
3568 	if (univ) {
3569 		isl_basic_map_free(context);
3570 		return map;
3571 	}
3572 	known = isl_basic_map_divs_known(context);
3573 	if (known < 0)
3574 		goto error;
3575 	if (!known)
3576 		isl_die(isl_map_get_ctx(map), isl_error_invalid,
3577 			"context has unknown divs", goto error);
3578 
3579 	map = isl_map_cow(map);
3580 	if (!map)
3581 		goto error;
3582 	for (i = 0; i < map->n; ++i) {
3583 		map->p[i] = isl_basic_map_plain_gist(map->p[i],
3584 						isl_basic_map_copy(context));
3585 		univ = isl_basic_map_plain_is_universe(map->p[i]);
3586 		if (univ < 0)
3587 			goto error;
3588 		if (univ && map->n > 1)
3589 			return replace_by_disjunct(map, i, context);
3590 	}
3591 
3592 	isl_basic_map_free(context);
3593 	ISL_F_CLR(map, ISL_MAP_NORMALIZED);
3594 	if (map->n > 1)
3595 		ISL_F_CLR(map, ISL_MAP_DISJOINT);
3596 	return map;
3597 error:
3598 	isl_map_free(map);
3599 	isl_basic_map_free(context);
3600 	return NULL;
3601 }
3602 
3603 /* Remove the constraints in "context" from "set".
3604  * If any of the disjuncts in the result turns out to be the universe,
3605  * then return this universe.
3606  * "context" is assumed to have explicit representations
3607  * for all local variables.
3608  */
isl_set_plain_gist_basic_set(__isl_take isl_set * set,__isl_take isl_basic_set * context)3609 __isl_give isl_set *isl_set_plain_gist_basic_set(__isl_take isl_set *set,
3610 	__isl_take isl_basic_set *context)
3611 {
3612 	return set_from_map(isl_map_plain_gist_basic_map(set_to_map(set),
3613 							bset_to_bmap(context)));
3614 }
3615 
3616 /* Remove the constraints in "context" from "map".
3617  * If any of the disjuncts in the result turns out to be the universe,
3618  * then return this universe.
3619  * "context" is assumed to consist of a single disjunct and
3620  * to have explicit representations for all local variables.
3621  */
isl_map_plain_gist(__isl_take isl_map * map,__isl_take isl_map * context)3622 __isl_give isl_map *isl_map_plain_gist(__isl_take isl_map *map,
3623 	__isl_take isl_map *context)
3624 {
3625 	isl_basic_map *hull;
3626 
3627 	hull = isl_map_unshifted_simple_hull(context);
3628 	return isl_map_plain_gist_basic_map(map, hull);
3629 }
3630 
3631 /* Replace "map" by a universe map in the same space and free "drop".
3632  */
replace_by_universe(__isl_take isl_map * map,__isl_take isl_map * drop)3633 static __isl_give isl_map *replace_by_universe(__isl_take isl_map *map,
3634 	__isl_take isl_map *drop)
3635 {
3636 	isl_map *res;
3637 
3638 	res = isl_map_universe(isl_map_get_space(map));
3639 	isl_map_free(map);
3640 	isl_map_free(drop);
3641 	return res;
3642 }
3643 
3644 /* Return a map that has the same intersection with "context" as "map"
3645  * and that is as "simple" as possible.
3646  *
3647  * If "map" is already the universe, then we cannot make it any simpler.
3648  * Similarly, if "context" is the universe, then we cannot exploit it
3649  * to simplify "map"
3650  * If "map" and "context" are identical to each other, then we can
3651  * return the corresponding universe.
3652  *
3653  * If either "map" or "context" consists of multiple disjuncts,
3654  * then check if "context" happens to be a subset of "map",
3655  * in which case all constraints can be removed.
3656  * In case of multiple disjuncts, the standard procedure
3657  * may not be able to detect that all constraints can be removed.
3658  *
3659  * If none of these cases apply, we have to work a bit harder.
3660  * During this computation, we make use of a single disjunct context,
3661  * so if the original context consists of more than one disjunct
3662  * then we need to approximate the context by a single disjunct set.
3663  * Simply taking the simple hull may drop constraints that are
3664  * only implicitly available in each disjunct.  We therefore also
3665  * look for constraints among those defining "map" that are valid
3666  * for the context.  These can then be used to simplify away
3667  * the corresponding constraints in "map".
3668  */
isl_map_gist(__isl_take isl_map * map,__isl_take isl_map * context)3669 __isl_give isl_map *isl_map_gist(__isl_take isl_map *map,
3670 	__isl_take isl_map *context)
3671 {
3672 	int equal;
3673 	int is_universe;
3674 	isl_size n_disjunct_map, n_disjunct_context;
3675 	isl_bool subset;
3676 	isl_basic_map *hull;
3677 
3678 	is_universe = isl_map_plain_is_universe(map);
3679 	if (is_universe >= 0 && !is_universe)
3680 		is_universe = isl_map_plain_is_universe(context);
3681 	if (is_universe < 0)
3682 		goto error;
3683 	if (is_universe) {
3684 		isl_map_free(context);
3685 		return map;
3686 	}
3687 
3688 	isl_map_align_params_bin(&map, &context);
3689 	equal = isl_map_plain_is_equal(map, context);
3690 	if (equal < 0)
3691 		goto error;
3692 	if (equal)
3693 		return replace_by_universe(map, context);
3694 
3695 	n_disjunct_map = isl_map_n_basic_map(map);
3696 	n_disjunct_context = isl_map_n_basic_map(context);
3697 	if (n_disjunct_map < 0 || n_disjunct_context < 0)
3698 		goto error;
3699 	if (n_disjunct_map != 1 || n_disjunct_context != 1) {
3700 		subset = isl_map_is_subset(context, map);
3701 		if (subset < 0)
3702 			goto error;
3703 		if (subset)
3704 			return replace_by_universe(map, context);
3705 	}
3706 
3707 	context = isl_map_compute_divs(context);
3708 	if (!context)
3709 		goto error;
3710 	if (n_disjunct_context == 1) {
3711 		hull = isl_map_simple_hull(context);
3712 	} else {
3713 		isl_ctx *ctx;
3714 		isl_map_list *list;
3715 
3716 		ctx = isl_map_get_ctx(map);
3717 		list = isl_map_list_alloc(ctx, 2);
3718 		list = isl_map_list_add(list, isl_map_copy(context));
3719 		list = isl_map_list_add(list, isl_map_copy(map));
3720 		hull = isl_map_unshifted_simple_hull_from_map_list(context,
3721 								    list);
3722 	}
3723 	return isl_map_gist_basic_map(map, hull);
3724 error:
3725 	isl_map_free(map);
3726 	isl_map_free(context);
3727 	return NULL;
3728 }
3729 
isl_basic_set_gist(__isl_take isl_basic_set * bset,__isl_take isl_basic_set * context)3730 __isl_give isl_basic_set *isl_basic_set_gist(__isl_take isl_basic_set *bset,
3731 	__isl_take isl_basic_set *context)
3732 {
3733 	return bset_from_bmap(isl_basic_map_gist(bset_to_bmap(bset),
3734 						bset_to_bmap(context)));
3735 }
3736 
isl_set_gist_basic_set(__isl_take isl_set * set,__isl_take isl_basic_set * context)3737 __isl_give isl_set *isl_set_gist_basic_set(__isl_take isl_set *set,
3738 	__isl_take isl_basic_set *context)
3739 {
3740 	return set_from_map(isl_map_gist_basic_map(set_to_map(set),
3741 					bset_to_bmap(context)));
3742 }
3743 
isl_set_gist_params_basic_set(__isl_take isl_set * set,__isl_take isl_basic_set * context)3744 __isl_give isl_set *isl_set_gist_params_basic_set(__isl_take isl_set *set,
3745 	__isl_take isl_basic_set *context)
3746 {
3747 	isl_space *space = isl_set_get_space(set);
3748 	isl_basic_set *dom_context = isl_basic_set_universe(space);
3749 	dom_context = isl_basic_set_intersect_params(dom_context, context);
3750 	return isl_set_gist_basic_set(set, dom_context);
3751 }
3752 
isl_set_gist(__isl_take isl_set * set,__isl_take isl_set * context)3753 __isl_give isl_set *isl_set_gist(__isl_take isl_set *set,
3754 	__isl_take isl_set *context)
3755 {
3756 	return set_from_map(isl_map_gist(set_to_map(set), set_to_map(context)));
3757 }
3758 
3759 /* Compute the gist of "bmap" with respect to the constraints "context"
3760  * on the domain.
3761  */
isl_basic_map_gist_domain(__isl_take isl_basic_map * bmap,__isl_take isl_basic_set * context)3762 __isl_give isl_basic_map *isl_basic_map_gist_domain(
3763 	__isl_take isl_basic_map *bmap, __isl_take isl_basic_set *context)
3764 {
3765 	isl_space *space = isl_basic_map_get_space(bmap);
3766 	isl_basic_map *bmap_context = isl_basic_map_universe(space);
3767 
3768 	bmap_context = isl_basic_map_intersect_domain(bmap_context, context);
3769 	return isl_basic_map_gist(bmap, bmap_context);
3770 }
3771 
isl_map_gist_domain(__isl_take isl_map * map,__isl_take isl_set * context)3772 __isl_give isl_map *isl_map_gist_domain(__isl_take isl_map *map,
3773 	__isl_take isl_set *context)
3774 {
3775 	isl_map *map_context = isl_map_universe(isl_map_get_space(map));
3776 	map_context = isl_map_intersect_domain(map_context, context);
3777 	return isl_map_gist(map, map_context);
3778 }
3779 
isl_map_gist_range(__isl_take isl_map * map,__isl_take isl_set * context)3780 __isl_give isl_map *isl_map_gist_range(__isl_take isl_map *map,
3781 	__isl_take isl_set *context)
3782 {
3783 	isl_map *map_context = isl_map_universe(isl_map_get_space(map));
3784 	map_context = isl_map_intersect_range(map_context, context);
3785 	return isl_map_gist(map, map_context);
3786 }
3787 
isl_map_gist_params(__isl_take isl_map * map,__isl_take isl_set * context)3788 __isl_give isl_map *isl_map_gist_params(__isl_take isl_map *map,
3789 	__isl_take isl_set *context)
3790 {
3791 	isl_map *map_context = isl_map_universe(isl_map_get_space(map));
3792 	map_context = isl_map_intersect_params(map_context, context);
3793 	return isl_map_gist(map, map_context);
3794 }
3795 
isl_set_gist_params(__isl_take isl_set * set,__isl_take isl_set * context)3796 __isl_give isl_set *isl_set_gist_params(__isl_take isl_set *set,
3797 	__isl_take isl_set *context)
3798 {
3799 	return isl_map_gist_params(set, context);
3800 }
3801 
3802 /* Quick check to see if two basic maps are disjoint.
3803  * In particular, we reduce the equalities and inequalities of
3804  * one basic map in the context of the equalities of the other
3805  * basic map and check if we get a contradiction.
3806  */
isl_basic_map_plain_is_disjoint(__isl_keep isl_basic_map * bmap1,__isl_keep isl_basic_map * bmap2)3807 isl_bool isl_basic_map_plain_is_disjoint(__isl_keep isl_basic_map *bmap1,
3808 	__isl_keep isl_basic_map *bmap2)
3809 {
3810 	struct isl_vec *v = NULL;
3811 	int *elim = NULL;
3812 	isl_size total;
3813 	int i;
3814 
3815 	if (isl_basic_map_check_equal_space(bmap1, bmap2) < 0)
3816 		return isl_bool_error;
3817 	if (bmap1->n_div || bmap2->n_div)
3818 		return isl_bool_false;
3819 	if (!bmap1->n_eq && !bmap2->n_eq)
3820 		return isl_bool_false;
3821 
3822 	total = isl_space_dim(bmap1->dim, isl_dim_all);
3823 	if (total < 0)
3824 		return isl_bool_error;
3825 	if (total == 0)
3826 		return isl_bool_false;
3827 	v = isl_vec_alloc(bmap1->ctx, 1 + total);
3828 	if (!v)
3829 		goto error;
3830 	elim = isl_alloc_array(bmap1->ctx, int, total);
3831 	if (!elim)
3832 		goto error;
3833 	compute_elimination_index(bmap1, elim, total);
3834 	for (i = 0; i < bmap2->n_eq; ++i) {
3835 		int reduced;
3836 		reduced = reduced_using_equalities(v->block.data, bmap2->eq[i],
3837 							bmap1, elim, total);
3838 		if (reduced && !isl_int_is_zero(v->block.data[0]) &&
3839 		    isl_seq_first_non_zero(v->block.data + 1, total) == -1)
3840 			goto disjoint;
3841 	}
3842 	for (i = 0; i < bmap2->n_ineq; ++i) {
3843 		int reduced;
3844 		reduced = reduced_using_equalities(v->block.data,
3845 					bmap2->ineq[i], bmap1, elim, total);
3846 		if (reduced && isl_int_is_neg(v->block.data[0]) &&
3847 		    isl_seq_first_non_zero(v->block.data + 1, total) == -1)
3848 			goto disjoint;
3849 	}
3850 	compute_elimination_index(bmap2, elim, total);
3851 	for (i = 0; i < bmap1->n_ineq; ++i) {
3852 		int reduced;
3853 		reduced = reduced_using_equalities(v->block.data,
3854 					bmap1->ineq[i], bmap2, elim, total);
3855 		if (reduced && isl_int_is_neg(v->block.data[0]) &&
3856 		    isl_seq_first_non_zero(v->block.data + 1, total) == -1)
3857 			goto disjoint;
3858 	}
3859 	isl_vec_free(v);
3860 	free(elim);
3861 	return isl_bool_false;
3862 disjoint:
3863 	isl_vec_free(v);
3864 	free(elim);
3865 	return isl_bool_true;
3866 error:
3867 	isl_vec_free(v);
3868 	free(elim);
3869 	return isl_bool_error;
3870 }
3871 
isl_basic_set_plain_is_disjoint(__isl_keep isl_basic_set * bset1,__isl_keep isl_basic_set * bset2)3872 int isl_basic_set_plain_is_disjoint(__isl_keep isl_basic_set *bset1,
3873 	__isl_keep isl_basic_set *bset2)
3874 {
3875 	return isl_basic_map_plain_is_disjoint(bset_to_bmap(bset1),
3876 					      bset_to_bmap(bset2));
3877 }
3878 
3879 /* Does "test" hold for all pairs of basic maps in "map1" and "map2"?
3880  */
all_pairs(__isl_keep isl_map * map1,__isl_keep isl_map * map2,isl_bool (* test)(__isl_keep isl_basic_map * bmap1,__isl_keep isl_basic_map * bmap2))3881 static isl_bool all_pairs(__isl_keep isl_map *map1, __isl_keep isl_map *map2,
3882 	isl_bool (*test)(__isl_keep isl_basic_map *bmap1,
3883 		__isl_keep isl_basic_map *bmap2))
3884 {
3885 	int i, j;
3886 
3887 	if (!map1 || !map2)
3888 		return isl_bool_error;
3889 
3890 	for (i = 0; i < map1->n; ++i) {
3891 		for (j = 0; j < map2->n; ++j) {
3892 			isl_bool d = test(map1->p[i], map2->p[j]);
3893 			if (d != isl_bool_true)
3894 				return d;
3895 		}
3896 	}
3897 
3898 	return isl_bool_true;
3899 }
3900 
3901 /* Are "map1" and "map2" obviously disjoint, based on information
3902  * that can be derived without looking at the individual basic maps?
3903  *
3904  * In particular, if one of them is empty or if they live in different spaces
3905  * (ignoring parameters), then they are clearly disjoint.
3906  */
isl_map_plain_is_disjoint_global(__isl_keep isl_map * map1,__isl_keep isl_map * map2)3907 static isl_bool isl_map_plain_is_disjoint_global(__isl_keep isl_map *map1,
3908 	__isl_keep isl_map *map2)
3909 {
3910 	isl_bool disjoint;
3911 	isl_bool match;
3912 
3913 	if (!map1 || !map2)
3914 		return isl_bool_error;
3915 
3916 	disjoint = isl_map_plain_is_empty(map1);
3917 	if (disjoint < 0 || disjoint)
3918 		return disjoint;
3919 
3920 	disjoint = isl_map_plain_is_empty(map2);
3921 	if (disjoint < 0 || disjoint)
3922 		return disjoint;
3923 
3924 	match = isl_map_tuple_is_equal(map1, isl_dim_in, map2, isl_dim_in);
3925 	if (match < 0 || !match)
3926 		return match < 0 ? isl_bool_error : isl_bool_true;
3927 
3928 	match = isl_map_tuple_is_equal(map1, isl_dim_out, map2, isl_dim_out);
3929 	if (match < 0 || !match)
3930 		return match < 0 ? isl_bool_error : isl_bool_true;
3931 
3932 	return isl_bool_false;
3933 }
3934 
3935 /* Are "map1" and "map2" obviously disjoint?
3936  *
3937  * If one of them is empty or if they live in different spaces (ignoring
3938  * parameters), then they are clearly disjoint.
3939  * This is checked by isl_map_plain_is_disjoint_global.
3940  *
3941  * If they have different parameters, then we skip any further tests.
3942  *
3943  * If they are obviously equal, but not obviously empty, then we will
3944  * not be able to detect if they are disjoint.
3945  *
3946  * Otherwise we check if each basic map in "map1" is obviously disjoint
3947  * from each basic map in "map2".
3948  */
isl_map_plain_is_disjoint(__isl_keep isl_map * map1,__isl_keep isl_map * map2)3949 isl_bool isl_map_plain_is_disjoint(__isl_keep isl_map *map1,
3950 	__isl_keep isl_map *map2)
3951 {
3952 	isl_bool disjoint;
3953 	isl_bool intersect;
3954 	isl_bool match;
3955 
3956 	disjoint = isl_map_plain_is_disjoint_global(map1, map2);
3957 	if (disjoint < 0 || disjoint)
3958 		return disjoint;
3959 
3960 	match = isl_map_has_equal_params(map1, map2);
3961 	if (match < 0 || !match)
3962 		return match < 0 ? isl_bool_error : isl_bool_false;
3963 
3964 	intersect = isl_map_plain_is_equal(map1, map2);
3965 	if (intersect < 0 || intersect)
3966 		return intersect < 0 ? isl_bool_error : isl_bool_false;
3967 
3968 	return all_pairs(map1, map2, &isl_basic_map_plain_is_disjoint);
3969 }
3970 
3971 /* Are "map1" and "map2" disjoint?
3972  * The parameters are assumed to have been aligned.
3973  *
3974  * In particular, check whether all pairs of basic maps are disjoint.
3975  */
isl_map_is_disjoint_aligned(__isl_keep isl_map * map1,__isl_keep isl_map * map2)3976 static isl_bool isl_map_is_disjoint_aligned(__isl_keep isl_map *map1,
3977 	__isl_keep isl_map *map2)
3978 {
3979 	return all_pairs(map1, map2, &isl_basic_map_is_disjoint);
3980 }
3981 
3982 /* Are "map1" and "map2" disjoint?
3983  *
3984  * They are disjoint if they are "obviously disjoint" or if one of them
3985  * is empty.  Otherwise, they are not disjoint if one of them is universal.
3986  * If the two inputs are (obviously) equal and not empty, then they are
3987  * not disjoint.
3988  * If none of these cases apply, then check if all pairs of basic maps
3989  * are disjoint after aligning the parameters.
3990  */
isl_map_is_disjoint(__isl_keep isl_map * map1,__isl_keep isl_map * map2)3991 isl_bool isl_map_is_disjoint(__isl_keep isl_map *map1, __isl_keep isl_map *map2)
3992 {
3993 	isl_bool disjoint;
3994 	isl_bool intersect;
3995 
3996 	disjoint = isl_map_plain_is_disjoint_global(map1, map2);
3997 	if (disjoint < 0 || disjoint)
3998 		return disjoint;
3999 
4000 	disjoint = isl_map_is_empty(map1);
4001 	if (disjoint < 0 || disjoint)
4002 		return disjoint;
4003 
4004 	disjoint = isl_map_is_empty(map2);
4005 	if (disjoint < 0 || disjoint)
4006 		return disjoint;
4007 
4008 	intersect = isl_map_plain_is_universe(map1);
4009 	if (intersect < 0 || intersect)
4010 		return isl_bool_not(intersect);
4011 
4012 	intersect = isl_map_plain_is_universe(map2);
4013 	if (intersect < 0 || intersect)
4014 		return isl_bool_not(intersect);
4015 
4016 	intersect = isl_map_plain_is_equal(map1, map2);
4017 	if (intersect < 0 || intersect)
4018 		return isl_bool_not(intersect);
4019 
4020 	return isl_map_align_params_map_map_and_test(map1, map2,
4021 						&isl_map_is_disjoint_aligned);
4022 }
4023 
4024 /* Are "bmap1" and "bmap2" disjoint?
4025  *
4026  * They are disjoint if they are "obviously disjoint" or if one of them
4027  * is empty.  Otherwise, they are not disjoint if one of them is universal.
4028  * If none of these cases apply, we compute the intersection and see if
4029  * the result is empty.
4030  */
isl_basic_map_is_disjoint(__isl_keep isl_basic_map * bmap1,__isl_keep isl_basic_map * bmap2)4031 isl_bool isl_basic_map_is_disjoint(__isl_keep isl_basic_map *bmap1,
4032 	__isl_keep isl_basic_map *bmap2)
4033 {
4034 	isl_bool disjoint;
4035 	isl_bool intersect;
4036 	isl_basic_map *test;
4037 
4038 	disjoint = isl_basic_map_plain_is_disjoint(bmap1, bmap2);
4039 	if (disjoint < 0 || disjoint)
4040 		return disjoint;
4041 
4042 	disjoint = isl_basic_map_is_empty(bmap1);
4043 	if (disjoint < 0 || disjoint)
4044 		return disjoint;
4045 
4046 	disjoint = isl_basic_map_is_empty(bmap2);
4047 	if (disjoint < 0 || disjoint)
4048 		return disjoint;
4049 
4050 	intersect = isl_basic_map_plain_is_universe(bmap1);
4051 	if (intersect < 0 || intersect)
4052 		return isl_bool_not(intersect);
4053 
4054 	intersect = isl_basic_map_plain_is_universe(bmap2);
4055 	if (intersect < 0 || intersect)
4056 		return isl_bool_not(intersect);
4057 
4058 	test = isl_basic_map_intersect(isl_basic_map_copy(bmap1),
4059 		isl_basic_map_copy(bmap2));
4060 	disjoint = isl_basic_map_is_empty(test);
4061 	isl_basic_map_free(test);
4062 
4063 	return disjoint;
4064 }
4065 
4066 /* Are "bset1" and "bset2" disjoint?
4067  */
isl_basic_set_is_disjoint(__isl_keep isl_basic_set * bset1,__isl_keep isl_basic_set * bset2)4068 isl_bool isl_basic_set_is_disjoint(__isl_keep isl_basic_set *bset1,
4069 	__isl_keep isl_basic_set *bset2)
4070 {
4071 	return isl_basic_map_is_disjoint(bset1, bset2);
4072 }
4073 
isl_set_plain_is_disjoint(__isl_keep isl_set * set1,__isl_keep isl_set * set2)4074 isl_bool isl_set_plain_is_disjoint(__isl_keep isl_set *set1,
4075 	__isl_keep isl_set *set2)
4076 {
4077 	return isl_map_plain_is_disjoint(set_to_map(set1), set_to_map(set2));
4078 }
4079 
4080 /* Are "set1" and "set2" disjoint?
4081  */
isl_set_is_disjoint(__isl_keep isl_set * set1,__isl_keep isl_set * set2)4082 isl_bool isl_set_is_disjoint(__isl_keep isl_set *set1, __isl_keep isl_set *set2)
4083 {
4084 	return isl_map_is_disjoint(set1, set2);
4085 }
4086 
4087 /* Is "v" equal to 0, 1 or -1?
4088  */
is_zero_or_one(isl_int v)4089 static int is_zero_or_one(isl_int v)
4090 {
4091 	return isl_int_is_zero(v) || isl_int_is_one(v) || isl_int_is_negone(v);
4092 }
4093 
4094 /* Are the "n" coefficients starting at "first" of inequality constraints
4095  * "i" and "j" of "bmap" opposite to each other?
4096  */
is_opposite_part(__isl_keep isl_basic_map * bmap,int i,int j,int first,int n)4097 static int is_opposite_part(__isl_keep isl_basic_map *bmap, int i, int j,
4098 	int first, int n)
4099 {
4100 	return isl_seq_is_neg(bmap->ineq[i] + first, bmap->ineq[j] + first, n);
4101 }
4102 
4103 /* Are inequality constraints "i" and "j" of "bmap" opposite to each other,
4104  * apart from the constant term?
4105  */
is_opposite(__isl_keep isl_basic_map * bmap,int i,int j)4106 static isl_bool is_opposite(__isl_keep isl_basic_map *bmap, int i, int j)
4107 {
4108 	isl_size total;
4109 
4110 	total = isl_basic_map_dim(bmap, isl_dim_all);
4111 	if (total < 0)
4112 		return isl_bool_error;
4113 	return is_opposite_part(bmap, i, j, 1, total);
4114 }
4115 
4116 /* Check if we can combine a given div with lower bound l and upper
4117  * bound u with some other div and if so return that other div.
4118  * Otherwise, return a position beyond the integer divisions.
4119  * Return -1 on error.
4120  *
4121  * We first check that
4122  *	- the bounds are opposites of each other (except for the constant
4123  *	  term)
4124  *	- the bounds do not reference any other div
4125  *	- no div is defined in terms of this div
4126  *
4127  * Let m be the size of the range allowed on the div by the bounds.
4128  * That is, the bounds are of the form
4129  *
4130  *	e <= a <= e + m - 1
4131  *
4132  * with e some expression in the other variables.
4133  * We look for another div b such that no third div is defined in terms
4134  * of this second div b and such that in any constraint that contains
4135  * a (except for the given lower and upper bound), also contains b
4136  * with a coefficient that is m times that of b.
4137  * That is, all constraints (except for the lower and upper bound)
4138  * are of the form
4139  *
4140  *	e + f (a + m b) >= 0
4141  *
4142  * Furthermore, in the constraints that only contain b, the coefficient
4143  * of b should be equal to 1 or -1.
4144  * If so, we return b so that "a + m b" can be replaced by
4145  * a single div "c = a + m b".
4146  */
div_find_coalesce(__isl_keep isl_basic_map * bmap,int * pairs,unsigned div,unsigned l,unsigned u)4147 static int div_find_coalesce(__isl_keep isl_basic_map *bmap, int *pairs,
4148 	unsigned div, unsigned l, unsigned u)
4149 {
4150 	int i, j;
4151 	unsigned n_div;
4152 	isl_size v_div;
4153 	int coalesce;
4154 	isl_bool opp;
4155 
4156 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
4157 	if (n_div <= 1)
4158 		return n_div;
4159 	v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
4160 	if (v_div < 0)
4161 		return -1;
4162 	if (isl_seq_first_non_zero(bmap->ineq[l] + 1 + v_div, div) != -1)
4163 		return n_div;
4164 	if (isl_seq_first_non_zero(bmap->ineq[l] + 1 + v_div + div + 1,
4165 				   n_div - div - 1) != -1)
4166 		return n_div;
4167 	opp = is_opposite(bmap, l, u);
4168 	if (opp < 0 || !opp)
4169 		return opp < 0 ? -1 : n_div;
4170 
4171 	for (i = 0; i < n_div; ++i) {
4172 		if (isl_int_is_zero(bmap->div[i][0]))
4173 			continue;
4174 		if (!isl_int_is_zero(bmap->div[i][1 + 1 + v_div + div]))
4175 			return n_div;
4176 	}
4177 
4178 	isl_int_add(bmap->ineq[l][0], bmap->ineq[l][0], bmap->ineq[u][0]);
4179 	if (isl_int_is_neg(bmap->ineq[l][0])) {
4180 		isl_int_sub(bmap->ineq[l][0],
4181 			    bmap->ineq[l][0], bmap->ineq[u][0]);
4182 		bmap = isl_basic_map_copy(bmap);
4183 		bmap = isl_basic_map_set_to_empty(bmap);
4184 		isl_basic_map_free(bmap);
4185 		return n_div;
4186 	}
4187 	isl_int_add_ui(bmap->ineq[l][0], bmap->ineq[l][0], 1);
4188 	coalesce = n_div;
4189 	for (i = 0; i < n_div; ++i) {
4190 		if (i == div)
4191 			continue;
4192 		if (!pairs[i])
4193 			continue;
4194 		for (j = 0; j < n_div; ++j) {
4195 			if (isl_int_is_zero(bmap->div[j][0]))
4196 				continue;
4197 			if (!isl_int_is_zero(bmap->div[j][1 + 1 + v_div + i]))
4198 				break;
4199 		}
4200 		if (j < n_div)
4201 			continue;
4202 		for (j = 0; j < bmap->n_ineq; ++j) {
4203 			int valid;
4204 			if (j == l || j == u)
4205 				continue;
4206 			if (isl_int_is_zero(bmap->ineq[j][1 + v_div + div])) {
4207 				if (is_zero_or_one(bmap->ineq[j][1 + v_div + i]))
4208 					continue;
4209 				break;
4210 			}
4211 			if (isl_int_is_zero(bmap->ineq[j][1 + v_div + i]))
4212 				break;
4213 			isl_int_mul(bmap->ineq[j][1 + v_div + div],
4214 				    bmap->ineq[j][1 + v_div + div],
4215 				    bmap->ineq[l][0]);
4216 			valid = isl_int_eq(bmap->ineq[j][1 + v_div + div],
4217 					   bmap->ineq[j][1 + v_div + i]);
4218 			isl_int_divexact(bmap->ineq[j][1 + v_div + div],
4219 					 bmap->ineq[j][1 + v_div + div],
4220 					 bmap->ineq[l][0]);
4221 			if (!valid)
4222 				break;
4223 		}
4224 		if (j < bmap->n_ineq)
4225 			continue;
4226 		coalesce = i;
4227 		break;
4228 	}
4229 	isl_int_sub_ui(bmap->ineq[l][0], bmap->ineq[l][0], 1);
4230 	isl_int_sub(bmap->ineq[l][0], bmap->ineq[l][0], bmap->ineq[u][0]);
4231 	return coalesce;
4232 }
4233 
4234 /* Internal data structure used during the construction and/or evaluation of
4235  * an inequality that ensures that a pair of bounds always allows
4236  * for an integer value.
4237  *
4238  * "tab" is the tableau in which the inequality is evaluated.  It may
4239  * be NULL until it is actually needed.
4240  * "v" contains the inequality coefficients.
4241  * "g", "fl" and "fu" are temporary scalars used during the construction and
4242  * evaluation.
4243  */
4244 struct test_ineq_data {
4245 	struct isl_tab *tab;
4246 	isl_vec *v;
4247 	isl_int g;
4248 	isl_int fl;
4249 	isl_int fu;
4250 };
4251 
4252 /* Free all the memory allocated by the fields of "data".
4253  */
test_ineq_data_clear(struct test_ineq_data * data)4254 static void test_ineq_data_clear(struct test_ineq_data *data)
4255 {
4256 	isl_tab_free(data->tab);
4257 	isl_vec_free(data->v);
4258 	isl_int_clear(data->g);
4259 	isl_int_clear(data->fl);
4260 	isl_int_clear(data->fu);
4261 }
4262 
4263 /* Is the inequality stored in data->v satisfied by "bmap"?
4264  * That is, does it only attain non-negative values?
4265  * data->tab is a tableau corresponding to "bmap".
4266  */
test_ineq_is_satisfied(__isl_keep isl_basic_map * bmap,struct test_ineq_data * data)4267 static isl_bool test_ineq_is_satisfied(__isl_keep isl_basic_map *bmap,
4268 	struct test_ineq_data *data)
4269 {
4270 	isl_ctx *ctx;
4271 	enum isl_lp_result res;
4272 
4273 	ctx = isl_basic_map_get_ctx(bmap);
4274 	if (!data->tab)
4275 		data->tab = isl_tab_from_basic_map(bmap, 0);
4276 	res = isl_tab_min(data->tab, data->v->el, ctx->one, &data->g, NULL, 0);
4277 	if (res == isl_lp_error)
4278 		return isl_bool_error;
4279 	return res == isl_lp_ok && isl_int_is_nonneg(data->g);
4280 }
4281 
4282 /* Given a lower and an upper bound on div i, do they always allow
4283  * for an integer value of the given div?
4284  * Determine this property by constructing an inequality
4285  * such that the property is guaranteed when the inequality is nonnegative.
4286  * The lower bound is inequality l, while the upper bound is inequality u.
4287  * The constructed inequality is stored in data->v.
4288  *
4289  * Let the upper bound be
4290  *
4291  *	-n_u a + e_u >= 0
4292  *
4293  * and the lower bound
4294  *
4295  *	n_l a + e_l >= 0
4296  *
4297  * Let n_u = f_u g and n_l = f_l g, with g = gcd(n_u, n_l).
4298  * We have
4299  *
4300  *	- f_u e_l <= f_u f_l g a <= f_l e_u
4301  *
4302  * Since all variables are integer valued, this is equivalent to
4303  *
4304  *	- f_u e_l - (f_u - 1) <= f_u f_l g a <= f_l e_u + (f_l - 1)
4305  *
4306  * If this interval is at least f_u f_l g, then it contains at least
4307  * one integer value for a.
4308  * That is, the test constraint is
4309  *
4310  *	f_l e_u + f_u e_l + f_l - 1 + f_u - 1 + 1 >= f_u f_l g
4311  *
4312  * or
4313  *
4314  *	f_l e_u + f_u e_l + f_l - 1 + f_u - 1 + 1 - f_u f_l g >= 0
4315  *
4316  * If the coefficients of f_l e_u + f_u e_l have a common divisor g',
4317  * then the constraint can be scaled down by a factor g',
4318  * with the constant term replaced by
4319  * floor((f_l e_{u,0} + f_u e_{l,0} + f_l - 1 + f_u - 1 + 1 - f_u f_l g)/g').
4320  * Note that the result of applying Fourier-Motzkin to this pair
4321  * of constraints is
4322  *
4323  *	f_l e_u + f_u e_l >= 0
4324  *
4325  * If the constant term of the scaled down version of this constraint,
4326  * i.e., floor((f_l e_{u,0} + f_u e_{l,0})/g') is equal to the constant
4327  * term of the scaled down test constraint, then the test constraint
4328  * is known to hold and no explicit evaluation is required.
4329  * This is essentially the Omega test.
4330  *
4331  * If the test constraint consists of only a constant term, then
4332  * it is sufficient to look at the sign of this constant term.
4333  */
int_between_bounds(__isl_keep isl_basic_map * bmap,int i,int l,int u,struct test_ineq_data * data)4334 static isl_bool int_between_bounds(__isl_keep isl_basic_map *bmap, int i,
4335 	int l, int u, struct test_ineq_data *data)
4336 {
4337 	unsigned offset;
4338 	isl_size n_div;
4339 
4340 	offset = isl_basic_map_offset(bmap, isl_dim_div);
4341 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
4342 	if (n_div < 0)
4343 		return isl_bool_error;
4344 
4345 	isl_int_gcd(data->g,
4346 		    bmap->ineq[l][offset + i], bmap->ineq[u][offset + i]);
4347 	isl_int_divexact(data->fl, bmap->ineq[l][offset + i], data->g);
4348 	isl_int_divexact(data->fu, bmap->ineq[u][offset + i], data->g);
4349 	isl_int_neg(data->fu, data->fu);
4350 	isl_seq_combine(data->v->el, data->fl, bmap->ineq[u],
4351 			data->fu, bmap->ineq[l], offset + n_div);
4352 	isl_int_mul(data->g, data->g, data->fl);
4353 	isl_int_mul(data->g, data->g, data->fu);
4354 	isl_int_sub(data->g, data->g, data->fl);
4355 	isl_int_sub(data->g, data->g, data->fu);
4356 	isl_int_add_ui(data->g, data->g, 1);
4357 	isl_int_sub(data->fl, data->v->el[0], data->g);
4358 
4359 	isl_seq_gcd(data->v->el + 1, offset - 1 + n_div, &data->g);
4360 	if (isl_int_is_zero(data->g))
4361 		return isl_int_is_nonneg(data->fl);
4362 	if (isl_int_is_one(data->g)) {
4363 		isl_int_set(data->v->el[0], data->fl);
4364 		return test_ineq_is_satisfied(bmap, data);
4365 	}
4366 	isl_int_fdiv_q(data->fl, data->fl, data->g);
4367 	isl_int_fdiv_q(data->v->el[0], data->v->el[0], data->g);
4368 	if (isl_int_eq(data->fl, data->v->el[0]))
4369 		return isl_bool_true;
4370 	isl_int_set(data->v->el[0], data->fl);
4371 	isl_seq_scale_down(data->v->el + 1, data->v->el + 1, data->g,
4372 			    offset - 1 + n_div);
4373 
4374 	return test_ineq_is_satisfied(bmap, data);
4375 }
4376 
4377 /* Remove more kinds of divs that are not strictly needed.
4378  * In particular, if all pairs of lower and upper bounds on a div
4379  * are such that they allow at least one integer value of the div,
4380  * then we can eliminate the div using Fourier-Motzkin without
4381  * introducing any spurious solutions.
4382  *
4383  * If at least one of the two constraints has a unit coefficient for the div,
4384  * then the presence of such a value is guaranteed so there is no need to check.
4385  * In particular, the value attained by the bound with unit coefficient
4386  * can serve as this intermediate value.
4387  */
drop_more_redundant_divs(__isl_take isl_basic_map * bmap,__isl_take int * pairs,int n)4388 static __isl_give isl_basic_map *drop_more_redundant_divs(
4389 	__isl_take isl_basic_map *bmap, __isl_take int *pairs, int n)
4390 {
4391 	isl_ctx *ctx;
4392 	struct test_ineq_data data = { NULL, NULL };
4393 	unsigned off;
4394 	isl_size n_div;
4395 	int remove = -1;
4396 
4397 	isl_int_init(data.g);
4398 	isl_int_init(data.fl);
4399 	isl_int_init(data.fu);
4400 
4401 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
4402 	if (n_div < 0)
4403 		goto error;
4404 
4405 	ctx = isl_basic_map_get_ctx(bmap);
4406 	off = isl_basic_map_offset(bmap, isl_dim_div);
4407 	data.v = isl_vec_alloc(ctx, off + n_div);
4408 	if (!data.v)
4409 		goto error;
4410 
4411 	while (n > 0) {
4412 		int i, l, u;
4413 		int best = -1;
4414 		isl_bool has_int;
4415 
4416 		for (i = 0; i < n_div; ++i) {
4417 			if (!pairs[i])
4418 				continue;
4419 			if (best >= 0 && pairs[best] <= pairs[i])
4420 				continue;
4421 			best = i;
4422 		}
4423 
4424 		i = best;
4425 		for (l = 0; l < bmap->n_ineq; ++l) {
4426 			if (!isl_int_is_pos(bmap->ineq[l][off + i]))
4427 				continue;
4428 			if (isl_int_is_one(bmap->ineq[l][off + i]))
4429 				continue;
4430 			for (u = 0; u < bmap->n_ineq; ++u) {
4431 				if (!isl_int_is_neg(bmap->ineq[u][off + i]))
4432 					continue;
4433 				if (isl_int_is_negone(bmap->ineq[u][off + i]))
4434 					continue;
4435 				has_int = int_between_bounds(bmap, i, l, u,
4436 								&data);
4437 				if (has_int < 0)
4438 					goto error;
4439 				if (data.tab && data.tab->empty)
4440 					break;
4441 				if (!has_int)
4442 					break;
4443 			}
4444 			if (u < bmap->n_ineq)
4445 				break;
4446 		}
4447 		if (data.tab && data.tab->empty) {
4448 			bmap = isl_basic_map_set_to_empty(bmap);
4449 			break;
4450 		}
4451 		if (l == bmap->n_ineq) {
4452 			remove = i;
4453 			break;
4454 		}
4455 		pairs[i] = 0;
4456 		--n;
4457 	}
4458 
4459 	test_ineq_data_clear(&data);
4460 
4461 	free(pairs);
4462 
4463 	if (remove < 0)
4464 		return bmap;
4465 
4466 	bmap = isl_basic_map_remove_dims(bmap, isl_dim_div, remove, 1);
4467 	return isl_basic_map_drop_redundant_divs(bmap);
4468 error:
4469 	free(pairs);
4470 	isl_basic_map_free(bmap);
4471 	test_ineq_data_clear(&data);
4472 	return NULL;
4473 }
4474 
4475 /* Given a pair of divs div1 and div2 such that, except for the lower bound l
4476  * and the upper bound u, div1 always occurs together with div2 in the form
4477  * (div1 + m div2), where m is the constant range on the variable div1
4478  * allowed by l and u, replace the pair div1 and div2 by a single
4479  * div that is equal to div1 + m div2.
4480  *
4481  * The new div will appear in the location that contains div2.
4482  * We need to modify all constraints that contain
4483  * div2 = (div - div1) / m
4484  * The coefficient of div2 is known to be equal to 1 or -1.
4485  * (If a constraint does not contain div2, it will also not contain div1.)
4486  * If the constraint also contains div1, then we know they appear
4487  * as f (div1 + m div2) and we can simply replace (div1 + m div2) by div,
4488  * i.e., the coefficient of div is f.
4489  *
4490  * Otherwise, we first need to introduce div1 into the constraint.
4491  * Let l be
4492  *
4493  *	div1 + f >=0
4494  *
4495  * and u
4496  *
4497  *	-div1 + f' >= 0
4498  *
4499  * A lower bound on div2
4500  *
4501  *	div2 + t >= 0
4502  *
4503  * can be replaced by
4504  *
4505  *	m div2 + div1 + m t + f >= 0
4506  *
4507  * An upper bound
4508  *
4509  *	-div2 + t >= 0
4510  *
4511  * can be replaced by
4512  *
4513  *	-(m div2 + div1) + m t + f' >= 0
4514  *
4515  * These constraint are those that we would obtain from eliminating
4516  * div1 using Fourier-Motzkin.
4517  *
4518  * After all constraints have been modified, we drop the lower and upper
4519  * bound and then drop div1.
4520  * Since the new div is only placed in the same location that used
4521  * to store div2, but otherwise has a different meaning, any possible
4522  * explicit representation of the original div2 is removed.
4523  */
coalesce_divs(__isl_take isl_basic_map * bmap,unsigned div1,unsigned div2,unsigned l,unsigned u)4524 static __isl_give isl_basic_map *coalesce_divs(__isl_take isl_basic_map *bmap,
4525 	unsigned div1, unsigned div2, unsigned l, unsigned u)
4526 {
4527 	isl_ctx *ctx;
4528 	isl_int m;
4529 	isl_size v_div;
4530 	unsigned total;
4531 	int i;
4532 
4533 	ctx = isl_basic_map_get_ctx(bmap);
4534 
4535 	v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
4536 	if (v_div < 0)
4537 		return isl_basic_map_free(bmap);
4538 	total = 1 + v_div + bmap->n_div;
4539 
4540 	isl_int_init(m);
4541 	isl_int_add(m, bmap->ineq[l][0], bmap->ineq[u][0]);
4542 	isl_int_add_ui(m, m, 1);
4543 
4544 	for (i = 0; i < bmap->n_ineq; ++i) {
4545 		if (i == l || i == u)
4546 			continue;
4547 		if (isl_int_is_zero(bmap->ineq[i][1 + v_div + div2]))
4548 			continue;
4549 		if (isl_int_is_zero(bmap->ineq[i][1 + v_div + div1])) {
4550 			if (isl_int_is_pos(bmap->ineq[i][1 + v_div + div2]))
4551 				isl_seq_combine(bmap->ineq[i], m, bmap->ineq[i],
4552 						ctx->one, bmap->ineq[l], total);
4553 			else
4554 				isl_seq_combine(bmap->ineq[i], m, bmap->ineq[i],
4555 						ctx->one, bmap->ineq[u], total);
4556 		}
4557 		isl_int_set(bmap->ineq[i][1 + v_div + div2],
4558 			    bmap->ineq[i][1 + v_div + div1]);
4559 		isl_int_set_si(bmap->ineq[i][1 + v_div + div1], 0);
4560 	}
4561 
4562 	isl_int_clear(m);
4563 	if (l > u) {
4564 		isl_basic_map_drop_inequality(bmap, l);
4565 		isl_basic_map_drop_inequality(bmap, u);
4566 	} else {
4567 		isl_basic_map_drop_inequality(bmap, u);
4568 		isl_basic_map_drop_inequality(bmap, l);
4569 	}
4570 	bmap = isl_basic_map_mark_div_unknown(bmap, div2);
4571 	bmap = isl_basic_map_drop_div(bmap, div1);
4572 	return bmap;
4573 }
4574 
4575 /* First check if we can coalesce any pair of divs and
4576  * then continue with dropping more redundant divs.
4577  *
4578  * We loop over all pairs of lower and upper bounds on a div
4579  * with coefficient 1 and -1, respectively, check if there
4580  * is any other div "c" with which we can coalesce the div
4581  * and if so, perform the coalescing.
4582  */
coalesce_or_drop_more_redundant_divs(__isl_take isl_basic_map * bmap,int * pairs,int n)4583 static __isl_give isl_basic_map *coalesce_or_drop_more_redundant_divs(
4584 	__isl_take isl_basic_map *bmap, int *pairs, int n)
4585 {
4586 	int i, l, u;
4587 	isl_size v_div;
4588 	isl_size n_div;
4589 
4590 	v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
4591 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
4592 	if (v_div < 0 || n_div < 0)
4593 		return isl_basic_map_free(bmap);
4594 
4595 	for (i = 0; i < n_div; ++i) {
4596 		if (!pairs[i])
4597 			continue;
4598 		for (l = 0; l < bmap->n_ineq; ++l) {
4599 			if (!isl_int_is_one(bmap->ineq[l][1 + v_div + i]))
4600 				continue;
4601 			for (u = 0; u < bmap->n_ineq; ++u) {
4602 				int c;
4603 
4604 				if (!isl_int_is_negone(bmap->ineq[u][1+v_div+i]))
4605 					continue;
4606 				c = div_find_coalesce(bmap, pairs, i, l, u);
4607 				if (c < 0)
4608 					goto error;
4609 				if (c >= n_div)
4610 					continue;
4611 				free(pairs);
4612 				bmap = coalesce_divs(bmap, i, c, l, u);
4613 				return isl_basic_map_drop_redundant_divs(bmap);
4614 			}
4615 		}
4616 	}
4617 
4618 	if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY)) {
4619 		free(pairs);
4620 		return bmap;
4621 	}
4622 
4623 	return drop_more_redundant_divs(bmap, pairs, n);
4624 error:
4625 	free(pairs);
4626 	isl_basic_map_free(bmap);
4627 	return NULL;
4628 }
4629 
4630 /* Are the "n" coefficients starting at "first" of inequality constraints
4631  * "i" and "j" of "bmap" equal to each other?
4632  */
is_parallel_part(__isl_keep isl_basic_map * bmap,int i,int j,int first,int n)4633 static int is_parallel_part(__isl_keep isl_basic_map *bmap, int i, int j,
4634 	int first, int n)
4635 {
4636 	return isl_seq_eq(bmap->ineq[i] + first, bmap->ineq[j] + first, n);
4637 }
4638 
4639 /* Are inequality constraints "i" and "j" of "bmap" equal to each other,
4640  * apart from the constant term and the coefficient at position "pos"?
4641  */
is_parallel_except(__isl_keep isl_basic_map * bmap,int i,int j,int pos)4642 static isl_bool is_parallel_except(__isl_keep isl_basic_map *bmap, int i, int j,
4643 	int pos)
4644 {
4645 	isl_size total;
4646 
4647 	total = isl_basic_map_dim(bmap, isl_dim_all);
4648 	if (total < 0)
4649 		return isl_bool_error;
4650 	return is_parallel_part(bmap, i, j, 1, pos - 1) &&
4651 		is_parallel_part(bmap, i, j, pos + 1, total - pos);
4652 }
4653 
4654 /* Are inequality constraints "i" and "j" of "bmap" opposite to each other,
4655  * apart from the constant term and the coefficient at position "pos"?
4656  */
is_opposite_except(__isl_keep isl_basic_map * bmap,int i,int j,int pos)4657 static isl_bool is_opposite_except(__isl_keep isl_basic_map *bmap, int i, int j,
4658 	int pos)
4659 {
4660 	isl_size total;
4661 
4662 	total = isl_basic_map_dim(bmap, isl_dim_all);
4663 	if (total < 0)
4664 		return isl_bool_error;
4665 	return is_opposite_part(bmap, i, j, 1, pos - 1) &&
4666 		is_opposite_part(bmap, i, j, pos + 1, total - pos);
4667 }
4668 
4669 /* Restart isl_basic_map_drop_redundant_divs after "bmap" has
4670  * been modified, simplying it if "simplify" is set.
4671  * Free the temporary data structure "pairs" that was associated
4672  * to the old version of "bmap".
4673  */
drop_redundant_divs_again(__isl_take isl_basic_map * bmap,__isl_take int * pairs,int simplify)4674 static __isl_give isl_basic_map *drop_redundant_divs_again(
4675 	__isl_take isl_basic_map *bmap, __isl_take int *pairs, int simplify)
4676 {
4677 	if (simplify)
4678 		bmap = isl_basic_map_simplify(bmap);
4679 	free(pairs);
4680 	return isl_basic_map_drop_redundant_divs(bmap);
4681 }
4682 
4683 /* Is "div" the single unknown existentially quantified variable
4684  * in inequality constraint "ineq" of "bmap"?
4685  * "div" is known to have a non-zero coefficient in "ineq".
4686  */
single_unknown(__isl_keep isl_basic_map * bmap,int ineq,int div)4687 static isl_bool single_unknown(__isl_keep isl_basic_map *bmap, int ineq,
4688 	int div)
4689 {
4690 	int i;
4691 	isl_size n_div;
4692 	unsigned o_div;
4693 	isl_bool known;
4694 
4695 	known = isl_basic_map_div_is_known(bmap, div);
4696 	if (known < 0 || known)
4697 		return isl_bool_not(known);
4698 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
4699 	if (n_div < 0)
4700 		return isl_bool_error;
4701 	if (n_div == 1)
4702 		return isl_bool_true;
4703 	o_div = isl_basic_map_offset(bmap, isl_dim_div);
4704 	for (i = 0; i < n_div; ++i) {
4705 		isl_bool known;
4706 
4707 		if (i == div)
4708 			continue;
4709 		if (isl_int_is_zero(bmap->ineq[ineq][o_div + i]))
4710 			continue;
4711 		known = isl_basic_map_div_is_known(bmap, i);
4712 		if (known < 0 || !known)
4713 			return known;
4714 	}
4715 
4716 	return isl_bool_true;
4717 }
4718 
4719 /* Does integer division "div" have coefficient 1 in inequality constraint
4720  * "ineq" of "map"?
4721  */
has_coef_one(__isl_keep isl_basic_map * bmap,int div,int ineq)4722 static isl_bool has_coef_one(__isl_keep isl_basic_map *bmap, int div, int ineq)
4723 {
4724 	unsigned o_div;
4725 
4726 	o_div = isl_basic_map_offset(bmap, isl_dim_div);
4727 	if (isl_int_is_one(bmap->ineq[ineq][o_div + div]))
4728 		return isl_bool_true;
4729 
4730 	return isl_bool_false;
4731 }
4732 
4733 /* Turn inequality constraint "ineq" of "bmap" into an equality and
4734  * then try and drop redundant divs again,
4735  * freeing the temporary data structure "pairs" that was associated
4736  * to the old version of "bmap".
4737  */
set_eq_and_try_again(__isl_take isl_basic_map * bmap,int ineq,__isl_take int * pairs)4738 static __isl_give isl_basic_map *set_eq_and_try_again(
4739 	__isl_take isl_basic_map *bmap, int ineq, __isl_take int *pairs)
4740 {
4741 	bmap = isl_basic_map_cow(bmap);
4742 	isl_basic_map_inequality_to_equality(bmap, ineq);
4743 	return drop_redundant_divs_again(bmap, pairs, 1);
4744 }
4745 
4746 /* Drop the integer division at position "div", along with the two
4747  * inequality constraints "ineq1" and "ineq2" in which it appears
4748  * from "bmap" and then try and drop redundant divs again,
4749  * freeing the temporary data structure "pairs" that was associated
4750  * to the old version of "bmap".
4751  */
drop_div_and_try_again(__isl_take isl_basic_map * bmap,int div,int ineq1,int ineq2,__isl_take int * pairs)4752 static __isl_give isl_basic_map *drop_div_and_try_again(
4753 	__isl_take isl_basic_map *bmap, int div, int ineq1, int ineq2,
4754 	__isl_take int *pairs)
4755 {
4756 	if (ineq1 > ineq2) {
4757 		isl_basic_map_drop_inequality(bmap, ineq1);
4758 		isl_basic_map_drop_inequality(bmap, ineq2);
4759 	} else {
4760 		isl_basic_map_drop_inequality(bmap, ineq2);
4761 		isl_basic_map_drop_inequality(bmap, ineq1);
4762 	}
4763 	bmap = isl_basic_map_drop_div(bmap, div);
4764 	return drop_redundant_divs_again(bmap, pairs, 0);
4765 }
4766 
4767 /* Given two inequality constraints
4768  *
4769  *	f(x) + n d + c >= 0,		(ineq)
4770  *
4771  * with d the variable at position "pos", and
4772  *
4773  *	f(x) + c0 >= 0,			(lower)
4774  *
4775  * compute the maximal value of the lower bound ceil((-f(x) - c)/n)
4776  * determined by the first constraint.
4777  * That is, store
4778  *
4779  *	ceil((c0 - c)/n)
4780  *
4781  * in *l.
4782  */
lower_bound_from_parallel(__isl_keep isl_basic_map * bmap,int ineq,int lower,int pos,isl_int * l)4783 static void lower_bound_from_parallel(__isl_keep isl_basic_map *bmap,
4784 	int ineq, int lower, int pos, isl_int *l)
4785 {
4786 	isl_int_neg(*l, bmap->ineq[ineq][0]);
4787 	isl_int_add(*l, *l, bmap->ineq[lower][0]);
4788 	isl_int_cdiv_q(*l, *l, bmap->ineq[ineq][pos]);
4789 }
4790 
4791 /* Given two inequality constraints
4792  *
4793  *	f(x) + n d + c >= 0,		(ineq)
4794  *
4795  * with d the variable at position "pos", and
4796  *
4797  *	-f(x) - c0 >= 0,		(upper)
4798  *
4799  * compute the minimal value of the lower bound ceil((-f(x) - c)/n)
4800  * determined by the first constraint.
4801  * That is, store
4802  *
4803  *	ceil((-c1 - c)/n)
4804  *
4805  * in *u.
4806  */
lower_bound_from_opposite(__isl_keep isl_basic_map * bmap,int ineq,int upper,int pos,isl_int * u)4807 static void lower_bound_from_opposite(__isl_keep isl_basic_map *bmap,
4808 	int ineq, int upper, int pos, isl_int *u)
4809 {
4810 	isl_int_neg(*u, bmap->ineq[ineq][0]);
4811 	isl_int_sub(*u, *u, bmap->ineq[upper][0]);
4812 	isl_int_cdiv_q(*u, *u, bmap->ineq[ineq][pos]);
4813 }
4814 
4815 /* Given a lower bound constraint "ineq" on "div" in "bmap",
4816  * does the corresponding lower bound have a fixed value in "bmap"?
4817  *
4818  * In particular, "ineq" is of the form
4819  *
4820  *	f(x) + n d + c >= 0
4821  *
4822  * with n > 0, c the constant term and
4823  * d the existentially quantified variable "div".
4824  * That is, the lower bound is
4825  *
4826  *	ceil((-f(x) - c)/n)
4827  *
4828  * Look for a pair of constraints
4829  *
4830  *	f(x) + c0 >= 0
4831  *	-f(x) + c1 >= 0
4832  *
4833  * i.e., -c1 <= -f(x) <= c0, that fix ceil((-f(x) - c)/n) to a constant value.
4834  * That is, check that
4835  *
4836  *	ceil((-c1 - c)/n) = ceil((c0 - c)/n)
4837  *
4838  * If so, return the index of inequality f(x) + c0 >= 0.
4839  * Otherwise, return bmap->n_ineq.
4840  * Return -1 on error.
4841  */
lower_bound_is_cst(__isl_keep isl_basic_map * bmap,int div,int ineq)4842 static int lower_bound_is_cst(__isl_keep isl_basic_map *bmap, int div, int ineq)
4843 {
4844 	int i;
4845 	int lower = -1, upper = -1;
4846 	unsigned o_div;
4847 	isl_int l, u;
4848 	int equal;
4849 
4850 	o_div = isl_basic_map_offset(bmap, isl_dim_div);
4851 	for (i = 0; i < bmap->n_ineq && (lower < 0 || upper < 0); ++i) {
4852 		isl_bool par, opp;
4853 
4854 		if (i == ineq)
4855 			continue;
4856 		if (!isl_int_is_zero(bmap->ineq[i][o_div + div]))
4857 			continue;
4858 		par = isl_bool_false;
4859 		if (lower < 0)
4860 			par = is_parallel_except(bmap, ineq, i, o_div + div);
4861 		if (par < 0)
4862 			return -1;
4863 		if (par) {
4864 			lower = i;
4865 			continue;
4866 		}
4867 		opp = isl_bool_false;
4868 		if (upper < 0)
4869 			opp = is_opposite_except(bmap, ineq, i, o_div + div);
4870 		if (opp < 0)
4871 			return -1;
4872 		if (opp)
4873 			upper = i;
4874 	}
4875 
4876 	if (lower < 0 || upper < 0)
4877 		return bmap->n_ineq;
4878 
4879 	isl_int_init(l);
4880 	isl_int_init(u);
4881 
4882 	lower_bound_from_parallel(bmap, ineq, lower, o_div + div, &l);
4883 	lower_bound_from_opposite(bmap, ineq, upper, o_div + div, &u);
4884 
4885 	equal = isl_int_eq(l, u);
4886 
4887 	isl_int_clear(l);
4888 	isl_int_clear(u);
4889 
4890 	return equal ? lower : bmap->n_ineq;
4891 }
4892 
4893 /* Given a lower bound constraint "ineq" on the existentially quantified
4894  * variable "div", such that the corresponding lower bound has
4895  * a fixed value in "bmap", assign this fixed value to the variable and
4896  * then try and drop redundant divs again,
4897  * freeing the temporary data structure "pairs" that was associated
4898  * to the old version of "bmap".
4899  * "lower" determines the constant value for the lower bound.
4900  *
4901  * In particular, "ineq" is of the form
4902  *
4903  *	f(x) + n d + c >= 0,
4904  *
4905  * while "lower" is of the form
4906  *
4907  *	f(x) + c0 >= 0
4908  *
4909  * The lower bound is ceil((-f(x) - c)/n) and its constant value
4910  * is ceil((c0 - c)/n).
4911  */
fix_cst_lower(__isl_take isl_basic_map * bmap,int div,int ineq,int lower,int * pairs)4912 static __isl_give isl_basic_map *fix_cst_lower(__isl_take isl_basic_map *bmap,
4913 	int div, int ineq, int lower, int *pairs)
4914 {
4915 	isl_int c;
4916 	unsigned o_div;
4917 
4918 	isl_int_init(c);
4919 
4920 	o_div = isl_basic_map_offset(bmap, isl_dim_div);
4921 	lower_bound_from_parallel(bmap, ineq, lower, o_div + div, &c);
4922 	bmap = isl_basic_map_fix(bmap, isl_dim_div, div, c);
4923 	free(pairs);
4924 
4925 	isl_int_clear(c);
4926 
4927 	return isl_basic_map_drop_redundant_divs(bmap);
4928 }
4929 
4930 /* Do any of the integer divisions of "bmap" involve integer division "div"?
4931  *
4932  * The integer division "div" could only ever appear in any later
4933  * integer division (with an explicit representation).
4934  */
any_div_involves_div(__isl_keep isl_basic_map * bmap,int div)4935 static isl_bool any_div_involves_div(__isl_keep isl_basic_map *bmap, int div)
4936 {
4937 	int i;
4938 	isl_size v_div, n_div;
4939 
4940 	v_div = isl_basic_map_var_offset(bmap, isl_dim_div);
4941 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
4942 	if (v_div < 0 || n_div < 0)
4943 		return isl_bool_error;
4944 
4945 	for (i = div + 1; i < n_div; ++i) {
4946 		isl_bool unknown;
4947 
4948 		unknown = isl_basic_map_div_is_marked_unknown(bmap, i);
4949 		if (unknown < 0)
4950 			return isl_bool_error;
4951 		if (unknown)
4952 			continue;
4953 		if (!isl_int_is_zero(bmap->div[i][1 + 1 + v_div + div]))
4954 			return isl_bool_true;
4955 	}
4956 
4957 	return isl_bool_false;
4958 }
4959 
4960 /* Remove divs that are not strictly needed based on the inequality
4961  * constraints.
4962  * In particular, if a div only occurs positively (or negatively)
4963  * in constraints, then it can simply be dropped.
4964  * Also, if a div occurs in only two constraints and if moreover
4965  * those two constraints are opposite to each other, except for the constant
4966  * term and if the sum of the constant terms is such that for any value
4967  * of the other values, there is always at least one integer value of the
4968  * div, i.e., if one plus this sum is greater than or equal to
4969  * the (absolute value) of the coefficient of the div in the constraints,
4970  * then we can also simply drop the div.
4971  *
4972  * If an existentially quantified variable does not have an explicit
4973  * representation, appears in only a single lower bound that does not
4974  * involve any other such existentially quantified variables and appears
4975  * in this lower bound with coefficient 1,
4976  * then fix the variable to the value of the lower bound.  That is,
4977  * turn the inequality into an equality.
4978  * If for any value of the other variables, there is any value
4979  * for the existentially quantified variable satisfying the constraints,
4980  * then this lower bound also satisfies the constraints.
4981  * It is therefore safe to pick this lower bound.
4982  *
4983  * The same reasoning holds even if the coefficient is not one.
4984  * However, fixing the variable to the value of the lower bound may
4985  * in general introduce an extra integer division, in which case
4986  * it may be better to pick another value.
4987  * If this integer division has a known constant value, then plugging
4988  * in this constant value removes the existentially quantified variable
4989  * completely.  In particular, if the lower bound is of the form
4990  * ceil((-f(x) - c)/n) and there are two constraints, f(x) + c0 >= 0 and
4991  * -f(x) + c1 >= 0 such that ceil((-c1 - c)/n) = ceil((c0 - c)/n),
4992  * then the existentially quantified variable can be assigned this
4993  * shared value.
4994  *
4995  * We skip divs that appear in equalities or in the definition of other divs.
4996  * Divs that appear in the definition of other divs usually occur in at least
4997  * 4 constraints, but the constraints may have been simplified.
4998  *
4999  * If any divs are left after these simple checks then we move on
5000  * to more complicated cases in drop_more_redundant_divs.
5001  */
isl_basic_map_drop_redundant_divs_ineq(__isl_take isl_basic_map * bmap)5002 static __isl_give isl_basic_map *isl_basic_map_drop_redundant_divs_ineq(
5003 	__isl_take isl_basic_map *bmap)
5004 {
5005 	int i, j;
5006 	isl_size off;
5007 	int *pairs = NULL;
5008 	int n = 0;
5009 	isl_size n_ineq;
5010 
5011 	if (!bmap)
5012 		goto error;
5013 	if (bmap->n_div == 0)
5014 		return bmap;
5015 
5016 	off = isl_basic_map_var_offset(bmap, isl_dim_div);
5017 	if (off < 0)
5018 		return isl_basic_map_free(bmap);
5019 	pairs = isl_calloc_array(bmap->ctx, int, bmap->n_div);
5020 	if (!pairs)
5021 		goto error;
5022 
5023 	n_ineq = isl_basic_map_n_inequality(bmap);
5024 	if (n_ineq < 0)
5025 		goto error;
5026 	for (i = 0; i < bmap->n_div; ++i) {
5027 		int pos, neg;
5028 		int last_pos, last_neg;
5029 		int redundant;
5030 		int defined;
5031 		isl_bool involves, opp, set_div;
5032 
5033 		defined = !isl_int_is_zero(bmap->div[i][0]);
5034 		involves = any_div_involves_div(bmap, i);
5035 		if (involves < 0)
5036 			goto error;
5037 		if (involves)
5038 			continue;
5039 		for (j = 0; j < bmap->n_eq; ++j)
5040 			if (!isl_int_is_zero(bmap->eq[j][1 + off + i]))
5041 				break;
5042 		if (j < bmap->n_eq)
5043 			continue;
5044 		++n;
5045 		pos = neg = 0;
5046 		for (j = 0; j < bmap->n_ineq; ++j) {
5047 			if (isl_int_is_pos(bmap->ineq[j][1 + off + i])) {
5048 				last_pos = j;
5049 				++pos;
5050 			}
5051 			if (isl_int_is_neg(bmap->ineq[j][1 + off + i])) {
5052 				last_neg = j;
5053 				++neg;
5054 			}
5055 		}
5056 		pairs[i] = pos * neg;
5057 		if (pairs[i] == 0) {
5058 			for (j = bmap->n_ineq - 1; j >= 0; --j)
5059 				if (!isl_int_is_zero(bmap->ineq[j][1+off+i]))
5060 					isl_basic_map_drop_inequality(bmap, j);
5061 			bmap = isl_basic_map_drop_div(bmap, i);
5062 			return drop_redundant_divs_again(bmap, pairs, 0);
5063 		}
5064 		if (pairs[i] != 1)
5065 			opp = isl_bool_false;
5066 		else
5067 			opp = is_opposite(bmap, last_pos, last_neg);
5068 		if (opp < 0)
5069 			goto error;
5070 		if (!opp) {
5071 			int lower;
5072 			isl_bool single, one;
5073 
5074 			if (pos != 1)
5075 				continue;
5076 			single = single_unknown(bmap, last_pos, i);
5077 			if (single < 0)
5078 				goto error;
5079 			if (!single)
5080 				continue;
5081 			one = has_coef_one(bmap, i, last_pos);
5082 			if (one < 0)
5083 				goto error;
5084 			if (one)
5085 				return set_eq_and_try_again(bmap, last_pos,
5086 							    pairs);
5087 			lower = lower_bound_is_cst(bmap, i, last_pos);
5088 			if (lower < 0)
5089 				goto error;
5090 			if (lower < n_ineq)
5091 				return fix_cst_lower(bmap, i, last_pos, lower,
5092 						pairs);
5093 			continue;
5094 		}
5095 
5096 		isl_int_add(bmap->ineq[last_pos][0],
5097 			    bmap->ineq[last_pos][0], bmap->ineq[last_neg][0]);
5098 		isl_int_add_ui(bmap->ineq[last_pos][0],
5099 			       bmap->ineq[last_pos][0], 1);
5100 		redundant = isl_int_ge(bmap->ineq[last_pos][0],
5101 				bmap->ineq[last_pos][1+off+i]);
5102 		isl_int_sub_ui(bmap->ineq[last_pos][0],
5103 			       bmap->ineq[last_pos][0], 1);
5104 		isl_int_sub(bmap->ineq[last_pos][0],
5105 			    bmap->ineq[last_pos][0], bmap->ineq[last_neg][0]);
5106 		if (redundant)
5107 			return drop_div_and_try_again(bmap, i,
5108 						    last_pos, last_neg, pairs);
5109 		if (defined)
5110 			set_div = isl_bool_false;
5111 		else
5112 			set_div = ok_to_set_div_from_bound(bmap, i, last_pos);
5113 		if (set_div < 0)
5114 			return isl_basic_map_free(bmap);
5115 		if (set_div) {
5116 			bmap = set_div_from_lower_bound(bmap, i, last_pos);
5117 			return drop_redundant_divs_again(bmap, pairs, 1);
5118 		}
5119 		pairs[i] = 0;
5120 		--n;
5121 	}
5122 
5123 	if (n > 0)
5124 		return coalesce_or_drop_more_redundant_divs(bmap, pairs, n);
5125 
5126 	free(pairs);
5127 	return bmap;
5128 error:
5129 	free(pairs);
5130 	isl_basic_map_free(bmap);
5131 	return NULL;
5132 }
5133 
5134 /* Consider the coefficients at "c" as a row vector and replace
5135  * them with their product with "T".  "T" is assumed to be a square matrix.
5136  */
preimage(isl_int * c,__isl_keep isl_mat * T)5137 static isl_stat preimage(isl_int *c, __isl_keep isl_mat *T)
5138 {
5139 	isl_size n;
5140 	isl_ctx *ctx;
5141 	isl_vec *v;
5142 
5143 	n = isl_mat_rows(T);
5144 	if (n < 0)
5145 		return isl_stat_error;
5146 	if (isl_seq_first_non_zero(c, n) == -1)
5147 		return isl_stat_ok;
5148 	ctx = isl_mat_get_ctx(T);
5149 	v = isl_vec_alloc(ctx, n);
5150 	if (!v)
5151 		return isl_stat_error;
5152 	isl_seq_swp_or_cpy(v->el, c, n);
5153 	v = isl_vec_mat_product(v, isl_mat_copy(T));
5154 	if (!v)
5155 		return isl_stat_error;
5156 	isl_seq_swp_or_cpy(c, v->el, n);
5157 	isl_vec_free(v);
5158 
5159 	return isl_stat_ok;
5160 }
5161 
5162 /* Plug in T for the variables in "bmap" starting at "pos".
5163  * T is a linear unimodular matrix, i.e., without constant term.
5164  */
isl_basic_map_preimage_vars(__isl_take isl_basic_map * bmap,unsigned pos,__isl_take isl_mat * T)5165 static __isl_give isl_basic_map *isl_basic_map_preimage_vars(
5166 	__isl_take isl_basic_map *bmap, unsigned pos, __isl_take isl_mat *T)
5167 {
5168 	int i;
5169 	isl_size n_row, n_col;
5170 
5171 	bmap = isl_basic_map_cow(bmap);
5172 	n_row = isl_mat_rows(T);
5173 	n_col = isl_mat_cols(T);
5174 	if (!bmap || n_row < 0 || n_col < 0)
5175 		goto error;
5176 
5177 	if (n_col != n_row)
5178 		isl_die(isl_mat_get_ctx(T), isl_error_invalid,
5179 			"expecting square matrix", goto error);
5180 
5181 	if (isl_basic_map_check_range(bmap, isl_dim_all, pos, n_col) < 0)
5182 		goto error;
5183 
5184 	for (i = 0; i < bmap->n_eq; ++i)
5185 		if (preimage(bmap->eq[i] + 1 + pos, T) < 0)
5186 			goto error;
5187 	for (i = 0; i < bmap->n_ineq; ++i)
5188 		if (preimage(bmap->ineq[i] + 1 + pos, T) < 0)
5189 			goto error;
5190 	for (i = 0; i < bmap->n_div; ++i) {
5191 		if (isl_basic_map_div_is_marked_unknown(bmap, i))
5192 			continue;
5193 		if (preimage(bmap->div[i] + 1 + 1 + pos, T) < 0)
5194 			goto error;
5195 	}
5196 
5197 	isl_mat_free(T);
5198 	return bmap;
5199 error:
5200 	isl_basic_map_free(bmap);
5201 	isl_mat_free(T);
5202 	return NULL;
5203 }
5204 
5205 /* Remove divs that are not strictly needed.
5206  *
5207  * First look for an equality constraint involving two or more
5208  * existentially quantified variables without an explicit
5209  * representation.  Replace the combination that appears
5210  * in the equality constraint by a single existentially quantified
5211  * variable such that the equality can be used to derive
5212  * an explicit representation for the variable.
5213  * If there are no more such equality constraints, then continue
5214  * with isl_basic_map_drop_redundant_divs_ineq.
5215  *
5216  * In particular, if the equality constraint is of the form
5217  *
5218  *	f(x) + \sum_i c_i a_i = 0
5219  *
5220  * with a_i existentially quantified variable without explicit
5221  * representation, then apply a transformation on the existentially
5222  * quantified variables to turn the constraint into
5223  *
5224  *	f(x) + g a_1' = 0
5225  *
5226  * with g the gcd of the c_i.
5227  * In order to easily identify which existentially quantified variables
5228  * have a complete explicit representation, i.e., without being defined
5229  * in terms of other existentially quantified variables without
5230  * an explicit representation, the existentially quantified variables
5231  * are first sorted.
5232  *
5233  * The variable transformation is computed by extending the row
5234  * [c_1/g ... c_n/g] to a unimodular matrix, obtaining the transformation
5235  *
5236  *	[a_1']   [c_1/g ... c_n/g]   [ a_1 ]
5237  *	[a_2']                       [ a_2 ]
5238  *	 ...   =         U             ....
5239  *	[a_n']            	     [ a_n ]
5240  *
5241  * with [c_1/g ... c_n/g] representing the first row of U.
5242  * The inverse of U is then plugged into the original constraints.
5243  * The call to isl_basic_map_simplify makes sure the explicit
5244  * representation for a_1' is extracted from the equality constraint.
5245  */
isl_basic_map_drop_redundant_divs(__isl_take isl_basic_map * bmap)5246 __isl_give isl_basic_map *isl_basic_map_drop_redundant_divs(
5247 	__isl_take isl_basic_map *bmap)
5248 {
5249 	int first;
5250 	int i;
5251 	unsigned o_div;
5252 	isl_size n_div;
5253 	int l;
5254 	isl_ctx *ctx;
5255 	isl_mat *T;
5256 
5257 	if (!bmap)
5258 		return NULL;
5259 	if (isl_basic_map_divs_known(bmap))
5260 		return isl_basic_map_drop_redundant_divs_ineq(bmap);
5261 	if (bmap->n_eq == 0)
5262 		return isl_basic_map_drop_redundant_divs_ineq(bmap);
5263 	bmap = isl_basic_map_sort_divs(bmap);
5264 	if (!bmap)
5265 		return NULL;
5266 
5267 	first = isl_basic_map_first_unknown_div(bmap);
5268 	if (first < 0)
5269 		return isl_basic_map_free(bmap);
5270 
5271 	o_div = isl_basic_map_offset(bmap, isl_dim_div);
5272 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
5273 	if (n_div < 0)
5274 		return isl_basic_map_free(bmap);
5275 
5276 	for (i = 0; i < bmap->n_eq; ++i) {
5277 		l = isl_seq_first_non_zero(bmap->eq[i] + o_div + first,
5278 					    n_div - (first));
5279 		if (l < 0)
5280 			continue;
5281 		l += first;
5282 		if (isl_seq_first_non_zero(bmap->eq[i] + o_div + l + 1,
5283 					    n_div - (l + 1)) == -1)
5284 			continue;
5285 		break;
5286 	}
5287 	if (i >= bmap->n_eq)
5288 		return isl_basic_map_drop_redundant_divs_ineq(bmap);
5289 
5290 	ctx = isl_basic_map_get_ctx(bmap);
5291 	T = isl_mat_alloc(ctx, n_div - l, n_div - l);
5292 	if (!T)
5293 		return isl_basic_map_free(bmap);
5294 	isl_seq_cpy(T->row[0], bmap->eq[i] + o_div + l, n_div - l);
5295 	T = isl_mat_normalize_row(T, 0);
5296 	T = isl_mat_unimodular_complete(T, 1);
5297 	T = isl_mat_right_inverse(T);
5298 
5299 	for (i = l; i < n_div; ++i)
5300 		bmap = isl_basic_map_mark_div_unknown(bmap, i);
5301 	bmap = isl_basic_map_preimage_vars(bmap, o_div - 1 + l, T);
5302 	bmap = isl_basic_map_simplify(bmap);
5303 
5304 	return isl_basic_map_drop_redundant_divs(bmap);
5305 }
5306 
5307 /* Does "bmap" satisfy any equality that involves more than 2 variables
5308  * and/or has coefficients different from -1 and 1?
5309  */
has_multiple_var_equality(__isl_keep isl_basic_map * bmap)5310 static isl_bool has_multiple_var_equality(__isl_keep isl_basic_map *bmap)
5311 {
5312 	int i;
5313 	isl_size total;
5314 
5315 	total = isl_basic_map_dim(bmap, isl_dim_all);
5316 	if (total < 0)
5317 		return isl_bool_error;
5318 
5319 	for (i = 0; i < bmap->n_eq; ++i) {
5320 		int j, k;
5321 
5322 		j = isl_seq_first_non_zero(bmap->eq[i] + 1, total);
5323 		if (j < 0)
5324 			continue;
5325 		if (!isl_int_is_one(bmap->eq[i][1 + j]) &&
5326 		    !isl_int_is_negone(bmap->eq[i][1 + j]))
5327 			return isl_bool_true;
5328 
5329 		j += 1;
5330 		k = isl_seq_first_non_zero(bmap->eq[i] + 1 + j, total - j);
5331 		if (k < 0)
5332 			continue;
5333 		j += k;
5334 		if (!isl_int_is_one(bmap->eq[i][1 + j]) &&
5335 		    !isl_int_is_negone(bmap->eq[i][1 + j]))
5336 			return isl_bool_true;
5337 
5338 		j += 1;
5339 		k = isl_seq_first_non_zero(bmap->eq[i] + 1 + j, total - j);
5340 		if (k >= 0)
5341 			return isl_bool_true;
5342 	}
5343 
5344 	return isl_bool_false;
5345 }
5346 
5347 /* Remove any common factor g from the constraint coefficients in "v".
5348  * The constant term is stored in the first position and is replaced
5349  * by floor(c/g).  If any common factor is removed and if this results
5350  * in a tightening of the constraint, then set *tightened.
5351  */
normalize_constraint(__isl_take isl_vec * v,int * tightened)5352 static __isl_give isl_vec *normalize_constraint(__isl_take isl_vec *v,
5353 	int *tightened)
5354 {
5355 	isl_ctx *ctx;
5356 
5357 	if (!v)
5358 		return NULL;
5359 	ctx = isl_vec_get_ctx(v);
5360 	isl_seq_gcd(v->el + 1, v->size - 1, &ctx->normalize_gcd);
5361 	if (isl_int_is_zero(ctx->normalize_gcd))
5362 		return v;
5363 	if (isl_int_is_one(ctx->normalize_gcd))
5364 		return v;
5365 	v = isl_vec_cow(v);
5366 	if (!v)
5367 		return NULL;
5368 	if (tightened && !isl_int_is_divisible_by(v->el[0], ctx->normalize_gcd))
5369 		*tightened = 1;
5370 	isl_int_fdiv_q(v->el[0], v->el[0], ctx->normalize_gcd);
5371 	isl_seq_scale_down(v->el + 1, v->el + 1, ctx->normalize_gcd,
5372 				v->size - 1);
5373 	return v;
5374 }
5375 
5376 /* If "bmap" is an integer set that satisfies any equality involving
5377  * more than 2 variables and/or has coefficients different from -1 and 1,
5378  * then use variable compression to reduce the coefficients by removing
5379  * any (hidden) common factor.
5380  * In particular, apply the variable compression to each constraint,
5381  * factor out any common factor in the non-constant coefficients and
5382  * then apply the inverse of the compression.
5383  * At the end, we mark the basic map as having reduced constants.
5384  * If this flag is still set on the next invocation of this function,
5385  * then we skip the computation.
5386  *
5387  * Removing a common factor may result in a tightening of some of
5388  * the constraints.  If this happens, then we may end up with two
5389  * opposite inequalities that can be replaced by an equality.
5390  * We therefore call isl_basic_map_detect_inequality_pairs,
5391  * which checks for such pairs of inequalities as well as eliminate_divs_eq
5392  * and isl_basic_map_gauss if such a pair was found.
5393  *
5394  * Tightening may also result in some other constraints becoming
5395  * (rationally) redundant with respect to the tightened constraint
5396  * (in combination with other constraints).  The basic map may
5397  * therefore no longer be assumed to have no redundant constraints.
5398  *
5399  * Note that this function may leave the result in an inconsistent state.
5400  * In particular, the constraints may not be gaussed.
5401  * Unfortunately, isl_map_coalesce actually depends on this inconsistent state
5402  * for some of the test cases to pass successfully.
5403  * Any potential modification of the representation is therefore only
5404  * performed on a single copy of the basic map.
5405  */
isl_basic_map_reduce_coefficients(__isl_take isl_basic_map * bmap)5406 __isl_give isl_basic_map *isl_basic_map_reduce_coefficients(
5407 	__isl_take isl_basic_map *bmap)
5408 {
5409 	isl_size total;
5410 	isl_bool multi;
5411 	isl_ctx *ctx;
5412 	isl_vec *v;
5413 	isl_mat *eq, *T, *T2;
5414 	int i;
5415 	int tightened;
5416 
5417 	if (!bmap)
5418 		return NULL;
5419 	if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_REDUCED_COEFFICIENTS))
5420 		return bmap;
5421 	if (isl_basic_map_is_rational(bmap))
5422 		return bmap;
5423 	if (bmap->n_eq == 0)
5424 		return bmap;
5425 	multi = has_multiple_var_equality(bmap);
5426 	if (multi < 0)
5427 		return isl_basic_map_free(bmap);
5428 	if (!multi)
5429 		return bmap;
5430 
5431 	total = isl_basic_map_dim(bmap, isl_dim_all);
5432 	if (total < 0)
5433 		return isl_basic_map_free(bmap);
5434 	ctx = isl_basic_map_get_ctx(bmap);
5435 	v = isl_vec_alloc(ctx, 1 + total);
5436 	if (!v)
5437 		return isl_basic_map_free(bmap);
5438 
5439 	eq = isl_mat_sub_alloc6(ctx, bmap->eq, 0, bmap->n_eq, 0, 1 + total);
5440 	T = isl_mat_variable_compression(eq, &T2);
5441 	if (!T || !T2)
5442 		goto error;
5443 	if (T->n_col == 0) {
5444 		isl_mat_free(T);
5445 		isl_mat_free(T2);
5446 		isl_vec_free(v);
5447 		return isl_basic_map_set_to_empty(bmap);
5448 	}
5449 
5450 	bmap = isl_basic_map_cow(bmap);
5451 	if (!bmap)
5452 		goto error;
5453 
5454 	tightened = 0;
5455 	for (i = 0; i < bmap->n_ineq; ++i) {
5456 		isl_seq_cpy(v->el, bmap->ineq[i], 1 + total);
5457 		v = isl_vec_mat_product(v, isl_mat_copy(T));
5458 		v = normalize_constraint(v, &tightened);
5459 		v = isl_vec_mat_product(v, isl_mat_copy(T2));
5460 		if (!v)
5461 			goto error;
5462 		isl_seq_cpy(bmap->ineq[i], v->el, 1 + total);
5463 	}
5464 
5465 	isl_mat_free(T);
5466 	isl_mat_free(T2);
5467 	isl_vec_free(v);
5468 
5469 	ISL_F_SET(bmap, ISL_BASIC_MAP_REDUCED_COEFFICIENTS);
5470 
5471 	if (tightened) {
5472 		int progress = 0;
5473 
5474 		ISL_F_CLR(bmap, ISL_BASIC_MAP_NO_REDUNDANT);
5475 		bmap = isl_basic_map_detect_inequality_pairs(bmap, &progress);
5476 		if (progress) {
5477 			bmap = eliminate_divs_eq(bmap, &progress);
5478 			bmap = isl_basic_map_gauss(bmap, NULL);
5479 		}
5480 	}
5481 
5482 	return bmap;
5483 error:
5484 	isl_mat_free(T);
5485 	isl_mat_free(T2);
5486 	isl_vec_free(v);
5487 	return isl_basic_map_free(bmap);
5488 }
5489 
5490 /* Shift the integer division at position "div" of "bmap"
5491  * by "shift" times the variable at position "pos".
5492  * "pos" is as determined by isl_basic_map_offset, i.e., pos == 0
5493  * corresponds to the constant term.
5494  *
5495  * That is, if the integer division has the form
5496  *
5497  *	floor(f(x)/d)
5498  *
5499  * then replace it by
5500  *
5501  *	floor((f(x) + shift * d * x_pos)/d) - shift * x_pos
5502  */
isl_basic_map_shift_div(__isl_take isl_basic_map * bmap,int div,int pos,isl_int shift)5503 __isl_give isl_basic_map *isl_basic_map_shift_div(
5504 	__isl_take isl_basic_map *bmap, int div, int pos, isl_int shift)
5505 {
5506 	int i;
5507 	isl_size total, n_div;
5508 
5509 	if (isl_int_is_zero(shift))
5510 		return bmap;
5511 	total = isl_basic_map_dim(bmap, isl_dim_all);
5512 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
5513 	total -= n_div;
5514 	if (total < 0 || n_div < 0)
5515 		return isl_basic_map_free(bmap);
5516 
5517 	isl_int_addmul(bmap->div[div][1 + pos], shift, bmap->div[div][0]);
5518 
5519 	for (i = 0; i < bmap->n_eq; ++i) {
5520 		if (isl_int_is_zero(bmap->eq[i][1 + total + div]))
5521 			continue;
5522 		isl_int_submul(bmap->eq[i][pos],
5523 				shift, bmap->eq[i][1 + total + div]);
5524 	}
5525 	for (i = 0; i < bmap->n_ineq; ++i) {
5526 		if (isl_int_is_zero(bmap->ineq[i][1 + total + div]))
5527 			continue;
5528 		isl_int_submul(bmap->ineq[i][pos],
5529 				shift, bmap->ineq[i][1 + total + div]);
5530 	}
5531 	for (i = 0; i < bmap->n_div; ++i) {
5532 		if (isl_int_is_zero(bmap->div[i][0]))
5533 			continue;
5534 		if (isl_int_is_zero(bmap->div[i][1 + 1 + total + div]))
5535 			continue;
5536 		isl_int_submul(bmap->div[i][1 + pos],
5537 				shift, bmap->div[i][1 + 1 + total + div]);
5538 	}
5539 
5540 	return bmap;
5541 }
5542