isl_scheduler.c: copy_nodes: return isl_stat
[isl.git] / isl_scheduler.c
blobbf3dac4718228e78883c7f6f2027784ecbc2bfbb
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/constraint.h>
24 #include <isl/schedule.h>
25 #include <isl_schedule_constraints.h>
26 #include <isl/schedule_node.h>
27 #include <isl_mat_private.h>
28 #include <isl_vec_private.h>
29 #include <isl/set.h>
30 #include <isl_union_set_private.h>
31 #include <isl_seq.h>
32 #include <isl_tab.h>
33 #include <isl_dim_map.h>
34 #include <isl/map_to_basic_set.h>
35 #include <isl_sort.h>
36 #include <isl_options_private.h>
37 #include <isl_tarjan.h>
38 #include <isl_morph.h>
39 #include <isl/ilp.h>
40 #include <isl_val_private.h>
43 * The scheduling algorithm implemented in this file was inspired by
44 * Bondhugula et al., "Automatic Transformations for Communication-Minimized
45 * Parallelization and Locality Optimization in the Polyhedral Model".
47 * For a detailed description of the variant implemented in isl,
48 * see Verdoolaege and Janssens, "Scheduling for PPCG" (2017).
52 /* Internal information about a node that is used during the construction
53 * of a schedule.
54 * space represents the original space in which the domain lives;
55 * that is, the space is not affected by compression
56 * sched is a matrix representation of the schedule being constructed
57 * for this node; if compressed is set, then this schedule is
58 * defined over the compressed domain space
59 * sched_map is an isl_map representation of the same (partial) schedule
60 * sched_map may be NULL; if compressed is set, then this map
61 * is defined over the uncompressed domain space
62 * rank is the number of linearly independent rows in the linear part
63 * of sched
64 * the rows of "vmap" represent a change of basis for the node
65 * variables; the first rank rows span the linear part of
66 * the schedule rows; the remaining rows are linearly independent
67 * the rows of "indep" represent linear combinations of the schedule
68 * coefficients that are non-zero when the schedule coefficients are
69 * linearly independent of previously computed schedule rows.
70 * start is the first variable in the LP problem in the sequences that
71 * represents the schedule coefficients of this node
72 * nvar is the dimension of the (compressed) domain
73 * nparam is the number of parameters or 0 if we are not constructing
74 * a parametric schedule
76 * If compressed is set, then hull represents the constraints
77 * that were used to derive the compression, while compress and
78 * decompress map the original space to the compressed space and
79 * vice versa.
81 * scc is the index of SCC (or WCC) this node belongs to
83 * "cluster" is only used inside extract_clusters and identifies
84 * the cluster of SCCs that the node belongs to.
86 * coincident contains a boolean for each of the rows of the schedule,
87 * indicating whether the corresponding scheduling dimension satisfies
88 * the coincidence constraints in the sense that the corresponding
89 * dependence distances are zero.
91 * If the schedule_treat_coalescing option is set, then
92 * "sizes" contains the sizes of the (compressed) instance set
93 * in each direction. If there is no fixed size in a given direction,
94 * then the corresponding size value is set to infinity.
95 * If the schedule_treat_coalescing option or the schedule_max_coefficient
96 * option is set, then "max" contains the maximal values for
97 * schedule coefficients of the (compressed) variables. If no bound
98 * needs to be imposed on a particular variable, then the corresponding
99 * value is negative.
100 * If not NULL, then "bounds" contains a non-parametric set
101 * in the compressed space that is bounded by the size in each direction.
103 struct isl_sched_node {
104 isl_space *space;
105 int compressed;
106 isl_set *hull;
107 isl_multi_aff *compress;
108 isl_multi_aff *decompress;
109 isl_mat *sched;
110 isl_map *sched_map;
111 int rank;
112 isl_mat *indep;
113 isl_mat *vmap;
114 int start;
115 int nvar;
116 int nparam;
118 int scc;
119 int cluster;
121 int *coincident;
123 isl_multi_val *sizes;
124 isl_basic_set *bounds;
125 isl_vec *max;
128 static int node_has_tuples(const void *entry, const void *val)
130 struct isl_sched_node *node = (struct isl_sched_node *)entry;
131 isl_space *space = (isl_space *) val;
133 return isl_space_has_equal_tuples(node->space, space);
136 static int node_scc_exactly(struct isl_sched_node *node, int scc)
138 return node->scc == scc;
141 static int node_scc_at_most(struct isl_sched_node *node, int scc)
143 return node->scc <= scc;
146 static int node_scc_at_least(struct isl_sched_node *node, int scc)
148 return node->scc >= scc;
151 /* An edge in the dependence graph. An edge may be used to
152 * ensure validity of the generated schedule, to minimize the dependence
153 * distance or both
155 * map is the dependence relation, with i -> j in the map if j depends on i
156 * tagged_condition and tagged_validity contain the union of all tagged
157 * condition or conditional validity dependence relations that
158 * specialize the dependence relation "map"; that is,
159 * if (i -> a) -> (j -> b) is an element of "tagged_condition"
160 * or "tagged_validity", then i -> j is an element of "map".
161 * If these fields are NULL, then they represent the empty relation.
162 * src is the source node
163 * dst is the sink node
165 * types is a bit vector containing the types of this edge.
166 * validity is set if the edge is used to ensure correctness
167 * coincidence is used to enforce zero dependence distances
168 * proximity is set if the edge is used to minimize dependence distances
169 * condition is set if the edge represents a condition
170 * for a conditional validity schedule constraint
171 * local can only be set for condition edges and indicates that
172 * the dependence distance over the edge should be zero
173 * conditional_validity is set if the edge is used to conditionally
174 * ensure correctness
176 * For validity edges, start and end mark the sequence of inequality
177 * constraints in the LP problem that encode the validity constraint
178 * corresponding to this edge.
180 * During clustering, an edge may be marked "no_merge" if it should
181 * not be used to merge clusters.
182 * The weight is also only used during clustering and it is
183 * an indication of how many schedule dimensions on either side
184 * of the schedule constraints can be aligned.
185 * If the weight is negative, then this means that this edge was postponed
186 * by has_bounded_distances or any_no_merge. The original weight can
187 * be retrieved by adding 1 + graph->max_weight, with "graph"
188 * the graph containing this edge.
190 struct isl_sched_edge {
191 isl_map *map;
192 isl_union_map *tagged_condition;
193 isl_union_map *tagged_validity;
195 struct isl_sched_node *src;
196 struct isl_sched_node *dst;
198 unsigned types;
200 int start;
201 int end;
203 int no_merge;
204 int weight;
207 /* Is "edge" marked as being of type "type"?
209 static int is_type(struct isl_sched_edge *edge, enum isl_edge_type type)
211 return ISL_FL_ISSET(edge->types, 1 << type);
214 /* Mark "edge" as being of type "type".
216 static void set_type(struct isl_sched_edge *edge, enum isl_edge_type type)
218 ISL_FL_SET(edge->types, 1 << type);
221 /* No longer mark "edge" as being of type "type"?
223 static void clear_type(struct isl_sched_edge *edge, enum isl_edge_type type)
225 ISL_FL_CLR(edge->types, 1 << type);
228 /* Is "edge" marked as a validity edge?
230 static int is_validity(struct isl_sched_edge *edge)
232 return is_type(edge, isl_edge_validity);
235 /* Mark "edge" as a validity edge.
237 static void set_validity(struct isl_sched_edge *edge)
239 set_type(edge, isl_edge_validity);
242 /* Is "edge" marked as a proximity edge?
244 static int is_proximity(struct isl_sched_edge *edge)
246 return is_type(edge, isl_edge_proximity);
249 /* Is "edge" marked as a local edge?
251 static int is_local(struct isl_sched_edge *edge)
253 return is_type(edge, isl_edge_local);
256 /* Mark "edge" as a local edge.
258 static void set_local(struct isl_sched_edge *edge)
260 set_type(edge, isl_edge_local);
263 /* No longer mark "edge" as a local edge.
265 static void clear_local(struct isl_sched_edge *edge)
267 clear_type(edge, isl_edge_local);
270 /* Is "edge" marked as a coincidence edge?
272 static int is_coincidence(struct isl_sched_edge *edge)
274 return is_type(edge, isl_edge_coincidence);
277 /* Is "edge" marked as a condition edge?
279 static int is_condition(struct isl_sched_edge *edge)
281 return is_type(edge, isl_edge_condition);
284 /* Is "edge" marked as a conditional validity edge?
286 static int is_conditional_validity(struct isl_sched_edge *edge)
288 return is_type(edge, isl_edge_conditional_validity);
291 /* Is "edge" of a type that can appear multiple times between
292 * the same pair of nodes?
294 * Condition edges and conditional validity edges may have tagged
295 * dependence relations, in which case an edge is added for each
296 * pair of tags.
298 static int is_multi_edge_type(struct isl_sched_edge *edge)
300 return is_condition(edge) || is_conditional_validity(edge);
303 /* Internal information about the dependence graph used during
304 * the construction of the schedule.
306 * intra_hmap is a cache, mapping dependence relations to their dual,
307 * for dependences from a node to itself, possibly without
308 * coefficients for the parameters
309 * intra_hmap_param is a cache, mapping dependence relations to their dual,
310 * for dependences from a node to itself, including coefficients
311 * for the parameters
312 * inter_hmap is a cache, mapping dependence relations to their dual,
313 * for dependences between distinct nodes
314 * if compression is involved then the key for these maps
315 * is the original, uncompressed dependence relation, while
316 * the value is the dual of the compressed dependence relation.
318 * n is the number of nodes
319 * node is the list of nodes
320 * maxvar is the maximal number of variables over all nodes
321 * max_row is the allocated number of rows in the schedule
322 * n_row is the current (maximal) number of linearly independent
323 * rows in the node schedules
324 * n_total_row is the current number of rows in the node schedules
325 * band_start is the starting row in the node schedules of the current band
326 * root is set to the the original dependence graph from which this graph
327 * is derived through splitting. If this graph is not the result of
328 * splitting, then the root field points to the graph itself.
330 * sorted contains a list of node indices sorted according to the
331 * SCC to which a node belongs
333 * n_edge is the number of edges
334 * edge is the list of edges
335 * max_edge contains the maximal number of edges of each type;
336 * in particular, it contains the number of edges in the inital graph.
337 * edge_table contains pointers into the edge array, hashed on the source
338 * and sink spaces; there is one such table for each type;
339 * a given edge may be referenced from more than one table
340 * if the corresponding relation appears in more than one of the
341 * sets of dependences; however, for each type there is only
342 * a single edge between a given pair of source and sink space
343 * in the entire graph
345 * node_table contains pointers into the node array, hashed on the space tuples
347 * region contains a list of variable sequences that should be non-trivial
349 * lp contains the (I)LP problem used to obtain new schedule rows
351 * src_scc and dst_scc are the source and sink SCCs of an edge with
352 * conflicting constraints
354 * scc represents the number of components
355 * weak is set if the components are weakly connected
357 * max_weight is used during clustering and represents the maximal
358 * weight of the relevant proximity edges.
360 struct isl_sched_graph {
361 isl_map_to_basic_set *intra_hmap;
362 isl_map_to_basic_set *intra_hmap_param;
363 isl_map_to_basic_set *inter_hmap;
365 struct isl_sched_node *node;
366 int n;
367 int maxvar;
368 int max_row;
369 int n_row;
371 int *sorted;
373 int n_total_row;
374 int band_start;
376 struct isl_sched_graph *root;
378 struct isl_sched_edge *edge;
379 int n_edge;
380 int max_edge[isl_edge_last + 1];
381 struct isl_hash_table *edge_table[isl_edge_last + 1];
383 struct isl_hash_table *node_table;
384 struct isl_trivial_region *region;
386 isl_basic_set *lp;
388 int src_scc;
389 int dst_scc;
391 int scc;
392 int weak;
394 int max_weight;
397 /* Initialize node_table based on the list of nodes.
399 static int graph_init_table(isl_ctx *ctx, struct isl_sched_graph *graph)
401 int i;
403 graph->node_table = isl_hash_table_alloc(ctx, graph->n);
404 if (!graph->node_table)
405 return -1;
407 for (i = 0; i < graph->n; ++i) {
408 struct isl_hash_table_entry *entry;
409 uint32_t hash;
411 hash = isl_space_get_tuple_hash(graph->node[i].space);
412 entry = isl_hash_table_find(ctx, graph->node_table, hash,
413 &node_has_tuples,
414 graph->node[i].space, 1);
415 if (!entry)
416 return -1;
417 entry->data = &graph->node[i];
420 return 0;
423 /* Return a pointer to the node that lives within the given space,
424 * or NULL if there is no such node.
426 static struct isl_sched_node *graph_find_node(isl_ctx *ctx,
427 struct isl_sched_graph *graph, __isl_keep isl_space *space)
429 struct isl_hash_table_entry *entry;
430 uint32_t hash;
432 hash = isl_space_get_tuple_hash(space);
433 entry = isl_hash_table_find(ctx, graph->node_table, hash,
434 &node_has_tuples, space, 0);
436 return entry ? entry->data : NULL;
439 /* Is "node" a node in "graph"?
441 static int is_node(struct isl_sched_graph *graph,
442 struct isl_sched_node *node)
444 return node && node >= &graph->node[0] && node < &graph->node[graph->n];
447 static int edge_has_src_and_dst(const void *entry, const void *val)
449 const struct isl_sched_edge *edge = entry;
450 const struct isl_sched_edge *temp = val;
452 return edge->src == temp->src && edge->dst == temp->dst;
455 /* Add the given edge to graph->edge_table[type].
457 static isl_stat graph_edge_table_add(isl_ctx *ctx,
458 struct isl_sched_graph *graph, enum isl_edge_type type,
459 struct isl_sched_edge *edge)
461 struct isl_hash_table_entry *entry;
462 uint32_t hash;
464 hash = isl_hash_init();
465 hash = isl_hash_builtin(hash, edge->src);
466 hash = isl_hash_builtin(hash, edge->dst);
467 entry = isl_hash_table_find(ctx, graph->edge_table[type], hash,
468 &edge_has_src_and_dst, edge, 1);
469 if (!entry)
470 return isl_stat_error;
471 entry->data = edge;
473 return isl_stat_ok;
476 /* Add "edge" to all relevant edge tables.
477 * That is, for every type of the edge, add it to the corresponding table.
479 static isl_stat graph_edge_tables_add(isl_ctx *ctx,
480 struct isl_sched_graph *graph, struct isl_sched_edge *edge)
482 enum isl_edge_type t;
484 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
485 if (!is_type(edge, t))
486 continue;
487 if (graph_edge_table_add(ctx, graph, t, edge) < 0)
488 return isl_stat_error;
491 return isl_stat_ok;
494 /* Allocate the edge_tables based on the maximal number of edges of
495 * each type.
497 static int graph_init_edge_tables(isl_ctx *ctx, struct isl_sched_graph *graph)
499 int i;
501 for (i = 0; i <= isl_edge_last; ++i) {
502 graph->edge_table[i] = isl_hash_table_alloc(ctx,
503 graph->max_edge[i]);
504 if (!graph->edge_table[i])
505 return -1;
508 return 0;
511 /* If graph->edge_table[type] contains an edge from the given source
512 * to the given destination, then return the hash table entry of this edge.
513 * Otherwise, return NULL.
515 static struct isl_hash_table_entry *graph_find_edge_entry(
516 struct isl_sched_graph *graph,
517 enum isl_edge_type type,
518 struct isl_sched_node *src, struct isl_sched_node *dst)
520 isl_ctx *ctx = isl_space_get_ctx(src->space);
521 uint32_t hash;
522 struct isl_sched_edge temp = { .src = src, .dst = dst };
524 hash = isl_hash_init();
525 hash = isl_hash_builtin(hash, temp.src);
526 hash = isl_hash_builtin(hash, temp.dst);
527 return isl_hash_table_find(ctx, graph->edge_table[type], hash,
528 &edge_has_src_and_dst, &temp, 0);
532 /* If graph->edge_table[type] contains an edge from the given source
533 * to the given destination, then return this edge.
534 * Otherwise, return NULL.
536 static struct isl_sched_edge *graph_find_edge(struct isl_sched_graph *graph,
537 enum isl_edge_type type,
538 struct isl_sched_node *src, struct isl_sched_node *dst)
540 struct isl_hash_table_entry *entry;
542 entry = graph_find_edge_entry(graph, type, src, dst);
543 if (!entry)
544 return NULL;
546 return entry->data;
549 /* Check whether the dependence graph has an edge of the given type
550 * between the given two nodes.
552 static isl_bool graph_has_edge(struct isl_sched_graph *graph,
553 enum isl_edge_type type,
554 struct isl_sched_node *src, struct isl_sched_node *dst)
556 struct isl_sched_edge *edge;
557 isl_bool empty;
559 edge = graph_find_edge(graph, type, src, dst);
560 if (!edge)
561 return 0;
563 empty = isl_map_plain_is_empty(edge->map);
564 if (empty < 0)
565 return isl_bool_error;
567 return !empty;
570 /* Look for any edge with the same src, dst and map fields as "model".
572 * Return the matching edge if one can be found.
573 * Return "model" if no matching edge is found.
574 * Return NULL on error.
576 static struct isl_sched_edge *graph_find_matching_edge(
577 struct isl_sched_graph *graph, struct isl_sched_edge *model)
579 enum isl_edge_type i;
580 struct isl_sched_edge *edge;
582 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
583 int is_equal;
585 edge = graph_find_edge(graph, i, model->src, model->dst);
586 if (!edge)
587 continue;
588 is_equal = isl_map_plain_is_equal(model->map, edge->map);
589 if (is_equal < 0)
590 return NULL;
591 if (is_equal)
592 return edge;
595 return model;
598 /* Remove the given edge from all the edge_tables that refer to it.
600 static void graph_remove_edge(struct isl_sched_graph *graph,
601 struct isl_sched_edge *edge)
603 isl_ctx *ctx = isl_map_get_ctx(edge->map);
604 enum isl_edge_type i;
606 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
607 struct isl_hash_table_entry *entry;
609 entry = graph_find_edge_entry(graph, i, edge->src, edge->dst);
610 if (!entry)
611 continue;
612 if (entry->data != edge)
613 continue;
614 isl_hash_table_remove(ctx, graph->edge_table[i], entry);
618 /* Check whether the dependence graph has any edge
619 * between the given two nodes.
621 static isl_bool graph_has_any_edge(struct isl_sched_graph *graph,
622 struct isl_sched_node *src, struct isl_sched_node *dst)
624 enum isl_edge_type i;
625 isl_bool r;
627 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
628 r = graph_has_edge(graph, i, src, dst);
629 if (r < 0 || r)
630 return r;
633 return r;
636 /* Check whether the dependence graph has a validity edge
637 * between the given two nodes.
639 * Conditional validity edges are essentially validity edges that
640 * can be ignored if the corresponding condition edges are iteration private.
641 * Here, we are only checking for the presence of validity
642 * edges, so we need to consider the conditional validity edges too.
643 * In particular, this function is used during the detection
644 * of strongly connected components and we cannot ignore
645 * conditional validity edges during this detection.
647 static isl_bool graph_has_validity_edge(struct isl_sched_graph *graph,
648 struct isl_sched_node *src, struct isl_sched_node *dst)
650 isl_bool r;
652 r = graph_has_edge(graph, isl_edge_validity, src, dst);
653 if (r < 0 || r)
654 return r;
656 return graph_has_edge(graph, isl_edge_conditional_validity, src, dst);
659 static int graph_alloc(isl_ctx *ctx, struct isl_sched_graph *graph,
660 int n_node, int n_edge)
662 int i;
664 graph->n = n_node;
665 graph->n_edge = n_edge;
666 graph->node = isl_calloc_array(ctx, struct isl_sched_node, graph->n);
667 graph->sorted = isl_calloc_array(ctx, int, graph->n);
668 graph->region = isl_alloc_array(ctx,
669 struct isl_trivial_region, graph->n);
670 graph->edge = isl_calloc_array(ctx,
671 struct isl_sched_edge, graph->n_edge);
673 graph->intra_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
674 graph->intra_hmap_param = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
675 graph->inter_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
677 if (!graph->node || !graph->region || (graph->n_edge && !graph->edge) ||
678 !graph->sorted)
679 return -1;
681 for(i = 0; i < graph->n; ++i)
682 graph->sorted[i] = i;
684 return 0;
687 static void graph_free(isl_ctx *ctx, struct isl_sched_graph *graph)
689 int i;
691 isl_map_to_basic_set_free(graph->intra_hmap);
692 isl_map_to_basic_set_free(graph->intra_hmap_param);
693 isl_map_to_basic_set_free(graph->inter_hmap);
695 if (graph->node)
696 for (i = 0; i < graph->n; ++i) {
697 isl_space_free(graph->node[i].space);
698 isl_set_free(graph->node[i].hull);
699 isl_multi_aff_free(graph->node[i].compress);
700 isl_multi_aff_free(graph->node[i].decompress);
701 isl_mat_free(graph->node[i].sched);
702 isl_map_free(graph->node[i].sched_map);
703 isl_mat_free(graph->node[i].indep);
704 isl_mat_free(graph->node[i].vmap);
705 if (graph->root == graph)
706 free(graph->node[i].coincident);
707 isl_multi_val_free(graph->node[i].sizes);
708 isl_basic_set_free(graph->node[i].bounds);
709 isl_vec_free(graph->node[i].max);
711 free(graph->node);
712 free(graph->sorted);
713 if (graph->edge)
714 for (i = 0; i < graph->n_edge; ++i) {
715 isl_map_free(graph->edge[i].map);
716 isl_union_map_free(graph->edge[i].tagged_condition);
717 isl_union_map_free(graph->edge[i].tagged_validity);
719 free(graph->edge);
720 free(graph->region);
721 for (i = 0; i <= isl_edge_last; ++i)
722 isl_hash_table_free(ctx, graph->edge_table[i]);
723 isl_hash_table_free(ctx, graph->node_table);
724 isl_basic_set_free(graph->lp);
727 /* For each "set" on which this function is called, increment
728 * graph->n by one and update graph->maxvar.
730 static isl_stat init_n_maxvar(__isl_take isl_set *set, void *user)
732 struct isl_sched_graph *graph = user;
733 int nvar = isl_set_dim(set, isl_dim_set);
735 graph->n++;
736 if (nvar > graph->maxvar)
737 graph->maxvar = nvar;
739 isl_set_free(set);
741 return isl_stat_ok;
744 /* Compute the number of rows that should be allocated for the schedule.
745 * In particular, we need one row for each variable or one row
746 * for each basic map in the dependences.
747 * Note that it is practically impossible to exhaust both
748 * the number of dependences and the number of variables.
750 static isl_stat compute_max_row(struct isl_sched_graph *graph,
751 __isl_keep isl_schedule_constraints *sc)
753 int n_edge;
754 isl_stat r;
755 isl_union_set *domain;
757 graph->n = 0;
758 graph->maxvar = 0;
759 domain = isl_schedule_constraints_get_domain(sc);
760 r = isl_union_set_foreach_set(domain, &init_n_maxvar, graph);
761 isl_union_set_free(domain);
762 if (r < 0)
763 return isl_stat_error;
764 n_edge = isl_schedule_constraints_n_basic_map(sc);
765 if (n_edge < 0)
766 return isl_stat_error;
767 graph->max_row = n_edge + graph->maxvar;
769 return isl_stat_ok;
772 /* Does "bset" have any defining equalities for its set variables?
774 static isl_bool has_any_defining_equality(__isl_keep isl_basic_set *bset)
776 int i, n;
778 if (!bset)
779 return isl_bool_error;
781 n = isl_basic_set_dim(bset, isl_dim_set);
782 for (i = 0; i < n; ++i) {
783 isl_bool has;
785 has = isl_basic_set_has_defining_equality(bset, isl_dim_set, i,
786 NULL);
787 if (has < 0 || has)
788 return has;
791 return isl_bool_false;
794 /* Set the entries of node->max to the value of the schedule_max_coefficient
795 * option, if set.
797 static isl_stat set_max_coefficient(isl_ctx *ctx, struct isl_sched_node *node)
799 int max;
801 max = isl_options_get_schedule_max_coefficient(ctx);
802 if (max == -1)
803 return isl_stat_ok;
805 node->max = isl_vec_alloc(ctx, node->nvar);
806 node->max = isl_vec_set_si(node->max, max);
807 if (!node->max)
808 return isl_stat_error;
810 return isl_stat_ok;
813 /* Set the entries of node->max to the minimum of the schedule_max_coefficient
814 * option (if set) and half of the minimum of the sizes in the other
815 * dimensions. Round up when computing the half such that
816 * if the minimum of the sizes is one, half of the size is taken to be one
817 * rather than zero.
818 * If the global minimum is unbounded (i.e., if both
819 * the schedule_max_coefficient is not set and the sizes in the other
820 * dimensions are unbounded), then store a negative value.
821 * If the schedule coefficient is close to the size of the instance set
822 * in another dimension, then the schedule may represent a loop
823 * coalescing transformation (especially if the coefficient
824 * in that other dimension is one). Forcing the coefficient to be
825 * smaller than or equal to half the minimal size should avoid this
826 * situation.
828 static isl_stat compute_max_coefficient(isl_ctx *ctx,
829 struct isl_sched_node *node)
831 int max;
832 int i, j;
833 isl_vec *v;
835 max = isl_options_get_schedule_max_coefficient(ctx);
836 v = isl_vec_alloc(ctx, node->nvar);
837 if (!v)
838 return isl_stat_error;
840 for (i = 0; i < node->nvar; ++i) {
841 isl_int_set_si(v->el[i], max);
842 isl_int_mul_si(v->el[i], v->el[i], 2);
845 for (i = 0; i < node->nvar; ++i) {
846 isl_val *size;
848 size = isl_multi_val_get_val(node->sizes, i);
849 if (!size)
850 goto error;
851 if (!isl_val_is_int(size)) {
852 isl_val_free(size);
853 continue;
855 for (j = 0; j < node->nvar; ++j) {
856 if (j == i)
857 continue;
858 if (isl_int_is_neg(v->el[j]) ||
859 isl_int_gt(v->el[j], size->n))
860 isl_int_set(v->el[j], size->n);
862 isl_val_free(size);
865 for (i = 0; i < node->nvar; ++i)
866 isl_int_cdiv_q_ui(v->el[i], v->el[i], 2);
868 node->max = v;
869 return isl_stat_ok;
870 error:
871 isl_vec_free(v);
872 return isl_stat_error;
875 /* Compute and return the size of "set" in dimension "dim".
876 * The size is taken to be the difference in values for that variable
877 * for fixed values of the other variables.
878 * This assumes that "set" is convex.
879 * In particular, the variable is first isolated from the other variables
880 * in the range of a map
882 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [i_dim]
884 * and then duplicated
886 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [[i_dim] -> [i_dim']]
888 * The shared variables are then projected out and the maximal value
889 * of i_dim' - i_dim is computed.
891 static __isl_give isl_val *compute_size(__isl_take isl_set *set, int dim)
893 isl_map *map;
894 isl_local_space *ls;
895 isl_aff *obj;
896 isl_val *v;
898 map = isl_set_project_onto_map(set, isl_dim_set, dim, 1);
899 map = isl_map_project_out(map, isl_dim_in, dim, 1);
900 map = isl_map_range_product(map, isl_map_copy(map));
901 map = isl_set_unwrap(isl_map_range(map));
902 set = isl_map_deltas(map);
903 ls = isl_local_space_from_space(isl_set_get_space(set));
904 obj = isl_aff_var_on_domain(ls, isl_dim_set, 0);
905 v = isl_set_max_val(set, obj);
906 isl_aff_free(obj);
907 isl_set_free(set);
909 return v;
912 /* Compute the size of the instance set "set" of "node", after compression,
913 * as well as bounds on the corresponding coefficients, if needed.
915 * The sizes are needed when the schedule_treat_coalescing option is set.
916 * The bounds are needed when the schedule_treat_coalescing option or
917 * the schedule_max_coefficient option is set.
919 * If the schedule_treat_coalescing option is not set, then at most
920 * the bounds need to be set and this is done in set_max_coefficient.
921 * Otherwise, compress the domain if needed, compute the size
922 * in each direction and store the results in node->size.
923 * If the domain is not convex, then the sizes are computed
924 * on a convex superset in order to avoid picking up sizes
925 * that are valid for the individual disjuncts, but not for
926 * the domain as a whole.
927 * Finally, set the bounds on the coefficients based on the sizes
928 * and the schedule_max_coefficient option in compute_max_coefficient.
930 static isl_stat compute_sizes_and_max(isl_ctx *ctx, struct isl_sched_node *node,
931 __isl_take isl_set *set)
933 int j, n;
934 isl_multi_val *mv;
936 if (!isl_options_get_schedule_treat_coalescing(ctx)) {
937 isl_set_free(set);
938 return set_max_coefficient(ctx, node);
941 if (node->compressed)
942 set = isl_set_preimage_multi_aff(set,
943 isl_multi_aff_copy(node->decompress));
944 set = isl_set_from_basic_set(isl_set_simple_hull(set));
945 mv = isl_multi_val_zero(isl_set_get_space(set));
946 n = isl_set_dim(set, isl_dim_set);
947 for (j = 0; j < n; ++j) {
948 isl_val *v;
950 v = compute_size(isl_set_copy(set), j);
951 mv = isl_multi_val_set_val(mv, j, v);
953 node->sizes = mv;
954 isl_set_free(set);
955 if (!node->sizes)
956 return isl_stat_error;
957 return compute_max_coefficient(ctx, node);
960 /* Add a new node to the graph representing the given instance set.
961 * "nvar" is the (possibly compressed) number of variables and
962 * may be smaller than then number of set variables in "set"
963 * if "compressed" is set.
964 * If "compressed" is set, then "hull" represents the constraints
965 * that were used to derive the compression, while "compress" and
966 * "decompress" map the original space to the compressed space and
967 * vice versa.
968 * If "compressed" is not set, then "hull", "compress" and "decompress"
969 * should be NULL.
971 * Compute the size of the instance set and bounds on the coefficients,
972 * if needed.
974 static isl_stat add_node(struct isl_sched_graph *graph,
975 __isl_take isl_set *set, int nvar, int compressed,
976 __isl_take isl_set *hull, __isl_take isl_multi_aff *compress,
977 __isl_take isl_multi_aff *decompress)
979 int nparam;
980 isl_ctx *ctx;
981 isl_mat *sched;
982 isl_space *space;
983 int *coincident;
984 struct isl_sched_node *node;
986 if (!set)
987 return isl_stat_error;
989 ctx = isl_set_get_ctx(set);
990 nparam = isl_set_dim(set, isl_dim_param);
991 if (!ctx->opt->schedule_parametric)
992 nparam = 0;
993 sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
994 node = &graph->node[graph->n];
995 graph->n++;
996 space = isl_set_get_space(set);
997 node->space = space;
998 node->nvar = nvar;
999 node->nparam = nparam;
1000 node->sched = sched;
1001 node->sched_map = NULL;
1002 coincident = isl_calloc_array(ctx, int, graph->max_row);
1003 node->coincident = coincident;
1004 node->compressed = compressed;
1005 node->hull = hull;
1006 node->compress = compress;
1007 node->decompress = decompress;
1008 if (compute_sizes_and_max(ctx, node, set) < 0)
1009 return isl_stat_error;
1011 if (!space || !sched || (graph->max_row && !coincident))
1012 return isl_stat_error;
1013 if (compressed && (!hull || !compress || !decompress))
1014 return isl_stat_error;
1016 return isl_stat_ok;
1019 /* Construct an identifier for node "node", which will represent "set".
1020 * The name of the identifier is either "compressed" or
1021 * "compressed_<name>", with <name> the name of the space of "set".
1022 * The user pointer of the identifier points to "node".
1024 static __isl_give isl_id *construct_compressed_id(__isl_keep isl_set *set,
1025 struct isl_sched_node *node)
1027 isl_bool has_name;
1028 isl_ctx *ctx;
1029 isl_id *id;
1030 isl_printer *p;
1031 const char *name;
1032 char *id_name;
1034 has_name = isl_set_has_tuple_name(set);
1035 if (has_name < 0)
1036 return NULL;
1038 ctx = isl_set_get_ctx(set);
1039 if (!has_name)
1040 return isl_id_alloc(ctx, "compressed", node);
1042 p = isl_printer_to_str(ctx);
1043 name = isl_set_get_tuple_name(set);
1044 p = isl_printer_print_str(p, "compressed_");
1045 p = isl_printer_print_str(p, name);
1046 id_name = isl_printer_get_str(p);
1047 isl_printer_free(p);
1049 id = isl_id_alloc(ctx, id_name, node);
1050 free(id_name);
1052 return id;
1055 /* Add a new node to the graph representing the given set.
1057 * If any of the set variables is defined by an equality, then
1058 * we perform variable compression such that we can perform
1059 * the scheduling on the compressed domain.
1060 * In this case, an identifier is used that references the new node
1061 * such that each compressed space is unique and
1062 * such that the node can be recovered from the compressed space.
1064 static isl_stat extract_node(__isl_take isl_set *set, void *user)
1066 int nvar;
1067 isl_bool has_equality;
1068 isl_id *id;
1069 isl_basic_set *hull;
1070 isl_set *hull_set;
1071 isl_morph *morph;
1072 isl_multi_aff *compress, *decompress;
1073 struct isl_sched_graph *graph = user;
1075 hull = isl_set_affine_hull(isl_set_copy(set));
1076 hull = isl_basic_set_remove_divs(hull);
1077 nvar = isl_set_dim(set, isl_dim_set);
1078 has_equality = has_any_defining_equality(hull);
1080 if (has_equality < 0)
1081 goto error;
1082 if (!has_equality) {
1083 isl_basic_set_free(hull);
1084 return add_node(graph, set, nvar, 0, NULL, NULL, NULL);
1087 id = construct_compressed_id(set, &graph->node[graph->n]);
1088 morph = isl_basic_set_variable_compression_with_id(hull,
1089 isl_dim_set, id);
1090 isl_id_free(id);
1091 nvar = isl_morph_ran_dim(morph, isl_dim_set);
1092 compress = isl_morph_get_var_multi_aff(morph);
1093 morph = isl_morph_inverse(morph);
1094 decompress = isl_morph_get_var_multi_aff(morph);
1095 isl_morph_free(morph);
1097 hull_set = isl_set_from_basic_set(hull);
1098 return add_node(graph, set, nvar, 1, hull_set, compress, decompress);
1099 error:
1100 isl_basic_set_free(hull);
1101 isl_set_free(set);
1102 return isl_stat_error;
1105 struct isl_extract_edge_data {
1106 enum isl_edge_type type;
1107 struct isl_sched_graph *graph;
1110 /* Merge edge2 into edge1, freeing the contents of edge2.
1111 * Return 0 on success and -1 on failure.
1113 * edge1 and edge2 are assumed to have the same value for the map field.
1115 static int merge_edge(struct isl_sched_edge *edge1,
1116 struct isl_sched_edge *edge2)
1118 edge1->types |= edge2->types;
1119 isl_map_free(edge2->map);
1121 if (is_condition(edge2)) {
1122 if (!edge1->tagged_condition)
1123 edge1->tagged_condition = edge2->tagged_condition;
1124 else
1125 edge1->tagged_condition =
1126 isl_union_map_union(edge1->tagged_condition,
1127 edge2->tagged_condition);
1130 if (is_conditional_validity(edge2)) {
1131 if (!edge1->tagged_validity)
1132 edge1->tagged_validity = edge2->tagged_validity;
1133 else
1134 edge1->tagged_validity =
1135 isl_union_map_union(edge1->tagged_validity,
1136 edge2->tagged_validity);
1139 if (is_condition(edge2) && !edge1->tagged_condition)
1140 return -1;
1141 if (is_conditional_validity(edge2) && !edge1->tagged_validity)
1142 return -1;
1144 return 0;
1147 /* Insert dummy tags in domain and range of "map".
1149 * In particular, if "map" is of the form
1151 * A -> B
1153 * then return
1155 * [A -> dummy_tag] -> [B -> dummy_tag]
1157 * where the dummy_tags are identical and equal to any dummy tags
1158 * introduced by any other call to this function.
1160 static __isl_give isl_map *insert_dummy_tags(__isl_take isl_map *map)
1162 static char dummy;
1163 isl_ctx *ctx;
1164 isl_id *id;
1165 isl_space *space;
1166 isl_set *domain, *range;
1168 ctx = isl_map_get_ctx(map);
1170 id = isl_id_alloc(ctx, NULL, &dummy);
1171 space = isl_space_params(isl_map_get_space(map));
1172 space = isl_space_set_from_params(space);
1173 space = isl_space_set_tuple_id(space, isl_dim_set, id);
1174 space = isl_space_map_from_set(space);
1176 domain = isl_map_wrap(map);
1177 range = isl_map_wrap(isl_map_universe(space));
1178 map = isl_map_from_domain_and_range(domain, range);
1179 map = isl_map_zip(map);
1181 return map;
1184 /* Given that at least one of "src" or "dst" is compressed, return
1185 * a map between the spaces of these nodes restricted to the affine
1186 * hull that was used in the compression.
1188 static __isl_give isl_map *extract_hull(struct isl_sched_node *src,
1189 struct isl_sched_node *dst)
1191 isl_set *dom, *ran;
1193 if (src->compressed)
1194 dom = isl_set_copy(src->hull);
1195 else
1196 dom = isl_set_universe(isl_space_copy(src->space));
1197 if (dst->compressed)
1198 ran = isl_set_copy(dst->hull);
1199 else
1200 ran = isl_set_universe(isl_space_copy(dst->space));
1202 return isl_map_from_domain_and_range(dom, ran);
1205 /* Intersect the domains of the nested relations in domain and range
1206 * of "tagged" with "map".
1208 static __isl_give isl_map *map_intersect_domains(__isl_take isl_map *tagged,
1209 __isl_keep isl_map *map)
1211 isl_set *set;
1213 tagged = isl_map_zip(tagged);
1214 set = isl_map_wrap(isl_map_copy(map));
1215 tagged = isl_map_intersect_domain(tagged, set);
1216 tagged = isl_map_zip(tagged);
1217 return tagged;
1220 /* Return a pointer to the node that lives in the domain space of "map"
1221 * or NULL if there is no such node.
1223 static struct isl_sched_node *find_domain_node(isl_ctx *ctx,
1224 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1226 struct isl_sched_node *node;
1227 isl_space *space;
1229 space = isl_space_domain(isl_map_get_space(map));
1230 node = graph_find_node(ctx, graph, space);
1231 isl_space_free(space);
1233 return node;
1236 /* Return a pointer to the node that lives in the range space of "map"
1237 * or NULL if there is no such node.
1239 static struct isl_sched_node *find_range_node(isl_ctx *ctx,
1240 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1242 struct isl_sched_node *node;
1243 isl_space *space;
1245 space = isl_space_range(isl_map_get_space(map));
1246 node = graph_find_node(ctx, graph, space);
1247 isl_space_free(space);
1249 return node;
1252 /* Refrain from adding a new edge based on "map".
1253 * Instead, just free the map.
1254 * "tagged" is either a copy of "map" with additional tags or NULL.
1256 static isl_stat skip_edge(__isl_take isl_map *map, __isl_take isl_map *tagged)
1258 isl_map_free(map);
1259 isl_map_free(tagged);
1261 return isl_stat_ok;
1264 /* Add a new edge to the graph based on the given map
1265 * and add it to data->graph->edge_table[data->type].
1266 * If a dependence relation of a given type happens to be identical
1267 * to one of the dependence relations of a type that was added before,
1268 * then we don't create a new edge, but instead mark the original edge
1269 * as also representing a dependence of the current type.
1271 * Edges of type isl_edge_condition or isl_edge_conditional_validity
1272 * may be specified as "tagged" dependence relations. That is, "map"
1273 * may contain elements (i -> a) -> (j -> b), where i -> j denotes
1274 * the dependence on iterations and a and b are tags.
1275 * edge->map is set to the relation containing the elements i -> j,
1276 * while edge->tagged_condition and edge->tagged_validity contain
1277 * the union of all the "map" relations
1278 * for which extract_edge is called that result in the same edge->map.
1280 * If the source or the destination node is compressed, then
1281 * intersect both "map" and "tagged" with the constraints that
1282 * were used to construct the compression.
1283 * This ensures that there are no schedule constraints defined
1284 * outside of these domains, while the scheduler no longer has
1285 * any control over those outside parts.
1287 static isl_stat extract_edge(__isl_take isl_map *map, void *user)
1289 isl_bool empty;
1290 isl_ctx *ctx = isl_map_get_ctx(map);
1291 struct isl_extract_edge_data *data = user;
1292 struct isl_sched_graph *graph = data->graph;
1293 struct isl_sched_node *src, *dst;
1294 struct isl_sched_edge *edge;
1295 isl_map *tagged = NULL;
1297 if (data->type == isl_edge_condition ||
1298 data->type == isl_edge_conditional_validity) {
1299 if (isl_map_can_zip(map)) {
1300 tagged = isl_map_copy(map);
1301 map = isl_set_unwrap(isl_map_domain(isl_map_zip(map)));
1302 } else {
1303 tagged = insert_dummy_tags(isl_map_copy(map));
1307 src = find_domain_node(ctx, graph, map);
1308 dst = find_range_node(ctx, graph, map);
1310 if (!src || !dst)
1311 return skip_edge(map, tagged);
1313 if (src->compressed || dst->compressed) {
1314 isl_map *hull;
1315 hull = extract_hull(src, dst);
1316 if (tagged)
1317 tagged = map_intersect_domains(tagged, hull);
1318 map = isl_map_intersect(map, hull);
1321 empty = isl_map_plain_is_empty(map);
1322 if (empty < 0)
1323 goto error;
1324 if (empty)
1325 return skip_edge(map, tagged);
1327 graph->edge[graph->n_edge].src = src;
1328 graph->edge[graph->n_edge].dst = dst;
1329 graph->edge[graph->n_edge].map = map;
1330 graph->edge[graph->n_edge].types = 0;
1331 graph->edge[graph->n_edge].tagged_condition = NULL;
1332 graph->edge[graph->n_edge].tagged_validity = NULL;
1333 set_type(&graph->edge[graph->n_edge], data->type);
1334 if (data->type == isl_edge_condition)
1335 graph->edge[graph->n_edge].tagged_condition =
1336 isl_union_map_from_map(tagged);
1337 if (data->type == isl_edge_conditional_validity)
1338 graph->edge[graph->n_edge].tagged_validity =
1339 isl_union_map_from_map(tagged);
1341 edge = graph_find_matching_edge(graph, &graph->edge[graph->n_edge]);
1342 if (!edge) {
1343 graph->n_edge++;
1344 return isl_stat_error;
1346 if (edge == &graph->edge[graph->n_edge])
1347 return graph_edge_table_add(ctx, graph, data->type,
1348 &graph->edge[graph->n_edge++]);
1350 if (merge_edge(edge, &graph->edge[graph->n_edge]) < 0)
1351 return isl_stat_error;
1353 return graph_edge_table_add(ctx, graph, data->type, edge);
1354 error:
1355 isl_map_free(map);
1356 isl_map_free(tagged);
1357 return isl_stat_error;
1360 /* Initialize the schedule graph "graph" from the schedule constraints "sc".
1362 * The context is included in the domain before the nodes of
1363 * the graphs are extracted in order to be able to exploit
1364 * any possible additional equalities.
1365 * Note that this intersection is only performed locally here.
1367 static isl_stat graph_init(struct isl_sched_graph *graph,
1368 __isl_keep isl_schedule_constraints *sc)
1370 isl_ctx *ctx;
1371 isl_union_set *domain;
1372 isl_union_map *c;
1373 struct isl_extract_edge_data data;
1374 enum isl_edge_type i;
1375 isl_stat r;
1377 if (!sc)
1378 return isl_stat_error;
1380 ctx = isl_schedule_constraints_get_ctx(sc);
1382 domain = isl_schedule_constraints_get_domain(sc);
1383 graph->n = isl_union_set_n_set(domain);
1384 isl_union_set_free(domain);
1386 if (graph_alloc(ctx, graph, graph->n,
1387 isl_schedule_constraints_n_map(sc)) < 0)
1388 return isl_stat_error;
1390 if (compute_max_row(graph, sc) < 0)
1391 return isl_stat_error;
1392 graph->root = graph;
1393 graph->n = 0;
1394 domain = isl_schedule_constraints_get_domain(sc);
1395 domain = isl_union_set_intersect_params(domain,
1396 isl_schedule_constraints_get_context(sc));
1397 r = isl_union_set_foreach_set(domain, &extract_node, graph);
1398 isl_union_set_free(domain);
1399 if (r < 0)
1400 return isl_stat_error;
1401 if (graph_init_table(ctx, graph) < 0)
1402 return isl_stat_error;
1403 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1404 c = isl_schedule_constraints_get(sc, i);
1405 graph->max_edge[i] = isl_union_map_n_map(c);
1406 isl_union_map_free(c);
1407 if (!c)
1408 return isl_stat_error;
1410 if (graph_init_edge_tables(ctx, graph) < 0)
1411 return isl_stat_error;
1412 graph->n_edge = 0;
1413 data.graph = graph;
1414 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1415 isl_stat r;
1417 data.type = i;
1418 c = isl_schedule_constraints_get(sc, i);
1419 r = isl_union_map_foreach_map(c, &extract_edge, &data);
1420 isl_union_map_free(c);
1421 if (r < 0)
1422 return isl_stat_error;
1425 return isl_stat_ok;
1428 /* Check whether there is any dependence from node[j] to node[i]
1429 * or from node[i] to node[j].
1431 static isl_bool node_follows_weak(int i, int j, void *user)
1433 isl_bool f;
1434 struct isl_sched_graph *graph = user;
1436 f = graph_has_any_edge(graph, &graph->node[j], &graph->node[i]);
1437 if (f < 0 || f)
1438 return f;
1439 return graph_has_any_edge(graph, &graph->node[i], &graph->node[j]);
1442 /* Check whether there is a (conditional) validity dependence from node[j]
1443 * to node[i], forcing node[i] to follow node[j].
1445 static isl_bool node_follows_strong(int i, int j, void *user)
1447 struct isl_sched_graph *graph = user;
1449 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
1452 /* Use Tarjan's algorithm for computing the strongly connected components
1453 * in the dependence graph only considering those edges defined by "follows".
1455 static isl_stat detect_ccs(isl_ctx *ctx, struct isl_sched_graph *graph,
1456 isl_bool (*follows)(int i, int j, void *user))
1458 int i, n;
1459 struct isl_tarjan_graph *g = NULL;
1461 g = isl_tarjan_graph_init(ctx, graph->n, follows, graph);
1462 if (!g)
1463 return isl_stat_error;
1465 graph->scc = 0;
1466 i = 0;
1467 n = graph->n;
1468 while (n) {
1469 while (g->order[i] != -1) {
1470 graph->node[g->order[i]].scc = graph->scc;
1471 --n;
1472 ++i;
1474 ++i;
1475 graph->scc++;
1478 isl_tarjan_graph_free(g);
1480 return isl_stat_ok;
1483 /* Apply Tarjan's algorithm to detect the strongly connected components
1484 * in the dependence graph.
1485 * Only consider the (conditional) validity dependences and clear "weak".
1487 static isl_stat detect_sccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1489 graph->weak = 0;
1490 return detect_ccs(ctx, graph, &node_follows_strong);
1493 /* Apply Tarjan's algorithm to detect the (weakly) connected components
1494 * in the dependence graph.
1495 * Consider all dependences and set "weak".
1497 static isl_stat detect_wccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1499 graph->weak = 1;
1500 return detect_ccs(ctx, graph, &node_follows_weak);
1503 static int cmp_scc(const void *a, const void *b, void *data)
1505 struct isl_sched_graph *graph = data;
1506 const int *i1 = a;
1507 const int *i2 = b;
1509 return graph->node[*i1].scc - graph->node[*i2].scc;
1512 /* Sort the elements of graph->sorted according to the corresponding SCCs.
1514 static int sort_sccs(struct isl_sched_graph *graph)
1516 return isl_sort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
1519 /* Return a non-parametric set in the compressed space of "node" that is
1520 * bounded by the size in each direction
1522 * { [x] : -S_i <= x_i <= S_i }
1524 * If S_i is infinity in direction i, then there are no constraints
1525 * in that direction.
1527 * Cache the result in node->bounds.
1529 static __isl_give isl_basic_set *get_size_bounds(struct isl_sched_node *node)
1531 isl_space *space;
1532 isl_basic_set *bounds;
1533 int i;
1534 unsigned nparam;
1536 if (node->bounds)
1537 return isl_basic_set_copy(node->bounds);
1539 if (node->compressed)
1540 space = isl_multi_aff_get_domain_space(node->decompress);
1541 else
1542 space = isl_space_copy(node->space);
1543 nparam = isl_space_dim(space, isl_dim_param);
1544 space = isl_space_drop_dims(space, isl_dim_param, 0, nparam);
1545 bounds = isl_basic_set_universe(space);
1547 for (i = 0; i < node->nvar; ++i) {
1548 isl_val *size;
1550 size = isl_multi_val_get_val(node->sizes, i);
1551 if (!size)
1552 return isl_basic_set_free(bounds);
1553 if (!isl_val_is_int(size)) {
1554 isl_val_free(size);
1555 continue;
1557 bounds = isl_basic_set_upper_bound_val(bounds, isl_dim_set, i,
1558 isl_val_copy(size));
1559 bounds = isl_basic_set_lower_bound_val(bounds, isl_dim_set, i,
1560 isl_val_neg(size));
1563 node->bounds = isl_basic_set_copy(bounds);
1564 return bounds;
1567 /* Drop some constraints from "delta" that could be exploited
1568 * to construct loop coalescing schedules.
1569 * In particular, drop those constraint that bound the difference
1570 * to the size of the domain.
1571 * First project out the parameters to improve the effectiveness.
1573 static __isl_give isl_set *drop_coalescing_constraints(
1574 __isl_take isl_set *delta, struct isl_sched_node *node)
1576 unsigned nparam;
1577 isl_basic_set *bounds;
1579 bounds = get_size_bounds(node);
1581 nparam = isl_set_dim(delta, isl_dim_param);
1582 delta = isl_set_project_out(delta, isl_dim_param, 0, nparam);
1583 delta = isl_set_remove_divs(delta);
1584 delta = isl_set_plain_gist_basic_set(delta, bounds);
1585 return delta;
1588 /* Given a dependence relation R from "node" to itself,
1589 * construct the set of coefficients of valid constraints for elements
1590 * in that dependence relation.
1591 * In particular, the result contains tuples of coefficients
1592 * c_0, c_n, c_x such that
1594 * c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
1596 * or, equivalently,
1598 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
1600 * We choose here to compute the dual of delta R.
1601 * Alternatively, we could have computed the dual of R, resulting
1602 * in a set of tuples c_0, c_n, c_x, c_y, and then
1603 * plugged in (c_0, c_n, c_x, -c_x).
1605 * If "need_param" is set, then the resulting coefficients effectively
1606 * include coefficients for the parameters c_n. Otherwise, they may
1607 * have been projected out already.
1608 * Since the constraints may be different for these two cases,
1609 * they are stored in separate caches.
1610 * In particular, if no parameter coefficients are required and
1611 * the schedule_treat_coalescing option is set, then the parameters
1612 * are projected out and some constraints that could be exploited
1613 * to construct coalescing schedules are removed before the dual
1614 * is computed.
1616 * If "node" has been compressed, then the dependence relation
1617 * is also compressed before the set of coefficients is computed.
1619 static __isl_give isl_basic_set *intra_coefficients(
1620 struct isl_sched_graph *graph, struct isl_sched_node *node,
1621 __isl_take isl_map *map, int need_param)
1623 isl_ctx *ctx;
1624 isl_set *delta;
1625 isl_map *key;
1626 isl_basic_set *coef;
1627 isl_maybe_isl_basic_set m;
1628 isl_map_to_basic_set **hmap = &graph->intra_hmap;
1629 int treat;
1631 if (!map)
1632 return NULL;
1634 ctx = isl_map_get_ctx(map);
1635 treat = !need_param && isl_options_get_schedule_treat_coalescing(ctx);
1636 if (!treat)
1637 hmap = &graph->intra_hmap_param;
1638 m = isl_map_to_basic_set_try_get(*hmap, map);
1639 if (m.valid < 0 || m.valid) {
1640 isl_map_free(map);
1641 return m.value;
1644 key = isl_map_copy(map);
1645 if (node->compressed) {
1646 map = isl_map_preimage_domain_multi_aff(map,
1647 isl_multi_aff_copy(node->decompress));
1648 map = isl_map_preimage_range_multi_aff(map,
1649 isl_multi_aff_copy(node->decompress));
1651 delta = isl_map_deltas(map);
1652 if (treat)
1653 delta = drop_coalescing_constraints(delta, node);
1654 delta = isl_set_remove_divs(delta);
1655 coef = isl_set_coefficients(delta);
1656 *hmap = isl_map_to_basic_set_set(*hmap, key, isl_basic_set_copy(coef));
1658 return coef;
1661 /* Given a dependence relation R, construct the set of coefficients
1662 * of valid constraints for elements in that dependence relation.
1663 * In particular, the result contains tuples of coefficients
1664 * c_0, c_n, c_x, c_y such that
1666 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
1668 * If the source or destination nodes of "edge" have been compressed,
1669 * then the dependence relation is also compressed before
1670 * the set of coefficients is computed.
1672 static __isl_give isl_basic_set *inter_coefficients(
1673 struct isl_sched_graph *graph, struct isl_sched_edge *edge,
1674 __isl_take isl_map *map)
1676 isl_set *set;
1677 isl_map *key;
1678 isl_basic_set *coef;
1679 isl_maybe_isl_basic_set m;
1681 m = isl_map_to_basic_set_try_get(graph->inter_hmap, map);
1682 if (m.valid < 0 || m.valid) {
1683 isl_map_free(map);
1684 return m.value;
1687 key = isl_map_copy(map);
1688 if (edge->src->compressed)
1689 map = isl_map_preimage_domain_multi_aff(map,
1690 isl_multi_aff_copy(edge->src->decompress));
1691 if (edge->dst->compressed)
1692 map = isl_map_preimage_range_multi_aff(map,
1693 isl_multi_aff_copy(edge->dst->decompress));
1694 set = isl_map_wrap(isl_map_remove_divs(map));
1695 coef = isl_set_coefficients(set);
1696 graph->inter_hmap = isl_map_to_basic_set_set(graph->inter_hmap, key,
1697 isl_basic_set_copy(coef));
1699 return coef;
1702 /* Return the position of the coefficients of the variables in
1703 * the coefficients constraints "coef".
1705 * The space of "coef" is of the form
1707 * { coefficients[[cst, params] -> S] }
1709 * Return the position of S.
1711 static int coef_var_offset(__isl_keep isl_basic_set *coef)
1713 int offset;
1714 isl_space *space;
1716 space = isl_space_unwrap(isl_basic_set_get_space(coef));
1717 offset = isl_space_dim(space, isl_dim_in);
1718 isl_space_free(space);
1720 return offset;
1723 /* Return the offset of the coefficient of the constant term of "node"
1724 * within the (I)LP.
1726 * Within each node, the coefficients have the following order:
1727 * - positive and negative parts of c_i_x
1728 * - c_i_n (if parametric)
1729 * - c_i_0
1731 static int node_cst_coef_offset(struct isl_sched_node *node)
1733 return node->start + 2 * node->nvar + node->nparam;
1736 /* Return the offset of the coefficients of the parameters of "node"
1737 * within the (I)LP.
1739 * Within each node, the coefficients have the following order:
1740 * - positive and negative parts of c_i_x
1741 * - c_i_n (if parametric)
1742 * - c_i_0
1744 static int node_par_coef_offset(struct isl_sched_node *node)
1746 return node->start + 2 * node->nvar;
1749 /* Return the offset of the coefficients of the variables of "node"
1750 * within the (I)LP.
1752 * Within each node, the coefficients have the following order:
1753 * - positive and negative parts of c_i_x
1754 * - c_i_n (if parametric)
1755 * - c_i_0
1757 static int node_var_coef_offset(struct isl_sched_node *node)
1759 return node->start;
1762 /* Return the position of the pair of variables encoding
1763 * coefficient "i" of "node".
1765 * The order of these variable pairs is the opposite of
1766 * that of the coefficients, with 2 variables per coefficient.
1768 static int node_var_coef_pos(struct isl_sched_node *node, int i)
1770 return node_var_coef_offset(node) + 2 * (node->nvar - 1 - i);
1773 /* Construct an isl_dim_map for mapping constraints on coefficients
1774 * for "node" to the corresponding positions in graph->lp.
1775 * "offset" is the offset of the coefficients for the variables
1776 * in the input constraints.
1777 * "s" is the sign of the mapping.
1779 * The input constraints are given in terms of the coefficients
1780 * (c_0, c_x) or (c_0, c_n, c_x).
1781 * The mapping produced by this function essentially plugs in
1782 * (0, c_i_x^+ - c_i_x^-) if s = 1 and
1783 * (0, -c_i_x^+ + c_i_x^-) if s = -1 or
1784 * (0, 0, c_i_x^+ - c_i_x^-) if s = 1 and
1785 * (0, 0, -c_i_x^+ + c_i_x^-) if s = -1.
1786 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1787 * Furthermore, the order of these pairs is the opposite of that
1788 * of the corresponding coefficients.
1790 * The caller can extend the mapping to also map the other coefficients
1791 * (and therefore not plug in 0).
1793 static __isl_give isl_dim_map *intra_dim_map(isl_ctx *ctx,
1794 struct isl_sched_graph *graph, struct isl_sched_node *node,
1795 int offset, int s)
1797 int pos;
1798 unsigned total;
1799 isl_dim_map *dim_map;
1801 if (!node || !graph->lp)
1802 return NULL;
1804 total = isl_basic_set_total_dim(graph->lp);
1805 pos = node_var_coef_pos(node, 0);
1806 dim_map = isl_dim_map_alloc(ctx, total);
1807 isl_dim_map_range(dim_map, pos, -2, offset, 1, node->nvar, -s);
1808 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, node->nvar, s);
1810 return dim_map;
1813 /* Construct an isl_dim_map for mapping constraints on coefficients
1814 * for "src" (node i) and "dst" (node j) to the corresponding positions
1815 * in graph->lp.
1816 * "offset" is the offset of the coefficients for the variables of "src"
1817 * in the input constraints.
1818 * "s" is the sign of the mapping.
1820 * The input constraints are given in terms of the coefficients
1821 * (c_0, c_n, c_x, c_y).
1822 * The mapping produced by this function essentially plugs in
1823 * (c_j_0 - c_i_0, c_j_n - c_i_n,
1824 * -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-) if s = 1 and
1825 * (-c_j_0 + c_i_0, -c_j_n + c_i_n,
1826 * c_i_x^+ - c_i_x^-, -(c_j_x^+ - c_j_x^-)) if s = -1.
1827 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1828 * Furthermore, the order of these pairs is the opposite of that
1829 * of the corresponding coefficients.
1831 * The caller can further extend the mapping.
1833 static __isl_give isl_dim_map *inter_dim_map(isl_ctx *ctx,
1834 struct isl_sched_graph *graph, struct isl_sched_node *src,
1835 struct isl_sched_node *dst, int offset, int s)
1837 int pos;
1838 unsigned total;
1839 isl_dim_map *dim_map;
1841 if (!src || !dst || !graph->lp)
1842 return NULL;
1844 total = isl_basic_set_total_dim(graph->lp);
1845 dim_map = isl_dim_map_alloc(ctx, total);
1847 pos = node_cst_coef_offset(dst);
1848 isl_dim_map_range(dim_map, pos, 0, 0, 0, 1, s);
1849 pos = node_par_coef_offset(dst);
1850 isl_dim_map_range(dim_map, pos, 1, 1, 1, dst->nparam, s);
1851 pos = node_var_coef_pos(dst, 0);
1852 isl_dim_map_range(dim_map, pos, -2, offset + src->nvar, 1,
1853 dst->nvar, -s);
1854 isl_dim_map_range(dim_map, pos + 1, -2, offset + src->nvar, 1,
1855 dst->nvar, s);
1857 pos = node_cst_coef_offset(src);
1858 isl_dim_map_range(dim_map, pos, 0, 0, 0, 1, -s);
1859 pos = node_par_coef_offset(src);
1860 isl_dim_map_range(dim_map, pos, 1, 1, 1, src->nparam, -s);
1861 pos = node_var_coef_pos(src, 0);
1862 isl_dim_map_range(dim_map, pos, -2, offset, 1, src->nvar, s);
1863 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, src->nvar, -s);
1865 return dim_map;
1868 /* Add the constraints from "src" to "dst" using "dim_map",
1869 * after making sure there is enough room in "dst" for the extra constraints.
1871 static __isl_give isl_basic_set *add_constraints_dim_map(
1872 __isl_take isl_basic_set *dst, __isl_take isl_basic_set *src,
1873 __isl_take isl_dim_map *dim_map)
1875 int n_eq, n_ineq;
1877 n_eq = isl_basic_set_n_equality(src);
1878 n_ineq = isl_basic_set_n_inequality(src);
1879 dst = isl_basic_set_extend_constraints(dst, n_eq, n_ineq);
1880 dst = isl_basic_set_add_constraints_dim_map(dst, src, dim_map);
1881 return dst;
1884 /* Add constraints to graph->lp that force validity for the given
1885 * dependence from a node i to itself.
1886 * That is, add constraints that enforce
1888 * (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
1889 * = c_i_x (y - x) >= 0
1891 * for each (x,y) in R.
1892 * We obtain general constraints on coefficients (c_0, c_x)
1893 * of valid constraints for (y - x) and then plug in (0, c_i_x^+ - c_i_x^-),
1894 * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
1895 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1896 * Note that the result of intra_coefficients may also contain
1897 * parameter coefficients c_n, in which case 0 is plugged in for them as well.
1899 static isl_stat add_intra_validity_constraints(struct isl_sched_graph *graph,
1900 struct isl_sched_edge *edge)
1902 int offset;
1903 isl_map *map = isl_map_copy(edge->map);
1904 isl_ctx *ctx = isl_map_get_ctx(map);
1905 isl_dim_map *dim_map;
1906 isl_basic_set *coef;
1907 struct isl_sched_node *node = edge->src;
1909 coef = intra_coefficients(graph, node, map, 0);
1911 offset = coef_var_offset(coef);
1913 if (!coef)
1914 return isl_stat_error;
1916 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
1917 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1919 return isl_stat_ok;
1922 /* Add constraints to graph->lp that force validity for the given
1923 * dependence from node i to node j.
1924 * That is, add constraints that enforce
1926 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
1928 * for each (x,y) in R.
1929 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1930 * of valid constraints for R and then plug in
1931 * (c_j_0 - c_i_0, c_j_n - c_i_n, -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-),
1932 * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
1933 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1935 static isl_stat add_inter_validity_constraints(struct isl_sched_graph *graph,
1936 struct isl_sched_edge *edge)
1938 int offset;
1939 isl_map *map;
1940 isl_ctx *ctx;
1941 isl_dim_map *dim_map;
1942 isl_basic_set *coef;
1943 struct isl_sched_node *src = edge->src;
1944 struct isl_sched_node *dst = edge->dst;
1946 if (!graph->lp)
1947 return isl_stat_error;
1949 map = isl_map_copy(edge->map);
1950 ctx = isl_map_get_ctx(map);
1951 coef = inter_coefficients(graph, edge, map);
1953 offset = coef_var_offset(coef);
1955 if (!coef)
1956 return isl_stat_error;
1958 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
1960 edge->start = graph->lp->n_ineq;
1961 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1962 if (!graph->lp)
1963 return isl_stat_error;
1964 edge->end = graph->lp->n_ineq;
1966 return isl_stat_ok;
1969 /* Add constraints to graph->lp that bound the dependence distance for the given
1970 * dependence from a node i to itself.
1971 * If s = 1, we add the constraint
1973 * c_i_x (y - x) <= m_0 + m_n n
1975 * or
1977 * -c_i_x (y - x) + m_0 + m_n n >= 0
1979 * for each (x,y) in R.
1980 * If s = -1, we add the constraint
1982 * -c_i_x (y - x) <= m_0 + m_n n
1984 * or
1986 * c_i_x (y - x) + m_0 + m_n n >= 0
1988 * for each (x,y) in R.
1989 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1990 * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
1991 * with each coefficient (except m_0) represented as a pair of non-negative
1992 * coefficients.
1995 * If "local" is set, then we add constraints
1997 * c_i_x (y - x) <= 0
1999 * or
2001 * -c_i_x (y - x) <= 0
2003 * instead, forcing the dependence distance to be (less than or) equal to 0.
2004 * That is, we plug in (0, 0, -s * c_i_x),
2005 * intra_coefficients is not required to have c_n in its result when
2006 * "local" is set. If they are missing, then (0, -s * c_i_x) is plugged in.
2007 * Note that dependences marked local are treated as validity constraints
2008 * by add_all_validity_constraints and therefore also have
2009 * their distances bounded by 0 from below.
2011 static isl_stat add_intra_proximity_constraints(struct isl_sched_graph *graph,
2012 struct isl_sched_edge *edge, int s, int local)
2014 int offset;
2015 unsigned nparam;
2016 isl_map *map = isl_map_copy(edge->map);
2017 isl_ctx *ctx = isl_map_get_ctx(map);
2018 isl_dim_map *dim_map;
2019 isl_basic_set *coef;
2020 struct isl_sched_node *node = edge->src;
2022 coef = intra_coefficients(graph, node, map, !local);
2024 offset = coef_var_offset(coef);
2026 if (!coef)
2027 return isl_stat_error;
2029 nparam = isl_space_dim(node->space, isl_dim_param);
2030 dim_map = intra_dim_map(ctx, graph, node, offset, -s);
2032 if (!local) {
2033 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
2034 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
2035 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
2037 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
2039 return isl_stat_ok;
2042 /* Add constraints to graph->lp that bound the dependence distance for the given
2043 * dependence from node i to node j.
2044 * If s = 1, we add the constraint
2046 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
2047 * <= m_0 + m_n n
2049 * or
2051 * -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
2052 * m_0 + m_n n >= 0
2054 * for each (x,y) in R.
2055 * If s = -1, we add the constraint
2057 * -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
2058 * <= m_0 + m_n n
2060 * or
2062 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
2063 * m_0 + m_n n >= 0
2065 * for each (x,y) in R.
2066 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
2067 * of valid constraints for R and then plug in
2068 * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
2069 * s*c_i_x, -s*c_j_x)
2070 * with each coefficient (except m_0, c_*_0 and c_*_n)
2071 * represented as a pair of non-negative coefficients.
2074 * If "local" is set (and s = 1), then we add constraints
2076 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) <= 0
2078 * or
2080 * -((c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x)) >= 0
2082 * instead, forcing the dependence distance to be (less than or) equal to 0.
2083 * That is, we plug in
2084 * (-s*c_j_0 + s*c_i_0, -s*c_j_n + s*c_i_n, s*c_i_x, -s*c_j_x).
2085 * Note that dependences marked local are treated as validity constraints
2086 * by add_all_validity_constraints and therefore also have
2087 * their distances bounded by 0 from below.
2089 static isl_stat add_inter_proximity_constraints(struct isl_sched_graph *graph,
2090 struct isl_sched_edge *edge, int s, int local)
2092 int offset;
2093 unsigned nparam;
2094 isl_map *map = isl_map_copy(edge->map);
2095 isl_ctx *ctx = isl_map_get_ctx(map);
2096 isl_dim_map *dim_map;
2097 isl_basic_set *coef;
2098 struct isl_sched_node *src = edge->src;
2099 struct isl_sched_node *dst = edge->dst;
2101 coef = inter_coefficients(graph, edge, map);
2103 offset = coef_var_offset(coef);
2105 if (!coef)
2106 return isl_stat_error;
2108 nparam = isl_space_dim(src->space, isl_dim_param);
2109 dim_map = inter_dim_map(ctx, graph, src, dst, offset, -s);
2111 if (!local) {
2112 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
2113 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
2114 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
2117 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
2119 return isl_stat_ok;
2122 /* Should the distance over "edge" be forced to zero?
2123 * That is, is it marked as a local edge?
2124 * If "use_coincidence" is set, then coincidence edges are treated
2125 * as local edges.
2127 static int force_zero(struct isl_sched_edge *edge, int use_coincidence)
2129 return is_local(edge) || (use_coincidence && is_coincidence(edge));
2132 /* Add all validity constraints to graph->lp.
2134 * An edge that is forced to be local needs to have its dependence
2135 * distances equal to zero. We take care of bounding them by 0 from below
2136 * here. add_all_proximity_constraints takes care of bounding them by 0
2137 * from above.
2139 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2140 * Otherwise, we ignore them.
2142 static int add_all_validity_constraints(struct isl_sched_graph *graph,
2143 int use_coincidence)
2145 int i;
2147 for (i = 0; i < graph->n_edge; ++i) {
2148 struct isl_sched_edge *edge = &graph->edge[i];
2149 int zero;
2151 zero = force_zero(edge, use_coincidence);
2152 if (!is_validity(edge) && !zero)
2153 continue;
2154 if (edge->src != edge->dst)
2155 continue;
2156 if (add_intra_validity_constraints(graph, edge) < 0)
2157 return -1;
2160 for (i = 0; i < graph->n_edge; ++i) {
2161 struct isl_sched_edge *edge = &graph->edge[i];
2162 int zero;
2164 zero = force_zero(edge, use_coincidence);
2165 if (!is_validity(edge) && !zero)
2166 continue;
2167 if (edge->src == edge->dst)
2168 continue;
2169 if (add_inter_validity_constraints(graph, edge) < 0)
2170 return -1;
2173 return 0;
2176 /* Add constraints to graph->lp that bound the dependence distance
2177 * for all dependence relations.
2178 * If a given proximity dependence is identical to a validity
2179 * dependence, then the dependence distance is already bounded
2180 * from below (by zero), so we only need to bound the distance
2181 * from above. (This includes the case of "local" dependences
2182 * which are treated as validity dependence by add_all_validity_constraints.)
2183 * Otherwise, we need to bound the distance both from above and from below.
2185 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2186 * Otherwise, we ignore them.
2188 static int add_all_proximity_constraints(struct isl_sched_graph *graph,
2189 int use_coincidence)
2191 int i;
2193 for (i = 0; i < graph->n_edge; ++i) {
2194 struct isl_sched_edge *edge = &graph->edge[i];
2195 int zero;
2197 zero = force_zero(edge, use_coincidence);
2198 if (!is_proximity(edge) && !zero)
2199 continue;
2200 if (edge->src == edge->dst &&
2201 add_intra_proximity_constraints(graph, edge, 1, zero) < 0)
2202 return -1;
2203 if (edge->src != edge->dst &&
2204 add_inter_proximity_constraints(graph, edge, 1, zero) < 0)
2205 return -1;
2206 if (is_validity(edge) || zero)
2207 continue;
2208 if (edge->src == edge->dst &&
2209 add_intra_proximity_constraints(graph, edge, -1, 0) < 0)
2210 return -1;
2211 if (edge->src != edge->dst &&
2212 add_inter_proximity_constraints(graph, edge, -1, 0) < 0)
2213 return -1;
2216 return 0;
2219 /* Normalize the rows of "indep" such that all rows are lexicographically
2220 * positive and such that each row contains as many final zeros as possible,
2221 * given the choice for the previous rows.
2222 * Do this by performing elementary row operations.
2224 static __isl_give isl_mat *normalize_independent(__isl_take isl_mat *indep)
2226 indep = isl_mat_reverse_gauss(indep);
2227 indep = isl_mat_lexnonneg_rows(indep);
2228 return indep;
2231 /* Compute a basis for the rows in the linear part of the schedule
2232 * and extend this basis to a full basis. The remaining rows
2233 * can then be used to force linear independence from the rows
2234 * in the schedule.
2236 * In particular, given the schedule rows S, we compute
2238 * S = H Q
2239 * S U = H
2241 * with H the Hermite normal form of S. That is, all but the
2242 * first rank columns of H are zero and so each row in S is
2243 * a linear combination of the first rank rows of Q.
2244 * The matrix Q can be used as a variable transformation
2245 * that isolates the directions of S in the first rank rows.
2246 * Transposing S U = H yields
2248 * U^T S^T = H^T
2250 * with all but the first rank rows of H^T zero.
2251 * The last rows of U^T are therefore linear combinations
2252 * of schedule coefficients that are all zero on schedule
2253 * coefficients that are linearly dependent on the rows of S.
2254 * At least one of these combinations is non-zero on
2255 * linearly independent schedule coefficients.
2256 * The rows are normalized to involve as few of the last
2257 * coefficients as possible and to have a positive initial value.
2259 static int node_update_vmap(struct isl_sched_node *node)
2261 isl_mat *H, *U, *Q;
2262 int n_row = isl_mat_rows(node->sched);
2264 H = isl_mat_sub_alloc(node->sched, 0, n_row,
2265 1 + node->nparam, node->nvar);
2267 H = isl_mat_left_hermite(H, 0, &U, &Q);
2268 isl_mat_free(node->indep);
2269 isl_mat_free(node->vmap);
2270 node->vmap = Q;
2271 node->indep = isl_mat_transpose(U);
2272 node->rank = isl_mat_initial_non_zero_cols(H);
2273 node->indep = isl_mat_drop_rows(node->indep, 0, node->rank);
2274 node->indep = normalize_independent(node->indep);
2275 isl_mat_free(H);
2277 if (!node->indep || !node->vmap || node->rank < 0)
2278 return -1;
2279 return 0;
2282 /* Is "edge" marked as a validity or a conditional validity edge?
2284 static int is_any_validity(struct isl_sched_edge *edge)
2286 return is_validity(edge) || is_conditional_validity(edge);
2289 /* How many times should we count the constraints in "edge"?
2291 * We count as follows
2292 * validity -> 1 (>= 0)
2293 * validity+proximity -> 2 (>= 0 and upper bound)
2294 * proximity -> 2 (lower and upper bound)
2295 * local(+any) -> 2 (>= 0 and <= 0)
2297 * If an edge is only marked conditional_validity then it counts
2298 * as zero since it is only checked afterwards.
2300 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2301 * Otherwise, we ignore them.
2303 static int edge_multiplicity(struct isl_sched_edge *edge, int use_coincidence)
2305 if (is_proximity(edge) || force_zero(edge, use_coincidence))
2306 return 2;
2307 if (is_validity(edge))
2308 return 1;
2309 return 0;
2312 /* How many times should the constraints in "edge" be counted
2313 * as a parametric intra-node constraint?
2315 * Only proximity edges that are not forced zero need
2316 * coefficient constraints that include coefficients for parameters.
2317 * If the edge is also a validity edge, then only
2318 * an upper bound is introduced. Otherwise, both lower and upper bounds
2319 * are introduced.
2321 static int parametric_intra_edge_multiplicity(struct isl_sched_edge *edge,
2322 int use_coincidence)
2324 if (edge->src != edge->dst)
2325 return 0;
2326 if (!is_proximity(edge))
2327 return 0;
2328 if (force_zero(edge, use_coincidence))
2329 return 0;
2330 if (is_validity(edge))
2331 return 1;
2332 else
2333 return 2;
2336 /* Add "f" times the number of equality and inequality constraints of "bset"
2337 * to "n_eq" and "n_ineq" and free "bset".
2339 static isl_stat update_count(__isl_take isl_basic_set *bset,
2340 int f, int *n_eq, int *n_ineq)
2342 if (!bset)
2343 return isl_stat_error;
2345 *n_eq += isl_basic_set_n_equality(bset);
2346 *n_ineq += isl_basic_set_n_inequality(bset);
2347 isl_basic_set_free(bset);
2349 return isl_stat_ok;
2352 /* Count the number of equality and inequality constraints
2353 * that will be added for the given map.
2355 * The edges that require parameter coefficients are counted separately.
2357 * "use_coincidence" is set if we should take into account coincidence edges.
2359 static isl_stat count_map_constraints(struct isl_sched_graph *graph,
2360 struct isl_sched_edge *edge, __isl_take isl_map *map,
2361 int *n_eq, int *n_ineq, int use_coincidence)
2363 isl_map *copy;
2364 isl_basic_set *coef;
2365 int f = edge_multiplicity(edge, use_coincidence);
2366 int fp = parametric_intra_edge_multiplicity(edge, use_coincidence);
2368 if (f == 0) {
2369 isl_map_free(map);
2370 return isl_stat_ok;
2373 if (edge->src != edge->dst) {
2374 coef = inter_coefficients(graph, edge, map);
2375 return update_count(coef, f, n_eq, n_ineq);
2378 if (fp > 0) {
2379 copy = isl_map_copy(map);
2380 coef = intra_coefficients(graph, edge->src, copy, 1);
2381 if (update_count(coef, fp, n_eq, n_ineq) < 0)
2382 goto error;
2385 if (f > fp) {
2386 copy = isl_map_copy(map);
2387 coef = intra_coefficients(graph, edge->src, copy, 0);
2388 if (update_count(coef, f - fp, n_eq, n_ineq) < 0)
2389 goto error;
2392 isl_map_free(map);
2393 return isl_stat_ok;
2394 error:
2395 isl_map_free(map);
2396 return isl_stat_error;
2399 /* Count the number of equality and inequality constraints
2400 * that will be added to the main lp problem.
2401 * We count as follows
2402 * validity -> 1 (>= 0)
2403 * validity+proximity -> 2 (>= 0 and upper bound)
2404 * proximity -> 2 (lower and upper bound)
2405 * local(+any) -> 2 (>= 0 and <= 0)
2407 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2408 * Otherwise, we ignore them.
2410 static int count_constraints(struct isl_sched_graph *graph,
2411 int *n_eq, int *n_ineq, int use_coincidence)
2413 int i;
2415 *n_eq = *n_ineq = 0;
2416 for (i = 0; i < graph->n_edge; ++i) {
2417 struct isl_sched_edge *edge = &graph->edge[i];
2418 isl_map *map = isl_map_copy(edge->map);
2420 if (count_map_constraints(graph, edge, map, n_eq, n_ineq,
2421 use_coincidence) < 0)
2422 return -1;
2425 return 0;
2428 /* Count the number of constraints that will be added by
2429 * add_bound_constant_constraints to bound the values of the constant terms
2430 * and increment *n_eq and *n_ineq accordingly.
2432 * In practice, add_bound_constant_constraints only adds inequalities.
2434 static isl_stat count_bound_constant_constraints(isl_ctx *ctx,
2435 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2437 if (isl_options_get_schedule_max_constant_term(ctx) == -1)
2438 return isl_stat_ok;
2440 *n_ineq += graph->n;
2442 return isl_stat_ok;
2445 /* Add constraints to bound the values of the constant terms in the schedule,
2446 * if requested by the user.
2448 * The maximal value of the constant terms is defined by the option
2449 * "schedule_max_constant_term".
2451 static isl_stat add_bound_constant_constraints(isl_ctx *ctx,
2452 struct isl_sched_graph *graph)
2454 int i, k;
2455 int max;
2456 int total;
2458 max = isl_options_get_schedule_max_constant_term(ctx);
2459 if (max == -1)
2460 return isl_stat_ok;
2462 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2464 for (i = 0; i < graph->n; ++i) {
2465 struct isl_sched_node *node = &graph->node[i];
2466 int pos;
2468 k = isl_basic_set_alloc_inequality(graph->lp);
2469 if (k < 0)
2470 return isl_stat_error;
2471 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2472 pos = node_cst_coef_offset(node);
2473 isl_int_set_si(graph->lp->ineq[k][1 + pos], -1);
2474 isl_int_set_si(graph->lp->ineq[k][0], max);
2477 return isl_stat_ok;
2480 /* Count the number of constraints that will be added by
2481 * add_bound_coefficient_constraints and increment *n_eq and *n_ineq
2482 * accordingly.
2484 * In practice, add_bound_coefficient_constraints only adds inequalities.
2486 static int count_bound_coefficient_constraints(isl_ctx *ctx,
2487 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2489 int i;
2491 if (isl_options_get_schedule_max_coefficient(ctx) == -1 &&
2492 !isl_options_get_schedule_treat_coalescing(ctx))
2493 return 0;
2495 for (i = 0; i < graph->n; ++i)
2496 *n_ineq += graph->node[i].nparam + 2 * graph->node[i].nvar;
2498 return 0;
2501 /* Add constraints to graph->lp that bound the values of
2502 * the parameter schedule coefficients of "node" to "max" and
2503 * the variable schedule coefficients to the corresponding entry
2504 * in node->max.
2505 * In either case, a negative value means that no bound needs to be imposed.
2507 * For parameter coefficients, this amounts to adding a constraint
2509 * c_n <= max
2511 * i.e.,
2513 * -c_n + max >= 0
2515 * The variables coefficients are, however, not represented directly.
2516 * Instead, the variable coefficients c_x are written as differences
2517 * c_x = c_x^+ - c_x^-.
2518 * That is,
2520 * -max_i <= c_x_i <= max_i
2522 * is encoded as
2524 * -max_i <= c_x_i^+ - c_x_i^- <= max_i
2526 * or
2528 * -(c_x_i^+ - c_x_i^-) + max_i >= 0
2529 * c_x_i^+ - c_x_i^- + max_i >= 0
2531 static isl_stat node_add_coefficient_constraints(isl_ctx *ctx,
2532 struct isl_sched_graph *graph, struct isl_sched_node *node, int max)
2534 int i, j, k;
2535 int total;
2536 isl_vec *ineq;
2538 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2540 for (j = 0; j < node->nparam; ++j) {
2541 int dim;
2543 if (max < 0)
2544 continue;
2546 k = isl_basic_set_alloc_inequality(graph->lp);
2547 if (k < 0)
2548 return isl_stat_error;
2549 dim = 1 + node_par_coef_offset(node) + j;
2550 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2551 isl_int_set_si(graph->lp->ineq[k][dim], -1);
2552 isl_int_set_si(graph->lp->ineq[k][0], max);
2555 ineq = isl_vec_alloc(ctx, 1 + total);
2556 ineq = isl_vec_clr(ineq);
2557 if (!ineq)
2558 return isl_stat_error;
2559 for (i = 0; i < node->nvar; ++i) {
2560 int pos = 1 + node_var_coef_pos(node, i);
2562 if (isl_int_is_neg(node->max->el[i]))
2563 continue;
2565 isl_int_set_si(ineq->el[pos], 1);
2566 isl_int_set_si(ineq->el[pos + 1], -1);
2567 isl_int_set(ineq->el[0], node->max->el[i]);
2569 k = isl_basic_set_alloc_inequality(graph->lp);
2570 if (k < 0)
2571 goto error;
2572 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2574 isl_seq_neg(ineq->el + pos, ineq->el + pos, 2);
2575 k = isl_basic_set_alloc_inequality(graph->lp);
2576 if (k < 0)
2577 goto error;
2578 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2580 isl_seq_clr(ineq->el + pos, 2);
2582 isl_vec_free(ineq);
2584 return isl_stat_ok;
2585 error:
2586 isl_vec_free(ineq);
2587 return isl_stat_error;
2590 /* Add constraints that bound the values of the variable and parameter
2591 * coefficients of the schedule.
2593 * The maximal value of the coefficients is defined by the option
2594 * 'schedule_max_coefficient' and the entries in node->max.
2595 * These latter entries are only set if either the schedule_max_coefficient
2596 * option or the schedule_treat_coalescing option is set.
2598 static isl_stat add_bound_coefficient_constraints(isl_ctx *ctx,
2599 struct isl_sched_graph *graph)
2601 int i;
2602 int max;
2604 max = isl_options_get_schedule_max_coefficient(ctx);
2606 if (max == -1 && !isl_options_get_schedule_treat_coalescing(ctx))
2607 return isl_stat_ok;
2609 for (i = 0; i < graph->n; ++i) {
2610 struct isl_sched_node *node = &graph->node[i];
2612 if (node_add_coefficient_constraints(ctx, graph, node, max) < 0)
2613 return isl_stat_error;
2616 return isl_stat_ok;
2619 /* Add a constraint to graph->lp that equates the value at position
2620 * "sum_pos" to the sum of the "n" values starting at "first".
2622 static isl_stat add_sum_constraint(struct isl_sched_graph *graph,
2623 int sum_pos, int first, int n)
2625 int i, k;
2626 int total;
2628 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2630 k = isl_basic_set_alloc_equality(graph->lp);
2631 if (k < 0)
2632 return isl_stat_error;
2633 isl_seq_clr(graph->lp->eq[k], 1 + total);
2634 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2635 for (i = 0; i < n; ++i)
2636 isl_int_set_si(graph->lp->eq[k][1 + first + i], 1);
2638 return isl_stat_ok;
2641 /* Add a constraint to graph->lp that equates the value at position
2642 * "sum_pos" to the sum of the parameter coefficients of all nodes.
2644 static isl_stat add_param_sum_constraint(struct isl_sched_graph *graph,
2645 int sum_pos)
2647 int i, j, k;
2648 int total;
2650 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2652 k = isl_basic_set_alloc_equality(graph->lp);
2653 if (k < 0)
2654 return isl_stat_error;
2655 isl_seq_clr(graph->lp->eq[k], 1 + total);
2656 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2657 for (i = 0; i < graph->n; ++i) {
2658 int pos = 1 + node_par_coef_offset(&graph->node[i]);
2660 for (j = 0; j < graph->node[i].nparam; ++j)
2661 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2664 return isl_stat_ok;
2667 /* Add a constraint to graph->lp that equates the value at position
2668 * "sum_pos" to the sum of the variable coefficients of all nodes.
2670 static isl_stat add_var_sum_constraint(struct isl_sched_graph *graph,
2671 int sum_pos)
2673 int i, j, k;
2674 int total;
2676 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2678 k = isl_basic_set_alloc_equality(graph->lp);
2679 if (k < 0)
2680 return isl_stat_error;
2681 isl_seq_clr(graph->lp->eq[k], 1 + total);
2682 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2683 for (i = 0; i < graph->n; ++i) {
2684 struct isl_sched_node *node = &graph->node[i];
2685 int pos = 1 + node_var_coef_offset(node);
2687 for (j = 0; j < 2 * node->nvar; ++j)
2688 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2691 return isl_stat_ok;
2694 /* Construct an ILP problem for finding schedule coefficients
2695 * that result in non-negative, but small dependence distances
2696 * over all dependences.
2697 * In particular, the dependence distances over proximity edges
2698 * are bounded by m_0 + m_n n and we compute schedule coefficients
2699 * with small values (preferably zero) of m_n and m_0.
2701 * All variables of the ILP are non-negative. The actual coefficients
2702 * may be negative, so each coefficient is represented as the difference
2703 * of two non-negative variables. The negative part always appears
2704 * immediately before the positive part.
2705 * Other than that, the variables have the following order
2707 * - sum of positive and negative parts of m_n coefficients
2708 * - m_0
2709 * - sum of all c_n coefficients
2710 * (unconstrained when computing non-parametric schedules)
2711 * - sum of positive and negative parts of all c_x coefficients
2712 * - positive and negative parts of m_n coefficients
2713 * - for each node
2714 * - positive and negative parts of c_i_x, in opposite order
2715 * - c_i_n (if parametric)
2716 * - c_i_0
2718 * The constraints are those from the edges plus two or three equalities
2719 * to express the sums.
2721 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2722 * Otherwise, we ignore them.
2724 static isl_stat setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
2725 int use_coincidence)
2727 int i;
2728 unsigned nparam;
2729 unsigned total;
2730 isl_space *space;
2731 int parametric;
2732 int param_pos;
2733 int n_eq, n_ineq;
2735 parametric = ctx->opt->schedule_parametric;
2736 nparam = isl_space_dim(graph->node[0].space, isl_dim_param);
2737 param_pos = 4;
2738 total = param_pos + 2 * nparam;
2739 for (i = 0; i < graph->n; ++i) {
2740 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2741 if (node_update_vmap(node) < 0)
2742 return isl_stat_error;
2743 node->start = total;
2744 total += 1 + node->nparam + 2 * node->nvar;
2747 if (count_constraints(graph, &n_eq, &n_ineq, use_coincidence) < 0)
2748 return isl_stat_error;
2749 if (count_bound_constant_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2750 return isl_stat_error;
2751 if (count_bound_coefficient_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2752 return isl_stat_error;
2754 space = isl_space_set_alloc(ctx, 0, total);
2755 isl_basic_set_free(graph->lp);
2756 n_eq += 2 + parametric;
2758 graph->lp = isl_basic_set_alloc_space(space, 0, n_eq, n_ineq);
2760 if (add_sum_constraint(graph, 0, param_pos, 2 * nparam) < 0)
2761 return isl_stat_error;
2762 if (parametric && add_param_sum_constraint(graph, 2) < 0)
2763 return isl_stat_error;
2764 if (add_var_sum_constraint(graph, 3) < 0)
2765 return isl_stat_error;
2766 if (add_bound_constant_constraints(ctx, graph) < 0)
2767 return isl_stat_error;
2768 if (add_bound_coefficient_constraints(ctx, graph) < 0)
2769 return isl_stat_error;
2770 if (add_all_validity_constraints(graph, use_coincidence) < 0)
2771 return isl_stat_error;
2772 if (add_all_proximity_constraints(graph, use_coincidence) < 0)
2773 return isl_stat_error;
2775 return isl_stat_ok;
2778 /* Analyze the conflicting constraint found by
2779 * isl_tab_basic_set_non_trivial_lexmin. If it corresponds to the validity
2780 * constraint of one of the edges between distinct nodes, living, moreover
2781 * in distinct SCCs, then record the source and sink SCC as this may
2782 * be a good place to cut between SCCs.
2784 static int check_conflict(int con, void *user)
2786 int i;
2787 struct isl_sched_graph *graph = user;
2789 if (graph->src_scc >= 0)
2790 return 0;
2792 con -= graph->lp->n_eq;
2794 if (con >= graph->lp->n_ineq)
2795 return 0;
2797 for (i = 0; i < graph->n_edge; ++i) {
2798 if (!is_validity(&graph->edge[i]))
2799 continue;
2800 if (graph->edge[i].src == graph->edge[i].dst)
2801 continue;
2802 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
2803 continue;
2804 if (graph->edge[i].start > con)
2805 continue;
2806 if (graph->edge[i].end <= con)
2807 continue;
2808 graph->src_scc = graph->edge[i].src->scc;
2809 graph->dst_scc = graph->edge[i].dst->scc;
2812 return 0;
2815 /* Check whether the next schedule row of the given node needs to be
2816 * non-trivial. Lower-dimensional domains may have some trivial rows,
2817 * but as soon as the number of remaining required non-trivial rows
2818 * is as large as the number or remaining rows to be computed,
2819 * all remaining rows need to be non-trivial.
2821 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
2823 return node->nvar - node->rank >= graph->maxvar - graph->n_row;
2826 /* Construct a non-triviality region with triviality directions
2827 * corresponding to the rows of "indep".
2828 * The rows of "indep" are expressed in terms of the schedule coefficients c_i,
2829 * while the triviality directions are expressed in terms of
2830 * pairs of non-negative variables c^+_i - c^-_i, with c^-_i appearing
2831 * before c^+_i. Furthermore,
2832 * the pairs of non-negative variables representing the coefficients
2833 * are stored in the opposite order.
2835 static __isl_give isl_mat *construct_trivial(__isl_keep isl_mat *indep)
2837 isl_ctx *ctx;
2838 isl_mat *mat;
2839 int i, j, n, n_var;
2841 if (!indep)
2842 return NULL;
2844 ctx = isl_mat_get_ctx(indep);
2845 n = isl_mat_rows(indep);
2846 n_var = isl_mat_cols(indep);
2847 mat = isl_mat_alloc(ctx, n, 2 * n_var);
2848 if (!mat)
2849 return NULL;
2850 for (i = 0; i < n; ++i) {
2851 for (j = 0; j < n_var; ++j) {
2852 int nj = n_var - 1 - j;
2853 isl_int_neg(mat->row[i][2 * nj], indep->row[i][j]);
2854 isl_int_set(mat->row[i][2 * nj + 1], indep->row[i][j]);
2858 return mat;
2861 /* Solve the ILP problem constructed in setup_lp.
2862 * For each node such that all the remaining rows of its schedule
2863 * need to be non-trivial, we construct a non-triviality region.
2864 * This region imposes that the next row is independent of previous rows.
2865 * In particular, the non-triviality region enforces that at least
2866 * one of the linear combinations in the rows of node->indep is non-zero.
2868 static __isl_give isl_vec *solve_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
2870 int i;
2871 isl_vec *sol;
2872 isl_basic_set *lp;
2874 for (i = 0; i < graph->n; ++i) {
2875 struct isl_sched_node *node = &graph->node[i];
2876 isl_mat *trivial;
2878 graph->region[i].pos = node_var_coef_offset(node);
2879 if (needs_row(graph, node))
2880 trivial = construct_trivial(node->indep);
2881 else
2882 trivial = isl_mat_zero(ctx, 0, 0);
2883 graph->region[i].trivial = trivial;
2885 lp = isl_basic_set_copy(graph->lp);
2886 sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
2887 graph->region, &check_conflict, graph);
2888 for (i = 0; i < graph->n; ++i)
2889 isl_mat_free(graph->region[i].trivial);
2890 return sol;
2893 /* Extract the coefficients for the variables of "node" from "sol".
2895 * Each schedule coefficient c_i_x is represented as the difference
2896 * between two non-negative variables c_i_x^+ - c_i_x^-.
2897 * The c_i_x^- appear before their c_i_x^+ counterpart.
2898 * Furthermore, the order of these pairs is the opposite of that
2899 * of the corresponding coefficients.
2901 * Return c_i_x = c_i_x^+ - c_i_x^-
2903 static __isl_give isl_vec *extract_var_coef(struct isl_sched_node *node,
2904 __isl_keep isl_vec *sol)
2906 int i;
2907 int pos;
2908 isl_vec *csol;
2910 if (!sol)
2911 return NULL;
2912 csol = isl_vec_alloc(isl_vec_get_ctx(sol), node->nvar);
2913 if (!csol)
2914 return NULL;
2916 pos = 1 + node_var_coef_offset(node);
2917 for (i = 0; i < node->nvar; ++i)
2918 isl_int_sub(csol->el[node->nvar - 1 - i],
2919 sol->el[pos + 2 * i + 1], sol->el[pos + 2 * i]);
2921 return csol;
2924 /* Update the schedules of all nodes based on the given solution
2925 * of the LP problem.
2926 * The new row is added to the current band.
2927 * All possibly negative coefficients are encoded as a difference
2928 * of two non-negative variables, so we need to perform the subtraction
2929 * here.
2931 * If coincident is set, then the caller guarantees that the new
2932 * row satisfies the coincidence constraints.
2934 static int update_schedule(struct isl_sched_graph *graph,
2935 __isl_take isl_vec *sol, int coincident)
2937 int i, j;
2938 isl_vec *csol = NULL;
2940 if (!sol)
2941 goto error;
2942 if (sol->size == 0)
2943 isl_die(sol->ctx, isl_error_internal,
2944 "no solution found", goto error);
2945 if (graph->n_total_row >= graph->max_row)
2946 isl_die(sol->ctx, isl_error_internal,
2947 "too many schedule rows", goto error);
2949 for (i = 0; i < graph->n; ++i) {
2950 struct isl_sched_node *node = &graph->node[i];
2951 int pos;
2952 int row = isl_mat_rows(node->sched);
2954 isl_vec_free(csol);
2955 csol = extract_var_coef(node, sol);
2956 if (!csol)
2957 goto error;
2959 isl_map_free(node->sched_map);
2960 node->sched_map = NULL;
2961 node->sched = isl_mat_add_rows(node->sched, 1);
2962 if (!node->sched)
2963 goto error;
2964 pos = node_cst_coef_offset(node);
2965 node->sched = isl_mat_set_element(node->sched,
2966 row, 0, sol->el[1 + pos]);
2967 pos = node_par_coef_offset(node);
2968 for (j = 0; j < node->nparam; ++j)
2969 node->sched = isl_mat_set_element(node->sched,
2970 row, 1 + j, sol->el[1 + pos + j]);
2971 for (j = 0; j < node->nvar; ++j)
2972 node->sched = isl_mat_set_element(node->sched,
2973 row, 1 + node->nparam + j, csol->el[j]);
2974 node->coincident[graph->n_total_row] = coincident;
2976 isl_vec_free(sol);
2977 isl_vec_free(csol);
2979 graph->n_row++;
2980 graph->n_total_row++;
2982 return 0;
2983 error:
2984 isl_vec_free(sol);
2985 isl_vec_free(csol);
2986 return -1;
2989 /* Convert row "row" of node->sched into an isl_aff living in "ls"
2990 * and return this isl_aff.
2992 static __isl_give isl_aff *extract_schedule_row(__isl_take isl_local_space *ls,
2993 struct isl_sched_node *node, int row)
2995 int j;
2996 isl_int v;
2997 isl_aff *aff;
2999 isl_int_init(v);
3001 aff = isl_aff_zero_on_domain(ls);
3002 if (isl_mat_get_element(node->sched, row, 0, &v) < 0)
3003 goto error;
3004 aff = isl_aff_set_constant(aff, v);
3005 for (j = 0; j < node->nparam; ++j) {
3006 if (isl_mat_get_element(node->sched, row, 1 + j, &v) < 0)
3007 goto error;
3008 aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
3010 for (j = 0; j < node->nvar; ++j) {
3011 if (isl_mat_get_element(node->sched, row,
3012 1 + node->nparam + j, &v) < 0)
3013 goto error;
3014 aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
3017 isl_int_clear(v);
3019 return aff;
3020 error:
3021 isl_int_clear(v);
3022 isl_aff_free(aff);
3023 return NULL;
3026 /* Convert the "n" rows starting at "first" of node->sched into a multi_aff
3027 * and return this multi_aff.
3029 * The result is defined over the uncompressed node domain.
3031 static __isl_give isl_multi_aff *node_extract_partial_schedule_multi_aff(
3032 struct isl_sched_node *node, int first, int n)
3034 int i;
3035 isl_space *space;
3036 isl_local_space *ls;
3037 isl_aff *aff;
3038 isl_multi_aff *ma;
3039 int nrow;
3041 if (!node)
3042 return NULL;
3043 nrow = isl_mat_rows(node->sched);
3044 if (node->compressed)
3045 space = isl_multi_aff_get_domain_space(node->decompress);
3046 else
3047 space = isl_space_copy(node->space);
3048 ls = isl_local_space_from_space(isl_space_copy(space));
3049 space = isl_space_from_domain(space);
3050 space = isl_space_add_dims(space, isl_dim_out, n);
3051 ma = isl_multi_aff_zero(space);
3053 for (i = first; i < first + n; ++i) {
3054 aff = extract_schedule_row(isl_local_space_copy(ls), node, i);
3055 ma = isl_multi_aff_set_aff(ma, i - first, aff);
3058 isl_local_space_free(ls);
3060 if (node->compressed)
3061 ma = isl_multi_aff_pullback_multi_aff(ma,
3062 isl_multi_aff_copy(node->compress));
3064 return ma;
3067 /* Convert node->sched into a multi_aff and return this multi_aff.
3069 * The result is defined over the uncompressed node domain.
3071 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
3072 struct isl_sched_node *node)
3074 int nrow;
3076 nrow = isl_mat_rows(node->sched);
3077 return node_extract_partial_schedule_multi_aff(node, 0, nrow);
3080 /* Convert node->sched into a map and return this map.
3082 * The result is cached in node->sched_map, which needs to be released
3083 * whenever node->sched is updated.
3084 * It is defined over the uncompressed node domain.
3086 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
3088 if (!node->sched_map) {
3089 isl_multi_aff *ma;
3091 ma = node_extract_schedule_multi_aff(node);
3092 node->sched_map = isl_map_from_multi_aff(ma);
3095 return isl_map_copy(node->sched_map);
3098 /* Construct a map that can be used to update a dependence relation
3099 * based on the current schedule.
3100 * That is, construct a map expressing that source and sink
3101 * are executed within the same iteration of the current schedule.
3102 * This map can then be intersected with the dependence relation.
3103 * This is not the most efficient way, but this shouldn't be a critical
3104 * operation.
3106 static __isl_give isl_map *specializer(struct isl_sched_node *src,
3107 struct isl_sched_node *dst)
3109 isl_map *src_sched, *dst_sched;
3111 src_sched = node_extract_schedule(src);
3112 dst_sched = node_extract_schedule(dst);
3113 return isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
3116 /* Intersect the domains of the nested relations in domain and range
3117 * of "umap" with "map".
3119 static __isl_give isl_union_map *intersect_domains(
3120 __isl_take isl_union_map *umap, __isl_keep isl_map *map)
3122 isl_union_set *uset;
3124 umap = isl_union_map_zip(umap);
3125 uset = isl_union_set_from_set(isl_map_wrap(isl_map_copy(map)));
3126 umap = isl_union_map_intersect_domain(umap, uset);
3127 umap = isl_union_map_zip(umap);
3128 return umap;
3131 /* Update the dependence relation of the given edge based
3132 * on the current schedule.
3133 * If the dependence is carried completely by the current schedule, then
3134 * it is removed from the edge_tables. It is kept in the list of edges
3135 * as otherwise all edge_tables would have to be recomputed.
3137 * If the edge is of a type that can appear multiple times
3138 * between the same pair of nodes, then it is added to
3139 * the edge table (again). This prevents the situation
3140 * where none of these edges is referenced from the edge table
3141 * because the one that was referenced turned out to be empty and
3142 * was therefore removed from the table.
3144 static int update_edge(isl_ctx *ctx, struct isl_sched_graph *graph,
3145 struct isl_sched_edge *edge)
3147 int empty;
3148 isl_map *id;
3150 id = specializer(edge->src, edge->dst);
3151 edge->map = isl_map_intersect(edge->map, isl_map_copy(id));
3152 if (!edge->map)
3153 goto error;
3155 if (edge->tagged_condition) {
3156 edge->tagged_condition =
3157 intersect_domains(edge->tagged_condition, id);
3158 if (!edge->tagged_condition)
3159 goto error;
3161 if (edge->tagged_validity) {
3162 edge->tagged_validity =
3163 intersect_domains(edge->tagged_validity, id);
3164 if (!edge->tagged_validity)
3165 goto error;
3168 empty = isl_map_plain_is_empty(edge->map);
3169 if (empty < 0)
3170 goto error;
3171 if (empty) {
3172 graph_remove_edge(graph, edge);
3173 } else if (is_multi_edge_type(edge)) {
3174 if (graph_edge_tables_add(ctx, graph, edge) < 0)
3175 goto error;
3178 isl_map_free(id);
3179 return 0;
3180 error:
3181 isl_map_free(id);
3182 return -1;
3185 /* Does the domain of "umap" intersect "uset"?
3187 static int domain_intersects(__isl_keep isl_union_map *umap,
3188 __isl_keep isl_union_set *uset)
3190 int empty;
3192 umap = isl_union_map_copy(umap);
3193 umap = isl_union_map_intersect_domain(umap, isl_union_set_copy(uset));
3194 empty = isl_union_map_is_empty(umap);
3195 isl_union_map_free(umap);
3197 return empty < 0 ? -1 : !empty;
3200 /* Does the range of "umap" intersect "uset"?
3202 static int range_intersects(__isl_keep isl_union_map *umap,
3203 __isl_keep isl_union_set *uset)
3205 int empty;
3207 umap = isl_union_map_copy(umap);
3208 umap = isl_union_map_intersect_range(umap, isl_union_set_copy(uset));
3209 empty = isl_union_map_is_empty(umap);
3210 isl_union_map_free(umap);
3212 return empty < 0 ? -1 : !empty;
3215 /* Are the condition dependences of "edge" local with respect to
3216 * the current schedule?
3218 * That is, are domain and range of the condition dependences mapped
3219 * to the same point?
3221 * In other words, is the condition false?
3223 static int is_condition_false(struct isl_sched_edge *edge)
3225 isl_union_map *umap;
3226 isl_map *map, *sched, *test;
3227 int empty, local;
3229 empty = isl_union_map_is_empty(edge->tagged_condition);
3230 if (empty < 0 || empty)
3231 return empty;
3233 umap = isl_union_map_copy(edge->tagged_condition);
3234 umap = isl_union_map_zip(umap);
3235 umap = isl_union_set_unwrap(isl_union_map_domain(umap));
3236 map = isl_map_from_union_map(umap);
3238 sched = node_extract_schedule(edge->src);
3239 map = isl_map_apply_domain(map, sched);
3240 sched = node_extract_schedule(edge->dst);
3241 map = isl_map_apply_range(map, sched);
3243 test = isl_map_identity(isl_map_get_space(map));
3244 local = isl_map_is_subset(map, test);
3245 isl_map_free(map);
3246 isl_map_free(test);
3248 return local;
3251 /* For each conditional validity constraint that is adjacent
3252 * to a condition with domain in condition_source or range in condition_sink,
3253 * turn it into an unconditional validity constraint.
3255 static int unconditionalize_adjacent_validity(struct isl_sched_graph *graph,
3256 __isl_take isl_union_set *condition_source,
3257 __isl_take isl_union_set *condition_sink)
3259 int i;
3261 condition_source = isl_union_set_coalesce(condition_source);
3262 condition_sink = isl_union_set_coalesce(condition_sink);
3264 for (i = 0; i < graph->n_edge; ++i) {
3265 int adjacent;
3266 isl_union_map *validity;
3268 if (!is_conditional_validity(&graph->edge[i]))
3269 continue;
3270 if (is_validity(&graph->edge[i]))
3271 continue;
3273 validity = graph->edge[i].tagged_validity;
3274 adjacent = domain_intersects(validity, condition_sink);
3275 if (adjacent >= 0 && !adjacent)
3276 adjacent = range_intersects(validity, condition_source);
3277 if (adjacent < 0)
3278 goto error;
3279 if (!adjacent)
3280 continue;
3282 set_validity(&graph->edge[i]);
3285 isl_union_set_free(condition_source);
3286 isl_union_set_free(condition_sink);
3287 return 0;
3288 error:
3289 isl_union_set_free(condition_source);
3290 isl_union_set_free(condition_sink);
3291 return -1;
3294 /* Update the dependence relations of all edges based on the current schedule
3295 * and enforce conditional validity constraints that are adjacent
3296 * to satisfied condition constraints.
3298 * First check if any of the condition constraints are satisfied
3299 * (i.e., not local to the outer schedule) and keep track of
3300 * their domain and range.
3301 * Then update all dependence relations (which removes the non-local
3302 * constraints).
3303 * Finally, if any condition constraints turned out to be satisfied,
3304 * then turn all adjacent conditional validity constraints into
3305 * unconditional validity constraints.
3307 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
3309 int i;
3310 int any = 0;
3311 isl_union_set *source, *sink;
3313 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3314 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3315 for (i = 0; i < graph->n_edge; ++i) {
3316 int local;
3317 isl_union_set *uset;
3318 isl_union_map *umap;
3320 if (!is_condition(&graph->edge[i]))
3321 continue;
3322 if (is_local(&graph->edge[i]))
3323 continue;
3324 local = is_condition_false(&graph->edge[i]);
3325 if (local < 0)
3326 goto error;
3327 if (local)
3328 continue;
3330 any = 1;
3332 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3333 uset = isl_union_map_domain(umap);
3334 source = isl_union_set_union(source, uset);
3336 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3337 uset = isl_union_map_range(umap);
3338 sink = isl_union_set_union(sink, uset);
3341 for (i = 0; i < graph->n_edge; ++i) {
3342 if (update_edge(ctx, graph, &graph->edge[i]) < 0)
3343 goto error;
3346 if (any)
3347 return unconditionalize_adjacent_validity(graph, source, sink);
3349 isl_union_set_free(source);
3350 isl_union_set_free(sink);
3351 return 0;
3352 error:
3353 isl_union_set_free(source);
3354 isl_union_set_free(sink);
3355 return -1;
3358 static void next_band(struct isl_sched_graph *graph)
3360 graph->band_start = graph->n_total_row;
3363 /* Return the union of the universe domains of the nodes in "graph"
3364 * that satisfy "pred".
3366 static __isl_give isl_union_set *isl_sched_graph_domain(isl_ctx *ctx,
3367 struct isl_sched_graph *graph,
3368 int (*pred)(struct isl_sched_node *node, int data), int data)
3370 int i;
3371 isl_set *set;
3372 isl_union_set *dom;
3374 for (i = 0; i < graph->n; ++i)
3375 if (pred(&graph->node[i], data))
3376 break;
3378 if (i >= graph->n)
3379 isl_die(ctx, isl_error_internal,
3380 "empty component", return NULL);
3382 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3383 dom = isl_union_set_from_set(set);
3385 for (i = i + 1; i < graph->n; ++i) {
3386 if (!pred(&graph->node[i], data))
3387 continue;
3388 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3389 dom = isl_union_set_union(dom, isl_union_set_from_set(set));
3392 return dom;
3395 /* Return a list of unions of universe domains, where each element
3396 * in the list corresponds to an SCC (or WCC) indexed by node->scc.
3398 static __isl_give isl_union_set_list *extract_sccs(isl_ctx *ctx,
3399 struct isl_sched_graph *graph)
3401 int i;
3402 isl_union_set_list *filters;
3404 filters = isl_union_set_list_alloc(ctx, graph->scc);
3405 for (i = 0; i < graph->scc; ++i) {
3406 isl_union_set *dom;
3408 dom = isl_sched_graph_domain(ctx, graph, &node_scc_exactly, i);
3409 filters = isl_union_set_list_add(filters, dom);
3412 return filters;
3415 /* Return a list of two unions of universe domains, one for the SCCs up
3416 * to and including graph->src_scc and another for the other SCCs.
3418 static __isl_give isl_union_set_list *extract_split(isl_ctx *ctx,
3419 struct isl_sched_graph *graph)
3421 isl_union_set *dom;
3422 isl_union_set_list *filters;
3424 filters = isl_union_set_list_alloc(ctx, 2);
3425 dom = isl_sched_graph_domain(ctx, graph,
3426 &node_scc_at_most, graph->src_scc);
3427 filters = isl_union_set_list_add(filters, dom);
3428 dom = isl_sched_graph_domain(ctx, graph,
3429 &node_scc_at_least, graph->src_scc + 1);
3430 filters = isl_union_set_list_add(filters, dom);
3432 return filters;
3435 /* Copy nodes that satisfy node_pred from the src dependence graph
3436 * to the dst dependence graph.
3438 static isl_stat copy_nodes(struct isl_sched_graph *dst,
3439 struct isl_sched_graph *src,
3440 int (*node_pred)(struct isl_sched_node *node, int data), int data)
3442 int i;
3444 dst->n = 0;
3445 for (i = 0; i < src->n; ++i) {
3446 int j;
3448 if (!node_pred(&src->node[i], data))
3449 continue;
3451 j = dst->n;
3452 dst->node[j].space = isl_space_copy(src->node[i].space);
3453 dst->node[j].compressed = src->node[i].compressed;
3454 dst->node[j].hull = isl_set_copy(src->node[i].hull);
3455 dst->node[j].compress =
3456 isl_multi_aff_copy(src->node[i].compress);
3457 dst->node[j].decompress =
3458 isl_multi_aff_copy(src->node[i].decompress);
3459 dst->node[j].nvar = src->node[i].nvar;
3460 dst->node[j].nparam = src->node[i].nparam;
3461 dst->node[j].sched = isl_mat_copy(src->node[i].sched);
3462 dst->node[j].sched_map = isl_map_copy(src->node[i].sched_map);
3463 dst->node[j].coincident = src->node[i].coincident;
3464 dst->node[j].sizes = isl_multi_val_copy(src->node[i].sizes);
3465 dst->node[j].bounds = isl_basic_set_copy(src->node[i].bounds);
3466 dst->node[j].max = isl_vec_copy(src->node[i].max);
3467 dst->n++;
3469 if (!dst->node[j].space || !dst->node[j].sched)
3470 return isl_stat_error;
3471 if (dst->node[j].compressed &&
3472 (!dst->node[j].hull || !dst->node[j].compress ||
3473 !dst->node[j].decompress))
3474 return isl_stat_error;
3477 return isl_stat_ok;
3480 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
3481 * to the dst dependence graph.
3482 * If the source or destination node of the edge is not in the destination
3483 * graph, then it must be a backward proximity edge and it should simply
3484 * be ignored.
3486 static int copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
3487 struct isl_sched_graph *src,
3488 int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
3490 int i;
3492 dst->n_edge = 0;
3493 for (i = 0; i < src->n_edge; ++i) {
3494 struct isl_sched_edge *edge = &src->edge[i];
3495 isl_map *map;
3496 isl_union_map *tagged_condition;
3497 isl_union_map *tagged_validity;
3498 struct isl_sched_node *dst_src, *dst_dst;
3500 if (!edge_pred(edge, data))
3501 continue;
3503 if (isl_map_plain_is_empty(edge->map))
3504 continue;
3506 dst_src = graph_find_node(ctx, dst, edge->src->space);
3507 dst_dst = graph_find_node(ctx, dst, edge->dst->space);
3508 if (!dst_src || !dst_dst) {
3509 if (is_validity(edge) || is_conditional_validity(edge))
3510 isl_die(ctx, isl_error_internal,
3511 "backward (conditional) validity edge",
3512 return -1);
3513 continue;
3516 map = isl_map_copy(edge->map);
3517 tagged_condition = isl_union_map_copy(edge->tagged_condition);
3518 tagged_validity = isl_union_map_copy(edge->tagged_validity);
3520 dst->edge[dst->n_edge].src = dst_src;
3521 dst->edge[dst->n_edge].dst = dst_dst;
3522 dst->edge[dst->n_edge].map = map;
3523 dst->edge[dst->n_edge].tagged_condition = tagged_condition;
3524 dst->edge[dst->n_edge].tagged_validity = tagged_validity;
3525 dst->edge[dst->n_edge].types = edge->types;
3526 dst->n_edge++;
3528 if (edge->tagged_condition && !tagged_condition)
3529 return -1;
3530 if (edge->tagged_validity && !tagged_validity)
3531 return -1;
3533 if (graph_edge_tables_add(ctx, dst,
3534 &dst->edge[dst->n_edge - 1]) < 0)
3535 return -1;
3538 return 0;
3541 /* Compute the maximal number of variables over all nodes.
3542 * This is the maximal number of linearly independent schedule
3543 * rows that we need to compute.
3544 * Just in case we end up in a part of the dependence graph
3545 * with only lower-dimensional domains, we make sure we will
3546 * compute the required amount of extra linearly independent rows.
3548 static int compute_maxvar(struct isl_sched_graph *graph)
3550 int i;
3552 graph->maxvar = 0;
3553 for (i = 0; i < graph->n; ++i) {
3554 struct isl_sched_node *node = &graph->node[i];
3555 int nvar;
3557 if (node_update_vmap(node) < 0)
3558 return -1;
3559 nvar = node->nvar + graph->n_row - node->rank;
3560 if (nvar > graph->maxvar)
3561 graph->maxvar = nvar;
3564 return 0;
3567 /* Extract the subgraph of "graph" that consists of the nodes satisfying
3568 * "node_pred" and the edges satisfying "edge_pred" and store
3569 * the result in "sub".
3571 static int extract_sub_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
3572 int (*node_pred)(struct isl_sched_node *node, int data),
3573 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3574 int data, struct isl_sched_graph *sub)
3576 int i, n = 0, n_edge = 0;
3577 int t;
3579 for (i = 0; i < graph->n; ++i)
3580 if (node_pred(&graph->node[i], data))
3581 ++n;
3582 for (i = 0; i < graph->n_edge; ++i)
3583 if (edge_pred(&graph->edge[i], data))
3584 ++n_edge;
3585 if (graph_alloc(ctx, sub, n, n_edge) < 0)
3586 return -1;
3587 sub->root = graph->root;
3588 if (copy_nodes(sub, graph, node_pred, data) < 0)
3589 return -1;
3590 if (graph_init_table(ctx, sub) < 0)
3591 return -1;
3592 for (t = 0; t <= isl_edge_last; ++t)
3593 sub->max_edge[t] = graph->max_edge[t];
3594 if (graph_init_edge_tables(ctx, sub) < 0)
3595 return -1;
3596 if (copy_edges(ctx, sub, graph, edge_pred, data) < 0)
3597 return -1;
3598 sub->n_row = graph->n_row;
3599 sub->max_row = graph->max_row;
3600 sub->n_total_row = graph->n_total_row;
3601 sub->band_start = graph->band_start;
3603 return 0;
3606 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
3607 struct isl_sched_graph *graph);
3608 static __isl_give isl_schedule_node *compute_schedule_wcc(
3609 isl_schedule_node *node, struct isl_sched_graph *graph);
3611 /* Compute a schedule for a subgraph of "graph". In particular, for
3612 * the graph composed of nodes that satisfy node_pred and edges that
3613 * that satisfy edge_pred.
3614 * If the subgraph is known to consist of a single component, then wcc should
3615 * be set and then we call compute_schedule_wcc on the constructed subgraph.
3616 * Otherwise, we call compute_schedule, which will check whether the subgraph
3617 * is connected.
3619 * The schedule is inserted at "node" and the updated schedule node
3620 * is returned.
3622 static __isl_give isl_schedule_node *compute_sub_schedule(
3623 __isl_take isl_schedule_node *node, isl_ctx *ctx,
3624 struct isl_sched_graph *graph,
3625 int (*node_pred)(struct isl_sched_node *node, int data),
3626 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3627 int data, int wcc)
3629 struct isl_sched_graph split = { 0 };
3631 if (extract_sub_graph(ctx, graph, node_pred, edge_pred, data,
3632 &split) < 0)
3633 goto error;
3635 if (wcc)
3636 node = compute_schedule_wcc(node, &split);
3637 else
3638 node = compute_schedule(node, &split);
3640 graph_free(ctx, &split);
3641 return node;
3642 error:
3643 graph_free(ctx, &split);
3644 return isl_schedule_node_free(node);
3647 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
3649 return edge->src->scc == scc && edge->dst->scc == scc;
3652 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
3654 return edge->dst->scc <= scc;
3657 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
3659 return edge->src->scc >= scc;
3662 /* Reset the current band by dropping all its schedule rows.
3664 static isl_stat reset_band(struct isl_sched_graph *graph)
3666 int i;
3667 int drop;
3669 drop = graph->n_total_row - graph->band_start;
3670 graph->n_total_row -= drop;
3671 graph->n_row -= drop;
3673 for (i = 0; i < graph->n; ++i) {
3674 struct isl_sched_node *node = &graph->node[i];
3676 isl_map_free(node->sched_map);
3677 node->sched_map = NULL;
3679 node->sched = isl_mat_drop_rows(node->sched,
3680 graph->band_start, drop);
3682 if (!node->sched)
3683 return isl_stat_error;
3686 return isl_stat_ok;
3689 /* Split the current graph into two parts and compute a schedule for each
3690 * part individually. In particular, one part consists of all SCCs up
3691 * to and including graph->src_scc, while the other part contains the other
3692 * SCCs. The split is enforced by a sequence node inserted at position "node"
3693 * in the schedule tree. Return the updated schedule node.
3694 * If either of these two parts consists of a sequence, then it is spliced
3695 * into the sequence containing the two parts.
3697 * The current band is reset. It would be possible to reuse
3698 * the previously computed rows as the first rows in the next
3699 * band, but recomputing them may result in better rows as we are looking
3700 * at a smaller part of the dependence graph.
3702 static __isl_give isl_schedule_node *compute_split_schedule(
3703 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3705 int is_seq;
3706 isl_ctx *ctx;
3707 isl_union_set_list *filters;
3709 if (!node)
3710 return NULL;
3712 if (reset_band(graph) < 0)
3713 return isl_schedule_node_free(node);
3715 next_band(graph);
3717 ctx = isl_schedule_node_get_ctx(node);
3718 filters = extract_split(ctx, graph);
3719 node = isl_schedule_node_insert_sequence(node, filters);
3720 node = isl_schedule_node_child(node, 1);
3721 node = isl_schedule_node_child(node, 0);
3723 node = compute_sub_schedule(node, ctx, graph,
3724 &node_scc_at_least, &edge_src_scc_at_least,
3725 graph->src_scc + 1, 0);
3726 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3727 node = isl_schedule_node_parent(node);
3728 node = isl_schedule_node_parent(node);
3729 if (is_seq)
3730 node = isl_schedule_node_sequence_splice_child(node, 1);
3731 node = isl_schedule_node_child(node, 0);
3732 node = isl_schedule_node_child(node, 0);
3733 node = compute_sub_schedule(node, ctx, graph,
3734 &node_scc_at_most, &edge_dst_scc_at_most,
3735 graph->src_scc, 0);
3736 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3737 node = isl_schedule_node_parent(node);
3738 node = isl_schedule_node_parent(node);
3739 if (is_seq)
3740 node = isl_schedule_node_sequence_splice_child(node, 0);
3742 return node;
3745 /* Insert a band node at position "node" in the schedule tree corresponding
3746 * to the current band in "graph". Mark the band node permutable
3747 * if "permutable" is set.
3748 * The partial schedules and the coincidence property are extracted
3749 * from the graph nodes.
3750 * Return the updated schedule node.
3752 static __isl_give isl_schedule_node *insert_current_band(
3753 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3754 int permutable)
3756 int i;
3757 int start, end, n;
3758 isl_multi_aff *ma;
3759 isl_multi_pw_aff *mpa;
3760 isl_multi_union_pw_aff *mupa;
3762 if (!node)
3763 return NULL;
3765 if (graph->n < 1)
3766 isl_die(isl_schedule_node_get_ctx(node), isl_error_internal,
3767 "graph should have at least one node",
3768 return isl_schedule_node_free(node));
3770 start = graph->band_start;
3771 end = graph->n_total_row;
3772 n = end - start;
3774 ma = node_extract_partial_schedule_multi_aff(&graph->node[0], start, n);
3775 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3776 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3778 for (i = 1; i < graph->n; ++i) {
3779 isl_multi_union_pw_aff *mupa_i;
3781 ma = node_extract_partial_schedule_multi_aff(&graph->node[i],
3782 start, n);
3783 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3784 mupa_i = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3785 mupa = isl_multi_union_pw_aff_union_add(mupa, mupa_i);
3787 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3789 for (i = 0; i < n; ++i)
3790 node = isl_schedule_node_band_member_set_coincident(node, i,
3791 graph->node[0].coincident[start + i]);
3792 node = isl_schedule_node_band_set_permutable(node, permutable);
3794 return node;
3797 /* Update the dependence relations based on the current schedule,
3798 * add the current band to "node" and then continue with the computation
3799 * of the next band.
3800 * Return the updated schedule node.
3802 static __isl_give isl_schedule_node *compute_next_band(
3803 __isl_take isl_schedule_node *node,
3804 struct isl_sched_graph *graph, int permutable)
3806 isl_ctx *ctx;
3808 if (!node)
3809 return NULL;
3811 ctx = isl_schedule_node_get_ctx(node);
3812 if (update_edges(ctx, graph) < 0)
3813 return isl_schedule_node_free(node);
3814 node = insert_current_band(node, graph, permutable);
3815 next_band(graph);
3817 node = isl_schedule_node_child(node, 0);
3818 node = compute_schedule(node, graph);
3819 node = isl_schedule_node_parent(node);
3821 return node;
3824 /* Add the constraints "coef" derived from an edge from "node" to itself
3825 * to graph->lp in order to respect the dependences and to try and carry them.
3826 * "pos" is the sequence number of the edge that needs to be carried.
3827 * "coef" represents general constraints on coefficients (c_0, c_x)
3828 * of valid constraints for (y - x) with x and y instances of the node.
3830 * The constraints added to graph->lp need to enforce
3832 * (c_j_0 + c_j_x y) - (c_j_0 + c_j_x x)
3833 * = c_j_x (y - x) >= e_i
3835 * for each (x,y) in the dependence relation of the edge.
3836 * That is, (-e_i, c_j_x) needs to be plugged in for (c_0, c_x),
3837 * taking into account that each coefficient in c_j_x is represented
3838 * as a pair of non-negative coefficients.
3840 static isl_stat add_intra_constraints(struct isl_sched_graph *graph,
3841 struct isl_sched_node *node, __isl_take isl_basic_set *coef, int pos)
3843 int offset;
3844 isl_ctx *ctx;
3845 isl_dim_map *dim_map;
3847 if (!coef)
3848 return isl_stat_error;
3850 ctx = isl_basic_set_get_ctx(coef);
3851 offset = coef_var_offset(coef);
3852 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
3853 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3854 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3856 return isl_stat_ok;
3859 /* Add the constraints "coef" derived from an edge from "src" to "dst"
3860 * to graph->lp in order to respect the dependences and to try and carry them.
3861 * "pos" is the sequence number of the edge that needs to be carried or
3862 * -1 if no attempt should be made to carry the dependences.
3863 * "coef" represents general constraints on coefficients (c_0, c_n, c_x, c_y)
3864 * of valid constraints for (x, y) with x and y instances of "src" and "dst".
3866 * The constraints added to graph->lp need to enforce
3868 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
3870 * for each (x,y) in the dependence relation of the edge or
3872 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= 0
3874 * if pos is -1.
3875 * That is,
3876 * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3877 * or
3878 * (c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3879 * needs to be plugged in for (c_0, c_n, c_x, c_y),
3880 * taking into account that each coefficient in c_j_x and c_k_x is represented
3881 * as a pair of non-negative coefficients.
3883 static isl_stat add_inter_constraints(struct isl_sched_graph *graph,
3884 struct isl_sched_node *src, struct isl_sched_node *dst,
3885 __isl_take isl_basic_set *coef, int pos)
3887 int offset;
3888 isl_ctx *ctx;
3889 isl_dim_map *dim_map;
3891 if (!coef)
3892 return isl_stat_error;
3894 ctx = isl_basic_set_get_ctx(coef);
3895 offset = coef_var_offset(coef);
3896 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
3897 if (pos >= 0)
3898 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3899 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3901 return isl_stat_ok;
3904 /* Data structure for keeping track of the data needed
3905 * to exploit non-trivial lineality spaces.
3907 * "any_non_trivial" is true if there are any non-trivial lineality spaces.
3908 * If "any_non_trivial" is not true, then "equivalent" and "mask" may be NULL.
3909 * "equivalent" connects instances to other instances on the same line(s).
3910 * "mask" contains the domain spaces of "equivalent".
3911 * Any instance set not in "mask" does not have a non-trivial lineality space.
3913 struct isl_exploit_lineality_data {
3914 isl_bool any_non_trivial;
3915 isl_union_map *equivalent;
3916 isl_union_set *mask;
3919 /* Data structure collecting information used during the construction
3920 * of an LP for carrying dependences.
3922 * "intra" is a sequence of coefficient constraints for intra-node edges.
3923 * "inter" is a sequence of coefficient constraints for inter-node edges.
3924 * "lineality" contains data used to exploit non-trivial lineality spaces.
3926 struct isl_carry {
3927 isl_basic_set_list *intra;
3928 isl_basic_set_list *inter;
3929 struct isl_exploit_lineality_data lineality;
3932 /* Free all the data stored in "carry".
3934 static void isl_carry_clear(struct isl_carry *carry)
3936 isl_basic_set_list_free(carry->intra);
3937 isl_basic_set_list_free(carry->inter);
3938 isl_union_map_free(carry->lineality.equivalent);
3939 isl_union_set_free(carry->lineality.mask);
3942 /* Return a pointer to the node in "graph" that lives in "space".
3943 * If the requested node has been compressed, then "space"
3944 * corresponds to the compressed space.
3946 * First try and see if "space" is the space of an uncompressed node.
3947 * If so, return that node.
3948 * Otherwise, "space" was constructed by construct_compressed_id and
3949 * contains a user pointer pointing to the node in the tuple id.
3950 * However, this node belongs to the original dependence graph.
3951 * If "graph" is a subgraph of this original dependence graph,
3952 * then the node with the same space still needs to be looked up
3953 * in the current graph.
3955 static struct isl_sched_node *graph_find_compressed_node(isl_ctx *ctx,
3956 struct isl_sched_graph *graph, __isl_keep isl_space *space)
3958 isl_id *id;
3959 struct isl_sched_node *node;
3961 if (!space)
3962 return NULL;
3964 node = graph_find_node(ctx, graph, space);
3965 if (node)
3966 return node;
3968 id = isl_space_get_tuple_id(space, isl_dim_set);
3969 node = isl_id_get_user(id);
3970 isl_id_free(id);
3972 if (!node)
3973 return NULL;
3975 if (!is_node(graph->root, node))
3976 isl_die(ctx, isl_error_internal,
3977 "space points to invalid node", return NULL);
3978 if (graph != graph->root)
3979 node = graph_find_node(ctx, graph, node->space);
3981 return node;
3984 /* Internal data structure for add_all_constraints.
3986 * "graph" is the schedule constraint graph for which an LP problem
3987 * is being constructed.
3988 * "carry_inter" indicates whether inter-node edges should be carried.
3989 * "pos" is the position of the next edge that needs to be carried.
3991 struct isl_add_all_constraints_data {
3992 isl_ctx *ctx;
3993 struct isl_sched_graph *graph;
3994 int carry_inter;
3995 int pos;
3998 /* Add the constraints "coef" derived from an edge from a node to itself
3999 * to data->graph->lp in order to respect the dependences and
4000 * to try and carry them.
4002 * The space of "coef" is of the form
4004 * coefficients[[c_cst] -> S[c_x]]
4006 * with S[c_x] the (compressed) space of the node.
4007 * Extract the node from the space and call add_intra_constraints.
4009 static isl_stat lp_add_intra(__isl_take isl_basic_set *coef, void *user)
4011 struct isl_add_all_constraints_data *data = user;
4012 isl_space *space;
4013 struct isl_sched_node *node;
4015 space = isl_basic_set_get_space(coef);
4016 space = isl_space_range(isl_space_unwrap(space));
4017 node = graph_find_compressed_node(data->ctx, data->graph, space);
4018 isl_space_free(space);
4019 return add_intra_constraints(data->graph, node, coef, data->pos++);
4022 /* Add the constraints "coef" derived from an edge from a node j
4023 * to a node k to data->graph->lp in order to respect the dependences and
4024 * to try and carry them (provided data->carry_inter is set).
4026 * The space of "coef" is of the form
4028 * coefficients[[c_cst, c_n] -> [S_j[c_x] -> S_k[c_y]]]
4030 * with S_j[c_x] and S_k[c_y] the (compressed) spaces of the nodes.
4031 * Extract the nodes from the space and call add_inter_constraints.
4033 static isl_stat lp_add_inter(__isl_take isl_basic_set *coef, void *user)
4035 struct isl_add_all_constraints_data *data = user;
4036 isl_space *space, *dom;
4037 struct isl_sched_node *src, *dst;
4038 int pos;
4040 space = isl_basic_set_get_space(coef);
4041 space = isl_space_unwrap(isl_space_range(isl_space_unwrap(space)));
4042 dom = isl_space_domain(isl_space_copy(space));
4043 src = graph_find_compressed_node(data->ctx, data->graph, dom);
4044 isl_space_free(dom);
4045 space = isl_space_range(space);
4046 dst = graph_find_compressed_node(data->ctx, data->graph, space);
4047 isl_space_free(space);
4049 pos = data->carry_inter ? data->pos++ : -1;
4050 return add_inter_constraints(data->graph, src, dst, coef, pos);
4053 /* Add constraints to graph->lp that force all (conditional) validity
4054 * dependences to be respected and attempt to carry them.
4055 * "intra" is the sequence of coefficient constraints for intra-node edges.
4056 * "inter" is the sequence of coefficient constraints for inter-node edges.
4057 * "carry_inter" indicates whether inter-node edges should be carried or
4058 * only respected.
4060 static isl_stat add_all_constraints(isl_ctx *ctx, struct isl_sched_graph *graph,
4061 __isl_keep isl_basic_set_list *intra,
4062 __isl_keep isl_basic_set_list *inter, int carry_inter)
4064 struct isl_add_all_constraints_data data = { ctx, graph, carry_inter };
4066 data.pos = 0;
4067 if (isl_basic_set_list_foreach(intra, &lp_add_intra, &data) < 0)
4068 return isl_stat_error;
4069 if (isl_basic_set_list_foreach(inter, &lp_add_inter, &data) < 0)
4070 return isl_stat_error;
4071 return isl_stat_ok;
4074 /* Internal data structure for count_all_constraints
4075 * for keeping track of the number of equality and inequality constraints.
4077 struct isl_sched_count {
4078 int n_eq;
4079 int n_ineq;
4082 /* Add the number of equality and inequality constraints of "bset"
4083 * to data->n_eq and data->n_ineq.
4085 static isl_stat bset_update_count(__isl_take isl_basic_set *bset, void *user)
4087 struct isl_sched_count *data = user;
4089 return update_count(bset, 1, &data->n_eq, &data->n_ineq);
4092 /* Count the number of equality and inequality constraints
4093 * that will be added to the carry_lp problem.
4094 * We count each edge exactly once.
4095 * "intra" is the sequence of coefficient constraints for intra-node edges.
4096 * "inter" is the sequence of coefficient constraints for inter-node edges.
4098 static isl_stat count_all_constraints(__isl_keep isl_basic_set_list *intra,
4099 __isl_keep isl_basic_set_list *inter, int *n_eq, int *n_ineq)
4101 struct isl_sched_count data;
4103 data.n_eq = data.n_ineq = 0;
4104 if (isl_basic_set_list_foreach(inter, &bset_update_count, &data) < 0)
4105 return isl_stat_error;
4106 if (isl_basic_set_list_foreach(intra, &bset_update_count, &data) < 0)
4107 return isl_stat_error;
4109 *n_eq = data.n_eq;
4110 *n_ineq = data.n_ineq;
4112 return isl_stat_ok;
4115 /* Construct an LP problem for finding schedule coefficients
4116 * such that the schedule carries as many validity dependences as possible.
4117 * In particular, for each dependence i, we bound the dependence distance
4118 * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
4119 * of all e_i's. Dependences with e_i = 0 in the solution are simply
4120 * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
4121 * "intra" is the sequence of coefficient constraints for intra-node edges.
4122 * "inter" is the sequence of coefficient constraints for inter-node edges.
4123 * "n_edge" is the total number of edges.
4124 * "carry_inter" indicates whether inter-node edges should be carried or
4125 * only respected. That is, if "carry_inter" is not set, then
4126 * no e_i variables are introduced for the inter-node edges.
4128 * All variables of the LP are non-negative. The actual coefficients
4129 * may be negative, so each coefficient is represented as the difference
4130 * of two non-negative variables. The negative part always appears
4131 * immediately before the positive part.
4132 * Other than that, the variables have the following order
4134 * - sum of (1 - e_i) over all edges
4135 * - sum of all c_n coefficients
4136 * (unconstrained when computing non-parametric schedules)
4137 * - sum of positive and negative parts of all c_x coefficients
4138 * - for each edge
4139 * - e_i
4140 * - for each node
4141 * - positive and negative parts of c_i_x, in opposite order
4142 * - c_i_n (if parametric)
4143 * - c_i_0
4145 * The constraints are those from the (validity) edges plus three equalities
4146 * to express the sums and n_edge inequalities to express e_i <= 1.
4148 static isl_stat setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
4149 int n_edge, __isl_keep isl_basic_set_list *intra,
4150 __isl_keep isl_basic_set_list *inter, int carry_inter)
4152 int i;
4153 int k;
4154 isl_space *dim;
4155 unsigned total;
4156 int n_eq, n_ineq;
4158 total = 3 + n_edge;
4159 for (i = 0; i < graph->n; ++i) {
4160 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
4161 node->start = total;
4162 total += 1 + node->nparam + 2 * node->nvar;
4165 if (count_all_constraints(intra, inter, &n_eq, &n_ineq) < 0)
4166 return isl_stat_error;
4168 dim = isl_space_set_alloc(ctx, 0, total);
4169 isl_basic_set_free(graph->lp);
4170 n_eq += 3;
4171 n_ineq += n_edge;
4172 graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
4173 graph->lp = isl_basic_set_set_rational(graph->lp);
4175 k = isl_basic_set_alloc_equality(graph->lp);
4176 if (k < 0)
4177 return isl_stat_error;
4178 isl_seq_clr(graph->lp->eq[k], 1 + total);
4179 isl_int_set_si(graph->lp->eq[k][0], -n_edge);
4180 isl_int_set_si(graph->lp->eq[k][1], 1);
4181 for (i = 0; i < n_edge; ++i)
4182 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
4184 if (add_param_sum_constraint(graph, 1) < 0)
4185 return isl_stat_error;
4186 if (add_var_sum_constraint(graph, 2) < 0)
4187 return isl_stat_error;
4189 for (i = 0; i < n_edge; ++i) {
4190 k = isl_basic_set_alloc_inequality(graph->lp);
4191 if (k < 0)
4192 return isl_stat_error;
4193 isl_seq_clr(graph->lp->ineq[k], 1 + total);
4194 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
4195 isl_int_set_si(graph->lp->ineq[k][0], 1);
4198 if (add_all_constraints(ctx, graph, intra, inter, carry_inter) < 0)
4199 return isl_stat_error;
4201 return isl_stat_ok;
4204 static __isl_give isl_schedule_node *compute_component_schedule(
4205 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4206 int wcc);
4208 /* If the schedule_split_scaled option is set and if the linear
4209 * parts of the scheduling rows for all nodes in the graphs have
4210 * a non-trivial common divisor, then remove this
4211 * common divisor from the linear part.
4212 * Otherwise, insert a band node directly and continue with
4213 * the construction of the schedule.
4215 * If a non-trivial common divisor is found, then
4216 * the linear part is reduced and the remainder is ignored.
4217 * The pieces of the graph that are assigned different remainders
4218 * form (groups of) strongly connected components within
4219 * the scaled down band. If needed, they can therefore
4220 * be ordered along this remainder in a sequence node.
4221 * However, this ordering is not enforced here in order to allow
4222 * the scheduler to combine some of the strongly connected components.
4224 static __isl_give isl_schedule_node *split_scaled(
4225 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4227 int i;
4228 int row;
4229 isl_ctx *ctx;
4230 isl_int gcd, gcd_i;
4232 if (!node)
4233 return NULL;
4235 ctx = isl_schedule_node_get_ctx(node);
4236 if (!ctx->opt->schedule_split_scaled)
4237 return compute_next_band(node, graph, 0);
4238 if (graph->n <= 1)
4239 return compute_next_band(node, graph, 0);
4241 isl_int_init(gcd);
4242 isl_int_init(gcd_i);
4244 isl_int_set_si(gcd, 0);
4246 row = isl_mat_rows(graph->node[0].sched) - 1;
4248 for (i = 0; i < graph->n; ++i) {
4249 struct isl_sched_node *node = &graph->node[i];
4250 int cols = isl_mat_cols(node->sched);
4252 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
4253 isl_int_gcd(gcd, gcd, gcd_i);
4256 isl_int_clear(gcd_i);
4258 if (isl_int_cmp_si(gcd, 1) <= 0) {
4259 isl_int_clear(gcd);
4260 return compute_next_band(node, graph, 0);
4263 for (i = 0; i < graph->n; ++i) {
4264 struct isl_sched_node *node = &graph->node[i];
4266 isl_int_fdiv_q(node->sched->row[row][0],
4267 node->sched->row[row][0], gcd);
4268 isl_int_mul(node->sched->row[row][0],
4269 node->sched->row[row][0], gcd);
4270 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
4271 if (!node->sched)
4272 goto error;
4275 isl_int_clear(gcd);
4277 return compute_next_band(node, graph, 0);
4278 error:
4279 isl_int_clear(gcd);
4280 return isl_schedule_node_free(node);
4283 /* Is the schedule row "sol" trivial on node "node"?
4284 * That is, is the solution zero on the dimensions linearly independent of
4285 * the previously found solutions?
4286 * Return 1 if the solution is trivial, 0 if it is not and -1 on error.
4288 * Each coefficient is represented as the difference between
4289 * two non-negative values in "sol".
4290 * We construct the schedule row s and check if it is linearly
4291 * independent of previously computed schedule rows
4292 * by computing T s, with T the linear combinations that are zero
4293 * on linearly dependent schedule rows.
4294 * If the result consists of all zeros, then the solution is trivial.
4296 static int is_trivial(struct isl_sched_node *node, __isl_keep isl_vec *sol)
4298 int trivial;
4299 isl_vec *node_sol;
4301 if (!sol)
4302 return -1;
4303 if (node->nvar == node->rank)
4304 return 0;
4306 node_sol = extract_var_coef(node, sol);
4307 node_sol = isl_mat_vec_product(isl_mat_copy(node->indep), node_sol);
4308 if (!node_sol)
4309 return -1;
4311 trivial = isl_seq_first_non_zero(node_sol->el,
4312 node->nvar - node->rank) == -1;
4314 isl_vec_free(node_sol);
4316 return trivial;
4319 /* Is the schedule row "sol" trivial on any node where it should
4320 * not be trivial?
4321 * Return 1 if any solution is trivial, 0 if they are not and -1 on error.
4323 static int is_any_trivial(struct isl_sched_graph *graph,
4324 __isl_keep isl_vec *sol)
4326 int i;
4328 for (i = 0; i < graph->n; ++i) {
4329 struct isl_sched_node *node = &graph->node[i];
4330 int trivial;
4332 if (!needs_row(graph, node))
4333 continue;
4334 trivial = is_trivial(node, sol);
4335 if (trivial < 0 || trivial)
4336 return trivial;
4339 return 0;
4342 /* Does the schedule represented by "sol" perform loop coalescing on "node"?
4343 * If so, return the position of the coalesced dimension.
4344 * Otherwise, return node->nvar or -1 on error.
4346 * In particular, look for pairs of coefficients c_i and c_j such that
4347 * |c_j/c_i| > ceil(size_i/2), i.e., |c_j| > |c_i * ceil(size_i/2)|.
4348 * If any such pair is found, then return i.
4349 * If size_i is infinity, then no check on c_i needs to be performed.
4351 static int find_node_coalescing(struct isl_sched_node *node,
4352 __isl_keep isl_vec *sol)
4354 int i, j;
4355 isl_int max;
4356 isl_vec *csol;
4358 if (node->nvar <= 1)
4359 return node->nvar;
4361 csol = extract_var_coef(node, sol);
4362 if (!csol)
4363 return -1;
4364 isl_int_init(max);
4365 for (i = 0; i < node->nvar; ++i) {
4366 isl_val *v;
4368 if (isl_int_is_zero(csol->el[i]))
4369 continue;
4370 v = isl_multi_val_get_val(node->sizes, i);
4371 if (!v)
4372 goto error;
4373 if (!isl_val_is_int(v)) {
4374 isl_val_free(v);
4375 continue;
4377 v = isl_val_div_ui(v, 2);
4378 v = isl_val_ceil(v);
4379 if (!v)
4380 goto error;
4381 isl_int_mul(max, v->n, csol->el[i]);
4382 isl_val_free(v);
4384 for (j = 0; j < node->nvar; ++j) {
4385 if (j == i)
4386 continue;
4387 if (isl_int_abs_gt(csol->el[j], max))
4388 break;
4390 if (j < node->nvar)
4391 break;
4394 isl_int_clear(max);
4395 isl_vec_free(csol);
4396 return i;
4397 error:
4398 isl_int_clear(max);
4399 isl_vec_free(csol);
4400 return -1;
4403 /* Force the schedule coefficient at position "pos" of "node" to be zero
4404 * in "tl".
4405 * The coefficient is encoded as the difference between two non-negative
4406 * variables. Force these two variables to have the same value.
4408 static __isl_give isl_tab_lexmin *zero_out_node_coef(
4409 __isl_take isl_tab_lexmin *tl, struct isl_sched_node *node, int pos)
4411 int dim;
4412 isl_ctx *ctx;
4413 isl_vec *eq;
4415 ctx = isl_space_get_ctx(node->space);
4416 dim = isl_tab_lexmin_dim(tl);
4417 if (dim < 0)
4418 return isl_tab_lexmin_free(tl);
4419 eq = isl_vec_alloc(ctx, 1 + dim);
4420 eq = isl_vec_clr(eq);
4421 if (!eq)
4422 return isl_tab_lexmin_free(tl);
4424 pos = 1 + node_var_coef_pos(node, pos);
4425 isl_int_set_si(eq->el[pos], 1);
4426 isl_int_set_si(eq->el[pos + 1], -1);
4427 tl = isl_tab_lexmin_add_eq(tl, eq->el);
4428 isl_vec_free(eq);
4430 return tl;
4433 /* Return the lexicographically smallest rational point in the basic set
4434 * from which "tl" was constructed, double checking that this input set
4435 * was not empty.
4437 static __isl_give isl_vec *non_empty_solution(__isl_keep isl_tab_lexmin *tl)
4439 isl_vec *sol;
4441 sol = isl_tab_lexmin_get_solution(tl);
4442 if (!sol)
4443 return NULL;
4444 if (sol->size == 0)
4445 isl_die(isl_vec_get_ctx(sol), isl_error_internal,
4446 "error in schedule construction",
4447 return isl_vec_free(sol));
4448 return sol;
4451 /* Does the solution "sol" of the LP problem constructed by setup_carry_lp
4452 * carry any of the "n_edge" groups of dependences?
4453 * The value in the first position is the sum of (1 - e_i) over all "n_edge"
4454 * edges, with 0 <= e_i <= 1 equal to 1 when the dependences represented
4455 * by the edge are carried by the solution.
4456 * If the sum of the (1 - e_i) is smaller than "n_edge" then at least
4457 * one of those is carried.
4459 * Note that despite the fact that the problem is solved using a rational
4460 * solver, the solution is guaranteed to be integral.
4461 * Specifically, the dependence distance lower bounds e_i (and therefore
4462 * also their sum) are integers. See Lemma 5 of [1].
4464 * Any potential denominator of the sum is cleared by this function.
4465 * The denominator is not relevant for any of the other elements
4466 * in the solution.
4468 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4469 * Problem, Part II: Multi-Dimensional Time.
4470 * In Intl. Journal of Parallel Programming, 1992.
4472 static int carries_dependences(__isl_keep isl_vec *sol, int n_edge)
4474 isl_int_divexact(sol->el[1], sol->el[1], sol->el[0]);
4475 isl_int_set_si(sol->el[0], 1);
4476 return isl_int_cmp_si(sol->el[1], n_edge) < 0;
4479 /* Return the lexicographically smallest rational point in "lp",
4480 * assuming that all variables are non-negative and performing some
4481 * additional sanity checks.
4482 * If "want_integral" is set, then compute the lexicographically smallest
4483 * integer point instead.
4484 * In particular, "lp" should not be empty by construction.
4485 * Double check that this is the case.
4486 * If dependences are not carried for any of the "n_edge" edges,
4487 * then return an empty vector.
4489 * If the schedule_treat_coalescing option is set and
4490 * if the computed schedule performs loop coalescing on a given node,
4491 * i.e., if it is of the form
4493 * c_i i + c_j j + ...
4495 * with |c_j/c_i| >= size_i, then force the coefficient c_i to be zero
4496 * to cut out this solution. Repeat this process until no more loop
4497 * coalescing occurs or until no more dependences can be carried.
4498 * In the latter case, revert to the previously computed solution.
4500 * If the caller requests an integral solution and if coalescing should
4501 * be treated, then perform the coalescing treatment first as
4502 * an integral solution computed before coalescing treatment
4503 * would carry the same number of edges and would therefore probably
4504 * also be coalescing.
4506 * To allow the coalescing treatment to be performed first,
4507 * the initial solution is allowed to be rational and it is only
4508 * cut out (if needed) in the next iteration, if no coalescing measures
4509 * were taken.
4511 static __isl_give isl_vec *non_neg_lexmin(struct isl_sched_graph *graph,
4512 __isl_take isl_basic_set *lp, int n_edge, int want_integral)
4514 int i, pos, cut;
4515 isl_ctx *ctx;
4516 isl_tab_lexmin *tl;
4517 isl_vec *sol = NULL, *prev;
4518 int treat_coalescing;
4519 int try_again;
4521 if (!lp)
4522 return NULL;
4523 ctx = isl_basic_set_get_ctx(lp);
4524 treat_coalescing = isl_options_get_schedule_treat_coalescing(ctx);
4525 tl = isl_tab_lexmin_from_basic_set(lp);
4527 cut = 0;
4528 do {
4529 int integral;
4531 try_again = 0;
4532 if (cut)
4533 tl = isl_tab_lexmin_cut_to_integer(tl);
4534 prev = sol;
4535 sol = non_empty_solution(tl);
4536 if (!sol)
4537 goto error;
4539 integral = isl_int_is_one(sol->el[0]);
4540 if (!carries_dependences(sol, n_edge)) {
4541 if (!prev)
4542 prev = isl_vec_alloc(ctx, 0);
4543 isl_vec_free(sol);
4544 sol = prev;
4545 break;
4547 prev = isl_vec_free(prev);
4548 cut = want_integral && !integral;
4549 if (cut)
4550 try_again = 1;
4551 if (!treat_coalescing)
4552 continue;
4553 for (i = 0; i < graph->n; ++i) {
4554 struct isl_sched_node *node = &graph->node[i];
4556 pos = find_node_coalescing(node, sol);
4557 if (pos < 0)
4558 goto error;
4559 if (pos < node->nvar)
4560 break;
4562 if (i < graph->n) {
4563 try_again = 1;
4564 tl = zero_out_node_coef(tl, &graph->node[i], pos);
4565 cut = 0;
4567 } while (try_again);
4569 isl_tab_lexmin_free(tl);
4571 return sol;
4572 error:
4573 isl_tab_lexmin_free(tl);
4574 isl_vec_free(prev);
4575 isl_vec_free(sol);
4576 return NULL;
4579 /* If "edge" is an edge from a node to itself, then add the corresponding
4580 * dependence relation to "umap".
4581 * If "node" has been compressed, then the dependence relation
4582 * is also compressed first.
4584 static __isl_give isl_union_map *add_intra(__isl_take isl_union_map *umap,
4585 struct isl_sched_edge *edge)
4587 isl_map *map;
4588 struct isl_sched_node *node = edge->src;
4590 if (edge->src != edge->dst)
4591 return umap;
4593 map = isl_map_copy(edge->map);
4594 if (node->compressed) {
4595 map = isl_map_preimage_domain_multi_aff(map,
4596 isl_multi_aff_copy(node->decompress));
4597 map = isl_map_preimage_range_multi_aff(map,
4598 isl_multi_aff_copy(node->decompress));
4600 umap = isl_union_map_add_map(umap, map);
4601 return umap;
4604 /* If "edge" is an edge from a node to another node, then add the corresponding
4605 * dependence relation to "umap".
4606 * If the source or destination nodes of "edge" have been compressed,
4607 * then the dependence relation is also compressed first.
4609 static __isl_give isl_union_map *add_inter(__isl_take isl_union_map *umap,
4610 struct isl_sched_edge *edge)
4612 isl_map *map;
4614 if (edge->src == edge->dst)
4615 return umap;
4617 map = isl_map_copy(edge->map);
4618 if (edge->src->compressed)
4619 map = isl_map_preimage_domain_multi_aff(map,
4620 isl_multi_aff_copy(edge->src->decompress));
4621 if (edge->dst->compressed)
4622 map = isl_map_preimage_range_multi_aff(map,
4623 isl_multi_aff_copy(edge->dst->decompress));
4624 umap = isl_union_map_add_map(umap, map);
4625 return umap;
4628 /* Internal data structure used by union_drop_coalescing_constraints
4629 * to collect bounds on all relevant statements.
4631 * "graph" is the schedule constraint graph for which an LP problem
4632 * is being constructed.
4633 * "bounds" collects the bounds.
4635 struct isl_collect_bounds_data {
4636 isl_ctx *ctx;
4637 struct isl_sched_graph *graph;
4638 isl_union_set *bounds;
4641 /* Add the size bounds for the node with instance deltas in "set"
4642 * to data->bounds.
4644 static isl_stat collect_bounds(__isl_take isl_set *set, void *user)
4646 struct isl_collect_bounds_data *data = user;
4647 struct isl_sched_node *node;
4648 isl_space *space;
4649 isl_set *bounds;
4651 space = isl_set_get_space(set);
4652 isl_set_free(set);
4654 node = graph_find_compressed_node(data->ctx, data->graph, space);
4655 isl_space_free(space);
4657 bounds = isl_set_from_basic_set(get_size_bounds(node));
4658 data->bounds = isl_union_set_add_set(data->bounds, bounds);
4660 return isl_stat_ok;
4663 /* Drop some constraints from "delta" that could be exploited
4664 * to construct loop coalescing schedules.
4665 * In particular, drop those constraint that bound the difference
4666 * to the size of the domain.
4667 * Do this for each set/node in "delta" separately.
4668 * The parameters are assumed to have been projected out by the caller.
4670 static __isl_give isl_union_set *union_drop_coalescing_constraints(isl_ctx *ctx,
4671 struct isl_sched_graph *graph, __isl_take isl_union_set *delta)
4673 struct isl_collect_bounds_data data = { ctx, graph };
4675 data.bounds = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4676 if (isl_union_set_foreach_set(delta, &collect_bounds, &data) < 0)
4677 data.bounds = isl_union_set_free(data.bounds);
4678 delta = isl_union_set_plain_gist(delta, data.bounds);
4680 return delta;
4683 /* Given a non-trivial lineality space "lineality", add the corresponding
4684 * universe set to data->mask and add a map from elements to
4685 * other elements along the lines in "lineality" to data->equivalent.
4686 * If this is the first time this function gets called
4687 * (data->any_non_trivial is still false), then set data->any_non_trivial and
4688 * initialize data->mask and data->equivalent.
4690 * In particular, if the lineality space is defined by equality constraints
4692 * E x = 0
4694 * then construct an affine mapping
4696 * f : x -> E x
4698 * and compute the equivalence relation of having the same image under f:
4700 * { x -> x' : E x = E x' }
4702 static isl_stat add_non_trivial_lineality(__isl_take isl_basic_set *lineality,
4703 struct isl_exploit_lineality_data *data)
4705 isl_mat *eq;
4706 isl_space *space;
4707 isl_set *univ;
4708 isl_multi_aff *ma;
4709 isl_multi_pw_aff *mpa;
4710 isl_map *map;
4711 int n;
4713 if (!lineality)
4714 return isl_stat_error;
4715 if (isl_basic_set_dim(lineality, isl_dim_div) != 0)
4716 isl_die(isl_basic_set_get_ctx(lineality), isl_error_internal,
4717 "local variables not allowed", goto error);
4719 space = isl_basic_set_get_space(lineality);
4720 if (!data->any_non_trivial) {
4721 data->equivalent = isl_union_map_empty(isl_space_copy(space));
4722 data->mask = isl_union_set_empty(isl_space_copy(space));
4724 data->any_non_trivial = isl_bool_true;
4726 univ = isl_set_universe(isl_space_copy(space));
4727 data->mask = isl_union_set_add_set(data->mask, univ);
4729 eq = isl_basic_set_extract_equalities(lineality);
4730 n = isl_mat_rows(eq);
4731 eq = isl_mat_insert_zero_rows(eq, 0, 1);
4732 eq = isl_mat_set_element_si(eq, 0, 0, 1);
4733 space = isl_space_from_domain(space);
4734 space = isl_space_add_dims(space, isl_dim_out, n);
4735 ma = isl_multi_aff_from_aff_mat(space, eq);
4736 mpa = isl_multi_pw_aff_from_multi_aff(ma);
4737 map = isl_multi_pw_aff_eq_map(mpa, isl_multi_pw_aff_copy(mpa));
4738 data->equivalent = isl_union_map_add_map(data->equivalent, map);
4740 isl_basic_set_free(lineality);
4741 return isl_stat_ok;
4742 error:
4743 isl_basic_set_free(lineality);
4744 return isl_stat_error;
4747 /* Check if the lineality space "set" is non-trivial (i.e., is not just
4748 * the origin or, in other words, satisfies a number of equality constraints
4749 * that is smaller than the dimension of the set).
4750 * If so, extend data->mask and data->equivalent accordingly.
4752 * The input should not have any local variables already, but
4753 * isl_set_remove_divs is called to make sure it does not.
4755 static isl_stat add_lineality(__isl_take isl_set *set, void *user)
4757 struct isl_exploit_lineality_data *data = user;
4758 isl_basic_set *hull;
4759 int dim, n_eq;
4761 set = isl_set_remove_divs(set);
4762 hull = isl_set_unshifted_simple_hull(set);
4763 dim = isl_basic_set_dim(hull, isl_dim_set);
4764 n_eq = isl_basic_set_n_equality(hull);
4765 if (!hull)
4766 return isl_stat_error;
4767 if (dim != n_eq)
4768 return add_non_trivial_lineality(hull, data);
4769 isl_basic_set_free(hull);
4770 return isl_stat_ok;
4773 /* Check if the difference set on intra-node schedule constraints "intra"
4774 * has any non-trivial lineality space.
4775 * If so, then extend the difference set to a difference set
4776 * on equivalent elements. That is, if "intra" is
4778 * { y - x : (x,y) \in V }
4780 * and elements are equivalent if they have the same image under f,
4781 * then return
4783 * { y' - x' : (x,y) \in V and f(x) = f(x') and f(y) = f(y') }
4785 * or, since f is linear,
4787 * { y' - x' : (x,y) \in V and f(y - x) = f(y' - x') }
4789 * The results of the search for non-trivial lineality spaces is stored
4790 * in "data".
4792 static __isl_give isl_union_set *exploit_intra_lineality(
4793 __isl_take isl_union_set *intra,
4794 struct isl_exploit_lineality_data *data)
4796 isl_union_set *lineality;
4797 isl_union_set *uset;
4799 data->any_non_trivial = isl_bool_false;
4800 lineality = isl_union_set_copy(intra);
4801 lineality = isl_union_set_combined_lineality_space(lineality);
4802 if (isl_union_set_foreach_set(lineality, &add_lineality, data) < 0)
4803 data->any_non_trivial = isl_bool_error;
4804 isl_union_set_free(lineality);
4806 if (data->any_non_trivial < 0)
4807 return isl_union_set_free(intra);
4808 if (!data->any_non_trivial)
4809 return intra;
4811 uset = isl_union_set_copy(intra);
4812 intra = isl_union_set_subtract(intra, isl_union_set_copy(data->mask));
4813 uset = isl_union_set_apply(uset, isl_union_map_copy(data->equivalent));
4814 intra = isl_union_set_union(intra, uset);
4816 intra = isl_union_set_remove_divs(intra);
4818 return intra;
4821 /* If the difference set on intra-node schedule constraints was found to have
4822 * any non-trivial lineality space by exploit_intra_lineality,
4823 * as recorded in "data", then extend the inter-node
4824 * schedule constraints "inter" to schedule constraints on equivalent elements.
4825 * That is, if "inter" is V and
4826 * elements are equivalent if they have the same image under f, then return
4828 * { (x', y') : (x,y) \in V and f(x) = f(x') and f(y) = f(y') }
4830 static __isl_give isl_union_map *exploit_inter_lineality(
4831 __isl_take isl_union_map *inter,
4832 struct isl_exploit_lineality_data *data)
4834 isl_union_map *umap;
4836 if (data->any_non_trivial < 0)
4837 return isl_union_map_free(inter);
4838 if (!data->any_non_trivial)
4839 return inter;
4841 umap = isl_union_map_copy(inter);
4842 inter = isl_union_map_subtract_range(inter,
4843 isl_union_set_copy(data->mask));
4844 umap = isl_union_map_apply_range(umap,
4845 isl_union_map_copy(data->equivalent));
4846 inter = isl_union_map_union(inter, umap);
4847 umap = isl_union_map_copy(inter);
4848 inter = isl_union_map_subtract_domain(inter,
4849 isl_union_set_copy(data->mask));
4850 umap = isl_union_map_apply_range(isl_union_map_copy(data->equivalent),
4851 umap);
4852 inter = isl_union_map_union(inter, umap);
4854 inter = isl_union_map_remove_divs(inter);
4856 return inter;
4859 /* For each (conditional) validity edge in "graph",
4860 * add the corresponding dependence relation using "add"
4861 * to a collection of dependence relations and return the result.
4862 * If "coincidence" is set, then coincidence edges are considered as well.
4864 static __isl_give isl_union_map *collect_validity(struct isl_sched_graph *graph,
4865 __isl_give isl_union_map *(*add)(__isl_take isl_union_map *umap,
4866 struct isl_sched_edge *edge), int coincidence)
4868 int i;
4869 isl_space *space;
4870 isl_union_map *umap;
4872 space = isl_space_copy(graph->node[0].space);
4873 umap = isl_union_map_empty(space);
4875 for (i = 0; i < graph->n_edge; ++i) {
4876 struct isl_sched_edge *edge = &graph->edge[i];
4878 if (!is_any_validity(edge) &&
4879 (!coincidence || !is_coincidence(edge)))
4880 continue;
4882 umap = add(umap, edge);
4885 return umap;
4888 /* Project out all parameters from "uset" and return the result.
4890 static __isl_give isl_union_set *union_set_drop_parameters(
4891 __isl_take isl_union_set *uset)
4893 unsigned nparam;
4895 nparam = isl_union_set_dim(uset, isl_dim_param);
4896 return isl_union_set_project_out(uset, isl_dim_param, 0, nparam);
4899 /* For each dependence relation on a (conditional) validity edge
4900 * from a node to itself,
4901 * construct the set of coefficients of valid constraints for elements
4902 * in that dependence relation and collect the results.
4903 * If "coincidence" is set, then coincidence edges are considered as well.
4905 * In particular, for each dependence relation R, constraints
4906 * on coefficients (c_0, c_x) are constructed such that
4908 * c_0 + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
4910 * If the schedule_treat_coalescing option is set, then some constraints
4911 * that could be exploited to construct coalescing schedules
4912 * are removed before the dual is computed, but after the parameters
4913 * have been projected out.
4914 * The entire computation is essentially the same as that performed
4915 * by intra_coefficients, except that it operates on multiple
4916 * edges together and that the parameters are always projected out.
4918 * Additionally, exploit any non-trivial lineality space
4919 * in the difference set after removing coalescing constraints and
4920 * store the results of the non-trivial lineality space detection in "data".
4921 * The procedure is currently run unconditionally, but it is unlikely
4922 * to find any non-trivial lineality spaces if no coalescing constraints
4923 * have been removed.
4925 * Note that if a dependence relation is a union of basic maps,
4926 * then each basic map needs to be treated individually as it may only
4927 * be possible to carry the dependences expressed by some of those
4928 * basic maps and not all of them.
4929 * The collected validity constraints are therefore not coalesced and
4930 * it is assumed that they are not coalesced automatically.
4931 * Duplicate basic maps can be removed, however.
4932 * In particular, if the same basic map appears as a disjunct
4933 * in multiple edges, then it only needs to be carried once.
4935 static __isl_give isl_basic_set_list *collect_intra_validity(isl_ctx *ctx,
4936 struct isl_sched_graph *graph, int coincidence,
4937 struct isl_exploit_lineality_data *data)
4939 isl_union_map *intra;
4940 isl_union_set *delta;
4941 isl_basic_set_list *list;
4943 intra = collect_validity(graph, &add_intra, coincidence);
4944 delta = isl_union_map_deltas(intra);
4945 delta = union_set_drop_parameters(delta);
4946 delta = isl_union_set_remove_divs(delta);
4947 if (isl_options_get_schedule_treat_coalescing(ctx))
4948 delta = union_drop_coalescing_constraints(ctx, graph, delta);
4949 delta = exploit_intra_lineality(delta, data);
4950 list = isl_union_set_get_basic_set_list(delta);
4951 isl_union_set_free(delta);
4953 return isl_basic_set_list_coefficients(list);
4956 /* For each dependence relation on a (conditional) validity edge
4957 * from a node to some other node,
4958 * construct the set of coefficients of valid constraints for elements
4959 * in that dependence relation and collect the results.
4960 * If "coincidence" is set, then coincidence edges are considered as well.
4962 * In particular, for each dependence relation R, constraints
4963 * on coefficients (c_0, c_n, c_x, c_y) are constructed such that
4965 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
4967 * This computation is essentially the same as that performed
4968 * by inter_coefficients, except that it operates on multiple
4969 * edges together.
4971 * Additionally, exploit any non-trivial lineality space
4972 * that may have been discovered by collect_intra_validity
4973 * (as stored in "data").
4975 * Note that if a dependence relation is a union of basic maps,
4976 * then each basic map needs to be treated individually as it may only
4977 * be possible to carry the dependences expressed by some of those
4978 * basic maps and not all of them.
4979 * The collected validity constraints are therefore not coalesced and
4980 * it is assumed that they are not coalesced automatically.
4981 * Duplicate basic maps can be removed, however.
4982 * In particular, if the same basic map appears as a disjunct
4983 * in multiple edges, then it only needs to be carried once.
4985 static __isl_give isl_basic_set_list *collect_inter_validity(
4986 struct isl_sched_graph *graph, int coincidence,
4987 struct isl_exploit_lineality_data *data)
4989 isl_union_map *inter;
4990 isl_union_set *wrap;
4991 isl_basic_set_list *list;
4993 inter = collect_validity(graph, &add_inter, coincidence);
4994 inter = exploit_inter_lineality(inter, data);
4995 inter = isl_union_map_remove_divs(inter);
4996 wrap = isl_union_map_wrap(inter);
4997 list = isl_union_set_get_basic_set_list(wrap);
4998 isl_union_set_free(wrap);
4999 return isl_basic_set_list_coefficients(list);
5002 /* Construct an LP problem for finding schedule coefficients
5003 * such that the schedule carries as many of the "n_edge" groups of
5004 * dependences as possible based on the corresponding coefficient
5005 * constraints and return the lexicographically smallest non-trivial solution.
5006 * "intra" is the sequence of coefficient constraints for intra-node edges.
5007 * "inter" is the sequence of coefficient constraints for inter-node edges.
5008 * If "want_integral" is set, then compute an integral solution
5009 * for the coefficients rather than using the numerators
5010 * of a rational solution.
5011 * "carry_inter" indicates whether inter-node edges should be carried or
5012 * only respected.
5014 * If none of the "n_edge" groups can be carried
5015 * then return an empty vector.
5017 static __isl_give isl_vec *compute_carrying_sol_coef(isl_ctx *ctx,
5018 struct isl_sched_graph *graph, int n_edge,
5019 __isl_keep isl_basic_set_list *intra,
5020 __isl_keep isl_basic_set_list *inter, int want_integral,
5021 int carry_inter)
5023 isl_basic_set *lp;
5025 if (setup_carry_lp(ctx, graph, n_edge, intra, inter, carry_inter) < 0)
5026 return NULL;
5028 lp = isl_basic_set_copy(graph->lp);
5029 return non_neg_lexmin(graph, lp, n_edge, want_integral);
5032 /* Construct an LP problem for finding schedule coefficients
5033 * such that the schedule carries as many of the validity dependences
5034 * as possible and
5035 * return the lexicographically smallest non-trivial solution.
5036 * If "fallback" is set, then the carrying is performed as a fallback
5037 * for the Pluto-like scheduler.
5038 * If "coincidence" is set, then try and carry coincidence edges as well.
5040 * The variable "n_edge" stores the number of groups that should be carried.
5041 * If none of the "n_edge" groups can be carried
5042 * then return an empty vector.
5043 * If, moreover, "n_edge" is zero, then the LP problem does not even
5044 * need to be constructed.
5046 * If a fallback solution is being computed, then compute an integral solution
5047 * for the coefficients rather than using the numerators
5048 * of a rational solution.
5050 * If a fallback solution is being computed, if there are any intra-node
5051 * dependences, and if requested by the user, then first try
5052 * to only carry those intra-node dependences.
5053 * If this fails to carry any dependences, then try again
5054 * with the inter-node dependences included.
5056 static __isl_give isl_vec *compute_carrying_sol(isl_ctx *ctx,
5057 struct isl_sched_graph *graph, int fallback, int coincidence)
5059 int n_intra, n_inter;
5060 int n_edge;
5061 struct isl_carry carry = { 0 };
5062 isl_vec *sol;
5064 carry.intra = collect_intra_validity(ctx, graph, coincidence,
5065 &carry.lineality);
5066 carry.inter = collect_inter_validity(graph, coincidence,
5067 &carry.lineality);
5068 if (!carry.intra || !carry.inter)
5069 goto error;
5070 n_intra = isl_basic_set_list_n_basic_set(carry.intra);
5071 n_inter = isl_basic_set_list_n_basic_set(carry.inter);
5073 if (fallback && n_intra > 0 &&
5074 isl_options_get_schedule_carry_self_first(ctx)) {
5075 sol = compute_carrying_sol_coef(ctx, graph, n_intra,
5076 carry.intra, carry.inter, fallback, 0);
5077 if (!sol || sol->size != 0 || n_inter == 0) {
5078 isl_carry_clear(&carry);
5079 return sol;
5081 isl_vec_free(sol);
5084 n_edge = n_intra + n_inter;
5085 if (n_edge == 0) {
5086 isl_carry_clear(&carry);
5087 return isl_vec_alloc(ctx, 0);
5090 sol = compute_carrying_sol_coef(ctx, graph, n_edge,
5091 carry.intra, carry.inter, fallback, 1);
5092 isl_carry_clear(&carry);
5093 return sol;
5094 error:
5095 isl_carry_clear(&carry);
5096 return NULL;
5099 /* Construct a schedule row for each node such that as many validity dependences
5100 * as possible are carried and then continue with the next band.
5101 * If "fallback" is set, then the carrying is performed as a fallback
5102 * for the Pluto-like scheduler.
5103 * If "coincidence" is set, then try and carry coincidence edges as well.
5105 * If there are no validity dependences, then no dependence can be carried and
5106 * the procedure is guaranteed to fail. If there is more than one component,
5107 * then try computing a schedule on each component separately
5108 * to prevent or at least postpone this failure.
5110 * If a schedule row is computed, then check that dependences are carried
5111 * for at least one of the edges.
5113 * If the computed schedule row turns out to be trivial on one or
5114 * more nodes where it should not be trivial, then we throw it away
5115 * and try again on each component separately.
5117 * If there is only one component, then we accept the schedule row anyway,
5118 * but we do not consider it as a complete row and therefore do not
5119 * increment graph->n_row. Note that the ranks of the nodes that
5120 * do get a non-trivial schedule part will get updated regardless and
5121 * graph->maxvar is computed based on these ranks. The test for
5122 * whether more schedule rows are required in compute_schedule_wcc
5123 * is therefore not affected.
5125 * Insert a band corresponding to the schedule row at position "node"
5126 * of the schedule tree and continue with the construction of the schedule.
5127 * This insertion and the continued construction is performed by split_scaled
5128 * after optionally checking for non-trivial common divisors.
5130 static __isl_give isl_schedule_node *carry(__isl_take isl_schedule_node *node,
5131 struct isl_sched_graph *graph, int fallback, int coincidence)
5133 int trivial;
5134 isl_ctx *ctx;
5135 isl_vec *sol;
5137 if (!node)
5138 return NULL;
5140 ctx = isl_schedule_node_get_ctx(node);
5141 sol = compute_carrying_sol(ctx, graph, fallback, coincidence);
5142 if (!sol)
5143 return isl_schedule_node_free(node);
5144 if (sol->size == 0) {
5145 isl_vec_free(sol);
5146 if (graph->scc > 1)
5147 return compute_component_schedule(node, graph, 1);
5148 isl_die(ctx, isl_error_unknown, "unable to carry dependences",
5149 return isl_schedule_node_free(node));
5152 trivial = is_any_trivial(graph, sol);
5153 if (trivial < 0) {
5154 sol = isl_vec_free(sol);
5155 } else if (trivial && graph->scc > 1) {
5156 isl_vec_free(sol);
5157 return compute_component_schedule(node, graph, 1);
5160 if (update_schedule(graph, sol, 0) < 0)
5161 return isl_schedule_node_free(node);
5162 if (trivial)
5163 graph->n_row--;
5165 return split_scaled(node, graph);
5168 /* Construct a schedule row for each node such that as many validity dependences
5169 * as possible are carried and then continue with the next band.
5170 * Do so as a fallback for the Pluto-like scheduler.
5171 * If "coincidence" is set, then try and carry coincidence edges as well.
5173 static __isl_give isl_schedule_node *carry_fallback(
5174 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5175 int coincidence)
5177 return carry(node, graph, 1, coincidence);
5180 /* Construct a schedule row for each node such that as many validity dependences
5181 * as possible are carried and then continue with the next band.
5182 * Do so for the case where the Feautrier scheduler was selected
5183 * by the user.
5185 static __isl_give isl_schedule_node *carry_feautrier(
5186 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5188 return carry(node, graph, 0, 0);
5191 /* Construct a schedule row for each node such that as many validity dependences
5192 * as possible are carried and then continue with the next band.
5193 * Do so as a fallback for the Pluto-like scheduler.
5195 static __isl_give isl_schedule_node *carry_dependences(
5196 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5198 return carry_fallback(node, graph, 0);
5201 /* Construct a schedule row for each node such that as many validity or
5202 * coincidence dependences as possible are carried and
5203 * then continue with the next band.
5204 * Do so as a fallback for the Pluto-like scheduler.
5206 static __isl_give isl_schedule_node *carry_coincidence(
5207 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5209 return carry_fallback(node, graph, 1);
5212 /* Topologically sort statements mapped to the same schedule iteration
5213 * and add insert a sequence node in front of "node"
5214 * corresponding to this order.
5215 * If "initialized" is set, then it may be assumed that compute_maxvar
5216 * has been called on the current band. Otherwise, call
5217 * compute_maxvar if and before carry_dependences gets called.
5219 * If it turns out to be impossible to sort the statements apart,
5220 * because different dependences impose different orderings
5221 * on the statements, then we extend the schedule such that
5222 * it carries at least one more dependence.
5224 static __isl_give isl_schedule_node *sort_statements(
5225 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5226 int initialized)
5228 isl_ctx *ctx;
5229 isl_union_set_list *filters;
5231 if (!node)
5232 return NULL;
5234 ctx = isl_schedule_node_get_ctx(node);
5235 if (graph->n < 1)
5236 isl_die(ctx, isl_error_internal,
5237 "graph should have at least one node",
5238 return isl_schedule_node_free(node));
5240 if (graph->n == 1)
5241 return node;
5243 if (update_edges(ctx, graph) < 0)
5244 return isl_schedule_node_free(node);
5246 if (graph->n_edge == 0)
5247 return node;
5249 if (detect_sccs(ctx, graph) < 0)
5250 return isl_schedule_node_free(node);
5252 next_band(graph);
5253 if (graph->scc < graph->n) {
5254 if (!initialized && compute_maxvar(graph) < 0)
5255 return isl_schedule_node_free(node);
5256 return carry_dependences(node, graph);
5259 filters = extract_sccs(ctx, graph);
5260 node = isl_schedule_node_insert_sequence(node, filters);
5262 return node;
5265 /* Are there any (non-empty) (conditional) validity edges in the graph?
5267 static int has_validity_edges(struct isl_sched_graph *graph)
5269 int i;
5271 for (i = 0; i < graph->n_edge; ++i) {
5272 int empty;
5274 empty = isl_map_plain_is_empty(graph->edge[i].map);
5275 if (empty < 0)
5276 return -1;
5277 if (empty)
5278 continue;
5279 if (is_any_validity(&graph->edge[i]))
5280 return 1;
5283 return 0;
5286 /* Should we apply a Feautrier step?
5287 * That is, did the user request the Feautrier algorithm and are
5288 * there any validity dependences (left)?
5290 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
5292 if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
5293 return 0;
5295 return has_validity_edges(graph);
5298 /* Compute a schedule for a connected dependence graph using Feautrier's
5299 * multi-dimensional scheduling algorithm and return the updated schedule node.
5301 * The original algorithm is described in [1].
5302 * The main idea is to minimize the number of scheduling dimensions, by
5303 * trying to satisfy as many dependences as possible per scheduling dimension.
5305 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
5306 * Problem, Part II: Multi-Dimensional Time.
5307 * In Intl. Journal of Parallel Programming, 1992.
5309 static __isl_give isl_schedule_node *compute_schedule_wcc_feautrier(
5310 isl_schedule_node *node, struct isl_sched_graph *graph)
5312 return carry_feautrier(node, graph);
5315 /* Turn off the "local" bit on all (condition) edges.
5317 static void clear_local_edges(struct isl_sched_graph *graph)
5319 int i;
5321 for (i = 0; i < graph->n_edge; ++i)
5322 if (is_condition(&graph->edge[i]))
5323 clear_local(&graph->edge[i]);
5326 /* Does "graph" have both condition and conditional validity edges?
5328 static int need_condition_check(struct isl_sched_graph *graph)
5330 int i;
5331 int any_condition = 0;
5332 int any_conditional_validity = 0;
5334 for (i = 0; i < graph->n_edge; ++i) {
5335 if (is_condition(&graph->edge[i]))
5336 any_condition = 1;
5337 if (is_conditional_validity(&graph->edge[i]))
5338 any_conditional_validity = 1;
5341 return any_condition && any_conditional_validity;
5344 /* Does "graph" contain any coincidence edge?
5346 static int has_any_coincidence(struct isl_sched_graph *graph)
5348 int i;
5350 for (i = 0; i < graph->n_edge; ++i)
5351 if (is_coincidence(&graph->edge[i]))
5352 return 1;
5354 return 0;
5357 /* Extract the final schedule row as a map with the iteration domain
5358 * of "node" as domain.
5360 static __isl_give isl_map *final_row(struct isl_sched_node *node)
5362 isl_multi_aff *ma;
5363 int row;
5365 row = isl_mat_rows(node->sched) - 1;
5366 ma = node_extract_partial_schedule_multi_aff(node, row, 1);
5367 return isl_map_from_multi_aff(ma);
5370 /* Is the conditional validity dependence in the edge with index "edge_index"
5371 * violated by the latest (i.e., final) row of the schedule?
5372 * That is, is i scheduled after j
5373 * for any conditional validity dependence i -> j?
5375 static int is_violated(struct isl_sched_graph *graph, int edge_index)
5377 isl_map *src_sched, *dst_sched, *map;
5378 struct isl_sched_edge *edge = &graph->edge[edge_index];
5379 int empty;
5381 src_sched = final_row(edge->src);
5382 dst_sched = final_row(edge->dst);
5383 map = isl_map_copy(edge->map);
5384 map = isl_map_apply_domain(map, src_sched);
5385 map = isl_map_apply_range(map, dst_sched);
5386 map = isl_map_order_gt(map, isl_dim_in, 0, isl_dim_out, 0);
5387 empty = isl_map_is_empty(map);
5388 isl_map_free(map);
5390 if (empty < 0)
5391 return -1;
5393 return !empty;
5396 /* Does "graph" have any satisfied condition edges that
5397 * are adjacent to the conditional validity constraint with
5398 * domain "conditional_source" and range "conditional_sink"?
5400 * A satisfied condition is one that is not local.
5401 * If a condition was forced to be local already (i.e., marked as local)
5402 * then there is no need to check if it is in fact local.
5404 * Additionally, mark all adjacent condition edges found as local.
5406 static int has_adjacent_true_conditions(struct isl_sched_graph *graph,
5407 __isl_keep isl_union_set *conditional_source,
5408 __isl_keep isl_union_set *conditional_sink)
5410 int i;
5411 int any = 0;
5413 for (i = 0; i < graph->n_edge; ++i) {
5414 int adjacent, local;
5415 isl_union_map *condition;
5417 if (!is_condition(&graph->edge[i]))
5418 continue;
5419 if (is_local(&graph->edge[i]))
5420 continue;
5422 condition = graph->edge[i].tagged_condition;
5423 adjacent = domain_intersects(condition, conditional_sink);
5424 if (adjacent >= 0 && !adjacent)
5425 adjacent = range_intersects(condition,
5426 conditional_source);
5427 if (adjacent < 0)
5428 return -1;
5429 if (!adjacent)
5430 continue;
5432 set_local(&graph->edge[i]);
5434 local = is_condition_false(&graph->edge[i]);
5435 if (local < 0)
5436 return -1;
5437 if (!local)
5438 any = 1;
5441 return any;
5444 /* Are there any violated conditional validity dependences with
5445 * adjacent condition dependences that are not local with respect
5446 * to the current schedule?
5447 * That is, is the conditional validity constraint violated?
5449 * Additionally, mark all those adjacent condition dependences as local.
5450 * We also mark those adjacent condition dependences that were not marked
5451 * as local before, but just happened to be local already. This ensures
5452 * that they remain local if the schedule is recomputed.
5454 * We first collect domain and range of all violated conditional validity
5455 * dependences and then check if there are any adjacent non-local
5456 * condition dependences.
5458 static int has_violated_conditional_constraint(isl_ctx *ctx,
5459 struct isl_sched_graph *graph)
5461 int i;
5462 int any = 0;
5463 isl_union_set *source, *sink;
5465 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
5466 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
5467 for (i = 0; i < graph->n_edge; ++i) {
5468 isl_union_set *uset;
5469 isl_union_map *umap;
5470 int violated;
5472 if (!is_conditional_validity(&graph->edge[i]))
5473 continue;
5475 violated = is_violated(graph, i);
5476 if (violated < 0)
5477 goto error;
5478 if (!violated)
5479 continue;
5481 any = 1;
5483 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
5484 uset = isl_union_map_domain(umap);
5485 source = isl_union_set_union(source, uset);
5486 source = isl_union_set_coalesce(source);
5488 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
5489 uset = isl_union_map_range(umap);
5490 sink = isl_union_set_union(sink, uset);
5491 sink = isl_union_set_coalesce(sink);
5494 if (any)
5495 any = has_adjacent_true_conditions(graph, source, sink);
5497 isl_union_set_free(source);
5498 isl_union_set_free(sink);
5499 return any;
5500 error:
5501 isl_union_set_free(source);
5502 isl_union_set_free(sink);
5503 return -1;
5506 /* Examine the current band (the rows between graph->band_start and
5507 * graph->n_total_row), deciding whether to drop it or add it to "node"
5508 * and then continue with the computation of the next band, if any.
5509 * If "initialized" is set, then it may be assumed that compute_maxvar
5510 * has been called on the current band. Otherwise, call
5511 * compute_maxvar if and before carry_dependences gets called.
5513 * The caller keeps looking for a new row as long as
5514 * graph->n_row < graph->maxvar. If the latest attempt to find
5515 * such a row failed (i.e., we still have graph->n_row < graph->maxvar),
5516 * then we either
5517 * - split between SCCs and start over (assuming we found an interesting
5518 * pair of SCCs between which to split)
5519 * - continue with the next band (assuming the current band has at least
5520 * one row)
5521 * - if there is more than one SCC left, then split along all SCCs
5522 * - if outer coincidence needs to be enforced, then try to carry as many
5523 * validity or coincidence dependences as possible and
5524 * continue with the next band
5525 * - try to carry as many validity dependences as possible and
5526 * continue with the next band
5527 * In each case, we first insert a band node in the schedule tree
5528 * if any rows have been computed.
5530 * If the caller managed to complete the schedule and the current band
5531 * is empty, then finish off by topologically
5532 * sorting the statements based on the remaining dependences.
5533 * If, on the other hand, the current band has at least one row,
5534 * then continue with the next band. Note that this next band
5535 * will necessarily be empty, but the graph may still be split up
5536 * into weakly connected components before arriving back here.
5538 static __isl_give isl_schedule_node *compute_schedule_finish_band(
5539 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
5540 int initialized)
5542 int empty;
5544 if (!node)
5545 return NULL;
5547 empty = graph->n_total_row == graph->band_start;
5548 if (graph->n_row < graph->maxvar) {
5549 isl_ctx *ctx;
5551 ctx = isl_schedule_node_get_ctx(node);
5552 if (!ctx->opt->schedule_maximize_band_depth && !empty)
5553 return compute_next_band(node, graph, 1);
5554 if (graph->src_scc >= 0)
5555 return compute_split_schedule(node, graph);
5556 if (!empty)
5557 return compute_next_band(node, graph, 1);
5558 if (graph->scc > 1)
5559 return compute_component_schedule(node, graph, 1);
5560 if (!initialized && compute_maxvar(graph) < 0)
5561 return isl_schedule_node_free(node);
5562 if (isl_options_get_schedule_outer_coincidence(ctx))
5563 return carry_coincidence(node, graph);
5564 return carry_dependences(node, graph);
5567 if (!empty)
5568 return compute_next_band(node, graph, 1);
5569 return sort_statements(node, graph, initialized);
5572 /* Construct a band of schedule rows for a connected dependence graph.
5573 * The caller is responsible for determining the strongly connected
5574 * components and calling compute_maxvar first.
5576 * We try to find a sequence of as many schedule rows as possible that result
5577 * in non-negative dependence distances (independent of the previous rows
5578 * in the sequence, i.e., such that the sequence is tilable), with as
5579 * many of the initial rows as possible satisfying the coincidence constraints.
5580 * The computation stops if we can't find any more rows or if we have found
5581 * all the rows we wanted to find.
5583 * If ctx->opt->schedule_outer_coincidence is set, then we force the
5584 * outermost dimension to satisfy the coincidence constraints. If this
5585 * turns out to be impossible, we fall back on the general scheme above
5586 * and try to carry as many dependences as possible.
5588 * If "graph" contains both condition and conditional validity dependences,
5589 * then we need to check that that the conditional schedule constraint
5590 * is satisfied, i.e., there are no violated conditional validity dependences
5591 * that are adjacent to any non-local condition dependences.
5592 * If there are, then we mark all those adjacent condition dependences
5593 * as local and recompute the current band. Those dependences that
5594 * are marked local will then be forced to be local.
5595 * The initial computation is performed with no dependences marked as local.
5596 * If we are lucky, then there will be no violated conditional validity
5597 * dependences adjacent to any non-local condition dependences.
5598 * Otherwise, we mark some additional condition dependences as local and
5599 * recompute. We continue this process until there are no violations left or
5600 * until we are no longer able to compute a schedule.
5601 * Since there are only a finite number of dependences,
5602 * there will only be a finite number of iterations.
5604 static isl_stat compute_schedule_wcc_band(isl_ctx *ctx,
5605 struct isl_sched_graph *graph)
5607 int has_coincidence;
5608 int use_coincidence;
5609 int force_coincidence = 0;
5610 int check_conditional;
5612 if (sort_sccs(graph) < 0)
5613 return isl_stat_error;
5615 clear_local_edges(graph);
5616 check_conditional = need_condition_check(graph);
5617 has_coincidence = has_any_coincidence(graph);
5619 if (ctx->opt->schedule_outer_coincidence)
5620 force_coincidence = 1;
5622 use_coincidence = has_coincidence;
5623 while (graph->n_row < graph->maxvar) {
5624 isl_vec *sol;
5625 int violated;
5626 int coincident;
5628 graph->src_scc = -1;
5629 graph->dst_scc = -1;
5631 if (setup_lp(ctx, graph, use_coincidence) < 0)
5632 return isl_stat_error;
5633 sol = solve_lp(ctx, graph);
5634 if (!sol)
5635 return isl_stat_error;
5636 if (sol->size == 0) {
5637 int empty = graph->n_total_row == graph->band_start;
5639 isl_vec_free(sol);
5640 if (use_coincidence && (!force_coincidence || !empty)) {
5641 use_coincidence = 0;
5642 continue;
5644 return isl_stat_ok;
5646 coincident = !has_coincidence || use_coincidence;
5647 if (update_schedule(graph, sol, coincident) < 0)
5648 return isl_stat_error;
5650 if (!check_conditional)
5651 continue;
5652 violated = has_violated_conditional_constraint(ctx, graph);
5653 if (violated < 0)
5654 return isl_stat_error;
5655 if (!violated)
5656 continue;
5657 if (reset_band(graph) < 0)
5658 return isl_stat_error;
5659 use_coincidence = has_coincidence;
5662 return isl_stat_ok;
5665 /* Compute a schedule for a connected dependence graph by considering
5666 * the graph as a whole and return the updated schedule node.
5668 * The actual schedule rows of the current band are computed by
5669 * compute_schedule_wcc_band. compute_schedule_finish_band takes
5670 * care of integrating the band into "node" and continuing
5671 * the computation.
5673 static __isl_give isl_schedule_node *compute_schedule_wcc_whole(
5674 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5676 isl_ctx *ctx;
5678 if (!node)
5679 return NULL;
5681 ctx = isl_schedule_node_get_ctx(node);
5682 if (compute_schedule_wcc_band(ctx, graph) < 0)
5683 return isl_schedule_node_free(node);
5685 return compute_schedule_finish_band(node, graph, 1);
5688 /* Clustering information used by compute_schedule_wcc_clustering.
5690 * "n" is the number of SCCs in the original dependence graph
5691 * "scc" is an array of "n" elements, each representing an SCC
5692 * of the original dependence graph. All entries in the same cluster
5693 * have the same number of schedule rows.
5694 * "scc_cluster" maps each SCC index to the cluster to which it belongs,
5695 * where each cluster is represented by the index of the first SCC
5696 * in the cluster. Initially, each SCC belongs to a cluster containing
5697 * only that SCC.
5699 * "scc_in_merge" is used by merge_clusters_along_edge to keep
5700 * track of which SCCs need to be merged.
5702 * "cluster" contains the merged clusters of SCCs after the clustering
5703 * has completed.
5705 * "scc_node" is a temporary data structure used inside copy_partial.
5706 * For each SCC, it keeps track of the number of nodes in the SCC
5707 * that have already been copied.
5709 struct isl_clustering {
5710 int n;
5711 struct isl_sched_graph *scc;
5712 struct isl_sched_graph *cluster;
5713 int *scc_cluster;
5714 int *scc_node;
5715 int *scc_in_merge;
5718 /* Initialize the clustering data structure "c" from "graph".
5720 * In particular, allocate memory, extract the SCCs from "graph"
5721 * into c->scc, initialize scc_cluster and construct
5722 * a band of schedule rows for each SCC.
5723 * Within each SCC, there is only one SCC by definition.
5724 * Each SCC initially belongs to a cluster containing only that SCC.
5726 static isl_stat clustering_init(isl_ctx *ctx, struct isl_clustering *c,
5727 struct isl_sched_graph *graph)
5729 int i;
5731 c->n = graph->scc;
5732 c->scc = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5733 c->cluster = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5734 c->scc_cluster = isl_calloc_array(ctx, int, c->n);
5735 c->scc_node = isl_calloc_array(ctx, int, c->n);
5736 c->scc_in_merge = isl_calloc_array(ctx, int, c->n);
5737 if (!c->scc || !c->cluster ||
5738 !c->scc_cluster || !c->scc_node || !c->scc_in_merge)
5739 return isl_stat_error;
5741 for (i = 0; i < c->n; ++i) {
5742 if (extract_sub_graph(ctx, graph, &node_scc_exactly,
5743 &edge_scc_exactly, i, &c->scc[i]) < 0)
5744 return isl_stat_error;
5745 c->scc[i].scc = 1;
5746 if (compute_maxvar(&c->scc[i]) < 0)
5747 return isl_stat_error;
5748 if (compute_schedule_wcc_band(ctx, &c->scc[i]) < 0)
5749 return isl_stat_error;
5750 c->scc_cluster[i] = i;
5753 return isl_stat_ok;
5756 /* Free all memory allocated for "c".
5758 static void clustering_free(isl_ctx *ctx, struct isl_clustering *c)
5760 int i;
5762 if (c->scc)
5763 for (i = 0; i < c->n; ++i)
5764 graph_free(ctx, &c->scc[i]);
5765 free(c->scc);
5766 if (c->cluster)
5767 for (i = 0; i < c->n; ++i)
5768 graph_free(ctx, &c->cluster[i]);
5769 free(c->cluster);
5770 free(c->scc_cluster);
5771 free(c->scc_node);
5772 free(c->scc_in_merge);
5775 /* Should we refrain from merging the cluster in "graph" with
5776 * any other cluster?
5777 * In particular, is its current schedule band empty and incomplete.
5779 static int bad_cluster(struct isl_sched_graph *graph)
5781 return graph->n_row < graph->maxvar &&
5782 graph->n_total_row == graph->band_start;
5785 /* Is "edge" a proximity edge with a non-empty dependence relation?
5787 static isl_bool is_non_empty_proximity(struct isl_sched_edge *edge)
5789 if (!is_proximity(edge))
5790 return isl_bool_false;
5791 return isl_bool_not(isl_map_plain_is_empty(edge->map));
5794 /* Return the index of an edge in "graph" that can be used to merge
5795 * two clusters in "c".
5796 * Return graph->n_edge if no such edge can be found.
5797 * Return -1 on error.
5799 * In particular, return a proximity edge between two clusters
5800 * that is not marked "no_merge" and such that neither of the
5801 * two clusters has an incomplete, empty band.
5803 * If there are multiple such edges, then try and find the most
5804 * appropriate edge to use for merging. In particular, pick the edge
5805 * with the greatest weight. If there are multiple of those,
5806 * then pick one with the shortest distance between
5807 * the two cluster representatives.
5809 static int find_proximity(struct isl_sched_graph *graph,
5810 struct isl_clustering *c)
5812 int i, best = graph->n_edge, best_dist, best_weight;
5814 for (i = 0; i < graph->n_edge; ++i) {
5815 struct isl_sched_edge *edge = &graph->edge[i];
5816 int dist, weight;
5817 isl_bool prox;
5819 prox = is_non_empty_proximity(edge);
5820 if (prox < 0)
5821 return -1;
5822 if (!prox)
5823 continue;
5824 if (edge->no_merge)
5825 continue;
5826 if (bad_cluster(&c->scc[edge->src->scc]) ||
5827 bad_cluster(&c->scc[edge->dst->scc]))
5828 continue;
5829 dist = c->scc_cluster[edge->dst->scc] -
5830 c->scc_cluster[edge->src->scc];
5831 if (dist == 0)
5832 continue;
5833 weight = edge->weight;
5834 if (best < graph->n_edge) {
5835 if (best_weight > weight)
5836 continue;
5837 if (best_weight == weight && best_dist <= dist)
5838 continue;
5840 best = i;
5841 best_dist = dist;
5842 best_weight = weight;
5845 return best;
5848 /* Internal data structure used in mark_merge_sccs.
5850 * "graph" is the dependence graph in which a strongly connected
5851 * component is constructed.
5852 * "scc_cluster" maps each SCC index to the cluster to which it belongs.
5853 * "src" and "dst" are the indices of the nodes that are being merged.
5855 struct isl_mark_merge_sccs_data {
5856 struct isl_sched_graph *graph;
5857 int *scc_cluster;
5858 int src;
5859 int dst;
5862 /* Check whether the cluster containing node "i" depends on the cluster
5863 * containing node "j". If "i" and "j" belong to the same cluster,
5864 * then they are taken to depend on each other to ensure that
5865 * the resulting strongly connected component consists of complete
5866 * clusters. Furthermore, if "i" and "j" are the two nodes that
5867 * are being merged, then they are taken to depend on each other as well.
5868 * Otherwise, check if there is a (conditional) validity dependence
5869 * from node[j] to node[i], forcing node[i] to follow node[j].
5871 static isl_bool cluster_follows(int i, int j, void *user)
5873 struct isl_mark_merge_sccs_data *data = user;
5874 struct isl_sched_graph *graph = data->graph;
5875 int *scc_cluster = data->scc_cluster;
5877 if (data->src == i && data->dst == j)
5878 return isl_bool_true;
5879 if (data->src == j && data->dst == i)
5880 return isl_bool_true;
5881 if (scc_cluster[graph->node[i].scc] == scc_cluster[graph->node[j].scc])
5882 return isl_bool_true;
5884 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
5887 /* Mark all SCCs that belong to either of the two clusters in "c"
5888 * connected by the edge in "graph" with index "edge", or to any
5889 * of the intermediate clusters.
5890 * The marking is recorded in c->scc_in_merge.
5892 * The given edge has been selected for merging two clusters,
5893 * meaning that there is at least a proximity edge between the two nodes.
5894 * However, there may also be (indirect) validity dependences
5895 * between the two nodes. When merging the two clusters, all clusters
5896 * containing one or more of the intermediate nodes along the
5897 * indirect validity dependences need to be merged in as well.
5899 * First collect all such nodes by computing the strongly connected
5900 * component (SCC) containing the two nodes connected by the edge, where
5901 * the two nodes are considered to depend on each other to make
5902 * sure they end up in the same SCC. Similarly, each node is considered
5903 * to depend on every other node in the same cluster to ensure
5904 * that the SCC consists of complete clusters.
5906 * Then the original SCCs that contain any of these nodes are marked
5907 * in c->scc_in_merge.
5909 static isl_stat mark_merge_sccs(isl_ctx *ctx, struct isl_sched_graph *graph,
5910 int edge, struct isl_clustering *c)
5912 struct isl_mark_merge_sccs_data data;
5913 struct isl_tarjan_graph *g;
5914 int i;
5916 for (i = 0; i < c->n; ++i)
5917 c->scc_in_merge[i] = 0;
5919 data.graph = graph;
5920 data.scc_cluster = c->scc_cluster;
5921 data.src = graph->edge[edge].src - graph->node;
5922 data.dst = graph->edge[edge].dst - graph->node;
5924 g = isl_tarjan_graph_component(ctx, graph->n, data.dst,
5925 &cluster_follows, &data);
5926 if (!g)
5927 goto error;
5929 i = g->op;
5930 if (i < 3)
5931 isl_die(ctx, isl_error_internal,
5932 "expecting at least two nodes in component",
5933 goto error);
5934 if (g->order[--i] != -1)
5935 isl_die(ctx, isl_error_internal,
5936 "expecting end of component marker", goto error);
5938 for (--i; i >= 0 && g->order[i] != -1; --i) {
5939 int scc = graph->node[g->order[i]].scc;
5940 c->scc_in_merge[scc] = 1;
5943 isl_tarjan_graph_free(g);
5944 return isl_stat_ok;
5945 error:
5946 isl_tarjan_graph_free(g);
5947 return isl_stat_error;
5950 /* Construct the identifier "cluster_i".
5952 static __isl_give isl_id *cluster_id(isl_ctx *ctx, int i)
5954 char name[40];
5956 snprintf(name, sizeof(name), "cluster_%d", i);
5957 return isl_id_alloc(ctx, name, NULL);
5960 /* Construct the space of the cluster with index "i" containing
5961 * the strongly connected component "scc".
5963 * In particular, construct a space called cluster_i with dimension equal
5964 * to the number of schedule rows in the current band of "scc".
5966 static __isl_give isl_space *cluster_space(struct isl_sched_graph *scc, int i)
5968 int nvar;
5969 isl_space *space;
5970 isl_id *id;
5972 nvar = scc->n_total_row - scc->band_start;
5973 space = isl_space_copy(scc->node[0].space);
5974 space = isl_space_params(space);
5975 space = isl_space_set_from_params(space);
5976 space = isl_space_add_dims(space, isl_dim_set, nvar);
5977 id = cluster_id(isl_space_get_ctx(space), i);
5978 space = isl_space_set_tuple_id(space, isl_dim_set, id);
5980 return space;
5983 /* Collect the domain of the graph for merging clusters.
5985 * In particular, for each cluster with first SCC "i", construct
5986 * a set in the space called cluster_i with dimension equal
5987 * to the number of schedule rows in the current band of the cluster.
5989 static __isl_give isl_union_set *collect_domain(isl_ctx *ctx,
5990 struct isl_sched_graph *graph, struct isl_clustering *c)
5992 int i;
5993 isl_space *space;
5994 isl_union_set *domain;
5996 space = isl_space_params_alloc(ctx, 0);
5997 domain = isl_union_set_empty(space);
5999 for (i = 0; i < graph->scc; ++i) {
6000 isl_space *space;
6002 if (!c->scc_in_merge[i])
6003 continue;
6004 if (c->scc_cluster[i] != i)
6005 continue;
6006 space = cluster_space(&c->scc[i], i);
6007 domain = isl_union_set_add_set(domain, isl_set_universe(space));
6010 return domain;
6013 /* Construct a map from the original instances to the corresponding
6014 * cluster instance in the current bands of the clusters in "c".
6016 static __isl_give isl_union_map *collect_cluster_map(isl_ctx *ctx,
6017 struct isl_sched_graph *graph, struct isl_clustering *c)
6019 int i, j;
6020 isl_space *space;
6021 isl_union_map *cluster_map;
6023 space = isl_space_params_alloc(ctx, 0);
6024 cluster_map = isl_union_map_empty(space);
6025 for (i = 0; i < graph->scc; ++i) {
6026 int start, n;
6027 isl_id *id;
6029 if (!c->scc_in_merge[i])
6030 continue;
6032 id = cluster_id(ctx, c->scc_cluster[i]);
6033 start = c->scc[i].band_start;
6034 n = c->scc[i].n_total_row - start;
6035 for (j = 0; j < c->scc[i].n; ++j) {
6036 isl_multi_aff *ma;
6037 isl_map *map;
6038 struct isl_sched_node *node = &c->scc[i].node[j];
6040 ma = node_extract_partial_schedule_multi_aff(node,
6041 start, n);
6042 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out,
6043 isl_id_copy(id));
6044 map = isl_map_from_multi_aff(ma);
6045 cluster_map = isl_union_map_add_map(cluster_map, map);
6047 isl_id_free(id);
6050 return cluster_map;
6053 /* Add "umap" to the schedule constraints "sc" of all types of "edge"
6054 * that are not isl_edge_condition or isl_edge_conditional_validity.
6056 static __isl_give isl_schedule_constraints *add_non_conditional_constraints(
6057 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
6058 __isl_take isl_schedule_constraints *sc)
6060 enum isl_edge_type t;
6062 if (!sc)
6063 return NULL;
6065 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
6066 if (t == isl_edge_condition ||
6067 t == isl_edge_conditional_validity)
6068 continue;
6069 if (!is_type(edge, t))
6070 continue;
6071 sc = isl_schedule_constraints_add(sc, t,
6072 isl_union_map_copy(umap));
6075 return sc;
6078 /* Add schedule constraints of types isl_edge_condition and
6079 * isl_edge_conditional_validity to "sc" by applying "umap" to
6080 * the domains of the wrapped relations in domain and range
6081 * of the corresponding tagged constraints of "edge".
6083 static __isl_give isl_schedule_constraints *add_conditional_constraints(
6084 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
6085 __isl_take isl_schedule_constraints *sc)
6087 enum isl_edge_type t;
6088 isl_union_map *tagged;
6090 for (t = isl_edge_condition; t <= isl_edge_conditional_validity; ++t) {
6091 if (!is_type(edge, t))
6092 continue;
6093 if (t == isl_edge_condition)
6094 tagged = isl_union_map_copy(edge->tagged_condition);
6095 else
6096 tagged = isl_union_map_copy(edge->tagged_validity);
6097 tagged = isl_union_map_zip(tagged);
6098 tagged = isl_union_map_apply_domain(tagged,
6099 isl_union_map_copy(umap));
6100 tagged = isl_union_map_zip(tagged);
6101 sc = isl_schedule_constraints_add(sc, t, tagged);
6102 if (!sc)
6103 return NULL;
6106 return sc;
6109 /* Given a mapping "cluster_map" from the original instances to
6110 * the cluster instances, add schedule constraints on the clusters
6111 * to "sc" corresponding to the original constraints represented by "edge".
6113 * For non-tagged dependence constraints, the cluster constraints
6114 * are obtained by applying "cluster_map" to the edge->map.
6116 * For tagged dependence constraints, "cluster_map" needs to be applied
6117 * to the domains of the wrapped relations in domain and range
6118 * of the tagged dependence constraints. Pick out the mappings
6119 * from these domains from "cluster_map" and construct their product.
6120 * This mapping can then be applied to the pair of domains.
6122 static __isl_give isl_schedule_constraints *collect_edge_constraints(
6123 struct isl_sched_edge *edge, __isl_keep isl_union_map *cluster_map,
6124 __isl_take isl_schedule_constraints *sc)
6126 isl_union_map *umap;
6127 isl_space *space;
6128 isl_union_set *uset;
6129 isl_union_map *umap1, *umap2;
6131 if (!sc)
6132 return NULL;
6134 umap = isl_union_map_from_map(isl_map_copy(edge->map));
6135 umap = isl_union_map_apply_domain(umap,
6136 isl_union_map_copy(cluster_map));
6137 umap = isl_union_map_apply_range(umap,
6138 isl_union_map_copy(cluster_map));
6139 sc = add_non_conditional_constraints(edge, umap, sc);
6140 isl_union_map_free(umap);
6142 if (!sc || (!is_condition(edge) && !is_conditional_validity(edge)))
6143 return sc;
6145 space = isl_space_domain(isl_map_get_space(edge->map));
6146 uset = isl_union_set_from_set(isl_set_universe(space));
6147 umap1 = isl_union_map_copy(cluster_map);
6148 umap1 = isl_union_map_intersect_domain(umap1, uset);
6149 space = isl_space_range(isl_map_get_space(edge->map));
6150 uset = isl_union_set_from_set(isl_set_universe(space));
6151 umap2 = isl_union_map_copy(cluster_map);
6152 umap2 = isl_union_map_intersect_domain(umap2, uset);
6153 umap = isl_union_map_product(umap1, umap2);
6155 sc = add_conditional_constraints(edge, umap, sc);
6157 isl_union_map_free(umap);
6158 return sc;
6161 /* Given a mapping "cluster_map" from the original instances to
6162 * the cluster instances, add schedule constraints on the clusters
6163 * to "sc" corresponding to all edges in "graph" between nodes that
6164 * belong to SCCs that are marked for merging in "scc_in_merge".
6166 static __isl_give isl_schedule_constraints *collect_constraints(
6167 struct isl_sched_graph *graph, int *scc_in_merge,
6168 __isl_keep isl_union_map *cluster_map,
6169 __isl_take isl_schedule_constraints *sc)
6171 int i;
6173 for (i = 0; i < graph->n_edge; ++i) {
6174 struct isl_sched_edge *edge = &graph->edge[i];
6176 if (!scc_in_merge[edge->src->scc])
6177 continue;
6178 if (!scc_in_merge[edge->dst->scc])
6179 continue;
6180 sc = collect_edge_constraints(edge, cluster_map, sc);
6183 return sc;
6186 /* Construct a dependence graph for scheduling clusters with respect
6187 * to each other and store the result in "merge_graph".
6188 * In particular, the nodes of the graph correspond to the schedule
6189 * dimensions of the current bands of those clusters that have been
6190 * marked for merging in "c".
6192 * First construct an isl_schedule_constraints object for this domain
6193 * by transforming the edges in "graph" to the domain.
6194 * Then initialize a dependence graph for scheduling from these
6195 * constraints.
6197 static isl_stat init_merge_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
6198 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6200 isl_union_set *domain;
6201 isl_union_map *cluster_map;
6202 isl_schedule_constraints *sc;
6203 isl_stat r;
6205 domain = collect_domain(ctx, graph, c);
6206 sc = isl_schedule_constraints_on_domain(domain);
6207 if (!sc)
6208 return isl_stat_error;
6209 cluster_map = collect_cluster_map(ctx, graph, c);
6210 sc = collect_constraints(graph, c->scc_in_merge, cluster_map, sc);
6211 isl_union_map_free(cluster_map);
6213 r = graph_init(merge_graph, sc);
6215 isl_schedule_constraints_free(sc);
6217 return r;
6220 /* Compute the maximal number of remaining schedule rows that still need
6221 * to be computed for the nodes that belong to clusters with the maximal
6222 * dimension for the current band (i.e., the band that is to be merged).
6223 * Only clusters that are about to be merged are considered.
6224 * "maxvar" is the maximal dimension for the current band.
6225 * "c" contains information about the clusters.
6227 * Return the maximal number of remaining schedule rows or -1 on error.
6229 static int compute_maxvar_max_slack(int maxvar, struct isl_clustering *c)
6231 int i, j;
6232 int max_slack;
6234 max_slack = 0;
6235 for (i = 0; i < c->n; ++i) {
6236 int nvar;
6237 struct isl_sched_graph *scc;
6239 if (!c->scc_in_merge[i])
6240 continue;
6241 scc = &c->scc[i];
6242 nvar = scc->n_total_row - scc->band_start;
6243 if (nvar != maxvar)
6244 continue;
6245 for (j = 0; j < scc->n; ++j) {
6246 struct isl_sched_node *node = &scc->node[j];
6247 int slack;
6249 if (node_update_vmap(node) < 0)
6250 return -1;
6251 slack = node->nvar - node->rank;
6252 if (slack > max_slack)
6253 max_slack = slack;
6257 return max_slack;
6260 /* If there are any clusters where the dimension of the current band
6261 * (i.e., the band that is to be merged) is smaller than "maxvar" and
6262 * if there are any nodes in such a cluster where the number
6263 * of remaining schedule rows that still need to be computed
6264 * is greater than "max_slack", then return the smallest current band
6265 * dimension of all these clusters. Otherwise return the original value
6266 * of "maxvar". Return -1 in case of any error.
6267 * Only clusters that are about to be merged are considered.
6268 * "c" contains information about the clusters.
6270 static int limit_maxvar_to_slack(int maxvar, int max_slack,
6271 struct isl_clustering *c)
6273 int i, j;
6275 for (i = 0; i < c->n; ++i) {
6276 int nvar;
6277 struct isl_sched_graph *scc;
6279 if (!c->scc_in_merge[i])
6280 continue;
6281 scc = &c->scc[i];
6282 nvar = scc->n_total_row - scc->band_start;
6283 if (nvar >= maxvar)
6284 continue;
6285 for (j = 0; j < scc->n; ++j) {
6286 struct isl_sched_node *node = &scc->node[j];
6287 int slack;
6289 if (node_update_vmap(node) < 0)
6290 return -1;
6291 slack = node->nvar - node->rank;
6292 if (slack > max_slack) {
6293 maxvar = nvar;
6294 break;
6299 return maxvar;
6302 /* Adjust merge_graph->maxvar based on the number of remaining schedule rows
6303 * that still need to be computed. In particular, if there is a node
6304 * in a cluster where the dimension of the current band is smaller
6305 * than merge_graph->maxvar, but the number of remaining schedule rows
6306 * is greater than that of any node in a cluster with the maximal
6307 * dimension for the current band (i.e., merge_graph->maxvar),
6308 * then adjust merge_graph->maxvar to the (smallest) current band dimension
6309 * of those clusters. Without this adjustment, the total number of
6310 * schedule dimensions would be increased, resulting in a skewed view
6311 * of the number of coincident dimensions.
6312 * "c" contains information about the clusters.
6314 * If the maximize_band_depth option is set and merge_graph->maxvar is reduced,
6315 * then there is no point in attempting any merge since it will be rejected
6316 * anyway. Set merge_graph->maxvar to zero in such cases.
6318 static isl_stat adjust_maxvar_to_slack(isl_ctx *ctx,
6319 struct isl_sched_graph *merge_graph, struct isl_clustering *c)
6321 int max_slack, maxvar;
6323 max_slack = compute_maxvar_max_slack(merge_graph->maxvar, c);
6324 if (max_slack < 0)
6325 return isl_stat_error;
6326 maxvar = limit_maxvar_to_slack(merge_graph->maxvar, max_slack, c);
6327 if (maxvar < 0)
6328 return isl_stat_error;
6330 if (maxvar < merge_graph->maxvar) {
6331 if (isl_options_get_schedule_maximize_band_depth(ctx))
6332 merge_graph->maxvar = 0;
6333 else
6334 merge_graph->maxvar = maxvar;
6337 return isl_stat_ok;
6340 /* Return the number of coincident dimensions in the current band of "graph",
6341 * where the nodes of "graph" are assumed to be scheduled by a single band.
6343 static int get_n_coincident(struct isl_sched_graph *graph)
6345 int i;
6347 for (i = graph->band_start; i < graph->n_total_row; ++i)
6348 if (!graph->node[0].coincident[i])
6349 break;
6351 return i - graph->band_start;
6354 /* Should the clusters be merged based on the cluster schedule
6355 * in the current (and only) band of "merge_graph", given that
6356 * coincidence should be maximized?
6358 * If the number of coincident schedule dimensions in the merged band
6359 * would be less than the maximal number of coincident schedule dimensions
6360 * in any of the merged clusters, then the clusters should not be merged.
6362 static isl_bool ok_to_merge_coincident(struct isl_clustering *c,
6363 struct isl_sched_graph *merge_graph)
6365 int i;
6366 int n_coincident;
6367 int max_coincident;
6369 max_coincident = 0;
6370 for (i = 0; i < c->n; ++i) {
6371 if (!c->scc_in_merge[i])
6372 continue;
6373 n_coincident = get_n_coincident(&c->scc[i]);
6374 if (n_coincident > max_coincident)
6375 max_coincident = n_coincident;
6378 n_coincident = get_n_coincident(merge_graph);
6380 return n_coincident >= max_coincident;
6383 /* Return the transformation on "node" expressed by the current (and only)
6384 * band of "merge_graph" applied to the clusters in "c".
6386 * First find the representation of "node" in its SCC in "c" and
6387 * extract the transformation expressed by the current band.
6388 * Then extract the transformation applied by "merge_graph"
6389 * to the cluster to which this SCC belongs.
6390 * Combine the two to obtain the complete transformation on the node.
6392 * Note that the range of the first transformation is an anonymous space,
6393 * while the domain of the second is named "cluster_X". The range
6394 * of the former therefore needs to be adjusted before the two
6395 * can be combined.
6397 static __isl_give isl_map *extract_node_transformation(isl_ctx *ctx,
6398 struct isl_sched_node *node, struct isl_clustering *c,
6399 struct isl_sched_graph *merge_graph)
6401 struct isl_sched_node *scc_node, *cluster_node;
6402 int start, n;
6403 isl_id *id;
6404 isl_space *space;
6405 isl_multi_aff *ma, *ma2;
6407 scc_node = graph_find_node(ctx, &c->scc[node->scc], node->space);
6408 start = c->scc[node->scc].band_start;
6409 n = c->scc[node->scc].n_total_row - start;
6410 ma = node_extract_partial_schedule_multi_aff(scc_node, start, n);
6411 space = cluster_space(&c->scc[node->scc], c->scc_cluster[node->scc]);
6412 cluster_node = graph_find_node(ctx, merge_graph, space);
6413 if (space && !cluster_node)
6414 isl_die(ctx, isl_error_internal, "unable to find cluster",
6415 space = isl_space_free(space));
6416 id = isl_space_get_tuple_id(space, isl_dim_set);
6417 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out, id);
6418 isl_space_free(space);
6419 n = merge_graph->n_total_row;
6420 ma2 = node_extract_partial_schedule_multi_aff(cluster_node, 0, n);
6421 ma = isl_multi_aff_pullback_multi_aff(ma2, ma);
6423 return isl_map_from_multi_aff(ma);
6426 /* Give a set of distances "set", are they bounded by a small constant
6427 * in direction "pos"?
6428 * In practice, check if they are bounded by 2 by checking that there
6429 * are no elements with a value greater than or equal to 3 or
6430 * smaller than or equal to -3.
6432 static isl_bool distance_is_bounded(__isl_keep isl_set *set, int pos)
6434 isl_bool bounded;
6435 isl_set *test;
6437 if (!set)
6438 return isl_bool_error;
6440 test = isl_set_copy(set);
6441 test = isl_set_lower_bound_si(test, isl_dim_set, pos, 3);
6442 bounded = isl_set_is_empty(test);
6443 isl_set_free(test);
6445 if (bounded < 0 || !bounded)
6446 return bounded;
6448 test = isl_set_copy(set);
6449 test = isl_set_upper_bound_si(test, isl_dim_set, pos, -3);
6450 bounded = isl_set_is_empty(test);
6451 isl_set_free(test);
6453 return bounded;
6456 /* Does the set "set" have a fixed (but possible parametric) value
6457 * at dimension "pos"?
6459 static isl_bool has_single_value(__isl_keep isl_set *set, int pos)
6461 int n;
6462 isl_bool single;
6464 if (!set)
6465 return isl_bool_error;
6466 set = isl_set_copy(set);
6467 n = isl_set_dim(set, isl_dim_set);
6468 set = isl_set_project_out(set, isl_dim_set, pos + 1, n - (pos + 1));
6469 set = isl_set_project_out(set, isl_dim_set, 0, pos);
6470 single = isl_set_is_singleton(set);
6471 isl_set_free(set);
6473 return single;
6476 /* Does "map" have a fixed (but possible parametric) value
6477 * at dimension "pos" of either its domain or its range?
6479 static isl_bool has_singular_src_or_dst(__isl_keep isl_map *map, int pos)
6481 isl_set *set;
6482 isl_bool single;
6484 set = isl_map_domain(isl_map_copy(map));
6485 single = has_single_value(set, pos);
6486 isl_set_free(set);
6488 if (single < 0 || single)
6489 return single;
6491 set = isl_map_range(isl_map_copy(map));
6492 single = has_single_value(set, pos);
6493 isl_set_free(set);
6495 return single;
6498 /* Does the edge "edge" from "graph" have bounded dependence distances
6499 * in the merged graph "merge_graph" of a selection of clusters in "c"?
6501 * Extract the complete transformations of the source and destination
6502 * nodes of the edge, apply them to the edge constraints and
6503 * compute the differences. Finally, check if these differences are bounded
6504 * in each direction.
6506 * If the dimension of the band is greater than the number of
6507 * dimensions that can be expected to be optimized by the edge
6508 * (based on its weight), then also allow the differences to be unbounded
6509 * in the remaining dimensions, but only if either the source or
6510 * the destination has a fixed value in that direction.
6511 * This allows a statement that produces values that are used by
6512 * several instances of another statement to be merged with that
6513 * other statement.
6514 * However, merging such clusters will introduce an inherently
6515 * large proximity distance inside the merged cluster, meaning
6516 * that proximity distances will no longer be optimized in
6517 * subsequent merges. These merges are therefore only allowed
6518 * after all other possible merges have been tried.
6519 * The first time such a merge is encountered, the weight of the edge
6520 * is replaced by a negative weight. The second time (i.e., after
6521 * all merges over edges with a non-negative weight have been tried),
6522 * the merge is allowed.
6524 static isl_bool has_bounded_distances(isl_ctx *ctx, struct isl_sched_edge *edge,
6525 struct isl_sched_graph *graph, struct isl_clustering *c,
6526 struct isl_sched_graph *merge_graph)
6528 int i, n, n_slack;
6529 isl_bool bounded;
6530 isl_map *map, *t;
6531 isl_set *dist;
6533 map = isl_map_copy(edge->map);
6534 t = extract_node_transformation(ctx, edge->src, c, merge_graph);
6535 map = isl_map_apply_domain(map, t);
6536 t = extract_node_transformation(ctx, edge->dst, c, merge_graph);
6537 map = isl_map_apply_range(map, t);
6538 dist = isl_map_deltas(isl_map_copy(map));
6540 bounded = isl_bool_true;
6541 n = isl_set_dim(dist, isl_dim_set);
6542 n_slack = n - edge->weight;
6543 if (edge->weight < 0)
6544 n_slack -= graph->max_weight + 1;
6545 for (i = 0; i < n; ++i) {
6546 isl_bool bounded_i, singular_i;
6548 bounded_i = distance_is_bounded(dist, i);
6549 if (bounded_i < 0)
6550 goto error;
6551 if (bounded_i)
6552 continue;
6553 if (edge->weight >= 0)
6554 bounded = isl_bool_false;
6555 n_slack--;
6556 if (n_slack < 0)
6557 break;
6558 singular_i = has_singular_src_or_dst(map, i);
6559 if (singular_i < 0)
6560 goto error;
6561 if (singular_i)
6562 continue;
6563 bounded = isl_bool_false;
6564 break;
6566 if (!bounded && i >= n && edge->weight >= 0)
6567 edge->weight -= graph->max_weight + 1;
6568 isl_map_free(map);
6569 isl_set_free(dist);
6571 return bounded;
6572 error:
6573 isl_map_free(map);
6574 isl_set_free(dist);
6575 return isl_bool_error;
6578 /* Should the clusters be merged based on the cluster schedule
6579 * in the current (and only) band of "merge_graph"?
6580 * "graph" is the original dependence graph, while "c" records
6581 * which SCCs are involved in the latest merge.
6583 * In particular, is there at least one proximity constraint
6584 * that is optimized by the merge?
6586 * A proximity constraint is considered to be optimized
6587 * if the dependence distances are small.
6589 static isl_bool ok_to_merge_proximity(isl_ctx *ctx,
6590 struct isl_sched_graph *graph, struct isl_clustering *c,
6591 struct isl_sched_graph *merge_graph)
6593 int i;
6595 for (i = 0; i < graph->n_edge; ++i) {
6596 struct isl_sched_edge *edge = &graph->edge[i];
6597 isl_bool bounded;
6599 if (!is_proximity(edge))
6600 continue;
6601 if (!c->scc_in_merge[edge->src->scc])
6602 continue;
6603 if (!c->scc_in_merge[edge->dst->scc])
6604 continue;
6605 if (c->scc_cluster[edge->dst->scc] ==
6606 c->scc_cluster[edge->src->scc])
6607 continue;
6608 bounded = has_bounded_distances(ctx, edge, graph, c,
6609 merge_graph);
6610 if (bounded < 0 || bounded)
6611 return bounded;
6614 return isl_bool_false;
6617 /* Should the clusters be merged based on the cluster schedule
6618 * in the current (and only) band of "merge_graph"?
6619 * "graph" is the original dependence graph, while "c" records
6620 * which SCCs are involved in the latest merge.
6622 * If the current band is empty, then the clusters should not be merged.
6624 * If the band depth should be maximized and the merge schedule
6625 * is incomplete (meaning that the dimension of some of the schedule
6626 * bands in the original schedule will be reduced), then the clusters
6627 * should not be merged.
6629 * If the schedule_maximize_coincidence option is set, then check that
6630 * the number of coincident schedule dimensions is not reduced.
6632 * Finally, only allow the merge if at least one proximity
6633 * constraint is optimized.
6635 static isl_bool ok_to_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6636 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6638 if (merge_graph->n_total_row == merge_graph->band_start)
6639 return isl_bool_false;
6641 if (isl_options_get_schedule_maximize_band_depth(ctx) &&
6642 merge_graph->n_total_row < merge_graph->maxvar)
6643 return isl_bool_false;
6645 if (isl_options_get_schedule_maximize_coincidence(ctx)) {
6646 isl_bool ok;
6648 ok = ok_to_merge_coincident(c, merge_graph);
6649 if (ok < 0 || !ok)
6650 return ok;
6653 return ok_to_merge_proximity(ctx, graph, c, merge_graph);
6656 /* Apply the schedule in "t_node" to the "n" rows starting at "first"
6657 * of the schedule in "node" and return the result.
6659 * That is, essentially compute
6661 * T * N(first:first+n-1)
6663 * taking into account the constant term and the parameter coefficients
6664 * in "t_node".
6666 static __isl_give isl_mat *node_transformation(isl_ctx *ctx,
6667 struct isl_sched_node *t_node, struct isl_sched_node *node,
6668 int first, int n)
6670 int i, j;
6671 isl_mat *t;
6672 int n_row, n_col, n_param, n_var;
6674 n_param = node->nparam;
6675 n_var = node->nvar;
6676 n_row = isl_mat_rows(t_node->sched);
6677 n_col = isl_mat_cols(node->sched);
6678 t = isl_mat_alloc(ctx, n_row, n_col);
6679 if (!t)
6680 return NULL;
6681 for (i = 0; i < n_row; ++i) {
6682 isl_seq_cpy(t->row[i], t_node->sched->row[i], 1 + n_param);
6683 isl_seq_clr(t->row[i] + 1 + n_param, n_var);
6684 for (j = 0; j < n; ++j)
6685 isl_seq_addmul(t->row[i],
6686 t_node->sched->row[i][1 + n_param + j],
6687 node->sched->row[first + j],
6688 1 + n_param + n_var);
6690 return t;
6693 /* Apply the cluster schedule in "t_node" to the current band
6694 * schedule of the nodes in "graph".
6696 * In particular, replace the rows starting at band_start
6697 * by the result of applying the cluster schedule in "t_node"
6698 * to the original rows.
6700 * The coincidence of the schedule is determined by the coincidence
6701 * of the cluster schedule.
6703 static isl_stat transform(isl_ctx *ctx, struct isl_sched_graph *graph,
6704 struct isl_sched_node *t_node)
6706 int i, j;
6707 int n_new;
6708 int start, n;
6710 start = graph->band_start;
6711 n = graph->n_total_row - start;
6713 n_new = isl_mat_rows(t_node->sched);
6714 for (i = 0; i < graph->n; ++i) {
6715 struct isl_sched_node *node = &graph->node[i];
6716 isl_mat *t;
6718 t = node_transformation(ctx, t_node, node, start, n);
6719 node->sched = isl_mat_drop_rows(node->sched, start, n);
6720 node->sched = isl_mat_concat(node->sched, t);
6721 node->sched_map = isl_map_free(node->sched_map);
6722 if (!node->sched)
6723 return isl_stat_error;
6724 for (j = 0; j < n_new; ++j)
6725 node->coincident[start + j] = t_node->coincident[j];
6727 graph->n_total_row -= n;
6728 graph->n_row -= n;
6729 graph->n_total_row += n_new;
6730 graph->n_row += n_new;
6732 return isl_stat_ok;
6735 /* Merge the clusters marked for merging in "c" into a single
6736 * cluster using the cluster schedule in the current band of "merge_graph".
6737 * The representative SCC for the new cluster is the SCC with
6738 * the smallest index.
6740 * The current band schedule of each SCC in the new cluster is obtained
6741 * by applying the schedule of the corresponding original cluster
6742 * to the original band schedule.
6743 * All SCCs in the new cluster have the same number of schedule rows.
6745 static isl_stat merge(isl_ctx *ctx, struct isl_clustering *c,
6746 struct isl_sched_graph *merge_graph)
6748 int i;
6749 int cluster = -1;
6750 isl_space *space;
6752 for (i = 0; i < c->n; ++i) {
6753 struct isl_sched_node *node;
6755 if (!c->scc_in_merge[i])
6756 continue;
6757 if (cluster < 0)
6758 cluster = i;
6759 space = cluster_space(&c->scc[i], c->scc_cluster[i]);
6760 if (!space)
6761 return isl_stat_error;
6762 node = graph_find_node(ctx, merge_graph, space);
6763 isl_space_free(space);
6764 if (!node)
6765 isl_die(ctx, isl_error_internal,
6766 "unable to find cluster",
6767 return isl_stat_error);
6768 if (transform(ctx, &c->scc[i], node) < 0)
6769 return isl_stat_error;
6770 c->scc_cluster[i] = cluster;
6773 return isl_stat_ok;
6776 /* Try and merge the clusters of SCCs marked in c->scc_in_merge
6777 * by scheduling the current cluster bands with respect to each other.
6779 * Construct a dependence graph with a space for each cluster and
6780 * with the coordinates of each space corresponding to the schedule
6781 * dimensions of the current band of that cluster.
6782 * Construct a cluster schedule in this cluster dependence graph and
6783 * apply it to the current cluster bands if it is applicable
6784 * according to ok_to_merge.
6786 * If the number of remaining schedule dimensions in a cluster
6787 * with a non-maximal current schedule dimension is greater than
6788 * the number of remaining schedule dimensions in clusters
6789 * with a maximal current schedule dimension, then restrict
6790 * the number of rows to be computed in the cluster schedule
6791 * to the minimal such non-maximal current schedule dimension.
6792 * Do this by adjusting merge_graph.maxvar.
6794 * Return isl_bool_true if the clusters have effectively been merged
6795 * into a single cluster.
6797 * Note that since the standard scheduling algorithm minimizes the maximal
6798 * distance over proximity constraints, the proximity constraints between
6799 * the merged clusters may not be optimized any further than what is
6800 * sufficient to bring the distances within the limits of the internal
6801 * proximity constraints inside the individual clusters.
6802 * It may therefore make sense to perform an additional translation step
6803 * to bring the clusters closer to each other, while maintaining
6804 * the linear part of the merging schedule found using the standard
6805 * scheduling algorithm.
6807 static isl_bool try_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6808 struct isl_clustering *c)
6810 struct isl_sched_graph merge_graph = { 0 };
6811 isl_bool merged;
6813 if (init_merge_graph(ctx, graph, c, &merge_graph) < 0)
6814 goto error;
6816 if (compute_maxvar(&merge_graph) < 0)
6817 goto error;
6818 if (adjust_maxvar_to_slack(ctx, &merge_graph,c) < 0)
6819 goto error;
6820 if (compute_schedule_wcc_band(ctx, &merge_graph) < 0)
6821 goto error;
6822 merged = ok_to_merge(ctx, graph, c, &merge_graph);
6823 if (merged && merge(ctx, c, &merge_graph) < 0)
6824 goto error;
6826 graph_free(ctx, &merge_graph);
6827 return merged;
6828 error:
6829 graph_free(ctx, &merge_graph);
6830 return isl_bool_error;
6833 /* Is there any edge marked "no_merge" between two SCCs that are
6834 * about to be merged (i.e., that are set in "scc_in_merge")?
6835 * "merge_edge" is the proximity edge along which the clusters of SCCs
6836 * are going to be merged.
6838 * If there is any edge between two SCCs with a negative weight,
6839 * while the weight of "merge_edge" is non-negative, then this
6840 * means that the edge was postponed. "merge_edge" should then
6841 * also be postponed since merging along the edge with negative weight should
6842 * be postponed until all edges with non-negative weight have been tried.
6843 * Replace the weight of "merge_edge" by a negative weight as well and
6844 * tell the caller not to attempt a merge.
6846 static int any_no_merge(struct isl_sched_graph *graph, int *scc_in_merge,
6847 struct isl_sched_edge *merge_edge)
6849 int i;
6851 for (i = 0; i < graph->n_edge; ++i) {
6852 struct isl_sched_edge *edge = &graph->edge[i];
6854 if (!scc_in_merge[edge->src->scc])
6855 continue;
6856 if (!scc_in_merge[edge->dst->scc])
6857 continue;
6858 if (edge->no_merge)
6859 return 1;
6860 if (merge_edge->weight >= 0 && edge->weight < 0) {
6861 merge_edge->weight -= graph->max_weight + 1;
6862 return 1;
6866 return 0;
6869 /* Merge the two clusters in "c" connected by the edge in "graph"
6870 * with index "edge" into a single cluster.
6871 * If it turns out to be impossible to merge these two clusters,
6872 * then mark the edge as "no_merge" such that it will not be
6873 * considered again.
6875 * First mark all SCCs that need to be merged. This includes the SCCs
6876 * in the two clusters, but it may also include the SCCs
6877 * of intermediate clusters.
6878 * If there is already a no_merge edge between any pair of such SCCs,
6879 * then simply mark the current edge as no_merge as well.
6880 * Likewise, if any of those edges was postponed by has_bounded_distances,
6881 * then postpone the current edge as well.
6882 * Otherwise, try and merge the clusters and mark "edge" as "no_merge"
6883 * if the clusters did not end up getting merged, unless the non-merge
6884 * is due to the fact that the edge was postponed. This postponement
6885 * can be recognized by a change in weight (from non-negative to negative).
6887 static isl_stat merge_clusters_along_edge(isl_ctx *ctx,
6888 struct isl_sched_graph *graph, int edge, struct isl_clustering *c)
6890 isl_bool merged;
6891 int edge_weight = graph->edge[edge].weight;
6893 if (mark_merge_sccs(ctx, graph, edge, c) < 0)
6894 return isl_stat_error;
6896 if (any_no_merge(graph, c->scc_in_merge, &graph->edge[edge]))
6897 merged = isl_bool_false;
6898 else
6899 merged = try_merge(ctx, graph, c);
6900 if (merged < 0)
6901 return isl_stat_error;
6902 if (!merged && edge_weight == graph->edge[edge].weight)
6903 graph->edge[edge].no_merge = 1;
6905 return isl_stat_ok;
6908 /* Does "node" belong to the cluster identified by "cluster"?
6910 static int node_cluster_exactly(struct isl_sched_node *node, int cluster)
6912 return node->cluster == cluster;
6915 /* Does "edge" connect two nodes belonging to the cluster
6916 * identified by "cluster"?
6918 static int edge_cluster_exactly(struct isl_sched_edge *edge, int cluster)
6920 return edge->src->cluster == cluster && edge->dst->cluster == cluster;
6923 /* Swap the schedule of "node1" and "node2".
6924 * Both nodes have been derived from the same node in a common parent graph.
6925 * Since the "coincident" field is shared with that node
6926 * in the parent graph, there is no need to also swap this field.
6928 static void swap_sched(struct isl_sched_node *node1,
6929 struct isl_sched_node *node2)
6931 isl_mat *sched;
6932 isl_map *sched_map;
6934 sched = node1->sched;
6935 node1->sched = node2->sched;
6936 node2->sched = sched;
6938 sched_map = node1->sched_map;
6939 node1->sched_map = node2->sched_map;
6940 node2->sched_map = sched_map;
6943 /* Copy the current band schedule from the SCCs that form the cluster
6944 * with index "pos" to the actual cluster at position "pos".
6945 * By construction, the index of the first SCC that belongs to the cluster
6946 * is also "pos".
6948 * The order of the nodes inside both the SCCs and the cluster
6949 * is assumed to be same as the order in the original "graph".
6951 * Since the SCC graphs will no longer be used after this function,
6952 * the schedules are actually swapped rather than copied.
6954 static isl_stat copy_partial(struct isl_sched_graph *graph,
6955 struct isl_clustering *c, int pos)
6957 int i, j;
6959 c->cluster[pos].n_total_row = c->scc[pos].n_total_row;
6960 c->cluster[pos].n_row = c->scc[pos].n_row;
6961 c->cluster[pos].maxvar = c->scc[pos].maxvar;
6962 j = 0;
6963 for (i = 0; i < graph->n; ++i) {
6964 int k;
6965 int s;
6967 if (graph->node[i].cluster != pos)
6968 continue;
6969 s = graph->node[i].scc;
6970 k = c->scc_node[s]++;
6971 swap_sched(&c->cluster[pos].node[j], &c->scc[s].node[k]);
6972 if (c->scc[s].maxvar > c->cluster[pos].maxvar)
6973 c->cluster[pos].maxvar = c->scc[s].maxvar;
6974 ++j;
6977 return isl_stat_ok;
6980 /* Is there a (conditional) validity dependence from node[j] to node[i],
6981 * forcing node[i] to follow node[j] or do the nodes belong to the same
6982 * cluster?
6984 static isl_bool node_follows_strong_or_same_cluster(int i, int j, void *user)
6986 struct isl_sched_graph *graph = user;
6988 if (graph->node[i].cluster == graph->node[j].cluster)
6989 return isl_bool_true;
6990 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
6993 /* Extract the merged clusters of SCCs in "graph", sort them, and
6994 * store them in c->clusters. Update c->scc_cluster accordingly.
6996 * First keep track of the cluster containing the SCC to which a node
6997 * belongs in the node itself.
6998 * Then extract the clusters into c->clusters, copying the current
6999 * band schedule from the SCCs that belong to the cluster.
7000 * Do this only once per cluster.
7002 * Finally, topologically sort the clusters and update c->scc_cluster
7003 * to match the new scc numbering. While the SCCs were originally
7004 * sorted already, some SCCs that depend on some other SCCs may
7005 * have been merged with SCCs that appear before these other SCCs.
7006 * A reordering may therefore be required.
7008 static isl_stat extract_clusters(isl_ctx *ctx, struct isl_sched_graph *graph,
7009 struct isl_clustering *c)
7011 int i;
7013 for (i = 0; i < graph->n; ++i)
7014 graph->node[i].cluster = c->scc_cluster[graph->node[i].scc];
7016 for (i = 0; i < graph->scc; ++i) {
7017 if (c->scc_cluster[i] != i)
7018 continue;
7019 if (extract_sub_graph(ctx, graph, &node_cluster_exactly,
7020 &edge_cluster_exactly, i, &c->cluster[i]) < 0)
7021 return isl_stat_error;
7022 c->cluster[i].src_scc = -1;
7023 c->cluster[i].dst_scc = -1;
7024 if (copy_partial(graph, c, i) < 0)
7025 return isl_stat_error;
7028 if (detect_ccs(ctx, graph, &node_follows_strong_or_same_cluster) < 0)
7029 return isl_stat_error;
7030 for (i = 0; i < graph->n; ++i)
7031 c->scc_cluster[graph->node[i].scc] = graph->node[i].cluster;
7033 return isl_stat_ok;
7036 /* Compute weights on the proximity edges of "graph" that can
7037 * be used by find_proximity to find the most appropriate
7038 * proximity edge to use to merge two clusters in "c".
7039 * The weights are also used by has_bounded_distances to determine
7040 * whether the merge should be allowed.
7041 * Store the maximum of the computed weights in graph->max_weight.
7043 * The computed weight is a measure for the number of remaining schedule
7044 * dimensions that can still be completely aligned.
7045 * In particular, compute the number of equalities between
7046 * input dimensions and output dimensions in the proximity constraints.
7047 * The directions that are already handled by outer schedule bands
7048 * are projected out prior to determining this number.
7050 * Edges that will never be considered by find_proximity are ignored.
7052 static isl_stat compute_weights(struct isl_sched_graph *graph,
7053 struct isl_clustering *c)
7055 int i;
7057 graph->max_weight = 0;
7059 for (i = 0; i < graph->n_edge; ++i) {
7060 struct isl_sched_edge *edge = &graph->edge[i];
7061 struct isl_sched_node *src = edge->src;
7062 struct isl_sched_node *dst = edge->dst;
7063 isl_basic_map *hull;
7064 isl_bool prox;
7065 int n_in, n_out;
7067 prox = is_non_empty_proximity(edge);
7068 if (prox < 0)
7069 return isl_stat_error;
7070 if (!prox)
7071 continue;
7072 if (bad_cluster(&c->scc[edge->src->scc]) ||
7073 bad_cluster(&c->scc[edge->dst->scc]))
7074 continue;
7075 if (c->scc_cluster[edge->dst->scc] ==
7076 c->scc_cluster[edge->src->scc])
7077 continue;
7079 hull = isl_map_affine_hull(isl_map_copy(edge->map));
7080 hull = isl_basic_map_transform_dims(hull, isl_dim_in, 0,
7081 isl_mat_copy(src->vmap));
7082 hull = isl_basic_map_transform_dims(hull, isl_dim_out, 0,
7083 isl_mat_copy(dst->vmap));
7084 hull = isl_basic_map_project_out(hull,
7085 isl_dim_in, 0, src->rank);
7086 hull = isl_basic_map_project_out(hull,
7087 isl_dim_out, 0, dst->rank);
7088 hull = isl_basic_map_remove_divs(hull);
7089 n_in = isl_basic_map_dim(hull, isl_dim_in);
7090 n_out = isl_basic_map_dim(hull, isl_dim_out);
7091 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
7092 isl_dim_in, 0, n_in);
7093 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
7094 isl_dim_out, 0, n_out);
7095 if (!hull)
7096 return isl_stat_error;
7097 edge->weight = isl_basic_map_n_equality(hull);
7098 isl_basic_map_free(hull);
7100 if (edge->weight > graph->max_weight)
7101 graph->max_weight = edge->weight;
7104 return isl_stat_ok;
7107 /* Call compute_schedule_finish_band on each of the clusters in "c"
7108 * in their topological order. This order is determined by the scc
7109 * fields of the nodes in "graph".
7110 * Combine the results in a sequence expressing the topological order.
7112 * If there is only one cluster left, then there is no need to introduce
7113 * a sequence node. Also, in this case, the cluster necessarily contains
7114 * the SCC at position 0 in the original graph and is therefore also
7115 * stored in the first cluster of "c".
7117 static __isl_give isl_schedule_node *finish_bands_clustering(
7118 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
7119 struct isl_clustering *c)
7121 int i;
7122 isl_ctx *ctx;
7123 isl_union_set_list *filters;
7125 if (graph->scc == 1)
7126 return compute_schedule_finish_band(node, &c->cluster[0], 0);
7128 ctx = isl_schedule_node_get_ctx(node);
7130 filters = extract_sccs(ctx, graph);
7131 node = isl_schedule_node_insert_sequence(node, filters);
7133 for (i = 0; i < graph->scc; ++i) {
7134 int j = c->scc_cluster[i];
7135 node = isl_schedule_node_child(node, i);
7136 node = isl_schedule_node_child(node, 0);
7137 node = compute_schedule_finish_band(node, &c->cluster[j], 0);
7138 node = isl_schedule_node_parent(node);
7139 node = isl_schedule_node_parent(node);
7142 return node;
7145 /* Compute a schedule for a connected dependence graph by first considering
7146 * each strongly connected component (SCC) in the graph separately and then
7147 * incrementally combining them into clusters.
7148 * Return the updated schedule node.
7150 * Initially, each cluster consists of a single SCC, each with its
7151 * own band schedule. The algorithm then tries to merge pairs
7152 * of clusters along a proximity edge until no more suitable
7153 * proximity edges can be found. During this merging, the schedule
7154 * is maintained in the individual SCCs.
7155 * After the merging is completed, the full resulting clusters
7156 * are extracted and in finish_bands_clustering,
7157 * compute_schedule_finish_band is called on each of them to integrate
7158 * the band into "node" and to continue the computation.
7160 * compute_weights initializes the weights that are used by find_proximity.
7162 static __isl_give isl_schedule_node *compute_schedule_wcc_clustering(
7163 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
7165 isl_ctx *ctx;
7166 struct isl_clustering c;
7167 int i;
7169 ctx = isl_schedule_node_get_ctx(node);
7171 if (clustering_init(ctx, &c, graph) < 0)
7172 goto error;
7174 if (compute_weights(graph, &c) < 0)
7175 goto error;
7177 for (;;) {
7178 i = find_proximity(graph, &c);
7179 if (i < 0)
7180 goto error;
7181 if (i >= graph->n_edge)
7182 break;
7183 if (merge_clusters_along_edge(ctx, graph, i, &c) < 0)
7184 goto error;
7187 if (extract_clusters(ctx, graph, &c) < 0)
7188 goto error;
7190 node = finish_bands_clustering(node, graph, &c);
7192 clustering_free(ctx, &c);
7193 return node;
7194 error:
7195 clustering_free(ctx, &c);
7196 return isl_schedule_node_free(node);
7199 /* Compute a schedule for a connected dependence graph and return
7200 * the updated schedule node.
7202 * If Feautrier's algorithm is selected, we first recursively try to satisfy
7203 * as many validity dependences as possible. When all validity dependences
7204 * are satisfied we extend the schedule to a full-dimensional schedule.
7206 * Call compute_schedule_wcc_whole or compute_schedule_wcc_clustering
7207 * depending on whether the user has selected the option to try and
7208 * compute a schedule for the entire (weakly connected) component first.
7209 * If there is only a single strongly connected component (SCC), then
7210 * there is no point in trying to combine SCCs
7211 * in compute_schedule_wcc_clustering, so compute_schedule_wcc_whole
7212 * is called instead.
7214 static __isl_give isl_schedule_node *compute_schedule_wcc(
7215 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
7217 isl_ctx *ctx;
7219 if (!node)
7220 return NULL;
7222 ctx = isl_schedule_node_get_ctx(node);
7223 if (detect_sccs(ctx, graph) < 0)
7224 return isl_schedule_node_free(node);
7226 if (compute_maxvar(graph) < 0)
7227 return isl_schedule_node_free(node);
7229 if (need_feautrier_step(ctx, graph))
7230 return compute_schedule_wcc_feautrier(node, graph);
7232 if (graph->scc <= 1 || isl_options_get_schedule_whole_component(ctx))
7233 return compute_schedule_wcc_whole(node, graph);
7234 else
7235 return compute_schedule_wcc_clustering(node, graph);
7238 /* Compute a schedule for each group of nodes identified by node->scc
7239 * separately and then combine them in a sequence node (or as set node
7240 * if graph->weak is set) inserted at position "node" of the schedule tree.
7241 * Return the updated schedule node.
7243 * If "wcc" is set then each of the groups belongs to a single
7244 * weakly connected component in the dependence graph so that
7245 * there is no need for compute_sub_schedule to look for weakly
7246 * connected components.
7248 * If a set node would be introduced and if the number of components
7249 * is equal to the number of nodes, then check if the schedule
7250 * is already complete. If so, a redundant set node would be introduced
7251 * (without any further descendants) stating that the statements
7252 * can be executed in arbitrary order, which is also expressed
7253 * by the absence of any node. Refrain from inserting any nodes
7254 * in this case and simply return.
7256 static __isl_give isl_schedule_node *compute_component_schedule(
7257 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
7258 int wcc)
7260 int component;
7261 isl_ctx *ctx;
7262 isl_union_set_list *filters;
7264 if (!node)
7265 return NULL;
7267 if (graph->weak && graph->scc == graph->n) {
7268 if (compute_maxvar(graph) < 0)
7269 return isl_schedule_node_free(node);
7270 if (graph->n_row >= graph->maxvar)
7271 return node;
7274 ctx = isl_schedule_node_get_ctx(node);
7275 filters = extract_sccs(ctx, graph);
7276 if (graph->weak)
7277 node = isl_schedule_node_insert_set(node, filters);
7278 else
7279 node = isl_schedule_node_insert_sequence(node, filters);
7281 for (component = 0; component < graph->scc; ++component) {
7282 node = isl_schedule_node_child(node, component);
7283 node = isl_schedule_node_child(node, 0);
7284 node = compute_sub_schedule(node, ctx, graph,
7285 &node_scc_exactly,
7286 &edge_scc_exactly, component, wcc);
7287 node = isl_schedule_node_parent(node);
7288 node = isl_schedule_node_parent(node);
7291 return node;
7294 /* Compute a schedule for the given dependence graph and insert it at "node".
7295 * Return the updated schedule node.
7297 * We first check if the graph is connected (through validity and conditional
7298 * validity dependences) and, if not, compute a schedule
7299 * for each component separately.
7300 * If the schedule_serialize_sccs option is set, then we check for strongly
7301 * connected components instead and compute a separate schedule for
7302 * each such strongly connected component.
7304 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
7305 struct isl_sched_graph *graph)
7307 isl_ctx *ctx;
7309 if (!node)
7310 return NULL;
7312 ctx = isl_schedule_node_get_ctx(node);
7313 if (isl_options_get_schedule_serialize_sccs(ctx)) {
7314 if (detect_sccs(ctx, graph) < 0)
7315 return isl_schedule_node_free(node);
7316 } else {
7317 if (detect_wccs(ctx, graph) < 0)
7318 return isl_schedule_node_free(node);
7321 if (graph->scc > 1)
7322 return compute_component_schedule(node, graph, 1);
7324 return compute_schedule_wcc(node, graph);
7327 /* Compute a schedule on sc->domain that respects the given schedule
7328 * constraints.
7330 * In particular, the schedule respects all the validity dependences.
7331 * If the default isl scheduling algorithm is used, it tries to minimize
7332 * the dependence distances over the proximity dependences.
7333 * If Feautrier's scheduling algorithm is used, the proximity dependence
7334 * distances are only minimized during the extension to a full-dimensional
7335 * schedule.
7337 * If there are any condition and conditional validity dependences,
7338 * then the conditional validity dependences may be violated inside
7339 * a tilable band, provided they have no adjacent non-local
7340 * condition dependences.
7342 __isl_give isl_schedule *isl_schedule_constraints_compute_schedule(
7343 __isl_take isl_schedule_constraints *sc)
7345 isl_ctx *ctx = isl_schedule_constraints_get_ctx(sc);
7346 struct isl_sched_graph graph = { 0 };
7347 isl_schedule *sched;
7348 isl_schedule_node *node;
7349 isl_union_set *domain;
7351 sc = isl_schedule_constraints_align_params(sc);
7353 domain = isl_schedule_constraints_get_domain(sc);
7354 if (isl_union_set_n_set(domain) == 0) {
7355 isl_schedule_constraints_free(sc);
7356 return isl_schedule_from_domain(domain);
7359 if (graph_init(&graph, sc) < 0)
7360 domain = isl_union_set_free(domain);
7362 node = isl_schedule_node_from_domain(domain);
7363 node = isl_schedule_node_child(node, 0);
7364 if (graph.n > 0)
7365 node = compute_schedule(node, &graph);
7366 sched = isl_schedule_node_get_schedule(node);
7367 isl_schedule_node_free(node);
7369 graph_free(ctx, &graph);
7370 isl_schedule_constraints_free(sc);
7372 return sched;
7375 /* Compute a schedule for the given union of domains that respects
7376 * all the validity dependences and minimizes
7377 * the dependence distances over the proximity dependences.
7379 * This function is kept for backward compatibility.
7381 __isl_give isl_schedule *isl_union_set_compute_schedule(
7382 __isl_take isl_union_set *domain,
7383 __isl_take isl_union_map *validity,
7384 __isl_take isl_union_map *proximity)
7386 isl_schedule_constraints *sc;
7388 sc = isl_schedule_constraints_on_domain(domain);
7389 sc = isl_schedule_constraints_set_validity(sc, validity);
7390 sc = isl_schedule_constraints_set_proximity(sc, proximity);
7392 return isl_schedule_constraints_compute_schedule(sc);