isl_scheduler.c: extract_var_coef: drop comment on order of coefficients
[isl.git] / isl_scheduler.c
blob472332d1bd7ea69954cbb861d44e91fecc14b050
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.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".
49 /* Internal information about a node that is used during the construction
50 * of a schedule.
51 * space represents the original space in which the domain lives;
52 * that is, the space is not affected by compression
53 * sched is a matrix representation of the schedule being constructed
54 * for this node; if compressed is set, then this schedule is
55 * defined over the compressed domain space
56 * sched_map is an isl_map representation of the same (partial) schedule
57 * sched_map may be NULL; if compressed is set, then this map
58 * is defined over the uncompressed domain space
59 * rank is the number of linearly independent rows in the linear part
60 * of sched
61 * the rows of "vmap" represent a change of basis for the node
62 * variables; the first rank rows span the linear part of
63 * the schedule rows; the remaining rows are linearly independent
64 * the rows of "indep" represent linear combinations of the schedule
65 * coefficients that are non-zero when the schedule coefficients are
66 * linearly independent of previously computed schedule rows.
67 * start is the first variable in the LP problem in the sequences that
68 * represents the schedule coefficients of this node
69 * nvar is the dimension of the domain
70 * nparam is the number of parameters or 0 if we are not constructing
71 * a parametric schedule
73 * If compressed is set, then hull represents the constraints
74 * that were used to derive the compression, while compress and
75 * decompress map the original space to the compressed space and
76 * vice versa.
78 * scc is the index of SCC (or WCC) this node belongs to
80 * "cluster" is only used inside extract_clusters and identifies
81 * the cluster of SCCs that the node belongs to.
83 * coincident contains a boolean for each of the rows of the schedule,
84 * indicating whether the corresponding scheduling dimension satisfies
85 * the coincidence constraints in the sense that the corresponding
86 * dependence distances are zero.
88 * If the schedule_treat_coalescing option is set, then
89 * "sizes" contains the sizes of the (compressed) instance set
90 * in each direction. If there is no fixed size in a given direction,
91 * then the corresponding size value is set to infinity.
92 * If the schedule_treat_coalescing option or the schedule_max_coefficient
93 * option is set, then "max" contains the maximal values for
94 * schedule coefficients of the (compressed) variables. If no bound
95 * needs to be imposed on a particular variable, then the corresponding
96 * value is negative.
98 struct isl_sched_node {
99 isl_space *space;
100 int compressed;
101 isl_set *hull;
102 isl_multi_aff *compress;
103 isl_multi_aff *decompress;
104 isl_mat *sched;
105 isl_map *sched_map;
106 int rank;
107 isl_mat *indep;
108 isl_mat *vmap;
109 int start;
110 int nvar;
111 int nparam;
113 int scc;
114 int cluster;
116 int *coincident;
118 isl_multi_val *sizes;
119 isl_vec *max;
122 static int node_has_tuples(const void *entry, const void *val)
124 struct isl_sched_node *node = (struct isl_sched_node *)entry;
125 isl_space *space = (isl_space *) val;
127 return isl_space_has_equal_tuples(node->space, space);
130 static int node_scc_exactly(struct isl_sched_node *node, int scc)
132 return node->scc == scc;
135 static int node_scc_at_most(struct isl_sched_node *node, int scc)
137 return node->scc <= scc;
140 static int node_scc_at_least(struct isl_sched_node *node, int scc)
142 return node->scc >= scc;
145 /* An edge in the dependence graph. An edge may be used to
146 * ensure validity of the generated schedule, to minimize the dependence
147 * distance or both
149 * map is the dependence relation, with i -> j in the map if j depends on i
150 * tagged_condition and tagged_validity contain the union of all tagged
151 * condition or conditional validity dependence relations that
152 * specialize the dependence relation "map"; that is,
153 * if (i -> a) -> (j -> b) is an element of "tagged_condition"
154 * or "tagged_validity", then i -> j is an element of "map".
155 * If these fields are NULL, then they represent the empty relation.
156 * src is the source node
157 * dst is the sink node
159 * types is a bit vector containing the types of this edge.
160 * validity is set if the edge is used to ensure correctness
161 * coincidence is used to enforce zero dependence distances
162 * proximity is set if the edge is used to minimize dependence distances
163 * condition is set if the edge represents a condition
164 * for a conditional validity schedule constraint
165 * local can only be set for condition edges and indicates that
166 * the dependence distance over the edge should be zero
167 * conditional_validity is set if the edge is used to conditionally
168 * ensure correctness
170 * For validity edges, start and end mark the sequence of inequality
171 * constraints in the LP problem that encode the validity constraint
172 * corresponding to this edge.
174 * During clustering, an edge may be marked "no_merge" if it should
175 * not be used to merge clusters.
176 * The weight is also only used during clustering and it is
177 * an indication of how many schedule dimensions on either side
178 * of the schedule constraints can be aligned.
179 * If the weight is negative, then this means that this edge was postponed
180 * by has_bounded_distances or any_no_merge. The original weight can
181 * be retrieved by adding 1 + graph->max_weight, with "graph"
182 * the graph containing this edge.
184 struct isl_sched_edge {
185 isl_map *map;
186 isl_union_map *tagged_condition;
187 isl_union_map *tagged_validity;
189 struct isl_sched_node *src;
190 struct isl_sched_node *dst;
192 unsigned types;
194 int start;
195 int end;
197 int no_merge;
198 int weight;
201 /* Is "edge" marked as being of type "type"?
203 static int is_type(struct isl_sched_edge *edge, enum isl_edge_type type)
205 return ISL_FL_ISSET(edge->types, 1 << type);
208 /* Mark "edge" as being of type "type".
210 static void set_type(struct isl_sched_edge *edge, enum isl_edge_type type)
212 ISL_FL_SET(edge->types, 1 << type);
215 /* No longer mark "edge" as being of type "type"?
217 static void clear_type(struct isl_sched_edge *edge, enum isl_edge_type type)
219 ISL_FL_CLR(edge->types, 1 << type);
222 /* Is "edge" marked as a validity edge?
224 static int is_validity(struct isl_sched_edge *edge)
226 return is_type(edge, isl_edge_validity);
229 /* Mark "edge" as a validity edge.
231 static void set_validity(struct isl_sched_edge *edge)
233 set_type(edge, isl_edge_validity);
236 /* Is "edge" marked as a proximity edge?
238 static int is_proximity(struct isl_sched_edge *edge)
240 return is_type(edge, isl_edge_proximity);
243 /* Is "edge" marked as a local edge?
245 static int is_local(struct isl_sched_edge *edge)
247 return is_type(edge, isl_edge_local);
250 /* Mark "edge" as a local edge.
252 static void set_local(struct isl_sched_edge *edge)
254 set_type(edge, isl_edge_local);
257 /* No longer mark "edge" as a local edge.
259 static void clear_local(struct isl_sched_edge *edge)
261 clear_type(edge, isl_edge_local);
264 /* Is "edge" marked as a coincidence edge?
266 static int is_coincidence(struct isl_sched_edge *edge)
268 return is_type(edge, isl_edge_coincidence);
271 /* Is "edge" marked as a condition edge?
273 static int is_condition(struct isl_sched_edge *edge)
275 return is_type(edge, isl_edge_condition);
278 /* Is "edge" marked as a conditional validity edge?
280 static int is_conditional_validity(struct isl_sched_edge *edge)
282 return is_type(edge, isl_edge_conditional_validity);
285 /* Internal information about the dependence graph used during
286 * the construction of the schedule.
288 * intra_hmap is a cache, mapping dependence relations to their dual,
289 * for dependences from a node to itself
290 * inter_hmap is a cache, mapping dependence relations to their dual,
291 * for dependences between distinct nodes
292 * if compression is involved then the key for these maps
293 * is the original, uncompressed dependence relation, while
294 * the value is the dual of the compressed dependence relation.
296 * n is the number of nodes
297 * node is the list of nodes
298 * maxvar is the maximal number of variables over all nodes
299 * max_row is the allocated number of rows in the schedule
300 * n_row is the current (maximal) number of linearly independent
301 * rows in the node schedules
302 * n_total_row is the current number of rows in the node schedules
303 * band_start is the starting row in the node schedules of the current band
304 * root is set if this graph is the original dependence graph,
305 * without any splitting
307 * sorted contains a list of node indices sorted according to the
308 * SCC to which a node belongs
310 * n_edge is the number of edges
311 * edge is the list of edges
312 * max_edge contains the maximal number of edges of each type;
313 * in particular, it contains the number of edges in the inital graph.
314 * edge_table contains pointers into the edge array, hashed on the source
315 * and sink spaces; there is one such table for each type;
316 * a given edge may be referenced from more than one table
317 * if the corresponding relation appears in more than one of the
318 * sets of dependences; however, for each type there is only
319 * a single edge between a given pair of source and sink space
320 * in the entire graph
322 * node_table contains pointers into the node array, hashed on the space tuples
324 * region contains a list of variable sequences that should be non-trivial
326 * lp contains the (I)LP problem used to obtain new schedule rows
328 * src_scc and dst_scc are the source and sink SCCs of an edge with
329 * conflicting constraints
331 * scc represents the number of components
332 * weak is set if the components are weakly connected
334 * max_weight is used during clustering and represents the maximal
335 * weight of the relevant proximity edges.
337 struct isl_sched_graph {
338 isl_map_to_basic_set *intra_hmap;
339 isl_map_to_basic_set *inter_hmap;
341 struct isl_sched_node *node;
342 int n;
343 int maxvar;
344 int max_row;
345 int n_row;
347 int *sorted;
349 int n_total_row;
350 int band_start;
352 int root;
354 struct isl_sched_edge *edge;
355 int n_edge;
356 int max_edge[isl_edge_last + 1];
357 struct isl_hash_table *edge_table[isl_edge_last + 1];
359 struct isl_hash_table *node_table;
360 struct isl_trivial_region *region;
362 isl_basic_set *lp;
364 int src_scc;
365 int dst_scc;
367 int scc;
368 int weak;
370 int max_weight;
373 /* Initialize node_table based on the list of nodes.
375 static int graph_init_table(isl_ctx *ctx, struct isl_sched_graph *graph)
377 int i;
379 graph->node_table = isl_hash_table_alloc(ctx, graph->n);
380 if (!graph->node_table)
381 return -1;
383 for (i = 0; i < graph->n; ++i) {
384 struct isl_hash_table_entry *entry;
385 uint32_t hash;
387 hash = isl_space_get_tuple_hash(graph->node[i].space);
388 entry = isl_hash_table_find(ctx, graph->node_table, hash,
389 &node_has_tuples,
390 graph->node[i].space, 1);
391 if (!entry)
392 return -1;
393 entry->data = &graph->node[i];
396 return 0;
399 /* Return a pointer to the node that lives within the given space,
400 * or NULL if there is no such node.
402 static struct isl_sched_node *graph_find_node(isl_ctx *ctx,
403 struct isl_sched_graph *graph, __isl_keep isl_space *space)
405 struct isl_hash_table_entry *entry;
406 uint32_t hash;
408 hash = isl_space_get_tuple_hash(space);
409 entry = isl_hash_table_find(ctx, graph->node_table, hash,
410 &node_has_tuples, space, 0);
412 return entry ? entry->data : NULL;
415 static int edge_has_src_and_dst(const void *entry, const void *val)
417 const struct isl_sched_edge *edge = entry;
418 const struct isl_sched_edge *temp = val;
420 return edge->src == temp->src && edge->dst == temp->dst;
423 /* Add the given edge to graph->edge_table[type].
425 static isl_stat graph_edge_table_add(isl_ctx *ctx,
426 struct isl_sched_graph *graph, enum isl_edge_type type,
427 struct isl_sched_edge *edge)
429 struct isl_hash_table_entry *entry;
430 uint32_t hash;
432 hash = isl_hash_init();
433 hash = isl_hash_builtin(hash, edge->src);
434 hash = isl_hash_builtin(hash, edge->dst);
435 entry = isl_hash_table_find(ctx, graph->edge_table[type], hash,
436 &edge_has_src_and_dst, edge, 1);
437 if (!entry)
438 return isl_stat_error;
439 entry->data = edge;
441 return isl_stat_ok;
444 /* Allocate the edge_tables based on the maximal number of edges of
445 * each type.
447 static int graph_init_edge_tables(isl_ctx *ctx, struct isl_sched_graph *graph)
449 int i;
451 for (i = 0; i <= isl_edge_last; ++i) {
452 graph->edge_table[i] = isl_hash_table_alloc(ctx,
453 graph->max_edge[i]);
454 if (!graph->edge_table[i])
455 return -1;
458 return 0;
461 /* If graph->edge_table[type] contains an edge from the given source
462 * to the given destination, then return the hash table entry of this edge.
463 * Otherwise, return NULL.
465 static struct isl_hash_table_entry *graph_find_edge_entry(
466 struct isl_sched_graph *graph,
467 enum isl_edge_type type,
468 struct isl_sched_node *src, struct isl_sched_node *dst)
470 isl_ctx *ctx = isl_space_get_ctx(src->space);
471 uint32_t hash;
472 struct isl_sched_edge temp = { .src = src, .dst = dst };
474 hash = isl_hash_init();
475 hash = isl_hash_builtin(hash, temp.src);
476 hash = isl_hash_builtin(hash, temp.dst);
477 return isl_hash_table_find(ctx, graph->edge_table[type], hash,
478 &edge_has_src_and_dst, &temp, 0);
482 /* If graph->edge_table[type] contains an edge from the given source
483 * to the given destination, then return this edge.
484 * Otherwise, return NULL.
486 static struct isl_sched_edge *graph_find_edge(struct isl_sched_graph *graph,
487 enum isl_edge_type type,
488 struct isl_sched_node *src, struct isl_sched_node *dst)
490 struct isl_hash_table_entry *entry;
492 entry = graph_find_edge_entry(graph, type, src, dst);
493 if (!entry)
494 return NULL;
496 return entry->data;
499 /* Check whether the dependence graph has an edge of the given type
500 * between the given two nodes.
502 static isl_bool graph_has_edge(struct isl_sched_graph *graph,
503 enum isl_edge_type type,
504 struct isl_sched_node *src, struct isl_sched_node *dst)
506 struct isl_sched_edge *edge;
507 isl_bool empty;
509 edge = graph_find_edge(graph, type, src, dst);
510 if (!edge)
511 return 0;
513 empty = isl_map_plain_is_empty(edge->map);
514 if (empty < 0)
515 return isl_bool_error;
517 return !empty;
520 /* Look for any edge with the same src, dst and map fields as "model".
522 * Return the matching edge if one can be found.
523 * Return "model" if no matching edge is found.
524 * Return NULL on error.
526 static struct isl_sched_edge *graph_find_matching_edge(
527 struct isl_sched_graph *graph, struct isl_sched_edge *model)
529 enum isl_edge_type i;
530 struct isl_sched_edge *edge;
532 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
533 int is_equal;
535 edge = graph_find_edge(graph, i, model->src, model->dst);
536 if (!edge)
537 continue;
538 is_equal = isl_map_plain_is_equal(model->map, edge->map);
539 if (is_equal < 0)
540 return NULL;
541 if (is_equal)
542 return edge;
545 return model;
548 /* Remove the given edge from all the edge_tables that refer to it.
550 static void graph_remove_edge(struct isl_sched_graph *graph,
551 struct isl_sched_edge *edge)
553 isl_ctx *ctx = isl_map_get_ctx(edge->map);
554 enum isl_edge_type i;
556 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
557 struct isl_hash_table_entry *entry;
559 entry = graph_find_edge_entry(graph, i, edge->src, edge->dst);
560 if (!entry)
561 continue;
562 if (entry->data != edge)
563 continue;
564 isl_hash_table_remove(ctx, graph->edge_table[i], entry);
568 /* Check whether the dependence graph has any edge
569 * between the given two nodes.
571 static isl_bool graph_has_any_edge(struct isl_sched_graph *graph,
572 struct isl_sched_node *src, struct isl_sched_node *dst)
574 enum isl_edge_type i;
575 isl_bool r;
577 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
578 r = graph_has_edge(graph, i, src, dst);
579 if (r < 0 || r)
580 return r;
583 return r;
586 /* Check whether the dependence graph has a validity edge
587 * between the given two nodes.
589 * Conditional validity edges are essentially validity edges that
590 * can be ignored if the corresponding condition edges are iteration private.
591 * Here, we are only checking for the presence of validity
592 * edges, so we need to consider the conditional validity edges too.
593 * In particular, this function is used during the detection
594 * of strongly connected components and we cannot ignore
595 * conditional validity edges during this detection.
597 static isl_bool graph_has_validity_edge(struct isl_sched_graph *graph,
598 struct isl_sched_node *src, struct isl_sched_node *dst)
600 isl_bool r;
602 r = graph_has_edge(graph, isl_edge_validity, src, dst);
603 if (r < 0 || r)
604 return r;
606 return graph_has_edge(graph, isl_edge_conditional_validity, src, dst);
609 static int graph_alloc(isl_ctx *ctx, struct isl_sched_graph *graph,
610 int n_node, int n_edge)
612 int i;
614 graph->n = n_node;
615 graph->n_edge = n_edge;
616 graph->node = isl_calloc_array(ctx, struct isl_sched_node, graph->n);
617 graph->sorted = isl_calloc_array(ctx, int, graph->n);
618 graph->region = isl_alloc_array(ctx,
619 struct isl_trivial_region, graph->n);
620 graph->edge = isl_calloc_array(ctx,
621 struct isl_sched_edge, graph->n_edge);
623 graph->intra_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
624 graph->inter_hmap = isl_map_to_basic_set_alloc(ctx, 2 * n_edge);
626 if (!graph->node || !graph->region || (graph->n_edge && !graph->edge) ||
627 !graph->sorted)
628 return -1;
630 for(i = 0; i < graph->n; ++i)
631 graph->sorted[i] = i;
633 return 0;
636 static void graph_free(isl_ctx *ctx, struct isl_sched_graph *graph)
638 int i;
640 isl_map_to_basic_set_free(graph->intra_hmap);
641 isl_map_to_basic_set_free(graph->inter_hmap);
643 if (graph->node)
644 for (i = 0; i < graph->n; ++i) {
645 isl_space_free(graph->node[i].space);
646 isl_set_free(graph->node[i].hull);
647 isl_multi_aff_free(graph->node[i].compress);
648 isl_multi_aff_free(graph->node[i].decompress);
649 isl_mat_free(graph->node[i].sched);
650 isl_map_free(graph->node[i].sched_map);
651 isl_mat_free(graph->node[i].indep);
652 isl_mat_free(graph->node[i].vmap);
653 if (graph->root)
654 free(graph->node[i].coincident);
655 isl_multi_val_free(graph->node[i].sizes);
656 isl_vec_free(graph->node[i].max);
658 free(graph->node);
659 free(graph->sorted);
660 if (graph->edge)
661 for (i = 0; i < graph->n_edge; ++i) {
662 isl_map_free(graph->edge[i].map);
663 isl_union_map_free(graph->edge[i].tagged_condition);
664 isl_union_map_free(graph->edge[i].tagged_validity);
666 free(graph->edge);
667 free(graph->region);
668 for (i = 0; i <= isl_edge_last; ++i)
669 isl_hash_table_free(ctx, graph->edge_table[i]);
670 isl_hash_table_free(ctx, graph->node_table);
671 isl_basic_set_free(graph->lp);
674 /* For each "set" on which this function is called, increment
675 * graph->n by one and update graph->maxvar.
677 static isl_stat init_n_maxvar(__isl_take isl_set *set, void *user)
679 struct isl_sched_graph *graph = user;
680 int nvar = isl_set_dim(set, isl_dim_set);
682 graph->n++;
683 if (nvar > graph->maxvar)
684 graph->maxvar = nvar;
686 isl_set_free(set);
688 return isl_stat_ok;
691 /* Compute the number of rows that should be allocated for the schedule.
692 * In particular, we need one row for each variable or one row
693 * for each basic map in the dependences.
694 * Note that it is practically impossible to exhaust both
695 * the number of dependences and the number of variables.
697 static isl_stat compute_max_row(struct isl_sched_graph *graph,
698 __isl_keep isl_schedule_constraints *sc)
700 int n_edge;
701 isl_stat r;
702 isl_union_set *domain;
704 graph->n = 0;
705 graph->maxvar = 0;
706 domain = isl_schedule_constraints_get_domain(sc);
707 r = isl_union_set_foreach_set(domain, &init_n_maxvar, graph);
708 isl_union_set_free(domain);
709 if (r < 0)
710 return isl_stat_error;
711 n_edge = isl_schedule_constraints_n_basic_map(sc);
712 if (n_edge < 0)
713 return isl_stat_error;
714 graph->max_row = n_edge + graph->maxvar;
716 return isl_stat_ok;
719 /* Does "bset" have any defining equalities for its set variables?
721 static isl_bool has_any_defining_equality(__isl_keep isl_basic_set *bset)
723 int i, n;
725 if (!bset)
726 return isl_bool_error;
728 n = isl_basic_set_dim(bset, isl_dim_set);
729 for (i = 0; i < n; ++i) {
730 isl_bool has;
732 has = isl_basic_set_has_defining_equality(bset, isl_dim_set, i,
733 NULL);
734 if (has < 0 || has)
735 return has;
738 return isl_bool_false;
741 /* Set the entries of node->max to the value of the schedule_max_coefficient
742 * option, if set.
744 static isl_stat set_max_coefficient(isl_ctx *ctx, struct isl_sched_node *node)
746 int max;
748 max = isl_options_get_schedule_max_coefficient(ctx);
749 if (max == -1)
750 return isl_stat_ok;
752 node->max = isl_vec_alloc(ctx, node->nvar);
753 node->max = isl_vec_set_si(node->max, max);
754 if (!node->max)
755 return isl_stat_error;
757 return isl_stat_ok;
760 /* Set the entries of node->max to the minimum of the schedule_max_coefficient
761 * option (if set) and half of the minimum of the sizes in the other
762 * dimensions. If the minimum of the sizes is one, half of the size
763 * is zero and this value is reset to one.
764 * If the global minimum is unbounded (i.e., if both
765 * the schedule_max_coefficient is not set and the sizes in the other
766 * dimensions are unbounded), then store a negative value.
767 * If the schedule coefficient is close to the size of the instance set
768 * in another dimension, then the schedule may represent a loop
769 * coalescing transformation (especially if the coefficient
770 * in that other dimension is one). Forcing the coefficient to be
771 * smaller than or equal to half the minimal size should avoid this
772 * situation.
774 static isl_stat compute_max_coefficient(isl_ctx *ctx,
775 struct isl_sched_node *node)
777 int max;
778 int i, j;
779 isl_vec *v;
781 max = isl_options_get_schedule_max_coefficient(ctx);
782 v = isl_vec_alloc(ctx, node->nvar);
783 if (!v)
784 return isl_stat_error;
786 for (i = 0; i < node->nvar; ++i) {
787 isl_int_set_si(v->el[i], max);
788 isl_int_mul_si(v->el[i], v->el[i], 2);
791 for (i = 0; i < node->nvar; ++i) {
792 isl_val *size;
794 size = isl_multi_val_get_val(node->sizes, i);
795 if (!size)
796 goto error;
797 if (!isl_val_is_int(size)) {
798 isl_val_free(size);
799 continue;
801 for (j = 0; j < node->nvar; ++j) {
802 if (j == i)
803 continue;
804 if (isl_int_is_neg(v->el[j]) ||
805 isl_int_gt(v->el[j], size->n))
806 isl_int_set(v->el[j], size->n);
808 isl_val_free(size);
811 for (i = 0; i < node->nvar; ++i) {
812 isl_int_fdiv_q_ui(v->el[i], v->el[i], 2);
813 if (isl_int_is_zero(v->el[i]))
814 isl_int_set_si(v->el[i], 1);
817 node->max = v;
818 return isl_stat_ok;
819 error:
820 isl_vec_free(v);
821 return isl_stat_error;
824 /* Compute and return the size of "set" in dimension "dim".
825 * The size is taken to be the difference in values for that variable
826 * for fixed values of the other variables.
827 * In particular, the variable is first isolated from the other variables
828 * in the range of a map
830 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [i_dim]
832 * and then duplicated
834 * [i_0, ..., i_dim-1, i_dim+1, ...] -> [[i_dim] -> [i_dim']]
836 * The shared variables are then projected out and the maximal value
837 * of i_dim' - i_dim is computed.
839 static __isl_give isl_val *compute_size(__isl_take isl_set *set, int dim)
841 isl_map *map;
842 isl_local_space *ls;
843 isl_aff *obj;
844 isl_val *v;
846 map = isl_set_project_onto_map(set, isl_dim_set, dim, 1);
847 map = isl_map_project_out(map, isl_dim_in, dim, 1);
848 map = isl_map_range_product(map, isl_map_copy(map));
849 map = isl_set_unwrap(isl_map_range(map));
850 set = isl_map_deltas(map);
851 ls = isl_local_space_from_space(isl_set_get_space(set));
852 obj = isl_aff_var_on_domain(ls, isl_dim_set, 0);
853 v = isl_set_max_val(set, obj);
854 isl_aff_free(obj);
855 isl_set_free(set);
857 return v;
860 /* Compute the size of the instance set "set" of "node", after compression,
861 * as well as bounds on the corresponding coefficients, if needed.
863 * The sizes are needed when the schedule_treat_coalescing option is set.
864 * The bounds are needed when the schedule_treat_coalescing option or
865 * the schedule_max_coefficient option is set.
867 * If the schedule_treat_coalescing option is not set, then at most
868 * the bounds need to be set and this is done in set_max_coefficient.
869 * Otherwise, compress the domain if needed, compute the size
870 * in each direction and store the results in node->size.
871 * Finally, set the bounds on the coefficients based on the sizes
872 * and the schedule_max_coefficient option in compute_max_coefficient.
874 static isl_stat compute_sizes_and_max(isl_ctx *ctx, struct isl_sched_node *node,
875 __isl_take isl_set *set)
877 int j, n;
878 isl_multi_val *mv;
880 if (!isl_options_get_schedule_treat_coalescing(ctx)) {
881 isl_set_free(set);
882 return set_max_coefficient(ctx, node);
885 if (node->compressed)
886 set = isl_set_preimage_multi_aff(set,
887 isl_multi_aff_copy(node->decompress));
888 mv = isl_multi_val_zero(isl_set_get_space(set));
889 n = isl_set_dim(set, isl_dim_set);
890 for (j = 0; j < n; ++j) {
891 isl_val *v;
893 v = compute_size(isl_set_copy(set), j);
894 mv = isl_multi_val_set_val(mv, j, v);
896 node->sizes = mv;
897 isl_set_free(set);
898 if (!node->sizes)
899 return isl_stat_error;
900 return compute_max_coefficient(ctx, node);
903 /* Add a new node to the graph representing the given instance set.
904 * "nvar" is the (possibly compressed) number of variables and
905 * may be smaller than then number of set variables in "set"
906 * if "compressed" is set.
907 * If "compressed" is set, then "hull" represents the constraints
908 * that were used to derive the compression, while "compress" and
909 * "decompress" map the original space to the compressed space and
910 * vice versa.
911 * If "compressed" is not set, then "hull", "compress" and "decompress"
912 * should be NULL.
914 * Compute the size of the instance set and bounds on the coefficients,
915 * if needed.
917 static isl_stat add_node(struct isl_sched_graph *graph,
918 __isl_take isl_set *set, int nvar, int compressed,
919 __isl_take isl_set *hull, __isl_take isl_multi_aff *compress,
920 __isl_take isl_multi_aff *decompress)
922 int nparam;
923 isl_ctx *ctx;
924 isl_mat *sched;
925 isl_space *space;
926 int *coincident;
927 struct isl_sched_node *node;
929 if (!set)
930 return isl_stat_error;
932 ctx = isl_set_get_ctx(set);
933 nparam = isl_set_dim(set, isl_dim_param);
934 if (!ctx->opt->schedule_parametric)
935 nparam = 0;
936 sched = isl_mat_alloc(ctx, 0, 1 + nparam + nvar);
937 node = &graph->node[graph->n];
938 graph->n++;
939 space = isl_set_get_space(set);
940 node->space = space;
941 node->nvar = nvar;
942 node->nparam = nparam;
943 node->sched = sched;
944 node->sched_map = NULL;
945 coincident = isl_calloc_array(ctx, int, graph->max_row);
946 node->coincident = coincident;
947 node->compressed = compressed;
948 node->hull = hull;
949 node->compress = compress;
950 node->decompress = decompress;
951 if (compute_sizes_and_max(ctx, node, set) < 0)
952 return isl_stat_error;
954 if (!space || !sched || (graph->max_row && !coincident))
955 return isl_stat_error;
956 if (compressed && (!hull || !compress || !decompress))
957 return isl_stat_error;
959 return isl_stat_ok;
962 /* Construct an identifier for node "node", which will represent "set".
963 * The name of the identifier is either "compressed" or
964 * "compressed_<name>", with <name> the name of the space of "set".
965 * The user pointer of the identifier points to "node".
967 static __isl_give isl_id *construct_compressed_id(__isl_keep isl_set *set,
968 struct isl_sched_node *node)
970 isl_bool has_name;
971 isl_ctx *ctx;
972 isl_id *id;
973 isl_printer *p;
974 const char *name;
975 char *id_name;
977 has_name = isl_set_has_tuple_name(set);
978 if (has_name < 0)
979 return NULL;
981 ctx = isl_set_get_ctx(set);
982 if (!has_name)
983 return isl_id_alloc(ctx, "compressed", node);
985 p = isl_printer_to_str(ctx);
986 name = isl_set_get_tuple_name(set);
987 p = isl_printer_print_str(p, "compressed_");
988 p = isl_printer_print_str(p, name);
989 id_name = isl_printer_get_str(p);
990 isl_printer_free(p);
992 id = isl_id_alloc(ctx, id_name, node);
993 free(id_name);
995 return id;
998 /* Add a new node to the graph representing the given set.
1000 * If any of the set variables is defined by an equality, then
1001 * we perform variable compression such that we can perform
1002 * the scheduling on the compressed domain.
1003 * In this case, an identifier is used that references the new node
1004 * such that each compressed space is unique and
1005 * such that the node can be recovered from the compressed space.
1007 static isl_stat extract_node(__isl_take isl_set *set, void *user)
1009 int nvar;
1010 isl_bool has_equality;
1011 isl_id *id;
1012 isl_basic_set *hull;
1013 isl_set *hull_set;
1014 isl_morph *morph;
1015 isl_multi_aff *compress, *decompress;
1016 struct isl_sched_graph *graph = user;
1018 hull = isl_set_affine_hull(isl_set_copy(set));
1019 hull = isl_basic_set_remove_divs(hull);
1020 nvar = isl_set_dim(set, isl_dim_set);
1021 has_equality = has_any_defining_equality(hull);
1023 if (has_equality < 0)
1024 goto error;
1025 if (!has_equality) {
1026 isl_basic_set_free(hull);
1027 return add_node(graph, set, nvar, 0, NULL, NULL, NULL);
1030 id = construct_compressed_id(set, &graph->node[graph->n]);
1031 morph = isl_basic_set_variable_compression_with_id(hull,
1032 isl_dim_set, id);
1033 isl_id_free(id);
1034 nvar = isl_morph_ran_dim(morph, isl_dim_set);
1035 compress = isl_morph_get_var_multi_aff(morph);
1036 morph = isl_morph_inverse(morph);
1037 decompress = isl_morph_get_var_multi_aff(morph);
1038 isl_morph_free(morph);
1040 hull_set = isl_set_from_basic_set(hull);
1041 return add_node(graph, set, nvar, 1, hull_set, compress, decompress);
1042 error:
1043 isl_basic_set_free(hull);
1044 isl_set_free(set);
1045 return isl_stat_error;
1048 struct isl_extract_edge_data {
1049 enum isl_edge_type type;
1050 struct isl_sched_graph *graph;
1053 /* Merge edge2 into edge1, freeing the contents of edge2.
1054 * Return 0 on success and -1 on failure.
1056 * edge1 and edge2 are assumed to have the same value for the map field.
1058 static int merge_edge(struct isl_sched_edge *edge1,
1059 struct isl_sched_edge *edge2)
1061 edge1->types |= edge2->types;
1062 isl_map_free(edge2->map);
1064 if (is_condition(edge2)) {
1065 if (!edge1->tagged_condition)
1066 edge1->tagged_condition = edge2->tagged_condition;
1067 else
1068 edge1->tagged_condition =
1069 isl_union_map_union(edge1->tagged_condition,
1070 edge2->tagged_condition);
1073 if (is_conditional_validity(edge2)) {
1074 if (!edge1->tagged_validity)
1075 edge1->tagged_validity = edge2->tagged_validity;
1076 else
1077 edge1->tagged_validity =
1078 isl_union_map_union(edge1->tagged_validity,
1079 edge2->tagged_validity);
1082 if (is_condition(edge2) && !edge1->tagged_condition)
1083 return -1;
1084 if (is_conditional_validity(edge2) && !edge1->tagged_validity)
1085 return -1;
1087 return 0;
1090 /* Insert dummy tags in domain and range of "map".
1092 * In particular, if "map" is of the form
1094 * A -> B
1096 * then return
1098 * [A -> dummy_tag] -> [B -> dummy_tag]
1100 * where the dummy_tags are identical and equal to any dummy tags
1101 * introduced by any other call to this function.
1103 static __isl_give isl_map *insert_dummy_tags(__isl_take isl_map *map)
1105 static char dummy;
1106 isl_ctx *ctx;
1107 isl_id *id;
1108 isl_space *space;
1109 isl_set *domain, *range;
1111 ctx = isl_map_get_ctx(map);
1113 id = isl_id_alloc(ctx, NULL, &dummy);
1114 space = isl_space_params(isl_map_get_space(map));
1115 space = isl_space_set_from_params(space);
1116 space = isl_space_set_tuple_id(space, isl_dim_set, id);
1117 space = isl_space_map_from_set(space);
1119 domain = isl_map_wrap(map);
1120 range = isl_map_wrap(isl_map_universe(space));
1121 map = isl_map_from_domain_and_range(domain, range);
1122 map = isl_map_zip(map);
1124 return map;
1127 /* Given that at least one of "src" or "dst" is compressed, return
1128 * a map between the spaces of these nodes restricted to the affine
1129 * hull that was used in the compression.
1131 static __isl_give isl_map *extract_hull(struct isl_sched_node *src,
1132 struct isl_sched_node *dst)
1134 isl_set *dom, *ran;
1136 if (src->compressed)
1137 dom = isl_set_copy(src->hull);
1138 else
1139 dom = isl_set_universe(isl_space_copy(src->space));
1140 if (dst->compressed)
1141 ran = isl_set_copy(dst->hull);
1142 else
1143 ran = isl_set_universe(isl_space_copy(dst->space));
1145 return isl_map_from_domain_and_range(dom, ran);
1148 /* Intersect the domains of the nested relations in domain and range
1149 * of "tagged" with "map".
1151 static __isl_give isl_map *map_intersect_domains(__isl_take isl_map *tagged,
1152 __isl_keep isl_map *map)
1154 isl_set *set;
1156 tagged = isl_map_zip(tagged);
1157 set = isl_map_wrap(isl_map_copy(map));
1158 tagged = isl_map_intersect_domain(tagged, set);
1159 tagged = isl_map_zip(tagged);
1160 return tagged;
1163 /* Return a pointer to the node that lives in the domain space of "map"
1164 * or NULL if there is no such node.
1166 static struct isl_sched_node *find_domain_node(isl_ctx *ctx,
1167 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1169 struct isl_sched_node *node;
1170 isl_space *space;
1172 space = isl_space_domain(isl_map_get_space(map));
1173 node = graph_find_node(ctx, graph, space);
1174 isl_space_free(space);
1176 return node;
1179 /* Return a pointer to the node that lives in the range space of "map"
1180 * or NULL if there is no such node.
1182 static struct isl_sched_node *find_range_node(isl_ctx *ctx,
1183 struct isl_sched_graph *graph, __isl_keep isl_map *map)
1185 struct isl_sched_node *node;
1186 isl_space *space;
1188 space = isl_space_range(isl_map_get_space(map));
1189 node = graph_find_node(ctx, graph, space);
1190 isl_space_free(space);
1192 return node;
1195 /* Add a new edge to the graph based on the given map
1196 * and add it to data->graph->edge_table[data->type].
1197 * If a dependence relation of a given type happens to be identical
1198 * to one of the dependence relations of a type that was added before,
1199 * then we don't create a new edge, but instead mark the original edge
1200 * as also representing a dependence of the current type.
1202 * Edges of type isl_edge_condition or isl_edge_conditional_validity
1203 * may be specified as "tagged" dependence relations. That is, "map"
1204 * may contain elements (i -> a) -> (j -> b), where i -> j denotes
1205 * the dependence on iterations and a and b are tags.
1206 * edge->map is set to the relation containing the elements i -> j,
1207 * while edge->tagged_condition and edge->tagged_validity contain
1208 * the union of all the "map" relations
1209 * for which extract_edge is called that result in the same edge->map.
1211 * If the source or the destination node is compressed, then
1212 * intersect both "map" and "tagged" with the constraints that
1213 * were used to construct the compression.
1214 * This ensures that there are no schedule constraints defined
1215 * outside of these domains, while the scheduler no longer has
1216 * any control over those outside parts.
1218 static isl_stat extract_edge(__isl_take isl_map *map, void *user)
1220 isl_ctx *ctx = isl_map_get_ctx(map);
1221 struct isl_extract_edge_data *data = user;
1222 struct isl_sched_graph *graph = data->graph;
1223 struct isl_sched_node *src, *dst;
1224 struct isl_sched_edge *edge;
1225 isl_map *tagged = NULL;
1227 if (data->type == isl_edge_condition ||
1228 data->type == isl_edge_conditional_validity) {
1229 if (isl_map_can_zip(map)) {
1230 tagged = isl_map_copy(map);
1231 map = isl_set_unwrap(isl_map_domain(isl_map_zip(map)));
1232 } else {
1233 tagged = insert_dummy_tags(isl_map_copy(map));
1237 src = find_domain_node(ctx, graph, map);
1238 dst = find_range_node(ctx, graph, map);
1240 if (!src || !dst) {
1241 isl_map_free(map);
1242 isl_map_free(tagged);
1243 return isl_stat_ok;
1246 if (src->compressed || dst->compressed) {
1247 isl_map *hull;
1248 hull = extract_hull(src, dst);
1249 if (tagged)
1250 tagged = map_intersect_domains(tagged, hull);
1251 map = isl_map_intersect(map, hull);
1254 graph->edge[graph->n_edge].src = src;
1255 graph->edge[graph->n_edge].dst = dst;
1256 graph->edge[graph->n_edge].map = map;
1257 graph->edge[graph->n_edge].types = 0;
1258 graph->edge[graph->n_edge].tagged_condition = NULL;
1259 graph->edge[graph->n_edge].tagged_validity = NULL;
1260 set_type(&graph->edge[graph->n_edge], data->type);
1261 if (data->type == isl_edge_condition)
1262 graph->edge[graph->n_edge].tagged_condition =
1263 isl_union_map_from_map(tagged);
1264 if (data->type == isl_edge_conditional_validity)
1265 graph->edge[graph->n_edge].tagged_validity =
1266 isl_union_map_from_map(tagged);
1268 edge = graph_find_matching_edge(graph, &graph->edge[graph->n_edge]);
1269 if (!edge) {
1270 graph->n_edge++;
1271 return isl_stat_error;
1273 if (edge == &graph->edge[graph->n_edge])
1274 return graph_edge_table_add(ctx, graph, data->type,
1275 &graph->edge[graph->n_edge++]);
1277 if (merge_edge(edge, &graph->edge[graph->n_edge]) < 0)
1278 return -1;
1280 return graph_edge_table_add(ctx, graph, data->type, edge);
1283 /* Initialize the schedule graph "graph" from the schedule constraints "sc".
1285 * The context is included in the domain before the nodes of
1286 * the graphs are extracted in order to be able to exploit
1287 * any possible additional equalities.
1288 * Note that this intersection is only performed locally here.
1290 static isl_stat graph_init(struct isl_sched_graph *graph,
1291 __isl_keep isl_schedule_constraints *sc)
1293 isl_ctx *ctx;
1294 isl_union_set *domain;
1295 isl_union_map *c;
1296 struct isl_extract_edge_data data;
1297 enum isl_edge_type i;
1298 isl_stat r;
1300 if (!sc)
1301 return isl_stat_error;
1303 ctx = isl_schedule_constraints_get_ctx(sc);
1305 domain = isl_schedule_constraints_get_domain(sc);
1306 graph->n = isl_union_set_n_set(domain);
1307 isl_union_set_free(domain);
1309 if (graph_alloc(ctx, graph, graph->n,
1310 isl_schedule_constraints_n_map(sc)) < 0)
1311 return isl_stat_error;
1313 if (compute_max_row(graph, sc) < 0)
1314 return isl_stat_error;
1315 graph->root = 1;
1316 graph->n = 0;
1317 domain = isl_schedule_constraints_get_domain(sc);
1318 domain = isl_union_set_intersect_params(domain,
1319 isl_schedule_constraints_get_context(sc));
1320 r = isl_union_set_foreach_set(domain, &extract_node, graph);
1321 isl_union_set_free(domain);
1322 if (r < 0)
1323 return isl_stat_error;
1324 if (graph_init_table(ctx, graph) < 0)
1325 return isl_stat_error;
1326 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1327 c = isl_schedule_constraints_get(sc, i);
1328 graph->max_edge[i] = isl_union_map_n_map(c);
1329 isl_union_map_free(c);
1330 if (!c)
1331 return isl_stat_error;
1333 if (graph_init_edge_tables(ctx, graph) < 0)
1334 return isl_stat_error;
1335 graph->n_edge = 0;
1336 data.graph = graph;
1337 for (i = isl_edge_first; i <= isl_edge_last; ++i) {
1338 isl_stat r;
1340 data.type = i;
1341 c = isl_schedule_constraints_get(sc, i);
1342 r = isl_union_map_foreach_map(c, &extract_edge, &data);
1343 isl_union_map_free(c);
1344 if (r < 0)
1345 return isl_stat_error;
1348 return isl_stat_ok;
1351 /* Check whether there is any dependence from node[j] to node[i]
1352 * or from node[i] to node[j].
1354 static isl_bool node_follows_weak(int i, int j, void *user)
1356 isl_bool f;
1357 struct isl_sched_graph *graph = user;
1359 f = graph_has_any_edge(graph, &graph->node[j], &graph->node[i]);
1360 if (f < 0 || f)
1361 return f;
1362 return graph_has_any_edge(graph, &graph->node[i], &graph->node[j]);
1365 /* Check whether there is a (conditional) validity dependence from node[j]
1366 * to node[i], forcing node[i] to follow node[j].
1368 static isl_bool node_follows_strong(int i, int j, void *user)
1370 struct isl_sched_graph *graph = user;
1372 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
1375 /* Use Tarjan's algorithm for computing the strongly connected components
1376 * in the dependence graph only considering those edges defined by "follows".
1378 static int detect_ccs(isl_ctx *ctx, struct isl_sched_graph *graph,
1379 isl_bool (*follows)(int i, int j, void *user))
1381 int i, n;
1382 struct isl_tarjan_graph *g = NULL;
1384 g = isl_tarjan_graph_init(ctx, graph->n, follows, graph);
1385 if (!g)
1386 return -1;
1388 graph->scc = 0;
1389 i = 0;
1390 n = graph->n;
1391 while (n) {
1392 while (g->order[i] != -1) {
1393 graph->node[g->order[i]].scc = graph->scc;
1394 --n;
1395 ++i;
1397 ++i;
1398 graph->scc++;
1401 isl_tarjan_graph_free(g);
1403 return 0;
1406 /* Apply Tarjan's algorithm to detect the strongly connected components
1407 * in the dependence graph.
1408 * Only consider the (conditional) validity dependences and clear "weak".
1410 static int detect_sccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1412 graph->weak = 0;
1413 return detect_ccs(ctx, graph, &node_follows_strong);
1416 /* Apply Tarjan's algorithm to detect the (weakly) connected components
1417 * in the dependence graph.
1418 * Consider all dependences and set "weak".
1420 static int detect_wccs(isl_ctx *ctx, struct isl_sched_graph *graph)
1422 graph->weak = 1;
1423 return detect_ccs(ctx, graph, &node_follows_weak);
1426 static int cmp_scc(const void *a, const void *b, void *data)
1428 struct isl_sched_graph *graph = data;
1429 const int *i1 = a;
1430 const int *i2 = b;
1432 return graph->node[*i1].scc - graph->node[*i2].scc;
1435 /* Sort the elements of graph->sorted according to the corresponding SCCs.
1437 static int sort_sccs(struct isl_sched_graph *graph)
1439 return isl_sort(graph->sorted, graph->n, sizeof(int), &cmp_scc, graph);
1442 /* Given a dependence relation R from "node" to itself,
1443 * construct the set of coefficients of valid constraints for elements
1444 * in that dependence relation.
1445 * In particular, the result contains tuples of coefficients
1446 * c_0, c_n, c_x such that
1448 * c_0 + c_n n + c_x y - c_x x >= 0 for each (x,y) in R
1450 * or, equivalently,
1452 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
1454 * We choose here to compute the dual of delta R.
1455 * Alternatively, we could have computed the dual of R, resulting
1456 * in a set of tuples c_0, c_n, c_x, c_y, and then
1457 * plugged in (c_0, c_n, c_x, -c_x).
1459 * If "node" has been compressed, then the dependence relation
1460 * is also compressed before the set of coefficients is computed.
1462 static __isl_give isl_basic_set *intra_coefficients(
1463 struct isl_sched_graph *graph, struct isl_sched_node *node,
1464 __isl_take isl_map *map)
1466 isl_set *delta;
1467 isl_map *key;
1468 isl_basic_set *coef;
1469 isl_maybe_isl_basic_set m;
1471 m = isl_map_to_basic_set_try_get(graph->intra_hmap, map);
1472 if (m.valid < 0 || m.valid) {
1473 isl_map_free(map);
1474 return m.value;
1477 key = isl_map_copy(map);
1478 if (node->compressed) {
1479 map = isl_map_preimage_domain_multi_aff(map,
1480 isl_multi_aff_copy(node->decompress));
1481 map = isl_map_preimage_range_multi_aff(map,
1482 isl_multi_aff_copy(node->decompress));
1484 delta = isl_set_remove_divs(isl_map_deltas(map));
1485 coef = isl_set_coefficients(delta);
1486 graph->intra_hmap = isl_map_to_basic_set_set(graph->intra_hmap, key,
1487 isl_basic_set_copy(coef));
1489 return coef;
1492 /* Given a dependence relation R, construct the set of coefficients
1493 * of valid constraints for elements in that dependence relation.
1494 * In particular, the result contains tuples of coefficients
1495 * c_0, c_n, c_x, c_y such that
1497 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
1499 * If the source or destination nodes of "edge" have been compressed,
1500 * then the dependence relation is also compressed before
1501 * the set of coefficients is computed.
1503 static __isl_give isl_basic_set *inter_coefficients(
1504 struct isl_sched_graph *graph, struct isl_sched_edge *edge,
1505 __isl_take isl_map *map)
1507 isl_set *set;
1508 isl_map *key;
1509 isl_basic_set *coef;
1510 isl_maybe_isl_basic_set m;
1512 m = isl_map_to_basic_set_try_get(graph->inter_hmap, map);
1513 if (m.valid < 0 || m.valid) {
1514 isl_map_free(map);
1515 return m.value;
1518 key = isl_map_copy(map);
1519 if (edge->src->compressed)
1520 map = isl_map_preimage_domain_multi_aff(map,
1521 isl_multi_aff_copy(edge->src->decompress));
1522 if (edge->dst->compressed)
1523 map = isl_map_preimage_range_multi_aff(map,
1524 isl_multi_aff_copy(edge->dst->decompress));
1525 set = isl_map_wrap(isl_map_remove_divs(map));
1526 coef = isl_set_coefficients(set);
1527 graph->inter_hmap = isl_map_to_basic_set_set(graph->inter_hmap, key,
1528 isl_basic_set_copy(coef));
1530 return coef;
1533 /* Return the position of the coefficients of the variables in
1534 * the coefficients constraints "coef".
1536 * The space of "coef" is of the form
1538 * { coefficients[[cst, params] -> S] }
1540 * Return the position of S.
1542 static int coef_var_offset(__isl_keep isl_basic_set *coef)
1544 int offset;
1545 isl_space *space;
1547 space = isl_space_unwrap(isl_basic_set_get_space(coef));
1548 offset = isl_space_dim(space, isl_dim_in);
1549 isl_space_free(space);
1551 return offset;
1554 /* Return the offset of the coefficients of the variables of "node"
1555 * within the (I)LP.
1557 * Within each node, the coefficients have the following order:
1558 * - c_i_0
1559 * - c_i_n (if parametric)
1560 * - positive and negative parts of c_i_x
1562 static int node_var_coef_offset(struct isl_sched_node *node)
1564 return node->start + 1 + node->nparam;
1567 /* Return the position of the pair of variables encoding
1568 * coefficient "i" of "node".
1570 * The order of these variable pairs is the opposite of
1571 * that of the coefficients, with 2 variables per coefficient.
1573 static int node_var_coef_pos(struct isl_sched_node *node, int i)
1575 return node_var_coef_offset(node) + 2 * (node->nvar - 1 - i);
1578 /* Construct an isl_dim_map for mapping constraints on coefficients
1579 * for "node" to the corresponding positions in graph->lp.
1580 * "offset" is the offset of the coefficients for the variables
1581 * in the input constraints.
1582 * "s" is the sign of the mapping.
1584 * The input constraints are given in terms of the coefficients (c_0, c_n, c_x).
1585 * The mapping produced by this function essentially plugs in
1586 * (0, 0, c_i_x^+ - c_i_x^-) if s = 1 and
1587 * (0, 0, -c_i_x^+ + c_i_x^-) if s = -1.
1588 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1589 * Furthermore, the order of these pairs is the opposite of that
1590 * of the corresponding coefficients.
1592 * The caller can extend the mapping to also map the other coefficients
1593 * (and therefore not plug in 0).
1595 static __isl_give isl_dim_map *intra_dim_map(isl_ctx *ctx,
1596 struct isl_sched_graph *graph, struct isl_sched_node *node,
1597 int offset, int s)
1599 int pos;
1600 unsigned total;
1601 isl_dim_map *dim_map;
1603 if (!node)
1604 return NULL;
1606 total = isl_basic_set_total_dim(graph->lp);
1607 pos = node_var_coef_pos(node, 0);
1608 dim_map = isl_dim_map_alloc(ctx, total);
1609 isl_dim_map_range(dim_map, pos, -2, offset, 1, node->nvar, -s);
1610 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, node->nvar, s);
1612 return dim_map;
1615 /* Construct an isl_dim_map for mapping constraints on coefficients
1616 * for "src" (node i) and "dst" (node j) to the corresponding positions
1617 * in graph->lp.
1618 * "offset" is the offset of the coefficients for the variables of "src"
1619 * in the input constraints.
1620 * "s" is the sign of the mapping.
1622 * The input constraints are given in terms of the coefficients
1623 * (c_0, c_n, c_x, c_y).
1624 * The mapping produced by this function essentially plugs in
1625 * (c_j_0 - c_i_0, c_j_n - c_i_n,
1626 * -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-) if s = 1 and
1627 * (-c_j_0 + c_i_0, -c_j_n + c_i_n,
1628 * c_i_x^+ - c_i_x^-, -(c_j_x^+ - c_j_x^-)) if s = -1.
1629 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1630 * Furthermore, the order of these pairs is the opposite of that
1631 * of the corresponding coefficients.
1633 * The caller can further extend the mapping.
1635 static __isl_give isl_dim_map *inter_dim_map(isl_ctx *ctx,
1636 struct isl_sched_graph *graph, struct isl_sched_node *src,
1637 struct isl_sched_node *dst, int offset, int s)
1639 int pos;
1640 unsigned total;
1641 isl_dim_map *dim_map;
1643 if (!src || !dst)
1644 return NULL;
1646 total = isl_basic_set_total_dim(graph->lp);
1647 dim_map = isl_dim_map_alloc(ctx, total);
1649 isl_dim_map_range(dim_map, dst->start, 0, 0, 0, 1, s);
1650 isl_dim_map_range(dim_map, dst->start + 1, 1, 1, 1, dst->nparam, s);
1651 pos = node_var_coef_pos(dst, 0);
1652 isl_dim_map_range(dim_map, pos, -2, offset + src->nvar, 1,
1653 dst->nvar, -s);
1654 isl_dim_map_range(dim_map, pos + 1, -2, offset + src->nvar, 1,
1655 dst->nvar, s);
1657 isl_dim_map_range(dim_map, src->start, 0, 0, 0, 1, -s);
1658 isl_dim_map_range(dim_map, src->start + 1, 1, 1, 1, src->nparam, -s);
1659 pos = node_var_coef_pos(src, 0);
1660 isl_dim_map_range(dim_map, pos, -2, offset, 1, src->nvar, s);
1661 isl_dim_map_range(dim_map, pos + 1, -2, offset, 1, src->nvar, -s);
1663 return dim_map;
1666 /* Add the constraints from "src" to "dst" using "dim_map",
1667 * after making sure there is enough room in "dst" for the extra constraints.
1669 static __isl_give isl_basic_set *add_constraints_dim_map(
1670 __isl_take isl_basic_set *dst, __isl_take isl_basic_set *src,
1671 __isl_take isl_dim_map *dim_map)
1673 int n_eq, n_ineq;
1675 n_eq = isl_basic_set_n_equality(src);
1676 n_ineq = isl_basic_set_n_inequality(src);
1677 dst = isl_basic_set_extend_constraints(dst, n_eq, n_ineq);
1678 dst = isl_basic_set_add_constraints_dim_map(dst, src, dim_map);
1679 return dst;
1682 /* Add constraints to graph->lp that force validity for the given
1683 * dependence from a node i to itself.
1684 * That is, add constraints that enforce
1686 * (c_i_0 + c_i_n n + c_i_x y) - (c_i_0 + c_i_n n + c_i_x x)
1687 * = c_i_x (y - x) >= 0
1689 * for each (x,y) in R.
1690 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1691 * of valid constraints for (y - x) and then plug in (0, 0, c_i_x^+ - c_i_x^-),
1692 * where c_i_x = c_i_x^+ - c_i_x^-, with c_i_x^+ and c_i_x^- non-negative.
1693 * In graph->lp, the c_i_x^- appear before their c_i_x^+ counterpart.
1695 static isl_stat add_intra_validity_constraints(struct isl_sched_graph *graph,
1696 struct isl_sched_edge *edge)
1698 int offset;
1699 isl_map *map = isl_map_copy(edge->map);
1700 isl_ctx *ctx = isl_map_get_ctx(map);
1701 isl_dim_map *dim_map;
1702 isl_basic_set *coef;
1703 struct isl_sched_node *node = edge->src;
1705 coef = intra_coefficients(graph, node, map);
1707 offset = coef_var_offset(coef);
1709 if (!coef)
1710 return isl_stat_error;
1712 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
1713 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1715 return isl_stat_ok;
1718 /* Add constraints to graph->lp that force validity for the given
1719 * dependence from node i to node j.
1720 * That is, add constraints that enforce
1722 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) >= 0
1724 * for each (x,y) in R.
1725 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1726 * of valid constraints for R and then plug in
1727 * (c_j_0 - c_i_0, c_j_n - c_i_n, -(c_i_x^+ - c_i_x^-), c_j_x^+ - c_j_x^-),
1728 * where c_* = c_*^+ - c_*^-, with c_*^+ and c_*^- non-negative.
1729 * In graph->lp, the c_*^- appear before their c_*^+ counterpart.
1731 static isl_stat add_inter_validity_constraints(struct isl_sched_graph *graph,
1732 struct isl_sched_edge *edge)
1734 int offset;
1735 isl_map *map;
1736 isl_ctx *ctx;
1737 isl_dim_map *dim_map;
1738 isl_basic_set *coef;
1739 struct isl_sched_node *src = edge->src;
1740 struct isl_sched_node *dst = edge->dst;
1742 if (!graph->lp)
1743 return isl_stat_error;
1745 map = isl_map_copy(edge->map);
1746 ctx = isl_map_get_ctx(map);
1747 coef = inter_coefficients(graph, edge, map);
1749 offset = coef_var_offset(coef);
1751 if (!coef)
1752 return isl_stat_error;
1754 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
1756 edge->start = graph->lp->n_ineq;
1757 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1758 if (!graph->lp)
1759 return isl_stat_error;
1760 edge->end = graph->lp->n_ineq;
1762 return isl_stat_ok;
1765 /* Add constraints to graph->lp that bound the dependence distance for the given
1766 * dependence from a node i to itself.
1767 * If s = 1, we add the constraint
1769 * c_i_x (y - x) <= m_0 + m_n n
1771 * or
1773 * -c_i_x (y - x) + m_0 + m_n n >= 0
1775 * for each (x,y) in R.
1776 * If s = -1, we add the constraint
1778 * -c_i_x (y - x) <= m_0 + m_n n
1780 * or
1782 * c_i_x (y - x) + m_0 + m_n n >= 0
1784 * for each (x,y) in R.
1785 * We obtain general constraints on coefficients (c_0, c_n, c_x)
1786 * of valid constraints for (y - x) and then plug in (m_0, m_n, -s * c_i_x),
1787 * with each coefficient (except m_0) represented as a pair of non-negative
1788 * coefficients.
1791 * If "local" is set, then we add constraints
1793 * c_i_x (y - x) <= 0
1795 * or
1797 * -c_i_x (y - x) <= 0
1799 * instead, forcing the dependence distance to be (less than or) equal to 0.
1800 * That is, we plug in (0, 0, -s * c_i_x),
1801 * Note that dependences marked local are treated as validity constraints
1802 * by add_all_validity_constraints and therefore also have
1803 * their distances bounded by 0 from below.
1805 static isl_stat add_intra_proximity_constraints(struct isl_sched_graph *graph,
1806 struct isl_sched_edge *edge, int s, int local)
1808 int offset;
1809 unsigned nparam;
1810 isl_map *map = isl_map_copy(edge->map);
1811 isl_ctx *ctx = isl_map_get_ctx(map);
1812 isl_dim_map *dim_map;
1813 isl_basic_set *coef;
1814 struct isl_sched_node *node = edge->src;
1816 coef = intra_coefficients(graph, node, map);
1818 offset = coef_var_offset(coef);
1820 if (!coef)
1821 return isl_stat_error;
1823 nparam = isl_space_dim(node->space, isl_dim_param);
1824 dim_map = intra_dim_map(ctx, graph, node, offset, -s);
1826 if (!local) {
1827 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1828 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1829 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1831 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1833 return isl_stat_ok;
1836 /* Add constraints to graph->lp that bound the dependence distance for the given
1837 * dependence from node i to node j.
1838 * If s = 1, we add the constraint
1840 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x)
1841 * <= m_0 + m_n n
1843 * or
1845 * -(c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x) +
1846 * m_0 + m_n n >= 0
1848 * for each (x,y) in R.
1849 * If s = -1, we add the constraint
1851 * -((c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x))
1852 * <= m_0 + m_n n
1854 * or
1856 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) +
1857 * m_0 + m_n n >= 0
1859 * for each (x,y) in R.
1860 * We obtain general constraints on coefficients (c_0, c_n, c_x, c_y)
1861 * of valid constraints for R and then plug in
1862 * (m_0 - s*c_j_0 + s*c_i_0, m_n - s*c_j_n + s*c_i_n,
1863 * s*c_i_x, -s*c_j_x)
1864 * with each coefficient (except m_0, c_*_0 and c_*_n)
1865 * represented as a pair of non-negative coefficients.
1868 * If "local" is set (and s = 1), then we add constraints
1870 * (c_j_0 + c_j_n n + c_j_x y) - (c_i_0 + c_i_n n + c_i_x x) <= 0
1872 * or
1874 * -((c_j_0 + c_j_n n + c_j_x y) + (c_i_0 + c_i_n n + c_i_x x)) >= 0
1876 * instead, forcing the dependence distance to be (less than or) equal to 0.
1877 * That is, we plug in
1878 * (-s*c_j_0 + s*c_i_0, -s*c_j_n + s*c_i_n, s*c_i_x, -s*c_j_x).
1879 * Note that dependences marked local are treated as validity constraints
1880 * by add_all_validity_constraints and therefore also have
1881 * their distances bounded by 0 from below.
1883 static isl_stat add_inter_proximity_constraints(struct isl_sched_graph *graph,
1884 struct isl_sched_edge *edge, int s, int local)
1886 int offset;
1887 unsigned nparam;
1888 isl_map *map = isl_map_copy(edge->map);
1889 isl_ctx *ctx = isl_map_get_ctx(map);
1890 isl_dim_map *dim_map;
1891 isl_basic_set *coef;
1892 struct isl_sched_node *src = edge->src;
1893 struct isl_sched_node *dst = edge->dst;
1895 coef = inter_coefficients(graph, edge, map);
1897 offset = coef_var_offset(coef);
1899 if (!coef)
1900 return isl_stat_error;
1902 nparam = isl_space_dim(src->space, isl_dim_param);
1903 dim_map = inter_dim_map(ctx, graph, src, dst, offset, -s);
1905 if (!local) {
1906 isl_dim_map_range(dim_map, 1, 0, 0, 0, 1, 1);
1907 isl_dim_map_range(dim_map, 4, 2, 1, 1, nparam, -1);
1908 isl_dim_map_range(dim_map, 5, 2, 1, 1, nparam, 1);
1911 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
1913 return isl_stat_ok;
1916 /* Add all validity constraints to graph->lp.
1918 * An edge that is forced to be local needs to have its dependence
1919 * distances equal to zero. We take care of bounding them by 0 from below
1920 * here. add_all_proximity_constraints takes care of bounding them by 0
1921 * from above.
1923 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
1924 * Otherwise, we ignore them.
1926 static int add_all_validity_constraints(struct isl_sched_graph *graph,
1927 int use_coincidence)
1929 int i;
1931 for (i = 0; i < graph->n_edge; ++i) {
1932 struct isl_sched_edge *edge = &graph->edge[i];
1933 int local;
1935 local = is_local(edge) ||
1936 (is_coincidence(edge) && use_coincidence);
1937 if (!is_validity(edge) && !local)
1938 continue;
1939 if (edge->src != edge->dst)
1940 continue;
1941 if (add_intra_validity_constraints(graph, edge) < 0)
1942 return -1;
1945 for (i = 0; i < graph->n_edge; ++i) {
1946 struct isl_sched_edge *edge = &graph->edge[i];
1947 int local;
1949 local = is_local(edge) ||
1950 (is_coincidence(edge) && use_coincidence);
1951 if (!is_validity(edge) && !local)
1952 continue;
1953 if (edge->src == edge->dst)
1954 continue;
1955 if (add_inter_validity_constraints(graph, edge) < 0)
1956 return -1;
1959 return 0;
1962 /* Add constraints to graph->lp that bound the dependence distance
1963 * for all dependence relations.
1964 * If a given proximity dependence is identical to a validity
1965 * dependence, then the dependence distance is already bounded
1966 * from below (by zero), so we only need to bound the distance
1967 * from above. (This includes the case of "local" dependences
1968 * which are treated as validity dependence by add_all_validity_constraints.)
1969 * Otherwise, we need to bound the distance both from above and from below.
1971 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
1972 * Otherwise, we ignore them.
1974 static int add_all_proximity_constraints(struct isl_sched_graph *graph,
1975 int use_coincidence)
1977 int i;
1979 for (i = 0; i < graph->n_edge; ++i) {
1980 struct isl_sched_edge *edge = &graph->edge[i];
1981 int local;
1983 local = is_local(edge) ||
1984 (is_coincidence(edge) && use_coincidence);
1985 if (!is_proximity(edge) && !local)
1986 continue;
1987 if (edge->src == edge->dst &&
1988 add_intra_proximity_constraints(graph, edge, 1, local) < 0)
1989 return -1;
1990 if (edge->src != edge->dst &&
1991 add_inter_proximity_constraints(graph, edge, 1, local) < 0)
1992 return -1;
1993 if (is_validity(edge) || local)
1994 continue;
1995 if (edge->src == edge->dst &&
1996 add_intra_proximity_constraints(graph, edge, -1, 0) < 0)
1997 return -1;
1998 if (edge->src != edge->dst &&
1999 add_inter_proximity_constraints(graph, edge, -1, 0) < 0)
2000 return -1;
2003 return 0;
2006 /* Normalize the rows of "indep" such that all rows are lexicographically
2007 * positive and such that each row contains as many final zeros as possible,
2008 * given the choice for the previous rows.
2009 * Do this by performing elementary row operations.
2011 static __isl_give isl_mat *normalize_independent(__isl_take isl_mat *indep)
2013 indep = isl_mat_reverse_gauss(indep);
2014 indep = isl_mat_lexnonneg_rows(indep);
2015 return indep;
2018 /* Compute a basis for the rows in the linear part of the schedule
2019 * and extend this basis to a full basis. The remaining rows
2020 * can then be used to force linear independence from the rows
2021 * in the schedule.
2023 * In particular, given the schedule rows S, we compute
2025 * S = H Q
2026 * S U = H
2028 * with H the Hermite normal form of S. That is, all but the
2029 * first rank columns of H are zero and so each row in S is
2030 * a linear combination of the first rank rows of Q.
2031 * The matrix Q can be used as a variable transformation
2032 * that isolates the directions of S in the first rank rows.
2033 * Transposing S U = H yields
2035 * U^T S^T = H^T
2037 * with all but the first rank rows of H^T zero.
2038 * The last rows of U^T are therefore linear combinations
2039 * of schedule coefficients that are all zero on schedule
2040 * coefficients that are linearly dependent on the rows of S.
2041 * At least one of these combinations is non-zero on
2042 * linearly independent schedule coefficients.
2043 * The rows are normalized to involve as few of the last
2044 * coefficients as possible and to have a positive initial value.
2046 static int node_update_vmap(struct isl_sched_node *node)
2048 isl_mat *H, *U, *Q;
2049 int n_row = isl_mat_rows(node->sched);
2051 H = isl_mat_sub_alloc(node->sched, 0, n_row,
2052 1 + node->nparam, node->nvar);
2054 H = isl_mat_left_hermite(H, 0, &U, &Q);
2055 isl_mat_free(node->indep);
2056 isl_mat_free(node->vmap);
2057 node->vmap = Q;
2058 node->indep = isl_mat_transpose(U);
2059 node->rank = isl_mat_initial_non_zero_cols(H);
2060 node->indep = isl_mat_drop_rows(node->indep, 0, node->rank);
2061 node->indep = normalize_independent(node->indep);
2062 isl_mat_free(H);
2064 if (!node->indep || !node->vmap || node->rank < 0)
2065 return -1;
2066 return 0;
2069 /* Is "edge" marked as a validity or a conditional validity edge?
2071 static int is_any_validity(struct isl_sched_edge *edge)
2073 return is_validity(edge) || is_conditional_validity(edge);
2076 /* How many times should we count the constraints in "edge"?
2078 * We count as follows
2079 * validity -> 1 (>= 0)
2080 * validity+proximity -> 2 (>= 0 and upper bound)
2081 * proximity -> 2 (lower and upper bound)
2082 * local(+any) -> 2 (>= 0 and <= 0)
2084 * If an edge is only marked conditional_validity then it counts
2085 * as zero since it is only checked afterwards.
2087 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2088 * Otherwise, we ignore them.
2090 static int edge_multiplicity(struct isl_sched_edge *edge, int use_coincidence)
2092 if (is_proximity(edge) || is_local(edge))
2093 return 2;
2094 if (use_coincidence && is_coincidence(edge))
2095 return 2;
2096 if (is_validity(edge))
2097 return 1;
2098 return 0;
2101 /* Count the number of equality and inequality constraints
2102 * that will be added for the given map.
2104 * "use_coincidence" is set if we should take into account coincidence edges.
2106 static isl_stat count_map_constraints(struct isl_sched_graph *graph,
2107 struct isl_sched_edge *edge, __isl_take isl_map *map,
2108 int *n_eq, int *n_ineq, int use_coincidence)
2110 isl_basic_set *coef;
2111 int f = edge_multiplicity(edge, use_coincidence);
2113 if (f == 0) {
2114 isl_map_free(map);
2115 return isl_stat_ok;
2118 if (edge->src == edge->dst)
2119 coef = intra_coefficients(graph, edge->src, map);
2120 else
2121 coef = inter_coefficients(graph, edge, map);
2122 if (!coef)
2123 return isl_stat_error;
2124 *n_eq += f * isl_basic_set_n_equality(coef);
2125 *n_ineq += f * isl_basic_set_n_inequality(coef);
2126 isl_basic_set_free(coef);
2128 return isl_stat_ok;
2131 /* Count the number of equality and inequality constraints
2132 * that will be added to the main lp problem.
2133 * We count as follows
2134 * validity -> 1 (>= 0)
2135 * validity+proximity -> 2 (>= 0 and upper bound)
2136 * proximity -> 2 (lower and upper bound)
2137 * local(+any) -> 2 (>= 0 and <= 0)
2139 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2140 * Otherwise, we ignore them.
2142 static int count_constraints(struct isl_sched_graph *graph,
2143 int *n_eq, int *n_ineq, int use_coincidence)
2145 int i;
2147 *n_eq = *n_ineq = 0;
2148 for (i = 0; i < graph->n_edge; ++i) {
2149 struct isl_sched_edge *edge = &graph->edge[i];
2150 isl_map *map = isl_map_copy(edge->map);
2152 if (count_map_constraints(graph, edge, map, n_eq, n_ineq,
2153 use_coincidence) < 0)
2154 return -1;
2157 return 0;
2160 /* Count the number of constraints that will be added by
2161 * add_bound_constant_constraints to bound the values of the constant terms
2162 * and increment *n_eq and *n_ineq accordingly.
2164 * In practice, add_bound_constant_constraints only adds inequalities.
2166 static isl_stat count_bound_constant_constraints(isl_ctx *ctx,
2167 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2169 if (isl_options_get_schedule_max_constant_term(ctx) == -1)
2170 return isl_stat_ok;
2172 *n_ineq += graph->n;
2174 return isl_stat_ok;
2177 /* Add constraints to bound the values of the constant terms in the schedule,
2178 * if requested by the user.
2180 * The maximal value of the constant terms is defined by the option
2181 * "schedule_max_constant_term".
2183 * Within each node, the coefficients have the following order:
2184 * - c_i_0
2185 * - c_i_n (if parametric)
2186 * - positive and negative parts of c_i_x
2188 static isl_stat add_bound_constant_constraints(isl_ctx *ctx,
2189 struct isl_sched_graph *graph)
2191 int i, k;
2192 int max;
2193 int total;
2195 max = isl_options_get_schedule_max_constant_term(ctx);
2196 if (max == -1)
2197 return isl_stat_ok;
2199 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2201 for (i = 0; i < graph->n; ++i) {
2202 struct isl_sched_node *node = &graph->node[i];
2203 k = isl_basic_set_alloc_inequality(graph->lp);
2204 if (k < 0)
2205 return isl_stat_error;
2206 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2207 isl_int_set_si(graph->lp->ineq[k][1 + node->start], -1);
2208 isl_int_set_si(graph->lp->ineq[k][0], max);
2211 return isl_stat_ok;
2214 /* Count the number of constraints that will be added by
2215 * add_bound_coefficient_constraints and increment *n_eq and *n_ineq
2216 * accordingly.
2218 * In practice, add_bound_coefficient_constraints only adds inequalities.
2220 static int count_bound_coefficient_constraints(isl_ctx *ctx,
2221 struct isl_sched_graph *graph, int *n_eq, int *n_ineq)
2223 int i;
2225 if (isl_options_get_schedule_max_coefficient(ctx) == -1 &&
2226 !isl_options_get_schedule_treat_coalescing(ctx))
2227 return 0;
2229 for (i = 0; i < graph->n; ++i)
2230 *n_ineq += graph->node[i].nparam + 2 * graph->node[i].nvar;
2232 return 0;
2235 /* Add constraints to graph->lp that bound the values of
2236 * the parameter schedule coefficients of "node" to "max" and
2237 * the variable schedule coefficients to the corresponding entry
2238 * in node->max.
2239 * In either case, a negative value means that no bound needs to be imposed.
2241 * For parameter coefficients, this amounts to adding a constraint
2243 * c_n <= max
2245 * i.e.,
2247 * -c_n + max >= 0
2249 * The variables coefficients are, however, not represented directly.
2250 * Instead, the variable coefficients c_x are written as differences
2251 * c_x = c_x^+ - c_x^-.
2252 * That is,
2254 * -max_i <= c_x_i <= max_i
2256 * is encoded as
2258 * -max_i <= c_x_i^+ - c_x_i^- <= max_i
2260 * or
2262 * -(c_x_i^+ - c_x_i^-) + max_i >= 0
2263 * c_x_i^+ - c_x_i^- + max_i >= 0
2265 static isl_stat node_add_coefficient_constraints(isl_ctx *ctx,
2266 struct isl_sched_graph *graph, struct isl_sched_node *node, int max)
2268 int i, j, k;
2269 int total;
2270 isl_vec *ineq;
2272 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2274 for (j = 0; j < node->nparam; ++j) {
2275 int dim;
2277 if (max < 0)
2278 continue;
2280 k = isl_basic_set_alloc_inequality(graph->lp);
2281 if (k < 0)
2282 return isl_stat_error;
2283 dim = 1 + node->start + 1 + j;
2284 isl_seq_clr(graph->lp->ineq[k], 1 + total);
2285 isl_int_set_si(graph->lp->ineq[k][dim], -1);
2286 isl_int_set_si(graph->lp->ineq[k][0], max);
2289 ineq = isl_vec_alloc(ctx, 1 + total);
2290 ineq = isl_vec_clr(ineq);
2291 if (!ineq)
2292 return isl_stat_error;
2293 for (i = 0; i < node->nvar; ++i) {
2294 int pos = 1 + node_var_coef_pos(node, i);
2296 if (isl_int_is_neg(node->max->el[i]))
2297 continue;
2299 isl_int_set_si(ineq->el[pos], 1);
2300 isl_int_set_si(ineq->el[pos + 1], -1);
2301 isl_int_set(ineq->el[0], node->max->el[i]);
2303 k = isl_basic_set_alloc_inequality(graph->lp);
2304 if (k < 0)
2305 goto error;
2306 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2308 isl_seq_neg(ineq->el + pos, ineq->el + pos + 2 * i, 2);
2309 k = isl_basic_set_alloc_inequality(graph->lp);
2310 if (k < 0)
2311 goto error;
2312 isl_seq_cpy(graph->lp->ineq[k], ineq->el, 1 + total);
2314 isl_vec_free(ineq);
2316 return isl_stat_ok;
2317 error:
2318 isl_vec_free(ineq);
2319 return isl_stat_error;
2322 /* Add constraints that bound the values of the variable and parameter
2323 * coefficients of the schedule.
2325 * The maximal value of the coefficients is defined by the option
2326 * 'schedule_max_coefficient' and the entries in node->max.
2327 * These latter entries are only set if either the schedule_max_coefficient
2328 * option or the schedule_treat_coalescing option is set.
2330 static isl_stat add_bound_coefficient_constraints(isl_ctx *ctx,
2331 struct isl_sched_graph *graph)
2333 int i;
2334 int max;
2336 max = isl_options_get_schedule_max_coefficient(ctx);
2338 if (max == -1 && !isl_options_get_schedule_treat_coalescing(ctx))
2339 return isl_stat_ok;
2341 for (i = 0; i < graph->n; ++i) {
2342 struct isl_sched_node *node = &graph->node[i];
2344 if (node_add_coefficient_constraints(ctx, graph, node, max) < 0)
2345 return isl_stat_error;
2348 return isl_stat_ok;
2351 /* Add a constraint to graph->lp that equates the value at position
2352 * "sum_pos" to the sum of the "n" values starting at "first".
2354 static isl_stat add_sum_constraint(struct isl_sched_graph *graph,
2355 int sum_pos, int first, int n)
2357 int i, k;
2358 int total;
2360 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2362 k = isl_basic_set_alloc_equality(graph->lp);
2363 if (k < 0)
2364 return isl_stat_error;
2365 isl_seq_clr(graph->lp->eq[k], 1 + total);
2366 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2367 for (i = 0; i < n; ++i)
2368 isl_int_set_si(graph->lp->eq[k][1 + first + i], 1);
2370 return isl_stat_ok;
2373 /* Add a constraint to graph->lp that equates the value at position
2374 * "sum_pos" to the sum of the parameter coefficients of all nodes.
2376 * Within each node, the coefficients have the following order:
2377 * - c_i_0
2378 * - c_i_n (if parametric)
2379 * - positive and negative parts of c_i_x
2381 static isl_stat add_param_sum_constraint(struct isl_sched_graph *graph,
2382 int sum_pos)
2384 int i, j, k;
2385 int total;
2387 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2389 k = isl_basic_set_alloc_equality(graph->lp);
2390 if (k < 0)
2391 return isl_stat_error;
2392 isl_seq_clr(graph->lp->eq[k], 1 + total);
2393 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2394 for (i = 0; i < graph->n; ++i) {
2395 int pos = 1 + graph->node[i].start + 1;
2397 for (j = 0; j < graph->node[i].nparam; ++j)
2398 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2401 return isl_stat_ok;
2404 /* Add a constraint to graph->lp that equates the value at position
2405 * "sum_pos" to the sum of the variable coefficients of all nodes.
2407 static isl_stat add_var_sum_constraint(struct isl_sched_graph *graph,
2408 int sum_pos)
2410 int i, j, k;
2411 int total;
2413 total = isl_basic_set_dim(graph->lp, isl_dim_set);
2415 k = isl_basic_set_alloc_equality(graph->lp);
2416 if (k < 0)
2417 return isl_stat_error;
2418 isl_seq_clr(graph->lp->eq[k], 1 + total);
2419 isl_int_set_si(graph->lp->eq[k][1 + sum_pos], -1);
2420 for (i = 0; i < graph->n; ++i) {
2421 struct isl_sched_node *node = &graph->node[i];
2422 int pos = 1 + node_var_coef_offset(node);
2424 for (j = 0; j < 2 * node->nvar; ++j)
2425 isl_int_set_si(graph->lp->eq[k][pos + j], 1);
2428 return isl_stat_ok;
2431 /* Construct an ILP problem for finding schedule coefficients
2432 * that result in non-negative, but small dependence distances
2433 * over all dependences.
2434 * In particular, the dependence distances over proximity edges
2435 * are bounded by m_0 + m_n n and we compute schedule coefficients
2436 * with small values (preferably zero) of m_n and m_0.
2438 * All variables of the ILP are non-negative. The actual coefficients
2439 * may be negative, so each coefficient is represented as the difference
2440 * of two non-negative variables. The negative part always appears
2441 * immediately before the positive part.
2442 * Other than that, the variables have the following order
2444 * - sum of positive and negative parts of m_n coefficients
2445 * - m_0
2446 * - sum of all c_n coefficients
2447 * (unconstrained when computing non-parametric schedules)
2448 * - sum of positive and negative parts of all c_x coefficients
2449 * - positive and negative parts of m_n coefficients
2450 * - for each node
2451 * - c_i_0
2452 * - c_i_n (if parametric)
2453 * - positive and negative parts of c_i_x, in opposite order
2455 * The constraints are those from the edges plus two or three equalities
2456 * to express the sums.
2458 * If "use_coincidence" is set, then we treat coincidence edges as local edges.
2459 * Otherwise, we ignore them.
2461 static isl_stat setup_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
2462 int use_coincidence)
2464 int i;
2465 unsigned nparam;
2466 unsigned total;
2467 isl_space *space;
2468 int parametric;
2469 int param_pos;
2470 int n_eq, n_ineq;
2472 parametric = ctx->opt->schedule_parametric;
2473 nparam = isl_space_dim(graph->node[0].space, isl_dim_param);
2474 param_pos = 4;
2475 total = param_pos + 2 * nparam;
2476 for (i = 0; i < graph->n; ++i) {
2477 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
2478 if (node_update_vmap(node) < 0)
2479 return isl_stat_error;
2480 node->start = total;
2481 total += 1 + node->nparam + 2 * node->nvar;
2484 if (count_constraints(graph, &n_eq, &n_ineq, use_coincidence) < 0)
2485 return isl_stat_error;
2486 if (count_bound_constant_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2487 return isl_stat_error;
2488 if (count_bound_coefficient_constraints(ctx, graph, &n_eq, &n_ineq) < 0)
2489 return isl_stat_error;
2491 space = isl_space_set_alloc(ctx, 0, total);
2492 isl_basic_set_free(graph->lp);
2493 n_eq += 2 + parametric;
2495 graph->lp = isl_basic_set_alloc_space(space, 0, n_eq, n_ineq);
2497 if (add_sum_constraint(graph, 0, param_pos, 2 * nparam) < 0)
2498 return isl_stat_error;
2499 if (parametric && add_param_sum_constraint(graph, 2) < 0)
2500 return isl_stat_error;
2501 if (add_var_sum_constraint(graph, 3) < 0)
2502 return isl_stat_error;
2503 if (add_bound_constant_constraints(ctx, graph) < 0)
2504 return isl_stat_error;
2505 if (add_bound_coefficient_constraints(ctx, graph) < 0)
2506 return isl_stat_error;
2507 if (add_all_validity_constraints(graph, use_coincidence) < 0)
2508 return isl_stat_error;
2509 if (add_all_proximity_constraints(graph, use_coincidence) < 0)
2510 return isl_stat_error;
2512 return isl_stat_ok;
2515 /* Analyze the conflicting constraint found by
2516 * isl_tab_basic_set_non_trivial_lexmin. If it corresponds to the validity
2517 * constraint of one of the edges between distinct nodes, living, moreover
2518 * in distinct SCCs, then record the source and sink SCC as this may
2519 * be a good place to cut between SCCs.
2521 static int check_conflict(int con, void *user)
2523 int i;
2524 struct isl_sched_graph *graph = user;
2526 if (graph->src_scc >= 0)
2527 return 0;
2529 con -= graph->lp->n_eq;
2531 if (con >= graph->lp->n_ineq)
2532 return 0;
2534 for (i = 0; i < graph->n_edge; ++i) {
2535 if (!is_validity(&graph->edge[i]))
2536 continue;
2537 if (graph->edge[i].src == graph->edge[i].dst)
2538 continue;
2539 if (graph->edge[i].src->scc == graph->edge[i].dst->scc)
2540 continue;
2541 if (graph->edge[i].start > con)
2542 continue;
2543 if (graph->edge[i].end <= con)
2544 continue;
2545 graph->src_scc = graph->edge[i].src->scc;
2546 graph->dst_scc = graph->edge[i].dst->scc;
2549 return 0;
2552 /* Check whether the next schedule row of the given node needs to be
2553 * non-trivial. Lower-dimensional domains may have some trivial rows,
2554 * but as soon as the number of remaining required non-trivial rows
2555 * is as large as the number or remaining rows to be computed,
2556 * all remaining rows need to be non-trivial.
2558 static int needs_row(struct isl_sched_graph *graph, struct isl_sched_node *node)
2560 return node->nvar - node->rank >= graph->maxvar - graph->n_row;
2563 /* Construct a non-triviality region with triviality directions
2564 * corresponding to the rows of "indep".
2565 * The rows of "indep" are expressed in terms of the schedule coefficients c_i,
2566 * while the triviality directions are expressed in terms of
2567 * pairs of non-negative variables c^+_i - c^-_i, with c^-_i appearing
2568 * before c^+_i. Furthermore,
2569 * the pairs of non-negative variables representing the coefficients
2570 * are stored in the opposite order.
2572 static __isl_give isl_mat *construct_trivial(__isl_keep isl_mat *indep)
2574 isl_ctx *ctx;
2575 isl_mat *mat;
2576 int i, j, n, n_var;
2578 if (!indep)
2579 return NULL;
2581 ctx = isl_mat_get_ctx(indep);
2582 n = isl_mat_rows(indep);
2583 n_var = isl_mat_cols(indep);
2584 mat = isl_mat_alloc(ctx, n, 2 * n_var);
2585 if (!mat)
2586 return NULL;
2587 for (i = 0; i < n; ++i) {
2588 for (j = 0; j < n_var; ++j) {
2589 int nj = n_var - 1 - j;
2590 isl_int_neg(mat->row[i][2 * nj], indep->row[i][j]);
2591 isl_int_set(mat->row[i][2 * nj + 1], indep->row[i][j]);
2595 return mat;
2598 /* Solve the ILP problem constructed in setup_lp.
2599 * For each node such that all the remaining rows of its schedule
2600 * need to be non-trivial, we construct a non-triviality region.
2601 * This region imposes that the next row is independent of previous rows.
2602 * In particular, the non-triviality region enforces that at least
2603 * one of the linear combinations in the rows of node->indep is non-zero.
2605 static __isl_give isl_vec *solve_lp(isl_ctx *ctx, struct isl_sched_graph *graph)
2607 int i;
2608 isl_vec *sol;
2609 isl_basic_set *lp;
2611 for (i = 0; i < graph->n; ++i) {
2612 struct isl_sched_node *node = &graph->node[i];
2613 isl_mat *trivial;
2615 graph->region[i].pos = node_var_coef_offset(node);
2616 if (needs_row(graph, node))
2617 trivial = construct_trivial(node->indep);
2618 else
2619 trivial = isl_mat_zero(ctx, 0, 0);
2620 graph->region[i].trivial = trivial;
2622 lp = isl_basic_set_copy(graph->lp);
2623 sol = isl_tab_basic_set_non_trivial_lexmin(lp, 2, graph->n,
2624 graph->region, &check_conflict, graph);
2625 for (i = 0; i < graph->n; ++i)
2626 isl_mat_free(graph->region[i].trivial);
2627 return sol;
2630 /* Extract the coefficients for the variables of "node" from "sol".
2632 * Each schedule coefficient c_i_x is represented as the difference
2633 * between two non-negative variables c_i_x^+ - c_i_x^-.
2634 * The c_i_x^- appear before their c_i_x^+ counterpart.
2635 * Furthermore, the order of these pairs is the opposite of that
2636 * of the corresponding coefficients.
2638 * Return c_i_x = c_i_x^+ - c_i_x^-
2640 static __isl_give isl_vec *extract_var_coef(struct isl_sched_node *node,
2641 __isl_keep isl_vec *sol)
2643 int i;
2644 int pos;
2645 isl_vec *csol;
2647 if (!sol)
2648 return NULL;
2649 csol = isl_vec_alloc(isl_vec_get_ctx(sol), node->nvar);
2650 if (!csol)
2651 return NULL;
2653 pos = 1 + node_var_coef_offset(node);
2654 for (i = 0; i < node->nvar; ++i)
2655 isl_int_sub(csol->el[node->nvar - 1 - i],
2656 sol->el[pos + 2 * i + 1], sol->el[pos + 2 * i]);
2658 return csol;
2661 /* Update the schedules of all nodes based on the given solution
2662 * of the LP problem.
2663 * The new row is added to the current band.
2664 * All possibly negative coefficients are encoded as a difference
2665 * of two non-negative variables, so we need to perform the subtraction
2666 * here.
2668 * If coincident is set, then the caller guarantees that the new
2669 * row satisfies the coincidence constraints.
2671 static int update_schedule(struct isl_sched_graph *graph,
2672 __isl_take isl_vec *sol, int coincident)
2674 int i, j;
2675 isl_vec *csol = NULL;
2677 if (!sol)
2678 goto error;
2679 if (sol->size == 0)
2680 isl_die(sol->ctx, isl_error_internal,
2681 "no solution found", goto error);
2682 if (graph->n_total_row >= graph->max_row)
2683 isl_die(sol->ctx, isl_error_internal,
2684 "too many schedule rows", goto error);
2686 for (i = 0; i < graph->n; ++i) {
2687 struct isl_sched_node *node = &graph->node[i];
2688 int pos = node->start;
2689 int row = isl_mat_rows(node->sched);
2691 isl_vec_free(csol);
2692 csol = extract_var_coef(node, sol);
2693 if (!csol)
2694 goto error;
2696 isl_map_free(node->sched_map);
2697 node->sched_map = NULL;
2698 node->sched = isl_mat_add_rows(node->sched, 1);
2699 if (!node->sched)
2700 goto error;
2701 for (j = 0; j < 1 + node->nparam; ++j)
2702 node->sched = isl_mat_set_element(node->sched,
2703 row, j, sol->el[1 + pos + j]);
2704 for (j = 0; j < node->nvar; ++j)
2705 node->sched = isl_mat_set_element(node->sched,
2706 row, 1 + node->nparam + j, csol->el[j]);
2707 node->coincident[graph->n_total_row] = coincident;
2709 isl_vec_free(sol);
2710 isl_vec_free(csol);
2712 graph->n_row++;
2713 graph->n_total_row++;
2715 return 0;
2716 error:
2717 isl_vec_free(sol);
2718 isl_vec_free(csol);
2719 return -1;
2722 /* Convert row "row" of node->sched into an isl_aff living in "ls"
2723 * and return this isl_aff.
2725 static __isl_give isl_aff *extract_schedule_row(__isl_take isl_local_space *ls,
2726 struct isl_sched_node *node, int row)
2728 int j;
2729 isl_int v;
2730 isl_aff *aff;
2732 isl_int_init(v);
2734 aff = isl_aff_zero_on_domain(ls);
2735 isl_mat_get_element(node->sched, row, 0, &v);
2736 aff = isl_aff_set_constant(aff, v);
2737 for (j = 0; j < node->nparam; ++j) {
2738 isl_mat_get_element(node->sched, row, 1 + j, &v);
2739 aff = isl_aff_set_coefficient(aff, isl_dim_param, j, v);
2741 for (j = 0; j < node->nvar; ++j) {
2742 isl_mat_get_element(node->sched, row, 1 + node->nparam + j, &v);
2743 aff = isl_aff_set_coefficient(aff, isl_dim_in, j, v);
2746 isl_int_clear(v);
2748 return aff;
2751 /* Convert the "n" rows starting at "first" of node->sched into a multi_aff
2752 * and return this multi_aff.
2754 * The result is defined over the uncompressed node domain.
2756 static __isl_give isl_multi_aff *node_extract_partial_schedule_multi_aff(
2757 struct isl_sched_node *node, int first, int n)
2759 int i;
2760 isl_space *space;
2761 isl_local_space *ls;
2762 isl_aff *aff;
2763 isl_multi_aff *ma;
2764 int nrow;
2766 if (!node)
2767 return NULL;
2768 nrow = isl_mat_rows(node->sched);
2769 if (node->compressed)
2770 space = isl_multi_aff_get_domain_space(node->decompress);
2771 else
2772 space = isl_space_copy(node->space);
2773 ls = isl_local_space_from_space(isl_space_copy(space));
2774 space = isl_space_from_domain(space);
2775 space = isl_space_add_dims(space, isl_dim_out, n);
2776 ma = isl_multi_aff_zero(space);
2778 for (i = first; i < first + n; ++i) {
2779 aff = extract_schedule_row(isl_local_space_copy(ls), node, i);
2780 ma = isl_multi_aff_set_aff(ma, i - first, aff);
2783 isl_local_space_free(ls);
2785 if (node->compressed)
2786 ma = isl_multi_aff_pullback_multi_aff(ma,
2787 isl_multi_aff_copy(node->compress));
2789 return ma;
2792 /* Convert node->sched into a multi_aff and return this multi_aff.
2794 * The result is defined over the uncompressed node domain.
2796 static __isl_give isl_multi_aff *node_extract_schedule_multi_aff(
2797 struct isl_sched_node *node)
2799 int nrow;
2801 nrow = isl_mat_rows(node->sched);
2802 return node_extract_partial_schedule_multi_aff(node, 0, nrow);
2805 /* Convert node->sched into a map and return this map.
2807 * The result is cached in node->sched_map, which needs to be released
2808 * whenever node->sched is updated.
2809 * It is defined over the uncompressed node domain.
2811 static __isl_give isl_map *node_extract_schedule(struct isl_sched_node *node)
2813 if (!node->sched_map) {
2814 isl_multi_aff *ma;
2816 ma = node_extract_schedule_multi_aff(node);
2817 node->sched_map = isl_map_from_multi_aff(ma);
2820 return isl_map_copy(node->sched_map);
2823 /* Construct a map that can be used to update a dependence relation
2824 * based on the current schedule.
2825 * That is, construct a map expressing that source and sink
2826 * are executed within the same iteration of the current schedule.
2827 * This map can then be intersected with the dependence relation.
2828 * This is not the most efficient way, but this shouldn't be a critical
2829 * operation.
2831 static __isl_give isl_map *specializer(struct isl_sched_node *src,
2832 struct isl_sched_node *dst)
2834 isl_map *src_sched, *dst_sched;
2836 src_sched = node_extract_schedule(src);
2837 dst_sched = node_extract_schedule(dst);
2838 return isl_map_apply_range(src_sched, isl_map_reverse(dst_sched));
2841 /* Intersect the domains of the nested relations in domain and range
2842 * of "umap" with "map".
2844 static __isl_give isl_union_map *intersect_domains(
2845 __isl_take isl_union_map *umap, __isl_keep isl_map *map)
2847 isl_union_set *uset;
2849 umap = isl_union_map_zip(umap);
2850 uset = isl_union_set_from_set(isl_map_wrap(isl_map_copy(map)));
2851 umap = isl_union_map_intersect_domain(umap, uset);
2852 umap = isl_union_map_zip(umap);
2853 return umap;
2856 /* Update the dependence relation of the given edge based
2857 * on the current schedule.
2858 * If the dependence is carried completely by the current schedule, then
2859 * it is removed from the edge_tables. It is kept in the list of edges
2860 * as otherwise all edge_tables would have to be recomputed.
2862 static int update_edge(struct isl_sched_graph *graph,
2863 struct isl_sched_edge *edge)
2865 int empty;
2866 isl_map *id;
2868 id = specializer(edge->src, edge->dst);
2869 edge->map = isl_map_intersect(edge->map, isl_map_copy(id));
2870 if (!edge->map)
2871 goto error;
2873 if (edge->tagged_condition) {
2874 edge->tagged_condition =
2875 intersect_domains(edge->tagged_condition, id);
2876 if (!edge->tagged_condition)
2877 goto error;
2879 if (edge->tagged_validity) {
2880 edge->tagged_validity =
2881 intersect_domains(edge->tagged_validity, id);
2882 if (!edge->tagged_validity)
2883 goto error;
2886 empty = isl_map_plain_is_empty(edge->map);
2887 if (empty < 0)
2888 goto error;
2889 if (empty)
2890 graph_remove_edge(graph, edge);
2892 isl_map_free(id);
2893 return 0;
2894 error:
2895 isl_map_free(id);
2896 return -1;
2899 /* Does the domain of "umap" intersect "uset"?
2901 static int domain_intersects(__isl_keep isl_union_map *umap,
2902 __isl_keep isl_union_set *uset)
2904 int empty;
2906 umap = isl_union_map_copy(umap);
2907 umap = isl_union_map_intersect_domain(umap, isl_union_set_copy(uset));
2908 empty = isl_union_map_is_empty(umap);
2909 isl_union_map_free(umap);
2911 return empty < 0 ? -1 : !empty;
2914 /* Does the range of "umap" intersect "uset"?
2916 static int range_intersects(__isl_keep isl_union_map *umap,
2917 __isl_keep isl_union_set *uset)
2919 int empty;
2921 umap = isl_union_map_copy(umap);
2922 umap = isl_union_map_intersect_range(umap, isl_union_set_copy(uset));
2923 empty = isl_union_map_is_empty(umap);
2924 isl_union_map_free(umap);
2926 return empty < 0 ? -1 : !empty;
2929 /* Are the condition dependences of "edge" local with respect to
2930 * the current schedule?
2932 * That is, are domain and range of the condition dependences mapped
2933 * to the same point?
2935 * In other words, is the condition false?
2937 static int is_condition_false(struct isl_sched_edge *edge)
2939 isl_union_map *umap;
2940 isl_map *map, *sched, *test;
2941 int empty, local;
2943 empty = isl_union_map_is_empty(edge->tagged_condition);
2944 if (empty < 0 || empty)
2945 return empty;
2947 umap = isl_union_map_copy(edge->tagged_condition);
2948 umap = isl_union_map_zip(umap);
2949 umap = isl_union_set_unwrap(isl_union_map_domain(umap));
2950 map = isl_map_from_union_map(umap);
2952 sched = node_extract_schedule(edge->src);
2953 map = isl_map_apply_domain(map, sched);
2954 sched = node_extract_schedule(edge->dst);
2955 map = isl_map_apply_range(map, sched);
2957 test = isl_map_identity(isl_map_get_space(map));
2958 local = isl_map_is_subset(map, test);
2959 isl_map_free(map);
2960 isl_map_free(test);
2962 return local;
2965 /* For each conditional validity constraint that is adjacent
2966 * to a condition with domain in condition_source or range in condition_sink,
2967 * turn it into an unconditional validity constraint.
2969 static int unconditionalize_adjacent_validity(struct isl_sched_graph *graph,
2970 __isl_take isl_union_set *condition_source,
2971 __isl_take isl_union_set *condition_sink)
2973 int i;
2975 condition_source = isl_union_set_coalesce(condition_source);
2976 condition_sink = isl_union_set_coalesce(condition_sink);
2978 for (i = 0; i < graph->n_edge; ++i) {
2979 int adjacent;
2980 isl_union_map *validity;
2982 if (!is_conditional_validity(&graph->edge[i]))
2983 continue;
2984 if (is_validity(&graph->edge[i]))
2985 continue;
2987 validity = graph->edge[i].tagged_validity;
2988 adjacent = domain_intersects(validity, condition_sink);
2989 if (adjacent >= 0 && !adjacent)
2990 adjacent = range_intersects(validity, condition_source);
2991 if (adjacent < 0)
2992 goto error;
2993 if (!adjacent)
2994 continue;
2996 set_validity(&graph->edge[i]);
2999 isl_union_set_free(condition_source);
3000 isl_union_set_free(condition_sink);
3001 return 0;
3002 error:
3003 isl_union_set_free(condition_source);
3004 isl_union_set_free(condition_sink);
3005 return -1;
3008 /* Update the dependence relations of all edges based on the current schedule
3009 * and enforce conditional validity constraints that are adjacent
3010 * to satisfied condition constraints.
3012 * First check if any of the condition constraints are satisfied
3013 * (i.e., not local to the outer schedule) and keep track of
3014 * their domain and range.
3015 * Then update all dependence relations (which removes the non-local
3016 * constraints).
3017 * Finally, if any condition constraints turned out to be satisfied,
3018 * then turn all adjacent conditional validity constraints into
3019 * unconditional validity constraints.
3021 static int update_edges(isl_ctx *ctx, struct isl_sched_graph *graph)
3023 int i;
3024 int any = 0;
3025 isl_union_set *source, *sink;
3027 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3028 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
3029 for (i = 0; i < graph->n_edge; ++i) {
3030 int local;
3031 isl_union_set *uset;
3032 isl_union_map *umap;
3034 if (!is_condition(&graph->edge[i]))
3035 continue;
3036 if (is_local(&graph->edge[i]))
3037 continue;
3038 local = is_condition_false(&graph->edge[i]);
3039 if (local < 0)
3040 goto error;
3041 if (local)
3042 continue;
3044 any = 1;
3046 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3047 uset = isl_union_map_domain(umap);
3048 source = isl_union_set_union(source, uset);
3050 umap = isl_union_map_copy(graph->edge[i].tagged_condition);
3051 uset = isl_union_map_range(umap);
3052 sink = isl_union_set_union(sink, uset);
3055 for (i = graph->n_edge - 1; i >= 0; --i) {
3056 if (update_edge(graph, &graph->edge[i]) < 0)
3057 goto error;
3060 if (any)
3061 return unconditionalize_adjacent_validity(graph, source, sink);
3063 isl_union_set_free(source);
3064 isl_union_set_free(sink);
3065 return 0;
3066 error:
3067 isl_union_set_free(source);
3068 isl_union_set_free(sink);
3069 return -1;
3072 static void next_band(struct isl_sched_graph *graph)
3074 graph->band_start = graph->n_total_row;
3077 /* Return the union of the universe domains of the nodes in "graph"
3078 * that satisfy "pred".
3080 static __isl_give isl_union_set *isl_sched_graph_domain(isl_ctx *ctx,
3081 struct isl_sched_graph *graph,
3082 int (*pred)(struct isl_sched_node *node, int data), int data)
3084 int i;
3085 isl_set *set;
3086 isl_union_set *dom;
3088 for (i = 0; i < graph->n; ++i)
3089 if (pred(&graph->node[i], data))
3090 break;
3092 if (i >= graph->n)
3093 isl_die(ctx, isl_error_internal,
3094 "empty component", return NULL);
3096 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3097 dom = isl_union_set_from_set(set);
3099 for (i = i + 1; i < graph->n; ++i) {
3100 if (!pred(&graph->node[i], data))
3101 continue;
3102 set = isl_set_universe(isl_space_copy(graph->node[i].space));
3103 dom = isl_union_set_union(dom, isl_union_set_from_set(set));
3106 return dom;
3109 /* Return a list of unions of universe domains, where each element
3110 * in the list corresponds to an SCC (or WCC) indexed by node->scc.
3112 static __isl_give isl_union_set_list *extract_sccs(isl_ctx *ctx,
3113 struct isl_sched_graph *graph)
3115 int i;
3116 isl_union_set_list *filters;
3118 filters = isl_union_set_list_alloc(ctx, graph->scc);
3119 for (i = 0; i < graph->scc; ++i) {
3120 isl_union_set *dom;
3122 dom = isl_sched_graph_domain(ctx, graph, &node_scc_exactly, i);
3123 filters = isl_union_set_list_add(filters, dom);
3126 return filters;
3129 /* Return a list of two unions of universe domains, one for the SCCs up
3130 * to and including graph->src_scc and another for the other SCCs.
3132 static __isl_give isl_union_set_list *extract_split(isl_ctx *ctx,
3133 struct isl_sched_graph *graph)
3135 isl_union_set *dom;
3136 isl_union_set_list *filters;
3138 filters = isl_union_set_list_alloc(ctx, 2);
3139 dom = isl_sched_graph_domain(ctx, graph,
3140 &node_scc_at_most, graph->src_scc);
3141 filters = isl_union_set_list_add(filters, dom);
3142 dom = isl_sched_graph_domain(ctx, graph,
3143 &node_scc_at_least, graph->src_scc + 1);
3144 filters = isl_union_set_list_add(filters, dom);
3146 return filters;
3149 /* Copy nodes that satisfy node_pred from the src dependence graph
3150 * to the dst dependence graph.
3152 static int copy_nodes(struct isl_sched_graph *dst, struct isl_sched_graph *src,
3153 int (*node_pred)(struct isl_sched_node *node, int data), int data)
3155 int i;
3157 dst->n = 0;
3158 for (i = 0; i < src->n; ++i) {
3159 int j;
3161 if (!node_pred(&src->node[i], data))
3162 continue;
3164 j = dst->n;
3165 dst->node[j].space = isl_space_copy(src->node[i].space);
3166 dst->node[j].compressed = src->node[i].compressed;
3167 dst->node[j].hull = isl_set_copy(src->node[i].hull);
3168 dst->node[j].compress =
3169 isl_multi_aff_copy(src->node[i].compress);
3170 dst->node[j].decompress =
3171 isl_multi_aff_copy(src->node[i].decompress);
3172 dst->node[j].nvar = src->node[i].nvar;
3173 dst->node[j].nparam = src->node[i].nparam;
3174 dst->node[j].sched = isl_mat_copy(src->node[i].sched);
3175 dst->node[j].sched_map = isl_map_copy(src->node[i].sched_map);
3176 dst->node[j].coincident = src->node[i].coincident;
3177 dst->node[j].sizes = isl_multi_val_copy(src->node[i].sizes);
3178 dst->node[j].max = isl_vec_copy(src->node[i].max);
3179 dst->n++;
3181 if (!dst->node[j].space || !dst->node[j].sched)
3182 return -1;
3183 if (dst->node[j].compressed &&
3184 (!dst->node[j].hull || !dst->node[j].compress ||
3185 !dst->node[j].decompress))
3186 return -1;
3189 return 0;
3192 /* Copy non-empty edges that satisfy edge_pred from the src dependence graph
3193 * to the dst dependence graph.
3194 * If the source or destination node of the edge is not in the destination
3195 * graph, then it must be a backward proximity edge and it should simply
3196 * be ignored.
3198 static int copy_edges(isl_ctx *ctx, struct isl_sched_graph *dst,
3199 struct isl_sched_graph *src,
3200 int (*edge_pred)(struct isl_sched_edge *edge, int data), int data)
3202 int i;
3203 enum isl_edge_type t;
3205 dst->n_edge = 0;
3206 for (i = 0; i < src->n_edge; ++i) {
3207 struct isl_sched_edge *edge = &src->edge[i];
3208 isl_map *map;
3209 isl_union_map *tagged_condition;
3210 isl_union_map *tagged_validity;
3211 struct isl_sched_node *dst_src, *dst_dst;
3213 if (!edge_pred(edge, data))
3214 continue;
3216 if (isl_map_plain_is_empty(edge->map))
3217 continue;
3219 dst_src = graph_find_node(ctx, dst, edge->src->space);
3220 dst_dst = graph_find_node(ctx, dst, edge->dst->space);
3221 if (!dst_src || !dst_dst) {
3222 if (is_validity(edge) || is_conditional_validity(edge))
3223 isl_die(ctx, isl_error_internal,
3224 "backward (conditional) validity edge",
3225 return -1);
3226 continue;
3229 map = isl_map_copy(edge->map);
3230 tagged_condition = isl_union_map_copy(edge->tagged_condition);
3231 tagged_validity = isl_union_map_copy(edge->tagged_validity);
3233 dst->edge[dst->n_edge].src = dst_src;
3234 dst->edge[dst->n_edge].dst = dst_dst;
3235 dst->edge[dst->n_edge].map = map;
3236 dst->edge[dst->n_edge].tagged_condition = tagged_condition;
3237 dst->edge[dst->n_edge].tagged_validity = tagged_validity;
3238 dst->edge[dst->n_edge].types = edge->types;
3239 dst->n_edge++;
3241 if (edge->tagged_condition && !tagged_condition)
3242 return -1;
3243 if (edge->tagged_validity && !tagged_validity)
3244 return -1;
3246 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
3247 if (edge !=
3248 graph_find_edge(src, t, edge->src, edge->dst))
3249 continue;
3250 if (graph_edge_table_add(ctx, dst, t,
3251 &dst->edge[dst->n_edge - 1]) < 0)
3252 return -1;
3256 return 0;
3259 /* Compute the maximal number of variables over all nodes.
3260 * This is the maximal number of linearly independent schedule
3261 * rows that we need to compute.
3262 * Just in case we end up in a part of the dependence graph
3263 * with only lower-dimensional domains, we make sure we will
3264 * compute the required amount of extra linearly independent rows.
3266 static int compute_maxvar(struct isl_sched_graph *graph)
3268 int i;
3270 graph->maxvar = 0;
3271 for (i = 0; i < graph->n; ++i) {
3272 struct isl_sched_node *node = &graph->node[i];
3273 int nvar;
3275 if (node_update_vmap(node) < 0)
3276 return -1;
3277 nvar = node->nvar + graph->n_row - node->rank;
3278 if (nvar > graph->maxvar)
3279 graph->maxvar = nvar;
3282 return 0;
3285 /* Extract the subgraph of "graph" that consists of the node satisfying
3286 * "node_pred" and the edges satisfying "edge_pred" and store
3287 * the result in "sub".
3289 static int extract_sub_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
3290 int (*node_pred)(struct isl_sched_node *node, int data),
3291 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3292 int data, struct isl_sched_graph *sub)
3294 int i, n = 0, n_edge = 0;
3295 int t;
3297 for (i = 0; i < graph->n; ++i)
3298 if (node_pred(&graph->node[i], data))
3299 ++n;
3300 for (i = 0; i < graph->n_edge; ++i)
3301 if (edge_pred(&graph->edge[i], data))
3302 ++n_edge;
3303 if (graph_alloc(ctx, sub, n, n_edge) < 0)
3304 return -1;
3305 if (copy_nodes(sub, graph, node_pred, data) < 0)
3306 return -1;
3307 if (graph_init_table(ctx, sub) < 0)
3308 return -1;
3309 for (t = 0; t <= isl_edge_last; ++t)
3310 sub->max_edge[t] = graph->max_edge[t];
3311 if (graph_init_edge_tables(ctx, sub) < 0)
3312 return -1;
3313 if (copy_edges(ctx, sub, graph, edge_pred, data) < 0)
3314 return -1;
3315 sub->n_row = graph->n_row;
3316 sub->max_row = graph->max_row;
3317 sub->n_total_row = graph->n_total_row;
3318 sub->band_start = graph->band_start;
3320 return 0;
3323 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
3324 struct isl_sched_graph *graph);
3325 static __isl_give isl_schedule_node *compute_schedule_wcc(
3326 isl_schedule_node *node, struct isl_sched_graph *graph);
3328 /* Compute a schedule for a subgraph of "graph". In particular, for
3329 * the graph composed of nodes that satisfy node_pred and edges that
3330 * that satisfy edge_pred.
3331 * If the subgraph is known to consist of a single component, then wcc should
3332 * be set and then we call compute_schedule_wcc on the constructed subgraph.
3333 * Otherwise, we call compute_schedule, which will check whether the subgraph
3334 * is connected.
3336 * The schedule is inserted at "node" and the updated schedule node
3337 * is returned.
3339 static __isl_give isl_schedule_node *compute_sub_schedule(
3340 __isl_take isl_schedule_node *node, isl_ctx *ctx,
3341 struct isl_sched_graph *graph,
3342 int (*node_pred)(struct isl_sched_node *node, int data),
3343 int (*edge_pred)(struct isl_sched_edge *edge, int data),
3344 int data, int wcc)
3346 struct isl_sched_graph split = { 0 };
3348 if (extract_sub_graph(ctx, graph, node_pred, edge_pred, data,
3349 &split) < 0)
3350 goto error;
3352 if (wcc)
3353 node = compute_schedule_wcc(node, &split);
3354 else
3355 node = compute_schedule(node, &split);
3357 graph_free(ctx, &split);
3358 return node;
3359 error:
3360 graph_free(ctx, &split);
3361 return isl_schedule_node_free(node);
3364 static int edge_scc_exactly(struct isl_sched_edge *edge, int scc)
3366 return edge->src->scc == scc && edge->dst->scc == scc;
3369 static int edge_dst_scc_at_most(struct isl_sched_edge *edge, int scc)
3371 return edge->dst->scc <= scc;
3374 static int edge_src_scc_at_least(struct isl_sched_edge *edge, int scc)
3376 return edge->src->scc >= scc;
3379 /* Reset the current band by dropping all its schedule rows.
3381 static int reset_band(struct isl_sched_graph *graph)
3383 int i;
3384 int drop;
3386 drop = graph->n_total_row - graph->band_start;
3387 graph->n_total_row -= drop;
3388 graph->n_row -= drop;
3390 for (i = 0; i < graph->n; ++i) {
3391 struct isl_sched_node *node = &graph->node[i];
3393 isl_map_free(node->sched_map);
3394 node->sched_map = NULL;
3396 node->sched = isl_mat_drop_rows(node->sched,
3397 graph->band_start, drop);
3399 if (!node->sched)
3400 return -1;
3403 return 0;
3406 /* Split the current graph into two parts and compute a schedule for each
3407 * part individually. In particular, one part consists of all SCCs up
3408 * to and including graph->src_scc, while the other part contains the other
3409 * SCCs. The split is enforced by a sequence node inserted at position "node"
3410 * in the schedule tree. Return the updated schedule node.
3411 * If either of these two parts consists of a sequence, then it is spliced
3412 * into the sequence containing the two parts.
3414 * The current band is reset. It would be possible to reuse
3415 * the previously computed rows as the first rows in the next
3416 * band, but recomputing them may result in better rows as we are looking
3417 * at a smaller part of the dependence graph.
3419 static __isl_give isl_schedule_node *compute_split_schedule(
3420 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3422 int is_seq;
3423 isl_ctx *ctx;
3424 isl_union_set_list *filters;
3426 if (!node)
3427 return NULL;
3429 if (reset_band(graph) < 0)
3430 return isl_schedule_node_free(node);
3432 next_band(graph);
3434 ctx = isl_schedule_node_get_ctx(node);
3435 filters = extract_split(ctx, graph);
3436 node = isl_schedule_node_insert_sequence(node, filters);
3437 node = isl_schedule_node_child(node, 1);
3438 node = isl_schedule_node_child(node, 0);
3440 node = compute_sub_schedule(node, ctx, graph,
3441 &node_scc_at_least, &edge_src_scc_at_least,
3442 graph->src_scc + 1, 0);
3443 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3444 node = isl_schedule_node_parent(node);
3445 node = isl_schedule_node_parent(node);
3446 if (is_seq)
3447 node = isl_schedule_node_sequence_splice_child(node, 1);
3448 node = isl_schedule_node_child(node, 0);
3449 node = isl_schedule_node_child(node, 0);
3450 node = compute_sub_schedule(node, ctx, graph,
3451 &node_scc_at_most, &edge_dst_scc_at_most,
3452 graph->src_scc, 0);
3453 is_seq = isl_schedule_node_get_type(node) == isl_schedule_node_sequence;
3454 node = isl_schedule_node_parent(node);
3455 node = isl_schedule_node_parent(node);
3456 if (is_seq)
3457 node = isl_schedule_node_sequence_splice_child(node, 0);
3459 return node;
3462 /* Insert a band node at position "node" in the schedule tree corresponding
3463 * to the current band in "graph". Mark the band node permutable
3464 * if "permutable" is set.
3465 * The partial schedules and the coincidence property are extracted
3466 * from the graph nodes.
3467 * Return the updated schedule node.
3469 static __isl_give isl_schedule_node *insert_current_band(
3470 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3471 int permutable)
3473 int i;
3474 int start, end, n;
3475 isl_multi_aff *ma;
3476 isl_multi_pw_aff *mpa;
3477 isl_multi_union_pw_aff *mupa;
3479 if (!node)
3480 return NULL;
3482 if (graph->n < 1)
3483 isl_die(isl_schedule_node_get_ctx(node), isl_error_internal,
3484 "graph should have at least one node",
3485 return isl_schedule_node_free(node));
3487 start = graph->band_start;
3488 end = graph->n_total_row;
3489 n = end - start;
3491 ma = node_extract_partial_schedule_multi_aff(&graph->node[0], start, n);
3492 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3493 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3495 for (i = 1; i < graph->n; ++i) {
3496 isl_multi_union_pw_aff *mupa_i;
3498 ma = node_extract_partial_schedule_multi_aff(&graph->node[i],
3499 start, n);
3500 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3501 mupa_i = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3502 mupa = isl_multi_union_pw_aff_union_add(mupa, mupa_i);
3504 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3506 for (i = 0; i < n; ++i)
3507 node = isl_schedule_node_band_member_set_coincident(node, i,
3508 graph->node[0].coincident[start + i]);
3509 node = isl_schedule_node_band_set_permutable(node, permutable);
3511 return node;
3514 /* Update the dependence relations based on the current schedule,
3515 * add the current band to "node" and then continue with the computation
3516 * of the next band.
3517 * Return the updated schedule node.
3519 static __isl_give isl_schedule_node *compute_next_band(
3520 __isl_take isl_schedule_node *node,
3521 struct isl_sched_graph *graph, int permutable)
3523 isl_ctx *ctx;
3525 if (!node)
3526 return NULL;
3528 ctx = isl_schedule_node_get_ctx(node);
3529 if (update_edges(ctx, graph) < 0)
3530 return isl_schedule_node_free(node);
3531 node = insert_current_band(node, graph, permutable);
3532 next_band(graph);
3534 node = isl_schedule_node_child(node, 0);
3535 node = compute_schedule(node, graph);
3536 node = isl_schedule_node_parent(node);
3538 return node;
3541 /* Add the constraints "coef" derived from an edge from "node" to itself
3542 * to graph->lp in order to respect the dependences and to try and carry them.
3543 * "pos" is the sequence number of the edge that needs to be carried.
3544 * "coef" represents general constraints on coefficients (c_0, c_n, c_x)
3545 * of valid constraints for (y - x) with x and y instances of the node.
3547 * The constraints added to graph->lp need to enforce
3549 * (c_j_0 + c_j_n n + c_j_x y) - (c_j_0 + c_j_n n + c_j_x x)
3550 * = c_j_x (y - x) >= e_i
3552 * for each (x,y) in the dependence relation of the edge.
3553 * That is, (-e_i, 0, c_j_x) needs to be plugged in for (c_0, c_n, c_x),
3554 * taking into account that each coefficient in c_j_x is represented
3555 * as a pair of non-negative coefficients.
3557 static isl_stat add_intra_constraints(struct isl_sched_graph *graph,
3558 struct isl_sched_node *node, __isl_take isl_basic_set *coef, int pos)
3560 int offset;
3561 isl_ctx *ctx;
3562 isl_dim_map *dim_map;
3564 if (!coef)
3565 return isl_stat_error;
3567 ctx = isl_basic_set_get_ctx(coef);
3568 offset = coef_var_offset(coef);
3569 dim_map = intra_dim_map(ctx, graph, node, offset, 1);
3570 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3571 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3573 return isl_stat_ok;
3576 /* Add the constraints "coef" derived from an edge from "src" to "dst"
3577 * to graph->lp in order to respect the dependences and to try and carry them.
3578 * "pos" is the sequence number of the edge that needs to be carried.
3579 * "coef" represents general constraints on coefficients (c_0, c_n, c_x, c_y)
3580 * of valid constraints for (x, y) with x and y instances of "src" and "dst".
3582 * The constraints added to graph->lp need to enforce
3584 * (c_k_0 + c_k_n n + c_k_x y) - (c_j_0 + c_j_n n + c_j_x x) >= e_i
3586 * for each (x,y) in the dependence relation of the edge.
3587 * That is,
3588 * (-e_i + c_k_0 - c_j_0, c_k_n - c_j_n, -c_j_x, c_k_x)
3589 * needs to be plugged in for (c_0, c_n, c_x, c_y),
3590 * taking into account that each coefficient in c_j_x and c_k_x is represented
3591 * as a pair of non-negative coefficients.
3593 static isl_stat add_inter_constraints(struct isl_sched_graph *graph,
3594 struct isl_sched_node *src, struct isl_sched_node *dst,
3595 __isl_take isl_basic_set *coef, int pos)
3597 int offset;
3598 isl_ctx *ctx;
3599 isl_dim_map *dim_map;
3601 if (!coef)
3602 return isl_stat_error;
3604 ctx = isl_basic_set_get_ctx(coef);
3605 offset = coef_var_offset(coef);
3606 dim_map = inter_dim_map(ctx, graph, src, dst, offset, 1);
3607 isl_dim_map_range(dim_map, 3 + pos, 0, 0, 0, 1, -1);
3608 graph->lp = add_constraints_dim_map(graph->lp, coef, dim_map);
3610 return isl_stat_ok;
3613 /* Data structure collecting information used during the construction
3614 * of an LP for carrying dependences.
3616 * "intra" is a sequence of coefficient constraints for intra-node edges.
3617 * "inter" is a sequence of coefficient constraints for inter-node edges.
3619 struct isl_carry {
3620 isl_basic_set_list *intra;
3621 isl_basic_set_list *inter;
3624 /* Free all the data stored in "carry".
3626 static void isl_carry_clear(struct isl_carry *carry)
3628 isl_basic_set_list_free(carry->intra);
3629 isl_basic_set_list_free(carry->inter);
3632 /* Return a pointer to the node in "graph" that lives in "space".
3633 * If the requested node has been compressed, then "space"
3634 * corresponds to the compressed space.
3636 * First try and see if "space" is the space of an uncompressed node.
3637 * If so, return that node.
3638 * Otherwise, "space" was constructed by construct_compressed_id and
3639 * contains a user pointer pointing to the node in the tuple id.
3641 static struct isl_sched_node *graph_find_compressed_node(isl_ctx *ctx,
3642 struct isl_sched_graph *graph, __isl_keep isl_space *space)
3644 isl_id *id;
3645 struct isl_sched_node *node;
3647 if (!space)
3648 return NULL;
3650 node = graph_find_node(ctx, graph, space);
3651 if (node)
3652 return node;
3654 id = isl_space_get_tuple_id(space, isl_dim_set);
3655 node = isl_id_get_user(id);
3656 isl_id_free(id);
3658 if (!node)
3659 return NULL;
3661 if (!(node >= &graph->node[0] && node < &graph->node[graph->n]))
3662 isl_die(ctx, isl_error_internal,
3663 "space points to invalid node", return NULL);
3665 return node;
3668 /* Internal data structure for add_all_constraints.
3670 * "graph" is the schedule constraint graph for which an LP problem
3671 * is being constructed.
3672 * "pos" is the position of the next edge that needs to be carried.
3674 struct isl_add_all_constraints_data {
3675 isl_ctx *ctx;
3676 struct isl_sched_graph *graph;
3677 int pos;
3680 /* Add the constraints "coef" derived from an edge from a node to itself
3681 * to data->graph->lp in order to respect the dependences and
3682 * to try and carry them.
3684 * The space of "coef" is of the form
3686 * coefficients[[c_cst, c_n] -> S[c_x]]
3688 * with S[c_x] the (compressed) space of the node.
3689 * Extract the node from the space and call add_intra_constraints.
3691 static isl_stat lp_add_intra(__isl_take isl_basic_set *coef, void *user)
3693 struct isl_add_all_constraints_data *data = user;
3694 isl_space *space;
3695 struct isl_sched_node *node;
3697 space = isl_basic_set_get_space(coef);
3698 space = isl_space_range(isl_space_unwrap(space));
3699 node = graph_find_compressed_node(data->ctx, data->graph, space);
3700 isl_space_free(space);
3701 return add_intra_constraints(data->graph, node, coef, data->pos++);
3704 /* Add the constraints "coef" derived from an edge from a node j
3705 * to a node k to data->graph->lp in order to respect the dependences and
3706 * to try and carry them.
3708 * The space of "coef" is of the form
3710 * coefficients[[c_cst, c_n] -> [S_j[c_x] -> S_k[c_y]]]
3712 * with S_j[c_x] and S_k[c_y] the (compressed) spaces of the nodes.
3713 * Extract the nodes from the space and call add_inter_constraints.
3715 static isl_stat lp_add_inter(__isl_take isl_basic_set *coef, void *user)
3717 struct isl_add_all_constraints_data *data = user;
3718 isl_space *space, *dom;
3719 struct isl_sched_node *src, *dst;
3721 space = isl_basic_set_get_space(coef);
3722 space = isl_space_unwrap(isl_space_range(isl_space_unwrap(space)));
3723 dom = isl_space_domain(isl_space_copy(space));
3724 src = graph_find_compressed_node(data->ctx, data->graph, dom);
3725 isl_space_free(dom);
3726 space = isl_space_range(space);
3727 dst = graph_find_compressed_node(data->ctx, data->graph, space);
3728 isl_space_free(space);
3730 return add_inter_constraints(data->graph, src, dst, coef, data->pos++);
3733 /* Add constraints to graph->lp that force all (conditional) validity
3734 * dependences to be respected and attempt to carry them.
3735 * "intra" is the sequence of coefficient constraints for intra-node edges.
3736 * "inter" is the sequence of coefficient constraints for inter-node edges.
3738 static isl_stat add_all_constraints(isl_ctx *ctx, struct isl_sched_graph *graph,
3739 __isl_keep isl_basic_set_list *intra,
3740 __isl_keep isl_basic_set_list *inter)
3742 struct isl_add_all_constraints_data data = { ctx, graph };
3744 data.pos = 0;
3745 if (isl_basic_set_list_foreach(intra, &lp_add_intra, &data) < 0)
3746 return isl_stat_error;
3747 if (isl_basic_set_list_foreach(inter, &lp_add_inter, &data) < 0)
3748 return isl_stat_error;
3749 return isl_stat_ok;
3752 /* Internal data structure for count_all_constraints
3753 * for keeping track of the number of equality and inequality constraints.
3755 struct isl_sched_count {
3756 int n_eq;
3757 int n_ineq;
3760 /* Add the number of equality and inequality constraints of "bset"
3761 * to data->n_eq and data->n_ineq.
3763 static isl_stat bset_update_count(__isl_take isl_basic_set *bset, void *user)
3765 struct isl_sched_count *data = user;
3767 data->n_eq += isl_basic_set_n_equality(bset);
3768 data->n_ineq += isl_basic_set_n_inequality(bset);
3769 isl_basic_set_free(bset);
3771 return isl_stat_ok;
3774 /* Count the number of equality and inequality constraints
3775 * that will be added to the carry_lp problem.
3776 * We count each edge exactly once.
3777 * "intra" is the sequence of coefficient constraints for intra-node edges.
3778 * "inter" is the sequence of coefficient constraints for inter-node edges.
3780 static isl_stat count_all_constraints(__isl_keep isl_basic_set_list *intra,
3781 __isl_keep isl_basic_set_list *inter, int *n_eq, int *n_ineq)
3783 struct isl_sched_count data;
3785 data.n_eq = data.n_ineq = 0;
3786 if (isl_basic_set_list_foreach(inter, &bset_update_count, &data) < 0)
3787 return isl_stat_error;
3788 if (isl_basic_set_list_foreach(intra, &bset_update_count, &data) < 0)
3789 return isl_stat_error;
3791 *n_eq = data.n_eq;
3792 *n_ineq = data.n_ineq;
3794 return isl_stat_ok;
3797 /* Construct an LP problem for finding schedule coefficients
3798 * such that the schedule carries as many validity dependences as possible.
3799 * In particular, for each dependence i, we bound the dependence distance
3800 * from below by e_i, with 0 <= e_i <= 1 and then maximize the sum
3801 * of all e_i's. Dependences with e_i = 0 in the solution are simply
3802 * respected, while those with e_i > 0 (in practice e_i = 1) are carried.
3803 * "intra" is the sequence of coefficient constraints for intra-node edges.
3804 * "inter" is the sequence of coefficient constraints for inter-node edges.
3805 * "n_edge" is the total number of edges.
3807 * All variables of the LP are non-negative. The actual coefficients
3808 * may be negative, so each coefficient is represented as the difference
3809 * of two non-negative variables. The negative part always appears
3810 * immediately before the positive part.
3811 * Other than that, the variables have the following order
3813 * - sum of (1 - e_i) over all edges
3814 * - sum of all c_n coefficients
3815 * (unconstrained when computing non-parametric schedules)
3816 * - sum of positive and negative parts of all c_x coefficients
3817 * - for each edge
3818 * - e_i
3819 * - for each node
3820 * - c_i_0
3821 * - c_i_n (if parametric)
3822 * - positive and negative parts of c_i_x, in opposite order
3824 * The constraints are those from the (validity) edges plus three equalities
3825 * to express the sums and n_edge inequalities to express e_i <= 1.
3827 static isl_stat setup_carry_lp(isl_ctx *ctx, struct isl_sched_graph *graph,
3828 int n_edge, __isl_keep isl_basic_set_list *intra,
3829 __isl_keep isl_basic_set_list *inter)
3831 int i;
3832 int k;
3833 isl_space *dim;
3834 unsigned total;
3835 int n_eq, n_ineq;
3837 total = 3 + n_edge;
3838 for (i = 0; i < graph->n; ++i) {
3839 struct isl_sched_node *node = &graph->node[graph->sorted[i]];
3840 node->start = total;
3841 total += 1 + node->nparam + 2 * node->nvar;
3844 if (count_all_constraints(intra, inter, &n_eq, &n_ineq) < 0)
3845 return isl_stat_error;
3847 dim = isl_space_set_alloc(ctx, 0, total);
3848 isl_basic_set_free(graph->lp);
3849 n_eq += 3;
3850 n_ineq += n_edge;
3851 graph->lp = isl_basic_set_alloc_space(dim, 0, n_eq, n_ineq);
3852 graph->lp = isl_basic_set_set_rational(graph->lp);
3854 k = isl_basic_set_alloc_equality(graph->lp);
3855 if (k < 0)
3856 return isl_stat_error;
3857 isl_seq_clr(graph->lp->eq[k], 1 + total);
3858 isl_int_set_si(graph->lp->eq[k][0], -n_edge);
3859 isl_int_set_si(graph->lp->eq[k][1], 1);
3860 for (i = 0; i < n_edge; ++i)
3861 isl_int_set_si(graph->lp->eq[k][4 + i], 1);
3863 if (add_param_sum_constraint(graph, 1) < 0)
3864 return isl_stat_error;
3865 if (add_var_sum_constraint(graph, 2) < 0)
3866 return isl_stat_error;
3868 for (i = 0; i < n_edge; ++i) {
3869 k = isl_basic_set_alloc_inequality(graph->lp);
3870 if (k < 0)
3871 return isl_stat_error;
3872 isl_seq_clr(graph->lp->ineq[k], 1 + total);
3873 isl_int_set_si(graph->lp->ineq[k][4 + i], -1);
3874 isl_int_set_si(graph->lp->ineq[k][0], 1);
3877 if (add_all_constraints(ctx, graph, intra, inter) < 0)
3878 return isl_stat_error;
3880 return isl_stat_ok;
3883 static __isl_give isl_schedule_node *compute_component_schedule(
3884 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
3885 int wcc);
3887 /* Comparison function for sorting the statements based on
3888 * the corresponding value in "r".
3890 static int smaller_value(const void *a, const void *b, void *data)
3892 isl_vec *r = data;
3893 const int *i1 = a;
3894 const int *i2 = b;
3896 return isl_int_cmp(r->el[*i1], r->el[*i2]);
3899 /* If the schedule_split_scaled option is set and if the linear
3900 * parts of the scheduling rows for all nodes in the graphs have
3901 * a non-trivial common divisor, then split off the remainder of the
3902 * constant term modulo this common divisor from the linear part.
3903 * Otherwise, insert a band node directly and continue with
3904 * the construction of the schedule.
3906 * If a non-trivial common divisor is found, then
3907 * the linear part is reduced and the remainder is enforced
3908 * by a sequence node with the children placed in the order
3909 * of this remainder.
3910 * In particular, we assign an scc index based on the remainder and
3911 * then rely on compute_component_schedule to insert the sequence and
3912 * to continue the schedule construction on each part.
3914 static __isl_give isl_schedule_node *split_scaled(
3915 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
3917 int i;
3918 int row;
3919 int scc;
3920 isl_ctx *ctx;
3921 isl_int gcd, gcd_i;
3922 isl_vec *r;
3923 int *order;
3925 if (!node)
3926 return NULL;
3928 ctx = isl_schedule_node_get_ctx(node);
3929 if (!ctx->opt->schedule_split_scaled)
3930 return compute_next_band(node, graph, 0);
3931 if (graph->n <= 1)
3932 return compute_next_band(node, graph, 0);
3934 isl_int_init(gcd);
3935 isl_int_init(gcd_i);
3937 isl_int_set_si(gcd, 0);
3939 row = isl_mat_rows(graph->node[0].sched) - 1;
3941 for (i = 0; i < graph->n; ++i) {
3942 struct isl_sched_node *node = &graph->node[i];
3943 int cols = isl_mat_cols(node->sched);
3945 isl_seq_gcd(node->sched->row[row] + 1, cols - 1, &gcd_i);
3946 isl_int_gcd(gcd, gcd, gcd_i);
3949 isl_int_clear(gcd_i);
3951 if (isl_int_cmp_si(gcd, 1) <= 0) {
3952 isl_int_clear(gcd);
3953 return compute_next_band(node, graph, 0);
3956 r = isl_vec_alloc(ctx, graph->n);
3957 order = isl_calloc_array(ctx, int, graph->n);
3958 if (!r || !order)
3959 goto error;
3961 for (i = 0; i < graph->n; ++i) {
3962 struct isl_sched_node *node = &graph->node[i];
3964 order[i] = i;
3965 isl_int_fdiv_r(r->el[i], node->sched->row[row][0], gcd);
3966 isl_int_fdiv_q(node->sched->row[row][0],
3967 node->sched->row[row][0], gcd);
3968 isl_int_mul(node->sched->row[row][0],
3969 node->sched->row[row][0], gcd);
3970 node->sched = isl_mat_scale_down_row(node->sched, row, gcd);
3971 if (!node->sched)
3972 goto error;
3975 if (isl_sort(order, graph->n, sizeof(order[0]), &smaller_value, r) < 0)
3976 goto error;
3978 scc = 0;
3979 for (i = 0; i < graph->n; ++i) {
3980 if (i > 0 && isl_int_ne(r->el[order[i - 1]], r->el[order[i]]))
3981 ++scc;
3982 graph->node[order[i]].scc = scc;
3984 graph->scc = ++scc;
3985 graph->weak = 0;
3987 isl_int_clear(gcd);
3988 isl_vec_free(r);
3989 free(order);
3991 if (update_edges(ctx, graph) < 0)
3992 return isl_schedule_node_free(node);
3993 node = insert_current_band(node, graph, 0);
3994 next_band(graph);
3996 node = isl_schedule_node_child(node, 0);
3997 node = compute_component_schedule(node, graph, 0);
3998 node = isl_schedule_node_parent(node);
4000 return node;
4001 error:
4002 isl_vec_free(r);
4003 free(order);
4004 isl_int_clear(gcd);
4005 return isl_schedule_node_free(node);
4008 /* Is the schedule row "sol" trivial on node "node"?
4009 * That is, is the solution zero on the dimensions linearly independent of
4010 * the previously found solutions?
4011 * Return 1 if the solution is trivial, 0 if it is not and -1 on error.
4013 * Each coefficient is represented as the difference between
4014 * two non-negative values in "sol".
4015 * We construct the schedule row s and check if it is linearly
4016 * independent of previously computed schedule rows
4017 * by computing T s, with T the linear combinations that are zero
4018 * on linearly dependent schedule rows.
4019 * If the result consists of all zeros, then the solution is trivial.
4021 static int is_trivial(struct isl_sched_node *node, __isl_keep isl_vec *sol)
4023 int trivial;
4024 isl_vec *node_sol;
4026 if (!sol)
4027 return -1;
4028 if (node->nvar == node->rank)
4029 return 0;
4031 node_sol = extract_var_coef(node, sol);
4032 node_sol = isl_mat_vec_product(isl_mat_copy(node->indep), node_sol);
4033 if (!node_sol)
4034 return -1;
4036 trivial = isl_seq_first_non_zero(node_sol->el,
4037 node->nvar - node->rank) == -1;
4039 isl_vec_free(node_sol);
4041 return trivial;
4044 /* Is the schedule row "sol" trivial on any node where it should
4045 * not be trivial?
4046 * Return 1 if any solution is trivial, 0 if they are not and -1 on error.
4048 static int is_any_trivial(struct isl_sched_graph *graph,
4049 __isl_keep isl_vec *sol)
4051 int i;
4053 for (i = 0; i < graph->n; ++i) {
4054 struct isl_sched_node *node = &graph->node[i];
4055 int trivial;
4057 if (!needs_row(graph, node))
4058 continue;
4059 trivial = is_trivial(node, sol);
4060 if (trivial < 0 || trivial)
4061 return trivial;
4064 return 0;
4067 /* Does the schedule represented by "sol" perform loop coalescing on "node"?
4068 * If so, return the position of the coalesced dimension.
4069 * Otherwise, return node->nvar or -1 on error.
4071 * In particular, look for pairs of coefficients c_i and c_j such that
4072 * |c_j/c_i| >= size_i, i.e., |c_j| >= |c_i * size_i|.
4073 * If any such pair is found, then return i.
4074 * If size_i is infinity, then no check on c_i needs to be performed.
4076 static int find_node_coalescing(struct isl_sched_node *node,
4077 __isl_keep isl_vec *sol)
4079 int i, j;
4080 isl_int max;
4081 isl_vec *csol;
4083 if (node->nvar <= 1)
4084 return node->nvar;
4086 csol = extract_var_coef(node, sol);
4087 if (!csol)
4088 return -1;
4089 isl_int_init(max);
4090 for (i = 0; i < node->nvar; ++i) {
4091 isl_val *v;
4093 if (isl_int_is_zero(csol->el[i]))
4094 continue;
4095 v = isl_multi_val_get_val(node->sizes, i);
4096 if (!v)
4097 goto error;
4098 if (!isl_val_is_int(v)) {
4099 isl_val_free(v);
4100 continue;
4102 isl_int_mul(max, v->n, csol->el[i]);
4103 isl_val_free(v);
4105 for (j = 0; j < node->nvar; ++j) {
4106 if (j == i)
4107 continue;
4108 if (isl_int_abs_ge(csol->el[j], max))
4109 break;
4111 if (j < node->nvar)
4112 break;
4115 isl_int_clear(max);
4116 isl_vec_free(csol);
4117 return i;
4118 error:
4119 isl_int_clear(max);
4120 isl_vec_free(csol);
4121 return -1;
4124 /* Force the schedule coefficient at position "pos" of "node" to be zero
4125 * in "tl".
4126 * The coefficient is encoded as the difference between two non-negative
4127 * variables. Force these two variables to have the same value.
4129 static __isl_give isl_tab_lexmin *zero_out_node_coef(
4130 __isl_take isl_tab_lexmin *tl, struct isl_sched_node *node, int pos)
4132 int dim;
4133 isl_ctx *ctx;
4134 isl_vec *eq;
4136 ctx = isl_space_get_ctx(node->space);
4137 dim = isl_tab_lexmin_dim(tl);
4138 if (dim < 0)
4139 return isl_tab_lexmin_free(tl);
4140 eq = isl_vec_alloc(ctx, 1 + dim);
4141 eq = isl_vec_clr(eq);
4142 if (!eq)
4143 return isl_tab_lexmin_free(tl);
4145 pos = 1 + node_var_coef_pos(node, pos);
4146 isl_int_set_si(eq->el[pos], 1);
4147 isl_int_set_si(eq->el[pos + 1], -1);
4148 tl = isl_tab_lexmin_add_eq(tl, eq->el);
4149 isl_vec_free(eq);
4151 return tl;
4154 /* Return the lexicographically smallest rational point in the basic set
4155 * from which "tl" was constructed, double checking that this input set
4156 * was not empty.
4158 static __isl_give isl_vec *non_empty_solution(__isl_keep isl_tab_lexmin *tl)
4160 isl_vec *sol;
4162 sol = isl_tab_lexmin_get_solution(tl);
4163 if (!sol)
4164 return NULL;
4165 if (sol->size == 0)
4166 isl_die(isl_vec_get_ctx(sol), isl_error_internal,
4167 "error in schedule construction",
4168 return isl_vec_free(sol));
4169 return sol;
4172 /* Does the solution "sol" of the LP problem constructed by setup_carry_lp
4173 * carry any of the "n_edge" groups of dependences?
4174 * The value in the first position is the sum of (1 - e_i) over all "n_edge"
4175 * edges, with 0 <= e_i <= 1 equal to 1 when the dependences represented
4176 * by the edge are carried by the solution.
4177 * If the sum of the (1 - e_i) is smaller than "n_edge" then at least
4178 * one of those is carried.
4180 * Note that despite the fact that the problem is solved using a rational
4181 * solver, the solution is guaranteed to be integral.
4182 * Specifically, the dependence distance lower bounds e_i (and therefore
4183 * also their sum) are integers. See Lemma 5 of [1].
4185 * Any potential denominator of the sum is cleared by this function.
4186 * The denominator is not relevant for any of the other elements
4187 * in the solution.
4189 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4190 * Problem, Part II: Multi-Dimensional Time.
4191 * In Intl. Journal of Parallel Programming, 1992.
4193 static int carries_dependences(__isl_keep isl_vec *sol, int n_edge)
4195 isl_int_divexact(sol->el[1], sol->el[1], sol->el[0]);
4196 isl_int_set_si(sol->el[0], 1);
4197 return isl_int_cmp_si(sol->el[1], n_edge) < 0;
4200 /* Return the lexicographically smallest rational point in "lp",
4201 * assuming that all variables are non-negative and performing some
4202 * additional sanity checks.
4203 * If "want_integral" is set, then compute the lexicographically smallest
4204 * integer point instead.
4205 * In particular, "lp" should not be empty by construction.
4206 * Double check that this is the case.
4207 * If dependences are not carried for any of the "n_edge" edges,
4208 * then return an empty vector.
4210 * If the schedule_treat_coalescing option is set and
4211 * if the computed schedule performs loop coalescing on a given node,
4212 * i.e., if it is of the form
4214 * c_i i + c_j j + ...
4216 * with |c_j/c_i| >= size_i, then force the coefficient c_i to be zero
4217 * to cut out this solution. Repeat this process until no more loop
4218 * coalescing occurs or until no more dependences can be carried.
4219 * In the latter case, revert to the previously computed solution.
4221 * If the caller requests an integral solution and if coalescing should
4222 * be treated, then perform the coalescing treatment first as
4223 * an integral solution computed before coalescing treatment
4224 * would carry the same number of edges and would therefore probably
4225 * also be coalescing.
4227 * To allow the coalescing treatment to be performed first,
4228 * the initial solution is allowed to be rational and it is only
4229 * cut out (if needed) in the next iteration, if no coalescing measures
4230 * were taken.
4232 static __isl_give isl_vec *non_neg_lexmin(struct isl_sched_graph *graph,
4233 __isl_take isl_basic_set *lp, int n_edge, int want_integral)
4235 int i, pos, cut;
4236 isl_ctx *ctx;
4237 isl_tab_lexmin *tl;
4238 isl_vec *sol, *prev = NULL;
4239 int treat_coalescing;
4241 if (!lp)
4242 return NULL;
4243 ctx = isl_basic_set_get_ctx(lp);
4244 treat_coalescing = isl_options_get_schedule_treat_coalescing(ctx);
4245 tl = isl_tab_lexmin_from_basic_set(lp);
4247 cut = 0;
4248 do {
4249 int integral;
4251 if (cut)
4252 tl = isl_tab_lexmin_cut_to_integer(tl);
4253 sol = non_empty_solution(tl);
4254 if (!sol)
4255 goto error;
4257 integral = isl_int_is_one(sol->el[0]);
4258 if (!carries_dependences(sol, n_edge)) {
4259 if (!prev)
4260 prev = isl_vec_alloc(ctx, 0);
4261 isl_vec_free(sol);
4262 sol = prev;
4263 break;
4265 prev = isl_vec_free(prev);
4266 cut = want_integral && !integral;
4267 if (cut)
4268 prev = sol;
4269 if (!treat_coalescing)
4270 continue;
4271 for (i = 0; i < graph->n; ++i) {
4272 struct isl_sched_node *node = &graph->node[i];
4274 pos = find_node_coalescing(node, sol);
4275 if (pos < 0)
4276 goto error;
4277 if (pos < node->nvar)
4278 break;
4280 if (i < graph->n) {
4281 prev = sol;
4282 tl = zero_out_node_coef(tl, &graph->node[i], pos);
4283 cut = 0;
4285 } while (prev);
4287 isl_tab_lexmin_free(tl);
4289 return sol;
4290 error:
4291 isl_tab_lexmin_free(tl);
4292 isl_vec_free(prev);
4293 isl_vec_free(sol);
4294 return NULL;
4297 /* If "edge" is an edge from a node to itself, then add the corresponding
4298 * dependence relation to "umap".
4299 * If "node" has been compressed, then the dependence relation
4300 * is also compressed first.
4302 static __isl_give isl_union_map *add_intra(__isl_take isl_union_map *umap,
4303 struct isl_sched_edge *edge)
4305 isl_map *map;
4306 struct isl_sched_node *node = edge->src;
4308 if (edge->src != edge->dst)
4309 return umap;
4311 map = isl_map_copy(edge->map);
4312 if (node->compressed) {
4313 map = isl_map_preimage_domain_multi_aff(map,
4314 isl_multi_aff_copy(node->decompress));
4315 map = isl_map_preimage_range_multi_aff(map,
4316 isl_multi_aff_copy(node->decompress));
4318 umap = isl_union_map_add_map(umap, map);
4319 return umap;
4322 /* If "edge" is an edge from a node to another node, then add the corresponding
4323 * dependence relation to "umap".
4324 * If the source or destination nodes of "edge" have been compressed,
4325 * then the dependence relation is also compressed first.
4327 static __isl_give isl_union_map *add_inter(__isl_take isl_union_map *umap,
4328 struct isl_sched_edge *edge)
4330 isl_map *map;
4332 if (edge->src == edge->dst)
4333 return umap;
4335 map = isl_map_copy(edge->map);
4336 if (edge->src->compressed)
4337 map = isl_map_preimage_domain_multi_aff(map,
4338 isl_multi_aff_copy(edge->src->decompress));
4339 if (edge->dst->compressed)
4340 map = isl_map_preimage_range_multi_aff(map,
4341 isl_multi_aff_copy(edge->dst->decompress));
4342 umap = isl_union_map_add_map(umap, map);
4343 return umap;
4346 /* For each (conditional) validity edge in "graph",
4347 * add the corresponding dependence relation using "add"
4348 * to a collection of dependence relations and return the result.
4349 * If "coincidence" is set, then coincidence edges are considered as well.
4351 static __isl_give isl_union_map *collect_validity(struct isl_sched_graph *graph,
4352 __isl_give isl_union_map *(*add)(__isl_take isl_union_map *umap,
4353 struct isl_sched_edge *edge), int coincidence)
4355 int i;
4356 isl_space *space;
4357 isl_union_map *umap;
4359 space = isl_space_copy(graph->node[0].space);
4360 umap = isl_union_map_empty(space);
4362 for (i = 0; i < graph->n_edge; ++i) {
4363 struct isl_sched_edge *edge = &graph->edge[i];
4365 if (!is_any_validity(edge) &&
4366 (!coincidence || !is_coincidence(edge)))
4367 continue;
4369 umap = add(umap, edge);
4372 return umap;
4375 /* For each dependence relation on a (conditional) validity edge
4376 * from a node to itself,
4377 * construct the set of coefficients of valid constraints for elements
4378 * in that dependence relation and collect the results.
4379 * If "coincidence" is set, then coincidence edges are considered as well.
4381 * In particular, for each dependence relation R, constraints
4382 * on coefficients (c_0, c_n, c_x) are constructed such that
4384 * c_0 + c_n n + c_x d >= 0 for each d in delta R = { y - x | (x,y) in R }
4386 * This computation is essentially the same as that performed
4387 * by intra_coefficients, except that it operates on multiple
4388 * edges together.
4390 * Note that if a dependence relation is a union of basic maps,
4391 * then each basic map needs to be treated individually as it may only
4392 * be possible to carry the dependences expressed by some of those
4393 * basic maps and not all of them.
4394 * The collected validity constraints are therefore not coalesced and
4395 * it is assumed that they are not coalesced automatically.
4396 * Duplicate basic maps can be removed, however.
4397 * In particular, if the same basic map appears as a disjunct
4398 * in multiple edges, then it only needs to be carried once.
4400 static __isl_give isl_basic_set_list *collect_intra_validity(
4401 struct isl_sched_graph *graph, int coincidence)
4403 isl_union_map *intra;
4404 isl_union_set *delta;
4405 isl_basic_set_list *list;
4407 intra = collect_validity(graph, &add_intra, coincidence);
4408 delta = isl_union_map_deltas(intra);
4409 delta = isl_union_set_remove_divs(delta);
4410 list = isl_union_set_get_basic_set_list(delta);
4411 isl_union_set_free(delta);
4413 return isl_basic_set_list_coefficients(list);
4416 /* For each dependence relation on a (conditional) validity edge
4417 * from a node to some other node,
4418 * construct the set of coefficients of valid constraints for elements
4419 * in that dependence relation and collect the results.
4420 * If "coincidence" is set, then coincidence edges are considered as well.
4422 * In particular, for each dependence relation R, constraints
4423 * on coefficients (c_0, c_n, c_x, c_y) are constructed such that
4425 * c_0 + c_n n + c_x x + c_y y >= 0 for each (x,y) in R
4427 * This computation is essentially the same as that performed
4428 * by inter_coefficients, except that it operates on multiple
4429 * edges together.
4431 * Note that if a dependence relation is a union of basic maps,
4432 * then each basic map needs to be treated individually as it may only
4433 * be possible to carry the dependences expressed by some of those
4434 * basic maps and not all of them.
4435 * The collected validity constraints are therefore not coalesced and
4436 * it is assumed that they are not coalesced automatically.
4437 * Duplicate basic maps can be removed, however.
4438 * In particular, if the same basic map appears as a disjunct
4439 * in multiple edges, then it only needs to be carried once.
4441 static __isl_give isl_basic_set_list *collect_inter_validity(
4442 struct isl_sched_graph *graph, int coincidence)
4444 isl_union_map *inter;
4445 isl_union_set *wrap;
4446 isl_basic_set_list *list;
4448 inter = collect_validity(graph, &add_inter, coincidence);
4449 inter = isl_union_map_remove_divs(inter);
4450 wrap = isl_union_map_wrap(inter);
4451 list = isl_union_set_get_basic_set_list(wrap);
4452 isl_union_set_free(wrap);
4453 return isl_basic_set_list_coefficients(list);
4456 /* Construct an LP problem for finding schedule coefficients
4457 * such that the schedule carries as many of the validity dependences
4458 * as possible and
4459 * return the lexicographically smallest non-trivial solution.
4460 * If "fallback" is set, then the carrying is performed as a fallback
4461 * for the Pluto-like scheduler.
4462 * If "coincidence" is set, then try and carry coincidence edges as well.
4464 * The variable "n_edge" stores the number of groups that should be carried.
4465 * If none of the "n_edge" groups can be carried
4466 * then return an empty vector.
4467 * If, moreover, "n_edge" is zero, then the LP problem does not even
4468 * need to be constructed.
4470 * If a fallback solution is being computed, then compute an integral solution
4471 * for the coefficients rather than using the numerators
4472 * of a rational solution.
4474 static __isl_give isl_vec *compute_carrying_sol(isl_ctx *ctx,
4475 struct isl_sched_graph *graph, int fallback, int coincidence)
4477 int n_intra, n_inter;
4478 int n_edge;
4479 isl_basic_set *lp;
4480 struct isl_carry carry = { 0 };
4482 carry.intra = collect_intra_validity(graph, coincidence);
4483 carry.inter = collect_inter_validity(graph, coincidence);
4484 if (!carry.intra || !carry.inter)
4485 goto error;
4486 n_intra = isl_basic_set_list_n_basic_set(carry.intra);
4487 n_inter = isl_basic_set_list_n_basic_set(carry.inter);
4488 n_edge = n_intra + n_inter;
4489 if (n_edge == 0) {
4490 isl_carry_clear(&carry);
4491 return isl_vec_alloc(ctx, 0);
4494 if (setup_carry_lp(ctx, graph, n_edge, carry.intra, carry.inter) < 0)
4495 goto error;
4497 isl_carry_clear(&carry);
4498 lp = isl_basic_set_copy(graph->lp);
4499 return non_neg_lexmin(graph, lp, n_edge, fallback);
4500 error:
4501 isl_carry_clear(&carry);
4502 return NULL;
4505 /* Construct a schedule row for each node such that as many validity dependences
4506 * as possible are carried and then continue with the next band.
4507 * If "fallback" is set, then the carrying is performed as a fallback
4508 * for the Pluto-like scheduler.
4509 * If "coincidence" is set, then try and carry coincidence edges as well.
4511 * If there are no validity dependences, then no dependence can be carried and
4512 * the procedure is guaranteed to fail. If there is more than one component,
4513 * then try computing a schedule on each component separately
4514 * to prevent or at least postpone this failure.
4516 * If a schedule row is computed, then check that dependences are carried
4517 * for at least one of the edges.
4519 * If the computed schedule row turns out to be trivial on one or
4520 * more nodes where it should not be trivial, then we throw it away
4521 * and try again on each component separately.
4523 * If there is only one component, then we accept the schedule row anyway,
4524 * but we do not consider it as a complete row and therefore do not
4525 * increment graph->n_row. Note that the ranks of the nodes that
4526 * do get a non-trivial schedule part will get updated regardless and
4527 * graph->maxvar is computed based on these ranks. The test for
4528 * whether more schedule rows are required in compute_schedule_wcc
4529 * is therefore not affected.
4531 * Insert a band corresponding to the schedule row at position "node"
4532 * of the schedule tree and continue with the construction of the schedule.
4533 * This insertion and the continued construction is performed by split_scaled
4534 * after optionally checking for non-trivial common divisors.
4536 static __isl_give isl_schedule_node *carry(__isl_take isl_schedule_node *node,
4537 struct isl_sched_graph *graph, int fallback, int coincidence)
4539 int trivial;
4540 isl_ctx *ctx;
4541 isl_vec *sol;
4543 if (!node)
4544 return NULL;
4546 ctx = isl_schedule_node_get_ctx(node);
4547 sol = compute_carrying_sol(ctx, graph, fallback, coincidence);
4548 if (!sol)
4549 return isl_schedule_node_free(node);
4550 if (sol->size == 0) {
4551 isl_vec_free(sol);
4552 if (graph->scc > 1)
4553 return compute_component_schedule(node, graph, 1);
4554 isl_die(ctx, isl_error_unknown, "unable to carry dependences",
4555 return isl_schedule_node_free(node));
4558 trivial = is_any_trivial(graph, sol);
4559 if (trivial < 0) {
4560 sol = isl_vec_free(sol);
4561 } else if (trivial && graph->scc > 1) {
4562 isl_vec_free(sol);
4563 return compute_component_schedule(node, graph, 1);
4566 if (update_schedule(graph, sol, 0) < 0)
4567 return isl_schedule_node_free(node);
4568 if (trivial)
4569 graph->n_row--;
4571 return split_scaled(node, graph);
4574 /* Construct a schedule row for each node such that as many validity dependences
4575 * as possible are carried and then continue with the next band.
4576 * Do so as a fallback for the Pluto-like scheduler.
4577 * If "coincidence" is set, then try and carry coincidence edges as well.
4579 static __isl_give isl_schedule_node *carry_fallback(
4580 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4581 int coincidence)
4583 return carry(node, graph, 1, coincidence);
4586 /* Construct a schedule row for each node such that as many validity dependences
4587 * as possible are carried and then continue with the next band.
4588 * Do so for the case where the Feautrier scheduler was selected
4589 * by the user.
4591 static __isl_give isl_schedule_node *carry_feautrier(
4592 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4594 return carry(node, graph, 0, 0);
4597 /* Construct a schedule row for each node such that as many validity dependences
4598 * as possible are carried and then continue with the next band.
4599 * Do so as a fallback for the Pluto-like scheduler.
4601 static __isl_give isl_schedule_node *carry_dependences(
4602 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4604 return carry_fallback(node, graph, 0);
4607 /* Construct a schedule row for each node such that as many validity or
4608 * coincidence dependences as possible are carried and
4609 * then continue with the next band.
4610 * Do so as a fallback for the Pluto-like scheduler.
4612 static __isl_give isl_schedule_node *carry_coincidence(
4613 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
4615 return carry_fallback(node, graph, 1);
4618 /* Topologically sort statements mapped to the same schedule iteration
4619 * and add insert a sequence node in front of "node"
4620 * corresponding to this order.
4621 * If "initialized" is set, then it may be assumed that compute_maxvar
4622 * has been called on the current band. Otherwise, call
4623 * compute_maxvar if and before carry_dependences gets called.
4625 * If it turns out to be impossible to sort the statements apart,
4626 * because different dependences impose different orderings
4627 * on the statements, then we extend the schedule such that
4628 * it carries at least one more dependence.
4630 static __isl_give isl_schedule_node *sort_statements(
4631 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4632 int initialized)
4634 isl_ctx *ctx;
4635 isl_union_set_list *filters;
4637 if (!node)
4638 return NULL;
4640 ctx = isl_schedule_node_get_ctx(node);
4641 if (graph->n < 1)
4642 isl_die(ctx, isl_error_internal,
4643 "graph should have at least one node",
4644 return isl_schedule_node_free(node));
4646 if (graph->n == 1)
4647 return node;
4649 if (update_edges(ctx, graph) < 0)
4650 return isl_schedule_node_free(node);
4652 if (graph->n_edge == 0)
4653 return node;
4655 if (detect_sccs(ctx, graph) < 0)
4656 return isl_schedule_node_free(node);
4658 next_band(graph);
4659 if (graph->scc < graph->n) {
4660 if (!initialized && compute_maxvar(graph) < 0)
4661 return isl_schedule_node_free(node);
4662 return carry_dependences(node, graph);
4665 filters = extract_sccs(ctx, graph);
4666 node = isl_schedule_node_insert_sequence(node, filters);
4668 return node;
4671 /* Are there any (non-empty) (conditional) validity edges in the graph?
4673 static int has_validity_edges(struct isl_sched_graph *graph)
4675 int i;
4677 for (i = 0; i < graph->n_edge; ++i) {
4678 int empty;
4680 empty = isl_map_plain_is_empty(graph->edge[i].map);
4681 if (empty < 0)
4682 return -1;
4683 if (empty)
4684 continue;
4685 if (is_any_validity(&graph->edge[i]))
4686 return 1;
4689 return 0;
4692 /* Should we apply a Feautrier step?
4693 * That is, did the user request the Feautrier algorithm and are
4694 * there any validity dependences (left)?
4696 static int need_feautrier_step(isl_ctx *ctx, struct isl_sched_graph *graph)
4698 if (ctx->opt->schedule_algorithm != ISL_SCHEDULE_ALGORITHM_FEAUTRIER)
4699 return 0;
4701 return has_validity_edges(graph);
4704 /* Compute a schedule for a connected dependence graph using Feautrier's
4705 * multi-dimensional scheduling algorithm and return the updated schedule node.
4707 * The original algorithm is described in [1].
4708 * The main idea is to minimize the number of scheduling dimensions, by
4709 * trying to satisfy as many dependences as possible per scheduling dimension.
4711 * [1] P. Feautrier, Some Efficient Solutions to the Affine Scheduling
4712 * Problem, Part II: Multi-Dimensional Time.
4713 * In Intl. Journal of Parallel Programming, 1992.
4715 static __isl_give isl_schedule_node *compute_schedule_wcc_feautrier(
4716 isl_schedule_node *node, struct isl_sched_graph *graph)
4718 return carry_feautrier(node, graph);
4721 /* Turn off the "local" bit on all (condition) edges.
4723 static void clear_local_edges(struct isl_sched_graph *graph)
4725 int i;
4727 for (i = 0; i < graph->n_edge; ++i)
4728 if (is_condition(&graph->edge[i]))
4729 clear_local(&graph->edge[i]);
4732 /* Does "graph" have both condition and conditional validity edges?
4734 static int need_condition_check(struct isl_sched_graph *graph)
4736 int i;
4737 int any_condition = 0;
4738 int any_conditional_validity = 0;
4740 for (i = 0; i < graph->n_edge; ++i) {
4741 if (is_condition(&graph->edge[i]))
4742 any_condition = 1;
4743 if (is_conditional_validity(&graph->edge[i]))
4744 any_conditional_validity = 1;
4747 return any_condition && any_conditional_validity;
4750 /* Does "graph" contain any coincidence edge?
4752 static int has_any_coincidence(struct isl_sched_graph *graph)
4754 int i;
4756 for (i = 0; i < graph->n_edge; ++i)
4757 if (is_coincidence(&graph->edge[i]))
4758 return 1;
4760 return 0;
4763 /* Extract the final schedule row as a map with the iteration domain
4764 * of "node" as domain.
4766 static __isl_give isl_map *final_row(struct isl_sched_node *node)
4768 isl_multi_aff *ma;
4769 int row;
4771 row = isl_mat_rows(node->sched) - 1;
4772 ma = node_extract_partial_schedule_multi_aff(node, row, 1);
4773 return isl_map_from_multi_aff(ma);
4776 /* Is the conditional validity dependence in the edge with index "edge_index"
4777 * violated by the latest (i.e., final) row of the schedule?
4778 * That is, is i scheduled after j
4779 * for any conditional validity dependence i -> j?
4781 static int is_violated(struct isl_sched_graph *graph, int edge_index)
4783 isl_map *src_sched, *dst_sched, *map;
4784 struct isl_sched_edge *edge = &graph->edge[edge_index];
4785 int empty;
4787 src_sched = final_row(edge->src);
4788 dst_sched = final_row(edge->dst);
4789 map = isl_map_copy(edge->map);
4790 map = isl_map_apply_domain(map, src_sched);
4791 map = isl_map_apply_range(map, dst_sched);
4792 map = isl_map_order_gt(map, isl_dim_in, 0, isl_dim_out, 0);
4793 empty = isl_map_is_empty(map);
4794 isl_map_free(map);
4796 if (empty < 0)
4797 return -1;
4799 return !empty;
4802 /* Does "graph" have any satisfied condition edges that
4803 * are adjacent to the conditional validity constraint with
4804 * domain "conditional_source" and range "conditional_sink"?
4806 * A satisfied condition is one that is not local.
4807 * If a condition was forced to be local already (i.e., marked as local)
4808 * then there is no need to check if it is in fact local.
4810 * Additionally, mark all adjacent condition edges found as local.
4812 static int has_adjacent_true_conditions(struct isl_sched_graph *graph,
4813 __isl_keep isl_union_set *conditional_source,
4814 __isl_keep isl_union_set *conditional_sink)
4816 int i;
4817 int any = 0;
4819 for (i = 0; i < graph->n_edge; ++i) {
4820 int adjacent, local;
4821 isl_union_map *condition;
4823 if (!is_condition(&graph->edge[i]))
4824 continue;
4825 if (is_local(&graph->edge[i]))
4826 continue;
4828 condition = graph->edge[i].tagged_condition;
4829 adjacent = domain_intersects(condition, conditional_sink);
4830 if (adjacent >= 0 && !adjacent)
4831 adjacent = range_intersects(condition,
4832 conditional_source);
4833 if (adjacent < 0)
4834 return -1;
4835 if (!adjacent)
4836 continue;
4838 set_local(&graph->edge[i]);
4840 local = is_condition_false(&graph->edge[i]);
4841 if (local < 0)
4842 return -1;
4843 if (!local)
4844 any = 1;
4847 return any;
4850 /* Are there any violated conditional validity dependences with
4851 * adjacent condition dependences that are not local with respect
4852 * to the current schedule?
4853 * That is, is the conditional validity constraint violated?
4855 * Additionally, mark all those adjacent condition dependences as local.
4856 * We also mark those adjacent condition dependences that were not marked
4857 * as local before, but just happened to be local already. This ensures
4858 * that they remain local if the schedule is recomputed.
4860 * We first collect domain and range of all violated conditional validity
4861 * dependences and then check if there are any adjacent non-local
4862 * condition dependences.
4864 static int has_violated_conditional_constraint(isl_ctx *ctx,
4865 struct isl_sched_graph *graph)
4867 int i;
4868 int any = 0;
4869 isl_union_set *source, *sink;
4871 source = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4872 sink = isl_union_set_empty(isl_space_params_alloc(ctx, 0));
4873 for (i = 0; i < graph->n_edge; ++i) {
4874 isl_union_set *uset;
4875 isl_union_map *umap;
4876 int violated;
4878 if (!is_conditional_validity(&graph->edge[i]))
4879 continue;
4881 violated = is_violated(graph, i);
4882 if (violated < 0)
4883 goto error;
4884 if (!violated)
4885 continue;
4887 any = 1;
4889 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4890 uset = isl_union_map_domain(umap);
4891 source = isl_union_set_union(source, uset);
4892 source = isl_union_set_coalesce(source);
4894 umap = isl_union_map_copy(graph->edge[i].tagged_validity);
4895 uset = isl_union_map_range(umap);
4896 sink = isl_union_set_union(sink, uset);
4897 sink = isl_union_set_coalesce(sink);
4900 if (any)
4901 any = has_adjacent_true_conditions(graph, source, sink);
4903 isl_union_set_free(source);
4904 isl_union_set_free(sink);
4905 return any;
4906 error:
4907 isl_union_set_free(source);
4908 isl_union_set_free(sink);
4909 return -1;
4912 /* Examine the current band (the rows between graph->band_start and
4913 * graph->n_total_row), deciding whether to drop it or add it to "node"
4914 * and then continue with the computation of the next band, if any.
4915 * If "initialized" is set, then it may be assumed that compute_maxvar
4916 * has been called on the current band. Otherwise, call
4917 * compute_maxvar if and before carry_dependences gets called.
4919 * The caller keeps looking for a new row as long as
4920 * graph->n_row < graph->maxvar. If the latest attempt to find
4921 * such a row failed (i.e., we still have graph->n_row < graph->maxvar),
4922 * then we either
4923 * - split between SCCs and start over (assuming we found an interesting
4924 * pair of SCCs between which to split)
4925 * - continue with the next band (assuming the current band has at least
4926 * one row)
4927 * - if outer coincidence needs to be enforced, then try to carry as many
4928 * validity or coincidence dependences as possible and
4929 * continue with the next band
4930 * - try to carry as many validity dependences as possible and
4931 * continue with the next band
4932 * In each case, we first insert a band node in the schedule tree
4933 * if any rows have been computed.
4935 * If the caller managed to complete the schedule, we insert a band node
4936 * (if any schedule rows were computed) and we finish off by topologically
4937 * sorting the statements based on the remaining dependences.
4939 static __isl_give isl_schedule_node *compute_schedule_finish_band(
4940 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
4941 int initialized)
4943 int insert;
4945 if (!node)
4946 return NULL;
4948 if (graph->n_row < graph->maxvar) {
4949 isl_ctx *ctx;
4950 int empty = graph->n_total_row == graph->band_start;
4952 ctx = isl_schedule_node_get_ctx(node);
4953 if (!ctx->opt->schedule_maximize_band_depth && !empty)
4954 return compute_next_band(node, graph, 1);
4955 if (graph->src_scc >= 0)
4956 return compute_split_schedule(node, graph);
4957 if (!empty)
4958 return compute_next_band(node, graph, 1);
4959 if (!initialized && compute_maxvar(graph) < 0)
4960 return isl_schedule_node_free(node);
4961 if (isl_options_get_schedule_outer_coincidence(ctx))
4962 return carry_coincidence(node, graph);
4963 return carry_dependences(node, graph);
4966 insert = graph->n_total_row > graph->band_start;
4967 if (insert) {
4968 node = insert_current_band(node, graph, 1);
4969 node = isl_schedule_node_child(node, 0);
4971 node = sort_statements(node, graph, initialized);
4972 if (insert)
4973 node = isl_schedule_node_parent(node);
4975 return node;
4978 /* Construct a band of schedule rows for a connected dependence graph.
4979 * The caller is responsible for determining the strongly connected
4980 * components and calling compute_maxvar first.
4982 * We try to find a sequence of as many schedule rows as possible that result
4983 * in non-negative dependence distances (independent of the previous rows
4984 * in the sequence, i.e., such that the sequence is tilable), with as
4985 * many of the initial rows as possible satisfying the coincidence constraints.
4986 * The computation stops if we can't find any more rows or if we have found
4987 * all the rows we wanted to find.
4989 * If ctx->opt->schedule_outer_coincidence is set, then we force the
4990 * outermost dimension to satisfy the coincidence constraints. If this
4991 * turns out to be impossible, we fall back on the general scheme above
4992 * and try to carry as many dependences as possible.
4994 * If "graph" contains both condition and conditional validity dependences,
4995 * then we need to check that that the conditional schedule constraint
4996 * is satisfied, i.e., there are no violated conditional validity dependences
4997 * that are adjacent to any non-local condition dependences.
4998 * If there are, then we mark all those adjacent condition dependences
4999 * as local and recompute the current band. Those dependences that
5000 * are marked local will then be forced to be local.
5001 * The initial computation is performed with no dependences marked as local.
5002 * If we are lucky, then there will be no violated conditional validity
5003 * dependences adjacent to any non-local condition dependences.
5004 * Otherwise, we mark some additional condition dependences as local and
5005 * recompute. We continue this process until there are no violations left or
5006 * until we are no longer able to compute a schedule.
5007 * Since there are only a finite number of dependences,
5008 * there will only be a finite number of iterations.
5010 static isl_stat compute_schedule_wcc_band(isl_ctx *ctx,
5011 struct isl_sched_graph *graph)
5013 int has_coincidence;
5014 int use_coincidence;
5015 int force_coincidence = 0;
5016 int check_conditional;
5018 if (sort_sccs(graph) < 0)
5019 return isl_stat_error;
5021 clear_local_edges(graph);
5022 check_conditional = need_condition_check(graph);
5023 has_coincidence = has_any_coincidence(graph);
5025 if (ctx->opt->schedule_outer_coincidence)
5026 force_coincidence = 1;
5028 use_coincidence = has_coincidence;
5029 while (graph->n_row < graph->maxvar) {
5030 isl_vec *sol;
5031 int violated;
5032 int coincident;
5034 graph->src_scc = -1;
5035 graph->dst_scc = -1;
5037 if (setup_lp(ctx, graph, use_coincidence) < 0)
5038 return isl_stat_error;
5039 sol = solve_lp(ctx, graph);
5040 if (!sol)
5041 return isl_stat_error;
5042 if (sol->size == 0) {
5043 int empty = graph->n_total_row == graph->band_start;
5045 isl_vec_free(sol);
5046 if (use_coincidence && (!force_coincidence || !empty)) {
5047 use_coincidence = 0;
5048 continue;
5050 return isl_stat_ok;
5052 coincident = !has_coincidence || use_coincidence;
5053 if (update_schedule(graph, sol, coincident) < 0)
5054 return isl_stat_error;
5056 if (!check_conditional)
5057 continue;
5058 violated = has_violated_conditional_constraint(ctx, graph);
5059 if (violated < 0)
5060 return isl_stat_error;
5061 if (!violated)
5062 continue;
5063 if (reset_band(graph) < 0)
5064 return isl_stat_error;
5065 use_coincidence = has_coincidence;
5068 return isl_stat_ok;
5071 /* Compute a schedule for a connected dependence graph by considering
5072 * the graph as a whole and return the updated schedule node.
5074 * The actual schedule rows of the current band are computed by
5075 * compute_schedule_wcc_band. compute_schedule_finish_band takes
5076 * care of integrating the band into "node" and continuing
5077 * the computation.
5079 static __isl_give isl_schedule_node *compute_schedule_wcc_whole(
5080 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
5082 isl_ctx *ctx;
5084 if (!node)
5085 return NULL;
5087 ctx = isl_schedule_node_get_ctx(node);
5088 if (compute_schedule_wcc_band(ctx, graph) < 0)
5089 return isl_schedule_node_free(node);
5091 return compute_schedule_finish_band(node, graph, 1);
5094 /* Clustering information used by compute_schedule_wcc_clustering.
5096 * "n" is the number of SCCs in the original dependence graph
5097 * "scc" is an array of "n" elements, each representing an SCC
5098 * of the original dependence graph. All entries in the same cluster
5099 * have the same number of schedule rows.
5100 * "scc_cluster" maps each SCC index to the cluster to which it belongs,
5101 * where each cluster is represented by the index of the first SCC
5102 * in the cluster. Initially, each SCC belongs to a cluster containing
5103 * only that SCC.
5105 * "scc_in_merge" is used by merge_clusters_along_edge to keep
5106 * track of which SCCs need to be merged.
5108 * "cluster" contains the merged clusters of SCCs after the clustering
5109 * has completed.
5111 * "scc_node" is a temporary data structure used inside copy_partial.
5112 * For each SCC, it keeps track of the number of nodes in the SCC
5113 * that have already been copied.
5115 struct isl_clustering {
5116 int n;
5117 struct isl_sched_graph *scc;
5118 struct isl_sched_graph *cluster;
5119 int *scc_cluster;
5120 int *scc_node;
5121 int *scc_in_merge;
5124 /* Initialize the clustering data structure "c" from "graph".
5126 * In particular, allocate memory, extract the SCCs from "graph"
5127 * into c->scc, initialize scc_cluster and construct
5128 * a band of schedule rows for each SCC.
5129 * Within each SCC, there is only one SCC by definition.
5130 * Each SCC initially belongs to a cluster containing only that SCC.
5132 static isl_stat clustering_init(isl_ctx *ctx, struct isl_clustering *c,
5133 struct isl_sched_graph *graph)
5135 int i;
5137 c->n = graph->scc;
5138 c->scc = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5139 c->cluster = isl_calloc_array(ctx, struct isl_sched_graph, c->n);
5140 c->scc_cluster = isl_calloc_array(ctx, int, c->n);
5141 c->scc_node = isl_calloc_array(ctx, int, c->n);
5142 c->scc_in_merge = isl_calloc_array(ctx, int, c->n);
5143 if (!c->scc || !c->cluster ||
5144 !c->scc_cluster || !c->scc_node || !c->scc_in_merge)
5145 return isl_stat_error;
5147 for (i = 0; i < c->n; ++i) {
5148 if (extract_sub_graph(ctx, graph, &node_scc_exactly,
5149 &edge_scc_exactly, i, &c->scc[i]) < 0)
5150 return isl_stat_error;
5151 c->scc[i].scc = 1;
5152 if (compute_maxvar(&c->scc[i]) < 0)
5153 return isl_stat_error;
5154 if (compute_schedule_wcc_band(ctx, &c->scc[i]) < 0)
5155 return isl_stat_error;
5156 c->scc_cluster[i] = i;
5159 return isl_stat_ok;
5162 /* Free all memory allocated for "c".
5164 static void clustering_free(isl_ctx *ctx, struct isl_clustering *c)
5166 int i;
5168 if (c->scc)
5169 for (i = 0; i < c->n; ++i)
5170 graph_free(ctx, &c->scc[i]);
5171 free(c->scc);
5172 if (c->cluster)
5173 for (i = 0; i < c->n; ++i)
5174 graph_free(ctx, &c->cluster[i]);
5175 free(c->cluster);
5176 free(c->scc_cluster);
5177 free(c->scc_node);
5178 free(c->scc_in_merge);
5181 /* Should we refrain from merging the cluster in "graph" with
5182 * any other cluster?
5183 * In particular, is its current schedule band empty and incomplete.
5185 static int bad_cluster(struct isl_sched_graph *graph)
5187 return graph->n_row < graph->maxvar &&
5188 graph->n_total_row == graph->band_start;
5191 /* Is "edge" a proximity edge with a non-empty dependence relation?
5193 static isl_bool is_non_empty_proximity(struct isl_sched_edge *edge)
5195 if (!is_proximity(edge))
5196 return isl_bool_false;
5197 return isl_bool_not(isl_map_plain_is_empty(edge->map));
5200 /* Return the index of an edge in "graph" that can be used to merge
5201 * two clusters in "c".
5202 * Return graph->n_edge if no such edge can be found.
5203 * Return -1 on error.
5205 * In particular, return a proximity edge between two clusters
5206 * that is not marked "no_merge" and such that neither of the
5207 * two clusters has an incomplete, empty band.
5209 * If there are multiple such edges, then try and find the most
5210 * appropriate edge to use for merging. In particular, pick the edge
5211 * with the greatest weight. If there are multiple of those,
5212 * then pick one with the shortest distance between
5213 * the two cluster representatives.
5215 static int find_proximity(struct isl_sched_graph *graph,
5216 struct isl_clustering *c)
5218 int i, best = graph->n_edge, best_dist, best_weight;
5220 for (i = 0; i < graph->n_edge; ++i) {
5221 struct isl_sched_edge *edge = &graph->edge[i];
5222 int dist, weight;
5223 isl_bool prox;
5225 prox = is_non_empty_proximity(edge);
5226 if (prox < 0)
5227 return -1;
5228 if (!prox)
5229 continue;
5230 if (edge->no_merge)
5231 continue;
5232 if (bad_cluster(&c->scc[edge->src->scc]) ||
5233 bad_cluster(&c->scc[edge->dst->scc]))
5234 continue;
5235 dist = c->scc_cluster[edge->dst->scc] -
5236 c->scc_cluster[edge->src->scc];
5237 if (dist == 0)
5238 continue;
5239 weight = edge->weight;
5240 if (best < graph->n_edge) {
5241 if (best_weight > weight)
5242 continue;
5243 if (best_weight == weight && best_dist <= dist)
5244 continue;
5246 best = i;
5247 best_dist = dist;
5248 best_weight = weight;
5251 return best;
5254 /* Internal data structure used in mark_merge_sccs.
5256 * "graph" is the dependence graph in which a strongly connected
5257 * component is constructed.
5258 * "scc_cluster" maps each SCC index to the cluster to which it belongs.
5259 * "src" and "dst" are the indices of the nodes that are being merged.
5261 struct isl_mark_merge_sccs_data {
5262 struct isl_sched_graph *graph;
5263 int *scc_cluster;
5264 int src;
5265 int dst;
5268 /* Check whether the cluster containing node "i" depends on the cluster
5269 * containing node "j". If "i" and "j" belong to the same cluster,
5270 * then they are taken to depend on each other to ensure that
5271 * the resulting strongly connected component consists of complete
5272 * clusters. Furthermore, if "i" and "j" are the two nodes that
5273 * are being merged, then they are taken to depend on each other as well.
5274 * Otherwise, check if there is a (conditional) validity dependence
5275 * from node[j] to node[i], forcing node[i] to follow node[j].
5277 static isl_bool cluster_follows(int i, int j, void *user)
5279 struct isl_mark_merge_sccs_data *data = user;
5280 struct isl_sched_graph *graph = data->graph;
5281 int *scc_cluster = data->scc_cluster;
5283 if (data->src == i && data->dst == j)
5284 return isl_bool_true;
5285 if (data->src == j && data->dst == i)
5286 return isl_bool_true;
5287 if (scc_cluster[graph->node[i].scc] == scc_cluster[graph->node[j].scc])
5288 return isl_bool_true;
5290 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
5293 /* Mark all SCCs that belong to either of the two clusters in "c"
5294 * connected by the edge in "graph" with index "edge", or to any
5295 * of the intermediate clusters.
5296 * The marking is recorded in c->scc_in_merge.
5298 * The given edge has been selected for merging two clusters,
5299 * meaning that there is at least a proximity edge between the two nodes.
5300 * However, there may also be (indirect) validity dependences
5301 * between the two nodes. When merging the two clusters, all clusters
5302 * containing one or more of the intermediate nodes along the
5303 * indirect validity dependences need to be merged in as well.
5305 * First collect all such nodes by computing the strongly connected
5306 * component (SCC) containing the two nodes connected by the edge, where
5307 * the two nodes are considered to depend on each other to make
5308 * sure they end up in the same SCC. Similarly, each node is considered
5309 * to depend on every other node in the same cluster to ensure
5310 * that the SCC consists of complete clusters.
5312 * Then the original SCCs that contain any of these nodes are marked
5313 * in c->scc_in_merge.
5315 static isl_stat mark_merge_sccs(isl_ctx *ctx, struct isl_sched_graph *graph,
5316 int edge, struct isl_clustering *c)
5318 struct isl_mark_merge_sccs_data data;
5319 struct isl_tarjan_graph *g;
5320 int i;
5322 for (i = 0; i < c->n; ++i)
5323 c->scc_in_merge[i] = 0;
5325 data.graph = graph;
5326 data.scc_cluster = c->scc_cluster;
5327 data.src = graph->edge[edge].src - graph->node;
5328 data.dst = graph->edge[edge].dst - graph->node;
5330 g = isl_tarjan_graph_component(ctx, graph->n, data.dst,
5331 &cluster_follows, &data);
5332 if (!g)
5333 goto error;
5335 i = g->op;
5336 if (i < 3)
5337 isl_die(ctx, isl_error_internal,
5338 "expecting at least two nodes in component",
5339 goto error);
5340 if (g->order[--i] != -1)
5341 isl_die(ctx, isl_error_internal,
5342 "expecting end of component marker", goto error);
5344 for (--i; i >= 0 && g->order[i] != -1; --i) {
5345 int scc = graph->node[g->order[i]].scc;
5346 c->scc_in_merge[scc] = 1;
5349 isl_tarjan_graph_free(g);
5350 return isl_stat_ok;
5351 error:
5352 isl_tarjan_graph_free(g);
5353 return isl_stat_error;
5356 /* Construct the identifier "cluster_i".
5358 static __isl_give isl_id *cluster_id(isl_ctx *ctx, int i)
5360 char name[40];
5362 snprintf(name, sizeof(name), "cluster_%d", i);
5363 return isl_id_alloc(ctx, name, NULL);
5366 /* Construct the space of the cluster with index "i" containing
5367 * the strongly connected component "scc".
5369 * In particular, construct a space called cluster_i with dimension equal
5370 * to the number of schedule rows in the current band of "scc".
5372 static __isl_give isl_space *cluster_space(struct isl_sched_graph *scc, int i)
5374 int nvar;
5375 isl_space *space;
5376 isl_id *id;
5378 nvar = scc->n_total_row - scc->band_start;
5379 space = isl_space_copy(scc->node[0].space);
5380 space = isl_space_params(space);
5381 space = isl_space_set_from_params(space);
5382 space = isl_space_add_dims(space, isl_dim_set, nvar);
5383 id = cluster_id(isl_space_get_ctx(space), i);
5384 space = isl_space_set_tuple_id(space, isl_dim_set, id);
5386 return space;
5389 /* Collect the domain of the graph for merging clusters.
5391 * In particular, for each cluster with first SCC "i", construct
5392 * a set in the space called cluster_i with dimension equal
5393 * to the number of schedule rows in the current band of the cluster.
5395 static __isl_give isl_union_set *collect_domain(isl_ctx *ctx,
5396 struct isl_sched_graph *graph, struct isl_clustering *c)
5398 int i;
5399 isl_space *space;
5400 isl_union_set *domain;
5402 space = isl_space_params_alloc(ctx, 0);
5403 domain = isl_union_set_empty(space);
5405 for (i = 0; i < graph->scc; ++i) {
5406 isl_space *space;
5408 if (!c->scc_in_merge[i])
5409 continue;
5410 if (c->scc_cluster[i] != i)
5411 continue;
5412 space = cluster_space(&c->scc[i], i);
5413 domain = isl_union_set_add_set(domain, isl_set_universe(space));
5416 return domain;
5419 /* Construct a map from the original instances to the corresponding
5420 * cluster instance in the current bands of the clusters in "c".
5422 static __isl_give isl_union_map *collect_cluster_map(isl_ctx *ctx,
5423 struct isl_sched_graph *graph, struct isl_clustering *c)
5425 int i, j;
5426 isl_space *space;
5427 isl_union_map *cluster_map;
5429 space = isl_space_params_alloc(ctx, 0);
5430 cluster_map = isl_union_map_empty(space);
5431 for (i = 0; i < graph->scc; ++i) {
5432 int start, n;
5433 isl_id *id;
5435 if (!c->scc_in_merge[i])
5436 continue;
5438 id = cluster_id(ctx, c->scc_cluster[i]);
5439 start = c->scc[i].band_start;
5440 n = c->scc[i].n_total_row - start;
5441 for (j = 0; j < c->scc[i].n; ++j) {
5442 isl_multi_aff *ma;
5443 isl_map *map;
5444 struct isl_sched_node *node = &c->scc[i].node[j];
5446 ma = node_extract_partial_schedule_multi_aff(node,
5447 start, n);
5448 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out,
5449 isl_id_copy(id));
5450 map = isl_map_from_multi_aff(ma);
5451 cluster_map = isl_union_map_add_map(cluster_map, map);
5453 isl_id_free(id);
5456 return cluster_map;
5459 /* Add "umap" to the schedule constraints "sc" of all types of "edge"
5460 * that are not isl_edge_condition or isl_edge_conditional_validity.
5462 static __isl_give isl_schedule_constraints *add_non_conditional_constraints(
5463 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
5464 __isl_take isl_schedule_constraints *sc)
5466 enum isl_edge_type t;
5468 if (!sc)
5469 return NULL;
5471 for (t = isl_edge_first; t <= isl_edge_last; ++t) {
5472 if (t == isl_edge_condition ||
5473 t == isl_edge_conditional_validity)
5474 continue;
5475 if (!is_type(edge, t))
5476 continue;
5477 sc = isl_schedule_constraints_add(sc, t,
5478 isl_union_map_copy(umap));
5481 return sc;
5484 /* Add schedule constraints of types isl_edge_condition and
5485 * isl_edge_conditional_validity to "sc" by applying "umap" to
5486 * the domains of the wrapped relations in domain and range
5487 * of the corresponding tagged constraints of "edge".
5489 static __isl_give isl_schedule_constraints *add_conditional_constraints(
5490 struct isl_sched_edge *edge, __isl_keep isl_union_map *umap,
5491 __isl_take isl_schedule_constraints *sc)
5493 enum isl_edge_type t;
5494 isl_union_map *tagged;
5496 for (t = isl_edge_condition; t <= isl_edge_conditional_validity; ++t) {
5497 if (!is_type(edge, t))
5498 continue;
5499 if (t == isl_edge_condition)
5500 tagged = isl_union_map_copy(edge->tagged_condition);
5501 else
5502 tagged = isl_union_map_copy(edge->tagged_validity);
5503 tagged = isl_union_map_zip(tagged);
5504 tagged = isl_union_map_apply_domain(tagged,
5505 isl_union_map_copy(umap));
5506 tagged = isl_union_map_zip(tagged);
5507 sc = isl_schedule_constraints_add(sc, t, tagged);
5508 if (!sc)
5509 return NULL;
5512 return sc;
5515 /* Given a mapping "cluster_map" from the original instances to
5516 * the cluster instances, add schedule constraints on the clusters
5517 * to "sc" corresponding to the original constraints represented by "edge".
5519 * For non-tagged dependence constraints, the cluster constraints
5520 * are obtained by applying "cluster_map" to the edge->map.
5522 * For tagged dependence constraints, "cluster_map" needs to be applied
5523 * to the domains of the wrapped relations in domain and range
5524 * of the tagged dependence constraints. Pick out the mappings
5525 * from these domains from "cluster_map" and construct their product.
5526 * This mapping can then be applied to the pair of domains.
5528 static __isl_give isl_schedule_constraints *collect_edge_constraints(
5529 struct isl_sched_edge *edge, __isl_keep isl_union_map *cluster_map,
5530 __isl_take isl_schedule_constraints *sc)
5532 isl_union_map *umap;
5533 isl_space *space;
5534 isl_union_set *uset;
5535 isl_union_map *umap1, *umap2;
5537 if (!sc)
5538 return NULL;
5540 umap = isl_union_map_from_map(isl_map_copy(edge->map));
5541 umap = isl_union_map_apply_domain(umap,
5542 isl_union_map_copy(cluster_map));
5543 umap = isl_union_map_apply_range(umap,
5544 isl_union_map_copy(cluster_map));
5545 sc = add_non_conditional_constraints(edge, umap, sc);
5546 isl_union_map_free(umap);
5548 if (!sc || (!is_condition(edge) && !is_conditional_validity(edge)))
5549 return sc;
5551 space = isl_space_domain(isl_map_get_space(edge->map));
5552 uset = isl_union_set_from_set(isl_set_universe(space));
5553 umap1 = isl_union_map_copy(cluster_map);
5554 umap1 = isl_union_map_intersect_domain(umap1, uset);
5555 space = isl_space_range(isl_map_get_space(edge->map));
5556 uset = isl_union_set_from_set(isl_set_universe(space));
5557 umap2 = isl_union_map_copy(cluster_map);
5558 umap2 = isl_union_map_intersect_domain(umap2, uset);
5559 umap = isl_union_map_product(umap1, umap2);
5561 sc = add_conditional_constraints(edge, umap, sc);
5563 isl_union_map_free(umap);
5564 return sc;
5567 /* Given a mapping "cluster_map" from the original instances to
5568 * the cluster instances, add schedule constraints on the clusters
5569 * to "sc" corresponding to all edges in "graph" between nodes that
5570 * belong to SCCs that are marked for merging in "scc_in_merge".
5572 static __isl_give isl_schedule_constraints *collect_constraints(
5573 struct isl_sched_graph *graph, int *scc_in_merge,
5574 __isl_keep isl_union_map *cluster_map,
5575 __isl_take isl_schedule_constraints *sc)
5577 int i;
5579 for (i = 0; i < graph->n_edge; ++i) {
5580 struct isl_sched_edge *edge = &graph->edge[i];
5582 if (!scc_in_merge[edge->src->scc])
5583 continue;
5584 if (!scc_in_merge[edge->dst->scc])
5585 continue;
5586 sc = collect_edge_constraints(edge, cluster_map, sc);
5589 return sc;
5592 /* Construct a dependence graph for scheduling clusters with respect
5593 * to each other and store the result in "merge_graph".
5594 * In particular, the nodes of the graph correspond to the schedule
5595 * dimensions of the current bands of those clusters that have been
5596 * marked for merging in "c".
5598 * First construct an isl_schedule_constraints object for this domain
5599 * by transforming the edges in "graph" to the domain.
5600 * Then initialize a dependence graph for scheduling from these
5601 * constraints.
5603 static isl_stat init_merge_graph(isl_ctx *ctx, struct isl_sched_graph *graph,
5604 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
5606 isl_union_set *domain;
5607 isl_union_map *cluster_map;
5608 isl_schedule_constraints *sc;
5609 isl_stat r;
5611 domain = collect_domain(ctx, graph, c);
5612 sc = isl_schedule_constraints_on_domain(domain);
5613 if (!sc)
5614 return isl_stat_error;
5615 cluster_map = collect_cluster_map(ctx, graph, c);
5616 sc = collect_constraints(graph, c->scc_in_merge, cluster_map, sc);
5617 isl_union_map_free(cluster_map);
5619 r = graph_init(merge_graph, sc);
5621 isl_schedule_constraints_free(sc);
5623 return r;
5626 /* Compute the maximal number of remaining schedule rows that still need
5627 * to be computed for the nodes that belong to clusters with the maximal
5628 * dimension for the current band (i.e., the band that is to be merged).
5629 * Only clusters that are about to be merged are considered.
5630 * "maxvar" is the maximal dimension for the current band.
5631 * "c" contains information about the clusters.
5633 * Return the maximal number of remaining schedule rows or -1 on error.
5635 static int compute_maxvar_max_slack(int maxvar, struct isl_clustering *c)
5637 int i, j;
5638 int max_slack;
5640 max_slack = 0;
5641 for (i = 0; i < c->n; ++i) {
5642 int nvar;
5643 struct isl_sched_graph *scc;
5645 if (!c->scc_in_merge[i])
5646 continue;
5647 scc = &c->scc[i];
5648 nvar = scc->n_total_row - scc->band_start;
5649 if (nvar != maxvar)
5650 continue;
5651 for (j = 0; j < scc->n; ++j) {
5652 struct isl_sched_node *node = &scc->node[j];
5653 int slack;
5655 if (node_update_vmap(node) < 0)
5656 return -1;
5657 slack = node->nvar - node->rank;
5658 if (slack > max_slack)
5659 max_slack = slack;
5663 return max_slack;
5666 /* If there are any clusters where the dimension of the current band
5667 * (i.e., the band that is to be merged) is smaller than "maxvar" and
5668 * if there are any nodes in such a cluster where the number
5669 * of remaining schedule rows that still need to be computed
5670 * is greater than "max_slack", then return the smallest current band
5671 * dimension of all these clusters. Otherwise return the original value
5672 * of "maxvar". Return -1 in case of any error.
5673 * Only clusters that are about to be merged are considered.
5674 * "c" contains information about the clusters.
5676 static int limit_maxvar_to_slack(int maxvar, int max_slack,
5677 struct isl_clustering *c)
5679 int i, j;
5681 for (i = 0; i < c->n; ++i) {
5682 int nvar;
5683 struct isl_sched_graph *scc;
5685 if (!c->scc_in_merge[i])
5686 continue;
5687 scc = &c->scc[i];
5688 nvar = scc->n_total_row - scc->band_start;
5689 if (nvar >= maxvar)
5690 continue;
5691 for (j = 0; j < scc->n; ++j) {
5692 struct isl_sched_node *node = &scc->node[j];
5693 int slack;
5695 if (node_update_vmap(node) < 0)
5696 return -1;
5697 slack = node->nvar - node->rank;
5698 if (slack > max_slack) {
5699 maxvar = nvar;
5700 break;
5705 return maxvar;
5708 /* Adjust merge_graph->maxvar based on the number of remaining schedule rows
5709 * that still need to be computed. In particular, if there is a node
5710 * in a cluster where the dimension of the current band is smaller
5711 * than merge_graph->maxvar, but the number of remaining schedule rows
5712 * is greater than that of any node in a cluster with the maximal
5713 * dimension for the current band (i.e., merge_graph->maxvar),
5714 * then adjust merge_graph->maxvar to the (smallest) current band dimension
5715 * of those clusters. Without this adjustment, the total number of
5716 * schedule dimensions would be increased, resulting in a skewed view
5717 * of the number of coincident dimensions.
5718 * "c" contains information about the clusters.
5720 * If the maximize_band_depth option is set and merge_graph->maxvar is reduced,
5721 * then there is no point in attempting any merge since it will be rejected
5722 * anyway. Set merge_graph->maxvar to zero in such cases.
5724 static isl_stat adjust_maxvar_to_slack(isl_ctx *ctx,
5725 struct isl_sched_graph *merge_graph, struct isl_clustering *c)
5727 int max_slack, maxvar;
5729 max_slack = compute_maxvar_max_slack(merge_graph->maxvar, c);
5730 if (max_slack < 0)
5731 return isl_stat_error;
5732 maxvar = limit_maxvar_to_slack(merge_graph->maxvar, max_slack, c);
5733 if (maxvar < 0)
5734 return isl_stat_error;
5736 if (maxvar < merge_graph->maxvar) {
5737 if (isl_options_get_schedule_maximize_band_depth(ctx))
5738 merge_graph->maxvar = 0;
5739 else
5740 merge_graph->maxvar = maxvar;
5743 return isl_stat_ok;
5746 /* Return the number of coincident dimensions in the current band of "graph",
5747 * where the nodes of "graph" are assumed to be scheduled by a single band.
5749 static int get_n_coincident(struct isl_sched_graph *graph)
5751 int i;
5753 for (i = graph->band_start; i < graph->n_total_row; ++i)
5754 if (!graph->node[0].coincident[i])
5755 break;
5757 return i - graph->band_start;
5760 /* Should the clusters be merged based on the cluster schedule
5761 * in the current (and only) band of "merge_graph", given that
5762 * coincidence should be maximized?
5764 * If the number of coincident schedule dimensions in the merged band
5765 * would be less than the maximal number of coincident schedule dimensions
5766 * in any of the merged clusters, then the clusters should not be merged.
5768 static isl_bool ok_to_merge_coincident(struct isl_clustering *c,
5769 struct isl_sched_graph *merge_graph)
5771 int i;
5772 int n_coincident;
5773 int max_coincident;
5775 max_coincident = 0;
5776 for (i = 0; i < c->n; ++i) {
5777 if (!c->scc_in_merge[i])
5778 continue;
5779 n_coincident = get_n_coincident(&c->scc[i]);
5780 if (n_coincident > max_coincident)
5781 max_coincident = n_coincident;
5784 n_coincident = get_n_coincident(merge_graph);
5786 return n_coincident >= max_coincident;
5789 /* Return the transformation on "node" expressed by the current (and only)
5790 * band of "merge_graph" applied to the clusters in "c".
5792 * First find the representation of "node" in its SCC in "c" and
5793 * extract the transformation expressed by the current band.
5794 * Then extract the transformation applied by "merge_graph"
5795 * to the cluster to which this SCC belongs.
5796 * Combine the two to obtain the complete transformation on the node.
5798 * Note that the range of the first transformation is an anonymous space,
5799 * while the domain of the second is named "cluster_X". The range
5800 * of the former therefore needs to be adjusted before the two
5801 * can be combined.
5803 static __isl_give isl_map *extract_node_transformation(isl_ctx *ctx,
5804 struct isl_sched_node *node, struct isl_clustering *c,
5805 struct isl_sched_graph *merge_graph)
5807 struct isl_sched_node *scc_node, *cluster_node;
5808 int start, n;
5809 isl_id *id;
5810 isl_space *space;
5811 isl_multi_aff *ma, *ma2;
5813 scc_node = graph_find_node(ctx, &c->scc[node->scc], node->space);
5814 start = c->scc[node->scc].band_start;
5815 n = c->scc[node->scc].n_total_row - start;
5816 ma = node_extract_partial_schedule_multi_aff(scc_node, start, n);
5817 space = cluster_space(&c->scc[node->scc], c->scc_cluster[node->scc]);
5818 cluster_node = graph_find_node(ctx, merge_graph, space);
5819 if (space && !cluster_node)
5820 isl_die(ctx, isl_error_internal, "unable to find cluster",
5821 space = isl_space_free(space));
5822 id = isl_space_get_tuple_id(space, isl_dim_set);
5823 ma = isl_multi_aff_set_tuple_id(ma, isl_dim_out, id);
5824 isl_space_free(space);
5825 n = merge_graph->n_total_row;
5826 ma2 = node_extract_partial_schedule_multi_aff(cluster_node, 0, n);
5827 ma = isl_multi_aff_pullback_multi_aff(ma2, ma);
5829 return isl_map_from_multi_aff(ma);
5832 /* Give a set of distances "set", are they bounded by a small constant
5833 * in direction "pos"?
5834 * In practice, check if they are bounded by 2 by checking that there
5835 * are no elements with a value greater than or equal to 3 or
5836 * smaller than or equal to -3.
5838 static isl_bool distance_is_bounded(__isl_keep isl_set *set, int pos)
5840 isl_bool bounded;
5841 isl_set *test;
5843 if (!set)
5844 return isl_bool_error;
5846 test = isl_set_copy(set);
5847 test = isl_set_lower_bound_si(test, isl_dim_set, pos, 3);
5848 bounded = isl_set_is_empty(test);
5849 isl_set_free(test);
5851 if (bounded < 0 || !bounded)
5852 return bounded;
5854 test = isl_set_copy(set);
5855 test = isl_set_upper_bound_si(test, isl_dim_set, pos, -3);
5856 bounded = isl_set_is_empty(test);
5857 isl_set_free(test);
5859 return bounded;
5862 /* Does the set "set" have a fixed (but possible parametric) value
5863 * at dimension "pos"?
5865 static isl_bool has_single_value(__isl_keep isl_set *set, int pos)
5867 int n;
5868 isl_bool single;
5870 if (!set)
5871 return isl_bool_error;
5872 set = isl_set_copy(set);
5873 n = isl_set_dim(set, isl_dim_set);
5874 set = isl_set_project_out(set, isl_dim_set, pos + 1, n - (pos + 1));
5875 set = isl_set_project_out(set, isl_dim_set, 0, pos);
5876 single = isl_set_is_singleton(set);
5877 isl_set_free(set);
5879 return single;
5882 /* Does "map" have a fixed (but possible parametric) value
5883 * at dimension "pos" of either its domain or its range?
5885 static isl_bool has_singular_src_or_dst(__isl_keep isl_map *map, int pos)
5887 isl_set *set;
5888 isl_bool single;
5890 set = isl_map_domain(isl_map_copy(map));
5891 single = has_single_value(set, pos);
5892 isl_set_free(set);
5894 if (single < 0 || single)
5895 return single;
5897 set = isl_map_range(isl_map_copy(map));
5898 single = has_single_value(set, pos);
5899 isl_set_free(set);
5901 return single;
5904 /* Does the edge "edge" from "graph" have bounded dependence distances
5905 * in the merged graph "merge_graph" of a selection of clusters in "c"?
5907 * Extract the complete transformations of the source and destination
5908 * nodes of the edge, apply them to the edge constraints and
5909 * compute the differences. Finally, check if these differences are bounded
5910 * in each direction.
5912 * If the dimension of the band is greater than the number of
5913 * dimensions that can be expected to be optimized by the edge
5914 * (based on its weight), then also allow the differences to be unbounded
5915 * in the remaining dimensions, but only if either the source or
5916 * the destination has a fixed value in that direction.
5917 * This allows a statement that produces values that are used by
5918 * several instances of another statement to be merged with that
5919 * other statement.
5920 * However, merging such clusters will introduce an inherently
5921 * large proximity distance inside the merged cluster, meaning
5922 * that proximity distances will no longer be optimized in
5923 * subsequent merges. These merges are therefore only allowed
5924 * after all other possible merges have been tried.
5925 * The first time such a merge is encountered, the weight of the edge
5926 * is replaced by a negative weight. The second time (i.e., after
5927 * all merges over edges with a non-negative weight have been tried),
5928 * the merge is allowed.
5930 static isl_bool has_bounded_distances(isl_ctx *ctx, struct isl_sched_edge *edge,
5931 struct isl_sched_graph *graph, struct isl_clustering *c,
5932 struct isl_sched_graph *merge_graph)
5934 int i, n, n_slack;
5935 isl_bool bounded;
5936 isl_map *map, *t;
5937 isl_set *dist;
5939 map = isl_map_copy(edge->map);
5940 t = extract_node_transformation(ctx, edge->src, c, merge_graph);
5941 map = isl_map_apply_domain(map, t);
5942 t = extract_node_transformation(ctx, edge->dst, c, merge_graph);
5943 map = isl_map_apply_range(map, t);
5944 dist = isl_map_deltas(isl_map_copy(map));
5946 bounded = isl_bool_true;
5947 n = isl_set_dim(dist, isl_dim_set);
5948 n_slack = n - edge->weight;
5949 if (edge->weight < 0)
5950 n_slack -= graph->max_weight + 1;
5951 for (i = 0; i < n; ++i) {
5952 isl_bool bounded_i, singular_i;
5954 bounded_i = distance_is_bounded(dist, i);
5955 if (bounded_i < 0)
5956 goto error;
5957 if (bounded_i)
5958 continue;
5959 if (edge->weight >= 0)
5960 bounded = isl_bool_false;
5961 n_slack--;
5962 if (n_slack < 0)
5963 break;
5964 singular_i = has_singular_src_or_dst(map, i);
5965 if (singular_i < 0)
5966 goto error;
5967 if (singular_i)
5968 continue;
5969 bounded = isl_bool_false;
5970 break;
5972 if (!bounded && i >= n && edge->weight >= 0)
5973 edge->weight -= graph->max_weight + 1;
5974 isl_map_free(map);
5975 isl_set_free(dist);
5977 return bounded;
5978 error:
5979 isl_map_free(map);
5980 isl_set_free(dist);
5981 return isl_bool_error;
5984 /* Should the clusters be merged based on the cluster schedule
5985 * in the current (and only) band of "merge_graph"?
5986 * "graph" is the original dependence graph, while "c" records
5987 * which SCCs are involved in the latest merge.
5989 * In particular, is there at least one proximity constraint
5990 * that is optimized by the merge?
5992 * A proximity constraint is considered to be optimized
5993 * if the dependence distances are small.
5995 static isl_bool ok_to_merge_proximity(isl_ctx *ctx,
5996 struct isl_sched_graph *graph, struct isl_clustering *c,
5997 struct isl_sched_graph *merge_graph)
5999 int i;
6001 for (i = 0; i < graph->n_edge; ++i) {
6002 struct isl_sched_edge *edge = &graph->edge[i];
6003 isl_bool bounded;
6005 if (!is_proximity(edge))
6006 continue;
6007 if (!c->scc_in_merge[edge->src->scc])
6008 continue;
6009 if (!c->scc_in_merge[edge->dst->scc])
6010 continue;
6011 if (c->scc_cluster[edge->dst->scc] ==
6012 c->scc_cluster[edge->src->scc])
6013 continue;
6014 bounded = has_bounded_distances(ctx, edge, graph, c,
6015 merge_graph);
6016 if (bounded < 0 || bounded)
6017 return bounded;
6020 return isl_bool_false;
6023 /* Should the clusters be merged based on the cluster schedule
6024 * in the current (and only) band of "merge_graph"?
6025 * "graph" is the original dependence graph, while "c" records
6026 * which SCCs are involved in the latest merge.
6028 * If the current band is empty, then the clusters should not be merged.
6030 * If the band depth should be maximized and the merge schedule
6031 * is incomplete (meaning that the dimension of some of the schedule
6032 * bands in the original schedule will be reduced), then the clusters
6033 * should not be merged.
6035 * If the schedule_maximize_coincidence option is set, then check that
6036 * the number of coincident schedule dimensions is not reduced.
6038 * Finally, only allow the merge if at least one proximity
6039 * constraint is optimized.
6041 static isl_bool ok_to_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6042 struct isl_clustering *c, struct isl_sched_graph *merge_graph)
6044 if (merge_graph->n_total_row == merge_graph->band_start)
6045 return isl_bool_false;
6047 if (isl_options_get_schedule_maximize_band_depth(ctx) &&
6048 merge_graph->n_total_row < merge_graph->maxvar)
6049 return isl_bool_false;
6051 if (isl_options_get_schedule_maximize_coincidence(ctx)) {
6052 isl_bool ok;
6054 ok = ok_to_merge_coincident(c, merge_graph);
6055 if (ok < 0 || !ok)
6056 return ok;
6059 return ok_to_merge_proximity(ctx, graph, c, merge_graph);
6062 /* Apply the schedule in "t_node" to the "n" rows starting at "first"
6063 * of the schedule in "node" and return the result.
6065 * That is, essentially compute
6067 * T * N(first:first+n-1)
6069 * taking into account the constant term and the parameter coefficients
6070 * in "t_node".
6072 static __isl_give isl_mat *node_transformation(isl_ctx *ctx,
6073 struct isl_sched_node *t_node, struct isl_sched_node *node,
6074 int first, int n)
6076 int i, j;
6077 isl_mat *t;
6078 int n_row, n_col, n_param, n_var;
6080 n_param = node->nparam;
6081 n_var = node->nvar;
6082 n_row = isl_mat_rows(t_node->sched);
6083 n_col = isl_mat_cols(node->sched);
6084 t = isl_mat_alloc(ctx, n_row, n_col);
6085 if (!t)
6086 return NULL;
6087 for (i = 0; i < n_row; ++i) {
6088 isl_seq_cpy(t->row[i], t_node->sched->row[i], 1 + n_param);
6089 isl_seq_clr(t->row[i] + 1 + n_param, n_var);
6090 for (j = 0; j < n; ++j)
6091 isl_seq_addmul(t->row[i],
6092 t_node->sched->row[i][1 + n_param + j],
6093 node->sched->row[first + j],
6094 1 + n_param + n_var);
6096 return t;
6099 /* Apply the cluster schedule in "t_node" to the current band
6100 * schedule of the nodes in "graph".
6102 * In particular, replace the rows starting at band_start
6103 * by the result of applying the cluster schedule in "t_node"
6104 * to the original rows.
6106 * The coincidence of the schedule is determined by the coincidence
6107 * of the cluster schedule.
6109 static isl_stat transform(isl_ctx *ctx, struct isl_sched_graph *graph,
6110 struct isl_sched_node *t_node)
6112 int i, j;
6113 int n_new;
6114 int start, n;
6116 start = graph->band_start;
6117 n = graph->n_total_row - start;
6119 n_new = isl_mat_rows(t_node->sched);
6120 for (i = 0; i < graph->n; ++i) {
6121 struct isl_sched_node *node = &graph->node[i];
6122 isl_mat *t;
6124 t = node_transformation(ctx, t_node, node, start, n);
6125 node->sched = isl_mat_drop_rows(node->sched, start, n);
6126 node->sched = isl_mat_concat(node->sched, t);
6127 node->sched_map = isl_map_free(node->sched_map);
6128 if (!node->sched)
6129 return isl_stat_error;
6130 for (j = 0; j < n_new; ++j)
6131 node->coincident[start + j] = t_node->coincident[j];
6133 graph->n_total_row -= n;
6134 graph->n_row -= n;
6135 graph->n_total_row += n_new;
6136 graph->n_row += n_new;
6138 return isl_stat_ok;
6141 /* Merge the clusters marked for merging in "c" into a single
6142 * cluster using the cluster schedule in the current band of "merge_graph".
6143 * The representative SCC for the new cluster is the SCC with
6144 * the smallest index.
6146 * The current band schedule of each SCC in the new cluster is obtained
6147 * by applying the schedule of the corresponding original cluster
6148 * to the original band schedule.
6149 * All SCCs in the new cluster have the same number of schedule rows.
6151 static isl_stat merge(isl_ctx *ctx, struct isl_clustering *c,
6152 struct isl_sched_graph *merge_graph)
6154 int i;
6155 int cluster = -1;
6156 isl_space *space;
6158 for (i = 0; i < c->n; ++i) {
6159 struct isl_sched_node *node;
6161 if (!c->scc_in_merge[i])
6162 continue;
6163 if (cluster < 0)
6164 cluster = i;
6165 space = cluster_space(&c->scc[i], c->scc_cluster[i]);
6166 if (!space)
6167 return isl_stat_error;
6168 node = graph_find_node(ctx, merge_graph, space);
6169 isl_space_free(space);
6170 if (!node)
6171 isl_die(ctx, isl_error_internal,
6172 "unable to find cluster",
6173 return isl_stat_error);
6174 if (transform(ctx, &c->scc[i], node) < 0)
6175 return isl_stat_error;
6176 c->scc_cluster[i] = cluster;
6179 return isl_stat_ok;
6182 /* Try and merge the clusters of SCCs marked in c->scc_in_merge
6183 * by scheduling the current cluster bands with respect to each other.
6185 * Construct a dependence graph with a space for each cluster and
6186 * with the coordinates of each space corresponding to the schedule
6187 * dimensions of the current band of that cluster.
6188 * Construct a cluster schedule in this cluster dependence graph and
6189 * apply it to the current cluster bands if it is applicable
6190 * according to ok_to_merge.
6192 * If the number of remaining schedule dimensions in a cluster
6193 * with a non-maximal current schedule dimension is greater than
6194 * the number of remaining schedule dimensions in clusters
6195 * with a maximal current schedule dimension, then restrict
6196 * the number of rows to be computed in the cluster schedule
6197 * to the minimal such non-maximal current schedule dimension.
6198 * Do this by adjusting merge_graph.maxvar.
6200 * Return isl_bool_true if the clusters have effectively been merged
6201 * into a single cluster.
6203 * Note that since the standard scheduling algorithm minimizes the maximal
6204 * distance over proximity constraints, the proximity constraints between
6205 * the merged clusters may not be optimized any further than what is
6206 * sufficient to bring the distances within the limits of the internal
6207 * proximity constraints inside the individual clusters.
6208 * It may therefore make sense to perform an additional translation step
6209 * to bring the clusters closer to each other, while maintaining
6210 * the linear part of the merging schedule found using the standard
6211 * scheduling algorithm.
6213 static isl_bool try_merge(isl_ctx *ctx, struct isl_sched_graph *graph,
6214 struct isl_clustering *c)
6216 struct isl_sched_graph merge_graph = { 0 };
6217 isl_bool merged;
6219 if (init_merge_graph(ctx, graph, c, &merge_graph) < 0)
6220 goto error;
6222 if (compute_maxvar(&merge_graph) < 0)
6223 goto error;
6224 if (adjust_maxvar_to_slack(ctx, &merge_graph,c) < 0)
6225 goto error;
6226 if (compute_schedule_wcc_band(ctx, &merge_graph) < 0)
6227 goto error;
6228 merged = ok_to_merge(ctx, graph, c, &merge_graph);
6229 if (merged && merge(ctx, c, &merge_graph) < 0)
6230 goto error;
6232 graph_free(ctx, &merge_graph);
6233 return merged;
6234 error:
6235 graph_free(ctx, &merge_graph);
6236 return isl_bool_error;
6239 /* Is there any edge marked "no_merge" between two SCCs that are
6240 * about to be merged (i.e., that are set in "scc_in_merge")?
6241 * "merge_edge" is the proximity edge along which the clusters of SCCs
6242 * are going to be merged.
6244 * If there is any edge between two SCCs with a negative weight,
6245 * while the weight of "merge_edge" is non-negative, then this
6246 * means that the edge was postponed. "merge_edge" should then
6247 * also be postponed since merging along the edge with negative weight should
6248 * be postponed until all edges with non-negative weight have been tried.
6249 * Replace the weight of "merge_edge" by a negative weight as well and
6250 * tell the caller not to attempt a merge.
6252 static int any_no_merge(struct isl_sched_graph *graph, int *scc_in_merge,
6253 struct isl_sched_edge *merge_edge)
6255 int i;
6257 for (i = 0; i < graph->n_edge; ++i) {
6258 struct isl_sched_edge *edge = &graph->edge[i];
6260 if (!scc_in_merge[edge->src->scc])
6261 continue;
6262 if (!scc_in_merge[edge->dst->scc])
6263 continue;
6264 if (edge->no_merge)
6265 return 1;
6266 if (merge_edge->weight >= 0 && edge->weight < 0) {
6267 merge_edge->weight -= graph->max_weight + 1;
6268 return 1;
6272 return 0;
6275 /* Merge the two clusters in "c" connected by the edge in "graph"
6276 * with index "edge" into a single cluster.
6277 * If it turns out to be impossible to merge these two clusters,
6278 * then mark the edge as "no_merge" such that it will not be
6279 * considered again.
6281 * First mark all SCCs that need to be merged. This includes the SCCs
6282 * in the two clusters, but it may also include the SCCs
6283 * of intermediate clusters.
6284 * If there is already a no_merge edge between any pair of such SCCs,
6285 * then simply mark the current edge as no_merge as well.
6286 * Likewise, if any of those edges was postponed by has_bounded_distances,
6287 * then postpone the current edge as well.
6288 * Otherwise, try and merge the clusters and mark "edge" as "no_merge"
6289 * if the clusters did not end up getting merged, unless the non-merge
6290 * is due to the fact that the edge was postponed. This postponement
6291 * can be recognized by a change in weight (from non-negative to negative).
6293 static isl_stat merge_clusters_along_edge(isl_ctx *ctx,
6294 struct isl_sched_graph *graph, int edge, struct isl_clustering *c)
6296 isl_bool merged;
6297 int edge_weight = graph->edge[edge].weight;
6299 if (mark_merge_sccs(ctx, graph, edge, c) < 0)
6300 return isl_stat_error;
6302 if (any_no_merge(graph, c->scc_in_merge, &graph->edge[edge]))
6303 merged = isl_bool_false;
6304 else
6305 merged = try_merge(ctx, graph, c);
6306 if (merged < 0)
6307 return isl_stat_error;
6308 if (!merged && edge_weight == graph->edge[edge].weight)
6309 graph->edge[edge].no_merge = 1;
6311 return isl_stat_ok;
6314 /* Does "node" belong to the cluster identified by "cluster"?
6316 static int node_cluster_exactly(struct isl_sched_node *node, int cluster)
6318 return node->cluster == cluster;
6321 /* Does "edge" connect two nodes belonging to the cluster
6322 * identified by "cluster"?
6324 static int edge_cluster_exactly(struct isl_sched_edge *edge, int cluster)
6326 return edge->src->cluster == cluster && edge->dst->cluster == cluster;
6329 /* Swap the schedule of "node1" and "node2".
6330 * Both nodes have been derived from the same node in a common parent graph.
6331 * Since the "coincident" field is shared with that node
6332 * in the parent graph, there is no need to also swap this field.
6334 static void swap_sched(struct isl_sched_node *node1,
6335 struct isl_sched_node *node2)
6337 isl_mat *sched;
6338 isl_map *sched_map;
6340 sched = node1->sched;
6341 node1->sched = node2->sched;
6342 node2->sched = sched;
6344 sched_map = node1->sched_map;
6345 node1->sched_map = node2->sched_map;
6346 node2->sched_map = sched_map;
6349 /* Copy the current band schedule from the SCCs that form the cluster
6350 * with index "pos" to the actual cluster at position "pos".
6351 * By construction, the index of the first SCC that belongs to the cluster
6352 * is also "pos".
6354 * The order of the nodes inside both the SCCs and the cluster
6355 * is assumed to be same as the order in the original "graph".
6357 * Since the SCC graphs will no longer be used after this function,
6358 * the schedules are actually swapped rather than copied.
6360 static isl_stat copy_partial(struct isl_sched_graph *graph,
6361 struct isl_clustering *c, int pos)
6363 int i, j;
6365 c->cluster[pos].n_total_row = c->scc[pos].n_total_row;
6366 c->cluster[pos].n_row = c->scc[pos].n_row;
6367 c->cluster[pos].maxvar = c->scc[pos].maxvar;
6368 j = 0;
6369 for (i = 0; i < graph->n; ++i) {
6370 int k;
6371 int s;
6373 if (graph->node[i].cluster != pos)
6374 continue;
6375 s = graph->node[i].scc;
6376 k = c->scc_node[s]++;
6377 swap_sched(&c->cluster[pos].node[j], &c->scc[s].node[k]);
6378 if (c->scc[s].maxvar > c->cluster[pos].maxvar)
6379 c->cluster[pos].maxvar = c->scc[s].maxvar;
6380 ++j;
6383 return isl_stat_ok;
6386 /* Is there a (conditional) validity dependence from node[j] to node[i],
6387 * forcing node[i] to follow node[j] or do the nodes belong to the same
6388 * cluster?
6390 static isl_bool node_follows_strong_or_same_cluster(int i, int j, void *user)
6392 struct isl_sched_graph *graph = user;
6394 if (graph->node[i].cluster == graph->node[j].cluster)
6395 return isl_bool_true;
6396 return graph_has_validity_edge(graph, &graph->node[j], &graph->node[i]);
6399 /* Extract the merged clusters of SCCs in "graph", sort them, and
6400 * store them in c->clusters. Update c->scc_cluster accordingly.
6402 * First keep track of the cluster containing the SCC to which a node
6403 * belongs in the node itself.
6404 * Then extract the clusters into c->clusters, copying the current
6405 * band schedule from the SCCs that belong to the cluster.
6406 * Do this only once per cluster.
6408 * Finally, topologically sort the clusters and update c->scc_cluster
6409 * to match the new scc numbering. While the SCCs were originally
6410 * sorted already, some SCCs that depend on some other SCCs may
6411 * have been merged with SCCs that appear before these other SCCs.
6412 * A reordering may therefore be required.
6414 static isl_stat extract_clusters(isl_ctx *ctx, struct isl_sched_graph *graph,
6415 struct isl_clustering *c)
6417 int i;
6419 for (i = 0; i < graph->n; ++i)
6420 graph->node[i].cluster = c->scc_cluster[graph->node[i].scc];
6422 for (i = 0; i < graph->scc; ++i) {
6423 if (c->scc_cluster[i] != i)
6424 continue;
6425 if (extract_sub_graph(ctx, graph, &node_cluster_exactly,
6426 &edge_cluster_exactly, i, &c->cluster[i]) < 0)
6427 return isl_stat_error;
6428 c->cluster[i].src_scc = -1;
6429 c->cluster[i].dst_scc = -1;
6430 if (copy_partial(graph, c, i) < 0)
6431 return isl_stat_error;
6434 if (detect_ccs(ctx, graph, &node_follows_strong_or_same_cluster) < 0)
6435 return isl_stat_error;
6436 for (i = 0; i < graph->n; ++i)
6437 c->scc_cluster[graph->node[i].scc] = graph->node[i].cluster;
6439 return isl_stat_ok;
6442 /* Compute weights on the proximity edges of "graph" that can
6443 * be used by find_proximity to find the most appropriate
6444 * proximity edge to use to merge two clusters in "c".
6445 * The weights are also used by has_bounded_distances to determine
6446 * whether the merge should be allowed.
6447 * Store the maximum of the computed weights in graph->max_weight.
6449 * The computed weight is a measure for the number of remaining schedule
6450 * dimensions that can still be completely aligned.
6451 * In particular, compute the number of equalities between
6452 * input dimensions and output dimensions in the proximity constraints.
6453 * The directions that are already handled by outer schedule bands
6454 * are projected out prior to determining this number.
6456 * Edges that will never be considered by find_proximity are ignored.
6458 static isl_stat compute_weights(struct isl_sched_graph *graph,
6459 struct isl_clustering *c)
6461 int i;
6463 graph->max_weight = 0;
6465 for (i = 0; i < graph->n_edge; ++i) {
6466 struct isl_sched_edge *edge = &graph->edge[i];
6467 struct isl_sched_node *src = edge->src;
6468 struct isl_sched_node *dst = edge->dst;
6469 isl_basic_map *hull;
6470 isl_bool prox;
6471 int n_in, n_out;
6473 prox = is_non_empty_proximity(edge);
6474 if (prox < 0)
6475 return isl_stat_error;
6476 if (!prox)
6477 continue;
6478 if (bad_cluster(&c->scc[edge->src->scc]) ||
6479 bad_cluster(&c->scc[edge->dst->scc]))
6480 continue;
6481 if (c->scc_cluster[edge->dst->scc] ==
6482 c->scc_cluster[edge->src->scc])
6483 continue;
6485 hull = isl_map_affine_hull(isl_map_copy(edge->map));
6486 hull = isl_basic_map_transform_dims(hull, isl_dim_in, 0,
6487 isl_mat_copy(src->vmap));
6488 hull = isl_basic_map_transform_dims(hull, isl_dim_out, 0,
6489 isl_mat_copy(dst->vmap));
6490 hull = isl_basic_map_project_out(hull,
6491 isl_dim_in, 0, src->rank);
6492 hull = isl_basic_map_project_out(hull,
6493 isl_dim_out, 0, dst->rank);
6494 hull = isl_basic_map_remove_divs(hull);
6495 n_in = isl_basic_map_dim(hull, isl_dim_in);
6496 n_out = isl_basic_map_dim(hull, isl_dim_out);
6497 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6498 isl_dim_in, 0, n_in);
6499 hull = isl_basic_map_drop_constraints_not_involving_dims(hull,
6500 isl_dim_out, 0, n_out);
6501 if (!hull)
6502 return isl_stat_error;
6503 edge->weight = isl_basic_map_n_equality(hull);
6504 isl_basic_map_free(hull);
6506 if (edge->weight > graph->max_weight)
6507 graph->max_weight = edge->weight;
6510 return isl_stat_ok;
6513 /* Call compute_schedule_finish_band on each of the clusters in "c"
6514 * in their topological order. This order is determined by the scc
6515 * fields of the nodes in "graph".
6516 * Combine the results in a sequence expressing the topological order.
6518 * If there is only one cluster left, then there is no need to introduce
6519 * a sequence node. Also, in this case, the cluster necessarily contains
6520 * the SCC at position 0 in the original graph and is therefore also
6521 * stored in the first cluster of "c".
6523 static __isl_give isl_schedule_node *finish_bands_clustering(
6524 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6525 struct isl_clustering *c)
6527 int i;
6528 isl_ctx *ctx;
6529 isl_union_set_list *filters;
6531 if (graph->scc == 1)
6532 return compute_schedule_finish_band(node, &c->cluster[0], 0);
6534 ctx = isl_schedule_node_get_ctx(node);
6536 filters = extract_sccs(ctx, graph);
6537 node = isl_schedule_node_insert_sequence(node, filters);
6539 for (i = 0; i < graph->scc; ++i) {
6540 int j = c->scc_cluster[i];
6541 node = isl_schedule_node_child(node, i);
6542 node = isl_schedule_node_child(node, 0);
6543 node = compute_schedule_finish_band(node, &c->cluster[j], 0);
6544 node = isl_schedule_node_parent(node);
6545 node = isl_schedule_node_parent(node);
6548 return node;
6551 /* Compute a schedule for a connected dependence graph by first considering
6552 * each strongly connected component (SCC) in the graph separately and then
6553 * incrementally combining them into clusters.
6554 * Return the updated schedule node.
6556 * Initially, each cluster consists of a single SCC, each with its
6557 * own band schedule. The algorithm then tries to merge pairs
6558 * of clusters along a proximity edge until no more suitable
6559 * proximity edges can be found. During this merging, the schedule
6560 * is maintained in the individual SCCs.
6561 * After the merging is completed, the full resulting clusters
6562 * are extracted and in finish_bands_clustering,
6563 * compute_schedule_finish_band is called on each of them to integrate
6564 * the band into "node" and to continue the computation.
6566 * compute_weights initializes the weights that are used by find_proximity.
6568 static __isl_give isl_schedule_node *compute_schedule_wcc_clustering(
6569 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6571 isl_ctx *ctx;
6572 struct isl_clustering c;
6573 int i;
6575 ctx = isl_schedule_node_get_ctx(node);
6577 if (clustering_init(ctx, &c, graph) < 0)
6578 goto error;
6580 if (compute_weights(graph, &c) < 0)
6581 goto error;
6583 for (;;) {
6584 i = find_proximity(graph, &c);
6585 if (i < 0)
6586 goto error;
6587 if (i >= graph->n_edge)
6588 break;
6589 if (merge_clusters_along_edge(ctx, graph, i, &c) < 0)
6590 goto error;
6593 if (extract_clusters(ctx, graph, &c) < 0)
6594 goto error;
6596 node = finish_bands_clustering(node, graph, &c);
6598 clustering_free(ctx, &c);
6599 return node;
6600 error:
6601 clustering_free(ctx, &c);
6602 return isl_schedule_node_free(node);
6605 /* Compute a schedule for a connected dependence graph and return
6606 * the updated schedule node.
6608 * If Feautrier's algorithm is selected, we first recursively try to satisfy
6609 * as many validity dependences as possible. When all validity dependences
6610 * are satisfied we extend the schedule to a full-dimensional schedule.
6612 * Call compute_schedule_wcc_whole or compute_schedule_wcc_clustering
6613 * depending on whether the user has selected the option to try and
6614 * compute a schedule for the entire (weakly connected) component first.
6615 * If there is only a single strongly connected component (SCC), then
6616 * there is no point in trying to combine SCCs
6617 * in compute_schedule_wcc_clustering, so compute_schedule_wcc_whole
6618 * is called instead.
6620 static __isl_give isl_schedule_node *compute_schedule_wcc(
6621 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph)
6623 isl_ctx *ctx;
6625 if (!node)
6626 return NULL;
6628 ctx = isl_schedule_node_get_ctx(node);
6629 if (detect_sccs(ctx, graph) < 0)
6630 return isl_schedule_node_free(node);
6632 if (compute_maxvar(graph) < 0)
6633 return isl_schedule_node_free(node);
6635 if (need_feautrier_step(ctx, graph))
6636 return compute_schedule_wcc_feautrier(node, graph);
6638 if (graph->scc <= 1 || isl_options_get_schedule_whole_component(ctx))
6639 return compute_schedule_wcc_whole(node, graph);
6640 else
6641 return compute_schedule_wcc_clustering(node, graph);
6644 /* Compute a schedule for each group of nodes identified by node->scc
6645 * separately and then combine them in a sequence node (or as set node
6646 * if graph->weak is set) inserted at position "node" of the schedule tree.
6647 * Return the updated schedule node.
6649 * If "wcc" is set then each of the groups belongs to a single
6650 * weakly connected component in the dependence graph so that
6651 * there is no need for compute_sub_schedule to look for weakly
6652 * connected components.
6654 static __isl_give isl_schedule_node *compute_component_schedule(
6655 __isl_take isl_schedule_node *node, struct isl_sched_graph *graph,
6656 int wcc)
6658 int component;
6659 isl_ctx *ctx;
6660 isl_union_set_list *filters;
6662 if (!node)
6663 return NULL;
6664 ctx = isl_schedule_node_get_ctx(node);
6666 filters = extract_sccs(ctx, graph);
6667 if (graph->weak)
6668 node = isl_schedule_node_insert_set(node, filters);
6669 else
6670 node = isl_schedule_node_insert_sequence(node, filters);
6672 for (component = 0; component < graph->scc; ++component) {
6673 node = isl_schedule_node_child(node, component);
6674 node = isl_schedule_node_child(node, 0);
6675 node = compute_sub_schedule(node, ctx, graph,
6676 &node_scc_exactly,
6677 &edge_scc_exactly, component, wcc);
6678 node = isl_schedule_node_parent(node);
6679 node = isl_schedule_node_parent(node);
6682 return node;
6685 /* Compute a schedule for the given dependence graph and insert it at "node".
6686 * Return the updated schedule node.
6688 * We first check if the graph is connected (through validity and conditional
6689 * validity dependences) and, if not, compute a schedule
6690 * for each component separately.
6691 * If the schedule_serialize_sccs option is set, then we check for strongly
6692 * connected components instead and compute a separate schedule for
6693 * each such strongly connected component.
6695 static __isl_give isl_schedule_node *compute_schedule(isl_schedule_node *node,
6696 struct isl_sched_graph *graph)
6698 isl_ctx *ctx;
6700 if (!node)
6701 return NULL;
6703 ctx = isl_schedule_node_get_ctx(node);
6704 if (isl_options_get_schedule_serialize_sccs(ctx)) {
6705 if (detect_sccs(ctx, graph) < 0)
6706 return isl_schedule_node_free(node);
6707 } else {
6708 if (detect_wccs(ctx, graph) < 0)
6709 return isl_schedule_node_free(node);
6712 if (graph->scc > 1)
6713 return compute_component_schedule(node, graph, 1);
6715 return compute_schedule_wcc(node, graph);
6718 /* Compute a schedule on sc->domain that respects the given schedule
6719 * constraints.
6721 * In particular, the schedule respects all the validity dependences.
6722 * If the default isl scheduling algorithm is used, it tries to minimize
6723 * the dependence distances over the proximity dependences.
6724 * If Feautrier's scheduling algorithm is used, the proximity dependence
6725 * distances are only minimized during the extension to a full-dimensional
6726 * schedule.
6728 * If there are any condition and conditional validity dependences,
6729 * then the conditional validity dependences may be violated inside
6730 * a tilable band, provided they have no adjacent non-local
6731 * condition dependences.
6733 __isl_give isl_schedule *isl_schedule_constraints_compute_schedule(
6734 __isl_take isl_schedule_constraints *sc)
6736 isl_ctx *ctx = isl_schedule_constraints_get_ctx(sc);
6737 struct isl_sched_graph graph = { 0 };
6738 isl_schedule *sched;
6739 isl_schedule_node *node;
6740 isl_union_set *domain;
6742 sc = isl_schedule_constraints_align_params(sc);
6744 domain = isl_schedule_constraints_get_domain(sc);
6745 if (isl_union_set_n_set(domain) == 0) {
6746 isl_schedule_constraints_free(sc);
6747 return isl_schedule_from_domain(domain);
6750 if (graph_init(&graph, sc) < 0)
6751 domain = isl_union_set_free(domain);
6753 node = isl_schedule_node_from_domain(domain);
6754 node = isl_schedule_node_child(node, 0);
6755 if (graph.n > 0)
6756 node = compute_schedule(node, &graph);
6757 sched = isl_schedule_node_get_schedule(node);
6758 isl_schedule_node_free(node);
6760 graph_free(ctx, &graph);
6761 isl_schedule_constraints_free(sc);
6763 return sched;
6766 /* Compute a schedule for the given union of domains that respects
6767 * all the validity dependences and minimizes
6768 * the dependence distances over the proximity dependences.
6770 * This function is kept for backward compatibility.
6772 __isl_give isl_schedule *isl_union_set_compute_schedule(
6773 __isl_take isl_union_set *domain,
6774 __isl_take isl_union_map *validity,
6775 __isl_take isl_union_map *proximity)
6777 isl_schedule_constraints *sc;
6779 sc = isl_schedule_constraints_on_domain(domain);
6780 sc = isl_schedule_constraints_set_validity(sc, validity);
6781 sc = isl_schedule_constraints_set_proximity(sc, proximity);
6783 return isl_schedule_constraints_compute_schedule(sc);