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