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