clean up isl_basic_set_variable_compression_with_id
[isl.git] / isl_scheduler.c
blobca295d776ea58b01fca4a4cf2861cacb9f5c2731
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 isl_size 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 if (nvar < 0)
758 return isl_stat_error;
759 return isl_stat_ok;
762 /* Compute the number of rows that should be allocated for the schedule.
763 * In particular, we need one row for each variable or one row
764 * for each basic map in the dependences.
765 * Note that it is practically impossible to exhaust both
766 * the number of dependences and the number of variables.
768 static isl_stat compute_max_row(struct isl_sched_graph *graph,
769 __isl_keep isl_schedule_constraints *sc)
771 int n_edge;
772 isl_stat r;
773 isl_union_set *domain;
775 graph->n = 0;
776 graph->maxvar = 0;
777 domain = isl_schedule_constraints_get_domain(sc);
778 r = isl_union_set_foreach_set(domain, &init_n_maxvar, graph);
779 isl_union_set_free(domain);
780 if (r < 0)
781 return isl_stat_error;
782 n_edge = isl_schedule_constraints_n_basic_map(sc);
783 if (n_edge < 0)
784 return isl_stat_error;
785 graph->max_row = n_edge + graph->maxvar;
787 return isl_stat_ok;
790 /* Does "bset" have any defining equalities for its set variables?
792 static isl_bool has_any_defining_equality(__isl_keep isl_basic_set *bset)
794 int i;
795 isl_size n;
797 n = isl_basic_set_dim(bset, isl_dim_set);
798 if (n < 0)
799 return isl_bool_error;
801 for (i = 0; i < n; ++i) {
802 isl_bool has;
804 has = isl_basic_set_has_defining_equality(bset, isl_dim_set, i,
805 NULL);
806 if (has < 0 || has)
807 return has;
810 return isl_bool_false;
813 /* Set the entries of node->max to the value of the schedule_max_coefficient
814 * option, if set.
816 static isl_stat set_max_coefficient(isl_ctx *ctx, struct isl_sched_node *node)
818 int max;
820 max = isl_options_get_schedule_max_coefficient(ctx);
821 if (max == -1)
822 return isl_stat_ok;
824 node->max = isl_vec_alloc(ctx, node->nvar);
825 node->max = isl_vec_set_si(node->max, max);
826 if (!node->max)
827 return isl_stat_error;
829 return isl_stat_ok;
832 /* Set the entries of node->max to the minimum of the schedule_max_coefficient
833 * option (if set) and half of the minimum of the sizes in the other
834 * dimensions. Round up when computing the half such that
835 * if the minimum of the sizes is one, half of the size is taken to be one
836 * rather than zero.
837 * If the global minimum is unbounded (i.e., if both
838 * the schedule_max_coefficient is not set and the sizes in the other
839 * dimensions are unbounded), then store a negative value.
840 * If the schedule coefficient is close to the size of the instance set
841 * in another dimension, then the schedule may represent a loop
842 * coalescing transformation (especially if the coefficient
843 * in that other dimension is one). Forcing the coefficient to be
844 * smaller than or equal to half the minimal size should avoid this
845 * situation.
847 static isl_stat compute_max_coefficient(isl_ctx *ctx,
848 struct isl_sched_node *node)
850 int max;
851 int i, j;
852 isl_vec *v;
854 max = isl_options_get_schedule_max_coefficient(ctx);
855 v = isl_vec_alloc(ctx, node->nvar);
856 if (!v)
857 return isl_stat_error;
859 for (i = 0; i < node->nvar; ++i) {
860 isl_int_set_si(v->el[i], max);
861 isl_int_mul_si(v->el[i], v->el[i], 2);
864 for (i = 0; i < node->nvar; ++i) {
865 isl_val *size;
867 size = isl_multi_val_get_val(node->sizes, i);
868 if (!size)
869 goto error;
870 if (!isl_val_is_int(size)) {
871 isl_val_free(size);
872 continue;
874 for (j = 0; j < node->nvar; ++j) {
875 if (j == i)
876 continue;
877 if (isl_int_is_neg(v->el[j]) ||
878 isl_int_gt(v->el[j], size->n))
879 isl_int_set(v->el[j], size->n);
881 isl_val_free(size);
884 for (i = 0; i < node->nvar; ++i)
885 isl_int_cdiv_q_ui(v->el[i], v->el[i], 2);
887 node->max = v;
888 return isl_stat_ok;
889 error:
890 isl_vec_free(v);
891 return isl_stat_error;
894 /* Compute and return the size of "set" in dimension "dim".
895 * The size is taken to be the difference in values for that variable
896 * for fixed values of the other variables.
897 * This assumes that "set" is convex.
898 * In particular, the variable is first isolated from the other variables
899 * in the range of a map
901 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [i_dim]
903 * and then duplicated
905 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [[i_dim] -> [i_dim']]
907 * The shared variables are then projected out and the maximal value
908 * of i_dim' - i_dim is computed.
910 static __isl_give isl_val *compute_size(__isl_take isl_set *set, int dim)
912 isl_map *map;
913 isl_local_space *ls;
914 isl_aff *obj;
915 isl_val *v;
917 map = isl_set_project_onto_map(set, isl_dim_set, dim, 1);
918 map = isl_map_project_out(map, isl_dim_in, dim, 1);
919 map = isl_map_range_product(map, isl_map_copy(map));
920 map = isl_set_unwrap(isl_map_range(map));
921 set = isl_map_deltas(map);
922 ls = isl_local_space_from_space(isl_set_get_space(set));
923 obj = isl_aff_var_on_domain(ls, isl_dim_set, 0);
924 v = isl_set_max_val(set, obj);
925 isl_aff_free(obj);
926 isl_set_free(set);
928 return v;
931 /* Compute the size of the instance set "set" of "node", after compression,
932 * as well as bounds on the corresponding coefficients, if needed.
934 * The sizes are needed when the schedule_treat_coalescing option is set.
935 * The bounds are needed when the schedule_treat_coalescing option or
936 * the schedule_max_coefficient option is set.
938 * If the schedule_treat_coalescing option is not set, then at most
939 * the bounds need to be set and this is done in set_max_coefficient.
940 * Otherwise, compress the domain if needed, compute the size
941 * in each direction and store the results in node->size.
942 * If the domain is not convex, then the sizes are computed
943 * on a convex superset in order to avoid picking up sizes
944 * that are valid for the individual disjuncts, but not for
945 * the domain as a whole.
946 * Finally, set the bounds on the coefficients based on the sizes
947 * and the schedule_max_coefficient option in compute_max_coefficient.
949 static isl_stat compute_sizes_and_max(isl_ctx *ctx, struct isl_sched_node *node,
950 __isl_take isl_set *set)
952 int j;
953 isl_size n;
954 isl_multi_val *mv;
956 if (!isl_options_get_schedule_treat_coalescing(ctx)) {
957 isl_set_free(set);
958 return set_max_coefficient(ctx, node);
961 if (node->compressed)
962 set = isl_set_preimage_multi_aff(set,
963 isl_multi_aff_copy(node->decompress));
964 set = isl_set_from_basic_set(isl_set_simple_hull(set));
965 mv = isl_multi_val_zero(isl_set_get_space(set));
966 n = isl_set_dim(set, isl_dim_set);
967 if (n < 0)
968 mv = isl_multi_val_free(mv);
969 for (j = 0; j < n; ++j) {
970 isl_val *v;
972 v = compute_size(isl_set_copy(set), j);
973 mv = isl_multi_val_set_val(mv, j, v);
975 node->sizes = mv;
976 isl_set_free(set);
977 if (!node->sizes)
978 return isl_stat_error;
979 return compute_max_coefficient(ctx, node);
982 /* Add a new node to the graph representing the given instance set.
983 * "nvar" is the (possibly compressed) number of variables and
984 * may be smaller than then number of set variables in "set"
985 * if "compressed" is set.
986 * If "compressed" is set, then "hull" represents the constraints
987 * that were used to derive the compression, while "compress" and
988 * "decompress" map the original space to the compressed space and
989 * vice versa.
990 * If "compressed" is not set, then "hull", "compress" and "decompress"
991 * should be NULL.
993 * Compute the size of the instance set and bounds on the coefficients,
994 * if needed.
996 static isl_stat add_node(struct isl_sched_graph *graph,
997 __isl_take isl_set *set, int nvar, int compressed,
998 __isl_take isl_set *hull, __isl_take isl_multi_aff *compress,
999 __isl_take isl_multi_aff *decompress)
1001 isl_size nparam;
1002 isl_ctx *ctx;
1003 isl_mat *sched;
1004 isl_space *space;
1005 int *coincident;
1006 struct isl_sched_node *node;
1008 nparam = isl_set_dim(set, isl_dim_param);
1009 if (nparam < 0)
1010 goto error;
1012 ctx = isl_set_get_ctx(set);
1013 if (!ctx->opt->schedule_parametric)
1014 nparam = 0;
1015 sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
1016 node = &graph->node[graph->n];
1017 graph->n++;
1018 space = isl_set_get_space(set);
1019 node->space = space;
1020 node->nvar = nvar;
1021 node->nparam = nparam;
1022 node->sched = sched;
1023 node->sched_map = NULL;
1024 coincident = isl_calloc_array(ctx, int, graph->max_row);
1025 node->coincident = coincident;
1026 node->compressed = compressed;
1027 node->hull = hull;
1028 node->compress = compress;
1029 node->decompress = decompress;
1030 if (compute_sizes_and_max(ctx, node, set) < 0)
1031 return isl_stat_error;
1033 if (!space || !sched || (graph->max_row && !coincident))
1034 return isl_stat_error;
1035 if (compressed && (!hull || !compress || !decompress))
1036 return isl_stat_error;
1038 return isl_stat_ok;
1039 error:
1040 isl_set_free(set);
1041 isl_set_free(hull);
1042 isl_multi_aff_free(compress);
1043 isl_multi_aff_free(decompress);
1044 return isl_stat_error;
1047 /* Construct an identifier for node "node", which will represent "set".
1048 * The name of the identifier is either "compressed" or
1049 * "compressed_<name>", with <name> the name of the space of "set".
1050 * The user pointer of the identifier points to "node".
1052 static __isl_give isl_id *construct_compressed_id(__isl_keep isl_set *set,
1053 struct isl_sched_node *node)
1055 isl_bool has_name;
1056 isl_ctx *ctx;
1057 isl_id *id;
1058 isl_printer *p;
1059 const char *name;
1060 char *id_name;
1062 has_name = isl_set_has_tuple_name(set);
1063 if (has_name < 0)
1064 return NULL;
1066 ctx = isl_set_get_ctx(set);
1067 if (!has_name)
1068 return isl_id_alloc(ctx, "compressed", node);
1070 p = isl_printer_to_str(ctx);
1071 name = isl_set_get_tuple_name(set);
1072 p = isl_printer_print_str(p, "compressed_");
1073 p = isl_printer_print_str(p, name);
1074 id_name = isl_printer_get_str(p);
1075 isl_printer_free(p);
1077 id = isl_id_alloc(ctx, id_name, node);
1078 free(id_name);
1080 return id;
1083 /* Add a new node to the graph representing the given set.
1085 * If any of the set variables is defined by an equality, then
1086 * we perform variable compression such that we can perform
1087 * the scheduling on the compressed domain.
1088 * In this case, an identifier is used that references the new node
1089 * such that each compressed space is unique and
1090 * such that the node can be recovered from the compressed space.
1092 static isl_stat extract_node(__isl_take isl_set *set, void *user)
1094 isl_size nvar;
1095 isl_bool has_equality;
1096 isl_id *id;
1097 isl_basic_set *hull;
1098 isl_set *hull_set;
1099 isl_morph *morph;
1100 isl_multi_aff *compress, *decompress;
1101 struct isl_sched_graph *graph = user;
1103 hull = isl_set_affine_hull(isl_set_copy(set));
1104 hull = isl_basic_set_remove_divs(hull);
1105 nvar = isl_set_dim(set, isl_dim_set);
1106 has_equality = has_any_defining_equality(hull);
1108 if (nvar < 0 || has_equality < 0)
1109 goto error;
1110 if (!has_equality) {
1111 isl_basic_set_free(hull);
1112 return add_node(graph, set, nvar, 0, NULL, NULL, NULL);
1115 id = construct_compressed_id(set, &graph->node[graph->n]);
1116 morph = isl_basic_set_variable_compression_with_id(hull, id);
1117 isl_id_free(id);
1118 nvar = isl_morph_ran_dim(morph, isl_dim_set);
1119 if (nvar < 0)
1120 set = isl_set_free(set);
1121 compress = isl_morph_get_var_multi_aff(morph);
1122 morph = isl_morph_inverse(morph);
1123 decompress = isl_morph_get_var_multi_aff(morph);
1124 isl_morph_free(morph);
1126 hull_set = isl_set_from_basic_set(hull);
1127 return add_node(graph, set, nvar, 1, hull_set, compress, decompress);
1128 error:
1129 isl_basic_set_free(hull);
1130 isl_set_free(set);
1131 return isl_stat_error;
1134 struct isl_extract_edge_data {
1135 enum isl_edge_type type;
1136 struct isl_sched_graph *graph;
1139 /* Merge edge2 into edge1, freeing the contents of edge2.
1140 * Return 0 on success and -1 on failure.
1142 * edge1 and edge2 are assumed to have the same value for the map field.
1144 static int merge_edge(struct isl_sched_edge *edge1,
1145 struct isl_sched_edge *edge2)
1147 edge1->types |= edge2->types;
1148 isl_map_free(edge2->map);
1150 if (is_condition(edge2)) {
1151 if (!edge1->tagged_condition)
1152 edge1->tagged_condition = edge2->tagged_condition;
1153 else
1154 edge1->tagged_condition =
1155 isl_union_map_union(edge1->tagged_condition,
1156 edge2->tagged_condition);
1159 if (is_conditional_validity(edge2)) {
1160 if (!edge1->tagged_validity)
1161 edge1->tagged_validity = edge2->tagged_validity;
1162 else
1163 edge1->tagged_validity =
1164 isl_union_map_union(edge1->tagged_validity,
1165 edge2->tagged_validity);
1168 if (is_condition(edge2) && !edge1->tagged_condition)
1169 return -1;
1170 if (is_conditional_validity(edge2) && !edge1->tagged_validity)
1171 return -1;
1173 return 0;
1176 /* Insert dummy tags in domain and range of "map".
1178 * In particular, if "map" is of the form
1180 * A -> B
1182 * then return
1184 * [A -> dummy_tag] -> [B -> dummy_tag]
1186 * where the dummy_tags are identical and equal to any dummy tags
1187 * introduced by any other call to this function.
1189 static __isl_give isl_map *insert_dummy_tags(__isl_take isl_map *map)
1191 static char dummy;
1192 isl_ctx *ctx;
1193 isl_id *id;
1194 isl_space *space;
1195 isl_set *domain, *range;
1197 ctx = isl_map_get_ctx(map);
1199 id = isl_id_alloc(ctx, NULL, &dummy);
1200 space = isl_space_params(isl_map_get_space(map));
1201 space = isl_space_set_from_params(space);
1202 space = isl_space_set_tuple_id(space, isl_dim_set, id);
1203 space = isl_space_map_from_set(space);
1205 domain = isl_map_wrap(map);
1206 range = isl_map_wrap(isl_map_universe(space));
1207 map = isl_map_from_domain_and_range(domain, range);
1208 map = isl_map_zip(map);
1210 return map;
1213 /* Given that at least one of "src" or "dst" is compressed, return
1214 * a map between the spaces of these nodes restricted to the affine
1215 * hull that was used in the compression.
1217 static __isl_give isl_map *extract_hull(struct isl_sched_node *src,
1218 struct isl_sched_node *dst)
1220 isl_set *dom, *ran;
1222 if (src->compressed)
1223 dom = isl_set_copy(src->hull);
1224 else
1225 dom = isl_set_universe(isl_space_copy(src->space));
1226 if (dst->compressed)
1227 ran = isl_set_copy(dst->hull);
1228 else
1229 ran = isl_set_universe(isl_space_copy(dst->space));
1231 return isl_map_from_domain_and_range(dom, ran);
1234 /* Intersect the domains of the nested relations in domain and range
1235 * of "tagged" with "map".
1237 static __isl_give isl_map *map_intersect_domains(__isl_take isl_map *tagged,
1238 __isl_keep isl_map *map)
1240 isl_set *set;
1242 tagged = isl_map_zip(tagged);
1243 set = isl_map_wrap(isl_map_copy(map));
1244 tagged = isl_map_intersect_domain(tagged, set);
1245 tagged = isl_map_zip(tagged);
1246 return tagged;
1249 /* Return a pointer to the node that lives in the domain space of "map",
1250 * an invalid node if there is no such node, or NULL in case of error.
1252 static struct isl_sched_node *find_domain_node(isl_ctx *ctx,
1253 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1255 struct isl_sched_node *node;
1256 isl_space *space;
1258 space = isl_space_domain(isl_map_get_space(map));
1259 node = graph_find_node(ctx, graph, space);
1260 isl_space_free(space);
1262 return node;
1265 /* Return a pointer to the node that lives in the range space of "map",
1266 * an invalid node if there is no such node, or NULL in case of error.
1268 static struct isl_sched_node *find_range_node(isl_ctx *ctx,
1269 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1271 struct isl_sched_node *node;
1272 isl_space *space;
1274 space = isl_space_range(isl_map_get_space(map));
1275 node = graph_find_node(ctx, graph, space);
1276 isl_space_free(space);
1278 return node;
1281 /* Refrain from adding a new edge based on "map".
1282 * Instead, just free the map.
1283 * "tagged" is either a copy of "map" with additional tags or NULL.
1285 static isl_stat skip_edge(__isl_take isl_map *map, __isl_take isl_map *tagged)
1287 isl_map_free(map);
1288 isl_map_free(tagged);
1290 return isl_stat_ok;
1293 /* Add a new edge to the graph based on the given map
1294 * and add it to data->graph->edge_table[data->type].
1295 * If a dependence relation of a given type happens to be identical
1296 * to one of the dependence relations of a type that was added before,
1297 * then we don't create a new edge, but instead mark the original edge
1298 * as also representing a dependence of the current type.
1300 * Edges of type isl_edge_condition or isl_edge_conditional_validity
1301 * may be specified as "tagged" dependence relations. That is, "map"
1302 * may contain elements (i -> a) -> (j -> b), where i -> j denotes
1303 * the dependence on iterations and a and b are tags.
1304 * edge->map is set to the relation containing the elements i -> j,
1305 * while edge->tagged_condition and edge->tagged_validity contain
1306 * the union of all the "map" relations
1307 * for which extract_edge is called that result in the same edge->map.
1309 * If the source or the destination node is compressed, then
1310 * intersect both "map" and "tagged" with the constraints that
1311 * were used to construct the compression.
1312 * This ensures that there are no schedule constraints defined
1313 * outside of these domains, while the scheduler no longer has
1314 * any control over those outside parts.
1316 static isl_stat extract_edge(__isl_take isl_map *map, void *user)
1318 isl_bool empty;
1319 isl_ctx *ctx = isl_map_get_ctx(map);
1320 struct isl_extract_edge_data *data = user;
1321 struct isl_sched_graph *graph = data->graph;
1322 struct isl_sched_node *src, *dst;
1323 struct isl_sched_edge *edge;
1324 isl_map *tagged = NULL;
1326 if (data->type == isl_edge_condition ||
1327 data->type == isl_edge_conditional_validity) {
1328 if (isl_map_can_zip(map)) {
1329 tagged = isl_map_copy(map);
1330 map = isl_set_unwrap(isl_map_domain(isl_map_zip(map)));
1331 } else {
1332 tagged = insert_dummy_tags(isl_map_copy(map));
1336 src = find_domain_node(ctx, graph, map);
1337 dst = find_range_node(ctx, graph, map);
1339 if (!src || !dst)
1340 goto error;
1341 if (!is_node(graph, src) || !is_node(graph, dst))
1342 return skip_edge(map, tagged);
1344 if (src->compressed || dst->compressed) {
1345 isl_map *hull;
1346 hull = extract_hull(src, dst);
1347 if (tagged)
1348 tagged = map_intersect_domains(tagged, hull);
1349 map = isl_map_intersect(map, hull);
1352 empty = isl_map_plain_is_empty(map);
1353 if (empty < 0)
1354 goto error;
1355 if (empty)
1356 return skip_edge(map, tagged);
1358 graph->edge[graph->n_edge].src = src;
1359 graph->edge[graph->n_edge].dst = dst;
1360 graph->edge[graph->n_edge].map = map;
1361 graph->edge[graph->n_edge].types = 0;
1362 graph->edge[graph->n_edge].tagged_condition = NULL;
1363 graph->edge[graph->n_edge].tagged_validity = NULL;
1364 set_type(&graph->edge[graph->n_edge], data->type);
1365 if (data->type == isl_edge_condition)
1366 graph->edge[graph->n_edge].tagged_condition =
1367 isl_union_map_from_map(tagged);
1368 if (data->type == isl_edge_conditional_validity)
1369 graph->edge[graph->n_edge].tagged_validity =
1370 isl_union_map_from_map(tagged);
1372 edge = graph_find_matching_edge(graph, &graph->edge[graph->n_edge]);
1373 if (!edge) {
1374 graph->n_edge++;
1375 return isl_stat_error;
1377 if (edge == &graph->edge[graph->n_edge])
1378 return graph_edge_table_add(ctx, graph, data->type,
1379 &graph->edge[graph->n_edge++]);
1381 if (merge_edge(edge, &graph->edge[graph->n_edge]) < 0)
1382 return isl_stat_error;
1384 return graph_edge_table_add(ctx, graph, data->type, edge);
1385 error:
1386 isl_map_free(map);
1387 isl_map_free(tagged);
1388 return isl_stat_error;
1391 /* Initialize the schedule graph "graph" from the schedule constraints "sc".
1393 * The context is included in the domain before the nodes of
1394 * the graphs are extracted in order to be able to exploit
1395 * any possible additional equalities.
1396 * Note that this intersection is only performed locally here.
1398 static isl_stat graph_init(struct isl_sched_graph *graph,
1399 __isl_keep isl_schedule_constraints *sc)
1401 isl_ctx *ctx;
1402 isl_union_set *domain;
1403 isl_union_map *c;
1404 struct isl_extract_edge_data data;
1405 enum isl_edge_type i;
1406 isl_stat r;
1407 isl_size n;
1409 if (!sc)
1410 return isl_stat_error;
1412 ctx = isl_schedule_constraints_get_ctx(sc);
1414 domain = isl_schedule_constraints_get_domain(sc);
1415 n = isl_union_set_n_set(domain);
1416 graph->n = n;
1417 isl_union_set_free(domain);
1418 if (n < 0)
1419 return isl_stat_error;
1421 n = isl_schedule_constraints_n_map(sc);
1422 if (n < 0 || graph_alloc(ctx, graph, graph->n, n) < 0)
1423 return isl_stat_error;
1425 if (compute_max_row(graph, sc) < 0)
1426 return isl_stat_error;
1427 graph->root = graph;
1428 graph->n = 0;
1429 domain = isl_schedule_constraints_get_domain(sc);
1430 domain = isl_union_set_intersect_params(domain,
1431 isl_schedule_constraints_get_context(sc));
1432 r = isl_union_set_foreach_set(domain, &extract_node, graph);
1433 isl_union_set_free(domain);
1434 if (r < 0)
1435 return isl_stat_error;
1436 if (graph_init_table(ctx, graph) < 0)
1437 return isl_stat_error;
1438 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1439 isl_size n;
1441 c = isl_schedule_constraints_get(sc, i);
1442 n = isl_union_map_n_map(c);
1443 graph->max_edge[i] = n;
1444 isl_union_map_free(c);
1445 if (n < 0)
1446 return isl_stat_error;
1448 if (graph_init_edge_tables(ctx, graph) < 0)
1449 return isl_stat_error;
1450 graph->n_edge = 0;
1451 data.graph = graph;
1452 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1453 isl_stat r;
1455 data.type = i;
1456 c = isl_schedule_constraints_get(sc, i);
1457 r = isl_union_map_foreach_map(c, &extract_edge, &data);
1458 isl_union_map_free(c);
1459 if (r < 0)
1460 return isl_stat_error;
1463 return isl_stat_ok;
1466 /* Check whether there is any dependence from node[j] to node[i]
1467 * or from node[i] to node[j].
1469 static isl_bool node_follows_weak(int i, int j, void *user)
1471 isl_bool f;
1472 struct isl_sched_graph *graph = user;
1474 f = graph_has_any_edge(graph, &graph->node[j], &graph->node[i]);
1475 if (f < 0 || f)
1476 return f;
1477 return graph_has_any_edge(graph, &graph->node[i], &graph->node[j]);
1480 /* Check whether there is a (conditional) validity dependence from node[j]
1481 * to node[i], forcing node[i] to follow node[j].
1483 static isl_bool node_follows_strong(int i, int j, void *user)
1485 struct isl_sched_graph *graph = user;
1487 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
1490 /* Use Tarjan's algorithm for computing the strongly connected components
1491 * in the dependence graph only considering those edges defined by "follows".
1493 static isl_stat detect_ccs(isl_ctx *ctx, struct isl_sched_graph *graph,
1494 isl_bool (*follows)(int i, int j, void *user))
1496 int i, n;
1497 struct isl_tarjan_graph *g = NULL;
1499 g = isl_tarjan_graph_init(ctx, graph->n, follows, graph);
1500 if (!g)
1501 return isl_stat_error;
1503 graph->scc = 0;
1504 i = 0;
1505 n = graph->n;
1506 while (n) {
1507 while (g->order[i] != -1) {
1508 graph->node[g->order[i]].scc = graph->scc;
1509 --n;
1510 ++i;
1512 ++i;
1513 graph->scc++;
1516 isl_tarjan_graph_free(g);
1518 return isl_stat_ok;
1521 /* Apply Tarjan's algorithm to detect the strongly connected components
1522 * in the dependence graph.
1523 * Only consider the (conditional) validity dependences and clear "weak".
1525 static isl_stat detect_sccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1527 graph->weak = 0;
1528 return detect_ccs(ctx, graph, &node_follows_strong);
1531 /* Apply Tarjan's algorithm to detect the (weakly) connected components
1532 * in the dependence graph.
1533 * Consider all dependences and set "weak".
1535 static isl_stat detect_wccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1537 graph->weak = 1;
1538 return detect_ccs(ctx, graph, &node_follows_weak);
1541 static int cmp_scc(const void *a, const void *b, void *data)
1543 struct isl_sched_graph *graph = data;
1544 const int *i1 = a;
1545 const int *i2 = b;
1547 return graph->node[*i1].scc - graph->node[*i2].scc;
1550 /* Sort the elements of graph->sorted according to the corresponding SCCs.
1552 static int sort_sccs(struct isl_sched_graph *graph)
1554 return isl_sort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
1557 /* Return a non-parametric set in the compressed space of "node" that is
1558 * bounded by the size in each direction
1560 * { [x] : -S_i <= x_i <= S_i }
1562 * If S_i is infinity in direction i, then there are no constraints
1563 * in that direction.
1565 * Cache the result in node->bounds.
1567 static __isl_give isl_basic_set *get_size_bounds(struct isl_sched_node *node)
1569 isl_space *space;
1570 isl_basic_set *bounds;
1571 int i;
1573 if (node->bounds)
1574 return isl_basic_set_copy(node->bounds);
1576 if (node->compressed)
1577 space = isl_multi_aff_get_domain_space(node->decompress);
1578 else
1579 space = isl_space_copy(node->space);
1580 space = isl_space_drop_all_params(space);
1581 bounds = isl_basic_set_universe(space);
1583 for (i = 0; i < node->nvar; ++i) {
1584 isl_val *size;
1586 size = isl_multi_val_get_val(node->sizes, i);
1587 if (!size)
1588 return isl_basic_set_free(bounds);
1589 if (!isl_val_is_int(size)) {
1590 isl_val_free(size);
1591 continue;
1593 bounds = isl_basic_set_upper_bound_val(bounds, isl_dim_set, i,
1594 isl_val_copy(size));
1595 bounds = isl_basic_set_lower_bound_val(bounds, isl_dim_set, i,
1596 isl_val_neg(size));
1599 node->bounds = isl_basic_set_copy(bounds);
1600 return bounds;
1603 /* Drop some constraints from "delta" that could be exploited
1604 * to construct loop coalescing schedules.
1605 * In particular, drop those constraint that bound the difference
1606 * to the size of the domain.
1607 * First project out the parameters to improve the effectiveness.
1609 static __isl_give isl_set *drop_coalescing_constraints(
1610 __isl_take isl_set *delta, struct isl_sched_node *node)
1612 isl_size nparam;
1613 isl_basic_set *bounds;
1615 nparam = isl_set_dim(delta, isl_dim_param);
1616 if (nparam < 0)
1617 return isl_set_free(delta);
1619 bounds = get_size_bounds(node);
1621 delta = isl_set_project_out(delta, isl_dim_param, 0, nparam);
1622 delta = isl_set_remove_divs(delta);
1623 delta = isl_set_plain_gist_basic_set(delta, bounds);
1624 return delta;
1627 /* Given a dependence relation R from "node" to itself,
1628 * construct the set of coefficients of valid constraints for elements
1629 * in that dependence relation.
1630 * In particular, the result contains tuples of coefficients
1631 * c_0, c_n, c_x such that
1633 * c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
1635 * or, equivalently,
1637 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
1639 * We choose here to compute the dual of delta R.
1640 * Alternatively, we could have computed the dual of R, resulting
1641 * in a set of tuples c_0, c_n, c_x, c_y, and then
1642 * plugged in (c_0, c_n, c_x, -c_x).
1644 * If "need_param" is set, then the resulting coefficients effectively
1645 * include coefficients for the parameters c_n. Otherwise, they may
1646 * have been projected out already.
1647 * Since the constraints may be different for these two cases,
1648 * they are stored in separate caches.
1649 * In particular, if no parameter coefficients are required and
1650 * the schedule_treat_coalescing option is set, then the parameters
1651 * are projected out and some constraints that could be exploited
1652 * to construct coalescing schedules are removed before the dual
1653 * is computed.
1655 * If "node" has been compressed, then the dependence relation
1656 * is also compressed before the set of coefficients is computed.
1658 static __isl_give isl_basic_set *intra_coefficients(
1659 struct isl_sched_graph *graph, struct isl_sched_node *node,
1660 __isl_take isl_map *map, int need_param)
1662 isl_ctx *ctx;
1663 isl_set *delta;
1664 isl_map *key;
1665 isl_basic_set *coef;
1666 isl_maybe_isl_basic_set m;
1667 isl_map_to_basic_set **hmap = &graph->intra_hmap;
1668 int treat;
1670 if (!map)
1671 return NULL;
1673 ctx = isl_map_get_ctx(map);
1674 treat = !need_param && isl_options_get_schedule_treat_coalescing(ctx);
1675 if (!treat)
1676 hmap = &graph->intra_hmap_param;
1677 m = isl_map_to_basic_set_try_get(*hmap, map);
1678 if (m.valid < 0 || m.valid) {
1679 isl_map_free(map);
1680 return m.value;
1683 key = isl_map_copy(map);
1684 if (node->compressed) {
1685 map = isl_map_preimage_domain_multi_aff(map,
1686 isl_multi_aff_copy(node->decompress));
1687 map = isl_map_preimage_range_multi_aff(map,
1688 isl_multi_aff_copy(node->decompress));
1690 delta = isl_map_deltas(map);
1691 if (treat)
1692 delta = drop_coalescing_constraints(delta, node);
1693 delta = isl_set_remove_divs(delta);
1694 coef = isl_set_coefficients(delta);
1695 *hmap = isl_map_to_basic_set_set(*hmap, key, isl_basic_set_copy(coef));
1697 return coef;
1700 /* Given a dependence relation R, construct the set of coefficients
1701 * of valid constraints for elements in that dependence relation.
1702 * In particular, the result contains tuples of coefficients
1703 * c_0, c_n, c_x, c_y such that
1705 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
1707 * If the source or destination nodes of "edge" have been compressed,
1708 * then the dependence relation is also compressed before
1709 * the set of coefficients is computed.
1711 static __isl_give isl_basic_set *inter_coefficients(
1712 struct isl_sched_graph *graph, struct isl_sched_edge *edge,
1713 __isl_take isl_map *map)
1715 isl_set *set;
1716 isl_map *key;
1717 isl_basic_set *coef;
1718 isl_maybe_isl_basic_set m;
1720 m = isl_map_to_basic_set_try_get(graph->inter_hmap, map);
1721 if (m.valid < 0 || m.valid) {
1722 isl_map_free(map);
1723 return m.value;
1726 key = isl_map_copy(map);
1727 if (edge->src->compressed)
1728 map = isl_map_preimage_domain_multi_aff(map,
1729 isl_multi_aff_copy(edge->src->decompress));
1730 if (edge->dst->compressed)
1731 map = isl_map_preimage_range_multi_aff(map,
1732 isl_multi_aff_copy(edge->dst->decompress));
1733 set = isl_map_wrap(isl_map_remove_divs(map));
1734 coef = isl_set_coefficients(set);
1735 graph->inter_hmap = isl_map_to_basic_set_set(graph->inter_hmap, key,
1736 isl_basic_set_copy(coef));
1738 return coef;
1741 /* Return the position of the coefficients of the variables in
1742 * the coefficients constraints "coef".
1744 * The space of "coef" is of the form
1746 * { coefficients[[cst, params] -> S] }
1748 * Return the position of S.
1750 static isl_size coef_var_offset(__isl_keep isl_basic_set *coef)
1752 isl_size offset;
1753 isl_space *space;
1755 space = isl_space_unwrap(isl_basic_set_get_space(coef));
1756 offset = isl_space_dim(space, isl_dim_in);
1757 isl_space_free(space);
1759 return offset;
1762 /* Return the offset of the coefficient of the constant term of "node"
1763 * within the (I)LP.
1765 * Within each node, the coefficients have the following order:
1766 * - positive and negative parts of c_i_x
1767 * - c_i_n (if parametric)
1768 * - c_i_0
1770 static int node_cst_coef_offset(struct isl_sched_node *node)
1772 return node->start + 2 * node->nvar + node->nparam;
1775 /* Return the offset of the coefficients of the parameters of "node"
1776 * within the (I)LP.
1778 * Within each node, the coefficients have the following order:
1779 * - positive and negative parts of c_i_x
1780 * - c_i_n (if parametric)
1781 * - c_i_0
1783 static int node_par_coef_offset(struct isl_sched_node *node)
1785 return node->start + 2 * node->nvar;
1788 /* Return the offset of the coefficients of the variables of "node"
1789 * within the (I)LP.
1791 * Within each node, the coefficients have the following order:
1792 * - positive and negative parts of c_i_x
1793 * - c_i_n (if parametric)
1794 * - c_i_0
1796 static int node_var_coef_offset(struct isl_sched_node *node)
1798 return node->start;
1801 /* Return the position of the pair of variables encoding
1802 * coefficient "i" of "node".
1804 * The order of these variable pairs is the opposite of
1805 * that of the coefficients, with 2 variables per coefficient.
1807 static int node_var_coef_pos(struct isl_sched_node *node, int i)
1809 return node_var_coef_offset(node) + 2 * (node->nvar - 1 - i);
1812 /* Construct an isl_dim_map for mapping constraints on coefficients
1813 * for "node" to the corresponding positions in graph->lp.
1814 * "offset" is the offset of the coefficients for the variables
1815 * in the input constraints.
1816 * "s" is the sign of the mapping.
1818 * The input constraints are given in terms of the coefficients
1819 * (c_0, c_x) or (c_0, c_n, c_x).
1820 * The mapping produced by this function essentially plugs in
1821 * (0, c_i_x^+ - c_i_x^-) if s = 1 and
1822 * (0, -c_i_x^+ + c_i_x^-) if s = -1 or
1823 * (0, 0, c_i_x^+ - c_i_x^-) if s = 1 and
1824 * (0, 0, -c_i_x^+ + c_i_x^-) if s = -1.
1825 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1826 * Furthermore, the order of these pairs is the opposite of that
1827 * of the corresponding coefficients.
1829 * The caller can extend the mapping to also map the other coefficients
1830 * (and therefore not plug in 0).
1832 static __isl_give isl_dim_map *intra_dim_map(isl_ctx *ctx,
1833 struct isl_sched_graph *graph, struct isl_sched_node *node,
1834 int offset, int s)
1836 int pos;
1837 isl_size total;
1838 isl_dim_map *dim_map;
1840 total = isl_basic_set_dim(graph->lp, isl_dim_all);
1841 if (!node || total < 0)
1842 return NULL;
1844 pos = node_var_coef_pos(node, 0);
1845 dim_map = isl_dim_map_alloc(ctx, total);
1846 isl_dim_map_range(dim_map, pos, -2, offset, 1, node->nvar, -s);
1847 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, node->nvar, s);
1849 return dim_map;
1852 /* Construct an isl_dim_map for mapping constraints on coefficients
1853 * for "src" (node i) and "dst" (node j) to the corresponding positions
1854 * in graph->lp.
1855 * "offset" is the offset of the coefficients for the variables of "src"
1856 * in the input constraints.
1857 * "s" is the sign of the mapping.
1859 * The input constraints are given in terms of the coefficients
1860 * (c_0, c_n, c_x, c_y).
1861 * The mapping produced by this function essentially plugs in
1862 * (c_j_0 - c_i_0, c_j_n - c_i_n,
1863 * -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-) if s = 1 and
1864 * (-c_j_0 + c_i_0, -c_j_n + c_i_n,
1865 * c_i_x^+ - c_i_x^-, -(c_j_x^+ - c_j_x^-)) if s = -1.
1866 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1867 * Furthermore, the order of these pairs is the opposite of that
1868 * of the corresponding coefficients.
1870 * The caller can further extend the mapping.
1872 static __isl_give isl_dim_map *inter_dim_map(isl_ctx *ctx,
1873 struct isl_sched_graph *graph, struct isl_sched_node *src,
1874 struct isl_sched_node *dst, int offset, int s)
1876 int pos;
1877 isl_size total;
1878 isl_dim_map *dim_map;
1880 total = isl_basic_set_dim(graph->lp, isl_dim_all);
1881 if (!src || !dst || total < 0)
1882 return NULL;
1884 dim_map = isl_dim_map_alloc(ctx, total);
1886 pos = node_cst_coef_offset(dst);
1887 isl_dim_map_range(dim_map, pos, 0, 0, 0, 1, s);
1888 pos = node_par_coef_offset(dst);
1889 isl_dim_map_range(dim_map, pos, 1, 1, 1, dst->nparam, s);
1890 pos = node_var_coef_pos(dst, 0);
1891 isl_dim_map_range(dim_map, pos, -2, offset + src->nvar, 1,
1892 dst->nvar, -s);
1893 isl_dim_map_range(dim_map, pos + 1, -2, offset + src->nvar, 1,
1894 dst->nvar, s);
1896 pos = node_cst_coef_offset(src);
1897 isl_dim_map_range(dim_map, pos, 0, 0, 0, 1, -s);
1898 pos = node_par_coef_offset(src);
1899 isl_dim_map_range(dim_map, pos, 1, 1, 1, src->nparam, -s);
1900 pos = node_var_coef_pos(src, 0);
1901 isl_dim_map_range(dim_map, pos, -2, offset, 1, src->nvar, s);
1902 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, src->nvar, -s);
1904 return dim_map;
1907 /* Add the constraints from "src" to "dst" using "dim_map",
1908 * after making sure there is enough room in "dst" for the extra constraints.
1910 static __isl_give isl_basic_set *add_constraints_dim_map(
1911 __isl_take isl_basic_set *dst, __isl_take isl_basic_set *src,
1912 __isl_take isl_dim_map *dim_map)
1914 int n_eq, n_ineq;
1916 n_eq = isl_basic_set_n_equality(src);
1917 n_ineq = isl_basic_set_n_inequality(src);
1918 dst = isl_basic_set_extend_constraints(dst, n_eq, n_ineq);
1919 dst = isl_basic_set_add_constraints_dim_map(dst, src, dim_map);
1920 return dst;
1923 /* Add constraints to graph->lp that force validity for the given
1924 * dependence from a node i to itself.
1925 * That is, add constraints that enforce
1927 * (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
1928 * = c_i_x (y - x) >= 0
1930 * for each (x,y) in R.
1931 * We obtain general constraints on coefficients (c_0, c_x)
1932 * of valid constraints for (y - x) and then plug in (0, c_i_x^+ - c_i_x^-),
1933 * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
1934 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1935 * Note that the result of intra_coefficients may also contain
1936 * parameter coefficients c_n, in which case 0 is plugged in for them as well.
1938 static isl_stat add_intra_validity_constraints(struct isl_sched_graph *graph,
1939 struct isl_sched_edge *edge)
1941 isl_size offset;
1942 isl_map *map = isl_map_copy(edge->map);
1943 isl_ctx *ctx = isl_map_get_ctx(map);
1944 isl_dim_map *dim_map;
1945 isl_basic_set *coef;
1946 struct isl_sched_node *node = edge->src;
1948 coef = intra_coefficients(graph, node, map, 0);
1950 offset = coef_var_offset(coef);
1951 if (offset < 0)
1952 coef = isl_basic_set_free(coef);
1953 if (!coef)
1954 return isl_stat_error;
1956 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
1957 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1959 return isl_stat_ok;
1962 /* Add constraints to graph->lp that force validity for the given
1963 * dependence from node i to node j.
1964 * That is, add constraints that enforce
1966 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
1968 * for each (x,y) in R.
1969 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1970 * of valid constraints for R and then plug in
1971 * (c_j_0 - c_i_0, c_j_n - c_i_n, -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-),
1972 * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
1973 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1975 static isl_stat add_inter_validity_constraints(struct isl_sched_graph *graph,
1976 struct isl_sched_edge *edge)
1978 isl_size offset;
1979 isl_map *map;
1980 isl_ctx *ctx;
1981 isl_dim_map *dim_map;
1982 isl_basic_set *coef;
1983 struct isl_sched_node *src = edge->src;
1984 struct isl_sched_node *dst = edge->dst;
1986 if (!graph->lp)
1987 return isl_stat_error;
1989 map = isl_map_copy(edge->map);
1990 ctx = isl_map_get_ctx(map);
1991 coef = inter_coefficients(graph, edge, map);
1993 offset = coef_var_offset(coef);
1994 if (offset < 0)
1995 coef = isl_basic_set_free(coef);
1996 if (!coef)
1997 return isl_stat_error;
1999 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
2001 edge->start = graph->lp->n_ineq;
2002 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
2003 if (!graph->lp)
2004 return isl_stat_error;
2005 edge->end = graph->lp->n_ineq;
2007 return isl_stat_ok;
2010 /* Add constraints to graph->lp that bound the dependence distance for the given
2011 * dependence from a node i to itself.
2012 * If s = 1, we add the constraint
2014 * c_i_x (y - x) <= m_0 + m_n n
2016 * or
2018 * -c_i_x (y - x) + m_0 + m_n n >= 0
2020 * for each (x,y) in R.
2021 * If s = -1, we add the constraint
2023 * -c_i_x (y - x) <= m_0 + m_n n
2025 * or
2027 * c_i_x (y - x) + m_0 + m_n n >= 0
2029 * for each (x,y) in R.
2030 * We obtain general constraints on coefficients (c_0, c_n, c_x)
2031 * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
2032 * with each coefficient (except m_0) represented as a pair of non-negative
2033 * coefficients.
2036 * If "local" is set, then we add constraints
2038 * c_i_x (y - x) <= 0
2040 * or
2042 * -c_i_x (y - x) <= 0
2044 * instead, forcing the dependence distance to be (less than or) equal to 0.
2045 * That is, we plug in (0, 0, -s * c_i_x),
2046 * intra_coefficients is not required to have c_n in its result when
2047 * "local" is set. If they are missing, then (0, -s * c_i_x) is plugged in.
2048 * Note that dependences marked local are treated as validity constraints
2049 * by add_all_validity_constraints and therefore also have
2050 * their distances bounded by 0 from below.
2052 static isl_stat add_intra_proximity_constraints(struct isl_sched_graph *graph,
2053 struct isl_sched_edge *edge, int s, int local)
2055 isl_size offset;
2056 isl_size nparam;
2057 isl_map *map = isl_map_copy(edge->map);
2058 isl_ctx *ctx = isl_map_get_ctx(map);
2059 isl_dim_map *dim_map;
2060 isl_basic_set *coef;
2061 struct isl_sched_node *node = edge->src;
2063 coef = intra_coefficients(graph, node, map, !local);
2064 nparam = isl_space_dim(node->space, isl_dim_param);
2066 offset = coef_var_offset(coef);
2067 if (nparam < 0 || offset < 0)
2068 coef = isl_basic_set_free(coef);
2069 if (!coef)
2070 return isl_stat_error;
2072 dim_map = intra_dim_map(ctx, graph, node, offset, -s);
2074 if (!local) {
2075 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
2076 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
2077 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
2079 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
2081 return isl_stat_ok;
2084 /* Add constraints to graph->lp that bound the dependence distance for the given
2085 * dependence from node i to node j.
2086 * If s = 1, we add the constraint
2088 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
2089 * <= m_0 + m_n n
2091 * or
2093 * -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
2094 * m_0 + m_n n >= 0
2096 * for each (x,y) in R.
2097 * If s = -1, we add the constraint
2099 * -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
2100 * <= m_0 + m_n n
2102 * or
2104 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
2105 * m_0 + m_n n >= 0
2107 * for each (x,y) in R.
2108 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
2109 * of valid constraints for R and then plug in
2110 * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
2111 * s*c_i_x, -s*c_j_x)
2112 * with each coefficient (except m_0, c_*_0 and c_*_n)
2113 * represented as a pair of non-negative coefficients.
2116 * If "local" is set (and s = 1), then we add constraints
2118 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) <= 0
2120 * or
2122 * -((c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x)) >= 0
2124 * instead, forcing the dependence distance to be (less than or) equal to 0.
2125 * That is, we plug in
2126 * (-s*c_j_0 + s*c_i_0, -s*c_j_n + s*c_i_n, s*c_i_x, -s*c_j_x).
2127 * Note that dependences marked local are treated as validity constraints
2128 * by add_all_validity_constraints and therefore also have
2129 * their distances bounded by 0 from below.
2131 static isl_stat add_inter_proximity_constraints(struct isl_sched_graph *graph,
2132 struct isl_sched_edge *edge, int s, int local)
2134 isl_size offset;
2135 isl_size nparam;
2136 isl_map *map = isl_map_copy(edge->map);
2137 isl_ctx *ctx = isl_map_get_ctx(map);
2138 isl_dim_map *dim_map;
2139 isl_basic_set *coef;
2140 struct isl_sched_node *src = edge->src;
2141 struct isl_sched_node *dst = edge->dst;
2143 coef = inter_coefficients(graph, edge, map);
2144 nparam = isl_space_dim(src->space, isl_dim_param);
2146 offset = coef_var_offset(coef);
2147 if (nparam < 0 || offset < 0)
2148 coef = isl_basic_set_free(coef);
2149 if (!coef)
2150 return isl_stat_error;
2152 dim_map = inter_dim_map(ctx, graph, src, dst, offset, -s);
2154 if (!local) {
2155 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
2156 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
2157 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
2160 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
2162 return isl_stat_ok;
2165 /* Should the distance over "edge" be forced to zero?
2166 * That is, is it marked as a local edge?
2167 * If "use_coincidence" is set, then coincidence edges are treated
2168 * as local edges.
2170 static int force_zero(struct isl_sched_edge *edge, int use_coincidence)
2172 return is_local(edge) || (use_coincidence && is_coincidence(edge));
2175 /* Add all validity constraints to graph->lp.
2177 * An edge that is forced to be local needs to have its dependence
2178 * distances equal to zero. We take care of bounding them by 0 from below
2179 * here. add_all_proximity_constraints takes care of bounding them by 0
2180 * from above.
2182 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2183 * Otherwise, we ignore them.
2185 static int add_all_validity_constraints(struct isl_sched_graph *graph,
2186 int use_coincidence)
2188 int i;
2190 for (i = 0; i < graph->n_edge; ++i) {
2191 struct isl_sched_edge *edge = &graph->edge[i];
2192 int zero;
2194 zero = force_zero(edge, use_coincidence);
2195 if (!is_validity(edge) && !zero)
2196 continue;
2197 if (edge->src != edge->dst)
2198 continue;
2199 if (add_intra_validity_constraints(graph, edge) < 0)
2200 return -1;
2203 for (i = 0; i < graph->n_edge; ++i) {
2204 struct isl_sched_edge *edge = &graph->edge[i];
2205 int zero;
2207 zero = force_zero(edge, use_coincidence);
2208 if (!is_validity(edge) && !zero)
2209 continue;
2210 if (edge->src == edge->dst)
2211 continue;
2212 if (add_inter_validity_constraints(graph, edge) < 0)
2213 return -1;
2216 return 0;
2219 /* Add constraints to graph->lp that bound the dependence distance
2220 * for all dependence relations.
2221 * If a given proximity dependence is identical to a validity
2222 * dependence, then the dependence distance is already bounded
2223 * from below (by zero), so we only need to bound the distance
2224 * from above. (This includes the case of "local" dependences
2225 * which are treated as validity dependence by add_all_validity_constraints.)
2226 * Otherwise, we need to bound the distance both from above and from below.
2228 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2229 * Otherwise, we ignore them.
2231 static int add_all_proximity_constraints(struct isl_sched_graph *graph,
2232 int use_coincidence)
2234 int i;
2236 for (i = 0; i < graph->n_edge; ++i) {
2237 struct isl_sched_edge *edge = &graph->edge[i];
2238 int zero;
2240 zero = force_zero(edge, use_coincidence);
2241 if (!is_proximity(edge) && !zero)
2242 continue;
2243 if (edge->src == edge->dst &&
2244 add_intra_proximity_constraints(graph, edge, 1, zero) < 0)
2245 return -1;
2246 if (edge->src != edge->dst &&
2247 add_inter_proximity_constraints(graph, edge, 1, zero) < 0)
2248 return -1;
2249 if (is_validity(edge) || zero)
2250 continue;
2251 if (edge->src == edge->dst &&
2252 add_intra_proximity_constraints(graph, edge, -1, 0) < 0)
2253 return -1;
2254 if (edge->src != edge->dst &&
2255 add_inter_proximity_constraints(graph, edge, -1, 0) < 0)
2256 return -1;
2259 return 0;
2262 /* Normalize the rows of "indep" such that all rows are lexicographically
2263 * positive and such that each row contains as many final zeros as possible,
2264 * given the choice for the previous rows.
2265 * Do this by performing elementary row operations.
2267 static __isl_give isl_mat *normalize_independent(__isl_take isl_mat *indep)
2269 indep = isl_mat_reverse_gauss(indep);
2270 indep = isl_mat_lexnonneg_rows(indep);
2271 return indep;
2274 /* Extract the linear part of the current schedule for node "node".
2276 static __isl_give isl_mat *extract_linear_schedule(struct isl_sched_node *node)
2278 isl_size n_row = isl_mat_rows(node->sched);
2280 if (n_row < 0)
2281 return NULL;
2282 return isl_mat_sub_alloc(node->sched, 0, n_row,
2283 1 + node->nparam, node->nvar);
2286 /* Compute a basis for the rows in the linear part of the schedule
2287 * and extend this basis to a full basis. The remaining rows
2288 * can then be used to force linear independence from the rows
2289 * in the schedule.
2291 * In particular, given the schedule rows S, we compute
2293 * S = H Q
2294 * S U = H
2296 * with H the Hermite normal form of S. That is, all but the
2297 * first rank columns of H are zero and so each row in S is
2298 * a linear combination of the first rank rows of Q.
2299 * The matrix Q can be used as a variable transformation
2300 * that isolates the directions of S in the first rank rows.
2301 * Transposing S U = H yields
2303 * U^T S^T = H^T
2305 * with all but the first rank rows of H^T zero.
2306 * The last rows of U^T are therefore linear combinations
2307 * of schedule coefficients that are all zero on schedule
2308 * coefficients that are linearly dependent on the rows of S.
2309 * At least one of these combinations is non-zero on
2310 * linearly independent schedule coefficients.
2311 * The rows are normalized to involve as few of the last
2312 * coefficients as possible and to have a positive initial value.
2314 static int node_update_vmap(struct isl_sched_node *node)
2316 isl_mat *H, *U, *Q;
2318 H = extract_linear_schedule(node);
2320 H = isl_mat_left_hermite(H, 0, &U, &Q);
2321 isl_mat_free(node->indep);
2322 isl_mat_free(node->vmap);
2323 node->vmap = Q;
2324 node->indep = isl_mat_transpose(U);
2325 node->rank = isl_mat_initial_non_zero_cols(H);
2326 node->indep = isl_mat_drop_rows(node->indep, 0, node->rank);
2327 node->indep = normalize_independent(node->indep);
2328 isl_mat_free(H);
2330 if (!node->indep || !node->vmap || node->rank < 0)
2331 return -1;
2332 return 0;
2335 /* Is "edge" marked as a validity or a conditional validity edge?
2337 static int is_any_validity(struct isl_sched_edge *edge)
2339 return is_validity(edge) || is_conditional_validity(edge);
2342 /* How many times should we count the constraints in "edge"?
2344 * We count as follows
2345 * validity -> 1 (>= 0)
2346 * validity+proximity -> 2 (>= 0 and upper bound)
2347 * proximity -> 2 (lower and upper bound)
2348 * local(+any) -> 2 (>= 0 and <= 0)
2350 * If an edge is only marked conditional_validity then it counts
2351 * as zero since it is only checked afterwards.
2353 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2354 * Otherwise, we ignore them.
2356 static int edge_multiplicity(struct isl_sched_edge *edge, int use_coincidence)
2358 if (is_proximity(edge) || force_zero(edge, use_coincidence))
2359 return 2;
2360 if (is_validity(edge))
2361 return 1;
2362 return 0;
2365 /* How many times should the constraints in "edge" be counted
2366 * as a parametric intra-node constraint?
2368 * Only proximity edges that are not forced zero need
2369 * coefficient constraints that include coefficients for parameters.
2370 * If the edge is also a validity edge, then only
2371 * an upper bound is introduced. Otherwise, both lower and upper bounds
2372 * are introduced.
2374 static int parametric_intra_edge_multiplicity(struct isl_sched_edge *edge,
2375 int use_coincidence)
2377 if (edge->src != edge->dst)
2378 return 0;
2379 if (!is_proximity(edge))
2380 return 0;
2381 if (force_zero(edge, use_coincidence))
2382 return 0;
2383 if (is_validity(edge))
2384 return 1;
2385 else
2386 return 2;
2389 /* Add "f" times the number of equality and inequality constraints of "bset"
2390 * to "n_eq" and "n_ineq" and free "bset".
2392 static isl_stat update_count(__isl_take isl_basic_set *bset,
2393 int f, int *n_eq, int *n_ineq)
2395 if (!bset)
2396 return isl_stat_error;
2398 *n_eq += isl_basic_set_n_equality(bset);
2399 *n_ineq += isl_basic_set_n_inequality(bset);
2400 isl_basic_set_free(bset);
2402 return isl_stat_ok;
2405 /* Count the number of equality and inequality constraints
2406 * that will be added for the given map.
2408 * The edges that require parameter coefficients are counted separately.
2410 * "use_coincidence" is set if we should take into account coincidence edges.
2412 static isl_stat count_map_constraints(struct isl_sched_graph *graph,
2413 struct isl_sched_edge *edge, __isl_take isl_map *map,
2414 int *n_eq, int *n_ineq, int use_coincidence)
2416 isl_map *copy;
2417 isl_basic_set *coef;
2418 int f = edge_multiplicity(edge, use_coincidence);
2419 int fp = parametric_intra_edge_multiplicity(edge, use_coincidence);
2421 if (f == 0) {
2422 isl_map_free(map);
2423 return isl_stat_ok;
2426 if (edge->src != edge->dst) {
2427 coef = inter_coefficients(graph, edge, map);
2428 return update_count(coef, f, n_eq, n_ineq);
2431 if (fp > 0) {
2432 copy = isl_map_copy(map);
2433 coef = intra_coefficients(graph, edge->src, copy, 1);
2434 if (update_count(coef, fp, n_eq, n_ineq) < 0)
2435 goto error;
2438 if (f > fp) {
2439 copy = isl_map_copy(map);
2440 coef = intra_coefficients(graph, edge->src, copy, 0);
2441 if (update_count(coef, f - fp, n_eq, n_ineq) < 0)
2442 goto error;
2445 isl_map_free(map);
2446 return isl_stat_ok;
2447 error:
2448 isl_map_free(map);
2449 return isl_stat_error;
2452 /* Count the number of equality and inequality constraints
2453 * that will be added to the main lp problem.
2454 * We count as follows
2455 * validity -> 1 (>= 0)
2456 * validity+proximity -> 2 (>= 0 and upper bound)
2457 * proximity -> 2 (lower and upper bound)
2458 * local(+any) -> 2 (>= 0 and <= 0)
2460 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2461 * Otherwise, we ignore them.
2463 static int count_constraints(struct isl_sched_graph *graph,
2464 int *n_eq, int *n_ineq, int use_coincidence)
2466 int i;
2468 *n_eq = *n_ineq = 0;
2469 for (i = 0; i < graph->n_edge; ++i) {
2470 struct isl_sched_edge *edge = &graph->edge[i];
2471 isl_map *map = isl_map_copy(edge->map);
2473 if (count_map_constraints(graph, edge, map, n_eq, n_ineq,
2474 use_coincidence) < 0)
2475 return -1;
2478 return 0;
2481 /* Count the number of constraints that will be added by
2482 * add_bound_constant_constraints to bound the values of the constant terms
2483 * and increment *n_eq and *n_ineq accordingly.
2485 * In practice, add_bound_constant_constraints only adds inequalities.
2487 static isl_stat count_bound_constant_constraints(isl_ctx *ctx,
2488 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2490 if (isl_options_get_schedule_max_constant_term(ctx) == -1)
2491 return isl_stat_ok;
2493 *n_ineq += graph->n;
2495 return isl_stat_ok;
2498 /* Add constraints to bound the values of the constant terms in the schedule,
2499 * if requested by the user.
2501 * The maximal value of the constant terms is defined by the option
2502 * "schedule_max_constant_term".
2504 static isl_stat add_bound_constant_constraints(isl_ctx *ctx,
2505 struct isl_sched_graph *graph)
2507 int i, k;
2508 int max;
2509 isl_size total;
2511 max = isl_options_get_schedule_max_constant_term(ctx);
2512 if (max == -1)
2513 return isl_stat_ok;
2515 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2516 if (total < 0)
2517 return isl_stat_error;
2519 for (i = 0; i < graph->n; ++i) {
2520 struct isl_sched_node *node = &graph->node[i];
2521 int pos;
2523 k = isl_basic_set_alloc_inequality(graph->lp);
2524 if (k < 0)
2525 return isl_stat_error;
2526 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2527 pos = node_cst_coef_offset(node);
2528 isl_int_set_si(graph->lp->ineq[k][1 + pos], -1);
2529 isl_int_set_si(graph->lp->ineq[k][0], max);
2532 return isl_stat_ok;
2535 /* Count the number of constraints that will be added by
2536 * add_bound_coefficient_constraints and increment *n_eq and *n_ineq
2537 * accordingly.
2539 * In practice, add_bound_coefficient_constraints only adds inequalities.
2541 static int count_bound_coefficient_constraints(isl_ctx *ctx,
2542 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2544 int i;
2546 if (isl_options_get_schedule_max_coefficient(ctx) == -1 &&
2547 !isl_options_get_schedule_treat_coalescing(ctx))
2548 return 0;
2550 for (i = 0; i < graph->n; ++i)
2551 *n_ineq += graph->node[i].nparam + 2 * graph->node[i].nvar;
2553 return 0;
2556 /* Add constraints to graph->lp that bound the values of
2557 * the parameter schedule coefficients of "node" to "max" and
2558 * the variable schedule coefficients to the corresponding entry
2559 * in node->max.
2560 * In either case, a negative value means that no bound needs to be imposed.
2562 * For parameter coefficients, this amounts to adding a constraint
2564 * c_n <= max
2566 * i.e.,
2568 * -c_n + max >= 0
2570 * The variables coefficients are, however, not represented directly.
2571 * Instead, the variable coefficients c_x are written as differences
2572 * c_x = c_x^+ - c_x^-.
2573 * That is,
2575 * -max_i <= c_x_i <= max_i
2577 * is encoded as
2579 * -max_i <= c_x_i^+ - c_x_i^- <= max_i
2581 * or
2583 * -(c_x_i^+ - c_x_i^-) + max_i >= 0
2584 * c_x_i^+ - c_x_i^- + max_i >= 0
2586 static isl_stat node_add_coefficient_constraints(isl_ctx *ctx,
2587 struct isl_sched_graph *graph, struct isl_sched_node *node, int max)
2589 int i, j, k;
2590 isl_size total;
2591 isl_vec *ineq;
2593 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2594 if (total < 0)
2595 return isl_stat_error;
2597 for (j = 0; j < node->nparam; ++j) {
2598 int dim;
2600 if (max < 0)
2601 continue;
2603 k = isl_basic_set_alloc_inequality(graph->lp);
2604 if (k < 0)
2605 return isl_stat_error;
2606 dim = 1 + node_par_coef_offset(node) + j;
2607 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2608 isl_int_set_si(graph->lp->ineq[k][dim], -1);
2609 isl_int_set_si(graph->lp->ineq[k][0], max);
2612 ineq = isl_vec_alloc(ctx, 1 + total);
2613 ineq = isl_vec_clr(ineq);
2614 if (!ineq)
2615 return isl_stat_error;
2616 for (i = 0; i < node->nvar; ++i) {
2617 int pos = 1 + node_var_coef_pos(node, i);
2619 if (isl_int_is_neg(node->max->el[i]))
2620 continue;
2622 isl_int_set_si(ineq->el[pos], 1);
2623 isl_int_set_si(ineq->el[pos + 1], -1);
2624 isl_int_set(ineq->el[0], node->max->el[i]);
2626 k = isl_basic_set_alloc_inequality(graph->lp);
2627 if (k < 0)
2628 goto error;
2629 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2631 isl_seq_neg(ineq->el + pos, ineq->el + pos, 2);
2632 k = isl_basic_set_alloc_inequality(graph->lp);
2633 if (k < 0)
2634 goto error;
2635 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2637 isl_seq_clr(ineq->el + pos, 2);
2639 isl_vec_free(ineq);
2641 return isl_stat_ok;
2642 error:
2643 isl_vec_free(ineq);
2644 return isl_stat_error;
2647 /* Add constraints that bound the values of the variable and parameter
2648 * coefficients of the schedule.
2650 * The maximal value of the coefficients is defined by the option
2651 * 'schedule_max_coefficient' and the entries in node->max.
2652 * These latter entries are only set if either the schedule_max_coefficient
2653 * option or the schedule_treat_coalescing option is set.
2655 static isl_stat add_bound_coefficient_constraints(isl_ctx *ctx,
2656 struct isl_sched_graph *graph)
2658 int i;
2659 int max;
2661 max = isl_options_get_schedule_max_coefficient(ctx);
2663 if (max == -1 && !isl_options_get_schedule_treat_coalescing(ctx))
2664 return isl_stat_ok;
2666 for (i = 0; i < graph->n; ++i) {
2667 struct isl_sched_node *node = &graph->node[i];
2669 if (node_add_coefficient_constraints(ctx, graph, node, max) < 0)
2670 return isl_stat_error;
2673 return isl_stat_ok;
2676 /* Add a constraint to graph->lp that equates the value at position
2677 * "sum_pos" to the sum of the "n" values starting at "first".
2679 static isl_stat add_sum_constraint(struct isl_sched_graph *graph,
2680 int sum_pos, int first, int n)
2682 int i, k;
2683 isl_size total;
2685 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2686 if (total < 0)
2687 return isl_stat_error;
2689 k = isl_basic_set_alloc_equality(graph->lp);
2690 if (k < 0)
2691 return isl_stat_error;
2692 isl_seq_clr(graph->lp->eq[k], 1 + total);
2693 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2694 for (i = 0; i < n; ++i)
2695 isl_int_set_si(graph->lp->eq[k][1 + first + i], 1);
2697 return isl_stat_ok;
2700 /* Add a constraint to graph->lp that equates the value at position
2701 * "sum_pos" to the sum of the parameter coefficients of all nodes.
2703 static isl_stat add_param_sum_constraint(struct isl_sched_graph *graph,
2704 int sum_pos)
2706 int i, j, k;
2707 isl_size total;
2709 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2710 if (total < 0)
2711 return isl_stat_error;
2713 k = isl_basic_set_alloc_equality(graph->lp);
2714 if (k < 0)
2715 return isl_stat_error;
2716 isl_seq_clr(graph->lp->eq[k], 1 + total);
2717 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2718 for (i = 0; i < graph->n; ++i) {
2719 int pos = 1 + node_par_coef_offset(&graph->node[i]);
2721 for (j = 0; j < graph->node[i].nparam; ++j)
2722 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2725 return isl_stat_ok;
2728 /* Add a constraint to graph->lp that equates the value at position
2729 * "sum_pos" to the sum of the variable coefficients of all nodes.
2731 static isl_stat add_var_sum_constraint(struct isl_sched_graph *graph,
2732 int sum_pos)
2734 int i, j, k;
2735 isl_size total;
2737 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2738 if (total < 0)
2739 return isl_stat_error;
2741 k = isl_basic_set_alloc_equality(graph->lp);
2742 if (k < 0)
2743 return isl_stat_error;
2744 isl_seq_clr(graph->lp->eq[k], 1 + total);
2745 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2746 for (i = 0; i < graph->n; ++i) {
2747 struct isl_sched_node *node = &graph->node[i];
2748 int pos = 1 + node_var_coef_offset(node);
2750 for (j = 0; j < 2 * node->nvar; ++j)
2751 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2754 return isl_stat_ok;
2757 /* Construct an ILP problem for finding schedule coefficients
2758 * that result in non-negative, but small dependence distances
2759 * over all dependences.
2760 * In particular, the dependence distances over proximity edges
2761 * are bounded by m_0 + m_n n and we compute schedule coefficients
2762 * with small values (preferably zero) of m_n and m_0.
2764 * All variables of the ILP are non-negative. The actual coefficients
2765 * may be negative, so each coefficient is represented as the difference
2766 * of two non-negative variables. The negative part always appears
2767 * immediately before the positive part.
2768 * Other than that, the variables have the following order
2770 * - sum of positive and negative parts of m_n coefficients
2771 * - m_0
2772 * - sum of all c_n coefficients
2773 * (unconstrained when computing non-parametric schedules)
2774 * - sum of positive and negative parts of all c_x coefficients
2775 * - positive and negative parts of m_n coefficients
2776 * - for each node
2777 * - positive and negative parts of c_i_x, in opposite order
2778 * - c_i_n (if parametric)
2779 * - c_i_0
2781 * The constraints are those from the edges plus two or three equalities
2782 * to express the sums.
2784 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2785 * Otherwise, we ignore them.
2787 static isl_stat setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
2788 int use_coincidence)
2790 int i;
2791 isl_size nparam;
2792 unsigned total;
2793 isl_space *space;
2794 int parametric;
2795 int param_pos;
2796 int n_eq, n_ineq;
2798 parametric = ctx->opt->schedule_parametric;
2799 nparam = isl_space_dim(graph->node[0].space, isl_dim_param);
2800 if (nparam < 0)
2801 return isl_stat_error;
2802 param_pos = 4;
2803 total = param_pos + 2 * nparam;
2804 for (i = 0; i < graph->n; ++i) {
2805 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2806 if (node_update_vmap(node) < 0)
2807 return isl_stat_error;
2808 node->start = total;
2809 total += 1 + node->nparam + 2 * node->nvar;
2812 if (count_constraints(graph, &n_eq, &n_ineq, use_coincidence) < 0)
2813 return isl_stat_error;
2814 if (count_bound_constant_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2815 return isl_stat_error;
2816 if (count_bound_coefficient_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2817 return isl_stat_error;
2819 space = isl_space_set_alloc(ctx, 0, total);
2820 isl_basic_set_free(graph->lp);
2821 n_eq += 2 + parametric;
2823 graph->lp = isl_basic_set_alloc_space(space, 0, n_eq, n_ineq);
2825 if (add_sum_constraint(graph, 0, param_pos, 2 * nparam) < 0)
2826 return isl_stat_error;
2827 if (parametric && add_param_sum_constraint(graph, 2) < 0)
2828 return isl_stat_error;
2829 if (add_var_sum_constraint(graph, 3) < 0)
2830 return isl_stat_error;
2831 if (add_bound_constant_constraints(ctx, graph) < 0)
2832 return isl_stat_error;
2833 if (add_bound_coefficient_constraints(ctx, graph) < 0)
2834 return isl_stat_error;
2835 if (add_all_validity_constraints(graph, use_coincidence) < 0)
2836 return isl_stat_error;
2837 if (add_all_proximity_constraints(graph, use_coincidence) < 0)
2838 return isl_stat_error;
2840 return isl_stat_ok;
2843 /* Analyze the conflicting constraint found by
2844 * isl_tab_basic_set_non_trivial_lexmin. If it corresponds to the validity
2845 * constraint of one of the edges between distinct nodes, living, moreover
2846 * in distinct SCCs, then record the source and sink SCC as this may
2847 * be a good place to cut between SCCs.
2849 static int check_conflict(int con, void *user)
2851 int i;
2852 struct isl_sched_graph *graph = user;
2854 if (graph->src_scc >= 0)
2855 return 0;
2857 con -= graph->lp->n_eq;
2859 if (con >= graph->lp->n_ineq)
2860 return 0;
2862 for (i = 0; i < graph->n_edge; ++i) {
2863 if (!is_validity(&graph->edge[i]))
2864 continue;
2865 if (graph->edge[i].src == graph->edge[i].dst)
2866 continue;
2867 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
2868 continue;
2869 if (graph->edge[i].start > con)
2870 continue;
2871 if (graph->edge[i].end <= con)
2872 continue;
2873 graph->src_scc = graph->edge[i].src->scc;
2874 graph->dst_scc = graph->edge[i].dst->scc;
2877 return 0;
2880 /* Check whether the next schedule row of the given node needs to be
2881 * non-trivial. Lower-dimensional domains may have some trivial rows,
2882 * but as soon as the number of remaining required non-trivial rows
2883 * is as large as the number or remaining rows to be computed,
2884 * all remaining rows need to be non-trivial.
2886 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
2888 return node->nvar - node->rank >= graph->maxvar - graph->n_row;
2891 /* Construct a non-triviality region with triviality directions
2892 * corresponding to the rows of "indep".
2893 * The rows of "indep" are expressed in terms of the schedule coefficients c_i,
2894 * while the triviality directions are expressed in terms of
2895 * pairs of non-negative variables c^+_i - c^-_i, with c^-_i appearing
2896 * before c^+_i. Furthermore,
2897 * the pairs of non-negative variables representing the coefficients
2898 * are stored in the opposite order.
2900 static __isl_give isl_mat *construct_trivial(__isl_keep isl_mat *indep)
2902 isl_ctx *ctx;
2903 isl_mat *mat;
2904 int i, j;
2905 isl_size n, n_var;
2907 n = isl_mat_rows(indep);
2908 n_var = isl_mat_cols(indep);
2909 if (n < 0 || n_var < 0)
2910 return NULL;
2912 ctx = isl_mat_get_ctx(indep);
2913 mat = isl_mat_alloc(ctx, n, 2 * n_var);
2914 if (!mat)
2915 return NULL;
2916 for (i = 0; i < n; ++i) {
2917 for (j = 0; j < n_var; ++j) {
2918 int nj = n_var - 1 - j;
2919 isl_int_neg(mat->row[i][2 * nj], indep->row[i][j]);
2920 isl_int_set(mat->row[i][2 * nj + 1], indep->row[i][j]);
2924 return mat;
2927 /* Solve the ILP problem constructed in setup_lp.
2928 * For each node such that all the remaining rows of its schedule
2929 * need to be non-trivial, we construct a non-triviality region.
2930 * This region imposes that the next row is independent of previous rows.
2931 * In particular, the non-triviality region enforces that at least
2932 * one of the linear combinations in the rows of node->indep is non-zero.
2934 static __isl_give isl_vec *solve_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
2936 int i;
2937 isl_vec *sol;
2938 isl_basic_set *lp;
2940 for (i = 0; i < graph->n; ++i) {
2941 struct isl_sched_node *node = &graph->node[i];
2942 isl_mat *trivial;
2944 graph->region[i].pos = node_var_coef_offset(node);
2945 if (needs_row(graph, node))
2946 trivial = construct_trivial(node->indep);
2947 else
2948 trivial = isl_mat_zero(ctx, 0, 0);
2949 graph->region[i].trivial = trivial;
2951 lp = isl_basic_set_copy(graph->lp);
2952 sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
2953 graph->region, &check_conflict, graph);
2954 for (i = 0; i < graph->n; ++i)
2955 isl_mat_free(graph->region[i].trivial);
2956 return sol;
2959 /* Extract the coefficients for the variables of "node" from "sol".
2961 * Each schedule coefficient c_i_x is represented as the difference
2962 * between two non-negative variables c_i_x^+ - c_i_x^-.
2963 * The c_i_x^- appear before their c_i_x^+ counterpart.
2964 * Furthermore, the order of these pairs is the opposite of that
2965 * of the corresponding coefficients.
2967 * Return c_i_x = c_i_x^+ - c_i_x^-
2969 static __isl_give isl_vec *extract_var_coef(struct isl_sched_node *node,
2970 __isl_keep isl_vec *sol)
2972 int i;
2973 int pos;
2974 isl_vec *csol;
2976 if (!sol)
2977 return NULL;
2978 csol = isl_vec_alloc(isl_vec_get_ctx(sol), node->nvar);
2979 if (!csol)
2980 return NULL;
2982 pos = 1 + node_var_coef_offset(node);
2983 for (i = 0; i < node->nvar; ++i)
2984 isl_int_sub(csol->el[node->nvar - 1 - i],
2985 sol->el[pos + 2 * i + 1], sol->el[pos + 2 * i]);
2987 return csol;
2990 /* Update the schedules of all nodes based on the given solution
2991 * of the LP problem.
2992 * The new row is added to the current band.
2993 * All possibly negative coefficients are encoded as a difference
2994 * of two non-negative variables, so we need to perform the subtraction
2995 * here.
2997 * If coincident is set, then the caller guarantees that the new
2998 * row satisfies the coincidence constraints.
3000 static int update_schedule(struct isl_sched_graph *graph,
3001 __isl_take isl_vec *sol, int coincident)
3003 int i, j;
3004 isl_vec *csol = NULL;
3006 if (!sol)
3007 goto error;
3008 if (sol->size == 0)
3009 isl_die(sol->ctx, isl_error_internal,
3010 "no solution found", goto error);
3011 if (graph->n_total_row >= graph->max_row)
3012 isl_die(sol->ctx, isl_error_internal,
3013 "too many schedule rows", goto error);
3015 for (i = 0; i < graph->n; ++i) {
3016 struct isl_sched_node *node = &graph->node[i];
3017 int pos;
3018 isl_size row = isl_mat_rows(node->sched);
3020 isl_vec_free(csol);
3021 csol = extract_var_coef(node, sol);
3022 if (row < 0 || !csol)
3023 goto error;
3025 isl_map_free(node->sched_map);
3026 node->sched_map = NULL;
3027 node->sched = isl_mat_add_rows(node->sched, 1);
3028 if (!node->sched)
3029 goto error;
3030 pos = node_cst_coef_offset(node);
3031 node->sched = isl_mat_set_element(node->sched,
3032 row, 0, sol->el[1 + pos]);
3033 pos = node_par_coef_offset(node);
3034 for (j = 0; j < node->nparam; ++j)
3035 node->sched = isl_mat_set_element(node->sched,
3036 row, 1 + j, sol->el[1 + pos + j]);
3037 for (j = 0; j < node->nvar; ++j)
3038 node->sched = isl_mat_set_element(node->sched,
3039 row, 1 + node->nparam + j, csol->el[j]);
3040 node->coincident[graph->n_total_row] = coincident;
3042 isl_vec_free(sol);
3043 isl_vec_free(csol);
3045 graph->n_row++;
3046 graph->n_total_row++;
3048 return 0;
3049 error:
3050 isl_vec_free(sol);
3051 isl_vec_free(csol);
3052 return -1;
3055 /* Convert row "row" of node->sched into an isl_aff living in "ls"
3056 * and return this isl_aff.
3058 static __isl_give isl_aff *extract_schedule_row(__isl_take isl_local_space *ls,
3059 struct isl_sched_node *node, int row)
3061 int j;
3062 isl_int v;
3063 isl_aff *aff;
3065 isl_int_init(v);
3067 aff = isl_aff_zero_on_domain(ls);
3068 if (isl_mat_get_element(node->sched, row, 0, &v) < 0)
3069 goto error;
3070 aff = isl_aff_set_constant(aff, v);
3071 for (j = 0; j < node->nparam; ++j) {
3072 if (isl_mat_get_element(node->sched, row, 1 + j, &v) < 0)
3073 goto error;
3074 aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
3076 for (j = 0; j < node->nvar; ++j) {
3077 if (isl_mat_get_element(node->sched, row,
3078 1 + node->nparam + j, &v) < 0)
3079 goto error;
3080 aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
3083 isl_int_clear(v);
3085 return aff;
3086 error:
3087 isl_int_clear(v);
3088 isl_aff_free(aff);
3089 return NULL;
3092 /* Convert the "n" rows starting at "first" of node->sched into a multi_aff
3093 * and return this multi_aff.
3095 * The result is defined over the uncompressed node domain.
3097 static __isl_give isl_multi_aff *node_extract_partial_schedule_multi_aff(
3098 struct isl_sched_node *node, int first, int n)
3100 int i;
3101 isl_space *space;
3102 isl_local_space *ls;
3103 isl_aff *aff;
3104 isl_multi_aff *ma;
3105 isl_size nrow;
3107 if (!node)
3108 return NULL;
3109 nrow = isl_mat_rows(node->sched);
3110 if (nrow < 0)
3111 return NULL;
3112 if (node->compressed)
3113 space = isl_multi_aff_get_domain_space(node->decompress);
3114 else
3115 space = isl_space_copy(node->space);
3116 ls = isl_local_space_from_space(isl_space_copy(space));
3117 space = isl_space_from_domain(space);
3118 space = isl_space_add_dims(space, isl_dim_out, n);
3119 ma = isl_multi_aff_zero(space);
3121 for (i = first; i < first + n; ++i) {
3122 aff = extract_schedule_row(isl_local_space_copy(ls), node, i);
3123 ma = isl_multi_aff_set_aff(ma, i - first, aff);
3126 isl_local_space_free(ls);
3128 if (node->compressed)
3129 ma = isl_multi_aff_pullback_multi_aff(ma,
3130 isl_multi_aff_copy(node->compress));
3132 return ma;
3135 /* Convert node->sched into a multi_aff and return this multi_aff.
3137 * The result is defined over the uncompressed node domain.
3139 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
3140 struct isl_sched_node *node)
3142 isl_size nrow;
3144 nrow = isl_mat_rows(node->sched);
3145 if (nrow < 0)
3146 return NULL;
3147 return node_extract_partial_schedule_multi_aff(node, 0, nrow);
3150 /* Convert node->sched into a map and return this map.
3152 * The result is cached in node->sched_map, which needs to be released
3153 * whenever node->sched is updated.
3154 * It is defined over the uncompressed node domain.
3156 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
3158 if (!node->sched_map) {
3159 isl_multi_aff *ma;
3161 ma = node_extract_schedule_multi_aff(node);
3162 node->sched_map = isl_map_from_multi_aff(ma);
3165 return isl_map_copy(node->sched_map);
3168 /* Construct a map that can be used to update a dependence relation
3169 * based on the current schedule.
3170 * That is, construct a map expressing that source and sink
3171 * are executed within the same iteration of the current schedule.
3172 * This map can then be intersected with the dependence relation.
3173 * This is not the most efficient way, but this shouldn't be a critical
3174 * operation.
3176 static __isl_give isl_map *specializer(struct isl_sched_node *src,
3177 struct isl_sched_node *dst)
3179 isl_map *src_sched, *dst_sched;
3181 src_sched = node_extract_schedule(src);
3182 dst_sched = node_extract_schedule(dst);
3183 return isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
3186 /* Intersect the domains of the nested relations in domain and range
3187 * of "umap" with "map".
3189 static __isl_give isl_union_map *intersect_domains(
3190 __isl_take isl_union_map *umap, __isl_keep isl_map *map)
3192 isl_union_set *uset;
3194 umap = isl_union_map_zip(umap);
3195 uset = isl_union_set_from_set(isl_map_wrap(isl_map_copy(map)));
3196 umap = isl_union_map_intersect_domain(umap, uset);
3197 umap = isl_union_map_zip(umap);
3198 return umap;
3201 /* Update the dependence relation of the given edge based
3202 * on the current schedule.
3203 * If the dependence is carried completely by the current schedule, then
3204 * it is removed from the edge_tables. It is kept in the list of edges
3205 * as otherwise all edge_tables would have to be recomputed.
3207 * If the edge is of a type that can appear multiple times
3208 * between the same pair of nodes, then it is added to
3209 * the edge table (again). This prevents the situation
3210 * where none of these edges is referenced from the edge table
3211 * because the one that was referenced turned out to be empty and
3212 * was therefore removed from the table.
3214 static isl_stat update_edge(isl_ctx *ctx, struct isl_sched_graph *graph,
3215 struct isl_sched_edge *edge)
3217 int empty;
3218 isl_map *id;
3220 id = specializer(edge->src, edge->dst);
3221 edge->map = isl_map_intersect(edge->map, isl_map_copy(id));
3222 if (!edge->map)
3223 goto error;
3225 if (edge->tagged_condition) {
3226 edge->tagged_condition =
3227 intersect_domains(edge->tagged_condition, id);
3228 if (!edge->tagged_condition)
3229 goto error;
3231 if (edge->tagged_validity) {
3232 edge->tagged_validity =
3233 intersect_domains(edge->tagged_validity, id);
3234 if (!edge->tagged_validity)
3235 goto error;
3238 empty = isl_map_plain_is_empty(edge->map);
3239 if (empty < 0)
3240 goto error;
3241 if (empty) {
3242 graph_remove_edge(graph, edge);
3243 } else if (is_multi_edge_type(edge)) {
3244 if (graph_edge_tables_add(ctx, graph, edge) < 0)
3245 goto error;
3248 isl_map_free(id);
3249 return isl_stat_ok;
3250 error:
3251 isl_map_free(id);
3252 return isl_stat_error;
3255 /* Does the domain of "umap" intersect "uset"?
3257 static int domain_intersects(__isl_keep isl_union_map *umap,
3258 __isl_keep isl_union_set *uset)
3260 int empty;
3262 umap = isl_union_map_copy(umap);
3263 umap = isl_union_map_intersect_domain(umap, isl_union_set_copy(uset));
3264 empty = isl_union_map_is_empty(umap);
3265 isl_union_map_free(umap);
3267 return empty < 0 ? -1 : !empty;
3270 /* Does the range of "umap" intersect "uset"?
3272 static int range_intersects(__isl_keep isl_union_map *umap,
3273 __isl_keep isl_union_set *uset)
3275 int empty;
3277 umap = isl_union_map_copy(umap);
3278 umap = isl_union_map_intersect_range(umap, isl_union_set_copy(uset));
3279 empty = isl_union_map_is_empty(umap);
3280 isl_union_map_free(umap);
3282 return empty < 0 ? -1 : !empty;
3285 /* Are the condition dependences of "edge" local with respect to
3286 * the current schedule?
3288 * That is, are domain and range of the condition dependences mapped
3289 * to the same point?
3291 * In other words, is the condition false?
3293 static int is_condition_false(struct isl_sched_edge *edge)
3295 isl_union_map *umap;
3296 isl_map *map, *sched, *test;
3297 int empty, local;
3299 empty = isl_union_map_is_empty(edge->tagged_condition);
3300 if (empty < 0 || empty)
3301 return empty;
3303 umap = isl_union_map_copy(edge->tagged_condition);
3304 umap = isl_union_map_zip(umap);
3305 umap = isl_union_set_unwrap(isl_union_map_domain(umap));
3306 map = isl_map_from_union_map(umap);
3308 sched = node_extract_schedule(edge->src);
3309 map = isl_map_apply_domain(map, sched);
3310 sched = node_extract_schedule(edge->dst);
3311 map = isl_map_apply_range(map, sched);
3313 test = isl_map_identity(isl_map_get_space(map));
3314 local = isl_map_is_subset(map, test);
3315 isl_map_free(map);
3316 isl_map_free(test);
3318 return local;
3321 /* For each conditional validity constraint that is adjacent
3322 * to a condition with domain in condition_source or range in condition_sink,
3323 * turn it into an unconditional validity constraint.
3325 static int unconditionalize_adjacent_validity(struct isl_sched_graph *graph,
3326 __isl_take isl_union_set *condition_source,
3327 __isl_take isl_union_set *condition_sink)
3329 int i;
3331 condition_source = isl_union_set_coalesce(condition_source);
3332 condition_sink = isl_union_set_coalesce(condition_sink);
3334 for (i = 0; i < graph->n_edge; ++i) {
3335 int adjacent;
3336 isl_union_map *validity;
3338 if (!is_conditional_validity(&graph->edge[i]))
3339 continue;
3340 if (is_validity(&graph->edge[i]))
3341 continue;
3343 validity = graph->edge[i].tagged_validity;
3344 adjacent = domain_intersects(validity, condition_sink);
3345 if (adjacent >= 0 && !adjacent)
3346 adjacent = range_intersects(validity, condition_source);
3347 if (adjacent < 0)
3348 goto error;
3349 if (!adjacent)
3350 continue;
3352 set_validity(&graph->edge[i]);
3355 isl_union_set_free(condition_source);
3356 isl_union_set_free(condition_sink);
3357 return 0;
3358 error:
3359 isl_union_set_free(condition_source);
3360 isl_union_set_free(condition_sink);
3361 return -1;
3364 /* Update the dependence relations of all edges based on the current schedule
3365 * and enforce conditional validity constraints that are adjacent
3366 * to satisfied condition constraints.
3368 * First check if any of the condition constraints are satisfied
3369 * (i.e., not local to the outer schedule) and keep track of
3370 * their domain and range.
3371 * Then update all dependence relations (which removes the non-local
3372 * constraints).
3373 * Finally, if any condition constraints turned out to be satisfied,
3374 * then turn all adjacent conditional validity constraints into
3375 * unconditional validity constraints.
3377 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
3379 int i;
3380 int any = 0;
3381 isl_union_set *source, *sink;
3383 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3384 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3385 for (i = 0; i < graph->n_edge; ++i) {
3386 int local;
3387 isl_union_set *uset;
3388 isl_union_map *umap;
3390 if (!is_condition(&graph->edge[i]))
3391 continue;
3392 if (is_local(&graph->edge[i]))
3393 continue;
3394 local = is_condition_false(&graph->edge[i]);
3395 if (local < 0)
3396 goto error;
3397 if (local)
3398 continue;
3400 any = 1;
3402 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3403 uset = isl_union_map_domain(umap);
3404 source = isl_union_set_union(source, uset);
3406 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3407 uset = isl_union_map_range(umap);
3408 sink = isl_union_set_union(sink, uset);
3411 for (i = 0; i < graph->n_edge; ++i) {
3412 if (update_edge(ctx, graph, &graph->edge[i]) < 0)
3413 goto error;
3416 if (any)
3417 return unconditionalize_adjacent_validity(graph, source, sink);
3419 isl_union_set_free(source);
3420 isl_union_set_free(sink);
3421 return 0;
3422 error:
3423 isl_union_set_free(source);
3424 isl_union_set_free(sink);
3425 return -1;
3428 static void next_band(struct isl_sched_graph *graph)
3430 graph->band_start = graph->n_total_row;
3433 /* Return the union of the universe domains of the nodes in "graph"
3434 * that satisfy "pred".
3436 static __isl_give isl_union_set *isl_sched_graph_domain(isl_ctx *ctx,
3437 struct isl_sched_graph *graph,
3438 int (*pred)(struct isl_sched_node *node, int data), int data)
3440 int i;
3441 isl_set *set;
3442 isl_union_set *dom;
3444 for (i = 0; i < graph->n; ++i)
3445 if (pred(&graph->node[i], data))
3446 break;
3448 if (i >= graph->n)
3449 isl_die(ctx, isl_error_internal,
3450 "empty component", return NULL);
3452 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3453 dom = isl_union_set_from_set(set);
3455 for (i = i + 1; i < graph->n; ++i) {
3456 if (!pred(&graph->node[i], data))
3457 continue;
3458 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3459 dom = isl_union_set_union(dom, isl_union_set_from_set(set));
3462 return dom;
3465 /* Return a list of unions of universe domains, where each element
3466 * in the list corresponds to an SCC (or WCC) indexed by node->scc.
3468 static __isl_give isl_union_set_list *extract_sccs(isl_ctx *ctx,
3469 struct isl_sched_graph *graph)
3471 int i;
3472 isl_union_set_list *filters;
3474 filters = isl_union_set_list_alloc(ctx, graph->scc);
3475 for (i = 0; i < graph->scc; ++i) {
3476 isl_union_set *dom;
3478 dom = isl_sched_graph_domain(ctx, graph, &node_scc_exactly, i);
3479 filters = isl_union_set_list_add(filters, dom);
3482 return filters;
3485 /* Return a list of two unions of universe domains, one for the SCCs up
3486 * to and including graph->src_scc and another for the other SCCs.
3488 static __isl_give isl_union_set_list *extract_split(isl_ctx *ctx,
3489 struct isl_sched_graph *graph)
3491 isl_union_set *dom;
3492 isl_union_set_list *filters;
3494 filters = isl_union_set_list_alloc(ctx, 2);
3495 dom = isl_sched_graph_domain(ctx, graph,
3496 &node_scc_at_most, graph->src_scc);
3497 filters = isl_union_set_list_add(filters, dom);
3498 dom = isl_sched_graph_domain(ctx, graph,
3499 &node_scc_at_least, graph->src_scc + 1);
3500 filters = isl_union_set_list_add(filters, dom);
3502 return filters;
3505 /* Copy nodes that satisfy node_pred from the src dependence graph
3506 * to the dst dependence graph.
3508 static isl_stat copy_nodes(struct isl_sched_graph *dst,
3509 struct isl_sched_graph *src,
3510 int (*node_pred)(struct isl_sched_node *node, int data), int data)
3512 int i;
3514 dst->n = 0;
3515 for (i = 0; i < src->n; ++i) {
3516 int j;
3518 if (!node_pred(&src->node[i], data))
3519 continue;
3521 j = dst->n;
3522 dst->node[j].space = isl_space_copy(src->node[i].space);
3523 dst->node[j].compressed = src->node[i].compressed;
3524 dst->node[j].hull = isl_set_copy(src->node[i].hull);
3525 dst->node[j].compress =
3526 isl_multi_aff_copy(src->node[i].compress);
3527 dst->node[j].decompress =
3528 isl_multi_aff_copy(src->node[i].decompress);
3529 dst->node[j].nvar = src->node[i].nvar;
3530 dst->node[j].nparam = src->node[i].nparam;
3531 dst->node[j].sched = isl_mat_copy(src->node[i].sched);
3532 dst->node[j].sched_map = isl_map_copy(src->node[i].sched_map);
3533 dst->node[j].coincident = src->node[i].coincident;
3534 dst->node[j].sizes = isl_multi_val_copy(src->node[i].sizes);
3535 dst->node[j].bounds = isl_basic_set_copy(src->node[i].bounds);
3536 dst->node[j].max = isl_vec_copy(src->node[i].max);
3537 dst->n++;
3539 if (!dst->node[j].space || !dst->node[j].sched)
3540 return isl_stat_error;
3541 if (dst->node[j].compressed &&
3542 (!dst->node[j].hull || !dst->node[j].compress ||
3543 !dst->node[j].decompress))
3544 return isl_stat_error;
3547 return isl_stat_ok;
3550 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
3551 * to the dst dependence graph.
3552 * If the source or destination node of the edge is not in the destination
3553 * graph, then it must be a backward proximity edge and it should simply
3554 * be ignored.
3556 static isl_stat copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
3557 struct isl_sched_graph *src,
3558 int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
3560 int i;
3562 dst->n_edge = 0;
3563 for (i = 0; i < src->n_edge; ++i) {
3564 struct isl_sched_edge *edge = &src->edge[i];
3565 isl_map *map;
3566 isl_union_map *tagged_condition;
3567 isl_union_map *tagged_validity;
3568 struct isl_sched_node *dst_src, *dst_dst;
3570 if (!edge_pred(edge, data))
3571 continue;
3573 if (isl_map_plain_is_empty(edge->map))
3574 continue;
3576 dst_src = graph_find_node(ctx, dst, edge->src->space);
3577 dst_dst = graph_find_node(ctx, dst, edge->dst->space);
3578 if (!dst_src || !dst_dst)
3579 return isl_stat_error;
3580 if (!is_node(dst, dst_src) || !is_node(dst, dst_dst)) {
3581 if (is_validity(edge) || is_conditional_validity(edge))
3582 isl_die(ctx, isl_error_internal,
3583 "backward (conditional) validity edge",
3584 return isl_stat_error);
3585 continue;
3588 map = isl_map_copy(edge->map);
3589 tagged_condition = isl_union_map_copy(edge->tagged_condition);
3590 tagged_validity = isl_union_map_copy(edge->tagged_validity);
3592 dst->edge[dst->n_edge].src = dst_src;
3593 dst->edge[dst->n_edge].dst = dst_dst;
3594 dst->edge[dst->n_edge].map = map;
3595 dst->edge[dst->n_edge].tagged_condition = tagged_condition;
3596 dst->edge[dst->n_edge].tagged_validity = tagged_validity;
3597 dst->edge[dst->n_edge].types = edge->types;
3598 dst->n_edge++;
3600 if (edge->tagged_condition && !tagged_condition)
3601 return isl_stat_error;
3602 if (edge->tagged_validity && !tagged_validity)
3603 return isl_stat_error;
3605 if (graph_edge_tables_add(ctx, dst,
3606 &dst->edge[dst->n_edge - 1]) < 0)
3607 return isl_stat_error;
3610 return isl_stat_ok;
3613 /* Compute the maximal number of variables over all nodes.
3614 * This is the maximal number of linearly independent schedule
3615 * rows that we need to compute.
3616 * Just in case we end up in a part of the dependence graph
3617 * with only lower-dimensional domains, we make sure we will
3618 * compute the required amount of extra linearly independent rows.
3620 static int compute_maxvar(struct isl_sched_graph *graph)
3622 int i;
3624 graph->maxvar = 0;
3625 for (i = 0; i < graph->n; ++i) {
3626 struct isl_sched_node *node = &graph->node[i];
3627 int nvar;
3629 if (node_update_vmap(node) < 0)
3630 return -1;
3631 nvar = node->nvar + graph->n_row - node->rank;
3632 if (nvar > graph->maxvar)
3633 graph->maxvar = nvar;
3636 return 0;
3639 /* Extract the subgraph of "graph" that consists of the nodes satisfying
3640 * "node_pred" and the edges satisfying "edge_pred" and store
3641 * the result in "sub".
3643 static isl_stat extract_sub_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
3644 int (*node_pred)(struct isl_sched_node *node, int data),
3645 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3646 int data, struct isl_sched_graph *sub)
3648 int i, n = 0, n_edge = 0;
3649 int t;
3651 for (i = 0; i < graph->n; ++i)
3652 if (node_pred(&graph->node[i], data))
3653 ++n;
3654 for (i = 0; i < graph->n_edge; ++i)
3655 if (edge_pred(&graph->edge[i], data))
3656 ++n_edge;
3657 if (graph_alloc(ctx, sub, n, n_edge) < 0)
3658 return isl_stat_error;
3659 sub->root = graph->root;
3660 if (copy_nodes(sub, graph, node_pred, data) < 0)
3661 return isl_stat_error;
3662 if (graph_init_table(ctx, sub) < 0)
3663 return isl_stat_error;
3664 for (t = 0; t <= isl_edge_last; ++t)
3665 sub->max_edge[t] = graph->max_edge[t];
3666 if (graph_init_edge_tables(ctx, sub) < 0)
3667 return isl_stat_error;
3668 if (copy_edges(ctx, sub, graph, edge_pred, data) < 0)
3669 return isl_stat_error;
3670 sub->n_row = graph->n_row;
3671 sub->max_row = graph->max_row;
3672 sub->n_total_row = graph->n_total_row;
3673 sub->band_start = graph->band_start;
3675 return isl_stat_ok;
3678 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
3679 struct isl_sched_graph *graph);
3680 static __isl_give isl_schedule_node *compute_schedule_wcc(
3681 isl_schedule_node *node, struct isl_sched_graph *graph);
3683 /* Compute a schedule for a subgraph of "graph". In particular, for
3684 * the graph composed of nodes that satisfy node_pred and edges that
3685 * that satisfy edge_pred.
3686 * If the subgraph is known to consist of a single component, then wcc should
3687 * be set and then we call compute_schedule_wcc on the constructed subgraph.
3688 * Otherwise, we call compute_schedule, which will check whether the subgraph
3689 * is connected.
3691 * The schedule is inserted at "node" and the updated schedule node
3692 * is returned.
3694 static __isl_give isl_schedule_node *compute_sub_schedule(
3695 __isl_take isl_schedule_node *node, isl_ctx *ctx,
3696 struct isl_sched_graph *graph,
3697 int (*node_pred)(struct isl_sched_node *node, int data),
3698 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3699 int data, int wcc)
3701 struct isl_sched_graph split = { 0 };
3703 if (extract_sub_graph(ctx, graph, node_pred, edge_pred, data,
3704 &split) < 0)
3705 goto error;
3707 if (wcc)
3708 node = compute_schedule_wcc(node, &split);
3709 else
3710 node = compute_schedule(node, &split);
3712 graph_free(ctx, &split);
3713 return node;
3714 error:
3715 graph_free(ctx, &split);
3716 return isl_schedule_node_free(node);
3719 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
3721 return edge->src->scc == scc && edge->dst->scc == scc;
3724 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
3726 return edge->dst->scc <= scc;
3729 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
3731 return edge->src->scc >= scc;
3734 /* Reset the current band by dropping all its schedule rows.
3736 static isl_stat reset_band(struct isl_sched_graph *graph)
3738 int i;
3739 int drop;
3741 drop = graph->n_total_row - graph->band_start;
3742 graph->n_total_row -= drop;
3743 graph->n_row -= drop;
3745 for (i = 0; i < graph->n; ++i) {
3746 struct isl_sched_node *node = &graph->node[i];
3748 isl_map_free(node->sched_map);
3749 node->sched_map = NULL;
3751 node->sched = isl_mat_drop_rows(node->sched,
3752 graph->band_start, drop);
3754 if (!node->sched)
3755 return isl_stat_error;
3758 return isl_stat_ok;
3761 /* Split the current graph into two parts and compute a schedule for each
3762 * part individually. In particular, one part consists of all SCCs up
3763 * to and including graph->src_scc, while the other part contains the other
3764 * SCCs. The split is enforced by a sequence node inserted at position "node"
3765 * in the schedule tree. Return the updated schedule node.
3766 * If either of these two parts consists of a sequence, then it is spliced
3767 * into the sequence containing the two parts.
3769 * The current band is reset. It would be possible to reuse
3770 * the previously computed rows as the first rows in the next
3771 * band, but recomputing them may result in better rows as we are looking
3772 * at a smaller part of the dependence graph.
3774 static __isl_give isl_schedule_node *compute_split_schedule(
3775 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3777 int is_seq;
3778 isl_ctx *ctx;
3779 isl_union_set_list *filters;
3781 if (!node)
3782 return NULL;
3784 if (reset_band(graph) < 0)
3785 return isl_schedule_node_free(node);
3787 next_band(graph);
3789 ctx = isl_schedule_node_get_ctx(node);
3790 filters = extract_split(ctx, graph);
3791 node = isl_schedule_node_insert_sequence(node, filters);
3792 node = isl_schedule_node_child(node, 1);
3793 node = isl_schedule_node_child(node, 0);
3795 node = compute_sub_schedule(node, ctx, graph,
3796 &node_scc_at_least, &edge_src_scc_at_least,
3797 graph->src_scc + 1, 0);
3798 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3799 node = isl_schedule_node_parent(node);
3800 node = isl_schedule_node_parent(node);
3801 if (is_seq)
3802 node = isl_schedule_node_sequence_splice_child(node, 1);
3803 node = isl_schedule_node_child(node, 0);
3804 node = isl_schedule_node_child(node, 0);
3805 node = compute_sub_schedule(node, ctx, graph,
3806 &node_scc_at_most, &edge_dst_scc_at_most,
3807 graph->src_scc, 0);
3808 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3809 node = isl_schedule_node_parent(node);
3810 node = isl_schedule_node_parent(node);
3811 if (is_seq)
3812 node = isl_schedule_node_sequence_splice_child(node, 0);
3814 return node;
3817 /* Insert a band node at position "node" in the schedule tree corresponding
3818 * to the current band in "graph". Mark the band node permutable
3819 * if "permutable" is set.
3820 * The partial schedules and the coincidence property are extracted
3821 * from the graph nodes.
3822 * Return the updated schedule node.
3824 static __isl_give isl_schedule_node *insert_current_band(
3825 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3826 int permutable)
3828 int i;
3829 int start, end, n;
3830 isl_multi_aff *ma;
3831 isl_multi_pw_aff *mpa;
3832 isl_multi_union_pw_aff *mupa;
3834 if (!node)
3835 return NULL;
3837 if (graph->n < 1)
3838 isl_die(isl_schedule_node_get_ctx(node), isl_error_internal,
3839 "graph should have at least one node",
3840 return isl_schedule_node_free(node));
3842 start = graph->band_start;
3843 end = graph->n_total_row;
3844 n = end - start;
3846 ma = node_extract_partial_schedule_multi_aff(&graph->node[0], start, n);
3847 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3848 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3850 for (i = 1; i < graph->n; ++i) {
3851 isl_multi_union_pw_aff *mupa_i;
3853 ma = node_extract_partial_schedule_multi_aff(&graph->node[i],
3854 start, n);
3855 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3856 mupa_i = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3857 mupa = isl_multi_union_pw_aff_union_add(mupa, mupa_i);
3859 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3861 for (i = 0; i < n; ++i)
3862 node = isl_schedule_node_band_member_set_coincident(node, i,
3863 graph->node[0].coincident[start + i]);
3864 node = isl_schedule_node_band_set_permutable(node, permutable);
3866 return node;
3869 /* Update the dependence relations based on the current schedule,
3870 * add the current band to "node" and then continue with the computation
3871 * of the next band.
3872 * Return the updated schedule node.
3874 static __isl_give isl_schedule_node *compute_next_band(
3875 __isl_take isl_schedule_node *node,
3876 struct isl_sched_graph *graph, int permutable)
3878 isl_ctx *ctx;
3880 if (!node)
3881 return NULL;
3883 ctx = isl_schedule_node_get_ctx(node);
3884 if (update_edges(ctx, graph) < 0)
3885 return isl_schedule_node_free(node);
3886 node = insert_current_band(node, graph, permutable);
3887 next_band(graph);
3889 node = isl_schedule_node_child(node, 0);
3890 node = compute_schedule(node, graph);
3891 node = isl_schedule_node_parent(node);
3893 return node;
3896 /* Add the constraints "coef" derived from an edge from "node" to itself
3897 * to graph->lp in order to respect the dependences and to try and carry them.
3898 * "pos" is the sequence number of the edge that needs to be carried.
3899 * "coef" represents general constraints on coefficients (c_0, c_x)
3900 * of valid constraints for (y - x) with x and y instances of the node.
3902 * The constraints added to graph->lp need to enforce
3904 * (c_j_0 + c_j_x y) - (c_j_0 + c_j_x x)
3905 * = c_j_x (y - x) >= e_i
3907 * for each (x,y) in the dependence relation of the edge.
3908 * That is, (-e_i, c_j_x) needs to be plugged in for (c_0, c_x),
3909 * taking into account that each coefficient in c_j_x is represented
3910 * as a pair of non-negative coefficients.
3912 static isl_stat add_intra_constraints(struct isl_sched_graph *graph,
3913 struct isl_sched_node *node, __isl_take isl_basic_set *coef, int pos)
3915 isl_size offset;
3916 isl_ctx *ctx;
3917 isl_dim_map *dim_map;
3919 offset = coef_var_offset(coef);
3920 if (offset < 0)
3921 coef = isl_basic_set_free(coef);
3922 if (!coef)
3923 return isl_stat_error;
3925 ctx = isl_basic_set_get_ctx(coef);
3926 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
3927 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3928 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3930 return isl_stat_ok;
3933 /* Add the constraints "coef" derived from an edge from "src" to "dst"
3934 * to graph->lp in order to respect the dependences and to try and carry them.
3935 * "pos" is the sequence number of the edge that needs to be carried or
3936 * -1 if no attempt should be made to carry the dependences.
3937 * "coef" represents general constraints on coefficients (c_0, c_n, c_x, c_y)
3938 * of valid constraints for (x, y) with x and y instances of "src" and "dst".
3940 * The constraints added to graph->lp need to enforce
3942 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
3944 * for each (x,y) in the dependence relation of the edge or
3946 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= 0
3948 * if pos is -1.
3949 * That is,
3950 * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3951 * or
3952 * (c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3953 * needs to be plugged in for (c_0, c_n, c_x, c_y),
3954 * taking into account that each coefficient in c_j_x and c_k_x is represented
3955 * as a pair of non-negative coefficients.
3957 static isl_stat add_inter_constraints(struct isl_sched_graph *graph,
3958 struct isl_sched_node *src, struct isl_sched_node *dst,
3959 __isl_take isl_basic_set *coef, int pos)
3961 isl_size offset;
3962 isl_ctx *ctx;
3963 isl_dim_map *dim_map;
3965 offset = coef_var_offset(coef);
3966 if (offset < 0)
3967 coef = isl_basic_set_free(coef);
3968 if (!coef)
3969 return isl_stat_error;
3971 ctx = isl_basic_set_get_ctx(coef);
3972 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
3973 if (pos >= 0)
3974 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3975 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3977 return isl_stat_ok;
3980 /* Data structure for keeping track of the data needed
3981 * to exploit non-trivial lineality spaces.
3983 * "any_non_trivial" is true if there are any non-trivial lineality spaces.
3984 * If "any_non_trivial" is not true, then "equivalent" and "mask" may be NULL.
3985 * "equivalent" connects instances to other instances on the same line(s).
3986 * "mask" contains the domain spaces of "equivalent".
3987 * Any instance set not in "mask" does not have a non-trivial lineality space.
3989 struct isl_exploit_lineality_data {
3990 isl_bool any_non_trivial;
3991 isl_union_map *equivalent;
3992 isl_union_set *mask;
3995 /* Data structure collecting information used during the construction
3996 * of an LP for carrying dependences.
3998 * "intra" is a sequence of coefficient constraints for intra-node edges.
3999 * "inter" is a sequence of coefficient constraints for inter-node edges.
4000 * "lineality" contains data used to exploit non-trivial lineality spaces.
4002 struct isl_carry {
4003 isl_basic_set_list *intra;
4004 isl_basic_set_list *inter;
4005 struct isl_exploit_lineality_data lineality;
4008 /* Free all the data stored in "carry".
4010 static void isl_carry_clear(struct isl_carry *carry)
4012 isl_basic_set_list_free(carry->intra);
4013 isl_basic_set_list_free(carry->inter);
4014 isl_union_map_free(carry->lineality.equivalent);
4015 isl_union_set_free(carry->lineality.mask);
4018 /* Return a pointer to the node in "graph" that lives in "space".
4019 * If the requested node has been compressed, then "space"
4020 * corresponds to the compressed space.
4021 * The graph is assumed to have such a node.
4022 * Return NULL in case of error.
4024 * First try and see if "space" is the space of an uncompressed node.
4025 * If so, return that node.
4026 * Otherwise, "space" was constructed by construct_compressed_id and
4027 * contains a user pointer pointing to the node in the tuple id.
4028 * However, this node belongs to the original dependence graph.
4029 * If "graph" is a subgraph of this original dependence graph,
4030 * then the node with the same space still needs to be looked up
4031 * in the current graph.
4033 static struct isl_sched_node *graph_find_compressed_node(isl_ctx *ctx,
4034 struct isl_sched_graph *graph, __isl_keep isl_space *space)
4036 isl_id *id;
4037 struct isl_sched_node *node;
4039 if (!space)
4040 return NULL;
4042 node = graph_find_node(ctx, graph, space);
4043 if (!node)
4044 return NULL;
4045 if (is_node(graph, node))
4046 return node;
4048 id = isl_space_get_tuple_id(space, isl_dim_set);
4049 node = isl_id_get_user(id);
4050 isl_id_free(id);
4052 if (!node)
4053 return NULL;
4055 if (!is_node(graph->root, node))
4056 isl_die(ctx, isl_error_internal,
4057 "space points to invalid node", return NULL);
4058 if (graph != graph->root)
4059 node = graph_find_node(ctx, graph, node->space);
4060 if (!is_node(graph, node))
4061 isl_die(ctx, isl_error_internal,
4062 "unable to find node", return NULL);
4064 return node;
4067 /* Internal data structure for add_all_constraints.
4069 * "graph" is the schedule constraint graph for which an LP problem
4070 * is being constructed.
4071 * "carry_inter" indicates whether inter-node edges should be carried.
4072 * "pos" is the position of the next edge that needs to be carried.
4074 struct isl_add_all_constraints_data {
4075 isl_ctx *ctx;
4076 struct isl_sched_graph *graph;
4077 int carry_inter;
4078 int pos;
4081 /* Add the constraints "coef" derived from an edge from a node to itself
4082 * to data->graph->lp in order to respect the dependences and
4083 * to try and carry them.
4085 * The space of "coef" is of the form
4087 * coefficients[[c_cst] -> S[c_x]]
4089 * with S[c_x] the (compressed) space of the node.
4090 * Extract the node from the space and call add_intra_constraints.
4092 static isl_stat lp_add_intra(__isl_take isl_basic_set *coef, void *user)
4094 struct isl_add_all_constraints_data *data = user;
4095 isl_space *space;
4096 struct isl_sched_node *node;
4098 space = isl_basic_set_get_space(coef);
4099 space = isl_space_range(isl_space_unwrap(space));
4100 node = graph_find_compressed_node(data->ctx, data->graph, space);
4101 isl_space_free(space);
4102 return add_intra_constraints(data->graph, node, coef, data->pos++);
4105 /* Add the constraints "coef" derived from an edge from a node j
4106 * to a node k to data->graph->lp in order to respect the dependences and
4107 * to try and carry them (provided data->carry_inter is set).
4109 * The space of "coef" is of the form
4111 * coefficients[[c_cst, c_n] -> [S_j[c_x] -> S_k[c_y]]]
4113 * with S_j[c_x] and S_k[c_y] the (compressed) spaces of the nodes.
4114 * Extract the nodes from the space and call add_inter_constraints.
4116 static isl_stat lp_add_inter(__isl_take isl_basic_set *coef, void *user)
4118 struct isl_add_all_constraints_data *data = user;
4119 isl_space *space, *dom;
4120 struct isl_sched_node *src, *dst;
4121 int pos;
4123 space = isl_basic_set_get_space(coef);
4124 space = isl_space_unwrap(isl_space_range(isl_space_unwrap(space)));
4125 dom = isl_space_domain(isl_space_copy(space));
4126 src = graph_find_compressed_node(data->ctx, data->graph, dom);
4127 isl_space_free(dom);
4128 space = isl_space_range(space);
4129 dst = graph_find_compressed_node(data->ctx, data->graph, space);
4130 isl_space_free(space);
4132 pos = data->carry_inter ? data->pos++ : -1;
4133 return add_inter_constraints(data->graph, src, dst, coef, pos);
4136 /* Add constraints to graph->lp that force all (conditional) validity
4137 * dependences to be respected and attempt to carry them.
4138 * "intra" is the sequence of coefficient constraints for intra-node edges.
4139 * "inter" is the sequence of coefficient constraints for inter-node edges.
4140 * "carry_inter" indicates whether inter-node edges should be carried or
4141 * only respected.
4143 static isl_stat add_all_constraints(isl_ctx *ctx, struct isl_sched_graph *graph,
4144 __isl_keep isl_basic_set_list *intra,
4145 __isl_keep isl_basic_set_list *inter, int carry_inter)
4147 struct isl_add_all_constraints_data data = { ctx, graph, carry_inter };
4149 data.pos = 0;
4150 if (isl_basic_set_list_foreach(intra, &lp_add_intra, &data) < 0)
4151 return isl_stat_error;
4152 if (isl_basic_set_list_foreach(inter, &lp_add_inter, &data) < 0)
4153 return isl_stat_error;
4154 return isl_stat_ok;
4157 /* Internal data structure for count_all_constraints
4158 * for keeping track of the number of equality and inequality constraints.
4160 struct isl_sched_count {
4161 int n_eq;
4162 int n_ineq;
4165 /* Add the number of equality and inequality constraints of "bset"
4166 * to data->n_eq and data->n_ineq.
4168 static isl_stat bset_update_count(__isl_take isl_basic_set *bset, void *user)
4170 struct isl_sched_count *data = user;
4172 return update_count(bset, 1, &data->n_eq, &data->n_ineq);
4175 /* Count the number of equality and inequality constraints
4176 * that will be added to the carry_lp problem.
4177 * We count each edge exactly once.
4178 * "intra" is the sequence of coefficient constraints for intra-node edges.
4179 * "inter" is the sequence of coefficient constraints for inter-node edges.
4181 static isl_stat count_all_constraints(__isl_keep isl_basic_set_list *intra,
4182 __isl_keep isl_basic_set_list *inter, int *n_eq, int *n_ineq)
4184 struct isl_sched_count data;
4186 data.n_eq = data.n_ineq = 0;
4187 if (isl_basic_set_list_foreach(inter, &bset_update_count, &data) < 0)
4188 return isl_stat_error;
4189 if (isl_basic_set_list_foreach(intra, &bset_update_count, &data) < 0)
4190 return isl_stat_error;
4192 *n_eq = data.n_eq;
4193 *n_ineq = data.n_ineq;
4195 return isl_stat_ok;
4198 /* Construct an LP problem for finding schedule coefficients
4199 * such that the schedule carries as many validity dependences as possible.
4200 * In particular, for each dependence i, we bound the dependence distance
4201 * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
4202 * of all e_i's. Dependences with e_i = 0 in the solution are simply
4203 * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
4204 * "intra" is the sequence of coefficient constraints for intra-node edges.
4205 * "inter" is the sequence of coefficient constraints for inter-node edges.
4206 * "n_edge" is the total number of edges.
4207 * "carry_inter" indicates whether inter-node edges should be carried or
4208 * only respected. That is, if "carry_inter" is not set, then
4209 * no e_i variables are introduced for the inter-node edges.
4211 * All variables of the LP are non-negative. The actual coefficients
4212 * may be negative, so each coefficient is represented as the difference
4213 * of two non-negative variables. The negative part always appears
4214 * immediately before the positive part.
4215 * Other than that, the variables have the following order
4217 * - sum of (1 - e_i) over all edges
4218 * - sum of all c_n coefficients
4219 * (unconstrained when computing non-parametric schedules)
4220 * - sum of positive and negative parts of all c_x coefficients
4221 * - for each edge
4222 * - e_i
4223 * - for each node
4224 * - positive and negative parts of c_i_x, in opposite order
4225 * - c_i_n (if parametric)
4226 * - c_i_0
4228 * The constraints are those from the (validity) edges plus three equalities
4229 * to express the sums and n_edge inequalities to express e_i <= 1.
4231 static isl_stat setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
4232 int n_edge, __isl_keep isl_basic_set_list *intra,
4233 __isl_keep isl_basic_set_list *inter, int carry_inter)
4235 int i;
4236 int k;
4237 isl_space *dim;
4238 unsigned total;
4239 int n_eq, n_ineq;
4241 total = 3 + n_edge;
4242 for (i = 0; i < graph->n; ++i) {
4243 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
4244 node->start = total;
4245 total += 1 + node->nparam + 2 * node->nvar;
4248 if (count_all_constraints(intra, inter, &n_eq, &n_ineq) < 0)
4249 return isl_stat_error;
4251 dim = isl_space_set_alloc(ctx, 0, total);
4252 isl_basic_set_free(graph->lp);
4253 n_eq += 3;
4254 n_ineq += n_edge;
4255 graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
4256 graph->lp = isl_basic_set_set_rational(graph->lp);
4258 k = isl_basic_set_alloc_equality(graph->lp);
4259 if (k < 0)
4260 return isl_stat_error;
4261 isl_seq_clr(graph->lp->eq[k], 1 + total);
4262 isl_int_set_si(graph->lp->eq[k][0], -n_edge);
4263 isl_int_set_si(graph->lp->eq[k][1], 1);
4264 for (i = 0; i < n_edge; ++i)
4265 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
4267 if (add_param_sum_constraint(graph, 1) < 0)
4268 return isl_stat_error;
4269 if (add_var_sum_constraint(graph, 2) < 0)
4270 return isl_stat_error;
4272 for (i = 0; i < n_edge; ++i) {
4273 k = isl_basic_set_alloc_inequality(graph->lp);
4274 if (k < 0)
4275 return isl_stat_error;
4276 isl_seq_clr(graph->lp->ineq[k], 1 + total);
4277 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
4278 isl_int_set_si(graph->lp->ineq[k][0], 1);
4281 if (add_all_constraints(ctx, graph, intra, inter, carry_inter) < 0)
4282 return isl_stat_error;
4284 return isl_stat_ok;
4287 static __isl_give isl_schedule_node *compute_component_schedule(
4288 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4289 int wcc);
4291 /* If the schedule_split_scaled option is set and if the linear
4292 * parts of the scheduling rows for all nodes in the graphs have
4293 * a non-trivial common divisor, then remove this
4294 * common divisor from the linear part.
4295 * Otherwise, insert a band node directly and continue with
4296 * the construction of the schedule.
4298 * If a non-trivial common divisor is found, then
4299 * the linear part is reduced and the remainder is ignored.
4300 * The pieces of the graph that are assigned different remainders
4301 * form (groups of) strongly connected components within
4302 * the scaled down band. If needed, they can therefore
4303 * be ordered along this remainder in a sequence node.
4304 * However, this ordering is not enforced here in order to allow
4305 * the scheduler to combine some of the strongly connected components.
4307 static __isl_give isl_schedule_node *split_scaled(
4308 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4310 int i;
4311 int row;
4312 isl_ctx *ctx;
4313 isl_int gcd, gcd_i;
4314 isl_size n_row;
4316 if (!node)
4317 return NULL;
4319 ctx = isl_schedule_node_get_ctx(node);
4320 if (!ctx->opt->schedule_split_scaled)
4321 return compute_next_band(node, graph, 0);
4322 if (graph->n <= 1)
4323 return compute_next_band(node, graph, 0);
4324 n_row = isl_mat_rows(graph->node[0].sched);
4325 if (n_row < 0)
4326 return isl_schedule_node_free(node);
4328 isl_int_init(gcd);
4329 isl_int_init(gcd_i);
4331 isl_int_set_si(gcd, 0);
4333 row = n_row - 1;
4335 for (i = 0; i < graph->n; ++i) {
4336 struct isl_sched_node *node = &graph->node[i];
4337 isl_size cols = isl_mat_cols(node->sched);
4339 if (cols < 0)
4340 break;
4341 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
4342 isl_int_gcd(gcd, gcd, gcd_i);
4345 isl_int_clear(gcd_i);
4346 if (i < graph->n)
4347 goto error;
4349 if (isl_int_cmp_si(gcd, 1) <= 0) {
4350 isl_int_clear(gcd);
4351 return compute_next_band(node, graph, 0);
4354 for (i = 0; i < graph->n; ++i) {
4355 struct isl_sched_node *node = &graph->node[i];
4357 isl_int_fdiv_q(node->sched->row[row][0],
4358 node->sched->row[row][0], gcd);
4359 isl_int_mul(node->sched->row[row][0],
4360 node->sched->row[row][0], gcd);
4361 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
4362 if (!node->sched)
4363 goto error;
4366 isl_int_clear(gcd);
4368 return compute_next_band(node, graph, 0);
4369 error:
4370 isl_int_clear(gcd);
4371 return isl_schedule_node_free(node);
4374 /* Is the schedule row "sol" trivial on node "node"?
4375 * That is, is the solution zero on the dimensions linearly independent of
4376 * the previously found solutions?
4377 * Return 1 if the solution is trivial, 0 if it is not and -1 on error.
4379 * Each coefficient is represented as the difference between
4380 * two non-negative values in "sol".
4381 * We construct the schedule row s and check if it is linearly
4382 * independent of previously computed schedule rows
4383 * by computing T s, with T the linear combinations that are zero
4384 * on linearly dependent schedule rows.
4385 * If the result consists of all zeros, then the solution is trivial.
4387 static int is_trivial(struct isl_sched_node *node, __isl_keep isl_vec *sol)
4389 int trivial;
4390 isl_vec *node_sol;
4392 if (!sol)
4393 return -1;
4394 if (node->nvar == node->rank)
4395 return 0;
4397 node_sol = extract_var_coef(node, sol);
4398 node_sol = isl_mat_vec_product(isl_mat_copy(node->indep), node_sol);
4399 if (!node_sol)
4400 return -1;
4402 trivial = isl_seq_first_non_zero(node_sol->el,
4403 node->nvar - node->rank) == -1;
4405 isl_vec_free(node_sol);
4407 return trivial;
4410 /* Is the schedule row "sol" trivial on any node where it should
4411 * not be trivial?
4412 * Return 1 if any solution is trivial, 0 if they are not and -1 on error.
4414 static int is_any_trivial(struct isl_sched_graph *graph,
4415 __isl_keep isl_vec *sol)
4417 int i;
4419 for (i = 0; i < graph->n; ++i) {
4420 struct isl_sched_node *node = &graph->node[i];
4421 int trivial;
4423 if (!needs_row(graph, node))
4424 continue;
4425 trivial = is_trivial(node, sol);
4426 if (trivial < 0 || trivial)
4427 return trivial;
4430 return 0;
4433 /* Does the schedule represented by "sol" perform loop coalescing on "node"?
4434 * If so, return the position of the coalesced dimension.
4435 * Otherwise, return node->nvar or -1 on error.
4437 * In particular, look for pairs of coefficients c_i and c_j such that
4438 * |c_j/c_i| > ceil(size_i/2), i.e., |c_j| > |c_i * ceil(size_i/2)|.
4439 * If any such pair is found, then return i.
4440 * If size_i is infinity, then no check on c_i needs to be performed.
4442 static int find_node_coalescing(struct isl_sched_node *node,
4443 __isl_keep isl_vec *sol)
4445 int i, j;
4446 isl_int max;
4447 isl_vec *csol;
4449 if (node->nvar <= 1)
4450 return node->nvar;
4452 csol = extract_var_coef(node, sol);
4453 if (!csol)
4454 return -1;
4455 isl_int_init(max);
4456 for (i = 0; i < node->nvar; ++i) {
4457 isl_val *v;
4459 if (isl_int_is_zero(csol->el[i]))
4460 continue;
4461 v = isl_multi_val_get_val(node->sizes, i);
4462 if (!v)
4463 goto error;
4464 if (!isl_val_is_int(v)) {
4465 isl_val_free(v);
4466 continue;
4468 v = isl_val_div_ui(v, 2);
4469 v = isl_val_ceil(v);
4470 if (!v)
4471 goto error;
4472 isl_int_mul(max, v->n, csol->el[i]);
4473 isl_val_free(v);
4475 for (j = 0; j < node->nvar; ++j) {
4476 if (j == i)
4477 continue;
4478 if (isl_int_abs_gt(csol->el[j], max))
4479 break;
4481 if (j < node->nvar)
4482 break;
4485 isl_int_clear(max);
4486 isl_vec_free(csol);
4487 return i;
4488 error:
4489 isl_int_clear(max);
4490 isl_vec_free(csol);
4491 return -1;
4494 /* Force the schedule coefficient at position "pos" of "node" to be zero
4495 * in "tl".
4496 * The coefficient is encoded as the difference between two non-negative
4497 * variables. Force these two variables to have the same value.
4499 static __isl_give isl_tab_lexmin *zero_out_node_coef(
4500 __isl_take isl_tab_lexmin *tl, struct isl_sched_node *node, int pos)
4502 int dim;
4503 isl_ctx *ctx;
4504 isl_vec *eq;
4506 ctx = isl_space_get_ctx(node->space);
4507 dim = isl_tab_lexmin_dim(tl);
4508 if (dim < 0)
4509 return isl_tab_lexmin_free(tl);
4510 eq = isl_vec_alloc(ctx, 1 + dim);
4511 eq = isl_vec_clr(eq);
4512 if (!eq)
4513 return isl_tab_lexmin_free(tl);
4515 pos = 1 + node_var_coef_pos(node, pos);
4516 isl_int_set_si(eq->el[pos], 1);
4517 isl_int_set_si(eq->el[pos + 1], -1);
4518 tl = isl_tab_lexmin_add_eq(tl, eq->el);
4519 isl_vec_free(eq);
4521 return tl;
4524 /* Return the lexicographically smallest rational point in the basic set
4525 * from which "tl" was constructed, double checking that this input set
4526 * was not empty.
4528 static __isl_give isl_vec *non_empty_solution(__isl_keep isl_tab_lexmin *tl)
4530 isl_vec *sol;
4532 sol = isl_tab_lexmin_get_solution(tl);
4533 if (!sol)
4534 return NULL;
4535 if (sol->size == 0)
4536 isl_die(isl_vec_get_ctx(sol), isl_error_internal,
4537 "error in schedule construction",
4538 return isl_vec_free(sol));
4539 return sol;
4542 /* Does the solution "sol" of the LP problem constructed by setup_carry_lp
4543 * carry any of the "n_edge" groups of dependences?
4544 * The value in the first position is the sum of (1 - e_i) over all "n_edge"
4545 * edges, with 0 <= e_i <= 1 equal to 1 when the dependences represented
4546 * by the edge are carried by the solution.
4547 * If the sum of the (1 - e_i) is smaller than "n_edge" then at least
4548 * one of those is carried.
4550 * Note that despite the fact that the problem is solved using a rational
4551 * solver, the solution is guaranteed to be integral.
4552 * Specifically, the dependence distance lower bounds e_i (and therefore
4553 * also their sum) are integers. See Lemma 5 of [1].
4555 * Any potential denominator of the sum is cleared by this function.
4556 * The denominator is not relevant for any of the other elements
4557 * in the solution.
4559 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4560 * Problem, Part II: Multi-Dimensional Time.
4561 * In Intl. Journal of Parallel Programming, 1992.
4563 static int carries_dependences(__isl_keep isl_vec *sol, int n_edge)
4565 isl_int_divexact(sol->el[1], sol->el[1], sol->el[0]);
4566 isl_int_set_si(sol->el[0], 1);
4567 return isl_int_cmp_si(sol->el[1], n_edge) < 0;
4570 /* Return the lexicographically smallest rational point in "lp",
4571 * assuming that all variables are non-negative and performing some
4572 * additional sanity checks.
4573 * If "want_integral" is set, then compute the lexicographically smallest
4574 * integer point instead.
4575 * In particular, "lp" should not be empty by construction.
4576 * Double check that this is the case.
4577 * If dependences are not carried for any of the "n_edge" edges,
4578 * then return an empty vector.
4580 * If the schedule_treat_coalescing option is set and
4581 * if the computed schedule performs loop coalescing on a given node,
4582 * i.e., if it is of the form
4584 * c_i i + c_j j + ...
4586 * with |c_j/c_i| >= size_i, then force the coefficient c_i to be zero
4587 * to cut out this solution. Repeat this process until no more loop
4588 * coalescing occurs or until no more dependences can be carried.
4589 * In the latter case, revert to the previously computed solution.
4591 * If the caller requests an integral solution and if coalescing should
4592 * be treated, then perform the coalescing treatment first as
4593 * an integral solution computed before coalescing treatment
4594 * would carry the same number of edges and would therefore probably
4595 * also be coalescing.
4597 * To allow the coalescing treatment to be performed first,
4598 * the initial solution is allowed to be rational and it is only
4599 * cut out (if needed) in the next iteration, if no coalescing measures
4600 * were taken.
4602 static __isl_give isl_vec *non_neg_lexmin(struct isl_sched_graph *graph,
4603 __isl_take isl_basic_set *lp, int n_edge, int want_integral)
4605 int i, pos, cut;
4606 isl_ctx *ctx;
4607 isl_tab_lexmin *tl;
4608 isl_vec *sol = NULL, *prev;
4609 int treat_coalescing;
4610 int try_again;
4612 if (!lp)
4613 return NULL;
4614 ctx = isl_basic_set_get_ctx(lp);
4615 treat_coalescing = isl_options_get_schedule_treat_coalescing(ctx);
4616 tl = isl_tab_lexmin_from_basic_set(lp);
4618 cut = 0;
4619 do {
4620 int integral;
4622 try_again = 0;
4623 if (cut)
4624 tl = isl_tab_lexmin_cut_to_integer(tl);
4625 prev = sol;
4626 sol = non_empty_solution(tl);
4627 if (!sol)
4628 goto error;
4630 integral = isl_int_is_one(sol->el[0]);
4631 if (!carries_dependences(sol, n_edge)) {
4632 if (!prev)
4633 prev = isl_vec_alloc(ctx, 0);
4634 isl_vec_free(sol);
4635 sol = prev;
4636 break;
4638 prev = isl_vec_free(prev);
4639 cut = want_integral && !integral;
4640 if (cut)
4641 try_again = 1;
4642 if (!treat_coalescing)
4643 continue;
4644 for (i = 0; i < graph->n; ++i) {
4645 struct isl_sched_node *node = &graph->node[i];
4647 pos = find_node_coalescing(node, sol);
4648 if (pos < 0)
4649 goto error;
4650 if (pos < node->nvar)
4651 break;
4653 if (i < graph->n) {
4654 try_again = 1;
4655 tl = zero_out_node_coef(tl, &graph->node[i], pos);
4656 cut = 0;
4658 } while (try_again);
4660 isl_tab_lexmin_free(tl);
4662 return sol;
4663 error:
4664 isl_tab_lexmin_free(tl);
4665 isl_vec_free(prev);
4666 isl_vec_free(sol);
4667 return NULL;
4670 /* If "edge" is an edge from a node to itself, then add the corresponding
4671 * dependence relation to "umap".
4672 * If "node" has been compressed, then the dependence relation
4673 * is also compressed first.
4675 static __isl_give isl_union_map *add_intra(__isl_take isl_union_map *umap,
4676 struct isl_sched_edge *edge)
4678 isl_map *map;
4679 struct isl_sched_node *node = edge->src;
4681 if (edge->src != edge->dst)
4682 return umap;
4684 map = isl_map_copy(edge->map);
4685 if (node->compressed) {
4686 map = isl_map_preimage_domain_multi_aff(map,
4687 isl_multi_aff_copy(node->decompress));
4688 map = isl_map_preimage_range_multi_aff(map,
4689 isl_multi_aff_copy(node->decompress));
4691 umap = isl_union_map_add_map(umap, map);
4692 return umap;
4695 /* If "edge" is an edge from a node to another node, then add the corresponding
4696 * dependence relation to "umap".
4697 * If the source or destination nodes of "edge" have been compressed,
4698 * then the dependence relation is also compressed first.
4700 static __isl_give isl_union_map *add_inter(__isl_take isl_union_map *umap,
4701 struct isl_sched_edge *edge)
4703 isl_map *map;
4705 if (edge->src == edge->dst)
4706 return umap;
4708 map = isl_map_copy(edge->map);
4709 if (edge->src->compressed)
4710 map = isl_map_preimage_domain_multi_aff(map,
4711 isl_multi_aff_copy(edge->src->decompress));
4712 if (edge->dst->compressed)
4713 map = isl_map_preimage_range_multi_aff(map,
4714 isl_multi_aff_copy(edge->dst->decompress));
4715 umap = isl_union_map_add_map(umap, map);
4716 return umap;
4719 /* Internal data structure used by union_drop_coalescing_constraints
4720 * to collect bounds on all relevant statements.
4722 * "graph" is the schedule constraint graph for which an LP problem
4723 * is being constructed.
4724 * "bounds" collects the bounds.
4726 struct isl_collect_bounds_data {
4727 isl_ctx *ctx;
4728 struct isl_sched_graph *graph;
4729 isl_union_set *bounds;
4732 /* Add the size bounds for the node with instance deltas in "set"
4733 * to data->bounds.
4735 static isl_stat collect_bounds(__isl_take isl_set *set, void *user)
4737 struct isl_collect_bounds_data *data = user;
4738 struct isl_sched_node *node;
4739 isl_space *space;
4740 isl_set *bounds;
4742 space = isl_set_get_space(set);
4743 isl_set_free(set);
4745 node = graph_find_compressed_node(data->ctx, data->graph, space);
4746 isl_space_free(space);
4748 bounds = isl_set_from_basic_set(get_size_bounds(node));
4749 data->bounds = isl_union_set_add_set(data->bounds, bounds);
4751 return isl_stat_ok;
4754 /* Drop some constraints from "delta" that could be exploited
4755 * to construct loop coalescing schedules.
4756 * In particular, drop those constraint that bound the difference
4757 * to the size of the domain.
4758 * Do this for each set/node in "delta" separately.
4759 * The parameters are assumed to have been projected out by the caller.
4761 static __isl_give isl_union_set *union_drop_coalescing_constraints(isl_ctx *ctx,
4762 struct isl_sched_graph *graph, __isl_take isl_union_set *delta)
4764 struct isl_collect_bounds_data data = { ctx, graph };
4766 data.bounds = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4767 if (isl_union_set_foreach_set(delta, &collect_bounds, &data) < 0)
4768 data.bounds = isl_union_set_free(data.bounds);
4769 delta = isl_union_set_plain_gist(delta, data.bounds);
4771 return delta;
4774 /* Given a non-trivial lineality space "lineality", add the corresponding
4775 * universe set to data->mask and add a map from elements to
4776 * other elements along the lines in "lineality" to data->equivalent.
4777 * If this is the first time this function gets called
4778 * (data->any_non_trivial is still false), then set data->any_non_trivial and
4779 * initialize data->mask and data->equivalent.
4781 * In particular, if the lineality space is defined by equality constraints
4783 * E x = 0
4785 * then construct an affine mapping
4787 * f : x -> E x
4789 * and compute the equivalence relation of having the same image under f:
4791 * { x -> x' : E x = E x' }
4793 static isl_stat add_non_trivial_lineality(__isl_take isl_basic_set *lineality,
4794 struct isl_exploit_lineality_data *data)
4796 isl_mat *eq;
4797 isl_space *space;
4798 isl_set *univ;
4799 isl_multi_aff *ma;
4800 isl_multi_pw_aff *mpa;
4801 isl_map *map;
4802 isl_size n;
4804 if (isl_basic_set_check_no_locals(lineality) < 0)
4805 goto error;
4807 space = isl_basic_set_get_space(lineality);
4808 if (!data->any_non_trivial) {
4809 data->equivalent = isl_union_map_empty(isl_space_copy(space));
4810 data->mask = isl_union_set_empty(isl_space_copy(space));
4812 data->any_non_trivial = isl_bool_true;
4814 univ = isl_set_universe(isl_space_copy(space));
4815 data->mask = isl_union_set_add_set(data->mask, univ);
4817 eq = isl_basic_set_extract_equalities(lineality);
4818 n = isl_mat_rows(eq);
4819 if (n < 0)
4820 space = isl_space_free(space);
4821 eq = isl_mat_insert_zero_rows(eq, 0, 1);
4822 eq = isl_mat_set_element_si(eq, 0, 0, 1);
4823 space = isl_space_from_domain(space);
4824 space = isl_space_add_dims(space, isl_dim_out, n);
4825 ma = isl_multi_aff_from_aff_mat(space, eq);
4826 mpa = isl_multi_pw_aff_from_multi_aff(ma);
4827 map = isl_multi_pw_aff_eq_map(mpa, isl_multi_pw_aff_copy(mpa));
4828 data->equivalent = isl_union_map_add_map(data->equivalent, map);
4830 isl_basic_set_free(lineality);
4831 return isl_stat_ok;
4832 error:
4833 isl_basic_set_free(lineality);
4834 return isl_stat_error;
4837 /* Check if the lineality space "set" is non-trivial (i.e., is not just
4838 * the origin or, in other words, satisfies a number of equality constraints
4839 * that is smaller than the dimension of the set).
4840 * If so, extend data->mask and data->equivalent accordingly.
4842 * The input should not have any local variables already, but
4843 * isl_set_remove_divs is called to make sure it does not.
4845 static isl_stat add_lineality(__isl_take isl_set *set, void *user)
4847 struct isl_exploit_lineality_data *data = user;
4848 isl_basic_set *hull;
4849 isl_size dim;
4850 int n_eq;
4852 set = isl_set_remove_divs(set);
4853 hull = isl_set_unshifted_simple_hull(set);
4854 dim = isl_basic_set_dim(hull, isl_dim_set);
4855 n_eq = isl_basic_set_n_equality(hull);
4856 if (dim < 0)
4857 goto error;
4858 if (dim != n_eq)
4859 return add_non_trivial_lineality(hull, data);
4860 isl_basic_set_free(hull);
4861 return isl_stat_ok;
4862 error:
4863 isl_basic_set_free(hull);
4864 return isl_stat_error;
4867 /* Check if the difference set on intra-node schedule constraints "intra"
4868 * has any non-trivial lineality space.
4869 * If so, then extend the difference set to a difference set
4870 * on equivalent elements. That is, if "intra" is
4872 * { y - x : (x,y) \in V }
4874 * and elements are equivalent if they have the same image under f,
4875 * then return
4877 * { y' - x' : (x,y) \in V and f(x) = f(x') and f(y) = f(y') }
4879 * or, since f is linear,
4881 * { y' - x' : (x,y) \in V and f(y - x) = f(y' - x') }
4883 * The results of the search for non-trivial lineality spaces is stored
4884 * in "data".
4886 static __isl_give isl_union_set *exploit_intra_lineality(
4887 __isl_take isl_union_set *intra,
4888 struct isl_exploit_lineality_data *data)
4890 isl_union_set *lineality;
4891 isl_union_set *uset;
4893 data->any_non_trivial = isl_bool_false;
4894 lineality = isl_union_set_copy(intra);
4895 lineality = isl_union_set_combined_lineality_space(lineality);
4896 if (isl_union_set_foreach_set(lineality, &add_lineality, data) < 0)
4897 data->any_non_trivial = isl_bool_error;
4898 isl_union_set_free(lineality);
4900 if (data->any_non_trivial < 0)
4901 return isl_union_set_free(intra);
4902 if (!data->any_non_trivial)
4903 return intra;
4905 uset = isl_union_set_copy(intra);
4906 intra = isl_union_set_subtract(intra, isl_union_set_copy(data->mask));
4907 uset = isl_union_set_apply(uset, isl_union_map_copy(data->equivalent));
4908 intra = isl_union_set_union(intra, uset);
4910 intra = isl_union_set_remove_divs(intra);
4912 return intra;
4915 /* If the difference set on intra-node schedule constraints was found to have
4916 * any non-trivial lineality space by exploit_intra_lineality,
4917 * as recorded in "data", then extend the inter-node
4918 * schedule constraints "inter" to schedule constraints on equivalent elements.
4919 * That is, if "inter" is V and
4920 * elements are equivalent if they have the same image under f, then return
4922 * { (x', y') : (x,y) \in V and f(x) = f(x') and f(y) = f(y') }
4924 static __isl_give isl_union_map *exploit_inter_lineality(
4925 __isl_take isl_union_map *inter,
4926 struct isl_exploit_lineality_data *data)
4928 isl_union_map *umap;
4930 if (data->any_non_trivial < 0)
4931 return isl_union_map_free(inter);
4932 if (!data->any_non_trivial)
4933 return inter;
4935 umap = isl_union_map_copy(inter);
4936 inter = isl_union_map_subtract_range(inter,
4937 isl_union_set_copy(data->mask));
4938 umap = isl_union_map_apply_range(umap,
4939 isl_union_map_copy(data->equivalent));
4940 inter = isl_union_map_union(inter, umap);
4941 umap = isl_union_map_copy(inter);
4942 inter = isl_union_map_subtract_domain(inter,
4943 isl_union_set_copy(data->mask));
4944 umap = isl_union_map_apply_range(isl_union_map_copy(data->equivalent),
4945 umap);
4946 inter = isl_union_map_union(inter, umap);
4948 inter = isl_union_map_remove_divs(inter);
4950 return inter;
4953 /* For each (conditional) validity edge in "graph",
4954 * add the corresponding dependence relation using "add"
4955 * to a collection of dependence relations and return the result.
4956 * If "coincidence" is set, then coincidence edges are considered as well.
4958 static __isl_give isl_union_map *collect_validity(struct isl_sched_graph *graph,
4959 __isl_give isl_union_map *(*add)(__isl_take isl_union_map *umap,
4960 struct isl_sched_edge *edge), int coincidence)
4962 int i;
4963 isl_space *space;
4964 isl_union_map *umap;
4966 space = isl_space_copy(graph->node[0].space);
4967 umap = isl_union_map_empty(space);
4969 for (i = 0; i < graph->n_edge; ++i) {
4970 struct isl_sched_edge *edge = &graph->edge[i];
4972 if (!is_any_validity(edge) &&
4973 (!coincidence || !is_coincidence(edge)))
4974 continue;
4976 umap = add(umap, edge);
4979 return umap;
4982 /* For each dependence relation on a (conditional) validity edge
4983 * from a node to itself,
4984 * construct the set of coefficients of valid constraints for elements
4985 * in that dependence relation and collect the results.
4986 * If "coincidence" is set, then coincidence edges are considered as well.
4988 * In particular, for each dependence relation R, constraints
4989 * on coefficients (c_0, c_x) are constructed such that
4991 * c_0 + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
4993 * If the schedule_treat_coalescing option is set, then some constraints
4994 * that could be exploited to construct coalescing schedules
4995 * are removed before the dual is computed, but after the parameters
4996 * have been projected out.
4997 * The entire computation is essentially the same as that performed
4998 * by intra_coefficients, except that it operates on multiple
4999 * edges together and that the parameters are always projected out.
5001 * Additionally, exploit any non-trivial lineality space
5002 * in the difference set after removing coalescing constraints and
5003 * store the results of the non-trivial lineality space detection in "data".
5004 * The procedure is currently run unconditionally, but it is unlikely
5005 * to find any non-trivial lineality spaces if no coalescing constraints
5006 * have been removed.
5008 * Note that if a dependence relation is a union of basic maps,
5009 * then each basic map needs to be treated individually as it may only
5010 * be possible to carry the dependences expressed by some of those
5011 * basic maps and not all of them.
5012 * The collected validity constraints are therefore not coalesced and
5013 * it is assumed that they are not coalesced automatically.
5014 * Duplicate basic maps can be removed, however.
5015 * In particular, if the same basic map appears as a disjunct
5016 * in multiple edges, then it only needs to be carried once.
5018 static __isl_give isl_basic_set_list *collect_intra_validity(isl_ctx *ctx,
5019 struct isl_sched_graph *graph, int coincidence,
5020 struct isl_exploit_lineality_data *data)
5022 isl_union_map *intra;
5023 isl_union_set *delta;
5024 isl_basic_set_list *list;
5026 intra = collect_validity(graph, &add_intra, coincidence);
5027 delta = isl_union_map_deltas(intra);
5028 delta = isl_union_set_project_out_all_params(delta);
5029 delta = isl_union_set_remove_divs(delta);
5030 if (isl_options_get_schedule_treat_coalescing(ctx))
5031 delta = union_drop_coalescing_constraints(ctx, graph, delta);
5032 delta = exploit_intra_lineality(delta, data);
5033 list = isl_union_set_get_basic_set_list(delta);
5034 isl_union_set_free(delta);
5036 return isl_basic_set_list_coefficients(list);
5039 /* For each dependence relation on a (conditional) validity edge
5040 * from a node to some other node,
5041 * construct the set of coefficients of valid constraints for elements
5042 * in that dependence relation and collect the results.
5043 * If "coincidence" is set, then coincidence edges are considered as well.
5045 * In particular, for each dependence relation R, constraints
5046 * on coefficients (c_0, c_n, c_x, c_y) are constructed such that
5048 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
5050 * This computation is essentially the same as that performed
5051 * by inter_coefficients, except that it operates on multiple
5052 * edges together.
5054 * Additionally, exploit any non-trivial lineality space
5055 * that may have been discovered by collect_intra_validity
5056 * (as stored in "data").
5058 * Note that if a dependence relation is a union of basic maps,
5059 * then each basic map needs to be treated individually as it may only
5060 * be possible to carry the dependences expressed by some of those
5061 * basic maps and not all of them.
5062 * The collected validity constraints are therefore not coalesced and
5063 * it is assumed that they are not coalesced automatically.
5064 * Duplicate basic maps can be removed, however.
5065 * In particular, if the same basic map appears as a disjunct
5066 * in multiple edges, then it only needs to be carried once.
5068 static __isl_give isl_basic_set_list *collect_inter_validity(
5069 struct isl_sched_graph *graph, int coincidence,
5070 struct isl_exploit_lineality_data *data)
5072 isl_union_map *inter;
5073 isl_union_set *wrap;
5074 isl_basic_set_list *list;
5076 inter = collect_validity(graph, &add_inter, coincidence);
5077 inter = exploit_inter_lineality(inter, data);
5078 inter = isl_union_map_remove_divs(inter);
5079 wrap = isl_union_map_wrap(inter);
5080 list = isl_union_set_get_basic_set_list(wrap);
5081 isl_union_set_free(wrap);
5082 return isl_basic_set_list_coefficients(list);
5085 /* Construct an LP problem for finding schedule coefficients
5086 * such that the schedule carries as many of the "n_edge" groups of
5087 * dependences as possible based on the corresponding coefficient
5088 * constraints and return the lexicographically smallest non-trivial solution.
5089 * "intra" is the sequence of coefficient constraints for intra-node edges.
5090 * "inter" is the sequence of coefficient constraints for inter-node edges.
5091 * If "want_integral" is set, then compute an integral solution
5092 * for the coefficients rather than using the numerators
5093 * of a rational solution.
5094 * "carry_inter" indicates whether inter-node edges should be carried or
5095 * only respected.
5097 * If none of the "n_edge" groups can be carried
5098 * then return an empty vector.
5100 static __isl_give isl_vec *compute_carrying_sol_coef(isl_ctx *ctx,
5101 struct isl_sched_graph *graph, int n_edge,
5102 __isl_keep isl_basic_set_list *intra,
5103 __isl_keep isl_basic_set_list *inter, int want_integral,
5104 int carry_inter)
5106 isl_basic_set *lp;
5108 if (setup_carry_lp(ctx, graph, n_edge, intra, inter, carry_inter) < 0)
5109 return NULL;
5111 lp = isl_basic_set_copy(graph->lp);
5112 return non_neg_lexmin(graph, lp, n_edge, want_integral);
5115 /* Construct an LP problem for finding schedule coefficients
5116 * such that the schedule carries as many of the validity dependences
5117 * as possible and
5118 * return the lexicographically smallest non-trivial solution.
5119 * If "fallback" is set, then the carrying is performed as a fallback
5120 * for the Pluto-like scheduler.
5121 * If "coincidence" is set, then try and carry coincidence edges as well.
5123 * The variable "n_edge" stores the number of groups that should be carried.
5124 * If none of the "n_edge" groups can be carried
5125 * then return an empty vector.
5126 * If, moreover, "n_edge" is zero, then the LP problem does not even
5127 * need to be constructed.
5129 * If a fallback solution is being computed, then compute an integral solution
5130 * for the coefficients rather than using the numerators
5131 * of a rational solution.
5133 * If a fallback solution is being computed, if there are any intra-node
5134 * dependences, and if requested by the user, then first try
5135 * to only carry those intra-node dependences.
5136 * If this fails to carry any dependences, then try again
5137 * with the inter-node dependences included.
5139 static __isl_give isl_vec *compute_carrying_sol(isl_ctx *ctx,
5140 struct isl_sched_graph *graph, int fallback, int coincidence)
5142 isl_size n_intra, n_inter;
5143 int n_edge;
5144 struct isl_carry carry = { 0 };
5145 isl_vec *sol;
5147 carry.intra = collect_intra_validity(ctx, graph, coincidence,
5148 &carry.lineality);
5149 carry.inter = collect_inter_validity(graph, coincidence,
5150 &carry.lineality);
5151 n_intra = isl_basic_set_list_n_basic_set(carry.intra);
5152 n_inter = isl_basic_set_list_n_basic_set(carry.inter);
5153 if (n_intra < 0 || n_inter < 0)
5154 goto error;
5156 if (fallback && n_intra > 0 &&
5157 isl_options_get_schedule_carry_self_first(ctx)) {
5158 sol = compute_carrying_sol_coef(ctx, graph, n_intra,
5159 carry.intra, carry.inter, fallback, 0);
5160 if (!sol || sol->size != 0 || n_inter == 0) {
5161 isl_carry_clear(&carry);
5162 return sol;
5164 isl_vec_free(sol);
5167 n_edge = n_intra + n_inter;
5168 if (n_edge == 0) {
5169 isl_carry_clear(&carry);
5170 return isl_vec_alloc(ctx, 0);
5173 sol = compute_carrying_sol_coef(ctx, graph, n_edge,
5174 carry.intra, carry.inter, fallback, 1);
5175 isl_carry_clear(&carry);
5176 return sol;
5177 error:
5178 isl_carry_clear(&carry);
5179 return NULL;
5182 /* Construct a schedule row for each node such that as many validity dependences
5183 * as possible are carried and then continue with the next band.
5184 * If "fallback" is set, then the carrying is performed as a fallback
5185 * for the Pluto-like scheduler.
5186 * If "coincidence" is set, then try and carry coincidence edges as well.
5188 * If there are no validity dependences, then no dependence can be carried and
5189 * the procedure is guaranteed to fail. If there is more than one component,
5190 * then try computing a schedule on each component separately
5191 * to prevent or at least postpone this failure.
5193 * If a schedule row is computed, then check that dependences are carried
5194 * for at least one of the edges.
5196 * If the computed schedule row turns out to be trivial on one or
5197 * more nodes where it should not be trivial, then we throw it away
5198 * and try again on each component separately.
5200 * If there is only one component, then we accept the schedule row anyway,
5201 * but we do not consider it as a complete row and therefore do not
5202 * increment graph->n_row. Note that the ranks of the nodes that
5203 * do get a non-trivial schedule part will get updated regardless and
5204 * graph->maxvar is computed based on these ranks. The test for
5205 * whether more schedule rows are required in compute_schedule_wcc
5206 * is therefore not affected.
5208 * Insert a band corresponding to the schedule row at position "node"
5209 * of the schedule tree and continue with the construction of the schedule.
5210 * This insertion and the continued construction is performed by split_scaled
5211 * after optionally checking for non-trivial common divisors.
5213 static __isl_give isl_schedule_node *carry(__isl_take isl_schedule_node *node,
5214 struct isl_sched_graph *graph, int fallback, int coincidence)
5216 int trivial;
5217 isl_ctx *ctx;
5218 isl_vec *sol;
5220 if (!node)
5221 return NULL;
5223 ctx = isl_schedule_node_get_ctx(node);
5224 sol = compute_carrying_sol(ctx, graph, fallback, coincidence);
5225 if (!sol)
5226 return isl_schedule_node_free(node);
5227 if (sol->size == 0) {
5228 isl_vec_free(sol);
5229 if (graph->scc > 1)
5230 return compute_component_schedule(node, graph, 1);
5231 isl_die(ctx, isl_error_unknown, "unable to carry dependences",
5232 return isl_schedule_node_free(node));
5235 trivial = is_any_trivial(graph, sol);
5236 if (trivial < 0) {
5237 sol = isl_vec_free(sol);
5238 } else if (trivial && graph->scc > 1) {
5239 isl_vec_free(sol);
5240 return compute_component_schedule(node, graph, 1);
5243 if (update_schedule(graph, sol, 0) < 0)
5244 return isl_schedule_node_free(node);
5245 if (trivial)
5246 graph->n_row--;
5248 return split_scaled(node, graph);
5251 /* Construct a schedule row for each node such that as many validity dependences
5252 * as possible are carried and then continue with the next band.
5253 * Do so as a fallback for the Pluto-like scheduler.
5254 * If "coincidence" is set, then try and carry coincidence edges as well.
5256 static __isl_give isl_schedule_node *carry_fallback(
5257 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5258 int coincidence)
5260 return carry(node, graph, 1, coincidence);
5263 /* Construct a schedule row for each node such that as many validity dependences
5264 * as possible are carried and then continue with the next band.
5265 * Do so for the case where the Feautrier scheduler was selected
5266 * by the user.
5268 static __isl_give isl_schedule_node *carry_feautrier(
5269 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5271 return carry(node, graph, 0, 0);
5274 /* Construct a schedule row for each node such that as many validity dependences
5275 * as possible are carried and then continue with the next band.
5276 * Do so as a fallback for the Pluto-like scheduler.
5278 static __isl_give isl_schedule_node *carry_dependences(
5279 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5281 return carry_fallback(node, graph, 0);
5284 /* Construct a schedule row for each node such that as many validity or
5285 * coincidence dependences as possible are carried and
5286 * then continue with the next band.
5287 * Do so as a fallback for the Pluto-like scheduler.
5289 static __isl_give isl_schedule_node *carry_coincidence(
5290 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5292 return carry_fallback(node, graph, 1);
5295 /* Topologically sort statements mapped to the same schedule iteration
5296 * and add insert a sequence node in front of "node"
5297 * corresponding to this order.
5298 * If "initialized" is set, then it may be assumed that compute_maxvar
5299 * has been called on the current band. Otherwise, call
5300 * compute_maxvar if and before carry_dependences gets called.
5302 * If it turns out to be impossible to sort the statements apart,
5303 * because different dependences impose different orderings
5304 * on the statements, then we extend the schedule such that
5305 * it carries at least one more dependence.
5307 static __isl_give isl_schedule_node *sort_statements(
5308 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5309 int initialized)
5311 isl_ctx *ctx;
5312 isl_union_set_list *filters;
5314 if (!node)
5315 return NULL;
5317 ctx = isl_schedule_node_get_ctx(node);
5318 if (graph->n < 1)
5319 isl_die(ctx, isl_error_internal,
5320 "graph should have at least one node",
5321 return isl_schedule_node_free(node));
5323 if (graph->n == 1)
5324 return node;
5326 if (update_edges(ctx, graph) < 0)
5327 return isl_schedule_node_free(node);
5329 if (graph->n_edge == 0)
5330 return node;
5332 if (detect_sccs(ctx, graph) < 0)
5333 return isl_schedule_node_free(node);
5335 next_band(graph);
5336 if (graph->scc < graph->n) {
5337 if (!initialized && compute_maxvar(graph) < 0)
5338 return isl_schedule_node_free(node);
5339 return carry_dependences(node, graph);
5342 filters = extract_sccs(ctx, graph);
5343 node = isl_schedule_node_insert_sequence(node, filters);
5345 return node;
5348 /* Are there any (non-empty) (conditional) validity edges in the graph?
5350 static int has_validity_edges(struct isl_sched_graph *graph)
5352 int i;
5354 for (i = 0; i < graph->n_edge; ++i) {
5355 int empty;
5357 empty = isl_map_plain_is_empty(graph->edge[i].map);
5358 if (empty < 0)
5359 return -1;
5360 if (empty)
5361 continue;
5362 if (is_any_validity(&graph->edge[i]))
5363 return 1;
5366 return 0;
5369 /* Should we apply a Feautrier step?
5370 * That is, did the user request the Feautrier algorithm and are
5371 * there any validity dependences (left)?
5373 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
5375 if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
5376 return 0;
5378 return has_validity_edges(graph);
5381 /* Compute a schedule for a connected dependence graph using Feautrier's
5382 * multi-dimensional scheduling algorithm and return the updated schedule node.
5384 * The original algorithm is described in [1].
5385 * The main idea is to minimize the number of scheduling dimensions, by
5386 * trying to satisfy as many dependences as possible per scheduling dimension.
5388 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
5389 * Problem, Part II: Multi-Dimensional Time.
5390 * In Intl. Journal of Parallel Programming, 1992.
5392 static __isl_give isl_schedule_node *compute_schedule_wcc_feautrier(
5393 isl_schedule_node *node, struct isl_sched_graph *graph)
5395 return carry_feautrier(node, graph);
5398 /* Turn off the "local" bit on all (condition) edges.
5400 static void clear_local_edges(struct isl_sched_graph *graph)
5402 int i;
5404 for (i = 0; i < graph->n_edge; ++i)
5405 if (is_condition(&graph->edge[i]))
5406 clear_local(&graph->edge[i]);
5409 /* Does "graph" have both condition and conditional validity edges?
5411 static int need_condition_check(struct isl_sched_graph *graph)
5413 int i;
5414 int any_condition = 0;
5415 int any_conditional_validity = 0;
5417 for (i = 0; i < graph->n_edge; ++i) {
5418 if (is_condition(&graph->edge[i]))
5419 any_condition = 1;
5420 if (is_conditional_validity(&graph->edge[i]))
5421 any_conditional_validity = 1;
5424 return any_condition && any_conditional_validity;
5427 /* Does "graph" contain any coincidence edge?
5429 static int has_any_coincidence(struct isl_sched_graph *graph)
5431 int i;
5433 for (i = 0; i < graph->n_edge; ++i)
5434 if (is_coincidence(&graph->edge[i]))
5435 return 1;
5437 return 0;
5440 /* Extract the final schedule row as a map with the iteration domain
5441 * of "node" as domain.
5443 static __isl_give isl_map *final_row(struct isl_sched_node *node)
5445 isl_multi_aff *ma;
5446 isl_size n_row;
5448 n_row = isl_mat_rows(node->sched);
5449 if (n_row < 0)
5450 return NULL;
5451 ma = node_extract_partial_schedule_multi_aff(node, n_row - 1, 1);
5452 return isl_map_from_multi_aff(ma);
5455 /* Is the conditional validity dependence in the edge with index "edge_index"
5456 * violated by the latest (i.e., final) row of the schedule?
5457 * That is, is i scheduled after j
5458 * for any conditional validity dependence i -> j?
5460 static int is_violated(struct isl_sched_graph *graph, int edge_index)
5462 isl_map *src_sched, *dst_sched, *map;
5463 struct isl_sched_edge *edge = &graph->edge[edge_index];
5464 int empty;
5466 src_sched = final_row(edge->src);
5467 dst_sched = final_row(edge->dst);
5468 map = isl_map_copy(edge->map);
5469 map = isl_map_apply_domain(map, src_sched);
5470 map = isl_map_apply_range(map, dst_sched);
5471 map = isl_map_order_gt(map, isl_dim_in, 0, isl_dim_out, 0);
5472 empty = isl_map_is_empty(map);
5473 isl_map_free(map);
5475 if (empty < 0)
5476 return -1;
5478 return !empty;
5481 /* Does "graph" have any satisfied condition edges that
5482 * are adjacent to the conditional validity constraint with
5483 * domain "conditional_source" and range "conditional_sink"?
5485 * A satisfied condition is one that is not local.
5486 * If a condition was forced to be local already (i.e., marked as local)
5487 * then there is no need to check if it is in fact local.
5489 * Additionally, mark all adjacent condition edges found as local.
5491 static int has_adjacent_true_conditions(struct isl_sched_graph *graph,
5492 __isl_keep isl_union_set *conditional_source,
5493 __isl_keep isl_union_set *conditional_sink)
5495 int i;
5496 int any = 0;
5498 for (i = 0; i < graph->n_edge; ++i) {
5499 int adjacent, local;
5500 isl_union_map *condition;
5502 if (!is_condition(&graph->edge[i]))
5503 continue;
5504 if (is_local(&graph->edge[i]))
5505 continue;
5507 condition = graph->edge[i].tagged_condition;
5508 adjacent = domain_intersects(condition, conditional_sink);
5509 if (adjacent >= 0 && !adjacent)
5510 adjacent = range_intersects(condition,
5511 conditional_source);
5512 if (adjacent < 0)
5513 return -1;
5514 if (!adjacent)
5515 continue;
5517 set_local(&graph->edge[i]);
5519 local = is_condition_false(&graph->edge[i]);
5520 if (local < 0)
5521 return -1;
5522 if (!local)
5523 any = 1;
5526 return any;
5529 /* Are there any violated conditional validity dependences with
5530 * adjacent condition dependences that are not local with respect
5531 * to the current schedule?
5532 * That is, is the conditional validity constraint violated?
5534 * Additionally, mark all those adjacent condition dependences as local.
5535 * We also mark those adjacent condition dependences that were not marked
5536 * as local before, but just happened to be local already. This ensures
5537 * that they remain local if the schedule is recomputed.
5539 * We first collect domain and range of all violated conditional validity
5540 * dependences and then check if there are any adjacent non-local
5541 * condition dependences.
5543 static int has_violated_conditional_constraint(isl_ctx *ctx,
5544 struct isl_sched_graph *graph)
5546 int i;
5547 int any = 0;
5548 isl_union_set *source, *sink;
5550 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
5551 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
5552 for (i = 0; i < graph->n_edge; ++i) {
5553 isl_union_set *uset;
5554 isl_union_map *umap;
5555 int violated;
5557 if (!is_conditional_validity(&graph->edge[i]))
5558 continue;
5560 violated = is_violated(graph, i);
5561 if (violated < 0)
5562 goto error;
5563 if (!violated)
5564 continue;
5566 any = 1;
5568 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
5569 uset = isl_union_map_domain(umap);
5570 source = isl_union_set_union(source, uset);
5571 source = isl_union_set_coalesce(source);
5573 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
5574 uset = isl_union_map_range(umap);
5575 sink = isl_union_set_union(sink, uset);
5576 sink = isl_union_set_coalesce(sink);
5579 if (any)
5580 any = has_adjacent_true_conditions(graph, source, sink);
5582 isl_union_set_free(source);
5583 isl_union_set_free(sink);
5584 return any;
5585 error:
5586 isl_union_set_free(source);
5587 isl_union_set_free(sink);
5588 return -1;
5591 /* Examine the current band (the rows between graph->band_start and
5592 * graph->n_total_row), deciding whether to drop it or add it to "node"
5593 * and then continue with the computation of the next band, if any.
5594 * If "initialized" is set, then it may be assumed that compute_maxvar
5595 * has been called on the current band. Otherwise, call
5596 * compute_maxvar if and before carry_dependences gets called.
5598 * The caller keeps looking for a new row as long as
5599 * graph->n_row < graph->maxvar. If the latest attempt to find
5600 * such a row failed (i.e., we still have graph->n_row < graph->maxvar),
5601 * then we either
5602 * - split between SCCs and start over (assuming we found an interesting
5603 * pair of SCCs between which to split)
5604 * - continue with the next band (assuming the current band has at least
5605 * one row)
5606 * - if there is more than one SCC left, then split along all SCCs
5607 * - if outer coincidence needs to be enforced, then try to carry as many
5608 * validity or coincidence dependences as possible and
5609 * continue with the next band
5610 * - try to carry as many validity dependences as possible and
5611 * continue with the next band
5612 * In each case, we first insert a band node in the schedule tree
5613 * if any rows have been computed.
5615 * If the caller managed to complete the schedule and the current band
5616 * is empty, then finish off by topologically
5617 * sorting the statements based on the remaining dependences.
5618 * If, on the other hand, the current band has at least one row,
5619 * then continue with the next band. Note that this next band
5620 * will necessarily be empty, but the graph may still be split up
5621 * into weakly connected components before arriving back here.
5623 static __isl_give isl_schedule_node *compute_schedule_finish_band(
5624 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5625 int initialized)
5627 int empty;
5629 if (!node)
5630 return NULL;
5632 empty = graph->n_total_row == graph->band_start;
5633 if (graph->n_row < graph->maxvar) {
5634 isl_ctx *ctx;
5636 ctx = isl_schedule_node_get_ctx(node);
5637 if (!ctx->opt->schedule_maximize_band_depth && !empty)
5638 return compute_next_band(node, graph, 1);
5639 if (graph->src_scc >= 0)
5640 return compute_split_schedule(node, graph);
5641 if (!empty)
5642 return compute_next_band(node, graph, 1);
5643 if (graph->scc > 1)
5644 return compute_component_schedule(node, graph, 1);
5645 if (!initialized && compute_maxvar(graph) < 0)
5646 return isl_schedule_node_free(node);
5647 if (isl_options_get_schedule_outer_coincidence(ctx))
5648 return carry_coincidence(node, graph);
5649 return carry_dependences(node, graph);
5652 if (!empty)
5653 return compute_next_band(node, graph, 1);
5654 return sort_statements(node, graph, initialized);
5657 /* Construct a band of schedule rows for a connected dependence graph.
5658 * The caller is responsible for determining the strongly connected
5659 * components and calling compute_maxvar first.
5661 * We try to find a sequence of as many schedule rows as possible that result
5662 * in non-negative dependence distances (independent of the previous rows
5663 * in the sequence, i.e., such that the sequence is tilable), with as
5664 * many of the initial rows as possible satisfying the coincidence constraints.
5665 * The computation stops if we can't find any more rows or if we have found
5666 * all the rows we wanted to find.
5668 * If ctx->opt->schedule_outer_coincidence is set, then we force the
5669 * outermost dimension to satisfy the coincidence constraints. If this
5670 * turns out to be impossible, we fall back on the general scheme above
5671 * and try to carry as many dependences as possible.
5673 * If "graph" contains both condition and conditional validity dependences,
5674 * then we need to check that that the conditional schedule constraint
5675 * is satisfied, i.e., there are no violated conditional validity dependences
5676 * that are adjacent to any non-local condition dependences.
5677 * If there are, then we mark all those adjacent condition dependences
5678 * as local and recompute the current band. Those dependences that
5679 * are marked local will then be forced to be local.
5680 * The initial computation is performed with no dependences marked as local.
5681 * If we are lucky, then there will be no violated conditional validity
5682 * dependences adjacent to any non-local condition dependences.
5683 * Otherwise, we mark some additional condition dependences as local and
5684 * recompute. We continue this process until there are no violations left or
5685 * until we are no longer able to compute a schedule.
5686 * Since there are only a finite number of dependences,
5687 * there will only be a finite number of iterations.
5689 static isl_stat compute_schedule_wcc_band(isl_ctx *ctx,
5690 struct isl_sched_graph *graph)
5692 int has_coincidence;
5693 int use_coincidence;
5694 int force_coincidence = 0;
5695 int check_conditional;
5697 if (sort_sccs(graph) < 0)
5698 return isl_stat_error;
5700 clear_local_edges(graph);
5701 check_conditional = need_condition_check(graph);
5702 has_coincidence = has_any_coincidence(graph);
5704 if (ctx->opt->schedule_outer_coincidence)
5705 force_coincidence = 1;
5707 use_coincidence = has_coincidence;
5708 while (graph->n_row < graph->maxvar) {
5709 isl_vec *sol;
5710 int violated;
5711 int coincident;
5713 graph->src_scc = -1;
5714 graph->dst_scc = -1;
5716 if (setup_lp(ctx, graph, use_coincidence) < 0)
5717 return isl_stat_error;
5718 sol = solve_lp(ctx, graph);
5719 if (!sol)
5720 return isl_stat_error;
5721 if (sol->size == 0) {
5722 int empty = graph->n_total_row == graph->band_start;
5724 isl_vec_free(sol);
5725 if (use_coincidence && (!force_coincidence || !empty)) {
5726 use_coincidence = 0;
5727 continue;
5729 return isl_stat_ok;
5731 coincident = !has_coincidence || use_coincidence;
5732 if (update_schedule(graph, sol, coincident) < 0)
5733 return isl_stat_error;
5735 if (!check_conditional)
5736 continue;
5737 violated = has_violated_conditional_constraint(ctx, graph);
5738 if (violated < 0)
5739 return isl_stat_error;
5740 if (!violated)
5741 continue;
5742 if (reset_band(graph) < 0)
5743 return isl_stat_error;
5744 use_coincidence = has_coincidence;
5747 return isl_stat_ok;
5750 /* Compute a schedule for a connected dependence graph by considering
5751 * the graph as a whole and return the updated schedule node.
5753 * The actual schedule rows of the current band are computed by
5754 * compute_schedule_wcc_band. compute_schedule_finish_band takes
5755 * care of integrating the band into "node" and continuing
5756 * the computation.
5758 static __isl_give isl_schedule_node *compute_schedule_wcc_whole(
5759 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5761 isl_ctx *ctx;
5763 if (!node)
5764 return NULL;
5766 ctx = isl_schedule_node_get_ctx(node);
5767 if (compute_schedule_wcc_band(ctx, graph) < 0)
5768 return isl_schedule_node_free(node);
5770 return compute_schedule_finish_band(node, graph, 1);
5773 /* Clustering information used by compute_schedule_wcc_clustering.
5775 * "n" is the number of SCCs in the original dependence graph
5776 * "scc" is an array of "n" elements, each representing an SCC
5777 * of the original dependence graph. All entries in the same cluster
5778 * have the same number of schedule rows.
5779 * "scc_cluster" maps each SCC index to the cluster to which it belongs,
5780 * where each cluster is represented by the index of the first SCC
5781 * in the cluster. Initially, each SCC belongs to a cluster containing
5782 * only that SCC.
5784 * "scc_in_merge" is used by merge_clusters_along_edge to keep
5785 * track of which SCCs need to be merged.
5787 * "cluster" contains the merged clusters of SCCs after the clustering
5788 * has completed.
5790 * "scc_node" is a temporary data structure used inside copy_partial.
5791 * For each SCC, it keeps track of the number of nodes in the SCC
5792 * that have already been copied.
5794 struct isl_clustering {
5795 int n;
5796 struct isl_sched_graph *scc;
5797 struct isl_sched_graph *cluster;
5798 int *scc_cluster;
5799 int *scc_node;
5800 int *scc_in_merge;
5803 /* Initialize the clustering data structure "c" from "graph".
5805 * In particular, allocate memory, extract the SCCs from "graph"
5806 * into c->scc, initialize scc_cluster and construct
5807 * a band of schedule rows for each SCC.
5808 * Within each SCC, there is only one SCC by definition.
5809 * Each SCC initially belongs to a cluster containing only that SCC.
5811 static isl_stat clustering_init(isl_ctx *ctx, struct isl_clustering *c,
5812 struct isl_sched_graph *graph)
5814 int i;
5816 c->n = graph->scc;
5817 c->scc = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5818 c->cluster = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5819 c->scc_cluster = isl_calloc_array(ctx, int, c->n);
5820 c->scc_node = isl_calloc_array(ctx, int, c->n);
5821 c->scc_in_merge = isl_calloc_array(ctx, int, c->n);
5822 if (!c->scc || !c->cluster ||
5823 !c->scc_cluster || !c->scc_node || !c->scc_in_merge)
5824 return isl_stat_error;
5826 for (i = 0; i < c->n; ++i) {
5827 if (extract_sub_graph(ctx, graph, &node_scc_exactly,
5828 &edge_scc_exactly, i, &c->scc[i]) < 0)
5829 return isl_stat_error;
5830 c->scc[i].scc = 1;
5831 if (compute_maxvar(&c->scc[i]) < 0)
5832 return isl_stat_error;
5833 if (compute_schedule_wcc_band(ctx, &c->scc[i]) < 0)
5834 return isl_stat_error;
5835 c->scc_cluster[i] = i;
5838 return isl_stat_ok;
5841 /* Free all memory allocated for "c".
5843 static void clustering_free(isl_ctx *ctx, struct isl_clustering *c)
5845 int i;
5847 if (c->scc)
5848 for (i = 0; i < c->n; ++i)
5849 graph_free(ctx, &c->scc[i]);
5850 free(c->scc);
5851 if (c->cluster)
5852 for (i = 0; i < c->n; ++i)
5853 graph_free(ctx, &c->cluster[i]);
5854 free(c->cluster);
5855 free(c->scc_cluster);
5856 free(c->scc_node);
5857 free(c->scc_in_merge);
5860 /* Should we refrain from merging the cluster in "graph" with
5861 * any other cluster?
5862 * In particular, is its current schedule band empty and incomplete.
5864 static int bad_cluster(struct isl_sched_graph *graph)
5866 return graph->n_row < graph->maxvar &&
5867 graph->n_total_row == graph->band_start;
5870 /* Is "edge" a proximity edge with a non-empty dependence relation?
5872 static isl_bool is_non_empty_proximity(struct isl_sched_edge *edge)
5874 if (!is_proximity(edge))
5875 return isl_bool_false;
5876 return isl_bool_not(isl_map_plain_is_empty(edge->map));
5879 /* Return the index of an edge in "graph" that can be used to merge
5880 * two clusters in "c".
5881 * Return graph->n_edge if no such edge can be found.
5882 * Return -1 on error.
5884 * In particular, return a proximity edge between two clusters
5885 * that is not marked "no_merge" and such that neither of the
5886 * two clusters has an incomplete, empty band.
5888 * If there are multiple such edges, then try and find the most
5889 * appropriate edge to use for merging. In particular, pick the edge
5890 * with the greatest weight. If there are multiple of those,
5891 * then pick one with the shortest distance between
5892 * the two cluster representatives.
5894 static int find_proximity(struct isl_sched_graph *graph,
5895 struct isl_clustering *c)
5897 int i, best = graph->n_edge, best_dist, best_weight;
5899 for (i = 0; i < graph->n_edge; ++i) {
5900 struct isl_sched_edge *edge = &graph->edge[i];
5901 int dist, weight;
5902 isl_bool prox;
5904 prox = is_non_empty_proximity(edge);
5905 if (prox < 0)
5906 return -1;
5907 if (!prox)
5908 continue;
5909 if (edge->no_merge)
5910 continue;
5911 if (bad_cluster(&c->scc[edge->src->scc]) ||
5912 bad_cluster(&c->scc[edge->dst->scc]))
5913 continue;
5914 dist = c->scc_cluster[edge->dst->scc] -
5915 c->scc_cluster[edge->src->scc];
5916 if (dist == 0)
5917 continue;
5918 weight = edge->weight;
5919 if (best < graph->n_edge) {
5920 if (best_weight > weight)
5921 continue;
5922 if (best_weight == weight && best_dist <= dist)
5923 continue;
5925 best = i;
5926 best_dist = dist;
5927 best_weight = weight;
5930 return best;
5933 /* Internal data structure used in mark_merge_sccs.
5935 * "graph" is the dependence graph in which a strongly connected
5936 * component is constructed.
5937 * "scc_cluster" maps each SCC index to the cluster to which it belongs.
5938 * "src" and "dst" are the indices of the nodes that are being merged.
5940 struct isl_mark_merge_sccs_data {
5941 struct isl_sched_graph *graph;
5942 int *scc_cluster;
5943 int src;
5944 int dst;
5947 /* Check whether the cluster containing node "i" depends on the cluster
5948 * containing node "j". If "i" and "j" belong to the same cluster,
5949 * then they are taken to depend on each other to ensure that
5950 * the resulting strongly connected component consists of complete
5951 * clusters. Furthermore, if "i" and "j" are the two nodes that
5952 * are being merged, then they are taken to depend on each other as well.
5953 * Otherwise, check if there is a (conditional) validity dependence
5954 * from node[j] to node[i], forcing node[i] to follow node[j].
5956 static isl_bool cluster_follows(int i, int j, void *user)
5958 struct isl_mark_merge_sccs_data *data = user;
5959 struct isl_sched_graph *graph = data->graph;
5960 int *scc_cluster = data->scc_cluster;
5962 if (data->src == i && data->dst == j)
5963 return isl_bool_true;
5964 if (data->src == j && data->dst == i)
5965 return isl_bool_true;
5966 if (scc_cluster[graph->node[i].scc] == scc_cluster[graph->node[j].scc])
5967 return isl_bool_true;
5969 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
5972 /* Mark all SCCs that belong to either of the two clusters in "c"
5973 * connected by the edge in "graph" with index "edge", or to any
5974 * of the intermediate clusters.
5975 * The marking is recorded in c->scc_in_merge.
5977 * The given edge has been selected for merging two clusters,
5978 * meaning that there is at least a proximity edge between the two nodes.
5979 * However, there may also be (indirect) validity dependences
5980 * between the two nodes. When merging the two clusters, all clusters
5981 * containing one or more of the intermediate nodes along the
5982 * indirect validity dependences need to be merged in as well.
5984 * First collect all such nodes by computing the strongly connected
5985 * component (SCC) containing the two nodes connected by the edge, where
5986 * the two nodes are considered to depend on each other to make
5987 * sure they end up in the same SCC. Similarly, each node is considered
5988 * to depend on every other node in the same cluster to ensure
5989 * that the SCC consists of complete clusters.
5991 * Then the original SCCs that contain any of these nodes are marked
5992 * in c->scc_in_merge.
5994 static isl_stat mark_merge_sccs(isl_ctx *ctx, struct isl_sched_graph *graph,
5995 int edge, struct isl_clustering *c)
5997 struct isl_mark_merge_sccs_data data;
5998 struct isl_tarjan_graph *g;
5999 int i;
6001 for (i = 0; i < c->n; ++i)
6002 c->scc_in_merge[i] = 0;
6004 data.graph = graph;
6005 data.scc_cluster = c->scc_cluster;
6006 data.src = graph->edge[edge].src - graph->node;
6007 data.dst = graph->edge[edge].dst - graph->node;
6009 g = isl_tarjan_graph_component(ctx, graph->n, data.dst,
6010 &cluster_follows, &data);
6011 if (!g)
6012 goto error;
6014 i = g->op;
6015 if (i < 3)
6016 isl_die(ctx, isl_error_internal,
6017 "expecting at least two nodes in component",
6018 goto error);
6019 if (g->order[--i] != -1)
6020 isl_die(ctx, isl_error_internal,
6021 "expecting end of component marker", goto error);
6023 for (--i; i >= 0 && g->order[i] != -1; --i) {
6024 int scc = graph->node[g->order[i]].scc;
6025 c->scc_in_merge[scc] = 1;
6028 isl_tarjan_graph_free(g);
6029 return isl_stat_ok;
6030 error:
6031 isl_tarjan_graph_free(g);
6032 return isl_stat_error;
6035 /* Construct the identifier "cluster_i".
6037 static __isl_give isl_id *cluster_id(isl_ctx *ctx, int i)
6039 char name[40];
6041 snprintf(name, sizeof(name), "cluster_%d", i);
6042 return isl_id_alloc(ctx, name, NULL);
6045 /* Construct the space of the cluster with index "i" containing
6046 * the strongly connected component "scc".
6048 * In particular, construct a space called cluster_i with dimension equal
6049 * to the number of schedule rows in the current band of "scc".
6051 static __isl_give isl_space *cluster_space(struct isl_sched_graph *scc, int i)
6053 int nvar;
6054 isl_space *space;
6055 isl_id *id;
6057 nvar = scc->n_total_row - scc->band_start;
6058 space = isl_space_copy(scc->node[0].space);
6059 space = isl_space_params(space);
6060 space = isl_space_set_from_params(space);
6061 space = isl_space_add_dims(space, isl_dim_set, nvar);
6062 id = cluster_id(isl_space_get_ctx(space), i);
6063 space = isl_space_set_tuple_id(space, isl_dim_set, id);
6065 return space;
6068 /* Collect the domain of the graph for merging clusters.
6070 * In particular, for each cluster with first SCC "i", construct
6071 * a set in the space called cluster_i with dimension equal
6072 * to the number of schedule rows in the current band of the cluster.
6074 static __isl_give isl_union_set *collect_domain(isl_ctx *ctx,
6075 struct isl_sched_graph *graph, struct isl_clustering *c)
6077 int i;
6078 isl_space *space;
6079 isl_union_set *domain;
6081 space = isl_space_params_alloc(ctx, 0);
6082 domain = isl_union_set_empty(space);
6084 for (i = 0; i < graph->scc; ++i) {
6085 isl_space *space;
6087 if (!c->scc_in_merge[i])
6088 continue;
6089 if (c->scc_cluster[i] != i)
6090 continue;
6091 space = cluster_space(&c->scc[i], i);
6092 domain = isl_union_set_add_set(domain, isl_set_universe(space));
6095 return domain;
6098 /* Construct a map from the original instances to the corresponding
6099 * cluster instance in the current bands of the clusters in "c".
6101 static __isl_give isl_union_map *collect_cluster_map(isl_ctx *ctx,
6102 struct isl_sched_graph *graph, struct isl_clustering *c)
6104 int i, j;
6105 isl_space *space;
6106 isl_union_map *cluster_map;
6108 space = isl_space_params_alloc(ctx, 0);
6109 cluster_map = isl_union_map_empty(space);
6110 for (i = 0; i < graph->scc; ++i) {
6111 int start, n;
6112 isl_id *id;
6114 if (!c->scc_in_merge[i])
6115 continue;
6117 id = cluster_id(ctx, c->scc_cluster[i]);
6118 start = c->scc[i].band_start;
6119 n = c->scc[i].n_total_row - start;
6120 for (j = 0; j < c->scc[i].n; ++j) {
6121 isl_multi_aff *ma;
6122 isl_map *map;
6123 struct isl_sched_node *node = &c->scc[i].node[j];
6125 ma = node_extract_partial_schedule_multi_aff(node,
6126 start, n);
6127 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out,
6128 isl_id_copy(id));
6129 map = isl_map_from_multi_aff(ma);
6130 cluster_map = isl_union_map_add_map(cluster_map, map);
6132 isl_id_free(id);
6135 return cluster_map;
6138 /* Add "umap" to the schedule constraints "sc" of all types of "edge"
6139 * that are not isl_edge_condition or isl_edge_conditional_validity.
6141 static __isl_give isl_schedule_constraints *add_non_conditional_constraints(
6142 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
6143 __isl_take isl_schedule_constraints *sc)
6145 enum isl_edge_type t;
6147 if (!sc)
6148 return NULL;
6150 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
6151 if (t == isl_edge_condition ||
6152 t == isl_edge_conditional_validity)
6153 continue;
6154 if (!is_type(edge, t))
6155 continue;
6156 sc = isl_schedule_constraints_add(sc, t,
6157 isl_union_map_copy(umap));
6160 return sc;
6163 /* Add schedule constraints of types isl_edge_condition and
6164 * isl_edge_conditional_validity to "sc" by applying "umap" to
6165 * the domains of the wrapped relations in domain and range
6166 * of the corresponding tagged constraints of "edge".
6168 static __isl_give isl_schedule_constraints *add_conditional_constraints(
6169 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
6170 __isl_take isl_schedule_constraints *sc)
6172 enum isl_edge_type t;
6173 isl_union_map *tagged;
6175 for (t = isl_edge_condition; t <= isl_edge_conditional_validity; ++t) {
6176 if (!is_type(edge, t))
6177 continue;
6178 if (t == isl_edge_condition)
6179 tagged = isl_union_map_copy(edge->tagged_condition);
6180 else
6181 tagged = isl_union_map_copy(edge->tagged_validity);
6182 tagged = isl_union_map_zip(tagged);
6183 tagged = isl_union_map_apply_domain(tagged,
6184 isl_union_map_copy(umap));
6185 tagged = isl_union_map_zip(tagged);
6186 sc = isl_schedule_constraints_add(sc, t, tagged);
6187 if (!sc)
6188 return NULL;
6191 return sc;
6194 /* Given a mapping "cluster_map" from the original instances to
6195 * the cluster instances, add schedule constraints on the clusters
6196 * to "sc" corresponding to the original constraints represented by "edge".
6198 * For non-tagged dependence constraints, the cluster constraints
6199 * are obtained by applying "cluster_map" to the edge->map.
6201 * For tagged dependence constraints, "cluster_map" needs to be applied
6202 * to the domains of the wrapped relations in domain and range
6203 * of the tagged dependence constraints. Pick out the mappings
6204 * from these domains from "cluster_map" and construct their product.
6205 * This mapping can then be applied to the pair of domains.
6207 static __isl_give isl_schedule_constraints *collect_edge_constraints(
6208 struct isl_sched_edge *edge, __isl_keep isl_union_map *cluster_map,
6209 __isl_take isl_schedule_constraints *sc)
6211 isl_union_map *umap;
6212 isl_space *space;
6213 isl_union_set *uset;
6214 isl_union_map *umap1, *umap2;
6216 if (!sc)
6217 return NULL;
6219 umap = isl_union_map_from_map(isl_map_copy(edge->map));
6220 umap = isl_union_map_apply_domain(umap,
6221 isl_union_map_copy(cluster_map));
6222 umap = isl_union_map_apply_range(umap,
6223 isl_union_map_copy(cluster_map));
6224 sc = add_non_conditional_constraints(edge, umap, sc);
6225 isl_union_map_free(umap);
6227 if (!sc || (!is_condition(edge) && !is_conditional_validity(edge)))
6228 return sc;
6230 space = isl_space_domain(isl_map_get_space(edge->map));
6231 uset = isl_union_set_from_set(isl_set_universe(space));
6232 umap1 = isl_union_map_copy(cluster_map);
6233 umap1 = isl_union_map_intersect_domain(umap1, uset);
6234 space = isl_space_range(isl_map_get_space(edge->map));
6235 uset = isl_union_set_from_set(isl_set_universe(space));
6236 umap2 = isl_union_map_copy(cluster_map);
6237 umap2 = isl_union_map_intersect_domain(umap2, uset);
6238 umap = isl_union_map_product(umap1, umap2);
6240 sc = add_conditional_constraints(edge, umap, sc);
6242 isl_union_map_free(umap);
6243 return sc;
6246 /* Given a mapping "cluster_map" from the original instances to
6247 * the cluster instances, add schedule constraints on the clusters
6248 * to "sc" corresponding to all edges in "graph" between nodes that
6249 * belong to SCCs that are marked for merging in "scc_in_merge".
6251 static __isl_give isl_schedule_constraints *collect_constraints(
6252 struct isl_sched_graph *graph, int *scc_in_merge,
6253 __isl_keep isl_union_map *cluster_map,
6254 __isl_take isl_schedule_constraints *sc)
6256 int i;
6258 for (i = 0; i < graph->n_edge; ++i) {
6259 struct isl_sched_edge *edge = &graph->edge[i];
6261 if (!scc_in_merge[edge->src->scc])
6262 continue;
6263 if (!scc_in_merge[edge->dst->scc])
6264 continue;
6265 sc = collect_edge_constraints(edge, cluster_map, sc);
6268 return sc;
6271 /* Construct a dependence graph for scheduling clusters with respect
6272 * to each other and store the result in "merge_graph".
6273 * In particular, the nodes of the graph correspond to the schedule
6274 * dimensions of the current bands of those clusters that have been
6275 * marked for merging in "c".
6277 * First construct an isl_schedule_constraints object for this domain
6278 * by transforming the edges in "graph" to the domain.
6279 * Then initialize a dependence graph for scheduling from these
6280 * constraints.
6282 static isl_stat init_merge_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
6283 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6285 isl_union_set *domain;
6286 isl_union_map *cluster_map;
6287 isl_schedule_constraints *sc;
6288 isl_stat r;
6290 domain = collect_domain(ctx, graph, c);
6291 sc = isl_schedule_constraints_on_domain(domain);
6292 if (!sc)
6293 return isl_stat_error;
6294 cluster_map = collect_cluster_map(ctx, graph, c);
6295 sc = collect_constraints(graph, c->scc_in_merge, cluster_map, sc);
6296 isl_union_map_free(cluster_map);
6298 r = graph_init(merge_graph, sc);
6300 isl_schedule_constraints_free(sc);
6302 return r;
6305 /* Compute the maximal number of remaining schedule rows that still need
6306 * to be computed for the nodes that belong to clusters with the maximal
6307 * dimension for the current band (i.e., the band that is to be merged).
6308 * Only clusters that are about to be merged are considered.
6309 * "maxvar" is the maximal dimension for the current band.
6310 * "c" contains information about the clusters.
6312 * Return the maximal number of remaining schedule rows or -1 on error.
6314 static int compute_maxvar_max_slack(int maxvar, struct isl_clustering *c)
6316 int i, j;
6317 int max_slack;
6319 max_slack = 0;
6320 for (i = 0; i < c->n; ++i) {
6321 int nvar;
6322 struct isl_sched_graph *scc;
6324 if (!c->scc_in_merge[i])
6325 continue;
6326 scc = &c->scc[i];
6327 nvar = scc->n_total_row - scc->band_start;
6328 if (nvar != maxvar)
6329 continue;
6330 for (j = 0; j < scc->n; ++j) {
6331 struct isl_sched_node *node = &scc->node[j];
6332 int slack;
6334 if (node_update_vmap(node) < 0)
6335 return -1;
6336 slack = node->nvar - node->rank;
6337 if (slack > max_slack)
6338 max_slack = slack;
6342 return max_slack;
6345 /* If there are any clusters where the dimension of the current band
6346 * (i.e., the band that is to be merged) is smaller than "maxvar" and
6347 * if there are any nodes in such a cluster where the number
6348 * of remaining schedule rows that still need to be computed
6349 * is greater than "max_slack", then return the smallest current band
6350 * dimension of all these clusters. Otherwise return the original value
6351 * of "maxvar". Return -1 in case of any error.
6352 * Only clusters that are about to be merged are considered.
6353 * "c" contains information about the clusters.
6355 static int limit_maxvar_to_slack(int maxvar, int max_slack,
6356 struct isl_clustering *c)
6358 int i, j;
6360 for (i = 0; i < c->n; ++i) {
6361 int nvar;
6362 struct isl_sched_graph *scc;
6364 if (!c->scc_in_merge[i])
6365 continue;
6366 scc = &c->scc[i];
6367 nvar = scc->n_total_row - scc->band_start;
6368 if (nvar >= maxvar)
6369 continue;
6370 for (j = 0; j < scc->n; ++j) {
6371 struct isl_sched_node *node = &scc->node[j];
6372 int slack;
6374 if (node_update_vmap(node) < 0)
6375 return -1;
6376 slack = node->nvar - node->rank;
6377 if (slack > max_slack) {
6378 maxvar = nvar;
6379 break;
6384 return maxvar;
6387 /* Adjust merge_graph->maxvar based on the number of remaining schedule rows
6388 * that still need to be computed. In particular, if there is a node
6389 * in a cluster where the dimension of the current band is smaller
6390 * than merge_graph->maxvar, but the number of remaining schedule rows
6391 * is greater than that of any node in a cluster with the maximal
6392 * dimension for the current band (i.e., merge_graph->maxvar),
6393 * then adjust merge_graph->maxvar to the (smallest) current band dimension
6394 * of those clusters. Without this adjustment, the total number of
6395 * schedule dimensions would be increased, resulting in a skewed view
6396 * of the number of coincident dimensions.
6397 * "c" contains information about the clusters.
6399 * If the maximize_band_depth option is set and merge_graph->maxvar is reduced,
6400 * then there is no point in attempting any merge since it will be rejected
6401 * anyway. Set merge_graph->maxvar to zero in such cases.
6403 static isl_stat adjust_maxvar_to_slack(isl_ctx *ctx,
6404 struct isl_sched_graph *merge_graph, struct isl_clustering *c)
6406 int max_slack, maxvar;
6408 max_slack = compute_maxvar_max_slack(merge_graph->maxvar, c);
6409 if (max_slack < 0)
6410 return isl_stat_error;
6411 maxvar = limit_maxvar_to_slack(merge_graph->maxvar, max_slack, c);
6412 if (maxvar < 0)
6413 return isl_stat_error;
6415 if (maxvar < merge_graph->maxvar) {
6416 if (isl_options_get_schedule_maximize_band_depth(ctx))
6417 merge_graph->maxvar = 0;
6418 else
6419 merge_graph->maxvar = maxvar;
6422 return isl_stat_ok;
6425 /* Return the number of coincident dimensions in the current band of "graph",
6426 * where the nodes of "graph" are assumed to be scheduled by a single band.
6428 static int get_n_coincident(struct isl_sched_graph *graph)
6430 int i;
6432 for (i = graph->band_start; i < graph->n_total_row; ++i)
6433 if (!graph->node[0].coincident[i])
6434 break;
6436 return i - graph->band_start;
6439 /* Should the clusters be merged based on the cluster schedule
6440 * in the current (and only) band of "merge_graph", given that
6441 * coincidence should be maximized?
6443 * If the number of coincident schedule dimensions in the merged band
6444 * would be less than the maximal number of coincident schedule dimensions
6445 * in any of the merged clusters, then the clusters should not be merged.
6447 static isl_bool ok_to_merge_coincident(struct isl_clustering *c,
6448 struct isl_sched_graph *merge_graph)
6450 int i;
6451 int n_coincident;
6452 int max_coincident;
6454 max_coincident = 0;
6455 for (i = 0; i < c->n; ++i) {
6456 if (!c->scc_in_merge[i])
6457 continue;
6458 n_coincident = get_n_coincident(&c->scc[i]);
6459 if (n_coincident > max_coincident)
6460 max_coincident = n_coincident;
6463 n_coincident = get_n_coincident(merge_graph);
6465 return isl_bool_ok(n_coincident >= max_coincident);
6468 /* Return the transformation on "node" expressed by the current (and only)
6469 * band of "merge_graph" applied to the clusters in "c".
6471 * First find the representation of "node" in its SCC in "c" and
6472 * extract the transformation expressed by the current band.
6473 * Then extract the transformation applied by "merge_graph"
6474 * to the cluster to which this SCC belongs.
6475 * Combine the two to obtain the complete transformation on the node.
6477 * Note that the range of the first transformation is an anonymous space,
6478 * while the domain of the second is named "cluster_X". The range
6479 * of the former therefore needs to be adjusted before the two
6480 * can be combined.
6482 static __isl_give isl_map *extract_node_transformation(isl_ctx *ctx,
6483 struct isl_sched_node *node, struct isl_clustering *c,
6484 struct isl_sched_graph *merge_graph)
6486 struct isl_sched_node *scc_node, *cluster_node;
6487 int start, n;
6488 isl_id *id;
6489 isl_space *space;
6490 isl_multi_aff *ma, *ma2;
6492 scc_node = graph_find_node(ctx, &c->scc[node->scc], node->space);
6493 if (scc_node && !is_node(&c->scc[node->scc], scc_node))
6494 isl_die(ctx, isl_error_internal, "unable to find node",
6495 return NULL);
6496 start = c->scc[node->scc].band_start;
6497 n = c->scc[node->scc].n_total_row - start;
6498 ma = node_extract_partial_schedule_multi_aff(scc_node, start, n);
6499 space = cluster_space(&c->scc[node->scc], c->scc_cluster[node->scc]);
6500 cluster_node = graph_find_node(ctx, merge_graph, space);
6501 if (cluster_node && !is_node(merge_graph, cluster_node))
6502 isl_die(ctx, isl_error_internal, "unable to find cluster",
6503 space = isl_space_free(space));
6504 id = isl_space_get_tuple_id(space, isl_dim_set);
6505 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out, id);
6506 isl_space_free(space);
6507 n = merge_graph->n_total_row;
6508 ma2 = node_extract_partial_schedule_multi_aff(cluster_node, 0, n);
6509 ma = isl_multi_aff_pullback_multi_aff(ma2, ma);
6511 return isl_map_from_multi_aff(ma);
6514 /* Give a set of distances "set", are they bounded by a small constant
6515 * in direction "pos"?
6516 * In practice, check if they are bounded by 2 by checking that there
6517 * are no elements with a value greater than or equal to 3 or
6518 * smaller than or equal to -3.
6520 static isl_bool distance_is_bounded(__isl_keep isl_set *set, int pos)
6522 isl_bool bounded;
6523 isl_set *test;
6525 if (!set)
6526 return isl_bool_error;
6528 test = isl_set_copy(set);
6529 test = isl_set_lower_bound_si(test, isl_dim_set, pos, 3);
6530 bounded = isl_set_is_empty(test);
6531 isl_set_free(test);
6533 if (bounded < 0 || !bounded)
6534 return bounded;
6536 test = isl_set_copy(set);
6537 test = isl_set_upper_bound_si(test, isl_dim_set, pos, -3);
6538 bounded = isl_set_is_empty(test);
6539 isl_set_free(test);
6541 return bounded;
6544 /* Does the set "set" have a fixed (but possible parametric) value
6545 * at dimension "pos"?
6547 static isl_bool has_single_value(__isl_keep isl_set *set, int pos)
6549 isl_size n;
6550 isl_bool single;
6552 n = isl_set_dim(set, isl_dim_set);
6553 if (n < 0)
6554 return isl_bool_error;
6555 set = isl_set_copy(set);
6556 set = isl_set_project_out(set, isl_dim_set, pos + 1, n - (pos + 1));
6557 set = isl_set_project_out(set, isl_dim_set, 0, pos);
6558 single = isl_set_is_singleton(set);
6559 isl_set_free(set);
6561 return single;
6564 /* Does "map" have a fixed (but possible parametric) value
6565 * at dimension "pos" of either its domain or its range?
6567 static isl_bool has_singular_src_or_dst(__isl_keep isl_map *map, int pos)
6569 isl_set *set;
6570 isl_bool single;
6572 set = isl_map_domain(isl_map_copy(map));
6573 single = has_single_value(set, pos);
6574 isl_set_free(set);
6576 if (single < 0 || single)
6577 return single;
6579 set = isl_map_range(isl_map_copy(map));
6580 single = has_single_value(set, pos);
6581 isl_set_free(set);
6583 return single;
6586 /* Does the edge "edge" from "graph" have bounded dependence distances
6587 * in the merged graph "merge_graph" of a selection of clusters in "c"?
6589 * Extract the complete transformations of the source and destination
6590 * nodes of the edge, apply them to the edge constraints and
6591 * compute the differences. Finally, check if these differences are bounded
6592 * in each direction.
6594 * If the dimension of the band is greater than the number of
6595 * dimensions that can be expected to be optimized by the edge
6596 * (based on its weight), then also allow the differences to be unbounded
6597 * in the remaining dimensions, but only if either the source or
6598 * the destination has a fixed value in that direction.
6599 * This allows a statement that produces values that are used by
6600 * several instances of another statement to be merged with that
6601 * other statement.
6602 * However, merging such clusters will introduce an inherently
6603 * large proximity distance inside the merged cluster, meaning
6604 * that proximity distances will no longer be optimized in
6605 * subsequent merges. These merges are therefore only allowed
6606 * after all other possible merges have been tried.
6607 * The first time such a merge is encountered, the weight of the edge
6608 * is replaced by a negative weight. The second time (i.e., after
6609 * all merges over edges with a non-negative weight have been tried),
6610 * the merge is allowed.
6612 static isl_bool has_bounded_distances(isl_ctx *ctx, struct isl_sched_edge *edge,
6613 struct isl_sched_graph *graph, struct isl_clustering *c,
6614 struct isl_sched_graph *merge_graph)
6616 int i, n_slack;
6617 isl_size n;
6618 isl_bool bounded;
6619 isl_map *map, *t;
6620 isl_set *dist;
6622 map = isl_map_copy(edge->map);
6623 t = extract_node_transformation(ctx, edge->src, c, merge_graph);
6624 map = isl_map_apply_domain(map, t);
6625 t = extract_node_transformation(ctx, edge->dst, c, merge_graph);
6626 map = isl_map_apply_range(map, t);
6627 dist = isl_map_deltas(isl_map_copy(map));
6629 bounded = isl_bool_true;
6630 n = isl_set_dim(dist, isl_dim_set);
6631 if (n < 0)
6632 goto error;
6633 n_slack = n - edge->weight;
6634 if (edge->weight < 0)
6635 n_slack -= graph->max_weight + 1;
6636 for (i = 0; i < n; ++i) {
6637 isl_bool bounded_i, singular_i;
6639 bounded_i = distance_is_bounded(dist, i);
6640 if (bounded_i < 0)
6641 goto error;
6642 if (bounded_i)
6643 continue;
6644 if (edge->weight >= 0)
6645 bounded = isl_bool_false;
6646 n_slack--;
6647 if (n_slack < 0)
6648 break;
6649 singular_i = has_singular_src_or_dst(map, i);
6650 if (singular_i < 0)
6651 goto error;
6652 if (singular_i)
6653 continue;
6654 bounded = isl_bool_false;
6655 break;
6657 if (!bounded && i >= n && edge->weight >= 0)
6658 edge->weight -= graph->max_weight + 1;
6659 isl_map_free(map);
6660 isl_set_free(dist);
6662 return bounded;
6663 error:
6664 isl_map_free(map);
6665 isl_set_free(dist);
6666 return isl_bool_error;
6669 /* Should the clusters be merged based on the cluster schedule
6670 * in the current (and only) band of "merge_graph"?
6671 * "graph" is the original dependence graph, while "c" records
6672 * which SCCs are involved in the latest merge.
6674 * In particular, is there at least one proximity constraint
6675 * that is optimized by the merge?
6677 * A proximity constraint is considered to be optimized
6678 * if the dependence distances are small.
6680 static isl_bool ok_to_merge_proximity(isl_ctx *ctx,
6681 struct isl_sched_graph *graph, struct isl_clustering *c,
6682 struct isl_sched_graph *merge_graph)
6684 int i;
6686 for (i = 0; i < graph->n_edge; ++i) {
6687 struct isl_sched_edge *edge = &graph->edge[i];
6688 isl_bool bounded;
6690 if (!is_proximity(edge))
6691 continue;
6692 if (!c->scc_in_merge[edge->src->scc])
6693 continue;
6694 if (!c->scc_in_merge[edge->dst->scc])
6695 continue;
6696 if (c->scc_cluster[edge->dst->scc] ==
6697 c->scc_cluster[edge->src->scc])
6698 continue;
6699 bounded = has_bounded_distances(ctx, edge, graph, c,
6700 merge_graph);
6701 if (bounded < 0 || bounded)
6702 return bounded;
6705 return isl_bool_false;
6708 /* Should the clusters be merged based on the cluster schedule
6709 * in the current (and only) band of "merge_graph"?
6710 * "graph" is the original dependence graph, while "c" records
6711 * which SCCs are involved in the latest merge.
6713 * If the current band is empty, then the clusters should not be merged.
6715 * If the band depth should be maximized and the merge schedule
6716 * is incomplete (meaning that the dimension of some of the schedule
6717 * bands in the original schedule will be reduced), then the clusters
6718 * should not be merged.
6720 * If the schedule_maximize_coincidence option is set, then check that
6721 * the number of coincident schedule dimensions is not reduced.
6723 * Finally, only allow the merge if at least one proximity
6724 * constraint is optimized.
6726 static isl_bool ok_to_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6727 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6729 if (merge_graph->n_total_row == merge_graph->band_start)
6730 return isl_bool_false;
6732 if (isl_options_get_schedule_maximize_band_depth(ctx) &&
6733 merge_graph->n_total_row < merge_graph->maxvar)
6734 return isl_bool_false;
6736 if (isl_options_get_schedule_maximize_coincidence(ctx)) {
6737 isl_bool ok;
6739 ok = ok_to_merge_coincident(c, merge_graph);
6740 if (ok < 0 || !ok)
6741 return ok;
6744 return ok_to_merge_proximity(ctx, graph, c, merge_graph);
6747 /* Apply the schedule in "t_node" to the "n" rows starting at "first"
6748 * of the schedule in "node" and return the result.
6750 * That is, essentially compute
6752 * T * N(first:first+n-1)
6754 * taking into account the constant term and the parameter coefficients
6755 * in "t_node".
6757 static __isl_give isl_mat *node_transformation(isl_ctx *ctx,
6758 struct isl_sched_node *t_node, struct isl_sched_node *node,
6759 int first, int n)
6761 int i, j;
6762 isl_mat *t;
6763 isl_size n_row, n_col;
6764 int n_param, n_var;
6766 n_param = node->nparam;
6767 n_var = node->nvar;
6768 n_row = isl_mat_rows(t_node->sched);
6769 n_col = isl_mat_cols(node->sched);
6770 if (n_row < 0 || n_col < 0)
6771 return NULL;
6772 t = isl_mat_alloc(ctx, n_row, n_col);
6773 if (!t)
6774 return NULL;
6775 for (i = 0; i < n_row; ++i) {
6776 isl_seq_cpy(t->row[i], t_node->sched->row[i], 1 + n_param);
6777 isl_seq_clr(t->row[i] + 1 + n_param, n_var);
6778 for (j = 0; j < n; ++j)
6779 isl_seq_addmul(t->row[i],
6780 t_node->sched->row[i][1 + n_param + j],
6781 node->sched->row[first + j],
6782 1 + n_param + n_var);
6784 return t;
6787 /* Apply the cluster schedule in "t_node" to the current band
6788 * schedule of the nodes in "graph".
6790 * In particular, replace the rows starting at band_start
6791 * by the result of applying the cluster schedule in "t_node"
6792 * to the original rows.
6794 * The coincidence of the schedule is determined by the coincidence
6795 * of the cluster schedule.
6797 static isl_stat transform(isl_ctx *ctx, struct isl_sched_graph *graph,
6798 struct isl_sched_node *t_node)
6800 int i, j;
6801 isl_size n_new;
6802 int start, n;
6804 start = graph->band_start;
6805 n = graph->n_total_row - start;
6807 n_new = isl_mat_rows(t_node->sched);
6808 if (n_new < 0)
6809 return isl_stat_error;
6810 for (i = 0; i < graph->n; ++i) {
6811 struct isl_sched_node *node = &graph->node[i];
6812 isl_mat *t;
6814 t = node_transformation(ctx, t_node, node, start, n);
6815 node->sched = isl_mat_drop_rows(node->sched, start, n);
6816 node->sched = isl_mat_concat(node->sched, t);
6817 node->sched_map = isl_map_free(node->sched_map);
6818 if (!node->sched)
6819 return isl_stat_error;
6820 for (j = 0; j < n_new; ++j)
6821 node->coincident[start + j] = t_node->coincident[j];
6823 graph->n_total_row -= n;
6824 graph->n_row -= n;
6825 graph->n_total_row += n_new;
6826 graph->n_row += n_new;
6828 return isl_stat_ok;
6831 /* Merge the clusters marked for merging in "c" into a single
6832 * cluster using the cluster schedule in the current band of "merge_graph".
6833 * The representative SCC for the new cluster is the SCC with
6834 * the smallest index.
6836 * The current band schedule of each SCC in the new cluster is obtained
6837 * by applying the schedule of the corresponding original cluster
6838 * to the original band schedule.
6839 * All SCCs in the new cluster have the same number of schedule rows.
6841 static isl_stat merge(isl_ctx *ctx, struct isl_clustering *c,
6842 struct isl_sched_graph *merge_graph)
6844 int i;
6845 int cluster = -1;
6846 isl_space *space;
6848 for (i = 0; i < c->n; ++i) {
6849 struct isl_sched_node *node;
6851 if (!c->scc_in_merge[i])
6852 continue;
6853 if (cluster < 0)
6854 cluster = i;
6855 space = cluster_space(&c->scc[i], c->scc_cluster[i]);
6856 node = graph_find_node(ctx, merge_graph, space);
6857 isl_space_free(space);
6858 if (!node)
6859 return isl_stat_error;
6860 if (!is_node(merge_graph, node))
6861 isl_die(ctx, isl_error_internal,
6862 "unable to find cluster",
6863 return isl_stat_error);
6864 if (transform(ctx, &c->scc[i], node) < 0)
6865 return isl_stat_error;
6866 c->scc_cluster[i] = cluster;
6869 return isl_stat_ok;
6872 /* Try and merge the clusters of SCCs marked in c->scc_in_merge
6873 * by scheduling the current cluster bands with respect to each other.
6875 * Construct a dependence graph with a space for each cluster and
6876 * with the coordinates of each space corresponding to the schedule
6877 * dimensions of the current band of that cluster.
6878 * Construct a cluster schedule in this cluster dependence graph and
6879 * apply it to the current cluster bands if it is applicable
6880 * according to ok_to_merge.
6882 * If the number of remaining schedule dimensions in a cluster
6883 * with a non-maximal current schedule dimension is greater than
6884 * the number of remaining schedule dimensions in clusters
6885 * with a maximal current schedule dimension, then restrict
6886 * the number of rows to be computed in the cluster schedule
6887 * to the minimal such non-maximal current schedule dimension.
6888 * Do this by adjusting merge_graph.maxvar.
6890 * Return isl_bool_true if the clusters have effectively been merged
6891 * into a single cluster.
6893 * Note that since the standard scheduling algorithm minimizes the maximal
6894 * distance over proximity constraints, the proximity constraints between
6895 * the merged clusters may not be optimized any further than what is
6896 * sufficient to bring the distances within the limits of the internal
6897 * proximity constraints inside the individual clusters.
6898 * It may therefore make sense to perform an additional translation step
6899 * to bring the clusters closer to each other, while maintaining
6900 * the linear part of the merging schedule found using the standard
6901 * scheduling algorithm.
6903 static isl_bool try_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6904 struct isl_clustering *c)
6906 struct isl_sched_graph merge_graph = { 0 };
6907 isl_bool merged;
6909 if (init_merge_graph(ctx, graph, c, &merge_graph) < 0)
6910 goto error;
6912 if (compute_maxvar(&merge_graph) < 0)
6913 goto error;
6914 if (adjust_maxvar_to_slack(ctx, &merge_graph,c) < 0)
6915 goto error;
6916 if (compute_schedule_wcc_band(ctx, &merge_graph) < 0)
6917 goto error;
6918 merged = ok_to_merge(ctx, graph, c, &merge_graph);
6919 if (merged && merge(ctx, c, &merge_graph) < 0)
6920 goto error;
6922 graph_free(ctx, &merge_graph);
6923 return merged;
6924 error:
6925 graph_free(ctx, &merge_graph);
6926 return isl_bool_error;
6929 /* Is there any edge marked "no_merge" between two SCCs that are
6930 * about to be merged (i.e., that are set in "scc_in_merge")?
6931 * "merge_edge" is the proximity edge along which the clusters of SCCs
6932 * are going to be merged.
6934 * If there is any edge between two SCCs with a negative weight,
6935 * while the weight of "merge_edge" is non-negative, then this
6936 * means that the edge was postponed. "merge_edge" should then
6937 * also be postponed since merging along the edge with negative weight should
6938 * be postponed until all edges with non-negative weight have been tried.
6939 * Replace the weight of "merge_edge" by a negative weight as well and
6940 * tell the caller not to attempt a merge.
6942 static int any_no_merge(struct isl_sched_graph *graph, int *scc_in_merge,
6943 struct isl_sched_edge *merge_edge)
6945 int i;
6947 for (i = 0; i < graph->n_edge; ++i) {
6948 struct isl_sched_edge *edge = &graph->edge[i];
6950 if (!scc_in_merge[edge->src->scc])
6951 continue;
6952 if (!scc_in_merge[edge->dst->scc])
6953 continue;
6954 if (edge->no_merge)
6955 return 1;
6956 if (merge_edge->weight >= 0 && edge->weight < 0) {
6957 merge_edge->weight -= graph->max_weight + 1;
6958 return 1;
6962 return 0;
6965 /* Merge the two clusters in "c" connected by the edge in "graph"
6966 * with index "edge" into a single cluster.
6967 * If it turns out to be impossible to merge these two clusters,
6968 * then mark the edge as "no_merge" such that it will not be
6969 * considered again.
6971 * First mark all SCCs that need to be merged. This includes the SCCs
6972 * in the two clusters, but it may also include the SCCs
6973 * of intermediate clusters.
6974 * If there is already a no_merge edge between any pair of such SCCs,
6975 * then simply mark the current edge as no_merge as well.
6976 * Likewise, if any of those edges was postponed by has_bounded_distances,
6977 * then postpone the current edge as well.
6978 * Otherwise, try and merge the clusters and mark "edge" as "no_merge"
6979 * if the clusters did not end up getting merged, unless the non-merge
6980 * is due to the fact that the edge was postponed. This postponement
6981 * can be recognized by a change in weight (from non-negative to negative).
6983 static isl_stat merge_clusters_along_edge(isl_ctx *ctx,
6984 struct isl_sched_graph *graph, int edge, struct isl_clustering *c)
6986 isl_bool merged;
6987 int edge_weight = graph->edge[edge].weight;
6989 if (mark_merge_sccs(ctx, graph, edge, c) < 0)
6990 return isl_stat_error;
6992 if (any_no_merge(graph, c->scc_in_merge, &graph->edge[edge]))
6993 merged = isl_bool_false;
6994 else
6995 merged = try_merge(ctx, graph, c);
6996 if (merged < 0)
6997 return isl_stat_error;
6998 if (!merged && edge_weight == graph->edge[edge].weight)
6999 graph->edge[edge].no_merge = 1;
7001 return isl_stat_ok;
7004 /* Does "node" belong to the cluster identified by "cluster"?
7006 static int node_cluster_exactly(struct isl_sched_node *node, int cluster)
7008 return node->cluster == cluster;
7011 /* Does "edge" connect two nodes belonging to the cluster
7012 * identified by "cluster"?
7014 static int edge_cluster_exactly(struct isl_sched_edge *edge, int cluster)
7016 return edge->src->cluster == cluster && edge->dst->cluster == cluster;
7019 /* Swap the schedule of "node1" and "node2".
7020 * Both nodes have been derived from the same node in a common parent graph.
7021 * Since the "coincident" field is shared with that node
7022 * in the parent graph, there is no need to also swap this field.
7024 static void swap_sched(struct isl_sched_node *node1,
7025 struct isl_sched_node *node2)
7027 isl_mat *sched;
7028 isl_map *sched_map;
7030 sched = node1->sched;
7031 node1->sched = node2->sched;
7032 node2->sched = sched;
7034 sched_map = node1->sched_map;
7035 node1->sched_map = node2->sched_map;
7036 node2->sched_map = sched_map;
7039 /* Copy the current band schedule from the SCCs that form the cluster
7040 * with index "pos" to the actual cluster at position "pos".
7041 * By construction, the index of the first SCC that belongs to the cluster
7042 * is also "pos".
7044 * The order of the nodes inside both the SCCs and the cluster
7045 * is assumed to be same as the order in the original "graph".
7047 * Since the SCC graphs will no longer be used after this function,
7048 * the schedules are actually swapped rather than copied.
7050 static isl_stat copy_partial(struct isl_sched_graph *graph,
7051 struct isl_clustering *c, int pos)
7053 int i, j;
7055 c->cluster[pos].n_total_row = c->scc[pos].n_total_row;
7056 c->cluster[pos].n_row = c->scc[pos].n_row;
7057 c->cluster[pos].maxvar = c->scc[pos].maxvar;
7058 j = 0;
7059 for (i = 0; i < graph->n; ++i) {
7060 int k;
7061 int s;
7063 if (graph->node[i].cluster != pos)
7064 continue;
7065 s = graph->node[i].scc;
7066 k = c->scc_node[s]++;
7067 swap_sched(&c->cluster[pos].node[j], &c->scc[s].node[k]);
7068 if (c->scc[s].maxvar > c->cluster[pos].maxvar)
7069 c->cluster[pos].maxvar = c->scc[s].maxvar;
7070 ++j;
7073 return isl_stat_ok;
7076 /* Is there a (conditional) validity dependence from node[j] to node[i],
7077 * forcing node[i] to follow node[j] or do the nodes belong to the same
7078 * cluster?
7080 static isl_bool node_follows_strong_or_same_cluster(int i, int j, void *user)
7082 struct isl_sched_graph *graph = user;
7084 if (graph->node[i].cluster == graph->node[j].cluster)
7085 return isl_bool_true;
7086 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
7089 /* Extract the merged clusters of SCCs in "graph", sort them, and
7090 * store them in c->clusters. Update c->scc_cluster accordingly.
7092 * First keep track of the cluster containing the SCC to which a node
7093 * belongs in the node itself.
7094 * Then extract the clusters into c->clusters, copying the current
7095 * band schedule from the SCCs that belong to the cluster.
7096 * Do this only once per cluster.
7098 * Finally, topologically sort the clusters and update c->scc_cluster
7099 * to match the new scc numbering. While the SCCs were originally
7100 * sorted already, some SCCs that depend on some other SCCs may
7101 * have been merged with SCCs that appear before these other SCCs.
7102 * A reordering may therefore be required.
7104 static isl_stat extract_clusters(isl_ctx *ctx, struct isl_sched_graph *graph,
7105 struct isl_clustering *c)
7107 int i;
7109 for (i = 0; i < graph->n; ++i)
7110 graph->node[i].cluster = c->scc_cluster[graph->node[i].scc];
7112 for (i = 0; i < graph->scc; ++i) {
7113 if (c->scc_cluster[i] != i)
7114 continue;
7115 if (extract_sub_graph(ctx, graph, &node_cluster_exactly,
7116 &edge_cluster_exactly, i, &c->cluster[i]) < 0)
7117 return isl_stat_error;
7118 c->cluster[i].src_scc = -1;
7119 c->cluster[i].dst_scc = -1;
7120 if (copy_partial(graph, c, i) < 0)
7121 return isl_stat_error;
7124 if (detect_ccs(ctx, graph, &node_follows_strong_or_same_cluster) < 0)
7125 return isl_stat_error;
7126 for (i = 0; i < graph->n; ++i)
7127 c->scc_cluster[graph->node[i].scc] = graph->node[i].cluster;
7129 return isl_stat_ok;
7132 /* Compute weights on the proximity edges of "graph" that can
7133 * be used by find_proximity to find the most appropriate
7134 * proximity edge to use to merge two clusters in "c".
7135 * The weights are also used by has_bounded_distances to determine
7136 * whether the merge should be allowed.
7137 * Store the maximum of the computed weights in graph->max_weight.
7139 * The computed weight is a measure for the number of remaining schedule
7140 * dimensions that can still be completely aligned.
7141 * In particular, compute the number of equalities between
7142 * input dimensions and output dimensions in the proximity constraints.
7143 * The directions that are already handled by outer schedule bands
7144 * are projected out prior to determining this number.
7146 * Edges that will never be considered by find_proximity are ignored.
7148 static isl_stat compute_weights(struct isl_sched_graph *graph,
7149 struct isl_clustering *c)
7151 int i;
7153 graph->max_weight = 0;
7155 for (i = 0; i < graph->n_edge; ++i) {
7156 struct isl_sched_edge *edge = &graph->edge[i];
7157 struct isl_sched_node *src = edge->src;
7158 struct isl_sched_node *dst = edge->dst;
7159 isl_basic_map *hull;
7160 isl_bool prox;
7161 isl_size n_in, n_out;
7163 prox = is_non_empty_proximity(edge);
7164 if (prox < 0)
7165 return isl_stat_error;
7166 if (!prox)
7167 continue;
7168 if (bad_cluster(&c->scc[edge->src->scc]) ||
7169 bad_cluster(&c->scc[edge->dst->scc]))
7170 continue;
7171 if (c->scc_cluster[edge->dst->scc] ==
7172 c->scc_cluster[edge->src->scc])
7173 continue;
7175 hull = isl_map_affine_hull(isl_map_copy(edge->map));
7176 hull = isl_basic_map_transform_dims(hull, isl_dim_in, 0,
7177 isl_mat_copy(src->vmap));
7178 hull = isl_basic_map_transform_dims(hull, isl_dim_out, 0,
7179 isl_mat_copy(dst->vmap));
7180 hull = isl_basic_map_project_out(hull,
7181 isl_dim_in, 0, src->rank);
7182 hull = isl_basic_map_project_out(hull,
7183 isl_dim_out, 0, dst->rank);
7184 hull = isl_basic_map_remove_divs(hull);
7185 n_in = isl_basic_map_dim(hull, isl_dim_in);
7186 n_out = isl_basic_map_dim(hull, isl_dim_out);
7187 if (n_in < 0 || n_out < 0)
7188 hull = isl_basic_map_free(hull);
7189 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
7190 isl_dim_in, 0, n_in);
7191 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
7192 isl_dim_out, 0, n_out);
7193 if (!hull)
7194 return isl_stat_error;
7195 edge->weight = isl_basic_map_n_equality(hull);
7196 isl_basic_map_free(hull);
7198 if (edge->weight > graph->max_weight)
7199 graph->max_weight = edge->weight;
7202 return isl_stat_ok;
7205 /* Call compute_schedule_finish_band on each of the clusters in "c"
7206 * in their topological order. This order is determined by the scc
7207 * fields of the nodes in "graph".
7208 * Combine the results in a sequence expressing the topological order.
7210 * If there is only one cluster left, then there is no need to introduce
7211 * a sequence node. Also, in this case, the cluster necessarily contains
7212 * the SCC at position 0 in the original graph and is therefore also
7213 * stored in the first cluster of "c".
7215 static __isl_give isl_schedule_node *finish_bands_clustering(
7216 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
7217 struct isl_clustering *c)
7219 int i;
7220 isl_ctx *ctx;
7221 isl_union_set_list *filters;
7223 if (graph->scc == 1)
7224 return compute_schedule_finish_band(node, &c->cluster[0], 0);
7226 ctx = isl_schedule_node_get_ctx(node);
7228 filters = extract_sccs(ctx, graph);
7229 node = isl_schedule_node_insert_sequence(node, filters);
7231 for (i = 0; i < graph->scc; ++i) {
7232 int j = c->scc_cluster[i];
7233 node = isl_schedule_node_child(node, i);
7234 node = isl_schedule_node_child(node, 0);
7235 node = compute_schedule_finish_band(node, &c->cluster[j], 0);
7236 node = isl_schedule_node_parent(node);
7237 node = isl_schedule_node_parent(node);
7240 return node;
7243 /* Compute a schedule for a connected dependence graph by first considering
7244 * each strongly connected component (SCC) in the graph separately and then
7245 * incrementally combining them into clusters.
7246 * Return the updated schedule node.
7248 * Initially, each cluster consists of a single SCC, each with its
7249 * own band schedule. The algorithm then tries to merge pairs
7250 * of clusters along a proximity edge until no more suitable
7251 * proximity edges can be found. During this merging, the schedule
7252 * is maintained in the individual SCCs.
7253 * After the merging is completed, the full resulting clusters
7254 * are extracted and in finish_bands_clustering,
7255 * compute_schedule_finish_band is called on each of them to integrate
7256 * the band into "node" and to continue the computation.
7258 * compute_weights initializes the weights that are used by find_proximity.
7260 static __isl_give isl_schedule_node *compute_schedule_wcc_clustering(
7261 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
7263 isl_ctx *ctx;
7264 struct isl_clustering c;
7265 int i;
7267 ctx = isl_schedule_node_get_ctx(node);
7269 if (clustering_init(ctx, &c, graph) < 0)
7270 goto error;
7272 if (compute_weights(graph, &c) < 0)
7273 goto error;
7275 for (;;) {
7276 i = find_proximity(graph, &c);
7277 if (i < 0)
7278 goto error;
7279 if (i >= graph->n_edge)
7280 break;
7281 if (merge_clusters_along_edge(ctx, graph, i, &c) < 0)
7282 goto error;
7285 if (extract_clusters(ctx, graph, &c) < 0)
7286 goto error;
7288 node = finish_bands_clustering(node, graph, &c);
7290 clustering_free(ctx, &c);
7291 return node;
7292 error:
7293 clustering_free(ctx, &c);
7294 return isl_schedule_node_free(node);
7297 /* Compute a schedule for a connected dependence graph and return
7298 * the updated schedule node.
7300 * If Feautrier's algorithm is selected, we first recursively try to satisfy
7301 * as many validity dependences as possible. When all validity dependences
7302 * are satisfied we extend the schedule to a full-dimensional schedule.
7304 * Call compute_schedule_wcc_whole or compute_schedule_wcc_clustering
7305 * depending on whether the user has selected the option to try and
7306 * compute a schedule for the entire (weakly connected) component first.
7307 * If there is only a single strongly connected component (SCC), then
7308 * there is no point in trying to combine SCCs
7309 * in compute_schedule_wcc_clustering, so compute_schedule_wcc_whole
7310 * is called instead.
7312 static __isl_give isl_schedule_node *compute_schedule_wcc(
7313 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
7315 isl_ctx *ctx;
7317 if (!node)
7318 return NULL;
7320 ctx = isl_schedule_node_get_ctx(node);
7321 if (detect_sccs(ctx, graph) < 0)
7322 return isl_schedule_node_free(node);
7324 if (compute_maxvar(graph) < 0)
7325 return isl_schedule_node_free(node);
7327 if (need_feautrier_step(ctx, graph))
7328 return compute_schedule_wcc_feautrier(node, graph);
7330 if (graph->scc <= 1 || isl_options_get_schedule_whole_component(ctx))
7331 return compute_schedule_wcc_whole(node, graph);
7332 else
7333 return compute_schedule_wcc_clustering(node, graph);
7336 /* Compute a schedule for each group of nodes identified by node->scc
7337 * separately and then combine them in a sequence node (or as set node
7338 * if graph->weak is set) inserted at position "node" of the schedule tree.
7339 * Return the updated schedule node.
7341 * If "wcc" is set then each of the groups belongs to a single
7342 * weakly connected component in the dependence graph so that
7343 * there is no need for compute_sub_schedule to look for weakly
7344 * connected components.
7346 * If a set node would be introduced and if the number of components
7347 * is equal to the number of nodes, then check if the schedule
7348 * is already complete. If so, a redundant set node would be introduced
7349 * (without any further descendants) stating that the statements
7350 * can be executed in arbitrary order, which is also expressed
7351 * by the absence of any node. Refrain from inserting any nodes
7352 * in this case and simply return.
7354 static __isl_give isl_schedule_node *compute_component_schedule(
7355 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
7356 int wcc)
7358 int component;
7359 isl_ctx *ctx;
7360 isl_union_set_list *filters;
7362 if (!node)
7363 return NULL;
7365 if (graph->weak && graph->scc == graph->n) {
7366 if (compute_maxvar(graph) < 0)
7367 return isl_schedule_node_free(node);
7368 if (graph->n_row >= graph->maxvar)
7369 return node;
7372 ctx = isl_schedule_node_get_ctx(node);
7373 filters = extract_sccs(ctx, graph);
7374 if (graph->weak)
7375 node = isl_schedule_node_insert_set(node, filters);
7376 else
7377 node = isl_schedule_node_insert_sequence(node, filters);
7379 for (component = 0; component < graph->scc; ++component) {
7380 node = isl_schedule_node_child(node, component);
7381 node = isl_schedule_node_child(node, 0);
7382 node = compute_sub_schedule(node, ctx, graph,
7383 &node_scc_exactly,
7384 &edge_scc_exactly, component, wcc);
7385 node = isl_schedule_node_parent(node);
7386 node = isl_schedule_node_parent(node);
7389 return node;
7392 /* Compute a schedule for the given dependence graph and insert it at "node".
7393 * Return the updated schedule node.
7395 * We first check if the graph is connected (through validity and conditional
7396 * validity dependences) and, if not, compute a schedule
7397 * for each component separately.
7398 * If the schedule_serialize_sccs option is set, then we check for strongly
7399 * connected components instead and compute a separate schedule for
7400 * each such strongly connected component.
7402 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
7403 struct isl_sched_graph *graph)
7405 isl_ctx *ctx;
7407 if (!node)
7408 return NULL;
7410 ctx = isl_schedule_node_get_ctx(node);
7411 if (isl_options_get_schedule_serialize_sccs(ctx)) {
7412 if (detect_sccs(ctx, graph) < 0)
7413 return isl_schedule_node_free(node);
7414 } else {
7415 if (detect_wccs(ctx, graph) < 0)
7416 return isl_schedule_node_free(node);
7419 if (graph->scc > 1)
7420 return compute_component_schedule(node, graph, 1);
7422 return compute_schedule_wcc(node, graph);
7425 /* Compute a schedule on sc->domain that respects the given schedule
7426 * constraints.
7428 * In particular, the schedule respects all the validity dependences.
7429 * If the default isl scheduling algorithm is used, it tries to minimize
7430 * the dependence distances over the proximity dependences.
7431 * If Feautrier's scheduling algorithm is used, the proximity dependence
7432 * distances are only minimized during the extension to a full-dimensional
7433 * schedule.
7435 * If there are any condition and conditional validity dependences,
7436 * then the conditional validity dependences may be violated inside
7437 * a tilable band, provided they have no adjacent non-local
7438 * condition dependences.
7440 __isl_give isl_schedule *isl_schedule_constraints_compute_schedule(
7441 __isl_take isl_schedule_constraints *sc)
7443 isl_ctx *ctx = isl_schedule_constraints_get_ctx(sc);
7444 struct isl_sched_graph graph = { 0 };
7445 isl_schedule *sched;
7446 isl_schedule_node *node;
7447 isl_union_set *domain;
7448 isl_size n;
7450 sc = isl_schedule_constraints_align_params(sc);
7452 domain = isl_schedule_constraints_get_domain(sc);
7453 n = isl_union_set_n_set(domain);
7454 if (n == 0) {
7455 isl_schedule_constraints_free(sc);
7456 return isl_schedule_from_domain(domain);
7459 if (n < 0 || graph_init(&graph, sc) < 0)
7460 domain = isl_union_set_free(domain);
7462 node = isl_schedule_node_from_domain(domain);
7463 node = isl_schedule_node_child(node, 0);
7464 if (graph.n > 0)
7465 node = compute_schedule(node, &graph);
7466 sched = isl_schedule_node_get_schedule(node);
7467 isl_schedule_node_free(node);
7469 graph_free(ctx, &graph);
7470 isl_schedule_constraints_free(sc);
7472 return sched;
7475 /* Compute a schedule for the given union of domains that respects
7476 * all the validity dependences and minimizes
7477 * the dependence distances over the proximity dependences.
7479 * This function is kept for backward compatibility.
7481 __isl_give isl_schedule *isl_union_set_compute_schedule(
7482 __isl_take isl_union_set *domain,
7483 __isl_take isl_union_map *validity,
7484 __isl_take isl_union_map *proximity)
7486 isl_schedule_constraints *sc;
7488 sc = isl_schedule_constraints_on_domain(domain);
7489 sc = isl_schedule_constraints_set_validity(sc, validity);
7490 sc = isl_schedule_constraints_set_proximity(sc, proximity);
7492 return isl_schedule_constraints_compute_schedule(sc);