use ppcg specific macro names in generated output
[ppcg.git] / gpu.c
blobd8d78f5870c10e25b55479a158588f720f500e10
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012-2013 Ecole Normale Superieure
5 * Use of this software is governed by the MIT license
7 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
8 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
9 * 91893 Orsay, France
10 * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
13 #include <assert.h>
14 #include <stdlib.h>
15 #include <string.h>
17 #include <isl/polynomial.h>
18 #include <isl/union_set.h>
19 #include <isl/aff.h>
20 #include <isl/ilp.h>
21 #include <isl/flow.h>
22 #include <isl/schedule.h>
23 #include <isl/schedule_node.h>
24 #include <isl/options.h>
25 #include <isl/ast_build.h>
27 #include "cpu.h"
28 #include "gpu.h"
29 #include "gpu_array_tile.h"
30 #include "gpu_group.h"
31 #include "gpu_tree.h"
32 #include "schedule.h"
33 #include "ppcg_options.h"
34 #include "print.h"
35 #include "util.h"
37 struct gpu_array_info;
39 /* Return the name of the outer array (of structs) accessed by "access".
41 static const char *get_outer_array_name(__isl_keep isl_map *access)
43 isl_space *space;
44 const char *name;
46 space = isl_space_range(isl_map_get_space(access));
47 while (space && isl_space_is_wrapping(space))
48 space = isl_space_domain(isl_space_unwrap(space));
49 name = isl_space_get_tuple_name(space, isl_dim_set);
50 isl_space_free(space);
52 return name;
55 /* Collect all references to the given array and store pointers to them
56 * in array->refs.
58 static void collect_references(struct gpu_prog *prog,
59 struct gpu_array_info *array)
61 int i;
62 int n;
64 n = 0;
65 for (i = 0; i < prog->n_stmts; ++i) {
66 struct gpu_stmt *stmt = &prog->stmts[i];
67 struct gpu_stmt_access *access;
69 for (access = stmt->accesses; access; access = access->next) {
70 const char *name;
71 name = get_outer_array_name(access->access);
72 if (name && !strcmp(array->name, name))
73 n++;
77 array->n_ref = n;
78 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
79 assert(array->refs);
81 n = 0;
82 for (i = 0; i < prog->n_stmts; ++i) {
83 struct gpu_stmt *stmt = &prog->stmts[i];
84 struct gpu_stmt_access *access;
86 for (access = stmt->accesses; access; access = access->next) {
87 const char *name;
88 name = get_outer_array_name(access->access);
89 if (!name || strcmp(array->name, name))
90 continue;
92 array->refs[n++] = access;
97 /* Compute and return the extent of "array", taking into account the set of
98 * accessed elements.
100 * In particular, the extent in the outer dimension is taken
101 * from "accessed", while the extents in the remaining dimensions
102 * are taken from array->extent.
104 * The extent in the outer dimension cannot be taken from array->extent
105 * because that may be unbounded. Furthermore, even if it is bounded,
106 * it may be larger than the piece of the array that is being accessed.
108 static __isl_give isl_set *compute_extent(struct pet_array *array,
109 __isl_keep isl_set *accessed)
111 int n_index;
112 isl_id *id;
113 isl_set *outer;
114 isl_set *extent;
116 extent = isl_set_copy(array->extent);
118 n_index = isl_set_dim(accessed, isl_dim_set);
119 if (n_index == 0)
120 return extent;
122 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
123 outer = isl_set_copy(accessed);
124 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
125 extent = isl_set_flat_product(outer, extent);
126 id = isl_set_get_tuple_id(accessed);
127 extent = isl_set_set_tuple_id(extent, id);
129 return extent;
132 /* Is the array "array" being extracted a read-only scalar?
134 * That is, is "array" a scalar that is never possibly written to.
135 * An array containing structures is never considered to be a scalar.
137 static int is_read_only_scalar(struct gpu_array_info *array,
138 struct gpu_prog *prog)
140 isl_set *space;
141 isl_union_map *write;
142 int empty;
144 if (array->has_compound_element)
145 return 0;
146 if (array->n_index != 0)
147 return 0;
149 write = isl_union_map_copy(prog->may_write);
150 space = isl_set_universe(isl_space_copy(array->space));
151 write = isl_union_map_intersect_range(write,
152 isl_union_set_from_set(space));
153 empty = isl_union_map_is_empty(write);
154 isl_union_map_free(write);
156 return empty;
159 /* Compute bounds on the host array "pa" based on the corresponding
160 * accessed elements in "arrays"
161 * and collect all references to the array.
162 * Store the results in "info".
164 * If the array is zero-dimensional and does not contain structures,
165 * i.e., if the array is a scalar, we check whether it is read-only.
166 * We also check whether the array is accessed at all.
168 static int extract_array_info(struct gpu_prog *prog,
169 struct gpu_array_info *info, struct pet_array *pa,
170 __isl_keep isl_union_set *arrays)
172 int i, empty;
173 const char *name;
174 int n_index;
175 isl_pw_aff **bounds;
176 isl_set *accessed, *extent;
178 n_index = isl_set_dim(pa->extent, isl_dim_set);
179 name = isl_set_get_tuple_name(pa->extent);
180 bounds = isl_alloc_array(prog->ctx, isl_pw_aff *, n_index);
181 if (!bounds)
182 return -1;
184 info->space = isl_set_get_space(pa->extent);
185 info->name = strdup(name);
186 info->n_index = n_index;
187 info->bound = bounds;
188 info->linearize = prog->scop->options->linearize_device_arrays;
190 info->type = strdup(pa->element_type);
191 info->size = pa->element_size;
192 info->local = pa->declared && !pa->exposed;
193 info->has_compound_element = pa->element_is_record;
194 info->read_only_scalar = is_read_only_scalar(info, prog);
196 accessed = isl_union_set_extract_set(arrays,
197 isl_space_copy(info->space));
198 empty = isl_set_is_empty(accessed);
199 extent = compute_extent(pa, accessed);
200 isl_set_free(accessed);
201 info->extent = extent;
202 if (empty < 0)
203 return -1;
204 info->accessed = !empty;
205 for (i = 0; i < n_index; ++i) {
206 isl_set *dom;
207 isl_local_space *ls;
208 isl_aff *one;
209 isl_pw_aff *bound;
211 dom = isl_set_copy(extent);
212 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
213 n_index - (i + 1));
214 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
215 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
216 fprintf(stderr, "unable to determine extent of '%s' "
217 "in dimension %d\n", info->name, i);
218 dom = isl_set_free(dom);
220 bound = isl_set_dim_max(dom, 0);
221 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
222 ls = isl_local_space_from_space(isl_set_get_space(dom));
223 one = isl_aff_zero_on_domain(ls);
224 one = isl_aff_add_constant_si(one, 1);
225 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
226 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
228 bounds[i] = bound;
229 if (!isl_pw_aff_is_cst(bound))
230 info->linearize = 1;
233 collect_references(prog, info);
235 return 0;
238 /* Remove independence from the order constraints "order" on array "array".
239 * Since the pairs of iterations in the filter relation of an independence
240 * are guaranteed to be completely independent by the user, there is
241 * no need to ensure that live ranges are ordered along thong pairs.
242 * We make an exception for local variables, though, as the independence
243 * guarantee does not apply to those.
245 * The order constraints are used in two places.
246 * Those on scalars are used in check_scalar_live_ranges to check if
247 * we need to force the scalar to be private. Any non-local scalar
248 * should not be forced scalar if it only appears in independent loops.
249 * Those on non-scalars are added to the coincidence constraints
250 * in compute_schedule because we do not support any array expansion.
251 * Accesses to non-local arrays should not prevent a loop from being
252 * considered coincident so we should indeed remove those constraints
253 * from the order constraints.
255 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
256 struct gpu_array_info *array, __isl_take isl_union_map *order)
258 int i;
260 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
261 struct pet_independence *pi = prog->scop->pet->independences[i];
262 if (isl_union_set_contains(pi->local, array->space))
263 continue;
265 order = isl_union_map_subtract(order,
266 isl_union_map_copy(pi->filter));
269 return order;
272 /* For each array in "prog", store the (untagged) order dependences
273 * derived from the array in array->dep_order.
274 * In particular, consider all references that access the given array
275 * and take the order dependences that have one of these references
276 * as source. (Since an order dependence relates two references to
277 * the same array, the target of these order dependences will also
278 * be one of these references.)
279 * Additionally, store the union of these array->dep_order relations
280 * for all non-scalar arrays in prog->array_order.
282 void collect_order_dependences(struct gpu_prog *prog)
284 int i;
285 isl_space *space;
286 isl_union_map *accesses;
288 space = isl_union_map_get_space(prog->read);
289 prog->array_order = isl_union_map_empty(space);
291 accesses = isl_union_map_copy(prog->scop->tagged_reads);
292 accesses = isl_union_map_union(accesses,
293 isl_union_map_copy(prog->scop->tagged_may_writes));
294 accesses = isl_union_map_universe(accesses);
295 accesses = isl_union_map_apply_range(accesses,
296 isl_union_map_copy(prog->to_outer));
298 for (i = 0; i < prog->n_array; ++i) {
299 struct gpu_array_info *array = &prog->array[i];
300 isl_set *set;
301 isl_union_set *uset;
302 isl_union_map *order;
304 set = isl_set_universe(isl_space_copy(array->space));
305 uset = isl_union_set_from_set(set);
306 uset = isl_union_map_domain(
307 isl_union_map_intersect_range(isl_union_map_copy(accesses),
308 uset));
309 order = isl_union_map_copy(prog->scop->tagged_dep_order);
310 order = isl_union_map_intersect_domain(order, uset);
311 order = isl_union_map_zip(order);
312 order = isl_union_set_unwrap(isl_union_map_domain(order));
313 order = remove_independences(prog, array, order);
314 array->dep_order = order;
316 if (gpu_array_is_scalar(array) && !array->has_compound_element)
317 continue;
319 prog->array_order = isl_union_map_union(prog->array_order,
320 isl_union_map_copy(array->dep_order));
323 isl_union_map_free(accesses);
326 /* Construct a gpu_array_info for each array referenced by prog->scop and
327 * collect them in prog->array.
329 * The sizes are based on the extents and the set of possibly accessed
330 * elements by "prog".
331 * If there are any member accesses involved, then they are first mapped
332 * to the outer arrays of structs.
334 * If we are allowing live range reordering, then also set
335 * the dep_order field. Otherwise leave it NULL.
337 static int collect_array_info(struct gpu_prog *prog)
339 int i;
340 int r = 0;
341 isl_union_set *arrays;
343 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
344 arrays = isl_union_set_union(arrays,
345 isl_union_map_range(isl_union_map_copy(prog->may_write)));
347 arrays = isl_union_set_apply(arrays,
348 isl_union_map_copy(prog->to_outer));
350 arrays = isl_union_set_coalesce(arrays);
352 prog->n_array = prog->scop->pet->n_array;
353 prog->array = isl_calloc_array(prog->ctx,
354 struct gpu_array_info, prog->n_array);
355 assert(prog->array);
356 for (i = 0; i < prog->scop->pet->n_array; ++i)
357 if (extract_array_info(prog, &prog->array[i],
358 prog->scop->pet->arrays[i], arrays) < 0)
359 r = -1;
361 isl_union_set_free(arrays);
363 if (prog->scop->options->live_range_reordering)
364 collect_order_dependences(prog);
366 return r;
369 static void free_array_info(struct gpu_prog *prog)
371 int i, j;
373 for (i = 0; i < prog->n_array; ++i) {
374 int n_index = prog->array[i].n_index;
375 free(prog->array[i].type);
376 free(prog->array[i].name);
377 for (j = 0; j < n_index; ++j)
378 isl_pw_aff_free(prog->array[i].bound[j]);
379 isl_space_free(prog->array[i].space);
380 isl_set_free(prog->array[i].extent);
381 free(prog->array[i].bound);
382 free(prog->array[i].refs);
383 isl_union_map_free(prog->array[i].dep_order);
385 free(prog->array);
388 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
389 * as an array or through a pointer reference, but as a single data element.
390 * At the moment, scalars are represented as zero-dimensional arrays.
391 * Note that the single data element may be an entire structure.
393 int gpu_array_is_scalar(struct gpu_array_info *array)
395 return array->n_index == 0;
398 /* Is "array" a read-only scalar?
400 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
402 return array->read_only_scalar;
405 /* Does "array" need to be allocated on the device?
406 * If it is a read-only scalar, then it will be passed as an argument
407 * to the kernel and therefore does not require any allocation.
408 * If this device memory is not accessed at all, then it does not
409 * need to be allocated either.
411 int gpu_array_requires_device_allocation(struct gpu_array_info *array)
413 if (gpu_array_is_read_only_scalar(array))
414 return 0;
415 if (!array->global)
416 return 0;
417 return 1;
420 /* Return the set of parameter values for which the array has a positive
421 * size in all dimensions.
422 * If the sizes are only valid for some parameter values, then those
423 * constraints are also taken into account.
425 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
427 int i;
428 isl_space *space;
429 isl_set *guard;
431 if (!array)
432 return NULL;
434 space = isl_space_params(isl_space_copy(array->space));
435 guard = isl_set_universe(space);
437 for (i = 0; i < array->n_index; ++i) {
438 isl_pw_aff *bound;
439 isl_set *guard_i, *zero;
441 bound = isl_pw_aff_copy(array->bound[i]);
442 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
443 zero = isl_pw_aff_zero_set(bound);
444 guard_i = isl_set_subtract(guard_i, zero);
445 guard = isl_set_intersect(guard, guard_i);
448 return guard;
451 /* Internal data structure for extract_size_of_type.
452 * "type" specifies the name of the space that we want to extract.
453 * "res" is used to store the subset of that space.
455 struct ppcg_extract_size_data {
456 const char *type;
457 isl_set *res;
460 /* This function is called for each set in a union_set.
461 * If the name of the set matches data->type, we store the
462 * set in data->res.
464 static isl_stat extract_size_of_type(__isl_take isl_set *size, void *user)
466 struct ppcg_extract_size_data *data = user;
467 const char *name;
469 name = isl_set_get_tuple_name(size);
470 if (name && !strcmp(name, data->type)) {
471 data->res = size;
472 return isl_stat_error;
475 isl_set_free(size);
476 return isl_stat_ok;
479 /* Given a union map { kernel[i] -> *[...] },
480 * return the range in the space called "type" for the kernel with
481 * sequence number "id".
483 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
484 const char *type, int id)
486 isl_space *space;
487 isl_set *dom;
488 isl_union_set *local_sizes;
489 struct ppcg_extract_size_data data = { type, NULL };
491 if (!sizes)
492 return NULL;
494 space = isl_union_map_get_space(sizes);
495 space = isl_space_set_from_params(space);
496 space = isl_space_add_dims(space, isl_dim_set, 1);
497 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
498 dom = isl_set_universe(space);
499 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
501 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
502 isl_union_map_copy(sizes));
503 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
504 isl_union_set_free(local_sizes);
505 return data.res;
508 /* Given a singleton set, extract the first (at most *len) elements
509 * of the single integer tuple into *sizes and update *len if needed.
511 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
513 int i;
514 int dim;
516 if (!set)
517 return;
519 dim = isl_set_dim(set, isl_dim_set);
520 if (dim < *len)
521 *len = dim;
523 for (i = 0; i < *len; ++i) {
524 isl_val *v;
526 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
527 assert(v);
529 sizes[i] = isl_val_get_num_si(v);
530 isl_val_free(v);
533 isl_set_free(set);
536 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
537 * if the option debug->dump_sizes is set.
539 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
540 int *sizes, int len)
542 int i;
543 isl_space *space;
544 isl_map *map;
546 if (!gen->options->debug->dump_sizes)
547 return;
549 space = isl_union_map_get_space(gen->used_sizes);
550 space = isl_space_set_from_params(space);
551 space = isl_space_add_dims(space, isl_dim_set, 1);
552 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
553 space = isl_space_from_domain(space);
554 space = isl_space_add_dims(space, isl_dim_out, len);
555 space = isl_space_set_tuple_name(space, isl_dim_out, type);
557 map = isl_map_universe(space);
558 map = isl_map_fix_si(map, isl_dim_in, 0, id);
559 for (i = 0; i < len; ++i)
560 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
562 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
565 /* Extract user specified "tile" sizes from the "sizes" command line option,
566 * defaulting to option->tile_size in each dimension.
567 * *tile_len contains the maximum number of tile sizes needed.
568 * Update *tile_len to the number of specified tile sizes, if any, and
569 * return a pointer to the tile sizes (or NULL on error).
570 * Add the effectively used sizes to gen->used_sizes.
572 static int *read_tile_sizes(struct gpu_gen *gen, int *tile_len)
574 int n;
575 int *tile_size;
576 isl_set *size;
578 tile_size = isl_alloc_array(gen->ctx, int, *tile_len);
579 if (!tile_size)
580 return NULL;
581 for (n = 0; n < *tile_len; ++n)
582 tile_size[n] = gen->options->tile_size;
584 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
585 read_sizes_from_set(size, tile_size, tile_len);
586 set_used_sizes(gen, "tile", gen->kernel_id, tile_size, *tile_len);
588 return tile_size;
591 /* Extract user specified "block" sizes from the "sizes" command line option,
592 * after filling in some potentially useful defaults.
594 static void read_block_sizes(struct ppcg_kernel *kernel,
595 __isl_keep isl_union_map *sizes)
597 isl_set *size;
599 if (kernel->n_block > 3)
600 kernel->n_block = 3;
601 switch (kernel->n_block) {
602 case 1:
603 kernel->block_dim[0] = 512;
604 break;
605 case 2:
606 kernel->block_dim[0] = 32;
607 kernel->block_dim[1] = 16;
608 break;
609 default:
610 kernel->block_dim[0] = 32;
611 kernel->block_dim[1] = 4;
612 kernel->block_dim[2] = 4;
613 break;
616 size = extract_sizes(sizes, "block", kernel->id);
617 read_sizes_from_set(size, kernel->block_dim, &kernel->n_block);
620 /* Extract user specified "grid" sizes from the "sizes" command line option,
621 * after filling in some potentially useful defaults.
623 static void read_grid_sizes(struct ppcg_kernel *kernel,
624 __isl_keep isl_union_map *sizes)
626 isl_set *size;
628 if (kernel->n_grid > 2)
629 kernel->n_grid = 2;
630 switch (kernel->n_grid) {
631 case 1:
632 kernel->grid_dim[0] = 32768;
633 break;
634 default:
635 kernel->grid_dim[0] = 256;
636 kernel->grid_dim[1] = 256;
637 break;
640 size = extract_sizes(sizes, "grid", kernel->id);
641 read_sizes_from_set(size, kernel->grid_dim, &kernel->n_grid);
644 /* Extract user specified grid and block sizes from the gen->sizes
645 * command line option after filling in some potentially useful defaults.
646 * Store the extracted sizes in "kernel".
647 * Add the effectively used sizes to gen->used_sizes.
649 static void read_grid_and_block_sizes(struct ppcg_kernel *kernel,
650 struct gpu_gen *gen)
652 read_block_sizes(kernel, gen->sizes);
653 read_grid_sizes(kernel, gen->sizes);
654 set_used_sizes(gen, "block", kernel->id,
655 kernel->block_dim, kernel->n_block);
656 set_used_sizes(gen, "grid", kernel->id,
657 kernel->grid_dim, kernel->n_grid);
660 static void *free_stmts(struct gpu_stmt *stmts, int n)
662 int i;
664 if (!stmts)
665 return NULL;
667 for (i = 0; i < n; ++i) {
668 struct gpu_stmt_access *access, *next;
670 for (access = stmts[i].accesses; access; access = next) {
671 next = access->next;
672 isl_id_free(access->ref_id);
673 isl_map_free(access->access);
674 isl_map_free(access->tagged_access);
675 free(access);
678 isl_id_free(stmts[i].id);
680 free(stmts);
682 return NULL;
685 /* Add parameters p[i] with identifiers "ids" to "set",
686 * with bounds to 0 <= p[i] < size[i].
688 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
689 int *size, __isl_keep isl_id_list *ids)
691 int i, len;
692 unsigned nparam;
694 len = isl_id_list_n_id(ids);
695 nparam = isl_set_dim(set, isl_dim_param);
696 set = isl_set_add_dims(set, isl_dim_param, len);
698 for (i = 0; i < len; ++i) {
699 isl_id *id;
701 id = isl_id_list_get_id(ids, i);
702 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
703 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
704 set = isl_set_upper_bound_si(set, isl_dim_param,
705 nparam + i, size[i] - 1);
708 return set;
711 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
712 * with
714 * { : 0 <= p[i] < size[i] }
716 * or an overapproximation.
718 static __isl_give isl_set *add_bounded_parameters_dynamic(
719 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
720 __isl_keep isl_id_list *ids)
722 int i, len;
723 unsigned nparam;
724 isl_space *space;
725 isl_local_space *ls;
727 len = isl_multi_pw_aff_dim(size, isl_dim_out);
728 nparam = isl_set_dim(set, isl_dim_param);
729 set = isl_set_add_dims(set, isl_dim_param, len);
731 for (i = 0; i < len; ++i) {
732 isl_id *id;
734 id = isl_id_list_get_id(ids, i);
735 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
738 space = isl_space_params(isl_set_get_space(set));
739 ls = isl_local_space_from_space(space);
740 for (i = 0; i < len; ++i) {
741 isl_pw_aff *param, *size_i, *zero;
742 isl_set *bound;
744 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
745 isl_dim_param, nparam + i);
747 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
748 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
749 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
750 set = isl_set_intersect_params(set, bound);
752 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
753 bound = isl_pw_aff_ge_set(param, zero);
754 set = isl_set_intersect_params(set, bound);
756 isl_local_space_free(ls);
758 return set;
761 /* Return the union of all tagged access relations in the group.
763 static __isl_give isl_union_map *group_tagged_access_relation(
764 struct gpu_array_ref_group *group)
766 int i;
767 isl_union_map *access;
769 access = isl_union_map_empty(isl_map_get_space(group->access));
770 for (i = 0; i < group->n_ref; ++i) {
771 isl_map *map_i;
773 map_i = isl_map_copy(group->refs[i]->tagged_access);
774 access = isl_union_map_union(access,
775 isl_union_map_from_map(map_i));
778 return access;
781 /* Return the extent of "array", recomputed from the bounds.
782 * The recomputed extent may be simpler than the original extent.
784 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
786 int i;
787 isl_id *id;
788 isl_space *space;
789 isl_local_space *ls;
790 isl_set *extent;
792 id = isl_set_get_tuple_id(array->extent);
793 space = isl_set_get_space(array->extent);
794 extent = isl_set_universe(isl_space_copy(space));
795 ls = isl_local_space_from_space(space);
796 for (i = 0; i < array->n_index; ++i) {
797 isl_pw_aff *bound;
798 isl_aff *aff;
799 isl_pw_aff *index;
800 isl_set *lt;
802 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
804 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
805 isl_dim_set, i);
806 index = isl_pw_aff_from_aff(aff);
807 bound = isl_pw_aff_copy(array->bound[i]);
808 bound = isl_pw_aff_from_range(bound);
809 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
810 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
811 isl_id_copy(id));
812 lt = isl_pw_aff_lt_set(index, bound);
813 extent = isl_set_intersect(extent, lt);
815 isl_local_space_free(ls);
816 isl_id_free(id);
818 return extent;
821 /* Return a map from the first group->shared_tile->depth dimensions
822 * of the computed schedule to the array tile in
823 * global memory that corresponds to the shared memory copy.
825 * In particular, return a map
827 * { D[i] -> A[a] }
829 * with constraints
831 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
833 * and
835 * 0 <= a <= array_size - 1 (2)
837 * Note that if some stride has been detected (i.e., when
838 * group->shared_tile->bound[i].shift is set), then a in (1) refers
839 * to the shifted and scaled down version.
841 * Constraints (1) are obtained by mapping the size constraints on the
842 * shared/private memory tile back to the access relation.
843 * Constraints (2) are obtained from the (recomputed) extent.
845 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
847 int i;
848 int n_index = group->array->n_index;
849 isl_map *tile;
850 isl_space *space;
851 isl_set *local;
852 isl_set *extent;
854 space = isl_multi_aff_get_space(group->shared_tile->tiling);
855 space = isl_space_range(space);
856 local = isl_set_universe(space);
857 for (i = 0; i < n_index; ++i) {
858 isl_val *bound;
860 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
861 bound = isl_val_copy(group->shared_tile->bound[i].size);
862 bound = isl_val_sub_ui(bound, 1);
863 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
865 local = isl_set_preimage_multi_aff(local,
866 isl_multi_aff_copy(group->shared_tile->tiling));
867 tile = isl_set_unwrap(local);
868 extent = array_extent(group->array);
869 tile = isl_map_intersect_range(tile, extent);
871 return tile;
874 /* Given a mapping "iterator_map" from the AST schedule to a domain,
875 * return the corresponding mapping from the AST schedule to
876 * to the outer kernel->copy_schedule_dim dimensions of
877 * the schedule computed by PPCG for this kernel.
879 * Note that kernel->copy_schedule_dim is at least as large as
880 * the largest depth of any array reference group associated to the kernel.
881 * This is needed as the returned schedule is used to extract a mapping
882 * to the outer tile->depth dimensions in transform_index.
884 static __isl_give isl_pw_multi_aff *compute_sched_to_copy(
885 struct ppcg_kernel *kernel, __isl_take isl_pw_multi_aff *iterator_map)
887 isl_union_pw_multi_aff *upma;
888 isl_pw_multi_aff *pma;
889 isl_space *space;
891 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
892 space = isl_space_from_domain(space);
893 space = isl_space_add_dims(space, isl_dim_out,
894 kernel->copy_schedule_dim);
896 upma = isl_union_pw_multi_aff_copy(kernel->copy_schedule);
897 pma = isl_union_pw_multi_aff_extract_pw_multi_aff(upma, space);
898 isl_union_pw_multi_aff_free(upma);
900 return isl_pw_multi_aff_pullback_pw_multi_aff(pma, iterator_map);
903 /* If max_shared_memory is not set to infinity (-1), then make
904 * sure that the total amount of shared memory required by the
905 * array reference groups mapped to shared memory by "kernel"
906 * is no larger than this maximum.
908 * We apply a greedy approach and discard (keep in global memory)
909 * those groups that would result in a total memory size that
910 * is larger than the maximum.
912 * This function should be called after any function that may
913 * affect the decision on whether to place a reference group
914 * in private, shared or global memory.
916 static void check_shared_memory_bound(struct ppcg_kernel *kernel)
918 int i, j;
919 isl_val *left, *size;
921 if (kernel->options->max_shared_memory < 0)
922 return;
924 left = isl_val_int_from_si(kernel->ctx,
925 kernel->options->max_shared_memory);
927 for (i = 0; i < kernel->n_array; ++i) {
928 struct gpu_local_array_info *local = &kernel->array[i];
930 for (j = 0; j < local->n_group; ++j) {
931 struct gpu_array_ref_group *group;
932 enum ppcg_group_access_type type;
934 group = local->groups[j];
935 type = gpu_array_ref_group_type(group);
936 if (type != ppcg_access_shared)
937 continue;
939 size = gpu_array_tile_size(group->shared_tile);
940 size = isl_val_mul_ui(size, local->array->size);
942 if (isl_val_le(size, left)) {
943 left = isl_val_sub(left, size);
944 continue;
946 isl_val_free(size);
948 group->shared_tile =
949 gpu_array_tile_free(group->shared_tile);
953 isl_val_free(left);
956 /* Mark all arrays of "kernel" that have an array reference group
957 * that is not mapped to private or shared memory as
958 * accessing the corresponding global device memory.
960 static void mark_global_arrays(struct ppcg_kernel *kernel)
962 int i, j;
964 for (i = 0; i < kernel->n_array; ++i) {
965 struct gpu_local_array_info *local = &kernel->array[i];
967 if (local->global)
968 continue;
969 for (j = 0; j < local->n_group; ++j) {
970 if (gpu_array_ref_group_tile(local->groups[j]))
971 continue;
973 local->global = 1;
974 local->array->global = 1;
975 break;
980 /* Compute a tiling for all the array reference groups in "kernel".
982 static void compute_group_tilings(struct ppcg_kernel *kernel)
984 int i, j;
986 for (i = 0; i < kernel->n_array; ++i) {
987 struct gpu_local_array_info *array = &kernel->array[i];
989 for (j = 0; j < array->n_group; ++j)
990 gpu_array_ref_group_compute_tiling(array->groups[j]);
994 /* Compute the size of a bounding box around the origin and "set",
995 * where "set" is assumed to contain only non-negative elements.
996 * In particular, compute the maximal value of "set" in each direction
997 * and add one.
999 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
1000 __isl_take isl_set *context)
1002 int i, n;
1003 isl_multi_pw_aff *mpa;
1005 context = isl_set_params(context);
1006 n = isl_set_dim(set, isl_dim_set);
1007 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
1008 for (i = 0; i < n; ++i) {
1009 isl_space *space;
1010 isl_aff *one;
1011 isl_pw_aff *bound;
1013 bound = isl_set_dim_max(isl_set_copy(set), i);
1014 bound = isl_pw_aff_coalesce(bound);
1015 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
1017 space = isl_pw_aff_get_domain_space(bound);
1018 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1019 one = isl_aff_add_constant_si(one, 1);
1020 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
1021 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
1023 isl_set_free(set);
1024 isl_set_free(context);
1026 return mpa;
1029 /* Compute the effective grid size as a list of the sizes in each dimension.
1031 * The grid size specified by the user or set by default
1032 * in read_grid_sizes() and applied by the block filter,
1033 * may be too large for the given code in the sense that
1034 * it may contain blocks that don't need to execute anything.
1035 * We therefore don't return this grid size, but instead the
1036 * smallest grid size that ensures that all blocks that actually
1037 * execute code are included in the grid.
1039 * We first extract a description of the grid, i.e., the possible values
1040 * of the block ids, from the domain elements in "domain" and
1041 * kernel->block_filter.
1042 * The block ids are parameters in kernel->block_filter.
1043 * We simply need to change them into set dimensions.
1045 * Then, for each block dimension, we compute the maximal value of the block id
1046 * and add one.
1048 static __isl_give isl_multi_pw_aff *extract_grid_size(
1049 struct ppcg_kernel *kernel, __isl_take isl_union_set *domain)
1051 int i;
1052 isl_set *grid;
1054 domain = isl_union_set_intersect(domain,
1055 isl_union_set_copy(kernel->block_filter));
1056 grid = isl_union_set_params(domain);
1057 grid = isl_set_from_params(grid);
1058 grid = isl_set_add_dims(grid, isl_dim_set, kernel->n_grid);
1059 for (i = 0; i < kernel->n_grid; ++i) {
1060 int pos;
1061 isl_id *id;
1063 id = isl_id_list_get_id(kernel->block_ids, i);
1064 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1065 isl_id_free(id);
1066 assert(pos >= 0);
1067 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1068 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1071 return extract_size(grid, isl_set_copy(kernel->context));
1074 /* Compute the size of a fixed bounding box around the origin and "set",
1075 * where "set" is assumed to contain only non-negative elements,
1076 * and store the results in "size".
1077 * In particular, compute the maximal value of "set" in each direction
1078 * and add one.
1080 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1082 int i, n;
1083 isl_local_space *ls;
1084 isl_aff *obj;
1086 n = isl_set_dim(set, isl_dim_set);
1087 ls = isl_local_space_from_space(isl_set_get_space(set));
1088 obj = isl_aff_zero_on_domain(ls);
1089 for (i = 0; i < n; ++i) {
1090 isl_val *max;
1092 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1093 max = isl_set_max_val(set, obj);
1094 size[i] = isl_val_get_num_si(max) + 1;
1095 isl_val_free(max);
1096 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1098 isl_aff_free(obj);
1099 isl_set_free(set);
1102 /* Compute the effective block size as a list of the sizes in each dimension
1103 * and store the sizes in kernel->block_dim.
1105 * The block size specified by the user or set by default
1106 * in read_block_sizes() and applied by the thread filter,
1107 * may be too large for the given code in the sense that
1108 * it may contain threads that don't need to execute anything.
1109 * We therefore update this block size in kernel->block_dim
1110 * to the smallest block size that ensures that all threads
1111 * that actually execute code are included in the block.
1113 * The possible values of the thread ids is obtained from
1114 * the domain elements "domain" and kernel->thread_filter.
1115 * The current implementation eliminates all parameters, ensuring
1116 * that the size is a fixed constant in each dimension.
1117 * In principle we could also compute parametric sizes.
1118 * We would have to make sure to project out all b%d and t%d parameters,
1119 * however.
1121 static isl_stat extract_block_size(struct ppcg_kernel *kernel,
1122 __isl_take isl_union_set *domain)
1124 int i;
1125 int nparam;
1126 isl_set *block;
1128 domain = isl_union_set_intersect(domain,
1129 isl_union_set_copy(kernel->thread_filter));
1130 block = isl_union_set_params(domain);
1131 block = isl_set_from_params(block);
1132 block = isl_set_add_dims(block, isl_dim_set, kernel->n_block);
1133 for (i = 0; i < kernel->n_block; ++i) {
1134 int pos;
1135 isl_id *id;
1137 if (!block)
1138 return isl_stat_error;
1140 id = isl_id_list_get_id(kernel->thread_ids, i);
1141 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1142 isl_id_free(id);
1143 if (pos < 0)
1144 isl_die(isl_set_get_ctx(block), isl_error_internal,
1145 "missing constraints on thread identifier",
1146 block = isl_set_free(block));
1147 block = isl_set_equate(block, isl_dim_param, pos,
1148 isl_dim_set, i);
1150 nparam = isl_set_dim(block, isl_dim_param);
1151 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1153 if (!block)
1154 return isl_stat_error;
1156 extract_fixed_size(block, kernel->block_dim);
1158 return isl_stat_ok;
1161 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1163 int i, j;
1165 if (!kernel)
1166 return NULL;
1168 isl_id_list_free(kernel->block_ids);
1169 isl_id_list_free(kernel->thread_ids);
1170 isl_multi_pw_aff_free(kernel->grid_size);
1171 isl_set_free(kernel->context);
1172 isl_union_set_free(kernel->core);
1173 isl_union_set_free(kernel->arrays);
1174 isl_space_free(kernel->space);
1175 isl_ast_node_free(kernel->tree);
1176 isl_union_set_free(kernel->block_filter);
1177 isl_union_set_free(kernel->thread_filter);
1178 isl_union_pw_multi_aff_free(kernel->copy_schedule);
1179 isl_union_set_free(kernel->sync_writes);
1181 for (i = 0; i < kernel->n_array; ++i) {
1182 struct gpu_local_array_info *array = &kernel->array[i];
1184 for (j = 0; j < array->n_group; ++j)
1185 gpu_array_ref_group_free(array->groups[j]);
1186 free(array->groups);
1188 isl_pw_aff_list_free(array->bound);
1190 free(kernel->array);
1192 for (i = 0; i < kernel->n_var; ++i) {
1193 free(kernel->var[i].name);
1194 isl_vec_free(kernel->var[i].size);
1196 free(kernel->var);
1198 free(kernel);
1200 return NULL;
1203 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1205 static void ppcg_kernel_free_wrap(void *user)
1207 struct ppcg_kernel *kernel = user;
1209 ppcg_kernel_free(kernel);
1212 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1213 struct ppcg_kernel_var *var)
1215 int j;
1216 struct gpu_array_tile *tile;
1217 isl_printer *p;
1218 char *name;
1220 var->array = group->array;
1222 var->type = gpu_array_ref_group_type(group);
1223 tile = gpu_array_ref_group_tile(group);
1225 p = isl_printer_to_str(ctx);
1226 p = gpu_array_ref_group_print_name(group, p);
1227 var->name = isl_printer_get_str(p);
1228 isl_printer_free(p);
1230 var->size = isl_vec_alloc(ctx, group->array->n_index);
1232 for (j = 0; j < group->array->n_index; ++j)
1233 var->size = isl_vec_set_element_val(var->size, j,
1234 isl_val_copy(tile->bound[j].size));
1237 static int create_kernel_vars(struct ppcg_kernel *kernel)
1239 int i, j, n;
1241 n = 0;
1242 for (i = 0; i < kernel->n_array; ++i) {
1243 struct gpu_local_array_info *array = &kernel->array[i];
1245 for (j = 0; j < array->n_group; ++j) {
1246 struct gpu_array_ref_group *group = array->groups[j];
1247 enum ppcg_group_access_type type;
1249 type = gpu_array_ref_group_type(group);
1250 if (type != ppcg_access_global)
1251 ++n;
1255 kernel->n_var = n;
1256 kernel->var = isl_calloc_array(kernel->ctx, struct ppcg_kernel_var, n);
1257 if (!kernel->var)
1258 return -1;
1260 n = 0;
1261 for (i = 0; i < kernel->n_array; ++i) {
1262 struct gpu_local_array_info *array = &kernel->array[i];
1264 for (j = 0; j < array->n_group; ++j) {
1265 struct gpu_array_ref_group *group = array->groups[j];
1266 enum ppcg_group_access_type type;
1268 type = gpu_array_ref_group_type(group);
1269 if (type == ppcg_access_global)
1270 continue;
1271 create_kernel_var(kernel->ctx, group, &kernel->var[n]);
1272 ++n;
1276 return 0;
1279 /* Replace "pa" by the zero function defined over the universe domain
1280 * in the space of "pa".
1282 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1284 isl_space *space;
1285 isl_aff *zero;
1287 space = isl_space_domain(isl_pw_aff_get_space(pa));
1288 isl_pw_aff_free(pa);
1289 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1291 return isl_pw_aff_from_aff(zero);
1294 /* The sizes of the arrays on the host that have been computed by
1295 * extract_array_info may depend on the parameters. Use the extra
1296 * constraints on the parameters that are valid at "host_domain"
1297 * to simplify these expressions and store the results in kernel->array.
1299 * We only need these localized bounds for arrays that are accessed
1300 * by the current kernel. If we have found at least one reference group
1301 * then the array is accessed by the kernel.
1303 * The resulting sizes may be functions that are nowhere defined
1304 * in case the access function cannot possibly access anything inside
1305 * the kernel for some reason. If so, they are replaced by the zero
1306 * function. Since the access function cannot actually access anything,
1307 * there is no harm in printing the array sizes as zero.
1309 static void localize_bounds(struct ppcg_kernel *kernel,
1310 __isl_keep isl_set *host_domain)
1312 int i, j;
1313 isl_set *context;
1315 context = isl_set_copy(host_domain);
1316 context = isl_set_params(context);
1318 for (i = 0; i < kernel->n_array; ++i) {
1319 struct gpu_local_array_info *local = &kernel->array[i];
1320 isl_pw_aff_list *bound;
1321 int n_index;
1323 if (local->n_group == 0)
1324 continue;
1326 n_index = local->array->n_index;
1327 bound = isl_pw_aff_list_alloc(kernel->ctx, n_index);
1329 for (j = 0; j < n_index; ++j) {
1330 isl_pw_aff *pwaff;
1331 int empty;
1333 pwaff = isl_pw_aff_copy(local->array->bound[j]);
1334 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1335 empty = isl_pw_aff_is_empty(pwaff);
1336 if (empty < 0)
1337 pwaff = isl_pw_aff_free(pwaff);
1338 else if (empty)
1339 pwaff = set_universally_zero(pwaff);
1340 bound = isl_pw_aff_list_add(bound, pwaff);
1343 local->n_index = n_index;
1344 local->bound = bound;
1346 isl_set_free(context);
1349 /* Create the array of gpu_local_array_info structures "array"
1350 * inside "kernel". The number of elements in this array is
1351 * the same as the number of arrays in "prog".
1352 * Initialize the "array" field of each local array to point
1353 * to the corresponding array in "prog".
1355 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1356 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1358 int i;
1359 isl_ctx *ctx;
1361 ctx = isl_set_get_ctx(prog->context);
1362 kernel->array = isl_calloc_array(ctx,
1363 struct gpu_local_array_info, prog->n_array);
1364 if (!kernel->array)
1365 return ppcg_kernel_free(kernel);
1366 kernel->n_array = prog->n_array;
1368 for (i = 0; i < prog->n_array; ++i)
1369 kernel->array[i].array = &prog->array[i];
1371 return kernel;
1374 /* Does "kernel" need to be passed an argument corresponding to array "i"?
1376 * The argument is only needed if the kernel accesses this device memory.
1378 int ppcg_kernel_requires_array_argument(struct ppcg_kernel *kernel, int i)
1380 return kernel->array[i].global;
1383 /* Find the element in gen->stmt that has the given "id".
1384 * Return NULL if no such gpu_stmt can be found.
1386 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1388 int i;
1390 for (i = 0; i < prog->n_stmts; ++i) {
1391 if (id == prog->stmts[i].id)
1392 break;
1395 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1398 void ppcg_kernel_stmt_free(void *user)
1400 int i;
1401 struct ppcg_kernel_stmt *stmt = user;
1403 if (!stmt)
1404 return;
1406 switch (stmt->type) {
1407 case ppcg_kernel_copy:
1408 isl_ast_expr_free(stmt->u.c.index);
1409 isl_ast_expr_free(stmt->u.c.local_index);
1410 break;
1411 case ppcg_kernel_domain:
1412 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1413 break;
1414 case ppcg_kernel_sync:
1415 break;
1418 free(stmt);
1421 /* Return the gpu_stmt_access in the list "accesses" that corresponds
1422 * to "ref_id".
1424 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1425 __isl_keep isl_id *ref_id)
1427 struct gpu_stmt_access *access;
1429 for (access = accesses; access; access = access->next)
1430 if (access->ref_id == ref_id)
1431 return access;
1433 return NULL;
1436 /* Return the index of the array called "name" in the list of arrays.
1438 static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1440 int i;
1442 for (i = 0; i < kernel->n_array; ++i)
1443 if (!strcmp(name, kernel->array[i].array->name))
1444 return i;
1446 return -1;
1449 /* Internal data structure for the index and AST expression transformation
1450 * callbacks for pet_stmt_build_ast_exprs.
1452 * "kernel" is the kernel for which are computing AST expressions and
1453 * may be NULL if we are not inside a kernel.
1454 * "accesses" is the list of gpu_stmt_access in the statement.
1455 * "iterator_map" expresses the statement iterators in terms of
1456 * the AST loop iterators.
1457 * "sched2copy" expresses the outer copy_schedule_dim dimensions of
1458 * the kernel schedule in terms of the AST loop iterators and
1459 * may be NULL if we are not inside a kernel.
1461 * The following fields are set in transform_index and used in transform_expr.
1462 * "array" is the array that is being accessed.
1463 * "global" is set if the global array is accessed (rather than
1464 * shared/private memory).
1465 * "local_array" refers to information on the array specialized
1466 * to the current kernel.
1468 struct ppcg_transform_data {
1469 struct ppcg_kernel *kernel;
1470 struct gpu_stmt_access *accesses;
1471 isl_pw_multi_aff *iterator_map;
1472 isl_pw_multi_aff *sched2copy;
1474 struct gpu_array_info *array;
1475 int global;
1476 struct gpu_local_array_info *local_array;
1479 /* Return a pointer to the gpu_array_ref_group in "local"
1480 * that contains the reference "access".
1481 * Return NULL if no such group can be found.
1483 static struct gpu_array_ref_group *find_ref_group(
1484 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1486 int i, j;
1488 for (i = 0; i < local->n_group; ++i) {
1489 struct gpu_array_ref_group *group = local->groups[i];
1491 for (j = 0; j < group->n_ref; ++j)
1492 if (group->refs[j] == access)
1493 return group;
1496 return NULL;
1499 /* Index transformation callback for pet_stmt_build_ast_exprs.
1501 * "index" expresses the array indices in terms of statement iterators
1503 * We first reformulate "index" in terms of the AST loop iterators.
1504 * Then we check if we are accessing the global array or
1505 * a shared/private copy. In particular, if we are not inside a kernel
1506 * then we must be accessing a global array.
1507 * In the former case, we simply return
1508 * the updated index. If "index" is an affine expression rather
1509 * than an array access, then we also return the updated index here.
1511 * If no reference groups have been computed for the array,
1512 * then we can only be accessing the global array.
1514 * Otherwise, we apply the tiling to the index.
1515 * This tiling is of the form
1517 * [D -> A] -> T
1519 * where D corresponds to the outer tile->depth dimensions of
1520 * the kernel schedule.
1521 * The index is of the form
1523 * L -> A
1525 * We update the tiling to refer to the AST loop iterators
1527 * [L -> A] -> T
1529 * and modify index to keep track of those iterators
1531 * L -> [L -> A]
1533 * Combining these two yields a tiled index expression in terms
1534 * of the AST loop iterators
1536 * L -> T
1538 static __isl_give isl_multi_pw_aff *transform_index(
1539 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
1540 void *user)
1542 struct ppcg_transform_data *data = user;
1543 struct gpu_stmt_access *access;
1544 struct gpu_array_ref_group *group;
1545 struct gpu_array_tile *tile;
1546 isl_pw_multi_aff *iterator_map;
1547 int i;
1548 int dim;
1549 const char *name;
1550 isl_space *space;
1551 isl_multi_pw_aff *tiling;
1552 isl_pw_multi_aff *pma;
1553 isl_multi_pw_aff *mpa;
1554 isl_pw_multi_aff *sched2depth;
1556 data->array = NULL;
1558 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
1559 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
1561 if (!data->kernel)
1562 return index;
1564 access = find_access(data->accesses, ref_id);
1565 if (!access)
1566 return index;
1567 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1568 return index;
1570 name = get_outer_array_name(access->access);
1571 i = find_array_index(data->kernel, name);
1572 if (i < 0)
1573 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
1574 "cannot find array",
1575 return isl_multi_pw_aff_free(index));
1576 data->local_array = &data->kernel->array[i];
1577 data->array = data->local_array->array;
1579 group = find_ref_group(data->local_array, access);
1580 if (!group) {
1581 data->global = 1;
1582 return index;
1585 tile = gpu_array_ref_group_tile(group);
1586 data->global = !tile;
1587 if (!tile)
1588 return index;
1590 space = isl_space_range(isl_multi_pw_aff_get_space(index));
1591 space = isl_space_map_from_set(space);
1592 pma = isl_pw_multi_aff_identity(space);
1593 sched2depth = isl_pw_multi_aff_copy(data->sched2copy);
1594 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1595 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1596 tile->depth, dim - tile->depth);
1597 pma = isl_pw_multi_aff_product(sched2depth, pma);
1598 tiling = isl_multi_pw_aff_from_multi_aff(
1599 isl_multi_aff_copy(tile->tiling));
1600 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1602 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1603 space = isl_space_map_from_set(space);
1604 mpa = isl_multi_pw_aff_identity(space);
1605 index = isl_multi_pw_aff_range_product(mpa, index);
1606 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1608 return index;
1611 /* Dereference "expr" by adding an index [0].
1612 * The original "expr" is assumed not to have any indices.
1614 * If "expr" is a member access, then the dereferencing needs
1615 * to be applied to the structure argument of this member access.
1617 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1619 isl_ctx *ctx;
1620 isl_ast_expr *arg0, *res;
1621 isl_ast_expr_list *list;
1623 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1624 if (!arg0)
1625 return isl_ast_expr_free(expr);
1626 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1627 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1628 isl_ast_expr *arg;
1630 arg = isl_ast_expr_get_op_arg(arg0, 0);
1631 arg = dereference(arg);
1632 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1633 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1635 return expr;
1637 isl_ast_expr_free(arg0);
1639 ctx = isl_ast_expr_get_ctx(expr);
1640 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1641 list = isl_ast_expr_list_from_ast_expr(res);
1642 res = isl_ast_expr_get_op_arg(expr, 0);
1643 res = isl_ast_expr_access(res, list);
1644 isl_ast_expr_free(expr);
1646 return res;
1649 /* Linearize the index expression "expr" based on the array bounds
1650 * of "array".
1652 * That is, transform expression
1654 * A[i_0][i_1]...[i_n]
1656 * to
1658 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1660 * where b_0, b_1, ..., b_n are the bounds on the array.
1662 * If the base of "expr" is a member access, then the linearization needs
1663 * to be applied to the structure argument of this member access.
1665 * In the base case, if "expr" has no arguments (other than the name of
1666 * the array), then we are passing an entire array to a function.
1667 * In this case, there is nothing to linearize.
1668 * Note that at this point an expression with no arguments can
1669 * only be an entire array because the scalar case and
1670 * the case of single struct are handled by the caller.
1672 * If the number of specified index expressions in "expr"
1673 * is smaller than the dimension of the accessed array,
1674 * then the missing i_j also do not appear in the linearized expression.
1675 * Furthermore, since such an expression does not refer to a single
1676 * element while the default linearized expression would refer to
1677 * a single element, we return the expression
1679 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
1681 * instead. Note that because of the special case handling above,
1682 * we can assume here that here that there is at least one index expression.
1684 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1685 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1687 int i, n;
1688 isl_ctx *ctx;
1689 isl_set *context;
1690 isl_ast_expr *arg0;
1691 isl_ast_expr *res;
1692 isl_ast_expr_list *list;
1693 isl_ast_build *build;
1695 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1696 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1697 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1698 isl_ast_expr *arg;
1700 arg = isl_ast_expr_get_op_arg(arg0, 0);
1701 arg = gpu_local_array_info_linearize_index(array, arg);
1702 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1703 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1705 return expr;
1707 isl_ast_expr_free(arg0);
1709 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1710 return expr;
1712 ctx = isl_ast_expr_get_ctx(expr);
1713 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
1714 build = isl_ast_build_from_context(context);
1716 n = isl_ast_expr_get_op_n_arg(expr);
1717 res = isl_ast_expr_get_op_arg(expr, 1);
1718 for (i = 1; i < array->n_index; ++i) {
1719 isl_pw_aff *bound_i;
1720 isl_ast_expr *expr_i;
1722 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
1723 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
1724 res = isl_ast_expr_mul(res, expr_i);
1726 if (i + 1 >= n)
1727 continue;
1728 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1729 res = isl_ast_expr_add(res, expr_i);
1732 isl_ast_build_free(build);
1734 if (1 + array->n_index > n) {
1735 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1736 } else {
1737 list = isl_ast_expr_list_from_ast_expr(res);
1738 res = isl_ast_expr_get_op_arg(expr, 0);
1739 res = isl_ast_expr_access(res, list);
1742 isl_ast_expr_free(expr);
1744 return res;
1747 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
1749 * If the AST expression refers to an array that is not accessed
1750 * at all, then this means the value of the expression is not used,
1751 * so we might as well print zero (NULL pointer) instead.
1753 * If the AST expression refers to a global scalar that is not
1754 * a read-only scalar, then its address was passed to the kernel and
1755 * we need to dereference it.
1757 * If the AST expression refers to an access to a global array,
1758 * then we linearize the access exploiting the bounds in data->local_array.
1760 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1761 __isl_keep isl_id *id, void *user)
1763 struct ppcg_transform_data *data = user;
1765 if (!data->array)
1766 return expr;
1767 if (!data->array->accessed) {
1768 isl_ctx *ctx;
1770 ctx = isl_ast_expr_get_ctx(expr);
1771 isl_ast_expr_free(expr);
1772 return isl_ast_expr_from_val(isl_val_zero(ctx));
1774 if (gpu_array_is_read_only_scalar(data->array))
1775 return expr;
1776 if (!data->global)
1777 return expr;
1778 if (data->array->n_index == 0)
1779 return dereference(expr);
1780 if (!data->array->linearize)
1781 return expr;
1783 return gpu_local_array_info_linearize_index(data->local_array, expr);
1786 /* This function is called for each instance of a user statement
1787 * in the kernel "kernel", identified by "gpu_stmt".
1788 * "kernel" may be NULL if we are not inside a kernel.
1790 * We attach a struct ppcg_kernel_stmt to the "node", containing
1791 * a computed AST expression for each access, through an annotation
1792 * with name "user".
1793 * These AST expressions are computed from iterator_map,
1794 * which expresses the domain
1795 * elements in terms of the generated loops, and sched2copy,
1796 * which expresses the outer copy_schedule_dim dimensions of
1797 * the kernel schedule computed by PPCG in terms of the generated loops.
1799 static __isl_give isl_ast_node *create_domain_leaf(
1800 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1801 __isl_keep isl_ast_build *build, struct gpu_stmt *gpu_stmt)
1803 struct ppcg_transform_data data;
1804 struct ppcg_kernel_stmt *stmt;
1805 isl_ctx *ctx;
1806 isl_id *id;
1807 isl_pw_multi_aff *sched2copy;
1808 isl_map *map;
1809 isl_pw_multi_aff *iterator_map;
1810 isl_union_map *schedule;
1812 if (!node)
1813 return NULL;
1814 ctx = isl_ast_node_get_ctx(node);
1816 stmt = isl_calloc_type(ctx, struct ppcg_kernel_stmt);
1817 if (!stmt)
1818 return isl_ast_node_free(node);
1820 schedule = isl_ast_build_get_schedule(build);
1821 map = isl_map_reverse(isl_map_from_union_map(schedule));
1822 iterator_map = isl_pw_multi_aff_from_map(map);
1823 if (kernel)
1824 sched2copy = compute_sched_to_copy(kernel,
1825 isl_pw_multi_aff_copy(iterator_map));
1826 else
1827 sched2copy = NULL;
1829 stmt->type = ppcg_kernel_domain;
1830 stmt->u.d.stmt = gpu_stmt;
1832 data.kernel = kernel;
1833 data.accesses = stmt->u.d.stmt->accesses;
1834 data.iterator_map = iterator_map;
1835 data.sched2copy = sched2copy;
1836 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
1837 build, &transform_index, &data,
1838 &transform_expr, &data);
1840 isl_pw_multi_aff_free(iterator_map);
1841 isl_pw_multi_aff_free(sched2copy);
1843 id = isl_id_alloc(ctx, "user", stmt);
1844 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1845 return isl_ast_node_set_annotation(node, id);
1848 /* This function is called for each statement node in the AST
1849 * for copying to or from shared/private memory.
1850 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1851 * statement to the node.
1852 * The statement name is "read" or "write", depending on whether we are
1853 * reading from global memory or writing to global memory.
1855 * The schedule is of the form
1857 * type[D -> A] -> L
1859 * where D corresponds to the outer tile->depth dimensions of
1860 * the kernel schedule, A to the global array and L to the outer
1861 * generated AST schedule.
1862 * We compute the inverse and strip off the type, resulting in
1864 * L -> [D -> A]
1866 * We combine this mapping with on the one hand the projection
1868 * [D -> A] -> A
1870 * and on the other hand the group tiling
1872 * [D -> A] -> T
1874 * resulting in
1876 * L -> A and L -> T
1878 * and store the corresponding expressions in stmt->index and stmt->local_index,
1879 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1881 static __isl_give isl_ast_node *create_access_leaf(struct ppcg_kernel *kernel,
1882 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1883 __isl_keep isl_ast_build *build)
1885 struct ppcg_kernel_stmt *stmt;
1886 struct gpu_array_tile *tile;
1887 isl_id *id;
1888 isl_ast_expr *expr;
1889 isl_space *space;
1890 isl_map *access;
1891 isl_pw_multi_aff *pma, *pma2;
1892 const char *type;
1894 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1895 if (!stmt)
1896 return isl_ast_node_free(node);
1898 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1899 type = isl_map_get_tuple_name(access, isl_dim_in);
1900 stmt->u.c.read = !strcmp(type, "read");
1901 access = isl_map_reverse(access);
1902 pma = isl_pw_multi_aff_from_map(access);
1903 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1905 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1906 space = isl_space_unwrap(space);
1907 pma2 = isl_pw_multi_aff_range_map(space);
1908 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1909 isl_pw_multi_aff_copy(pma));
1910 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1911 stmt->u.c.index = expr;
1913 tile = gpu_array_ref_group_tile(group);
1914 pma2 = isl_pw_multi_aff_from_multi_aff(
1915 isl_multi_aff_copy(tile->tiling));
1916 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1917 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1918 stmt->u.c.local_index = expr;
1920 stmt->u.c.array = group->array;
1921 stmt->u.c.local_array = group->local_array;
1922 stmt->type = ppcg_kernel_copy;
1924 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1925 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1926 return isl_ast_node_set_annotation(node, id);
1929 /* Create a synchronization ppcg_kernel_stmt and
1930 * attach it to the node "node" representing the synchronization.
1932 static __isl_give isl_ast_node *create_sync_leaf(
1933 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1934 __isl_keep isl_ast_build *build)
1936 struct ppcg_kernel_stmt *stmt;
1937 isl_id *id;
1939 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1940 if (!stmt)
1941 return isl_ast_node_free(node);
1943 stmt->type = ppcg_kernel_sync;
1944 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1945 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1946 return isl_ast_node_set_annotation(node, id);
1949 /* Internal data structure for at_domain.
1951 * "prog" represents the entire scop.
1952 * "kernel" points to the kernel to which the current schedule node
1953 * belongs. It is set by before_mark and reset by after_mark.
1954 * It may be NULL if we are outside any kernel.
1956 struct ppcg_at_domain_data {
1957 struct gpu_prog *prog;
1958 struct ppcg_kernel *kernel;
1961 /* This function is called for each instance of a user statement
1962 * in the kernel. This may be one of the original user statements
1963 * or a statement introduced by PPCG.
1965 * We first check if the statement id corresponds to a gpu statement,
1966 * which indicates the statement is an original user statement. Any statement
1967 * that is not an original user statement has been introduced by PPCG and
1968 * requires special handling.
1970 * If the user statement is one of the original user statements, then we call
1971 * create_domain_leaf. Otherwise, we check if it is a copy or synchronization
1972 * statement and call the appropriate functions. Statements that copy an array
1973 * to/from the device do not need any further treatment.
1975 static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
1976 __isl_keep isl_ast_build *build, void *user)
1978 struct ppcg_at_domain_data *data = user;
1979 struct gpu_stmt *gpu_stmt;
1980 isl_ast_expr *expr, *arg;
1981 isl_id *id;
1982 int is_sync;
1983 const char *name;
1984 void *p;
1986 expr = isl_ast_node_user_get_expr(node);
1987 arg = isl_ast_expr_get_op_arg(expr, 0);
1988 id = isl_ast_expr_get_id(arg);
1989 name = isl_id_get_name(id);
1990 p = isl_id_get_user(id);
1991 isl_ast_expr_free(expr);
1992 isl_ast_expr_free(arg);
1994 gpu_stmt = find_stmt(data->prog, id);
1995 is_sync = gpu_tree_id_is_sync(id, data->kernel);
1996 isl_id_free(id);
1998 if (gpu_stmt)
1999 return create_domain_leaf(data->kernel, node, build, gpu_stmt);
2001 if (!prefixcmp(name, "to_device_") || !prefixcmp(name, "from_device_"))
2002 return node;
2003 if (is_sync < 0)
2004 return isl_ast_node_free(node);
2005 if (!strcmp(name, "read") || !strcmp(name, "write")) {
2006 struct gpu_array_ref_group *group = p;
2007 return create_access_leaf(data->kernel, group, node, build);
2009 if (!is_sync)
2010 isl_die(data->prog->ctx, isl_error_internal,
2011 "unknown statement type",
2012 return isl_ast_node_free(node));
2013 return create_sync_leaf(data->kernel, node, build);
2016 /* Given a set of wrapped references "ref", return the corresponding
2017 * access relations based on the tagged access relations "tagged".
2019 * The elements of "ref" are of the form
2021 * [D -> R]
2023 * with D an iteration domains and R a reference.
2024 * The elements of "tagged" are of the form
2026 * [D -> R] -> A
2028 * with A an array.
2030 * Extend "tagged" to include the iteration domain in the range, i.e.,
2032 * [D -> R] -> [D -> A]
2034 * apply the result to "ref" and then unwrap the resulting set
2035 * to obtain relations of the form
2037 * D -> A
2039 static __isl_give isl_union_map *wrapped_reference_to_access(
2040 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
2042 isl_union_map *tag2access;
2044 tag2access = isl_union_map_copy(tagged);
2045 tag2access = isl_union_map_universe(tag2access);
2046 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
2047 tag2access = isl_union_map_domain_map(tag2access);
2048 tag2access = isl_union_map_range_product(tag2access, tagged);
2050 ref = isl_union_set_coalesce(ref);
2051 ref = isl_union_set_apply(ref, tag2access);
2053 return isl_union_set_unwrap(ref);
2056 /* Given an access relation "access" from one or more array reference groups,
2057 * remove those reads if ("read" is 1) or writes (if "read" is 0)
2058 * that are only needed to communicate data within
2059 * the same iteration of "sched".
2060 * "tagged" contains all tagged access relations to all
2061 * the array reference groups accessed by "access" from statement
2062 * instances scheduled by "sched".
2064 * If the access is a read then it is either an element of
2066 * live_in union (range flow)
2068 * where live_in and flow may be overapproximations, or
2069 * it reads an uninitialized value (that is not live-in because
2070 * there is an intermediate kill) or it reads a value that was
2071 * written within the same (compound) statement instance.
2072 * If the access is a write then it is either an element of
2074 * live_out union (domain flow)
2076 * or it writes a value that is never read (and is not live-out
2077 * because of an intermediate kill) or only
2078 * within the same (compound) statement instance.
2079 * In both cases, the access relation is also a subset of
2080 * the group access relation.
2082 * The cases where an uninitialized value is read or a value is written
2083 * that is never read or where the dataflow occurs within a statement
2084 * instance are also considered local and may also be removed.
2086 * Essentially, we compute the intersection of "access" with either
2088 * live_in union (range non-local-flow)
2090 * or
2092 * live_out union (domain non-local-flow)
2094 * We first construct a relation "local"
2096 * [[D -> R] -> [D' -> R']]
2098 * of pairs of domain iterations accessing the reference group
2099 * and references in the group that are coscheduled by "sched".
2101 * If this relation does not intersect the dataflow dependences,
2102 * then there is nothing we can possibly remove, unless the dataflow
2103 * dependences themselves only relate a subset of the accesses.
2104 * In particular, the accesses may not be involved in any dataflow
2105 * dependences, either because they are uninitialized reads/dead writes
2106 * or because the dataflow occurs inside a statement instance.
2108 * Since the computation below may break up the access relation
2109 * into smaller pieces, we only perform the intersection with
2110 * the non-local dependent accesses if the local pairs
2111 * intersect the dataflow dependences. Otherwise, we intersect
2112 * with the universe of the non-local dependent accesses.
2113 * This should at least remove accesses from statements that
2114 * do not participate in any dependences.
2116 * In particular, we remove the "local" dataflow dependences from
2117 * the set of all dataflow dependences, or at least those
2118 * that may contribute to a domain/range that intersects
2119 * the domain of "access".
2120 * Note that if the potential dataflow dependences are an overapproximation
2121 * of the actual dataflow dependences, then the result remains an
2122 * overapproximation of the non-local dataflow dependences.
2123 * Copying to/from global memory is only needed for the references
2124 * in the domain/range of the result or for accesses that are live out/in
2125 * for the entire scop.
2127 * We therefore map the domain/range of the "external" relation
2128 * to the corresponding access relation and take the union with
2129 * the live out/in relation.
2131 static __isl_give isl_union_map *remove_local_accesses(
2132 struct gpu_prog *prog, __isl_take isl_union_map *tagged,
2133 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2134 int read)
2136 int empty;
2137 isl_union_pw_multi_aff *tagger;
2138 isl_union_set *domain, *access_domain;
2139 isl_union_map *local, *external, *universe;
2140 isl_union_set *tag_set;
2142 if (isl_union_map_is_empty(access)) {
2143 isl_union_map_free(sched);
2144 isl_union_map_free(tagged);
2145 return access;
2148 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2149 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2150 tagger = isl_union_pw_multi_aff_intersect_domain(tagger,
2151 isl_union_set_copy(domain));
2152 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2154 local = isl_union_map_apply_range(sched,
2155 isl_union_map_reverse(isl_union_map_copy(sched)));
2156 local = isl_union_map_intersect(local,
2157 isl_union_map_copy(prog->scop->tagged_dep_flow));
2159 empty = isl_union_map_is_empty(local);
2161 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2162 universe = isl_union_map_universe(isl_union_map_copy(access));
2163 access_domain = isl_union_map_domain(universe);
2164 domain = isl_union_set_universe(domain);
2165 universe = isl_union_set_unwrap(domain);
2166 universe = isl_union_map_intersect_domain(universe, access_domain);
2167 domain = isl_union_map_wrap(universe);
2168 if (read)
2169 external = isl_union_map_intersect_range(external, domain);
2170 else
2171 external = isl_union_map_intersect_domain(external, domain);
2172 external = isl_union_map_intersect_params(external,
2173 isl_set_copy(prog->scop->context));
2174 external = isl_union_map_subtract(external, local);
2176 if (read) {
2177 tag_set = isl_union_map_range(external);
2178 external = wrapped_reference_to_access(tag_set, tagged);
2179 external = isl_union_map_union(external,
2180 isl_union_map_copy(prog->scop->live_in));
2181 } else {
2182 tag_set = isl_union_map_domain(external);
2183 external = wrapped_reference_to_access(tag_set, tagged);
2184 external = isl_union_map_union(external,
2185 isl_union_map_copy(prog->scop->live_out));
2188 if (empty < 0)
2189 external = isl_union_map_free(external);
2190 else if (empty)
2191 external = isl_union_map_universe(external);
2193 access = isl_union_map_intersect(access, external);
2195 return access;
2198 /* Given an access relation "access" from "group", remove those reads
2199 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2200 * communicate data within the same iteration of the schedule at the
2201 * position where the copying of the group is inserted.
2202 * "node" points to this position, i.e., the depth at "node"
2203 * is equal to tile->depth.
2205 * We extract a schedule that picks out the iterations of the outer
2206 * tile->depth dimensions and call remove_local_accesses.
2208 static __isl_give isl_union_map *remove_local_accesses_group(
2209 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2210 __isl_take isl_union_map *access, __isl_keep isl_schedule_node *node,
2211 int read)
2213 isl_union_map *sched, *tagged;
2215 if (isl_union_map_is_empty(access))
2216 return access;
2218 tagged = group_tagged_access_relation(group);
2219 sched = isl_schedule_node_get_prefix_schedule_relation(node);
2221 return remove_local_accesses(kernel->prog, tagged, access, sched, read);
2224 /* This function is called before the AST generator starts traversing
2225 * the schedule subtree of a node with mark "mark".
2227 * If the mark is called "kernel", store the kernel pointer in data->kernel
2228 * for use in at_domain.
2230 static int before_mark(__isl_keep isl_id *mark,
2231 __isl_keep isl_ast_build *build, void *user)
2233 struct ppcg_at_domain_data *data = user;
2235 if (!mark)
2236 return -1;
2237 if (!strcmp(isl_id_get_name(mark), "kernel"))
2238 data->kernel = isl_id_get_user(mark);
2239 return 0;
2242 /* This function is called after the AST generator has finished traversing
2243 * the schedule subtree of a mark node. "node" points to the corresponding
2244 * mark AST node.
2246 * If the mark is called "kernel", then replace "node" by a user node
2247 * that "calls" the kernel, representing the launch of the kernel.
2248 * The original "node" is stored inside the kernel object so that
2249 * it can be used to print the device code.
2250 * Note that this assumes that a kernel is only launched once.
2251 * Also clear data->kernel.
2253 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2254 __isl_keep isl_ast_build *build, void *user)
2256 isl_ctx *ctx;
2257 isl_id *id;
2258 isl_ast_expr *expr;
2259 isl_ast_expr_list *list;
2260 struct ppcg_kernel *kernel;
2261 struct ppcg_at_domain_data *data = user;
2263 ctx = isl_ast_node_get_ctx(node);
2264 id = isl_ast_node_mark_get_id(node);
2265 if (!id)
2266 return isl_ast_node_free(node);
2267 if (strcmp(isl_id_get_name(id), "kernel") || !data->kernel) {
2268 isl_id_free(id);
2269 return node;
2271 kernel = data->kernel;
2272 data->kernel = NULL;
2273 kernel->space = isl_ast_build_get_schedule_space(build);
2274 kernel->tree = isl_ast_node_mark_get_node(node);
2275 isl_ast_node_free(node);
2277 expr = isl_ast_expr_from_id(isl_id_copy(id));
2278 list = isl_ast_expr_list_alloc(ctx, 0);
2279 expr = isl_ast_expr_call(expr, list);
2280 node = isl_ast_node_alloc_user(expr);
2281 node = isl_ast_node_set_annotation(node, id);
2283 return node;
2286 static isl_bool update_depth(__isl_keep isl_schedule_node *node, void *user)
2288 int *depth = user;
2289 int node_depth;
2291 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2292 return isl_bool_true;
2293 node_depth = isl_schedule_node_get_schedule_depth(node);
2294 if (node_depth > *depth)
2295 *depth = node_depth;
2297 return isl_bool_false;
2300 /* Use isl to generate code for both the host and the device
2301 * from "schedule".
2302 * The device code is marked by "kernel" mark nodes in the schedule tree,
2303 * containing a pointer to a ppcg_kernel object.
2304 * The returned AST only contains the AST for the host code.
2305 * The ASTs for the device code are embedded in ppcg_kernel objects
2306 * attached to the leaf nodes that call "kernel".
2308 static __isl_give isl_ast_node *generate_code(struct gpu_gen *gen,
2309 __isl_take isl_schedule *schedule)
2311 struct ppcg_at_domain_data data;
2312 isl_ast_build *build;
2313 isl_ast_node *tree;
2314 isl_id_list *iterators;
2315 int depth;
2317 data.prog = gen->prog;
2318 data.kernel = NULL;
2320 depth = 0;
2321 if (isl_schedule_foreach_schedule_node_top_down(schedule, &update_depth,
2322 &depth) < 0)
2323 return NULL;
2324 build = isl_ast_build_alloc(gen->prog->ctx);
2325 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2326 build = isl_ast_build_set_iterators(build, iterators);
2327 build = isl_ast_build_set_at_each_domain(build, &at_domain, &data);
2328 build = isl_ast_build_set_before_each_mark(build, &before_mark, &data);
2329 build = isl_ast_build_set_after_each_mark(build, &after_mark, &data);
2330 if (gen->prog->scop->options->debug->dump_final_schedule)
2331 isl_schedule_dump(schedule);
2332 tree = isl_ast_build_node_from_schedule(build, schedule);
2333 isl_ast_build_free(build);
2335 return tree;
2338 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2340 if (!str)
2341 return NULL;
2342 return isl_union_map_read_from_str(ctx, str);
2345 /* Can "node" be tiled and then mapped to block and thread identifiers?
2346 * That is, is it permutable with at least one coincident dimension?
2348 static int is_permutable(__isl_keep isl_schedule_node *node)
2350 if (!node)
2351 return -1;
2353 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
2354 return 0;
2355 if (!isl_schedule_node_band_get_permutable(node))
2356 return 0;
2357 if (isl_schedule_node_band_n_member(node) < 1)
2358 return 0;
2359 if (!isl_schedule_node_band_member_get_coincident(node, 0))
2360 return 0;
2362 return 1;
2365 /* A isl_schedule_foreach_schedule_node_top_down callback
2366 * for setting *any_permutable and aborting the search
2367 * if "node" is a permutable band with coincident dimensions.
2368 * Otherwise, continue searching.
2370 static isl_bool set_permutable(__isl_keep isl_schedule_node *node, void *user)
2372 int *any_permutable = user;
2373 int permutable;
2375 permutable = is_permutable(node);
2376 if (permutable < 0)
2377 return isl_bool_error;
2378 if (!permutable)
2379 return isl_bool_true;
2381 *any_permutable = 1;
2383 return isl_bool_error;
2386 /* Does the subtree rooted at "node" have any suitably permutable band nodes?
2387 * That is, does it have any nodes that are permutable and that
2388 * have a least one coincident dimension?
2390 static int subtree_has_permutable_bands(__isl_keep isl_schedule_node *node)
2392 int any_parallelism = 0;
2394 if (isl_schedule_node_foreach_descendant_top_down(node, &set_permutable,
2395 &any_parallelism) < 0 &&
2396 !any_parallelism)
2397 return -1;
2399 return any_parallelism;
2402 /* Does "schedule" contain any permutable band with at least one coincident
2403 * member?
2405 static int has_any_permutable_node(__isl_keep isl_schedule *schedule)
2407 isl_schedule_node *root;
2408 int any_permutable;
2410 root = isl_schedule_get_root(schedule);
2411 any_permutable = subtree_has_permutable_bands(root);
2412 isl_schedule_node_free(root);
2414 return any_permutable;
2417 /* Is "node" a candidate for mapping to block and thread identifiers?
2418 * In particular, is it permutable with at least one coincident dimension?
2419 * Alternatively, does the subtree rooted at "node" not contain
2420 * any such permutable node? Filter nodes are skipped in this case,
2421 * because a band node will be inserted in front of the returned
2422 * node and this is not possible for filter nodes that are children
2423 * of set or sequence nodes.
2425 static int is_candidate(__isl_keep isl_schedule_node *node)
2427 int permutable;
2429 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
2430 return 1;
2431 permutable = is_permutable(node);
2432 if (permutable < 0 || permutable)
2433 return permutable;
2434 if (isl_schedule_node_get_type(node) == isl_schedule_node_filter)
2435 return 0;
2436 permutable = subtree_has_permutable_bands(node);
2437 if (permutable < 0)
2438 return -1;
2439 return !permutable;
2442 /* Is "node" the outermost node in its branch that can be tiled
2443 * and then mapped to block and thread identifiers?
2444 * If there are no such nodes in the subtree at "node" and
2445 * if "node" is not a filter node, then it is accepted too.
2447 static int is_outer_tilable(__isl_keep isl_schedule_node *node)
2449 int tilable;
2450 isl_schedule_node *ancestor;
2452 tilable = is_candidate(node);
2453 if (tilable < 0)
2454 return -1;
2455 if (!tilable)
2456 return 0;
2458 tilable = 0;
2459 ancestor = isl_schedule_node_copy(node);
2460 while (isl_schedule_node_has_parent(ancestor)) {
2461 ancestor = isl_schedule_node_parent(ancestor);
2463 tilable = is_candidate(ancestor);
2464 if (tilable < 0 || tilable)
2465 break;
2468 isl_schedule_node_free(ancestor);
2469 return tilable < 0 ? -1 : !tilable;
2472 /* Collect the references to all writes in "group".
2473 * Each reference is represented by a universe set in a space
2475 * [S[i,j] -> R[]]
2477 * with S[i,j] the statement instance space and R[] the array reference.
2479 static __isl_give isl_union_set *group_tagged_writes(
2480 struct gpu_array_ref_group *group)
2482 int i;
2483 isl_space *space;
2484 isl_union_set *writes;
2486 space = isl_map_get_space(group->access);
2487 writes = isl_union_set_empty(space);
2488 for (i = 0; i < group->n_ref; ++i) {
2489 isl_space *space;
2490 isl_set *writes_i;
2492 if (!group->refs[i]->write)
2493 continue;
2495 space = isl_map_get_space(group->refs[i]->tagged_access);
2496 space = isl_space_domain(space);
2497 writes_i = isl_set_universe(space);
2498 writes = isl_union_set_add_set(writes, writes_i);
2501 return writes;
2504 /* Is there any write access in "group" that requires synchronization
2505 * on a write to global memory?
2506 * We currently take into account all writes that would require
2507 * synchronization at the thread level depth, but if the copying
2508 * for this group is performed at an outer level, then we do not
2509 * actually need to take into account dependences at intermediate levels.
2511 static int any_sync_writes_in_group(struct ppcg_kernel *kernel,
2512 struct gpu_array_ref_group *group)
2514 isl_union_set *writes;
2515 int empty, disjoint;
2517 empty = isl_union_set_is_empty(kernel->sync_writes);
2518 if (empty < 0)
2519 return -1;
2520 if (empty)
2521 return 0;
2523 writes = group_tagged_writes(group);
2524 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2525 isl_union_set_free(writes);
2527 return disjoint < 0 ? -1 : !disjoint;
2530 /* Collect the references to all writes in "kernel" that write directly
2531 * to global or shared memory, i.e., that are not mapped to private memory.
2532 * Each reference is represented by a universe set in a space
2534 * [S[i,j] -> R[]]
2536 * with S[i,j] the statement instance space and R[] the array reference.
2538 static __isl_give isl_union_set *collect_non_private_tagged_writes(
2539 struct ppcg_kernel *kernel)
2541 isl_union_set *writes;
2542 int i, j;
2544 writes = isl_union_set_empty(isl_union_set_get_space(kernel->arrays));
2546 for (i = 0; i < kernel->n_array; ++i) {
2547 struct gpu_local_array_info *array = &kernel->array[i];
2549 for (j = 0; j < array->n_group; ++j) {
2550 struct gpu_array_ref_group *group = array->groups[j];
2551 enum ppcg_group_access_type type;
2552 isl_union_set *writes_ij;
2554 if (!group->write)
2555 continue;
2556 type = gpu_array_ref_group_type(group);
2557 if (type == ppcg_access_private)
2558 continue;
2559 writes_ij = group_tagged_writes(group);
2560 writes = isl_union_set_union(writes, writes_ij);
2564 return writes;
2567 /* Are there any direct writes to global memory that require
2568 * synchronization?
2570 static int any_global_or_shared_sync_writes(struct ppcg_kernel *kernel)
2572 isl_union_set *writes;
2573 int empty, disjoint;
2575 empty = isl_union_set_is_empty(kernel->sync_writes);
2576 if (empty < 0)
2577 return -1;
2578 if (empty)
2579 return 0;
2581 writes = collect_non_private_tagged_writes(kernel);
2582 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2583 isl_union_set_free(writes);
2585 return disjoint < 0 ? -1 : !disjoint;
2588 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
2589 * from the elements in "tile_size".
2591 static __isl_give isl_multi_val *construct_band_tiles_sizes(
2592 __isl_keep isl_schedule_node *node, int *tile_size)
2594 int i, n;
2595 isl_ctx *ctx;
2596 isl_space *space;
2597 isl_multi_val *mv;
2599 if (!node)
2600 return NULL;
2602 ctx = isl_schedule_node_get_ctx(node);
2603 space = isl_schedule_node_band_get_space(node);
2604 n = isl_schedule_node_band_n_member(node);
2605 mv = isl_multi_val_zero(space);
2606 for (i = 0; i < n; ++i) {
2607 isl_val *v;
2609 v = isl_val_int_from_si(ctx, tile_size[i]);
2610 mv = isl_multi_val_set_val(mv, i, v);
2613 return mv;
2616 /* Replace the partial schedule S of the band node "node" by
2618 * floor(S/f)
2620 * or
2622 * f * floor(S/f)
2624 * if scale_tile_loops is set, with f the integers in "factor".
2625 * The list that "factor" points to is assumed to contain at least
2626 * as many elements as the number of members in the band.
2628 static __isl_give isl_schedule_node *snap_band_to_sizes(
2629 __isl_take isl_schedule_node *node, int *factor,
2630 struct ppcg_options *options)
2632 isl_multi_val *mv;
2634 mv = construct_band_tiles_sizes(node, factor);
2635 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2636 if (options->scale_tile_loops)
2637 node = isl_schedule_node_band_scale(node,
2638 isl_multi_val_copy(mv));
2639 isl_multi_val_free(mv);
2641 return node;
2644 /* Tile "band" with tile size specified by "sizes".
2646 * Since the tile loops will be mapped to block ids, we forcibly
2647 * turn off tile loop scaling. We may want to enable tile loop scaling
2648 * at some later point, but then we would have to support the detection
2649 * of strides during the mapping to block ids.
2650 * Similarly, since the point loops will be mapped to thread ids,
2651 * we forcibly shift the point loops so that they start at zero.
2653 static __isl_give isl_schedule_node *tile_band(
2654 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2656 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2657 int scale_tile;
2658 int shift_point;
2660 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2661 isl_options_set_tile_scale_tile_loops(ctx, 0);
2662 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2663 isl_options_set_tile_shift_point_loops(ctx, 1);
2665 node = isl_schedule_node_band_tile(node, sizes);
2667 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2668 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2670 return node;
2673 /* Extract the set of parameter values and outer schedule dimensions
2674 * for which any statement instance
2675 * in the kernel inserted at "node" needs to be executed.
2676 * Intersect the set of parameter values derived from the host schedule
2677 * relation with the context of "prog".
2679 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2680 struct gpu_prog *prog)
2682 isl_union_map *schedule;
2683 isl_union_set *schedule_domain;
2684 isl_set *context;
2685 int empty;
2687 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2688 schedule_domain = isl_union_map_range(schedule);
2689 empty = isl_union_set_is_empty(schedule_domain);
2690 if (empty < 0) {
2691 isl_union_set_free(schedule_domain);
2692 return NULL;
2694 if (empty) {
2695 int depth;
2696 isl_space *space;
2698 space = isl_union_set_get_space(schedule_domain);
2699 isl_union_set_free(schedule_domain);
2700 space = isl_space_set_from_params(space);
2701 depth = isl_schedule_node_get_schedule_depth(node);
2702 space = isl_space_add_dims(space, isl_dim_set, depth);
2703 context = isl_set_empty(space);
2704 } else {
2705 context = isl_set_from_union_set(schedule_domain);
2707 context = isl_set_intersect_params(context,
2708 isl_set_copy(prog->context));
2710 return context;
2713 /* Return the set of outer array elements accessed by
2714 * by the statement instance in "domain" in "prog".
2716 static __isl_give isl_union_set *accessed_by_domain(
2717 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2719 isl_union_map *access;
2720 isl_union_set *arrays;
2722 access = isl_union_map_union(isl_union_map_copy(prog->read),
2723 isl_union_map_copy(prog->may_write));
2724 access = isl_union_map_intersect_domain(access, domain);
2725 arrays = isl_union_map_range(access);
2726 arrays = isl_union_set_apply(arrays,
2727 isl_union_map_copy(prog->to_outer));
2729 return arrays;
2732 /* Return the number of outer band members of the band node "node"
2733 * that are marked coincident.
2735 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2737 int i, n;
2739 n = isl_schedule_node_band_n_member(node);
2741 for (i = 0; i < n; ++i)
2742 if (!isl_schedule_node_band_member_get_coincident(node, i))
2743 break;
2745 return i;
2748 /* If the band node "node" has more than "n" members, then split off
2749 * the first "n" of them.
2751 static __isl_give isl_schedule_node *split_band(
2752 __isl_take isl_schedule_node *node, int n)
2754 int dim;
2756 dim = isl_schedule_node_band_n_member(node);
2757 if (n < dim)
2758 node = isl_schedule_node_band_split(node, n);
2760 return node;
2763 /* Scale a band node that may have been split by split_band.
2764 * "sizes" are the scaling factors for the original node.
2765 * "node" either points to the original band node, or the outer
2766 * of the two pieces after splitting.
2768 * If the number of elements in "node" is smaller than the number of
2769 * elements in "sizes", then some splitting has occurred and we split
2770 * "sizes" in the same way.
2772 static __isl_give isl_schedule_node *scale_band(
2773 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2775 int n, dim;
2777 n = isl_multi_val_dim(sizes, isl_dim_set);
2778 dim = isl_schedule_node_band_n_member(node);
2779 if (n > dim) {
2780 isl_multi_val *sizes2;
2782 sizes2 = isl_multi_val_copy(sizes);
2783 sizes = isl_multi_val_drop_dims(sizes,
2784 isl_dim_set, dim, n - dim);
2785 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2786 node = isl_schedule_node_child(node, 0);
2787 node = isl_schedule_node_band_scale(node, sizes2);
2788 node = isl_schedule_node_parent(node);
2791 return isl_schedule_node_band_scale(node, sizes);
2794 /* Return an isl_multi_aff, with as elements the parameters in "space"
2795 * that have the names specified by the elements in "names".
2796 * If (some of) these parameters do not already appear in "space",
2797 * then they are added first.
2799 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2800 __isl_keep isl_id_list *names)
2802 int i, n;
2803 isl_local_space *ls;
2804 isl_multi_aff *ma;
2806 if (!names)
2807 space = isl_space_free(space);
2809 n = isl_id_list_n_id(names);
2810 for (i = 0; i < n; ++i) {
2811 int pos;
2812 isl_id *id;
2814 id = isl_id_list_get_id(names, i);
2815 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2816 if (pos >= 0) {
2817 isl_id_free(id);
2818 continue;
2820 pos = isl_space_dim(space, isl_dim_param);
2821 space = isl_space_add_dims(space, isl_dim_param, 1);
2822 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2824 ma = isl_multi_aff_zero(isl_space_copy(space));
2825 ls = isl_local_space_from_space(isl_space_domain(space));
2826 for (i = 0; i < n; ++i) {
2827 int pos;
2828 isl_id *id;
2829 isl_aff *aff;
2831 id = isl_id_list_get_id(names, i);
2832 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2833 isl_id_free(id);
2834 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2835 isl_dim_param, pos);
2836 ma = isl_multi_aff_set_aff(ma, i, aff);
2838 isl_local_space_free(ls);
2840 return ma;
2843 /* Return constraints on the domain elements that equate a sequence of
2844 * parameters called "names", to the partial schedule
2845 * of "node" modulo the integers in "size".
2846 * The number of elements in the array "size" should be equal
2847 * to the number of elements in "names".
2848 * The number of members of the band node "node" should be smaller
2849 * than or equal to this number. If it is smaller, then the first
2850 * elements of "names" are equated to zero.
2852 static __isl_give isl_union_set *set_schedule_modulo(
2853 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
2854 int *size)
2856 int n, n_zero;
2857 isl_space *space;
2858 isl_multi_aff *ma;
2859 isl_multi_union_pw_aff *mupa, *mupa2;
2860 isl_multi_val *mv;
2861 isl_union_set *domain;
2863 if (!node)
2864 return NULL;
2865 n = isl_id_list_n_id(names);
2866 if (n == 0)
2867 return isl_schedule_node_get_universe_domain(node);
2868 n_zero = n - isl_schedule_node_band_n_member(node);
2870 mupa = isl_schedule_node_band_get_partial_schedule(node);
2871 mv = construct_band_tiles_sizes(node, size + n_zero);
2872 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
2874 space = isl_multi_union_pw_aff_get_space(mupa);
2875 space = isl_space_params(space);
2876 space = isl_space_set_from_params(space);
2877 space = isl_space_add_dims(space, isl_dim_set, n_zero);
2878 ma = isl_multi_aff_zero(space);
2880 domain = isl_schedule_node_get_universe_domain(node);
2881 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
2882 isl_union_set_copy(domain), ma);
2883 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
2885 space = isl_multi_union_pw_aff_get_space(mupa);
2886 ma = parameter_vector(space, names);
2888 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
2889 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
2891 return isl_multi_union_pw_aff_zero_union_set(mupa);
2894 /* Insert a context node at "node" introducing the block and thread
2895 * identifiers along with their bounds, which are stored in kernel->grid_size
2896 * and kernel->block_dim.
2897 * Note that the bounds on the block identifiers may implicitly impose
2898 * constraints on the parameters. A guard needs to be inserted
2899 * in the schedule tree to ensure that those bounds hold at "node".
2900 * This guard is inserted in insert_guard.
2902 static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
2903 __isl_take isl_schedule_node *node)
2905 isl_set *context;
2907 context = isl_set_universe(isl_set_get_space(kernel->context));
2909 context = add_bounded_parameters_dynamic(context,
2910 kernel->grid_size, kernel->block_ids);
2911 context = add_bounded_parameters(context,
2912 kernel->block_dim, kernel->thread_ids);
2914 node = isl_schedule_node_insert_context(node, context);
2916 return node;
2919 /* Insert a guard that eliminates kernel launches where the kernel
2920 * obviously does not have any work to do.
2922 * In particular, eliminate kernel launches where there are obviously
2923 * zero blocks.
2924 * Use the same block size constraints that are used to create the context
2925 * to ensure that all constraints implicit in the constructed context
2926 * are imposed by the guard.
2928 * Additionally, add other constraints that are valid
2929 * for each executed instance ("context"), as long as this does not result
2930 * in a disjunction.
2932 static __isl_give isl_schedule_node *insert_guard(
2933 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
2934 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
2936 unsigned nparam, n;
2937 isl_set *guard;
2938 isl_id_list *ids;
2940 guard = isl_set_copy(context);
2941 guard = isl_set_compute_divs(guard);
2942 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
2944 nparam = isl_set_dim(guard, isl_dim_param);
2945 n = isl_multi_pw_aff_dim(size, isl_dim_out);
2946 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
2947 guard = add_bounded_parameters_dynamic(guard, size, ids);
2948 isl_id_list_free(ids);
2949 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
2951 node = isl_schedule_node_insert_guard(node, guard);
2953 return node;
2956 /* Does any array reference group mapping require the band that is mapped
2957 * to threads to be unrolled?
2959 static int kernel_requires_unroll(struct ppcg_kernel *kernel)
2961 int i, j;
2963 for (i = 0; i < kernel->n_array; ++i) {
2964 struct gpu_local_array_info *array = &kernel->array[i];
2966 for (j = 0; j < array->n_group; ++j) {
2967 struct gpu_array_ref_group *group = array->groups[j];
2968 if (gpu_array_ref_group_requires_unroll(group))
2969 return 1;
2973 return 0;
2976 /* Mark the given band node "node" for unrolling by the AST generator and
2977 * then sink it to the leaves of the schedule tree.
2978 * All dimensions of "node" are assumed to be coincident, such that this
2979 * sinking is a valid operation.
2981 static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
2983 node = ppcg_set_schedule_node_type(node, isl_ast_loop_unroll);
2985 node = isl_schedule_node_band_sink(node);
2987 return node;
2990 /* Insert a synchronization node in the schedule tree of "node"
2991 * after the core computation of "kernel" at the level of the band
2992 * that is mapped to threads, except if that level is equal to
2993 * that of the band that is mapped to blocks or if there are no writes
2994 * to global or shared memory in the core computation that require
2995 * synchronization.
2996 * If there are any writes to shared memory and the shared memory
2997 * copying is performed at the same level, then synchronization
2998 * is needed between the core and the copying anyway, so we might
2999 * as well add it here. If the copying is performed at a higher
3000 * level, then different iterations of intermediate schedule dimensions
3001 * may have a different mapping from between shared memory elements and
3002 * threads, such that synchronization is required after the core.
3003 * "node" is assumed to point to the kernel node.
3005 static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
3006 __isl_take isl_schedule_node *node)
3008 int kernel_depth;
3009 int need_sync;
3011 need_sync = any_global_or_shared_sync_writes(kernel);
3012 if (need_sync < 0)
3013 return isl_schedule_node_free(node);
3014 if (!need_sync)
3015 return node;
3017 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3019 node = gpu_tree_move_down_to_thread(node, kernel->core);
3020 if (kernel_depth == isl_schedule_node_get_schedule_depth(node))
3021 return gpu_tree_move_up_to_kernel(node);
3023 node = gpu_tree_ensure_following_sync(node, kernel);
3025 node = gpu_tree_move_up_to_kernel(node);
3027 return node;
3030 /* Return a read ("read" is 1) or write access relation for "group"
3031 * with those accesses removed that are only needed to communicate data
3032 * within the subtree of the schedule rooted at "node".
3033 * Furthermore, include the prefix schedule at "node".
3034 * That is, return a relation of the form
3036 * S -> [D -> A]
3038 * with D the outer schedule dimensions at "node".
3040 static __isl_give isl_union_map *anchored_non_local_accesses(
3041 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3042 __isl_take isl_schedule_node *node, int read)
3044 isl_union_map *access;
3045 isl_union_map *prefix;
3047 access = gpu_array_ref_group_access_relation(group, read, !read);
3048 access = remove_local_accesses_group(kernel, group, access, node, read);
3049 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
3050 access = isl_union_map_range_product(prefix, access);
3052 return access;
3055 /* Given an array reference group "group", create a mapping
3057 * read[D -> A] -> [D -> A]
3059 * if "read" is set or
3061 * write[D -> A] -> [D -> A]
3063 * if "read" is not set.
3064 * D corresponds to the outer tile->depth dimensions of
3065 * the kernel schedule.
3067 static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
3068 struct gpu_array_ref_group *group, int read)
3070 struct gpu_array_tile *tile;
3071 isl_space *space;
3072 isl_id *id;
3074 tile = gpu_array_ref_group_tile(group);
3075 space = isl_space_copy(group->array->space);
3076 space = isl_space_from_range(space);
3077 space = isl_space_add_dims(space, isl_dim_in, tile->depth);
3078 space = isl_space_wrap(space);
3079 space = isl_space_map_from_set(space);
3081 id = isl_id_alloc(ctx, read ? "read" : "write", group);
3082 space = isl_space_set_tuple_id(space, isl_dim_in, id);
3084 return isl_multi_aff_identity(space);
3087 /* If any writes in "group" require synchronization, then make sure
3088 * that there is a synchronization node for "kernel" after the node
3089 * following "node" in a sequence.
3091 * If "shared" is set and no synchronization is needed for
3092 * the writes to global memory, then add synchronization before
3093 * the kernel to protect shared memory from being overwritten
3094 * by the next iteration of the core computation.
3095 * No additional synchronization is needed to protect against
3096 * the next copy into shared memory because each element of
3097 * the shared memory tile is always copied by the same thread.
3099 static __isl_give isl_schedule_node *add_group_write_sync(
3100 __isl_take isl_schedule_node *node, struct ppcg_kernel *kernel,
3101 struct gpu_array_ref_group *group, int shared)
3103 int need_sync;
3105 need_sync = any_sync_writes_in_group(kernel, group);
3106 if (need_sync < 0)
3107 return isl_schedule_node_free(node);
3108 if (need_sync) {
3109 node = isl_schedule_node_parent(node);
3110 node = isl_schedule_node_next_sibling(node);
3111 node = isl_schedule_node_child(node, 0);
3112 node = gpu_tree_ensure_following_sync(node, kernel);
3113 } else if (shared) {
3114 struct gpu_array_tile *tile;
3116 tile = gpu_array_ref_group_tile(group);
3117 node = isl_schedule_node_parent(node);
3118 node = isl_schedule_node_parent(node);
3119 node = gpu_tree_move_down_to_depth(node, tile->depth,
3120 kernel->core);
3121 node = gpu_tree_move_left_to_sync(node, kernel);
3124 return node;
3127 /* Add copy statements to the schedule tree of "node"
3128 * for reading from global memory to private memory (if "read" is set) or
3129 * for writing back from private memory to global memory
3130 * (if "read" is not set) for the array reference group "group" that
3131 * is mapped to private memory.
3132 * On input, "node" points to the kernel node, and it is moved
3133 * back there on output.
3135 * The copies are performed in the order of the array elements.
3136 * The copy statement instances include a reference to the outer
3137 * tile->depth dimensions of the kernel schedule for ease of
3138 * combining them with the group tiling.
3140 * That is, the extra schedule is of the form
3142 * type[D -> A] -> A
3144 * where D corresponds to the outer tile->depth dimensions of
3145 * the kernel schedule and A to the global array.
3146 * This schedule is unrolled because registers are not addressable.
3148 * The copying is inserted in the schedule tree through an extension
3149 * of the form
3151 * D -> type[D -> A]
3153 * where the extra domain elements type[D -> A] are those accessed
3154 * by the group.
3155 * A filter is inserted on type[D -> A] to ensure that the element
3156 * is read/written by the same thread that needs the element.
3157 * This filter is obtained by applying
3159 * S -> type[D -> A]
3161 * to the thread filter for the core statements.
3163 * The extension is inserted before the core computation in case of a read
3164 * and after the core computation in case of a write.
3165 * In the latter case, we also make sure that there is a synchronization
3166 * node after the write to global memory, unless this write is performed
3167 * at the outer level of the kernel.
3168 * In principle, this synchronization could be inserted higher
3169 * in the schedule tree depending on where the corresponding reads
3170 * from global memory are performed.
3172 static __isl_give isl_schedule_node *add_copies_group_private(
3173 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3174 __isl_take isl_schedule_node *node, int read)
3176 struct gpu_array_tile *tile;
3177 isl_union_map *access;
3178 isl_union_map *prefix;
3179 isl_union_set *domain;
3180 isl_space *space;
3181 isl_multi_aff *from_access;
3182 isl_multi_pw_aff *mpa;
3183 isl_multi_union_pw_aff *mupa;
3184 isl_schedule_node *graft;
3185 isl_union_set *filter;
3186 int kernel_depth;
3187 int empty;
3189 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3190 tile = gpu_array_ref_group_tile(group);
3191 node = gpu_tree_move_down_to_depth(node, tile->depth, kernel->core);
3193 access = anchored_non_local_accesses(kernel, group, node, read);
3194 empty = isl_union_map_is_empty(access);
3195 if (empty < 0 || empty) {
3196 isl_union_map_free(access);
3197 if (empty < 0)
3198 return isl_schedule_node_free(node);
3199 return gpu_tree_move_up_to_kernel(node);
3202 group->array->global = 1;
3203 group->local_array->global = 1;
3205 from_access = create_from_access(kernel->ctx, group, read);
3206 space = isl_space_domain(isl_multi_aff_get_space(from_access));
3207 access = isl_union_map_preimage_range_multi_aff(access, from_access);
3209 filter = isl_union_set_copy(kernel->thread_filter);
3210 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
3211 filter = isl_union_set_detect_equalities(filter);
3212 filter = isl_union_set_coalesce(filter);
3214 domain = isl_union_map_range(access);
3215 access = isl_union_set_wrapped_domain_map(domain);
3216 access = isl_union_map_reverse(access);
3217 access = isl_union_map_coalesce(access);
3218 graft = isl_schedule_node_from_extension(access);
3220 space = isl_space_map_from_set(space);
3221 mpa = isl_multi_pw_aff_identity(space);
3222 mpa = isl_multi_pw_aff_range_factor_range(mpa);
3223 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3225 graft = isl_schedule_node_child(graft, 0);
3226 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3227 graft = unroll(graft);
3229 graft = isl_schedule_node_insert_filter(graft, filter);
3231 graft = isl_schedule_node_parent(graft);
3233 if (read)
3234 node = isl_schedule_node_graft_before(node, graft);
3235 else {
3236 node = isl_schedule_node_graft_after(node, graft);
3237 if (kernel_depth < tile->depth)
3238 node = add_group_write_sync(node, kernel, group, 0);
3241 node = gpu_tree_move_up_to_kernel(node);
3243 return node;
3246 /* Add copy statements to the schedule tree of "node"
3247 * for reading from global memory to shared memory (if "read" is set) or
3248 * for writing back from shared memory to global memory
3249 * (if "read" is not set) for the array reference group "group" that
3250 * is mapped to shared memory.
3251 * On input, "node" points to the kernel node, and it is moved
3252 * back there on output.
3254 * The copies are performed in the order of the corresponding shared
3255 * memory tile.
3256 * The copy statement instances include a reference to the outer
3257 * tile->depth dimensions of the kernel schedule for ease of
3258 * combining them with the group tiling.
3260 * If we are performing a read from global memory to shared memory and
3261 * if the array involved is not a scalar, then we copy
3262 * the entire tile to shared memory. This may result in some extra
3263 * elements getting copied, but it should lead to simpler code
3264 * (which means that fewer registers may be needed) and less divergence.
3266 * Otherwise, we only copy the elements that will be read or have been written
3267 * in the kernel.
3269 * That is, the extra schedule is of the form
3271 * type[D -> A] -> T
3273 * where D corresponds to the outer tile->depth dimensions of
3274 * the kernel schedule, A to the global array and T is the corresponding
3275 * shared memory tile.
3277 * The copying is inserted in the schedule tree through an extension
3278 * of the form
3280 * D -> type[D -> A]
3282 * where the extra domain elements type[D -> A] are those accessed
3283 * by the group. In the case of read from a non-scalar, this set
3284 * is replaced by the entire shared memory tile.
3286 * A filter is inserted on type[D -> A] to map the copy instances
3287 * to the threads. In particular, the thread identifiers are
3288 * equated to the position inside the shared memory tile (T)
3289 * modulo the block size.
3290 * We try to align the innermost tile dimension with the innermost
3291 * thread identifier (x) as a heuristic to improve coalescing.
3292 * In particular, if the dimension of the tile is greater than
3293 * the dimension of the block, then the schedule mapping to the tile
3294 * is broken up into two pieces and the filter is applied to the inner part.
3295 * If, on the other hand, the dimension of the tile is smaller than
3296 * the dimension of the block, then the initial thread identifiers
3297 * are equated to zero and the remaining thread identifiers are
3298 * matched to the memory tile.
3300 * The extension is inserted before the core computation in case of a read
3301 * and after the core computation in case of a write.
3302 * In the case of a read, we first need to make sure there is some
3303 * synchronization before the core computation such that we can put the read
3304 * from global memory to shared memory before that synchronization.
3305 * This ensures that all threads have finished copying into shared memory
3306 * before the shared memory is used.
3307 * We also need to make sure that there is a synchronization node after
3308 * the core computation to ensure that the next load into shared memory
3309 * only happens after all data has been used. There is no need for
3310 * this synchronization if we are at the outer level since then there
3311 * won't be a next load.
3312 * In the case of a write, we need to make sure there is some synchronization
3313 * after the core computation such taht we can put the write from shared
3314 * memory to global memory after that synchronization.
3315 * Unless we are at the outer level, we also need a synchronization node
3316 * after the write to ensure the data is saved to global memory
3317 * before the next iteration write to the same shared memory.
3318 * It also makes sure the data has arrived in global memory before
3319 * it is read in a subsequent iteration.
3321 static __isl_give isl_schedule_node *add_copies_group_shared(
3322 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3323 __isl_take isl_schedule_node *node, int read)
3325 struct gpu_array_tile *tile;
3326 isl_union_map *access;
3327 isl_union_set *domain;
3328 isl_union_set *sync;
3329 isl_multi_aff *ma;
3330 isl_multi_aff *from_access;
3331 isl_multi_pw_aff *mpa;
3332 isl_multi_union_pw_aff *mupa;
3333 isl_schedule_node *graft;
3334 isl_union_set *filter;
3335 int skip;
3336 int kernel_depth;
3337 int empty;
3339 tile = gpu_array_ref_group_tile(group);
3340 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3341 node = gpu_tree_move_down_to_depth(node, tile->depth, kernel->core);
3343 access = anchored_non_local_accesses(kernel, group, node, read);
3344 empty = isl_union_map_is_empty(access);
3345 if (empty < 0 || empty) {
3346 isl_union_map_free(access);
3347 if (empty < 0)
3348 return isl_schedule_node_free(node);
3349 return gpu_tree_move_up_to_kernel(node);
3352 group->array->global = 1;
3353 group->local_array->global = 1;
3355 from_access = create_from_access(kernel->ctx, group, read);
3357 ma = isl_multi_aff_copy(tile->tiling);
3358 ma = isl_multi_aff_pullback_multi_aff(ma,
3359 isl_multi_aff_copy(from_access));
3360 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3361 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3363 domain = isl_union_map_range(access);
3365 if (read && !gpu_array_is_scalar(group->array)) {
3366 isl_map *map;
3367 isl_union_set_free(domain);
3368 map = group_tile(group);
3369 domain = isl_union_set_from_set(isl_map_wrap(map));
3372 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3373 access = isl_union_set_wrapped_domain_map(domain);
3374 access = isl_union_map_reverse(access);
3375 access = isl_union_map_coalesce(access);
3376 graft = isl_schedule_node_from_extension(access);
3378 graft = isl_schedule_node_child(graft, 0);
3380 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3382 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3383 graft = isl_schedule_node_band_split(graft,
3384 tile->n - kernel->n_block);
3385 graft = isl_schedule_node_child(graft, 0);
3387 if (tile->n < kernel->n_block)
3388 skip = kernel->n_block - tile->n;
3389 else
3390 skip = 0;
3391 filter = set_schedule_modulo(graft, kernel->thread_ids,
3392 kernel->block_dim);
3393 if (!kernel->options->wrap)
3394 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3395 kernel->options);
3396 if (tile->n > kernel->n_block && kernel->n_block > 0)
3397 graft = isl_schedule_node_parent(graft);
3398 graft = isl_schedule_node_insert_filter(graft, filter);
3400 while (graft && isl_schedule_node_has_parent(graft))
3401 graft = isl_schedule_node_parent(graft);
3403 if (read) {
3404 if (kernel_depth < tile->depth)
3405 node = gpu_tree_ensure_sync_after_core(node, kernel);
3406 node = gpu_tree_move_left_to_sync(node, kernel);
3407 node = isl_schedule_node_graft_before(node, graft);
3408 } else {
3409 node = gpu_tree_move_right_to_sync(node, kernel);
3410 node = isl_schedule_node_graft_after(node, graft);
3411 if (kernel_depth < tile->depth)
3412 node = add_group_write_sync(node, kernel, group, 1);
3415 node = gpu_tree_move_up_to_kernel(node);
3417 return node;
3420 /* Check whether the array reference group "group" is mapped to
3421 * private or shared memory and, if so,
3422 * add copy statements to the schedule tree of "node"
3423 * for reading from global memory to private or shared memory
3424 * (if "read" is set) or for writing back from private or shared memory
3425 * to global memory (if "read" is not set) for this group.
3426 * On input, "node" points to the kernel node, and it is moved
3427 * back there on output.
3429 static __isl_give isl_schedule_node *add_copies_group(
3430 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3431 __isl_take isl_schedule_node *node, int read)
3433 enum ppcg_group_access_type type;
3435 type = gpu_array_ref_group_type(group);
3436 if (type == ppcg_access_private)
3437 return add_copies_group_private(kernel, group, node, read);
3438 if (type == ppcg_access_shared)
3439 return add_copies_group_shared(kernel, group, node, read);
3440 return node;
3443 /* For each array reference group that is mapped to private or shared memory,
3444 * add copy statements to the schedule tree of "node"
3445 * for reading from global memory to private or shared memory
3446 * and for writing back.
3447 * On input, "node" points to the kernel node, and it is moved
3448 * back there on output.
3450 static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3451 __isl_take isl_schedule_node *node)
3453 int i, j;
3455 for (i = 0; i < kernel->n_array; ++i) {
3456 struct gpu_local_array_info *array = &kernel->array[i];
3458 for (j = 0; j < array->n_group; ++j) {
3459 struct gpu_array_ref_group *group = array->groups[j];
3461 node = add_copies_group(kernel, group, node, 1);
3462 if (!node)
3463 return NULL;
3464 node = add_copies_group(kernel, group, node, 0);
3465 if (!node)
3466 return NULL;
3470 return node;
3473 /* Mark all dimensions in the current band node atomic.
3475 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3477 return ppcg_set_schedule_node_type(node, isl_ast_loop_atomic);
3480 /* Mark "node" atomic, if it is a band node.
3481 * Do the same for all ancestors.
3482 * Return a pointer to "node" (in the updated schedule tree).
3484 static __isl_give isl_schedule_node *atomic_ancestors(
3485 __isl_take isl_schedule_node *node)
3487 int pos;
3489 if (!node)
3490 return NULL;
3491 if (!isl_schedule_node_has_parent(node))
3492 return node;
3494 pos = isl_schedule_node_get_child_position(node);
3495 node = isl_schedule_node_parent(node);
3496 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3497 node = atomic(node);
3498 node = atomic_ancestors(node);
3499 node = isl_schedule_node_child(node, pos);
3501 return node;
3504 /* Collect all write references that require synchronization.
3505 * "node" is assumed to point to the kernel node.
3506 * Each reference is represented by a universe set in a space
3508 * [S[i,j] -> R[]]
3510 * with S[i,j] the statement instance space and R[] the array reference.
3512 * This function should be called before block and thread filters are added.
3514 * Synchronization is needed after a write if there is a subsequent read
3515 * within the same block that may not be performed by the same thread.
3516 * There should not be any dependences between different blocks,
3517 * so we start with the flow dependences within the same kernel invocation
3518 * and we subtract from these those dependences that are mapped
3519 * to the same iteration of the bands where synchronization is inserted.
3520 * We do not remove pairs of instances that are known to map to
3521 * the same thread across different iterations of the intermediate
3522 * bands because the read may be performed by a different thread
3523 * than the one that needs the value if shared memory is involved.
3525 * We also consider all pairs of possible writes that access the same
3526 * memory location and that may be mapped to the same block but not
3527 * to the same iteration of the intermediate bands.
3528 * In theory, it would be possible for one thread to still be in
3529 * a previous iteration of a loop in these bands.
3530 * A write to global memory in this delayed thread could then overwrite
3531 * a write from another thread that has already moved on to
3532 * the next iteration.
3534 * After computing the above writes paired off with reads or writes
3535 * that depend on them, we project onto the domain writes.
3536 * Sychronization is needed after writes to global memory
3537 * through these references.
3539 static __isl_give isl_union_set *compute_sync_writes(
3540 struct ppcg_kernel *kernel, __isl_keep isl_schedule_node *node)
3542 isl_union_map *local;
3543 isl_union_map *may_writes, *shared_access;
3544 isl_union_map *kernel_prefix, *thread_prefix;
3545 isl_union_map *equal;
3546 isl_union_set *wrap;
3547 isl_union_set *domain;
3549 domain = isl_schedule_node_get_universe_domain(node);
3550 kernel_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3551 node = isl_schedule_node_copy(node);
3552 node = gpu_tree_move_down_to_thread(node, kernel->core);
3553 thread_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3554 isl_schedule_node_free(node);
3556 may_writes = isl_union_map_copy(kernel->prog->scop->tagged_may_writes);
3557 may_writes = isl_union_map_curry(may_writes);
3558 may_writes = isl_union_map_intersect_domain(may_writes, domain);
3559 may_writes = isl_union_map_uncurry(may_writes);
3560 shared_access = isl_union_map_copy(may_writes);
3561 shared_access = isl_union_map_apply_range(shared_access,
3562 isl_union_map_reverse(may_writes));
3564 local = isl_union_map_copy(kernel->prog->scop->tagged_dep_flow);
3565 local = isl_union_map_union(local, shared_access);
3566 local = isl_union_map_zip(local);
3568 equal = isl_union_map_apply_range(kernel_prefix,
3569 isl_union_map_reverse(isl_union_map_copy(kernel_prefix)));
3570 wrap = isl_union_map_wrap(equal);
3571 local = isl_union_map_intersect_domain(local, wrap);
3572 equal = isl_union_map_apply_range(thread_prefix,
3573 isl_union_map_reverse(isl_union_map_copy(thread_prefix)));
3574 wrap = isl_union_map_wrap(equal);
3575 local = isl_union_map_subtract_domain(local, wrap);
3577 local = isl_union_map_zip(local);
3578 local = isl_union_map_universe(local);
3580 return isl_union_map_domain(local);
3583 /* Group the domain elements into a single space, named kernelX,
3584 * with X the kernel sequence number "kernel_id".
3586 static __isl_give isl_schedule_node *group_statements(
3587 __isl_take isl_schedule_node *node, int kernel_id)
3589 char buffer[20];
3590 isl_id *id;
3592 if (!node)
3593 return NULL;
3595 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3596 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3597 return isl_schedule_node_group(node, id);
3600 /* Create a ppcg_kernel representing the domain instances that reach "node"
3601 * and insert a mark node pointing to the ppcg_kernel before "node".
3602 * The band that "node" points to is the band that needs to be mapped
3603 * to block identifiers. The band that needs to be mapped to thread
3604 * identifiers should be marked by a "thread" mark by the caller.
3605 * This mark is removed by this function.
3606 * If "scale" is set, then the band that "node" points to is scaled
3607 * by "sizes".
3609 * Mark all outer band nodes as atomic to ensure each kernel is only
3610 * scheduled once.
3611 * If the domain elements that reach "node" live in more than one space,
3612 * then group the domain elements into a single space, named kernelX,
3613 * with X the kernel sequence number.
3615 * Insert a guard node governing the kernel node to ensure that
3616 * no kernels with zero blocks are launched.
3618 * Insert a context node describing the block and thread
3619 * identifiers inside the kernel mark.
3620 * The context node needs to be inserted after the effective block size
3621 * has been determined such that the bounds on the thread identifiers
3622 * would reflect the effective block size.
3623 * Insert a filter node inside the context node mapping the statement
3624 * instances to block identifiers. In particular, the block identifiers
3625 * are equated to the partial schedule of band that was marked for mapping
3626 * to blocks modulo the grid size.
3627 * Insert a filter node inside the "thread" mark mapping the statement
3628 * instances to thread identifiers. In particular, the thread identifiers
3629 * are equated to the partial schedule of band that was marked for mapping
3630 * to threads modulo the block size.
3632 * Compute array reference groups for all arrays, set the local
3633 * array bounds based on the set of domain instances that reach
3634 * the kernel node, check the total amount of shared memory used
3635 * and compute all group tilings.
3636 * The array reference groups are computed after the block filter
3637 * has been inserted because it affects the mapping to shared or
3638 * private memory. This computation also requires the thread filter
3639 * (in the ppcg_kernel object), but this thread filter should not
3640 * have been added to the schedule tree yet since the computation
3641 * requires the schedule of the band that needs to be mapped to
3642 * threads before the privatization is applied.
3644 * If any array reference group requires the band mapped to threads
3645 * to be unrolled, then we perform the required unrolling.
3647 * We save a copy of the schedule that may influence the mappings
3648 * to shared or private memory in kernel->copy_schedule.
3650 * Finally, we add synchronization and copy statements to the schedule tree,
3651 * remove the "thread" mark and create representations for the local
3652 * variables in the kernel.
3654 * We keep a copy of the isl_id that points to the kernel to ensure
3655 * that the kernel does not get destroyed if the schedule node
3656 * is freed due to some error condition.
3658 static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
3659 __isl_take isl_schedule_node *node, int scale,
3660 __isl_keep isl_multi_val *sizes)
3662 struct ppcg_kernel *kernel;
3663 isl_id *id;
3664 isl_schedule_node *node_thread;
3665 isl_union_map *host_schedule;
3666 isl_set *host_domain;
3667 isl_union_set *domain;
3668 int single_statement;
3670 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3671 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3672 if (!kernel)
3673 return isl_schedule_node_free(node);
3675 domain = isl_schedule_node_get_domain(node);
3676 single_statement = isl_union_set_n_set(domain) == 1;
3678 kernel->ctx = gen->ctx;
3679 kernel->prog = gen->prog;
3680 kernel->options = gen->options;
3681 kernel->context = extract_context(node, gen->prog);
3682 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3683 kernel->arrays = accessed_by_domain(isl_union_set_copy(domain),
3684 gen->prog);
3685 kernel->n_grid = n_outer_coincidence(node);
3686 node_thread = isl_schedule_node_copy(node);
3687 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3688 node_thread = isl_schedule_node_child(node_thread, 0);
3689 kernel->n_block = n_outer_coincidence(node_thread);
3690 isl_schedule_node_free(node_thread);
3691 kernel->id = gen->kernel_id++;
3692 read_grid_and_block_sizes(kernel, gen);
3694 kernel->sync_writes = compute_sync_writes(kernel, node);
3696 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3697 host_domain = isl_set_from_union_set(isl_union_map_range(
3698 host_schedule));
3700 node = atomic_ancestors(node);
3702 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3703 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3704 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3706 if (!single_statement)
3707 node = group_statements(node, kernel->id);
3709 node = isl_schedule_node_child(node, 0);
3710 node = split_band(node, kernel->n_grid);
3711 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3712 kernel->n_grid, "b");
3713 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3714 kernel->grid_dim);
3715 kernel->grid_size = extract_grid_size(kernel,
3716 isl_union_set_copy(domain));
3717 if (!kernel->options->wrap)
3718 node = snap_band_to_sizes(node, kernel->grid_dim,
3719 kernel->options);
3720 if (scale)
3721 node = scale_band(node, isl_multi_val_copy(sizes));
3722 node = isl_schedule_node_parent(node);
3723 if (!single_statement)
3724 node = isl_schedule_node_parent(node);
3725 node = insert_guard(node, kernel->context, kernel->grid_size,
3726 gen->prog->scop);
3727 node = gpu_tree_move_down_to_thread(node, kernel->core);
3728 node = isl_schedule_node_child(node, 0);
3729 node = split_band(node, kernel->n_block);
3730 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3731 kernel->n_block, "t");
3732 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3733 kernel->block_dim);
3734 if (extract_block_size(kernel, domain) < 0)
3735 node = isl_schedule_node_free(node);
3737 node = gpu_tree_move_up_to_kernel(node);
3738 node = isl_schedule_node_child(node, 0);
3739 node = insert_context(kernel, node);
3740 node = isl_schedule_node_child(node, 0);
3741 node = isl_schedule_node_insert_filter(node,
3742 isl_union_set_copy(kernel->block_filter));
3744 node = gpu_tree_move_up_to_kernel(node);
3746 if (gpu_group_references(kernel, node) < 0)
3747 node = isl_schedule_node_free(node);
3748 localize_bounds(kernel, host_domain);
3749 isl_set_free(host_domain);
3751 check_shared_memory_bound(kernel);
3752 mark_global_arrays(kernel);
3753 compute_group_tilings(kernel);
3755 node = gpu_tree_move_down_to_thread(node, kernel->core);
3756 node = isl_schedule_node_child(node, 0);
3757 if (!kernel->options->wrap)
3758 node = snap_band_to_sizes(node, kernel->block_dim,
3759 kernel->options);
3760 node = isl_schedule_node_insert_filter(node,
3761 isl_union_set_copy(kernel->thread_filter));
3762 if (kernel_requires_unroll(kernel)) {
3763 node = isl_schedule_node_child(node, 0);
3764 node = unroll(node);
3767 node = gpu_tree_move_up_to_thread(node);
3768 kernel->copy_schedule_dim = isl_schedule_node_get_schedule_depth(node);
3769 kernel->copy_schedule =
3770 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3772 node = gpu_tree_move_up_to_kernel(node);
3774 node = add_sync(kernel, node);
3775 node = add_copies(kernel, node);
3777 node = gpu_tree_move_down_to_thread(node, kernel->core);
3778 node = isl_schedule_node_delete(node);
3780 node = gpu_tree_move_up_to_kernel(node);
3782 if (create_kernel_vars(kernel) < 0)
3783 node = isl_schedule_node_free(node);
3785 if (!single_statement)
3786 node = isl_schedule_node_parent(node);
3787 node = isl_schedule_node_parent(node);
3789 isl_id_free(id);
3790 return node;
3793 /* Insert a zero-dimensional permutable band at "node".
3795 static __isl_give isl_schedule_node *insert_empty_permutable_band(
3796 __isl_take isl_schedule_node *node)
3798 isl_space *space;
3799 isl_schedule *schedule;
3800 isl_union_set *domain;
3801 isl_multi_union_pw_aff *mupa;
3803 schedule = isl_schedule_node_get_schedule(node);
3804 domain = isl_schedule_get_domain(schedule);
3805 space = isl_union_set_get_space(domain);
3806 isl_union_set_free(domain);
3807 isl_schedule_free(schedule);
3809 space = isl_space_set_from_params(space);
3810 mupa = isl_multi_union_pw_aff_zero(space);
3811 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3812 node = isl_schedule_node_band_set_permutable(node, 1);
3814 return node;
3817 /* If "node" is the outermost permutable band that can be mapped to block and
3818 * thread identifiers in its branch (or the root of a subtree with
3819 * no such outer bands),
3820 * then mark the band as such, attaching a ppcg_kernel to the mark.
3822 * If "node" is the root of a subtree without permutable bands,
3823 * then insert a zero-dimensional permutable band such that
3824 * we can assume that "node" always points to a band node.
3825 * This includes the case where "node" already points to a band node,
3826 * but one without any coincident dimension. In this case,
3827 * the extra node ensures that this original node does not get tiled.
3829 * Tile "node" using user specified tile sizes, after splitting the band
3830 * if the number of specified tile sizes is smaller than the dimension
3831 * of the band. Mark the point band of this tiling as the band that
3832 * needs to be mapped to threads.
3833 * Create a kernel representing the domain instances that reach "node" and
3834 * insert a mark node pointing to the ppcg_kernel before the band node.
3836 static __isl_give isl_schedule_node *mark_outer_permutable(
3837 __isl_take isl_schedule_node *node, void *user)
3839 struct gpu_gen *gen = user;
3840 int outer;
3841 int scale;
3842 int tile_len;
3843 int *tile_size;
3844 isl_id *id;
3845 isl_multi_val *sizes;
3847 outer = is_outer_tilable(node);
3848 if (outer < 0)
3849 return isl_schedule_node_free(node);
3850 if (!outer)
3851 return node;
3853 if (isl_schedule_node_get_type(node) != isl_schedule_node_band ||
3854 !isl_schedule_node_band_member_get_coincident(node, 0))
3855 node = insert_empty_permutable_band(node);
3857 tile_len = isl_schedule_node_band_n_member(node);
3858 tile_size = read_tile_sizes(gen, &tile_len);
3859 if (!tile_size)
3860 return isl_schedule_node_free(node);
3861 if (tile_len < isl_schedule_node_band_n_member(node))
3862 node = isl_schedule_node_band_split(node, tile_len);
3863 sizes = construct_band_tiles_sizes(node, tile_size);
3864 node = tile_band(node, isl_multi_val_copy(sizes));
3865 node = isl_schedule_node_child(node, 0);
3866 id = isl_id_alloc(gen->ctx, "thread", NULL);
3867 node = isl_schedule_node_insert_mark(node, id);
3868 node = isl_schedule_node_parent(node);
3870 scale = gen->options->scale_tile_loops;
3871 node = create_kernel(gen, node, scale, sizes);
3872 isl_multi_val_free(sizes);
3873 free(tile_size);
3875 return node;
3878 /* Given a set or sequence node, return the union the filters of either all
3879 * (if "only_initial" is not set) or the initial (if "only_initial" is set)
3880 * direct subtrees that do not contain any suitably permutable bands
3881 * (according to subtree_has_permutable_bands).
3883 static __isl_give isl_union_set *get_non_parallel_subtree_filters(
3884 __isl_keep isl_schedule_node *node, int only_initial)
3886 isl_space *space;
3887 isl_union_set *filter;
3888 int i, n;
3890 n = isl_schedule_node_n_children(node);
3891 if (n < 0)
3892 return NULL;
3894 node = isl_schedule_node_copy(node);
3895 node = isl_schedule_node_child(node, 0);
3896 filter = isl_schedule_node_filter_get_filter(node);
3897 node = isl_schedule_node_parent(node);
3898 space = isl_union_set_get_space(filter);
3899 isl_union_set_free(filter);
3900 filter = isl_union_set_empty(space);
3902 for (i = 0; i < n; ++i) {
3903 int parallelism;
3905 node = isl_schedule_node_child(node, i);
3906 parallelism = subtree_has_permutable_bands(node);
3907 if (parallelism < 0) {
3908 filter = isl_union_set_free(filter);
3909 } else if (!parallelism) {
3910 isl_union_set *filter_i;
3911 filter_i = isl_schedule_node_filter_get_filter(node);
3912 filter = isl_union_set_union(filter, filter_i);
3913 } else if (only_initial)
3914 break;
3915 node = isl_schedule_node_parent(node);
3918 isl_schedule_node_free(node);
3920 return filter;
3923 /* Given a set or sequence node, return the union of the filters of
3924 * the direct subtrees that do not contain any suitably permutable bands
3925 * (according to subtree_has_permutable_bands).
3927 static __isl_give isl_union_set *get_all_non_parallel_subtree_filters(
3928 __isl_keep isl_schedule_node *node)
3930 return get_non_parallel_subtree_filters(node, 0);
3933 /* Given a set or sequence node, return the union of the filters of
3934 * the initial direct subtrees that do not contain any suitably permutable
3935 * bands (according to subtree_has_permutable_bands).
3937 static __isl_give isl_union_set *get_initial_non_parallel_subtree_filters(
3938 __isl_keep isl_schedule_node *node)
3940 return get_non_parallel_subtree_filters(node, 1);
3943 /* Mark all variables that are accessed by the statement instances in "domain"
3944 * and that are local to "prog" as requiring a declaration in the host code.
3946 static int declare_accessed_local_variables(struct gpu_prog *prog,
3947 __isl_keep isl_union_set *domain)
3949 isl_union_set *arrays;
3950 int i;
3952 if (!ppcg_scop_any_hidden_declarations(prog->scop))
3953 return 0;
3954 arrays = accessed_by_domain(isl_union_set_copy(domain), prog);
3956 for (i = 0; i < prog->n_array; ++i) {
3957 isl_space *space;
3958 isl_set *set;
3959 int empty;
3961 if (!prog->array[i].local)
3962 continue;
3963 space = isl_set_get_space(prog->array[i].extent);
3964 set = isl_union_set_extract_set(arrays, space);
3965 empty = isl_set_plain_is_empty(set);
3966 isl_set_free(set);
3967 if (empty < 0)
3968 goto error;
3969 if (!empty)
3970 prog->array[i].declare_local = 1;
3973 isl_union_set_free(arrays);
3974 return 0;
3975 error:
3976 isl_union_set_free(arrays);
3977 return -1;
3980 /* If "node" points to a set node, then separate its children
3981 * into subtrees that have suitably permutable bands and
3982 * those that do not.
3983 * Adjust the schedule tree in order to execute the second group
3984 * after the first group and return a pointer to the first group,
3985 * assuming there are any such subtrees.
3986 * If "node" points to a sequence node, then separate the initial
3987 * children that do not have suitably permutable bands and
3988 * return a pointer to the subsequence of children that do have such bands,
3989 * assuming there are any such subtrees.
3991 * In both cases, mark all local variables in "prog" that are accessed by
3992 * the group without permutable bands as requiring a declaration on the host.
3994 static __isl_give isl_schedule_node *isolate_permutable_subtrees(
3995 __isl_take isl_schedule_node *node, struct gpu_prog *prog)
3997 isl_union_set *filter;
3998 enum isl_schedule_node_type type;
4000 if (!node)
4001 return NULL;
4002 type = isl_schedule_node_get_type(node);
4003 if (type == isl_schedule_node_set) {
4004 filter = get_all_non_parallel_subtree_filters(node);
4005 if (!filter)
4006 node = isl_schedule_node_free(node);
4008 if (declare_accessed_local_variables(prog, filter) < 0)
4009 node = isl_schedule_node_free(node);
4010 node = isl_schedule_node_order_after(node, filter);
4011 } else if (type == isl_schedule_node_sequence) {
4012 filter = get_initial_non_parallel_subtree_filters(node);
4013 if (!filter)
4014 node = isl_schedule_node_free(node);
4016 if (declare_accessed_local_variables(prog, filter) < 0)
4017 node = isl_schedule_node_free(node);
4018 node = isl_schedule_node_order_before(node, filter);
4021 return node;
4024 /* Replace any reference to an array element in the range of "copy"
4025 * by a reference to all array elements (defined by the extent of the array).
4027 static __isl_give isl_union_map *approximate_copy_out(
4028 __isl_take isl_union_map *copy, struct gpu_prog *prog)
4030 int i;
4031 isl_union_map *res;
4033 res = isl_union_map_empty(isl_union_map_get_space(copy));
4035 for (i = 0; i < prog->n_array; ++i) {
4036 isl_space *space;
4037 isl_set *set;
4038 isl_union_map *copy_i;
4039 isl_union_set *extent, *domain;
4041 space = isl_space_copy(prog->array[i].space);
4042 extent = isl_union_set_from_set(isl_set_universe(space));
4043 copy_i = isl_union_map_copy(copy);
4044 copy_i = isl_union_map_intersect_range(copy_i, extent);
4045 set = isl_set_copy(prog->array[i].extent);
4046 extent = isl_union_set_from_set(set);
4047 domain = isl_union_map_domain(copy_i);
4048 copy_i = isl_union_map_from_domain_and_range(domain, extent);
4049 res = isl_union_map_union(res, copy_i);
4052 isl_union_map_free(copy);
4054 return res;
4057 /* Insert "kernel" marks that point to a ppcg_kernel structure
4058 * in front of all outermost tilable band that (by construction)
4059 * have at least one parallel loop.
4061 static __isl_give isl_schedule_node *mark_kernels(struct gpu_gen *gen,
4062 __isl_take isl_schedule_node *node)
4064 return isl_schedule_node_map_descendant_bottom_up(node,
4065 &mark_outer_permutable, gen);
4068 /* Construct schedule constraints from the dependences in prog->scop and
4069 * the array order dependences in prog->array_order.
4071 * If live range reordering is allowed, then we need to make sure
4072 * that live ranges on arrays are not run in parallel since doing
4073 * so would require array expansion. We therefore add the array
4074 * order dependences to the coincidence dependences. Non-zero array
4075 * order dependences will then prevent a schedule dimension from being
4076 * considered parallel.
4077 * Live ranges derived from scalars are allowed to be run in parallel
4078 * since we force the scalars to be mapped to private memory in
4079 * check_scalar_live_ranges.
4080 * If live range reordering is allowed, then the false dependences
4081 * are not added to the validity constraints as that would prevent
4082 * reordering. Instead, the external false dependences that enforce that reads
4083 * from potentially live-in data precede any later write and
4084 * that writes of potentially live-out data follow any other earlier write
4085 * are added to the validity and the coincidence constraints.
4086 * The false dependences are still added to the proximity constraints
4087 * for consistency with the case where live range reordering is not allowed.
4088 * The coincidence constraints then consist of flow dependences,
4089 * external false dependences and array order dependences.
4090 * The independences can be filtered out from the first two sets.
4091 * They have already been filtered out from the array order dependences
4092 * on a per array basis in collect_order_dependences.
4093 * There is no need for a per array handling of the other two sets
4094 * as there should be no flow or external false dependence on local
4095 * variables that can be filtered out.
4097 static __isl_give isl_schedule_constraints *construct_schedule_constraints(
4098 struct gpu_prog *prog)
4100 isl_union_set *domain;
4101 isl_union_map *dep_raw, *dep;
4102 isl_union_map *validity, *proximity, *coincidence;
4103 isl_schedule_constraints *sc;
4105 domain = isl_union_set_copy(prog->scop->domain);
4106 sc = isl_schedule_constraints_on_domain(domain);
4107 sc = isl_schedule_constraints_set_context(sc,
4108 isl_set_copy(prog->scop->context));
4109 if (prog->scop->options->live_range_reordering) {
4110 sc = isl_schedule_constraints_set_conditional_validity(sc,
4111 isl_union_map_copy(prog->scop->tagged_dep_flow),
4112 isl_union_map_copy(prog->scop->tagged_dep_order));
4113 proximity = isl_union_map_copy(prog->scop->dep_flow);
4114 validity = isl_union_map_copy(proximity);
4115 validity = isl_union_map_union(validity,
4116 isl_union_map_copy(prog->scop->dep_forced));
4117 proximity = isl_union_map_union(proximity,
4118 isl_union_map_copy(prog->scop->dep_false));
4119 coincidence = isl_union_map_copy(validity);
4120 coincidence = isl_union_map_subtract(coincidence,
4121 isl_union_map_copy(prog->scop->independence));
4122 coincidence = isl_union_map_union(coincidence,
4123 isl_union_map_copy(prog->array_order));
4124 } else {
4125 dep_raw = isl_union_map_copy(prog->scop->dep_flow);
4126 dep = isl_union_map_copy(prog->scop->dep_false);
4127 dep = isl_union_map_union(dep, dep_raw);
4128 dep = isl_union_map_coalesce(dep);
4129 proximity = isl_union_map_copy(dep);
4130 coincidence = isl_union_map_copy(dep);
4131 validity = dep;
4133 sc = isl_schedule_constraints_set_validity(sc, validity);
4134 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4135 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4137 if (prog->scop->options->debug->dump_schedule_constraints)
4138 isl_schedule_constraints_dump(sc);
4139 return sc;
4142 /* Compute an appropriate schedule based on the accesses in
4143 * gen->read and gen->write.
4145 * We derive schedule constraints from the dependences in gen->prog->scop
4146 * and then use isl to compute a schedule that has a parallel loop
4147 * in each tilable band.
4149 static __isl_give isl_schedule *compute_schedule(struct gpu_gen *gen)
4151 isl_schedule_constraints *sc;
4152 isl_schedule *schedule;
4154 sc = construct_schedule_constraints(gen->prog);
4155 schedule = isl_schedule_constraints_compute_schedule(sc);
4157 return schedule;
4160 /* If the band node "node" has exactly one member then mark it permutable.
4162 static __isl_give isl_schedule_node *band_set_permutable(
4163 __isl_take isl_schedule_node *node,
4164 __isl_keep isl_schedule_constraints *sc)
4166 if (isl_schedule_node_band_n_member(node) == 1)
4167 node = isl_schedule_node_band_set_permutable(node, 1);
4169 return node;
4172 /* Return the coincidence constraints between pairs of instances
4173 * that are scheduled together by the ancestors of "node".
4174 * That is, select those coincidence constraints that relate
4175 * pairs of instances that have the same value for the prefix schedule.
4176 * If the schedule depth is zero, then the prefix schedule does not
4177 * contain any information, so we intersect domain and range
4178 * of the schedule constraints with the reaching domain elements instead.
4180 static __isl_give isl_union_map *get_local_coincidence(
4181 __isl_keep isl_schedule_node *node,
4182 __isl_keep isl_schedule_constraints *sc)
4184 isl_union_map *coincidence;
4185 isl_multi_union_pw_aff *prefix;
4186 isl_union_pw_multi_aff *contraction;
4188 coincidence = isl_schedule_constraints_get_coincidence(sc);
4189 contraction = isl_schedule_node_get_subtree_contraction(node);
4190 if (isl_schedule_node_get_schedule_depth(node) == 0) {
4191 isl_union_set *domain;
4193 domain = isl_schedule_node_get_domain(node);
4194 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4195 contraction);
4196 coincidence = isl_union_map_intersect_domain(coincidence,
4197 isl_union_set_copy(domain));
4198 coincidence = isl_union_map_intersect_range(coincidence,
4199 domain);
4200 return coincidence;
4203 prefix = isl_schedule_node_get_prefix_schedule_multi_union_pw_aff(node);
4204 prefix = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(prefix,
4205 contraction);
4206 return isl_union_map_eq_at_multi_union_pw_aff(coincidence, prefix);
4209 /* For each member in the band node "node", determine whether
4210 * it is coincident with respect to the outer nodes and mark
4211 * it accordingly.
4213 * That is, for each coincidence constraint between pairs
4214 * of instances that are scheduled together by the outer nodes,
4215 * check that domain and range are assigned the same value
4216 * by the band member. This test is performed by checking
4217 * that imposing the same value for the band member does not
4218 * remove any elements from the set of coincidence constraints.
4220 static __isl_give isl_schedule_node *band_set_coincident(
4221 __isl_take isl_schedule_node *node,
4222 __isl_keep isl_schedule_constraints *sc)
4224 isl_union_map *coincidence;
4225 isl_union_pw_multi_aff *contraction;
4226 isl_multi_union_pw_aff *partial;
4227 int i, n;
4229 coincidence = get_local_coincidence(node, sc);
4231 partial = isl_schedule_node_band_get_partial_schedule(node);
4232 contraction = isl_schedule_node_get_subtree_contraction(node);
4233 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4234 contraction);
4235 n = isl_schedule_node_band_n_member(node);
4236 for (i = 0; i < n; ++i) {
4237 isl_union_map *coincidence_i;
4238 isl_union_pw_aff *upa;
4239 isl_multi_union_pw_aff *partial_i;
4240 int subset;
4242 upa = isl_multi_union_pw_aff_get_union_pw_aff(partial, i);
4243 partial_i = isl_multi_union_pw_aff_from_union_pw_aff(upa);
4244 coincidence_i = isl_union_map_copy(coincidence);
4245 coincidence_i = isl_union_map_eq_at_multi_union_pw_aff(
4246 coincidence_i, partial_i);
4247 subset = isl_union_map_is_subset(coincidence, coincidence_i);
4248 isl_union_map_free(coincidence_i);
4250 if (subset < 0)
4251 break;
4252 node = isl_schedule_node_band_member_set_coincident(node, i,
4253 subset);
4255 if (i < n)
4256 node = isl_schedule_node_free(node);
4257 isl_multi_union_pw_aff_free(partial);
4258 isl_union_map_free(coincidence);
4260 return node;
4263 /* If "node" is a band, then set its properties.
4265 * In particular, if the band has exactly one member, then mark it permutable.
4266 * Mark the band member coincident based on the coincidence constraints
4267 * of "sc".
4269 static __isl_give isl_schedule_node *set_band_properties(
4270 __isl_take isl_schedule_node *node, void *user)
4272 isl_schedule_constraints *sc = user;
4274 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
4275 return node;
4276 if (isl_schedule_node_band_n_member(node) == 0)
4277 return node;
4279 node = band_set_permutable(node, sc);
4280 node = band_set_coincident(node, sc);
4282 return node;
4285 /* Return the original schedule with all bands marked permutable and
4286 * all band members marked coincident based on the coincidence constraints.
4287 * The bands are explicitly marked permutable so that they will be considered
4288 * by mark_outer_permutable.
4290 static __isl_give isl_schedule *determine_properties_original_schedule(
4291 struct gpu_gen *gen)
4293 isl_schedule *schedule;
4294 isl_schedule_constraints *sc;
4296 schedule = isl_schedule_copy(gen->prog->scop->schedule);
4297 sc = construct_schedule_constraints(gen->prog);
4298 schedule = isl_schedule_map_schedule_node_bottom_up(schedule,
4299 &set_band_properties, sc);
4300 isl_schedule_constraints_free(sc);
4302 return schedule;
4305 /* Compute a schedule or determine the properties of the original schedule
4306 * depending on the value of the "reschedule" option.
4308 static __isl_give isl_schedule *compute_or_set_properties(void *user)
4310 struct gpu_gen *gen = user;
4312 if (gen->options->reschedule)
4313 return compute_schedule(gen);
4314 else
4315 return determine_properties_original_schedule(gen);
4318 /* Obtain a schedule for the scop, by reading it from
4319 * a file, by computing one or by determining the properties
4320 * of the original schedule.
4322 static __isl_give isl_schedule *get_schedule(struct gpu_gen *gen)
4324 return ppcg_get_schedule(gen->ctx, gen->options,
4325 &compute_or_set_properties, gen);
4328 /* Construct the string "<a>_<b>".
4330 static char *concat(isl_ctx *ctx, const char *a, const char *b)
4332 isl_printer *p;
4333 char *s;
4335 p = isl_printer_to_str(ctx);
4336 p = isl_printer_print_str(p, a);
4337 p = isl_printer_print_str(p, "_");
4338 p = isl_printer_print_str(p, b);
4339 s = isl_printer_get_str(p);
4340 isl_printer_free(p);
4342 return s;
4345 /* For each array in "prog" of which an element appears in "accessed" and
4346 * that is not a read only scalar, create a zero-dimensional universe set
4347 * of which the tuple id has name "<prefix>_<name of array>" and a user
4348 * pointer pointing to the array (gpu_array_info).
4350 * If the array is local to "prog", then make sure it will be declared
4351 * in the host code.
4353 * Return the list of these universe sets.
4355 static __isl_give isl_union_set_list *create_copy_filters(struct gpu_prog *prog,
4356 const char *prefix, __isl_take isl_union_set *accessed)
4358 int i;
4359 isl_ctx *ctx;
4360 isl_union_set_list *filters;
4362 ctx = prog->ctx;
4363 filters = isl_union_set_list_alloc(ctx, 0);
4364 for (i = 0; i < prog->n_array; ++i) {
4365 struct gpu_array_info *array = &prog->array[i];
4366 isl_space *space;
4367 isl_set *accessed_i;
4368 int empty;
4369 char *name;
4370 isl_id *id;
4371 isl_union_set *uset;
4373 if (gpu_array_is_read_only_scalar(array))
4374 continue;
4376 space = isl_space_copy(array->space);
4377 accessed_i = isl_union_set_extract_set(accessed, space);
4378 empty = isl_set_plain_is_empty(accessed_i);
4379 isl_set_free(accessed_i);
4380 if (empty < 0) {
4381 filters = isl_union_set_list_free(filters);
4382 break;
4384 if (empty)
4385 continue;
4387 array->global = 1;
4388 if (array->local)
4389 array->declare_local = 1;
4391 name = concat(ctx, prefix, array->name);
4392 id = name ? isl_id_alloc(ctx, name, array) : NULL;
4393 free(name);
4394 space = isl_space_set_alloc(ctx, 0, 0);
4395 space = isl_space_set_tuple_id(space, isl_dim_set, id);
4396 uset = isl_union_set_from_set(isl_set_universe(space));
4398 filters = isl_union_set_list_add(filters, uset);
4400 isl_union_set_free(accessed);
4402 return filters;
4405 /* Make sure that code for the statements in "filters" that
4406 * copy arrays to or from the device is only generated when
4407 * the size of the corresponding array is positive.
4408 * That is, add a set node underneath "graft" with "filters" as children
4409 * and for each child add a guard that the selects the parameter
4410 * values for which the corresponding array has a positive size.
4411 * The array is available in the user pointer of the statement identifier.
4412 * "depth" is the schedule depth of the position where "graft"
4413 * will be added.
4415 static __isl_give isl_schedule_node *insert_positive_size_guards(
4416 __isl_take isl_schedule_node *graft,
4417 __isl_take isl_union_set_list *filters, int depth)
4419 int i, n;
4421 graft = isl_schedule_node_child(graft, 0);
4422 graft = isl_schedule_node_insert_set(graft, filters);
4423 n = isl_schedule_node_n_children(graft);
4424 for (i = 0; i < n; ++i) {
4425 isl_union_set *filter;
4426 isl_set *domain, *guard;
4427 isl_id *id;
4428 struct gpu_array_info *array;
4430 graft = isl_schedule_node_child(graft, i);
4431 filter = isl_schedule_node_filter_get_filter(graft);
4432 domain = isl_set_from_union_set(filter);
4433 id = isl_set_get_tuple_id(domain);
4434 array = isl_id_get_user(id);
4435 isl_id_free(id);
4436 isl_set_free(domain);
4437 guard = gpu_array_positive_size_guard(array);
4438 guard = isl_set_from_params(guard);
4439 guard = isl_set_add_dims(guard, isl_dim_set, depth);
4440 graft = isl_schedule_node_child(graft, 0);
4441 graft = isl_schedule_node_insert_guard(graft, guard);
4442 graft = isl_schedule_node_parent(graft);
4443 graft = isl_schedule_node_parent(graft);
4445 graft = isl_schedule_node_parent(graft);
4447 return graft;
4450 /* Create a graft for copying arrays to or from the device,
4451 * whenever the size of the array is strictly positive.
4452 * Each statement is called "<prefix>_<name of array>" and
4453 * the identifier has a user pointer pointing to the array.
4454 * The graft will be added at the position specified by "node".
4455 * "copy" contains the array elements that need to be copied.
4456 * Only arrays of which some elements need to be copied
4457 * will have a corresponding statement in the graph.
4458 * Note though that each such statement will copy the entire array.
4460 static __isl_give isl_schedule_node *create_copy_device(struct gpu_prog *prog,
4461 __isl_keep isl_schedule_node *node, const char *prefix,
4462 __isl_take isl_union_set *copy)
4464 int depth;
4465 isl_ctx *ctx;
4466 isl_space *space;
4467 isl_union_set *all, *domain;
4468 isl_union_set_list *filters;
4469 isl_union_map *extension;
4470 isl_schedule_node *graft;
4472 ctx = prog->ctx;
4473 depth = isl_schedule_node_get_schedule_depth(node);
4474 filters = create_copy_filters(prog, prefix, copy);
4475 all = isl_union_set_list_union(isl_union_set_list_copy(filters));
4477 space = depth < 0 ? NULL : isl_space_set_alloc(ctx, 0, depth);
4478 domain = isl_union_set_from_set(isl_set_universe(space));
4479 extension = isl_union_map_from_domain_and_range(domain, all);
4480 graft = isl_schedule_node_from_extension(extension);
4482 if (!filters)
4483 return isl_schedule_node_free(graft);
4484 if (isl_union_set_list_n_union_set(filters) == 0) {
4485 isl_union_set_list_free(filters);
4486 return graft;
4489 return insert_positive_size_guards(graft, filters, depth);
4492 /* Return (the universe spaces of) the arrays that are declared
4493 * inside the scop corresponding to "prog" and for which all
4494 * potential writes inside the scop form a subset of "domain".
4496 static __isl_give isl_union_set *extract_local_accesses(struct gpu_prog *prog,
4497 __isl_keep isl_union_set *domain)
4499 int i;
4500 isl_union_set *local;
4502 local = isl_union_set_empty(isl_union_set_get_space(domain));
4504 for (i = 0; i < prog->n_array; ++i) {
4505 isl_set *set;
4506 isl_union_map *to_outer;
4507 isl_union_map *may_write;
4508 isl_union_set *write_domain;
4509 isl_union_set *fields;
4510 int subset;
4512 if (!prog->array[i].local)
4513 continue;
4515 set = isl_set_universe(isl_space_copy(prog->array[i].space));
4516 to_outer = isl_union_map_copy(prog->to_outer);
4517 to_outer = isl_union_map_intersect_range(to_outer,
4518 isl_union_set_from_set(isl_set_copy(set)));
4519 fields = isl_union_map_domain(to_outer);
4520 may_write = isl_union_map_copy(prog->may_write);
4521 may_write = isl_union_map_intersect_range(may_write, fields);
4522 write_domain = isl_union_map_domain(may_write);
4523 subset = isl_union_set_is_subset(write_domain, domain);
4524 isl_union_set_free(write_domain);
4526 if (subset < 0) {
4527 isl_set_free(set);
4528 return isl_union_set_free(local);
4529 } else if (subset) {
4530 local = isl_union_set_add_set(local, set);
4531 } else {
4532 isl_set_free(set);
4536 return local;
4539 /* Internal data structure for node_may_persist.
4541 * "tagger" maps tagged iteration domains to the corresponding untagged
4542 * iteration domain.
4544 * "may_persist_flow" is the set of all tagged dataflow dependences
4545 * with those dependences removed that either precede or follow
4546 * the kernel launch in a sequence.
4547 * "inner_band_flow" is the set of all tagged dataflow dependences
4548 * that are local to a given iteration of the outer band nodes
4549 * with respect to the current node.
4550 * "local_flow" is equal to "inner_band_flow", except that the domain
4551 * and the range have been intersected with intermediate filters
4552 * on children of sets or sequences.
4554 struct ppcg_may_persist_data {
4555 isl_union_pw_multi_aff *tagger;
4557 isl_union_map *local_flow;
4558 isl_union_map *inner_band_flow;
4559 isl_union_map *may_persist_flow;
4562 /* Update the information in "data" based on the band ancestor "node".
4564 * In particular, we restrict the dependences in data->local_flow
4565 * to those dependence where the source and the sink occur in
4566 * the same iteration of the given band node.
4567 * We also update data->inner_band_flow to the new value of
4568 * data->local_flow.
4570 static int update_may_persist_at_band(__isl_keep isl_schedule_node *node,
4571 struct ppcg_may_persist_data *data)
4573 isl_multi_union_pw_aff *partial;
4574 isl_union_pw_multi_aff *contraction;
4575 isl_union_map *flow;
4577 if (isl_schedule_node_band_n_member(node) == 0)
4578 return 0;
4580 partial = isl_schedule_node_band_get_partial_schedule(node);
4581 contraction = isl_schedule_node_get_subtree_contraction(node);
4582 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4583 contraction);
4584 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4585 isl_union_pw_multi_aff_copy(data->tagger));
4587 flow = data->local_flow;
4588 flow = isl_union_map_eq_at_multi_union_pw_aff(flow, partial);
4589 data->local_flow = flow;
4591 isl_union_map_free(data->inner_band_flow);
4592 data->inner_band_flow = isl_union_map_copy(data->local_flow);
4594 return 0;
4597 /* Given a set of local reaching domain elements "domain",
4598 * expand them to the corresponding leaf domain elements using "contraction"
4599 * and insert the array references tags using data->tagger.
4601 static __isl_give isl_union_set *expand_and_tag(
4602 __isl_take isl_union_set *domain,
4603 __isl_take isl_union_pw_multi_aff *contraction,
4604 struct ppcg_may_persist_data *data)
4606 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4607 contraction);
4608 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4609 isl_union_pw_multi_aff_copy(data->tagger));
4610 return domain;
4613 /* Given a filter node that is the child of a set or sequence node,
4614 * restrict data->local_flow to refer only to those elements
4615 * in the filter of the node.
4616 * "contraction" maps the leaf domain elements of the schedule tree
4617 * to the corresponding domain elements at (the parent of) "node".
4619 static int filter_flow(__isl_keep isl_schedule_node *node,
4620 struct ppcg_may_persist_data *data,
4621 __isl_take isl_union_pw_multi_aff *contraction)
4623 isl_union_set *filter;
4624 isl_union_map *flow;
4626 flow = data->local_flow;
4627 filter = isl_schedule_node_filter_get_filter(node);
4628 filter = expand_and_tag(filter, contraction, data);
4629 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(filter));
4630 flow = isl_union_map_intersect_range(flow, filter);
4631 data->local_flow = flow;
4633 return 0;
4636 /* Given a filter node "node", collect the filters on all preceding siblings
4637 * (which are also filter nodes), add them to "filters" and return the result.
4639 static __isl_give isl_union_set *add_previous_filters(
4640 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4642 isl_schedule_node *sibling;
4644 sibling = isl_schedule_node_copy(node);
4645 while (sibling && isl_schedule_node_has_previous_sibling(sibling)) {
4646 isl_union_set *filter;
4648 sibling = isl_schedule_node_previous_sibling(sibling);
4649 filter = isl_schedule_node_filter_get_filter(sibling);
4650 filters = isl_union_set_union(filters, filter);
4652 isl_schedule_node_free(sibling);
4653 if (!sibling)
4654 return isl_union_set_free(filters);
4656 return filters;
4659 /* Given a filter node "node", collect the filters on all following siblings
4660 * (which are also filter nodes), add them to "filters" and return the result.
4662 static __isl_give isl_union_set *add_next_filters(
4663 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4665 isl_schedule_node *sibling;
4667 sibling = isl_schedule_node_copy(node);
4668 while (sibling && isl_schedule_node_has_next_sibling(sibling)) {
4669 isl_union_set *filter;
4671 sibling = isl_schedule_node_next_sibling(sibling);
4672 filter = isl_schedule_node_filter_get_filter(sibling);
4673 filters = isl_union_set_union(filters, filter);
4675 isl_schedule_node_free(sibling);
4676 if (!sibling)
4677 return isl_union_set_free(filters);
4679 return filters;
4682 /* Remove those flow dependences from data->may_persist_flow
4683 * that flow between elements of "domain" within the same iteration
4684 * of all outer band nodes.
4685 * "contraction" maps the leaf domain elements of the schedule tree
4686 * to the corresponding elements "domain".
4688 static void remove_external_flow(struct ppcg_may_persist_data *data,
4689 __isl_take isl_union_set *domain,
4690 __isl_keep isl_union_pw_multi_aff *contraction)
4692 isl_union_map *flow;
4694 contraction = isl_union_pw_multi_aff_copy(contraction);
4695 domain = expand_and_tag(domain, contraction, data);
4696 flow = isl_union_map_copy(data->local_flow);
4697 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(domain));
4698 flow = isl_union_map_intersect_range(flow, domain);
4700 data->may_persist_flow = isl_union_map_subtract(data->may_persist_flow,
4701 flow);
4704 /* Update the information in "data" based on the filter ancestor "node".
4705 * We only need to modify anything if the filter is the child
4706 * of a set or sequence node.
4708 * In the case of a sequence, we remove the dependences between
4709 * statement instances that are both executed either before or
4710 * after the subtree that will be mapped to a kernel, within
4711 * the same iteration of outer bands.
4713 * In both cases, we restrict data->local_flow to the current child.
4715 static int update_may_persist_at_filter(__isl_keep isl_schedule_node *node,
4716 struct ppcg_may_persist_data *data)
4718 enum isl_schedule_node_type type;
4719 isl_schedule_node *parent;
4720 isl_space *space;
4721 isl_union_pw_multi_aff *contraction;
4722 isl_union_set *before, *after, *filter;
4723 isl_union_map *flow;
4725 type = isl_schedule_node_get_parent_type(node);
4726 if (type != isl_schedule_node_sequence && type != isl_schedule_node_set)
4727 return 0;
4729 parent = isl_schedule_node_copy(node);
4730 parent = isl_schedule_node_parent(parent);
4731 contraction = isl_schedule_node_get_subtree_contraction(parent);
4732 isl_schedule_node_free(parent);
4734 if (type == isl_schedule_node_set)
4735 return filter_flow(node, data, contraction);
4737 filter = isl_schedule_node_filter_get_filter(node);
4738 space = isl_union_set_get_space(filter);
4739 isl_union_set_free(filter);
4740 before = isl_union_set_empty(space);
4741 after = isl_union_set_copy(before);
4742 before = add_previous_filters(before, node);
4743 after = add_next_filters(after, node);
4745 remove_external_flow(data, before, contraction);
4746 remove_external_flow(data, after, contraction);
4748 return filter_flow(node, data, contraction);
4751 /* Update the information in "data" based on the ancestor "node".
4753 static isl_stat update_may_persist_at(__isl_keep isl_schedule_node *node,
4754 void *user)
4756 struct ppcg_may_persist_data *data = user;
4758 switch (isl_schedule_node_get_type(node)) {
4759 case isl_schedule_node_error:
4760 return isl_stat_error;
4761 case isl_schedule_node_context:
4762 case isl_schedule_node_domain:
4763 case isl_schedule_node_expansion:
4764 case isl_schedule_node_extension:
4765 case isl_schedule_node_guard:
4766 case isl_schedule_node_leaf:
4767 case isl_schedule_node_mark:
4768 case isl_schedule_node_sequence:
4769 case isl_schedule_node_set:
4770 break;
4771 case isl_schedule_node_band:
4772 if (update_may_persist_at_band(node, data) < 0)
4773 return isl_stat_error;
4774 break;
4775 case isl_schedule_node_filter:
4776 if (update_may_persist_at_filter(node, data) < 0)
4777 return isl_stat_error;
4778 break;
4781 return isl_stat_ok;
4784 /* Determine the set of array elements that may need to be perserved
4785 * by a kernel constructed from the subtree at "node".
4786 * This includes the set of array elements that may need to be preserved
4787 * by the entire scop (prog->may_persist) and the elements for which
4788 * there is a potential flow dependence that may cross a kernel launch.
4790 * To determine the second set, we start from all flow dependences.
4791 * From this set of dependences, we remove those that cannot possibly
4792 * require data to be preserved by a kernel launch.
4793 * In particular, we consider the following sets of dependences.
4794 * - dependences of which the write occurs inside the kernel.
4795 * If the data is needed outside the kernel, then it will
4796 * be copied out immediately after the kernel launch, so there
4797 * is no need for any special care.
4798 * - dependences of which the read occurs inside the kernel and the
4799 * corresponding write occurs inside the same iteration of the
4800 * outer band nodes. This means that the data is needed in
4801 * the first kernel launch after the write, which is already
4802 * taken care of by the standard copy-in. That is, the data
4803 * do not need to be preserved by any intermediate call to
4804 * the same kernel.
4805 * - dependences of which the write and the read either both occur
4806 * before the kernel launch or both occur after the kernel launch,
4807 * within the same iteration of the outer band nodes with respect
4808 * to the sequence that determines the ordering of the dependence
4809 * and the kernel launch. Such flow dependences cannot cross
4810 * any kernel launch.
4812 * For the remaining (tagged) dependences, we take the domain
4813 * (i.e., the tagged writes) and apply the tagged access relation
4814 * to obtain the accessed data elements.
4815 * These are then combined with the elements that may need to be
4816 * preserved by the entire scop.
4818 static __isl_give isl_union_set *node_may_persist(
4819 __isl_keep isl_schedule_node *node, struct gpu_prog *prog)
4821 struct ppcg_may_persist_data data;
4822 isl_schedule_node *root;
4823 isl_union_pw_multi_aff *contraction;
4824 isl_union_set *domain;
4825 isl_union_set *persist;
4826 isl_union_map *flow, *local_flow;
4828 data.tagger = prog->scop->tagger;
4830 flow = isl_union_map_copy(prog->scop->tagged_dep_flow);
4831 data.local_flow = isl_union_map_copy(flow);
4832 data.inner_band_flow = isl_union_map_copy(flow);
4833 data.may_persist_flow = flow;
4834 if (isl_schedule_node_foreach_ancestor_top_down(node,
4835 &update_may_persist_at, &data) < 0)
4836 data.may_persist_flow =
4837 isl_union_map_free(data.may_persist_flow);
4838 flow = data.may_persist_flow;
4839 isl_union_map_free(data.local_flow);
4841 domain = isl_schedule_node_get_domain(node);
4842 contraction = isl_schedule_node_get_subtree_contraction(node);
4843 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4844 contraction);
4845 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4846 isl_union_pw_multi_aff_copy(data.tagger));
4847 flow = isl_union_map_subtract_domain(flow, isl_union_set_copy(domain));
4848 local_flow = data.inner_band_flow;
4849 local_flow = isl_union_map_intersect_range(local_flow, domain);
4850 flow = isl_union_map_subtract(flow, local_flow);
4852 persist = isl_union_map_domain(flow);
4853 persist = isl_union_set_apply(persist,
4854 isl_union_map_copy(prog->scop->tagged_may_writes));
4855 persist = isl_union_set_union(persist,
4856 isl_union_set_copy(prog->may_persist));
4858 return persist;
4861 /* Add nodes for copying outer arrays in and out of the device
4862 * before and after the subtree "node", which contains one or more kernels.
4863 * "domain" contains the original reaching domain elements before
4864 * the kernels were created, i.e., before the contraction that
4865 * may have been performed in creating the kernels has been applied.
4866 * "prefix" contains the prefix schedule at that point, in terms
4867 * of the same original reaching domain elements.
4869 * We first compute the sets of outer array elements that need
4870 * to be copied in and out and then graft in the nodes for
4871 * performing this copying.
4873 * In particular, for each array that is possibly written anywhere in
4874 * the subtree "node" and that may be used after "node"
4875 * or that may be visible outside the corresponding scop,
4876 * we copy out its entire extent.
4878 * Any array elements that is read without first being written inside
4879 * the subtree "node" needs to be copied in.
4880 * Furthermore, if there are any array elements that
4881 * are copied out, but that may not be written inside "node, then
4882 * they also need to be copied in to ensure that the value after execution
4883 * is the same as the value before execution, at least for those array
4884 * elements that may have their values preserved by the scop or that
4885 * may be written before "node" and read after "node".
4886 * In case the array elements are structures, we need to take into
4887 * account that all members of the structures need to be written
4888 * by "node" before we can avoid copying the data structure in.
4890 * Note that the may_write relation is intersected with the domain,
4891 * which has been intersected with the context.
4892 * This helps in those cases where the arrays are declared with a fixed size,
4893 * while the accesses are parametric and the context assigns a fixed value
4894 * to the parameters.
4896 * If an element from a local array is read without first being written,
4897 * then there is no point in copying it in since it cannot have been
4898 * written prior to the scop. Warn about the uninitialized read instead.
4900 static __isl_give isl_schedule_node *add_to_from_device(
4901 __isl_take isl_schedule_node *node, __isl_take isl_union_set *domain,
4902 __isl_take isl_union_map *prefix, struct gpu_prog *prog)
4904 isl_union_set *local;
4905 isl_union_set *to_device, *from_device, *may_persist;
4906 isl_union_map *may_write, *must_write, *copy_out, *not_written;
4907 isl_union_map *read, *copy_in;
4908 isl_union_map *tagged;
4909 isl_union_map *local_uninitialized;
4910 isl_schedule_node *graft;
4912 tagged = isl_union_map_copy(prog->scop->tagged_reads);
4913 tagged = isl_union_map_union(tagged,
4914 isl_union_map_copy(prog->scop->tagged_may_writes));
4916 may_write = isl_union_map_copy(prog->may_write);
4917 may_write = isl_union_map_intersect_domain(may_write,
4918 isl_union_set_copy(domain));
4919 may_write = remove_local_accesses(prog,
4920 isl_union_map_copy(tagged), may_write,
4921 isl_union_map_copy(prefix), 0);
4922 may_write = isl_union_map_apply_range(may_write,
4923 isl_union_map_copy(prog->to_outer));
4924 may_write = isl_union_map_apply_domain(may_write,
4925 isl_union_map_copy(prefix));
4926 may_write = approximate_copy_out(may_write, prog);
4927 copy_out = isl_union_map_copy(may_write);
4928 may_write = isl_union_map_apply_range(may_write,
4929 isl_union_map_copy(prog->to_inner));
4930 must_write = isl_union_map_copy(prog->must_write);
4931 must_write = isl_union_map_apply_domain(must_write,
4932 isl_union_map_copy(prefix));
4933 may_persist = node_may_persist(node, prog);
4934 may_write = isl_union_map_intersect_range(may_write, may_persist);
4935 not_written = isl_union_map_subtract(may_write, must_write);
4937 local = extract_local_accesses(prog, domain);
4938 read = isl_union_map_copy(prog->read);
4939 read = isl_union_map_intersect_domain(read, domain);
4940 read = remove_local_accesses(prog, tagged, read,
4941 isl_union_map_copy(prefix), 1);
4942 local = isl_union_set_apply(local, isl_union_map_copy(prog->to_inner));
4943 local_uninitialized = isl_union_map_copy(prog->scop->live_in);
4944 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4945 local);
4946 local_uninitialized = isl_union_map_intersect(local_uninitialized,
4947 isl_union_map_copy(read));
4948 if (!isl_union_map_is_empty(local_uninitialized)) {
4949 fprintf(stderr,
4950 "possibly uninitialized reads (not copied in):\n");
4951 isl_union_map_dump(local_uninitialized);
4953 read = isl_union_map_subtract(read, local_uninitialized);
4954 read = isl_union_map_apply_domain(read, prefix);
4955 copy_in = isl_union_map_union(read, not_written);
4956 copy_in = isl_union_map_apply_range(copy_in,
4957 isl_union_map_copy(prog->to_outer));
4959 graft = create_copy_device(prog, node, "to_device",
4960 isl_union_map_range(copy_in));
4961 node = isl_schedule_node_graft_before(node, graft);
4962 graft = create_copy_device(prog, node, "from_device",
4963 isl_union_map_range(copy_out));
4964 node = isl_schedule_node_graft_after(node, graft);
4966 return node;
4969 /* Update "schedule" for mapping to a GPU device.
4971 * In particular, insert a context node, create kernels for
4972 * each outermost tilable band and introduce node for copying array
4973 * in and out of the device.
4974 * If the child of the initial root points to a set node,
4975 * then children of this node that do not contain any tilable bands
4976 * are separated from the other children and are not mapped to
4977 * the device.
4979 static __isl_give isl_schedule *map_to_device(struct gpu_gen *gen,
4980 __isl_take isl_schedule *schedule)
4982 isl_schedule_node *node;
4983 isl_set *context;
4984 isl_union_set *domain;
4985 isl_union_map *prefix;
4987 context = isl_set_copy(gen->prog->context);
4988 context = isl_set_from_params(context);
4989 schedule = isl_schedule_insert_context(schedule, context);
4991 node = isl_schedule_get_root(schedule);
4992 isl_schedule_free(schedule);
4993 node = isl_schedule_node_child(node, 0);
4994 if (isl_schedule_node_get_type(node) == isl_schedule_node_context)
4995 node = isl_schedule_node_child(node, 0);
4996 node = isolate_permutable_subtrees(node, gen->prog);
4997 domain = isl_schedule_node_get_domain(node);
4998 prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
4999 node = mark_kernels(gen, node);
5000 node = add_to_from_device(node, domain, prefix, gen->prog);
5001 schedule = isl_schedule_node_get_schedule(node);
5002 isl_schedule_node_free(node);
5004 return schedule;
5007 /* Internal data structure for extract_access.
5008 * "next_access" points to the end of a linked list that is extended
5009 * by extract_access.
5010 * "single_expression" is set if the access expressions belong to
5011 * an expression statement (i.e., a statement without internal control).
5012 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5014 struct ppcg_extract_access_data {
5015 struct gpu_stmt_access **next_access;
5016 int single_expression;
5017 isl_union_map *any_to_outer;
5020 /* Given a tagged access relation to a single array "tagged", extract it
5021 * as a map, taking into account that the input may be empty.
5022 * If the access relation is empty, then it does not contain
5023 * any space information, so we try to recover it from the index
5024 * expression.
5025 * The space of the index expression is of the form I -> A,
5026 * with I the statement instances and A the array, or [I -> F] -> A,
5027 * with F the filters corresponding to arguments.
5028 * We first drop F, if present, obtaining I -> A.
5029 * Then we construct I -> R, with R the reference tag,
5030 * combine the two into I -> [R -> A] and uncurry to obtain
5031 * the final result [I -> R] -> A.
5032 * Note that the index expression may have a lower dimension
5033 * than that of the array, but this dimension is not used
5034 * if the access relation is empty.
5036 static __isl_give isl_map *extract_single_tagged_access(
5037 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
5039 int empty;
5040 isl_id *id;
5041 isl_space *space, *space2;
5042 isl_multi_pw_aff *index;
5044 empty = isl_union_map_is_empty(tagged);
5045 if (empty < 0)
5046 goto error;
5047 if (!empty)
5048 return isl_map_from_union_map(tagged);
5049 isl_union_map_free(tagged);
5051 index = pet_expr_access_get_index(expr);
5052 space = isl_multi_pw_aff_get_space(index);
5053 isl_multi_pw_aff_free(index);
5054 if (isl_space_domain_is_wrapping(space))
5055 space = isl_space_domain_factor_domain(space);
5056 space2 = isl_space_copy(space);
5057 space2 = isl_space_from_domain(isl_space_domain(space));
5058 id = pet_expr_access_get_ref_id(expr);
5059 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
5060 space = isl_space_range_product(space2, space);
5061 space = isl_space_uncurry(space);
5063 return isl_map_empty(space);
5064 error:
5065 isl_union_map_free(tagged);
5066 return NULL;
5069 /* Extract a gpu_stmt_access from "expr", append it to the list
5070 * that ends in *data->next_access and update the end of the list.
5071 * If the access expression performs a write, then it is considered
5072 * exact only if it appears in a single expression statement and
5073 * if its may access relation is equal to its must access relation.
5075 * The combined set of may accesses may be union if member accesses
5076 * are involved, but the entire set is derived from a single reference and
5077 * therefore from a single index expression. These accesses therefore
5078 * all map to the same outer array.
5080 static int extract_access(__isl_keep pet_expr *expr, void *user)
5082 struct ppcg_extract_access_data *data = user;
5083 isl_union_map *tagged;
5084 struct gpu_stmt_access *access;
5085 isl_ctx *ctx = pet_expr_get_ctx(expr);
5086 isl_multi_pw_aff *index;
5088 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5089 assert(access);
5090 access->next = NULL;
5091 access->read = pet_expr_access_is_read(expr);
5092 access->write = pet_expr_access_is_write(expr);
5093 tagged = pet_expr_access_get_tagged_may_read(expr);
5094 tagged = isl_union_map_union(tagged,
5095 pet_expr_access_get_tagged_may_write(expr));
5096 tagged = isl_union_map_apply_range(tagged,
5097 isl_union_map_copy(data->any_to_outer));
5098 if (!access->write) {
5099 access->exact_write = 1;
5100 } else if (!data->single_expression) {
5101 access->exact_write = 0;
5102 } else {
5103 isl_union_map *must, *may;
5104 may = isl_union_map_copy(tagged);
5105 may = isl_union_map_domain_factor_domain(may);
5106 must = pet_expr_access_get_must_write(expr);
5107 access->exact_write = isl_union_map_is_equal(must, may);
5108 isl_union_map_free(must);
5109 isl_union_map_free(may);
5111 index = pet_expr_access_get_index(expr);
5112 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5113 isl_multi_pw_aff_free(index);
5114 access->ref_id = pet_expr_access_get_ref_id(expr);
5115 access->tagged_access = extract_single_tagged_access(tagged, expr);
5116 access->access = isl_map_copy(access->tagged_access);
5117 access->access = isl_map_domain_factor_domain(access->access);
5119 *data->next_access = access;
5120 data->next_access = &(*data->next_access)->next;
5122 if (!access->access)
5123 return -1;
5125 return 0;
5128 /* Construct a linked list of gpu_stmt_access objects,
5129 * one for each access expression in the statement body.
5130 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5132 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5133 __isl_keep isl_union_map *any_to_outer)
5135 struct ppcg_extract_access_data data;
5137 stmt->accesses = NULL;
5138 data.next_access = &stmt->accesses;
5139 data.single_expression =
5140 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5141 data.any_to_outer = any_to_outer;
5142 return pet_tree_foreach_access_expr(stmt->stmt->body,
5143 &extract_access, &data);
5146 /* Return an array of gpu_stmt representing the statements in "scop".
5148 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5149 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
5151 int i;
5152 struct gpu_stmt *stmts;
5154 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5155 if (!stmts)
5156 return NULL;
5158 for (i = 0; i < scop->pet->n_stmt; ++i) {
5159 struct gpu_stmt *s = &stmts[i];
5161 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5162 s->stmt = scop->pet->stmts[i];
5163 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
5164 return free_stmts(stmts, i + 1);
5167 return stmts;
5170 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5172 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5174 struct gpu_gen *gen = user;
5176 return gen->print(p, gen->prog, gen->tree, &gen->types,
5177 gen->print_user);
5180 /* Generate CUDA code for "scop" and print it to "p".
5181 * After generating an AST for the transformed scop as explained below,
5182 * we call "gen->print" to print the AST in the desired output format
5183 * to "p".
5185 * If it turns out that it does not make sense to generate GPU code,
5186 * then we generate CPU code instead.
5188 * The GPU code is generated in a context where at least one
5189 * statement instance is executed. The corresponding guard (if any) is printed
5190 * around the entire generated GPU code, except for the declaration
5191 * of the arrays that are visible outside of the scop and that therefore
5192 * cannot be declared inside the body of any possible guard.
5194 * We first compute a schedule that respects the dependences
5195 * of the original program and select the outermost bands
5196 * of tilable dimensions that have at least one parallel loop.
5197 * If the --load-schedule is specified, then the loaded schedule
5198 * is used instead of a computed schedule.
5200 * Each of these bands B is then tiled according to "tile" sizes, resulting
5201 * in two nested bands, with a kernel marker on top
5209 * We then split off at most 2 parallel dimensions from the T band and
5210 * at most 3 parallel dimension from the P band
5215 * T1
5217 * T2
5219 * P1
5221 * P2
5223 * A filter is introduced in front of T1 that maps the domain instances
5224 * to block identifiers. Similarly, a filter is introduced in front of P1
5225 * that maps the domain instances to thread identifiers.
5227 * For each iteration of the T2 band and for each array, we compute
5228 * the array elements accessed by that iteration, construct a rectangular
5229 * box around it and shift it to the origin. The result is used
5230 * as shared memory for the array.
5232 * Copying and synchronization statements are added to this schedule tree.
5233 * In principle, these are added in front of the P1 band, but some of
5234 * them may get hoisted up to higher levels.
5236 * The entire AST is then generated from the single resulting schedule tree.
5237 * During the generation the subtrees at kernel nodes (K) are saved
5238 * aside and replaced by kernel calls. The result is printed as host code
5239 * while the saved subtrees are printed as device code.
5241 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5242 struct gpu_gen *gen, struct ppcg_scop *scop,
5243 struct ppcg_options *options)
5245 struct gpu_prog *prog;
5246 isl_ctx *ctx;
5247 isl_set *context, *guard;
5248 isl_schedule *schedule;
5249 int any_permutable;
5251 if (!scop)
5252 return isl_printer_free(p);
5254 ctx = isl_printer_get_ctx(p);
5255 prog = gpu_prog_alloc(ctx, scop);
5256 if (!prog)
5257 return isl_printer_free(p);
5259 context = isl_set_copy(prog->context);
5260 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5261 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5263 gen->prog = prog;
5264 schedule = get_schedule(gen);
5266 any_permutable = has_any_permutable_node(schedule);
5267 if (any_permutable < 0 || !any_permutable) {
5268 isl_set_free(context);
5269 isl_set_free(guard);
5270 if (any_permutable < 0)
5271 p = isl_printer_free(p);
5272 else
5273 p = print_cpu(p, scop, options);
5274 isl_schedule_free(schedule);
5275 } else {
5276 schedule = map_to_device(gen, schedule);
5277 gen->tree = generate_code(gen, schedule);
5278 p = ppcg_set_macro_names(p);
5279 p = isl_ast_op_type_print_macro(isl_ast_op_fdiv_q, p);
5280 p = ppcg_print_exposed_declarations(p, prog->scop);
5281 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5282 isl_ast_node_free(gen->tree);
5285 gpu_prog_free(prog);
5287 return p;
5290 /* Wrapper around generate for use as a ppcg_transform callback.
5292 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5293 struct ppcg_scop *scop, void *user)
5295 struct gpu_gen *gen = user;
5297 return generate(p, gen, scop, gen->options);
5300 /* Transform the code in the file called "input" by replacing
5301 * all scops by corresponding GPU code and write the results to "out".
5303 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5304 struct ppcg_options *options,
5305 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5306 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5307 struct gpu_types *types, void *user), void *user)
5309 struct gpu_gen gen;
5310 int r;
5311 int i;
5313 gen.ctx = ctx;
5314 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5315 gen.options = options;
5316 gen.kernel_id = 0;
5317 gen.print = print;
5318 gen.print_user = user;
5319 gen.types.n = 0;
5320 gen.types.name = NULL;
5322 if (options->debug->dump_sizes) {
5323 isl_space *space = isl_space_params_alloc(ctx, 0);
5324 gen.used_sizes = isl_union_map_empty(space);
5327 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5329 if (options->debug->dump_sizes) {
5330 isl_union_map_dump(gen.used_sizes);
5331 isl_union_map_free(gen.used_sizes);
5334 isl_union_map_free(gen.sizes);
5335 for (i = 0; i < gen.types.n; ++i)
5336 free(gen.types.name[i]);
5337 free(gen.types.name);
5339 return r;
5342 /* Compute the set of inner array elements that may have their values
5343 * preserved by "prog". In particular, collect the array elements of
5344 * arrays that are not local to "prog" and remove those elements that
5345 * are definitely killed or definitely written by "prog".
5347 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5349 int i;
5350 isl_union_set *may_persist, *killed;
5351 isl_union_map *must_kill;
5353 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5354 for (i = 0; i < prog->n_array; ++i) {
5355 isl_set *extent;
5357 if (prog->array[i].local)
5358 continue;
5360 extent = isl_set_copy(prog->array[i].extent);
5361 may_persist = isl_union_set_add_set(may_persist, extent);
5364 may_persist = isl_union_set_intersect_params(may_persist,
5365 isl_set_copy(prog->context));
5366 may_persist = isl_union_set_apply(may_persist,
5367 isl_union_map_copy(prog->to_inner));
5368 must_kill = isl_union_map_copy(prog->tagged_must_kill);
5369 killed = isl_union_map_range(must_kill);
5370 must_kill = isl_union_map_copy(prog->must_write);
5371 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
5373 may_persist = isl_union_set_subtract(may_persist, killed);
5374 return may_persist;
5377 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5379 struct gpu_prog *prog;
5380 isl_space *space;
5381 isl_map *id;
5383 if (!scop)
5384 return NULL;
5386 prog = isl_calloc_type(ctx, struct gpu_prog);
5387 assert(prog);
5389 prog->ctx = ctx;
5390 prog->scop = scop;
5391 prog->context = isl_set_copy(scop->context);
5392 prog->n_stmts = scop->pet->n_stmt;
5393 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5394 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5395 space = isl_union_map_get_space(prog->any_to_outer);
5396 space = isl_space_set_from_params(space);
5397 space = isl_space_add_dims(space, isl_dim_set, 1);
5398 space = isl_space_map_from_set(space);
5399 id = isl_map_identity(space);
5400 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
5401 prog->stmts = extract_stmts(ctx, scop,
5402 prog->context, prog->any_to_outer);
5403 prog->read = isl_union_map_copy(scop->reads);
5404 prog->may_write = isl_union_map_copy(scop->may_writes);
5405 prog->must_write = isl_union_map_copy(scop->must_writes);
5406 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
5407 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
5408 prog->to_outer = isl_union_map_copy(prog->to_inner);
5409 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5411 if (!prog->stmts)
5412 return gpu_prog_free(prog);
5414 if (collect_array_info(prog) < 0)
5415 return gpu_prog_free(prog);
5416 prog->may_persist = compute_may_persist(prog);
5418 return prog;
5421 void *gpu_prog_free(struct gpu_prog *prog)
5423 if (!prog)
5424 return NULL;
5425 free_array_info(prog);
5426 free_stmts(prog->stmts, prog->n_stmts);
5427 isl_union_map_free(prog->any_to_outer);
5428 isl_union_map_free(prog->to_outer);
5429 isl_union_map_free(prog->to_inner);
5430 isl_union_map_free(prog->read);
5431 isl_union_map_free(prog->may_write);
5432 isl_union_map_free(prog->must_write);
5433 isl_union_map_free(prog->tagged_must_kill);
5434 isl_union_map_free(prog->array_order);
5435 isl_union_set_free(prog->may_persist);
5436 isl_set_free(prog->context);
5437 free(prog);
5438 return NULL;