update isl for rename of isl_schedule_*_foreach_*
[ppcg.git] / gpu.c
blob85221bad06e3397d4bc17610c189dd5129a749a3
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->depth dimensions of the computed
822 * 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->shared_schedule_dim dimensions of
877 * the schedule computed by PPCG for this kernel.
879 * Note that kernel->shared_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 group->depth dimensions in transform_index.
884 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(
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->shared_schedule_dim);
896 upma = isl_union_pw_multi_aff_copy(kernel->shared_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;
933 group = local->groups[j];
934 if (group->private_tile)
935 continue;
936 if (!group->shared_tile)
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 void 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 id = isl_id_list_get_id(kernel->thread_ids, i);
1138 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1139 isl_id_free(id);
1140 assert(pos >= 0);
1141 block = isl_set_equate(block, isl_dim_param, pos,
1142 isl_dim_set, i);
1144 nparam = isl_set_dim(block, isl_dim_param);
1145 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1147 extract_fixed_size(block, kernel->block_dim);
1150 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1152 int i, j;
1154 if (!kernel)
1155 return NULL;
1157 isl_id_list_free(kernel->block_ids);
1158 isl_id_list_free(kernel->thread_ids);
1159 isl_multi_pw_aff_free(kernel->grid_size);
1160 isl_set_free(kernel->context);
1161 isl_union_set_free(kernel->core);
1162 isl_union_set_free(kernel->arrays);
1163 isl_space_free(kernel->space);
1164 isl_ast_node_free(kernel->tree);
1165 isl_union_set_free(kernel->block_filter);
1166 isl_union_set_free(kernel->thread_filter);
1167 isl_union_pw_multi_aff_free(kernel->shared_schedule);
1168 isl_union_set_free(kernel->sync_writes);
1170 for (i = 0; i < kernel->n_array; ++i) {
1171 struct gpu_local_array_info *array = &kernel->array[i];
1173 for (j = 0; j < array->n_group; ++j)
1174 gpu_array_ref_group_free(array->groups[j]);
1175 free(array->groups);
1177 isl_pw_aff_list_free(array->bound);
1179 free(kernel->array);
1181 for (i = 0; i < kernel->n_var; ++i) {
1182 free(kernel->var[i].name);
1183 isl_vec_free(kernel->var[i].size);
1185 free(kernel->var);
1187 free(kernel);
1189 return NULL;
1192 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1194 static void ppcg_kernel_free_wrap(void *user)
1196 struct ppcg_kernel *kernel = user;
1198 ppcg_kernel_free(kernel);
1201 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1202 struct ppcg_kernel_var *var)
1204 int j;
1205 struct gpu_array_tile *tile;
1206 isl_printer *p;
1207 char *name;
1209 var->array = group->array;
1211 tile = group->private_tile;
1212 var->type = ppcg_access_private;
1213 if (!tile) {
1214 tile = group->shared_tile;
1215 var->type = ppcg_access_shared;
1218 p = isl_printer_to_str(ctx);
1219 p = gpu_array_ref_group_print_name(group, p);
1220 var->name = isl_printer_get_str(p);
1221 isl_printer_free(p);
1223 var->size = isl_vec_alloc(ctx, group->array->n_index);
1225 for (j = 0; j < group->array->n_index; ++j)
1226 var->size = isl_vec_set_element_val(var->size, j,
1227 isl_val_copy(tile->bound[j].size));
1230 static int create_kernel_vars(struct ppcg_kernel *kernel)
1232 int i, j, n;
1234 n = 0;
1235 for (i = 0; i < kernel->n_array; ++i) {
1236 struct gpu_local_array_info *array = &kernel->array[i];
1238 for (j = 0; j < array->n_group; ++j) {
1239 struct gpu_array_ref_group *group = array->groups[j];
1240 if (group->private_tile || group->shared_tile)
1241 ++n;
1245 kernel->n_var = n;
1246 kernel->var = isl_calloc_array(kernel->ctx, struct ppcg_kernel_var, n);
1247 if (!kernel->var)
1248 return -1;
1250 n = 0;
1251 for (i = 0; i < kernel->n_array; ++i) {
1252 struct gpu_local_array_info *array = &kernel->array[i];
1254 for (j = 0; j < array->n_group; ++j) {
1255 struct gpu_array_ref_group *group = array->groups[j];
1256 if (!group->private_tile && !group->shared_tile)
1257 continue;
1258 create_kernel_var(kernel->ctx, group, &kernel->var[n]);
1259 ++n;
1263 return 0;
1266 /* Replace "pa" by the zero function defined over the universe domain
1267 * in the space of "pa".
1269 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1271 isl_space *space;
1272 isl_aff *zero;
1274 space = isl_space_domain(isl_pw_aff_get_space(pa));
1275 isl_pw_aff_free(pa);
1276 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1278 return isl_pw_aff_from_aff(zero);
1281 /* The sizes of the arrays on the host that have been computed by
1282 * extract_array_info may depend on the parameters. Use the extra
1283 * constraints on the parameters that are valid at "host_domain"
1284 * to simplify these expressions and store the results in kernel->array.
1286 * We only need these localized bounds for arrays that are accessed
1287 * by the current kernel. If we have found at least one reference group
1288 * then the array is accessed by the kernel.
1290 * The resulting sizes may be functions that are nowhere defined
1291 * in case the access function cannot possibly access anything inside
1292 * the kernel for some reason. If so, they are replaced by the zero
1293 * function. Since the access function cannot actually access anything,
1294 * there is no harm in printing the array sizes as zero.
1296 static void localize_bounds(struct ppcg_kernel *kernel,
1297 __isl_keep isl_set *host_domain)
1299 int i, j;
1300 isl_set *context;
1302 context = isl_set_copy(host_domain);
1303 context = isl_set_params(context);
1305 for (i = 0; i < kernel->n_array; ++i) {
1306 struct gpu_local_array_info *local = &kernel->array[i];
1307 isl_pw_aff_list *bound;
1308 int n_index;
1310 if (local->n_group == 0)
1311 continue;
1313 n_index = local->array->n_index;
1314 bound = isl_pw_aff_list_alloc(kernel->ctx, n_index);
1316 for (j = 0; j < n_index; ++j) {
1317 isl_pw_aff *pwaff;
1318 int empty;
1320 pwaff = isl_pw_aff_copy(local->array->bound[j]);
1321 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1322 empty = isl_pw_aff_is_empty(pwaff);
1323 if (empty < 0)
1324 pwaff = isl_pw_aff_free(pwaff);
1325 else if (empty)
1326 pwaff = set_universally_zero(pwaff);
1327 bound = isl_pw_aff_list_add(bound, pwaff);
1330 local->n_index = n_index;
1331 local->bound = bound;
1333 isl_set_free(context);
1336 /* Create the array of gpu_local_array_info structures "array"
1337 * inside "kernel". The number of elements in this array is
1338 * the same as the number of arrays in "prog".
1339 * Initialize the "array" field of each local array to point
1340 * to the corresponding array in "prog".
1342 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1343 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1345 int i;
1346 isl_ctx *ctx;
1348 ctx = isl_set_get_ctx(prog->context);
1349 kernel->array = isl_calloc_array(ctx,
1350 struct gpu_local_array_info, prog->n_array);
1351 if (!kernel->array)
1352 return ppcg_kernel_free(kernel);
1353 kernel->n_array = prog->n_array;
1355 for (i = 0; i < prog->n_array; ++i)
1356 kernel->array[i].array = &prog->array[i];
1358 return kernel;
1361 /* Does "kernel" need to be passed an argument corresponding to array "i"?
1363 * The argument is only needed if the kernel accesses this device memory.
1365 int ppcg_kernel_requires_array_argument(struct ppcg_kernel *kernel, int i)
1367 return kernel->array[i].global;
1370 /* Find the element in gen->stmt that has the given "id".
1371 * Return NULL if no such gpu_stmt can be found.
1373 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1375 int i;
1377 for (i = 0; i < prog->n_stmts; ++i) {
1378 if (id == prog->stmts[i].id)
1379 break;
1382 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1385 void ppcg_kernel_stmt_free(void *user)
1387 int i;
1388 struct ppcg_kernel_stmt *stmt = user;
1390 if (!stmt)
1391 return;
1393 switch (stmt->type) {
1394 case ppcg_kernel_copy:
1395 isl_ast_expr_free(stmt->u.c.index);
1396 isl_ast_expr_free(stmt->u.c.local_index);
1397 break;
1398 case ppcg_kernel_domain:
1399 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1400 break;
1401 case ppcg_kernel_sync:
1402 break;
1405 free(stmt);
1408 /* Return the gpu_stmt_access in the list "accesses" that corresponds
1409 * to "ref_id".
1411 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1412 __isl_keep isl_id *ref_id)
1414 struct gpu_stmt_access *access;
1416 for (access = accesses; access; access = access->next)
1417 if (access->ref_id == ref_id)
1418 return access;
1420 return NULL;
1423 /* Return the index of the array called "name" in the list of arrays.
1425 static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1427 int i;
1429 for (i = 0; i < kernel->n_array; ++i)
1430 if (!strcmp(name, kernel->array[i].array->name))
1431 return i;
1433 return -1;
1436 /* Internal data structure for the index and AST expression transformation
1437 * callbacks for pet_stmt_build_ast_exprs.
1439 * "kernel" is the kernel for which are computing AST expressions and
1440 * may be NULL if we are not inside a kernel.
1441 * "accesses" is the list of gpu_stmt_access in the statement.
1442 * "iterator_map" expresses the statement iterators in terms of
1443 * the AST loop iterators.
1444 * "sched2shared" expresses the outer shared_schedule_dim dimensions of
1445 * the kernel schedule in terms of the AST loop iterators and
1446 * may be NULL if we are not inside a kernel.
1448 * The following fields are set in transform_index and used in transform_expr.
1449 * "array" is the array that is being accessed.
1450 * "global" is set if the global array is accessed (rather than
1451 * shared/private memory).
1452 * "local_array" refers to information on the array specialized
1453 * to the current kernel.
1455 struct ppcg_transform_data {
1456 struct ppcg_kernel *kernel;
1457 struct gpu_stmt_access *accesses;
1458 isl_pw_multi_aff *iterator_map;
1459 isl_pw_multi_aff *sched2shared;
1461 struct gpu_array_info *array;
1462 int global;
1463 struct gpu_local_array_info *local_array;
1466 /* Return a pointer to the gpu_array_ref_group in "local"
1467 * that contains the reference "access".
1468 * Return NULL if no such group can be found.
1470 static struct gpu_array_ref_group *find_ref_group(
1471 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1473 int i, j;
1475 for (i = 0; i < local->n_group; ++i) {
1476 struct gpu_array_ref_group *group = local->groups[i];
1478 for (j = 0; j < group->n_ref; ++j)
1479 if (group->refs[j] == access)
1480 return group;
1483 return NULL;
1486 /* Index transformation callback for pet_stmt_build_ast_exprs.
1488 * "index" expresses the array indices in terms of statement iterators
1490 * We first reformulate "index" in terms of the AST loop iterators.
1491 * Then we check if we are accessing the global array or
1492 * a shared/private copy. In particular, if we are not inside a kernel
1493 * then we must be accessing a global array.
1494 * In the former case, we simply return
1495 * the updated index. If "index" is an affine expression rather
1496 * than an array access, then we also return the updated index here.
1498 * If no reference groups have been computed for the array,
1499 * then we can only be accessing the global array.
1501 * Otherwise, we apply the tiling to the index.
1502 * This tiling is of the form
1504 * [D -> A] -> T
1506 * where D corresponds to the outer group->depth dimensions of
1507 * the kernel schedule.
1508 * The index is of the form
1510 * L -> A
1512 * We update the tiling to refer to the AST loop iterators
1514 * [L -> A] -> T
1516 * and modify index to keep track of those iterators
1518 * L -> [L -> A]
1520 * Combining these two yields a tiled index expression in terms
1521 * of the AST loop iterators
1523 * L -> T
1525 static __isl_give isl_multi_pw_aff *transform_index(
1526 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
1527 void *user)
1529 struct ppcg_transform_data *data = user;
1530 struct gpu_stmt_access *access;
1531 struct gpu_array_ref_group *group;
1532 struct gpu_array_tile *tile;
1533 isl_pw_multi_aff *iterator_map;
1534 int i;
1535 int dim;
1536 const char *name;
1537 isl_space *space;
1538 isl_multi_pw_aff *tiling;
1539 isl_pw_multi_aff *pma;
1540 isl_multi_pw_aff *mpa;
1541 isl_pw_multi_aff *sched2depth;
1543 data->array = NULL;
1545 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
1546 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
1548 if (!data->kernel)
1549 return index;
1551 access = find_access(data->accesses, ref_id);
1552 if (!access)
1553 return index;
1554 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1555 return index;
1557 name = get_outer_array_name(access->access);
1558 i = find_array_index(data->kernel, name);
1559 if (i < 0)
1560 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
1561 "cannot find array",
1562 return isl_multi_pw_aff_free(index));
1563 data->local_array = &data->kernel->array[i];
1564 data->array = data->local_array->array;
1566 group = find_ref_group(data->local_array, access);
1567 if (!group) {
1568 data->global = 1;
1569 return index;
1572 tile = group->private_tile;
1573 if (!tile)
1574 tile = group->shared_tile;
1575 data->global = !tile;
1576 if (!tile)
1577 return index;
1579 space = isl_space_range(isl_multi_pw_aff_get_space(index));
1580 space = isl_space_map_from_set(space);
1581 pma = isl_pw_multi_aff_identity(space);
1582 sched2depth = isl_pw_multi_aff_copy(data->sched2shared);
1583 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1584 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1585 group->depth, dim - group->depth);
1586 pma = isl_pw_multi_aff_product(sched2depth, pma);
1587 tiling = isl_multi_pw_aff_from_multi_aff(
1588 isl_multi_aff_copy(tile->tiling));
1589 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1591 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1592 space = isl_space_map_from_set(space);
1593 mpa = isl_multi_pw_aff_identity(space);
1594 index = isl_multi_pw_aff_range_product(mpa, index);
1595 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1597 return index;
1600 /* Dereference "expr" by adding an index [0].
1601 * The original "expr" is assumed not to have any indices.
1603 * If "expr" is a member access, then the dereferencing needs
1604 * to be applied to the structure argument of this member access.
1606 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1608 isl_ctx *ctx;
1609 isl_ast_expr *arg0, *res;
1610 isl_ast_expr_list *list;
1612 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1613 if (!arg0)
1614 return isl_ast_expr_free(expr);
1615 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1616 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1617 isl_ast_expr *arg;
1619 arg = isl_ast_expr_get_op_arg(arg0, 0);
1620 arg = dereference(arg);
1621 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1622 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1624 return expr;
1626 isl_ast_expr_free(arg0);
1628 ctx = isl_ast_expr_get_ctx(expr);
1629 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1630 list = isl_ast_expr_list_from_ast_expr(res);
1631 res = isl_ast_expr_get_op_arg(expr, 0);
1632 res = isl_ast_expr_access(res, list);
1633 isl_ast_expr_free(expr);
1635 return res;
1638 /* Linearize the index expression "expr" based on the array bounds
1639 * of "array".
1641 * That is, transform expression
1643 * A[i_0][i_1]...[i_n]
1645 * to
1647 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1649 * where b_0, b_1, ..., b_n are the bounds on the array.
1651 * If the base of "expr" is a member access, then the linearization needs
1652 * to be applied to the structure argument of this member access.
1654 * In the base case, if "expr" has no arguments (other than the name of
1655 * the array), then we are passing an entire array to a function.
1656 * In this case, there is nothing to linearize.
1657 * Note that at this point an expression with no arguments can
1658 * only be an entire array because the scalar case and
1659 * the case of single struct are handled by the caller.
1661 * If the number of specified index expressions in "expr"
1662 * is smaller than the dimension of the accessed array,
1663 * then the missing i_j also do not appear in the linearized expression.
1664 * Furthermore, since such an expression does not refer to a single
1665 * element while the default linearized expression would refer to
1666 * a single element, we return the expression
1668 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
1670 * instead. Note that because of the special case handling above,
1671 * we can assume here that here that there is at least one index expression.
1673 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1674 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1676 int i, n;
1677 isl_ctx *ctx;
1678 isl_set *context;
1679 isl_ast_expr *arg0;
1680 isl_ast_expr *res;
1681 isl_ast_expr_list *list;
1682 isl_ast_build *build;
1684 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1685 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1686 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1687 isl_ast_expr *arg;
1689 arg = isl_ast_expr_get_op_arg(arg0, 0);
1690 arg = gpu_local_array_info_linearize_index(array, arg);
1691 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1692 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1694 return expr;
1696 isl_ast_expr_free(arg0);
1698 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1699 return expr;
1701 ctx = isl_ast_expr_get_ctx(expr);
1702 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
1703 build = isl_ast_build_from_context(context);
1705 n = isl_ast_expr_get_op_n_arg(expr);
1706 res = isl_ast_expr_get_op_arg(expr, 1);
1707 for (i = 1; i < array->n_index; ++i) {
1708 isl_pw_aff *bound_i;
1709 isl_ast_expr *expr_i;
1711 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
1712 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
1713 res = isl_ast_expr_mul(res, expr_i);
1715 if (i + 1 >= n)
1716 continue;
1717 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1718 res = isl_ast_expr_add(res, expr_i);
1721 isl_ast_build_free(build);
1723 if (1 + array->n_index > n) {
1724 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1725 } else {
1726 list = isl_ast_expr_list_from_ast_expr(res);
1727 res = isl_ast_expr_get_op_arg(expr, 0);
1728 res = isl_ast_expr_access(res, list);
1731 isl_ast_expr_free(expr);
1733 return res;
1736 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
1738 * If the AST expression refers to an array that is not accessed
1739 * at all, then this means the value of the expression is not used,
1740 * so we might as well print zero (NULL pointer) instead.
1742 * If the AST expression refers to a global scalar that is not
1743 * a read-only scalar, then its address was passed to the kernel and
1744 * we need to dereference it.
1746 * If the AST expression refers to an access to a global array,
1747 * then we linearize the access exploiting the bounds in data->local_array.
1749 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1750 __isl_keep isl_id *id, void *user)
1752 struct ppcg_transform_data *data = user;
1754 if (!data->array)
1755 return expr;
1756 if (!data->array->accessed) {
1757 isl_ctx *ctx;
1759 ctx = isl_ast_expr_get_ctx(expr);
1760 isl_ast_expr_free(expr);
1761 return isl_ast_expr_from_val(isl_val_zero(ctx));
1763 if (gpu_array_is_read_only_scalar(data->array))
1764 return expr;
1765 if (!data->global)
1766 return expr;
1767 if (data->array->n_index == 0)
1768 return dereference(expr);
1769 if (!data->array->linearize)
1770 return expr;
1772 return gpu_local_array_info_linearize_index(data->local_array, expr);
1775 /* This function is called for each instance of a user statement
1776 * in the kernel "kernel", identified by "gpu_stmt".
1777 * "kernel" may be NULL if we are not inside a kernel.
1779 * We attach a struct ppcg_kernel_stmt to the "node", containing
1780 * a computed AST expression for each access, through an annotation
1781 * with name "user".
1782 * These AST expressions are computed from iterator_map,
1783 * which expresses the domain
1784 * elements in terms of the generated loops, and sched2shared,
1785 * which expresses the outer shared_schedule_dim dimensions of
1786 * the kernel schedule computed by PPCG in terms of the generated loops.
1788 static __isl_give isl_ast_node *create_domain_leaf(
1789 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1790 __isl_keep isl_ast_build *build, struct gpu_stmt *gpu_stmt)
1792 struct ppcg_transform_data data;
1793 struct ppcg_kernel_stmt *stmt;
1794 isl_ctx *ctx;
1795 isl_id *id;
1796 isl_pw_multi_aff *sched2shared;
1797 isl_map *map;
1798 isl_pw_multi_aff *iterator_map;
1799 isl_union_map *schedule;
1801 if (!node)
1802 return NULL;
1803 ctx = isl_ast_node_get_ctx(node);
1805 stmt = isl_calloc_type(ctx, struct ppcg_kernel_stmt);
1806 if (!stmt)
1807 return isl_ast_node_free(node);
1809 schedule = isl_ast_build_get_schedule(build);
1810 map = isl_map_reverse(isl_map_from_union_map(schedule));
1811 iterator_map = isl_pw_multi_aff_from_map(map);
1812 if (kernel)
1813 sched2shared = compute_sched_to_shared(kernel,
1814 isl_pw_multi_aff_copy(iterator_map));
1815 else
1816 sched2shared = NULL;
1818 stmt->type = ppcg_kernel_domain;
1819 stmt->u.d.stmt = gpu_stmt;
1821 data.kernel = kernel;
1822 data.accesses = stmt->u.d.stmt->accesses;
1823 data.iterator_map = iterator_map;
1824 data.sched2shared = sched2shared;
1825 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
1826 build, &transform_index, &data,
1827 &transform_expr, &data);
1829 isl_pw_multi_aff_free(iterator_map);
1830 isl_pw_multi_aff_free(sched2shared);
1832 id = isl_id_alloc(ctx, "user", stmt);
1833 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1834 return isl_ast_node_set_annotation(node, id);
1837 /* This function is called for each statement node in the AST
1838 * for copying to or from shared/private memory.
1839 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1840 * statement to the node.
1841 * The statement name is "read" or "write", depending on whether we are
1842 * reading from global memory or writing to global memory.
1844 * The schedule is of the form
1846 * type[D -> A] -> L
1848 * where D corresponds to the outer group->depth dimensions of
1849 * the kernel schedule, A to the global array and L to the outer
1850 * generated AST schedule.
1851 * We compute the inverse and strip off the type, resulting in
1853 * L -> [D -> A]
1855 * We combine this mapping with on the one hand the projection
1857 * [D -> A] -> A
1859 * and on the other hand the group tiling
1861 * [D -> A] -> T
1863 * resulting in
1865 * L -> A and L -> T
1867 * and store the corresponding expressions in stmt->index and stmt->local_index,
1868 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1870 static __isl_give isl_ast_node *create_access_leaf(struct ppcg_kernel *kernel,
1871 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1872 __isl_keep isl_ast_build *build)
1874 struct ppcg_kernel_stmt *stmt;
1875 struct gpu_array_tile *tile;
1876 isl_id *id;
1877 isl_ast_expr *expr;
1878 isl_space *space;
1879 isl_map *access;
1880 isl_pw_multi_aff *pma, *pma2;
1881 const char *type;
1883 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1884 if (!stmt)
1885 return isl_ast_node_free(node);
1887 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1888 type = isl_map_get_tuple_name(access, isl_dim_in);
1889 stmt->u.c.read = !strcmp(type, "read");
1890 access = isl_map_reverse(access);
1891 pma = isl_pw_multi_aff_from_map(access);
1892 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1894 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1895 space = isl_space_unwrap(space);
1896 pma2 = isl_pw_multi_aff_range_map(space);
1897 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1898 isl_pw_multi_aff_copy(pma));
1899 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1900 stmt->u.c.index = expr;
1902 tile = gpu_array_ref_group_tile(group);
1903 pma2 = isl_pw_multi_aff_from_multi_aff(
1904 isl_multi_aff_copy(tile->tiling));
1905 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1906 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1907 stmt->u.c.local_index = expr;
1909 stmt->u.c.array = group->array;
1910 stmt->u.c.local_array = group->local_array;
1911 stmt->type = ppcg_kernel_copy;
1913 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1914 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1915 return isl_ast_node_set_annotation(node, id);
1918 /* Create a synchronization ppcg_kernel_stmt and
1919 * attach it to the node "node" representing the synchronization.
1921 static __isl_give isl_ast_node *create_sync_leaf(
1922 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1923 __isl_keep isl_ast_build *build)
1925 struct ppcg_kernel_stmt *stmt;
1926 isl_id *id;
1928 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1929 if (!stmt)
1930 return isl_ast_node_free(node);
1932 stmt->type = ppcg_kernel_sync;
1933 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1934 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1935 return isl_ast_node_set_annotation(node, id);
1938 /* Internal data structure for at_domain.
1940 * "prog" represents the entire scop.
1941 * "kernel" points to the kernel to which the current schedule node
1942 * belongs. It is set by before_mark and reset by after_mark.
1943 * It may be NULL if we are outside any kernel.
1945 struct ppcg_at_domain_data {
1946 struct gpu_prog *prog;
1947 struct ppcg_kernel *kernel;
1950 /* This function is called for each instance of a user statement
1951 * in the kernel. This may be one of the original user statements
1952 * or a statement introduced by PPCG.
1954 * We first check if the statement id corresponds to a gpu statement,
1955 * which indicates the statement is an original user statement. Any statement
1956 * that is not an original user statement has been introduced by PPCG and
1957 * requires special handling.
1959 * If the user statement is one of the original user statements, then we call
1960 * create_domain_leaf. Otherwise, we check if it is a copy or synchronization
1961 * statement and call the appropriate functions. Statements that copy an array
1962 * to/from the device do not need any further treatment.
1964 static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
1965 __isl_keep isl_ast_build *build, void *user)
1967 struct ppcg_at_domain_data *data = user;
1968 struct gpu_stmt *gpu_stmt;
1969 isl_ast_expr *expr, *arg;
1970 isl_id *id;
1971 int is_sync;
1972 const char *name;
1973 void *p;
1975 expr = isl_ast_node_user_get_expr(node);
1976 arg = isl_ast_expr_get_op_arg(expr, 0);
1977 id = isl_ast_expr_get_id(arg);
1978 name = isl_id_get_name(id);
1979 p = isl_id_get_user(id);
1980 isl_ast_expr_free(expr);
1981 isl_ast_expr_free(arg);
1983 gpu_stmt = find_stmt(data->prog, id);
1984 is_sync = gpu_tree_id_is_sync(id, data->kernel);
1985 isl_id_free(id);
1987 if (gpu_stmt)
1988 return create_domain_leaf(data->kernel, node, build, gpu_stmt);
1990 if (!prefixcmp(name, "to_device_") || !prefixcmp(name, "from_device_"))
1991 return node;
1992 if (is_sync < 0)
1993 return isl_ast_node_free(node);
1994 if (!strcmp(name, "read") || !strcmp(name, "write")) {
1995 struct gpu_array_ref_group *group = p;
1996 return create_access_leaf(data->kernel, group, node, build);
1998 if (!is_sync)
1999 isl_die(data->prog->ctx, isl_error_internal,
2000 "unknown statement type",
2001 return isl_ast_node_free(node));
2002 return create_sync_leaf(data->kernel, node, build);
2005 /* Given a set of wrapped references "ref", return the corresponding
2006 * access relations based on the tagged access relations "tagged".
2008 * The elements of "ref" are of the form
2010 * [D -> R]
2012 * with D an iteration domains and R a reference.
2013 * The elements of "tagged" are of the form
2015 * [D -> R] -> A
2017 * with A an array.
2019 * Extend "tagged" to include the iteration domain in the range, i.e.,
2021 * [D -> R] -> [D -> A]
2023 * apply the result to "ref" and then unwrap the resulting set
2024 * to obtain relations of the form
2026 * D -> A
2028 static __isl_give isl_union_map *wrapped_reference_to_access(
2029 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
2031 isl_union_map *tag2access;
2033 tag2access = isl_union_map_copy(tagged);
2034 tag2access = isl_union_map_universe(tag2access);
2035 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
2036 tag2access = isl_union_map_domain_map(tag2access);
2037 tag2access = isl_union_map_range_product(tag2access, tagged);
2039 ref = isl_union_set_coalesce(ref);
2040 ref = isl_union_set_apply(ref, tag2access);
2042 return isl_union_set_unwrap(ref);
2045 /* Given an access relation "access" from one or more array reference groups,
2046 * remove those reads if ("read" is 1) or writes (if "read" is 0)
2047 * that are only needed to communicate data within
2048 * the same iteration of "sched".
2049 * "tagged" contains all tagged access relations to all
2050 * the array reference groups accessed by "access" from statement
2051 * instances scheduled by "sched".
2053 * If the access is a read then it is either an element of
2055 * live_in union (range flow)
2057 * where live_in and flow may be overapproximations, or
2058 * it reads an uninitialized value (that is not live-in because
2059 * there is an intermediate kill) or it reads a value that was
2060 * written within the same (compound) statement instance.
2061 * If the access is a write then it is either an element of
2063 * live_out union (domain flow)
2065 * or it writes a value that is never read (and is not live-out
2066 * because of an intermediate kill) or only
2067 * within the same (compound) statement instance.
2068 * In both cases, the access relation is also a subset of
2069 * the group access relation.
2071 * The cases where an uninitialized value is read or a value is written
2072 * that is never read or where the dataflow occurs within a statement
2073 * instance are also considered local and may also be removed.
2075 * Essentially, we compute the intersection of "access" with either
2077 * live_in union (range non-local-flow)
2079 * or
2081 * live_out union (domain non-local-flow)
2083 * We first construct a relation "local"
2085 * [[D -> R] -> [D' -> R']]
2087 * of pairs of domain iterations accessing the reference group
2088 * and references in the group that are coscheduled by "sched".
2090 * If this relation does not intersect the dataflow dependences,
2091 * then there is nothing we can possibly remove, unless the dataflow
2092 * dependences themselves only relate a subset of the accesses.
2093 * In particular, the accesses may not be involved in any dataflow
2094 * dependences, either because they are uninitialized reads/dead writes
2095 * or because the dataflow occurs inside a statement instance.
2097 * Since the computation below may break up the access relation
2098 * into smaller pieces, we only perform the intersection with
2099 * the non-local dependent accesses if the local pairs
2100 * intersect the dataflow dependences. Otherwise, we intersect
2101 * with the universe of the non-local dependent accesses.
2102 * This should at least remove accesses from statements that
2103 * do not participate in any dependences.
2105 * In particular, we remove the "local" dataflow dependences from
2106 * the set of all dataflow dependences, or at least those
2107 * that may contribute to a domain/range that intersects
2108 * the domain of "access".
2109 * Note that if the potential dataflow dependences are an overapproximation
2110 * of the actual dataflow dependences, then the result remains an
2111 * overapproximation of the non-local dataflow dependences.
2112 * Copying to/from global memory is only needed for the references
2113 * in the domain/range of the result or for accesses that are live out/in
2114 * for the entire scop.
2116 * We therefore map the domain/range of the "external" relation
2117 * to the corresponding access relation and take the union with
2118 * the live out/in relation.
2120 static __isl_give isl_union_map *remove_local_accesses(
2121 struct gpu_prog *prog, __isl_take isl_union_map *tagged,
2122 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2123 int read)
2125 int empty;
2126 isl_union_pw_multi_aff *tagger;
2127 isl_union_set *domain, *access_domain;
2128 isl_union_map *local, *external, *universe;
2129 isl_union_set *tag_set;
2131 if (isl_union_map_is_empty(access)) {
2132 isl_union_map_free(sched);
2133 isl_union_map_free(tagged);
2134 return access;
2137 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2138 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2139 tagger = isl_union_pw_multi_aff_intersect_domain(tagger,
2140 isl_union_set_copy(domain));
2141 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2143 local = isl_union_map_apply_range(sched,
2144 isl_union_map_reverse(isl_union_map_copy(sched)));
2145 local = isl_union_map_intersect(local,
2146 isl_union_map_copy(prog->scop->tagged_dep_flow));
2148 empty = isl_union_map_is_empty(local);
2150 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2151 universe = isl_union_map_universe(isl_union_map_copy(access));
2152 access_domain = isl_union_map_domain(universe);
2153 domain = isl_union_set_universe(domain);
2154 universe = isl_union_set_unwrap(domain);
2155 universe = isl_union_map_intersect_domain(universe, access_domain);
2156 domain = isl_union_map_wrap(universe);
2157 if (read)
2158 external = isl_union_map_intersect_range(external, domain);
2159 else
2160 external = isl_union_map_intersect_domain(external, domain);
2161 external = isl_union_map_intersect_params(external,
2162 isl_set_copy(prog->scop->context));
2163 external = isl_union_map_subtract(external, local);
2165 if (read) {
2166 tag_set = isl_union_map_range(external);
2167 external = wrapped_reference_to_access(tag_set, tagged);
2168 external = isl_union_map_union(external,
2169 isl_union_map_copy(prog->scop->live_in));
2170 } else {
2171 tag_set = isl_union_map_domain(external);
2172 external = wrapped_reference_to_access(tag_set, tagged);
2173 external = isl_union_map_union(external,
2174 isl_union_map_copy(prog->scop->live_out));
2177 if (empty < 0)
2178 external = isl_union_map_free(external);
2179 else if (empty)
2180 external = isl_union_map_universe(external);
2182 access = isl_union_map_intersect(access, external);
2184 return access;
2187 /* Given an access relation "access" from "group", remove those reads
2188 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2189 * communicate data within the same iteration of the schedule at the
2190 * position where the copying of the group is inserted.
2191 * "node" points to this position, i.e., the depth at "node"
2192 * is equal to group->depth.
2194 * We extract a schedule that picks out the iterations of the outer
2195 * group->depth dimensions and call remove_local_accesses.
2197 static __isl_give isl_union_map *remove_local_accesses_group(
2198 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2199 __isl_take isl_union_map *access, __isl_keep isl_schedule_node *node,
2200 int read)
2202 isl_union_map *sched, *tagged;
2204 if (isl_union_map_is_empty(access))
2205 return access;
2207 tagged = group_tagged_access_relation(group);
2208 sched = isl_schedule_node_get_prefix_schedule_relation(node);
2210 return remove_local_accesses(kernel->prog, tagged, access, sched, read);
2213 /* This function is called before the AST generator starts traversing
2214 * the schedule subtree of a node with mark "mark".
2216 * If the mark is called "kernel", store the kernel pointer in data->kernel
2217 * for use in at_domain.
2219 static int before_mark(__isl_keep isl_id *mark,
2220 __isl_keep isl_ast_build *build, void *user)
2222 struct ppcg_at_domain_data *data = user;
2224 if (!mark)
2225 return -1;
2226 if (!strcmp(isl_id_get_name(mark), "kernel"))
2227 data->kernel = isl_id_get_user(mark);
2228 return 0;
2231 /* This function is called after the AST generator has finished traversing
2232 * the schedule subtree of a mark node. "node" points to the corresponding
2233 * mark AST node.
2235 * If the mark is called "kernel", then replace "node" by a user node
2236 * that "calls" the kernel, representing the launch of the kernel.
2237 * The original "node" is stored inside the kernel object so that
2238 * it can be used to print the device code.
2239 * Note that this assumes that a kernel is only launched once.
2240 * Also clear data->kernel.
2242 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2243 __isl_keep isl_ast_build *build, void *user)
2245 isl_ctx *ctx;
2246 isl_id *id;
2247 isl_ast_expr *expr;
2248 isl_ast_expr_list *list;
2249 struct ppcg_kernel *kernel;
2250 struct ppcg_at_domain_data *data = user;
2252 ctx = isl_ast_node_get_ctx(node);
2253 id = isl_ast_node_mark_get_id(node);
2254 if (!id)
2255 return isl_ast_node_free(node);
2256 if (strcmp(isl_id_get_name(id), "kernel") || !data->kernel) {
2257 isl_id_free(id);
2258 return node;
2260 kernel = data->kernel;
2261 data->kernel = NULL;
2262 kernel->space = isl_ast_build_get_schedule_space(build);
2263 kernel->tree = isl_ast_node_mark_get_node(node);
2264 isl_ast_node_free(node);
2266 expr = isl_ast_expr_from_id(isl_id_copy(id));
2267 list = isl_ast_expr_list_alloc(ctx, 0);
2268 expr = isl_ast_expr_call(expr, list);
2269 node = isl_ast_node_alloc_user(expr);
2270 node = isl_ast_node_set_annotation(node, id);
2272 return node;
2275 static isl_bool update_depth(__isl_keep isl_schedule_node *node, void *user)
2277 int *depth = user;
2278 int node_depth;
2280 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2281 return isl_bool_true;
2282 node_depth = isl_schedule_node_get_schedule_depth(node);
2283 if (node_depth > *depth)
2284 *depth = node_depth;
2286 return isl_bool_false;
2289 /* Use isl to generate code for both the host and the device
2290 * from "schedule".
2291 * The device code is marked by "kernel" mark nodes in the schedule tree,
2292 * containing a pointer to a ppcg_kernel object.
2293 * The returned AST only contains the AST for the host code.
2294 * The ASTs for the device code are embedded in ppcg_kernel objects
2295 * attached to the leaf nodes that call "kernel".
2297 static __isl_give isl_ast_node *generate_code(struct gpu_gen *gen,
2298 __isl_take isl_schedule *schedule)
2300 struct ppcg_at_domain_data data;
2301 isl_ast_build *build;
2302 isl_ast_node *tree;
2303 isl_id_list *iterators;
2304 int depth;
2306 data.prog = gen->prog;
2307 data.kernel = NULL;
2309 depth = 0;
2310 if (isl_schedule_foreach_schedule_node_top_down(schedule, &update_depth,
2311 &depth) < 0)
2312 return NULL;
2313 build = isl_ast_build_alloc(gen->prog->ctx);
2314 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2315 build = isl_ast_build_set_iterators(build, iterators);
2316 build = isl_ast_build_set_at_each_domain(build, &at_domain, &data);
2317 build = isl_ast_build_set_before_each_mark(build, &before_mark, &data);
2318 build = isl_ast_build_set_after_each_mark(build, &after_mark, &data);
2319 if (gen->prog->scop->options->debug->dump_final_schedule)
2320 isl_schedule_dump(schedule);
2321 tree = isl_ast_build_node_from_schedule(build, schedule);
2322 isl_ast_build_free(build);
2324 return tree;
2327 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2329 if (!str)
2330 return NULL;
2331 return isl_union_map_read_from_str(ctx, str);
2334 /* Can "node" be tiled and then mapped to block and thread identifiers?
2335 * That is, is it permutable with at least one coincident dimension?
2337 static int is_permutable(__isl_keep isl_schedule_node *node)
2339 if (!node)
2340 return -1;
2342 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
2343 return 0;
2344 if (!isl_schedule_node_band_get_permutable(node))
2345 return 0;
2346 if (isl_schedule_node_band_n_member(node) < 1)
2347 return 0;
2348 if (!isl_schedule_node_band_member_get_coincident(node, 0))
2349 return 0;
2351 return 1;
2354 /* A isl_schedule_foreach_schedule_node_top_down callback
2355 * for setting *any_permutable and aborting the search
2356 * if "node" is a permutable band with coincident dimensions.
2357 * Otherwise, continue searching.
2359 static isl_bool set_permutable(__isl_keep isl_schedule_node *node, void *user)
2361 int *any_permutable = user;
2362 int permutable;
2364 permutable = is_permutable(node);
2365 if (permutable < 0)
2366 return isl_bool_error;
2367 if (!permutable)
2368 return isl_bool_true;
2370 *any_permutable = 1;
2372 return isl_bool_error;
2375 /* Does "schedule" contain any permutable band with at least one coincident
2376 * member?
2378 static int has_any_permutable_node(__isl_keep isl_schedule *schedule)
2380 int any_permutable = 0;
2382 if (isl_schedule_foreach_schedule_node_top_down(schedule,
2383 &set_permutable, &any_permutable) < 0 &&
2384 !any_permutable)
2385 return -1;
2387 return any_permutable;
2390 /* Is "node" a leaf or can it be tiled and then mapped to
2391 * block and thread identifiers?
2393 static int is_leaf_or_tilable(__isl_keep isl_schedule_node *node)
2395 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
2396 return 1;
2397 return is_permutable(node);
2400 /* Is "node" the outermost node in its branch that can be tiled
2401 * and then mapped to block and thread identifiers?
2402 * If there are no such nodes in the branch and if "node" is a leaf,
2403 * then it is accepted too.
2405 static int is_outer_tilable(__isl_keep isl_schedule_node *node)
2407 int tilable;
2408 isl_schedule_node *ancestor;
2410 tilable = is_leaf_or_tilable(node);
2411 if (tilable < 0)
2412 return -1;
2413 if (!tilable)
2414 return 0;
2416 tilable = 0;
2417 ancestor = isl_schedule_node_copy(node);
2418 while (isl_schedule_node_has_parent(ancestor)) {
2419 ancestor = isl_schedule_node_parent(ancestor);
2421 tilable = is_permutable(ancestor);
2422 if (tilable < 0 || tilable)
2423 break;
2426 isl_schedule_node_free(ancestor);
2427 return tilable < 0 ? -1 : !tilable;
2430 /* Collect the references to all writes in "group".
2431 * Each reference is represented by a universe set in a space
2433 * [S[i,j] -> R[]]
2435 * with S[i,j] the statement instance space and R[] the array reference.
2437 static __isl_give isl_union_set *group_tagged_writes(
2438 struct gpu_array_ref_group *group)
2440 int i;
2441 isl_space *space;
2442 isl_union_set *writes;
2444 space = isl_map_get_space(group->access);
2445 writes = isl_union_set_empty(space);
2446 for (i = 0; i < group->n_ref; ++i) {
2447 isl_space *space;
2448 isl_set *writes_i;
2450 if (!group->refs[i]->write)
2451 continue;
2453 space = isl_map_get_space(group->refs[i]->tagged_access);
2454 space = isl_space_domain(space);
2455 writes_i = isl_set_universe(space);
2456 writes = isl_union_set_add_set(writes, writes_i);
2459 return writes;
2462 /* Is there any write access in "group" that requires synchronization
2463 * on a write to global memory?
2464 * We currently take into account all writes that would require
2465 * synchronization at the thread level depth, but if the copying
2466 * for this group is performed at an outer level, then we do not
2467 * actually need to take into account dependences at intermediate levels.
2469 static int any_sync_writes_in_group(struct ppcg_kernel *kernel,
2470 struct gpu_array_ref_group *group)
2472 isl_union_set *writes;
2473 int empty, disjoint;
2475 empty = isl_union_set_is_empty(kernel->sync_writes);
2476 if (empty < 0)
2477 return -1;
2478 if (empty)
2479 return 0;
2481 writes = group_tagged_writes(group);
2482 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2483 isl_union_set_free(writes);
2485 return disjoint < 0 ? -1 : !disjoint;
2488 /* Collect the references to all writes in "kernel" that write directly
2489 * to global or shared memory, i.e., that are not mapped to private memory.
2490 * Each reference is represented by a universe set in a space
2492 * [S[i,j] -> R[]]
2494 * with S[i,j] the statement instance space and R[] the array reference.
2496 static __isl_give isl_union_set *collect_non_private_tagged_writes(
2497 struct ppcg_kernel *kernel)
2499 isl_union_set *writes;
2500 int i, j;
2502 writes = isl_union_set_empty(isl_union_set_get_space(kernel->arrays));
2504 for (i = 0; i < kernel->n_array; ++i) {
2505 struct gpu_local_array_info *array = &kernel->array[i];
2507 for (j = 0; j < array->n_group; ++j) {
2508 struct gpu_array_ref_group *group = array->groups[j];
2509 isl_union_set *writes_ij;
2511 if (!group->write)
2512 continue;
2513 if (group->private_tile)
2514 continue;
2515 writes_ij = group_tagged_writes(group);
2516 writes = isl_union_set_union(writes, writes_ij);
2520 return writes;
2523 /* Are there any direct writes to global memory that require
2524 * synchronization?
2526 static int any_global_or_shared_sync_writes(struct ppcg_kernel *kernel)
2528 isl_union_set *writes;
2529 int empty, disjoint;
2531 empty = isl_union_set_is_empty(kernel->sync_writes);
2532 if (empty < 0)
2533 return -1;
2534 if (empty)
2535 return 0;
2537 writes = collect_non_private_tagged_writes(kernel);
2538 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2539 isl_union_set_free(writes);
2541 return disjoint < 0 ? -1 : !disjoint;
2544 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
2545 * from the elements in "tile_size".
2547 static __isl_give isl_multi_val *construct_band_tiles_sizes(
2548 __isl_keep isl_schedule_node *node, int *tile_size)
2550 int i, n;
2551 isl_ctx *ctx;
2552 isl_space *space;
2553 isl_multi_val *mv;
2555 if (!node)
2556 return NULL;
2558 ctx = isl_schedule_node_get_ctx(node);
2559 space = isl_schedule_node_band_get_space(node);
2560 n = isl_schedule_node_band_n_member(node);
2561 mv = isl_multi_val_zero(space);
2562 for (i = 0; i < n; ++i) {
2563 isl_val *v;
2565 v = isl_val_int_from_si(ctx, tile_size[i]);
2566 mv = isl_multi_val_set_val(mv, i, v);
2569 return mv;
2572 /* Replace the partial schedule S of the band node "node" by
2574 * floor(S/f)
2576 * or
2578 * f * floor(S/f)
2580 * if scale_tile_loops is set, with f the integers in "factor".
2581 * The list that "factor" points to is assumed to contain at least
2582 * as many elements as the number of members in the band.
2584 static __isl_give isl_schedule_node *snap_band_to_sizes(
2585 __isl_take isl_schedule_node *node, int *factor,
2586 struct ppcg_options *options)
2588 isl_multi_val *mv;
2590 mv = construct_band_tiles_sizes(node, factor);
2591 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2592 if (options->scale_tile_loops)
2593 node = isl_schedule_node_band_scale(node,
2594 isl_multi_val_copy(mv));
2595 isl_multi_val_free(mv);
2597 return node;
2600 /* Tile "band" with tile size specified by "sizes".
2602 * Since the tile loops will be mapped to block ids, we forcibly
2603 * turn off tile loop scaling. We may want to enable tile loop scaling
2604 * at some later point, but then we would have to support the detection
2605 * of strides during the mapping to block ids.
2606 * Similarly, since the point loops will be mapped to thread ids,
2607 * we forcibly shift the point loops so that they start at zero.
2609 static __isl_give isl_schedule_node *tile_band(
2610 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2612 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2613 int scale_tile;
2614 int shift_point;
2616 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2617 isl_options_set_tile_scale_tile_loops(ctx, 0);
2618 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2619 isl_options_set_tile_shift_point_loops(ctx, 1);
2621 node = isl_schedule_node_band_tile(node, sizes);
2623 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2624 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2626 return node;
2629 /* Extract the set of parameter values and outer schedule dimensions
2630 * for which any statement instance
2631 * in the kernel inserted at "node" needs to be executed.
2632 * Intersect the set of parameter values derived from the host schedule
2633 * relation with the context of "prog".
2635 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2636 struct gpu_prog *prog)
2638 isl_union_map *schedule;
2639 isl_union_set *schedule_domain;
2640 isl_set *context;
2641 int empty;
2643 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2644 schedule_domain = isl_union_map_range(schedule);
2645 empty = isl_union_set_is_empty(schedule_domain);
2646 if (empty < 0) {
2647 isl_union_set_free(schedule_domain);
2648 return NULL;
2650 if (empty) {
2651 int depth;
2652 isl_space *space;
2654 space = isl_union_set_get_space(schedule_domain);
2655 isl_union_set_free(schedule_domain);
2656 space = isl_space_set_from_params(space);
2657 depth = isl_schedule_node_get_schedule_depth(node);
2658 space = isl_space_add_dims(space, isl_dim_set, depth);
2659 context = isl_set_empty(space);
2660 } else {
2661 context = isl_set_from_union_set(schedule_domain);
2663 context = isl_set_intersect_params(context,
2664 isl_set_copy(prog->context));
2666 return context;
2669 /* Return the set of outer array elements accessed by
2670 * by the statement instance in "domain" in "prog".
2672 static __isl_give isl_union_set *accessed_by_domain(
2673 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2675 isl_union_map *access;
2676 isl_union_set *arrays;
2678 access = isl_union_map_union(isl_union_map_copy(prog->read),
2679 isl_union_map_copy(prog->may_write));
2680 access = isl_union_map_intersect_domain(access, domain);
2681 arrays = isl_union_map_range(access);
2682 arrays = isl_union_set_apply(arrays,
2683 isl_union_map_copy(prog->to_outer));
2685 return arrays;
2688 /* Return the number of outer band members of the band node "node"
2689 * that are marked coincident.
2691 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2693 int i, n;
2695 n = isl_schedule_node_band_n_member(node);
2697 for (i = 0; i < n; ++i)
2698 if (!isl_schedule_node_band_member_get_coincident(node, i))
2699 break;
2701 return i;
2704 /* If the band node "node" has more than "n" members, then split off
2705 * the first "n" of them.
2707 static __isl_give isl_schedule_node *split_band(
2708 __isl_take isl_schedule_node *node, int n)
2710 int dim;
2712 dim = isl_schedule_node_band_n_member(node);
2713 if (n < dim)
2714 node = isl_schedule_node_band_split(node, n);
2716 return node;
2719 /* Scale a band node that may have been split by split_band.
2720 * "sizes" are the scaling factors for the original node.
2721 * "node" either points to the original band node, or the outer
2722 * of the two pieces after splitting.
2724 * If the number of elements in "node" is smaller than the number of
2725 * elements in "sizes", then some splitting has occurred and we split
2726 * "sizes" in the same way.
2728 static __isl_give isl_schedule_node *scale_band(
2729 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2731 int n, dim;
2733 n = isl_multi_val_dim(sizes, isl_dim_set);
2734 dim = isl_schedule_node_band_n_member(node);
2735 if (n > dim) {
2736 isl_multi_val *sizes2;
2738 sizes2 = isl_multi_val_copy(sizes);
2739 sizes = isl_multi_val_drop_dims(sizes,
2740 isl_dim_set, dim, n - dim);
2741 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2742 node = isl_schedule_node_child(node, 0);
2743 node = isl_schedule_node_band_scale(node, sizes2);
2744 node = isl_schedule_node_parent(node);
2747 return isl_schedule_node_band_scale(node, sizes);
2750 /* Return an isl_multi_aff, with as elements the parameters in "space"
2751 * that have the names specified by the elements in "names".
2752 * If (some of) these parameters do not already appear in "space",
2753 * then they are added first.
2755 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2756 __isl_keep isl_id_list *names)
2758 int i, n;
2759 isl_local_space *ls;
2760 isl_multi_aff *ma;
2762 if (!names)
2763 space = isl_space_free(space);
2765 n = isl_id_list_n_id(names);
2766 for (i = 0; i < n; ++i) {
2767 int pos;
2768 isl_id *id;
2770 id = isl_id_list_get_id(names, i);
2771 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2772 if (pos >= 0) {
2773 isl_id_free(id);
2774 continue;
2776 pos = isl_space_dim(space, isl_dim_param);
2777 space = isl_space_add_dims(space, isl_dim_param, 1);
2778 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2780 ma = isl_multi_aff_zero(isl_space_copy(space));
2781 ls = isl_local_space_from_space(isl_space_domain(space));
2782 for (i = 0; i < n; ++i) {
2783 int pos;
2784 isl_id *id;
2785 isl_aff *aff;
2787 id = isl_id_list_get_id(names, i);
2788 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2789 isl_id_free(id);
2790 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2791 isl_dim_param, pos);
2792 ma = isl_multi_aff_set_aff(ma, i, aff);
2794 isl_local_space_free(ls);
2796 return ma;
2799 /* Return constraints on the domain elements that equate a sequence of
2800 * parameters called "names", to the partial schedule
2801 * of "node" modulo the integers in "size".
2802 * The number of elements in the array "size" should be equal
2803 * to the number of elements in "names".
2804 * The number of members of the band node "node" should be smaller
2805 * than or equal to this number. If it is smaller, then the first
2806 * elements of "names" are equated to zero.
2808 static __isl_give isl_union_set *set_schedule_modulo(
2809 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
2810 int *size)
2812 int n, n_zero;
2813 isl_space *space;
2814 isl_multi_aff *ma;
2815 isl_multi_union_pw_aff *mupa, *mupa2;
2816 isl_multi_val *mv;
2817 isl_union_set *domain;
2819 if (!node)
2820 return NULL;
2821 n = isl_id_list_n_id(names);
2822 if (n == 0)
2823 return isl_schedule_node_get_universe_domain(node);
2824 n_zero = n - isl_schedule_node_band_n_member(node);
2826 mupa = isl_schedule_node_band_get_partial_schedule(node);
2827 mv = construct_band_tiles_sizes(node, size + n_zero);
2828 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
2830 space = isl_multi_union_pw_aff_get_space(mupa);
2831 space = isl_space_params(space);
2832 space = isl_space_set_from_params(space);
2833 space = isl_space_add_dims(space, isl_dim_set, n_zero);
2834 ma = isl_multi_aff_zero(space);
2836 domain = isl_schedule_node_get_universe_domain(node);
2837 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
2838 isl_union_set_copy(domain), ma);
2839 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
2841 space = isl_multi_union_pw_aff_get_space(mupa);
2842 ma = parameter_vector(space, names);
2844 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
2845 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
2847 return isl_multi_union_pw_aff_zero_union_set(mupa);
2850 /* Insert a context node at "node" introducing the block and thread
2851 * identifiers along with their bounds, which are stored in kernel->grid_size
2852 * and kernel->block_dim.
2853 * Note that the bounds on the block identifiers may implicitly impose
2854 * constraints on the parameters. A guard needs to be inserted
2855 * in the schedule tree to ensure that those bounds hold at "node".
2856 * This guard is inserted in insert_guard.
2858 static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
2859 __isl_take isl_schedule_node *node)
2861 isl_set *context;
2863 context = isl_set_universe(isl_set_get_space(kernel->context));
2865 context = add_bounded_parameters_dynamic(context,
2866 kernel->grid_size, kernel->block_ids);
2867 context = add_bounded_parameters(context,
2868 kernel->block_dim, kernel->thread_ids);
2870 node = isl_schedule_node_insert_context(node, context);
2872 return node;
2875 /* Insert a guard that eliminates kernel launches where the kernel
2876 * obviously does not have any work to do.
2878 * In particular, eliminate kernel launches where there are obviously
2879 * zero blocks.
2880 * Use the same block size constraints that are used to create the context
2881 * to ensure that all constraints implicit in the constructed context
2882 * are imposed by the guard.
2884 * Additionally, add other constraints that are valid
2885 * for each executed instance ("context"), as long as this does not result
2886 * in a disjunction.
2888 static __isl_give isl_schedule_node *insert_guard(
2889 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
2890 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
2892 unsigned nparam, n;
2893 isl_set *guard;
2894 isl_id_list *ids;
2896 guard = isl_set_copy(context);
2897 guard = isl_set_compute_divs(guard);
2898 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
2900 nparam = isl_set_dim(guard, isl_dim_param);
2901 n = isl_multi_pw_aff_dim(size, isl_dim_out);
2902 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
2903 guard = add_bounded_parameters_dynamic(guard, size, ids);
2904 isl_id_list_free(ids);
2905 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
2907 node = isl_schedule_node_insert_guard(node, guard);
2909 return node;
2912 /* Does any array reference group mapping require the band that is mapped
2913 * to threads to be unrolled?
2915 static int kernel_requires_unroll(struct ppcg_kernel *kernel)
2917 int i, j;
2919 for (i = 0; i < kernel->n_array; ++i) {
2920 struct gpu_local_array_info *array = &kernel->array[i];
2922 for (j = 0; j < array->n_group; ++j) {
2923 struct gpu_array_ref_group *group = array->groups[j];
2924 if (gpu_array_ref_group_requires_unroll(group))
2925 return 1;
2929 return 0;
2932 /* Mark the given band node "node" for unrolling by the AST generator and
2933 * then sink it to the leaves of the schedule tree.
2934 * All dimensions of "node" are assumed to be coincident, such that this
2935 * sinking is a valid operation.
2937 static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
2939 int i, n;
2941 n = isl_schedule_node_band_n_member(node);
2942 for (i = 0; i < n; ++i)
2943 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
2944 isl_ast_loop_unroll);
2946 node = isl_schedule_node_band_sink(node);
2948 return node;
2951 /* Insert a synchronization node in the schedule tree of "node"
2952 * after the core computation of "kernel" at the level of the band
2953 * that is mapped to threads, except if that level is equal to
2954 * that of the band that is mapped to blocks or if there are no writes
2955 * to global or shared memory in the core computation that require
2956 * synchronization.
2957 * If there are any writes to shared memory and the shared memory
2958 * copying is performed at the same level, then synchronization
2959 * is needed between the core and the copying anyway, so we might
2960 * as well add it here. If the copying is performed at a higher
2961 * level, then different iterations of intermediate schedule dimensions
2962 * may have a different mapping from between shared memory elements and
2963 * threads, such that synchronization is required after the core.
2964 * "node" is assumed to point to the kernel node.
2966 static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
2967 __isl_take isl_schedule_node *node)
2969 int kernel_depth;
2970 int need_sync;
2972 need_sync = any_global_or_shared_sync_writes(kernel);
2973 if (need_sync < 0)
2974 return isl_schedule_node_free(node);
2975 if (!need_sync)
2976 return node;
2978 kernel_depth = isl_schedule_node_get_schedule_depth(node);
2980 node = gpu_tree_move_down_to_thread(node, kernel->core);
2981 if (kernel_depth == isl_schedule_node_get_schedule_depth(node))
2982 return gpu_tree_move_up_to_kernel(node);
2984 node = gpu_tree_ensure_following_sync(node, kernel);
2986 node = gpu_tree_move_up_to_kernel(node);
2988 return node;
2991 /* Return a read ("read" is 1) or write access relation for "group"
2992 * with those accesses removed that are only needed to communicate data
2993 * within the subtree of the schedule rooted at "node".
2994 * Furthermore, include the prefix schedule at "node".
2995 * That is, return a relation of the form
2997 * S -> [D -> A]
2999 * with D the outer schedule dimensions at "node".
3001 static __isl_give isl_union_map *anchored_non_local_accesses(
3002 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3003 __isl_take isl_schedule_node *node, int read)
3005 isl_union_map *access;
3006 isl_union_map *prefix;
3008 access = gpu_array_ref_group_access_relation(group, read, !read);
3009 access = remove_local_accesses_group(kernel, group, access, node, read);
3010 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
3011 access = isl_union_map_range_product(prefix, access);
3013 return access;
3016 /* Given an array reference group "group", create a mapping
3018 * read[D -> A] -> [D -> A]
3020 * if "read" is set or
3022 * write[D -> A] -> [D -> A]
3024 * if "read" is not set.
3025 * D corresponds to the outer group->depth dimensions of
3026 * the kernel schedule.
3028 static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
3029 struct gpu_array_ref_group *group, int read)
3031 isl_space *space;
3032 isl_id *id;
3034 space = isl_space_copy(group->array->space);
3035 space = isl_space_from_range(space);
3036 space = isl_space_add_dims(space, isl_dim_in, group->depth);
3037 space = isl_space_wrap(space);
3038 space = isl_space_map_from_set(space);
3040 id = isl_id_alloc(ctx, read ? "read" : "write", group);
3041 space = isl_space_set_tuple_id(space, isl_dim_in, id);
3043 return isl_multi_aff_identity(space);
3046 /* If any writes in "group" require synchronization, then make sure
3047 * that there is a synchronization node for "kernel" after the node
3048 * following "node" in a sequence.
3050 * If "shared" is set and no synchronization is needed for
3051 * the writes to global memory, then add synchronization before
3052 * the kernel to protect shared memory from being overwritten
3053 * by the next iteration of the core computation.
3054 * No additional synchronization is needed to protect against
3055 * the next copy into shared memory because each element of
3056 * the shared memory tile is always copied by the same thread.
3058 static __isl_give isl_schedule_node *add_group_write_sync(
3059 __isl_take isl_schedule_node *node, struct ppcg_kernel *kernel,
3060 struct gpu_array_ref_group *group, int shared)
3062 int need_sync;
3064 need_sync = any_sync_writes_in_group(kernel, group);
3065 if (need_sync < 0)
3066 return isl_schedule_node_free(node);
3067 if (need_sync) {
3068 node = isl_schedule_node_parent(node);
3069 node = isl_schedule_node_next_sibling(node);
3070 node = isl_schedule_node_child(node, 0);
3071 node = gpu_tree_ensure_following_sync(node, kernel);
3072 } else if (shared) {
3073 node = isl_schedule_node_parent(node);
3074 node = isl_schedule_node_parent(node);
3075 node = gpu_tree_move_down_to_depth(node, group->depth,
3076 kernel->core);
3077 node = gpu_tree_move_left_to_sync(node, kernel);
3080 return node;
3083 /* Add copy statements to the schedule tree of "node"
3084 * for reading from global memory to private memory (if "read" is set) or
3085 * for writing back from private memory to global memory
3086 * (if "read" is not set) for the array reference group "group" that
3087 * is mapped to private memory.
3088 * On input, "node" points to the kernel node, and it is moved
3089 * back there on output.
3091 * The copies are performed in the order of the array elements.
3092 * The copy statement instances include a reference to the outer
3093 * group->depth dimensions of the kernel schedule for ease of
3094 * combining them with the group tiling.
3096 * That is, the extra schedule is of the form
3098 * type[D -> A] -> A
3100 * where D corresponds to the outer group->depth dimensions of
3101 * the kernel schedule and A to the global array.
3102 * This schedule is unrolled because registers are not addressable.
3104 * The copying is inserted in the schedule tree through an extension
3105 * of the form
3107 * D -> type[D -> A]
3109 * where the extra domain elements type[D -> A] are those accessed
3110 * by the group.
3111 * A filter is inserted on type[D -> A] to ensure that the element
3112 * is read/written by the same thread that needs the element.
3113 * This filter is obtained by applying
3115 * S -> type[D -> A]
3117 * to the thread filter for the core statements.
3119 * The extension is inserted before the core computation in case of a read
3120 * and after the core computation in case of a write.
3121 * In the latter case, we also make sure that there is a synchronization
3122 * node after the write to global memory, unless this write is performed
3123 * at the outer level of the kernel.
3124 * In principle, this synchronization could be inserted higher
3125 * in the schedule tree depending on where the corresponding reads
3126 * from global memory are performed.
3128 static __isl_give isl_schedule_node *add_copies_group_private(
3129 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3130 __isl_take isl_schedule_node *node, int read)
3132 isl_union_map *access;
3133 isl_union_map *prefix;
3134 isl_union_set *domain;
3135 isl_space *space;
3136 isl_multi_aff *from_access;
3137 isl_multi_pw_aff *mpa;
3138 isl_multi_union_pw_aff *mupa;
3139 isl_schedule_node *graft;
3140 isl_union_set *filter;
3141 int kernel_depth;
3142 int empty;
3144 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3145 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3147 access = anchored_non_local_accesses(kernel, group, node, read);
3148 empty = isl_union_map_is_empty(access);
3149 if (empty < 0 || empty) {
3150 isl_union_map_free(access);
3151 if (empty < 0)
3152 return isl_schedule_node_free(node);
3153 return gpu_tree_move_up_to_kernel(node);
3156 group->array->global = 1;
3157 group->local_array->global = 1;
3159 from_access = create_from_access(kernel->ctx, group, read);
3160 space = isl_space_domain(isl_multi_aff_get_space(from_access));
3161 access = isl_union_map_preimage_range_multi_aff(access, from_access);
3163 filter = isl_union_set_copy(kernel->thread_filter);
3164 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
3165 filter = isl_union_set_detect_equalities(filter);
3166 filter = isl_union_set_coalesce(filter);
3168 domain = isl_union_map_range(access);
3169 access = isl_union_set_wrapped_domain_map(domain);
3170 access = isl_union_map_reverse(access);
3171 access = isl_union_map_coalesce(access);
3172 graft = isl_schedule_node_from_extension(access);
3174 space = isl_space_map_from_set(space);
3175 mpa = isl_multi_pw_aff_identity(space);
3176 mpa = isl_multi_pw_aff_range_factor_range(mpa);
3177 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3179 graft = isl_schedule_node_child(graft, 0);
3180 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3181 graft = unroll(graft);
3183 graft = isl_schedule_node_insert_filter(graft, filter);
3185 graft = isl_schedule_node_parent(graft);
3187 if (read)
3188 node = isl_schedule_node_graft_before(node, graft);
3189 else {
3190 node = isl_schedule_node_graft_after(node, graft);
3191 if (kernel_depth < group->depth)
3192 node = add_group_write_sync(node, kernel, group, 0);
3195 node = gpu_tree_move_up_to_kernel(node);
3197 return node;
3200 /* Add copy statements to the schedule tree of "node"
3201 * for reading from global memory to shared memory (if "read" is set) or
3202 * for writing back from shared memory to global memory
3203 * (if "read" is not set) for the array reference group "group" that
3204 * is mapped to shared memory.
3205 * On input, "node" points to the kernel node, and it is moved
3206 * back there on output.
3208 * The copies are performed in the order of the corresponding shared
3209 * memory tile.
3210 * The copy statement instances include a reference to the outer
3211 * group->depth dimensions of the kernel schedule for ease of
3212 * combining them with the group tiling.
3214 * If we are performing a read from global memory to shared memory and
3215 * if the array involved is not a scalar, then we copy
3216 * the entire tile to shared memory. This may result in some extra
3217 * elements getting copied, but it should lead to simpler code
3218 * (which means that fewer registers may be needed) and less divergence.
3220 * Otherwise, we only copy the elements that will be read or have been written
3221 * in the kernel.
3223 * That is, the extra schedule is of the form
3225 * type[D -> A] -> T
3227 * where D corresponds to the outer group->depth dimensions of
3228 * the kernel schedule, A to the global array and T is the corresponding
3229 * shared memory tile.
3231 * The copying is inserted in the schedule tree through an extension
3232 * of the form
3234 * D -> type[D -> A]
3236 * where the extra domain elements type[D -> A] are those accessed
3237 * by the group. In the case of read from a non-scalar, this set
3238 * is replaced by the entire shared memory tile.
3240 * A filter is inserted on type[D -> A] to map the copy instances
3241 * to the threads. In particular, the thread identifiers are
3242 * equated to the position inside the shared memory tile (T)
3243 * modulo the block size.
3244 * We try to align the innermost tile dimension with the innermost
3245 * thread identifier (x) as a heuristic to improve coalescing.
3246 * In particular, if the dimension of the tile is greater than
3247 * the dimension of the block, then the schedule mapping to the tile
3248 * is broken up into two pieces and the filter is applied to the inner part.
3249 * If, on the other hand, the dimension of the tile is smaller than
3250 * the dimension of the block, then the initial thread identifiers
3251 * are equated to zero and the remaining thread identifiers are
3252 * matched to the memory tile.
3254 * The extension is inserted before the core computation in case of a read
3255 * and after the core computation in case of a write.
3256 * In the case of a read, we first need to make sure there is some
3257 * synchronization before the core computation such that we can put the read
3258 * from global memory to shared memory before that synchronization.
3259 * This ensures that all threads have finished copying into shared memory
3260 * before the shared memory is used.
3261 * We also need to make sure that there is a synchronization node after
3262 * the core computation to ensure that the next load into shared memory
3263 * only happens after all data has been used. There is no need for
3264 * this synchronization if we are at the outer level since then there
3265 * won't be a next load.
3266 * In the case of a write, we need to make sure there is some synchronization
3267 * after the core computation such taht we can put the write from shared
3268 * memory to global memory after that synchronization.
3269 * Unless we are at the outer level, we also need a synchronization node
3270 * after the write to ensure the data is saved to global memory
3271 * before the next iteration write to the same shared memory.
3272 * It also makes sure the data has arrived in global memory before
3273 * it is read in a subsequent iteration.
3275 static __isl_give isl_schedule_node *add_copies_group_shared(
3276 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3277 __isl_take isl_schedule_node *node, int read)
3279 struct gpu_array_tile *tile;
3280 isl_union_map *access;
3281 isl_union_set *domain;
3282 isl_union_set *sync;
3283 isl_multi_aff *ma;
3284 isl_multi_aff *from_access;
3285 isl_multi_pw_aff *mpa;
3286 isl_multi_union_pw_aff *mupa;
3287 isl_schedule_node *graft;
3288 isl_union_set *filter;
3289 int skip;
3290 int kernel_depth;
3291 int empty;
3293 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3294 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3296 access = anchored_non_local_accesses(kernel, group, node, read);
3297 empty = isl_union_map_is_empty(access);
3298 if (empty < 0 || empty) {
3299 isl_union_map_free(access);
3300 if (empty < 0)
3301 return isl_schedule_node_free(node);
3302 return gpu_tree_move_up_to_kernel(node);
3305 group->array->global = 1;
3306 group->local_array->global = 1;
3308 from_access = create_from_access(kernel->ctx, group, read);
3310 tile = gpu_array_ref_group_tile(group);
3311 ma = isl_multi_aff_copy(tile->tiling);
3312 ma = isl_multi_aff_pullback_multi_aff(ma,
3313 isl_multi_aff_copy(from_access));
3314 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3315 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3317 domain = isl_union_map_range(access);
3319 if (read && !gpu_array_is_scalar(group->array)) {
3320 isl_map *map;
3321 isl_union_set_free(domain);
3322 map = group_tile(group);
3323 domain = isl_union_set_from_set(isl_map_wrap(map));
3326 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3327 access = isl_union_set_wrapped_domain_map(domain);
3328 access = isl_union_map_reverse(access);
3329 access = isl_union_map_coalesce(access);
3330 graft = isl_schedule_node_from_extension(access);
3332 graft = isl_schedule_node_child(graft, 0);
3334 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3336 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3337 graft = isl_schedule_node_band_split(graft,
3338 tile->n - kernel->n_block);
3339 graft = isl_schedule_node_child(graft, 0);
3341 if (tile->n < kernel->n_block)
3342 skip = kernel->n_block - tile->n;
3343 else
3344 skip = 0;
3345 filter = set_schedule_modulo(graft, kernel->thread_ids,
3346 kernel->block_dim);
3347 if (!kernel->options->wrap)
3348 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3349 kernel->options);
3350 if (tile->n > kernel->n_block && kernel->n_block > 0)
3351 graft = isl_schedule_node_parent(graft);
3352 graft = isl_schedule_node_insert_filter(graft, filter);
3354 while (graft && isl_schedule_node_has_parent(graft))
3355 graft = isl_schedule_node_parent(graft);
3357 if (read) {
3358 if (kernel_depth < group->depth)
3359 node = gpu_tree_ensure_sync_after_core(node, kernel);
3360 node = gpu_tree_move_left_to_sync(node, kernel);
3361 node = isl_schedule_node_graft_before(node, graft);
3362 } else {
3363 node = gpu_tree_move_right_to_sync(node, kernel);
3364 node = isl_schedule_node_graft_after(node, graft);
3365 if (kernel_depth < group->depth)
3366 node = add_group_write_sync(node, kernel, group, 1);
3369 node = gpu_tree_move_up_to_kernel(node);
3371 return node;
3374 /* Check whether the array reference group "group" is mapped to
3375 * private or shared memory and, if so,
3376 * add copy statements to the schedule tree of "node"
3377 * for reading from global memory to private or shared memory
3378 * (if "read" is set) or for writing back from private or shared memory
3379 * to global memory (if "read" is not set) for this group.
3380 * On input, "node" points to the kernel node, and it is moved
3381 * back there on output.
3383 static __isl_give isl_schedule_node *add_copies_group(
3384 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3385 __isl_take isl_schedule_node *node, int read)
3387 if (group->private_tile)
3388 return add_copies_group_private(kernel, group, node, read);
3389 if (group->shared_tile)
3390 return add_copies_group_shared(kernel, group, node, read);
3391 return node;
3394 /* For each array reference group that is mapped to private or shared memory,
3395 * add copy statements to the schedule tree of "node"
3396 * for reading from global memory to private or shared memory
3397 * and for writing back.
3398 * On input, "node" points to the kernel node, and it is moved
3399 * back there on output.
3401 static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3402 __isl_take isl_schedule_node *node)
3404 int i, j;
3406 for (i = 0; i < kernel->n_array; ++i) {
3407 struct gpu_local_array_info *array = &kernel->array[i];
3409 for (j = 0; j < array->n_group; ++j) {
3410 struct gpu_array_ref_group *group = array->groups[j];
3412 node = add_copies_group(kernel, group, node, 1);
3413 if (!node)
3414 return NULL;
3415 node = add_copies_group(kernel, group, node, 0);
3416 if (!node)
3417 return NULL;
3421 return node;
3424 /* Mark all dimensions in the current band node atomic.
3426 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3428 int i, n;
3430 n = isl_schedule_node_band_n_member(node);
3431 for (i = 0; i < n; ++i)
3432 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
3433 isl_ast_loop_atomic);
3435 return node;
3438 /* Mark "node" atomic, if it is a band node.
3439 * Do the same for all ancestors.
3440 * Return a pointer to "node" (in the updated schedule tree).
3442 static __isl_give isl_schedule_node *atomic_ancestors(
3443 __isl_take isl_schedule_node *node)
3445 int pos;
3447 if (!node)
3448 return NULL;
3449 if (!isl_schedule_node_has_parent(node))
3450 return node;
3452 pos = isl_schedule_node_get_child_position(node);
3453 node = isl_schedule_node_parent(node);
3454 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3455 node = atomic(node);
3456 node = atomic_ancestors(node);
3457 node = isl_schedule_node_child(node, pos);
3459 return node;
3462 /* Collect all write references that require synchronization.
3463 * "node" is assumed to point to the kernel node.
3464 * Each reference is represented by a universe set in a space
3466 * [S[i,j] -> R[]]
3468 * with S[i,j] the statement instance space and R[] the array reference.
3470 * This function should be called before block and thread filters are added.
3472 * Synchronization is needed after a write if there is a subsequent read
3473 * within the same block that may not be performed by the same thread.
3474 * There should not be any dependences between different blocks,
3475 * so we start with the flow dependences within the same kernel invocation
3476 * and we subtract from these those dependences that are mapped
3477 * to the same iteration of the bands where synchronization is inserted.
3478 * We do not remove pairs of instances that are known to map to
3479 * the same thread across different iterations of the intermediate
3480 * bands because the read may be performed by a different thread
3481 * than the one that needs the value if shared memory is involved.
3483 * We also consider all pairs of possible writes that access the same
3484 * memory location and that may be mapped to the same block but not
3485 * to the same iteration of the intermediate bands.
3486 * In theory, it would be possible for one thread to still be in
3487 * a previous iteration of a loop in these bands.
3488 * A write to global memory in this delayed thread could then overwrite
3489 * a write from another thread that has already moved on to
3490 * the next iteration.
3492 * After computing the above writes paired off with reads or writes
3493 * that depend on them, we project onto the domain writes.
3494 * Sychronization is needed after writes to global memory
3495 * through these references.
3497 static __isl_give isl_union_set *compute_sync_writes(
3498 struct ppcg_kernel *kernel, __isl_keep isl_schedule_node *node)
3500 isl_union_map *local;
3501 isl_union_map *may_writes, *shared_access;
3502 isl_union_map *kernel_prefix, *thread_prefix;
3503 isl_union_map *equal;
3504 isl_union_set *wrap;
3505 isl_union_set *domain;
3507 domain = isl_schedule_node_get_universe_domain(node);
3508 kernel_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3509 node = isl_schedule_node_copy(node);
3510 node = gpu_tree_move_down_to_thread(node, kernel->core);
3511 thread_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3512 isl_schedule_node_free(node);
3514 may_writes = isl_union_map_copy(kernel->prog->scop->tagged_may_writes);
3515 may_writes = isl_union_map_curry(may_writes);
3516 may_writes = isl_union_map_intersect_domain(may_writes, domain);
3517 may_writes = isl_union_map_uncurry(may_writes);
3518 shared_access = isl_union_map_copy(may_writes);
3519 shared_access = isl_union_map_apply_range(shared_access,
3520 isl_union_map_reverse(may_writes));
3522 local = isl_union_map_copy(kernel->prog->scop->tagged_dep_flow);
3523 local = isl_union_map_union(local, shared_access);
3524 local = isl_union_map_zip(local);
3526 equal = isl_union_map_apply_range(kernel_prefix,
3527 isl_union_map_reverse(isl_union_map_copy(kernel_prefix)));
3528 wrap = isl_union_map_wrap(equal);
3529 local = isl_union_map_intersect_domain(local, wrap);
3530 equal = isl_union_map_apply_range(thread_prefix,
3531 isl_union_map_reverse(isl_union_map_copy(thread_prefix)));
3532 wrap = isl_union_map_wrap(equal);
3533 local = isl_union_map_subtract_domain(local, wrap);
3535 local = isl_union_map_zip(local);
3536 local = isl_union_map_universe(local);
3538 return isl_union_map_domain(local);
3541 /* Group the domain elements into a single space, named kernelX,
3542 * with X the kernel sequence number "kernel_id".
3544 static __isl_give isl_schedule_node *group_statements(
3545 __isl_take isl_schedule_node *node, int kernel_id)
3547 char buffer[20];
3548 isl_id *id;
3550 if (!node)
3551 return NULL;
3553 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3554 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3555 return isl_schedule_node_group(node, id);
3558 /* Create a ppcg_kernel representing the domain instances that reach "node"
3559 * and insert a mark node pointing to the ppcg_kernel before "node".
3560 * The band that "node" points to is the band that needs to be mapped
3561 * to block identifiers. The band that needs to be mapped to thread
3562 * identifiers should be marked by a "thread" mark by the caller.
3563 * This mark is removed by this function.
3564 * If "scale" is set, then the band that "node" points to is scaled
3565 * by "sizes".
3567 * Mark all outer band nodes as atomic to ensure each kernel is only
3568 * scheduled once.
3569 * If the domain elements that reach "node" live in more than one space,
3570 * then group the domain elements into a single space, named kernelX,
3571 * with X the kernel sequence number.
3573 * Insert a guard node governing the kernel node to ensure that
3574 * no kernels with zero blocks are launched.
3576 * Insert a context node describing the block and thread
3577 * identifiers inside the kernel mark.
3578 * The context node needs to be inserted after the effective block size
3579 * has been determined such that the bounds on the thread identifiers
3580 * would reflect the effective block size.
3581 * Insert a filter node inside the context node mapping the statement
3582 * instances to block identifiers. In particular, the block identifiers
3583 * are equated to the partial schedule of band that was marked for mapping
3584 * to blocks modulo the grid size.
3585 * Insert a filter node inside the "thread" mark mapping the statement
3586 * instances to thread identifiers. In particular, the thread identifiers
3587 * are equated to the partial schedule of band that was marked for mapping
3588 * to threads modulo the block size.
3590 * Compute array reference groups for all arrays, set the local
3591 * array bounds based on the set of domain instances that reach
3592 * the kernel node, check the total amount of shared memory used
3593 * and compute all group tilings.
3594 * The array reference groups are computed after the block filter
3595 * has been inserted because it affects the mapping to shared or
3596 * private memory. This computation also requires the thread filter
3597 * (in the ppcg_kernel object), but this thread filter should not
3598 * have been added to the schedule tree yet since the computation
3599 * requires the schedule of the band that needs to be mapped to
3600 * threads before the privatization is applied.
3602 * If any array reference group requires the band mapped to threads
3603 * to be unrolled, then we perform the required unrolling.
3605 * We save a copy of the schedule that may influence the mappings
3606 * to shared or private memory in kernel->shared_schedule.
3608 * Finally, we add synchronization and copy statements to the schedule tree,
3609 * remove the "thread" mark and create representations for the local
3610 * variables in the kernel.
3612 * We keep a copy of the isl_id that points to the kernel to ensure
3613 * that the kernel does not get destroyed if the schedule node
3614 * is freed due to some error condition.
3616 static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
3617 __isl_take isl_schedule_node *node, int scale,
3618 __isl_keep isl_multi_val *sizes)
3620 struct ppcg_kernel *kernel;
3621 isl_id *id;
3622 isl_schedule_node *node_thread;
3623 isl_union_map *host_schedule;
3624 isl_set *host_domain;
3625 isl_union_set *domain;
3626 int single_statement;
3628 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3629 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3630 if (!kernel)
3631 return isl_schedule_node_free(node);
3633 domain = isl_schedule_node_get_domain(node);
3634 single_statement = isl_union_set_n_set(domain) == 1;
3636 kernel->ctx = gen->ctx;
3637 kernel->prog = gen->prog;
3638 kernel->options = gen->options;
3639 kernel->context = extract_context(node, gen->prog);
3640 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3641 kernel->arrays = accessed_by_domain(isl_union_set_copy(domain),
3642 gen->prog);
3643 kernel->n_grid = n_outer_coincidence(node);
3644 node_thread = isl_schedule_node_copy(node);
3645 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3646 node_thread = isl_schedule_node_child(node_thread, 0);
3647 kernel->n_block = n_outer_coincidence(node_thread);
3648 isl_schedule_node_free(node_thread);
3649 kernel->id = gen->kernel_id++;
3650 read_grid_and_block_sizes(kernel, gen);
3652 kernel->sync_writes = compute_sync_writes(kernel, node);
3654 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3655 host_domain = isl_set_from_union_set(isl_union_map_range(
3656 host_schedule));
3658 node = atomic_ancestors(node);
3660 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3661 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3662 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3664 if (!single_statement)
3665 node = group_statements(node, kernel->id);
3667 node = isl_schedule_node_child(node, 0);
3668 node = split_band(node, kernel->n_grid);
3669 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3670 kernel->n_grid, "b");
3671 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3672 kernel->grid_dim);
3673 kernel->grid_size = extract_grid_size(kernel,
3674 isl_union_set_copy(domain));
3675 if (!kernel->options->wrap)
3676 node = snap_band_to_sizes(node, kernel->grid_dim,
3677 kernel->options);
3678 if (scale)
3679 node = scale_band(node, isl_multi_val_copy(sizes));
3680 node = isl_schedule_node_parent(node);
3681 if (!single_statement)
3682 node = isl_schedule_node_parent(node);
3683 node = insert_guard(node, kernel->context, kernel->grid_size,
3684 gen->prog->scop);
3685 node = gpu_tree_move_down_to_thread(node, kernel->core);
3686 node = isl_schedule_node_child(node, 0);
3687 node = split_band(node, kernel->n_block);
3688 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3689 kernel->n_block, "t");
3690 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3691 kernel->block_dim);
3692 extract_block_size(kernel, domain);
3694 node = gpu_tree_move_up_to_kernel(node);
3695 node = isl_schedule_node_child(node, 0);
3696 node = insert_context(kernel, node);
3697 node = isl_schedule_node_child(node, 0);
3698 node = isl_schedule_node_insert_filter(node,
3699 isl_union_set_copy(kernel->block_filter));
3701 node = gpu_tree_move_up_to_kernel(node);
3703 if (gpu_group_references(kernel, node) < 0)
3704 node = isl_schedule_node_free(node);
3705 localize_bounds(kernel, host_domain);
3706 isl_set_free(host_domain);
3708 check_shared_memory_bound(kernel);
3709 mark_global_arrays(kernel);
3710 compute_group_tilings(kernel);
3712 node = gpu_tree_move_down_to_thread(node, kernel->core);
3713 node = isl_schedule_node_child(node, 0);
3714 if (!kernel->options->wrap)
3715 node = snap_band_to_sizes(node, kernel->block_dim,
3716 kernel->options);
3717 node = isl_schedule_node_insert_filter(node,
3718 isl_union_set_copy(kernel->thread_filter));
3719 if (kernel_requires_unroll(kernel)) {
3720 node = isl_schedule_node_child(node, 0);
3721 node = unroll(node);
3724 node = gpu_tree_move_up_to_thread(node);
3725 kernel->shared_schedule_dim =
3726 isl_schedule_node_get_schedule_depth(node);
3727 kernel->shared_schedule =
3728 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3730 node = gpu_tree_move_up_to_kernel(node);
3732 node = add_sync(kernel, node);
3733 node = add_copies(kernel, node);
3735 node = gpu_tree_move_down_to_thread(node, kernel->core);
3736 node = isl_schedule_node_delete(node);
3738 node = gpu_tree_move_up_to_kernel(node);
3740 if (create_kernel_vars(kernel) < 0)
3741 node = isl_schedule_node_free(node);
3743 if (!single_statement)
3744 node = isl_schedule_node_parent(node);
3745 node = isl_schedule_node_parent(node);
3747 isl_id_free(id);
3748 return node;
3751 /* Insert a zero-dimensional permutable band at "node".
3753 static __isl_give isl_schedule_node *insert_empty_permutable_band(
3754 __isl_take isl_schedule_node *node)
3756 isl_space *space;
3757 isl_schedule *schedule;
3758 isl_union_set *domain;
3759 isl_multi_union_pw_aff *mupa;
3761 schedule = isl_schedule_node_get_schedule(node);
3762 domain = isl_schedule_get_domain(schedule);
3763 space = isl_union_set_get_space(domain);
3764 isl_union_set_free(domain);
3765 isl_schedule_free(schedule);
3767 space = isl_space_set_from_params(space);
3768 mupa = isl_multi_union_pw_aff_zero(space);
3769 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3770 node = isl_schedule_node_band_set_permutable(node, 1);
3772 return node;
3775 /* If "node" is the outermost permutable band that can be mapped to block and
3776 * thread identifiers in its branch (or a leaf with no such outer bands),
3777 * then mark the band as such, attaching a ppcg_kernel to the mark.
3779 * If "node" originally points to a leaf, then insert a zero-dimensional
3780 * permutable band such that we can assume that "node" always
3781 * points to a band node.
3783 * Tile "node" using user specified tile sizes, after splitting the band
3784 * if the number of specified tile sizes is smaller than the dimension
3785 * of the band. Mark the point band of this tiling as the band that
3786 * needs to be mapped to threads.
3787 * Create a kernel representing the domain instances that reach "node" and
3788 * insert a mark node pointing to the ppcg_kernel before the band node.
3790 static __isl_give isl_schedule_node *mark_outer_permutable(
3791 __isl_take isl_schedule_node *node, void *user)
3793 struct gpu_gen *gen = user;
3794 int outer;
3795 int scale;
3796 int tile_len;
3797 int *tile_size;
3798 isl_id *id;
3799 isl_multi_val *sizes;
3801 outer = is_outer_tilable(node);
3802 if (outer < 0)
3803 return isl_schedule_node_free(node);
3804 if (!outer)
3805 return node;
3807 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
3808 node = insert_empty_permutable_band(node);
3810 tile_len = isl_schedule_node_band_n_member(node);
3811 tile_size = read_tile_sizes(gen, &tile_len);
3812 if (!tile_size)
3813 return isl_schedule_node_free(node);
3814 if (tile_len < isl_schedule_node_band_n_member(node))
3815 node = isl_schedule_node_band_split(node, tile_len);
3816 sizes = construct_band_tiles_sizes(node, tile_size);
3817 node = tile_band(node, isl_multi_val_copy(sizes));
3818 node = isl_schedule_node_child(node, 0);
3819 id = isl_id_alloc(gen->ctx, "thread", NULL);
3820 node = isl_schedule_node_insert_mark(node, id);
3821 node = isl_schedule_node_parent(node);
3823 scale = gen->options->scale_tile_loops;
3824 node = create_kernel(gen, node, scale, sizes);
3825 isl_multi_val_free(sizes);
3826 free(tile_size);
3828 return node;
3831 /* Does the subtree rooted at "node" have any suitably permutable band nodes?
3832 * That is, does it have any nodes that are permutable and that
3833 * have a least one coincident dimension?
3835 static int subtree_has_permutable_bands(__isl_keep isl_schedule_node *node)
3837 int any_parallelism = 0;
3839 if (isl_schedule_node_foreach_descendant_top_down(node, &set_permutable,
3840 &any_parallelism) < 0 &&
3841 !any_parallelism)
3842 return -1;
3844 return any_parallelism;
3847 /* Mark all variables that are accessed by the statement instances in "domain"
3848 * and that are local to "prog" as requiring a declaration in the host code.
3850 static int declare_accessed_local_variables(struct gpu_prog *prog,
3851 __isl_keep isl_union_set *domain)
3853 isl_union_set *arrays;
3854 int i;
3856 if (!ppcg_scop_any_hidden_declarations(prog->scop))
3857 return 0;
3858 arrays = accessed_by_domain(isl_union_set_copy(domain), prog);
3860 for (i = 0; i < prog->n_array; ++i) {
3861 isl_space *space;
3862 isl_set *set;
3863 int empty;
3865 if (!prog->array[i].local)
3866 continue;
3867 space = isl_set_get_space(prog->array[i].extent);
3868 set = isl_union_set_extract_set(arrays, space);
3869 empty = isl_set_plain_is_empty(set);
3870 isl_set_free(set);
3871 if (empty < 0)
3872 goto error;
3873 if (!empty)
3874 prog->array[i].declare_local = 1;
3877 isl_union_set_free(arrays);
3878 return 0;
3879 error:
3880 isl_union_set_free(arrays);
3881 return -1;
3884 /* If "node" points to a set node, then separate its children
3885 * into subtrees that have suitably permutable bands and
3886 * those that do not.
3887 * Adjust the schedule tree in order to execute the second group
3888 * after the first group and return a pointer to the first group,
3889 * assuming there are any such subtrees.
3890 * Mark all local variables in "prog" that are accessed by
3891 * the second group as requiring a declaration on the host.
3893 static __isl_give isl_schedule_node *isolate_permutable_subtrees(
3894 __isl_take isl_schedule_node *node, struct gpu_prog *prog)
3896 isl_space *space;
3897 isl_union_set *filter;
3898 int i, n;
3900 if (!node)
3901 return NULL;
3902 if (isl_schedule_node_get_type(node) != isl_schedule_node_set)
3903 return node;
3905 n = isl_schedule_node_n_children(node);
3906 if (n < 0)
3907 return isl_schedule_node_free(node);
3909 node = isl_schedule_node_child(node, 0);
3910 filter = isl_schedule_node_filter_get_filter(node);
3911 node = isl_schedule_node_parent(node);
3912 space = isl_union_set_get_space(filter);
3913 isl_union_set_free(filter);
3914 filter = isl_union_set_empty(space);
3916 for (i = 0; i < n; ++i) {
3917 int parallelism;
3919 node = isl_schedule_node_child(node, i);
3920 parallelism = subtree_has_permutable_bands(node);
3921 if (parallelism < 0) {
3922 node = isl_schedule_node_free(node);
3923 } else if (!parallelism) {
3924 isl_union_set *filter_i;
3925 filter_i = isl_schedule_node_filter_get_filter(node);
3926 filter = isl_union_set_union(filter, filter_i);
3928 node = isl_schedule_node_parent(node);
3931 if (declare_accessed_local_variables(prog, filter) < 0)
3932 node = isl_schedule_node_free(node);
3933 node = isl_schedule_node_order_after(node, filter);
3935 return node;
3938 /* Replace any reference to an array element in the range of "copy"
3939 * by a reference to all array elements (defined by the extent of the array).
3941 static __isl_give isl_union_map *approximate_copy_out(
3942 __isl_take isl_union_map *copy, struct gpu_prog *prog)
3944 int i;
3945 isl_union_map *res;
3947 res = isl_union_map_empty(isl_union_map_get_space(copy));
3949 for (i = 0; i < prog->n_array; ++i) {
3950 isl_space *space;
3951 isl_set *set;
3952 isl_union_map *copy_i;
3953 isl_union_set *extent, *domain;
3955 space = isl_space_copy(prog->array[i].space);
3956 extent = isl_union_set_from_set(isl_set_universe(space));
3957 copy_i = isl_union_map_copy(copy);
3958 copy_i = isl_union_map_intersect_range(copy_i, extent);
3959 set = isl_set_copy(prog->array[i].extent);
3960 extent = isl_union_set_from_set(set);
3961 domain = isl_union_map_domain(copy_i);
3962 copy_i = isl_union_map_from_domain_and_range(domain, extent);
3963 res = isl_union_map_union(res, copy_i);
3966 isl_union_map_free(copy);
3968 return res;
3971 /* Insert "kernel" marks that point to a ppcg_kernel structure
3972 * in front of all outermost tilable band that (by construction)
3973 * have at least one parallel loop.
3975 static __isl_give isl_schedule_node *mark_kernels(struct gpu_gen *gen,
3976 __isl_take isl_schedule_node *node)
3978 return isl_schedule_node_map_descendant(node,
3979 &mark_outer_permutable, gen);
3982 /* Save the schedule "schedule" to a file called "filename".
3983 * The schedule is printed in block style.
3985 static void save_schedule(__isl_keep isl_schedule *schedule,
3986 const char *filename)
3988 FILE *file;
3989 isl_ctx *ctx;
3990 isl_printer *p;
3992 if (!schedule)
3993 return;
3995 file = fopen(filename, "w");
3996 if (!file) {
3997 fprintf(stderr, "Unable to open '%s' for writing\n", filename);
3998 return;
4000 ctx = isl_schedule_get_ctx(schedule);
4001 p = isl_printer_to_file(ctx, file);
4002 p = isl_printer_set_yaml_style(p, ISL_YAML_STYLE_BLOCK);
4003 p = isl_printer_print_schedule(p, schedule);
4004 isl_printer_free(p);
4005 fclose(file);
4008 /* Load and return a schedule from a file called "filename".
4010 static __isl_give isl_schedule *load_schedule(isl_ctx *ctx,
4011 const char *filename)
4013 FILE *file;
4014 isl_schedule *schedule;
4016 file = fopen(filename, "r");
4017 if (!file) {
4018 fprintf(stderr, "Unable to open '%s' for reading\n", filename);
4019 return NULL;
4021 schedule = isl_schedule_read_from_file(ctx, file);
4022 fclose(file);
4024 return schedule;
4027 /* Construct schedule constraints from the dependences in prog->scop and
4028 * the array order dependences in prog->array_order.
4030 * If live range reordering is allowed, then we need to make sure
4031 * that live ranges on arrays are not run in parallel since doing
4032 * so would require array expansion. We therefore add the array
4033 * order dependences to the coincidence dependences. Non-zero array
4034 * order dependences will then prevent a schedule dimension from being
4035 * considered parallel.
4036 * Live ranges derived from scalars are allowed to be run in parallel
4037 * since we force the scalars to be mapped to private memory in
4038 * check_scalar_live_ranges.
4039 * If live range reordering is allowed, then the false dependences
4040 * are not added to the validity constraints as that would prevent
4041 * reordering. Instead, the external false dependences that enforce that reads
4042 * from potentially live-in data precede any later write and
4043 * that writes of potentially live-out data follow any other earlier write
4044 * are added to the validity and the coincidence constraints.
4045 * The false dependences are still added to the proximity constraints
4046 * for consistency with the case where live range reordering is not allowed.
4047 * The coincidence constraints then consist of flow dependences,
4048 * external false dependences and array order dependences.
4049 * The independences can be filtered out from the first two sets.
4050 * They have already been filtered out from the array order dependences
4051 * on a per array basis in collect_order_dependences.
4052 * There is no need for a per array handling of the other two sets
4053 * as there should be no flow or external false dependence on local
4054 * variables that can be filtered out.
4056 static __isl_give isl_schedule_constraints *construct_schedule_constraints(
4057 struct gpu_prog *prog)
4059 isl_union_set *domain;
4060 isl_union_map *dep_raw, *dep;
4061 isl_union_map *validity, *proximity, *coincidence;
4062 isl_schedule_constraints *sc;
4064 domain = isl_union_set_copy(prog->scop->domain);
4065 sc = isl_schedule_constraints_on_domain(domain);
4066 sc = isl_schedule_constraints_set_context(sc,
4067 isl_set_copy(prog->scop->context));
4068 if (prog->scop->options->live_range_reordering) {
4069 sc = isl_schedule_constraints_set_conditional_validity(sc,
4070 isl_union_map_copy(prog->scop->tagged_dep_flow),
4071 isl_union_map_copy(prog->scop->tagged_dep_order));
4072 proximity = isl_union_map_copy(prog->scop->dep_flow);
4073 validity = isl_union_map_copy(proximity);
4074 validity = isl_union_map_union(validity,
4075 isl_union_map_copy(prog->scop->dep_forced));
4076 proximity = isl_union_map_union(proximity,
4077 isl_union_map_copy(prog->scop->dep_false));
4078 coincidence = isl_union_map_copy(validity);
4079 coincidence = isl_union_map_subtract(coincidence,
4080 isl_union_map_copy(prog->scop->independence));
4081 coincidence = isl_union_map_union(coincidence,
4082 isl_union_map_copy(prog->array_order));
4083 } else {
4084 dep_raw = isl_union_map_copy(prog->scop->dep_flow);
4085 dep = isl_union_map_copy(prog->scop->dep_false);
4086 dep = isl_union_map_union(dep, dep_raw);
4087 dep = isl_union_map_coalesce(dep);
4088 proximity = isl_union_map_copy(dep);
4089 coincidence = isl_union_map_copy(dep);
4090 validity = dep;
4092 sc = isl_schedule_constraints_set_validity(sc, validity);
4093 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4094 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4096 if (prog->scop->options->debug->dump_schedule_constraints)
4097 isl_schedule_constraints_dump(sc);
4098 return sc;
4101 /* Compute an appropriate schedule based on the accesses in
4102 * gen->read and gen->write.
4104 * We derive schedule constraints from the dependences in gen->prog->scop
4105 * and then use isl to compute a schedule that has a parallel loop
4106 * in each tilable band.
4108 static __isl_give isl_schedule *compute_schedule(struct gpu_gen *gen)
4110 isl_schedule_constraints *sc;
4111 isl_schedule *schedule;
4113 sc = construct_schedule_constraints(gen->prog);
4114 schedule = isl_schedule_constraints_compute_schedule(sc);
4116 return schedule;
4119 /* If the band node "node" has exactly one member then mark it permutable.
4121 static __isl_give isl_schedule_node *band_set_permutable(
4122 __isl_take isl_schedule_node *node,
4123 __isl_keep isl_schedule_constraints *sc)
4125 if (isl_schedule_node_band_n_member(node) == 1)
4126 node = isl_schedule_node_band_set_permutable(node, 1);
4128 return node;
4131 /* Return the coincidence constraints between pairs of instances
4132 * that are scheduled together by the ancestors of "node".
4133 * That is, select those coincidence constraints that relate
4134 * pairs of instances that have the same value for the prefix schedule.
4135 * If the schedule depth is zero, then the prefix schedule does not
4136 * contain any information, so we intersect domain and range
4137 * of the schedule constraints with the reaching domain elements instead.
4139 static __isl_give isl_union_map *get_local_coincidence(
4140 __isl_keep isl_schedule_node *node,
4141 __isl_keep isl_schedule_constraints *sc)
4143 isl_union_map *coincidence;
4144 isl_multi_union_pw_aff *prefix;
4145 isl_union_pw_multi_aff *contraction;
4147 coincidence = isl_schedule_constraints_get_coincidence(sc);
4148 contraction = isl_schedule_node_get_subtree_contraction(node);
4149 if (isl_schedule_node_get_schedule_depth(node) == 0) {
4150 isl_union_set *domain;
4152 domain = isl_schedule_node_get_domain(node);
4153 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4154 contraction);
4155 coincidence = isl_union_map_intersect_domain(coincidence,
4156 isl_union_set_copy(domain));
4157 coincidence = isl_union_map_intersect_range(coincidence,
4158 domain);
4159 return coincidence;
4162 prefix = isl_schedule_node_get_prefix_schedule_multi_union_pw_aff(node);
4163 prefix = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(prefix,
4164 contraction);
4165 return isl_union_map_eq_at_multi_union_pw_aff(coincidence, prefix);
4168 /* For each member in the band node "node", determine whether
4169 * it is coincident with respect to the outer nodes and mark
4170 * it accordingly.
4172 * That is, for each coincidence constraint between pairs
4173 * of instances that are scheduled together by the outer nodes,
4174 * check that domain and range are assigned the same value
4175 * by the band member. This test is performed by checking
4176 * that imposing the same value for the band member does not
4177 * remove any elements from the set of coincidence constraints.
4179 static __isl_give isl_schedule_node *band_set_coincident(
4180 __isl_take isl_schedule_node *node,
4181 __isl_keep isl_schedule_constraints *sc)
4183 isl_union_map *coincidence;
4184 isl_union_pw_multi_aff *contraction;
4185 isl_multi_union_pw_aff *partial;
4186 int i, n;
4188 coincidence = get_local_coincidence(node, sc);
4190 partial = isl_schedule_node_band_get_partial_schedule(node);
4191 contraction = isl_schedule_node_get_subtree_contraction(node);
4192 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4193 contraction);
4194 n = isl_schedule_node_band_n_member(node);
4195 for (i = 0; i < n; ++i) {
4196 isl_union_map *coincidence_i;
4197 isl_union_pw_aff *upa;
4198 isl_multi_union_pw_aff *partial_i;
4199 int subset;
4201 upa = isl_multi_union_pw_aff_get_union_pw_aff(partial, i);
4202 partial_i = isl_multi_union_pw_aff_from_union_pw_aff(upa);
4203 coincidence_i = isl_union_map_copy(coincidence);
4204 coincidence_i = isl_union_map_eq_at_multi_union_pw_aff(
4205 coincidence_i, partial_i);
4206 subset = isl_union_map_is_subset(coincidence, coincidence_i);
4207 isl_union_map_free(coincidence_i);
4209 if (subset < 0)
4210 break;
4211 node = isl_schedule_node_band_member_set_coincident(node, i,
4212 subset);
4214 if (i < n)
4215 node = isl_schedule_node_free(node);
4216 isl_multi_union_pw_aff_free(partial);
4217 isl_union_map_free(coincidence);
4219 return node;
4222 /* If "node" is a band, then set its properties.
4224 * In particular, if the band has exactly one member, then mark it permutable.
4225 * Mark the band member coincident based on the coincidence constraints
4226 * of "sc".
4228 static __isl_give isl_schedule_node *set_band_properties(
4229 __isl_take isl_schedule_node *node, void *user)
4231 isl_schedule_constraints *sc = user;
4233 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
4234 return node;
4235 if (isl_schedule_node_band_n_member(node) == 0)
4236 return node;
4238 node = band_set_permutable(node, sc);
4239 node = band_set_coincident(node, sc);
4241 return node;
4244 /* Return the original schedule with all bands marked permutable and
4245 * all band members marked coincident based on the coincidence constraints.
4246 * The bands are explicitly marked permutable so that they will be considered
4247 * by mark_outer_permutable.
4249 static __isl_give isl_schedule *determine_properties_original_schedule(
4250 struct gpu_gen *gen)
4252 isl_schedule *schedule;
4253 isl_schedule_constraints *sc;
4255 schedule = isl_schedule_copy(gen->prog->scop->schedule);
4256 sc = construct_schedule_constraints(gen->prog);
4257 schedule = isl_schedule_map_schedule_node(schedule,
4258 &set_band_properties, sc);
4259 isl_schedule_constraints_free(sc);
4261 return schedule;
4264 /* Obtain a schedule for the scop, by reading it from
4265 * a file, by computing one or by determining the properties
4266 * of the original schedule.
4268 static __isl_give isl_schedule *get_schedule(struct gpu_gen *gen)
4270 isl_schedule *schedule;
4272 if (gen->options->load_schedule_file) {
4273 schedule = load_schedule(gen->ctx,
4274 gen->options->load_schedule_file);
4275 } else {
4276 if (gen->options->reschedule)
4277 schedule = compute_schedule(gen);
4278 else
4279 schedule = determine_properties_original_schedule(gen);
4280 if (gen->options->save_schedule_file)
4281 save_schedule(schedule,
4282 gen->options->save_schedule_file);
4284 if (gen->options->debug->dump_schedule)
4285 isl_schedule_dump(schedule);
4287 return schedule;
4290 /* Construct the string "<a>_<b>".
4292 static char *concat(isl_ctx *ctx, const char *a, const char *b)
4294 isl_printer *p;
4295 char *s;
4297 p = isl_printer_to_str(ctx);
4298 p = isl_printer_print_str(p, a);
4299 p = isl_printer_print_str(p, "_");
4300 p = isl_printer_print_str(p, b);
4301 s = isl_printer_get_str(p);
4302 isl_printer_free(p);
4304 return s;
4307 /* For each array in "prog" of which an element appears in "accessed" and
4308 * that is not a read only scalar, create a zero-dimensional universe set
4309 * of which the tuple id has name "<prefix>_<name of array>" and a user
4310 * pointer pointing to the array (gpu_array_info).
4312 * If the array is local to "prog", then make sure it will be declared
4313 * in the host code.
4315 * Return the list of these universe sets.
4317 static __isl_give isl_union_set_list *create_copy_filters(struct gpu_prog *prog,
4318 const char *prefix, __isl_take isl_union_set *accessed)
4320 int i;
4321 isl_ctx *ctx;
4322 isl_union_set_list *filters;
4324 ctx = prog->ctx;
4325 filters = isl_union_set_list_alloc(ctx, 0);
4326 for (i = 0; i < prog->n_array; ++i) {
4327 struct gpu_array_info *array = &prog->array[i];
4328 isl_space *space;
4329 isl_set *accessed_i;
4330 int empty;
4331 char *name;
4332 isl_id *id;
4333 isl_union_set *uset;
4335 if (gpu_array_is_read_only_scalar(array))
4336 continue;
4338 space = isl_space_copy(array->space);
4339 accessed_i = isl_union_set_extract_set(accessed, space);
4340 empty = isl_set_plain_is_empty(accessed_i);
4341 isl_set_free(accessed_i);
4342 if (empty < 0) {
4343 filters = isl_union_set_list_free(filters);
4344 break;
4346 if (empty)
4347 continue;
4349 array->global = 1;
4350 if (array->local)
4351 array->declare_local = 1;
4353 name = concat(ctx, prefix, array->name);
4354 id = name ? isl_id_alloc(ctx, name, array) : NULL;
4355 free(name);
4356 space = isl_space_set_alloc(ctx, 0, 0);
4357 space = isl_space_set_tuple_id(space, isl_dim_set, id);
4358 uset = isl_union_set_from_set(isl_set_universe(space));
4360 filters = isl_union_set_list_add(filters, uset);
4362 isl_union_set_free(accessed);
4364 return filters;
4367 /* Make sure that code for the statements in "filters" that
4368 * copy arrays to or from the device is only generated when
4369 * the size of the corresponding array is positive.
4370 * That is, add a set node underneath "graft" with "filters" as children
4371 * and for each child add a guard that the selects the parameter
4372 * values for which the corresponding array has a positive size.
4373 * The array is available in the user pointer of the statement identifier.
4374 * "depth" is the schedule depth of the position where "graft"
4375 * will be added.
4377 static __isl_give isl_schedule_node *insert_positive_size_guards(
4378 __isl_take isl_schedule_node *graft,
4379 __isl_take isl_union_set_list *filters, int depth)
4381 int i, n;
4383 graft = isl_schedule_node_child(graft, 0);
4384 graft = isl_schedule_node_insert_set(graft, filters);
4385 n = isl_schedule_node_n_children(graft);
4386 for (i = 0; i < n; ++i) {
4387 isl_union_set *filter;
4388 isl_set *domain, *guard;
4389 isl_id *id;
4390 struct gpu_array_info *array;
4392 graft = isl_schedule_node_child(graft, i);
4393 filter = isl_schedule_node_filter_get_filter(graft);
4394 domain = isl_set_from_union_set(filter);
4395 id = isl_set_get_tuple_id(domain);
4396 array = isl_id_get_user(id);
4397 isl_id_free(id);
4398 isl_set_free(domain);
4399 guard = gpu_array_positive_size_guard(array);
4400 guard = isl_set_from_params(guard);
4401 guard = isl_set_add_dims(guard, isl_dim_set, depth);
4402 graft = isl_schedule_node_child(graft, 0);
4403 graft = isl_schedule_node_insert_guard(graft, guard);
4404 graft = isl_schedule_node_parent(graft);
4405 graft = isl_schedule_node_parent(graft);
4407 graft = isl_schedule_node_parent(graft);
4409 return graft;
4412 /* Create a graft for copying arrays to or from the device,
4413 * whenever the size of the array is strictly positive.
4414 * Each statement is called "<prefix>_<name of array>" and
4415 * the identifier has a user pointer pointing to the array.
4416 * The graft will be added at the position specified by "node".
4417 * "copy" contains the array elements that need to be copied.
4418 * Only arrays of which some elements need to be copied
4419 * will have a corresponding statement in the graph.
4420 * Note though that each such statement will copy the entire array.
4422 static __isl_give isl_schedule_node *create_copy_device(struct gpu_prog *prog,
4423 __isl_keep isl_schedule_node *node, const char *prefix,
4424 __isl_take isl_union_set *copy)
4426 int depth;
4427 isl_ctx *ctx;
4428 isl_space *space;
4429 isl_union_set *all, *domain;
4430 isl_union_set_list *filters;
4431 isl_union_map *extension;
4432 isl_schedule_node *graft;
4434 ctx = prog->ctx;
4435 depth = isl_schedule_node_get_schedule_depth(node);
4436 filters = create_copy_filters(prog, prefix, copy);
4437 all = isl_union_set_list_union(isl_union_set_list_copy(filters));
4439 space = depth < 0 ? NULL : isl_space_set_alloc(ctx, 0, depth);
4440 domain = isl_union_set_from_set(isl_set_universe(space));
4441 extension = isl_union_map_from_domain_and_range(domain, all);
4442 graft = isl_schedule_node_from_extension(extension);
4444 if (!filters)
4445 return isl_schedule_node_free(graft);
4446 if (isl_union_set_list_n_union_set(filters) == 0) {
4447 isl_union_set_list_free(filters);
4448 return graft;
4451 return insert_positive_size_guards(graft, filters, depth);
4454 /* Return (the universe spaces of) the arrays that are declared
4455 * inside the scop corresponding to "prog" and for which all
4456 * potential writes inside the scop form a subset of "domain".
4458 static __isl_give isl_union_set *extract_local_accesses(struct gpu_prog *prog,
4459 __isl_keep isl_union_set *domain)
4461 int i;
4462 isl_union_set *local;
4464 local = isl_union_set_empty(isl_union_set_get_space(domain));
4466 for (i = 0; i < prog->n_array; ++i) {
4467 isl_set *set;
4468 isl_union_map *to_outer;
4469 isl_union_map *may_write;
4470 isl_union_set *write_domain;
4471 isl_union_set *fields;
4472 int subset;
4474 if (!prog->array[i].local)
4475 continue;
4477 set = isl_set_universe(isl_space_copy(prog->array[i].space));
4478 to_outer = isl_union_map_copy(prog->to_outer);
4479 to_outer = isl_union_map_intersect_range(to_outer,
4480 isl_union_set_from_set(isl_set_copy(set)));
4481 fields = isl_union_map_domain(to_outer);
4482 may_write = isl_union_map_copy(prog->may_write);
4483 may_write = isl_union_map_intersect_range(may_write, fields);
4484 write_domain = isl_union_map_domain(may_write);
4485 subset = isl_union_set_is_subset(write_domain, domain);
4486 isl_union_set_free(write_domain);
4488 if (subset < 0) {
4489 isl_set_free(set);
4490 return isl_union_set_free(local);
4491 } else if (subset) {
4492 local = isl_union_set_add_set(local, set);
4493 } else {
4494 isl_set_free(set);
4498 return local;
4501 /* Internal data structure for node_may_persist.
4503 * "tagger" maps tagged iteration domains to the corresponding untagged
4504 * iteration domain.
4506 * "may_persist_flow" is the set of all tagged dataflow dependences
4507 * with those dependences removed that either precede or follow
4508 * the kernel launch in a sequence.
4509 * "inner_band_flow" is the set of all tagged dataflow dependences
4510 * that are local to a given iteration of the outer band nodes
4511 * with respect to the current node.
4512 * "local_flow" is equal to "inner_band_flow", except that the domain
4513 * and the range have been intersected with intermediate filters
4514 * on children of sets or sequences.
4516 struct ppcg_may_persist_data {
4517 isl_union_pw_multi_aff *tagger;
4519 isl_union_map *local_flow;
4520 isl_union_map *inner_band_flow;
4521 isl_union_map *may_persist_flow;
4524 /* Update the information in "data" based on the band ancestor "node".
4526 * In particular, we restrict the dependences in data->local_flow
4527 * to those dependence where the source and the sink occur in
4528 * the same iteration of the given band node.
4529 * We also update data->inner_band_flow to the new value of
4530 * data->local_flow.
4532 static int update_may_persist_at_band(__isl_keep isl_schedule_node *node,
4533 struct ppcg_may_persist_data *data)
4535 isl_multi_union_pw_aff *partial;
4536 isl_union_pw_multi_aff *contraction;
4537 isl_union_map *flow;
4539 if (isl_schedule_node_band_n_member(node) == 0)
4540 return 0;
4542 partial = isl_schedule_node_band_get_partial_schedule(node);
4543 contraction = isl_schedule_node_get_subtree_contraction(node);
4544 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4545 contraction);
4546 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4547 isl_union_pw_multi_aff_copy(data->tagger));
4549 flow = data->local_flow;
4550 flow = isl_union_map_eq_at_multi_union_pw_aff(flow, partial);
4551 data->local_flow = flow;
4553 isl_union_map_free(data->inner_band_flow);
4554 data->inner_band_flow = isl_union_map_copy(data->local_flow);
4556 return 0;
4559 /* Given a set of local reaching domain elements "domain",
4560 * expand them to the corresponding leaf domain elements using "contraction"
4561 * and insert the array references tags using data->tagger.
4563 static __isl_give isl_union_set *expand_and_tag(
4564 __isl_take isl_union_set *domain,
4565 __isl_take isl_union_pw_multi_aff *contraction,
4566 struct ppcg_may_persist_data *data)
4568 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4569 contraction);
4570 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4571 isl_union_pw_multi_aff_copy(data->tagger));
4572 return domain;
4575 /* Given a filter node that is the child of a set or sequence node,
4576 * restrict data->local_flow to refer only to those elements
4577 * in the filter of the node.
4578 * "contraction" maps the leaf domain elements of the schedule tree
4579 * to the corresponding domain elements at (the parent of) "node".
4581 static int filter_flow(__isl_keep isl_schedule_node *node,
4582 struct ppcg_may_persist_data *data,
4583 __isl_take isl_union_pw_multi_aff *contraction)
4585 isl_union_set *filter;
4586 isl_union_map *flow;
4588 flow = data->local_flow;
4589 filter = isl_schedule_node_filter_get_filter(node);
4590 filter = expand_and_tag(filter, contraction, data);
4591 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(filter));
4592 flow = isl_union_map_intersect_range(flow, filter);
4593 data->local_flow = flow;
4595 return 0;
4598 /* Given a filter node "node", collect the filters on all preceding siblings
4599 * (which are also filter nodes), add them to "filters" and return the result.
4601 static __isl_give isl_union_set *add_previous_filters(
4602 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4604 isl_schedule_node *sibling;
4606 sibling = isl_schedule_node_copy(node);
4607 while (sibling && isl_schedule_node_has_previous_sibling(sibling)) {
4608 isl_union_set *filter;
4610 sibling = isl_schedule_node_previous_sibling(sibling);
4611 filter = isl_schedule_node_filter_get_filter(sibling);
4612 filters = isl_union_set_union(filters, filter);
4614 isl_schedule_node_free(sibling);
4615 if (!sibling)
4616 return isl_union_set_free(filters);
4618 return filters;
4621 /* Given a filter node "node", collect the filters on all following siblings
4622 * (which are also filter nodes), add them to "filters" and return the result.
4624 static __isl_give isl_union_set *add_next_filters(
4625 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4627 isl_schedule_node *sibling;
4629 sibling = isl_schedule_node_copy(node);
4630 while (sibling && isl_schedule_node_has_next_sibling(sibling)) {
4631 isl_union_set *filter;
4633 sibling = isl_schedule_node_next_sibling(sibling);
4634 filter = isl_schedule_node_filter_get_filter(sibling);
4635 filters = isl_union_set_union(filters, filter);
4637 isl_schedule_node_free(sibling);
4638 if (!sibling)
4639 return isl_union_set_free(filters);
4641 return filters;
4644 /* Remove those flow dependences from data->may_persist_flow
4645 * that flow between elements of "domain" within the same iteration
4646 * of all outer band nodes.
4647 * "contraction" maps the leaf domain elements of the schedule tree
4648 * to the corresponding elements "domain".
4650 static void remove_external_flow(struct ppcg_may_persist_data *data,
4651 __isl_take isl_union_set *domain,
4652 __isl_keep isl_union_pw_multi_aff *contraction)
4654 isl_union_map *flow;
4656 contraction = isl_union_pw_multi_aff_copy(contraction);
4657 domain = expand_and_tag(domain, contraction, data);
4658 flow = isl_union_map_copy(data->local_flow);
4659 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(domain));
4660 flow = isl_union_map_intersect_range(flow, domain);
4662 data->may_persist_flow = isl_union_map_subtract(data->may_persist_flow,
4663 flow);
4666 /* Update the information in "data" based on the filter ancestor "node".
4667 * We only need to modify anything if the filter is the child
4668 * of a set or sequence node.
4670 * In the case of a sequence, we remove the dependences between
4671 * statement instances that are both executed either before or
4672 * after the subtree that will be mapped to a kernel, within
4673 * the same iteration of outer bands.
4675 * In both cases, we restrict data->local_flow to the current child.
4677 static int update_may_persist_at_filter(__isl_keep isl_schedule_node *node,
4678 struct ppcg_may_persist_data *data)
4680 enum isl_schedule_node_type type;
4681 isl_schedule_node *parent;
4682 isl_space *space;
4683 isl_union_pw_multi_aff *contraction;
4684 isl_union_set *before, *after, *filter;
4685 isl_union_map *flow;
4687 type = isl_schedule_node_get_parent_type(node);
4688 if (type != isl_schedule_node_sequence && type != isl_schedule_node_set)
4689 return 0;
4691 parent = isl_schedule_node_copy(node);
4692 parent = isl_schedule_node_parent(parent);
4693 contraction = isl_schedule_node_get_subtree_contraction(parent);
4694 isl_schedule_node_free(parent);
4696 if (type == isl_schedule_node_set)
4697 return filter_flow(node, data, contraction);
4699 filter = isl_schedule_node_filter_get_filter(node);
4700 space = isl_union_set_get_space(filter);
4701 isl_union_set_free(filter);
4702 before = isl_union_set_empty(space);
4703 after = isl_union_set_copy(before);
4704 before = add_previous_filters(before, node);
4705 after = add_next_filters(after, node);
4707 remove_external_flow(data, before, contraction);
4708 remove_external_flow(data, after, contraction);
4710 return filter_flow(node, data, contraction);
4713 /* Update the information in "data" based on the ancestor "node".
4715 static isl_stat update_may_persist_at(__isl_keep isl_schedule_node *node,
4716 void *user)
4718 struct ppcg_may_persist_data *data = user;
4720 switch (isl_schedule_node_get_type(node)) {
4721 case isl_schedule_node_error:
4722 return isl_stat_error;
4723 case isl_schedule_node_context:
4724 case isl_schedule_node_domain:
4725 case isl_schedule_node_expansion:
4726 case isl_schedule_node_extension:
4727 case isl_schedule_node_guard:
4728 case isl_schedule_node_leaf:
4729 case isl_schedule_node_mark:
4730 case isl_schedule_node_sequence:
4731 case isl_schedule_node_set:
4732 break;
4733 case isl_schedule_node_band:
4734 if (update_may_persist_at_band(node, data) < 0)
4735 return isl_stat_error;
4736 break;
4737 case isl_schedule_node_filter:
4738 if (update_may_persist_at_filter(node, data) < 0)
4739 return isl_stat_error;
4740 break;
4743 return isl_stat_ok;
4746 /* Determine the set of array elements that may need to be perserved
4747 * by a kernel constructed from the subtree at "node".
4748 * This includes the set of array elements that may need to be preserved
4749 * by the entire scop (prog->may_persist) and the elements for which
4750 * there is a potential flow dependence that may cross a kernel launch.
4752 * To determine the second set, we start from all flow dependences.
4753 * From this set of dependences, we remove those that cannot possibly
4754 * require data to be preserved by a kernel launch.
4755 * In particular, we consider the following sets of dependences.
4756 * - dependences of which the write occurs inside the kernel.
4757 * If the data is needed outside the kernel, then it will
4758 * be copied out immediately after the kernel launch, so there
4759 * is no need for any special care.
4760 * - dependences of which the read occurs inside the kernel and the
4761 * corresponding write occurs inside the same iteration of the
4762 * outer band nodes. This means that the data is needed in
4763 * the first kernel launch after the write, which is already
4764 * taken care of by the standard copy-in. That is, the data
4765 * do not need to be preserved by any intermediate call to
4766 * the same kernel.
4767 * - dependences of which the write and the read either both occur
4768 * before the kernel launch or both occur after the kernel launch,
4769 * within the same iteration of the outer band nodes with respect
4770 * to the sequence that determines the ordering of the dependence
4771 * and the kernel launch. Such flow dependences cannot cross
4772 * any kernel launch.
4774 * For the remaining (tagged) dependences, we take the domain
4775 * (i.e., the tagged writes) and apply the tagged access relation
4776 * to obtain the accessed data elements.
4777 * These are then combined with the elements that may need to be
4778 * preserved by the entire scop.
4780 static __isl_give isl_union_set *node_may_persist(
4781 __isl_keep isl_schedule_node *node, struct gpu_prog *prog)
4783 struct ppcg_may_persist_data data;
4784 isl_schedule_node *root;
4785 isl_union_pw_multi_aff *contraction;
4786 isl_union_set *domain;
4787 isl_union_set *persist;
4788 isl_union_map *flow, *local_flow;
4790 data.tagger = prog->scop->tagger;
4792 flow = isl_union_map_copy(prog->scop->tagged_dep_flow);
4793 data.local_flow = isl_union_map_copy(flow);
4794 data.inner_band_flow = isl_union_map_copy(flow);
4795 data.may_persist_flow = flow;
4796 if (isl_schedule_node_foreach_ancestor_top_down(node,
4797 &update_may_persist_at, &data) < 0)
4798 data.may_persist_flow =
4799 isl_union_map_free(data.may_persist_flow);
4800 flow = data.may_persist_flow;
4801 isl_union_map_free(data.local_flow);
4803 domain = isl_schedule_node_get_domain(node);
4804 contraction = isl_schedule_node_get_subtree_contraction(node);
4805 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4806 contraction);
4807 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4808 isl_union_pw_multi_aff_copy(data.tagger));
4809 flow = isl_union_map_subtract_domain(flow, isl_union_set_copy(domain));
4810 local_flow = data.inner_band_flow;
4811 local_flow = isl_union_map_intersect_range(local_flow, domain);
4812 flow = isl_union_map_subtract(flow, local_flow);
4814 persist = isl_union_map_domain(flow);
4815 persist = isl_union_set_apply(persist,
4816 isl_union_map_copy(prog->scop->tagged_may_writes));
4817 persist = isl_union_set_union(persist,
4818 isl_union_set_copy(prog->may_persist));
4820 return persist;
4823 /* Add nodes for copying outer arrays in and out of the device
4824 * before and after the subtree "node", which contains one or more kernels.
4825 * "domain" contains the original reaching domain elements before
4826 * the kernels were created, i.e., before the contraction that
4827 * may have been performed in creating the kernels has been applied.
4828 * "prefix" contains the prefix schedule at that point, in terms
4829 * of the same original reaching domain elements.
4831 * We first compute the sets of outer array elements that need
4832 * to be copied in and out and then graft in the nodes for
4833 * performing this copying.
4835 * In particular, for each array that is possibly written anywhere in
4836 * the subtree "node" and that may be used after "node"
4837 * or that may be visible outside the corresponding scop,
4838 * we copy out its entire extent.
4840 * Any array elements that is read without first being written inside
4841 * the subtree "node" needs to be copied in.
4842 * Furthermore, if there are any array elements that
4843 * are copied out, but that may not be written inside "node, then
4844 * they also need to be copied in to ensure that the value after execution
4845 * is the same as the value before execution, at least for those array
4846 * elements that may have their values preserved by the scop or that
4847 * may be written before "node" and read after "node".
4848 * In case the array elements are structures, we need to take into
4849 * account that all members of the structures need to be written
4850 * by "node" before we can avoid copying the data structure in.
4852 * Note that the may_write relation is intersected with the domain,
4853 * which has been intersected with the context.
4854 * This helps in those cases where the arrays are declared with a fixed size,
4855 * while the accesses are parametric and the context assigns a fixed value
4856 * to the parameters.
4858 * If an element from a local array is read without first being written,
4859 * then there is no point in copying it in since it cannot have been
4860 * written prior to the scop. Warn about the uninitialized read instead.
4862 static __isl_give isl_schedule_node *add_to_from_device(
4863 __isl_take isl_schedule_node *node, __isl_take isl_union_set *domain,
4864 __isl_take isl_union_map *prefix, struct gpu_prog *prog)
4866 isl_union_set *local;
4867 isl_union_set *to_device, *from_device, *may_persist;
4868 isl_union_map *may_write, *must_write, *copy_out, *not_written;
4869 isl_union_map *read, *copy_in;
4870 isl_union_map *tagged;
4871 isl_union_map *local_uninitialized;
4872 isl_schedule_node *graft;
4874 tagged = isl_union_map_copy(prog->scop->tagged_reads);
4875 tagged = isl_union_map_union(tagged,
4876 isl_union_map_copy(prog->scop->tagged_may_writes));
4878 may_write = isl_union_map_copy(prog->may_write);
4879 may_write = isl_union_map_intersect_domain(may_write,
4880 isl_union_set_copy(domain));
4881 may_write = remove_local_accesses(prog,
4882 isl_union_map_copy(tagged), may_write,
4883 isl_union_map_copy(prefix), 0);
4884 may_write = isl_union_map_apply_range(may_write,
4885 isl_union_map_copy(prog->to_outer));
4886 may_write = isl_union_map_apply_domain(may_write,
4887 isl_union_map_copy(prefix));
4888 may_write = approximate_copy_out(may_write, prog);
4889 copy_out = isl_union_map_copy(may_write);
4890 may_write = isl_union_map_apply_range(may_write,
4891 isl_union_map_copy(prog->to_inner));
4892 must_write = isl_union_map_copy(prog->must_write);
4893 must_write = isl_union_map_apply_domain(must_write,
4894 isl_union_map_copy(prefix));
4895 may_persist = node_may_persist(node, prog);
4896 may_write = isl_union_map_intersect_range(may_write, may_persist);
4897 not_written = isl_union_map_subtract(may_write, must_write);
4899 local = extract_local_accesses(prog, domain);
4900 read = isl_union_map_copy(prog->read);
4901 read = isl_union_map_intersect_domain(read, domain);
4902 read = remove_local_accesses(prog, tagged, read,
4903 isl_union_map_copy(prefix), 1);
4904 local = isl_union_set_apply(local, isl_union_map_copy(prog->to_inner));
4905 local_uninitialized = isl_union_map_copy(prog->scop->live_in);
4906 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4907 local);
4908 local_uninitialized = isl_union_map_intersect(local_uninitialized,
4909 isl_union_map_copy(read));
4910 if (!isl_union_map_is_empty(local_uninitialized)) {
4911 fprintf(stderr,
4912 "possibly uninitialized reads (not copied in):\n");
4913 isl_union_map_dump(local_uninitialized);
4915 read = isl_union_map_subtract(read, local_uninitialized);
4916 read = isl_union_map_apply_domain(read, prefix);
4917 copy_in = isl_union_map_union(read, not_written);
4918 copy_in = isl_union_map_apply_range(copy_in,
4919 isl_union_map_copy(prog->to_outer));
4921 graft = create_copy_device(prog, node, "to_device",
4922 isl_union_map_range(copy_in));
4923 node = isl_schedule_node_graft_before(node, graft);
4924 graft = create_copy_device(prog, node, "from_device",
4925 isl_union_map_range(copy_out));
4926 node = isl_schedule_node_graft_after(node, graft);
4928 return node;
4931 /* Update "schedule" for mapping to a GPU device.
4933 * In particular, insert a context node, create kernels for
4934 * each outermost tilable band and introduce node for copying array
4935 * in and out of the device.
4936 * If the child of the initial root points to a set node,
4937 * then children of this node that do not contain any tilable bands
4938 * are separated from the other children and are not mapped to
4939 * the device.
4941 static __isl_give isl_schedule *map_to_device(struct gpu_gen *gen,
4942 __isl_take isl_schedule *schedule)
4944 isl_schedule_node *node;
4945 isl_set *context;
4946 isl_union_set *domain;
4947 isl_union_map *prefix;
4949 context = isl_set_copy(gen->prog->context);
4950 context = isl_set_from_params(context);
4951 schedule = isl_schedule_insert_context(schedule, context);
4953 node = isl_schedule_get_root(schedule);
4954 isl_schedule_free(schedule);
4955 node = isl_schedule_node_child(node, 0);
4956 if (isl_schedule_node_get_type(node) == isl_schedule_node_context)
4957 node = isl_schedule_node_child(node, 0);
4958 node = isolate_permutable_subtrees(node, gen->prog);
4959 domain = isl_schedule_node_get_domain(node);
4960 prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
4961 node = mark_kernels(gen, node);
4962 node = add_to_from_device(node, domain, prefix, gen->prog);
4963 schedule = isl_schedule_node_get_schedule(node);
4964 isl_schedule_node_free(node);
4966 return schedule;
4969 /* Internal data structure for extract_access.
4970 * "next_access" points to the end of a linked list that is extended
4971 * by extract_access.
4972 * "single_expression" is set if the access expressions belong to
4973 * an expression statement (i.e., a statement without internal control).
4974 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4976 struct ppcg_extract_access_data {
4977 struct gpu_stmt_access **next_access;
4978 int single_expression;
4979 isl_union_map *any_to_outer;
4982 /* Given a tagged access relation to a single array "tagged", extract it
4983 * as a map, taking into account that the input may be empty.
4984 * If the access relation is empty, then it does not contain
4985 * any space information, so we try to recover it from the index
4986 * expression.
4987 * The space of the index expression is of the form I -> A,
4988 * with I the statement instances and A the array, or [I -> F] -> A,
4989 * with F the filters corresponding to arguments.
4990 * We first drop F, if present, obtaining I -> A.
4991 * Then we construct I -> R, with R the reference tag,
4992 * combine the two into I -> [R -> A] and uncurry to obtain
4993 * the final result [I -> R] -> A.
4994 * Note that the index expression may have a lower dimension
4995 * than that of the array, but this dimension is not used
4996 * if the access relation is empty.
4998 static __isl_give isl_map *extract_single_tagged_access(
4999 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
5001 int empty;
5002 isl_id *id;
5003 isl_space *space, *space2;
5004 isl_multi_pw_aff *index;
5006 empty = isl_union_map_is_empty(tagged);
5007 if (empty < 0)
5008 goto error;
5009 if (!empty)
5010 return isl_map_from_union_map(tagged);
5011 isl_union_map_free(tagged);
5013 index = pet_expr_access_get_index(expr);
5014 space = isl_multi_pw_aff_get_space(index);
5015 isl_multi_pw_aff_free(index);
5016 if (isl_space_domain_is_wrapping(space))
5017 space = isl_space_domain_factor_domain(space);
5018 space2 = isl_space_copy(space);
5019 space2 = isl_space_from_domain(isl_space_domain(space));
5020 id = pet_expr_access_get_ref_id(expr);
5021 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
5022 space = isl_space_range_product(space2, space);
5023 space = isl_space_uncurry(space);
5025 return isl_map_empty(space);
5026 error:
5027 isl_union_map_free(tagged);
5028 return NULL;
5031 /* Extract a gpu_stmt_access from "expr", append it to the list
5032 * that ends in *data->next_access and update the end of the list.
5033 * If the access expression performs a write, then it is considered
5034 * exact only if it appears in a single expression statement and
5035 * if its may access relation is equal to its must access relation.
5037 * The combined set of may accesses may be union if member accesses
5038 * are involved, but the entire set is derived from a single reference and
5039 * therefore from a single index expression. These accesses therefore
5040 * all map to the same outer array.
5042 static int extract_access(__isl_keep pet_expr *expr, void *user)
5044 struct ppcg_extract_access_data *data = user;
5045 isl_union_map *tagged;
5046 struct gpu_stmt_access *access;
5047 isl_ctx *ctx = pet_expr_get_ctx(expr);
5048 isl_multi_pw_aff *index;
5050 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5051 assert(access);
5052 access->next = NULL;
5053 access->read = pet_expr_access_is_read(expr);
5054 access->write = pet_expr_access_is_write(expr);
5055 tagged = pet_expr_access_get_tagged_may_read(expr);
5056 tagged = isl_union_map_union(tagged,
5057 pet_expr_access_get_tagged_may_write(expr));
5058 tagged = isl_union_map_apply_range(tagged,
5059 isl_union_map_copy(data->any_to_outer));
5060 if (!access->write) {
5061 access->exact_write = 1;
5062 } else if (!data->single_expression) {
5063 access->exact_write = 0;
5064 } else {
5065 isl_union_map *must, *may;
5066 may = isl_union_map_copy(tagged);
5067 may = isl_union_map_domain_factor_domain(may);
5068 must = pet_expr_access_get_must_write(expr);
5069 access->exact_write = isl_union_map_is_equal(must, may);
5070 isl_union_map_free(must);
5071 isl_union_map_free(may);
5073 index = pet_expr_access_get_index(expr);
5074 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5075 isl_multi_pw_aff_free(index);
5076 access->ref_id = pet_expr_access_get_ref_id(expr);
5077 access->tagged_access = extract_single_tagged_access(tagged, expr);
5078 access->access = isl_map_copy(access->tagged_access);
5079 access->access = isl_map_domain_factor_domain(access->access);
5081 *data->next_access = access;
5082 data->next_access = &(*data->next_access)->next;
5084 if (!access->access)
5085 return -1;
5087 return 0;
5090 /* Construct a linked list of gpu_stmt_access objects,
5091 * one for each access expression in the statement body.
5092 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5094 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5095 __isl_keep isl_union_map *any_to_outer)
5097 struct ppcg_extract_access_data data;
5099 stmt->accesses = NULL;
5100 data.next_access = &stmt->accesses;
5101 data.single_expression =
5102 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5103 data.any_to_outer = any_to_outer;
5104 return pet_tree_foreach_access_expr(stmt->stmt->body,
5105 &extract_access, &data);
5108 /* Return an array of gpu_stmt representing the statements in "scop".
5110 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5111 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
5113 int i;
5114 struct gpu_stmt *stmts;
5116 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5117 if (!stmts)
5118 return NULL;
5120 for (i = 0; i < scop->pet->n_stmt; ++i) {
5121 struct gpu_stmt *s = &stmts[i];
5123 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5124 s->stmt = scop->pet->stmts[i];
5125 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
5126 return free_stmts(stmts, i + 1);
5129 return stmts;
5132 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5134 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5136 struct gpu_gen *gen = user;
5138 return gen->print(p, gen->prog, gen->tree, &gen->types,
5139 gen->print_user);
5142 /* Generate CUDA code for "scop" and print it to "p".
5143 * After generating an AST for the transformed scop as explained below,
5144 * we call "gen->print" to print the AST in the desired output format
5145 * to "p".
5147 * If it turns out that it does not make sense to generate GPU code,
5148 * then we generate CPU code instead.
5150 * The GPU code is generated in a context where at least one
5151 * statement instance is executed. The corresponding guard (if any) is printed
5152 * around the entire generated GPU code, except for the declaration
5153 * of the arrays that are visible outside of the scop and that therefore
5154 * cannot be declared inside the body of any possible guard.
5156 * We first compute a schedule that respects the dependences
5157 * of the original program and select the outermost bands
5158 * of tilable dimensions that have at least one parallel loop.
5159 * If the --load-schedule is specified, then the loaded schedule
5160 * is used instead of a computed schedule.
5162 * Each of these bands B is then tiled according to "tile" sizes, resulting
5163 * in two nested bands, with a kernel marker on top
5171 * We then split off at most 2 parallel dimensions from the T band and
5172 * at most 3 parallel dimension from the P band
5177 * T1
5179 * T2
5181 * P1
5183 * P2
5185 * A filter is introduced in front of T1 that maps the domain instances
5186 * to block identifiers. Similarly, a filter is introduced in front of P1
5187 * that maps the domain instances to thread identifiers.
5189 * For each iteration of the T2 band and for each array, we compute
5190 * the array elements accessed by that iteration, construct a rectangular
5191 * box around it and shift it to the origin. The result is used
5192 * as shared memory for the array.
5194 * Copying and synchronization statements are added to this schedule tree.
5195 * In principle, these are added in front of the P1 band, but some of
5196 * them may get hoisted up to higher levels.
5198 * The entire AST is then generated from the single resulting schedule tree.
5199 * During the generation the subtrees at kernel nodes (K) are saved
5200 * aside and replaced by kernel calls. The result is printed as host code
5201 * while the saved subtrees are printed as device code.
5203 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5204 struct gpu_gen *gen, struct ppcg_scop *scop,
5205 struct ppcg_options *options)
5207 struct gpu_prog *prog;
5208 isl_ctx *ctx;
5209 isl_set *context, *guard;
5210 isl_schedule *schedule;
5211 int any_permutable;
5213 if (!scop)
5214 return isl_printer_free(p);
5216 ctx = isl_printer_get_ctx(p);
5217 prog = gpu_prog_alloc(ctx, scop);
5218 if (!prog)
5219 return isl_printer_free(p);
5221 context = isl_set_copy(prog->context);
5222 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5223 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5225 gen->prog = prog;
5226 schedule = get_schedule(gen);
5228 any_permutable = has_any_permutable_node(schedule);
5229 if (any_permutable < 0 || !any_permutable) {
5230 isl_set_free(context);
5231 isl_set_free(guard);
5232 if (any_permutable < 0)
5233 p = isl_printer_free(p);
5234 else
5235 p = print_cpu(p, scop, options);
5236 isl_schedule_free(schedule);
5237 } else {
5238 schedule = map_to_device(gen, schedule);
5239 gen->tree = generate_code(gen, schedule);
5240 p = ppcg_print_exposed_declarations(p, prog->scop);
5241 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5242 isl_ast_node_free(gen->tree);
5245 gpu_prog_free(prog);
5247 return p;
5250 /* Wrapper around generate for use as a ppcg_transform callback.
5252 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5253 struct ppcg_scop *scop, void *user)
5255 struct gpu_gen *gen = user;
5257 return generate(p, gen, scop, gen->options);
5260 /* Transform the code in the file called "input" by replacing
5261 * all scops by corresponding GPU code and write the results to "out".
5263 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5264 struct ppcg_options *options,
5265 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5266 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5267 struct gpu_types *types, void *user), void *user)
5269 struct gpu_gen gen;
5270 int r;
5271 int i;
5273 gen.ctx = ctx;
5274 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5275 gen.options = options;
5276 gen.kernel_id = 0;
5277 gen.print = print;
5278 gen.print_user = user;
5279 gen.types.n = 0;
5280 gen.types.name = NULL;
5282 if (options->debug->dump_sizes) {
5283 isl_space *space = isl_space_params_alloc(ctx, 0);
5284 gen.used_sizes = isl_union_map_empty(space);
5287 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5289 if (options->debug->dump_sizes) {
5290 isl_union_map_dump(gen.used_sizes);
5291 isl_union_map_free(gen.used_sizes);
5294 isl_union_map_free(gen.sizes);
5295 for (i = 0; i < gen.types.n; ++i)
5296 free(gen.types.name[i]);
5297 free(gen.types.name);
5299 return r;
5302 /* Compute the set of inner array elements that may have their values
5303 * preserved by "prog". In particular, collect the array elements of
5304 * arrays that are not local to "prog" and remove those elements that
5305 * are definitely killed or definitely written by "prog".
5307 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5309 int i;
5310 isl_union_set *may_persist, *killed;
5311 isl_union_map *must_kill;
5313 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5314 for (i = 0; i < prog->n_array; ++i) {
5315 isl_set *extent;
5317 if (prog->array[i].local)
5318 continue;
5320 extent = isl_set_copy(prog->array[i].extent);
5321 may_persist = isl_union_set_add_set(may_persist, extent);
5324 may_persist = isl_union_set_intersect_params(may_persist,
5325 isl_set_copy(prog->context));
5326 may_persist = isl_union_set_apply(may_persist,
5327 isl_union_map_copy(prog->to_inner));
5328 must_kill = isl_union_map_copy(prog->tagged_must_kill);
5329 killed = isl_union_map_range(must_kill);
5330 must_kill = isl_union_map_copy(prog->must_write);
5331 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
5333 may_persist = isl_union_set_subtract(may_persist, killed);
5334 return may_persist;
5337 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5339 struct gpu_prog *prog;
5340 isl_space *space;
5341 isl_map *id;
5343 if (!scop)
5344 return NULL;
5346 prog = isl_calloc_type(ctx, struct gpu_prog);
5347 assert(prog);
5349 prog->ctx = ctx;
5350 prog->scop = scop;
5351 prog->context = isl_set_copy(scop->context);
5352 prog->n_stmts = scop->pet->n_stmt;
5353 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5354 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5355 space = isl_union_map_get_space(prog->any_to_outer);
5356 space = isl_space_set_from_params(space);
5357 space = isl_space_add_dims(space, isl_dim_set, 1);
5358 space = isl_space_map_from_set(space);
5359 id = isl_map_identity(space);
5360 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
5361 prog->stmts = extract_stmts(ctx, scop,
5362 prog->context, prog->any_to_outer);
5363 prog->read = isl_union_map_copy(scop->reads);
5364 prog->may_write = isl_union_map_copy(scop->may_writes);
5365 prog->must_write = isl_union_map_copy(scop->must_writes);
5366 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
5367 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
5368 prog->to_outer = isl_union_map_copy(prog->to_inner);
5369 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5371 if (!prog->stmts)
5372 return gpu_prog_free(prog);
5374 if (collect_array_info(prog) < 0)
5375 return gpu_prog_free(prog);
5376 prog->may_persist = compute_may_persist(prog);
5378 return prog;
5381 void *gpu_prog_free(struct gpu_prog *prog)
5383 if (!prog)
5384 return NULL;
5385 free_array_info(prog);
5386 free_stmts(prog->stmts, prog->n_stmts);
5387 isl_union_map_free(prog->any_to_outer);
5388 isl_union_map_free(prog->to_outer);
5389 isl_union_map_free(prog->to_inner);
5390 isl_union_map_free(prog->read);
5391 isl_union_map_free(prog->may_write);
5392 isl_union_map_free(prog->must_write);
5393 isl_union_map_free(prog->tagged_must_kill);
5394 isl_union_map_free(prog->array_order);
5395 isl_union_set_free(prog->may_persist);
5396 isl_set_free(prog->context);
5397 free(prog);
5398 return NULL;