isl_ast_build_get_stride: use isl_val
[platform/upstream/isl.git] / isl_ast_codegen.c
1 /*
2  * Copyright 2012      Ecole Normale Superieure
3  *
4  * Use of this software is governed by the MIT license
5  *
6  * Written by Sven Verdoolaege,
7  * Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
8  */
9
10 #include <limits.h>
11 #include <isl/aff.h>
12 #include <isl/set.h>
13 #include <isl/ilp.h>
14 #include <isl/union_map.h>
15 #include <isl_sort.h>
16 #include <isl_tarjan.h>
17 #include <isl_ast_private.h>
18 #include <isl_ast_build_expr.h>
19 #include <isl_ast_build_private.h>
20 #include <isl_ast_graft_private.h>
21
22 /* Add the constraint to the list that "user" points to, if it is not
23  * a div constraint.
24  */
25 static int collect_constraint(__isl_take isl_constraint *constraint,
26         void *user)
27 {
28         isl_constraint_list **list = user;
29
30         if (isl_constraint_is_div_constraint(constraint))
31                 isl_constraint_free(constraint);
32         else
33                 *list = isl_constraint_list_add(*list, constraint);
34
35         return 0;
36 }
37
38 /* Extract the constraints of "bset" (except the div constraints)
39  * and collect them in an isl_constraint_list.
40  */
41 static __isl_give isl_constraint_list *isl_constraint_list_from_basic_set(
42         __isl_take isl_basic_set *bset)
43 {
44         int n;
45         isl_ctx *ctx;
46         isl_constraint_list *list;
47
48         if (!bset)
49                 return NULL;
50
51         ctx = isl_basic_set_get_ctx(bset);
52
53         n = isl_basic_set_n_constraint(bset);
54         list = isl_constraint_list_alloc(ctx, n);
55         if (isl_basic_set_foreach_constraint(bset,
56                                             &collect_constraint, &list) < 0)
57                 list = isl_constraint_list_free(list);
58
59         isl_basic_set_free(bset);
60         return list;
61 }
62
63 /* Data used in generate_domain.
64  *
65  * "build" is the input build.
66  * "list" collects the results.
67  */
68 struct isl_generate_domain_data {
69         isl_ast_build *build;
70
71         isl_ast_graft_list *list;
72 };
73
74 static __isl_give isl_ast_graft_list *generate_next_level(
75         __isl_take isl_union_map *executed,
76         __isl_take isl_ast_build *build);
77 static __isl_give isl_ast_graft_list *generate_code(
78         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build,
79         int internal);
80
81 /* Generate an AST for a single domain based on
82  * the (non single valued) inverse schedule "executed".
83  *
84  * We extend the schedule with the iteration domain
85  * and continue generating through a call to generate_code.
86  *
87  * In particular, if executed has the form
88  *
89  *      S -> D
90  *
91  * then we continue generating code on
92  *
93  *      [S -> D] -> D
94  *
95  * The extended inverse schedule is clearly single valued
96  * ensuring that the nested generate_code will not reach this function,
97  * but will instead create calls to all elements of D that need
98  * to be executed from the current schedule domain.
99  */
100 static int generate_non_single_valued(__isl_take isl_map *executed,
101         struct isl_generate_domain_data *data)
102 {
103         isl_map *identity;
104         isl_ast_build *build;
105         isl_ast_graft_list *list;
106
107         build = isl_ast_build_copy(data->build);
108
109         identity = isl_set_identity(isl_map_range(isl_map_copy(executed)));
110         executed = isl_map_domain_product(executed, identity);
111         build = isl_ast_build_set_single_valued(build, 1);
112
113         list = generate_code(isl_union_map_from_map(executed), build, 1);
114
115         data->list = isl_ast_graft_list_concat(data->list, list);
116
117         return 0;
118 }
119
120 /* Call the at_each_domain callback, if requested by the user,
121  * after recording the current inverse schedule in the build.
122  */
123 static __isl_give isl_ast_graft *at_each_domain(__isl_take isl_ast_graft *graft,
124         __isl_keep isl_map *executed, __isl_keep isl_ast_build *build)
125 {
126         if (!graft || !build)
127                 return isl_ast_graft_free(graft);
128         if (!build->at_each_domain)
129                 return graft;
130
131         build = isl_ast_build_copy(build);
132         build = isl_ast_build_set_executed(build,
133                         isl_union_map_from_map(isl_map_copy(executed)));
134         if (!build)
135                 return isl_ast_graft_free(graft);
136
137         graft->node = build->at_each_domain(graft->node,
138                                         build, build->at_each_domain_user);
139         isl_ast_build_free(build);
140
141         if (!graft->node)
142                 graft = isl_ast_graft_free(graft);
143
144         return graft;
145 }
146
147 /* Generate an AST for a single domain based on
148  * the inverse schedule "executed".
149  *
150  * If there is more than one domain element associated to the current
151  * schedule "time", then we need to continue the generation process
152  * in generate_non_single_valued.
153  * Note that the inverse schedule being single-valued may depend
154  * on constraints that are only available in the original context
155  * domain specified by the user.  We therefore first introduce
156  * the constraints from data->build->domain.
157  * On the other hand, we only perform the test after having taken the gist
158  * of the domain as the resulting map is the one from which the call
159  * expression is constructed.  Using this map to construct the call
160  * expression usually yields simpler results.
161  * Because we perform the single-valuedness test on the gisted map,
162  * we may in rare cases fail to recognize that the inverse schedule
163  * is single-valued.  This becomes problematic if this happens
164  * from the recursive call through generate_non_single_valued
165  * as we would then end up in an infinite recursion.
166  * We therefore check if we are inside a call to generate_non_single_valued
167  * and revert to the ungisted map if the gisted map turns out not to be
168  * single-valued.
169  *
170  * Otherwise, we generate a call expression for the single executed
171  * domain element and put a guard around it based on the (simplified)
172  * domain of "executed".
173  *
174  * If the user has set an at_each_domain callback, it is called
175  * on the constructed call expression node.
176  */
177 static int generate_domain(__isl_take isl_map *executed, void *user)
178 {
179         struct isl_generate_domain_data *data = user;
180         isl_ast_graft *graft;
181         isl_ast_graft_list *list;
182         isl_set *guard;
183         isl_map *map;
184         int sv;
185
186         executed = isl_map_intersect_domain(executed,
187                                             isl_set_copy(data->build->domain));
188
189         executed = isl_map_coalesce(executed);
190         map = isl_map_copy(executed);
191         map = isl_ast_build_compute_gist_map_domain(data->build, map);
192         sv = isl_map_is_single_valued(map);
193         if (sv < 0)
194                 goto error;
195         if (!sv) {
196                 isl_map_free(map);
197                 if (data->build->single_valued)
198                         map = isl_map_copy(executed);
199                 else
200                         return generate_non_single_valued(executed, data);
201         }
202         guard = isl_map_domain(isl_map_copy(map));
203         guard = isl_set_coalesce(guard);
204         guard = isl_ast_build_compute_gist(data->build, guard);
205         graft = isl_ast_graft_alloc_domain(map, data->build);
206         graft = at_each_domain(graft, executed, data->build);
207
208         isl_map_free(executed);
209         graft = isl_ast_graft_add_guard(graft, guard, data->build);
210
211         list = isl_ast_graft_list_from_ast_graft(graft);
212         data->list = isl_ast_graft_list_concat(data->list, list);
213
214         return 0;
215 error:
216         isl_map_free(map);
217         isl_map_free(executed);
218         return -1;
219 }
220
221 /* Call build->create_leaf to a create "leaf" node in the AST,
222  * encapsulate the result in an isl_ast_graft and return the result
223  * as a 1-element list.
224  *
225  * Note that the node returned by the user may be an entire tree.
226  *
227  * Before we pass control to the user, we first clear some information
228  * from the build that is (presumbably) only meaningful
229  * for the current code generation.
230  * This includes the create_leaf callback itself, so we make a copy
231  * of the build first.
232  */
233 static __isl_give isl_ast_graft_list *call_create_leaf(
234         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build)
235 {
236         isl_ast_node *node;
237         isl_ast_graft *graft;
238         isl_ast_build *user_build;
239
240         user_build = isl_ast_build_copy(build);
241         user_build = isl_ast_build_set_executed(user_build, executed);
242         user_build = isl_ast_build_clear_local_info(user_build);
243         if (!user_build)
244                 node = NULL;
245         else
246                 node = build->create_leaf(user_build, build->create_leaf_user);
247         graft = isl_ast_graft_alloc(node, build);
248         isl_ast_build_free(build);
249         return isl_ast_graft_list_from_ast_graft(graft);
250 }
251
252 /* Generate an AST after having handled the complete schedule
253  * of this call to the code generator.
254  *
255  * If the user has specified a create_leaf callback, control
256  * is passed to the user in call_create_leaf.
257  *
258  * Otherwise, we generate one or more calls for each individual
259  * domain in generate_domain.
260  */
261 static __isl_give isl_ast_graft_list *generate_inner_level(
262         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build)
263 {
264         isl_ctx *ctx;
265         struct isl_generate_domain_data data = { build };
266
267         if (!build || !executed)
268                 goto error;
269
270         if (build->create_leaf)
271                 return call_create_leaf(executed, build);
272
273         ctx = isl_union_map_get_ctx(executed);
274         data.list = isl_ast_graft_list_alloc(ctx, 0);
275         if (isl_union_map_foreach_map(executed, &generate_domain, &data) < 0)
276                 data.list = isl_ast_graft_list_free(data.list);
277
278         if (0)
279 error:          data.list = NULL;
280         isl_ast_build_free(build);
281         isl_union_map_free(executed);
282         return data.list;
283 }
284
285 /* Call the before_each_for callback, if requested by the user.
286  */
287 static __isl_give isl_ast_node *before_each_for(__isl_take isl_ast_node *node,
288         __isl_keep isl_ast_build *build)
289 {
290         isl_id *id;
291
292         if (!node || !build)
293                 return isl_ast_node_free(node);
294         if (!build->before_each_for)
295                 return node;
296         id = build->before_each_for(build, build->before_each_for_user);
297         node = isl_ast_node_set_annotation(node, id);
298         return node;
299 }
300
301 /* Call the after_each_for callback, if requested by the user.
302  */
303 static __isl_give isl_ast_graft *after_each_for(__isl_keep isl_ast_graft *graft,
304         __isl_keep isl_ast_build *build)
305 {
306         if (!graft || !build)
307                 return isl_ast_graft_free(graft);
308         if (!build->after_each_for)
309                 return graft;
310         graft->node = build->after_each_for(graft->node, build,
311                                                 build->after_each_for_user);
312         if (!graft->node)
313                 return isl_ast_graft_free(graft);
314         return graft;
315 }
316
317 /* Plug in all the know values of the current and outer dimensions
318  * in the domain of "executed".  In principle, we only need to plug
319  * in the known value of the current dimension since the values of
320  * outer dimensions have been plugged in already.
321  * However, it turns out to be easier to just plug in all known values.
322  */
323 static __isl_give isl_union_map *plug_in_values(
324         __isl_take isl_union_map *executed, __isl_keep isl_ast_build *build)
325 {
326         return isl_ast_build_substitute_values_union_map_domain(build,
327                                                                     executed);
328 }
329
330 /* Check if the constraint "c" is a lower bound on dimension "pos",
331  * an upper bound, or independent of dimension "pos".
332  */
333 static int constraint_type(isl_constraint *c, int pos)
334 {
335         if (isl_constraint_is_lower_bound(c, isl_dim_set, pos))
336                 return 1;
337         if (isl_constraint_is_upper_bound(c, isl_dim_set, pos))
338                 return 2;
339         return 0;
340 }
341
342 /* Compare the types of the constraints "a" and "b",
343  * resulting in constraints that are independent of "depth"
344  * to be sorted before the lower bounds on "depth", which in
345  * turn are sorted before the upper bounds on "depth".
346  */
347 static int cmp_constraint(__isl_keep isl_constraint *a,
348         __isl_keep isl_constraint *b, void *user)
349 {
350         int *depth = user;
351         int t1 = constraint_type(a, *depth);
352         int t2 = constraint_type(b, *depth);
353
354         return t1 - t2;
355 }
356
357 /* Extract a lower bound on dimension "pos" from constraint "c".
358  *
359  * If the constraint is of the form
360  *
361  *      a x + f(...) >= 0
362  *
363  * then we essentially return
364  *
365  *      l = ceil(-f(...)/a)
366  *
367  * However, if the current dimension is strided, then we need to make
368  * sure that the lower bound we construct is of the form
369  *
370  *      f + s a
371  *
372  * with f the offset and s the stride.
373  * We therefore compute
374  *
375  *      f + s * ceil((l - f)/s)
376  */
377 static __isl_give isl_aff *lower_bound(__isl_keep isl_constraint *c,
378         int pos, __isl_keep isl_ast_build *build)
379 {
380         isl_aff *aff;
381
382         aff = isl_constraint_get_bound(c, isl_dim_set, pos);
383         aff = isl_aff_ceil(aff);
384
385         if (isl_ast_build_has_stride(build, pos)) {
386                 isl_aff *offset;
387                 isl_val *stride;
388
389                 offset = isl_ast_build_get_offset(build, pos);
390                 stride = isl_ast_build_get_stride(build, pos);
391
392                 aff = isl_aff_sub(aff, isl_aff_copy(offset));
393                 aff = isl_aff_scale_down_val(aff, isl_val_copy(stride));
394                 aff = isl_aff_ceil(aff);
395                 aff = isl_aff_scale_val(aff, stride);
396                 aff = isl_aff_add(aff, offset);
397         }
398
399         aff = isl_ast_build_compute_gist_aff(build, aff);
400
401         return aff;
402 }
403
404 /* Return the exact lower bound (or upper bound if "upper" is set)
405  * of "domain" as a piecewise affine expression.
406  *
407  * If we are computing a lower bound (of a strided dimension), then
408  * we need to make sure it is of the form
409  *
410  *      f + s a
411  *
412  * where f is the offset and s is the stride.
413  * We therefore need to include the stride constraint before computing
414  * the minimum.
415  */
416 static __isl_give isl_pw_aff *exact_bound(__isl_keep isl_set *domain,
417         __isl_keep isl_ast_build *build, int upper)
418 {
419         isl_set *stride;
420         isl_map *it_map;
421         isl_pw_aff *pa;
422         isl_pw_multi_aff *pma;
423
424         domain = isl_set_copy(domain);
425         if (!upper) {
426                 stride = isl_ast_build_get_stride_constraint(build);
427                 domain = isl_set_intersect(domain, stride);
428         }
429         it_map = isl_ast_build_map_to_iterator(build, domain);
430         if (upper)
431                 pma = isl_map_lexmax_pw_multi_aff(it_map);
432         else
433                 pma = isl_map_lexmin_pw_multi_aff(it_map);
434         pa = isl_pw_multi_aff_get_pw_aff(pma, 0);
435         isl_pw_multi_aff_free(pma);
436         pa = isl_ast_build_compute_gist_pw_aff(build, pa);
437         pa = isl_pw_aff_coalesce(pa);
438
439         return pa;
440 }
441
442 /* Extract a lower bound on dimension "pos" from each constraint
443  * in "constraints" and return the list of lower bounds.
444  * If "constraints" has zero elements, then we extract a lower bound
445  * from "domain" instead.
446  */
447 static __isl_give isl_pw_aff_list *lower_bounds(
448         __isl_keep isl_constraint_list *constraints, int pos,
449         __isl_keep isl_set *domain, __isl_keep isl_ast_build *build)
450 {
451         isl_ctx *ctx;
452         isl_pw_aff_list *list;
453         int i, n;
454
455         if (!build)
456                 return NULL;
457
458         n = isl_constraint_list_n_constraint(constraints);
459         if (n == 0) {
460                 isl_pw_aff *pa;
461                 pa = exact_bound(domain, build, 0);
462                 return isl_pw_aff_list_from_pw_aff(pa);
463         }
464
465         ctx = isl_ast_build_get_ctx(build);
466         list = isl_pw_aff_list_alloc(ctx,n);
467
468         for (i = 0; i < n; ++i) {
469                 isl_aff *aff;
470                 isl_constraint *c;
471
472                 c = isl_constraint_list_get_constraint(constraints, i);
473                 aff = lower_bound(c, pos, build);
474                 isl_constraint_free(c);
475                 list = isl_pw_aff_list_add(list, isl_pw_aff_from_aff(aff));
476         }
477
478         return list;
479 }
480
481 /* Extract an upper bound on dimension "pos" from each constraint
482  * in "constraints" and return the list of upper bounds.
483  * If "constraints" has zero elements, then we extract an upper bound
484  * from "domain" instead.
485  */
486 static __isl_give isl_pw_aff_list *upper_bounds(
487         __isl_keep isl_constraint_list *constraints, int pos,
488         __isl_keep isl_set *domain, __isl_keep isl_ast_build *build)
489 {
490         isl_ctx *ctx;
491         isl_pw_aff_list *list;
492         int i, n;
493
494         n = isl_constraint_list_n_constraint(constraints);
495         if (n == 0) {
496                 isl_pw_aff *pa;
497                 pa = exact_bound(domain, build, 1);
498                 return isl_pw_aff_list_from_pw_aff(pa);
499         }
500
501         ctx = isl_ast_build_get_ctx(build);
502         list = isl_pw_aff_list_alloc(ctx,n);
503
504         for (i = 0; i < n; ++i) {
505                 isl_aff *aff;
506                 isl_constraint *c;
507
508                 c = isl_constraint_list_get_constraint(constraints, i);
509                 aff = isl_constraint_get_bound(c, isl_dim_set, pos);
510                 isl_constraint_free(c);
511                 aff = isl_aff_floor(aff);
512                 list = isl_pw_aff_list_add(list, isl_pw_aff_from_aff(aff));
513         }
514
515         return list;
516 }
517
518 /* Return an isl_ast_expr that performs the reduction of type "type"
519  * on AST expressions corresponding to the elements in "list".
520  *
521  * The list is assumed to contain at least one element.
522  * If the list contains exactly one element, then the returned isl_ast_expr
523  * simply computes that affine expression.
524  */
525 static __isl_give isl_ast_expr *reduce_list(enum isl_ast_op_type type,
526         __isl_keep isl_pw_aff_list *list, __isl_keep isl_ast_build *build)
527 {
528         int i, n;
529         isl_ctx *ctx;
530         isl_ast_expr *expr;
531
532         if (!list)
533                 return NULL;
534
535         n = isl_pw_aff_list_n_pw_aff(list);
536
537         if (n == 1)
538                 return isl_ast_build_expr_from_pw_aff_internal(build,
539                                 isl_pw_aff_list_get_pw_aff(list, 0));
540
541         ctx = isl_pw_aff_list_get_ctx(list);
542         expr = isl_ast_expr_alloc_op(ctx, type, n);
543         if (!expr)
544                 return NULL;
545
546         for (i = 0; i < n; ++i) {
547                 isl_ast_expr *expr_i;
548
549                 expr_i = isl_ast_build_expr_from_pw_aff_internal(build,
550                                 isl_pw_aff_list_get_pw_aff(list, i));
551                 if (!expr_i)
552                         return isl_ast_expr_free(expr);
553                 expr->u.op.args[i] = expr_i;
554         }
555
556         return expr;
557 }
558
559 /* Add a guard to "graft" based on "bound" in the case of a degenerate
560  * level (including the special case of an eliminated level).
561  *
562  * We eliminate the current dimension, simplify the result in the current
563  * build and add the result as guards to the graft.
564  *
565  * Note that we cannot simply drop the constraints on the current dimension
566  * even in the eliminated case, because the single affine expression may
567  * not be explicitly available in "bounds".  Moreover, the single affine
568  * expression may only be defined on a subset of the build domain,
569  * so we do in some cases need to insert a guard even in the eliminated case.
570  */
571 static __isl_give isl_ast_graft *add_degenerate_guard(
572         __isl_take isl_ast_graft *graft, __isl_keep isl_basic_set *bounds,
573         __isl_keep isl_ast_build *build)
574 {
575         int depth;
576         isl_set *dom;
577
578         depth = isl_ast_build_get_depth(build);
579
580         dom = isl_set_from_basic_set(isl_basic_set_copy(bounds));
581         if (isl_ast_build_has_stride(build, depth)) {
582                 isl_set *stride;
583
584                 stride = isl_ast_build_get_stride_constraint(build);
585                 dom = isl_set_intersect(dom, stride);
586         }
587         dom = isl_set_eliminate(dom, isl_dim_set, depth, 1);
588         dom = isl_ast_build_compute_gist(build, dom);
589
590         graft = isl_ast_graft_add_guard(graft, dom, build);
591
592         return graft;
593 }
594
595 /* Update "graft" based on "bounds" for the eliminated case.
596  *
597  * In the eliminated case, no for node is created, so we only need
598  * to check if "bounds" imply any guards that need to be inserted.
599  */
600 static __isl_give isl_ast_graft *refine_eliminated(
601         __isl_take isl_ast_graft *graft, __isl_keep isl_basic_set *bounds,
602         __isl_keep isl_ast_build *build)
603 {
604         return add_degenerate_guard(graft, bounds, build);
605 }
606
607 /* Update "graft" based on "bounds" and "sub_build" for the degenerate case.
608  *
609  * "build" is the build in which graft->node was created
610  * "sub_build" contains information about the current level itself,
611  * including the single value attained.
612  *
613  * We first set the initialization part of the for loop to the single
614  * value attained by the current dimension.
615  * The increment and condition are not strictly needed as the are known
616  * to be "1" and "iterator <= value" respectively.
617  * Then we set the size of the iterator and
618  * check if "bounds" imply any guards that need to be inserted.
619  */
620 static __isl_give isl_ast_graft *refine_degenerate(
621         __isl_take isl_ast_graft *graft, __isl_keep isl_basic_set *bounds,
622         __isl_keep isl_ast_build *build,
623         __isl_keep isl_ast_build *sub_build)
624 {
625         isl_pw_aff *value;
626
627         if (!graft || !sub_build)
628                 return isl_ast_graft_free(graft);
629
630         value = isl_pw_aff_copy(sub_build->value);
631
632         graft->node->u.f.init = isl_ast_build_expr_from_pw_aff_internal(build,
633                                                 value);
634         if (!graft->node->u.f.init)
635                 return isl_ast_graft_free(graft);
636
637         graft = add_degenerate_guard(graft, bounds, build);
638
639         return graft;
640 }
641
642 /* Return the intersection of constraints in "list" as a set.
643  */
644 static __isl_give isl_set *intersect_constraints(
645         __isl_keep isl_constraint_list *list)
646 {
647         int i, n;
648         isl_basic_set *bset;
649
650         n = isl_constraint_list_n_constraint(list);
651         if (n < 1)
652                 isl_die(isl_constraint_list_get_ctx(list), isl_error_internal,
653                         "expecting at least one constraint", return NULL);
654
655         bset = isl_basic_set_from_constraint(
656                                 isl_constraint_list_get_constraint(list, 0));
657         for (i = 1; i < n; ++i) {
658                 isl_basic_set *bset_i;
659
660                 bset_i = isl_basic_set_from_constraint(
661                                 isl_constraint_list_get_constraint(list, i));
662                 bset = isl_basic_set_intersect(bset, bset_i);
663         }
664
665         return isl_set_from_basic_set(bset);
666 }
667
668 /* Compute the constraints on the outer dimensions enforced by
669  * graft->node and add those constraints to graft->enforced,
670  * in case the upper bound is expressed as a set "upper".
671  *
672  * In particular, if l(...) is a lower bound in "lower", and
673  *
674  *      -a i + f(...) >= 0              or      a i <= f(...)
675  *
676  * is an upper bound ocnstraint on the current dimension i,
677  * then the for loop enforces the constraint
678  *
679  *      -a l(...) + f(...) >= 0         or      a l(...) <= f(...)
680  *
681  * We therefore simply take each lower bound in turn, plug it into
682  * the upper bounds and compute the intersection over all lower bounds.
683  *
684  * If a lower bound is a rational expression, then
685  * isl_basic_set_preimage_multi_aff will force this rational
686  * expression to have only integer values.  However, the loop
687  * itself does not enforce this integrality constraint.  We therefore
688  * use the ceil of the lower bounds instead of the lower bounds themselves.
689  * Other constraints will make sure that the for loop is only executed
690  * when each of the lower bounds attains an integral value.
691  * In particular, potentially rational values only occur in
692  * lower_bound if the offset is a (seemingly) rational expression,
693  * but then outer conditions will make sure that this rational expression
694  * only attains integer values.
695  */
696 static __isl_give isl_ast_graft *set_enforced_from_set(
697         __isl_take isl_ast_graft *graft,
698         __isl_keep isl_pw_aff_list *lower, int pos, __isl_keep isl_set *upper)
699 {
700         isl_space *space;
701         isl_basic_set *enforced;
702         isl_pw_multi_aff *pma;
703         int i, n;
704
705         if (!graft || !lower)
706                 return isl_ast_graft_free(graft);
707
708         space = isl_set_get_space(upper);
709         enforced = isl_basic_set_universe(isl_space_copy(space));
710
711         space = isl_space_map_from_set(space);
712         pma = isl_pw_multi_aff_identity(space);
713
714         n = isl_pw_aff_list_n_pw_aff(lower);
715         for (i = 0; i < n; ++i) {
716                 isl_pw_aff *pa;
717                 isl_set *enforced_i;
718                 isl_basic_set *hull;
719                 isl_pw_multi_aff *pma_i;
720
721                 pa = isl_pw_aff_list_get_pw_aff(lower, i);
722                 pa = isl_pw_aff_ceil(pa);
723                 pma_i = isl_pw_multi_aff_copy(pma);
724                 pma_i = isl_pw_multi_aff_set_pw_aff(pma_i, pos, pa);
725                 enforced_i = isl_set_copy(upper);
726                 enforced_i = isl_set_preimage_pw_multi_aff(enforced_i, pma_i);
727                 hull = isl_set_simple_hull(enforced_i);
728                 enforced = isl_basic_set_intersect(enforced, hull);
729         }
730
731         isl_pw_multi_aff_free(pma);
732
733         graft = isl_ast_graft_enforce(graft, enforced);
734
735         return graft;
736 }
737
738 /* Compute the constraints on the outer dimensions enforced by
739  * graft->node and add those constraints to graft->enforced,
740  * in case the upper bound is expressed as
741  * a list of affine expressions "upper".
742  *
743  * The enforced condition is that each lower bound expression is less
744  * than or equal to each upper bound expression.
745  */
746 static __isl_give isl_ast_graft *set_enforced_from_list(
747         __isl_take isl_ast_graft *graft,
748         __isl_keep isl_pw_aff_list *lower, __isl_keep isl_pw_aff_list *upper)
749 {
750         isl_set *cond;
751         isl_basic_set *enforced;
752
753         lower = isl_pw_aff_list_copy(lower);
754         upper = isl_pw_aff_list_copy(upper);
755         cond = isl_pw_aff_list_le_set(lower, upper);
756         enforced = isl_set_simple_hull(cond);
757         graft = isl_ast_graft_enforce(graft, enforced);
758
759         return graft;
760 }
761
762 /* Does "aff" have a negative constant term?
763  */
764 static int aff_constant_is_negative(__isl_take isl_set *set,
765         __isl_take isl_aff *aff, void *user)
766 {
767         int *neg = user;
768         isl_int v;
769
770         isl_int_init(v);
771         isl_aff_get_constant(aff, &v);
772         *neg = isl_int_is_neg(v);
773         isl_int_clear(v);
774         isl_set_free(set);
775         isl_aff_free(aff);
776
777         return *neg ? 0 : -1;
778 }
779
780 /* Does "pa" have a negative constant term over its entire domain?
781  */
782 static int pw_aff_constant_is_negative(__isl_take isl_pw_aff *pa, void *user)
783 {
784         int r;
785         int *neg = user;
786
787         r = isl_pw_aff_foreach_piece(pa, &aff_constant_is_negative, user);
788         isl_pw_aff_free(pa);
789
790         return *neg ? 0 : -1;
791 }
792
793 /* Does each element in "list" have a negative constant term?
794  *
795  * The callback terminates the iteration as soon an element has been
796  * found that does not have a negative constant term.
797  */
798 static int list_constant_is_negative(__isl_keep isl_pw_aff_list *list)
799 {
800         int neg = 1;
801
802         if (isl_pw_aff_list_foreach(list,
803                                 &pw_aff_constant_is_negative, &neg) < 0 && neg)
804                 return -1;
805
806         return neg;
807 }
808
809 /* Add 1 to each of the elements in "list", where each of these elements
810  * is defined over the internal schedule space of "build".
811  */
812 static __isl_give isl_pw_aff_list *list_add_one(
813         __isl_take isl_pw_aff_list *list, __isl_keep isl_ast_build *build)
814 {
815         int i, n;
816         isl_space *space;
817         isl_aff *aff;
818         isl_pw_aff *one;
819
820         space = isl_ast_build_get_space(build, 1);
821         aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
822         aff = isl_aff_add_constant_si(aff, 1);
823         one = isl_pw_aff_from_aff(aff);
824
825         n = isl_pw_aff_list_n_pw_aff(list);
826         for (i = 0; i < n; ++i) {
827                 isl_pw_aff *pa;
828                 pa = isl_pw_aff_list_get_pw_aff(list, i);
829                 pa = isl_pw_aff_add(pa, isl_pw_aff_copy(one));
830                 list = isl_pw_aff_list_set_pw_aff(list, i, pa);
831         }
832
833         isl_pw_aff_free(one);
834
835         return list;
836 }
837
838 /* Set the condition part of the for node graft->node in case
839  * the upper bound is represented as a list of piecewise affine expressions.
840  *
841  * In particular, set the condition to
842  *
843  *      iterator <= min(list of upper bounds)
844  *
845  * If each of the upper bounds has a negative constant term, then
846  * set the condition to
847  *
848  *      iterator < min(list of (upper bound + 1)s)
849  *
850  */
851 static __isl_give isl_ast_graft *set_for_cond_from_list(
852         __isl_take isl_ast_graft *graft, __isl_keep isl_pw_aff_list *list,
853         __isl_keep isl_ast_build *build)
854 {
855         int neg;
856         isl_ast_expr *bound, *iterator, *cond;
857         enum isl_ast_op_type type = isl_ast_op_le;
858
859         if (!graft || !list)
860                 return isl_ast_graft_free(graft);
861
862         neg = list_constant_is_negative(list);
863         if (neg < 0)
864                 return isl_ast_graft_free(graft);
865         list = isl_pw_aff_list_copy(list);
866         if (neg) {
867                 list = list_add_one(list, build);
868                 type = isl_ast_op_lt;
869         }
870
871         bound = reduce_list(isl_ast_op_min, list, build);
872         iterator = isl_ast_expr_copy(graft->node->u.f.iterator);
873         cond = isl_ast_expr_alloc_binary(type, iterator, bound);
874         graft->node->u.f.cond = cond;
875
876         isl_pw_aff_list_free(list);
877         if (!graft->node->u.f.cond)
878                 return isl_ast_graft_free(graft);
879         return graft;
880 }
881
882 /* Set the condition part of the for node graft->node in case
883  * the upper bound is represented as a set.
884  */
885 static __isl_give isl_ast_graft *set_for_cond_from_set(
886         __isl_take isl_ast_graft *graft, __isl_keep isl_set *set,
887         __isl_keep isl_ast_build *build)
888 {
889         isl_ast_expr *cond;
890
891         if (!graft)
892                 return NULL;
893
894         cond = isl_ast_build_expr_from_set(build, isl_set_copy(set));
895         graft->node->u.f.cond = cond;
896         if (!graft->node->u.f.cond)
897                 return isl_ast_graft_free(graft);
898         return graft;
899 }
900
901 /* Construct an isl_ast_expr for the increment (i.e., stride) of
902  * the current dimension.
903  */
904 static __isl_give isl_ast_expr *for_inc(__isl_keep isl_ast_build *build)
905 {
906         int depth;
907         isl_val *v;
908         isl_ctx *ctx;
909
910         if (!build)
911                 return NULL;
912         ctx = isl_ast_build_get_ctx(build);
913         depth = isl_ast_build_get_depth(build);
914
915         if (!isl_ast_build_has_stride(build, depth))
916                 return isl_ast_expr_alloc_int_si(ctx, 1);
917
918         v = isl_ast_build_get_stride(build, depth);
919         return isl_ast_expr_from_val(v);
920 }
921
922 /* Should we express the loop condition as
923  *
924  *      iterator <= min(list of upper bounds)
925  *
926  * or as a conjunction of constraints?
927  *
928  * The first is constructed from a list of upper bounds.
929  * The second is constructed from a set.
930  *
931  * If there are no upper bounds in "constraints", then this could mean
932  * that "domain" simply doesn't have an upper bound or that we didn't
933  * pick any upper bound.  In the first case, we want to generate the
934  * loop condition as a(n empty) conjunction of constraints
935  * In the second case, we will compute
936  * a single upper bound from "domain" and so we use the list form.
937  *
938  * If there are upper bounds in "constraints",
939  * then we use the list form iff the atomic_upper_bound option is set.
940  */
941 static int use_upper_bound_list(isl_ctx *ctx, int n_upper,
942         __isl_keep isl_set *domain, int depth)
943 {
944         if (n_upper > 0)
945                 return isl_options_get_ast_build_atomic_upper_bound(ctx);
946         else
947                 return isl_set_dim_has_upper_bound(domain, isl_dim_set, depth);
948 }
949
950 /* Fill in the expressions of the for node in graft->node.
951  *
952  * In particular,
953  * - set the initialization part of the loop to the maximum of the lower bounds
954  * - set the size of the iterator based on the values attained by the iterator
955  * - extract the increment from the stride of the current dimension
956  * - construct the for condition either based on a list of upper bounds
957  *      or on a set of upper bound constraints.
958  */
959 static __isl_give isl_ast_graft *set_for_node_expressions(
960         __isl_take isl_ast_graft *graft, __isl_keep isl_pw_aff_list *lower,
961         int use_list, __isl_keep isl_pw_aff_list *upper_list,
962         __isl_keep isl_set *upper_set, __isl_keep isl_ast_build *build)
963 {
964         isl_ast_node *node;
965
966         if (!graft)
967                 return NULL;
968
969         build = isl_ast_build_copy(build);
970         build = isl_ast_build_set_enforced(build,
971                                         isl_ast_graft_get_enforced(graft));
972
973         node = graft->node;
974         node->u.f.init = reduce_list(isl_ast_op_max, lower, build);
975         node->u.f.inc = for_inc(build);
976
977         if (use_list)
978                 graft = set_for_cond_from_list(graft, upper_list, build);
979         else
980                 graft = set_for_cond_from_set(graft, upper_set, build);
981
982         isl_ast_build_free(build);
983
984         if (!node->u.f.iterator || !node->u.f.init ||
985             !node->u.f.cond || !node->u.f.inc)
986                 return isl_ast_graft_free(graft);
987
988         return graft;
989 }
990
991 /* Update "graft" based on "bounds" and "domain" for the generic,
992  * non-degenerate, case.
993  *
994  * "c_lower" and "c_upper" contain the lower and upper bounds
995  * that the loop node should express.
996  * "domain" is the subset of the intersection of the constraints
997  * for which some code is executed.
998  *
999  * There may be zero lower bounds or zero upper bounds in "constraints"
1000  * in case the list of constraints was created
1001  * based on the atomic option or based on separation with explicit bounds.
1002  * In that case, we use "domain" to derive lower and/or upper bounds.
1003  *
1004  * We first compute a list of one or more lower bounds.
1005  *
1006  * Then we decide if we want to express the condition as
1007  *
1008  *      iterator <= min(list of upper bounds)
1009  *
1010  * or as a conjunction of constraints.
1011  *
1012  * The set of enforced constraints is then computed either based on
1013  * a list of upper bounds or on a set of upper bound constraints.
1014  * We do not compute any enforced constraints if we were forced
1015  * to compute a lower or upper bound using exact_bound.  The domains
1016  * of the resulting expressions may imply some bounds on outer dimensions
1017  * that we do not want to appear in the enforced constraints since
1018  * they are not actually enforced by the corresponding code.
1019  *
1020  * Finally, we fill in the expressions of the for node.
1021  */
1022 static __isl_give isl_ast_graft *refine_generic_bounds(
1023         __isl_take isl_ast_graft *graft,
1024         __isl_take isl_constraint_list *c_lower,
1025         __isl_take isl_constraint_list *c_upper,
1026         __isl_keep isl_set *domain, __isl_keep isl_ast_build *build)
1027 {
1028         int depth;
1029         isl_ctx *ctx;
1030         isl_pw_aff_list *lower;
1031         int use_list;
1032         isl_set *upper_set = NULL;
1033         isl_pw_aff_list *upper_list = NULL;
1034         int n_lower, n_upper;
1035
1036         if (!graft || !c_lower || !c_upper || !build)
1037                 goto error;
1038
1039         depth = isl_ast_build_get_depth(build);
1040         ctx = isl_ast_graft_get_ctx(graft);
1041
1042         n_lower = isl_constraint_list_n_constraint(c_lower);
1043         n_upper = isl_constraint_list_n_constraint(c_upper);
1044
1045         use_list = use_upper_bound_list(ctx, n_upper, domain, depth);
1046
1047         lower = lower_bounds(c_lower, depth, domain, build);
1048
1049         if (use_list)
1050                 upper_list = upper_bounds(c_upper, depth, domain, build);
1051         else if (n_upper > 0)
1052                 upper_set = intersect_constraints(c_upper);
1053         else
1054                 upper_set = isl_set_universe(isl_set_get_space(domain));
1055
1056         if (n_lower == 0 || n_upper == 0)
1057                 ;
1058         else if (use_list)
1059                 graft = set_enforced_from_list(graft, lower, upper_list);
1060         else
1061                 graft = set_enforced_from_set(graft, lower, depth, upper_set);
1062
1063         graft = set_for_node_expressions(graft, lower, use_list, upper_list,
1064                                         upper_set, build);
1065
1066         isl_pw_aff_list_free(lower);
1067         isl_pw_aff_list_free(upper_list);
1068         isl_set_free(upper_set);
1069         isl_constraint_list_free(c_lower);
1070         isl_constraint_list_free(c_upper);
1071
1072         return graft;
1073 error:
1074         isl_constraint_list_free(c_lower);
1075         isl_constraint_list_free(c_upper);
1076         return isl_ast_graft_free(graft);
1077 }
1078
1079 /* Internal data structure used inside count_constraints to keep
1080  * track of the number of constraints that are independent of dimension "pos",
1081  * the lower bounds in "pos" and the upper bounds in "pos".
1082  */
1083 struct isl_ast_count_constraints_data {
1084         int pos;
1085
1086         int n_indep;
1087         int n_lower;
1088         int n_upper;
1089 };
1090
1091 /* Increment data->n_indep, data->lower or data->upper depending
1092  * on whether "c" is independenct of dimensions data->pos,
1093  * a lower bound or an upper bound.
1094  */
1095 static int count_constraints(__isl_take isl_constraint *c, void *user)
1096 {
1097         struct isl_ast_count_constraints_data *data = user;
1098
1099         if (isl_constraint_is_lower_bound(c, isl_dim_set, data->pos))
1100                 data->n_lower++;
1101         else if (isl_constraint_is_upper_bound(c, isl_dim_set, data->pos))
1102                 data->n_upper++;
1103         else
1104                 data->n_indep++;
1105
1106         isl_constraint_free(c);
1107
1108         return 0;
1109 }
1110
1111 /* Update "graft" based on "bounds" and "domain" for the generic,
1112  * non-degenerate, case.
1113  *
1114  * "list" respresent the list of bounds that need to be encoded by
1115  * the for loop (or a guard around the for loop).
1116  * "domain" is the subset of the intersection of the constraints
1117  * for which some code is executed.
1118  * "build" is the build in which graft->node was created.
1119  *
1120  * We separate lower bounds, upper bounds and constraints that
1121  * are independent of the loop iterator.
1122  *
1123  * The actual for loop bounds are generated in refine_generic_bounds.
1124  * If there are any constraints that are independent of the loop iterator,
1125  * we need to put a guard around the for loop (which may get hoisted up
1126  * to higher levels) and we call refine_generic_bounds in a build
1127  * where this guard is enforced.
1128  */
1129 static __isl_give isl_ast_graft *refine_generic_split(
1130         __isl_take isl_ast_graft *graft, __isl_take isl_constraint_list *list,
1131         __isl_keep isl_set *domain, __isl_keep isl_ast_build *build)
1132 {
1133         isl_ast_build *for_build;
1134         isl_set *guard;
1135         struct isl_ast_count_constraints_data data;
1136         isl_constraint_list *lower;
1137         isl_constraint_list *upper;
1138
1139         if (!list)
1140                 return isl_ast_graft_free(graft);
1141
1142         data.pos = isl_ast_build_get_depth(build);
1143
1144         list = isl_constraint_list_sort(list, &cmp_constraint, &data.pos);
1145         if (!list)
1146                 return isl_ast_graft_free(graft);
1147
1148         data.n_indep = data.n_lower = data.n_upper = 0;
1149         if (isl_constraint_list_foreach(list, &count_constraints, &data) < 0) {
1150                 isl_constraint_list_free(list);
1151                 return isl_ast_graft_free(graft);
1152         }
1153
1154         lower = isl_constraint_list_copy(list);
1155         lower = isl_constraint_list_drop(lower, 0, data.n_indep);
1156         upper = isl_constraint_list_copy(lower);
1157         lower = isl_constraint_list_drop(lower, data.n_lower, data.n_upper);
1158         upper = isl_constraint_list_drop(upper, 0, data.n_lower);
1159
1160         if (data.n_indep == 0) {
1161                 isl_constraint_list_free(list);
1162                 return refine_generic_bounds(graft, lower, upper,
1163                                                 domain, build);
1164         }
1165
1166         list = isl_constraint_list_drop(list, data.n_indep,
1167                                         data.n_lower + data.n_upper);
1168         guard = intersect_constraints(list);
1169         isl_constraint_list_free(list);
1170
1171         for_build = isl_ast_build_copy(build);
1172         for_build = isl_ast_build_restrict_pending(for_build,
1173                                                 isl_set_copy(guard));
1174         graft = refine_generic_bounds(graft, lower, upper, domain, for_build);
1175         isl_ast_build_free(for_build);
1176
1177         graft = isl_ast_graft_add_guard(graft, guard, build);
1178
1179         return graft;
1180 }
1181
1182 /* Add the guard implied by the current stride constraint (if any),
1183  * but not (necessarily) enforced by the generated AST to "graft".
1184  */
1185 static __isl_give isl_ast_graft *add_stride_guard(
1186         __isl_take isl_ast_graft *graft, __isl_keep isl_ast_build *build)
1187 {
1188         int depth;
1189         isl_set *dom;
1190
1191         depth = isl_ast_build_get_depth(build);
1192         if (!isl_ast_build_has_stride(build, depth))
1193                 return graft;
1194
1195         dom = isl_ast_build_get_stride_constraint(build);
1196         dom = isl_set_eliminate(dom, isl_dim_set, depth, 1);
1197         dom = isl_ast_build_compute_gist(build, dom);
1198
1199         graft = isl_ast_graft_add_guard(graft, dom, build);
1200
1201         return graft;
1202 }
1203
1204 /* Update "graft" based on "bounds" and "domain" for the generic,
1205  * non-degenerate, case.
1206  *
1207  * "bounds" respresent the bounds that need to be encoded by
1208  * the for loop (or a guard around the for loop).
1209  * "domain" is the subset of "bounds" for which some code is executed.
1210  * "build" is the build in which graft->node was created.
1211  *
1212  * We break up "bounds" into a list of constraints and continue with
1213  * refine_generic_split.
1214  */
1215 static __isl_give isl_ast_graft *refine_generic(
1216         __isl_take isl_ast_graft *graft,
1217         __isl_keep isl_basic_set *bounds, __isl_keep isl_set *domain,
1218         __isl_keep isl_ast_build *build)
1219 {
1220         isl_constraint_list *list;
1221
1222         if (!build || !graft)
1223                 return isl_ast_graft_free(graft);
1224
1225         bounds = isl_basic_set_copy(bounds);
1226         bounds = isl_ast_build_compute_gist_basic_set(build, bounds);
1227         list = isl_constraint_list_from_basic_set(bounds);
1228
1229         graft = refine_generic_split(graft, list, domain, build);
1230         graft = add_stride_guard(graft, build);
1231
1232         return graft;
1233 }
1234
1235 /* Create a for node for the current level.
1236  *
1237  * Mark the for node degenerate if "degenerate" is set.
1238  */
1239 static __isl_give isl_ast_node *create_for(__isl_keep isl_ast_build *build,
1240         int degenerate)
1241 {
1242         int depth;
1243         isl_id *id;
1244         isl_ast_node *node;
1245
1246         if (!build)
1247                 return NULL;
1248
1249         depth = isl_ast_build_get_depth(build);
1250         id = isl_ast_build_get_iterator_id(build, depth);
1251         node = isl_ast_node_alloc_for(id);
1252         if (degenerate)
1253                 node = isl_ast_node_for_mark_degenerate(node);
1254
1255         return node;
1256 }
1257
1258 /* Create an AST node for the current dimension based on
1259  * the schedule domain "bounds" and return the node encapsulated
1260  * in an isl_ast_graft.
1261  *
1262  * "executed" is the current inverse schedule, taking into account
1263  * the bounds in "bounds"
1264  * "domain" is the domain of "executed", with inner dimensions projected out.
1265  * It may be a strict subset of "bounds" in case "bounds" was created
1266  * based on the atomic option or based on separation with explicit bounds.
1267  *
1268  * "domain" may satisfy additional equalities that result
1269  * from intersecting "executed" with "bounds" in add_node.
1270  * It may also satisfy some global constraints that were dropped out because
1271  * we performed separation with explicit bounds.
1272  * The very first step is then to copy these constraints to "bounds".
1273  *
1274  * Since we may be calling before_each_for and after_each_for
1275  * callbacks, we record the current inverse schedule in the build.
1276  *
1277  * We consider three builds,
1278  * "build" is the one in which the current level is created,
1279  * "body_build" is the build in which the next level is created,
1280  * "sub_build" is essentially the same as "body_build", except that
1281  * the depth has not been increased yet.
1282  *
1283  * "build" already contains information (in strides and offsets)
1284  * about the strides at the current level, but this information is not
1285  * reflected in the build->domain.
1286  * We first add this information and the "bounds" to the sub_build->domain.
1287  * isl_ast_build_set_loop_bounds checks whether the current dimension attains
1288  * only a single value and whether this single value can be represented using
1289  * a single affine expression.
1290  * In the first case, the current level is considered "degenerate".
1291  * In the second, sub-case, the current level is considered "eliminated".
1292  * Eliminated level don't need to be reflected in the AST since we can
1293  * simply plug in the affine expression.  For degenerate, but non-eliminated,
1294  * levels, we do introduce a for node, but mark is as degenerate so that
1295  * it can be printed as an assignment of the single value to the loop
1296  * "iterator".
1297  *
1298  * If the current level is eliminated, we explicitly plug in the value
1299  * for the current level found by isl_ast_build_set_loop_bounds in the
1300  * inverse schedule.  This ensures that if we are working on a slice
1301  * of the domain based on information available in the inverse schedule
1302  * and the build domain, that then this information is also reflected
1303  * in the inverse schedule.  This operation also eliminates the current
1304  * dimension from the inverse schedule making sure no inner dimensions depend
1305  * on the current dimension.  Otherwise, we create a for node, marking
1306  * it degenerate if appropriate.  The initial for node is still incomplete
1307  * and will be completed in either refine_degenerate or refine_generic.
1308  *
1309  * We then generate a sequence of grafts for the next level,
1310  * create a surrounding graft for the current level and insert
1311  * the for node we created (if the current level is not eliminated).
1312  *
1313  * Finally, we set the bounds of the for loop and insert guards
1314  * (either in the AST or in the graft) in one of
1315  * refine_eliminated, refine_degenerate or refine_generic.
1316  */
1317 static __isl_give isl_ast_graft *create_node_scaled(
1318         __isl_take isl_union_map *executed,
1319         __isl_take isl_basic_set *bounds, __isl_take isl_set *domain,
1320         __isl_take isl_ast_build *build)
1321 {
1322         int depth;
1323         int degenerate, eliminated;
1324         isl_basic_set *hull;
1325         isl_ast_node *node = NULL;
1326         isl_ast_graft *graft;
1327         isl_ast_graft_list *children;
1328         isl_ast_build *sub_build;
1329         isl_ast_build *body_build;
1330
1331         domain = isl_ast_build_eliminate_divs(build, domain);
1332         domain = isl_set_detect_equalities(domain);
1333         hull = isl_set_unshifted_simple_hull(isl_set_copy(domain));
1334         bounds = isl_basic_set_intersect(bounds, hull);
1335         build = isl_ast_build_set_executed(build, isl_union_map_copy(executed));
1336
1337         depth = isl_ast_build_get_depth(build);
1338         sub_build = isl_ast_build_copy(build);
1339         sub_build = isl_ast_build_include_stride(sub_build);
1340         sub_build = isl_ast_build_set_loop_bounds(sub_build,
1341                                                 isl_basic_set_copy(bounds));
1342         degenerate = isl_ast_build_has_value(sub_build);
1343         eliminated = isl_ast_build_has_affine_value(sub_build, depth);
1344         if (degenerate < 0 || eliminated < 0)
1345                 executed = isl_union_map_free(executed);
1346         if (eliminated)
1347                 executed = plug_in_values(executed, sub_build);
1348         else
1349                 node = create_for(build, degenerate);
1350
1351         body_build = isl_ast_build_copy(sub_build);
1352         body_build = isl_ast_build_increase_depth(body_build);
1353         if (!eliminated)
1354                 node = before_each_for(node, body_build);
1355         children = generate_next_level(executed,
1356                                     isl_ast_build_copy(body_build));
1357
1358         graft = isl_ast_graft_alloc_level(children, build, sub_build);
1359         if (!eliminated)
1360                 graft = isl_ast_graft_insert_for(graft, node);
1361         if (eliminated)
1362                 graft = refine_eliminated(graft, bounds, build);
1363         else if (degenerate)
1364                 graft = refine_degenerate(graft, bounds, build, sub_build);
1365         else
1366                 graft = refine_generic(graft, bounds, domain, build);
1367         if (!eliminated)
1368                 graft = after_each_for(graft, body_build);
1369
1370         isl_ast_build_free(body_build);
1371         isl_ast_build_free(sub_build);
1372         isl_ast_build_free(build);
1373         isl_basic_set_free(bounds);
1374         isl_set_free(domain);
1375
1376         return graft;
1377 }
1378
1379 /* Internal data structure for checking if all constraints involving
1380  * the input dimension "depth" are such that the other coefficients
1381  * are multiples of "m", reducing "m" if they are not.
1382  * If "m" is reduced all the way down to "1", then the check has failed
1383  * and we break out of the iteration.
1384  */
1385 struct isl_check_scaled_data {
1386         int depth;
1387         isl_val *m;
1388 };
1389
1390 /* If constraint "c" involves the input dimension data->depth,
1391  * then make sure that all the other coefficients are multiples of data->m,
1392  * reducing data->m if needed.
1393  * Break out of the iteration if data->m has become equal to "1".
1394  */
1395 static int constraint_check_scaled(__isl_take isl_constraint *c, void *user)
1396 {
1397         struct isl_check_scaled_data *data = user;
1398         int i, j, n;
1399         enum isl_dim_type t[] = { isl_dim_param, isl_dim_in, isl_dim_out,
1400                                     isl_dim_div };
1401
1402         if (!isl_constraint_involves_dims(c, isl_dim_in, data->depth, 1)) {
1403                 isl_constraint_free(c);
1404                 return 0;
1405         }
1406
1407         for (i = 0; i < 4; ++i) {
1408                 n = isl_constraint_dim(c, t[i]);
1409                 for (j = 0; j < n; ++j) {
1410                         isl_val *d;
1411
1412                         if (t[i] == isl_dim_in && j == data->depth)
1413                                 continue;
1414                         if (!isl_constraint_involves_dims(c, t[i], j, 1))
1415                                 continue;
1416                         d = isl_constraint_get_coefficient_val(c, t[i], j);
1417                         data->m = isl_val_gcd(data->m, d);
1418                         if (isl_val_is_one(data->m))
1419                                 break;
1420                 }
1421                 if (j < n)
1422                         break;
1423         }
1424
1425         isl_constraint_free(c);
1426
1427         return i < 4 ? -1 : 0;
1428 }
1429
1430 /* For each constraint of "bmap" that involves the input dimension data->depth,
1431  * make sure that all the other coefficients are multiples of data->m,
1432  * reducing data->m if needed.
1433  * Break out of the iteration if data->m has become equal to "1".
1434  */
1435 static int basic_map_check_scaled(__isl_take isl_basic_map *bmap, void *user)
1436 {
1437         int r;
1438
1439         r = isl_basic_map_foreach_constraint(bmap,
1440                                                 &constraint_check_scaled, user);
1441         isl_basic_map_free(bmap);
1442
1443         return r;
1444 }
1445
1446 /* For each constraint of "map" that involves the input dimension data->depth,
1447  * make sure that all the other coefficients are multiples of data->m,
1448  * reducing data->m if needed.
1449  * Break out of the iteration if data->m has become equal to "1".
1450  */
1451 static int map_check_scaled(__isl_take isl_map *map, void *user)
1452 {
1453         int r;
1454
1455         r = isl_map_foreach_basic_map(map, &basic_map_check_scaled, user);
1456         isl_map_free(map);
1457
1458         return r;
1459 }
1460
1461 /* Create an AST node for the current dimension based on
1462  * the schedule domain "bounds" and return the node encapsulated
1463  * in an isl_ast_graft.
1464  *
1465  * "executed" is the current inverse schedule, taking into account
1466  * the bounds in "bounds"
1467  * "domain" is the domain of "executed", with inner dimensions projected out.
1468  *
1469  *
1470  * Before moving on to the actual AST node construction in create_node_scaled,
1471  * we first check if the current dimension is strided and if we can scale
1472  * down this stride.  Note that we only do this if the ast_build_scale_strides
1473  * option is set.
1474  *
1475  * In particular, let the current dimension take on values
1476  *
1477  *      f + s a
1478  *
1479  * with a an integer.  We check if we can find an integer m that (obviouly)
1480  * divides both f and s.
1481  *
1482  * If so, we check if the current dimension only appears in constraints
1483  * where the coefficients of the other variables are multiples of m.
1484  * We perform this extra check to avoid the risk of introducing
1485  * divisions by scaling down the current dimension.
1486  *
1487  * If so, we scale the current dimension down by a factor of m.
1488  * That is, we plug in
1489  *
1490  *      i = m i'                                                        (1)
1491  *
1492  * Note that in principle we could always scale down strided loops
1493  * by plugging in
1494  *
1495  *      i = f + s i'
1496  *
1497  * but this may result in i' taking on larger values than the original i,
1498  * due to the shift by "f".
1499  * By constrast, the scaling in (1) can only reduce the (absolute) value "i".
1500  */
1501 static __isl_give isl_ast_graft *create_node(__isl_take isl_union_map *executed,
1502         __isl_take isl_basic_set *bounds, __isl_take isl_set *domain,
1503         __isl_take isl_ast_build *build)
1504 {
1505         struct isl_check_scaled_data data;
1506         isl_ctx *ctx;
1507         isl_aff *offset;
1508         isl_val *d;
1509
1510         ctx = isl_ast_build_get_ctx(build);
1511         if (!isl_options_get_ast_build_scale_strides(ctx))
1512                 return create_node_scaled(executed, bounds, domain, build);
1513
1514         data.depth = isl_ast_build_get_depth(build);
1515         if (!isl_ast_build_has_stride(build, data.depth))
1516                 return create_node_scaled(executed, bounds, domain, build);
1517
1518         offset = isl_ast_build_get_offset(build, data.depth);
1519         data.m = isl_ast_build_get_stride(build, data.depth);
1520         if (!data.m)
1521                 offset = isl_aff_free(offset);
1522         offset = isl_aff_scale_down_val(offset, isl_val_copy(data.m));
1523         d = isl_aff_get_denominator_val(offset);
1524         if (!d)
1525                 executed = isl_union_map_free(executed);
1526
1527         if (executed && isl_val_is_divisible_by(data.m, d))
1528                 data.m = isl_val_div(data.m, d);
1529         else {
1530                 data.m = isl_val_set_si(data.m, 1);
1531                 isl_val_free(d);
1532         }
1533
1534         if (!isl_val_is_one(data.m)) {
1535                 if (isl_union_map_foreach_map(executed, &map_check_scaled,
1536                                                 &data) < 0 &&
1537                     !isl_val_is_one(data.m))
1538                         executed = isl_union_map_free(executed);
1539         }
1540
1541         if (!isl_val_is_one(data.m)) {
1542                 isl_space *space;
1543                 isl_multi_aff *ma;
1544                 isl_aff *aff;
1545                 isl_map *map;
1546                 isl_union_map *umap;
1547
1548                 space = isl_ast_build_get_space(build, 1);
1549                 space = isl_space_map_from_set(space);
1550                 ma = isl_multi_aff_identity(space);
1551                 aff = isl_multi_aff_get_aff(ma, data.depth);
1552                 aff = isl_aff_scale_val(aff, isl_val_copy(data.m));
1553                 ma = isl_multi_aff_set_aff(ma, data.depth, aff);
1554
1555                 bounds = isl_basic_set_preimage_multi_aff(bounds,
1556                                                 isl_multi_aff_copy(ma));
1557                 domain = isl_set_preimage_multi_aff(domain,
1558                                                 isl_multi_aff_copy(ma));
1559                 map = isl_map_reverse(isl_map_from_multi_aff(ma));
1560                 umap = isl_union_map_from_map(map);
1561                 executed = isl_union_map_apply_domain(executed,
1562                                                 isl_union_map_copy(umap));
1563                 build = isl_ast_build_scale_down(build, isl_val_copy(data.m),
1564                                                 umap);
1565         }
1566         isl_aff_free(offset);
1567         isl_val_free(data.m);
1568
1569         return create_node_scaled(executed, bounds, domain, build);
1570 }
1571
1572 /* Add the basic set to the list that "user" points to.
1573  */
1574 static int collect_basic_set(__isl_take isl_basic_set *bset, void *user)
1575 {
1576         isl_basic_set_list **list = user;
1577
1578         *list = isl_basic_set_list_add(*list, bset);
1579
1580         return 0;
1581 }
1582
1583 /* Extract the basic sets of "set" and collect them in an isl_basic_set_list.
1584  */
1585 static __isl_give isl_basic_set_list *isl_basic_set_list_from_set(
1586         __isl_take isl_set *set)
1587 {
1588         int n;
1589         isl_ctx *ctx;
1590         isl_basic_set_list *list;
1591
1592         if (!set)
1593                 return NULL;
1594
1595         ctx = isl_set_get_ctx(set);
1596
1597         n = isl_set_n_basic_set(set);
1598         list = isl_basic_set_list_alloc(ctx, n);
1599         if (isl_set_foreach_basic_set(set, &collect_basic_set, &list) < 0)
1600                 list = isl_basic_set_list_free(list);
1601
1602         isl_set_free(set);
1603         return list;
1604 }
1605
1606 /* Generate code for the schedule domain "bounds"
1607  * and add the result to "list".
1608  *
1609  * We mainly detect strides and additional equalities here
1610  * and then pass over control to create_node.
1611  *
1612  * "bounds" reflects the bounds on the current dimension and possibly
1613  * some extra conditions on outer dimensions.
1614  * It does not, however, include any divs involving the current dimension,
1615  * so it does not capture any stride constraints.
1616  * We therefore need to compute that part of the schedule domain that
1617  * intersects with "bounds" and derive the strides from the result.
1618  */
1619 static __isl_give isl_ast_graft_list *add_node(
1620         __isl_take isl_ast_graft_list *list, __isl_take isl_union_map *executed,
1621         __isl_take isl_basic_set *bounds, __isl_take isl_ast_build *build)
1622 {
1623         isl_ast_graft *graft;
1624         isl_set *domain = NULL;
1625         isl_union_set *uset;
1626         int empty;
1627
1628         uset = isl_union_set_from_basic_set(isl_basic_set_copy(bounds));
1629         executed = isl_union_map_intersect_domain(executed, uset);
1630         empty = isl_union_map_is_empty(executed);
1631         if (empty < 0)
1632                 goto error;
1633         if (empty)
1634                 goto done;
1635
1636         uset = isl_union_map_domain(isl_union_map_copy(executed));
1637         domain = isl_set_from_union_set(uset);
1638         domain = isl_ast_build_compute_gist(build, domain);
1639         empty = isl_set_is_empty(domain);
1640         if (empty < 0)
1641                 goto error;
1642         if (empty)
1643                 goto done;
1644
1645         domain = isl_ast_build_eliminate_inner(build, domain);
1646         build = isl_ast_build_detect_strides(build, isl_set_copy(domain));
1647
1648         graft = create_node(executed, bounds, domain,
1649                                 isl_ast_build_copy(build));
1650         list = isl_ast_graft_list_add(list, graft);
1651         isl_ast_build_free(build);
1652         return list;
1653 error:
1654         list = isl_ast_graft_list_free(list);
1655 done:
1656         isl_set_free(domain);
1657         isl_basic_set_free(bounds);
1658         isl_union_map_free(executed);
1659         isl_ast_build_free(build);
1660         return list;
1661 }
1662
1663 /* Does any element of i follow or coincide with any element of j
1664  * at the current depth for equal values of the outer dimensions?
1665  */
1666 static int domain_follows_at_depth(__isl_keep isl_basic_set *i,
1667         __isl_keep isl_basic_set *j, void *user)
1668 {
1669         int depth = *(int *) user;
1670         isl_basic_map *test;
1671         int empty;
1672         int l;
1673
1674         test = isl_basic_map_from_domain_and_range(isl_basic_set_copy(i),
1675                                                     isl_basic_set_copy(j));
1676         for (l = 0; l < depth; ++l)
1677                 test = isl_basic_map_equate(test, isl_dim_in, l,
1678                                                 isl_dim_out, l);
1679         test = isl_basic_map_order_ge(test, isl_dim_in, depth,
1680                                         isl_dim_out, depth);
1681         empty = isl_basic_map_is_empty(test);
1682         isl_basic_map_free(test);
1683
1684         return empty < 0 ? -1 : !empty;
1685 }
1686
1687 /* Split up each element of "list" into a part that is related to "bset"
1688  * according to "gt" and a part that is not.
1689  * Return a list that consist of "bset" and all the pieces.
1690  */
1691 static __isl_give isl_basic_set_list *add_split_on(
1692         __isl_take isl_basic_set_list *list, __isl_take isl_basic_set *bset,
1693         __isl_keep isl_basic_map *gt)
1694 {
1695         int i, n;
1696         isl_basic_set_list *res;
1697
1698         gt = isl_basic_map_copy(gt);
1699         gt = isl_basic_map_intersect_domain(gt, isl_basic_set_copy(bset));
1700         n = isl_basic_set_list_n_basic_set(list);
1701         res = isl_basic_set_list_from_basic_set(bset);
1702         for (i = 0; res && i < n; ++i) {
1703                 isl_basic_set *bset;
1704                 isl_set *set1, *set2;
1705                 isl_basic_map *bmap;
1706                 int empty;
1707
1708                 bset = isl_basic_set_list_get_basic_set(list, i);
1709                 bmap = isl_basic_map_copy(gt);
1710                 bmap = isl_basic_map_intersect_range(bmap, bset);
1711                 bset = isl_basic_map_range(bmap);
1712                 empty = isl_basic_set_is_empty(bset);
1713                 if (empty < 0)
1714                         res = isl_basic_set_list_free(res);
1715                 if (empty)  {
1716                         isl_basic_set_free(bset);
1717                         bset = isl_basic_set_list_get_basic_set(list, i);
1718                         res = isl_basic_set_list_add(res, bset);
1719                         continue;
1720                 }
1721
1722                 res = isl_basic_set_list_add(res, isl_basic_set_copy(bset));
1723                 set1 = isl_set_from_basic_set(bset);
1724                 bset = isl_basic_set_list_get_basic_set(list, i);
1725                 set2 = isl_set_from_basic_set(bset);
1726                 set1 = isl_set_subtract(set2, set1);
1727                 set1 = isl_set_make_disjoint(set1);
1728
1729                 res = isl_basic_set_list_concat(res,
1730                                             isl_basic_set_list_from_set(set1));
1731         }
1732         isl_basic_map_free(gt);
1733         isl_basic_set_list_free(list);
1734         return res;
1735 }
1736
1737 static __isl_give isl_ast_graft_list *generate_sorted_domains(
1738         __isl_keep isl_basic_set_list *domain_list,
1739         __isl_keep isl_union_map *executed,
1740         __isl_keep isl_ast_build *build);
1741
1742 /* Internal data structure for add_nodes.
1743  *
1744  * "executed" and "build" are extra arguments to be passed to add_node.
1745  * "list" collects the results.
1746  */
1747 struct isl_add_nodes_data {
1748         isl_union_map *executed;
1749         isl_ast_build *build;
1750
1751         isl_ast_graft_list *list;
1752 };
1753
1754 /* Generate code for the schedule domains in "scc"
1755  * and add the results to "list".
1756  *
1757  * The domains in "scc" form a strongly connected component in the ordering.
1758  * If the number of domains in "scc" is larger than 1, then this means
1759  * that we cannot determine a valid ordering for the domains in the component.
1760  * This should be fairly rare because the individual domains
1761  * have been made disjoint first.
1762  * The problem is that the domains may be integrally disjoint but not
1763  * rationally disjoint.  For example, we may have domains
1764  *
1765  *      { [i,i] : 0 <= i <= 1 }         and     { [i,1-i] : 0 <= i <= 1 }
1766  *
1767  * These two domains have an empty intersection, but their rational
1768  * relaxations do intersect.  It is impossible to order these domains
1769  * in the second dimension because the first should be ordered before
1770  * the second for outer dimension equal to 0, while it should be ordered
1771  * after for outer dimension equal to 1.
1772  *
1773  * This may happen in particular in case of unrolling since the domain
1774  * of each slice is replaced by its simple hull.
1775  *
1776  * For each basic set i in "scc" and for each of the following basic sets j,
1777  * we split off that part of the basic set i that shares the outer dimensions
1778  * with j and lies before j in the current dimension.
1779  * We collect all the pieces in a new list that replaces "scc".
1780  */
1781 static int add_nodes(__isl_take isl_basic_set_list *scc, void *user)
1782 {
1783         struct isl_add_nodes_data *data = user;
1784         int i, n, depth;
1785         isl_basic_set *bset;
1786         isl_basic_set_list *list;
1787         isl_space *space;
1788         isl_basic_map *gt;
1789
1790         n = isl_basic_set_list_n_basic_set(scc);
1791         bset = isl_basic_set_list_get_basic_set(scc, 0);
1792         if (n == 1) {
1793                 isl_basic_set_list_free(scc);
1794                 data->list = add_node(data->list,
1795                                 isl_union_map_copy(data->executed), bset,
1796                                 isl_ast_build_copy(data->build));
1797                 return data->list ? 0 : -1;
1798         }
1799
1800         depth = isl_ast_build_get_depth(data->build);
1801         space = isl_basic_set_get_space(bset);
1802         space = isl_space_map_from_set(space);
1803         gt = isl_basic_map_universe(space);
1804         for (i = 0; i < depth; ++i)
1805                 gt = isl_basic_map_equate(gt, isl_dim_in, i, isl_dim_out, i);
1806         gt = isl_basic_map_order_gt(gt, isl_dim_in, depth, isl_dim_out, depth);
1807
1808         list = isl_basic_set_list_from_basic_set(bset);
1809         for (i = 1; i < n; ++i) {
1810                 bset = isl_basic_set_list_get_basic_set(scc, i);
1811                 list = add_split_on(list, bset, gt);
1812         }
1813         isl_basic_map_free(gt);
1814         isl_basic_set_list_free(scc);
1815         scc = list;
1816         data->list = isl_ast_graft_list_concat(data->list,
1817                     generate_sorted_domains(scc, data->executed, data->build));
1818         isl_basic_set_list_free(scc);
1819
1820         return data->list ? 0 : -1;
1821 }
1822
1823 /* Sort the domains in "domain_list" according to the execution order
1824  * at the current depth (for equal values of the outer dimensions),
1825  * generate code for each of them, collecting the results in a list.
1826  * If no code is generated (because the intersection of the inverse schedule
1827  * with the domains turns out to be empty), then an empty list is returned.
1828  *
1829  * The caller is responsible for ensuring that the basic sets in "domain_list"
1830  * are pair-wise disjoint.  It can, however, in principle happen that
1831  * two basic sets should be ordered one way for one value of the outer
1832  * dimensions and the other way for some other value of the outer dimensions.
1833  * We therefore play safe and look for strongly connected components.
1834  * The function add_nodes takes care of handling non-trivial components.
1835  */
1836 static __isl_give isl_ast_graft_list *generate_sorted_domains(
1837         __isl_keep isl_basic_set_list *domain_list,
1838         __isl_keep isl_union_map *executed, __isl_keep isl_ast_build *build)
1839 {
1840         isl_ctx *ctx;
1841         struct isl_add_nodes_data data;
1842         int depth;
1843         int n;
1844
1845         if (!domain_list)
1846                 return NULL;
1847
1848         ctx = isl_basic_set_list_get_ctx(domain_list);
1849         n = isl_basic_set_list_n_basic_set(domain_list);
1850         data.list = isl_ast_graft_list_alloc(ctx, n);
1851         if (n == 0)
1852                 return data.list;
1853         if (n == 1)
1854                 return add_node(data.list, isl_union_map_copy(executed),
1855                         isl_basic_set_list_get_basic_set(domain_list, 0),
1856                         isl_ast_build_copy(build));
1857
1858         depth = isl_ast_build_get_depth(build);
1859         data.executed = executed;
1860         data.build = build;
1861         if (isl_basic_set_list_foreach_scc(domain_list,
1862                                         &domain_follows_at_depth, &depth,
1863                                         &add_nodes, &data) < 0)
1864                 data.list = isl_ast_graft_list_free(data.list);
1865
1866         return data.list;
1867 }
1868
1869 /* Do i and j share any values for the outer dimensions?
1870  */
1871 static int shared_outer(__isl_keep isl_basic_set *i,
1872         __isl_keep isl_basic_set *j, void *user)
1873 {
1874         int depth = *(int *) user;
1875         isl_basic_map *test;
1876         int empty;
1877         int l;
1878
1879         test = isl_basic_map_from_domain_and_range(isl_basic_set_copy(i),
1880                                                     isl_basic_set_copy(j));
1881         for (l = 0; l < depth; ++l)
1882                 test = isl_basic_map_equate(test, isl_dim_in, l,
1883                                                 isl_dim_out, l);
1884         empty = isl_basic_map_is_empty(test);
1885         isl_basic_map_free(test);
1886
1887         return empty < 0 ? -1 : !empty;
1888 }
1889
1890 /* Internal data structure for generate_sorted_domains_wrap.
1891  *
1892  * "n" is the total number of basic sets
1893  * "executed" and "build" are extra arguments to be passed
1894  *      to generate_sorted_domains.
1895  *
1896  * "single" is set to 1 by generate_sorted_domains_wrap if there
1897  * is only a single component.
1898  * "list" collects the results.
1899  */
1900 struct isl_ast_generate_parallel_domains_data {
1901         int n;
1902         isl_union_map *executed;
1903         isl_ast_build *build;
1904
1905         int single;
1906         isl_ast_graft_list *list;
1907 };
1908
1909 /* Call generate_sorted_domains on "scc", fuse the result into a list
1910  * with either zero or one graft and collect the these single element
1911  * lists into data->list.
1912  *
1913  * If there is only one component, i.e., if the number of basic sets
1914  * in the current component is equal to the total number of basic sets,
1915  * then data->single is set to 1 and the result of generate_sorted_domains
1916  * is not fused.
1917  */
1918 static int generate_sorted_domains_wrap(__isl_take isl_basic_set_list *scc,
1919         void *user)
1920 {
1921         struct isl_ast_generate_parallel_domains_data *data = user;
1922         isl_ast_graft_list *list;
1923
1924         list = generate_sorted_domains(scc, data->executed, data->build);
1925         data->single = isl_basic_set_list_n_basic_set(scc) == data->n;
1926         if (!data->single)
1927                 list = isl_ast_graft_list_fuse(list, data->build);
1928         if (!data->list)
1929                 data->list = list;
1930         else
1931                 data->list = isl_ast_graft_list_concat(data->list, list);
1932
1933         isl_basic_set_list_free(scc);
1934         if (!data->list)
1935                 return -1;
1936
1937         return 0;
1938 }
1939
1940 /* Look for any (weakly connected) components in the "domain_list"
1941  * of domains that share some values of the outer dimensions.
1942  * That is, domains in different components do not share any values
1943  * of the outer dimensions.  This means that these components
1944  * can be freely reordered.
1945  * Within each of the components, we sort the domains according
1946  * to the execution order at the current depth.
1947  *
1948  * If there is more than one component, then generate_sorted_domains_wrap
1949  * fuses the result of each call to generate_sorted_domains
1950  * into a list with either zero or one graft and collects these (at most)
1951  * single element lists into a bigger list. This means that the elements of the
1952  * final list can be freely reordered.  In particular, we sort them
1953  * according to an arbitrary but fixed ordering to ease merging of
1954  * graft lists from different components.
1955  */
1956 static __isl_give isl_ast_graft_list *generate_parallel_domains(
1957         __isl_keep isl_basic_set_list *domain_list,
1958         __isl_keep isl_union_map *executed, __isl_keep isl_ast_build *build)
1959 {
1960         int depth;
1961         struct isl_ast_generate_parallel_domains_data data;
1962
1963         if (!domain_list)
1964                 return NULL;
1965
1966         data.n = isl_basic_set_list_n_basic_set(domain_list);
1967         if (data.n <= 1)
1968                 return generate_sorted_domains(domain_list, executed, build);
1969
1970         depth = isl_ast_build_get_depth(build);
1971         data.list = NULL;
1972         data.executed = executed;
1973         data.build = build;
1974         data.single = 0;
1975         if (isl_basic_set_list_foreach_scc(domain_list, &shared_outer, &depth,
1976                                             &generate_sorted_domains_wrap,
1977                                             &data) < 0)
1978                 data.list = isl_ast_graft_list_free(data.list);
1979
1980         if (!data.single)
1981                 data.list = isl_ast_graft_list_sort_guard(data.list);
1982
1983         return data.list;
1984 }
1985
1986 /* Internal data for separate_domain.
1987  *
1988  * "explicit" is set if we only want to use explicit bounds.
1989  *
1990  * "domain" collects the separated domains.
1991  */
1992 struct isl_separate_domain_data {
1993         isl_ast_build *build;
1994         int explicit;
1995         isl_set *domain;
1996 };
1997
1998 /* Extract implicit bounds on the current dimension for the executed "map".
1999  *
2000  * The domain of "map" may involve inner dimensions, so we
2001  * need to eliminate them.
2002  */
2003 static __isl_give isl_set *implicit_bounds(__isl_take isl_map *map,
2004         __isl_keep isl_ast_build *build)
2005 {
2006         isl_set *domain;
2007
2008         domain = isl_map_domain(map);
2009         domain = isl_ast_build_eliminate(build, domain);
2010
2011         return domain;
2012 }
2013
2014 /* Extract explicit bounds on the current dimension for the executed "map".
2015  *
2016  * Rather than eliminating the inner dimensions as in implicit_bounds,
2017  * we simply drop any constraints involving those inner dimensions.
2018  * The idea is that most bounds that are implied by constraints on the
2019  * inner dimensions will be enforced by for loops and not by explicit guards.
2020  * There is then no need to separate along those bounds.
2021  */
2022 static __isl_give isl_set *explicit_bounds(__isl_take isl_map *map,
2023         __isl_keep isl_ast_build *build)
2024 {
2025         isl_set *domain;
2026         int depth, dim;
2027
2028         dim = isl_map_dim(map, isl_dim_out);
2029         map = isl_map_drop_constraints_involving_dims(map, isl_dim_out, 0, dim);
2030
2031         domain = isl_map_domain(map);
2032         depth = isl_ast_build_get_depth(build);
2033         dim = isl_set_dim(domain, isl_dim_set);
2034         domain = isl_set_detect_equalities(domain);
2035         domain = isl_set_drop_constraints_involving_dims(domain,
2036                                 isl_dim_set, depth + 1, dim - (depth + 1));
2037         domain = isl_set_remove_divs_involving_dims(domain,
2038                                 isl_dim_set, depth, 1);
2039         domain = isl_set_remove_unknown_divs(domain);
2040
2041         return domain;
2042 }
2043
2044 /* Split data->domain into pieces that intersect with the range of "map"
2045  * and pieces that do not intersect with the range of "map"
2046  * and then add that part of the range of "map" that does not intersect
2047  * with data->domain.
2048  */
2049 static int separate_domain(__isl_take isl_map *map, void *user)
2050 {
2051         struct isl_separate_domain_data *data = user;
2052         isl_set *domain;
2053         isl_set *d1, *d2;
2054
2055         if (data->explicit)
2056                 domain = explicit_bounds(map, data->build);
2057         else
2058                 domain = implicit_bounds(map, data->build);
2059
2060         domain = isl_set_coalesce(domain);
2061         domain = isl_set_make_disjoint(domain);
2062         d1 = isl_set_subtract(isl_set_copy(domain), isl_set_copy(data->domain));
2063         d2 = isl_set_subtract(isl_set_copy(data->domain), isl_set_copy(domain));
2064         data->domain = isl_set_intersect(data->domain, domain);
2065         data->domain = isl_set_union(data->domain, d1);
2066         data->domain = isl_set_union(data->domain, d2);
2067
2068         return 0;
2069 }
2070
2071 /* Separate the schedule domains of "executed".
2072  *
2073  * That is, break up the domain of "executed" into basic sets,
2074  * such that for each basic set S, every element in S is associated with
2075  * the same domain spaces.
2076  *
2077  * "space" is the (single) domain space of "executed".
2078  */
2079 static __isl_give isl_set *separate_schedule_domains(
2080         __isl_take isl_space *space, __isl_take isl_union_map *executed,
2081         __isl_keep isl_ast_build *build)
2082 {
2083         struct isl_separate_domain_data data = { build };
2084         isl_ctx *ctx;
2085
2086         ctx = isl_ast_build_get_ctx(build);
2087         data.explicit = isl_options_get_ast_build_separation_bounds(ctx) ==
2088                                     ISL_AST_BUILD_SEPARATION_BOUNDS_EXPLICIT;
2089         data.domain = isl_set_empty(space);
2090         if (isl_union_map_foreach_map(executed, &separate_domain, &data) < 0)
2091                 data.domain = isl_set_free(data.domain);
2092
2093         isl_union_map_free(executed);
2094         return data.domain;
2095 }
2096
2097 /* Temporary data used during the search for a lower bound for unrolling.
2098  *
2099  * "domain" is the original set for which to find a lower bound
2100  * "depth" is the dimension for which to find a lower boudn
2101  *
2102  * "lower" is the best lower bound found so far.  It is NULL if we have not
2103  * found any yet.
2104  * "n" is the corresponding size.  If lower is NULL, then the value of n
2105  * is undefined.
2106  *
2107  * "tmp" is a temporary initialized isl_int.
2108  */
2109 struct isl_find_unroll_data {
2110         isl_set *domain;
2111         int depth;
2112
2113         isl_aff *lower;
2114         int *n;
2115         isl_int tmp;
2116 };
2117
2118 /* Check if we can use "c" as a lower bound and if it is better than
2119  * any previously found lower bound.
2120  *
2121  * If "c" does not involve the dimension at the current depth,
2122  * then we cannot use it.
2123  * Otherwise, let "c" be of the form
2124  *
2125  *      i >= f(j)/a
2126  *
2127  * We compute the maximal value of
2128  *
2129  *      -ceil(f(j)/a)) + i + 1
2130  *
2131  * over the domain.  If there is such a value "n", then we know
2132  *
2133  *      -ceil(f(j)/a)) + i + 1 <= n
2134  *
2135  * or
2136  *
2137  *      i < ceil(f(j)/a)) + n
2138  *
2139  * meaning that we can use ceil(f(j)/a)) as a lower bound for unrolling.
2140  * We just need to check if we have found any lower bound before and
2141  * if the new lower bound is better (smaller n) than the previously found
2142  * lower bounds.
2143  */
2144 static int update_unrolling_lower_bound(struct isl_find_unroll_data *data,
2145         __isl_keep isl_constraint *c)
2146 {
2147         isl_aff *aff, *lower;
2148         enum isl_lp_result res;
2149
2150         if (!isl_constraint_is_lower_bound(c, isl_dim_set, data->depth))
2151                 return 0;
2152
2153         lower = isl_constraint_get_bound(c, isl_dim_set, data->depth);
2154         lower = isl_aff_ceil(lower);
2155         aff = isl_aff_copy(lower);
2156         aff = isl_aff_neg(aff);
2157         aff = isl_aff_add_coefficient_si(aff, isl_dim_in, data->depth, 1);
2158         aff = isl_aff_add_constant_si(aff, 1);
2159         res = isl_set_max(data->domain, aff, &data->tmp);
2160         isl_aff_free(aff);
2161
2162         if (res == isl_lp_error)
2163                 goto error;
2164         if (res == isl_lp_unbounded) {
2165                 isl_aff_free(lower);
2166                 return 0;
2167         }
2168
2169         if (isl_int_cmp_si(data->tmp, INT_MAX) <= 0 &&
2170             (!data->lower || isl_int_cmp_si(data->tmp, *data->n) < 0)) {
2171                 isl_aff_free(data->lower);
2172                 data->lower = lower;
2173                 *data->n = isl_int_get_si(data->tmp);
2174         } else
2175                 isl_aff_free(lower);
2176
2177         return 1;
2178 error:
2179         isl_aff_free(lower);
2180         return -1;
2181 }
2182
2183 /* Check if we can use "c" as a lower bound and if it is better than
2184  * any previously found lower bound.
2185  */
2186 static int constraint_find_unroll(__isl_take isl_constraint *c, void *user)
2187 {
2188         struct isl_find_unroll_data *data;
2189         int r;
2190
2191         data = (struct isl_find_unroll_data *) user;
2192         r = update_unrolling_lower_bound(data, c);
2193         isl_constraint_free(c);
2194
2195         return r;
2196 }
2197
2198 /* Look for a lower bound l(i) on the dimension at "depth"
2199  * and a size n such that "domain" is a subset of
2200  *
2201  *      { [i] : l(i) <= i_d < l(i) + n }
2202  *
2203  * where d is "depth" and l(i) depends only on earlier dimensions.
2204  * Furthermore, try and find a lower bound such that n is as small as possible.
2205  * In particular, "n" needs to be finite.
2206  *
2207  * Inner dimensions have been eliminated from "domain" by the caller.
2208  *
2209  * We first construct a collection of lower bounds on the input set
2210  * by computing its simple hull.  We then iterate through them,
2211  * discarding those that we cannot use (either because they do not
2212  * involve the dimension at "depth" or because they have no corresponding
2213  * upper bound, meaning that "n" would be unbounded) and pick out the
2214  * best from the remaining ones.
2215  *
2216  * If we cannot find a suitable lower bound, then we consider that
2217  * to be an error.
2218  */
2219 static __isl_give isl_aff *find_unroll_lower_bound(__isl_keep isl_set *domain,
2220         int depth, int *n)
2221 {
2222         struct isl_find_unroll_data data = { domain, depth, NULL, n };
2223         isl_basic_set *hull;
2224
2225         isl_int_init(data.tmp);
2226         hull = isl_set_simple_hull(isl_set_copy(domain));
2227
2228         if (isl_basic_set_foreach_constraint(hull,
2229                                             &constraint_find_unroll, &data) < 0)
2230                 goto error;
2231
2232         isl_basic_set_free(hull);
2233         isl_int_clear(data.tmp);
2234
2235         if (!data.lower)
2236                 isl_die(isl_set_get_ctx(domain), isl_error_invalid,
2237                         "cannot find lower bound for unrolling", return NULL);
2238
2239         return data.lower;
2240 error:
2241         isl_basic_set_free(hull);
2242         isl_int_clear(data.tmp);
2243         return isl_aff_free(data.lower);
2244 }
2245
2246 /* Return the constraint
2247  *
2248  *      i_"depth" = aff + offset
2249  */
2250 static __isl_give isl_constraint *at_offset(int depth, __isl_keep isl_aff *aff,
2251         int offset)
2252 {
2253         aff = isl_aff_copy(aff);
2254         aff = isl_aff_add_coefficient_si(aff, isl_dim_in, depth, -1);
2255         aff = isl_aff_add_constant_si(aff, offset);
2256         return isl_equality_from_aff(aff);
2257 }
2258
2259 /* Return a list of basic sets, one for each value of the current dimension
2260  * in "domain".
2261  * The divs that involve the current dimension have not been projected out
2262  * from this domain.
2263  *
2264  * Since we are going to be iterating over the individual values,
2265  * we first check if there are any strides on the current dimension.
2266  * If there is, we rewrite the current dimension i as
2267  *
2268  *              i = stride i' + offset
2269  *
2270  * and then iterate over individual values of i' instead.
2271  *
2272  * We then look for a lower bound on i' and a size such that the domain
2273  * is a subset of
2274  *
2275  *      { [j,i'] : l(j) <= i' < l(j) + n }
2276  *
2277  * and then take slices of the domain at values of i'
2278  * between l(j) and l(j) + n - 1.
2279  *
2280  * We compute the unshifted simple hull of each slice to ensure that
2281  * we have a single basic set per offset.  The slicing constraint
2282  * may get simplified away before the unshifted simple hull is taken
2283  * and may therefore in some rare cases disappear from the result.
2284  * We therefore explicitly add the constraint back after computing
2285  * the unshifted simple hull to ensure that the basic sets
2286  * remain disjoint.  The constraints that are dropped by taking the hull
2287  * will be taken into account at the next level, as in the case of the
2288  * atomic option.
2289  *
2290  * Finally, we map i' back to i and add each basic set to the list.
2291  */
2292 static __isl_give isl_basic_set_list *do_unroll(__isl_take isl_set *domain,
2293         __isl_keep isl_ast_build *build)
2294 {
2295         int i, n;
2296         int depth;
2297         isl_ctx *ctx;
2298         isl_aff *lower;
2299         isl_basic_set_list *list;
2300         isl_multi_aff *expansion;
2301         isl_basic_map *bmap;
2302
2303         if (!domain)
2304                 return NULL;
2305
2306         ctx = isl_set_get_ctx(domain);
2307         depth = isl_ast_build_get_depth(build);
2308         build = isl_ast_build_copy(build);
2309         domain = isl_ast_build_eliminate_inner(build, domain);
2310         build = isl_ast_build_detect_strides(build, isl_set_copy(domain));
2311         expansion = isl_ast_build_get_stride_expansion(build);
2312
2313         domain = isl_set_preimage_multi_aff(domain,
2314                                             isl_multi_aff_copy(expansion));
2315         domain = isl_ast_build_eliminate_divs(build, domain);
2316
2317         isl_ast_build_free(build);
2318
2319         list = isl_basic_set_list_alloc(ctx, 0);
2320
2321         lower = find_unroll_lower_bound(domain, depth, &n);
2322         if (!lower)
2323                 list = isl_basic_set_list_free(list);
2324
2325         bmap = isl_basic_map_from_multi_aff(expansion);
2326
2327         for (i = 0; list && i < n; ++i) {
2328                 isl_set *set;
2329                 isl_basic_set *bset;
2330                 isl_constraint *slice;
2331
2332                 slice = at_offset(depth, lower, i);
2333                 set = isl_set_copy(domain);
2334                 set = isl_set_add_constraint(set, isl_constraint_copy(slice));
2335                 bset = isl_set_unshifted_simple_hull(set);
2336                 bset = isl_basic_set_add_constraint(bset, slice);
2337                 bset = isl_basic_set_apply(bset, isl_basic_map_copy(bmap));
2338                 list = isl_basic_set_list_add(list, bset);
2339         }
2340
2341         isl_aff_free(lower);
2342         isl_set_free(domain);
2343         isl_basic_map_free(bmap);
2344
2345         return list;
2346 }
2347
2348 /* Data structure for storing the results and the intermediate objects
2349  * of compute_domains.
2350  *
2351  * "list" is the main result of the function and contains a list
2352  * of disjoint basic sets for which code should be generated.
2353  *
2354  * "executed" and "build" are inputs to compute_domains.
2355  * "schedule_domain" is the domain of "executed".
2356  *
2357  * "option" constains the domains at the current depth that should by
2358  * atomic, separated or unrolled.  These domains are as specified by
2359  * the user, except that inner dimensions have been eliminated and
2360  * that they have been made pair-wise disjoint.
2361  *
2362  * "sep_class" contains the user-specified split into separation classes
2363  * specialized to the current depth.
2364  * "done" contains the union of the separation domains that have already
2365  * been handled.
2366  * "atomic" contains the domain that has effectively been made atomic.
2367  * This domain may be larger than the intersection of option[atomic]
2368  * and the schedule domain.
2369  */
2370 struct isl_codegen_domains {
2371         isl_basic_set_list *list;
2372
2373         isl_union_map *executed;
2374         isl_ast_build *build;
2375         isl_set *schedule_domain;
2376
2377         isl_set *option[3];
2378
2379         isl_map *sep_class;
2380         isl_set *done;
2381         isl_set *atomic;
2382 };
2383
2384 /* Add domains to domains->list for each individual value of the current
2385  * dimension, for that part of the schedule domain that lies in the
2386  * intersection of the option domain and the class domain.
2387  *
2388  * "domain" is the intersection of the class domain and the schedule domain.
2389  * The divs that involve the current dimension have not been projected out
2390  * from this domain.
2391  *
2392  * We first break up the unroll option domain into individual pieces
2393  * and then handle each of them separately.  The unroll option domain
2394  * has been made disjoint in compute_domains_init_options,
2395  *
2396  * Note that we actively want to combine different pieces of the
2397  * schedule domain that have the same value at the current dimension.
2398  * We therefore need to break up the unroll option domain before
2399  * intersecting with class and schedule domain, hoping that the
2400  * unroll option domain specified by the user is relatively simple.
2401  */
2402 static int compute_unroll_domains(struct isl_codegen_domains *domains,
2403         __isl_keep isl_set *domain)
2404 {
2405         isl_set *unroll_domain;
2406         isl_basic_set_list *unroll_list;
2407         int i, n;
2408         int empty;
2409
2410         empty = isl_set_is_empty(domains->option[unroll]);
2411         if (empty < 0)
2412                 return -1;
2413         if (empty)
2414                 return 0;
2415
2416         unroll_domain = isl_set_copy(domains->option[unroll]);
2417         unroll_list = isl_basic_set_list_from_set(unroll_domain);
2418
2419         n = isl_basic_set_list_n_basic_set(unroll_list);
2420         for (i = 0; i < n; ++i) {
2421                 isl_basic_set *bset;
2422                 isl_basic_set_list *list;
2423
2424                 bset = isl_basic_set_list_get_basic_set(unroll_list, i);
2425                 unroll_domain = isl_set_from_basic_set(bset);
2426                 unroll_domain = isl_set_intersect(unroll_domain,
2427                                                     isl_set_copy(domain));
2428
2429                 empty = isl_set_is_empty(unroll_domain);
2430                 if (empty >= 0 && empty) {
2431                         isl_set_free(unroll_domain);
2432                         continue;
2433                 }
2434
2435                 list = do_unroll(unroll_domain, domains->build);
2436                 domains->list = isl_basic_set_list_concat(domains->list, list);
2437         }
2438
2439         isl_basic_set_list_free(unroll_list);
2440
2441         return 0;
2442 }
2443
2444 /* Construct a single basic set that includes the intersection of
2445  * the schedule domain, the atomic option domain and the class domain.
2446  * Add the resulting basic set to domains->list and save a copy
2447  * in domains->atomic for use in compute_partial_domains.
2448  *
2449  * We construct a single domain rather than trying to combine
2450  * the schedule domains of individual domains because we are working
2451  * within a single component so that non-overlapping schedule domains
2452  * should already have been separated.
2453  * Note, though, that this does not take into account the class domain.
2454  * So, it is possible for a class domain to carve out a piece of the
2455  * schedule domain with independent pieces and then we would only
2456  * generate a single domain for them.  If this proves to be problematic
2457  * for some users, then this function will have to be adjusted.
2458  *
2459  * "domain" is the intersection of the schedule domain and the class domain,
2460  * with inner dimensions projected out.
2461  */
2462 static int compute_atomic_domain(struct isl_codegen_domains *domains,
2463         __isl_keep isl_set *domain)
2464 {
2465         isl_basic_set *bset;
2466         isl_set *atomic_domain;
2467         int empty;
2468
2469         atomic_domain = isl_set_copy(domains->option[atomic]);
2470         atomic_domain = isl_set_intersect(atomic_domain, isl_set_copy(domain));
2471         empty = isl_set_is_empty(atomic_domain);
2472         if (empty < 0 || empty) {
2473                 domains->atomic = atomic_domain;
2474                 return empty < 0 ? -1 : 0;
2475         }
2476
2477         atomic_domain = isl_set_coalesce(atomic_domain);
2478         bset = isl_set_unshifted_simple_hull(atomic_domain);
2479         domains->atomic = isl_set_from_basic_set(isl_basic_set_copy(bset));
2480         domains->list = isl_basic_set_list_add(domains->list, bset);
2481
2482         return 0;
2483 }
2484
2485 /* Split up the schedule domain into uniform basic sets,
2486  * in the sense that each element in a basic set is associated to
2487  * elements of the same domains, and add the result to domains->list.
2488  * Do this for that part of the schedule domain that lies in the
2489  * intersection of "class_domain" and the separate option domain.
2490  *
2491  * "class_domain" may or may not include the constraints
2492  * of the schedule domain, but this does not make a difference
2493  * since we are going to intersect it with the domain of the inverse schedule.
2494  * If it includes schedule domain constraints, then they may involve
2495  * inner dimensions, but we will eliminate them in separation_domain.
2496  */
2497 static int compute_separate_domain(struct isl_codegen_domains *domains,
2498         __isl_keep isl_set *class_domain)
2499 {
2500         isl_space *space;
2501         isl_set *domain;
2502         isl_union_map *executed;
2503         isl_basic_set_list *list;
2504         int empty;
2505
2506         domain = isl_set_copy(domains->option[separate]);
2507         domain = isl_set_intersect(domain, isl_set_copy(class_domain));
2508         executed = isl_union_map_copy(domains->executed);
2509         executed = isl_union_map_intersect_domain(executed,
2510                                     isl_union_set_from_set(domain));
2511         empty = isl_union_map_is_empty(executed);
2512         if (empty < 0 || empty) {
2513                 isl_union_map_free(executed);
2514                 return empty < 0 ? -1 : 0;
2515         }
2516
2517         space = isl_set_get_space(class_domain);
2518         domain = separate_schedule_domains(space, executed, domains->build);
2519
2520         list = isl_basic_set_list_from_set(domain);
2521         domains->list = isl_basic_set_list_concat(domains->list, list);
2522
2523         return 0;
2524 }
2525
2526 /* Split up the domain at the current depth into disjoint
2527  * basic sets for which code should be generated separately
2528  * for the given separation class domain.
2529  *
2530  * If any separation classes have been defined, then "class_domain"
2531  * is the domain of the current class and does not refer to inner dimensions.
2532  * Otherwise, "class_domain" is the universe domain.
2533  *
2534  * We first make sure that the class domain is disjoint from
2535  * previously considered class domains.
2536  *
2537  * The separate domains can be computed directly from the "class_domain".
2538  *
2539  * The unroll, atomic and remainder domains need the constraints
2540  * from the schedule domain.
2541  *
2542  * For unrolling, the actual schedule domain is needed (with divs that
2543  * may refer to the current dimension) so that stride detection can be
2544  * performed.
2545  *
2546  * For atomic and remainder domains, inner dimensions and divs involving
2547  * the current dimensions should be eliminated.
2548  * In case we are working within a separation class, we need to intersect
2549  * the result with the current "class_domain" to ensure that the domains
2550  * are disjoint from those generated from other class domains.
2551  *
2552  * The domain that has been made atomic may be larger than specified
2553  * by the user since it needs to be representable as a single basic set.
2554  * This possibly larger domain is stored in domains->atomic by
2555  * compute_atomic_domain.
2556  *
2557  * If anything is left after handling separate, unroll and atomic,
2558  * we split it up into basic sets and append the basic sets to domains->list.
2559  */
2560 static int compute_partial_domains(struct isl_codegen_domains *domains,
2561         __isl_take isl_set *class_domain)
2562 {
2563         isl_basic_set_list *list;
2564         isl_set *domain;
2565
2566         class_domain = isl_set_subtract(class_domain,
2567                                         isl_set_copy(domains->done));
2568         domains->done = isl_set_union(domains->done,
2569                                         isl_set_copy(class_domain));
2570
2571         domain = isl_set_copy(class_domain);
2572
2573         if (compute_separate_domain(domains, domain) < 0)
2574                 goto error;
2575         domain = isl_set_subtract(domain,
2576                                     isl_set_copy(domains->option[separate]));
2577
2578         domain = isl_set_intersect(domain,
2579                                 isl_set_copy(domains->schedule_domain));
2580
2581         if (compute_unroll_domains(domains, domain) < 0)
2582                 goto error;
2583         domain = isl_set_subtract(domain,
2584                                     isl_set_copy(domains->option[unroll]));
2585
2586         domain = isl_ast_build_eliminate(domains->build, domain);
2587         domain = isl_set_intersect(domain, isl_set_copy(class_domain));
2588
2589         if (compute_atomic_domain(domains, domain) < 0)
2590                 domain = isl_set_free(domain);
2591         domain = isl_set_subtract(domain, domains->atomic);
2592
2593         domain = isl_set_coalesce(domain);
2594         domain = isl_set_make_disjoint(domain);
2595
2596         list = isl_basic_set_list_from_set(domain);
2597         domains->list = isl_basic_set_list_concat(domains->list, list);
2598
2599         isl_set_free(class_domain);
2600
2601         return 0;
2602 error:
2603         isl_set_free(domain);
2604         isl_set_free(class_domain);
2605         return -1;
2606 }
2607
2608 /* Split up the domain at the current depth into disjoint
2609  * basic sets for which code should be generated separately
2610  * for the separation class identified by "pnt".
2611  *
2612  * We extract the corresponding class domain from domains->sep_class,
2613  * eliminate inner dimensions and pass control to compute_partial_domains.
2614  */
2615 static int compute_class_domains(__isl_take isl_point *pnt, void *user)
2616 {
2617         struct isl_codegen_domains *domains = user;
2618         isl_set *class_set;
2619         isl_set *domain;
2620         int disjoint;
2621
2622         class_set = isl_set_from_point(pnt);
2623         domain = isl_map_domain(isl_map_intersect_range(
2624                                 isl_map_copy(domains->sep_class), class_set));
2625         domain = isl_ast_build_compute_gist(domains->build, domain);
2626         domain = isl_ast_build_eliminate(domains->build, domain);
2627
2628         disjoint = isl_set_plain_is_disjoint(domain, domains->schedule_domain);
2629         if (disjoint < 0)
2630                 return -1;
2631         if (disjoint) {
2632                 isl_set_free(domain);
2633                 return 0;
2634         }
2635
2636         return compute_partial_domains(domains, domain);
2637 }
2638
2639 /* Extract the domains at the current depth that should be atomic,
2640  * separated or unrolled and store them in option.
2641  *
2642  * The domains specified by the user might overlap, so we make
2643  * them disjoint by subtracting earlier domains from later domains.
2644  */
2645 static void compute_domains_init_options(isl_set *option[3],
2646         __isl_keep isl_ast_build *build)
2647 {
2648         enum isl_ast_build_domain_type type, type2;
2649
2650         for (type = atomic; type <= separate; ++type) {
2651                 option[type] = isl_ast_build_get_option_domain(build, type);
2652                 for (type2 = atomic; type2 < type; ++type2)
2653                         option[type] = isl_set_subtract(option[type],
2654                                                 isl_set_copy(option[type2]));
2655         }
2656
2657         option[unroll] = isl_set_coalesce(option[unroll]);
2658         option[unroll] = isl_set_make_disjoint(option[unroll]);
2659 }
2660
2661 /* Split up the domain at the current depth into disjoint
2662  * basic sets for which code should be generated separately,
2663  * based on the user-specified options.
2664  * Return the list of disjoint basic sets.
2665  *
2666  * There are three kinds of domains that we need to keep track of.
2667  * - the "schedule domain" is the domain of "executed"
2668  * - the "class domain" is the domain corresponding to the currrent
2669  *      separation class
2670  * - the "option domain" is the domain corresponding to one of the options
2671  *      atomic, unroll or separate
2672  *
2673  * We first consider the individial values of the separation classes
2674  * and split up the domain for each of them separately.
2675  * Finally, we consider the remainder.  If no separation classes were
2676  * specified, then we call compute_partial_domains with the universe
2677  * "class_domain".  Otherwise, we take the "schedule_domain" as "class_domain",
2678  * with inner dimensions removed.  We do this because we want to
2679  * avoid computing the complement of the class domains (i.e., the difference
2680  * between the universe and domains->done).
2681  */
2682 static __isl_give isl_basic_set_list *compute_domains(
2683         __isl_keep isl_union_map *executed, __isl_keep isl_ast_build *build)
2684 {
2685         struct isl_codegen_domains domains;
2686         isl_ctx *ctx;
2687         isl_set *domain;
2688         isl_union_set *schedule_domain;
2689         isl_set *classes;
2690         isl_space *space;
2691         int n_param;
2692         enum isl_ast_build_domain_type type;
2693         int empty;
2694
2695         if (!executed)
2696                 return NULL;
2697
2698         ctx = isl_union_map_get_ctx(executed);
2699         domains.list = isl_basic_set_list_alloc(ctx, 0);
2700
2701         schedule_domain = isl_union_map_domain(isl_union_map_copy(executed));
2702         domain = isl_set_from_union_set(schedule_domain);
2703
2704         compute_domains_init_options(domains.option, build);
2705
2706         domains.sep_class = isl_ast_build_get_separation_class(build);
2707         classes = isl_map_range(isl_map_copy(domains.sep_class));
2708         n_param = isl_set_dim(classes, isl_dim_param);
2709         classes = isl_set_project_out(classes, isl_dim_param, 0, n_param);
2710
2711         space = isl_set_get_space(domain);
2712         domains.build = build;
2713         domains.schedule_domain = isl_set_copy(domain);
2714         domains.executed = executed;
2715         domains.done = isl_set_empty(space);
2716
2717         if (isl_set_foreach_point(classes, &compute_class_domains, &domains) < 0)
2718                 domains.list = isl_basic_set_list_free(domains.list);
2719         isl_set_free(classes);
2720
2721         empty = isl_set_is_empty(domains.done);
2722         if (empty < 0) {
2723                 domains.list = isl_basic_set_list_free(domains.list);
2724                 domain = isl_set_free(domain);
2725         } else if (empty) {
2726                 isl_set_free(domain);
2727                 domain = isl_set_universe(isl_set_get_space(domains.done));
2728         } else {
2729                 domain = isl_ast_build_eliminate(build, domain);
2730         }
2731         if (compute_partial_domains(&domains, domain) < 0)
2732                 domains.list = isl_basic_set_list_free(domains.list);
2733
2734         isl_set_free(domains.schedule_domain);
2735         isl_set_free(domains.done);
2736         isl_map_free(domains.sep_class);
2737         for (type = atomic; type <= separate; ++type)
2738                 isl_set_free(domains.option[type]);
2739
2740         return domains.list;
2741 }
2742
2743 /* Generate code for a single component, after shifting (if any)
2744  * has been applied.
2745  *
2746  * We first split up the domain at the current depth into disjoint
2747  * basic sets based on the user-specified options.
2748  * Then we generated code for each of them and concatenate the results.
2749  */
2750 static __isl_give isl_ast_graft_list *generate_shifted_component(
2751         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build)
2752 {
2753         isl_basic_set_list *domain_list;
2754         isl_ast_graft_list *list = NULL;
2755
2756         domain_list = compute_domains(executed, build);
2757         list = generate_parallel_domains(domain_list, executed, build);
2758
2759         isl_basic_set_list_free(domain_list);
2760         isl_union_map_free(executed);
2761         isl_ast_build_free(build);
2762
2763         return list;
2764 }
2765
2766 struct isl_set_map_pair {
2767         isl_set *set;
2768         isl_map *map;
2769 };
2770
2771 /* Given an array "domain" of isl_set_map_pairs and an array "order"
2772  * of indices into the "domain" array,
2773  * return the union of the "map" fields of the elements
2774  * indexed by the first "n" elements of "order".
2775  */
2776 static __isl_give isl_union_map *construct_component_executed(
2777         struct isl_set_map_pair *domain, int *order, int n)
2778 {
2779         int i;
2780         isl_map *map;
2781         isl_union_map *executed;
2782
2783         map = isl_map_copy(domain[order[0]].map);
2784         executed = isl_union_map_from_map(map);
2785         for (i = 1; i < n; ++i) {
2786                 map = isl_map_copy(domain[order[i]].map);
2787                 executed = isl_union_map_add_map(executed, map);
2788         }
2789
2790         return executed;
2791 }
2792
2793 /* Generate code for a single component, after shifting (if any)
2794  * has been applied.
2795  *
2796  * The component inverse schedule is specified as the "map" fields
2797  * of the elements of "domain" indexed by the first "n" elements of "order".
2798  */
2799 static __isl_give isl_ast_graft_list *generate_shifted_component_from_list(
2800         struct isl_set_map_pair *domain, int *order, int n,
2801         __isl_take isl_ast_build *build)
2802 {
2803         isl_union_map *executed;
2804
2805         executed = construct_component_executed(domain, order, n);
2806         return generate_shifted_component(executed, build);
2807 }
2808
2809 /* Given an array "domain" of isl_set_map_pairs and an array "order"
2810  * of indices into the "domain" array,
2811  * do all (except for at most one) of the "set" field of the elements
2812  * indexed by the first "n" elements of "order" have a fixed value
2813  * at position "depth"?
2814  */
2815 static int at_most_one_non_fixed(struct isl_set_map_pair *domain,
2816         int *order, int n, int depth)
2817 {
2818         int i;
2819         int non_fixed = -1;
2820
2821         for (i = 0; i < n; ++i) {
2822                 int f;
2823
2824                 f = isl_set_plain_is_fixed(domain[order[i]].set,
2825                                                 isl_dim_set, depth, NULL);
2826                 if (f < 0)
2827                         return -1;
2828                 if (f)
2829                         continue;
2830                 if (non_fixed >= 0)
2831                         return 0;
2832                 non_fixed = i;
2833         }
2834
2835         return 1;
2836 }
2837
2838 /* Given an array "domain" of isl_set_map_pairs and an array "order"
2839  * of indices into the "domain" array,
2840  * eliminate the inner dimensions from the "set" field of the elements
2841  * indexed by the first "n" elements of "order", provided the current
2842  * dimension does not have a fixed value.
2843  *
2844  * Return the index of the first element in "order" with a corresponding
2845  * "set" field that does not have an (obviously) fixed value.
2846  */
2847 static int eliminate_non_fixed(struct isl_set_map_pair *domain,
2848         int *order, int n, int depth, __isl_keep isl_ast_build *build)
2849 {
2850         int i;
2851         int base = -1;
2852
2853         for (i = n - 1; i >= 0; --i) {
2854                 int f;
2855                 f = isl_set_plain_is_fixed(domain[order[i]].set,
2856                                                 isl_dim_set, depth, NULL);
2857                 if (f < 0)
2858                         return -1;
2859                 if (f)
2860                         continue;
2861                 domain[order[i]].set = isl_ast_build_eliminate_inner(build,
2862                                                         domain[order[i]].set);
2863                 base = i;
2864         }
2865
2866         return base;
2867 }
2868
2869 /* Given an array "domain" of isl_set_map_pairs and an array "order"
2870  * of indices into the "domain" array,
2871  * find the element of "domain" (amongst those indexed by the first "n"
2872  * elements of "order") with the "set" field that has the smallest
2873  * value for the current iterator.
2874  *
2875  * Note that the domain with the smallest value may depend on the parameters
2876  * and/or outer loop dimension.  Since the result of this function is only
2877  * used as heuristic, we only make a reasonable attempt at finding the best
2878  * domain, one that should work in case a single domain provides the smallest
2879  * value for the current dimension over all values of the parameters
2880  * and outer dimensions.
2881  *
2882  * In particular, we compute the smallest value of the first domain
2883  * and replace it by that of any later domain if that later domain
2884  * has a smallest value that is smaller for at least some value
2885  * of the parameters and outer dimensions.
2886  */
2887 static int first_offset(struct isl_set_map_pair *domain, int *order, int n,
2888         __isl_keep isl_ast_build *build)
2889 {
2890         int i;
2891         isl_map *min_first;
2892         int first = 0;
2893
2894         min_first = isl_ast_build_map_to_iterator(build,
2895                                         isl_set_copy(domain[order[0]].set));
2896         min_first = isl_map_lexmin(min_first);
2897
2898         for (i = 1; i < n; ++i) {
2899                 isl_map *min, *test;
2900                 int empty;
2901
2902                 min = isl_ast_build_map_to_iterator(build,
2903                                         isl_set_copy(domain[order[i]].set));
2904                 min = isl_map_lexmin(min);
2905                 test = isl_map_copy(min);
2906                 test = isl_map_apply_domain(isl_map_copy(min_first), test);
2907                 test = isl_map_order_lt(test, isl_dim_in, 0, isl_dim_out, 0);
2908                 empty = isl_map_is_empty(test);
2909                 isl_map_free(test);
2910                 if (empty >= 0 && !empty) {
2911                         isl_map_free(min_first);
2912                         first = i;
2913                         min_first = min;
2914                 } else
2915                         isl_map_free(min);
2916
2917                 if (empty < 0)
2918                         break;
2919         }
2920
2921         isl_map_free(min_first);
2922
2923         return i < n ? -1 : first;
2924 }
2925
2926 /* Construct a shifted inverse schedule based on the original inverse schedule,
2927  * the stride and the offset.
2928  *
2929  * The original inverse schedule is specified as the "map" fields
2930  * of the elements of "domain" indexed by the first "n" elements of "order".
2931  *
2932  * "stride" and "offset" are such that the difference
2933  * between the values of the current dimension of domain "i"
2934  * and the values of the current dimension for some reference domain are
2935  * equal to
2936  *
2937  *      stride * integer + offset[i]
2938  *
2939  * Moreover, 0 <= offset[i] < stride.
2940  *
2941  * For each domain, we create a map
2942  *
2943  *      { [..., j, ...] -> [..., j - offset[i], offset[i], ....] }
2944  *
2945  * where j refers to the current dimension and the other dimensions are
2946  * unchanged, and apply this map to the original schedule domain.
2947  *
2948  * For example, for the original schedule
2949  *
2950  *      { A[i] -> [2i]: 0 <= i < 10; B[i] -> [2i+1] : 0 <= i < 10 }
2951  *
2952  * and assuming the offset is 0 for the A domain and 1 for the B domain,
2953  * we apply the mapping
2954  *
2955  *      { [j] -> [j, 0] }
2956  *
2957  * to the schedule of the "A" domain and the mapping
2958  *
2959  *      { [j - 1] -> [j, 1] }
2960  *
2961  * to the schedule of the "B" domain.
2962  *
2963  *
2964  * Note that after the transformation, the differences between pairs
2965  * of values of the current dimension over all domains are multiples
2966  * of stride and that we have therefore exposed the stride.
2967  *
2968  *
2969  * To see that the mapping preserves the lexicographic order,
2970  * first note that each of the individual maps above preserves the order.
2971  * If the value of the current iterator is j1 in one domain and j2 in another,
2972  * then if j1 = j2, we know that the same map is applied to both domains
2973  * and the order is preserved.
2974  * Otherwise, let us assume, without loss of generality, that j1 < j2.
2975  * If c1 >= c2 (with c1 and c2 the corresponding offsets), then
2976  *
2977  *      j1 - c1 < j2 - c2
2978  *
2979  * and the order is preserved.
2980  * If c1 < c2, then we know
2981  *
2982  *      0 <= c2 - c1 < s
2983  *
2984  * We also have
2985  *
2986  *      j2 - j1 = n * s + r
2987  *
2988  * with n >= 0 and 0 <= r < s.
2989  * In other words, r = c2 - c1.
2990  * If n > 0, then
2991  *
2992  *      j1 - c1 < j2 - c2
2993  *
2994  * If n = 0, then
2995  *
2996  *      j1 - c1 = j2 - c2
2997  *
2998  * and so
2999  *
3000  *      (j1 - c1, c1) << (j2 - c2, c2)
3001  *
3002  * with "<<" the lexicographic order, proving that the order is preserved
3003  * in all cases.
3004  */
3005 static __isl_give isl_union_map *contruct_shifted_executed(
3006         struct isl_set_map_pair *domain, int *order, int n, isl_int stride,
3007         __isl_keep isl_vec *offset, __isl_keep isl_ast_build *build)
3008 {
3009         int i;
3010         isl_int v;
3011         isl_union_map *executed;
3012         isl_space *space;
3013         isl_map *map;
3014         int depth;
3015         isl_constraint *c;
3016
3017         depth = isl_ast_build_get_depth(build);
3018         space = isl_ast_build_get_space(build, 1);
3019         executed = isl_union_map_empty(isl_space_copy(space));
3020         space = isl_space_map_from_set(space);
3021         map = isl_map_identity(isl_space_copy(space));
3022         map = isl_map_eliminate(map, isl_dim_out, depth, 1);
3023         map = isl_map_insert_dims(map, isl_dim_out, depth + 1, 1);
3024         space = isl_space_insert_dims(space, isl_dim_out, depth + 1, 1);
3025
3026         c = isl_equality_alloc(isl_local_space_from_space(space));
3027         c = isl_constraint_set_coefficient_si(c, isl_dim_in, depth, 1);
3028         c = isl_constraint_set_coefficient_si(c, isl_dim_out, depth, -1);
3029
3030         isl_int_init(v);
3031
3032         for (i = 0; i < n; ++i) {
3033                 isl_map *map_i;
3034
3035                 if (isl_vec_get_element(offset, i, &v) < 0)
3036                         break;
3037                 map_i = isl_map_copy(map);
3038                 map_i = isl_map_fix(map_i, isl_dim_out, depth + 1, v);
3039                 isl_int_neg(v, v);
3040                 c = isl_constraint_set_constant(c, v);
3041                 map_i = isl_map_add_constraint(map_i, isl_constraint_copy(c));
3042
3043                 map_i = isl_map_apply_domain(isl_map_copy(domain[order[i]].map),
3044                                                 map_i);
3045                 executed = isl_union_map_add_map(executed, map_i);
3046         }
3047
3048         isl_constraint_free(c);
3049         isl_map_free(map);
3050
3051         isl_int_clear(v);
3052
3053         if (i < n)
3054                 executed = isl_union_map_free(executed);
3055
3056         return executed;
3057 }
3058
3059 /* Generate code for a single component, after exposing the stride,
3060  * given that the schedule domain is "shifted strided".
3061  *
3062  * The component inverse schedule is specified as the "map" fields
3063  * of the elements of "domain" indexed by the first "n" elements of "order".
3064  *
3065  * The schedule domain being "shifted strided" means that the differences
3066  * between the values of the current dimension of domain "i"
3067  * and the values of the current dimension for some reference domain are
3068  * equal to
3069  *
3070  *      stride * integer + offset[i]
3071  *
3072  * We first look for the domain with the "smallest" value for the current
3073  * dimension and adjust the offsets such that the offset of the "smallest"
3074  * domain is equal to zero.  The other offsets are reduced modulo stride.
3075  *
3076  * Based on this information, we construct a new inverse schedule in
3077  * contruct_shifted_executed that exposes the stride.
3078  * Since this involves the introduction of a new schedule dimension,
3079  * the build needs to be changed accodingly.
3080  * After computing the AST, the newly introduced dimension needs
3081  * to be removed again from the list of grafts.  We do this by plugging
3082  * in a mapping that represents the new schedule domain in terms of the
3083  * old schedule domain.
3084  */
3085 static __isl_give isl_ast_graft_list *generate_shift_component(
3086         struct isl_set_map_pair *domain, int *order, int n, isl_int stride,
3087         __isl_keep isl_vec *offset, __isl_take isl_ast_build *build)
3088 {
3089         isl_ast_graft_list *list;
3090         int first;
3091         int depth;
3092         isl_ctx *ctx;
3093         isl_int val;
3094         isl_vec *v;
3095         isl_space *space;
3096         isl_multi_aff *ma, *zero;
3097         isl_union_map *executed;
3098
3099         ctx = isl_ast_build_get_ctx(build);
3100         depth = isl_ast_build_get_depth(build);
3101
3102         first = first_offset(domain, order, n, build);
3103         if (first < 0)
3104                 return isl_ast_build_free(build);
3105
3106         isl_int_init(val);
3107         v = isl_vec_alloc(ctx, n);
3108         if (isl_vec_get_element(offset, first, &val) < 0)
3109                 v = isl_vec_free(v);
3110         isl_int_neg(val, val);
3111         v = isl_vec_set(v, val);
3112         v = isl_vec_add(v, isl_vec_copy(offset));
3113         v = isl_vec_fdiv_r(v, stride);
3114
3115         executed = contruct_shifted_executed(domain, order, n, stride, v,
3116                                                 build);
3117         space = isl_ast_build_get_space(build, 1);
3118         space = isl_space_map_from_set(space);
3119         ma = isl_multi_aff_identity(isl_space_copy(space));
3120         space = isl_space_from_domain(isl_space_domain(space));
3121         space = isl_space_add_dims(space, isl_dim_out, 1);
3122         zero = isl_multi_aff_zero(space);
3123         ma = isl_multi_aff_range_splice(ma, depth + 1, zero);
3124         build = isl_ast_build_insert_dim(build, depth + 1);
3125         list = generate_shifted_component(executed, build);
3126
3127         list = isl_ast_graft_list_preimage_multi_aff(list, ma);
3128
3129         isl_vec_free(v);
3130         isl_int_clear(val);
3131
3132         return list;
3133 }
3134
3135 /* Generate code for a single component.
3136  *
3137  * The component inverse schedule is specified as the "map" fields
3138  * of the elements of "domain" indexed by the first "n" elements of "order".
3139  *
3140  * This function may modify the "set" fields of "domain".
3141  *
3142  * Before proceeding with the actual code generation for the component,
3143  * we first check if there are any "shifted" strides, meaning that
3144  * the schedule domains of the individual domains are all strided,
3145  * but that they have different offsets, resulting in the union
3146  * of schedule domains not being strided anymore.
3147  *
3148  * The simplest example is the schedule
3149  *
3150  *      { A[i] -> [2i]: 0 <= i < 10; B[i] -> [2i+1] : 0 <= i < 10 }
3151  *
3152  * Both schedule domains are strided, but their union is not.
3153  * This function detects such cases and then rewrites the schedule to
3154  *
3155  *      { A[i] -> [2i, 0]: 0 <= i < 10; B[i] -> [2i, 1] : 0 <= i < 10 }
3156  *
3157  * In the new schedule, the schedule domains have the same offset (modulo
3158  * the stride), ensuring that the union of schedule domains is also strided.
3159  *
3160  *
3161  * If there is only a single domain in the component, then there is
3162  * nothing to do.   Similarly, if the current schedule dimension has
3163  * a fixed value for almost all domains then there is nothing to be done.
3164  * In particular, we need at least two domains where the current schedule
3165  * dimension does not have a fixed value.
3166  * Finally, if any of the options refer to the current schedule dimension,
3167  * then we bail out as well.  It would be possible to reformulate the options
3168  * in terms of the new schedule domain, but that would introduce constraints
3169  * that separate the domains in the options and that is something we would
3170  * like to avoid.
3171  *
3172  *
3173  * To see if there is any shifted stride, we look at the differences
3174  * between the values of the current dimension in pairs of domains
3175  * for equal values of outer dimensions.  These differences should be
3176  * of the form
3177  *
3178  *      m x + r
3179  *
3180  * with "m" the stride and "r" a constant.  Note that we cannot perform
3181  * this analysis on individual domains as the lower bound in each domain
3182  * may depend on parameters or outer dimensions and so the current dimension
3183  * itself may not have a fixed remainder on division by the stride.
3184  *
3185  * In particular, we compare the first domain that does not have an
3186  * obviously fixed value for the current dimension to itself and all
3187  * other domains and collect the offsets and the gcd of the strides.
3188  * If the gcd becomes one, then we failed to find shifted strides.
3189  * If all the offsets are the same (for those domains that do not have
3190  * an obviously fixed value for the current dimension), then we do not
3191  * apply the transformation.
3192  * If none of the domains were skipped, then there is nothing to do.
3193  * If some of them were skipped, then if we apply separation, the schedule
3194  * domain should get split in pieces with a (non-shifted) stride.
3195  *
3196  * Otherwise, we apply a shift to expose the stride in
3197  * generate_shift_component.
3198  */
3199 static __isl_give isl_ast_graft_list *generate_component(
3200         struct isl_set_map_pair *domain, int *order, int n,
3201         __isl_take isl_ast_build *build)
3202 {
3203         int i, d;
3204         int depth;
3205         isl_ctx *ctx;
3206         isl_map *map;
3207         isl_set *deltas;
3208         isl_int m, r, gcd;
3209         isl_vec *v;
3210         int fixed, skip;
3211         int base;
3212         isl_ast_graft_list *list;
3213         int res = 0;
3214
3215         depth = isl_ast_build_get_depth(build);
3216
3217         skip = n == 1;
3218         if (skip >= 0 && !skip)
3219                 skip = at_most_one_non_fixed(domain, order, n, depth);
3220         if (skip >= 0 && !skip)
3221                 skip = isl_ast_build_options_involve_depth(build);
3222         if (skip < 0)
3223                 return isl_ast_build_free(build);
3224         if (skip)
3225                 return generate_shifted_component_from_list(domain,
3226                                                             order, n, build);
3227
3228         base = eliminate_non_fixed(domain, order, n, depth, build);
3229         if (base < 0)
3230                 return isl_ast_build_free(build);
3231
3232         ctx = isl_ast_build_get_ctx(build);
3233
3234         isl_int_init(m);
3235         isl_int_init(r);
3236         isl_int_init(gcd);
3237         v = isl_vec_alloc(ctx, n);
3238
3239         fixed = 1;
3240         for (i = 0; i < n; ++i) {
3241                 map = isl_map_from_domain_and_range(
3242                                         isl_set_copy(domain[order[base]].set),
3243                                         isl_set_copy(domain[order[i]].set));
3244                 for (d = 0; d < depth; ++d)
3245                         map = isl_map_equate(map, isl_dim_in, d,
3246                                                     isl_dim_out, d);
3247                 deltas = isl_map_deltas(map);
3248                 res = isl_set_dim_residue_class(deltas, depth, &m, &r);
3249                 isl_set_free(deltas);
3250                 if (res < 0)
3251                         break;
3252
3253                 if (i == 0)
3254                         isl_int_set(gcd, m);
3255                 else
3256                         isl_int_gcd(gcd, gcd, m);
3257                 if (isl_int_is_one(gcd))
3258                         break;
3259                 v = isl_vec_set_element(v, i, r);
3260
3261                 res = isl_set_plain_is_fixed(domain[order[i]].set,
3262                                                 isl_dim_set, depth, NULL);
3263                 if (res < 0)
3264                         break;
3265                 if (res)
3266                         continue;
3267
3268                 if (fixed && i > base) {
3269                         isl_vec_get_element(v, base, &m);
3270                         if (isl_int_ne(m, r))
3271                                 fixed = 0;
3272                 }
3273         }
3274
3275         if (res < 0) {
3276                 isl_ast_build_free(build);
3277                 list = NULL;
3278         } else if (i < n || fixed) {
3279                 list = generate_shifted_component_from_list(domain,
3280                                                             order, n, build);
3281         } else {
3282                 list = generate_shift_component(domain, order, n, gcd, v,
3283                                                 build);
3284         }
3285
3286         isl_vec_free(v);
3287         isl_int_clear(gcd);
3288         isl_int_clear(r);
3289         isl_int_clear(m);
3290
3291         return list;
3292 }
3293
3294 /* Store both "map" itself and its domain in the
3295  * structure pointed to by *next and advance to the next array element.
3296  */
3297 static int extract_domain(__isl_take isl_map *map, void *user)
3298 {
3299         struct isl_set_map_pair **next = user;
3300
3301         (*next)->map = isl_map_copy(map);
3302         (*next)->set = isl_map_domain(map);
3303         (*next)++;
3304
3305         return 0;
3306 }
3307
3308 /* Internal data for any_scheduled_after.
3309  *
3310  * "depth" is the number of loops that have already been generated
3311  * "group_coscheduled" is a local copy of options->ast_build_group_coscheduled
3312  * "domain" is an array of set-map pairs corresponding to the different
3313  * iteration domains.  The set is the schedule domain, i.e., the domain
3314  * of the inverse schedule, while the map is the inverse schedule itself.
3315  */
3316 struct isl_any_scheduled_after_data {
3317         int depth;
3318         int group_coscheduled;
3319         struct isl_set_map_pair *domain;
3320 };
3321
3322 /* Is any element of domain "i" scheduled after any element of domain "j"
3323  * (for a common iteration of the first data->depth loops)?
3324  *
3325  * data->domain[i].set contains the domain of the inverse schedule
3326  * for domain "i", i.e., elements in the schedule domain.
3327  *
3328  * If data->group_coscheduled is set, then we also return 1 if there
3329  * is any pair of elements in the two domains that are scheduled together.
3330  */
3331 static int any_scheduled_after(int i, int j, void *user)
3332 {
3333         struct isl_any_scheduled_after_data *data = user;
3334         int dim = isl_set_dim(data->domain[i].set, isl_dim_set);
3335         int pos;
3336
3337         for (pos = data->depth; pos < dim; ++pos) {
3338                 int follows;
3339
3340                 follows = isl_set_follows_at(data->domain[i].set,
3341                                                 data->domain[j].set, pos);
3342
3343                 if (follows < -1)
3344                         return -1;
3345                 if (follows > 0)
3346                         return 1;
3347                 if (follows < 0)
3348                         return 0;
3349         }
3350
3351         return data->group_coscheduled;
3352 }
3353
3354 /* Look for independent components at the current depth and generate code
3355  * for each component separately.  The resulting lists of grafts are
3356  * merged in an attempt to combine grafts with identical guards.
3357  *
3358  * Code for two domains can be generated separately if all the elements
3359  * of one domain are scheduled before (or together with) all the elements
3360  * of the other domain.  We therefore consider the graph with as nodes
3361  * the domains and an edge between two nodes if any element of the first
3362  * node is scheduled after any element of the second node.
3363  * If the ast_build_group_coscheduled is set, then we also add an edge if
3364  * there is any pair of elements in the two domains that are scheduled
3365  * together.
3366  * Code is then generated (by generate_component)
3367  * for each of the strongly connected components in this graph
3368  * in their topological order.
3369  *
3370  * Since the test is performed on the domain of the inverse schedules of
3371  * the different domains, we precompute these domains and store
3372  * them in data.domain.
3373  */
3374 static __isl_give isl_ast_graft_list *generate_components(
3375         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build)
3376 {
3377         int i;
3378         isl_ctx *ctx = isl_ast_build_get_ctx(build);
3379         int n = isl_union_map_n_map(executed);
3380         struct isl_any_scheduled_after_data data;
3381         struct isl_set_map_pair *next;
3382         struct isl_tarjan_graph *g = NULL;
3383         isl_ast_graft_list *list = NULL;
3384         int n_domain = 0;
3385
3386         data.domain = isl_calloc_array(ctx, struct isl_set_map_pair, n);
3387         if (!data.domain)
3388                 goto error;
3389         n_domain = n;
3390
3391         next = data.domain;
3392         if (isl_union_map_foreach_map(executed, &extract_domain, &next) < 0)
3393                 goto error;
3394
3395         if (!build)
3396                 goto error;
3397         data.depth = isl_ast_build_get_depth(build);
3398         data.group_coscheduled = isl_options_get_ast_build_group_coscheduled(ctx);
3399         g = isl_tarjan_graph_init(ctx, n, &any_scheduled_after, &data);
3400
3401         list = isl_ast_graft_list_alloc(ctx, 0);
3402
3403         i = 0;
3404         while (list && n) {
3405                 isl_ast_graft_list *list_c;
3406                 int first = i;
3407
3408                 if (g->order[i] == -1)
3409                         isl_die(ctx, isl_error_internal, "cannot happen",
3410                                 goto error);
3411                 ++i; --n;
3412                 while (g->order[i] != -1) {
3413                         ++i; --n;
3414                 }
3415
3416                 list_c = generate_component(data.domain,
3417                                             g->order + first, i - first,
3418                                             isl_ast_build_copy(build));
3419                 list = isl_ast_graft_list_merge(list, list_c, build);
3420
3421                 ++i;
3422         }
3423
3424         if (0)
3425 error:          list = isl_ast_graft_list_free(list);
3426         isl_tarjan_graph_free(g);
3427         for (i = 0; i < n_domain; ++i) {
3428                 isl_map_free(data.domain[i].map);
3429                 isl_set_free(data.domain[i].set);
3430         }
3431         free(data.domain);
3432         isl_union_map_free(executed);
3433         isl_ast_build_free(build);
3434
3435         return list;
3436 }
3437
3438 /* Generate code for the next level (and all inner levels).
3439  *
3440  * If "executed" is empty, i.e., no code needs to be generated,
3441  * then we return an empty list.
3442  *
3443  * If we have already generated code for all loop levels, then we pass
3444  * control to generate_inner_level.
3445  *
3446  * If "executed" lives in a single space, i.e., if code needs to be
3447  * generated for a single domain, then there can only be a single
3448  * component and we go directly to generate_shifted_component.
3449  * Otherwise, we call generate_components to detect the components
3450  * and to call generate_component on each of them separately.
3451  */
3452 static __isl_give isl_ast_graft_list *generate_next_level(
3453         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build)
3454 {
3455         int depth;
3456
3457         if (!build || !executed)
3458                 goto error;
3459
3460         if (isl_union_map_is_empty(executed)) {
3461                 isl_ctx *ctx = isl_ast_build_get_ctx(build);
3462                 isl_union_map_free(executed);
3463                 isl_ast_build_free(build);
3464                 return isl_ast_graft_list_alloc(ctx, 0);
3465         }
3466
3467         depth = isl_ast_build_get_depth(build);
3468         if (depth >= isl_set_dim(build->domain, isl_dim_set))
3469                 return generate_inner_level(executed, build);
3470
3471         if (isl_union_map_n_map(executed) == 1)
3472                 return generate_shifted_component(executed, build);
3473
3474         return generate_components(executed, build);
3475 error:
3476         isl_union_map_free(executed);
3477         isl_ast_build_free(build);
3478         return NULL;
3479 }
3480
3481 /* Internal data structure used by isl_ast_build_ast_from_schedule.
3482  * internal, executed and build are the inputs to generate_code.
3483  * list collects the output.
3484  */
3485 struct isl_generate_code_data {
3486         int internal;
3487         isl_union_map *executed;
3488         isl_ast_build *build;
3489
3490         isl_ast_graft_list *list;
3491 };
3492
3493 /* Given an inverse schedule in terms of the external build schedule, i.e.,
3494  *
3495  *      [E -> S] -> D
3496  *
3497  * with E the external build schedule and S the additional schedule "space",
3498  * reformulate the inverse schedule in terms of the internal schedule domain,
3499  * i.e., return
3500  *
3501  *      [I -> S] -> D
3502  *
3503  * We first obtain a mapping
3504  *
3505  *      I -> E
3506  *
3507  * take the inverse and the product with S -> S, resulting in
3508  *
3509  *      [I -> S] -> [E -> S]
3510  *
3511  * Applying the map to the input produces the desired result.
3512  */
3513 static __isl_give isl_union_map *internal_executed(
3514         __isl_take isl_union_map *executed, __isl_keep isl_space *space,
3515         __isl_keep isl_ast_build *build)
3516 {
3517         isl_map *id, *proj;
3518
3519         proj = isl_ast_build_get_schedule_map(build);
3520         proj = isl_map_reverse(proj);
3521         space = isl_space_map_from_set(isl_space_copy(space));
3522         id = isl_map_identity(space);
3523         proj = isl_map_product(proj, id);
3524         executed = isl_union_map_apply_domain(executed,
3525                                                 isl_union_map_from_map(proj));
3526         return executed;
3527 }
3528
3529 /* Generate an AST that visits the elements in the range of data->executed
3530  * in the relative order specified by the corresponding image element(s)
3531  * for those image elements that belong to "set".
3532  * Add the result to data->list.
3533  *
3534  * The caller ensures that "set" is a universe domain.
3535  * "space" is the space of the additional part of the schedule.
3536  * It is equal to the space of "set" if build->domain is parametric.
3537  * Otherwise, it is equal to the range of the wrapped space of "set".
3538  *
3539  * If the build space is not parametric and if isl_ast_build_ast_from_schedule
3540  * was called from an outside user (data->internal not set), then
3541  * the (inverse) schedule refers to the external build domain and needs to
3542  * be transformed to refer to the internal build domain.
3543  *
3544  * The build is extended to include the additional part of the schedule.
3545  * If the original build space was not parametric, then the options
3546  * in data->build refer only to the additional part of the schedule
3547  * and they need to be adjusted to refer to the complete AST build
3548  * domain.
3549  *
3550  * After having adjusted inverse schedule and build, we start generating
3551  * code with the outer loop of the current code generation
3552  * in generate_next_level.
3553  *
3554  * If the original build space was not parametric, we undo the embedding
3555  * on the resulting isl_ast_node_list so that it can be used within
3556  * the outer AST build.
3557  */
3558 static int generate_code_in_space(struct isl_generate_code_data *data,
3559         __isl_take isl_set *set, __isl_take isl_space *space)
3560 {
3561         isl_union_map *executed;
3562         isl_ast_build *build;
3563         isl_ast_graft_list *list;
3564         int embed;
3565
3566         executed = isl_union_map_copy(data->executed);
3567         executed = isl_union_map_intersect_domain(executed,
3568                                                  isl_union_set_from_set(set));
3569
3570         embed = !isl_set_is_params(data->build->domain);
3571         if (embed && !data->internal)
3572                 executed = internal_executed(executed, space, data->build);
3573
3574         build = isl_ast_build_copy(data->build);
3575         build = isl_ast_build_product(build, space);
3576
3577         list = generate_next_level(executed, build);
3578
3579         list = isl_ast_graft_list_unembed(list, embed);
3580
3581         data->list = isl_ast_graft_list_concat(data->list, list);
3582
3583         return 0;
3584 }
3585
3586 /* Generate an AST that visits the elements in the range of data->executed
3587  * in the relative order specified by the corresponding domain element(s)
3588  * for those domain elements that belong to "set".
3589  * Add the result to data->list.
3590  *
3591  * The caller ensures that "set" is a universe domain.
3592  *
3593  * If the build space S is not parametric, then the space of "set"
3594  * need to be a wrapped relation with S as domain.  That is, it needs
3595  * to be of the form
3596  *
3597  *      [S -> T]
3598  *
3599  * Check this property and pass control to generate_code_in_space
3600  * passing along T.
3601  * If the build space is not parametric, then T is the space of "set".
3602  */
3603 static int generate_code_set(__isl_take isl_set *set, void *user)
3604 {
3605         struct isl_generate_code_data *data = user;
3606         isl_space *space, *build_space;
3607         int is_domain;
3608
3609         space = isl_set_get_space(set);
3610
3611         if (isl_set_is_params(data->build->domain))
3612                 return generate_code_in_space(data, set, space);
3613
3614         build_space = isl_ast_build_get_space(data->build, data->internal);
3615         space = isl_space_unwrap(space);
3616         is_domain = isl_space_is_domain(build_space, space);
3617         isl_space_free(build_space);
3618         space = isl_space_range(space);
3619
3620         if (is_domain < 0)
3621                 goto error;
3622         if (!is_domain)
3623                 isl_die(isl_set_get_ctx(set), isl_error_invalid,
3624                         "invalid nested schedule space", goto error);
3625
3626         return generate_code_in_space(data, set, space);
3627 error:
3628         isl_set_free(set);
3629         isl_space_free(space);
3630         return -1;
3631 }
3632
3633 /* Generate an AST that visits the elements in the range of "executed"
3634  * in the relative order specified by the corresponding domain element(s).
3635  *
3636  * "build" is an isl_ast_build that has either been constructed by
3637  * isl_ast_build_from_context or passed to a callback set by
3638  * isl_ast_build_set_create_leaf.
3639  * In the first case, the space of the isl_ast_build is typically
3640  * a parametric space, although this is currently not enforced.
3641  * In the second case, the space is never a parametric space.
3642  * If the space S is not parametric, then the domain space(s) of "executed"
3643  * need to be wrapped relations with S as domain.
3644  *
3645  * If the domain of "executed" consists of several spaces, then an AST
3646  * is generated for each of them (in arbitrary order) and the results
3647  * are concatenated.
3648  *
3649  * If "internal" is set, then the domain "S" above refers to the internal
3650  * schedule domain representation.  Otherwise, it refers to the external
3651  * representation, as returned by isl_ast_build_get_schedule_space.
3652  *
3653  * We essentially run over all the spaces in the domain of "executed"
3654  * and call generate_code_set on each of them.
3655  */
3656 static __isl_give isl_ast_graft_list *generate_code(
3657         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build,
3658         int internal)
3659 {
3660         isl_ctx *ctx;
3661         struct isl_generate_code_data data = { 0 };
3662         isl_space *space;
3663         isl_union_set *schedule_domain;
3664         isl_union_map *universe;
3665
3666         if (!build)
3667                 goto error;
3668         space = isl_ast_build_get_space(build, 1);
3669         space = isl_space_align_params(space,
3670                                     isl_union_map_get_space(executed));
3671         space = isl_space_align_params(space,
3672                                     isl_union_map_get_space(build->options));
3673         build = isl_ast_build_align_params(build, isl_space_copy(space));
3674         executed = isl_union_map_align_params(executed, space);
3675         if (!executed || !build)
3676                 goto error;
3677
3678         ctx = isl_ast_build_get_ctx(build);
3679
3680         data.internal = internal;
3681         data.executed = executed;
3682         data.build = build;
3683         data.list = isl_ast_graft_list_alloc(ctx, 0);
3684
3685         universe = isl_union_map_universe(isl_union_map_copy(executed));
3686         schedule_domain = isl_union_map_domain(universe);
3687         if (isl_union_set_foreach_set(schedule_domain, &generate_code_set,
3688                                         &data) < 0)
3689                 data.list = isl_ast_graft_list_free(data.list);
3690
3691         isl_union_set_free(schedule_domain);
3692         isl_union_map_free(executed);
3693
3694         isl_ast_build_free(build);
3695         return data.list;
3696 error:
3697         isl_union_map_free(executed);
3698         isl_ast_build_free(build);
3699         return NULL;
3700 }
3701
3702 /* Generate an AST that visits the elements in the domain of "schedule"
3703  * in the relative order specified by the corresponding image element(s).
3704  *
3705  * "build" is an isl_ast_build that has either been constructed by
3706  * isl_ast_build_from_context or passed to a callback set by
3707  * isl_ast_build_set_create_leaf.
3708  * In the first case, the space of the isl_ast_build is typically
3709  * a parametric space, although this is currently not enforced.
3710  * In the second case, the space is never a parametric space.
3711  * If the space S is not parametric, then the range space(s) of "schedule"
3712  * need to be wrapped relations with S as domain.
3713  *
3714  * If the range of "schedule" consists of several spaces, then an AST
3715  * is generated for each of them (in arbitrary order) and the results
3716  * are concatenated.
3717  *
3718  * We first initialize the local copies of the relevant options.
3719  * We do this here rather than when the isl_ast_build is created
3720  * because the options may have changed between the construction
3721  * of the isl_ast_build and the call to isl_generate_code.
3722  *
3723  * The main computation is performed on an inverse schedule (with
3724  * the schedule domain in the domain and the elements to be executed
3725  * in the range) called "executed".
3726  */
3727 __isl_give isl_ast_node *isl_ast_build_ast_from_schedule(
3728         __isl_keep isl_ast_build *build, __isl_take isl_union_map *schedule)
3729 {
3730         isl_ast_graft_list *list;
3731         isl_ast_node *node;
3732         isl_union_map *executed;
3733
3734         build = isl_ast_build_copy(build);
3735         build = isl_ast_build_set_single_valued(build, 0);
3736         executed = isl_union_map_reverse(schedule);
3737         list = generate_code(executed, isl_ast_build_copy(build), 0);
3738         node = isl_ast_node_from_graft_list(list, build);
3739         isl_ast_build_free(build);
3740
3741         return node;
3742 }