isl_union_set_compute_schedule: double check that we do not run out of rows
[platform/upstream/isl.git] / isl_schedule.c
1 /*
2  * Copyright 2011      INRIA Saclay
3  *
4  * Use of this software is governed by the MIT license
5  *
6  * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
7  * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
8  * 91893 Orsay, France
9  */
10
11 #include <isl_ctx_private.h>
12 #include <isl_map_private.h>
13 #include <isl_space_private.h>
14 #include <isl/aff.h>
15 #include <isl/hash.h>
16 #include <isl/constraint.h>
17 #include <isl/schedule.h>
18 #include <isl_mat_private.h>
19 #include <isl/set.h>
20 #include <isl/seq.h>
21 #include <isl_tab.h>
22 #include <isl_dim_map.h>
23 #include <isl_hmap_map_basic_set.h>
24 #include <isl_sort.h>
25 #include <isl_schedule_private.h>
26 #include <isl_band_private.h>
27 #include <isl_list_private.h>
28 #include <isl_options_private.h>
29 #include <isl_tarjan.h>
30
31 /*
32  * The scheduling algorithm implemented in this file was inspired by
33  * Bondhugula et al., "Automatic Transformations for Communication-Minimized
34  * Parallelization and Locality Optimization in the Polyhedral Model".
35  */
36
37
38 /* Internal information about a node that is used during the construction
39  * of a schedule.
40  * dim represents the space in which the domain lives
41  * sched is a matrix representation of the schedule being constructed
42  *      for this node
43  * sched_map is an isl_map representation of the same (partial) schedule
44  *      sched_map may be NULL
45  * rank is the number of linearly independent rows in the linear part
46  *      of sched
47  * the columns of cmap represent a change of basis for the schedule
48  *      coefficients; the first rank columns span the linear part of
49  *      the schedule rows
50  * start is the first variable in the LP problem in the sequences that
51  *      represents the schedule coefficients of this node
52  * nvar is the dimension of the domain
53  * nparam is the number of parameters or 0 if we are not constructing
54  *      a parametric schedule
55  *
56  * scc is the index of SCC (or WCC) this node belongs to
57  *
58  * band contains the band index for each of the rows of the schedule.
59  * band_id is used to differentiate between separate bands at the same
60  * level within the same parent band, i.e., bands that are separated
61  * by the parent band or bands that are independent of each other.
62  * zero contains a boolean for each of the rows of the schedule,
63  * indicating whether the corresponding scheduling dimension results
64  * in zero dependence distances within its band and with respect
65  * to the proximity edges.
66  */
67 struct isl_sched_node {
68         isl_space *dim;
69         isl_mat *sched;
70         isl_map *sched_map;
71         int      rank;
72         isl_mat *cmap;
73         int      start;
74         int      nvar;
75         int      nparam;
76
77         int      scc;
78
79         int     *band;
80         int     *band_id;
81         int     *zero;
82 };
83
84 static int node_has_dim(const void *entry, const void *val)
85 {
86         struct isl_sched_node *node = (struct isl_sched_node *)entry;
87         isl_space *dim = (isl_space *)val;
88
89         return isl_space_is_equal(node->dim, dim);
90 }
91
92 /* An edge in the dependence graph.  An edge may be used to
93  * ensure validity of the generated schedule, to minimize the dependence
94  * distance or both
95  *
96  * map is the dependence relation
97  * src is the source node
98  * dst is the sink node
99  * validity is set if the edge is used to ensure correctness
100  * proximity is set if the edge is used to minimize dependence distances
101  *
102  * For validity edges, start and end mark the sequence of inequality
103  * constraints in the LP problem that encode the validity constraint
104  * corresponding to this edge.
105  */
106 struct isl_sched_edge {
107         isl_map *map;
108
109         struct isl_sched_node *src;
110         struct isl_sched_node *dst;
111
112         int validity;
113         int proximity;
114
115         int start;
116         int end;
117 };
118
119 enum isl_edge_type {
120         isl_edge_validity = 0,
121         isl_edge_first = isl_edge_validity,
122         isl_edge_proximity,
123         isl_edge_last = isl_edge_proximity
124 };
125
126 /* Internal information about the dependence graph used during
127  * the construction of the schedule.
128  *
129  * intra_hmap is a cache, mapping dependence relations to their dual,
130  *      for dependences from a node to itself
131  * inter_hmap is a cache, mapping dependence relations to their dual,
132  *      for dependences between distinct nodes
133  *
134  * n is the number of nodes
135  * node is the list of nodes
136  * maxvar is the maximal number of variables over all nodes
137  * max_row is the allocated number of rows in the schedule
138  * n_row is the current (maximal) number of linearly independent
139  *      rows in the node schedules
140  * n_total_row is the current number of rows in the node schedules
141  * n_band is the current number of completed bands
142  * band_start is the starting row in the node schedules of the current band
143  * root is set if this graph is the original dependence graph,
144  *      without any splitting
145  *
146  * sorted contains a list of node indices sorted according to the
147  *      SCC to which a node belongs
148  *
149  * n_edge is the number of edges
150  * edge is the list of edges
151  * max_edge contains the maximal number of edges of each type;
152  *      in particular, it contains the number of edges in the inital graph.
153  * edge_table contains pointers into the edge array, hashed on the source
154  *      and sink spaces; there is one such table for each type;
155  *      a given edge may be referenced from more than one table
156  *      if the corresponding relation appears in more than of the
157  *      sets of dependences
158  *
159  * node_table contains pointers into the node array, hashed on the space
160  *
161  * region contains a list of variable sequences that should be non-trivial
162  *
163  * lp contains the (I)LP problem used to obtain new schedule rows
164  *
165  * src_scc and dst_scc are the source and sink SCCs of an edge with
166  *      conflicting constraints
167  *
168  * scc represents the number of components
169  */
170 struct isl_sched_graph {
171         isl_hmap_map_basic_set *intra_hmap;
172         isl_hmap_map_basic_set *inter_hmap;
173
174         struct isl_sched_node *node;
175         int n;
176         int maxvar;
177         int max_row;
178         int n_row;
179
180         int *sorted;
181
182         int n_band;
183         int n_total_row;
184         int band_start;
185
186         int root;
187
188         struct isl_sched_edge *edge;
189         int n_edge;
190         int max_edge[isl_edge_last + 1];
191         struct isl_hash_table *edge_table[isl_edge_last + 1];
192
193         struct isl_hash_table *node_table;
194         struct isl_region *region;
195
196         isl_basic_set *lp;
197
198         int src_scc;
199         int dst_scc;
200
201         int scc;
202 };
203
204 /* Initialize node_table based on the list of nodes.
205  */
206 static int graph_init_table(isl_ctx *ctx, struct isl_sched_graph *graph)
207 {
208         int i;
209
210         graph->node_table = isl_hash_table_alloc(ctx, graph->n);
211         if (!graph->node_table)
212                 return -1;
213
214         for (i = 0; i < graph->n; ++i) {
215                 struct isl_hash_table_entry *entry;
216                 uint32_t hash;
217
218                 hash = isl_space_get_hash(graph->node[i].dim);
219                 entry = isl_hash_table_find(ctx, graph->node_table, hash,
220                                             &node_has_dim,
221                                             graph->node[i].dim, 1);
222                 if (!entry)
223                         return -1;
224                 entry->data = &graph->node[i];
225         }
226
227         return 0;
228 }
229
230 /* Return a pointer to the node that lives within the given space,
231  * or NULL if there is no such node.
232  */
233 static struct isl_sched_node *graph_find_node(isl_ctx *ctx,
234         struct isl_sched_graph *graph, __isl_keep isl_space *dim)
235 {
236         struct isl_hash_table_entry *entry;
237         uint32_t hash;
238
239         hash = isl_space_get_hash(dim);
240         entry = isl_hash_table_find(ctx, graph->node_table, hash,
241                                     &node_has_dim, dim, 0);
242
243         return entry ? entry->data : NULL;
244 }
245
246 static int edge_has_src_and_dst(const void *entry, const void *val)
247 {
248         const struct isl_sched_edge *edge = entry;
249         const struct isl_sched_edge *temp = val;
250
251         return edge->src == temp->src && edge->dst == temp->dst;
252 }
253
254 /* Add the given edge to graph->edge_table[type].
255  */
256 static int graph_edge_table_add(isl_ctx *ctx, struct isl_sched_graph *graph,
257         enum isl_edge_type type, struct isl_sched_edge *edge)
258 {
259         struct isl_hash_table_entry *entry;
260         uint32_t hash;
261
262         hash = isl_hash_init();
263         hash = isl_hash_builtin(hash, edge->src);
264         hash = isl_hash_builtin(hash, edge->dst);
265         entry = isl_hash_table_find(ctx, graph->edge_table[type], hash,
266                                     &edge_has_src_and_dst, edge, 1);
267         if (!entry)
268                 return -1;
269         entry->data = edge;
270
271         return 0;
272 }
273
274 /* Allocate the edge_tables based on the maximal number of edges of
275  * each type.
276  */
277 static int graph_init_edge_tables(isl_ctx *ctx, struct isl_sched_graph *graph)
278 {
279         int i;
280
281         for (i = 0; i <= isl_edge_last; ++i) {
282                 graph->edge_table[i] = isl_hash_table_alloc(ctx,
283                                                             graph->max_edge[i]);
284                 if (!graph->edge_table[i])
285                         return -1;
286         }
287
288         return 0;
289 }
290
291 /* If graph->edge_table[type] contains an edge from the given source
292  * to the given destination, then return the hash table entry of this edge.
293  * Otherwise, return NULL.
294  */
295 static struct isl_hash_table_entry *graph_find_edge_entry(
296         struct isl_sched_graph *graph,
297         enum isl_edge_type type,
298         struct isl_sched_node *src, struct isl_sched_node *dst)
299 {
300         isl_ctx *ctx = isl_space_get_ctx(src->dim);
301         uint32_t hash;
302         struct isl_sched_edge temp = { .src = src, .dst = dst };
303
304         hash = isl_hash_init();
305         hash = isl_hash_builtin(hash, temp.src);
306         hash = isl_hash_builtin(hash, temp.dst);
307         return isl_hash_table_find(ctx, graph->edge_table[type], hash,
308                                     &edge_has_src_and_dst, &temp, 0);
309 }
310
311
312 /* If graph->edge_table[type] contains an edge from the given source
313  * to the given destination, then return this edge.
314  * Otherwise, return NULL.
315  */
316 static struct isl_sched_edge *graph_find_edge(struct isl_sched_graph *graph,
317         enum isl_edge_type type,
318         struct isl_sched_node *src, struct isl_sched_node *dst)
319 {
320         struct isl_hash_table_entry *entry;
321
322         entry = graph_find_edge_entry(graph, type, src, dst);
323         if (!entry)
324                 return NULL;
325
326         return entry->data;
327 }
328
329 /* Check whether the dependence graph has an edge of the give type
330  * between the given two nodes.
331  */
332 static int graph_has_edge(struct isl_sched_graph *graph,
333         enum isl_edge_type type,
334         struct isl_sched_node *src, struct isl_sched_node *dst)
335 {
336         struct isl_sched_edge *edge;
337         int empty;
338
339         edge = graph_find_edge(graph, type, src, dst);
340         if (!edge)
341                 return 0;
342
343         empty = isl_map_plain_is_empty(edge->map);
344         if (empty < 0)
345                 return -1;
346
347         return !empty;
348 }
349
350 /* If there is an edge from the given source to the given destination
351  * of any type then return this edge.
352  * Otherwise, return NULL.
353  */
354 static struct isl_sched_edge *graph_find_any_edge(struct isl_sched_graph *graph,
355         struct isl_sched_node *src, struct isl_sched_node *dst)
356 {
357         enum isl_edge_type i;
358         struct isl_sched_edge *edge;
359
360         for (i = isl_edge_first; i <= isl_edge_last; ++i) {
361                 edge = graph_find_edge(graph, i, src, dst);
362                 if (edge)
363                         return edge;
364         }
365
366         return NULL;
367 }
368
369 /* Remove the given edge from all the edge_tables that refer to it.
370  */
371 static void graph_remove_edge(struct isl_sched_graph *graph,
372         struct isl_sched_edge *edge)
373 {
374         isl_ctx *ctx = isl_map_get_ctx(edge->map);
375         enum isl_edge_type i;
376
377         for (i = isl_edge_first; i <= isl_edge_last; ++i) {
378                 struct isl_hash_table_entry *entry;
379
380                 entry = graph_find_edge_entry(graph, i, edge->src, edge->dst);
381                 if (!entry)
382                         continue;
383                 if (entry->data != edge)
384                         continue;
385                 isl_hash_table_remove(ctx, graph->edge_table[i], entry);
386         }
387 }
388
389 /* Check whether the dependence graph has any edge
390  * between the given two nodes.
391  */
392 static int graph_has_any_edge(struct isl_sched_graph *graph,
393         struct isl_sched_node *src, struct isl_sched_node *dst)
394 {
395         enum isl_edge_type i;
396         int r;
397
398         for (i = isl_edge_first; i <= isl_edge_last; ++i) {
399                 r = graph_has_edge(graph, i, src, dst);
400                 if (r < 0 || r)
401                         return r;
402         }
403
404         return r;
405 }
406
407 /* Check whether the dependence graph has a validity edge
408  * between the given two nodes.
409  */
410 static int graph_has_validity_edge(struct isl_sched_graph *graph,
411         struct isl_sched_node *src, struct isl_sched_node *dst)
412 {
413         return graph_has_edge(graph, isl_edge_validity, src, dst);
414 }
415
416 static int graph_alloc(isl_ctx *ctx, struct isl_sched_graph *graph,
417         int n_node, int n_edge)
418 {
419         int i;
420
421         graph->n = n_node;
422         graph->n_edge = n_edge;
423         graph->node = isl_calloc_array(ctx, struct isl_sched_node, graph->n);
424         graph->sorted = isl_calloc_array(ctx, int, graph->n);
425         graph->region = isl_alloc_array(ctx, struct isl_region, graph->n);
426         graph->edge = isl_calloc_array(ctx,
427                                         struct isl_sched_edge, graph->n_edge);
428
429         graph->intra_hmap = isl_hmap_map_basic_set_alloc(ctx, 2 * n_edge);
430         graph->inter_hmap = isl_hmap_map_basic_set_alloc(ctx, 2 * n_edge);
431
432         if (!graph->node || !graph->region || !graph->edge || !graph->sorted)
433                 return -1;
434
435         for(i = 0; i < graph->n; ++i)
436                 graph->sorted[i] = i;
437
438         return 0;
439 }
440
441 static void graph_free(isl_ctx *ctx, struct isl_sched_graph *graph)
442 {
443         int i;
444
445         isl_hmap_map_basic_set_free(ctx, graph->intra_hmap);
446         isl_hmap_map_basic_set_free(ctx, graph->inter_hmap);
447
448         for (i = 0; i < graph->n; ++i) {
449                 isl_space_free(graph->node[i].dim);
450                 isl_mat_free(graph->node[i].sched);
451                 isl_map_free(graph->node[i].sched_map);
452                 isl_mat_free(graph->node[i].cmap);
453                 if (graph->root) {
454                         free(graph->node[i].band);
455                         free(graph->node[i].band_id);
456                         free(graph->node[i].zero);
457                 }
458         }
459         free(graph->node);
460         free(graph->sorted);
461         for (i = 0; i < graph->n_edge; ++i)
462                 isl_map_free(graph->edge[i].map);
463         free(graph->edge);
464         free(graph->region);
465         for (i = 0; i <= isl_edge_last; ++i)
466                 isl_hash_table_free(ctx, graph->edge_table[i]);
467         isl_hash_table_free(ctx, graph->node_table);
468         isl_basic_set_free(graph->lp);
469 }
470
471 /* For each "set" on which this function is called, increment
472  * graph->n by one and update graph->maxvar.
473  */
474 static int init_n_maxvar(__isl_take isl_set *set, void *user)
475 {
476         struct isl_sched_graph *graph = user;
477         int nvar = isl_set_dim(set, isl_dim_set);
478
479         graph->n++;
480         if (nvar > graph->maxvar)
481                 graph->maxvar = nvar;
482
483         isl_set_free(set);
484
485         return 0;
486 }
487
488 /* Compute the number of rows that should be allocated for the schedule.
489  * The graph can be split at most "n - 1" times, there can be at most
490  * two rows for each dimension in the iteration domains (in particular,
491  * we usually have one row, but it may be split by split_scaled),
492  * and there can be one extra row for ordering the statements.
493  * Note that if we have actually split "n - 1" times, then no ordering
494  * is needed, so in principle we could use "graph->n + 2 * graph->maxvar - 1".
495  */
496 static int compute_max_row(struct isl_sched_graph *graph,
497         __isl_keep isl_union_set *domain)
498 {
499         graph->n = 0;
500         graph->maxvar = 0;
501         if (isl_union_set_foreach_set(domain, &init_n_maxvar, graph) < 0)
502                 return -1;
503         graph->max_row = graph->n + 2 * graph->maxvar;
504
505         return 0;
506 }
507
508 /* Add a new node to the graph representing the given set.
509  */
510 static int extract_node(__isl_take isl_set *set, void *user)
511 {
512         int nvar, nparam;
513         isl_ctx *ctx;
514         isl_space *dim;
515         isl_mat *sched;
516         struct isl_sched_graph *graph = user;
517         int *band, *band_id, *zero;
518
519         ctx = isl_set_get_ctx(set);
520         dim = isl_set_get_space(set);
521         isl_set_free(set);
522         nvar = isl_space_dim(dim, isl_dim_set);
523         nparam = isl_space_dim(dim, isl_dim_param);
524         if (!ctx->opt->schedule_parametric)
525                 nparam = 0;
526         sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
527         graph->node[graph->n].dim = dim;
528         graph->node[graph->n].nvar = nvar;
529         graph->node[graph->n].nparam = nparam;
530         graph->node[graph->n].sched = sched;
531         graph->node[graph->n].sched_map = NULL;
532         band = isl_alloc_array(ctx, int, graph->max_row);
533         graph->node[graph->n].band = band;
534         band_id = isl_calloc_array(ctx, int, graph->max_row);
535         graph->node[graph->n].band_id = band_id;
536         zero = isl_calloc_array(ctx, int, graph->max_row);
537         graph->node[graph->n].zero = zero;
538         graph->n++;
539
540         if (!sched || !band || !band_id || !zero)
541                 return -1;
542
543         return 0;
544 }
545
546 struct isl_extract_edge_data {
547         enum isl_edge_type type;
548         struct isl_sched_graph *graph;
549 };
550
551 /* Add a new edge to the graph based on the given map
552  * and add it to data->graph->edge_table[data->type].
553  * If a dependence relation of a given type happens to be identical
554  * to one of the dependence relations of a type that was added before,
555  * then we don't create a new edge, but instead mark the original edge
556  * as also representing a dependence of the current type.
557  */
558 static int extract_edge(__isl_take isl_map *map, void *user)
559 {
560         isl_ctx *ctx = isl_map_get_ctx(map);
561         struct isl_extract_edge_data *data = user;
562         struct isl_sched_graph *graph = data->graph;
563         struct isl_sched_node *src, *dst;
564         isl_space *dim;
565         struct isl_sched_edge *edge;
566         int is_equal;
567
568         dim = isl_space_domain(isl_map_get_space(map));
569         src = graph_find_node(ctx, graph, dim);
570         isl_space_free(dim);
571         dim = isl_space_range(isl_map_get_space(map));
572         dst = graph_find_node(ctx, graph, dim);
573         isl_space_free(dim);
574
575         if (!src || !dst) {
576                 isl_map_free(map);
577                 return 0;
578         }
579
580         graph->edge[graph->n_edge].src = src;
581         graph->edge[graph->n_edge].dst = dst;
582         graph->edge[graph->n_edge].map = map;
583         if (data->type == isl_edge_validity) {
584                 graph->edge[graph->n_edge].validity = 1;
585                 graph->edge[graph->n_edge].proximity = 0;
586         }
587         if (data->type == isl_edge_proximity) {
588                 graph->edge[graph->n_edge].validity = 0;
589                 graph->edge[graph->n_edge].proximity = 1;
590         }
591         graph->n_edge++;
592
593         edge = graph_find_any_edge(graph, src, dst);
594         if (!edge)
595                 return graph_edge_table_add(ctx, graph, data->type,
596                                     &graph->edge[graph->n_edge - 1]);
597         is_equal = isl_map_plain_is_equal(map, edge->map);
598         if (is_equal < 0)
599                 return -1;
600         if (!is_equal)
601                 return graph_edge_table_add(ctx, graph, data->type,
602                                     &graph->edge[graph->n_edge - 1]);
603
604         graph->n_edge--;
605         edge->validity |= graph->edge[graph->n_edge].validity;
606         edge->proximity |= graph->edge[graph->n_edge].proximity;
607         isl_map_free(map);
608
609         return graph_edge_table_add(ctx, graph, data->type, edge);
610 }
611
612 /* Check whether there is any dependence from node[j] to node[i]
613  * or from node[i] to node[j].
614  */
615 static int node_follows_weak(int i, int j, void *user)
616 {
617         int f;
618         struct isl_sched_graph *graph = user;
619
620         f = graph_has_any_edge(graph, &graph->node[j], &graph->node[i]);
621         if (f < 0 || f)
622                 return f;
623         return graph_has_any_edge(graph, &graph->node[i], &graph->node[j]);
624 }
625
626 /* Check whether there is a validity dependence from node[j] to node[i],
627  * forcing node[i] to follow node[j].
628  */
629 static int node_follows_strong(int i, int j, void *user)
630 {
631         struct isl_sched_graph *graph = user;
632
633         return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
634 }
635
636 /* Use Tarjan's algorithm for computing the strongly connected components
637  * in the dependence graph (only validity edges).
638  * If weak is set, we consider the graph to be undirected and
639  * we effectively compute the (weakly) connected components.
640  * Additionally, we also consider other edges when weak is set.
641  */
642 static int detect_ccs(isl_ctx *ctx, struct isl_sched_graph *graph, int weak)
643 {
644         int i, n;
645         struct isl_tarjan_graph *g = NULL;
646
647         g = isl_tarjan_graph_init(ctx, graph->n,
648                 weak ? &node_follows_weak : &node_follows_strong, graph);
649         if (!g)
650                 return -1;
651
652         graph->scc = 0;
653         i = 0;
654         n = graph->n;
655         while (n) {
656                 while (g->order[i] != -1) {
657                         graph->node[g->order[i]].scc = graph->scc;
658                         --n;
659                         ++i;
660                 }
661                 ++i;
662                 graph->scc++;
663         }
664
665         isl_tarjan_graph_free(g);
666
667         return 0;
668 }
669
670 /* Apply Tarjan's algorithm to detect the strongly connected components
671  * in the dependence graph.
672  */
673 static int detect_sccs(isl_ctx *ctx, struct isl_sched_graph *graph)
674 {
675         return detect_ccs(ctx, graph, 0);
676 }
677
678 /* Apply Tarjan's algorithm to detect the (weakly) connected components
679  * in the dependence graph.
680  */
681 static int detect_wccs(isl_ctx *ctx, struct isl_sched_graph *graph)
682 {
683         return detect_ccs(ctx, graph, 1);
684 }
685
686 static int cmp_scc(const void *a, const void *b, void *data)
687 {
688         struct isl_sched_graph *graph = data;
689         const int *i1 = a;
690         const int *i2 = b;
691
692         return graph->node[*i1].scc - graph->node[*i2].scc;
693 }
694
695 /* Sort the elements of graph->sorted according to the corresponding SCCs.
696  */
697 static int sort_sccs(struct isl_sched_graph *graph)
698 {
699         return isl_sort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
700 }
701
702 /* Given a dependence relation R from a node to itself,
703  * construct the set of coefficients of valid constraints for elements
704  * in that dependence relation.
705  * In particular, the result contains tuples of coefficients
706  * c_0, c_n, c_x such that
707  *
708  *      c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
709  *
710  * or, equivalently,
711  *
712  *      c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
713  *
714  * We choose here to compute the dual of delta R.
715  * Alternatively, we could have computed the dual of R, resulting
716  * in a set of tuples c_0, c_n, c_x, c_y, and then
717  * plugged in (c_0, c_n, c_x, -c_x).
718  */
719 static __isl_give isl_basic_set *intra_coefficients(
720         struct isl_sched_graph *graph, __isl_take isl_map *map)
721 {
722         isl_ctx *ctx = isl_map_get_ctx(map);
723         isl_set *delta;
724         isl_basic_set *coef;
725
726         if (isl_hmap_map_basic_set_has(ctx, graph->intra_hmap, map))
727                 return isl_hmap_map_basic_set_get(ctx, graph->intra_hmap, map);
728
729         delta = isl_set_remove_divs(isl_map_deltas(isl_map_copy(map)));
730         coef = isl_set_coefficients(delta);
731         isl_hmap_map_basic_set_set(ctx, graph->intra_hmap, map,
732                                         isl_basic_set_copy(coef));
733
734         return coef;
735 }
736
737 /* Given a dependence relation R, * construct the set of coefficients
738  * of valid constraints for elements in that dependence relation.
739  * In particular, the result contains tuples of coefficients
740  * c_0, c_n, c_x, c_y such that
741  *
742  *      c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
743  *
744  */
745 static __isl_give isl_basic_set *inter_coefficients(
746         struct isl_sched_graph *graph, __isl_take isl_map *map)
747 {
748         isl_ctx *ctx = isl_map_get_ctx(map);
749         isl_set *set;
750         isl_basic_set *coef;
751
752         if (isl_hmap_map_basic_set_has(ctx, graph->inter_hmap, map))
753                 return isl_hmap_map_basic_set_get(ctx, graph->inter_hmap, map);
754
755         set = isl_map_wrap(isl_map_remove_divs(isl_map_copy(map)));
756         coef = isl_set_coefficients(set);
757         isl_hmap_map_basic_set_set(ctx, graph->inter_hmap, map,
758                                         isl_basic_set_copy(coef));
759
760         return coef;
761 }
762
763 /* Add constraints to graph->lp that force validity for the given
764  * dependence from a node i to itself.
765  * That is, add constraints that enforce
766  *
767  *      (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
768  *      = c_i_x (y - x) >= 0
769  *
770  * for each (x,y) in R.
771  * We obtain general constraints on coefficients (c_0, c_n, c_x)
772  * of valid constraints for (y - x) and then plug in (0, 0, c_i_x^+ - c_i_x^-),
773  * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
774  * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
775  *
776  * Actually, we do not construct constraints for the c_i_x themselves,
777  * but for the coefficients of c_i_x written as a linear combination
778  * of the columns in node->cmap.
779  */
780 static int add_intra_validity_constraints(struct isl_sched_graph *graph,
781         struct isl_sched_edge *edge)
782 {
783         unsigned total;
784         isl_map *map = isl_map_copy(edge->map);
785         isl_ctx *ctx = isl_map_get_ctx(map);
786         isl_space *dim;
787         isl_dim_map *dim_map;
788         isl_basic_set *coef;
789         struct isl_sched_node *node = edge->src;
790
791         coef = intra_coefficients(graph, map);
792
793         dim = isl_space_domain(isl_space_unwrap(isl_basic_set_get_space(coef)));
794
795         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
796                     isl_space_dim(dim, isl_dim_set), isl_mat_copy(node->cmap));
797
798         total = isl_basic_set_total_dim(graph->lp);
799         dim_map = isl_dim_map_alloc(ctx, total);
800         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 1, 2,
801                           isl_space_dim(dim, isl_dim_set), 1,
802                           node->nvar, -1);
803         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 2, 2,
804                           isl_space_dim(dim, isl_dim_set), 1,
805                           node->nvar, 1);
806         graph->lp = isl_basic_set_extend_constraints(graph->lp,
807                         coef->n_eq, coef->n_ineq);
808         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
809                                                            coef, dim_map);
810         isl_space_free(dim);
811
812         return 0;
813 }
814
815 /* Add constraints to graph->lp that force validity for the given
816  * dependence from node i to node j.
817  * That is, add constraints that enforce
818  *
819  *      (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
820  *
821  * for each (x,y) in R.
822  * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
823  * of valid constraints for R and then plug in
824  * (c_j_0 - c_i_0, c_j_n^+ - c_j_n^- - (c_i_n^+ - c_i_n^-),
825  *  c_j_x^+ - c_j_x^- - (c_i_x^+ - c_i_x^-)),
826  * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
827  * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
828  *
829  * Actually, we do not construct constraints for the c_*_x themselves,
830  * but for the coefficients of c_*_x written as a linear combination
831  * of the columns in node->cmap.
832  */
833 static int add_inter_validity_constraints(struct isl_sched_graph *graph,
834         struct isl_sched_edge *edge)
835 {
836         unsigned total;
837         isl_map *map = isl_map_copy(edge->map);
838         isl_ctx *ctx = isl_map_get_ctx(map);
839         isl_space *dim;
840         isl_dim_map *dim_map;
841         isl_basic_set *coef;
842         struct isl_sched_node *src = edge->src;
843         struct isl_sched_node *dst = edge->dst;
844
845         coef = inter_coefficients(graph, map);
846
847         dim = isl_space_domain(isl_space_unwrap(isl_basic_set_get_space(coef)));
848
849         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
850                     isl_space_dim(dim, isl_dim_set), isl_mat_copy(src->cmap));
851         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
852                     isl_space_dim(dim, isl_dim_set) + src->nvar,
853                     isl_mat_copy(dst->cmap));
854
855         total = isl_basic_set_total_dim(graph->lp);
856         dim_map = isl_dim_map_alloc(ctx, total);
857
858         isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, 1);
859         isl_dim_map_range(dim_map, dst->start + 1, 2, 1, 1, dst->nparam, -1);
860         isl_dim_map_range(dim_map, dst->start + 2, 2, 1, 1, dst->nparam, 1);
861         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 1, 2,
862                           isl_space_dim(dim, isl_dim_set) + src->nvar, 1,
863                           dst->nvar, -1);
864         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 2, 2,
865                           isl_space_dim(dim, isl_dim_set) + src->nvar, 1,
866                           dst->nvar, 1);
867
868         isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, -1);
869         isl_dim_map_range(dim_map, src->start + 1, 2, 1, 1, src->nparam, 1);
870         isl_dim_map_range(dim_map, src->start + 2, 2, 1, 1, src->nparam, -1);
871         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 1, 2,
872                           isl_space_dim(dim, isl_dim_set), 1,
873                           src->nvar, 1);
874         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 2, 2,
875                           isl_space_dim(dim, isl_dim_set), 1,
876                           src->nvar, -1);
877
878         edge->start = graph->lp->n_ineq;
879         graph->lp = isl_basic_set_extend_constraints(graph->lp,
880                         coef->n_eq, coef->n_ineq);
881         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
882                                                            coef, dim_map);
883         isl_space_free(dim);
884         edge->end = graph->lp->n_ineq;
885
886         return 0;
887 }
888
889 /* Add constraints to graph->lp that bound the dependence distance for the given
890  * dependence from a node i to itself.
891  * If s = 1, we add the constraint
892  *
893  *      c_i_x (y - x) <= m_0 + m_n n
894  *
895  * or
896  *
897  *      -c_i_x (y - x) + m_0 + m_n n >= 0
898  *
899  * for each (x,y) in R.
900  * If s = -1, we add the constraint
901  *
902  *      -c_i_x (y - x) <= m_0 + m_n n
903  *
904  * or
905  *
906  *      c_i_x (y - x) + m_0 + m_n n >= 0
907  *
908  * for each (x,y) in R.
909  * We obtain general constraints on coefficients (c_0, c_n, c_x)
910  * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
911  * with each coefficient (except m_0) represented as a pair of non-negative
912  * coefficients.
913  *
914  * Actually, we do not construct constraints for the c_i_x themselves,
915  * but for the coefficients of c_i_x written as a linear combination
916  * of the columns in node->cmap.
917  */
918 static int add_intra_proximity_constraints(struct isl_sched_graph *graph,
919         struct isl_sched_edge *edge, int s)
920 {
921         unsigned total;
922         unsigned nparam;
923         isl_map *map = isl_map_copy(edge->map);
924         isl_ctx *ctx = isl_map_get_ctx(map);
925         isl_space *dim;
926         isl_dim_map *dim_map;
927         isl_basic_set *coef;
928         struct isl_sched_node *node = edge->src;
929
930         coef = intra_coefficients(graph, map);
931
932         dim = isl_space_domain(isl_space_unwrap(isl_basic_set_get_space(coef)));
933
934         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
935                     isl_space_dim(dim, isl_dim_set), isl_mat_copy(node->cmap));
936
937         nparam = isl_space_dim(node->dim, isl_dim_param);
938         total = isl_basic_set_total_dim(graph->lp);
939         dim_map = isl_dim_map_alloc(ctx, total);
940         isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
941         isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
942         isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
943         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 1, 2,
944                           isl_space_dim(dim, isl_dim_set), 1,
945                           node->nvar, s);
946         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 2, 2,
947                           isl_space_dim(dim, isl_dim_set), 1,
948                           node->nvar, -s);
949         graph->lp = isl_basic_set_extend_constraints(graph->lp,
950                         coef->n_eq, coef->n_ineq);
951         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
952                                                            coef, dim_map);
953         isl_space_free(dim);
954
955         return 0;
956 }
957
958 /* Add constraints to graph->lp that bound the dependence distance for the given
959  * dependence from node i to node j.
960  * If s = 1, we add the constraint
961  *
962  *      (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
963  *              <= m_0 + m_n n
964  *
965  * or
966  *
967  *      -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
968  *              m_0 + m_n n >= 0
969  *
970  * for each (x,y) in R.
971  * If s = -1, we add the constraint
972  *
973  *      -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
974  *              <= m_0 + m_n n
975  *
976  * or
977  *
978  *      (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
979  *              m_0 + m_n n >= 0
980  *
981  * for each (x,y) in R.
982  * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
983  * of valid constraints for R and then plug in
984  * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
985  *  -s*c_j_x+s*c_i_x)
986  * with each coefficient (except m_0, c_j_0 and c_i_0)
987  * represented as a pair of non-negative coefficients.
988  *
989  * Actually, we do not construct constraints for the c_*_x themselves,
990  * but for the coefficients of c_*_x written as a linear combination
991  * of the columns in node->cmap.
992  */
993 static int add_inter_proximity_constraints(struct isl_sched_graph *graph,
994         struct isl_sched_edge *edge, int s)
995 {
996         unsigned total;
997         unsigned nparam;
998         isl_map *map = isl_map_copy(edge->map);
999         isl_ctx *ctx = isl_map_get_ctx(map);
1000         isl_space *dim;
1001         isl_dim_map *dim_map;
1002         isl_basic_set *coef;
1003         struct isl_sched_node *src = edge->src;
1004         struct isl_sched_node *dst = edge->dst;
1005
1006         coef = inter_coefficients(graph, map);
1007
1008         dim = isl_space_domain(isl_space_unwrap(isl_basic_set_get_space(coef)));
1009
1010         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1011                     isl_space_dim(dim, isl_dim_set), isl_mat_copy(src->cmap));
1012         coef = isl_basic_set_transform_dims(coef, isl_dim_set,
1013                     isl_space_dim(dim, isl_dim_set) + src->nvar,
1014                     isl_mat_copy(dst->cmap));
1015
1016         nparam = isl_space_dim(src->dim, isl_dim_param);
1017         total = isl_basic_set_total_dim(graph->lp);
1018         dim_map = isl_dim_map_alloc(ctx, total);
1019
1020         isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1021         isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1022         isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1023
1024         isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, -s);
1025         isl_dim_map_range(dim_map, dst->start + 1, 2, 1, 1, dst->nparam, s);
1026         isl_dim_map_range(dim_map, dst->start + 2, 2, 1, 1, dst->nparam, -s);
1027         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 1, 2,
1028                           isl_space_dim(dim, isl_dim_set) + src->nvar, 1,
1029                           dst->nvar, s);
1030         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 2, 2,
1031                           isl_space_dim(dim, isl_dim_set) + src->nvar, 1,
1032                           dst->nvar, -s);
1033
1034         isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, s);
1035         isl_dim_map_range(dim_map, src->start + 1, 2, 1, 1, src->nparam, -s);
1036         isl_dim_map_range(dim_map, src->start + 2, 2, 1, 1, src->nparam, s);
1037         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 1, 2,
1038                           isl_space_dim(dim, isl_dim_set), 1,
1039                           src->nvar, -s);
1040         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 2, 2,
1041                           isl_space_dim(dim, isl_dim_set), 1,
1042                           src->nvar, s);
1043
1044         graph->lp = isl_basic_set_extend_constraints(graph->lp,
1045                         coef->n_eq, coef->n_ineq);
1046         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
1047                                                            coef, dim_map);
1048         isl_space_free(dim);
1049
1050         return 0;
1051 }
1052
1053 static int add_all_validity_constraints(struct isl_sched_graph *graph)
1054 {
1055         int i;
1056
1057         for (i = 0; i < graph->n_edge; ++i) {
1058                 struct isl_sched_edge *edge= &graph->edge[i];
1059                 if (!edge->validity)
1060                         continue;
1061                 if (edge->src != edge->dst)
1062                         continue;
1063                 if (add_intra_validity_constraints(graph, edge) < 0)
1064                         return -1;
1065         }
1066
1067         for (i = 0; i < graph->n_edge; ++i) {
1068                 struct isl_sched_edge *edge = &graph->edge[i];
1069                 if (!edge->validity)
1070                         continue;
1071                 if (edge->src == edge->dst)
1072                         continue;
1073                 if (add_inter_validity_constraints(graph, edge) < 0)
1074                         return -1;
1075         }
1076
1077         return 0;
1078 }
1079
1080 /* Add constraints to graph->lp that bound the dependence distance
1081  * for all dependence relations.
1082  * If a given proximity dependence is identical to a validity
1083  * dependence, then the dependence distance is already bounded
1084  * from below (by zero), so we only need to bound the distance
1085  * from above.
1086  * Otherwise, we need to bound the distance both from above and from below.
1087  */
1088 static int add_all_proximity_constraints(struct isl_sched_graph *graph)
1089 {
1090         int i;
1091
1092         for (i = 0; i < graph->n_edge; ++i) {
1093                 struct isl_sched_edge *edge= &graph->edge[i];
1094                 if (!edge->proximity)
1095                         continue;
1096                 if (edge->src == edge->dst &&
1097                     add_intra_proximity_constraints(graph, edge, 1) < 0)
1098                         return -1;
1099                 if (edge->src != edge->dst &&
1100                     add_inter_proximity_constraints(graph, edge, 1) < 0)
1101                         return -1;
1102                 if (edge->validity)
1103                         continue;
1104                 if (edge->src == edge->dst &&
1105                     add_intra_proximity_constraints(graph, edge, -1) < 0)
1106                         return -1;
1107                 if (edge->src != edge->dst &&
1108                     add_inter_proximity_constraints(graph, edge, -1) < 0)
1109                         return -1;
1110         }
1111
1112         return 0;
1113 }
1114
1115 /* Compute a basis for the rows in the linear part of the schedule
1116  * and extend this basis to a full basis.  The remaining rows
1117  * can then be used to force linear independence from the rows
1118  * in the schedule.
1119  *
1120  * In particular, given the schedule rows S, we compute
1121  *
1122  *      S = H Q
1123  *
1124  * with H the Hermite normal form of S.  That is, all but the
1125  * first rank columns of Q are zero and so each row in S is
1126  * a linear combination of the first rank rows of Q.
1127  * The matrix Q is then transposed because we will write the
1128  * coefficients of the next schedule row as a column vector s
1129  * and express this s as a linear combination s = Q c of the
1130  * computed basis.
1131  */
1132 static int node_update_cmap(struct isl_sched_node *node)
1133 {
1134         isl_mat *H, *Q;
1135         int n_row = isl_mat_rows(node->sched);
1136
1137         H = isl_mat_sub_alloc(node->sched, 0, n_row,
1138                               1 + node->nparam, node->nvar);
1139
1140         H = isl_mat_left_hermite(H, 0, NULL, &Q);
1141         isl_mat_free(node->cmap);
1142         node->cmap = isl_mat_transpose(Q);
1143         node->rank = isl_mat_initial_non_zero_cols(H);
1144         isl_mat_free(H);
1145
1146         if (!node->cmap || node->rank < 0)
1147                 return -1;
1148         return 0;
1149 }
1150
1151 /* Count the number of equality and inequality constraints
1152  * that will be added for the given map.
1153  * If carry is set, then we are counting the number of (validity)
1154  * constraints that will be added in setup_carry_lp and we count
1155  * each edge exactly once.  Otherwise, we count as follows
1156  * validity             -> 1 (>= 0)
1157  * validity+proximity   -> 2 (>= 0 and upper bound)
1158  * proximity            -> 2 (lower and upper bound)
1159  */
1160 static int count_map_constraints(struct isl_sched_graph *graph,
1161         struct isl_sched_edge *edge, __isl_take isl_map *map,
1162         int *n_eq, int *n_ineq, int carry)
1163 {
1164         isl_basic_set *coef;
1165         int f = carry ? 1 : edge->proximity ? 2 : 1;
1166
1167         if (carry && !edge->validity) {
1168                 isl_map_free(map);
1169                 return 0;
1170         }
1171
1172         if (edge->src == edge->dst)
1173                 coef = intra_coefficients(graph, map);
1174         else
1175                 coef = inter_coefficients(graph, map);
1176         if (!coef)
1177                 return -1;
1178         *n_eq += f * coef->n_eq;
1179         *n_ineq += f * coef->n_ineq;
1180         isl_basic_set_free(coef);
1181
1182         return 0;
1183 }
1184
1185 /* Count the number of equality and inequality constraints
1186  * that will be added to the main lp problem.
1187  * We count as follows
1188  * validity             -> 1 (>= 0)
1189  * validity+proximity   -> 2 (>= 0 and upper bound)
1190  * proximity            -> 2 (lower and upper bound)
1191  */
1192 static int count_constraints(struct isl_sched_graph *graph,
1193         int *n_eq, int *n_ineq)
1194 {
1195         int i;
1196
1197         *n_eq = *n_ineq = 0;
1198         for (i = 0; i < graph->n_edge; ++i) {
1199                 struct isl_sched_edge *edge= &graph->edge[i];
1200                 isl_map *map = isl_map_copy(edge->map);
1201
1202                 if (count_map_constraints(graph, edge, map,
1203                                           n_eq, n_ineq, 0) < 0)
1204                         return -1;
1205         }
1206
1207         return 0;
1208 }
1209
1210 /* Add constraints that bound the values of the variable and parameter
1211  * coefficients of the schedule.
1212  *
1213  * The maximal value of the coefficients is defined by the option
1214  * 'schedule_max_coefficient'.
1215  */
1216 static int add_bound_coefficient_constraints(isl_ctx *ctx,
1217         struct isl_sched_graph *graph)
1218 {
1219         int i, j, k;
1220         int max_coefficient;
1221         int total;
1222
1223         max_coefficient = ctx->opt->schedule_max_coefficient;
1224
1225         if (max_coefficient == -1)
1226                 return 0;
1227
1228         total = isl_basic_set_total_dim(graph->lp);
1229
1230         for (i = 0; i < graph->n; ++i) {
1231                 struct isl_sched_node *node = &graph->node[i];
1232                 for (j = 0; j < 2 * node->nparam + 2 * node->nvar; ++j) {
1233                         int dim;
1234                         k = isl_basic_set_alloc_inequality(graph->lp);
1235                         if (k < 0)
1236                                 return -1;
1237                         dim = 1 + node->start + 1 + j;
1238                         isl_seq_clr(graph->lp->ineq[k], 1 +  total);
1239                         isl_int_set_si(graph->lp->ineq[k][dim], -1);
1240                         isl_int_set_si(graph->lp->ineq[k][0], max_coefficient);
1241                 }
1242         }
1243
1244         return 0;
1245 }
1246
1247 /* Construct an ILP problem for finding schedule coefficients
1248  * that result in non-negative, but small dependence distances
1249  * over all dependences.
1250  * In particular, the dependence distances over proximity edges
1251  * are bounded by m_0 + m_n n and we compute schedule coefficients
1252  * with small values (preferably zero) of m_n and m_0.
1253  *
1254  * All variables of the ILP are non-negative.  The actual coefficients
1255  * may be negative, so each coefficient is represented as the difference
1256  * of two non-negative variables.  The negative part always appears
1257  * immediately before the positive part.
1258  * Other than that, the variables have the following order
1259  *
1260  *      - sum of positive and negative parts of m_n coefficients
1261  *      - m_0
1262  *      - sum of positive and negative parts of all c_n coefficients
1263  *              (unconstrained when computing non-parametric schedules)
1264  *      - sum of positive and negative parts of all c_x coefficients
1265  *      - positive and negative parts of m_n coefficients
1266  *      - for each node
1267  *              - c_i_0
1268  *              - positive and negative parts of c_i_n (if parametric)
1269  *              - positive and negative parts of c_i_x
1270  *
1271  * The c_i_x are not represented directly, but through the columns of
1272  * node->cmap.  That is, the computed values are for variable t_i_x
1273  * such that c_i_x = Q t_i_x with Q equal to node->cmap.
1274  *
1275  * The constraints are those from the edges plus two or three equalities
1276  * to express the sums.
1277  *
1278  * If force_zero is set, then we add equalities to ensure that
1279  * the sum of the m_n coefficients and m_0 are both zero.
1280  */
1281 static int setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
1282         int force_zero)
1283 {
1284         int i, j;
1285         int k;
1286         unsigned nparam;
1287         unsigned total;
1288         isl_space *dim;
1289         int parametric;
1290         int param_pos;
1291         int n_eq, n_ineq;
1292         int max_constant_term;
1293         int max_coefficient;
1294
1295         max_constant_term = ctx->opt->schedule_max_constant_term;
1296         max_coefficient = ctx->opt->schedule_max_coefficient;
1297
1298         parametric = ctx->opt->schedule_parametric;
1299         nparam = isl_space_dim(graph->node[0].dim, isl_dim_param);
1300         param_pos = 4;
1301         total = param_pos + 2 * nparam;
1302         for (i = 0; i < graph->n; ++i) {
1303                 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
1304                 if (node_update_cmap(node) < 0)
1305                         return -1;
1306                 node->start = total;
1307                 total += 1 + 2 * (node->nparam + node->nvar);
1308         }
1309
1310         if (count_constraints(graph, &n_eq, &n_ineq) < 0)
1311                 return -1;
1312
1313         dim = isl_space_set_alloc(ctx, 0, total);
1314         isl_basic_set_free(graph->lp);
1315         n_eq += 2 + parametric + force_zero;
1316         if (max_constant_term != -1)
1317                 n_ineq += graph->n;
1318         if (max_coefficient != -1)
1319                 for (i = 0; i < graph->n; ++i)
1320                         n_ineq += 2 * graph->node[i].nparam +
1321                                   2 * graph->node[i].nvar;
1322
1323         graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
1324
1325         k = isl_basic_set_alloc_equality(graph->lp);
1326         if (k < 0)
1327                 return -1;
1328         isl_seq_clr(graph->lp->eq[k], 1 +  total);
1329         if (!force_zero)
1330                 isl_int_set_si(graph->lp->eq[k][1], -1);
1331         for (i = 0; i < 2 * nparam; ++i)
1332                 isl_int_set_si(graph->lp->eq[k][1 + param_pos + i], 1);
1333
1334         if (force_zero) {
1335                 k = isl_basic_set_alloc_equality(graph->lp);
1336                 if (k < 0)
1337                         return -1;
1338                 isl_seq_clr(graph->lp->eq[k], 1 +  total);
1339                 isl_int_set_si(graph->lp->eq[k][2], -1);
1340         }
1341
1342         if (parametric) {
1343                 k = isl_basic_set_alloc_equality(graph->lp);
1344                 if (k < 0)
1345                         return -1;
1346                 isl_seq_clr(graph->lp->eq[k], 1 +  total);
1347                 isl_int_set_si(graph->lp->eq[k][3], -1);
1348                 for (i = 0; i < graph->n; ++i) {
1349                         int pos = 1 + graph->node[i].start + 1;
1350
1351                         for (j = 0; j < 2 * graph->node[i].nparam; ++j)
1352                                 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
1353                 }
1354         }
1355
1356         k = isl_basic_set_alloc_equality(graph->lp);
1357         if (k < 0)
1358                 return -1;
1359         isl_seq_clr(graph->lp->eq[k], 1 +  total);
1360         isl_int_set_si(graph->lp->eq[k][4], -1);
1361         for (i = 0; i < graph->n; ++i) {
1362                 struct isl_sched_node *node = &graph->node[i];
1363                 int pos = 1 + node->start + 1 + 2 * node->nparam;
1364
1365                 for (j = 0; j < 2 * node->nvar; ++j)
1366                         isl_int_set_si(graph->lp->eq[k][pos + j], 1);
1367         }
1368
1369         if (max_constant_term != -1)
1370                 for (i = 0; i < graph->n; ++i) {
1371                         struct isl_sched_node *node = &graph->node[i];
1372                         k = isl_basic_set_alloc_inequality(graph->lp);
1373                         if (k < 0)
1374                                 return -1;
1375                         isl_seq_clr(graph->lp->ineq[k], 1 +  total);
1376                         isl_int_set_si(graph->lp->ineq[k][1 + node->start], -1);
1377                         isl_int_set_si(graph->lp->ineq[k][0], max_constant_term);
1378                 }
1379
1380         if (add_bound_coefficient_constraints(ctx, graph) < 0)
1381                 return -1;
1382         if (add_all_validity_constraints(graph) < 0)
1383                 return -1;
1384         if (add_all_proximity_constraints(graph) < 0)
1385                 return -1;
1386
1387         return 0;
1388 }
1389
1390 /* Analyze the conflicting constraint found by
1391  * isl_tab_basic_set_non_trivial_lexmin.  If it corresponds to the validity
1392  * constraint of one of the edges between distinct nodes, living, moreover
1393  * in distinct SCCs, then record the source and sink SCC as this may
1394  * be a good place to cut between SCCs.
1395  */
1396 static int check_conflict(int con, void *user)
1397 {
1398         int i;
1399         struct isl_sched_graph *graph = user;
1400
1401         if (graph->src_scc >= 0)
1402                 return 0;
1403
1404         con -= graph->lp->n_eq;
1405
1406         if (con >= graph->lp->n_ineq)
1407                 return 0;
1408
1409         for (i = 0; i < graph->n_edge; ++i) {
1410                 if (!graph->edge[i].validity)
1411                         continue;
1412                 if (graph->edge[i].src == graph->edge[i].dst)
1413                         continue;
1414                 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
1415                         continue;
1416                 if (graph->edge[i].start > con)
1417                         continue;
1418                 if (graph->edge[i].end <= con)
1419                         continue;
1420                 graph->src_scc = graph->edge[i].src->scc;
1421                 graph->dst_scc = graph->edge[i].dst->scc;
1422         }
1423
1424         return 0;
1425 }
1426
1427 /* Check whether the next schedule row of the given node needs to be
1428  * non-trivial.  Lower-dimensional domains may have some trivial rows,
1429  * but as soon as the number of remaining required non-trivial rows
1430  * is as large as the number or remaining rows to be computed,
1431  * all remaining rows need to be non-trivial.
1432  */
1433 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
1434 {
1435         return node->nvar - node->rank >= graph->maxvar - graph->n_row;
1436 }
1437
1438 /* Solve the ILP problem constructed in setup_lp.
1439  * For each node such that all the remaining rows of its schedule
1440  * need to be non-trivial, we construct a non-triviality region.
1441  * This region imposes that the next row is independent of previous rows.
1442  * In particular the coefficients c_i_x are represented by t_i_x
1443  * variables with c_i_x = Q t_i_x and Q a unimodular matrix such that
1444  * its first columns span the rows of the previously computed part
1445  * of the schedule.  The non-triviality region enforces that at least
1446  * one of the remaining components of t_i_x is non-zero, i.e.,
1447  * that the new schedule row depends on at least one of the remaining
1448  * columns of Q.
1449  */
1450 static __isl_give isl_vec *solve_lp(struct isl_sched_graph *graph)
1451 {
1452         int i;
1453         isl_vec *sol;
1454         isl_basic_set *lp;
1455
1456         for (i = 0; i < graph->n; ++i) {
1457                 struct isl_sched_node *node = &graph->node[i];
1458                 int skip = node->rank;
1459                 graph->region[i].pos = node->start + 1 + 2*(node->nparam+skip);
1460                 if (needs_row(graph, node))
1461                         graph->region[i].len = 2 * (node->nvar - skip);
1462                 else
1463                         graph->region[i].len = 0;
1464         }
1465         lp = isl_basic_set_copy(graph->lp);
1466         sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
1467                                        graph->region, &check_conflict, graph);
1468         return sol;
1469 }
1470
1471 /* Update the schedules of all nodes based on the given solution
1472  * of the LP problem.
1473  * The new row is added to the current band.
1474  * All possibly negative coefficients are encoded as a difference
1475  * of two non-negative variables, so we need to perform the subtraction
1476  * here.  Moreover, if use_cmap is set, then the solution does
1477  * not refer to the actual coefficients c_i_x, but instead to variables
1478  * t_i_x such that c_i_x = Q t_i_x and Q is equal to node->cmap.
1479  * In this case, we then also need to perform this multiplication
1480  * to obtain the values of c_i_x.
1481  *
1482  * If check_zero is set, then the first two coordinates of sol are
1483  * assumed to correspond to the dependence distance.  If these two
1484  * coordinates are zero, then the corresponding scheduling dimension
1485  * is marked as being zero distance.
1486  */
1487 static int update_schedule(struct isl_sched_graph *graph,
1488         __isl_take isl_vec *sol, int use_cmap, int check_zero)
1489 {
1490         int i, j;
1491         int zero = 0;
1492         isl_vec *csol = NULL;
1493
1494         if (!sol)
1495                 goto error;
1496         if (sol->size == 0)
1497                 isl_die(sol->ctx, isl_error_internal,
1498                         "no solution found", goto error);
1499         if (graph->n_total_row >= graph->max_row)
1500                 isl_die(sol->ctx, isl_error_internal,
1501                         "too many schedule rows", goto error);
1502
1503         if (check_zero)
1504                 zero = isl_int_is_zero(sol->el[1]) &&
1505                            isl_int_is_zero(sol->el[2]);
1506
1507         for (i = 0; i < graph->n; ++i) {
1508                 struct isl_sched_node *node = &graph->node[i];
1509                 int pos = node->start;
1510                 int row = isl_mat_rows(node->sched);
1511
1512                 isl_vec_free(csol);
1513                 csol = isl_vec_alloc(sol->ctx, node->nvar);
1514                 if (!csol)
1515                         goto error;
1516
1517                 isl_map_free(node->sched_map);
1518                 node->sched_map = NULL;
1519                 node->sched = isl_mat_add_rows(node->sched, 1);
1520                 if (!node->sched)
1521                         goto error;
1522                 node->sched = isl_mat_set_element(node->sched, row, 0,
1523                                                   sol->el[1 + pos]);
1524                 for (j = 0; j < node->nparam + node->nvar; ++j)
1525                         isl_int_sub(sol->el[1 + pos + 1 + 2 * j + 1],
1526                                     sol->el[1 + pos + 1 + 2 * j + 1],
1527                                     sol->el[1 + pos + 1 + 2 * j]);
1528                 for (j = 0; j < node->nparam; ++j)
1529                         node->sched = isl_mat_set_element(node->sched,
1530                                         row, 1 + j, sol->el[1+pos+1+2*j+1]);
1531                 for (j = 0; j < node->nvar; ++j)
1532                         isl_int_set(csol->el[j],
1533                                     sol->el[1+pos+1+2*(node->nparam+j)+1]);
1534                 if (use_cmap)
1535                         csol = isl_mat_vec_product(isl_mat_copy(node->cmap),
1536                                                    csol);
1537                 if (!csol)
1538                         goto error;
1539                 for (j = 0; j < node->nvar; ++j)
1540                         node->sched = isl_mat_set_element(node->sched,
1541                                         row, 1 + node->nparam + j, csol->el[j]);
1542                 node->band[graph->n_total_row] = graph->n_band;
1543                 node->zero[graph->n_total_row] = zero;
1544         }
1545         isl_vec_free(sol);
1546         isl_vec_free(csol);
1547
1548         graph->n_row++;
1549         graph->n_total_row++;
1550
1551         return 0;
1552 error:
1553         isl_vec_free(sol);
1554         isl_vec_free(csol);
1555         return -1;
1556 }
1557
1558 /* Convert node->sched into a multi_aff and return this multi_aff.
1559  */
1560 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
1561         struct isl_sched_node *node)
1562 {
1563         int i, j;
1564         isl_space *space;
1565         isl_local_space *ls;
1566         isl_aff *aff;
1567         isl_multi_aff *ma;
1568         int nrow, ncol;
1569         isl_int v;
1570
1571         nrow = isl_mat_rows(node->sched);
1572         ncol = isl_mat_cols(node->sched) - 1;
1573         space = isl_space_from_domain(isl_space_copy(node->dim));
1574         space = isl_space_add_dims(space, isl_dim_out, nrow);
1575         ma = isl_multi_aff_zero(space);
1576         ls = isl_local_space_from_space(isl_space_copy(node->dim));
1577
1578         isl_int_init(v);
1579
1580         for (i = 0; i < nrow; ++i) {
1581                 aff = isl_aff_zero_on_domain(isl_local_space_copy(ls));
1582                 isl_mat_get_element(node->sched, i, 0, &v);
1583                 aff = isl_aff_set_constant(aff, v);
1584                 for (j = 0; j < node->nparam; ++j) {
1585                         isl_mat_get_element(node->sched, i, 1 + j, &v);
1586                         aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
1587                 }
1588                 for (j = 0; j < node->nvar; ++j) {
1589                         isl_mat_get_element(node->sched,
1590                                             i, 1 + node->nparam + j, &v);
1591                         aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
1592                 }
1593                 ma = isl_multi_aff_set_aff(ma, i, aff);
1594         }
1595
1596         isl_int_clear(v);
1597
1598         isl_local_space_free(ls);
1599
1600         return ma;
1601 }
1602
1603 /* Convert node->sched into a map and return this map.
1604  *
1605  * The result is cached in node->sched_map, which needs to be released
1606  * whenever node->sched is updated.
1607  */
1608 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
1609 {
1610         if (!node->sched_map) {
1611                 isl_multi_aff *ma;
1612
1613                 ma = node_extract_schedule_multi_aff(node);
1614                 node->sched_map = isl_map_from_multi_aff(ma);
1615         }
1616
1617         return isl_map_copy(node->sched_map);
1618 }
1619
1620 /* Update the given dependence relation based on the current schedule.
1621  * That is, intersect the dependence relation with a map expressing
1622  * that source and sink are executed within the same iteration of
1623  * the current schedule.
1624  * This is not the most efficient way, but this shouldn't be a critical
1625  * operation.
1626  */
1627 static __isl_give isl_map *specialize(__isl_take isl_map *map,
1628         struct isl_sched_node *src, struct isl_sched_node *dst)
1629 {
1630         isl_map *src_sched, *dst_sched, *id;
1631
1632         src_sched = node_extract_schedule(src);
1633         dst_sched = node_extract_schedule(dst);
1634         id = isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
1635         return isl_map_intersect(map, id);
1636 }
1637
1638 /* Update the dependence relations of all edges based on the current schedule.
1639  * If a dependence is carried completely by the current schedule, then
1640  * it is removed from the edge_tables.  It is kept in the list of edges
1641  * as otherwise all edge_tables would have to be recomputed.
1642  */
1643 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
1644 {
1645         int i;
1646
1647         for (i = graph->n_edge - 1; i >= 0; --i) {
1648                 struct isl_sched_edge *edge = &graph->edge[i];
1649                 edge->map = specialize(edge->map, edge->src, edge->dst);
1650                 if (!edge->map)
1651                         return -1;
1652
1653                 if (isl_map_plain_is_empty(edge->map))
1654                         graph_remove_edge(graph, edge);
1655         }
1656
1657         return 0;
1658 }
1659
1660 static void next_band(struct isl_sched_graph *graph)
1661 {
1662         graph->band_start = graph->n_total_row;
1663         graph->n_band++;
1664 }
1665
1666 /* Topologically sort statements mapped to the same schedule iteration
1667  * and add a row to the schedule corresponding to this order.
1668  */
1669 static int sort_statements(isl_ctx *ctx, struct isl_sched_graph *graph)
1670 {
1671         int i, j;
1672
1673         if (graph->n <= 1)
1674                 return 0;
1675
1676         if (update_edges(ctx, graph) < 0)
1677                 return -1;
1678
1679         if (graph->n_edge == 0)
1680                 return 0;
1681
1682         if (detect_sccs(ctx, graph) < 0)
1683                 return -1;
1684
1685         if (graph->n_total_row >= graph->max_row)
1686                 isl_die(ctx, isl_error_internal,
1687                         "too many schedule rows", return -1);
1688
1689         for (i = 0; i < graph->n; ++i) {
1690                 struct isl_sched_node *node = &graph->node[i];
1691                 int row = isl_mat_rows(node->sched);
1692                 int cols = isl_mat_cols(node->sched);
1693
1694                 isl_map_free(node->sched_map);
1695                 node->sched_map = NULL;
1696                 node->sched = isl_mat_add_rows(node->sched, 1);
1697                 if (!node->sched)
1698                         return -1;
1699                 node->sched = isl_mat_set_element_si(node->sched, row, 0,
1700                                                      node->scc);
1701                 for (j = 1; j < cols; ++j)
1702                         node->sched = isl_mat_set_element_si(node->sched,
1703                                                              row, j, 0);
1704                 node->band[graph->n_total_row] = graph->n_band;
1705         }
1706
1707         graph->n_total_row++;
1708         next_band(graph);
1709
1710         return 0;
1711 }
1712
1713 /* Construct an isl_schedule based on the computed schedule stored
1714  * in graph and with parameters specified by dim.
1715  */
1716 static __isl_give isl_schedule *extract_schedule(struct isl_sched_graph *graph,
1717         __isl_take isl_space *dim)
1718 {
1719         int i;
1720         isl_ctx *ctx;
1721         isl_schedule *sched = NULL;
1722                 
1723         if (!dim)
1724                 return NULL;
1725
1726         ctx = isl_space_get_ctx(dim);
1727         sched = isl_calloc(ctx, struct isl_schedule,
1728                            sizeof(struct isl_schedule) +
1729                            (graph->n - 1) * sizeof(struct isl_schedule_node));
1730         if (!sched)
1731                 goto error;
1732
1733         sched->ref = 1;
1734         sched->n = graph->n;
1735         sched->n_band = graph->n_band;
1736         sched->n_total_row = graph->n_total_row;
1737
1738         for (i = 0; i < sched->n; ++i) {
1739                 int r, b;
1740                 int *band_end, *band_id, *zero;
1741
1742                 sched->node[i].sched =
1743                         node_extract_schedule_multi_aff(&graph->node[i]);
1744                 if (!sched->node[i].sched)
1745                         goto error;
1746
1747                 sched->node[i].n_band = graph->n_band;
1748                 if (graph->n_band == 0)
1749                         continue;
1750
1751                 band_end = isl_alloc_array(ctx, int, graph->n_band);
1752                 band_id = isl_alloc_array(ctx, int, graph->n_band);
1753                 zero = isl_alloc_array(ctx, int, graph->n_total_row);
1754                 sched->node[i].band_end = band_end;
1755                 sched->node[i].band_id = band_id;
1756                 sched->node[i].zero = zero;
1757                 if (!band_end || !band_id || !zero)
1758                         goto error;
1759
1760                 for (r = 0; r < graph->n_total_row; ++r)
1761                         zero[r] = graph->node[i].zero[r];
1762                 for (r = b = 0; r < graph->n_total_row; ++r) {
1763                         if (graph->node[i].band[r] == b)
1764                                 continue;
1765                         band_end[b++] = r;
1766                         if (graph->node[i].band[r] == -1)
1767                                 break;
1768                 }
1769                 if (r == graph->n_total_row)
1770                         band_end[b++] = r;
1771                 sched->node[i].n_band = b;
1772                 for (--b; b >= 0; --b)
1773                         band_id[b] = graph->node[i].band_id[b];
1774         }
1775
1776         sched->dim = dim;
1777
1778         return sched;
1779 error:
1780         isl_space_free(dim);
1781         isl_schedule_free(sched);
1782         return NULL;
1783 }
1784
1785 /* Copy nodes that satisfy node_pred from the src dependence graph
1786  * to the dst dependence graph.
1787  */
1788 static int copy_nodes(struct isl_sched_graph *dst, struct isl_sched_graph *src,
1789         int (*node_pred)(struct isl_sched_node *node, int data), int data)
1790 {
1791         int i;
1792
1793         dst->n = 0;
1794         for (i = 0; i < src->n; ++i) {
1795                 if (!node_pred(&src->node[i], data))
1796                         continue;
1797                 dst->node[dst->n].dim = isl_space_copy(src->node[i].dim);
1798                 dst->node[dst->n].nvar = src->node[i].nvar;
1799                 dst->node[dst->n].nparam = src->node[i].nparam;
1800                 dst->node[dst->n].sched = isl_mat_copy(src->node[i].sched);
1801                 dst->node[dst->n].sched_map =
1802                         isl_map_copy(src->node[i].sched_map);
1803                 dst->node[dst->n].band = src->node[i].band;
1804                 dst->node[dst->n].band_id = src->node[i].band_id;
1805                 dst->node[dst->n].zero = src->node[i].zero;
1806                 dst->n++;
1807         }
1808
1809         return 0;
1810 }
1811
1812 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
1813  * to the dst dependence graph.
1814  * If the source or destination node of the edge is not in the destination
1815  * graph, then it must be a backward proximity edge and it should simply
1816  * be ignored.
1817  */
1818 static int copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
1819         struct isl_sched_graph *src,
1820         int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
1821 {
1822         int i;
1823         enum isl_edge_type t;
1824
1825         dst->n_edge = 0;
1826         for (i = 0; i < src->n_edge; ++i) {
1827                 struct isl_sched_edge *edge = &src->edge[i];
1828                 isl_map *map;
1829                 struct isl_sched_node *dst_src, *dst_dst;
1830
1831                 if (!edge_pred(edge, data))
1832                         continue;
1833
1834                 if (isl_map_plain_is_empty(edge->map))
1835                         continue;
1836
1837                 dst_src = graph_find_node(ctx, dst, edge->src->dim);
1838                 dst_dst = graph_find_node(ctx, dst, edge->dst->dim);
1839                 if (!dst_src || !dst_dst) {
1840                         if (edge->validity)
1841                                 isl_die(ctx, isl_error_internal,
1842                                         "backward validity edge", return -1);
1843                         continue;
1844                 }
1845
1846                 map = isl_map_copy(edge->map);
1847
1848                 dst->edge[dst->n_edge].src = dst_src;
1849                 dst->edge[dst->n_edge].dst = dst_dst;
1850                 dst->edge[dst->n_edge].map = map;
1851                 dst->edge[dst->n_edge].validity = edge->validity;
1852                 dst->edge[dst->n_edge].proximity = edge->proximity;
1853                 dst->n_edge++;
1854
1855                 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
1856                         if (edge !=
1857                             graph_find_edge(src, t, edge->src, edge->dst))
1858                                 continue;
1859                         if (graph_edge_table_add(ctx, dst, t,
1860                                             &dst->edge[dst->n_edge - 1]) < 0)
1861                                 return -1;
1862                 }
1863         }
1864
1865         return 0;
1866 }
1867
1868 /* Given a "src" dependence graph that contains the nodes from "dst"
1869  * that satisfy node_pred, copy the schedule computed in "src"
1870  * for those nodes back to "dst".
1871  */
1872 static int copy_schedule(struct isl_sched_graph *dst,
1873         struct isl_sched_graph *src,
1874         int (*node_pred)(struct isl_sched_node *node, int data), int data)
1875 {
1876         int i;
1877
1878         src->n = 0;
1879         for (i = 0; i < dst->n; ++i) {
1880                 if (!node_pred(&dst->node[i], data))
1881                         continue;
1882                 isl_mat_free(dst->node[i].sched);
1883                 isl_map_free(dst->node[i].sched_map);
1884                 dst->node[i].sched = isl_mat_copy(src->node[src->n].sched);
1885                 dst->node[i].sched_map =
1886                         isl_map_copy(src->node[src->n].sched_map);
1887                 src->n++;
1888         }
1889
1890         dst->max_row = src->max_row;
1891         dst->n_total_row = src->n_total_row;
1892         dst->n_band = src->n_band;
1893
1894         return 0;
1895 }
1896
1897 /* Compute the maximal number of variables over all nodes.
1898  * This is the maximal number of linearly independent schedule
1899  * rows that we need to compute.
1900  * Just in case we end up in a part of the dependence graph
1901  * with only lower-dimensional domains, we make sure we will
1902  * compute the required amount of extra linearly independent rows.
1903  */
1904 static int compute_maxvar(struct isl_sched_graph *graph)
1905 {
1906         int i;
1907
1908         graph->maxvar = 0;
1909         for (i = 0; i < graph->n; ++i) {
1910                 struct isl_sched_node *node = &graph->node[i];
1911                 int nvar;
1912
1913                 if (node_update_cmap(node) < 0)
1914                         return -1;
1915                 nvar = node->nvar + graph->n_row - node->rank;
1916                 if (nvar > graph->maxvar)
1917                         graph->maxvar = nvar;
1918         }
1919
1920         return 0;
1921 }
1922
1923 static int compute_schedule(isl_ctx *ctx, struct isl_sched_graph *graph);
1924 static int compute_schedule_wcc(isl_ctx *ctx, struct isl_sched_graph *graph);
1925
1926 /* Compute a schedule for a subgraph of "graph".  In particular, for
1927  * the graph composed of nodes that satisfy node_pred and edges that
1928  * that satisfy edge_pred.  The caller should precompute the number
1929  * of nodes and edges that satisfy these predicates and pass them along
1930  * as "n" and "n_edge".
1931  * If the subgraph is known to consist of a single component, then wcc should
1932  * be set and then we call compute_schedule_wcc on the constructed subgraph.
1933  * Otherwise, we call compute_schedule, which will check whether the subgraph
1934  * is connected.
1935  */
1936 static int compute_sub_schedule(isl_ctx *ctx,
1937         struct isl_sched_graph *graph, int n, int n_edge,
1938         int (*node_pred)(struct isl_sched_node *node, int data),
1939         int (*edge_pred)(struct isl_sched_edge *edge, int data),
1940         int data, int wcc)
1941 {
1942         struct isl_sched_graph split = { 0 };
1943         int t;
1944
1945         if (graph_alloc(ctx, &split, n, n_edge) < 0)
1946                 goto error;
1947         if (copy_nodes(&split, graph, node_pred, data) < 0)
1948                 goto error;
1949         if (graph_init_table(ctx, &split) < 0)
1950                 goto error;
1951         for (t = 0; t <= isl_edge_last; ++t)
1952                 split.max_edge[t] = graph->max_edge[t];
1953         if (graph_init_edge_tables(ctx, &split) < 0)
1954                 goto error;
1955         if (copy_edges(ctx, &split, graph, edge_pred, data) < 0)
1956                 goto error;
1957         split.n_row = graph->n_row;
1958         split.max_row = graph->max_row;
1959         split.n_total_row = graph->n_total_row;
1960         split.n_band = graph->n_band;
1961         split.band_start = graph->band_start;
1962
1963         if (wcc && compute_schedule_wcc(ctx, &split) < 0)
1964                 goto error;
1965         if (!wcc && compute_schedule(ctx, &split) < 0)
1966                 goto error;
1967
1968         copy_schedule(graph, &split, node_pred, data);
1969
1970         graph_free(ctx, &split);
1971         return 0;
1972 error:
1973         graph_free(ctx, &split);
1974         return -1;
1975 }
1976
1977 static int node_scc_exactly(struct isl_sched_node *node, int scc)
1978 {
1979         return node->scc == scc;
1980 }
1981
1982 static int node_scc_at_most(struct isl_sched_node *node, int scc)
1983 {
1984         return node->scc <= scc;
1985 }
1986
1987 static int node_scc_at_least(struct isl_sched_node *node, int scc)
1988 {
1989         return node->scc >= scc;
1990 }
1991
1992 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
1993 {
1994         return edge->src->scc == scc && edge->dst->scc == scc;
1995 }
1996
1997 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
1998 {
1999         return edge->dst->scc <= scc;
2000 }
2001
2002 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
2003 {
2004         return edge->src->scc >= scc;
2005 }
2006
2007 /* Pad the schedules of all nodes with zero rows such that in the end
2008  * they all have graph->n_total_row rows.
2009  * The extra rows don't belong to any band, so they get assigned band number -1.
2010  */
2011 static int pad_schedule(struct isl_sched_graph *graph)
2012 {
2013         int i, j;
2014
2015         for (i = 0; i < graph->n; ++i) {
2016                 struct isl_sched_node *node = &graph->node[i];
2017                 int row = isl_mat_rows(node->sched);
2018                 if (graph->n_total_row > row) {
2019                         isl_map_free(node->sched_map);
2020                         node->sched_map = NULL;
2021                 }
2022                 node->sched = isl_mat_add_zero_rows(node->sched,
2023                                                     graph->n_total_row - row);
2024                 if (!node->sched)
2025                         return -1;
2026                 for (j = row; j < graph->n_total_row; ++j)
2027                         node->band[j] = -1;
2028         }
2029
2030         return 0;
2031 }
2032
2033 /* Split the current graph into two parts and compute a schedule for each
2034  * part individually.  In particular, one part consists of all SCCs up
2035  * to and including graph->src_scc, while the other part contains the other
2036  * SCCS.
2037  *
2038  * The split is enforced in the schedule by constant rows with two different
2039  * values (0 and 1).  These constant rows replace the previously computed rows
2040  * in the current band.
2041  * It would be possible to reuse them as the first rows in the next
2042  * band, but recomputing them may result in better rows as we are looking
2043  * at a smaller part of the dependence graph.
2044  * compute_split_schedule is only called when no zero-distance schedule row
2045  * could be found on the entire graph, so we wark the splitting row as
2046  * non zero-distance.
2047  *
2048  * The band_id of the second group is set to n, where n is the number
2049  * of nodes in the first group.  This ensures that the band_ids over
2050  * the two groups remain disjoint, even if either or both of the two
2051  * groups contain independent components.
2052  */
2053 static int compute_split_schedule(isl_ctx *ctx, struct isl_sched_graph *graph)
2054 {
2055         int i, j, n, e1, e2;
2056         int n_total_row, orig_total_row;
2057         int n_band, orig_band;
2058         int drop;
2059
2060         if (graph->n_total_row >= graph->max_row)
2061                 isl_die(ctx, isl_error_internal,
2062                         "too many schedule rows", return -1);
2063
2064         drop = graph->n_total_row - graph->band_start;
2065         graph->n_total_row -= drop;
2066         graph->n_row -= drop;
2067
2068         n = 0;
2069         for (i = 0; i < graph->n; ++i) {
2070                 struct isl_sched_node *node = &graph->node[i];
2071                 int row = isl_mat_rows(node->sched) - drop;
2072                 int cols = isl_mat_cols(node->sched);
2073                 int before = node->scc <= graph->src_scc;
2074
2075                 if (before)
2076                         n++;
2077
2078                 isl_map_free(node->sched_map);
2079                 node->sched_map = NULL;
2080                 node->sched = isl_mat_drop_rows(node->sched,
2081                                                 graph->band_start, drop);
2082                 node->sched = isl_mat_add_rows(node->sched, 1);
2083                 if (!node->sched)
2084                         return -1;
2085                 node->sched = isl_mat_set_element_si(node->sched, row, 0,
2086                                                      !before);
2087                 for (j = 1; j < cols; ++j)
2088                         node->sched = isl_mat_set_element_si(node->sched,
2089                                                              row, j, 0);
2090                 node->band[graph->n_total_row] = graph->n_band;
2091                 node->zero[graph->n_total_row] = 0;
2092         }
2093
2094         e1 = e2 = 0;
2095         for (i = 0; i < graph->n_edge; ++i) {
2096                 if (graph->edge[i].dst->scc <= graph->src_scc)
2097                         e1++;
2098                 if (graph->edge[i].src->scc > graph->src_scc)
2099                         e2++;
2100         }
2101
2102         graph->n_total_row++;
2103         next_band(graph);
2104
2105         for (i = 0; i < graph->n; ++i) {
2106                 struct isl_sched_node *node = &graph->node[i];
2107                 if (node->scc > graph->src_scc)
2108                         node->band_id[graph->n_band] = n;
2109         }
2110
2111         orig_total_row = graph->n_total_row;
2112         orig_band = graph->n_band;
2113         if (compute_sub_schedule(ctx, graph, n, e1,
2114                                 &node_scc_at_most, &edge_dst_scc_at_most,
2115                                 graph->src_scc, 0) < 0)
2116                 return -1;
2117         n_total_row = graph->n_total_row;
2118         graph->n_total_row = orig_total_row;
2119         n_band = graph->n_band;
2120         graph->n_band = orig_band;
2121         if (compute_sub_schedule(ctx, graph, graph->n - n, e2,
2122                                 &node_scc_at_least, &edge_src_scc_at_least,
2123                                 graph->src_scc + 1, 0) < 0)
2124                 return -1;
2125         if (n_total_row > graph->n_total_row)
2126                 graph->n_total_row = n_total_row;
2127         if (n_band > graph->n_band)
2128                 graph->n_band = n_band;
2129
2130         return pad_schedule(graph);
2131 }
2132
2133 /* Compute the next band of the schedule after updating the dependence
2134  * relations based on the the current schedule.
2135  */
2136 static int compute_next_band(isl_ctx *ctx, struct isl_sched_graph *graph)
2137 {
2138         if (update_edges(ctx, graph) < 0)
2139                 return -1;
2140         next_band(graph);
2141                 
2142         return compute_schedule(ctx, graph);
2143 }
2144
2145 /* Add constraints to graph->lp that force the dependence "map" (which
2146  * is part of the dependence relation of "edge")
2147  * to be respected and attempt to carry it, where the edge is one from
2148  * a node j to itself.  "pos" is the sequence number of the given map.
2149  * That is, add constraints that enforce
2150  *
2151  *      (c_j_0 + c_j_n n + c_j_x y) - (c_j_0 + c_j_n n + c_j_x x)
2152  *      = c_j_x (y - x) >= e_i
2153  *
2154  * for each (x,y) in R.
2155  * We obtain general constraints on coefficients (c_0, c_n, c_x)
2156  * of valid constraints for (y - x) and then plug in (-e_i, 0, c_j_x),
2157  * with each coefficient in c_j_x represented as a pair of non-negative
2158  * coefficients.
2159  */
2160 static int add_intra_constraints(struct isl_sched_graph *graph,
2161         struct isl_sched_edge *edge, __isl_take isl_map *map, int pos)
2162 {
2163         unsigned total;
2164         isl_ctx *ctx = isl_map_get_ctx(map);
2165         isl_space *dim;
2166         isl_dim_map *dim_map;
2167         isl_basic_set *coef;
2168         struct isl_sched_node *node = edge->src;
2169
2170         coef = intra_coefficients(graph, map);
2171
2172         dim = isl_space_domain(isl_space_unwrap(isl_basic_set_get_space(coef)));
2173
2174         total = isl_basic_set_total_dim(graph->lp);
2175         dim_map = isl_dim_map_alloc(ctx, total);
2176         isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
2177         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 1, 2,
2178                           isl_space_dim(dim, isl_dim_set), 1,
2179                           node->nvar, -1);
2180         isl_dim_map_range(dim_map, node->start + 2 * node->nparam + 2, 2,
2181                           isl_space_dim(dim, isl_dim_set), 1,
2182                           node->nvar, 1);
2183         graph->lp = isl_basic_set_extend_constraints(graph->lp,
2184                         coef->n_eq, coef->n_ineq);
2185         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
2186                                                            coef, dim_map);
2187         isl_space_free(dim);
2188
2189         return 0;
2190 }
2191
2192 /* Add constraints to graph->lp that force the dependence "map" (which
2193  * is part of the dependence relation of "edge")
2194  * to be respected and attempt to carry it, where the edge is one from
2195  * node j to node k.  "pos" is the sequence number of the given map.
2196  * That is, add constraints that enforce
2197  *
2198  *      (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
2199  *
2200  * for each (x,y) in R.
2201  * We obtain general constraints on coefficients (c_0, c_n, c_x)
2202  * of valid constraints for R and then plug in
2203  * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, c_k_x - c_j_x)
2204  * with each coefficient (except e_i, c_k_0 and c_j_0)
2205  * represented as a pair of non-negative coefficients.
2206  */
2207 static int add_inter_constraints(struct isl_sched_graph *graph,
2208         struct isl_sched_edge *edge, __isl_take isl_map *map, int pos)
2209 {
2210         unsigned total;
2211         isl_ctx *ctx = isl_map_get_ctx(map);
2212         isl_space *dim;
2213         isl_dim_map *dim_map;
2214         isl_basic_set *coef;
2215         struct isl_sched_node *src = edge->src;
2216         struct isl_sched_node *dst = edge->dst;
2217
2218         coef = inter_coefficients(graph, map);
2219
2220         dim = isl_space_domain(isl_space_unwrap(isl_basic_set_get_space(coef)));
2221
2222         total = isl_basic_set_total_dim(graph->lp);
2223         dim_map = isl_dim_map_alloc(ctx, total);
2224
2225         isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
2226
2227         isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, 1);
2228         isl_dim_map_range(dim_map, dst->start + 1, 2, 1, 1, dst->nparam, -1);
2229         isl_dim_map_range(dim_map, dst->start + 2, 2, 1, 1, dst->nparam, 1);
2230         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 1, 2,
2231                           isl_space_dim(dim, isl_dim_set) + src->nvar, 1,
2232                           dst->nvar, -1);
2233         isl_dim_map_range(dim_map, dst->start + 2 * dst->nparam + 2, 2,
2234                           isl_space_dim(dim, isl_dim_set) + src->nvar, 1,
2235                           dst->nvar, 1);
2236
2237         isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, -1);
2238         isl_dim_map_range(dim_map, src->start + 1, 2, 1, 1, src->nparam, 1);
2239         isl_dim_map_range(dim_map, src->start + 2, 2, 1, 1, src->nparam, -1);
2240         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 1, 2,
2241                           isl_space_dim(dim, isl_dim_set), 1,
2242                           src->nvar, 1);
2243         isl_dim_map_range(dim_map, src->start + 2 * src->nparam + 2, 2,
2244                           isl_space_dim(dim, isl_dim_set), 1,
2245                           src->nvar, -1);
2246
2247         graph->lp = isl_basic_set_extend_constraints(graph->lp,
2248                         coef->n_eq, coef->n_ineq);
2249         graph->lp = isl_basic_set_add_constraints_dim_map(graph->lp,
2250                                                            coef, dim_map);
2251         isl_space_free(dim);
2252
2253         return 0;
2254 }
2255
2256 /* Add constraints to graph->lp that force all validity dependences
2257  * to be respected and attempt to carry them.
2258  */
2259 static int add_all_constraints(struct isl_sched_graph *graph)
2260 {
2261         int i, j;
2262         int pos;
2263
2264         pos = 0;
2265         for (i = 0; i < graph->n_edge; ++i) {
2266                 struct isl_sched_edge *edge= &graph->edge[i];
2267
2268                 if (!edge->validity)
2269                         continue;
2270
2271                 for (j = 0; j < edge->map->n; ++j) {
2272                         isl_basic_map *bmap;
2273                         isl_map *map;
2274
2275                         bmap = isl_basic_map_copy(edge->map->p[j]);
2276                         map = isl_map_from_basic_map(bmap);
2277
2278                         if (edge->src == edge->dst &&
2279                             add_intra_constraints(graph, edge, map, pos) < 0)
2280                                 return -1;
2281                         if (edge->src != edge->dst &&
2282                             add_inter_constraints(graph, edge, map, pos) < 0)
2283                                 return -1;
2284                         ++pos;
2285                 }
2286         }
2287
2288         return 0;
2289 }
2290
2291 /* Count the number of equality and inequality constraints
2292  * that will be added to the carry_lp problem.
2293  * We count each edge exactly once.
2294  */
2295 static int count_all_constraints(struct isl_sched_graph *graph,
2296         int *n_eq, int *n_ineq)
2297 {
2298         int i, j;
2299
2300         *n_eq = *n_ineq = 0;
2301         for (i = 0; i < graph->n_edge; ++i) {
2302                 struct isl_sched_edge *edge= &graph->edge[i];
2303                 for (j = 0; j < edge->map->n; ++j) {
2304                         isl_basic_map *bmap;
2305                         isl_map *map;
2306
2307                         bmap = isl_basic_map_copy(edge->map->p[j]);
2308                         map = isl_map_from_basic_map(bmap);
2309
2310                         if (count_map_constraints(graph, edge, map,
2311                                                   n_eq, n_ineq, 1) < 0)
2312                                     return -1;
2313                 }
2314         }
2315
2316         return 0;
2317 }
2318
2319 /* Construct an LP problem for finding schedule coefficients
2320  * such that the schedule carries as many dependences as possible.
2321  * In particular, for each dependence i, we bound the dependence distance
2322  * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
2323  * of all e_i's.  Dependence with e_i = 0 in the solution are simply
2324  * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
2325  * Note that if the dependence relation is a union of basic maps,
2326  * then we have to consider each basic map individually as it may only
2327  * be possible to carry the dependences expressed by some of those
2328  * basic maps and not all off them.
2329  * Below, we consider each of those basic maps as a separate "edge".
2330  *
2331  * All variables of the LP are non-negative.  The actual coefficients
2332  * may be negative, so each coefficient is represented as the difference
2333  * of two non-negative variables.  The negative part always appears
2334  * immediately before the positive part.
2335  * Other than that, the variables have the following order
2336  *
2337  *      - sum of (1 - e_i) over all edges
2338  *      - sum of positive and negative parts of all c_n coefficients
2339  *              (unconstrained when computing non-parametric schedules)
2340  *      - sum of positive and negative parts of all c_x coefficients
2341  *      - for each edge
2342  *              - e_i
2343  *      - for each node
2344  *              - c_i_0
2345  *              - positive and negative parts of c_i_n (if parametric)
2346  *              - positive and negative parts of c_i_x
2347  *
2348  * The constraints are those from the (validity) edges plus three equalities
2349  * to express the sums and n_edge inequalities to express e_i <= 1.
2350  */
2351 static int setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
2352 {
2353         int i, j;
2354         int k;
2355         isl_space *dim;
2356         unsigned total;
2357         int n_eq, n_ineq;
2358         int n_edge;
2359
2360         n_edge = 0;
2361         for (i = 0; i < graph->n_edge; ++i)
2362                 n_edge += graph->edge[i].map->n;
2363
2364         total = 3 + n_edge;
2365         for (i = 0; i < graph->n; ++i) {
2366                 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2367                 node->start = total;
2368                 total += 1 + 2 * (node->nparam + node->nvar);
2369         }
2370
2371         if (count_all_constraints(graph, &n_eq, &n_ineq) < 0)
2372                 return -1;
2373
2374         dim = isl_space_set_alloc(ctx, 0, total);
2375         isl_basic_set_free(graph->lp);
2376         n_eq += 3;
2377         n_ineq += n_edge;
2378         graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
2379         graph->lp = isl_basic_set_set_rational(graph->lp);
2380
2381         k = isl_basic_set_alloc_equality(graph->lp);
2382         if (k < 0)
2383                 return -1;
2384         isl_seq_clr(graph->lp->eq[k], 1 +  total);
2385         isl_int_set_si(graph->lp->eq[k][0], -n_edge);
2386         isl_int_set_si(graph->lp->eq[k][1], 1);
2387         for (i = 0; i < n_edge; ++i)
2388                 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
2389
2390         k = isl_basic_set_alloc_equality(graph->lp);
2391         if (k < 0)
2392                 return -1;
2393         isl_seq_clr(graph->lp->eq[k], 1 +  total);
2394         isl_int_set_si(graph->lp->eq[k][2], -1);
2395         for (i = 0; i < graph->n; ++i) {
2396                 int pos = 1 + graph->node[i].start + 1;
2397
2398                 for (j = 0; j < 2 * graph->node[i].nparam; ++j)
2399                         isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2400         }
2401
2402         k = isl_basic_set_alloc_equality(graph->lp);
2403         if (k < 0)
2404                 return -1;
2405         isl_seq_clr(graph->lp->eq[k], 1 +  total);
2406         isl_int_set_si(graph->lp->eq[k][3], -1);
2407         for (i = 0; i < graph->n; ++i) {
2408                 struct isl_sched_node *node = &graph->node[i];
2409                 int pos = 1 + node->start + 1 + 2 * node->nparam;
2410
2411                 for (j = 0; j < 2 * node->nvar; ++j)
2412                         isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2413         }
2414
2415         for (i = 0; i < n_edge; ++i) {
2416                 k = isl_basic_set_alloc_inequality(graph->lp);
2417                 if (k < 0)
2418                         return -1;
2419                 isl_seq_clr(graph->lp->ineq[k], 1 +  total);
2420                 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
2421                 isl_int_set_si(graph->lp->ineq[k][0], 1);
2422         }
2423
2424         if (add_all_constraints(graph) < 0)
2425                 return -1;
2426
2427         return 0;
2428 }
2429
2430 /* If the schedule_split_scaled option is set and if the linear
2431  * parts of the scheduling rows for all nodes in the graphs have
2432  * non-trivial common divisor, then split off the constant term
2433  * from the linear part.
2434  * The constant term is then placed in a separate band and
2435  * the linear part is reduced.
2436  */
2437 static int split_scaled(isl_ctx *ctx, struct isl_sched_graph *graph)
2438 {
2439         int i;
2440         int row;
2441         isl_int gcd, gcd_i;
2442
2443         if (!ctx->opt->schedule_split_scaled)
2444                 return 0;
2445         if (graph->n <= 1)
2446                 return 0;
2447
2448         if (graph->n_total_row >= graph->max_row)
2449                 isl_die(ctx, isl_error_internal,
2450                         "too many schedule rows", return -1);
2451
2452         isl_int_init(gcd);
2453         isl_int_init(gcd_i);
2454
2455         isl_int_set_si(gcd, 0);
2456
2457         row = isl_mat_rows(graph->node[0].sched) - 1;
2458
2459         for (i = 0; i < graph->n; ++i) {
2460                 struct isl_sched_node *node = &graph->node[i];
2461                 int cols = isl_mat_cols(node->sched);
2462
2463                 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
2464                 isl_int_gcd(gcd, gcd, gcd_i);
2465         }
2466
2467         isl_int_clear(gcd_i);
2468
2469         if (isl_int_cmp_si(gcd, 1) <= 0) {
2470                 isl_int_clear(gcd);
2471                 return 0;
2472         }
2473
2474         next_band(graph);
2475
2476         for (i = 0; i < graph->n; ++i) {
2477                 struct isl_sched_node *node = &graph->node[i];
2478
2479                 isl_map_free(node->sched_map);
2480                 node->sched_map = NULL;
2481                 node->sched = isl_mat_add_zero_rows(node->sched, 1);
2482                 if (!node->sched)
2483                         goto error;
2484                 isl_int_fdiv_r(node->sched->row[row + 1][0],
2485                                node->sched->row[row][0], gcd);
2486                 isl_int_fdiv_q(node->sched->row[row][0],
2487                                node->sched->row[row][0], gcd);
2488                 isl_int_mul(node->sched->row[row][0],
2489                             node->sched->row[row][0], gcd);
2490                 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
2491                 if (!node->sched)
2492                         goto error;
2493                 node->band[graph->n_total_row] = graph->n_band;
2494         }
2495
2496         graph->n_total_row++;
2497
2498         isl_int_clear(gcd);
2499         return 0;
2500 error:
2501         isl_int_clear(gcd);
2502         return -1;
2503 }
2504
2505 static int compute_component_schedule(isl_ctx *ctx,
2506         struct isl_sched_graph *graph);
2507
2508 /* Is the schedule row "sol" trivial on node "node"?
2509  * That is, is the solution zero on the dimensions orthogonal to
2510  * the previously found solutions?
2511  * Each coefficient is represented as the difference between
2512  * two non-negative values in "sol".  The coefficient is then
2513  * zero if those two values are equal to each other.
2514  */
2515 static int is_trivial(struct isl_sched_node *node, __isl_keep isl_vec *sol)
2516 {
2517         int i;
2518         int pos;
2519         int len;
2520
2521         pos = 1 + node->start + 1 + 2 * (node->nparam + node->rank);
2522         len = 2 * (node->nvar - node->rank);
2523
2524         if (len == 0)
2525                 return 0;
2526
2527         for (i = 0; i < len; i += 2)
2528                 if (isl_int_ne(sol->el[pos + i], sol->el[pos + i + 1]))
2529                         return 0;
2530
2531         return 1;
2532 }
2533
2534 /* Is the schedule row "sol" trivial on any node where it should
2535  * not be trivial?
2536  */
2537 static int is_any_trivial(struct isl_sched_graph *graph,
2538         __isl_keep isl_vec *sol)
2539 {
2540         int i;
2541
2542         for (i = 0; i < graph->n; ++i) {
2543                 struct isl_sched_node *node = &graph->node[i];
2544
2545                 if (!needs_row(graph, node))
2546                         continue;
2547                 if (is_trivial(node, sol))
2548                         return 1;
2549         }
2550
2551         return 0;
2552 }
2553
2554 /* Construct a schedule row for each node such that as many dependences
2555  * as possible are carried and then continue with the next band.
2556  *
2557  * If the computed schedule row turns out to be trivial on one or
2558  * more nodes where it should not be trivial, then we throw it away
2559  * and try again on each component separately.
2560  */
2561 static int carry_dependences(isl_ctx *ctx, struct isl_sched_graph *graph)
2562 {
2563         int i;
2564         int n_edge;
2565         isl_vec *sol;
2566         isl_basic_set *lp;
2567
2568         n_edge = 0;
2569         for (i = 0; i < graph->n_edge; ++i)
2570                 n_edge += graph->edge[i].map->n;
2571
2572         if (setup_carry_lp(ctx, graph) < 0)
2573                 return -1;
2574
2575         lp = isl_basic_set_copy(graph->lp);
2576         sol = isl_tab_basic_set_non_neg_lexmin(lp);
2577         if (!sol)
2578                 return -1;
2579
2580         if (sol->size == 0) {
2581                 isl_vec_free(sol);
2582                 isl_die(ctx, isl_error_internal,
2583                         "error in schedule construction", return -1);
2584         }
2585
2586         if (isl_int_cmp_si(sol->el[1], n_edge) >= 0) {
2587                 isl_vec_free(sol);
2588                 isl_die(ctx, isl_error_unknown,
2589                         "unable to carry dependences", return -1);
2590         }
2591
2592         if (is_any_trivial(graph, sol)) {
2593                 isl_vec_free(sol);
2594                 if (graph->scc > 1)
2595                         return compute_component_schedule(ctx, graph);
2596                 isl_die(ctx, isl_error_unknown,
2597                         "unable to construct non-trivial solution", return -1);
2598         }
2599
2600         if (update_schedule(graph, sol, 0, 0) < 0)
2601                 return -1;
2602
2603         if (split_scaled(ctx, graph) < 0)
2604                 return -1;
2605
2606         return compute_next_band(ctx, graph);
2607 }
2608
2609 /* Are there any (non-empty) validity edges in the graph?
2610  */
2611 static int has_validity_edges(struct isl_sched_graph *graph)
2612 {
2613         int i;
2614
2615         for (i = 0; i < graph->n_edge; ++i) {
2616                 int empty;
2617
2618                 empty = isl_map_plain_is_empty(graph->edge[i].map);
2619                 if (empty < 0)
2620                         return -1;
2621                 if (empty)
2622                         continue;
2623                 if (graph->edge[i].validity)
2624                         return 1;
2625         }
2626
2627         return 0;
2628 }
2629
2630 /* Should we apply a Feautrier step?
2631  * That is, did the user request the Feautrier algorithm and are
2632  * there any validity dependences (left)?
2633  */
2634 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
2635 {
2636         if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
2637                 return 0;
2638
2639         return has_validity_edges(graph);
2640 }
2641
2642 /* Compute a schedule for a connected dependence graph using Feautrier's
2643  * multi-dimensional scheduling algorithm.
2644  * The original algorithm is described in [1].
2645  * The main idea is to minimize the number of scheduling dimensions, by
2646  * trying to satisfy as many dependences as possible per scheduling dimension.
2647  *
2648  * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
2649  *     Problem, Part II: Multi-Dimensional Time.
2650  *     In Intl. Journal of Parallel Programming, 1992.
2651  */
2652 static int compute_schedule_wcc_feautrier(isl_ctx *ctx,
2653         struct isl_sched_graph *graph)
2654 {
2655         return carry_dependences(ctx, graph);
2656 }
2657
2658 /* Compute a schedule for a connected dependence graph.
2659  * We try to find a sequence of as many schedule rows as possible that result
2660  * in non-negative dependence distances (independent of the previous rows
2661  * in the sequence, i.e., such that the sequence is tilable).
2662  * If we can't find any more rows we either
2663  * - split between SCCs and start over (assuming we found an interesting
2664  *      pair of SCCs between which to split)
2665  * - continue with the next band (assuming the current band has at least
2666  *      one row)
2667  * - try to carry as many dependences as possible and continue with the next
2668  *      band
2669  *
2670  * If Feautrier's algorithm is selected, we first recursively try to satisfy
2671  * as many validity dependences as possible. When all validity dependences
2672  * are satisfied we extend the schedule to a full-dimensional schedule.
2673  *
2674  * If we manage to complete the schedule, we finish off by topologically
2675  * sorting the statements based on the remaining dependences.
2676  *
2677  * If ctx->opt->schedule_outer_zero_distance is set, then we force the
2678  * outermost dimension in the current band to be zero distance.  If this
2679  * turns out to be impossible, we fall back on the general scheme above
2680  * and try to carry as many dependences as possible.
2681  */
2682 static int compute_schedule_wcc(isl_ctx *ctx, struct isl_sched_graph *graph)
2683 {
2684         int force_zero = 0;
2685
2686         if (detect_sccs(ctx, graph) < 0)
2687                 return -1;
2688         if (sort_sccs(graph) < 0)
2689                 return -1;
2690
2691         if (compute_maxvar(graph) < 0)
2692                 return -1;
2693
2694         if (need_feautrier_step(ctx, graph))
2695                 return compute_schedule_wcc_feautrier(ctx, graph);
2696
2697         if (ctx->opt->schedule_outer_zero_distance)
2698                 force_zero = 1;
2699
2700         while (graph->n_row < graph->maxvar) {
2701                 isl_vec *sol;
2702
2703                 graph->src_scc = -1;
2704                 graph->dst_scc = -1;
2705
2706                 if (setup_lp(ctx, graph, force_zero) < 0)
2707                         return -1;
2708                 sol = solve_lp(graph);
2709                 if (!sol)
2710                         return -1;
2711                 if (sol->size == 0) {
2712                         isl_vec_free(sol);
2713                         if (!ctx->opt->schedule_maximize_band_depth &&
2714                             graph->n_total_row > graph->band_start)
2715                                 return compute_next_band(ctx, graph);
2716                         if (graph->src_scc >= 0)
2717                                 return compute_split_schedule(ctx, graph);
2718                         if (graph->n_total_row > graph->band_start)
2719                                 return compute_next_band(ctx, graph);
2720                         return carry_dependences(ctx, graph);
2721                 }
2722                 if (update_schedule(graph, sol, 1, 1) < 0)
2723                         return -1;
2724                 force_zero = 0;
2725         }
2726
2727         if (graph->n_total_row > graph->band_start)
2728                 next_band(graph);
2729         return sort_statements(ctx, graph);
2730 }
2731
2732 /* Add a row to the schedules that separates the SCCs and move
2733  * to the next band.
2734  */
2735 static int split_on_scc(isl_ctx *ctx, struct isl_sched_graph *graph)
2736 {
2737         int i;
2738
2739         if (graph->n_total_row >= graph->max_row)
2740                 isl_die(ctx, isl_error_internal,
2741                         "too many schedule rows", return -1);
2742
2743         for (i = 0; i < graph->n; ++i) {
2744                 struct isl_sched_node *node = &graph->node[i];
2745                 int row = isl_mat_rows(node->sched);
2746
2747                 isl_map_free(node->sched_map);
2748                 node->sched_map = NULL;
2749                 node->sched = isl_mat_add_zero_rows(node->sched, 1);
2750                 node->sched = isl_mat_set_element_si(node->sched, row, 0,
2751                                                      node->scc);
2752                 if (!node->sched)
2753                         return -1;
2754                 node->band[graph->n_total_row] = graph->n_band;
2755         }
2756
2757         graph->n_total_row++;
2758         next_band(graph);
2759
2760         return 0;
2761 }
2762
2763 /* Compute a schedule for each component (identified by node->scc)
2764  * of the dependence graph separately and then combine the results.
2765  * Depending on the setting of schedule_fuse, a component may be
2766  * either weakly or strongly connected.
2767  *
2768  * The band_id is adjusted such that each component has a separate id.
2769  * Note that the band_id may have already been set to a value different
2770  * from zero by compute_split_schedule.
2771  */
2772 static int compute_component_schedule(isl_ctx *ctx,
2773         struct isl_sched_graph *graph)
2774 {
2775         int wcc, i;
2776         int n, n_edge;
2777         int n_total_row, orig_total_row;
2778         int n_band, orig_band;
2779
2780         if (ctx->opt->schedule_fuse == ISL_SCHEDULE_FUSE_MIN ||
2781             ctx->opt->schedule_separate_components)
2782                 if (split_on_scc(ctx, graph) < 0)
2783                         return -1;
2784
2785         n_total_row = 0;
2786         orig_total_row = graph->n_total_row;
2787         n_band = 0;
2788         orig_band = graph->n_band;
2789         for (i = 0; i < graph->n; ++i)
2790                 graph->node[i].band_id[graph->n_band] += graph->node[i].scc;
2791         for (wcc = 0; wcc < graph->scc; ++wcc) {
2792                 n = 0;
2793                 for (i = 0; i < graph->n; ++i)
2794                         if (graph->node[i].scc == wcc)
2795                                 n++;
2796                 n_edge = 0;
2797                 for (i = 0; i < graph->n_edge; ++i)
2798                         if (graph->edge[i].src->scc == wcc &&
2799                             graph->edge[i].dst->scc == wcc)
2800                                 n_edge++;
2801
2802                 if (compute_sub_schedule(ctx, graph, n, n_edge,
2803                                     &node_scc_exactly,
2804                                     &edge_scc_exactly, wcc, 1) < 0)
2805                         return -1;
2806                 if (graph->n_total_row > n_total_row)
2807                         n_total_row = graph->n_total_row;
2808                 graph->n_total_row = orig_total_row;
2809                 if (graph->n_band > n_band)
2810                         n_band = graph->n_band;
2811                 graph->n_band = orig_band;
2812         }
2813
2814         graph->n_total_row = n_total_row;
2815         graph->n_band = n_band;
2816
2817         return pad_schedule(graph);
2818 }
2819
2820 /* Compute a schedule for the given dependence graph.
2821  * We first check if the graph is connected (through validity dependences)
2822  * and, if not, compute a schedule for each component separately.
2823  * If schedule_fuse is set to minimal fusion, then we check for strongly
2824  * connected components instead and compute a separate schedule for
2825  * each such strongly connected component.
2826  */
2827 static int compute_schedule(isl_ctx *ctx, struct isl_sched_graph *graph)
2828 {
2829         if (ctx->opt->schedule_fuse == ISL_SCHEDULE_FUSE_MIN) {
2830                 if (detect_sccs(ctx, graph) < 0)
2831                         return -1;
2832         } else {
2833                 if (detect_wccs(ctx, graph) < 0)
2834                         return -1;
2835         }
2836
2837         if (graph->scc > 1)
2838                 return compute_component_schedule(ctx, graph);
2839
2840         return compute_schedule_wcc(ctx, graph);
2841 }
2842
2843 /* Compute a schedule for the given union of domains that respects
2844  * all the validity dependences.
2845  * If the default isl scheduling algorithm is used, it tries to minimize
2846  * the dependence distances over the proximity dependences.
2847  * If Feautrier's scheduling algorithm is used, the proximity dependence
2848  * distances are only minimized during the extension to a full-dimensional
2849  * schedule.
2850  */
2851 __isl_give isl_schedule *isl_union_set_compute_schedule(
2852         __isl_take isl_union_set *domain,
2853         __isl_take isl_union_map *validity,
2854         __isl_take isl_union_map *proximity)
2855 {
2856         isl_ctx *ctx = isl_union_set_get_ctx(domain);
2857         isl_space *dim;
2858         struct isl_sched_graph graph = { 0 };
2859         isl_schedule *sched;
2860         struct isl_extract_edge_data data;
2861
2862         domain = isl_union_set_align_params(domain,
2863                                             isl_union_map_get_space(validity));
2864         domain = isl_union_set_align_params(domain,
2865                                             isl_union_map_get_space(proximity));
2866         dim = isl_union_set_get_space(domain);
2867         validity = isl_union_map_align_params(validity, isl_space_copy(dim));
2868         proximity = isl_union_map_align_params(proximity, dim);
2869
2870         if (!domain)
2871                 goto error;
2872
2873         graph.n = isl_union_set_n_set(domain);
2874         if (graph.n == 0)
2875                 goto empty;
2876         if (graph_alloc(ctx, &graph, graph.n,
2877             isl_union_map_n_map(validity) + isl_union_map_n_map(proximity)) < 0)
2878                 goto error;
2879         if (compute_max_row(&graph, domain) < 0)
2880                 goto error;
2881         graph.root = 1;
2882         graph.n = 0;
2883         if (isl_union_set_foreach_set(domain, &extract_node, &graph) < 0)
2884                 goto error;
2885         if (graph_init_table(ctx, &graph) < 0)
2886                 goto error;
2887         graph.max_edge[isl_edge_validity] = isl_union_map_n_map(validity);
2888         graph.max_edge[isl_edge_proximity] = isl_union_map_n_map(proximity);
2889         if (graph_init_edge_tables(ctx, &graph) < 0)
2890                 goto error;
2891         graph.n_edge = 0;
2892         data.graph = &graph;
2893         data.type = isl_edge_validity;
2894         if (isl_union_map_foreach_map(validity, &extract_edge, &data) < 0)
2895                 goto error;
2896         data.type = isl_edge_proximity;
2897         if (isl_union_map_foreach_map(proximity, &extract_edge, &data) < 0)
2898                 goto error;
2899
2900         if (compute_schedule(ctx, &graph) < 0)
2901                 goto error;
2902
2903 empty:
2904         sched = extract_schedule(&graph, isl_union_set_get_space(domain));
2905
2906         graph_free(ctx, &graph);
2907         isl_union_set_free(domain);
2908         isl_union_map_free(validity);
2909         isl_union_map_free(proximity);
2910
2911         return sched;
2912 error:
2913         graph_free(ctx, &graph);
2914         isl_union_set_free(domain);
2915         isl_union_map_free(validity);
2916         isl_union_map_free(proximity);
2917         return NULL;
2918 }
2919
2920 void *isl_schedule_free(__isl_take isl_schedule *sched)
2921 {
2922         int i;
2923         if (!sched)
2924                 return NULL;
2925
2926         if (--sched->ref > 0)
2927                 return NULL;
2928
2929         for (i = 0; i < sched->n; ++i) {
2930                 isl_multi_aff_free(sched->node[i].sched);
2931                 free(sched->node[i].band_end);
2932                 free(sched->node[i].band_id);
2933                 free(sched->node[i].zero);
2934         }
2935         isl_space_free(sched->dim);
2936         isl_band_list_free(sched->band_forest);
2937         free(sched);
2938         return NULL;
2939 }
2940
2941 isl_ctx *isl_schedule_get_ctx(__isl_keep isl_schedule *schedule)
2942 {
2943         return schedule ? isl_space_get_ctx(schedule->dim) : NULL;
2944 }
2945
2946 /* Return an isl_union_map of the schedule.  If we have already constructed
2947  * a band forest, then this band forest may have been modified so we need
2948  * to extract the isl_union_map from the forest rather than from
2949  * the originally computed schedule.
2950  */
2951 __isl_give isl_union_map *isl_schedule_get_map(__isl_keep isl_schedule *sched)
2952 {
2953         int i;
2954         isl_union_map *umap;
2955
2956         if (!sched)
2957                 return NULL;
2958
2959         if (sched->band_forest)
2960                 return isl_band_list_get_suffix_schedule(sched->band_forest);
2961
2962         umap = isl_union_map_empty(isl_space_copy(sched->dim));
2963         for (i = 0; i < sched->n; ++i) {
2964                 isl_multi_aff *ma;
2965
2966                 ma = isl_multi_aff_copy(sched->node[i].sched);
2967                 umap = isl_union_map_add_map(umap, isl_map_from_multi_aff(ma));
2968         }
2969
2970         return umap;
2971 }
2972
2973 static __isl_give isl_band_list *construct_band_list(
2974         __isl_keep isl_schedule *schedule, __isl_keep isl_band *parent,
2975         int band_nr, int *parent_active, int n_active);
2976
2977 /* Construct an isl_band structure for the band in the given schedule
2978  * with sequence number band_nr for the n_active nodes marked by active.
2979  * If the nodes don't have a band with the given sequence number,
2980  * then a band without members is created.
2981  *
2982  * Because of the way the schedule is constructed, we know that
2983  * the position of the band inside the schedule of a node is the same
2984  * for all active nodes.
2985  */
2986 static __isl_give isl_band *construct_band(__isl_keep isl_schedule *schedule,
2987         __isl_keep isl_band *parent,
2988         int band_nr, int *active, int n_active)
2989 {
2990         int i, j;
2991         isl_ctx *ctx = isl_schedule_get_ctx(schedule);
2992         isl_band *band;
2993         unsigned start, end;
2994
2995         band = isl_band_alloc(ctx);
2996         if (!band)
2997                 return NULL;
2998
2999         band->schedule = schedule;
3000         band->parent = parent;
3001
3002         for (i = 0; i < schedule->n; ++i)
3003                 if (active[i] && schedule->node[i].n_band > band_nr + 1)
3004                         break;
3005
3006         if (i < schedule->n) {
3007                 band->children = construct_band_list(schedule, band,
3008                                                 band_nr + 1, active, n_active);
3009                 if (!band->children)
3010                         goto error;
3011         }
3012
3013         for (i = 0; i < schedule->n; ++i)
3014                 if (active[i])
3015                         break;
3016
3017         if (i >= schedule->n)
3018                 isl_die(ctx, isl_error_internal,
3019                         "band without active statements", goto error);
3020
3021         start = band_nr ? schedule->node[i].band_end[band_nr - 1] : 0;
3022         end = band_nr < schedule->node[i].n_band ?
3023                 schedule->node[i].band_end[band_nr] : start;
3024         band->n = end - start;
3025
3026         band->zero = isl_alloc_array(ctx, int, band->n);
3027         if (!band->zero)
3028                 goto error;
3029
3030         for (j = 0; j < band->n; ++j)
3031                 band->zero[j] = schedule->node[i].zero[start + j];
3032
3033         band->pma = isl_union_pw_multi_aff_empty(isl_space_copy(schedule->dim));
3034         for (i = 0; i < schedule->n; ++i) {
3035                 isl_multi_aff *ma;
3036                 isl_pw_multi_aff *pma;
3037                 unsigned n_out;
3038
3039                 if (!active[i])
3040                         continue;
3041
3042                 ma = isl_multi_aff_copy(schedule->node[i].sched);
3043                 n_out = isl_multi_aff_dim(ma, isl_dim_out);
3044                 ma = isl_multi_aff_drop_dims(ma, isl_dim_out, end, n_out - end);
3045                 ma = isl_multi_aff_drop_dims(ma, isl_dim_out, 0, start);
3046                 pma = isl_pw_multi_aff_from_multi_aff(ma);
3047                 band->pma = isl_union_pw_multi_aff_add_pw_multi_aff(band->pma,
3048                                                                     pma);
3049         }
3050         if (!band->pma)
3051                 goto error;
3052
3053         return band;
3054 error:
3055         isl_band_free(band);
3056         return NULL;
3057 }
3058
3059 /* Construct a list of bands that start at the same position (with
3060  * sequence number band_nr) in the schedules of the nodes that
3061  * were active in the parent band.
3062  *
3063  * A separate isl_band structure is created for each band_id
3064  * and for each node that does not have a band with sequence
3065  * number band_nr.  In the latter case, a band without members
3066  * is created.
3067  * This ensures that if a band has any children, then each node
3068  * that was active in the band is active in exactly one of the children.
3069  */
3070 static __isl_give isl_band_list *construct_band_list(
3071         __isl_keep isl_schedule *schedule, __isl_keep isl_band *parent,
3072         int band_nr, int *parent_active, int n_active)
3073 {
3074         int i, j;
3075         isl_ctx *ctx = isl_schedule_get_ctx(schedule);
3076         int *active;
3077         int n_band;
3078         isl_band_list *list;
3079
3080         n_band = 0;
3081         for (i = 0; i < n_active; ++i) {
3082                 for (j = 0; j < schedule->n; ++j) {
3083                         if (!parent_active[j])
3084                                 continue;
3085                         if (schedule->node[j].n_band <= band_nr)
3086                                 continue;
3087                         if (schedule->node[j].band_id[band_nr] == i) {
3088                                 n_band++;
3089                                 break;
3090                         }
3091                 }
3092         }
3093         for (j = 0; j < schedule->n; ++j)
3094                 if (schedule->node[j].n_band <= band_nr)
3095                         n_band++;
3096
3097         if (n_band == 1) {
3098                 isl_band *band;
3099                 list = isl_band_list_alloc(ctx, n_band);
3100                 band = construct_band(schedule, parent, band_nr,
3101                                         parent_active, n_active);
3102                 return isl_band_list_add(list, band);
3103         }
3104
3105         active = isl_alloc_array(ctx, int, schedule->n);
3106         if (!active)
3107                 return NULL;
3108
3109         list = isl_band_list_alloc(ctx, n_band);
3110
3111         for (i = 0; i < n_active; ++i) {
3112                 int n = 0;
3113                 isl_band *band;
3114
3115                 for (j = 0; j < schedule->n; ++j) {
3116                         active[j] = parent_active[j] &&
3117                                         schedule->node[j].n_band > band_nr &&
3118                                         schedule->node[j].band_id[band_nr] == i;
3119                         if (active[j])
3120                                 n++;
3121                 }
3122                 if (n == 0)
3123                         continue;
3124
3125                 band = construct_band(schedule, parent, band_nr, active, n);
3126
3127                 list = isl_band_list_add(list, band);
3128         }
3129         for (i = 0; i < schedule->n; ++i) {
3130                 isl_band *band;
3131                 if (!parent_active[i])
3132                         continue;
3133                 if (schedule->node[i].n_band > band_nr)
3134                         continue;
3135                 for (j = 0; j < schedule->n; ++j)
3136                         active[j] = j == i;
3137                 band = construct_band(schedule, parent, band_nr, active, 1);
3138                 list = isl_band_list_add(list, band);
3139         }
3140
3141         free(active);
3142
3143         return list;
3144 }
3145
3146 /* Construct a band forest representation of the schedule and
3147  * return the list of roots.
3148  */
3149 static __isl_give isl_band_list *construct_forest(
3150         __isl_keep isl_schedule *schedule)
3151 {
3152         int i;
3153         isl_ctx *ctx = isl_schedule_get_ctx(schedule);
3154         isl_band_list *forest;
3155         int *active;
3156
3157         active = isl_alloc_array(ctx, int, schedule->n);
3158         if (!active)
3159                 return NULL;
3160
3161         for (i = 0; i < schedule->n; ++i)
3162                 active[i] = 1;
3163
3164         forest = construct_band_list(schedule, NULL, 0, active, schedule->n);
3165
3166         free(active);
3167
3168         return forest;
3169 }
3170
3171 /* Return the roots of a band forest representation of the schedule.
3172  */
3173 __isl_give isl_band_list *isl_schedule_get_band_forest(
3174         __isl_keep isl_schedule *schedule)
3175 {
3176         if (!schedule)
3177                 return NULL;
3178         if (!schedule->band_forest)
3179                 schedule->band_forest = construct_forest(schedule);
3180         return isl_band_list_dup(schedule->band_forest);
3181 }
3182
3183 /* Call "fn" on each band in the schedule in depth-first post-order.
3184  */
3185 int isl_schedule_foreach_band(__isl_keep isl_schedule *sched,
3186         int (*fn)(__isl_keep isl_band *band, void *user), void *user)
3187 {
3188         int r;
3189         isl_band_list *forest;
3190
3191         if (!sched)
3192                 return -1;
3193
3194         forest = isl_schedule_get_band_forest(sched);
3195         r = isl_band_list_foreach_band(forest, fn, user);
3196         isl_band_list_free(forest);
3197
3198         return r;
3199 }
3200
3201 static __isl_give isl_printer *print_band_list(__isl_take isl_printer *p,
3202         __isl_keep isl_band_list *list);
3203
3204 static __isl_give isl_printer *print_band(__isl_take isl_printer *p,
3205         __isl_keep isl_band *band)
3206 {
3207         isl_band_list *children;
3208
3209         p = isl_printer_start_line(p);
3210         p = isl_printer_print_union_pw_multi_aff(p, band->pma);
3211         p = isl_printer_end_line(p);
3212
3213         if (!isl_band_has_children(band))
3214                 return p;
3215
3216         children = isl_band_get_children(band);
3217
3218         p = isl_printer_indent(p, 4);
3219         p = print_band_list(p, children);
3220         p = isl_printer_indent(p, -4);
3221
3222         isl_band_list_free(children);
3223
3224         return p;
3225 }
3226
3227 static __isl_give isl_printer *print_band_list(__isl_take isl_printer *p,
3228         __isl_keep isl_band_list *list)
3229 {
3230         int i, n;
3231
3232         n = isl_band_list_n_band(list);
3233         for (i = 0; i < n; ++i) {
3234                 isl_band *band;
3235                 band = isl_band_list_get_band(list, i);
3236                 p = print_band(p, band);
3237                 isl_band_free(band);
3238         }
3239
3240         return p;
3241 }
3242
3243 __isl_give isl_printer *isl_printer_print_schedule(__isl_take isl_printer *p,
3244         __isl_keep isl_schedule *schedule)
3245 {
3246         isl_band_list *forest;
3247
3248         forest = isl_schedule_get_band_forest(schedule);
3249
3250         p = print_band_list(p, forest);
3251
3252         isl_band_list_free(forest);
3253
3254         return p;
3255 }
3256
3257 void isl_schedule_dump(__isl_keep isl_schedule *schedule)
3258 {
3259         isl_printer *printer;
3260
3261         if (!schedule)
3262                 return;
3263
3264         printer = isl_printer_to_file(isl_schedule_get_ctx(schedule), stderr);
3265         printer = isl_printer_print_schedule(printer, schedule);
3266
3267         isl_printer_free(printer);
3268 }