expose isl_union_set_project_out_all_params
[isl.git] / isl_scheduler.c
blob967627b6e058bc9582da6d2cdd1f3fac1f2ba45e
1 /*
2 * Copyright 2011 INRIA Saclay
3 * Copyright 2012-2014 Ecole Normale Superieure
4 * Copyright 2015-2016 Sven Verdoolaege
5 * Copyright 2016 INRIA Paris
6 * Copyright 2017 Sven Verdoolaege
8 * Use of this software is governed by the MIT license
10 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
11 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
12 * 91893 Orsay, France
13 * and Ecole Normale Superieure, 45 rue d'Ulm, 75230 Paris, France
14 * and Centre de Recherche Inria de Paris, 2 rue Simone Iff - Voie DQ12,
15 * CS 42112, 75589 Paris Cedex 12, France
18 #include <isl_ctx_private.h>
19 #include <isl_map_private.h>
20 #include <isl_space_private.h>
21 #include <isl_aff_private.h>
22 #include <isl/hash.h>
23 #include <isl/id.h>
24 #include <isl/constraint.h>
25 #include <isl/schedule.h>
26 #include <isl_schedule_constraints.h>
27 #include <isl/schedule_node.h>
28 #include <isl_mat_private.h>
29 #include <isl_vec_private.h>
30 #include <isl/set.h>
31 #include <isl_union_set_private.h>
32 #include <isl_seq.h>
33 #include <isl_tab.h>
34 #include <isl_dim_map.h>
35 #include <isl/map_to_basic_set.h>
36 #include <isl_sort.h>
37 #include <isl_options_private.h>
38 #include <isl_tarjan.h>
39 #include <isl_morph.h>
40 #include <isl/ilp.h>
41 #include <isl_val_private.h>
44 * The scheduling algorithm implemented in this file was inspired by
45 * Bondhugula et al., "Automatic Transformations for Communication-Minimized
46 * Parallelization and Locality Optimization in the Polyhedral Model".
48 * For a detailed description of the variant implemented in isl,
49 * see Verdoolaege and Janssens, "Scheduling for PPCG" (2017).
53 /* Internal information about a node that is used during the construction
54 * of a schedule.
55 * space represents the original space in which the domain lives;
56 * that is, the space is not affected by compression
57 * sched is a matrix representation of the schedule being constructed
58 * for this node; if compressed is set, then this schedule is
59 * defined over the compressed domain space
60 * sched_map is an isl_map representation of the same (partial) schedule
61 * sched_map may be NULL; if compressed is set, then this map
62 * is defined over the uncompressed domain space
63 * rank is the number of linearly independent rows in the linear part
64 * of sched
65 * the rows of "vmap" represent a change of basis for the node
66 * variables; the first rank rows span the linear part of
67 * the schedule rows; the remaining rows are linearly independent
68 * the rows of "indep" represent linear combinations of the schedule
69 * coefficients that are non-zero when the schedule coefficients are
70 * linearly independent of previously computed schedule rows.
71 * start is the first variable in the LP problem in the sequences that
72 * represents the schedule coefficients of this node
73 * nvar is the dimension of the (compressed) domain
74 * nparam is the number of parameters or 0 if we are not constructing
75 * a parametric schedule
77 * If compressed is set, then hull represents the constraints
78 * that were used to derive the compression, while compress and
79 * decompress map the original space to the compressed space and
80 * vice versa.
82 * scc is the index of SCC (or WCC) this node belongs to
84 * "cluster" is only used inside extract_clusters and identifies
85 * the cluster of SCCs that the node belongs to.
87 * coincident contains a boolean for each of the rows of the schedule,
88 * indicating whether the corresponding scheduling dimension satisfies
89 * the coincidence constraints in the sense that the corresponding
90 * dependence distances are zero.
92 * If the schedule_treat_coalescing option is set, then
93 * "sizes" contains the sizes of the (compressed) instance set
94 * in each direction. If there is no fixed size in a given direction,
95 * then the corresponding size value is set to infinity.
96 * If the schedule_treat_coalescing option or the schedule_max_coefficient
97 * option is set, then "max" contains the maximal values for
98 * schedule coefficients of the (compressed) variables. If no bound
99 * needs to be imposed on a particular variable, then the corresponding
100 * value is negative.
101 * If not NULL, then "bounds" contains a non-parametric set
102 * in the compressed space that is bounded by the size in each direction.
104 struct isl_sched_node {
105 isl_space *space;
106 int compressed;
107 isl_set *hull;
108 isl_multi_aff *compress;
109 isl_multi_aff *decompress;
110 isl_mat *sched;
111 isl_map *sched_map;
112 int rank;
113 isl_mat *indep;
114 isl_mat *vmap;
115 int start;
116 int nvar;
117 int nparam;
119 int scc;
120 int cluster;
122 int *coincident;
124 isl_multi_val *sizes;
125 isl_basic_set *bounds;
126 isl_vec *max;
129 static int node_has_tuples(const void *entry, const void *val)
131 struct isl_sched_node *node = (struct isl_sched_node *)entry;
132 isl_space *space = (isl_space *) val;
134 return isl_space_has_equal_tuples(node->space, space);
137 static int node_scc_exactly(struct isl_sched_node *node, int scc)
139 return node->scc == scc;
142 static int node_scc_at_most(struct isl_sched_node *node, int scc)
144 return node->scc <= scc;
147 static int node_scc_at_least(struct isl_sched_node *node, int scc)
149 return node->scc >= scc;
152 /* An edge in the dependence graph. An edge may be used to
153 * ensure validity of the generated schedule, to minimize the dependence
154 * distance or both
156 * map is the dependence relation, with i -> j in the map if j depends on i
157 * tagged_condition and tagged_validity contain the union of all tagged
158 * condition or conditional validity dependence relations that
159 * specialize the dependence relation "map"; that is,
160 * if (i -> a) -> (j -> b) is an element of "tagged_condition"
161 * or "tagged_validity", then i -> j is an element of "map".
162 * If these fields are NULL, then they represent the empty relation.
163 * src is the source node
164 * dst is the sink node
166 * types is a bit vector containing the types of this edge.
167 * validity is set if the edge is used to ensure correctness
168 * coincidence is used to enforce zero dependence distances
169 * proximity is set if the edge is used to minimize dependence distances
170 * condition is set if the edge represents a condition
171 * for a conditional validity schedule constraint
172 * local can only be set for condition edges and indicates that
173 * the dependence distance over the edge should be zero
174 * conditional_validity is set if the edge is used to conditionally
175 * ensure correctness
177 * For validity edges, start and end mark the sequence of inequality
178 * constraints in the LP problem that encode the validity constraint
179 * corresponding to this edge.
181 * During clustering, an edge may be marked "no_merge" if it should
182 * not be used to merge clusters.
183 * The weight is also only used during clustering and it is
184 * an indication of how many schedule dimensions on either side
185 * of the schedule constraints can be aligned.
186 * If the weight is negative, then this means that this edge was postponed
187 * by has_bounded_distances or any_no_merge. The original weight can
188 * be retrieved by adding 1 + graph->max_weight, with "graph"
189 * the graph containing this edge.
191 struct isl_sched_edge {
192 isl_map *map;
193 isl_union_map *tagged_condition;
194 isl_union_map *tagged_validity;
196 struct isl_sched_node *src;
197 struct isl_sched_node *dst;
199 unsigned types;
201 int start;
202 int end;
204 int no_merge;
205 int weight;
208 /* Is "edge" marked as being of type "type"?
210 static int is_type(struct isl_sched_edge *edge, enum isl_edge_type type)
212 return ISL_FL_ISSET(edge->types, 1 << type);
215 /* Mark "edge" as being of type "type".
217 static void set_type(struct isl_sched_edge *edge, enum isl_edge_type type)
219 ISL_FL_SET(edge->types, 1 << type);
222 /* No longer mark "edge" as being of type "type"?
224 static void clear_type(struct isl_sched_edge *edge, enum isl_edge_type type)
226 ISL_FL_CLR(edge->types, 1 << type);
229 /* Is "edge" marked as a validity edge?
231 static int is_validity(struct isl_sched_edge *edge)
233 return is_type(edge, isl_edge_validity);
236 /* Mark "edge" as a validity edge.
238 static void set_validity(struct isl_sched_edge *edge)
240 set_type(edge, isl_edge_validity);
243 /* Is "edge" marked as a proximity edge?
245 static int is_proximity(struct isl_sched_edge *edge)
247 return is_type(edge, isl_edge_proximity);
250 /* Is "edge" marked as a local edge?
252 static int is_local(struct isl_sched_edge *edge)
254 return is_type(edge, isl_edge_local);
257 /* Mark "edge" as a local edge.
259 static void set_local(struct isl_sched_edge *edge)
261 set_type(edge, isl_edge_local);
264 /* No longer mark "edge" as a local edge.
266 static void clear_local(struct isl_sched_edge *edge)
268 clear_type(edge, isl_edge_local);
271 /* Is "edge" marked as a coincidence edge?
273 static int is_coincidence(struct isl_sched_edge *edge)
275 return is_type(edge, isl_edge_coincidence);
278 /* Is "edge" marked as a condition edge?
280 static int is_condition(struct isl_sched_edge *edge)
282 return is_type(edge, isl_edge_condition);
285 /* Is "edge" marked as a conditional validity edge?
287 static int is_conditional_validity(struct isl_sched_edge *edge)
289 return is_type(edge, isl_edge_conditional_validity);
292 /* Is "edge" of a type that can appear multiple times between
293 * the same pair of nodes?
295 * Condition edges and conditional validity edges may have tagged
296 * dependence relations, in which case an edge is added for each
297 * pair of tags.
299 static int is_multi_edge_type(struct isl_sched_edge *edge)
301 return is_condition(edge) || is_conditional_validity(edge);
304 /* Internal information about the dependence graph used during
305 * the construction of the schedule.
307 * intra_hmap is a cache, mapping dependence relations to their dual,
308 * for dependences from a node to itself, possibly without
309 * coefficients for the parameters
310 * intra_hmap_param is a cache, mapping dependence relations to their dual,
311 * for dependences from a node to itself, including coefficients
312 * for the parameters
313 * inter_hmap is a cache, mapping dependence relations to their dual,
314 * for dependences between distinct nodes
315 * if compression is involved then the key for these maps
316 * is the original, uncompressed dependence relation, while
317 * the value is the dual of the compressed dependence relation.
319 * n is the number of nodes
320 * node is the list of nodes
321 * maxvar is the maximal number of variables over all nodes
322 * max_row is the allocated number of rows in the schedule
323 * n_row is the current (maximal) number of linearly independent
324 * rows in the node schedules
325 * n_total_row is the current number of rows in the node schedules
326 * band_start is the starting row in the node schedules of the current band
327 * root is set to the original dependence graph from which this graph
328 * is derived through splitting. If this graph is not the result of
329 * splitting, then the root field points to the graph itself.
331 * sorted contains a list of node indices sorted according to the
332 * SCC to which a node belongs
334 * n_edge is the number of edges
335 * edge is the list of edges
336 * max_edge contains the maximal number of edges of each type;
337 * in particular, it contains the number of edges in the inital graph.
338 * edge_table contains pointers into the edge array, hashed on the source
339 * and sink spaces; there is one such table for each type;
340 * a given edge may be referenced from more than one table
341 * if the corresponding relation appears in more than one of the
342 * sets of dependences; however, for each type there is only
343 * a single edge between a given pair of source and sink space
344 * in the entire graph
346 * node_table contains pointers into the node array, hashed on the space tuples
348 * region contains a list of variable sequences that should be non-trivial
350 * lp contains the (I)LP problem used to obtain new schedule rows
352 * src_scc and dst_scc are the source and sink SCCs of an edge with
353 * conflicting constraints
355 * scc represents the number of components
356 * weak is set if the components are weakly connected
358 * max_weight is used during clustering and represents the maximal
359 * weight of the relevant proximity edges.
361 struct isl_sched_graph {
362 isl_map_to_basic_set *intra_hmap;
363 isl_map_to_basic_set *intra_hmap_param;
364 isl_map_to_basic_set *inter_hmap;
366 struct isl_sched_node *node;
367 int n;
368 int maxvar;
369 int max_row;
370 int n_row;
372 int *sorted;
374 int n_total_row;
375 int band_start;
377 struct isl_sched_graph *root;
379 struct isl_sched_edge *edge;
380 int n_edge;
381 int max_edge[isl_edge_last + 1];
382 struct isl_hash_table *edge_table[isl_edge_last + 1];
384 struct isl_hash_table *node_table;
385 struct isl_trivial_region *region;
387 isl_basic_set *lp;
389 int src_scc;
390 int dst_scc;
392 int scc;
393 int weak;
395 int max_weight;
398 /* Initialize node_table based on the list of nodes.
400 static int graph_init_table(isl_ctx *ctx, struct isl_sched_graph *graph)
402 int i;
404 graph->node_table = isl_hash_table_alloc(ctx, graph->n);
405 if (!graph->node_table)
406 return -1;
408 for (i = 0; i < graph->n; ++i) {
409 struct isl_hash_table_entry *entry;
410 uint32_t hash;
412 hash = isl_space_get_tuple_hash(graph->node[i].space);
413 entry = isl_hash_table_find(ctx, graph->node_table, hash,
414 &node_has_tuples,
415 graph->node[i].space, 1);
416 if (!entry)
417 return -1;
418 entry->data = &graph->node[i];
421 return 0;
424 /* Return a pointer to the node that lives within the given space,
425 * an invalid node if there is no such node, or NULL in case of error.
427 static struct isl_sched_node *graph_find_node(isl_ctx *ctx,
428 struct isl_sched_graph *graph, __isl_keep isl_space *space)
430 struct isl_hash_table_entry *entry;
431 uint32_t hash;
433 if (!space)
434 return NULL;
436 hash = isl_space_get_tuple_hash(space);
437 entry = isl_hash_table_find(ctx, graph->node_table, hash,
438 &node_has_tuples, space, 0);
440 return entry ? entry->data : graph->node + graph->n;
443 /* Is "node" a node in "graph"?
445 static int is_node(struct isl_sched_graph *graph,
446 struct isl_sched_node *node)
448 return node && node >= &graph->node[0] && node < &graph->node[graph->n];
451 static int edge_has_src_and_dst(const void *entry, const void *val)
453 const struct isl_sched_edge *edge = entry;
454 const struct isl_sched_edge *temp = val;
456 return edge->src == temp->src && edge->dst == temp->dst;
459 /* Add the given edge to graph->edge_table[type].
461 static isl_stat graph_edge_table_add(isl_ctx *ctx,
462 struct isl_sched_graph *graph, enum isl_edge_type type,
463 struct isl_sched_edge *edge)
465 struct isl_hash_table_entry *entry;
466 uint32_t hash;
468 hash = isl_hash_init();
469 hash = isl_hash_builtin(hash, edge->src);
470 hash = isl_hash_builtin(hash, edge->dst);
471 entry = isl_hash_table_find(ctx, graph->edge_table[type], hash,
472 &edge_has_src_and_dst, edge, 1);
473 if (!entry)
474 return isl_stat_error;
475 entry->data = edge;
477 return isl_stat_ok;
480 /* Add "edge" to all relevant edge tables.
481 * That is, for every type of the edge, add it to the corresponding table.
483 static isl_stat graph_edge_tables_add(isl_ctx *ctx,
484 struct isl_sched_graph *graph, struct isl_sched_edge *edge)
486 enum isl_edge_type t;
488 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
489 if (!is_type(edge, t))
490 continue;
491 if (graph_edge_table_add(ctx, graph, t, edge) < 0)
492 return isl_stat_error;
495 return isl_stat_ok;
498 /* Allocate the edge_tables based on the maximal number of edges of
499 * each type.
501 static int graph_init_edge_tables(isl_ctx *ctx, struct isl_sched_graph *graph)
503 int i;
505 for (i = 0; i <= isl_edge_last; ++i) {
506 graph->edge_table[i] = isl_hash_table_alloc(ctx,
507 graph->max_edge[i]);
508 if (!graph->edge_table[i])
509 return -1;
512 return 0;
515 /* If graph->edge_table[type] contains an edge from the given source
516 * to the given destination, then return the hash table entry of this edge.
517 * Otherwise, return NULL.
519 static struct isl_hash_table_entry *graph_find_edge_entry(
520 struct isl_sched_graph *graph,
521 enum isl_edge_type type,
522 struct isl_sched_node *src, struct isl_sched_node *dst)
524 isl_ctx *ctx = isl_space_get_ctx(src->space);
525 uint32_t hash;
526 struct isl_sched_edge temp = { .src = src, .dst = dst };
528 hash = isl_hash_init();
529 hash = isl_hash_builtin(hash, temp.src);
530 hash = isl_hash_builtin(hash, temp.dst);
531 return isl_hash_table_find(ctx, graph->edge_table[type], hash,
532 &edge_has_src_and_dst, &temp, 0);
536 /* If graph->edge_table[type] contains an edge from the given source
537 * to the given destination, then return this edge.
538 * Otherwise, return NULL.
540 static struct isl_sched_edge *graph_find_edge(struct isl_sched_graph *graph,
541 enum isl_edge_type type,
542 struct isl_sched_node *src, struct isl_sched_node *dst)
544 struct isl_hash_table_entry *entry;
546 entry = graph_find_edge_entry(graph, type, src, dst);
547 if (!entry)
548 return NULL;
550 return entry->data;
553 /* Check whether the dependence graph has an edge of the given type
554 * between the given two nodes.
556 static isl_bool graph_has_edge(struct isl_sched_graph *graph,
557 enum isl_edge_type type,
558 struct isl_sched_node *src, struct isl_sched_node *dst)
560 struct isl_sched_edge *edge;
561 isl_bool empty;
563 edge = graph_find_edge(graph, type, src, dst);
564 if (!edge)
565 return isl_bool_false;
567 empty = isl_map_plain_is_empty(edge->map);
569 return isl_bool_not(empty);
572 /* Look for any edge with the same src, dst and map fields as "model".
574 * Return the matching edge if one can be found.
575 * Return "model" if no matching edge is found.
576 * Return NULL on error.
578 static struct isl_sched_edge *graph_find_matching_edge(
579 struct isl_sched_graph *graph, struct isl_sched_edge *model)
581 enum isl_edge_type i;
582 struct isl_sched_edge *edge;
584 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
585 int is_equal;
587 edge = graph_find_edge(graph, i, model->src, model->dst);
588 if (!edge)
589 continue;
590 is_equal = isl_map_plain_is_equal(model->map, edge->map);
591 if (is_equal < 0)
592 return NULL;
593 if (is_equal)
594 return edge;
597 return model;
600 /* Remove the given edge from all the edge_tables that refer to it.
602 static void graph_remove_edge(struct isl_sched_graph *graph,
603 struct isl_sched_edge *edge)
605 isl_ctx *ctx = isl_map_get_ctx(edge->map);
606 enum isl_edge_type i;
608 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
609 struct isl_hash_table_entry *entry;
611 entry = graph_find_edge_entry(graph, i, edge->src, edge->dst);
612 if (!entry)
613 continue;
614 if (entry->data != edge)
615 continue;
616 isl_hash_table_remove(ctx, graph->edge_table[i], entry);
620 /* Check whether the dependence graph has any edge
621 * between the given two nodes.
623 static isl_bool graph_has_any_edge(struct isl_sched_graph *graph,
624 struct isl_sched_node *src, struct isl_sched_node *dst)
626 enum isl_edge_type i;
627 isl_bool r;
629 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
630 r = graph_has_edge(graph, i, src, dst);
631 if (r < 0 || r)
632 return r;
635 return r;
638 /* Check whether the dependence graph has a validity edge
639 * between the given two nodes.
641 * Conditional validity edges are essentially validity edges that
642 * can be ignored if the corresponding condition edges are iteration private.
643 * Here, we are only checking for the presence of validity
644 * edges, so we need to consider the conditional validity edges too.
645 * In particular, this function is used during the detection
646 * of strongly connected components and we cannot ignore
647 * conditional validity edges during this detection.
649 static isl_bool graph_has_validity_edge(struct isl_sched_graph *graph,
650 struct isl_sched_node *src, struct isl_sched_node *dst)
652 isl_bool r;
654 r = graph_has_edge(graph, isl_edge_validity, src, dst);
655 if (r < 0 || r)
656 return r;
658 return graph_has_edge(graph, isl_edge_conditional_validity, src, dst);
661 /* Perform all the required memory allocations for a schedule graph "graph"
662 * with "n_node" nodes and "n_edge" edge and initialize the corresponding
663 * fields.
665 static isl_stat graph_alloc(isl_ctx *ctx, struct isl_sched_graph *graph,
666 int n_node, int n_edge)
668 int i;
670 graph->n = n_node;
671 graph->n_edge = n_edge;
672 graph->node = isl_calloc_array(ctx, struct isl_sched_node, graph->n);
673 graph->sorted = isl_calloc_array(ctx, int, graph->n);
674 graph->region = isl_alloc_array(ctx,
675 struct isl_trivial_region, graph->n);
676 graph->edge = isl_calloc_array(ctx,
677 struct isl_sched_edge, graph->n_edge);
679 graph->intra_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
680 graph->intra_hmap_param = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
681 graph->inter_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
683 if (!graph->node || !graph->region || (graph->n_edge && !graph->edge) ||
684 !graph->sorted)
685 return isl_stat_error;
687 for(i = 0; i < graph->n; ++i)
688 graph->sorted[i] = i;
690 return isl_stat_ok;
693 /* Free the memory associated to node "node" in "graph".
694 * The "coincident" field is shared by nodes in a graph and its subgraph.
695 * It therefore only needs to be freed for the original dependence graph,
696 * i.e., one that is not the result of splitting.
698 static void clear_node(struct isl_sched_graph *graph,
699 struct isl_sched_node *node)
701 isl_space_free(node->space);
702 isl_set_free(node->hull);
703 isl_multi_aff_free(node->compress);
704 isl_multi_aff_free(node->decompress);
705 isl_mat_free(node->sched);
706 isl_map_free(node->sched_map);
707 isl_mat_free(node->indep);
708 isl_mat_free(node->vmap);
709 if (graph->root == graph)
710 free(node->coincident);
711 isl_multi_val_free(node->sizes);
712 isl_basic_set_free(node->bounds);
713 isl_vec_free(node->max);
716 static void graph_free(isl_ctx *ctx, struct isl_sched_graph *graph)
718 int i;
720 isl_map_to_basic_set_free(graph->intra_hmap);
721 isl_map_to_basic_set_free(graph->intra_hmap_param);
722 isl_map_to_basic_set_free(graph->inter_hmap);
724 if (graph->node)
725 for (i = 0; i < graph->n; ++i)
726 clear_node(graph, &graph->node[i]);
727 free(graph->node);
728 free(graph->sorted);
729 if (graph->edge)
730 for (i = 0; i < graph->n_edge; ++i) {
731 isl_map_free(graph->edge[i].map);
732 isl_union_map_free(graph->edge[i].tagged_condition);
733 isl_union_map_free(graph->edge[i].tagged_validity);
735 free(graph->edge);
736 free(graph->region);
737 for (i = 0; i <= isl_edge_last; ++i)
738 isl_hash_table_free(ctx, graph->edge_table[i]);
739 isl_hash_table_free(ctx, graph->node_table);
740 isl_basic_set_free(graph->lp);
743 /* For each "set" on which this function is called, increment
744 * graph->n by one and update graph->maxvar.
746 static isl_stat init_n_maxvar(__isl_take isl_set *set, void *user)
748 struct isl_sched_graph *graph = user;
749 int nvar = isl_set_dim(set, isl_dim_set);
751 graph->n++;
752 if (nvar > graph->maxvar)
753 graph->maxvar = nvar;
755 isl_set_free(set);
757 return isl_stat_ok;
760 /* Compute the number of rows that should be allocated for the schedule.
761 * In particular, we need one row for each variable or one row
762 * for each basic map in the dependences.
763 * Note that it is practically impossible to exhaust both
764 * the number of dependences and the number of variables.
766 static isl_stat compute_max_row(struct isl_sched_graph *graph,
767 __isl_keep isl_schedule_constraints *sc)
769 int n_edge;
770 isl_stat r;
771 isl_union_set *domain;
773 graph->n = 0;
774 graph->maxvar = 0;
775 domain = isl_schedule_constraints_get_domain(sc);
776 r = isl_union_set_foreach_set(domain, &init_n_maxvar, graph);
777 isl_union_set_free(domain);
778 if (r < 0)
779 return isl_stat_error;
780 n_edge = isl_schedule_constraints_n_basic_map(sc);
781 if (n_edge < 0)
782 return isl_stat_error;
783 graph->max_row = n_edge + graph->maxvar;
785 return isl_stat_ok;
788 /* Does "bset" have any defining equalities for its set variables?
790 static isl_bool has_any_defining_equality(__isl_keep isl_basic_set *bset)
792 int i, n;
794 if (!bset)
795 return isl_bool_error;
797 n = isl_basic_set_dim(bset, isl_dim_set);
798 for (i = 0; i < n; ++i) {
799 isl_bool has;
801 has = isl_basic_set_has_defining_equality(bset, isl_dim_set, i,
802 NULL);
803 if (has < 0 || has)
804 return has;
807 return isl_bool_false;
810 /* Set the entries of node->max to the value of the schedule_max_coefficient
811 * option, if set.
813 static isl_stat set_max_coefficient(isl_ctx *ctx, struct isl_sched_node *node)
815 int max;
817 max = isl_options_get_schedule_max_coefficient(ctx);
818 if (max == -1)
819 return isl_stat_ok;
821 node->max = isl_vec_alloc(ctx, node->nvar);
822 node->max = isl_vec_set_si(node->max, max);
823 if (!node->max)
824 return isl_stat_error;
826 return isl_stat_ok;
829 /* Set the entries of node->max to the minimum of the schedule_max_coefficient
830 * option (if set) and half of the minimum of the sizes in the other
831 * dimensions. Round up when computing the half such that
832 * if the minimum of the sizes is one, half of the size is taken to be one
833 * rather than zero.
834 * If the global minimum is unbounded (i.e., if both
835 * the schedule_max_coefficient is not set and the sizes in the other
836 * dimensions are unbounded), then store a negative value.
837 * If the schedule coefficient is close to the size of the instance set
838 * in another dimension, then the schedule may represent a loop
839 * coalescing transformation (especially if the coefficient
840 * in that other dimension is one). Forcing the coefficient to be
841 * smaller than or equal to half the minimal size should avoid this
842 * situation.
844 static isl_stat compute_max_coefficient(isl_ctx *ctx,
845 struct isl_sched_node *node)
847 int max;
848 int i, j;
849 isl_vec *v;
851 max = isl_options_get_schedule_max_coefficient(ctx);
852 v = isl_vec_alloc(ctx, node->nvar);
853 if (!v)
854 return isl_stat_error;
856 for (i = 0; i < node->nvar; ++i) {
857 isl_int_set_si(v->el[i], max);
858 isl_int_mul_si(v->el[i], v->el[i], 2);
861 for (i = 0; i < node->nvar; ++i) {
862 isl_val *size;
864 size = isl_multi_val_get_val(node->sizes, i);
865 if (!size)
866 goto error;
867 if (!isl_val_is_int(size)) {
868 isl_val_free(size);
869 continue;
871 for (j = 0; j < node->nvar; ++j) {
872 if (j == i)
873 continue;
874 if (isl_int_is_neg(v->el[j]) ||
875 isl_int_gt(v->el[j], size->n))
876 isl_int_set(v->el[j], size->n);
878 isl_val_free(size);
881 for (i = 0; i < node->nvar; ++i)
882 isl_int_cdiv_q_ui(v->el[i], v->el[i], 2);
884 node->max = v;
885 return isl_stat_ok;
886 error:
887 isl_vec_free(v);
888 return isl_stat_error;
891 /* Compute and return the size of "set" in dimension "dim".
892 * The size is taken to be the difference in values for that variable
893 * for fixed values of the other variables.
894 * This assumes that "set" is convex.
895 * In particular, the variable is first isolated from the other variables
896 * in the range of a map
898 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [i_dim]
900 * and then duplicated
902 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [[i_dim] -> [i_dim']]
904 * The shared variables are then projected out and the maximal value
905 * of i_dim' - i_dim is computed.
907 static __isl_give isl_val *compute_size(__isl_take isl_set *set, int dim)
909 isl_map *map;
910 isl_local_space *ls;
911 isl_aff *obj;
912 isl_val *v;
914 map = isl_set_project_onto_map(set, isl_dim_set, dim, 1);
915 map = isl_map_project_out(map, isl_dim_in, dim, 1);
916 map = isl_map_range_product(map, isl_map_copy(map));
917 map = isl_set_unwrap(isl_map_range(map));
918 set = isl_map_deltas(map);
919 ls = isl_local_space_from_space(isl_set_get_space(set));
920 obj = isl_aff_var_on_domain(ls, isl_dim_set, 0);
921 v = isl_set_max_val(set, obj);
922 isl_aff_free(obj);
923 isl_set_free(set);
925 return v;
928 /* Compute the size of the instance set "set" of "node", after compression,
929 * as well as bounds on the corresponding coefficients, if needed.
931 * The sizes are needed when the schedule_treat_coalescing option is set.
932 * The bounds are needed when the schedule_treat_coalescing option or
933 * the schedule_max_coefficient option is set.
935 * If the schedule_treat_coalescing option is not set, then at most
936 * the bounds need to be set and this is done in set_max_coefficient.
937 * Otherwise, compress the domain if needed, compute the size
938 * in each direction and store the results in node->size.
939 * If the domain is not convex, then the sizes are computed
940 * on a convex superset in order to avoid picking up sizes
941 * that are valid for the individual disjuncts, but not for
942 * the domain as a whole.
943 * Finally, set the bounds on the coefficients based on the sizes
944 * and the schedule_max_coefficient option in compute_max_coefficient.
946 static isl_stat compute_sizes_and_max(isl_ctx *ctx, struct isl_sched_node *node,
947 __isl_take isl_set *set)
949 int j, n;
950 isl_multi_val *mv;
952 if (!isl_options_get_schedule_treat_coalescing(ctx)) {
953 isl_set_free(set);
954 return set_max_coefficient(ctx, node);
957 if (node->compressed)
958 set = isl_set_preimage_multi_aff(set,
959 isl_multi_aff_copy(node->decompress));
960 set = isl_set_from_basic_set(isl_set_simple_hull(set));
961 mv = isl_multi_val_zero(isl_set_get_space(set));
962 n = isl_set_dim(set, isl_dim_set);
963 for (j = 0; j < n; ++j) {
964 isl_val *v;
966 v = compute_size(isl_set_copy(set), j);
967 mv = isl_multi_val_set_val(mv, j, v);
969 node->sizes = mv;
970 isl_set_free(set);
971 if (!node->sizes)
972 return isl_stat_error;
973 return compute_max_coefficient(ctx, node);
976 /* Add a new node to the graph representing the given instance set.
977 * "nvar" is the (possibly compressed) number of variables and
978 * may be smaller than then number of set variables in "set"
979 * if "compressed" is set.
980 * If "compressed" is set, then "hull" represents the constraints
981 * that were used to derive the compression, while "compress" and
982 * "decompress" map the original space to the compressed space and
983 * vice versa.
984 * If "compressed" is not set, then "hull", "compress" and "decompress"
985 * should be NULL.
987 * Compute the size of the instance set and bounds on the coefficients,
988 * if needed.
990 static isl_stat add_node(struct isl_sched_graph *graph,
991 __isl_take isl_set *set, int nvar, int compressed,
992 __isl_take isl_set *hull, __isl_take isl_multi_aff *compress,
993 __isl_take isl_multi_aff *decompress)
995 int nparam;
996 isl_ctx *ctx;
997 isl_mat *sched;
998 isl_space *space;
999 int *coincident;
1000 struct isl_sched_node *node;
1002 if (!set)
1003 goto error;
1005 ctx = isl_set_get_ctx(set);
1006 nparam = isl_set_dim(set, isl_dim_param);
1007 if (!ctx->opt->schedule_parametric)
1008 nparam = 0;
1009 sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
1010 node = &graph->node[graph->n];
1011 graph->n++;
1012 space = isl_set_get_space(set);
1013 node->space = space;
1014 node->nvar = nvar;
1015 node->nparam = nparam;
1016 node->sched = sched;
1017 node->sched_map = NULL;
1018 coincident = isl_calloc_array(ctx, int, graph->max_row);
1019 node->coincident = coincident;
1020 node->compressed = compressed;
1021 node->hull = hull;
1022 node->compress = compress;
1023 node->decompress = decompress;
1024 if (compute_sizes_and_max(ctx, node, set) < 0)
1025 return isl_stat_error;
1027 if (!space || !sched || (graph->max_row && !coincident))
1028 return isl_stat_error;
1029 if (compressed && (!hull || !compress || !decompress))
1030 return isl_stat_error;
1032 return isl_stat_ok;
1033 error:
1034 isl_set_free(set);
1035 isl_set_free(hull);
1036 isl_multi_aff_free(compress);
1037 isl_multi_aff_free(decompress);
1038 return isl_stat_error;
1041 /* Construct an identifier for node "node", which will represent "set".
1042 * The name of the identifier is either "compressed" or
1043 * "compressed_<name>", with <name> the name of the space of "set".
1044 * The user pointer of the identifier points to "node".
1046 static __isl_give isl_id *construct_compressed_id(__isl_keep isl_set *set,
1047 struct isl_sched_node *node)
1049 isl_bool has_name;
1050 isl_ctx *ctx;
1051 isl_id *id;
1052 isl_printer *p;
1053 const char *name;
1054 char *id_name;
1056 has_name = isl_set_has_tuple_name(set);
1057 if (has_name < 0)
1058 return NULL;
1060 ctx = isl_set_get_ctx(set);
1061 if (!has_name)
1062 return isl_id_alloc(ctx, "compressed", node);
1064 p = isl_printer_to_str(ctx);
1065 name = isl_set_get_tuple_name(set);
1066 p = isl_printer_print_str(p, "compressed_");
1067 p = isl_printer_print_str(p, name);
1068 id_name = isl_printer_get_str(p);
1069 isl_printer_free(p);
1071 id = isl_id_alloc(ctx, id_name, node);
1072 free(id_name);
1074 return id;
1077 /* Add a new node to the graph representing the given set.
1079 * If any of the set variables is defined by an equality, then
1080 * we perform variable compression such that we can perform
1081 * the scheduling on the compressed domain.
1082 * In this case, an identifier is used that references the new node
1083 * such that each compressed space is unique and
1084 * such that the node can be recovered from the compressed space.
1086 static isl_stat extract_node(__isl_take isl_set *set, void *user)
1088 int nvar;
1089 isl_bool has_equality;
1090 isl_id *id;
1091 isl_basic_set *hull;
1092 isl_set *hull_set;
1093 isl_morph *morph;
1094 isl_multi_aff *compress, *decompress;
1095 struct isl_sched_graph *graph = user;
1097 hull = isl_set_affine_hull(isl_set_copy(set));
1098 hull = isl_basic_set_remove_divs(hull);
1099 nvar = isl_set_dim(set, isl_dim_set);
1100 has_equality = has_any_defining_equality(hull);
1102 if (has_equality < 0)
1103 goto error;
1104 if (!has_equality) {
1105 isl_basic_set_free(hull);
1106 return add_node(graph, set, nvar, 0, NULL, NULL, NULL);
1109 id = construct_compressed_id(set, &graph->node[graph->n]);
1110 morph = isl_basic_set_variable_compression_with_id(hull,
1111 isl_dim_set, id);
1112 isl_id_free(id);
1113 nvar = isl_morph_ran_dim(morph, isl_dim_set);
1114 compress = isl_morph_get_var_multi_aff(morph);
1115 morph = isl_morph_inverse(morph);
1116 decompress = isl_morph_get_var_multi_aff(morph);
1117 isl_morph_free(morph);
1119 hull_set = isl_set_from_basic_set(hull);
1120 return add_node(graph, set, nvar, 1, hull_set, compress, decompress);
1121 error:
1122 isl_basic_set_free(hull);
1123 isl_set_free(set);
1124 return isl_stat_error;
1127 struct isl_extract_edge_data {
1128 enum isl_edge_type type;
1129 struct isl_sched_graph *graph;
1132 /* Merge edge2 into edge1, freeing the contents of edge2.
1133 * Return 0 on success and -1 on failure.
1135 * edge1 and edge2 are assumed to have the same value for the map field.
1137 static int merge_edge(struct isl_sched_edge *edge1,
1138 struct isl_sched_edge *edge2)
1140 edge1->types |= edge2->types;
1141 isl_map_free(edge2->map);
1143 if (is_condition(edge2)) {
1144 if (!edge1->tagged_condition)
1145 edge1->tagged_condition = edge2->tagged_condition;
1146 else
1147 edge1->tagged_condition =
1148 isl_union_map_union(edge1->tagged_condition,
1149 edge2->tagged_condition);
1152 if (is_conditional_validity(edge2)) {
1153 if (!edge1->tagged_validity)
1154 edge1->tagged_validity = edge2->tagged_validity;
1155 else
1156 edge1->tagged_validity =
1157 isl_union_map_union(edge1->tagged_validity,
1158 edge2->tagged_validity);
1161 if (is_condition(edge2) && !edge1->tagged_condition)
1162 return -1;
1163 if (is_conditional_validity(edge2) && !edge1->tagged_validity)
1164 return -1;
1166 return 0;
1169 /* Insert dummy tags in domain and range of "map".
1171 * In particular, if "map" is of the form
1173 * A -> B
1175 * then return
1177 * [A -> dummy_tag] -> [B -> dummy_tag]
1179 * where the dummy_tags are identical and equal to any dummy tags
1180 * introduced by any other call to this function.
1182 static __isl_give isl_map *insert_dummy_tags(__isl_take isl_map *map)
1184 static char dummy;
1185 isl_ctx *ctx;
1186 isl_id *id;
1187 isl_space *space;
1188 isl_set *domain, *range;
1190 ctx = isl_map_get_ctx(map);
1192 id = isl_id_alloc(ctx, NULL, &dummy);
1193 space = isl_space_params(isl_map_get_space(map));
1194 space = isl_space_set_from_params(space);
1195 space = isl_space_set_tuple_id(space, isl_dim_set, id);
1196 space = isl_space_map_from_set(space);
1198 domain = isl_map_wrap(map);
1199 range = isl_map_wrap(isl_map_universe(space));
1200 map = isl_map_from_domain_and_range(domain, range);
1201 map = isl_map_zip(map);
1203 return map;
1206 /* Given that at least one of "src" or "dst" is compressed, return
1207 * a map between the spaces of these nodes restricted to the affine
1208 * hull that was used in the compression.
1210 static __isl_give isl_map *extract_hull(struct isl_sched_node *src,
1211 struct isl_sched_node *dst)
1213 isl_set *dom, *ran;
1215 if (src->compressed)
1216 dom = isl_set_copy(src->hull);
1217 else
1218 dom = isl_set_universe(isl_space_copy(src->space));
1219 if (dst->compressed)
1220 ran = isl_set_copy(dst->hull);
1221 else
1222 ran = isl_set_universe(isl_space_copy(dst->space));
1224 return isl_map_from_domain_and_range(dom, ran);
1227 /* Intersect the domains of the nested relations in domain and range
1228 * of "tagged" with "map".
1230 static __isl_give isl_map *map_intersect_domains(__isl_take isl_map *tagged,
1231 __isl_keep isl_map *map)
1233 isl_set *set;
1235 tagged = isl_map_zip(tagged);
1236 set = isl_map_wrap(isl_map_copy(map));
1237 tagged = isl_map_intersect_domain(tagged, set);
1238 tagged = isl_map_zip(tagged);
1239 return tagged;
1242 /* Return a pointer to the node that lives in the domain space of "map",
1243 * an invalid node if there is no such node, or NULL in case of error.
1245 static struct isl_sched_node *find_domain_node(isl_ctx *ctx,
1246 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1248 struct isl_sched_node *node;
1249 isl_space *space;
1251 space = isl_space_domain(isl_map_get_space(map));
1252 node = graph_find_node(ctx, graph, space);
1253 isl_space_free(space);
1255 return node;
1258 /* Return a pointer to the node that lives in the range space of "map",
1259 * an invalid node if there is no such node, or NULL in case of error.
1261 static struct isl_sched_node *find_range_node(isl_ctx *ctx,
1262 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1264 struct isl_sched_node *node;
1265 isl_space *space;
1267 space = isl_space_range(isl_map_get_space(map));
1268 node = graph_find_node(ctx, graph, space);
1269 isl_space_free(space);
1271 return node;
1274 /* Refrain from adding a new edge based on "map".
1275 * Instead, just free the map.
1276 * "tagged" is either a copy of "map" with additional tags or NULL.
1278 static isl_stat skip_edge(__isl_take isl_map *map, __isl_take isl_map *tagged)
1280 isl_map_free(map);
1281 isl_map_free(tagged);
1283 return isl_stat_ok;
1286 /* Add a new edge to the graph based on the given map
1287 * and add it to data->graph->edge_table[data->type].
1288 * If a dependence relation of a given type happens to be identical
1289 * to one of the dependence relations of a type that was added before,
1290 * then we don't create a new edge, but instead mark the original edge
1291 * as also representing a dependence of the current type.
1293 * Edges of type isl_edge_condition or isl_edge_conditional_validity
1294 * may be specified as "tagged" dependence relations. That is, "map"
1295 * may contain elements (i -> a) -> (j -> b), where i -> j denotes
1296 * the dependence on iterations and a and b are tags.
1297 * edge->map is set to the relation containing the elements i -> j,
1298 * while edge->tagged_condition and edge->tagged_validity contain
1299 * the union of all the "map" relations
1300 * for which extract_edge is called that result in the same edge->map.
1302 * If the source or the destination node is compressed, then
1303 * intersect both "map" and "tagged" with the constraints that
1304 * were used to construct the compression.
1305 * This ensures that there are no schedule constraints defined
1306 * outside of these domains, while the scheduler no longer has
1307 * any control over those outside parts.
1309 static isl_stat extract_edge(__isl_take isl_map *map, void *user)
1311 isl_bool empty;
1312 isl_ctx *ctx = isl_map_get_ctx(map);
1313 struct isl_extract_edge_data *data = user;
1314 struct isl_sched_graph *graph = data->graph;
1315 struct isl_sched_node *src, *dst;
1316 struct isl_sched_edge *edge;
1317 isl_map *tagged = NULL;
1319 if (data->type == isl_edge_condition ||
1320 data->type == isl_edge_conditional_validity) {
1321 if (isl_map_can_zip(map)) {
1322 tagged = isl_map_copy(map);
1323 map = isl_set_unwrap(isl_map_domain(isl_map_zip(map)));
1324 } else {
1325 tagged = insert_dummy_tags(isl_map_copy(map));
1329 src = find_domain_node(ctx, graph, map);
1330 dst = find_range_node(ctx, graph, map);
1332 if (!src || !dst)
1333 goto error;
1334 if (!is_node(graph, src) || !is_node(graph, dst))
1335 return skip_edge(map, tagged);
1337 if (src->compressed || dst->compressed) {
1338 isl_map *hull;
1339 hull = extract_hull(src, dst);
1340 if (tagged)
1341 tagged = map_intersect_domains(tagged, hull);
1342 map = isl_map_intersect(map, hull);
1345 empty = isl_map_plain_is_empty(map);
1346 if (empty < 0)
1347 goto error;
1348 if (empty)
1349 return skip_edge(map, tagged);
1351 graph->edge[graph->n_edge].src = src;
1352 graph->edge[graph->n_edge].dst = dst;
1353 graph->edge[graph->n_edge].map = map;
1354 graph->edge[graph->n_edge].types = 0;
1355 graph->edge[graph->n_edge].tagged_condition = NULL;
1356 graph->edge[graph->n_edge].tagged_validity = NULL;
1357 set_type(&graph->edge[graph->n_edge], data->type);
1358 if (data->type == isl_edge_condition)
1359 graph->edge[graph->n_edge].tagged_condition =
1360 isl_union_map_from_map(tagged);
1361 if (data->type == isl_edge_conditional_validity)
1362 graph->edge[graph->n_edge].tagged_validity =
1363 isl_union_map_from_map(tagged);
1365 edge = graph_find_matching_edge(graph, &graph->edge[graph->n_edge]);
1366 if (!edge) {
1367 graph->n_edge++;
1368 return isl_stat_error;
1370 if (edge == &graph->edge[graph->n_edge])
1371 return graph_edge_table_add(ctx, graph, data->type,
1372 &graph->edge[graph->n_edge++]);
1374 if (merge_edge(edge, &graph->edge[graph->n_edge]) < 0)
1375 return isl_stat_error;
1377 return graph_edge_table_add(ctx, graph, data->type, edge);
1378 error:
1379 isl_map_free(map);
1380 isl_map_free(tagged);
1381 return isl_stat_error;
1384 /* Initialize the schedule graph "graph" from the schedule constraints "sc".
1386 * The context is included in the domain before the nodes of
1387 * the graphs are extracted in order to be able to exploit
1388 * any possible additional equalities.
1389 * Note that this intersection is only performed locally here.
1391 static isl_stat graph_init(struct isl_sched_graph *graph,
1392 __isl_keep isl_schedule_constraints *sc)
1394 isl_ctx *ctx;
1395 isl_union_set *domain;
1396 isl_union_map *c;
1397 struct isl_extract_edge_data data;
1398 enum isl_edge_type i;
1399 isl_stat r;
1401 if (!sc)
1402 return isl_stat_error;
1404 ctx = isl_schedule_constraints_get_ctx(sc);
1406 domain = isl_schedule_constraints_get_domain(sc);
1407 graph->n = isl_union_set_n_set(domain);
1408 isl_union_set_free(domain);
1410 if (graph_alloc(ctx, graph, graph->n,
1411 isl_schedule_constraints_n_map(sc)) < 0)
1412 return isl_stat_error;
1414 if (compute_max_row(graph, sc) < 0)
1415 return isl_stat_error;
1416 graph->root = graph;
1417 graph->n = 0;
1418 domain = isl_schedule_constraints_get_domain(sc);
1419 domain = isl_union_set_intersect_params(domain,
1420 isl_schedule_constraints_get_context(sc));
1421 r = isl_union_set_foreach_set(domain, &extract_node, graph);
1422 isl_union_set_free(domain);
1423 if (r < 0)
1424 return isl_stat_error;
1425 if (graph_init_table(ctx, graph) < 0)
1426 return isl_stat_error;
1427 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1428 c = isl_schedule_constraints_get(sc, i);
1429 graph->max_edge[i] = isl_union_map_n_map(c);
1430 isl_union_map_free(c);
1431 if (!c)
1432 return isl_stat_error;
1434 if (graph_init_edge_tables(ctx, graph) < 0)
1435 return isl_stat_error;
1436 graph->n_edge = 0;
1437 data.graph = graph;
1438 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1439 isl_stat r;
1441 data.type = i;
1442 c = isl_schedule_constraints_get(sc, i);
1443 r = isl_union_map_foreach_map(c, &extract_edge, &data);
1444 isl_union_map_free(c);
1445 if (r < 0)
1446 return isl_stat_error;
1449 return isl_stat_ok;
1452 /* Check whether there is any dependence from node[j] to node[i]
1453 * or from node[i] to node[j].
1455 static isl_bool node_follows_weak(int i, int j, void *user)
1457 isl_bool f;
1458 struct isl_sched_graph *graph = user;
1460 f = graph_has_any_edge(graph, &graph->node[j], &graph->node[i]);
1461 if (f < 0 || f)
1462 return f;
1463 return graph_has_any_edge(graph, &graph->node[i], &graph->node[j]);
1466 /* Check whether there is a (conditional) validity dependence from node[j]
1467 * to node[i], forcing node[i] to follow node[j].
1469 static isl_bool node_follows_strong(int i, int j, void *user)
1471 struct isl_sched_graph *graph = user;
1473 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
1476 /* Use Tarjan's algorithm for computing the strongly connected components
1477 * in the dependence graph only considering those edges defined by "follows".
1479 static isl_stat detect_ccs(isl_ctx *ctx, struct isl_sched_graph *graph,
1480 isl_bool (*follows)(int i, int j, void *user))
1482 int i, n;
1483 struct isl_tarjan_graph *g = NULL;
1485 g = isl_tarjan_graph_init(ctx, graph->n, follows, graph);
1486 if (!g)
1487 return isl_stat_error;
1489 graph->scc = 0;
1490 i = 0;
1491 n = graph->n;
1492 while (n) {
1493 while (g->order[i] != -1) {
1494 graph->node[g->order[i]].scc = graph->scc;
1495 --n;
1496 ++i;
1498 ++i;
1499 graph->scc++;
1502 isl_tarjan_graph_free(g);
1504 return isl_stat_ok;
1507 /* Apply Tarjan's algorithm to detect the strongly connected components
1508 * in the dependence graph.
1509 * Only consider the (conditional) validity dependences and clear "weak".
1511 static isl_stat detect_sccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1513 graph->weak = 0;
1514 return detect_ccs(ctx, graph, &node_follows_strong);
1517 /* Apply Tarjan's algorithm to detect the (weakly) connected components
1518 * in the dependence graph.
1519 * Consider all dependences and set "weak".
1521 static isl_stat detect_wccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1523 graph->weak = 1;
1524 return detect_ccs(ctx, graph, &node_follows_weak);
1527 static int cmp_scc(const void *a, const void *b, void *data)
1529 struct isl_sched_graph *graph = data;
1530 const int *i1 = a;
1531 const int *i2 = b;
1533 return graph->node[*i1].scc - graph->node[*i2].scc;
1536 /* Sort the elements of graph->sorted according to the corresponding SCCs.
1538 static int sort_sccs(struct isl_sched_graph *graph)
1540 return isl_sort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
1543 /* Return a non-parametric set in the compressed space of "node" that is
1544 * bounded by the size in each direction
1546 * { [x] : -S_i <= x_i <= S_i }
1548 * If S_i is infinity in direction i, then there are no constraints
1549 * in that direction.
1551 * Cache the result in node->bounds.
1553 static __isl_give isl_basic_set *get_size_bounds(struct isl_sched_node *node)
1555 isl_space *space;
1556 isl_basic_set *bounds;
1557 int i;
1559 if (node->bounds)
1560 return isl_basic_set_copy(node->bounds);
1562 if (node->compressed)
1563 space = isl_multi_aff_get_domain_space(node->decompress);
1564 else
1565 space = isl_space_copy(node->space);
1566 space = isl_space_drop_all_params(space);
1567 bounds = isl_basic_set_universe(space);
1569 for (i = 0; i < node->nvar; ++i) {
1570 isl_val *size;
1572 size = isl_multi_val_get_val(node->sizes, i);
1573 if (!size)
1574 return isl_basic_set_free(bounds);
1575 if (!isl_val_is_int(size)) {
1576 isl_val_free(size);
1577 continue;
1579 bounds = isl_basic_set_upper_bound_val(bounds, isl_dim_set, i,
1580 isl_val_copy(size));
1581 bounds = isl_basic_set_lower_bound_val(bounds, isl_dim_set, i,
1582 isl_val_neg(size));
1585 node->bounds = isl_basic_set_copy(bounds);
1586 return bounds;
1589 /* Drop some constraints from "delta" that could be exploited
1590 * to construct loop coalescing schedules.
1591 * In particular, drop those constraint that bound the difference
1592 * to the size of the domain.
1593 * First project out the parameters to improve the effectiveness.
1595 static __isl_give isl_set *drop_coalescing_constraints(
1596 __isl_take isl_set *delta, struct isl_sched_node *node)
1598 unsigned nparam;
1599 isl_basic_set *bounds;
1601 bounds = get_size_bounds(node);
1603 nparam = isl_set_dim(delta, isl_dim_param);
1604 delta = isl_set_project_out(delta, isl_dim_param, 0, nparam);
1605 delta = isl_set_remove_divs(delta);
1606 delta = isl_set_plain_gist_basic_set(delta, bounds);
1607 return delta;
1610 /* Given a dependence relation R from "node" to itself,
1611 * construct the set of coefficients of valid constraints for elements
1612 * in that dependence relation.
1613 * In particular, the result contains tuples of coefficients
1614 * c_0, c_n, c_x such that
1616 * c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
1618 * or, equivalently,
1620 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
1622 * We choose here to compute the dual of delta R.
1623 * Alternatively, we could have computed the dual of R, resulting
1624 * in a set of tuples c_0, c_n, c_x, c_y, and then
1625 * plugged in (c_0, c_n, c_x, -c_x).
1627 * If "need_param" is set, then the resulting coefficients effectively
1628 * include coefficients for the parameters c_n. Otherwise, they may
1629 * have been projected out already.
1630 * Since the constraints may be different for these two cases,
1631 * they are stored in separate caches.
1632 * In particular, if no parameter coefficients are required and
1633 * the schedule_treat_coalescing option is set, then the parameters
1634 * are projected out and some constraints that could be exploited
1635 * to construct coalescing schedules are removed before the dual
1636 * is computed.
1638 * If "node" has been compressed, then the dependence relation
1639 * is also compressed before the set of coefficients is computed.
1641 static __isl_give isl_basic_set *intra_coefficients(
1642 struct isl_sched_graph *graph, struct isl_sched_node *node,
1643 __isl_take isl_map *map, int need_param)
1645 isl_ctx *ctx;
1646 isl_set *delta;
1647 isl_map *key;
1648 isl_basic_set *coef;
1649 isl_maybe_isl_basic_set m;
1650 isl_map_to_basic_set **hmap = &graph->intra_hmap;
1651 int treat;
1653 if (!map)
1654 return NULL;
1656 ctx = isl_map_get_ctx(map);
1657 treat = !need_param && isl_options_get_schedule_treat_coalescing(ctx);
1658 if (!treat)
1659 hmap = &graph->intra_hmap_param;
1660 m = isl_map_to_basic_set_try_get(*hmap, map);
1661 if (m.valid < 0 || m.valid) {
1662 isl_map_free(map);
1663 return m.value;
1666 key = isl_map_copy(map);
1667 if (node->compressed) {
1668 map = isl_map_preimage_domain_multi_aff(map,
1669 isl_multi_aff_copy(node->decompress));
1670 map = isl_map_preimage_range_multi_aff(map,
1671 isl_multi_aff_copy(node->decompress));
1673 delta = isl_map_deltas(map);
1674 if (treat)
1675 delta = drop_coalescing_constraints(delta, node);
1676 delta = isl_set_remove_divs(delta);
1677 coef = isl_set_coefficients(delta);
1678 *hmap = isl_map_to_basic_set_set(*hmap, key, isl_basic_set_copy(coef));
1680 return coef;
1683 /* Given a dependence relation R, construct the set of coefficients
1684 * of valid constraints for elements in that dependence relation.
1685 * In particular, the result contains tuples of coefficients
1686 * c_0, c_n, c_x, c_y such that
1688 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
1690 * If the source or destination nodes of "edge" have been compressed,
1691 * then the dependence relation is also compressed before
1692 * the set of coefficients is computed.
1694 static __isl_give isl_basic_set *inter_coefficients(
1695 struct isl_sched_graph *graph, struct isl_sched_edge *edge,
1696 __isl_take isl_map *map)
1698 isl_set *set;
1699 isl_map *key;
1700 isl_basic_set *coef;
1701 isl_maybe_isl_basic_set m;
1703 m = isl_map_to_basic_set_try_get(graph->inter_hmap, map);
1704 if (m.valid < 0 || m.valid) {
1705 isl_map_free(map);
1706 return m.value;
1709 key = isl_map_copy(map);
1710 if (edge->src->compressed)
1711 map = isl_map_preimage_domain_multi_aff(map,
1712 isl_multi_aff_copy(edge->src->decompress));
1713 if (edge->dst->compressed)
1714 map = isl_map_preimage_range_multi_aff(map,
1715 isl_multi_aff_copy(edge->dst->decompress));
1716 set = isl_map_wrap(isl_map_remove_divs(map));
1717 coef = isl_set_coefficients(set);
1718 graph->inter_hmap = isl_map_to_basic_set_set(graph->inter_hmap, key,
1719 isl_basic_set_copy(coef));
1721 return coef;
1724 /* Return the position of the coefficients of the variables in
1725 * the coefficients constraints "coef".
1727 * The space of "coef" is of the form
1729 * { coefficients[[cst, params] -> S] }
1731 * Return the position of S.
1733 static int coef_var_offset(__isl_keep isl_basic_set *coef)
1735 int offset;
1736 isl_space *space;
1738 space = isl_space_unwrap(isl_basic_set_get_space(coef));
1739 offset = isl_space_dim(space, isl_dim_in);
1740 isl_space_free(space);
1742 return offset;
1745 /* Return the offset of the coefficient of the constant term of "node"
1746 * within the (I)LP.
1748 * Within each node, the coefficients have the following order:
1749 * - positive and negative parts of c_i_x
1750 * - c_i_n (if parametric)
1751 * - c_i_0
1753 static int node_cst_coef_offset(struct isl_sched_node *node)
1755 return node->start + 2 * node->nvar + node->nparam;
1758 /* Return the offset of the coefficients of the parameters of "node"
1759 * within the (I)LP.
1761 * Within each node, the coefficients have the following order:
1762 * - positive and negative parts of c_i_x
1763 * - c_i_n (if parametric)
1764 * - c_i_0
1766 static int node_par_coef_offset(struct isl_sched_node *node)
1768 return node->start + 2 * node->nvar;
1771 /* Return the offset of the coefficients of the variables of "node"
1772 * within the (I)LP.
1774 * Within each node, the coefficients have the following order:
1775 * - positive and negative parts of c_i_x
1776 * - c_i_n (if parametric)
1777 * - c_i_0
1779 static int node_var_coef_offset(struct isl_sched_node *node)
1781 return node->start;
1784 /* Return the position of the pair of variables encoding
1785 * coefficient "i" of "node".
1787 * The order of these variable pairs is the opposite of
1788 * that of the coefficients, with 2 variables per coefficient.
1790 static int node_var_coef_pos(struct isl_sched_node *node, int i)
1792 return node_var_coef_offset(node) + 2 * (node->nvar - 1 - i);
1795 /* Construct an isl_dim_map for mapping constraints on coefficients
1796 * for "node" to the corresponding positions in graph->lp.
1797 * "offset" is the offset of the coefficients for the variables
1798 * in the input constraints.
1799 * "s" is the sign of the mapping.
1801 * The input constraints are given in terms of the coefficients
1802 * (c_0, c_x) or (c_0, c_n, c_x).
1803 * The mapping produced by this function essentially plugs in
1804 * (0, c_i_x^+ - c_i_x^-) if s = 1 and
1805 * (0, -c_i_x^+ + c_i_x^-) if s = -1 or
1806 * (0, 0, c_i_x^+ - c_i_x^-) if s = 1 and
1807 * (0, 0, -c_i_x^+ + c_i_x^-) if s = -1.
1808 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1809 * Furthermore, the order of these pairs is the opposite of that
1810 * of the corresponding coefficients.
1812 * The caller can extend the mapping to also map the other coefficients
1813 * (and therefore not plug in 0).
1815 static __isl_give isl_dim_map *intra_dim_map(isl_ctx *ctx,
1816 struct isl_sched_graph *graph, struct isl_sched_node *node,
1817 int offset, int s)
1819 int pos;
1820 unsigned total;
1821 isl_dim_map *dim_map;
1823 if (!node || !graph->lp)
1824 return NULL;
1826 total = isl_basic_set_total_dim(graph->lp);
1827 pos = node_var_coef_pos(node, 0);
1828 dim_map = isl_dim_map_alloc(ctx, total);
1829 isl_dim_map_range(dim_map, pos, -2, offset, 1, node->nvar, -s);
1830 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, node->nvar, s);
1832 return dim_map;
1835 /* Construct an isl_dim_map for mapping constraints on coefficients
1836 * for "src" (node i) and "dst" (node j) to the corresponding positions
1837 * in graph->lp.
1838 * "offset" is the offset of the coefficients for the variables of "src"
1839 * in the input constraints.
1840 * "s" is the sign of the mapping.
1842 * The input constraints are given in terms of the coefficients
1843 * (c_0, c_n, c_x, c_y).
1844 * The mapping produced by this function essentially plugs in
1845 * (c_j_0 - c_i_0, c_j_n - c_i_n,
1846 * -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-) if s = 1 and
1847 * (-c_j_0 + c_i_0, -c_j_n + c_i_n,
1848 * c_i_x^+ - c_i_x^-, -(c_j_x^+ - c_j_x^-)) if s = -1.
1849 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1850 * Furthermore, the order of these pairs is the opposite of that
1851 * of the corresponding coefficients.
1853 * The caller can further extend the mapping.
1855 static __isl_give isl_dim_map *inter_dim_map(isl_ctx *ctx,
1856 struct isl_sched_graph *graph, struct isl_sched_node *src,
1857 struct isl_sched_node *dst, int offset, int s)
1859 int pos;
1860 unsigned total;
1861 isl_dim_map *dim_map;
1863 if (!src || !dst || !graph->lp)
1864 return NULL;
1866 total = isl_basic_set_total_dim(graph->lp);
1867 dim_map = isl_dim_map_alloc(ctx, total);
1869 pos = node_cst_coef_offset(dst);
1870 isl_dim_map_range(dim_map, pos, 0, 0, 0, 1, s);
1871 pos = node_par_coef_offset(dst);
1872 isl_dim_map_range(dim_map, pos, 1, 1, 1, dst->nparam, s);
1873 pos = node_var_coef_pos(dst, 0);
1874 isl_dim_map_range(dim_map, pos, -2, offset + src->nvar, 1,
1875 dst->nvar, -s);
1876 isl_dim_map_range(dim_map, pos + 1, -2, offset + src->nvar, 1,
1877 dst->nvar, s);
1879 pos = node_cst_coef_offset(src);
1880 isl_dim_map_range(dim_map, pos, 0, 0, 0, 1, -s);
1881 pos = node_par_coef_offset(src);
1882 isl_dim_map_range(dim_map, pos, 1, 1, 1, src->nparam, -s);
1883 pos = node_var_coef_pos(src, 0);
1884 isl_dim_map_range(dim_map, pos, -2, offset, 1, src->nvar, s);
1885 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, src->nvar, -s);
1887 return dim_map;
1890 /* Add the constraints from "src" to "dst" using "dim_map",
1891 * after making sure there is enough room in "dst" for the extra constraints.
1893 static __isl_give isl_basic_set *add_constraints_dim_map(
1894 __isl_take isl_basic_set *dst, __isl_take isl_basic_set *src,
1895 __isl_take isl_dim_map *dim_map)
1897 int n_eq, n_ineq;
1899 n_eq = isl_basic_set_n_equality(src);
1900 n_ineq = isl_basic_set_n_inequality(src);
1901 dst = isl_basic_set_extend_constraints(dst, n_eq, n_ineq);
1902 dst = isl_basic_set_add_constraints_dim_map(dst, src, dim_map);
1903 return dst;
1906 /* Add constraints to graph->lp that force validity for the given
1907 * dependence from a node i to itself.
1908 * That is, add constraints that enforce
1910 * (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
1911 * = c_i_x (y - x) >= 0
1913 * for each (x,y) in R.
1914 * We obtain general constraints on coefficients (c_0, c_x)
1915 * of valid constraints for (y - x) and then plug in (0, c_i_x^+ - c_i_x^-),
1916 * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
1917 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1918 * Note that the result of intra_coefficients may also contain
1919 * parameter coefficients c_n, in which case 0 is plugged in for them as well.
1921 static isl_stat add_intra_validity_constraints(struct isl_sched_graph *graph,
1922 struct isl_sched_edge *edge)
1924 int offset;
1925 isl_map *map = isl_map_copy(edge->map);
1926 isl_ctx *ctx = isl_map_get_ctx(map);
1927 isl_dim_map *dim_map;
1928 isl_basic_set *coef;
1929 struct isl_sched_node *node = edge->src;
1931 coef = intra_coefficients(graph, node, map, 0);
1933 offset = coef_var_offset(coef);
1935 if (!coef)
1936 return isl_stat_error;
1938 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
1939 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1941 return isl_stat_ok;
1944 /* Add constraints to graph->lp that force validity for the given
1945 * dependence from node i to node j.
1946 * That is, add constraints that enforce
1948 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
1950 * for each (x,y) in R.
1951 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1952 * of valid constraints for R and then plug in
1953 * (c_j_0 - c_i_0, c_j_n - c_i_n, -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-),
1954 * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
1955 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1957 static isl_stat add_inter_validity_constraints(struct isl_sched_graph *graph,
1958 struct isl_sched_edge *edge)
1960 int offset;
1961 isl_map *map;
1962 isl_ctx *ctx;
1963 isl_dim_map *dim_map;
1964 isl_basic_set *coef;
1965 struct isl_sched_node *src = edge->src;
1966 struct isl_sched_node *dst = edge->dst;
1968 if (!graph->lp)
1969 return isl_stat_error;
1971 map = isl_map_copy(edge->map);
1972 ctx = isl_map_get_ctx(map);
1973 coef = inter_coefficients(graph, edge, map);
1975 offset = coef_var_offset(coef);
1977 if (!coef)
1978 return isl_stat_error;
1980 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
1982 edge->start = graph->lp->n_ineq;
1983 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1984 if (!graph->lp)
1985 return isl_stat_error;
1986 edge->end = graph->lp->n_ineq;
1988 return isl_stat_ok;
1991 /* Add constraints to graph->lp that bound the dependence distance for the given
1992 * dependence from a node i to itself.
1993 * If s = 1, we add the constraint
1995 * c_i_x (y - x) <= m_0 + m_n n
1997 * or
1999 * -c_i_x (y - x) + m_0 + m_n n >= 0
2001 * for each (x,y) in R.
2002 * If s = -1, we add the constraint
2004 * -c_i_x (y - x) <= m_0 + m_n n
2006 * or
2008 * c_i_x (y - x) + m_0 + m_n n >= 0
2010 * for each (x,y) in R.
2011 * We obtain general constraints on coefficients (c_0, c_n, c_x)
2012 * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
2013 * with each coefficient (except m_0) represented as a pair of non-negative
2014 * coefficients.
2017 * If "local" is set, then we add constraints
2019 * c_i_x (y - x) <= 0
2021 * or
2023 * -c_i_x (y - x) <= 0
2025 * instead, forcing the dependence distance to be (less than or) equal to 0.
2026 * That is, we plug in (0, 0, -s * c_i_x),
2027 * intra_coefficients is not required to have c_n in its result when
2028 * "local" is set. If they are missing, then (0, -s * c_i_x) is plugged in.
2029 * Note that dependences marked local are treated as validity constraints
2030 * by add_all_validity_constraints and therefore also have
2031 * their distances bounded by 0 from below.
2033 static isl_stat add_intra_proximity_constraints(struct isl_sched_graph *graph,
2034 struct isl_sched_edge *edge, int s, int local)
2036 int offset;
2037 unsigned nparam;
2038 isl_map *map = isl_map_copy(edge->map);
2039 isl_ctx *ctx = isl_map_get_ctx(map);
2040 isl_dim_map *dim_map;
2041 isl_basic_set *coef;
2042 struct isl_sched_node *node = edge->src;
2044 coef = intra_coefficients(graph, node, map, !local);
2046 offset = coef_var_offset(coef);
2048 if (!coef)
2049 return isl_stat_error;
2051 nparam = isl_space_dim(node->space, isl_dim_param);
2052 dim_map = intra_dim_map(ctx, graph, node, offset, -s);
2054 if (!local) {
2055 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
2056 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
2057 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
2059 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
2061 return isl_stat_ok;
2064 /* Add constraints to graph->lp that bound the dependence distance for the given
2065 * dependence from node i to node j.
2066 * If s = 1, we add the constraint
2068 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
2069 * <= m_0 + m_n n
2071 * or
2073 * -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
2074 * m_0 + m_n n >= 0
2076 * for each (x,y) in R.
2077 * If s = -1, we add the constraint
2079 * -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
2080 * <= m_0 + m_n n
2082 * or
2084 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
2085 * m_0 + m_n n >= 0
2087 * for each (x,y) in R.
2088 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
2089 * of valid constraints for R and then plug in
2090 * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
2091 * s*c_i_x, -s*c_j_x)
2092 * with each coefficient (except m_0, c_*_0 and c_*_n)
2093 * represented as a pair of non-negative coefficients.
2096 * If "local" is set (and s = 1), then we add constraints
2098 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) <= 0
2100 * or
2102 * -((c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x)) >= 0
2104 * instead, forcing the dependence distance to be (less than or) equal to 0.
2105 * That is, we plug in
2106 * (-s*c_j_0 + s*c_i_0, -s*c_j_n + s*c_i_n, s*c_i_x, -s*c_j_x).
2107 * Note that dependences marked local are treated as validity constraints
2108 * by add_all_validity_constraints and therefore also have
2109 * their distances bounded by 0 from below.
2111 static isl_stat add_inter_proximity_constraints(struct isl_sched_graph *graph,
2112 struct isl_sched_edge *edge, int s, int local)
2114 int offset;
2115 unsigned nparam;
2116 isl_map *map = isl_map_copy(edge->map);
2117 isl_ctx *ctx = isl_map_get_ctx(map);
2118 isl_dim_map *dim_map;
2119 isl_basic_set *coef;
2120 struct isl_sched_node *src = edge->src;
2121 struct isl_sched_node *dst = edge->dst;
2123 coef = inter_coefficients(graph, edge, map);
2125 offset = coef_var_offset(coef);
2127 if (!coef)
2128 return isl_stat_error;
2130 nparam = isl_space_dim(src->space, isl_dim_param);
2131 dim_map = inter_dim_map(ctx, graph, src, dst, offset, -s);
2133 if (!local) {
2134 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
2135 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
2136 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
2139 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
2141 return isl_stat_ok;
2144 /* Should the distance over "edge" be forced to zero?
2145 * That is, is it marked as a local edge?
2146 * If "use_coincidence" is set, then coincidence edges are treated
2147 * as local edges.
2149 static int force_zero(struct isl_sched_edge *edge, int use_coincidence)
2151 return is_local(edge) || (use_coincidence && is_coincidence(edge));
2154 /* Add all validity constraints to graph->lp.
2156 * An edge that is forced to be local needs to have its dependence
2157 * distances equal to zero. We take care of bounding them by 0 from below
2158 * here. add_all_proximity_constraints takes care of bounding them by 0
2159 * from above.
2161 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2162 * Otherwise, we ignore them.
2164 static int add_all_validity_constraints(struct isl_sched_graph *graph,
2165 int use_coincidence)
2167 int i;
2169 for (i = 0; i < graph->n_edge; ++i) {
2170 struct isl_sched_edge *edge = &graph->edge[i];
2171 int zero;
2173 zero = force_zero(edge, use_coincidence);
2174 if (!is_validity(edge) && !zero)
2175 continue;
2176 if (edge->src != edge->dst)
2177 continue;
2178 if (add_intra_validity_constraints(graph, edge) < 0)
2179 return -1;
2182 for (i = 0; i < graph->n_edge; ++i) {
2183 struct isl_sched_edge *edge = &graph->edge[i];
2184 int zero;
2186 zero = force_zero(edge, use_coincidence);
2187 if (!is_validity(edge) && !zero)
2188 continue;
2189 if (edge->src == edge->dst)
2190 continue;
2191 if (add_inter_validity_constraints(graph, edge) < 0)
2192 return -1;
2195 return 0;
2198 /* Add constraints to graph->lp that bound the dependence distance
2199 * for all dependence relations.
2200 * If a given proximity dependence is identical to a validity
2201 * dependence, then the dependence distance is already bounded
2202 * from below (by zero), so we only need to bound the distance
2203 * from above. (This includes the case of "local" dependences
2204 * which are treated as validity dependence by add_all_validity_constraints.)
2205 * Otherwise, we need to bound the distance both from above and from below.
2207 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2208 * Otherwise, we ignore them.
2210 static int add_all_proximity_constraints(struct isl_sched_graph *graph,
2211 int use_coincidence)
2213 int i;
2215 for (i = 0; i < graph->n_edge; ++i) {
2216 struct isl_sched_edge *edge = &graph->edge[i];
2217 int zero;
2219 zero = force_zero(edge, use_coincidence);
2220 if (!is_proximity(edge) && !zero)
2221 continue;
2222 if (edge->src == edge->dst &&
2223 add_intra_proximity_constraints(graph, edge, 1, zero) < 0)
2224 return -1;
2225 if (edge->src != edge->dst &&
2226 add_inter_proximity_constraints(graph, edge, 1, zero) < 0)
2227 return -1;
2228 if (is_validity(edge) || zero)
2229 continue;
2230 if (edge->src == edge->dst &&
2231 add_intra_proximity_constraints(graph, edge, -1, 0) < 0)
2232 return -1;
2233 if (edge->src != edge->dst &&
2234 add_inter_proximity_constraints(graph, edge, -1, 0) < 0)
2235 return -1;
2238 return 0;
2241 /* Normalize the rows of "indep" such that all rows are lexicographically
2242 * positive and such that each row contains as many final zeros as possible,
2243 * given the choice for the previous rows.
2244 * Do this by performing elementary row operations.
2246 static __isl_give isl_mat *normalize_independent(__isl_take isl_mat *indep)
2248 indep = isl_mat_reverse_gauss(indep);
2249 indep = isl_mat_lexnonneg_rows(indep);
2250 return indep;
2253 /* Compute a basis for the rows in the linear part of the schedule
2254 * and extend this basis to a full basis. The remaining rows
2255 * can then be used to force linear independence from the rows
2256 * in the schedule.
2258 * In particular, given the schedule rows S, we compute
2260 * S = H Q
2261 * S U = H
2263 * with H the Hermite normal form of S. That is, all but the
2264 * first rank columns of H are zero and so each row in S is
2265 * a linear combination of the first rank rows of Q.
2266 * The matrix Q can be used as a variable transformation
2267 * that isolates the directions of S in the first rank rows.
2268 * Transposing S U = H yields
2270 * U^T S^T = H^T
2272 * with all but the first rank rows of H^T zero.
2273 * The last rows of U^T are therefore linear combinations
2274 * of schedule coefficients that are all zero on schedule
2275 * coefficients that are linearly dependent on the rows of S.
2276 * At least one of these combinations is non-zero on
2277 * linearly independent schedule coefficients.
2278 * The rows are normalized to involve as few of the last
2279 * coefficients as possible and to have a positive initial value.
2281 static int node_update_vmap(struct isl_sched_node *node)
2283 isl_mat *H, *U, *Q;
2284 int n_row = isl_mat_rows(node->sched);
2286 H = isl_mat_sub_alloc(node->sched, 0, n_row,
2287 1 + node->nparam, node->nvar);
2289 H = isl_mat_left_hermite(H, 0, &U, &Q);
2290 isl_mat_free(node->indep);
2291 isl_mat_free(node->vmap);
2292 node->vmap = Q;
2293 node->indep = isl_mat_transpose(U);
2294 node->rank = isl_mat_initial_non_zero_cols(H);
2295 node->indep = isl_mat_drop_rows(node->indep, 0, node->rank);
2296 node->indep = normalize_independent(node->indep);
2297 isl_mat_free(H);
2299 if (!node->indep || !node->vmap || node->rank < 0)
2300 return -1;
2301 return 0;
2304 /* Is "edge" marked as a validity or a conditional validity edge?
2306 static int is_any_validity(struct isl_sched_edge *edge)
2308 return is_validity(edge) || is_conditional_validity(edge);
2311 /* How many times should we count the constraints in "edge"?
2313 * We count as follows
2314 * validity -> 1 (>= 0)
2315 * validity+proximity -> 2 (>= 0 and upper bound)
2316 * proximity -> 2 (lower and upper bound)
2317 * local(+any) -> 2 (>= 0 and <= 0)
2319 * If an edge is only marked conditional_validity then it counts
2320 * as zero since it is only checked afterwards.
2322 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2323 * Otherwise, we ignore them.
2325 static int edge_multiplicity(struct isl_sched_edge *edge, int use_coincidence)
2327 if (is_proximity(edge) || force_zero(edge, use_coincidence))
2328 return 2;
2329 if (is_validity(edge))
2330 return 1;
2331 return 0;
2334 /* How many times should the constraints in "edge" be counted
2335 * as a parametric intra-node constraint?
2337 * Only proximity edges that are not forced zero need
2338 * coefficient constraints that include coefficients for parameters.
2339 * If the edge is also a validity edge, then only
2340 * an upper bound is introduced. Otherwise, both lower and upper bounds
2341 * are introduced.
2343 static int parametric_intra_edge_multiplicity(struct isl_sched_edge *edge,
2344 int use_coincidence)
2346 if (edge->src != edge->dst)
2347 return 0;
2348 if (!is_proximity(edge))
2349 return 0;
2350 if (force_zero(edge, use_coincidence))
2351 return 0;
2352 if (is_validity(edge))
2353 return 1;
2354 else
2355 return 2;
2358 /* Add "f" times the number of equality and inequality constraints of "bset"
2359 * to "n_eq" and "n_ineq" and free "bset".
2361 static isl_stat update_count(__isl_take isl_basic_set *bset,
2362 int f, int *n_eq, int *n_ineq)
2364 if (!bset)
2365 return isl_stat_error;
2367 *n_eq += isl_basic_set_n_equality(bset);
2368 *n_ineq += isl_basic_set_n_inequality(bset);
2369 isl_basic_set_free(bset);
2371 return isl_stat_ok;
2374 /* Count the number of equality and inequality constraints
2375 * that will be added for the given map.
2377 * The edges that require parameter coefficients are counted separately.
2379 * "use_coincidence" is set if we should take into account coincidence edges.
2381 static isl_stat count_map_constraints(struct isl_sched_graph *graph,
2382 struct isl_sched_edge *edge, __isl_take isl_map *map,
2383 int *n_eq, int *n_ineq, int use_coincidence)
2385 isl_map *copy;
2386 isl_basic_set *coef;
2387 int f = edge_multiplicity(edge, use_coincidence);
2388 int fp = parametric_intra_edge_multiplicity(edge, use_coincidence);
2390 if (f == 0) {
2391 isl_map_free(map);
2392 return isl_stat_ok;
2395 if (edge->src != edge->dst) {
2396 coef = inter_coefficients(graph, edge, map);
2397 return update_count(coef, f, n_eq, n_ineq);
2400 if (fp > 0) {
2401 copy = isl_map_copy(map);
2402 coef = intra_coefficients(graph, edge->src, copy, 1);
2403 if (update_count(coef, fp, n_eq, n_ineq) < 0)
2404 goto error;
2407 if (f > fp) {
2408 copy = isl_map_copy(map);
2409 coef = intra_coefficients(graph, edge->src, copy, 0);
2410 if (update_count(coef, f - fp, n_eq, n_ineq) < 0)
2411 goto error;
2414 isl_map_free(map);
2415 return isl_stat_ok;
2416 error:
2417 isl_map_free(map);
2418 return isl_stat_error;
2421 /* Count the number of equality and inequality constraints
2422 * that will be added to the main lp problem.
2423 * We count as follows
2424 * validity -> 1 (>= 0)
2425 * validity+proximity -> 2 (>= 0 and upper bound)
2426 * proximity -> 2 (lower and upper bound)
2427 * local(+any) -> 2 (>= 0 and <= 0)
2429 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2430 * Otherwise, we ignore them.
2432 static int count_constraints(struct isl_sched_graph *graph,
2433 int *n_eq, int *n_ineq, int use_coincidence)
2435 int i;
2437 *n_eq = *n_ineq = 0;
2438 for (i = 0; i < graph->n_edge; ++i) {
2439 struct isl_sched_edge *edge = &graph->edge[i];
2440 isl_map *map = isl_map_copy(edge->map);
2442 if (count_map_constraints(graph, edge, map, n_eq, n_ineq,
2443 use_coincidence) < 0)
2444 return -1;
2447 return 0;
2450 /* Count the number of constraints that will be added by
2451 * add_bound_constant_constraints to bound the values of the constant terms
2452 * and increment *n_eq and *n_ineq accordingly.
2454 * In practice, add_bound_constant_constraints only adds inequalities.
2456 static isl_stat count_bound_constant_constraints(isl_ctx *ctx,
2457 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2459 if (isl_options_get_schedule_max_constant_term(ctx) == -1)
2460 return isl_stat_ok;
2462 *n_ineq += graph->n;
2464 return isl_stat_ok;
2467 /* Add constraints to bound the values of the constant terms in the schedule,
2468 * if requested by the user.
2470 * The maximal value of the constant terms is defined by the option
2471 * "schedule_max_constant_term".
2473 static isl_stat add_bound_constant_constraints(isl_ctx *ctx,
2474 struct isl_sched_graph *graph)
2476 int i, k;
2477 int max;
2478 int total;
2480 max = isl_options_get_schedule_max_constant_term(ctx);
2481 if (max == -1)
2482 return isl_stat_ok;
2484 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2486 for (i = 0; i < graph->n; ++i) {
2487 struct isl_sched_node *node = &graph->node[i];
2488 int pos;
2490 k = isl_basic_set_alloc_inequality(graph->lp);
2491 if (k < 0)
2492 return isl_stat_error;
2493 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2494 pos = node_cst_coef_offset(node);
2495 isl_int_set_si(graph->lp->ineq[k][1 + pos], -1);
2496 isl_int_set_si(graph->lp->ineq[k][0], max);
2499 return isl_stat_ok;
2502 /* Count the number of constraints that will be added by
2503 * add_bound_coefficient_constraints and increment *n_eq and *n_ineq
2504 * accordingly.
2506 * In practice, add_bound_coefficient_constraints only adds inequalities.
2508 static int count_bound_coefficient_constraints(isl_ctx *ctx,
2509 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2511 int i;
2513 if (isl_options_get_schedule_max_coefficient(ctx) == -1 &&
2514 !isl_options_get_schedule_treat_coalescing(ctx))
2515 return 0;
2517 for (i = 0; i < graph->n; ++i)
2518 *n_ineq += graph->node[i].nparam + 2 * graph->node[i].nvar;
2520 return 0;
2523 /* Add constraints to graph->lp that bound the values of
2524 * the parameter schedule coefficients of "node" to "max" and
2525 * the variable schedule coefficients to the corresponding entry
2526 * in node->max.
2527 * In either case, a negative value means that no bound needs to be imposed.
2529 * For parameter coefficients, this amounts to adding a constraint
2531 * c_n <= max
2533 * i.e.,
2535 * -c_n + max >= 0
2537 * The variables coefficients are, however, not represented directly.
2538 * Instead, the variable coefficients c_x are written as differences
2539 * c_x = c_x^+ - c_x^-.
2540 * That is,
2542 * -max_i <= c_x_i <= max_i
2544 * is encoded as
2546 * -max_i <= c_x_i^+ - c_x_i^- <= max_i
2548 * or
2550 * -(c_x_i^+ - c_x_i^-) + max_i >= 0
2551 * c_x_i^+ - c_x_i^- + max_i >= 0
2553 static isl_stat node_add_coefficient_constraints(isl_ctx *ctx,
2554 struct isl_sched_graph *graph, struct isl_sched_node *node, int max)
2556 int i, j, k;
2557 int total;
2558 isl_vec *ineq;
2560 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2562 for (j = 0; j < node->nparam; ++j) {
2563 int dim;
2565 if (max < 0)
2566 continue;
2568 k = isl_basic_set_alloc_inequality(graph->lp);
2569 if (k < 0)
2570 return isl_stat_error;
2571 dim = 1 + node_par_coef_offset(node) + j;
2572 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2573 isl_int_set_si(graph->lp->ineq[k][dim], -1);
2574 isl_int_set_si(graph->lp->ineq[k][0], max);
2577 ineq = isl_vec_alloc(ctx, 1 + total);
2578 ineq = isl_vec_clr(ineq);
2579 if (!ineq)
2580 return isl_stat_error;
2581 for (i = 0; i < node->nvar; ++i) {
2582 int pos = 1 + node_var_coef_pos(node, i);
2584 if (isl_int_is_neg(node->max->el[i]))
2585 continue;
2587 isl_int_set_si(ineq->el[pos], 1);
2588 isl_int_set_si(ineq->el[pos + 1], -1);
2589 isl_int_set(ineq->el[0], node->max->el[i]);
2591 k = isl_basic_set_alloc_inequality(graph->lp);
2592 if (k < 0)
2593 goto error;
2594 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2596 isl_seq_neg(ineq->el + pos, ineq->el + pos, 2);
2597 k = isl_basic_set_alloc_inequality(graph->lp);
2598 if (k < 0)
2599 goto error;
2600 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2602 isl_seq_clr(ineq->el + pos, 2);
2604 isl_vec_free(ineq);
2606 return isl_stat_ok;
2607 error:
2608 isl_vec_free(ineq);
2609 return isl_stat_error;
2612 /* Add constraints that bound the values of the variable and parameter
2613 * coefficients of the schedule.
2615 * The maximal value of the coefficients is defined by the option
2616 * 'schedule_max_coefficient' and the entries in node->max.
2617 * These latter entries are only set if either the schedule_max_coefficient
2618 * option or the schedule_treat_coalescing option is set.
2620 static isl_stat add_bound_coefficient_constraints(isl_ctx *ctx,
2621 struct isl_sched_graph *graph)
2623 int i;
2624 int max;
2626 max = isl_options_get_schedule_max_coefficient(ctx);
2628 if (max == -1 && !isl_options_get_schedule_treat_coalescing(ctx))
2629 return isl_stat_ok;
2631 for (i = 0; i < graph->n; ++i) {
2632 struct isl_sched_node *node = &graph->node[i];
2634 if (node_add_coefficient_constraints(ctx, graph, node, max) < 0)
2635 return isl_stat_error;
2638 return isl_stat_ok;
2641 /* Add a constraint to graph->lp that equates the value at position
2642 * "sum_pos" to the sum of the "n" values starting at "first".
2644 static isl_stat add_sum_constraint(struct isl_sched_graph *graph,
2645 int sum_pos, int first, int n)
2647 int i, k;
2648 int total;
2650 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2652 k = isl_basic_set_alloc_equality(graph->lp);
2653 if (k < 0)
2654 return isl_stat_error;
2655 isl_seq_clr(graph->lp->eq[k], 1 + total);
2656 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2657 for (i = 0; i < n; ++i)
2658 isl_int_set_si(graph->lp->eq[k][1 + first + i], 1);
2660 return isl_stat_ok;
2663 /* Add a constraint to graph->lp that equates the value at position
2664 * "sum_pos" to the sum of the parameter coefficients of all nodes.
2666 static isl_stat add_param_sum_constraint(struct isl_sched_graph *graph,
2667 int sum_pos)
2669 int i, j, k;
2670 int total;
2672 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2674 k = isl_basic_set_alloc_equality(graph->lp);
2675 if (k < 0)
2676 return isl_stat_error;
2677 isl_seq_clr(graph->lp->eq[k], 1 + total);
2678 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2679 for (i = 0; i < graph->n; ++i) {
2680 int pos = 1 + node_par_coef_offset(&graph->node[i]);
2682 for (j = 0; j < graph->node[i].nparam; ++j)
2683 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2686 return isl_stat_ok;
2689 /* Add a constraint to graph->lp that equates the value at position
2690 * "sum_pos" to the sum of the variable coefficients of all nodes.
2692 static isl_stat add_var_sum_constraint(struct isl_sched_graph *graph,
2693 int sum_pos)
2695 int i, j, k;
2696 int total;
2698 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2700 k = isl_basic_set_alloc_equality(graph->lp);
2701 if (k < 0)
2702 return isl_stat_error;
2703 isl_seq_clr(graph->lp->eq[k], 1 + total);
2704 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2705 for (i = 0; i < graph->n; ++i) {
2706 struct isl_sched_node *node = &graph->node[i];
2707 int pos = 1 + node_var_coef_offset(node);
2709 for (j = 0; j < 2 * node->nvar; ++j)
2710 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2713 return isl_stat_ok;
2716 /* Construct an ILP problem for finding schedule coefficients
2717 * that result in non-negative, but small dependence distances
2718 * over all dependences.
2719 * In particular, the dependence distances over proximity edges
2720 * are bounded by m_0 + m_n n and we compute schedule coefficients
2721 * with small values (preferably zero) of m_n and m_0.
2723 * All variables of the ILP are non-negative. The actual coefficients
2724 * may be negative, so each coefficient is represented as the difference
2725 * of two non-negative variables. The negative part always appears
2726 * immediately before the positive part.
2727 * Other than that, the variables have the following order
2729 * - sum of positive and negative parts of m_n coefficients
2730 * - m_0
2731 * - sum of all c_n coefficients
2732 * (unconstrained when computing non-parametric schedules)
2733 * - sum of positive and negative parts of all c_x coefficients
2734 * - positive and negative parts of m_n coefficients
2735 * - for each node
2736 * - positive and negative parts of c_i_x, in opposite order
2737 * - c_i_n (if parametric)
2738 * - c_i_0
2740 * The constraints are those from the edges plus two or three equalities
2741 * to express the sums.
2743 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2744 * Otherwise, we ignore them.
2746 static isl_stat setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
2747 int use_coincidence)
2749 int i;
2750 unsigned nparam;
2751 unsigned total;
2752 isl_space *space;
2753 int parametric;
2754 int param_pos;
2755 int n_eq, n_ineq;
2757 parametric = ctx->opt->schedule_parametric;
2758 nparam = isl_space_dim(graph->node[0].space, isl_dim_param);
2759 param_pos = 4;
2760 total = param_pos + 2 * nparam;
2761 for (i = 0; i < graph->n; ++i) {
2762 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2763 if (node_update_vmap(node) < 0)
2764 return isl_stat_error;
2765 node->start = total;
2766 total += 1 + node->nparam + 2 * node->nvar;
2769 if (count_constraints(graph, &n_eq, &n_ineq, use_coincidence) < 0)
2770 return isl_stat_error;
2771 if (count_bound_constant_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2772 return isl_stat_error;
2773 if (count_bound_coefficient_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2774 return isl_stat_error;
2776 space = isl_space_set_alloc(ctx, 0, total);
2777 isl_basic_set_free(graph->lp);
2778 n_eq += 2 + parametric;
2780 graph->lp = isl_basic_set_alloc_space(space, 0, n_eq, n_ineq);
2782 if (add_sum_constraint(graph, 0, param_pos, 2 * nparam) < 0)
2783 return isl_stat_error;
2784 if (parametric && add_param_sum_constraint(graph, 2) < 0)
2785 return isl_stat_error;
2786 if (add_var_sum_constraint(graph, 3) < 0)
2787 return isl_stat_error;
2788 if (add_bound_constant_constraints(ctx, graph) < 0)
2789 return isl_stat_error;
2790 if (add_bound_coefficient_constraints(ctx, graph) < 0)
2791 return isl_stat_error;
2792 if (add_all_validity_constraints(graph, use_coincidence) < 0)
2793 return isl_stat_error;
2794 if (add_all_proximity_constraints(graph, use_coincidence) < 0)
2795 return isl_stat_error;
2797 return isl_stat_ok;
2800 /* Analyze the conflicting constraint found by
2801 * isl_tab_basic_set_non_trivial_lexmin. If it corresponds to the validity
2802 * constraint of one of the edges between distinct nodes, living, moreover
2803 * in distinct SCCs, then record the source and sink SCC as this may
2804 * be a good place to cut between SCCs.
2806 static int check_conflict(int con, void *user)
2808 int i;
2809 struct isl_sched_graph *graph = user;
2811 if (graph->src_scc >= 0)
2812 return 0;
2814 con -= graph->lp->n_eq;
2816 if (con >= graph->lp->n_ineq)
2817 return 0;
2819 for (i = 0; i < graph->n_edge; ++i) {
2820 if (!is_validity(&graph->edge[i]))
2821 continue;
2822 if (graph->edge[i].src == graph->edge[i].dst)
2823 continue;
2824 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
2825 continue;
2826 if (graph->edge[i].start > con)
2827 continue;
2828 if (graph->edge[i].end <= con)
2829 continue;
2830 graph->src_scc = graph->edge[i].src->scc;
2831 graph->dst_scc = graph->edge[i].dst->scc;
2834 return 0;
2837 /* Check whether the next schedule row of the given node needs to be
2838 * non-trivial. Lower-dimensional domains may have some trivial rows,
2839 * but as soon as the number of remaining required non-trivial rows
2840 * is as large as the number or remaining rows to be computed,
2841 * all remaining rows need to be non-trivial.
2843 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
2845 return node->nvar - node->rank >= graph->maxvar - graph->n_row;
2848 /* Construct a non-triviality region with triviality directions
2849 * corresponding to the rows of "indep".
2850 * The rows of "indep" are expressed in terms of the schedule coefficients c_i,
2851 * while the triviality directions are expressed in terms of
2852 * pairs of non-negative variables c^+_i - c^-_i, with c^-_i appearing
2853 * before c^+_i. Furthermore,
2854 * the pairs of non-negative variables representing the coefficients
2855 * are stored in the opposite order.
2857 static __isl_give isl_mat *construct_trivial(__isl_keep isl_mat *indep)
2859 isl_ctx *ctx;
2860 isl_mat *mat;
2861 int i, j, n, n_var;
2863 if (!indep)
2864 return NULL;
2866 ctx = isl_mat_get_ctx(indep);
2867 n = isl_mat_rows(indep);
2868 n_var = isl_mat_cols(indep);
2869 mat = isl_mat_alloc(ctx, n, 2 * n_var);
2870 if (!mat)
2871 return NULL;
2872 for (i = 0; i < n; ++i) {
2873 for (j = 0; j < n_var; ++j) {
2874 int nj = n_var - 1 - j;
2875 isl_int_neg(mat->row[i][2 * nj], indep->row[i][j]);
2876 isl_int_set(mat->row[i][2 * nj + 1], indep->row[i][j]);
2880 return mat;
2883 /* Solve the ILP problem constructed in setup_lp.
2884 * For each node such that all the remaining rows of its schedule
2885 * need to be non-trivial, we construct a non-triviality region.
2886 * This region imposes that the next row is independent of previous rows.
2887 * In particular, the non-triviality region enforces that at least
2888 * one of the linear combinations in the rows of node->indep is non-zero.
2890 static __isl_give isl_vec *solve_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
2892 int i;
2893 isl_vec *sol;
2894 isl_basic_set *lp;
2896 for (i = 0; i < graph->n; ++i) {
2897 struct isl_sched_node *node = &graph->node[i];
2898 isl_mat *trivial;
2900 graph->region[i].pos = node_var_coef_offset(node);
2901 if (needs_row(graph, node))
2902 trivial = construct_trivial(node->indep);
2903 else
2904 trivial = isl_mat_zero(ctx, 0, 0);
2905 graph->region[i].trivial = trivial;
2907 lp = isl_basic_set_copy(graph->lp);
2908 sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
2909 graph->region, &check_conflict, graph);
2910 for (i = 0; i < graph->n; ++i)
2911 isl_mat_free(graph->region[i].trivial);
2912 return sol;
2915 /* Extract the coefficients for the variables of "node" from "sol".
2917 * Each schedule coefficient c_i_x is represented as the difference
2918 * between two non-negative variables c_i_x^+ - c_i_x^-.
2919 * The c_i_x^- appear before their c_i_x^+ counterpart.
2920 * Furthermore, the order of these pairs is the opposite of that
2921 * of the corresponding coefficients.
2923 * Return c_i_x = c_i_x^+ - c_i_x^-
2925 static __isl_give isl_vec *extract_var_coef(struct isl_sched_node *node,
2926 __isl_keep isl_vec *sol)
2928 int i;
2929 int pos;
2930 isl_vec *csol;
2932 if (!sol)
2933 return NULL;
2934 csol = isl_vec_alloc(isl_vec_get_ctx(sol), node->nvar);
2935 if (!csol)
2936 return NULL;
2938 pos = 1 + node_var_coef_offset(node);
2939 for (i = 0; i < node->nvar; ++i)
2940 isl_int_sub(csol->el[node->nvar - 1 - i],
2941 sol->el[pos + 2 * i + 1], sol->el[pos + 2 * i]);
2943 return csol;
2946 /* Update the schedules of all nodes based on the given solution
2947 * of the LP problem.
2948 * The new row is added to the current band.
2949 * All possibly negative coefficients are encoded as a difference
2950 * of two non-negative variables, so we need to perform the subtraction
2951 * here.
2953 * If coincident is set, then the caller guarantees that the new
2954 * row satisfies the coincidence constraints.
2956 static int update_schedule(struct isl_sched_graph *graph,
2957 __isl_take isl_vec *sol, int coincident)
2959 int i, j;
2960 isl_vec *csol = NULL;
2962 if (!sol)
2963 goto error;
2964 if (sol->size == 0)
2965 isl_die(sol->ctx, isl_error_internal,
2966 "no solution found", goto error);
2967 if (graph->n_total_row >= graph->max_row)
2968 isl_die(sol->ctx, isl_error_internal,
2969 "too many schedule rows", goto error);
2971 for (i = 0; i < graph->n; ++i) {
2972 struct isl_sched_node *node = &graph->node[i];
2973 int pos;
2974 int row = isl_mat_rows(node->sched);
2976 isl_vec_free(csol);
2977 csol = extract_var_coef(node, sol);
2978 if (!csol)
2979 goto error;
2981 isl_map_free(node->sched_map);
2982 node->sched_map = NULL;
2983 node->sched = isl_mat_add_rows(node->sched, 1);
2984 if (!node->sched)
2985 goto error;
2986 pos = node_cst_coef_offset(node);
2987 node->sched = isl_mat_set_element(node->sched,
2988 row, 0, sol->el[1 + pos]);
2989 pos = node_par_coef_offset(node);
2990 for (j = 0; j < node->nparam; ++j)
2991 node->sched = isl_mat_set_element(node->sched,
2992 row, 1 + j, sol->el[1 + pos + j]);
2993 for (j = 0; j < node->nvar; ++j)
2994 node->sched = isl_mat_set_element(node->sched,
2995 row, 1 + node->nparam + j, csol->el[j]);
2996 node->coincident[graph->n_total_row] = coincident;
2998 isl_vec_free(sol);
2999 isl_vec_free(csol);
3001 graph->n_row++;
3002 graph->n_total_row++;
3004 return 0;
3005 error:
3006 isl_vec_free(sol);
3007 isl_vec_free(csol);
3008 return -1;
3011 /* Convert row "row" of node->sched into an isl_aff living in "ls"
3012 * and return this isl_aff.
3014 static __isl_give isl_aff *extract_schedule_row(__isl_take isl_local_space *ls,
3015 struct isl_sched_node *node, int row)
3017 int j;
3018 isl_int v;
3019 isl_aff *aff;
3021 isl_int_init(v);
3023 aff = isl_aff_zero_on_domain(ls);
3024 if (isl_mat_get_element(node->sched, row, 0, &v) < 0)
3025 goto error;
3026 aff = isl_aff_set_constant(aff, v);
3027 for (j = 0; j < node->nparam; ++j) {
3028 if (isl_mat_get_element(node->sched, row, 1 + j, &v) < 0)
3029 goto error;
3030 aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
3032 for (j = 0; j < node->nvar; ++j) {
3033 if (isl_mat_get_element(node->sched, row,
3034 1 + node->nparam + j, &v) < 0)
3035 goto error;
3036 aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
3039 isl_int_clear(v);
3041 return aff;
3042 error:
3043 isl_int_clear(v);
3044 isl_aff_free(aff);
3045 return NULL;
3048 /* Convert the "n" rows starting at "first" of node->sched into a multi_aff
3049 * and return this multi_aff.
3051 * The result is defined over the uncompressed node domain.
3053 static __isl_give isl_multi_aff *node_extract_partial_schedule_multi_aff(
3054 struct isl_sched_node *node, int first, int n)
3056 int i;
3057 isl_space *space;
3058 isl_local_space *ls;
3059 isl_aff *aff;
3060 isl_multi_aff *ma;
3061 int nrow;
3063 if (!node)
3064 return NULL;
3065 nrow = isl_mat_rows(node->sched);
3066 if (node->compressed)
3067 space = isl_multi_aff_get_domain_space(node->decompress);
3068 else
3069 space = isl_space_copy(node->space);
3070 ls = isl_local_space_from_space(isl_space_copy(space));
3071 space = isl_space_from_domain(space);
3072 space = isl_space_add_dims(space, isl_dim_out, n);
3073 ma = isl_multi_aff_zero(space);
3075 for (i = first; i < first + n; ++i) {
3076 aff = extract_schedule_row(isl_local_space_copy(ls), node, i);
3077 ma = isl_multi_aff_set_aff(ma, i - first, aff);
3080 isl_local_space_free(ls);
3082 if (node->compressed)
3083 ma = isl_multi_aff_pullback_multi_aff(ma,
3084 isl_multi_aff_copy(node->compress));
3086 return ma;
3089 /* Convert node->sched into a multi_aff and return this multi_aff.
3091 * The result is defined over the uncompressed node domain.
3093 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
3094 struct isl_sched_node *node)
3096 int nrow;
3098 nrow = isl_mat_rows(node->sched);
3099 return node_extract_partial_schedule_multi_aff(node, 0, nrow);
3102 /* Convert node->sched into a map and return this map.
3104 * The result is cached in node->sched_map, which needs to be released
3105 * whenever node->sched is updated.
3106 * It is defined over the uncompressed node domain.
3108 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
3110 if (!node->sched_map) {
3111 isl_multi_aff *ma;
3113 ma = node_extract_schedule_multi_aff(node);
3114 node->sched_map = isl_map_from_multi_aff(ma);
3117 return isl_map_copy(node->sched_map);
3120 /* Construct a map that can be used to update a dependence relation
3121 * based on the current schedule.
3122 * That is, construct a map expressing that source and sink
3123 * are executed within the same iteration of the current schedule.
3124 * This map can then be intersected with the dependence relation.
3125 * This is not the most efficient way, but this shouldn't be a critical
3126 * operation.
3128 static __isl_give isl_map *specializer(struct isl_sched_node *src,
3129 struct isl_sched_node *dst)
3131 isl_map *src_sched, *dst_sched;
3133 src_sched = node_extract_schedule(src);
3134 dst_sched = node_extract_schedule(dst);
3135 return isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
3138 /* Intersect the domains of the nested relations in domain and range
3139 * of "umap" with "map".
3141 static __isl_give isl_union_map *intersect_domains(
3142 __isl_take isl_union_map *umap, __isl_keep isl_map *map)
3144 isl_union_set *uset;
3146 umap = isl_union_map_zip(umap);
3147 uset = isl_union_set_from_set(isl_map_wrap(isl_map_copy(map)));
3148 umap = isl_union_map_intersect_domain(umap, uset);
3149 umap = isl_union_map_zip(umap);
3150 return umap;
3153 /* Update the dependence relation of the given edge based
3154 * on the current schedule.
3155 * If the dependence is carried completely by the current schedule, then
3156 * it is removed from the edge_tables. It is kept in the list of edges
3157 * as otherwise all edge_tables would have to be recomputed.
3159 * If the edge is of a type that can appear multiple times
3160 * between the same pair of nodes, then it is added to
3161 * the edge table (again). This prevents the situation
3162 * where none of these edges is referenced from the edge table
3163 * because the one that was referenced turned out to be empty and
3164 * was therefore removed from the table.
3166 static isl_stat update_edge(isl_ctx *ctx, struct isl_sched_graph *graph,
3167 struct isl_sched_edge *edge)
3169 int empty;
3170 isl_map *id;
3172 id = specializer(edge->src, edge->dst);
3173 edge->map = isl_map_intersect(edge->map, isl_map_copy(id));
3174 if (!edge->map)
3175 goto error;
3177 if (edge->tagged_condition) {
3178 edge->tagged_condition =
3179 intersect_domains(edge->tagged_condition, id);
3180 if (!edge->tagged_condition)
3181 goto error;
3183 if (edge->tagged_validity) {
3184 edge->tagged_validity =
3185 intersect_domains(edge->tagged_validity, id);
3186 if (!edge->tagged_validity)
3187 goto error;
3190 empty = isl_map_plain_is_empty(edge->map);
3191 if (empty < 0)
3192 goto error;
3193 if (empty) {
3194 graph_remove_edge(graph, edge);
3195 } else if (is_multi_edge_type(edge)) {
3196 if (graph_edge_tables_add(ctx, graph, edge) < 0)
3197 goto error;
3200 isl_map_free(id);
3201 return isl_stat_ok;
3202 error:
3203 isl_map_free(id);
3204 return isl_stat_error;
3207 /* Does the domain of "umap" intersect "uset"?
3209 static int domain_intersects(__isl_keep isl_union_map *umap,
3210 __isl_keep isl_union_set *uset)
3212 int empty;
3214 umap = isl_union_map_copy(umap);
3215 umap = isl_union_map_intersect_domain(umap, isl_union_set_copy(uset));
3216 empty = isl_union_map_is_empty(umap);
3217 isl_union_map_free(umap);
3219 return empty < 0 ? -1 : !empty;
3222 /* Does the range of "umap" intersect "uset"?
3224 static int range_intersects(__isl_keep isl_union_map *umap,
3225 __isl_keep isl_union_set *uset)
3227 int empty;
3229 umap = isl_union_map_copy(umap);
3230 umap = isl_union_map_intersect_range(umap, isl_union_set_copy(uset));
3231 empty = isl_union_map_is_empty(umap);
3232 isl_union_map_free(umap);
3234 return empty < 0 ? -1 : !empty;
3237 /* Are the condition dependences of "edge" local with respect to
3238 * the current schedule?
3240 * That is, are domain and range of the condition dependences mapped
3241 * to the same point?
3243 * In other words, is the condition false?
3245 static int is_condition_false(struct isl_sched_edge *edge)
3247 isl_union_map *umap;
3248 isl_map *map, *sched, *test;
3249 int empty, local;
3251 empty = isl_union_map_is_empty(edge->tagged_condition);
3252 if (empty < 0 || empty)
3253 return empty;
3255 umap = isl_union_map_copy(edge->tagged_condition);
3256 umap = isl_union_map_zip(umap);
3257 umap = isl_union_set_unwrap(isl_union_map_domain(umap));
3258 map = isl_map_from_union_map(umap);
3260 sched = node_extract_schedule(edge->src);
3261 map = isl_map_apply_domain(map, sched);
3262 sched = node_extract_schedule(edge->dst);
3263 map = isl_map_apply_range(map, sched);
3265 test = isl_map_identity(isl_map_get_space(map));
3266 local = isl_map_is_subset(map, test);
3267 isl_map_free(map);
3268 isl_map_free(test);
3270 return local;
3273 /* For each conditional validity constraint that is adjacent
3274 * to a condition with domain in condition_source or range in condition_sink,
3275 * turn it into an unconditional validity constraint.
3277 static int unconditionalize_adjacent_validity(struct isl_sched_graph *graph,
3278 __isl_take isl_union_set *condition_source,
3279 __isl_take isl_union_set *condition_sink)
3281 int i;
3283 condition_source = isl_union_set_coalesce(condition_source);
3284 condition_sink = isl_union_set_coalesce(condition_sink);
3286 for (i = 0; i < graph->n_edge; ++i) {
3287 int adjacent;
3288 isl_union_map *validity;
3290 if (!is_conditional_validity(&graph->edge[i]))
3291 continue;
3292 if (is_validity(&graph->edge[i]))
3293 continue;
3295 validity = graph->edge[i].tagged_validity;
3296 adjacent = domain_intersects(validity, condition_sink);
3297 if (adjacent >= 0 && !adjacent)
3298 adjacent = range_intersects(validity, condition_source);
3299 if (adjacent < 0)
3300 goto error;
3301 if (!adjacent)
3302 continue;
3304 set_validity(&graph->edge[i]);
3307 isl_union_set_free(condition_source);
3308 isl_union_set_free(condition_sink);
3309 return 0;
3310 error:
3311 isl_union_set_free(condition_source);
3312 isl_union_set_free(condition_sink);
3313 return -1;
3316 /* Update the dependence relations of all edges based on the current schedule
3317 * and enforce conditional validity constraints that are adjacent
3318 * to satisfied condition constraints.
3320 * First check if any of the condition constraints are satisfied
3321 * (i.e., not local to the outer schedule) and keep track of
3322 * their domain and range.
3323 * Then update all dependence relations (which removes the non-local
3324 * constraints).
3325 * Finally, if any condition constraints turned out to be satisfied,
3326 * then turn all adjacent conditional validity constraints into
3327 * unconditional validity constraints.
3329 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
3331 int i;
3332 int any = 0;
3333 isl_union_set *source, *sink;
3335 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3336 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3337 for (i = 0; i < graph->n_edge; ++i) {
3338 int local;
3339 isl_union_set *uset;
3340 isl_union_map *umap;
3342 if (!is_condition(&graph->edge[i]))
3343 continue;
3344 if (is_local(&graph->edge[i]))
3345 continue;
3346 local = is_condition_false(&graph->edge[i]);
3347 if (local < 0)
3348 goto error;
3349 if (local)
3350 continue;
3352 any = 1;
3354 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3355 uset = isl_union_map_domain(umap);
3356 source = isl_union_set_union(source, uset);
3358 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3359 uset = isl_union_map_range(umap);
3360 sink = isl_union_set_union(sink, uset);
3363 for (i = 0; i < graph->n_edge; ++i) {
3364 if (update_edge(ctx, graph, &graph->edge[i]) < 0)
3365 goto error;
3368 if (any)
3369 return unconditionalize_adjacent_validity(graph, source, sink);
3371 isl_union_set_free(source);
3372 isl_union_set_free(sink);
3373 return 0;
3374 error:
3375 isl_union_set_free(source);
3376 isl_union_set_free(sink);
3377 return -1;
3380 static void next_band(struct isl_sched_graph *graph)
3382 graph->band_start = graph->n_total_row;
3385 /* Return the union of the universe domains of the nodes in "graph"
3386 * that satisfy "pred".
3388 static __isl_give isl_union_set *isl_sched_graph_domain(isl_ctx *ctx,
3389 struct isl_sched_graph *graph,
3390 int (*pred)(struct isl_sched_node *node, int data), int data)
3392 int i;
3393 isl_set *set;
3394 isl_union_set *dom;
3396 for (i = 0; i < graph->n; ++i)
3397 if (pred(&graph->node[i], data))
3398 break;
3400 if (i >= graph->n)
3401 isl_die(ctx, isl_error_internal,
3402 "empty component", return NULL);
3404 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3405 dom = isl_union_set_from_set(set);
3407 for (i = i + 1; i < graph->n; ++i) {
3408 if (!pred(&graph->node[i], data))
3409 continue;
3410 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3411 dom = isl_union_set_union(dom, isl_union_set_from_set(set));
3414 return dom;
3417 /* Return a list of unions of universe domains, where each element
3418 * in the list corresponds to an SCC (or WCC) indexed by node->scc.
3420 static __isl_give isl_union_set_list *extract_sccs(isl_ctx *ctx,
3421 struct isl_sched_graph *graph)
3423 int i;
3424 isl_union_set_list *filters;
3426 filters = isl_union_set_list_alloc(ctx, graph->scc);
3427 for (i = 0; i < graph->scc; ++i) {
3428 isl_union_set *dom;
3430 dom = isl_sched_graph_domain(ctx, graph, &node_scc_exactly, i);
3431 filters = isl_union_set_list_add(filters, dom);
3434 return filters;
3437 /* Return a list of two unions of universe domains, one for the SCCs up
3438 * to and including graph->src_scc and another for the other SCCs.
3440 static __isl_give isl_union_set_list *extract_split(isl_ctx *ctx,
3441 struct isl_sched_graph *graph)
3443 isl_union_set *dom;
3444 isl_union_set_list *filters;
3446 filters = isl_union_set_list_alloc(ctx, 2);
3447 dom = isl_sched_graph_domain(ctx, graph,
3448 &node_scc_at_most, graph->src_scc);
3449 filters = isl_union_set_list_add(filters, dom);
3450 dom = isl_sched_graph_domain(ctx, graph,
3451 &node_scc_at_least, graph->src_scc + 1);
3452 filters = isl_union_set_list_add(filters, dom);
3454 return filters;
3457 /* Copy nodes that satisfy node_pred from the src dependence graph
3458 * to the dst dependence graph.
3460 static isl_stat copy_nodes(struct isl_sched_graph *dst,
3461 struct isl_sched_graph *src,
3462 int (*node_pred)(struct isl_sched_node *node, int data), int data)
3464 int i;
3466 dst->n = 0;
3467 for (i = 0; i < src->n; ++i) {
3468 int j;
3470 if (!node_pred(&src->node[i], data))
3471 continue;
3473 j = dst->n;
3474 dst->node[j].space = isl_space_copy(src->node[i].space);
3475 dst->node[j].compressed = src->node[i].compressed;
3476 dst->node[j].hull = isl_set_copy(src->node[i].hull);
3477 dst->node[j].compress =
3478 isl_multi_aff_copy(src->node[i].compress);
3479 dst->node[j].decompress =
3480 isl_multi_aff_copy(src->node[i].decompress);
3481 dst->node[j].nvar = src->node[i].nvar;
3482 dst->node[j].nparam = src->node[i].nparam;
3483 dst->node[j].sched = isl_mat_copy(src->node[i].sched);
3484 dst->node[j].sched_map = isl_map_copy(src->node[i].sched_map);
3485 dst->node[j].coincident = src->node[i].coincident;
3486 dst->node[j].sizes = isl_multi_val_copy(src->node[i].sizes);
3487 dst->node[j].bounds = isl_basic_set_copy(src->node[i].bounds);
3488 dst->node[j].max = isl_vec_copy(src->node[i].max);
3489 dst->n++;
3491 if (!dst->node[j].space || !dst->node[j].sched)
3492 return isl_stat_error;
3493 if (dst->node[j].compressed &&
3494 (!dst->node[j].hull || !dst->node[j].compress ||
3495 !dst->node[j].decompress))
3496 return isl_stat_error;
3499 return isl_stat_ok;
3502 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
3503 * to the dst dependence graph.
3504 * If the source or destination node of the edge is not in the destination
3505 * graph, then it must be a backward proximity edge and it should simply
3506 * be ignored.
3508 static isl_stat copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
3509 struct isl_sched_graph *src,
3510 int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
3512 int i;
3514 dst->n_edge = 0;
3515 for (i = 0; i < src->n_edge; ++i) {
3516 struct isl_sched_edge *edge = &src->edge[i];
3517 isl_map *map;
3518 isl_union_map *tagged_condition;
3519 isl_union_map *tagged_validity;
3520 struct isl_sched_node *dst_src, *dst_dst;
3522 if (!edge_pred(edge, data))
3523 continue;
3525 if (isl_map_plain_is_empty(edge->map))
3526 continue;
3528 dst_src = graph_find_node(ctx, dst, edge->src->space);
3529 dst_dst = graph_find_node(ctx, dst, edge->dst->space);
3530 if (!dst_src || !dst_dst)
3531 return isl_stat_error;
3532 if (!is_node(dst, dst_src) || !is_node(dst, dst_dst)) {
3533 if (is_validity(edge) || is_conditional_validity(edge))
3534 isl_die(ctx, isl_error_internal,
3535 "backward (conditional) validity edge",
3536 return isl_stat_error);
3537 continue;
3540 map = isl_map_copy(edge->map);
3541 tagged_condition = isl_union_map_copy(edge->tagged_condition);
3542 tagged_validity = isl_union_map_copy(edge->tagged_validity);
3544 dst->edge[dst->n_edge].src = dst_src;
3545 dst->edge[dst->n_edge].dst = dst_dst;
3546 dst->edge[dst->n_edge].map = map;
3547 dst->edge[dst->n_edge].tagged_condition = tagged_condition;
3548 dst->edge[dst->n_edge].tagged_validity = tagged_validity;
3549 dst->edge[dst->n_edge].types = edge->types;
3550 dst->n_edge++;
3552 if (edge->tagged_condition && !tagged_condition)
3553 return isl_stat_error;
3554 if (edge->tagged_validity && !tagged_validity)
3555 return isl_stat_error;
3557 if (graph_edge_tables_add(ctx, dst,
3558 &dst->edge[dst->n_edge - 1]) < 0)
3559 return isl_stat_error;
3562 return isl_stat_ok;
3565 /* Compute the maximal number of variables over all nodes.
3566 * This is the maximal number of linearly independent schedule
3567 * rows that we need to compute.
3568 * Just in case we end up in a part of the dependence graph
3569 * with only lower-dimensional domains, we make sure we will
3570 * compute the required amount of extra linearly independent rows.
3572 static int compute_maxvar(struct isl_sched_graph *graph)
3574 int i;
3576 graph->maxvar = 0;
3577 for (i = 0; i < graph->n; ++i) {
3578 struct isl_sched_node *node = &graph->node[i];
3579 int nvar;
3581 if (node_update_vmap(node) < 0)
3582 return -1;
3583 nvar = node->nvar + graph->n_row - node->rank;
3584 if (nvar > graph->maxvar)
3585 graph->maxvar = nvar;
3588 return 0;
3591 /* Extract the subgraph of "graph" that consists of the nodes satisfying
3592 * "node_pred" and the edges satisfying "edge_pred" and store
3593 * the result in "sub".
3595 static isl_stat extract_sub_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
3596 int (*node_pred)(struct isl_sched_node *node, int data),
3597 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3598 int data, struct isl_sched_graph *sub)
3600 int i, n = 0, n_edge = 0;
3601 int t;
3603 for (i = 0; i < graph->n; ++i)
3604 if (node_pred(&graph->node[i], data))
3605 ++n;
3606 for (i = 0; i < graph->n_edge; ++i)
3607 if (edge_pred(&graph->edge[i], data))
3608 ++n_edge;
3609 if (graph_alloc(ctx, sub, n, n_edge) < 0)
3610 return isl_stat_error;
3611 sub->root = graph->root;
3612 if (copy_nodes(sub, graph, node_pred, data) < 0)
3613 return isl_stat_error;
3614 if (graph_init_table(ctx, sub) < 0)
3615 return isl_stat_error;
3616 for (t = 0; t <= isl_edge_last; ++t)
3617 sub->max_edge[t] = graph->max_edge[t];
3618 if (graph_init_edge_tables(ctx, sub) < 0)
3619 return isl_stat_error;
3620 if (copy_edges(ctx, sub, graph, edge_pred, data) < 0)
3621 return isl_stat_error;
3622 sub->n_row = graph->n_row;
3623 sub->max_row = graph->max_row;
3624 sub->n_total_row = graph->n_total_row;
3625 sub->band_start = graph->band_start;
3627 return isl_stat_ok;
3630 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
3631 struct isl_sched_graph *graph);
3632 static __isl_give isl_schedule_node *compute_schedule_wcc(
3633 isl_schedule_node *node, struct isl_sched_graph *graph);
3635 /* Compute a schedule for a subgraph of "graph". In particular, for
3636 * the graph composed of nodes that satisfy node_pred and edges that
3637 * that satisfy edge_pred.
3638 * If the subgraph is known to consist of a single component, then wcc should
3639 * be set and then we call compute_schedule_wcc on the constructed subgraph.
3640 * Otherwise, we call compute_schedule, which will check whether the subgraph
3641 * is connected.
3643 * The schedule is inserted at "node" and the updated schedule node
3644 * is returned.
3646 static __isl_give isl_schedule_node *compute_sub_schedule(
3647 __isl_take isl_schedule_node *node, isl_ctx *ctx,
3648 struct isl_sched_graph *graph,
3649 int (*node_pred)(struct isl_sched_node *node, int data),
3650 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3651 int data, int wcc)
3653 struct isl_sched_graph split = { 0 };
3655 if (extract_sub_graph(ctx, graph, node_pred, edge_pred, data,
3656 &split) < 0)
3657 goto error;
3659 if (wcc)
3660 node = compute_schedule_wcc(node, &split);
3661 else
3662 node = compute_schedule(node, &split);
3664 graph_free(ctx, &split);
3665 return node;
3666 error:
3667 graph_free(ctx, &split);
3668 return isl_schedule_node_free(node);
3671 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
3673 return edge->src->scc == scc && edge->dst->scc == scc;
3676 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
3678 return edge->dst->scc <= scc;
3681 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
3683 return edge->src->scc >= scc;
3686 /* Reset the current band by dropping all its schedule rows.
3688 static isl_stat reset_band(struct isl_sched_graph *graph)
3690 int i;
3691 int drop;
3693 drop = graph->n_total_row - graph->band_start;
3694 graph->n_total_row -= drop;
3695 graph->n_row -= drop;
3697 for (i = 0; i < graph->n; ++i) {
3698 struct isl_sched_node *node = &graph->node[i];
3700 isl_map_free(node->sched_map);
3701 node->sched_map = NULL;
3703 node->sched = isl_mat_drop_rows(node->sched,
3704 graph->band_start, drop);
3706 if (!node->sched)
3707 return isl_stat_error;
3710 return isl_stat_ok;
3713 /* Split the current graph into two parts and compute a schedule for each
3714 * part individually. In particular, one part consists of all SCCs up
3715 * to and including graph->src_scc, while the other part contains the other
3716 * SCCs. The split is enforced by a sequence node inserted at position "node"
3717 * in the schedule tree. Return the updated schedule node.
3718 * If either of these two parts consists of a sequence, then it is spliced
3719 * into the sequence containing the two parts.
3721 * The current band is reset. It would be possible to reuse
3722 * the previously computed rows as the first rows in the next
3723 * band, but recomputing them may result in better rows as we are looking
3724 * at a smaller part of the dependence graph.
3726 static __isl_give isl_schedule_node *compute_split_schedule(
3727 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3729 int is_seq;
3730 isl_ctx *ctx;
3731 isl_union_set_list *filters;
3733 if (!node)
3734 return NULL;
3736 if (reset_band(graph) < 0)
3737 return isl_schedule_node_free(node);
3739 next_band(graph);
3741 ctx = isl_schedule_node_get_ctx(node);
3742 filters = extract_split(ctx, graph);
3743 node = isl_schedule_node_insert_sequence(node, filters);
3744 node = isl_schedule_node_child(node, 1);
3745 node = isl_schedule_node_child(node, 0);
3747 node = compute_sub_schedule(node, ctx, graph,
3748 &node_scc_at_least, &edge_src_scc_at_least,
3749 graph->src_scc + 1, 0);
3750 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3751 node = isl_schedule_node_parent(node);
3752 node = isl_schedule_node_parent(node);
3753 if (is_seq)
3754 node = isl_schedule_node_sequence_splice_child(node, 1);
3755 node = isl_schedule_node_child(node, 0);
3756 node = isl_schedule_node_child(node, 0);
3757 node = compute_sub_schedule(node, ctx, graph,
3758 &node_scc_at_most, &edge_dst_scc_at_most,
3759 graph->src_scc, 0);
3760 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3761 node = isl_schedule_node_parent(node);
3762 node = isl_schedule_node_parent(node);
3763 if (is_seq)
3764 node = isl_schedule_node_sequence_splice_child(node, 0);
3766 return node;
3769 /* Insert a band node at position "node" in the schedule tree corresponding
3770 * to the current band in "graph". Mark the band node permutable
3771 * if "permutable" is set.
3772 * The partial schedules and the coincidence property are extracted
3773 * from the graph nodes.
3774 * Return the updated schedule node.
3776 static __isl_give isl_schedule_node *insert_current_band(
3777 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3778 int permutable)
3780 int i;
3781 int start, end, n;
3782 isl_multi_aff *ma;
3783 isl_multi_pw_aff *mpa;
3784 isl_multi_union_pw_aff *mupa;
3786 if (!node)
3787 return NULL;
3789 if (graph->n < 1)
3790 isl_die(isl_schedule_node_get_ctx(node), isl_error_internal,
3791 "graph should have at least one node",
3792 return isl_schedule_node_free(node));
3794 start = graph->band_start;
3795 end = graph->n_total_row;
3796 n = end - start;
3798 ma = node_extract_partial_schedule_multi_aff(&graph->node[0], start, n);
3799 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3800 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3802 for (i = 1; i < graph->n; ++i) {
3803 isl_multi_union_pw_aff *mupa_i;
3805 ma = node_extract_partial_schedule_multi_aff(&graph->node[i],
3806 start, n);
3807 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3808 mupa_i = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3809 mupa = isl_multi_union_pw_aff_union_add(mupa, mupa_i);
3811 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3813 for (i = 0; i < n; ++i)
3814 node = isl_schedule_node_band_member_set_coincident(node, i,
3815 graph->node[0].coincident[start + i]);
3816 node = isl_schedule_node_band_set_permutable(node, permutable);
3818 return node;
3821 /* Update the dependence relations based on the current schedule,
3822 * add the current band to "node" and then continue with the computation
3823 * of the next band.
3824 * Return the updated schedule node.
3826 static __isl_give isl_schedule_node *compute_next_band(
3827 __isl_take isl_schedule_node *node,
3828 struct isl_sched_graph *graph, int permutable)
3830 isl_ctx *ctx;
3832 if (!node)
3833 return NULL;
3835 ctx = isl_schedule_node_get_ctx(node);
3836 if (update_edges(ctx, graph) < 0)
3837 return isl_schedule_node_free(node);
3838 node = insert_current_band(node, graph, permutable);
3839 next_band(graph);
3841 node = isl_schedule_node_child(node, 0);
3842 node = compute_schedule(node, graph);
3843 node = isl_schedule_node_parent(node);
3845 return node;
3848 /* Add the constraints "coef" derived from an edge from "node" to itself
3849 * to graph->lp in order to respect the dependences and to try and carry them.
3850 * "pos" is the sequence number of the edge that needs to be carried.
3851 * "coef" represents general constraints on coefficients (c_0, c_x)
3852 * of valid constraints for (y - x) with x and y instances of the node.
3854 * The constraints added to graph->lp need to enforce
3856 * (c_j_0 + c_j_x y) - (c_j_0 + c_j_x x)
3857 * = c_j_x (y - x) >= e_i
3859 * for each (x,y) in the dependence relation of the edge.
3860 * That is, (-e_i, c_j_x) needs to be plugged in for (c_0, c_x),
3861 * taking into account that each coefficient in c_j_x is represented
3862 * as a pair of non-negative coefficients.
3864 static isl_stat add_intra_constraints(struct isl_sched_graph *graph,
3865 struct isl_sched_node *node, __isl_take isl_basic_set *coef, int pos)
3867 int offset;
3868 isl_ctx *ctx;
3869 isl_dim_map *dim_map;
3871 if (!coef)
3872 return isl_stat_error;
3874 ctx = isl_basic_set_get_ctx(coef);
3875 offset = coef_var_offset(coef);
3876 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
3877 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3878 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3880 return isl_stat_ok;
3883 /* Add the constraints "coef" derived from an edge from "src" to "dst"
3884 * to graph->lp in order to respect the dependences and to try and carry them.
3885 * "pos" is the sequence number of the edge that needs to be carried or
3886 * -1 if no attempt should be made to carry the dependences.
3887 * "coef" represents general constraints on coefficients (c_0, c_n, c_x, c_y)
3888 * of valid constraints for (x, y) with x and y instances of "src" and "dst".
3890 * The constraints added to graph->lp need to enforce
3892 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
3894 * for each (x,y) in the dependence relation of the edge or
3896 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= 0
3898 * if pos is -1.
3899 * That is,
3900 * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3901 * or
3902 * (c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3903 * needs to be plugged in for (c_0, c_n, c_x, c_y),
3904 * taking into account that each coefficient in c_j_x and c_k_x is represented
3905 * as a pair of non-negative coefficients.
3907 static isl_stat add_inter_constraints(struct isl_sched_graph *graph,
3908 struct isl_sched_node *src, struct isl_sched_node *dst,
3909 __isl_take isl_basic_set *coef, int pos)
3911 int offset;
3912 isl_ctx *ctx;
3913 isl_dim_map *dim_map;
3915 if (!coef)
3916 return isl_stat_error;
3918 ctx = isl_basic_set_get_ctx(coef);
3919 offset = coef_var_offset(coef);
3920 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
3921 if (pos >= 0)
3922 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3923 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3925 return isl_stat_ok;
3928 /* Data structure for keeping track of the data needed
3929 * to exploit non-trivial lineality spaces.
3931 * "any_non_trivial" is true if there are any non-trivial lineality spaces.
3932 * If "any_non_trivial" is not true, then "equivalent" and "mask" may be NULL.
3933 * "equivalent" connects instances to other instances on the same line(s).
3934 * "mask" contains the domain spaces of "equivalent".
3935 * Any instance set not in "mask" does not have a non-trivial lineality space.
3937 struct isl_exploit_lineality_data {
3938 isl_bool any_non_trivial;
3939 isl_union_map *equivalent;
3940 isl_union_set *mask;
3943 /* Data structure collecting information used during the construction
3944 * of an LP for carrying dependences.
3946 * "intra" is a sequence of coefficient constraints for intra-node edges.
3947 * "inter" is a sequence of coefficient constraints for inter-node edges.
3948 * "lineality" contains data used to exploit non-trivial lineality spaces.
3950 struct isl_carry {
3951 isl_basic_set_list *intra;
3952 isl_basic_set_list *inter;
3953 struct isl_exploit_lineality_data lineality;
3956 /* Free all the data stored in "carry".
3958 static void isl_carry_clear(struct isl_carry *carry)
3960 isl_basic_set_list_free(carry->intra);
3961 isl_basic_set_list_free(carry->inter);
3962 isl_union_map_free(carry->lineality.equivalent);
3963 isl_union_set_free(carry->lineality.mask);
3966 /* Return a pointer to the node in "graph" that lives in "space".
3967 * If the requested node has been compressed, then "space"
3968 * corresponds to the compressed space.
3969 * The graph is assumed to have such a node.
3970 * Return NULL in case of error.
3972 * First try and see if "space" is the space of an uncompressed node.
3973 * If so, return that node.
3974 * Otherwise, "space" was constructed by construct_compressed_id and
3975 * contains a user pointer pointing to the node in the tuple id.
3976 * However, this node belongs to the original dependence graph.
3977 * If "graph" is a subgraph of this original dependence graph,
3978 * then the node with the same space still needs to be looked up
3979 * in the current graph.
3981 static struct isl_sched_node *graph_find_compressed_node(isl_ctx *ctx,
3982 struct isl_sched_graph *graph, __isl_keep isl_space *space)
3984 isl_id *id;
3985 struct isl_sched_node *node;
3987 if (!space)
3988 return NULL;
3990 node = graph_find_node(ctx, graph, space);
3991 if (!node)
3992 return NULL;
3993 if (is_node(graph, node))
3994 return node;
3996 id = isl_space_get_tuple_id(space, isl_dim_set);
3997 node = isl_id_get_user(id);
3998 isl_id_free(id);
4000 if (!node)
4001 return NULL;
4003 if (!is_node(graph->root, node))
4004 isl_die(ctx, isl_error_internal,
4005 "space points to invalid node", return NULL);
4006 if (graph != graph->root)
4007 node = graph_find_node(ctx, graph, node->space);
4008 if (!is_node(graph, node))
4009 isl_die(ctx, isl_error_internal,
4010 "unable to find node", return NULL);
4012 return node;
4015 /* Internal data structure for add_all_constraints.
4017 * "graph" is the schedule constraint graph for which an LP problem
4018 * is being constructed.
4019 * "carry_inter" indicates whether inter-node edges should be carried.
4020 * "pos" is the position of the next edge that needs to be carried.
4022 struct isl_add_all_constraints_data {
4023 isl_ctx *ctx;
4024 struct isl_sched_graph *graph;
4025 int carry_inter;
4026 int pos;
4029 /* Add the constraints "coef" derived from an edge from a node to itself
4030 * to data->graph->lp in order to respect the dependences and
4031 * to try and carry them.
4033 * The space of "coef" is of the form
4035 * coefficients[[c_cst] -> S[c_x]]
4037 * with S[c_x] the (compressed) space of the node.
4038 * Extract the node from the space and call add_intra_constraints.
4040 static isl_stat lp_add_intra(__isl_take isl_basic_set *coef, void *user)
4042 struct isl_add_all_constraints_data *data = user;
4043 isl_space *space;
4044 struct isl_sched_node *node;
4046 space = isl_basic_set_get_space(coef);
4047 space = isl_space_range(isl_space_unwrap(space));
4048 node = graph_find_compressed_node(data->ctx, data->graph, space);
4049 isl_space_free(space);
4050 return add_intra_constraints(data->graph, node, coef, data->pos++);
4053 /* Add the constraints "coef" derived from an edge from a node j
4054 * to a node k to data->graph->lp in order to respect the dependences and
4055 * to try and carry them (provided data->carry_inter is set).
4057 * The space of "coef" is of the form
4059 * coefficients[[c_cst, c_n] -> [S_j[c_x] -> S_k[c_y]]]
4061 * with S_j[c_x] and S_k[c_y] the (compressed) spaces of the nodes.
4062 * Extract the nodes from the space and call add_inter_constraints.
4064 static isl_stat lp_add_inter(__isl_take isl_basic_set *coef, void *user)
4066 struct isl_add_all_constraints_data *data = user;
4067 isl_space *space, *dom;
4068 struct isl_sched_node *src, *dst;
4069 int pos;
4071 space = isl_basic_set_get_space(coef);
4072 space = isl_space_unwrap(isl_space_range(isl_space_unwrap(space)));
4073 dom = isl_space_domain(isl_space_copy(space));
4074 src = graph_find_compressed_node(data->ctx, data->graph, dom);
4075 isl_space_free(dom);
4076 space = isl_space_range(space);
4077 dst = graph_find_compressed_node(data->ctx, data->graph, space);
4078 isl_space_free(space);
4080 pos = data->carry_inter ? data->pos++ : -1;
4081 return add_inter_constraints(data->graph, src, dst, coef, pos);
4084 /* Add constraints to graph->lp that force all (conditional) validity
4085 * dependences to be respected and attempt to carry them.
4086 * "intra" is the sequence of coefficient constraints for intra-node edges.
4087 * "inter" is the sequence of coefficient constraints for inter-node edges.
4088 * "carry_inter" indicates whether inter-node edges should be carried or
4089 * only respected.
4091 static isl_stat add_all_constraints(isl_ctx *ctx, struct isl_sched_graph *graph,
4092 __isl_keep isl_basic_set_list *intra,
4093 __isl_keep isl_basic_set_list *inter, int carry_inter)
4095 struct isl_add_all_constraints_data data = { ctx, graph, carry_inter };
4097 data.pos = 0;
4098 if (isl_basic_set_list_foreach(intra, &lp_add_intra, &data) < 0)
4099 return isl_stat_error;
4100 if (isl_basic_set_list_foreach(inter, &lp_add_inter, &data) < 0)
4101 return isl_stat_error;
4102 return isl_stat_ok;
4105 /* Internal data structure for count_all_constraints
4106 * for keeping track of the number of equality and inequality constraints.
4108 struct isl_sched_count {
4109 int n_eq;
4110 int n_ineq;
4113 /* Add the number of equality and inequality constraints of "bset"
4114 * to data->n_eq and data->n_ineq.
4116 static isl_stat bset_update_count(__isl_take isl_basic_set *bset, void *user)
4118 struct isl_sched_count *data = user;
4120 return update_count(bset, 1, &data->n_eq, &data->n_ineq);
4123 /* Count the number of equality and inequality constraints
4124 * that will be added to the carry_lp problem.
4125 * We count each edge exactly once.
4126 * "intra" is the sequence of coefficient constraints for intra-node edges.
4127 * "inter" is the sequence of coefficient constraints for inter-node edges.
4129 static isl_stat count_all_constraints(__isl_keep isl_basic_set_list *intra,
4130 __isl_keep isl_basic_set_list *inter, int *n_eq, int *n_ineq)
4132 struct isl_sched_count data;
4134 data.n_eq = data.n_ineq = 0;
4135 if (isl_basic_set_list_foreach(inter, &bset_update_count, &data) < 0)
4136 return isl_stat_error;
4137 if (isl_basic_set_list_foreach(intra, &bset_update_count, &data) < 0)
4138 return isl_stat_error;
4140 *n_eq = data.n_eq;
4141 *n_ineq = data.n_ineq;
4143 return isl_stat_ok;
4146 /* Construct an LP problem for finding schedule coefficients
4147 * such that the schedule carries as many validity dependences as possible.
4148 * In particular, for each dependence i, we bound the dependence distance
4149 * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
4150 * of all e_i's. Dependences with e_i = 0 in the solution are simply
4151 * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
4152 * "intra" is the sequence of coefficient constraints for intra-node edges.
4153 * "inter" is the sequence of coefficient constraints for inter-node edges.
4154 * "n_edge" is the total number of edges.
4155 * "carry_inter" indicates whether inter-node edges should be carried or
4156 * only respected. That is, if "carry_inter" is not set, then
4157 * no e_i variables are introduced for the inter-node edges.
4159 * All variables of the LP are non-negative. The actual coefficients
4160 * may be negative, so each coefficient is represented as the difference
4161 * of two non-negative variables. The negative part always appears
4162 * immediately before the positive part.
4163 * Other than that, the variables have the following order
4165 * - sum of (1 - e_i) over all edges
4166 * - sum of all c_n coefficients
4167 * (unconstrained when computing non-parametric schedules)
4168 * - sum of positive and negative parts of all c_x coefficients
4169 * - for each edge
4170 * - e_i
4171 * - for each node
4172 * - positive and negative parts of c_i_x, in opposite order
4173 * - c_i_n (if parametric)
4174 * - c_i_0
4176 * The constraints are those from the (validity) edges plus three equalities
4177 * to express the sums and n_edge inequalities to express e_i <= 1.
4179 static isl_stat setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
4180 int n_edge, __isl_keep isl_basic_set_list *intra,
4181 __isl_keep isl_basic_set_list *inter, int carry_inter)
4183 int i;
4184 int k;
4185 isl_space *dim;
4186 unsigned total;
4187 int n_eq, n_ineq;
4189 total = 3 + n_edge;
4190 for (i = 0; i < graph->n; ++i) {
4191 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
4192 node->start = total;
4193 total += 1 + node->nparam + 2 * node->nvar;
4196 if (count_all_constraints(intra, inter, &n_eq, &n_ineq) < 0)
4197 return isl_stat_error;
4199 dim = isl_space_set_alloc(ctx, 0, total);
4200 isl_basic_set_free(graph->lp);
4201 n_eq += 3;
4202 n_ineq += n_edge;
4203 graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
4204 graph->lp = isl_basic_set_set_rational(graph->lp);
4206 k = isl_basic_set_alloc_equality(graph->lp);
4207 if (k < 0)
4208 return isl_stat_error;
4209 isl_seq_clr(graph->lp->eq[k], 1 + total);
4210 isl_int_set_si(graph->lp->eq[k][0], -n_edge);
4211 isl_int_set_si(graph->lp->eq[k][1], 1);
4212 for (i = 0; i < n_edge; ++i)
4213 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
4215 if (add_param_sum_constraint(graph, 1) < 0)
4216 return isl_stat_error;
4217 if (add_var_sum_constraint(graph, 2) < 0)
4218 return isl_stat_error;
4220 for (i = 0; i < n_edge; ++i) {
4221 k = isl_basic_set_alloc_inequality(graph->lp);
4222 if (k < 0)
4223 return isl_stat_error;
4224 isl_seq_clr(graph->lp->ineq[k], 1 + total);
4225 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
4226 isl_int_set_si(graph->lp->ineq[k][0], 1);
4229 if (add_all_constraints(ctx, graph, intra, inter, carry_inter) < 0)
4230 return isl_stat_error;
4232 return isl_stat_ok;
4235 static __isl_give isl_schedule_node *compute_component_schedule(
4236 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4237 int wcc);
4239 /* If the schedule_split_scaled option is set and if the linear
4240 * parts of the scheduling rows for all nodes in the graphs have
4241 * a non-trivial common divisor, then remove this
4242 * common divisor from the linear part.
4243 * Otherwise, insert a band node directly and continue with
4244 * the construction of the schedule.
4246 * If a non-trivial common divisor is found, then
4247 * the linear part is reduced and the remainder is ignored.
4248 * The pieces of the graph that are assigned different remainders
4249 * form (groups of) strongly connected components within
4250 * the scaled down band. If needed, they can therefore
4251 * be ordered along this remainder in a sequence node.
4252 * However, this ordering is not enforced here in order to allow
4253 * the scheduler to combine some of the strongly connected components.
4255 static __isl_give isl_schedule_node *split_scaled(
4256 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4258 int i;
4259 int row;
4260 isl_ctx *ctx;
4261 isl_int gcd, gcd_i;
4263 if (!node)
4264 return NULL;
4266 ctx = isl_schedule_node_get_ctx(node);
4267 if (!ctx->opt->schedule_split_scaled)
4268 return compute_next_band(node, graph, 0);
4269 if (graph->n <= 1)
4270 return compute_next_band(node, graph, 0);
4272 isl_int_init(gcd);
4273 isl_int_init(gcd_i);
4275 isl_int_set_si(gcd, 0);
4277 row = isl_mat_rows(graph->node[0].sched) - 1;
4279 for (i = 0; i < graph->n; ++i) {
4280 struct isl_sched_node *node = &graph->node[i];
4281 int cols = isl_mat_cols(node->sched);
4283 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
4284 isl_int_gcd(gcd, gcd, gcd_i);
4287 isl_int_clear(gcd_i);
4289 if (isl_int_cmp_si(gcd, 1) <= 0) {
4290 isl_int_clear(gcd);
4291 return compute_next_band(node, graph, 0);
4294 for (i = 0; i < graph->n; ++i) {
4295 struct isl_sched_node *node = &graph->node[i];
4297 isl_int_fdiv_q(node->sched->row[row][0],
4298 node->sched->row[row][0], gcd);
4299 isl_int_mul(node->sched->row[row][0],
4300 node->sched->row[row][0], gcd);
4301 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
4302 if (!node->sched)
4303 goto error;
4306 isl_int_clear(gcd);
4308 return compute_next_band(node, graph, 0);
4309 error:
4310 isl_int_clear(gcd);
4311 return isl_schedule_node_free(node);
4314 /* Is the schedule row "sol" trivial on node "node"?
4315 * That is, is the solution zero on the dimensions linearly independent of
4316 * the previously found solutions?
4317 * Return 1 if the solution is trivial, 0 if it is not and -1 on error.
4319 * Each coefficient is represented as the difference between
4320 * two non-negative values in "sol".
4321 * We construct the schedule row s and check if it is linearly
4322 * independent of previously computed schedule rows
4323 * by computing T s, with T the linear combinations that are zero
4324 * on linearly dependent schedule rows.
4325 * If the result consists of all zeros, then the solution is trivial.
4327 static int is_trivial(struct isl_sched_node *node, __isl_keep isl_vec *sol)
4329 int trivial;
4330 isl_vec *node_sol;
4332 if (!sol)
4333 return -1;
4334 if (node->nvar == node->rank)
4335 return 0;
4337 node_sol = extract_var_coef(node, sol);
4338 node_sol = isl_mat_vec_product(isl_mat_copy(node->indep), node_sol);
4339 if (!node_sol)
4340 return -1;
4342 trivial = isl_seq_first_non_zero(node_sol->el,
4343 node->nvar - node->rank) == -1;
4345 isl_vec_free(node_sol);
4347 return trivial;
4350 /* Is the schedule row "sol" trivial on any node where it should
4351 * not be trivial?
4352 * Return 1 if any solution is trivial, 0 if they are not and -1 on error.
4354 static int is_any_trivial(struct isl_sched_graph *graph,
4355 __isl_keep isl_vec *sol)
4357 int i;
4359 for (i = 0; i < graph->n; ++i) {
4360 struct isl_sched_node *node = &graph->node[i];
4361 int trivial;
4363 if (!needs_row(graph, node))
4364 continue;
4365 trivial = is_trivial(node, sol);
4366 if (trivial < 0 || trivial)
4367 return trivial;
4370 return 0;
4373 /* Does the schedule represented by "sol" perform loop coalescing on "node"?
4374 * If so, return the position of the coalesced dimension.
4375 * Otherwise, return node->nvar or -1 on error.
4377 * In particular, look for pairs of coefficients c_i and c_j such that
4378 * |c_j/c_i| > ceil(size_i/2), i.e., |c_j| > |c_i * ceil(size_i/2)|.
4379 * If any such pair is found, then return i.
4380 * If size_i is infinity, then no check on c_i needs to be performed.
4382 static int find_node_coalescing(struct isl_sched_node *node,
4383 __isl_keep isl_vec *sol)
4385 int i, j;
4386 isl_int max;
4387 isl_vec *csol;
4389 if (node->nvar <= 1)
4390 return node->nvar;
4392 csol = extract_var_coef(node, sol);
4393 if (!csol)
4394 return -1;
4395 isl_int_init(max);
4396 for (i = 0; i < node->nvar; ++i) {
4397 isl_val *v;
4399 if (isl_int_is_zero(csol->el[i]))
4400 continue;
4401 v = isl_multi_val_get_val(node->sizes, i);
4402 if (!v)
4403 goto error;
4404 if (!isl_val_is_int(v)) {
4405 isl_val_free(v);
4406 continue;
4408 v = isl_val_div_ui(v, 2);
4409 v = isl_val_ceil(v);
4410 if (!v)
4411 goto error;
4412 isl_int_mul(max, v->n, csol->el[i]);
4413 isl_val_free(v);
4415 for (j = 0; j < node->nvar; ++j) {
4416 if (j == i)
4417 continue;
4418 if (isl_int_abs_gt(csol->el[j], max))
4419 break;
4421 if (j < node->nvar)
4422 break;
4425 isl_int_clear(max);
4426 isl_vec_free(csol);
4427 return i;
4428 error:
4429 isl_int_clear(max);
4430 isl_vec_free(csol);
4431 return -1;
4434 /* Force the schedule coefficient at position "pos" of "node" to be zero
4435 * in "tl".
4436 * The coefficient is encoded as the difference between two non-negative
4437 * variables. Force these two variables to have the same value.
4439 static __isl_give isl_tab_lexmin *zero_out_node_coef(
4440 __isl_take isl_tab_lexmin *tl, struct isl_sched_node *node, int pos)
4442 int dim;
4443 isl_ctx *ctx;
4444 isl_vec *eq;
4446 ctx = isl_space_get_ctx(node->space);
4447 dim = isl_tab_lexmin_dim(tl);
4448 if (dim < 0)
4449 return isl_tab_lexmin_free(tl);
4450 eq = isl_vec_alloc(ctx, 1 + dim);
4451 eq = isl_vec_clr(eq);
4452 if (!eq)
4453 return isl_tab_lexmin_free(tl);
4455 pos = 1 + node_var_coef_pos(node, pos);
4456 isl_int_set_si(eq->el[pos], 1);
4457 isl_int_set_si(eq->el[pos + 1], -1);
4458 tl = isl_tab_lexmin_add_eq(tl, eq->el);
4459 isl_vec_free(eq);
4461 return tl;
4464 /* Return the lexicographically smallest rational point in the basic set
4465 * from which "tl" was constructed, double checking that this input set
4466 * was not empty.
4468 static __isl_give isl_vec *non_empty_solution(__isl_keep isl_tab_lexmin *tl)
4470 isl_vec *sol;
4472 sol = isl_tab_lexmin_get_solution(tl);
4473 if (!sol)
4474 return NULL;
4475 if (sol->size == 0)
4476 isl_die(isl_vec_get_ctx(sol), isl_error_internal,
4477 "error in schedule construction",
4478 return isl_vec_free(sol));
4479 return sol;
4482 /* Does the solution "sol" of the LP problem constructed by setup_carry_lp
4483 * carry any of the "n_edge" groups of dependences?
4484 * The value in the first position is the sum of (1 - e_i) over all "n_edge"
4485 * edges, with 0 <= e_i <= 1 equal to 1 when the dependences represented
4486 * by the edge are carried by the solution.
4487 * If the sum of the (1 - e_i) is smaller than "n_edge" then at least
4488 * one of those is carried.
4490 * Note that despite the fact that the problem is solved using a rational
4491 * solver, the solution is guaranteed to be integral.
4492 * Specifically, the dependence distance lower bounds e_i (and therefore
4493 * also their sum) are integers. See Lemma 5 of [1].
4495 * Any potential denominator of the sum is cleared by this function.
4496 * The denominator is not relevant for any of the other elements
4497 * in the solution.
4499 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4500 * Problem, Part II: Multi-Dimensional Time.
4501 * In Intl. Journal of Parallel Programming, 1992.
4503 static int carries_dependences(__isl_keep isl_vec *sol, int n_edge)
4505 isl_int_divexact(sol->el[1], sol->el[1], sol->el[0]);
4506 isl_int_set_si(sol->el[0], 1);
4507 return isl_int_cmp_si(sol->el[1], n_edge) < 0;
4510 /* Return the lexicographically smallest rational point in "lp",
4511 * assuming that all variables are non-negative and performing some
4512 * additional sanity checks.
4513 * If "want_integral" is set, then compute the lexicographically smallest
4514 * integer point instead.
4515 * In particular, "lp" should not be empty by construction.
4516 * Double check that this is the case.
4517 * If dependences are not carried for any of the "n_edge" edges,
4518 * then return an empty vector.
4520 * If the schedule_treat_coalescing option is set and
4521 * if the computed schedule performs loop coalescing on a given node,
4522 * i.e., if it is of the form
4524 * c_i i + c_j j + ...
4526 * with |c_j/c_i| >= size_i, then force the coefficient c_i to be zero
4527 * to cut out this solution. Repeat this process until no more loop
4528 * coalescing occurs or until no more dependences can be carried.
4529 * In the latter case, revert to the previously computed solution.
4531 * If the caller requests an integral solution and if coalescing should
4532 * be treated, then perform the coalescing treatment first as
4533 * an integral solution computed before coalescing treatment
4534 * would carry the same number of edges and would therefore probably
4535 * also be coalescing.
4537 * To allow the coalescing treatment to be performed first,
4538 * the initial solution is allowed to be rational and it is only
4539 * cut out (if needed) in the next iteration, if no coalescing measures
4540 * were taken.
4542 static __isl_give isl_vec *non_neg_lexmin(struct isl_sched_graph *graph,
4543 __isl_take isl_basic_set *lp, int n_edge, int want_integral)
4545 int i, pos, cut;
4546 isl_ctx *ctx;
4547 isl_tab_lexmin *tl;
4548 isl_vec *sol = NULL, *prev;
4549 int treat_coalescing;
4550 int try_again;
4552 if (!lp)
4553 return NULL;
4554 ctx = isl_basic_set_get_ctx(lp);
4555 treat_coalescing = isl_options_get_schedule_treat_coalescing(ctx);
4556 tl = isl_tab_lexmin_from_basic_set(lp);
4558 cut = 0;
4559 do {
4560 int integral;
4562 try_again = 0;
4563 if (cut)
4564 tl = isl_tab_lexmin_cut_to_integer(tl);
4565 prev = sol;
4566 sol = non_empty_solution(tl);
4567 if (!sol)
4568 goto error;
4570 integral = isl_int_is_one(sol->el[0]);
4571 if (!carries_dependences(sol, n_edge)) {
4572 if (!prev)
4573 prev = isl_vec_alloc(ctx, 0);
4574 isl_vec_free(sol);
4575 sol = prev;
4576 break;
4578 prev = isl_vec_free(prev);
4579 cut = want_integral && !integral;
4580 if (cut)
4581 try_again = 1;
4582 if (!treat_coalescing)
4583 continue;
4584 for (i = 0; i < graph->n; ++i) {
4585 struct isl_sched_node *node = &graph->node[i];
4587 pos = find_node_coalescing(node, sol);
4588 if (pos < 0)
4589 goto error;
4590 if (pos < node->nvar)
4591 break;
4593 if (i < graph->n) {
4594 try_again = 1;
4595 tl = zero_out_node_coef(tl, &graph->node[i], pos);
4596 cut = 0;
4598 } while (try_again);
4600 isl_tab_lexmin_free(tl);
4602 return sol;
4603 error:
4604 isl_tab_lexmin_free(tl);
4605 isl_vec_free(prev);
4606 isl_vec_free(sol);
4607 return NULL;
4610 /* If "edge" is an edge from a node to itself, then add the corresponding
4611 * dependence relation to "umap".
4612 * If "node" has been compressed, then the dependence relation
4613 * is also compressed first.
4615 static __isl_give isl_union_map *add_intra(__isl_take isl_union_map *umap,
4616 struct isl_sched_edge *edge)
4618 isl_map *map;
4619 struct isl_sched_node *node = edge->src;
4621 if (edge->src != edge->dst)
4622 return umap;
4624 map = isl_map_copy(edge->map);
4625 if (node->compressed) {
4626 map = isl_map_preimage_domain_multi_aff(map,
4627 isl_multi_aff_copy(node->decompress));
4628 map = isl_map_preimage_range_multi_aff(map,
4629 isl_multi_aff_copy(node->decompress));
4631 umap = isl_union_map_add_map(umap, map);
4632 return umap;
4635 /* If "edge" is an edge from a node to another node, then add the corresponding
4636 * dependence relation to "umap".
4637 * If the source or destination nodes of "edge" have been compressed,
4638 * then the dependence relation is also compressed first.
4640 static __isl_give isl_union_map *add_inter(__isl_take isl_union_map *umap,
4641 struct isl_sched_edge *edge)
4643 isl_map *map;
4645 if (edge->src == edge->dst)
4646 return umap;
4648 map = isl_map_copy(edge->map);
4649 if (edge->src->compressed)
4650 map = isl_map_preimage_domain_multi_aff(map,
4651 isl_multi_aff_copy(edge->src->decompress));
4652 if (edge->dst->compressed)
4653 map = isl_map_preimage_range_multi_aff(map,
4654 isl_multi_aff_copy(edge->dst->decompress));
4655 umap = isl_union_map_add_map(umap, map);
4656 return umap;
4659 /* Internal data structure used by union_drop_coalescing_constraints
4660 * to collect bounds on all relevant statements.
4662 * "graph" is the schedule constraint graph for which an LP problem
4663 * is being constructed.
4664 * "bounds" collects the bounds.
4666 struct isl_collect_bounds_data {
4667 isl_ctx *ctx;
4668 struct isl_sched_graph *graph;
4669 isl_union_set *bounds;
4672 /* Add the size bounds for the node with instance deltas in "set"
4673 * to data->bounds.
4675 static isl_stat collect_bounds(__isl_take isl_set *set, void *user)
4677 struct isl_collect_bounds_data *data = user;
4678 struct isl_sched_node *node;
4679 isl_space *space;
4680 isl_set *bounds;
4682 space = isl_set_get_space(set);
4683 isl_set_free(set);
4685 node = graph_find_compressed_node(data->ctx, data->graph, space);
4686 isl_space_free(space);
4688 bounds = isl_set_from_basic_set(get_size_bounds(node));
4689 data->bounds = isl_union_set_add_set(data->bounds, bounds);
4691 return isl_stat_ok;
4694 /* Drop some constraints from "delta" that could be exploited
4695 * to construct loop coalescing schedules.
4696 * In particular, drop those constraint that bound the difference
4697 * to the size of the domain.
4698 * Do this for each set/node in "delta" separately.
4699 * The parameters are assumed to have been projected out by the caller.
4701 static __isl_give isl_union_set *union_drop_coalescing_constraints(isl_ctx *ctx,
4702 struct isl_sched_graph *graph, __isl_take isl_union_set *delta)
4704 struct isl_collect_bounds_data data = { ctx, graph };
4706 data.bounds = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4707 if (isl_union_set_foreach_set(delta, &collect_bounds, &data) < 0)
4708 data.bounds = isl_union_set_free(data.bounds);
4709 delta = isl_union_set_plain_gist(delta, data.bounds);
4711 return delta;
4714 /* Given a non-trivial lineality space "lineality", add the corresponding
4715 * universe set to data->mask and add a map from elements to
4716 * other elements along the lines in "lineality" to data->equivalent.
4717 * If this is the first time this function gets called
4718 * (data->any_non_trivial is still false), then set data->any_non_trivial and
4719 * initialize data->mask and data->equivalent.
4721 * In particular, if the lineality space is defined by equality constraints
4723 * E x = 0
4725 * then construct an affine mapping
4727 * f : x -> E x
4729 * and compute the equivalence relation of having the same image under f:
4731 * { x -> x' : E x = E x' }
4733 static isl_stat add_non_trivial_lineality(__isl_take isl_basic_set *lineality,
4734 struct isl_exploit_lineality_data *data)
4736 isl_mat *eq;
4737 isl_space *space;
4738 isl_set *univ;
4739 isl_multi_aff *ma;
4740 isl_multi_pw_aff *mpa;
4741 isl_map *map;
4742 int n;
4744 if (isl_basic_set_check_no_locals(lineality) < 0)
4745 goto error;
4747 space = isl_basic_set_get_space(lineality);
4748 if (!data->any_non_trivial) {
4749 data->equivalent = isl_union_map_empty(isl_space_copy(space));
4750 data->mask = isl_union_set_empty(isl_space_copy(space));
4752 data->any_non_trivial = isl_bool_true;
4754 univ = isl_set_universe(isl_space_copy(space));
4755 data->mask = isl_union_set_add_set(data->mask, univ);
4757 eq = isl_basic_set_extract_equalities(lineality);
4758 n = isl_mat_rows(eq);
4759 eq = isl_mat_insert_zero_rows(eq, 0, 1);
4760 eq = isl_mat_set_element_si(eq, 0, 0, 1);
4761 space = isl_space_from_domain(space);
4762 space = isl_space_add_dims(space, isl_dim_out, n);
4763 ma = isl_multi_aff_from_aff_mat(space, eq);
4764 mpa = isl_multi_pw_aff_from_multi_aff(ma);
4765 map = isl_multi_pw_aff_eq_map(mpa, isl_multi_pw_aff_copy(mpa));
4766 data->equivalent = isl_union_map_add_map(data->equivalent, map);
4768 isl_basic_set_free(lineality);
4769 return isl_stat_ok;
4770 error:
4771 isl_basic_set_free(lineality);
4772 return isl_stat_error;
4775 /* Check if the lineality space "set" is non-trivial (i.e., is not just
4776 * the origin or, in other words, satisfies a number of equality constraints
4777 * that is smaller than the dimension of the set).
4778 * If so, extend data->mask and data->equivalent accordingly.
4780 * The input should not have any local variables already, but
4781 * isl_set_remove_divs is called to make sure it does not.
4783 static isl_stat add_lineality(__isl_take isl_set *set, void *user)
4785 struct isl_exploit_lineality_data *data = user;
4786 isl_basic_set *hull;
4787 int dim, n_eq;
4789 set = isl_set_remove_divs(set);
4790 hull = isl_set_unshifted_simple_hull(set);
4791 dim = isl_basic_set_dim(hull, isl_dim_set);
4792 n_eq = isl_basic_set_n_equality(hull);
4793 if (!hull)
4794 return isl_stat_error;
4795 if (dim != n_eq)
4796 return add_non_trivial_lineality(hull, data);
4797 isl_basic_set_free(hull);
4798 return isl_stat_ok;
4801 /* Check if the difference set on intra-node schedule constraints "intra"
4802 * has any non-trivial lineality space.
4803 * If so, then extend the difference set to a difference set
4804 * on equivalent elements. That is, if "intra" is
4806 * { y - x : (x,y) \in V }
4808 * and elements are equivalent if they have the same image under f,
4809 * then return
4811 * { y' - x' : (x,y) \in V and f(x) = f(x') and f(y) = f(y') }
4813 * or, since f is linear,
4815 * { y' - x' : (x,y) \in V and f(y - x) = f(y' - x') }
4817 * The results of the search for non-trivial lineality spaces is stored
4818 * in "data".
4820 static __isl_give isl_union_set *exploit_intra_lineality(
4821 __isl_take isl_union_set *intra,
4822 struct isl_exploit_lineality_data *data)
4824 isl_union_set *lineality;
4825 isl_union_set *uset;
4827 data->any_non_trivial = isl_bool_false;
4828 lineality = isl_union_set_copy(intra);
4829 lineality = isl_union_set_combined_lineality_space(lineality);
4830 if (isl_union_set_foreach_set(lineality, &add_lineality, data) < 0)
4831 data->any_non_trivial = isl_bool_error;
4832 isl_union_set_free(lineality);
4834 if (data->any_non_trivial < 0)
4835 return isl_union_set_free(intra);
4836 if (!data->any_non_trivial)
4837 return intra;
4839 uset = isl_union_set_copy(intra);
4840 intra = isl_union_set_subtract(intra, isl_union_set_copy(data->mask));
4841 uset = isl_union_set_apply(uset, isl_union_map_copy(data->equivalent));
4842 intra = isl_union_set_union(intra, uset);
4844 intra = isl_union_set_remove_divs(intra);
4846 return intra;
4849 /* If the difference set on intra-node schedule constraints was found to have
4850 * any non-trivial lineality space by exploit_intra_lineality,
4851 * as recorded in "data", then extend the inter-node
4852 * schedule constraints "inter" to schedule constraints on equivalent elements.
4853 * That is, if "inter" is V and
4854 * elements are equivalent if they have the same image under f, then return
4856 * { (x', y') : (x,y) \in V and f(x) = f(x') and f(y) = f(y') }
4858 static __isl_give isl_union_map *exploit_inter_lineality(
4859 __isl_take isl_union_map *inter,
4860 struct isl_exploit_lineality_data *data)
4862 isl_union_map *umap;
4864 if (data->any_non_trivial < 0)
4865 return isl_union_map_free(inter);
4866 if (!data->any_non_trivial)
4867 return inter;
4869 umap = isl_union_map_copy(inter);
4870 inter = isl_union_map_subtract_range(inter,
4871 isl_union_set_copy(data->mask));
4872 umap = isl_union_map_apply_range(umap,
4873 isl_union_map_copy(data->equivalent));
4874 inter = isl_union_map_union(inter, umap);
4875 umap = isl_union_map_copy(inter);
4876 inter = isl_union_map_subtract_domain(inter,
4877 isl_union_set_copy(data->mask));
4878 umap = isl_union_map_apply_range(isl_union_map_copy(data->equivalent),
4879 umap);
4880 inter = isl_union_map_union(inter, umap);
4882 inter = isl_union_map_remove_divs(inter);
4884 return inter;
4887 /* For each (conditional) validity edge in "graph",
4888 * add the corresponding dependence relation using "add"
4889 * to a collection of dependence relations and return the result.
4890 * If "coincidence" is set, then coincidence edges are considered as well.
4892 static __isl_give isl_union_map *collect_validity(struct isl_sched_graph *graph,
4893 __isl_give isl_union_map *(*add)(__isl_take isl_union_map *umap,
4894 struct isl_sched_edge *edge), int coincidence)
4896 int i;
4897 isl_space *space;
4898 isl_union_map *umap;
4900 space = isl_space_copy(graph->node[0].space);
4901 umap = isl_union_map_empty(space);
4903 for (i = 0; i < graph->n_edge; ++i) {
4904 struct isl_sched_edge *edge = &graph->edge[i];
4906 if (!is_any_validity(edge) &&
4907 (!coincidence || !is_coincidence(edge)))
4908 continue;
4910 umap = add(umap, edge);
4913 return umap;
4916 /* For each dependence relation on a (conditional) validity edge
4917 * from a node to itself,
4918 * construct the set of coefficients of valid constraints for elements
4919 * in that dependence relation and collect the results.
4920 * If "coincidence" is set, then coincidence edges are considered as well.
4922 * In particular, for each dependence relation R, constraints
4923 * on coefficients (c_0, c_x) are constructed such that
4925 * c_0 + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
4927 * If the schedule_treat_coalescing option is set, then some constraints
4928 * that could be exploited to construct coalescing schedules
4929 * are removed before the dual is computed, but after the parameters
4930 * have been projected out.
4931 * The entire computation is essentially the same as that performed
4932 * by intra_coefficients, except that it operates on multiple
4933 * edges together and that the parameters are always projected out.
4935 * Additionally, exploit any non-trivial lineality space
4936 * in the difference set after removing coalescing constraints and
4937 * store the results of the non-trivial lineality space detection in "data".
4938 * The procedure is currently run unconditionally, but it is unlikely
4939 * to find any non-trivial lineality spaces if no coalescing constraints
4940 * have been removed.
4942 * Note that if a dependence relation is a union of basic maps,
4943 * then each basic map needs to be treated individually as it may only
4944 * be possible to carry the dependences expressed by some of those
4945 * basic maps and not all of them.
4946 * The collected validity constraints are therefore not coalesced and
4947 * it is assumed that they are not coalesced automatically.
4948 * Duplicate basic maps can be removed, however.
4949 * In particular, if the same basic map appears as a disjunct
4950 * in multiple edges, then it only needs to be carried once.
4952 static __isl_give isl_basic_set_list *collect_intra_validity(isl_ctx *ctx,
4953 struct isl_sched_graph *graph, int coincidence,
4954 struct isl_exploit_lineality_data *data)
4956 isl_union_map *intra;
4957 isl_union_set *delta;
4958 isl_basic_set_list *list;
4960 intra = collect_validity(graph, &add_intra, coincidence);
4961 delta = isl_union_map_deltas(intra);
4962 delta = isl_union_set_project_out_all_params(delta);
4963 delta = isl_union_set_remove_divs(delta);
4964 if (isl_options_get_schedule_treat_coalescing(ctx))
4965 delta = union_drop_coalescing_constraints(ctx, graph, delta);
4966 delta = exploit_intra_lineality(delta, data);
4967 list = isl_union_set_get_basic_set_list(delta);
4968 isl_union_set_free(delta);
4970 return isl_basic_set_list_coefficients(list);
4973 /* For each dependence relation on a (conditional) validity edge
4974 * from a node to some other node,
4975 * construct the set of coefficients of valid constraints for elements
4976 * in that dependence relation and collect the results.
4977 * If "coincidence" is set, then coincidence edges are considered as well.
4979 * In particular, for each dependence relation R, constraints
4980 * on coefficients (c_0, c_n, c_x, c_y) are constructed such that
4982 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
4984 * This computation is essentially the same as that performed
4985 * by inter_coefficients, except that it operates on multiple
4986 * edges together.
4988 * Additionally, exploit any non-trivial lineality space
4989 * that may have been discovered by collect_intra_validity
4990 * (as stored in "data").
4992 * Note that if a dependence relation is a union of basic maps,
4993 * then each basic map needs to be treated individually as it may only
4994 * be possible to carry the dependences expressed by some of those
4995 * basic maps and not all of them.
4996 * The collected validity constraints are therefore not coalesced and
4997 * it is assumed that they are not coalesced automatically.
4998 * Duplicate basic maps can be removed, however.
4999 * In particular, if the same basic map appears as a disjunct
5000 * in multiple edges, then it only needs to be carried once.
5002 static __isl_give isl_basic_set_list *collect_inter_validity(
5003 struct isl_sched_graph *graph, int coincidence,
5004 struct isl_exploit_lineality_data *data)
5006 isl_union_map *inter;
5007 isl_union_set *wrap;
5008 isl_basic_set_list *list;
5010 inter = collect_validity(graph, &add_inter, coincidence);
5011 inter = exploit_inter_lineality(inter, data);
5012 inter = isl_union_map_remove_divs(inter);
5013 wrap = isl_union_map_wrap(inter);
5014 list = isl_union_set_get_basic_set_list(wrap);
5015 isl_union_set_free(wrap);
5016 return isl_basic_set_list_coefficients(list);
5019 /* Construct an LP problem for finding schedule coefficients
5020 * such that the schedule carries as many of the "n_edge" groups of
5021 * dependences as possible based on the corresponding coefficient
5022 * constraints and return the lexicographically smallest non-trivial solution.
5023 * "intra" is the sequence of coefficient constraints for intra-node edges.
5024 * "inter" is the sequence of coefficient constraints for inter-node edges.
5025 * If "want_integral" is set, then compute an integral solution
5026 * for the coefficients rather than using the numerators
5027 * of a rational solution.
5028 * "carry_inter" indicates whether inter-node edges should be carried or
5029 * only respected.
5031 * If none of the "n_edge" groups can be carried
5032 * then return an empty vector.
5034 static __isl_give isl_vec *compute_carrying_sol_coef(isl_ctx *ctx,
5035 struct isl_sched_graph *graph, int n_edge,
5036 __isl_keep isl_basic_set_list *intra,
5037 __isl_keep isl_basic_set_list *inter, int want_integral,
5038 int carry_inter)
5040 isl_basic_set *lp;
5042 if (setup_carry_lp(ctx, graph, n_edge, intra, inter, carry_inter) < 0)
5043 return NULL;
5045 lp = isl_basic_set_copy(graph->lp);
5046 return non_neg_lexmin(graph, lp, n_edge, want_integral);
5049 /* Construct an LP problem for finding schedule coefficients
5050 * such that the schedule carries as many of the validity dependences
5051 * as possible and
5052 * return the lexicographically smallest non-trivial solution.
5053 * If "fallback" is set, then the carrying is performed as a fallback
5054 * for the Pluto-like scheduler.
5055 * If "coincidence" is set, then try and carry coincidence edges as well.
5057 * The variable "n_edge" stores the number of groups that should be carried.
5058 * If none of the "n_edge" groups can be carried
5059 * then return an empty vector.
5060 * If, moreover, "n_edge" is zero, then the LP problem does not even
5061 * need to be constructed.
5063 * If a fallback solution is being computed, then compute an integral solution
5064 * for the coefficients rather than using the numerators
5065 * of a rational solution.
5067 * If a fallback solution is being computed, if there are any intra-node
5068 * dependences, and if requested by the user, then first try
5069 * to only carry those intra-node dependences.
5070 * If this fails to carry any dependences, then try again
5071 * with the inter-node dependences included.
5073 static __isl_give isl_vec *compute_carrying_sol(isl_ctx *ctx,
5074 struct isl_sched_graph *graph, int fallback, int coincidence)
5076 int n_intra, n_inter;
5077 int n_edge;
5078 struct isl_carry carry = { 0 };
5079 isl_vec *sol;
5081 carry.intra = collect_intra_validity(ctx, graph, coincidence,
5082 &carry.lineality);
5083 carry.inter = collect_inter_validity(graph, coincidence,
5084 &carry.lineality);
5085 if (!carry.intra || !carry.inter)
5086 goto error;
5087 n_intra = isl_basic_set_list_n_basic_set(carry.intra);
5088 n_inter = isl_basic_set_list_n_basic_set(carry.inter);
5090 if (fallback && n_intra > 0 &&
5091 isl_options_get_schedule_carry_self_first(ctx)) {
5092 sol = compute_carrying_sol_coef(ctx, graph, n_intra,
5093 carry.intra, carry.inter, fallback, 0);
5094 if (!sol || sol->size != 0 || n_inter == 0) {
5095 isl_carry_clear(&carry);
5096 return sol;
5098 isl_vec_free(sol);
5101 n_edge = n_intra + n_inter;
5102 if (n_edge == 0) {
5103 isl_carry_clear(&carry);
5104 return isl_vec_alloc(ctx, 0);
5107 sol = compute_carrying_sol_coef(ctx, graph, n_edge,
5108 carry.intra, carry.inter, fallback, 1);
5109 isl_carry_clear(&carry);
5110 return sol;
5111 error:
5112 isl_carry_clear(&carry);
5113 return NULL;
5116 /* Construct a schedule row for each node such that as many validity dependences
5117 * as possible are carried and then continue with the next band.
5118 * If "fallback" is set, then the carrying is performed as a fallback
5119 * for the Pluto-like scheduler.
5120 * If "coincidence" is set, then try and carry coincidence edges as well.
5122 * If there are no validity dependences, then no dependence can be carried and
5123 * the procedure is guaranteed to fail. If there is more than one component,
5124 * then try computing a schedule on each component separately
5125 * to prevent or at least postpone this failure.
5127 * If a schedule row is computed, then check that dependences are carried
5128 * for at least one of the edges.
5130 * If the computed schedule row turns out to be trivial on one or
5131 * more nodes where it should not be trivial, then we throw it away
5132 * and try again on each component separately.
5134 * If there is only one component, then we accept the schedule row anyway,
5135 * but we do not consider it as a complete row and therefore do not
5136 * increment graph->n_row. Note that the ranks of the nodes that
5137 * do get a non-trivial schedule part will get updated regardless and
5138 * graph->maxvar is computed based on these ranks. The test for
5139 * whether more schedule rows are required in compute_schedule_wcc
5140 * is therefore not affected.
5142 * Insert a band corresponding to the schedule row at position "node"
5143 * of the schedule tree and continue with the construction of the schedule.
5144 * This insertion and the continued construction is performed by split_scaled
5145 * after optionally checking for non-trivial common divisors.
5147 static __isl_give isl_schedule_node *carry(__isl_take isl_schedule_node *node,
5148 struct isl_sched_graph *graph, int fallback, int coincidence)
5150 int trivial;
5151 isl_ctx *ctx;
5152 isl_vec *sol;
5154 if (!node)
5155 return NULL;
5157 ctx = isl_schedule_node_get_ctx(node);
5158 sol = compute_carrying_sol(ctx, graph, fallback, coincidence);
5159 if (!sol)
5160 return isl_schedule_node_free(node);
5161 if (sol->size == 0) {
5162 isl_vec_free(sol);
5163 if (graph->scc > 1)
5164 return compute_component_schedule(node, graph, 1);
5165 isl_die(ctx, isl_error_unknown, "unable to carry dependences",
5166 return isl_schedule_node_free(node));
5169 trivial = is_any_trivial(graph, sol);
5170 if (trivial < 0) {
5171 sol = isl_vec_free(sol);
5172 } else if (trivial && graph->scc > 1) {
5173 isl_vec_free(sol);
5174 return compute_component_schedule(node, graph, 1);
5177 if (update_schedule(graph, sol, 0) < 0)
5178 return isl_schedule_node_free(node);
5179 if (trivial)
5180 graph->n_row--;
5182 return split_scaled(node, graph);
5185 /* Construct a schedule row for each node such that as many validity dependences
5186 * as possible are carried and then continue with the next band.
5187 * Do so as a fallback for the Pluto-like scheduler.
5188 * If "coincidence" is set, then try and carry coincidence edges as well.
5190 static __isl_give isl_schedule_node *carry_fallback(
5191 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5192 int coincidence)
5194 return carry(node, graph, 1, coincidence);
5197 /* Construct a schedule row for each node such that as many validity dependences
5198 * as possible are carried and then continue with the next band.
5199 * Do so for the case where the Feautrier scheduler was selected
5200 * by the user.
5202 static __isl_give isl_schedule_node *carry_feautrier(
5203 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5205 return carry(node, graph, 0, 0);
5208 /* Construct a schedule row for each node such that as many validity dependences
5209 * as possible are carried and then continue with the next band.
5210 * Do so as a fallback for the Pluto-like scheduler.
5212 static __isl_give isl_schedule_node *carry_dependences(
5213 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5215 return carry_fallback(node, graph, 0);
5218 /* Construct a schedule row for each node such that as many validity or
5219 * coincidence dependences as possible are carried and
5220 * then continue with the next band.
5221 * Do so as a fallback for the Pluto-like scheduler.
5223 static __isl_give isl_schedule_node *carry_coincidence(
5224 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5226 return carry_fallback(node, graph, 1);
5229 /* Topologically sort statements mapped to the same schedule iteration
5230 * and add insert a sequence node in front of "node"
5231 * corresponding to this order.
5232 * If "initialized" is set, then it may be assumed that compute_maxvar
5233 * has been called on the current band. Otherwise, call
5234 * compute_maxvar if and before carry_dependences gets called.
5236 * If it turns out to be impossible to sort the statements apart,
5237 * because different dependences impose different orderings
5238 * on the statements, then we extend the schedule such that
5239 * it carries at least one more dependence.
5241 static __isl_give isl_schedule_node *sort_statements(
5242 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5243 int initialized)
5245 isl_ctx *ctx;
5246 isl_union_set_list *filters;
5248 if (!node)
5249 return NULL;
5251 ctx = isl_schedule_node_get_ctx(node);
5252 if (graph->n < 1)
5253 isl_die(ctx, isl_error_internal,
5254 "graph should have at least one node",
5255 return isl_schedule_node_free(node));
5257 if (graph->n == 1)
5258 return node;
5260 if (update_edges(ctx, graph) < 0)
5261 return isl_schedule_node_free(node);
5263 if (graph->n_edge == 0)
5264 return node;
5266 if (detect_sccs(ctx, graph) < 0)
5267 return isl_schedule_node_free(node);
5269 next_band(graph);
5270 if (graph->scc < graph->n) {
5271 if (!initialized && compute_maxvar(graph) < 0)
5272 return isl_schedule_node_free(node);
5273 return carry_dependences(node, graph);
5276 filters = extract_sccs(ctx, graph);
5277 node = isl_schedule_node_insert_sequence(node, filters);
5279 return node;
5282 /* Are there any (non-empty) (conditional) validity edges in the graph?
5284 static int has_validity_edges(struct isl_sched_graph *graph)
5286 int i;
5288 for (i = 0; i < graph->n_edge; ++i) {
5289 int empty;
5291 empty = isl_map_plain_is_empty(graph->edge[i].map);
5292 if (empty < 0)
5293 return -1;
5294 if (empty)
5295 continue;
5296 if (is_any_validity(&graph->edge[i]))
5297 return 1;
5300 return 0;
5303 /* Should we apply a Feautrier step?
5304 * That is, did the user request the Feautrier algorithm and are
5305 * there any validity dependences (left)?
5307 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
5309 if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
5310 return 0;
5312 return has_validity_edges(graph);
5315 /* Compute a schedule for a connected dependence graph using Feautrier's
5316 * multi-dimensional scheduling algorithm and return the updated schedule node.
5318 * The original algorithm is described in [1].
5319 * The main idea is to minimize the number of scheduling dimensions, by
5320 * trying to satisfy as many dependences as possible per scheduling dimension.
5322 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
5323 * Problem, Part II: Multi-Dimensional Time.
5324 * In Intl. Journal of Parallel Programming, 1992.
5326 static __isl_give isl_schedule_node *compute_schedule_wcc_feautrier(
5327 isl_schedule_node *node, struct isl_sched_graph *graph)
5329 return carry_feautrier(node, graph);
5332 /* Turn off the "local" bit on all (condition) edges.
5334 static void clear_local_edges(struct isl_sched_graph *graph)
5336 int i;
5338 for (i = 0; i < graph->n_edge; ++i)
5339 if (is_condition(&graph->edge[i]))
5340 clear_local(&graph->edge[i]);
5343 /* Does "graph" have both condition and conditional validity edges?
5345 static int need_condition_check(struct isl_sched_graph *graph)
5347 int i;
5348 int any_condition = 0;
5349 int any_conditional_validity = 0;
5351 for (i = 0; i < graph->n_edge; ++i) {
5352 if (is_condition(&graph->edge[i]))
5353 any_condition = 1;
5354 if (is_conditional_validity(&graph->edge[i]))
5355 any_conditional_validity = 1;
5358 return any_condition && any_conditional_validity;
5361 /* Does "graph" contain any coincidence edge?
5363 static int has_any_coincidence(struct isl_sched_graph *graph)
5365 int i;
5367 for (i = 0; i < graph->n_edge; ++i)
5368 if (is_coincidence(&graph->edge[i]))
5369 return 1;
5371 return 0;
5374 /* Extract the final schedule row as a map with the iteration domain
5375 * of "node" as domain.
5377 static __isl_give isl_map *final_row(struct isl_sched_node *node)
5379 isl_multi_aff *ma;
5380 int row;
5382 row = isl_mat_rows(node->sched) - 1;
5383 ma = node_extract_partial_schedule_multi_aff(node, row, 1);
5384 return isl_map_from_multi_aff(ma);
5387 /* Is the conditional validity dependence in the edge with index "edge_index"
5388 * violated by the latest (i.e., final) row of the schedule?
5389 * That is, is i scheduled after j
5390 * for any conditional validity dependence i -> j?
5392 static int is_violated(struct isl_sched_graph *graph, int edge_index)
5394 isl_map *src_sched, *dst_sched, *map;
5395 struct isl_sched_edge *edge = &graph->edge[edge_index];
5396 int empty;
5398 src_sched = final_row(edge->src);
5399 dst_sched = final_row(edge->dst);
5400 map = isl_map_copy(edge->map);
5401 map = isl_map_apply_domain(map, src_sched);
5402 map = isl_map_apply_range(map, dst_sched);
5403 map = isl_map_order_gt(map, isl_dim_in, 0, isl_dim_out, 0);
5404 empty = isl_map_is_empty(map);
5405 isl_map_free(map);
5407 if (empty < 0)
5408 return -1;
5410 return !empty;
5413 /* Does "graph" have any satisfied condition edges that
5414 * are adjacent to the conditional validity constraint with
5415 * domain "conditional_source" and range "conditional_sink"?
5417 * A satisfied condition is one that is not local.
5418 * If a condition was forced to be local already (i.e., marked as local)
5419 * then there is no need to check if it is in fact local.
5421 * Additionally, mark all adjacent condition edges found as local.
5423 static int has_adjacent_true_conditions(struct isl_sched_graph *graph,
5424 __isl_keep isl_union_set *conditional_source,
5425 __isl_keep isl_union_set *conditional_sink)
5427 int i;
5428 int any = 0;
5430 for (i = 0; i < graph->n_edge; ++i) {
5431 int adjacent, local;
5432 isl_union_map *condition;
5434 if (!is_condition(&graph->edge[i]))
5435 continue;
5436 if (is_local(&graph->edge[i]))
5437 continue;
5439 condition = graph->edge[i].tagged_condition;
5440 adjacent = domain_intersects(condition, conditional_sink);
5441 if (adjacent >= 0 && !adjacent)
5442 adjacent = range_intersects(condition,
5443 conditional_source);
5444 if (adjacent < 0)
5445 return -1;
5446 if (!adjacent)
5447 continue;
5449 set_local(&graph->edge[i]);
5451 local = is_condition_false(&graph->edge[i]);
5452 if (local < 0)
5453 return -1;
5454 if (!local)
5455 any = 1;
5458 return any;
5461 /* Are there any violated conditional validity dependences with
5462 * adjacent condition dependences that are not local with respect
5463 * to the current schedule?
5464 * That is, is the conditional validity constraint violated?
5466 * Additionally, mark all those adjacent condition dependences as local.
5467 * We also mark those adjacent condition dependences that were not marked
5468 * as local before, but just happened to be local already. This ensures
5469 * that they remain local if the schedule is recomputed.
5471 * We first collect domain and range of all violated conditional validity
5472 * dependences and then check if there are any adjacent non-local
5473 * condition dependences.
5475 static int has_violated_conditional_constraint(isl_ctx *ctx,
5476 struct isl_sched_graph *graph)
5478 int i;
5479 int any = 0;
5480 isl_union_set *source, *sink;
5482 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
5483 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
5484 for (i = 0; i < graph->n_edge; ++i) {
5485 isl_union_set *uset;
5486 isl_union_map *umap;
5487 int violated;
5489 if (!is_conditional_validity(&graph->edge[i]))
5490 continue;
5492 violated = is_violated(graph, i);
5493 if (violated < 0)
5494 goto error;
5495 if (!violated)
5496 continue;
5498 any = 1;
5500 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
5501 uset = isl_union_map_domain(umap);
5502 source = isl_union_set_union(source, uset);
5503 source = isl_union_set_coalesce(source);
5505 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
5506 uset = isl_union_map_range(umap);
5507 sink = isl_union_set_union(sink, uset);
5508 sink = isl_union_set_coalesce(sink);
5511 if (any)
5512 any = has_adjacent_true_conditions(graph, source, sink);
5514 isl_union_set_free(source);
5515 isl_union_set_free(sink);
5516 return any;
5517 error:
5518 isl_union_set_free(source);
5519 isl_union_set_free(sink);
5520 return -1;
5523 /* Examine the current band (the rows between graph->band_start and
5524 * graph->n_total_row), deciding whether to drop it or add it to "node"
5525 * and then continue with the computation of the next band, if any.
5526 * If "initialized" is set, then it may be assumed that compute_maxvar
5527 * has been called on the current band. Otherwise, call
5528 * compute_maxvar if and before carry_dependences gets called.
5530 * The caller keeps looking for a new row as long as
5531 * graph->n_row < graph->maxvar. If the latest attempt to find
5532 * such a row failed (i.e., we still have graph->n_row < graph->maxvar),
5533 * then we either
5534 * - split between SCCs and start over (assuming we found an interesting
5535 * pair of SCCs between which to split)
5536 * - continue with the next band (assuming the current band has at least
5537 * one row)
5538 * - if there is more than one SCC left, then split along all SCCs
5539 * - if outer coincidence needs to be enforced, then try to carry as many
5540 * validity or coincidence dependences as possible and
5541 * continue with the next band
5542 * - try to carry as many validity dependences as possible and
5543 * continue with the next band
5544 * In each case, we first insert a band node in the schedule tree
5545 * if any rows have been computed.
5547 * If the caller managed to complete the schedule and the current band
5548 * is empty, then finish off by topologically
5549 * sorting the statements based on the remaining dependences.
5550 * If, on the other hand, the current band has at least one row,
5551 * then continue with the next band. Note that this next band
5552 * will necessarily be empty, but the graph may still be split up
5553 * into weakly connected components before arriving back here.
5555 static __isl_give isl_schedule_node *compute_schedule_finish_band(
5556 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5557 int initialized)
5559 int empty;
5561 if (!node)
5562 return NULL;
5564 empty = graph->n_total_row == graph->band_start;
5565 if (graph->n_row < graph->maxvar) {
5566 isl_ctx *ctx;
5568 ctx = isl_schedule_node_get_ctx(node);
5569 if (!ctx->opt->schedule_maximize_band_depth && !empty)
5570 return compute_next_band(node, graph, 1);
5571 if (graph->src_scc >= 0)
5572 return compute_split_schedule(node, graph);
5573 if (!empty)
5574 return compute_next_band(node, graph, 1);
5575 if (graph->scc > 1)
5576 return compute_component_schedule(node, graph, 1);
5577 if (!initialized && compute_maxvar(graph) < 0)
5578 return isl_schedule_node_free(node);
5579 if (isl_options_get_schedule_outer_coincidence(ctx))
5580 return carry_coincidence(node, graph);
5581 return carry_dependences(node, graph);
5584 if (!empty)
5585 return compute_next_band(node, graph, 1);
5586 return sort_statements(node, graph, initialized);
5589 /* Construct a band of schedule rows for a connected dependence graph.
5590 * The caller is responsible for determining the strongly connected
5591 * components and calling compute_maxvar first.
5593 * We try to find a sequence of as many schedule rows as possible that result
5594 * in non-negative dependence distances (independent of the previous rows
5595 * in the sequence, i.e., such that the sequence is tilable), with as
5596 * many of the initial rows as possible satisfying the coincidence constraints.
5597 * The computation stops if we can't find any more rows or if we have found
5598 * all the rows we wanted to find.
5600 * If ctx->opt->schedule_outer_coincidence is set, then we force the
5601 * outermost dimension to satisfy the coincidence constraints. If this
5602 * turns out to be impossible, we fall back on the general scheme above
5603 * and try to carry as many dependences as possible.
5605 * If "graph" contains both condition and conditional validity dependences,
5606 * then we need to check that that the conditional schedule constraint
5607 * is satisfied, i.e., there are no violated conditional validity dependences
5608 * that are adjacent to any non-local condition dependences.
5609 * If there are, then we mark all those adjacent condition dependences
5610 * as local and recompute the current band. Those dependences that
5611 * are marked local will then be forced to be local.
5612 * The initial computation is performed with no dependences marked as local.
5613 * If we are lucky, then there will be no violated conditional validity
5614 * dependences adjacent to any non-local condition dependences.
5615 * Otherwise, we mark some additional condition dependences as local and
5616 * recompute. We continue this process until there are no violations left or
5617 * until we are no longer able to compute a schedule.
5618 * Since there are only a finite number of dependences,
5619 * there will only be a finite number of iterations.
5621 static isl_stat compute_schedule_wcc_band(isl_ctx *ctx,
5622 struct isl_sched_graph *graph)
5624 int has_coincidence;
5625 int use_coincidence;
5626 int force_coincidence = 0;
5627 int check_conditional;
5629 if (sort_sccs(graph) < 0)
5630 return isl_stat_error;
5632 clear_local_edges(graph);
5633 check_conditional = need_condition_check(graph);
5634 has_coincidence = has_any_coincidence(graph);
5636 if (ctx->opt->schedule_outer_coincidence)
5637 force_coincidence = 1;
5639 use_coincidence = has_coincidence;
5640 while (graph->n_row < graph->maxvar) {
5641 isl_vec *sol;
5642 int violated;
5643 int coincident;
5645 graph->src_scc = -1;
5646 graph->dst_scc = -1;
5648 if (setup_lp(ctx, graph, use_coincidence) < 0)
5649 return isl_stat_error;
5650 sol = solve_lp(ctx, graph);
5651 if (!sol)
5652 return isl_stat_error;
5653 if (sol->size == 0) {
5654 int empty = graph->n_total_row == graph->band_start;
5656 isl_vec_free(sol);
5657 if (use_coincidence && (!force_coincidence || !empty)) {
5658 use_coincidence = 0;
5659 continue;
5661 return isl_stat_ok;
5663 coincident = !has_coincidence || use_coincidence;
5664 if (update_schedule(graph, sol, coincident) < 0)
5665 return isl_stat_error;
5667 if (!check_conditional)
5668 continue;
5669 violated = has_violated_conditional_constraint(ctx, graph);
5670 if (violated < 0)
5671 return isl_stat_error;
5672 if (!violated)
5673 continue;
5674 if (reset_band(graph) < 0)
5675 return isl_stat_error;
5676 use_coincidence = has_coincidence;
5679 return isl_stat_ok;
5682 /* Compute a schedule for a connected dependence graph by considering
5683 * the graph as a whole and return the updated schedule node.
5685 * The actual schedule rows of the current band are computed by
5686 * compute_schedule_wcc_band. compute_schedule_finish_band takes
5687 * care of integrating the band into "node" and continuing
5688 * the computation.
5690 static __isl_give isl_schedule_node *compute_schedule_wcc_whole(
5691 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5693 isl_ctx *ctx;
5695 if (!node)
5696 return NULL;
5698 ctx = isl_schedule_node_get_ctx(node);
5699 if (compute_schedule_wcc_band(ctx, graph) < 0)
5700 return isl_schedule_node_free(node);
5702 return compute_schedule_finish_band(node, graph, 1);
5705 /* Clustering information used by compute_schedule_wcc_clustering.
5707 * "n" is the number of SCCs in the original dependence graph
5708 * "scc" is an array of "n" elements, each representing an SCC
5709 * of the original dependence graph. All entries in the same cluster
5710 * have the same number of schedule rows.
5711 * "scc_cluster" maps each SCC index to the cluster to which it belongs,
5712 * where each cluster is represented by the index of the first SCC
5713 * in the cluster. Initially, each SCC belongs to a cluster containing
5714 * only that SCC.
5716 * "scc_in_merge" is used by merge_clusters_along_edge to keep
5717 * track of which SCCs need to be merged.
5719 * "cluster" contains the merged clusters of SCCs after the clustering
5720 * has completed.
5722 * "scc_node" is a temporary data structure used inside copy_partial.
5723 * For each SCC, it keeps track of the number of nodes in the SCC
5724 * that have already been copied.
5726 struct isl_clustering {
5727 int n;
5728 struct isl_sched_graph *scc;
5729 struct isl_sched_graph *cluster;
5730 int *scc_cluster;
5731 int *scc_node;
5732 int *scc_in_merge;
5735 /* Initialize the clustering data structure "c" from "graph".
5737 * In particular, allocate memory, extract the SCCs from "graph"
5738 * into c->scc, initialize scc_cluster and construct
5739 * a band of schedule rows for each SCC.
5740 * Within each SCC, there is only one SCC by definition.
5741 * Each SCC initially belongs to a cluster containing only that SCC.
5743 static isl_stat clustering_init(isl_ctx *ctx, struct isl_clustering *c,
5744 struct isl_sched_graph *graph)
5746 int i;
5748 c->n = graph->scc;
5749 c->scc = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5750 c->cluster = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5751 c->scc_cluster = isl_calloc_array(ctx, int, c->n);
5752 c->scc_node = isl_calloc_array(ctx, int, c->n);
5753 c->scc_in_merge = isl_calloc_array(ctx, int, c->n);
5754 if (!c->scc || !c->cluster ||
5755 !c->scc_cluster || !c->scc_node || !c->scc_in_merge)
5756 return isl_stat_error;
5758 for (i = 0; i < c->n; ++i) {
5759 if (extract_sub_graph(ctx, graph, &node_scc_exactly,
5760 &edge_scc_exactly, i, &c->scc[i]) < 0)
5761 return isl_stat_error;
5762 c->scc[i].scc = 1;
5763 if (compute_maxvar(&c->scc[i]) < 0)
5764 return isl_stat_error;
5765 if (compute_schedule_wcc_band(ctx, &c->scc[i]) < 0)
5766 return isl_stat_error;
5767 c->scc_cluster[i] = i;
5770 return isl_stat_ok;
5773 /* Free all memory allocated for "c".
5775 static void clustering_free(isl_ctx *ctx, struct isl_clustering *c)
5777 int i;
5779 if (c->scc)
5780 for (i = 0; i < c->n; ++i)
5781 graph_free(ctx, &c->scc[i]);
5782 free(c->scc);
5783 if (c->cluster)
5784 for (i = 0; i < c->n; ++i)
5785 graph_free(ctx, &c->cluster[i]);
5786 free(c->cluster);
5787 free(c->scc_cluster);
5788 free(c->scc_node);
5789 free(c->scc_in_merge);
5792 /* Should we refrain from merging the cluster in "graph" with
5793 * any other cluster?
5794 * In particular, is its current schedule band empty and incomplete.
5796 static int bad_cluster(struct isl_sched_graph *graph)
5798 return graph->n_row < graph->maxvar &&
5799 graph->n_total_row == graph->band_start;
5802 /* Is "edge" a proximity edge with a non-empty dependence relation?
5804 static isl_bool is_non_empty_proximity(struct isl_sched_edge *edge)
5806 if (!is_proximity(edge))
5807 return isl_bool_false;
5808 return isl_bool_not(isl_map_plain_is_empty(edge->map));
5811 /* Return the index of an edge in "graph" that can be used to merge
5812 * two clusters in "c".
5813 * Return graph->n_edge if no such edge can be found.
5814 * Return -1 on error.
5816 * In particular, return a proximity edge between two clusters
5817 * that is not marked "no_merge" and such that neither of the
5818 * two clusters has an incomplete, empty band.
5820 * If there are multiple such edges, then try and find the most
5821 * appropriate edge to use for merging. In particular, pick the edge
5822 * with the greatest weight. If there are multiple of those,
5823 * then pick one with the shortest distance between
5824 * the two cluster representatives.
5826 static int find_proximity(struct isl_sched_graph *graph,
5827 struct isl_clustering *c)
5829 int i, best = graph->n_edge, best_dist, best_weight;
5831 for (i = 0; i < graph->n_edge; ++i) {
5832 struct isl_sched_edge *edge = &graph->edge[i];
5833 int dist, weight;
5834 isl_bool prox;
5836 prox = is_non_empty_proximity(edge);
5837 if (prox < 0)
5838 return -1;
5839 if (!prox)
5840 continue;
5841 if (edge->no_merge)
5842 continue;
5843 if (bad_cluster(&c->scc[edge->src->scc]) ||
5844 bad_cluster(&c->scc[edge->dst->scc]))
5845 continue;
5846 dist = c->scc_cluster[edge->dst->scc] -
5847 c->scc_cluster[edge->src->scc];
5848 if (dist == 0)
5849 continue;
5850 weight = edge->weight;
5851 if (best < graph->n_edge) {
5852 if (best_weight > weight)
5853 continue;
5854 if (best_weight == weight && best_dist <= dist)
5855 continue;
5857 best = i;
5858 best_dist = dist;
5859 best_weight = weight;
5862 return best;
5865 /* Internal data structure used in mark_merge_sccs.
5867 * "graph" is the dependence graph in which a strongly connected
5868 * component is constructed.
5869 * "scc_cluster" maps each SCC index to the cluster to which it belongs.
5870 * "src" and "dst" are the indices of the nodes that are being merged.
5872 struct isl_mark_merge_sccs_data {
5873 struct isl_sched_graph *graph;
5874 int *scc_cluster;
5875 int src;
5876 int dst;
5879 /* Check whether the cluster containing node "i" depends on the cluster
5880 * containing node "j". If "i" and "j" belong to the same cluster,
5881 * then they are taken to depend on each other to ensure that
5882 * the resulting strongly connected component consists of complete
5883 * clusters. Furthermore, if "i" and "j" are the two nodes that
5884 * are being merged, then they are taken to depend on each other as well.
5885 * Otherwise, check if there is a (conditional) validity dependence
5886 * from node[j] to node[i], forcing node[i] to follow node[j].
5888 static isl_bool cluster_follows(int i, int j, void *user)
5890 struct isl_mark_merge_sccs_data *data = user;
5891 struct isl_sched_graph *graph = data->graph;
5892 int *scc_cluster = data->scc_cluster;
5894 if (data->src == i && data->dst == j)
5895 return isl_bool_true;
5896 if (data->src == j && data->dst == i)
5897 return isl_bool_true;
5898 if (scc_cluster[graph->node[i].scc] == scc_cluster[graph->node[j].scc])
5899 return isl_bool_true;
5901 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
5904 /* Mark all SCCs that belong to either of the two clusters in "c"
5905 * connected by the edge in "graph" with index "edge", or to any
5906 * of the intermediate clusters.
5907 * The marking is recorded in c->scc_in_merge.
5909 * The given edge has been selected for merging two clusters,
5910 * meaning that there is at least a proximity edge between the two nodes.
5911 * However, there may also be (indirect) validity dependences
5912 * between the two nodes. When merging the two clusters, all clusters
5913 * containing one or more of the intermediate nodes along the
5914 * indirect validity dependences need to be merged in as well.
5916 * First collect all such nodes by computing the strongly connected
5917 * component (SCC) containing the two nodes connected by the edge, where
5918 * the two nodes are considered to depend on each other to make
5919 * sure they end up in the same SCC. Similarly, each node is considered
5920 * to depend on every other node in the same cluster to ensure
5921 * that the SCC consists of complete clusters.
5923 * Then the original SCCs that contain any of these nodes are marked
5924 * in c->scc_in_merge.
5926 static isl_stat mark_merge_sccs(isl_ctx *ctx, struct isl_sched_graph *graph,
5927 int edge, struct isl_clustering *c)
5929 struct isl_mark_merge_sccs_data data;
5930 struct isl_tarjan_graph *g;
5931 int i;
5933 for (i = 0; i < c->n; ++i)
5934 c->scc_in_merge[i] = 0;
5936 data.graph = graph;
5937 data.scc_cluster = c->scc_cluster;
5938 data.src = graph->edge[edge].src - graph->node;
5939 data.dst = graph->edge[edge].dst - graph->node;
5941 g = isl_tarjan_graph_component(ctx, graph->n, data.dst,
5942 &cluster_follows, &data);
5943 if (!g)
5944 goto error;
5946 i = g->op;
5947 if (i < 3)
5948 isl_die(ctx, isl_error_internal,
5949 "expecting at least two nodes in component",
5950 goto error);
5951 if (g->order[--i] != -1)
5952 isl_die(ctx, isl_error_internal,
5953 "expecting end of component marker", goto error);
5955 for (--i; i >= 0 && g->order[i] != -1; --i) {
5956 int scc = graph->node[g->order[i]].scc;
5957 c->scc_in_merge[scc] = 1;
5960 isl_tarjan_graph_free(g);
5961 return isl_stat_ok;
5962 error:
5963 isl_tarjan_graph_free(g);
5964 return isl_stat_error;
5967 /* Construct the identifier "cluster_i".
5969 static __isl_give isl_id *cluster_id(isl_ctx *ctx, int i)
5971 char name[40];
5973 snprintf(name, sizeof(name), "cluster_%d", i);
5974 return isl_id_alloc(ctx, name, NULL);
5977 /* Construct the space of the cluster with index "i" containing
5978 * the strongly connected component "scc".
5980 * In particular, construct a space called cluster_i with dimension equal
5981 * to the number of schedule rows in the current band of "scc".
5983 static __isl_give isl_space *cluster_space(struct isl_sched_graph *scc, int i)
5985 int nvar;
5986 isl_space *space;
5987 isl_id *id;
5989 nvar = scc->n_total_row - scc->band_start;
5990 space = isl_space_copy(scc->node[0].space);
5991 space = isl_space_params(space);
5992 space = isl_space_set_from_params(space);
5993 space = isl_space_add_dims(space, isl_dim_set, nvar);
5994 id = cluster_id(isl_space_get_ctx(space), i);
5995 space = isl_space_set_tuple_id(space, isl_dim_set, id);
5997 return space;
6000 /* Collect the domain of the graph for merging clusters.
6002 * In particular, for each cluster with first SCC "i", construct
6003 * a set in the space called cluster_i with dimension equal
6004 * to the number of schedule rows in the current band of the cluster.
6006 static __isl_give isl_union_set *collect_domain(isl_ctx *ctx,
6007 struct isl_sched_graph *graph, struct isl_clustering *c)
6009 int i;
6010 isl_space *space;
6011 isl_union_set *domain;
6013 space = isl_space_params_alloc(ctx, 0);
6014 domain = isl_union_set_empty(space);
6016 for (i = 0; i < graph->scc; ++i) {
6017 isl_space *space;
6019 if (!c->scc_in_merge[i])
6020 continue;
6021 if (c->scc_cluster[i] != i)
6022 continue;
6023 space = cluster_space(&c->scc[i], i);
6024 domain = isl_union_set_add_set(domain, isl_set_universe(space));
6027 return domain;
6030 /* Construct a map from the original instances to the corresponding
6031 * cluster instance in the current bands of the clusters in "c".
6033 static __isl_give isl_union_map *collect_cluster_map(isl_ctx *ctx,
6034 struct isl_sched_graph *graph, struct isl_clustering *c)
6036 int i, j;
6037 isl_space *space;
6038 isl_union_map *cluster_map;
6040 space = isl_space_params_alloc(ctx, 0);
6041 cluster_map = isl_union_map_empty(space);
6042 for (i = 0; i < graph->scc; ++i) {
6043 int start, n;
6044 isl_id *id;
6046 if (!c->scc_in_merge[i])
6047 continue;
6049 id = cluster_id(ctx, c->scc_cluster[i]);
6050 start = c->scc[i].band_start;
6051 n = c->scc[i].n_total_row - start;
6052 for (j = 0; j < c->scc[i].n; ++j) {
6053 isl_multi_aff *ma;
6054 isl_map *map;
6055 struct isl_sched_node *node = &c->scc[i].node[j];
6057 ma = node_extract_partial_schedule_multi_aff(node,
6058 start, n);
6059 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out,
6060 isl_id_copy(id));
6061 map = isl_map_from_multi_aff(ma);
6062 cluster_map = isl_union_map_add_map(cluster_map, map);
6064 isl_id_free(id);
6067 return cluster_map;
6070 /* Add "umap" to the schedule constraints "sc" of all types of "edge"
6071 * that are not isl_edge_condition or isl_edge_conditional_validity.
6073 static __isl_give isl_schedule_constraints *add_non_conditional_constraints(
6074 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
6075 __isl_take isl_schedule_constraints *sc)
6077 enum isl_edge_type t;
6079 if (!sc)
6080 return NULL;
6082 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
6083 if (t == isl_edge_condition ||
6084 t == isl_edge_conditional_validity)
6085 continue;
6086 if (!is_type(edge, t))
6087 continue;
6088 sc = isl_schedule_constraints_add(sc, t,
6089 isl_union_map_copy(umap));
6092 return sc;
6095 /* Add schedule constraints of types isl_edge_condition and
6096 * isl_edge_conditional_validity to "sc" by applying "umap" to
6097 * the domains of the wrapped relations in domain and range
6098 * of the corresponding tagged constraints of "edge".
6100 static __isl_give isl_schedule_constraints *add_conditional_constraints(
6101 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
6102 __isl_take isl_schedule_constraints *sc)
6104 enum isl_edge_type t;
6105 isl_union_map *tagged;
6107 for (t = isl_edge_condition; t <= isl_edge_conditional_validity; ++t) {
6108 if (!is_type(edge, t))
6109 continue;
6110 if (t == isl_edge_condition)
6111 tagged = isl_union_map_copy(edge->tagged_condition);
6112 else
6113 tagged = isl_union_map_copy(edge->tagged_validity);
6114 tagged = isl_union_map_zip(tagged);
6115 tagged = isl_union_map_apply_domain(tagged,
6116 isl_union_map_copy(umap));
6117 tagged = isl_union_map_zip(tagged);
6118 sc = isl_schedule_constraints_add(sc, t, tagged);
6119 if (!sc)
6120 return NULL;
6123 return sc;
6126 /* Given a mapping "cluster_map" from the original instances to
6127 * the cluster instances, add schedule constraints on the clusters
6128 * to "sc" corresponding to the original constraints represented by "edge".
6130 * For non-tagged dependence constraints, the cluster constraints
6131 * are obtained by applying "cluster_map" to the edge->map.
6133 * For tagged dependence constraints, "cluster_map" needs to be applied
6134 * to the domains of the wrapped relations in domain and range
6135 * of the tagged dependence constraints. Pick out the mappings
6136 * from these domains from "cluster_map" and construct their product.
6137 * This mapping can then be applied to the pair of domains.
6139 static __isl_give isl_schedule_constraints *collect_edge_constraints(
6140 struct isl_sched_edge *edge, __isl_keep isl_union_map *cluster_map,
6141 __isl_take isl_schedule_constraints *sc)
6143 isl_union_map *umap;
6144 isl_space *space;
6145 isl_union_set *uset;
6146 isl_union_map *umap1, *umap2;
6148 if (!sc)
6149 return NULL;
6151 umap = isl_union_map_from_map(isl_map_copy(edge->map));
6152 umap = isl_union_map_apply_domain(umap,
6153 isl_union_map_copy(cluster_map));
6154 umap = isl_union_map_apply_range(umap,
6155 isl_union_map_copy(cluster_map));
6156 sc = add_non_conditional_constraints(edge, umap, sc);
6157 isl_union_map_free(umap);
6159 if (!sc || (!is_condition(edge) && !is_conditional_validity(edge)))
6160 return sc;
6162 space = isl_space_domain(isl_map_get_space(edge->map));
6163 uset = isl_union_set_from_set(isl_set_universe(space));
6164 umap1 = isl_union_map_copy(cluster_map);
6165 umap1 = isl_union_map_intersect_domain(umap1, uset);
6166 space = isl_space_range(isl_map_get_space(edge->map));
6167 uset = isl_union_set_from_set(isl_set_universe(space));
6168 umap2 = isl_union_map_copy(cluster_map);
6169 umap2 = isl_union_map_intersect_domain(umap2, uset);
6170 umap = isl_union_map_product(umap1, umap2);
6172 sc = add_conditional_constraints(edge, umap, sc);
6174 isl_union_map_free(umap);
6175 return sc;
6178 /* Given a mapping "cluster_map" from the original instances to
6179 * the cluster instances, add schedule constraints on the clusters
6180 * to "sc" corresponding to all edges in "graph" between nodes that
6181 * belong to SCCs that are marked for merging in "scc_in_merge".
6183 static __isl_give isl_schedule_constraints *collect_constraints(
6184 struct isl_sched_graph *graph, int *scc_in_merge,
6185 __isl_keep isl_union_map *cluster_map,
6186 __isl_take isl_schedule_constraints *sc)
6188 int i;
6190 for (i = 0; i < graph->n_edge; ++i) {
6191 struct isl_sched_edge *edge = &graph->edge[i];
6193 if (!scc_in_merge[edge->src->scc])
6194 continue;
6195 if (!scc_in_merge[edge->dst->scc])
6196 continue;
6197 sc = collect_edge_constraints(edge, cluster_map, sc);
6200 return sc;
6203 /* Construct a dependence graph for scheduling clusters with respect
6204 * to each other and store the result in "merge_graph".
6205 * In particular, the nodes of the graph correspond to the schedule
6206 * dimensions of the current bands of those clusters that have been
6207 * marked for merging in "c".
6209 * First construct an isl_schedule_constraints object for this domain
6210 * by transforming the edges in "graph" to the domain.
6211 * Then initialize a dependence graph for scheduling from these
6212 * constraints.
6214 static isl_stat init_merge_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
6215 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6217 isl_union_set *domain;
6218 isl_union_map *cluster_map;
6219 isl_schedule_constraints *sc;
6220 isl_stat r;
6222 domain = collect_domain(ctx, graph, c);
6223 sc = isl_schedule_constraints_on_domain(domain);
6224 if (!sc)
6225 return isl_stat_error;
6226 cluster_map = collect_cluster_map(ctx, graph, c);
6227 sc = collect_constraints(graph, c->scc_in_merge, cluster_map, sc);
6228 isl_union_map_free(cluster_map);
6230 r = graph_init(merge_graph, sc);
6232 isl_schedule_constraints_free(sc);
6234 return r;
6237 /* Compute the maximal number of remaining schedule rows that still need
6238 * to be computed for the nodes that belong to clusters with the maximal
6239 * dimension for the current band (i.e., the band that is to be merged).
6240 * Only clusters that are about to be merged are considered.
6241 * "maxvar" is the maximal dimension for the current band.
6242 * "c" contains information about the clusters.
6244 * Return the maximal number of remaining schedule rows or -1 on error.
6246 static int compute_maxvar_max_slack(int maxvar, struct isl_clustering *c)
6248 int i, j;
6249 int max_slack;
6251 max_slack = 0;
6252 for (i = 0; i < c->n; ++i) {
6253 int nvar;
6254 struct isl_sched_graph *scc;
6256 if (!c->scc_in_merge[i])
6257 continue;
6258 scc = &c->scc[i];
6259 nvar = scc->n_total_row - scc->band_start;
6260 if (nvar != maxvar)
6261 continue;
6262 for (j = 0; j < scc->n; ++j) {
6263 struct isl_sched_node *node = &scc->node[j];
6264 int slack;
6266 if (node_update_vmap(node) < 0)
6267 return -1;
6268 slack = node->nvar - node->rank;
6269 if (slack > max_slack)
6270 max_slack = slack;
6274 return max_slack;
6277 /* If there are any clusters where the dimension of the current band
6278 * (i.e., the band that is to be merged) is smaller than "maxvar" and
6279 * if there are any nodes in such a cluster where the number
6280 * of remaining schedule rows that still need to be computed
6281 * is greater than "max_slack", then return the smallest current band
6282 * dimension of all these clusters. Otherwise return the original value
6283 * of "maxvar". Return -1 in case of any error.
6284 * Only clusters that are about to be merged are considered.
6285 * "c" contains information about the clusters.
6287 static int limit_maxvar_to_slack(int maxvar, int max_slack,
6288 struct isl_clustering *c)
6290 int i, j;
6292 for (i = 0; i < c->n; ++i) {
6293 int nvar;
6294 struct isl_sched_graph *scc;
6296 if (!c->scc_in_merge[i])
6297 continue;
6298 scc = &c->scc[i];
6299 nvar = scc->n_total_row - scc->band_start;
6300 if (nvar >= maxvar)
6301 continue;
6302 for (j = 0; j < scc->n; ++j) {
6303 struct isl_sched_node *node = &scc->node[j];
6304 int slack;
6306 if (node_update_vmap(node) < 0)
6307 return -1;
6308 slack = node->nvar - node->rank;
6309 if (slack > max_slack) {
6310 maxvar = nvar;
6311 break;
6316 return maxvar;
6319 /* Adjust merge_graph->maxvar based on the number of remaining schedule rows
6320 * that still need to be computed. In particular, if there is a node
6321 * in a cluster where the dimension of the current band is smaller
6322 * than merge_graph->maxvar, but the number of remaining schedule rows
6323 * is greater than that of any node in a cluster with the maximal
6324 * dimension for the current band (i.e., merge_graph->maxvar),
6325 * then adjust merge_graph->maxvar to the (smallest) current band dimension
6326 * of those clusters. Without this adjustment, the total number of
6327 * schedule dimensions would be increased, resulting in a skewed view
6328 * of the number of coincident dimensions.
6329 * "c" contains information about the clusters.
6331 * If the maximize_band_depth option is set and merge_graph->maxvar is reduced,
6332 * then there is no point in attempting any merge since it will be rejected
6333 * anyway. Set merge_graph->maxvar to zero in such cases.
6335 static isl_stat adjust_maxvar_to_slack(isl_ctx *ctx,
6336 struct isl_sched_graph *merge_graph, struct isl_clustering *c)
6338 int max_slack, maxvar;
6340 max_slack = compute_maxvar_max_slack(merge_graph->maxvar, c);
6341 if (max_slack < 0)
6342 return isl_stat_error;
6343 maxvar = limit_maxvar_to_slack(merge_graph->maxvar, max_slack, c);
6344 if (maxvar < 0)
6345 return isl_stat_error;
6347 if (maxvar < merge_graph->maxvar) {
6348 if (isl_options_get_schedule_maximize_band_depth(ctx))
6349 merge_graph->maxvar = 0;
6350 else
6351 merge_graph->maxvar = maxvar;
6354 return isl_stat_ok;
6357 /* Return the number of coincident dimensions in the current band of "graph",
6358 * where the nodes of "graph" are assumed to be scheduled by a single band.
6360 static int get_n_coincident(struct isl_sched_graph *graph)
6362 int i;
6364 for (i = graph->band_start; i < graph->n_total_row; ++i)
6365 if (!graph->node[0].coincident[i])
6366 break;
6368 return i - graph->band_start;
6371 /* Should the clusters be merged based on the cluster schedule
6372 * in the current (and only) band of "merge_graph", given that
6373 * coincidence should be maximized?
6375 * If the number of coincident schedule dimensions in the merged band
6376 * would be less than the maximal number of coincident schedule dimensions
6377 * in any of the merged clusters, then the clusters should not be merged.
6379 static isl_bool ok_to_merge_coincident(struct isl_clustering *c,
6380 struct isl_sched_graph *merge_graph)
6382 int i;
6383 int n_coincident;
6384 int max_coincident;
6386 max_coincident = 0;
6387 for (i = 0; i < c->n; ++i) {
6388 if (!c->scc_in_merge[i])
6389 continue;
6390 n_coincident = get_n_coincident(&c->scc[i]);
6391 if (n_coincident > max_coincident)
6392 max_coincident = n_coincident;
6395 n_coincident = get_n_coincident(merge_graph);
6397 return n_coincident >= max_coincident;
6400 /* Return the transformation on "node" expressed by the current (and only)
6401 * band of "merge_graph" applied to the clusters in "c".
6403 * First find the representation of "node" in its SCC in "c" and
6404 * extract the transformation expressed by the current band.
6405 * Then extract the transformation applied by "merge_graph"
6406 * to the cluster to which this SCC belongs.
6407 * Combine the two to obtain the complete transformation on the node.
6409 * Note that the range of the first transformation is an anonymous space,
6410 * while the domain of the second is named "cluster_X". The range
6411 * of the former therefore needs to be adjusted before the two
6412 * can be combined.
6414 static __isl_give isl_map *extract_node_transformation(isl_ctx *ctx,
6415 struct isl_sched_node *node, struct isl_clustering *c,
6416 struct isl_sched_graph *merge_graph)
6418 struct isl_sched_node *scc_node, *cluster_node;
6419 int start, n;
6420 isl_id *id;
6421 isl_space *space;
6422 isl_multi_aff *ma, *ma2;
6424 scc_node = graph_find_node(ctx, &c->scc[node->scc], node->space);
6425 if (scc_node && !is_node(&c->scc[node->scc], scc_node))
6426 isl_die(ctx, isl_error_internal, "unable to find node",
6427 return NULL);
6428 start = c->scc[node->scc].band_start;
6429 n = c->scc[node->scc].n_total_row - start;
6430 ma = node_extract_partial_schedule_multi_aff(scc_node, start, n);
6431 space = cluster_space(&c->scc[node->scc], c->scc_cluster[node->scc]);
6432 cluster_node = graph_find_node(ctx, merge_graph, space);
6433 if (cluster_node && !is_node(merge_graph, cluster_node))
6434 isl_die(ctx, isl_error_internal, "unable to find cluster",
6435 space = isl_space_free(space));
6436 id = isl_space_get_tuple_id(space, isl_dim_set);
6437 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out, id);
6438 isl_space_free(space);
6439 n = merge_graph->n_total_row;
6440 ma2 = node_extract_partial_schedule_multi_aff(cluster_node, 0, n);
6441 ma = isl_multi_aff_pullback_multi_aff(ma2, ma);
6443 return isl_map_from_multi_aff(ma);
6446 /* Give a set of distances "set", are they bounded by a small constant
6447 * in direction "pos"?
6448 * In practice, check if they are bounded by 2 by checking that there
6449 * are no elements with a value greater than or equal to 3 or
6450 * smaller than or equal to -3.
6452 static isl_bool distance_is_bounded(__isl_keep isl_set *set, int pos)
6454 isl_bool bounded;
6455 isl_set *test;
6457 if (!set)
6458 return isl_bool_error;
6460 test = isl_set_copy(set);
6461 test = isl_set_lower_bound_si(test, isl_dim_set, pos, 3);
6462 bounded = isl_set_is_empty(test);
6463 isl_set_free(test);
6465 if (bounded < 0 || !bounded)
6466 return bounded;
6468 test = isl_set_copy(set);
6469 test = isl_set_upper_bound_si(test, isl_dim_set, pos, -3);
6470 bounded = isl_set_is_empty(test);
6471 isl_set_free(test);
6473 return bounded;
6476 /* Does the set "set" have a fixed (but possible parametric) value
6477 * at dimension "pos"?
6479 static isl_bool has_single_value(__isl_keep isl_set *set, int pos)
6481 int n;
6482 isl_bool single;
6484 if (!set)
6485 return isl_bool_error;
6486 set = isl_set_copy(set);
6487 n = isl_set_dim(set, isl_dim_set);
6488 set = isl_set_project_out(set, isl_dim_set, pos + 1, n - (pos + 1));
6489 set = isl_set_project_out(set, isl_dim_set, 0, pos);
6490 single = isl_set_is_singleton(set);
6491 isl_set_free(set);
6493 return single;
6496 /* Does "map" have a fixed (but possible parametric) value
6497 * at dimension "pos" of either its domain or its range?
6499 static isl_bool has_singular_src_or_dst(__isl_keep isl_map *map, int pos)
6501 isl_set *set;
6502 isl_bool single;
6504 set = isl_map_domain(isl_map_copy(map));
6505 single = has_single_value(set, pos);
6506 isl_set_free(set);
6508 if (single < 0 || single)
6509 return single;
6511 set = isl_map_range(isl_map_copy(map));
6512 single = has_single_value(set, pos);
6513 isl_set_free(set);
6515 return single;
6518 /* Does the edge "edge" from "graph" have bounded dependence distances
6519 * in the merged graph "merge_graph" of a selection of clusters in "c"?
6521 * Extract the complete transformations of the source and destination
6522 * nodes of the edge, apply them to the edge constraints and
6523 * compute the differences. Finally, check if these differences are bounded
6524 * in each direction.
6526 * If the dimension of the band is greater than the number of
6527 * dimensions that can be expected to be optimized by the edge
6528 * (based on its weight), then also allow the differences to be unbounded
6529 * in the remaining dimensions, but only if either the source or
6530 * the destination has a fixed value in that direction.
6531 * This allows a statement that produces values that are used by
6532 * several instances of another statement to be merged with that
6533 * other statement.
6534 * However, merging such clusters will introduce an inherently
6535 * large proximity distance inside the merged cluster, meaning
6536 * that proximity distances will no longer be optimized in
6537 * subsequent merges. These merges are therefore only allowed
6538 * after all other possible merges have been tried.
6539 * The first time such a merge is encountered, the weight of the edge
6540 * is replaced by a negative weight. The second time (i.e., after
6541 * all merges over edges with a non-negative weight have been tried),
6542 * the merge is allowed.
6544 static isl_bool has_bounded_distances(isl_ctx *ctx, struct isl_sched_edge *edge,
6545 struct isl_sched_graph *graph, struct isl_clustering *c,
6546 struct isl_sched_graph *merge_graph)
6548 int i, n, n_slack;
6549 isl_bool bounded;
6550 isl_map *map, *t;
6551 isl_set *dist;
6553 map = isl_map_copy(edge->map);
6554 t = extract_node_transformation(ctx, edge->src, c, merge_graph);
6555 map = isl_map_apply_domain(map, t);
6556 t = extract_node_transformation(ctx, edge->dst, c, merge_graph);
6557 map = isl_map_apply_range(map, t);
6558 dist = isl_map_deltas(isl_map_copy(map));
6560 bounded = isl_bool_true;
6561 n = isl_set_dim(dist, isl_dim_set);
6562 n_slack = n - edge->weight;
6563 if (edge->weight < 0)
6564 n_slack -= graph->max_weight + 1;
6565 for (i = 0; i < n; ++i) {
6566 isl_bool bounded_i, singular_i;
6568 bounded_i = distance_is_bounded(dist, i);
6569 if (bounded_i < 0)
6570 goto error;
6571 if (bounded_i)
6572 continue;
6573 if (edge->weight >= 0)
6574 bounded = isl_bool_false;
6575 n_slack--;
6576 if (n_slack < 0)
6577 break;
6578 singular_i = has_singular_src_or_dst(map, i);
6579 if (singular_i < 0)
6580 goto error;
6581 if (singular_i)
6582 continue;
6583 bounded = isl_bool_false;
6584 break;
6586 if (!bounded && i >= n && edge->weight >= 0)
6587 edge->weight -= graph->max_weight + 1;
6588 isl_map_free(map);
6589 isl_set_free(dist);
6591 return bounded;
6592 error:
6593 isl_map_free(map);
6594 isl_set_free(dist);
6595 return isl_bool_error;
6598 /* Should the clusters be merged based on the cluster schedule
6599 * in the current (and only) band of "merge_graph"?
6600 * "graph" is the original dependence graph, while "c" records
6601 * which SCCs are involved in the latest merge.
6603 * In particular, is there at least one proximity constraint
6604 * that is optimized by the merge?
6606 * A proximity constraint is considered to be optimized
6607 * if the dependence distances are small.
6609 static isl_bool ok_to_merge_proximity(isl_ctx *ctx,
6610 struct isl_sched_graph *graph, struct isl_clustering *c,
6611 struct isl_sched_graph *merge_graph)
6613 int i;
6615 for (i = 0; i < graph->n_edge; ++i) {
6616 struct isl_sched_edge *edge = &graph->edge[i];
6617 isl_bool bounded;
6619 if (!is_proximity(edge))
6620 continue;
6621 if (!c->scc_in_merge[edge->src->scc])
6622 continue;
6623 if (!c->scc_in_merge[edge->dst->scc])
6624 continue;
6625 if (c->scc_cluster[edge->dst->scc] ==
6626 c->scc_cluster[edge->src->scc])
6627 continue;
6628 bounded = has_bounded_distances(ctx, edge, graph, c,
6629 merge_graph);
6630 if (bounded < 0 || bounded)
6631 return bounded;
6634 return isl_bool_false;
6637 /* Should the clusters be merged based on the cluster schedule
6638 * in the current (and only) band of "merge_graph"?
6639 * "graph" is the original dependence graph, while "c" records
6640 * which SCCs are involved in the latest merge.
6642 * If the current band is empty, then the clusters should not be merged.
6644 * If the band depth should be maximized and the merge schedule
6645 * is incomplete (meaning that the dimension of some of the schedule
6646 * bands in the original schedule will be reduced), then the clusters
6647 * should not be merged.
6649 * If the schedule_maximize_coincidence option is set, then check that
6650 * the number of coincident schedule dimensions is not reduced.
6652 * Finally, only allow the merge if at least one proximity
6653 * constraint is optimized.
6655 static isl_bool ok_to_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6656 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6658 if (merge_graph->n_total_row == merge_graph->band_start)
6659 return isl_bool_false;
6661 if (isl_options_get_schedule_maximize_band_depth(ctx) &&
6662 merge_graph->n_total_row < merge_graph->maxvar)
6663 return isl_bool_false;
6665 if (isl_options_get_schedule_maximize_coincidence(ctx)) {
6666 isl_bool ok;
6668 ok = ok_to_merge_coincident(c, merge_graph);
6669 if (ok < 0 || !ok)
6670 return ok;
6673 return ok_to_merge_proximity(ctx, graph, c, merge_graph);
6676 /* Apply the schedule in "t_node" to the "n" rows starting at "first"
6677 * of the schedule in "node" and return the result.
6679 * That is, essentially compute
6681 * T * N(first:first+n-1)
6683 * taking into account the constant term and the parameter coefficients
6684 * in "t_node".
6686 static __isl_give isl_mat *node_transformation(isl_ctx *ctx,
6687 struct isl_sched_node *t_node, struct isl_sched_node *node,
6688 int first, int n)
6690 int i, j;
6691 isl_mat *t;
6692 int n_row, n_col, n_param, n_var;
6694 n_param = node->nparam;
6695 n_var = node->nvar;
6696 n_row = isl_mat_rows(t_node->sched);
6697 n_col = isl_mat_cols(node->sched);
6698 t = isl_mat_alloc(ctx, n_row, n_col);
6699 if (!t)
6700 return NULL;
6701 for (i = 0; i < n_row; ++i) {
6702 isl_seq_cpy(t->row[i], t_node->sched->row[i], 1 + n_param);
6703 isl_seq_clr(t->row[i] + 1 + n_param, n_var);
6704 for (j = 0; j < n; ++j)
6705 isl_seq_addmul(t->row[i],
6706 t_node->sched->row[i][1 + n_param + j],
6707 node->sched->row[first + j],
6708 1 + n_param + n_var);
6710 return t;
6713 /* Apply the cluster schedule in "t_node" to the current band
6714 * schedule of the nodes in "graph".
6716 * In particular, replace the rows starting at band_start
6717 * by the result of applying the cluster schedule in "t_node"
6718 * to the original rows.
6720 * The coincidence of the schedule is determined by the coincidence
6721 * of the cluster schedule.
6723 static isl_stat transform(isl_ctx *ctx, struct isl_sched_graph *graph,
6724 struct isl_sched_node *t_node)
6726 int i, j;
6727 int n_new;
6728 int start, n;
6730 start = graph->band_start;
6731 n = graph->n_total_row - start;
6733 n_new = isl_mat_rows(t_node->sched);
6734 for (i = 0; i < graph->n; ++i) {
6735 struct isl_sched_node *node = &graph->node[i];
6736 isl_mat *t;
6738 t = node_transformation(ctx, t_node, node, start, n);
6739 node->sched = isl_mat_drop_rows(node->sched, start, n);
6740 node->sched = isl_mat_concat(node->sched, t);
6741 node->sched_map = isl_map_free(node->sched_map);
6742 if (!node->sched)
6743 return isl_stat_error;
6744 for (j = 0; j < n_new; ++j)
6745 node->coincident[start + j] = t_node->coincident[j];
6747 graph->n_total_row -= n;
6748 graph->n_row -= n;
6749 graph->n_total_row += n_new;
6750 graph->n_row += n_new;
6752 return isl_stat_ok;
6755 /* Merge the clusters marked for merging in "c" into a single
6756 * cluster using the cluster schedule in the current band of "merge_graph".
6757 * The representative SCC for the new cluster is the SCC with
6758 * the smallest index.
6760 * The current band schedule of each SCC in the new cluster is obtained
6761 * by applying the schedule of the corresponding original cluster
6762 * to the original band schedule.
6763 * All SCCs in the new cluster have the same number of schedule rows.
6765 static isl_stat merge(isl_ctx *ctx, struct isl_clustering *c,
6766 struct isl_sched_graph *merge_graph)
6768 int i;
6769 int cluster = -1;
6770 isl_space *space;
6772 for (i = 0; i < c->n; ++i) {
6773 struct isl_sched_node *node;
6775 if (!c->scc_in_merge[i])
6776 continue;
6777 if (cluster < 0)
6778 cluster = i;
6779 space = cluster_space(&c->scc[i], c->scc_cluster[i]);
6780 node = graph_find_node(ctx, merge_graph, space);
6781 isl_space_free(space);
6782 if (!node)
6783 return isl_stat_error;
6784 if (!is_node(merge_graph, node))
6785 isl_die(ctx, isl_error_internal,
6786 "unable to find cluster",
6787 return isl_stat_error);
6788 if (transform(ctx, &c->scc[i], node) < 0)
6789 return isl_stat_error;
6790 c->scc_cluster[i] = cluster;
6793 return isl_stat_ok;
6796 /* Try and merge the clusters of SCCs marked in c->scc_in_merge
6797 * by scheduling the current cluster bands with respect to each other.
6799 * Construct a dependence graph with a space for each cluster and
6800 * with the coordinates of each space corresponding to the schedule
6801 * dimensions of the current band of that cluster.
6802 * Construct a cluster schedule in this cluster dependence graph and
6803 * apply it to the current cluster bands if it is applicable
6804 * according to ok_to_merge.
6806 * If the number of remaining schedule dimensions in a cluster
6807 * with a non-maximal current schedule dimension is greater than
6808 * the number of remaining schedule dimensions in clusters
6809 * with a maximal current schedule dimension, then restrict
6810 * the number of rows to be computed in the cluster schedule
6811 * to the minimal such non-maximal current schedule dimension.
6812 * Do this by adjusting merge_graph.maxvar.
6814 * Return isl_bool_true if the clusters have effectively been merged
6815 * into a single cluster.
6817 * Note that since the standard scheduling algorithm minimizes the maximal
6818 * distance over proximity constraints, the proximity constraints between
6819 * the merged clusters may not be optimized any further than what is
6820 * sufficient to bring the distances within the limits of the internal
6821 * proximity constraints inside the individual clusters.
6822 * It may therefore make sense to perform an additional translation step
6823 * to bring the clusters closer to each other, while maintaining
6824 * the linear part of the merging schedule found using the standard
6825 * scheduling algorithm.
6827 static isl_bool try_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6828 struct isl_clustering *c)
6830 struct isl_sched_graph merge_graph = { 0 };
6831 isl_bool merged;
6833 if (init_merge_graph(ctx, graph, c, &merge_graph) < 0)
6834 goto error;
6836 if (compute_maxvar(&merge_graph) < 0)
6837 goto error;
6838 if (adjust_maxvar_to_slack(ctx, &merge_graph,c) < 0)
6839 goto error;
6840 if (compute_schedule_wcc_band(ctx, &merge_graph) < 0)
6841 goto error;
6842 merged = ok_to_merge(ctx, graph, c, &merge_graph);
6843 if (merged && merge(ctx, c, &merge_graph) < 0)
6844 goto error;
6846 graph_free(ctx, &merge_graph);
6847 return merged;
6848 error:
6849 graph_free(ctx, &merge_graph);
6850 return isl_bool_error;
6853 /* Is there any edge marked "no_merge" between two SCCs that are
6854 * about to be merged (i.e., that are set in "scc_in_merge")?
6855 * "merge_edge" is the proximity edge along which the clusters of SCCs
6856 * are going to be merged.
6858 * If there is any edge between two SCCs with a negative weight,
6859 * while the weight of "merge_edge" is non-negative, then this
6860 * means that the edge was postponed. "merge_edge" should then
6861 * also be postponed since merging along the edge with negative weight should
6862 * be postponed until all edges with non-negative weight have been tried.
6863 * Replace the weight of "merge_edge" by a negative weight as well and
6864 * tell the caller not to attempt a merge.
6866 static int any_no_merge(struct isl_sched_graph *graph, int *scc_in_merge,
6867 struct isl_sched_edge *merge_edge)
6869 int i;
6871 for (i = 0; i < graph->n_edge; ++i) {
6872 struct isl_sched_edge *edge = &graph->edge[i];
6874 if (!scc_in_merge[edge->src->scc])
6875 continue;
6876 if (!scc_in_merge[edge->dst->scc])
6877 continue;
6878 if (edge->no_merge)
6879 return 1;
6880 if (merge_edge->weight >= 0 && edge->weight < 0) {
6881 merge_edge->weight -= graph->max_weight + 1;
6882 return 1;
6886 return 0;
6889 /* Merge the two clusters in "c" connected by the edge in "graph"
6890 * with index "edge" into a single cluster.
6891 * If it turns out to be impossible to merge these two clusters,
6892 * then mark the edge as "no_merge" such that it will not be
6893 * considered again.
6895 * First mark all SCCs that need to be merged. This includes the SCCs
6896 * in the two clusters, but it may also include the SCCs
6897 * of intermediate clusters.
6898 * If there is already a no_merge edge between any pair of such SCCs,
6899 * then simply mark the current edge as no_merge as well.
6900 * Likewise, if any of those edges was postponed by has_bounded_distances,
6901 * then postpone the current edge as well.
6902 * Otherwise, try and merge the clusters and mark "edge" as "no_merge"
6903 * if the clusters did not end up getting merged, unless the non-merge
6904 * is due to the fact that the edge was postponed. This postponement
6905 * can be recognized by a change in weight (from non-negative to negative).
6907 static isl_stat merge_clusters_along_edge(isl_ctx *ctx,
6908 struct isl_sched_graph *graph, int edge, struct isl_clustering *c)
6910 isl_bool merged;
6911 int edge_weight = graph->edge[edge].weight;
6913 if (mark_merge_sccs(ctx, graph, edge, c) < 0)
6914 return isl_stat_error;
6916 if (any_no_merge(graph, c->scc_in_merge, &graph->edge[edge]))
6917 merged = isl_bool_false;
6918 else
6919 merged = try_merge(ctx, graph, c);
6920 if (merged < 0)
6921 return isl_stat_error;
6922 if (!merged && edge_weight == graph->edge[edge].weight)
6923 graph->edge[edge].no_merge = 1;
6925 return isl_stat_ok;
6928 /* Does "node" belong to the cluster identified by "cluster"?
6930 static int node_cluster_exactly(struct isl_sched_node *node, int cluster)
6932 return node->cluster == cluster;
6935 /* Does "edge" connect two nodes belonging to the cluster
6936 * identified by "cluster"?
6938 static int edge_cluster_exactly(struct isl_sched_edge *edge, int cluster)
6940 return edge->src->cluster == cluster && edge->dst->cluster == cluster;
6943 /* Swap the schedule of "node1" and "node2".
6944 * Both nodes have been derived from the same node in a common parent graph.
6945 * Since the "coincident" field is shared with that node
6946 * in the parent graph, there is no need to also swap this field.
6948 static void swap_sched(struct isl_sched_node *node1,
6949 struct isl_sched_node *node2)
6951 isl_mat *sched;
6952 isl_map *sched_map;
6954 sched = node1->sched;
6955 node1->sched = node2->sched;
6956 node2->sched = sched;
6958 sched_map = node1->sched_map;
6959 node1->sched_map = node2->sched_map;
6960 node2->sched_map = sched_map;
6963 /* Copy the current band schedule from the SCCs that form the cluster
6964 * with index "pos" to the actual cluster at position "pos".
6965 * By construction, the index of the first SCC that belongs to the cluster
6966 * is also "pos".
6968 * The order of the nodes inside both the SCCs and the cluster
6969 * is assumed to be same as the order in the original "graph".
6971 * Since the SCC graphs will no longer be used after this function,
6972 * the schedules are actually swapped rather than copied.
6974 static isl_stat copy_partial(struct isl_sched_graph *graph,
6975 struct isl_clustering *c, int pos)
6977 int i, j;
6979 c->cluster[pos].n_total_row = c->scc[pos].n_total_row;
6980 c->cluster[pos].n_row = c->scc[pos].n_row;
6981 c->cluster[pos].maxvar = c->scc[pos].maxvar;
6982 j = 0;
6983 for (i = 0; i < graph->n; ++i) {
6984 int k;
6985 int s;
6987 if (graph->node[i].cluster != pos)
6988 continue;
6989 s = graph->node[i].scc;
6990 k = c->scc_node[s]++;
6991 swap_sched(&c->cluster[pos].node[j], &c->scc[s].node[k]);
6992 if (c->scc[s].maxvar > c->cluster[pos].maxvar)
6993 c->cluster[pos].maxvar = c->scc[s].maxvar;
6994 ++j;
6997 return isl_stat_ok;
7000 /* Is there a (conditional) validity dependence from node[j] to node[i],
7001 * forcing node[i] to follow node[j] or do the nodes belong to the same
7002 * cluster?
7004 static isl_bool node_follows_strong_or_same_cluster(int i, int j, void *user)
7006 struct isl_sched_graph *graph = user;
7008 if (graph->node[i].cluster == graph->node[j].cluster)
7009 return isl_bool_true;
7010 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
7013 /* Extract the merged clusters of SCCs in "graph", sort them, and
7014 * store them in c->clusters. Update c->scc_cluster accordingly.
7016 * First keep track of the cluster containing the SCC to which a node
7017 * belongs in the node itself.
7018 * Then extract the clusters into c->clusters, copying the current
7019 * band schedule from the SCCs that belong to the cluster.
7020 * Do this only once per cluster.
7022 * Finally, topologically sort the clusters and update c->scc_cluster
7023 * to match the new scc numbering. While the SCCs were originally
7024 * sorted already, some SCCs that depend on some other SCCs may
7025 * have been merged with SCCs that appear before these other SCCs.
7026 * A reordering may therefore be required.
7028 static isl_stat extract_clusters(isl_ctx *ctx, struct isl_sched_graph *graph,
7029 struct isl_clustering *c)
7031 int i;
7033 for (i = 0; i < graph->n; ++i)
7034 graph->node[i].cluster = c->scc_cluster[graph->node[i].scc];
7036 for (i = 0; i < graph->scc; ++i) {
7037 if (c->scc_cluster[i] != i)
7038 continue;
7039 if (extract_sub_graph(ctx, graph, &node_cluster_exactly,
7040 &edge_cluster_exactly, i, &c->cluster[i]) < 0)
7041 return isl_stat_error;
7042 c->cluster[i].src_scc = -1;
7043 c->cluster[i].dst_scc = -1;
7044 if (copy_partial(graph, c, i) < 0)
7045 return isl_stat_error;
7048 if (detect_ccs(ctx, graph, &node_follows_strong_or_same_cluster) < 0)
7049 return isl_stat_error;
7050 for (i = 0; i < graph->n; ++i)
7051 c->scc_cluster[graph->node[i].scc] = graph->node[i].cluster;
7053 return isl_stat_ok;
7056 /* Compute weights on the proximity edges of "graph" that can
7057 * be used by find_proximity to find the most appropriate
7058 * proximity edge to use to merge two clusters in "c".
7059 * The weights are also used by has_bounded_distances to determine
7060 * whether the merge should be allowed.
7061 * Store the maximum of the computed weights in graph->max_weight.
7063 * The computed weight is a measure for the number of remaining schedule
7064 * dimensions that can still be completely aligned.
7065 * In particular, compute the number of equalities between
7066 * input dimensions and output dimensions in the proximity constraints.
7067 * The directions that are already handled by outer schedule bands
7068 * are projected out prior to determining this number.
7070 * Edges that will never be considered by find_proximity are ignored.
7072 static isl_stat compute_weights(struct isl_sched_graph *graph,
7073 struct isl_clustering *c)
7075 int i;
7077 graph->max_weight = 0;
7079 for (i = 0; i < graph->n_edge; ++i) {
7080 struct isl_sched_edge *edge = &graph->edge[i];
7081 struct isl_sched_node *src = edge->src;
7082 struct isl_sched_node *dst = edge->dst;
7083 isl_basic_map *hull;
7084 isl_bool prox;
7085 int n_in, n_out;
7087 prox = is_non_empty_proximity(edge);
7088 if (prox < 0)
7089 return isl_stat_error;
7090 if (!prox)
7091 continue;
7092 if (bad_cluster(&c->scc[edge->src->scc]) ||
7093 bad_cluster(&c->scc[edge->dst->scc]))
7094 continue;
7095 if (c->scc_cluster[edge->dst->scc] ==
7096 c->scc_cluster[edge->src->scc])
7097 continue;
7099 hull = isl_map_affine_hull(isl_map_copy(edge->map));
7100 hull = isl_basic_map_transform_dims(hull, isl_dim_in, 0,
7101 isl_mat_copy(src->vmap));
7102 hull = isl_basic_map_transform_dims(hull, isl_dim_out, 0,
7103 isl_mat_copy(dst->vmap));
7104 hull = isl_basic_map_project_out(hull,
7105 isl_dim_in, 0, src->rank);
7106 hull = isl_basic_map_project_out(hull,
7107 isl_dim_out, 0, dst->rank);
7108 hull = isl_basic_map_remove_divs(hull);
7109 n_in = isl_basic_map_dim(hull, isl_dim_in);
7110 n_out = isl_basic_map_dim(hull, isl_dim_out);
7111 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
7112 isl_dim_in, 0, n_in);
7113 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
7114 isl_dim_out, 0, n_out);
7115 if (!hull)
7116 return isl_stat_error;
7117 edge->weight = isl_basic_map_n_equality(hull);
7118 isl_basic_map_free(hull);
7120 if (edge->weight > graph->max_weight)
7121 graph->max_weight = edge->weight;
7124 return isl_stat_ok;
7127 /* Call compute_schedule_finish_band on each of the clusters in "c"
7128 * in their topological order. This order is determined by the scc
7129 * fields of the nodes in "graph".
7130 * Combine the results in a sequence expressing the topological order.
7132 * If there is only one cluster left, then there is no need to introduce
7133 * a sequence node. Also, in this case, the cluster necessarily contains
7134 * the SCC at position 0 in the original graph and is therefore also
7135 * stored in the first cluster of "c".
7137 static __isl_give isl_schedule_node *finish_bands_clustering(
7138 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
7139 struct isl_clustering *c)
7141 int i;
7142 isl_ctx *ctx;
7143 isl_union_set_list *filters;
7145 if (graph->scc == 1)
7146 return compute_schedule_finish_band(node, &c->cluster[0], 0);
7148 ctx = isl_schedule_node_get_ctx(node);
7150 filters = extract_sccs(ctx, graph);
7151 node = isl_schedule_node_insert_sequence(node, filters);
7153 for (i = 0; i < graph->scc; ++i) {
7154 int j = c->scc_cluster[i];
7155 node = isl_schedule_node_child(node, i);
7156 node = isl_schedule_node_child(node, 0);
7157 node = compute_schedule_finish_band(node, &c->cluster[j], 0);
7158 node = isl_schedule_node_parent(node);
7159 node = isl_schedule_node_parent(node);
7162 return node;
7165 /* Compute a schedule for a connected dependence graph by first considering
7166 * each strongly connected component (SCC) in the graph separately and then
7167 * incrementally combining them into clusters.
7168 * Return the updated schedule node.
7170 * Initially, each cluster consists of a single SCC, each with its
7171 * own band schedule. The algorithm then tries to merge pairs
7172 * of clusters along a proximity edge until no more suitable
7173 * proximity edges can be found. During this merging, the schedule
7174 * is maintained in the individual SCCs.
7175 * After the merging is completed, the full resulting clusters
7176 * are extracted and in finish_bands_clustering,
7177 * compute_schedule_finish_band is called on each of them to integrate
7178 * the band into "node" and to continue the computation.
7180 * compute_weights initializes the weights that are used by find_proximity.
7182 static __isl_give isl_schedule_node *compute_schedule_wcc_clustering(
7183 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
7185 isl_ctx *ctx;
7186 struct isl_clustering c;
7187 int i;
7189 ctx = isl_schedule_node_get_ctx(node);
7191 if (clustering_init(ctx, &c, graph) < 0)
7192 goto error;
7194 if (compute_weights(graph, &c) < 0)
7195 goto error;
7197 for (;;) {
7198 i = find_proximity(graph, &c);
7199 if (i < 0)
7200 goto error;
7201 if (i >= graph->n_edge)
7202 break;
7203 if (merge_clusters_along_edge(ctx, graph, i, &c) < 0)
7204 goto error;
7207 if (extract_clusters(ctx, graph, &c) < 0)
7208 goto error;
7210 node = finish_bands_clustering(node, graph, &c);
7212 clustering_free(ctx, &c);
7213 return node;
7214 error:
7215 clustering_free(ctx, &c);
7216 return isl_schedule_node_free(node);
7219 /* Compute a schedule for a connected dependence graph and return
7220 * the updated schedule node.
7222 * If Feautrier's algorithm is selected, we first recursively try to satisfy
7223 * as many validity dependences as possible. When all validity dependences
7224 * are satisfied we extend the schedule to a full-dimensional schedule.
7226 * Call compute_schedule_wcc_whole or compute_schedule_wcc_clustering
7227 * depending on whether the user has selected the option to try and
7228 * compute a schedule for the entire (weakly connected) component first.
7229 * If there is only a single strongly connected component (SCC), then
7230 * there is no point in trying to combine SCCs
7231 * in compute_schedule_wcc_clustering, so compute_schedule_wcc_whole
7232 * is called instead.
7234 static __isl_give isl_schedule_node *compute_schedule_wcc(
7235 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
7237 isl_ctx *ctx;
7239 if (!node)
7240 return NULL;
7242 ctx = isl_schedule_node_get_ctx(node);
7243 if (detect_sccs(ctx, graph) < 0)
7244 return isl_schedule_node_free(node);
7246 if (compute_maxvar(graph) < 0)
7247 return isl_schedule_node_free(node);
7249 if (need_feautrier_step(ctx, graph))
7250 return compute_schedule_wcc_feautrier(node, graph);
7252 if (graph->scc <= 1 || isl_options_get_schedule_whole_component(ctx))
7253 return compute_schedule_wcc_whole(node, graph);
7254 else
7255 return compute_schedule_wcc_clustering(node, graph);
7258 /* Compute a schedule for each group of nodes identified by node->scc
7259 * separately and then combine them in a sequence node (or as set node
7260 * if graph->weak is set) inserted at position "node" of the schedule tree.
7261 * Return the updated schedule node.
7263 * If "wcc" is set then each of the groups belongs to a single
7264 * weakly connected component in the dependence graph so that
7265 * there is no need for compute_sub_schedule to look for weakly
7266 * connected components.
7268 * If a set node would be introduced and if the number of components
7269 * is equal to the number of nodes, then check if the schedule
7270 * is already complete. If so, a redundant set node would be introduced
7271 * (without any further descendants) stating that the statements
7272 * can be executed in arbitrary order, which is also expressed
7273 * by the absence of any node. Refrain from inserting any nodes
7274 * in this case and simply return.
7276 static __isl_give isl_schedule_node *compute_component_schedule(
7277 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
7278 int wcc)
7280 int component;
7281 isl_ctx *ctx;
7282 isl_union_set_list *filters;
7284 if (!node)
7285 return NULL;
7287 if (graph->weak && graph->scc == graph->n) {
7288 if (compute_maxvar(graph) < 0)
7289 return isl_schedule_node_free(node);
7290 if (graph->n_row >= graph->maxvar)
7291 return node;
7294 ctx = isl_schedule_node_get_ctx(node);
7295 filters = extract_sccs(ctx, graph);
7296 if (graph->weak)
7297 node = isl_schedule_node_insert_set(node, filters);
7298 else
7299 node = isl_schedule_node_insert_sequence(node, filters);
7301 for (component = 0; component < graph->scc; ++component) {
7302 node = isl_schedule_node_child(node, component);
7303 node = isl_schedule_node_child(node, 0);
7304 node = compute_sub_schedule(node, ctx, graph,
7305 &node_scc_exactly,
7306 &edge_scc_exactly, component, wcc);
7307 node = isl_schedule_node_parent(node);
7308 node = isl_schedule_node_parent(node);
7311 return node;
7314 /* Compute a schedule for the given dependence graph and insert it at "node".
7315 * Return the updated schedule node.
7317 * We first check if the graph is connected (through validity and conditional
7318 * validity dependences) and, if not, compute a schedule
7319 * for each component separately.
7320 * If the schedule_serialize_sccs option is set, then we check for strongly
7321 * connected components instead and compute a separate schedule for
7322 * each such strongly connected component.
7324 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
7325 struct isl_sched_graph *graph)
7327 isl_ctx *ctx;
7329 if (!node)
7330 return NULL;
7332 ctx = isl_schedule_node_get_ctx(node);
7333 if (isl_options_get_schedule_serialize_sccs(ctx)) {
7334 if (detect_sccs(ctx, graph) < 0)
7335 return isl_schedule_node_free(node);
7336 } else {
7337 if (detect_wccs(ctx, graph) < 0)
7338 return isl_schedule_node_free(node);
7341 if (graph->scc > 1)
7342 return compute_component_schedule(node, graph, 1);
7344 return compute_schedule_wcc(node, graph);
7347 /* Compute a schedule on sc->domain that respects the given schedule
7348 * constraints.
7350 * In particular, the schedule respects all the validity dependences.
7351 * If the default isl scheduling algorithm is used, it tries to minimize
7352 * the dependence distances over the proximity dependences.
7353 * If Feautrier's scheduling algorithm is used, the proximity dependence
7354 * distances are only minimized during the extension to a full-dimensional
7355 * schedule.
7357 * If there are any condition and conditional validity dependences,
7358 * then the conditional validity dependences may be violated inside
7359 * a tilable band, provided they have no adjacent non-local
7360 * condition dependences.
7362 __isl_give isl_schedule *isl_schedule_constraints_compute_schedule(
7363 __isl_take isl_schedule_constraints *sc)
7365 isl_ctx *ctx = isl_schedule_constraints_get_ctx(sc);
7366 struct isl_sched_graph graph = { 0 };
7367 isl_schedule *sched;
7368 isl_schedule_node *node;
7369 isl_union_set *domain;
7371 sc = isl_schedule_constraints_align_params(sc);
7373 domain = isl_schedule_constraints_get_domain(sc);
7374 if (isl_union_set_n_set(domain) == 0) {
7375 isl_schedule_constraints_free(sc);
7376 return isl_schedule_from_domain(domain);
7379 if (graph_init(&graph, sc) < 0)
7380 domain = isl_union_set_free(domain);
7382 node = isl_schedule_node_from_domain(domain);
7383 node = isl_schedule_node_child(node, 0);
7384 if (graph.n > 0)
7385 node = compute_schedule(node, &graph);
7386 sched = isl_schedule_node_get_schedule(node);
7387 isl_schedule_node_free(node);
7389 graph_free(ctx, &graph);
7390 isl_schedule_constraints_free(sc);
7392 return sched;
7395 /* Compute a schedule for the given union of domains that respects
7396 * all the validity dependences and minimizes
7397 * the dependence distances over the proximity dependences.
7399 * This function is kept for backward compatibility.
7401 __isl_give isl_schedule *isl_union_set_compute_schedule(
7402 __isl_take isl_union_set *domain,
7403 __isl_take isl_union_map *validity,
7404 __isl_take isl_union_map *proximity)
7406 isl_schedule_constraints *sc;
7408 sc = isl_schedule_constraints_on_domain(domain);
7409 sc = isl_schedule_constraints_set_validity(sc, validity);
7410 sc = isl_schedule_constraints_set_proximity(sc, proximity);
7412 return isl_schedule_constraints_compute_schedule(sc);