gpu: also create (a single) array reference group for arrays of structs
[ppcg.git] / gpu.c
blob3722f8444d7de6d267a3cce543c358618c4ca376
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 /* Return the set of parameter values for which the array has a positive
406 * size in all dimensions.
407 * If the sizes are only valid for some parameter values, then those
408 * constraints are also taken into account.
410 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
412 int i;
413 isl_space *space;
414 isl_set *guard;
416 if (!array)
417 return NULL;
419 space = isl_space_params(isl_space_copy(array->space));
420 guard = isl_set_universe(space);
422 for (i = 0; i < array->n_index; ++i) {
423 isl_pw_aff *bound;
424 isl_set *guard_i, *zero;
426 bound = isl_pw_aff_copy(array->bound[i]);
427 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
428 zero = isl_pw_aff_zero_set(bound);
429 guard_i = isl_set_subtract(guard_i, zero);
430 guard = isl_set_intersect(guard, guard_i);
433 return guard;
436 /* Internal data structure for extract_size_of_type.
437 * "type" specifies the name of the space that we want to extract.
438 * "res" is used to store the subset of that space.
440 struct ppcg_extract_size_data {
441 const char *type;
442 isl_set *res;
445 /* This function is called for each set in a union_set.
446 * If the name of the set matches data->type, we store the
447 * set in data->res.
449 static int extract_size_of_type(__isl_take isl_set *size, void *user)
451 struct ppcg_extract_size_data *data = user;
452 const char *name;
454 name = isl_set_get_tuple_name(size);
455 if (name && !strcmp(name, data->type)) {
456 data->res = size;
457 return -1;
460 isl_set_free(size);
461 return 0;
464 /* Given a union map { kernel[i] -> *[...] },
465 * return the range in the space called "type" for the kernel with
466 * sequence number "id".
468 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
469 const char *type, int id)
471 isl_space *space;
472 isl_set *dom;
473 isl_union_set *local_sizes;
474 struct ppcg_extract_size_data data = { type, NULL };
476 if (!sizes)
477 return NULL;
479 space = isl_union_map_get_space(sizes);
480 space = isl_space_set_from_params(space);
481 space = isl_space_add_dims(space, isl_dim_set, 1);
482 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
483 dom = isl_set_universe(space);
484 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
486 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
487 isl_union_map_copy(sizes));
488 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
489 isl_union_set_free(local_sizes);
490 return data.res;
493 /* Given a singleton set, extract the first (at most *len) elements
494 * of the single integer tuple into *sizes and update *len if needed.
496 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
498 int i;
499 int dim;
501 if (!set)
502 return;
504 dim = isl_set_dim(set, isl_dim_set);
505 if (dim < *len)
506 *len = dim;
508 for (i = 0; i < *len; ++i) {
509 isl_val *v;
511 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
512 assert(v);
514 sizes[i] = isl_val_get_num_si(v);
515 isl_val_free(v);
518 isl_set_free(set);
521 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
522 * if the option debug->dump_sizes is set.
524 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
525 int *sizes, int len)
527 int i;
528 isl_space *space;
529 isl_map *map;
531 if (!gen->options->debug->dump_sizes)
532 return;
534 space = isl_union_map_get_space(gen->used_sizes);
535 space = isl_space_set_from_params(space);
536 space = isl_space_add_dims(space, isl_dim_set, 1);
537 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
538 space = isl_space_from_domain(space);
539 space = isl_space_add_dims(space, isl_dim_out, len);
540 space = isl_space_set_tuple_name(space, isl_dim_out, type);
542 map = isl_map_universe(space);
543 map = isl_map_fix_si(map, isl_dim_in, 0, id);
544 for (i = 0; i < len; ++i)
545 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
547 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
550 /* Extract user specified "tile" sizes from the "sizes" command line option,
551 * defaulting to option->tile_size in each dimension.
552 * *tile_len contains the maximum number of tile sizes needed.
553 * Update *tile_len to the number of specified tile sizes, if any, and
554 * return a pointer to the tile sizes (or NULL on error).
555 * Add the effectively used sizes to gen->used_sizes.
557 static int *read_tile_sizes(struct gpu_gen *gen, int *tile_len)
559 int n;
560 int *tile_size;
561 isl_set *size;
563 tile_size = isl_alloc_array(gen->ctx, int, *tile_len);
564 if (!tile_size)
565 return NULL;
566 for (n = 0; n < *tile_len; ++n)
567 tile_size[n] = gen->options->tile_size;
569 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
570 read_sizes_from_set(size, tile_size, tile_len);
571 set_used_sizes(gen, "tile", gen->kernel_id, tile_size, *tile_len);
573 return tile_size;
576 /* Extract user specified "block" sizes from the "sizes" command line option,
577 * after filling in some potentially useful defaults.
579 static void read_block_sizes(struct ppcg_kernel *kernel,
580 __isl_keep isl_union_map *sizes)
582 isl_set *size;
584 if (kernel->n_block > 3)
585 kernel->n_block = 3;
586 switch (kernel->n_block) {
587 case 1:
588 kernel->block_dim[0] = 512;
589 break;
590 case 2:
591 kernel->block_dim[0] = 32;
592 kernel->block_dim[1] = 16;
593 break;
594 default:
595 kernel->block_dim[0] = 32;
596 kernel->block_dim[1] = 4;
597 kernel->block_dim[2] = 4;
598 break;
601 size = extract_sizes(sizes, "block", kernel->id);
602 read_sizes_from_set(size, kernel->block_dim, &kernel->n_block);
605 /* Extract user specified "grid" sizes from the "sizes" command line option,
606 * after filling in some potentially useful defaults.
608 static void read_grid_sizes(struct ppcg_kernel *kernel,
609 __isl_keep isl_union_map *sizes)
611 isl_set *size;
613 if (kernel->n_grid > 2)
614 kernel->n_grid = 2;
615 switch (kernel->n_grid) {
616 case 1:
617 kernel->grid_dim[0] = 32768;
618 break;
619 default:
620 kernel->grid_dim[0] = 256;
621 kernel->grid_dim[1] = 256;
622 break;
625 size = extract_sizes(sizes, "grid", kernel->id);
626 read_sizes_from_set(size, kernel->grid_dim, &kernel->n_grid);
629 /* Extract user specified grid and block sizes from the gen->sizes
630 * command line option after filling in some potentially useful defaults.
631 * Store the extracted sizes in "kernel".
632 * Add the effectively used sizes to gen->used_sizes.
634 static void read_grid_and_block_sizes(struct ppcg_kernel *kernel,
635 struct gpu_gen *gen)
637 read_block_sizes(kernel, gen->sizes);
638 read_grid_sizes(kernel, gen->sizes);
639 set_used_sizes(gen, "block", kernel->id,
640 kernel->block_dim, kernel->n_block);
641 set_used_sizes(gen, "grid", kernel->id,
642 kernel->grid_dim, kernel->n_grid);
645 static void *free_stmts(struct gpu_stmt *stmts, int n)
647 int i;
649 if (!stmts)
650 return NULL;
652 for (i = 0; i < n; ++i) {
653 struct gpu_stmt_access *access, *next;
655 for (access = stmts[i].accesses; access; access = next) {
656 next = access->next;
657 isl_id_free(access->ref_id);
658 isl_map_free(access->access);
659 isl_map_free(access->tagged_access);
660 free(access);
663 isl_id_free(stmts[i].id);
665 free(stmts);
667 return NULL;
670 /* Add parameters p[i] with identifiers "ids" to "set",
671 * with bounds to 0 <= p[i] < size[i].
673 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
674 int *size, __isl_keep isl_id_list *ids)
676 int i, len;
677 unsigned nparam;
679 len = isl_id_list_n_id(ids);
680 nparam = isl_set_dim(set, isl_dim_param);
681 set = isl_set_add_dims(set, isl_dim_param, len);
683 for (i = 0; i < len; ++i) {
684 isl_id *id;
686 id = isl_id_list_get_id(ids, i);
687 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
688 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
689 set = isl_set_upper_bound_si(set, isl_dim_param,
690 nparam + i, size[i] - 1);
693 return set;
696 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
697 * with
699 * { : 0 <= p[i] < size[i] }
701 * or an overapproximation.
703 static __isl_give isl_set *add_bounded_parameters_dynamic(
704 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
705 __isl_keep isl_id_list *ids)
707 int i, len;
708 unsigned nparam;
709 isl_space *space;
710 isl_local_space *ls;
712 len = isl_multi_pw_aff_dim(size, isl_dim_out);
713 nparam = isl_set_dim(set, isl_dim_param);
714 set = isl_set_add_dims(set, isl_dim_param, len);
716 for (i = 0; i < len; ++i) {
717 isl_id *id;
719 id = isl_id_list_get_id(ids, i);
720 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
723 space = isl_space_params(isl_set_get_space(set));
724 ls = isl_local_space_from_space(space);
725 for (i = 0; i < len; ++i) {
726 isl_pw_aff *param, *size_i, *zero;
727 isl_set *bound;
729 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
730 isl_dim_param, nparam + i);
732 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
733 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
734 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
735 set = isl_set_intersect_params(set, bound);
737 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
738 bound = isl_pw_aff_ge_set(param, zero);
739 set = isl_set_intersect_params(set, bound);
741 isl_local_space_free(ls);
743 return set;
746 /* Return the union of all tagged access relations in the group.
748 static __isl_give isl_union_map *group_tagged_access_relation(
749 struct gpu_array_ref_group *group)
751 int i;
752 isl_union_map *access;
754 access = isl_union_map_empty(isl_map_get_space(group->access));
755 for (i = 0; i < group->n_ref; ++i) {
756 isl_map *map_i;
758 map_i = isl_map_copy(group->refs[i]->tagged_access);
759 access = isl_union_map_union(access,
760 isl_union_map_from_map(map_i));
763 return access;
766 /* Return the extent of "array", recomputed from the bounds.
767 * The recomputed extent may be simpler than the original extent.
769 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
771 int i;
772 isl_id *id;
773 isl_space *space;
774 isl_local_space *ls;
775 isl_set *extent;
777 id = isl_set_get_tuple_id(array->extent);
778 space = isl_set_get_space(array->extent);
779 extent = isl_set_universe(isl_space_copy(space));
780 ls = isl_local_space_from_space(space);
781 for (i = 0; i < array->n_index; ++i) {
782 isl_pw_aff *bound;
783 isl_aff *aff;
784 isl_pw_aff *index;
785 isl_set *lt;
787 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
789 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
790 isl_dim_set, i);
791 index = isl_pw_aff_from_aff(aff);
792 bound = isl_pw_aff_copy(array->bound[i]);
793 bound = isl_pw_aff_from_range(bound);
794 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
795 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
796 isl_id_copy(id));
797 lt = isl_pw_aff_lt_set(index, bound);
798 extent = isl_set_intersect(extent, lt);
800 isl_local_space_free(ls);
801 isl_id_free(id);
803 return extent;
806 /* Return a map from the first group->depth dimensions of the computed
807 * schedule to the array tile in
808 * global memory that corresponds to the shared memory copy.
810 * In particular, return a map
812 * { D[i] -> A[a] }
814 * with constraints
816 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
818 * and
820 * 0 <= a <= array_size - 1 (2)
822 * Note that if some stride has been detected (i.e., when
823 * group->shared_tile->bound[i].shift is set), then a in (1) refers
824 * to the shifted and scaled down version.
826 * Constraints (1) are obtained by mapping the size constraints on the
827 * shared/private memory tile back to the access relation.
828 * Constraints (2) are obtained from the (recomputed) extent.
830 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
832 int i;
833 int n_index = group->array->n_index;
834 isl_map *tile;
835 isl_space *space;
836 isl_set *local;
837 isl_set *extent;
839 space = isl_multi_aff_get_space(group->shared_tile->tiling);
840 space = isl_space_range(space);
841 local = isl_set_universe(space);
842 for (i = 0; i < n_index; ++i) {
843 isl_val *bound;
845 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
846 bound = isl_val_copy(group->shared_tile->bound[i].size);
847 bound = isl_val_sub_ui(bound, 1);
848 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
850 local = isl_set_preimage_multi_aff(local,
851 isl_multi_aff_copy(group->shared_tile->tiling));
852 tile = isl_set_unwrap(local);
853 extent = array_extent(group->array);
854 tile = isl_map_intersect_range(tile, extent);
856 return tile;
859 /* Given a mapping "iterator_map" from the AST schedule to a domain,
860 * return the corresponding mapping from the AST schedule to
861 * to the outer kernel->shared_schedule_dim dimensions of
862 * the schedule computed by PPCG for this kernel.
864 * Note that kernel->shared_schedule_dim is at least as large as
865 * the largest depth of any array reference group associated to the kernel.
866 * This is needed as the returned schedule is used to extract a mapping
867 * to the outer group->depth dimensions in transform_index.
869 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(
870 struct ppcg_kernel *kernel, __isl_take isl_pw_multi_aff *iterator_map)
872 isl_union_pw_multi_aff *upma;
873 isl_pw_multi_aff *pma;
874 isl_space *space;
876 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
877 space = isl_space_from_domain(space);
878 space = isl_space_add_dims(space, isl_dim_out,
879 kernel->shared_schedule_dim);
881 upma = isl_union_pw_multi_aff_copy(kernel->shared_schedule);
882 pma = isl_union_pw_multi_aff_extract_pw_multi_aff(upma, space);
883 isl_union_pw_multi_aff_free(upma);
885 return isl_pw_multi_aff_pullback_pw_multi_aff(pma, iterator_map);
888 /* If max_shared_memory is not set to infinity (-1), then make
889 * sure that the total amount of shared memory required by the
890 * array reference groups mapped to shared memory by "kernel"
891 * is no larger than this maximum.
893 * We apply a greedy approach and discard (keep in global memory)
894 * those groups that would result in a total memory size that
895 * is larger than the maximum.
897 * This function should be called after any function that may
898 * affect the decision on whether to place a reference group
899 * in private, shared or global memory.
901 static void check_shared_memory_bound(struct ppcg_kernel *kernel)
903 int i, j;
904 isl_val *left, *size;
906 if (kernel->options->max_shared_memory < 0)
907 return;
909 left = isl_val_int_from_si(kernel->ctx,
910 kernel->options->max_shared_memory);
912 for (i = 0; i < kernel->n_array; ++i) {
913 struct gpu_local_array_info *local = &kernel->array[i];
915 for (j = 0; j < local->n_group; ++j) {
916 struct gpu_array_ref_group *group;
918 group = local->groups[j];
919 if (group->private_tile)
920 continue;
921 if (!group->shared_tile)
922 continue;
924 size = gpu_array_tile_size(group->shared_tile);
925 size = isl_val_mul_ui(size, local->array->size);
927 if (isl_val_le(size, left)) {
928 left = isl_val_sub(left, size);
929 continue;
931 isl_val_free(size);
933 group->shared_tile =
934 gpu_array_tile_free(group->shared_tile);
938 isl_val_free(left);
941 /* Compute a tiling for all the array reference groups in "kernel".
943 static void compute_group_tilings(struct ppcg_kernel *kernel)
945 int i, j;
947 for (i = 0; i < kernel->n_array; ++i) {
948 struct gpu_local_array_info *array = &kernel->array[i];
950 for (j = 0; j < array->n_group; ++j)
951 gpu_array_ref_group_compute_tiling(array->groups[j]);
955 /* Compute the size of a bounding box around the origin and "set",
956 * where "set" is assumed to contain only non-negative elements.
957 * In particular, compute the maximal value of "set" in each direction
958 * and add one.
960 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
961 __isl_take isl_set *context)
963 int i, n;
964 isl_multi_pw_aff *mpa;
966 context = isl_set_params(context);
967 n = isl_set_dim(set, isl_dim_set);
968 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
969 for (i = 0; i < n; ++i) {
970 isl_space *space;
971 isl_aff *one;
972 isl_pw_aff *bound;
974 bound = isl_set_dim_max(isl_set_copy(set), i);
975 bound = isl_pw_aff_coalesce(bound);
976 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
978 space = isl_pw_aff_get_domain_space(bound);
979 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
980 one = isl_aff_add_constant_si(one, 1);
981 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
982 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
984 isl_set_free(set);
985 isl_set_free(context);
987 return mpa;
990 /* Compute the effective grid size as a list of the sizes in each dimension.
992 * The grid size specified by the user or set by default
993 * in read_grid_sizes() and applied by the block filter,
994 * may be too large for the given code in the sense that
995 * it may contain blocks that don't need to execute anything.
996 * We therefore don't return this grid size, but instead the
997 * smallest grid size that ensures that all blocks that actually
998 * execute code are included in the grid.
1000 * We first extract a description of the grid, i.e., the possible values
1001 * of the block ids, from the domain elements in "domain" and
1002 * kernel->block_filter.
1003 * The block ids are parameters in kernel->block_filter.
1004 * We simply need to change them into set dimensions.
1006 * Then, for each block dimension, we compute the maximal value of the block id
1007 * and add one.
1009 static __isl_give isl_multi_pw_aff *extract_grid_size(
1010 struct ppcg_kernel *kernel, __isl_take isl_union_set *domain)
1012 int i;
1013 isl_set *grid;
1015 domain = isl_union_set_intersect(domain,
1016 isl_union_set_copy(kernel->block_filter));
1017 grid = isl_union_set_params(domain);
1018 grid = isl_set_from_params(grid);
1019 grid = isl_set_add_dims(grid, isl_dim_set, kernel->n_grid);
1020 for (i = 0; i < kernel->n_grid; ++i) {
1021 int pos;
1022 isl_id *id;
1024 id = isl_id_list_get_id(kernel->block_ids, i);
1025 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1026 isl_id_free(id);
1027 assert(pos >= 0);
1028 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1029 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1032 return extract_size(grid, isl_set_copy(kernel->context));
1035 /* Compute the size of a fixed bounding box around the origin and "set",
1036 * where "set" is assumed to contain only non-negative elements,
1037 * and store the results in "size".
1038 * In particular, compute the maximal value of "set" in each direction
1039 * and add one.
1041 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1043 int i, n;
1044 isl_local_space *ls;
1045 isl_aff *obj;
1047 n = isl_set_dim(set, isl_dim_set);
1048 ls = isl_local_space_from_space(isl_set_get_space(set));
1049 obj = isl_aff_zero_on_domain(ls);
1050 for (i = 0; i < n; ++i) {
1051 isl_val *max;
1053 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1054 max = isl_set_max_val(set, obj);
1055 size[i] = isl_val_get_num_si(max) + 1;
1056 isl_val_free(max);
1057 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1059 isl_aff_free(obj);
1060 isl_set_free(set);
1063 /* Compute the effective block size as a list of the sizes in each dimension
1064 * and store the sizes in kernel->block_dim.
1066 * The block size specified by the user or set by default
1067 * in read_block_sizes() and applied by the thread filter,
1068 * may be too large for the given code in the sense that
1069 * it may contain threads that don't need to execute anything.
1070 * We therefore update this block size in kernel->block_dim
1071 * to the smallest block size that ensures that all threads
1072 * that actually execute code are included in the block.
1074 * The possible values of the thread ids is obtained from
1075 * the domain elements "domain" and kernel->thread_filter.
1076 * The current implementation eliminates all parameters, ensuring
1077 * that the size is a fixed constant in each dimension.
1078 * In principle we could also compute parametric sizes.
1079 * We would have to make sure to project out all b%d and t%d parameters,
1080 * however.
1082 static void extract_block_size(struct ppcg_kernel *kernel,
1083 __isl_take isl_union_set *domain)
1085 int i;
1086 int nparam;
1087 isl_set *block;
1089 domain = isl_union_set_intersect(domain,
1090 isl_union_set_copy(kernel->thread_filter));
1091 block = isl_union_set_params(domain);
1092 block = isl_set_from_params(block);
1093 block = isl_set_add_dims(block, isl_dim_set, kernel->n_block);
1094 for (i = 0; i < kernel->n_block; ++i) {
1095 int pos;
1096 isl_id *id;
1098 id = isl_id_list_get_id(kernel->thread_ids, i);
1099 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1100 isl_id_free(id);
1101 assert(pos >= 0);
1102 block = isl_set_equate(block, isl_dim_param, pos,
1103 isl_dim_set, i);
1105 nparam = isl_set_dim(block, isl_dim_param);
1106 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1108 extract_fixed_size(block, kernel->block_dim);
1111 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1113 int i, j;
1115 if (!kernel)
1116 return NULL;
1118 isl_id_list_free(kernel->block_ids);
1119 isl_id_list_free(kernel->thread_ids);
1120 isl_multi_pw_aff_free(kernel->grid_size);
1121 isl_set_free(kernel->context);
1122 isl_union_set_free(kernel->core);
1123 isl_union_set_free(kernel->arrays);
1124 isl_space_free(kernel->space);
1125 isl_ast_node_free(kernel->tree);
1126 isl_union_set_free(kernel->block_filter);
1127 isl_union_set_free(kernel->thread_filter);
1128 isl_union_pw_multi_aff_free(kernel->shared_schedule);
1129 isl_union_set_free(kernel->sync_writes);
1131 for (i = 0; i < kernel->n_array; ++i) {
1132 struct gpu_local_array_info *array = &kernel->array[i];
1134 for (j = 0; j < array->n_group; ++j)
1135 gpu_array_ref_group_free(array->groups[j]);
1136 free(array->groups);
1138 isl_pw_aff_list_free(array->bound);
1140 free(kernel->array);
1142 for (i = 0; i < kernel->n_var; ++i) {
1143 free(kernel->var[i].name);
1144 isl_vec_free(kernel->var[i].size);
1146 free(kernel->var);
1148 free(kernel);
1150 return NULL;
1153 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1155 static void ppcg_kernel_free_wrap(void *user)
1157 struct ppcg_kernel *kernel = user;
1159 ppcg_kernel_free(kernel);
1162 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1163 struct ppcg_kernel_var *var)
1165 int j;
1166 struct gpu_array_tile *tile;
1167 isl_printer *p;
1168 char *name;
1170 var->array = group->array;
1172 tile = group->private_tile;
1173 var->type = ppcg_access_private;
1174 if (!tile) {
1175 tile = group->shared_tile;
1176 var->type = ppcg_access_shared;
1179 p = isl_printer_to_str(ctx);
1180 p = gpu_array_ref_group_print_name(group, p);
1181 var->name = isl_printer_get_str(p);
1182 isl_printer_free(p);
1184 var->size = isl_vec_alloc(ctx, group->array->n_index);
1186 for (j = 0; j < group->array->n_index; ++j)
1187 var->size = isl_vec_set_element_val(var->size, j,
1188 isl_val_copy(tile->bound[j].size));
1191 static int create_kernel_vars(struct ppcg_kernel *kernel)
1193 int i, j, n;
1195 n = 0;
1196 for (i = 0; i < kernel->n_array; ++i) {
1197 struct gpu_local_array_info *array = &kernel->array[i];
1199 for (j = 0; j < array->n_group; ++j) {
1200 struct gpu_array_ref_group *group = array->groups[j];
1201 if (group->private_tile || group->shared_tile)
1202 ++n;
1206 kernel->n_var = n;
1207 kernel->var = isl_calloc_array(kernel->ctx, struct ppcg_kernel_var, n);
1208 if (!kernel->var)
1209 return -1;
1211 n = 0;
1212 for (i = 0; i < kernel->n_array; ++i) {
1213 struct gpu_local_array_info *array = &kernel->array[i];
1215 for (j = 0; j < array->n_group; ++j) {
1216 struct gpu_array_ref_group *group = array->groups[j];
1217 if (!group->private_tile && !group->shared_tile)
1218 continue;
1219 create_kernel_var(kernel->ctx, group, &kernel->var[n]);
1220 ++n;
1224 return 0;
1227 /* Replace "pa" by the zero function defined over the universe domain
1228 * in the space of "pa".
1230 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1232 isl_space *space;
1233 isl_aff *zero;
1235 space = isl_space_domain(isl_pw_aff_get_space(pa));
1236 isl_pw_aff_free(pa);
1237 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1239 return isl_pw_aff_from_aff(zero);
1242 /* The sizes of the arrays on the host that have been computed by
1243 * extract_array_info may depend on the parameters. Use the extra
1244 * constraints on the parameters that are valid at "host_domain"
1245 * to simplify these expressions and store the results in kernel->array.
1247 * We only need these localized bounds for arrays that are accessed
1248 * by the current kernel. If we have found at least one reference group
1249 * then the array is accessed by the kernel.
1251 * The resulting sizes may be functions that are nowhere defined
1252 * in case the access function cannot possibly access anything inside
1253 * the kernel for some reason. If so, they are replaced by the zero
1254 * function. Since the access function cannot actually access anything,
1255 * there is no harm in printing the array sizes as zero.
1257 static void localize_bounds(struct ppcg_kernel *kernel,
1258 __isl_keep isl_set *host_domain)
1260 int i, j;
1261 isl_set *context;
1263 context = isl_set_copy(host_domain);
1264 context = isl_set_params(context);
1266 for (i = 0; i < kernel->n_array; ++i) {
1267 struct gpu_local_array_info *local = &kernel->array[i];
1268 isl_pw_aff_list *bound;
1269 int n_index;
1271 if (local->n_group == 0)
1272 continue;
1274 n_index = local->array->n_index;
1275 bound = isl_pw_aff_list_alloc(kernel->ctx, n_index);
1277 for (j = 0; j < n_index; ++j) {
1278 isl_pw_aff *pwaff;
1279 int empty;
1281 pwaff = isl_pw_aff_copy(local->array->bound[j]);
1282 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1283 empty = isl_pw_aff_is_empty(pwaff);
1284 if (empty < 0)
1285 pwaff = isl_pw_aff_free(pwaff);
1286 else if (empty)
1287 pwaff = set_universally_zero(pwaff);
1288 bound = isl_pw_aff_list_add(bound, pwaff);
1291 local->n_index = n_index;
1292 local->bound = bound;
1294 isl_set_free(context);
1297 /* Create the array of gpu_local_array_info structures "array"
1298 * inside "kernel". The number of elements in this array is
1299 * the same as the number of arrays in "prog".
1300 * Initialize the "array" field of each local array to point
1301 * to the corresponding array in "prog".
1303 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1304 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1306 int i;
1307 isl_ctx *ctx;
1309 ctx = isl_set_get_ctx(prog->context);
1310 kernel->array = isl_calloc_array(ctx,
1311 struct gpu_local_array_info, prog->n_array);
1312 if (!kernel->array)
1313 return ppcg_kernel_free(kernel);
1314 kernel->n_array = prog->n_array;
1316 for (i = 0; i < prog->n_array; ++i)
1317 kernel->array[i].array = &prog->array[i];
1319 return kernel;
1322 /* Find the element in gen->stmt that has the given "id".
1323 * Return NULL if no such gpu_stmt can be found.
1325 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1327 int i;
1329 for (i = 0; i < prog->n_stmts; ++i) {
1330 if (id == prog->stmts[i].id)
1331 break;
1334 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1337 void ppcg_kernel_stmt_free(void *user)
1339 int i;
1340 struct ppcg_kernel_stmt *stmt = user;
1342 if (!stmt)
1343 return;
1345 switch (stmt->type) {
1346 case ppcg_kernel_copy:
1347 isl_ast_expr_free(stmt->u.c.index);
1348 isl_ast_expr_free(stmt->u.c.local_index);
1349 break;
1350 case ppcg_kernel_domain:
1351 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1352 break;
1353 case ppcg_kernel_sync:
1354 break;
1357 free(stmt);
1360 /* Return the gpu_stmt_access in the list "accesses" that corresponds
1361 * to "ref_id".
1363 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1364 __isl_keep isl_id *ref_id)
1366 struct gpu_stmt_access *access;
1368 for (access = accesses; access; access = access->next)
1369 if (access->ref_id == ref_id)
1370 return access;
1372 return NULL;
1375 /* Return the index of the array called "name" in the list of arrays.
1377 static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1379 int i;
1381 for (i = 0; i < kernel->n_array; ++i)
1382 if (!strcmp(name, kernel->array[i].array->name))
1383 return i;
1385 return -1;
1388 /* Internal data structure for the index and AST expression transformation
1389 * callbacks for pet_stmt_build_ast_exprs.
1391 * "kernel" is the kernel for which are computing AST expressions and
1392 * may be NULL if we are not inside a kernel.
1393 * "accesses" is the list of gpu_stmt_access in the statement.
1394 * "iterator_map" expresses the statement iterators in terms of
1395 * the AST loop iterators.
1396 * "sched2shared" expresses the outer shared_schedule_dim dimensions of
1397 * the kernel schedule in terms of the AST loop iterators and
1398 * may be NULL if we are not inside a kernel.
1400 * The following fields are set in transform_index and used in transform_expr.
1401 * "array" is the array that is being accessed.
1402 * "global" is set if the global array is accessed (rather than
1403 * shared/private memory).
1404 * "local_array" refers to information on the array specialized
1405 * to the current kernel.
1407 struct ppcg_transform_data {
1408 struct ppcg_kernel *kernel;
1409 struct gpu_stmt_access *accesses;
1410 isl_pw_multi_aff *iterator_map;
1411 isl_pw_multi_aff *sched2shared;
1413 struct gpu_array_info *array;
1414 int global;
1415 struct gpu_local_array_info *local_array;
1418 /* Return a pointer to the gpu_array_ref_group in "local"
1419 * that contains the reference "access".
1420 * Return NULL if no such group can be found.
1422 static struct gpu_array_ref_group *find_ref_group(
1423 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1425 int i, j;
1427 for (i = 0; i < local->n_group; ++i) {
1428 struct gpu_array_ref_group *group = local->groups[i];
1430 for (j = 0; j < group->n_ref; ++j)
1431 if (group->refs[j] == access)
1432 return group;
1435 return NULL;
1438 /* Index transformation callback for pet_stmt_build_ast_exprs.
1440 * "index" expresses the array indices in terms of statement iterators
1442 * We first reformulate "index" in terms of the AST loop iterators.
1443 * Then we check if we are accessing the global array or
1444 * a shared/private copy. In particular, if we are not inside a kernel
1445 * then we must be accessing a global array.
1446 * In the former case, we simply return
1447 * the updated index. If "index" is an affine expression rather
1448 * than an array access, then we also return the updated index here.
1450 * If no reference groups have been computed for the array,
1451 * then we can only be accessing the global array.
1453 * Otherwise, we apply the tiling to the index.
1454 * This tiling is of the form
1456 * [D -> A] -> T
1458 * where D corresponds to the outer group->depth dimensions of
1459 * the kernel schedule.
1460 * The index is of the form
1462 * L -> A
1464 * We update the tiling to refer to the AST loop iterators
1466 * [L -> A] -> T
1468 * and modify index to keep track of those iterators
1470 * L -> [L -> A]
1472 * Combining these two yields a tiled index expression in terms
1473 * of the AST loop iterators
1475 * L -> T
1477 static __isl_give isl_multi_pw_aff *transform_index(
1478 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
1479 void *user)
1481 struct ppcg_transform_data *data = user;
1482 struct gpu_stmt_access *access;
1483 struct gpu_array_ref_group *group;
1484 struct gpu_array_tile *tile;
1485 isl_pw_multi_aff *iterator_map;
1486 int i;
1487 int dim;
1488 const char *name;
1489 isl_space *space;
1490 isl_multi_pw_aff *tiling;
1491 isl_pw_multi_aff *pma;
1492 isl_multi_pw_aff *mpa;
1493 isl_pw_multi_aff *sched2depth;
1495 data->array = NULL;
1497 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
1498 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
1500 if (!data->kernel)
1501 return index;
1503 access = find_access(data->accesses, ref_id);
1504 if (!access)
1505 return index;
1506 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1507 return index;
1509 name = get_outer_array_name(access->access);
1510 i = find_array_index(data->kernel, name);
1511 if (i < 0)
1512 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
1513 "cannot find array",
1514 return isl_multi_pw_aff_free(index));
1515 data->local_array = &data->kernel->array[i];
1516 data->array = data->local_array->array;
1518 group = find_ref_group(data->local_array, access);
1519 if (!group) {
1520 data->global = 1;
1521 return index;
1524 tile = group->private_tile;
1525 if (!tile)
1526 tile = group->shared_tile;
1527 data->global = !tile;
1528 if (!tile)
1529 return index;
1531 space = isl_space_range(isl_multi_pw_aff_get_space(index));
1532 space = isl_space_map_from_set(space);
1533 pma = isl_pw_multi_aff_identity(space);
1534 sched2depth = isl_pw_multi_aff_copy(data->sched2shared);
1535 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1536 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1537 group->depth, dim - group->depth);
1538 pma = isl_pw_multi_aff_product(sched2depth, pma);
1539 tiling = isl_multi_pw_aff_from_multi_aff(
1540 isl_multi_aff_copy(tile->tiling));
1541 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1543 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1544 space = isl_space_map_from_set(space);
1545 mpa = isl_multi_pw_aff_identity(space);
1546 index = isl_multi_pw_aff_range_product(mpa, index);
1547 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1549 return index;
1552 /* Dereference "expr" by adding an index [0].
1553 * The original "expr" is assumed not to have any indices.
1555 * If "expr" is a member access, then the dereferencing needs
1556 * to be applied to the structure argument of this member access.
1558 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1560 isl_ctx *ctx;
1561 isl_ast_expr *arg0, *res;
1562 isl_ast_expr_list *list;
1564 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1565 if (!arg0)
1566 return isl_ast_expr_free(expr);
1567 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1568 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1569 isl_ast_expr *arg;
1571 arg = isl_ast_expr_get_op_arg(arg0, 0);
1572 arg = dereference(arg);
1573 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1574 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1576 return expr;
1578 isl_ast_expr_free(arg0);
1580 ctx = isl_ast_expr_get_ctx(expr);
1581 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1582 list = isl_ast_expr_list_from_ast_expr(res);
1583 res = isl_ast_expr_get_op_arg(expr, 0);
1584 res = isl_ast_expr_access(res, list);
1585 isl_ast_expr_free(expr);
1587 return res;
1590 /* Linearize the index expression "expr" based on the array bounds
1591 * of "array".
1593 * That is, transform expression
1595 * A[i_0][i_1]...[i_n]
1597 * to
1599 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1601 * where b_0, b_1, ..., b_n are the bounds on the array.
1603 * If the base of "expr" is a member access, then the linearization needs
1604 * to be applied to the structure argument of this member access.
1606 * In the base case, if "expr" has no arguments (other than the name of
1607 * the array), then we are passing an entire array to a function.
1608 * In this case, there is nothing to linearize.
1609 * Note that at this point an expression with no arguments can
1610 * only be an entire array because the scalar case and
1611 * the case of single struct are handled by the caller.
1613 * If the number of specified index expressions in "expr"
1614 * is smaller than the dimension of the accessed array,
1615 * then the missing i_j also do not appear in the linearized expression.
1616 * Furthermore, since such an expression does not refer to a single
1617 * element while the default linearized expression would refer to
1618 * a single element, we return the expression
1620 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
1622 * instead. Note that because of the special case handling above,
1623 * we can assume here that here that there is at least one index expression.
1625 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1626 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1628 int i, n;
1629 isl_ctx *ctx;
1630 isl_set *context;
1631 isl_ast_expr *arg0;
1632 isl_ast_expr *res;
1633 isl_ast_expr_list *list;
1634 isl_ast_build *build;
1636 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1637 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1638 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1639 isl_ast_expr *arg;
1641 arg = isl_ast_expr_get_op_arg(arg0, 0);
1642 arg = gpu_local_array_info_linearize_index(array, arg);
1643 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1644 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1646 return expr;
1648 isl_ast_expr_free(arg0);
1650 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1651 return expr;
1653 ctx = isl_ast_expr_get_ctx(expr);
1654 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
1655 build = isl_ast_build_from_context(context);
1657 n = isl_ast_expr_get_op_n_arg(expr);
1658 res = isl_ast_expr_get_op_arg(expr, 1);
1659 for (i = 1; i < array->n_index; ++i) {
1660 isl_pw_aff *bound_i;
1661 isl_ast_expr *expr_i;
1663 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
1664 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
1665 res = isl_ast_expr_mul(res, expr_i);
1667 if (i + 1 >= n)
1668 continue;
1669 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1670 res = isl_ast_expr_add(res, expr_i);
1673 isl_ast_build_free(build);
1675 if (1 + array->n_index > n) {
1676 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1677 } else {
1678 list = isl_ast_expr_list_from_ast_expr(res);
1679 res = isl_ast_expr_get_op_arg(expr, 0);
1680 res = isl_ast_expr_access(res, list);
1683 isl_ast_expr_free(expr);
1685 return res;
1688 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
1690 * If the AST expression refers to an array that is not accessed
1691 * at all, then this means the value of the expression is not used,
1692 * so we might as well print zero (NULL pointer) instead.
1694 * If the AST expression refers to a global scalar that is not
1695 * a read-only scalar, then its address was passed to the kernel and
1696 * we need to dereference it.
1698 * If the AST expression refers to an access to a global array,
1699 * then we linearize the access exploiting the bounds in data->local_array.
1701 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1702 __isl_keep isl_id *id, void *user)
1704 struct ppcg_transform_data *data = user;
1706 if (!data->array)
1707 return expr;
1708 if (!data->array->accessed) {
1709 isl_ctx *ctx;
1711 ctx = isl_ast_expr_get_ctx(expr);
1712 isl_ast_expr_free(expr);
1713 return isl_ast_expr_from_val(isl_val_zero(ctx));
1715 if (gpu_array_is_read_only_scalar(data->array))
1716 return expr;
1717 if (!data->global)
1718 return expr;
1719 if (data->array->n_index == 0)
1720 return dereference(expr);
1721 if (!data->array->linearize)
1722 return expr;
1724 return gpu_local_array_info_linearize_index(data->local_array, expr);
1727 /* This function is called for each instance of a user statement
1728 * in the kernel "kernel", identified by "gpu_stmt".
1729 * "kernel" may be NULL if we are not inside a kernel.
1731 * We attach a struct ppcg_kernel_stmt to the "node", containing
1732 * a computed AST expression for each access, through an annotation
1733 * with name "user".
1734 * These AST expressions are computed from iterator_map,
1735 * which expresses the domain
1736 * elements in terms of the generated loops, and sched2shared,
1737 * which expresses the outer shared_schedule_dim dimensions of
1738 * the kernel schedule computed by PPCG in terms of the generated loops.
1740 static __isl_give isl_ast_node *create_domain_leaf(
1741 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1742 __isl_keep isl_ast_build *build, struct gpu_stmt *gpu_stmt)
1744 struct ppcg_transform_data data;
1745 struct ppcg_kernel_stmt *stmt;
1746 isl_ctx *ctx;
1747 isl_id *id;
1748 isl_pw_multi_aff *sched2shared;
1749 isl_map *map;
1750 isl_pw_multi_aff *iterator_map;
1751 isl_union_map *schedule;
1753 if (!node)
1754 return NULL;
1755 ctx = isl_ast_node_get_ctx(node);
1757 stmt = isl_calloc_type(ctx, struct ppcg_kernel_stmt);
1758 if (!stmt)
1759 return isl_ast_node_free(node);
1761 schedule = isl_ast_build_get_schedule(build);
1762 map = isl_map_reverse(isl_map_from_union_map(schedule));
1763 iterator_map = isl_pw_multi_aff_from_map(map);
1764 if (kernel)
1765 sched2shared = compute_sched_to_shared(kernel,
1766 isl_pw_multi_aff_copy(iterator_map));
1767 else
1768 sched2shared = NULL;
1770 stmt->type = ppcg_kernel_domain;
1771 stmt->u.d.stmt = gpu_stmt;
1773 data.kernel = kernel;
1774 data.accesses = stmt->u.d.stmt->accesses;
1775 data.iterator_map = iterator_map;
1776 data.sched2shared = sched2shared;
1777 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
1778 build, &transform_index, &data,
1779 &transform_expr, &data);
1781 isl_pw_multi_aff_free(iterator_map);
1782 isl_pw_multi_aff_free(sched2shared);
1784 id = isl_id_alloc(ctx, "user", stmt);
1785 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1786 return isl_ast_node_set_annotation(node, id);
1789 /* This function is called for each statement node in the AST
1790 * for copying to or from shared/private memory.
1791 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1792 * statement to the node.
1793 * The statement name is "read" or "write", depending on whether we are
1794 * reading from global memory or writing to global memory.
1796 * The schedule is of the form
1798 * type[D -> A] -> L
1800 * where D corresponds to the outer group->depth dimensions of
1801 * the kernel schedule, A to the global array and L to the outer
1802 * generated AST schedule.
1803 * We compute the inverse and strip off the type, resulting in
1805 * L -> [D -> A]
1807 * We combine this mapping with on the one hand the projection
1809 * [D -> A] -> A
1811 * and on the other hand the group tiling
1813 * [D -> A] -> T
1815 * resulting in
1817 * L -> A and L -> T
1819 * and store the corresponding expressions in stmt->index and stmt->local_index,
1820 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1822 static __isl_give isl_ast_node *create_access_leaf(struct ppcg_kernel *kernel,
1823 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1824 __isl_keep isl_ast_build *build)
1826 struct ppcg_kernel_stmt *stmt;
1827 struct gpu_array_tile *tile;
1828 isl_id *id;
1829 isl_ast_expr *expr;
1830 isl_space *space;
1831 isl_map *access;
1832 isl_pw_multi_aff *pma, *pma2;
1833 const char *type;
1835 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1836 if (!stmt)
1837 return isl_ast_node_free(node);
1839 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1840 type = isl_map_get_tuple_name(access, isl_dim_in);
1841 stmt->u.c.read = !strcmp(type, "read");
1842 access = isl_map_reverse(access);
1843 pma = isl_pw_multi_aff_from_map(access);
1844 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1846 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1847 space = isl_space_unwrap(space);
1848 pma2 = isl_pw_multi_aff_range_map(space);
1849 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1850 isl_pw_multi_aff_copy(pma));
1851 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1852 stmt->u.c.index = expr;
1854 tile = gpu_array_ref_group_tile(group);
1855 pma2 = isl_pw_multi_aff_from_multi_aff(
1856 isl_multi_aff_copy(tile->tiling));
1857 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1858 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1859 stmt->u.c.local_index = expr;
1861 stmt->u.c.array = group->array;
1862 stmt->u.c.local_array = group->local_array;
1863 stmt->type = ppcg_kernel_copy;
1865 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1866 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1867 return isl_ast_node_set_annotation(node, id);
1870 /* Create a synchronization ppcg_kernel_stmt and
1871 * attach it to the node "node" representing the synchronization.
1873 static __isl_give isl_ast_node *create_sync_leaf(
1874 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1875 __isl_keep isl_ast_build *build)
1877 struct ppcg_kernel_stmt *stmt;
1878 isl_id *id;
1880 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1881 if (!stmt)
1882 return isl_ast_node_free(node);
1884 stmt->type = ppcg_kernel_sync;
1885 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1886 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1887 return isl_ast_node_set_annotation(node, id);
1890 /* Internal data structure for at_domain.
1892 * "prog" represents the entire scop.
1893 * "kernel" points to the kernel to which the current schedule node
1894 * belongs. It is set by before_mark and reset by after_mark.
1895 * It may be NULL if we are outside any kernel.
1897 struct ppcg_at_domain_data {
1898 struct gpu_prog *prog;
1899 struct ppcg_kernel *kernel;
1902 /* This function is called for each instance of a user statement
1903 * in the kernel. This may be one of the original user statements
1904 * or a statement introduced by PPCG.
1906 * We assume that the original user statements only have a name
1907 * and no user pointer. The statements introduced by PPCG
1908 * on the other hand all have a user pointer.
1910 * If the user statement is one of the original user statements
1911 * (one with no user pointer), then we call create_domain_leaf. Otherwise,
1912 * we check if it is a copy or synchronization statement and
1913 * call the appropriate functions.
1914 * Statements that copy an array to/from the device do not need
1915 * any further treatment.
1917 static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
1918 __isl_keep isl_ast_build *build, void *user)
1920 struct ppcg_at_domain_data *data = user;
1921 isl_ast_expr *expr, *arg;
1922 isl_id *id;
1923 int is_sync;
1924 const char *name;
1925 void *p;
1927 expr = isl_ast_node_user_get_expr(node);
1928 arg = isl_ast_expr_get_op_arg(expr, 0);
1929 id = isl_ast_expr_get_id(arg);
1930 name = isl_id_get_name(id);
1931 p = isl_id_get_user(id);
1932 isl_ast_expr_free(expr);
1933 isl_ast_expr_free(arg);
1935 if (!p) {
1936 struct gpu_stmt *gpu_stmt;
1938 gpu_stmt = find_stmt(data->prog, id);
1939 isl_id_free(id);
1940 if (!gpu_stmt)
1941 isl_die(data->prog->ctx, isl_error_internal,
1942 "statement not found",
1943 return isl_ast_node_free(node));
1945 return create_domain_leaf(data->kernel, node, build, gpu_stmt);
1948 is_sync = gpu_tree_id_is_sync(id, data->kernel);
1949 isl_id_free(id);
1950 if (!prefixcmp(name, "to_device_") || !prefixcmp(name, "from_device_"))
1951 return node;
1952 if (is_sync < 0)
1953 return isl_ast_node_free(node);
1954 if (!strcmp(name, "read") || !strcmp(name, "write")) {
1955 struct gpu_array_ref_group *group = p;
1956 return create_access_leaf(data->kernel, group, node, build);
1958 if (!is_sync)
1959 isl_die(data->prog->ctx, isl_error_internal,
1960 "unknown statement type",
1961 return isl_ast_node_free(node));
1962 return create_sync_leaf(data->kernel, node, build);
1965 /* Given a set of wrapped references "ref", return the corresponding
1966 * access relations based on the tagged access relations "tagged".
1968 * The elements of "ref" are of the form
1970 * [D -> R]
1972 * with D an iteration domains and R a reference.
1973 * The elements of "tagged" are of the form
1975 * [D -> R] -> A
1977 * with A an array.
1979 * Extend "tagged" to include the iteration domain in the range, i.e.,
1981 * [D -> R] -> [D -> A]
1983 * apply the result to "ref" and then unwrap the resulting set
1984 * to obtain relations of the form
1986 * D -> A
1988 static __isl_give isl_union_map *wrapped_reference_to_access(
1989 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
1991 isl_union_map *tag2access;
1993 tag2access = isl_union_map_copy(tagged);
1994 tag2access = isl_union_map_universe(tag2access);
1995 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
1996 tag2access = isl_union_map_domain_map(tag2access);
1997 tag2access = isl_union_map_range_product(tag2access, tagged);
1999 ref = isl_union_set_coalesce(ref);
2000 ref = isl_union_set_apply(ref, tag2access);
2002 return isl_union_set_unwrap(ref);
2005 /* Given an access relation "access" from one or more array reference groups,
2006 * remove those reads if ("read" is 1) or writes (if "read" is 0)
2007 * that are only needed to communicate data within
2008 * the same iteration of "sched".
2009 * "tagged" contains all tagged access relations to all
2010 * the array reference groups accessed by "access" from statement
2011 * instances scheduled by "sched".
2013 * If the access is a read then it is either an element of
2015 * live_in union (range flow)
2017 * where live_in and flow may be overapproximations, or
2018 * it reads an uninitialized value (that is not live-in because
2019 * there is an intermediate kill) or it reads a value that was
2020 * written within the same (compound) statement instance.
2021 * If the access is a write then it is either an element of
2023 * live_out union (domain flow)
2025 * or it writes a value that is never read (and is not live-out
2026 * because of an intermediate kill) or only
2027 * within the same (compound) statement instance.
2028 * In both cases, the access relation is also a subset of
2029 * the group access relation.
2031 * The cases where an uninitialized value is read or a value is written
2032 * that is never read or where the dataflow occurs within a statement
2033 * instance are also considered local and may also be removed.
2035 * Essentially, we compute the intersection of "access" with either
2037 * live_in union (range non-local-flow)
2039 * or
2041 * live_out union (domain non-local-flow)
2043 * We first construct a relation "local"
2045 * [[D -> R] -> [D' -> R']]
2047 * of pairs of domain iterations accessing the reference group
2048 * and references in the group that are coscheduled by "sched".
2050 * If this relation does not intersect the dataflow dependences,
2051 * then there is nothing we can possibly remove, unless the dataflow
2052 * dependences themselves only relate a subset of the accesses.
2053 * In particular, the accesses may not be involved in any dataflow
2054 * dependences, either because they are uninitialized reads/dead writes
2055 * or because the dataflow occurs inside a statement instance.
2057 * Since the computation below may break up the access relation
2058 * into smaller pieces, we only perform the intersection with
2059 * the non-local dependent accesses if the local pairs
2060 * intersect the dataflow dependences. Otherwise, we intersect
2061 * with the universe of the non-local dependent accesses.
2062 * This should at least remove accesses from statements that
2063 * do not participate in any dependences.
2065 * In particular, we remove the "local" dataflow dependences from
2066 * the set of all dataflow dependences.
2067 * Note that if the potential dataflow dependences are an overapproximation
2068 * of the actual dataflow dependences, then the result remains an
2069 * overapproximation of the non-local dataflow dependences.
2070 * Copying to/from global memory is only needed for the references
2071 * in the domain/range of the result or for accesses that are live out/in
2072 * for the entire scop.
2074 * We therefore map the domain/range of the "external" relation
2075 * to the corresponding access relation and take the union with
2076 * the live out/in relation.
2078 static __isl_give isl_union_map *remove_local_accesses(
2079 struct gpu_prog *prog, __isl_take isl_union_map *tagged,
2080 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2081 int read)
2083 int empty;
2084 isl_union_pw_multi_aff *tagger;
2085 isl_union_set *domain;
2086 isl_union_map *local, *external;
2087 isl_union_set *tag_set;
2089 if (isl_union_map_is_empty(access)) {
2090 isl_union_map_free(sched);
2091 isl_union_map_free(tagged);
2092 return access;
2095 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2096 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2097 tagger = isl_union_pw_multi_aff_intersect_domain(tagger, domain);
2098 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2100 local = isl_union_map_apply_range(sched,
2101 isl_union_map_reverse(isl_union_map_copy(sched)));
2102 local = isl_union_map_intersect(local,
2103 isl_union_map_copy(prog->scop->tagged_dep_flow));
2105 empty = isl_union_map_is_empty(local);
2107 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2108 external = isl_union_map_intersect_params(external,
2109 isl_set_copy(prog->scop->context));
2110 external = isl_union_map_subtract(external, local);
2112 if (read) {
2113 tag_set = isl_union_map_range(external);
2114 external = wrapped_reference_to_access(tag_set, tagged);
2115 external = isl_union_map_union(external,
2116 isl_union_map_copy(prog->scop->live_in));
2117 } else {
2118 tag_set = isl_union_map_domain(external);
2119 external = wrapped_reference_to_access(tag_set, tagged);
2120 external = isl_union_map_union(external,
2121 isl_union_map_copy(prog->scop->live_out));
2124 if (empty < 0)
2125 external = isl_union_map_free(external);
2126 else if (empty)
2127 external = isl_union_map_universe(external);
2129 access = isl_union_map_intersect(access, external);
2131 return access;
2134 /* Given an access relation "access" from "group", remove those reads
2135 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2136 * communicate data within the same iteration of the schedule at the
2137 * position where the copying of the group is inserted.
2138 * "node" points to this position, i.e., the depth at "node"
2139 * is equal to group->depth.
2141 * We extract a schedule that picks out the iterations of the outer
2142 * group->depth dimensions and call remove_local_accesses.
2144 static __isl_give isl_union_map *remove_local_accesses_group(
2145 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2146 __isl_take isl_union_map *access, __isl_keep isl_schedule_node *node,
2147 int read)
2149 isl_union_map *sched, *tagged;
2151 if (isl_union_map_is_empty(access))
2152 return access;
2154 tagged = group_tagged_access_relation(group);
2155 sched = isl_schedule_node_get_prefix_schedule_relation(node);
2157 return remove_local_accesses(kernel->prog, tagged, access, sched, read);
2160 /* This function is called before the AST generator starts traversing
2161 * the schedule subtree of a node with mark "mark".
2163 * If the mark is called "kernel", store the kernel pointer in data->kernel
2164 * for use in at_domain.
2166 static int before_mark(__isl_keep isl_id *mark,
2167 __isl_keep isl_ast_build *build, void *user)
2169 struct ppcg_at_domain_data *data = user;
2171 if (!mark)
2172 return -1;
2173 if (!strcmp(isl_id_get_name(mark), "kernel"))
2174 data->kernel = isl_id_get_user(mark);
2175 return 0;
2178 /* This function is called after the AST generator has finished traversing
2179 * the schedule subtree of a mark node. "node" points to the corresponding
2180 * mark AST node.
2182 * If the mark is called "kernel", then replace "node" by a user node
2183 * that "calls" the kernel, representing the launch of the kernel.
2184 * The original "node" is stored inside the kernel object so that
2185 * it can be used to print the device code.
2186 * Note that this assumes that a kernel is only launched once.
2187 * Also clear data->kernel.
2189 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2190 __isl_keep isl_ast_build *build, void *user)
2192 isl_ctx *ctx;
2193 isl_id *id;
2194 isl_ast_expr *expr;
2195 isl_ast_expr_list *list;
2196 struct ppcg_kernel *kernel;
2197 struct ppcg_at_domain_data *data = user;
2199 ctx = isl_ast_node_get_ctx(node);
2200 id = isl_ast_node_mark_get_id(node);
2201 if (!id)
2202 return isl_ast_node_free(node);
2203 if (strcmp(isl_id_get_name(id), "kernel") || !data->kernel) {
2204 isl_id_free(id);
2205 return node;
2207 kernel = data->kernel;
2208 data->kernel = NULL;
2209 kernel->space = isl_ast_build_get_schedule_space(build);
2210 kernel->tree = isl_ast_node_mark_get_node(node);
2211 isl_ast_node_free(node);
2213 expr = isl_ast_expr_from_id(isl_id_copy(id));
2214 list = isl_ast_expr_list_alloc(ctx, 0);
2215 expr = isl_ast_expr_call(expr, list);
2216 node = isl_ast_node_alloc_user(expr);
2217 node = isl_ast_node_set_annotation(node, id);
2219 return node;
2222 static int update_depth(__isl_keep isl_schedule_node *node, void *user)
2224 int *depth = user;
2225 int node_depth;
2227 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2228 return 1;
2229 node_depth = isl_schedule_node_get_schedule_depth(node);
2230 if (node_depth > *depth)
2231 *depth = node_depth;
2233 return 0;
2236 /* Use isl to generate code for both the host and the device
2237 * from "schedule".
2238 * The device code is marked by "kernel" mark nodes in the schedule tree,
2239 * containing a pointer to a ppcg_kernel object.
2240 * The returned AST only contains the AST for the host code.
2241 * The ASTs for the device code are embedded in ppcg_kernel objects
2242 * attached to the leaf nodes that call "kernel".
2244 static __isl_give isl_ast_node *generate_code(struct gpu_gen *gen,
2245 __isl_take isl_schedule *schedule)
2247 struct ppcg_at_domain_data data;
2248 isl_ast_build *build;
2249 isl_ast_node *tree;
2250 isl_id_list *iterators;
2251 int depth;
2253 data.prog = gen->prog;
2254 data.kernel = NULL;
2256 depth = 0;
2257 if (isl_schedule_foreach_schedule_node(schedule, &update_depth,
2258 &depth) < 0)
2259 return NULL;
2260 build = isl_ast_build_alloc(gen->prog->ctx);
2261 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2262 build = isl_ast_build_set_iterators(build, iterators);
2263 build = isl_ast_build_set_at_each_domain(build, &at_domain, &data);
2264 build = isl_ast_build_set_before_each_mark(build, &before_mark, &data);
2265 build = isl_ast_build_set_after_each_mark(build, &after_mark, &data);
2266 if (gen->prog->scop->options->debug->dump_final_schedule)
2267 isl_schedule_dump(schedule);
2268 tree = isl_ast_build_node_from_schedule(build, schedule);
2269 isl_ast_build_free(build);
2271 return tree;
2274 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2276 if (!str)
2277 return NULL;
2278 return isl_union_map_read_from_str(ctx, str);
2281 /* Can "node" be tiled and then mapped to block and thread identifiers?
2282 * That is, is it permutable with at least one coincident dimension?
2284 static int is_permutable(__isl_keep isl_schedule_node *node)
2286 if (!node)
2287 return -1;
2289 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
2290 return 0;
2291 if (!isl_schedule_node_band_get_permutable(node))
2292 return 0;
2293 if (isl_schedule_node_band_n_member(node) < 1)
2294 return 0;
2295 if (!isl_schedule_node_band_member_get_coincident(node, 0))
2296 return 0;
2298 return 1;
2301 /* A isl_schedule_foreach_schedule_node callback
2302 * for setting *any_permutable and aborting the search
2303 * if "node" is a permutable band with coincident dimensions.
2304 * Otherwise, continue searching.
2306 static int set_permutable(__isl_keep isl_schedule_node *node, void *user)
2308 int *any_permutable = user;
2309 int permutable;
2311 permutable = is_permutable(node);
2312 if (permutable < 0)
2313 return -1;
2314 if (!permutable)
2315 return 1;
2317 *any_permutable = 1;
2319 return -1;
2322 /* Does "schedule" contain any permutable band with at least one coincident
2323 * member?
2325 static int has_any_permutable_node(__isl_keep isl_schedule *schedule)
2327 int any_permutable = 0;
2329 if (isl_schedule_foreach_schedule_node(schedule, &set_permutable,
2330 &any_permutable) < 0 &&
2331 !any_permutable)
2332 return -1;
2334 return any_permutable;
2337 /* Is "node" a leaf or can it be tiled and then mapped to
2338 * block and thread identifiers?
2340 static int is_leaf_or_tilable(__isl_keep isl_schedule_node *node)
2342 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
2343 return 1;
2344 return is_permutable(node);
2347 /* Is "node" the outermost node in its branch that can be tiled
2348 * and then mapped to block and thread identifiers?
2349 * If there are no such nodes in the branch and if "node" is a leaf,
2350 * then it is accepted too.
2352 static int is_outer_tilable(__isl_keep isl_schedule_node *node)
2354 int tilable;
2355 isl_schedule_node *ancestor;
2357 tilable = is_leaf_or_tilable(node);
2358 if (tilable < 0)
2359 return -1;
2360 if (!tilable)
2361 return 0;
2363 tilable = 0;
2364 ancestor = isl_schedule_node_copy(node);
2365 while (isl_schedule_node_has_parent(ancestor)) {
2366 ancestor = isl_schedule_node_parent(ancestor);
2368 tilable = is_permutable(ancestor);
2369 if (tilable < 0 || tilable)
2370 break;
2373 isl_schedule_node_free(ancestor);
2374 return tilable < 0 ? -1 : !tilable;
2377 /* Collect the references to all writes in "group".
2378 * Each reference is represented by a universe set in a space
2380 * [S[i,j] -> R[]]
2382 * with S[i,j] the statement instance space and R[] the array reference.
2384 static __isl_give isl_union_set *group_tagged_writes(
2385 struct gpu_array_ref_group *group)
2387 int i;
2388 isl_space *space;
2389 isl_union_set *writes;
2391 space = isl_map_get_space(group->access);
2392 writes = isl_union_set_empty(space);
2393 for (i = 0; i < group->n_ref; ++i) {
2394 isl_space *space;
2395 isl_set *writes_i;
2397 if (!group->refs[i]->write)
2398 continue;
2400 space = isl_map_get_space(group->refs[i]->tagged_access);
2401 space = isl_space_domain(space);
2402 writes_i = isl_set_universe(space);
2403 writes = isl_union_set_add_set(writes, writes_i);
2406 return writes;
2409 /* Is there any write access in "group" that requires synchronization
2410 * on a write to global memory?
2411 * We currently take into account all writes that would require
2412 * synchronization at the thread level depth, but if the copying
2413 * for this group is performed at an outer level, then we do not
2414 * actually need to take into account dependences at intermediate levels.
2416 static int any_sync_writes_in_group(struct ppcg_kernel *kernel,
2417 struct gpu_array_ref_group *group)
2419 isl_union_set *writes;
2420 int empty, disjoint;
2422 empty = isl_union_set_is_empty(kernel->sync_writes);
2423 if (empty < 0)
2424 return -1;
2425 if (empty)
2426 return 0;
2428 writes = group_tagged_writes(group);
2429 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2430 isl_union_set_free(writes);
2432 return disjoint < 0 ? -1 : !disjoint;
2435 /* Collect the references to all writes in "kernel" that write directly
2436 * to global or shared memory, i.e., that are not mapped to private memory.
2437 * Each reference is represented by a universe set in a space
2439 * [S[i,j] -> R[]]
2441 * with S[i,j] the statement instance space and R[] the array reference.
2443 static __isl_give isl_union_set *collect_non_private_tagged_writes(
2444 struct ppcg_kernel *kernel)
2446 isl_union_set *writes;
2447 int i, j;
2449 writes = isl_union_set_empty(isl_union_set_get_space(kernel->arrays));
2451 for (i = 0; i < kernel->n_array; ++i) {
2452 struct gpu_local_array_info *array = &kernel->array[i];
2454 for (j = 0; j < array->n_group; ++j) {
2455 struct gpu_array_ref_group *group = array->groups[j];
2456 isl_union_set *writes_ij;
2458 if (!group->write)
2459 continue;
2460 if (group->private_tile)
2461 continue;
2462 writes_ij = group_tagged_writes(group);
2463 writes = isl_union_set_union(writes, writes_ij);
2467 return writes;
2470 /* Are there any direct writes to global memory that require
2471 * synchronization?
2473 static int any_global_or_shared_sync_writes(struct ppcg_kernel *kernel)
2475 isl_union_set *writes;
2476 int empty, disjoint;
2478 empty = isl_union_set_is_empty(kernel->sync_writes);
2479 if (empty < 0)
2480 return -1;
2481 if (empty)
2482 return 0;
2484 writes = collect_non_private_tagged_writes(kernel);
2485 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2486 isl_union_set_free(writes);
2488 return disjoint < 0 ? -1 : !disjoint;
2491 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
2492 * from the elements in "tile_size".
2494 static __isl_give isl_multi_val *construct_band_tiles_sizes(
2495 __isl_keep isl_schedule_node *node, int *tile_size)
2497 int i, n;
2498 isl_ctx *ctx;
2499 isl_space *space;
2500 isl_multi_val *mv;
2502 if (!node)
2503 return NULL;
2505 ctx = isl_schedule_node_get_ctx(node);
2506 space = isl_schedule_node_band_get_space(node);
2507 n = isl_schedule_node_band_n_member(node);
2508 mv = isl_multi_val_zero(space);
2509 for (i = 0; i < n; ++i) {
2510 isl_val *v;
2512 v = isl_val_int_from_si(ctx, tile_size[i]);
2513 mv = isl_multi_val_set_val(mv, i, v);
2516 return mv;
2519 /* Replace the partial schedule S of the band node "node" by
2521 * floor(S/f)
2523 * or
2525 * f * floor(S/f)
2527 * if scale_tile_loops is set, with f the integers in "factor".
2528 * The list that "factor" points to is assumed to contain at least
2529 * as many elements as the number of members in the band.
2531 static __isl_give isl_schedule_node *snap_band_to_sizes(
2532 __isl_take isl_schedule_node *node, int *factor,
2533 struct ppcg_options *options)
2535 isl_multi_val *mv;
2537 mv = construct_band_tiles_sizes(node, factor);
2538 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2539 if (options->scale_tile_loops)
2540 node = isl_schedule_node_band_scale(node,
2541 isl_multi_val_copy(mv));
2542 isl_multi_val_free(mv);
2544 return node;
2547 /* Tile "band" with tile size specified by "sizes".
2549 * Since the tile loops will be mapped to block ids, we forcibly
2550 * turn off tile loop scaling. We may want to enable tile loop scaling
2551 * at some later point, but then we would have to support the detection
2552 * of strides during the mapping to block ids.
2553 * Similarly, since the point loops will be mapped to thread ids,
2554 * we forcibly shift the point loops so that they start at zero.
2556 static __isl_give isl_schedule_node *tile_band(
2557 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2559 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2560 int scale_tile;
2561 int shift_point;
2563 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2564 isl_options_set_tile_scale_tile_loops(ctx, 0);
2565 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2566 isl_options_set_tile_shift_point_loops(ctx, 1);
2568 node = isl_schedule_node_band_tile(node, sizes);
2570 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2571 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2573 return node;
2576 /* Extract the set of parameter values and outer schedule dimensions
2577 * for which any statement instance
2578 * in the kernel inserted at "node" needs to be executed.
2579 * Intersect the set of parameter values derived from the host schedule
2580 * relation with the context of "prog".
2582 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2583 struct gpu_prog *prog)
2585 isl_union_map *schedule;
2586 isl_union_set *schedule_domain;
2587 isl_set *context;
2588 int empty;
2590 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2591 schedule_domain = isl_union_map_range(schedule);
2592 empty = isl_union_set_is_empty(schedule_domain);
2593 if (empty < 0) {
2594 isl_union_set_free(schedule_domain);
2595 return NULL;
2597 if (empty) {
2598 int depth;
2599 isl_space *space;
2601 space = isl_union_set_get_space(schedule_domain);
2602 isl_union_set_free(schedule_domain);
2603 space = isl_space_set_from_params(space);
2604 depth = isl_schedule_node_get_schedule_depth(node);
2605 space = isl_space_add_dims(space, isl_dim_set, depth);
2606 context = isl_set_empty(space);
2607 } else {
2608 context = isl_set_from_union_set(schedule_domain);
2610 context = isl_set_intersect_params(context,
2611 isl_set_copy(prog->context));
2613 return context;
2616 /* Return the set of outer array elements accessed by
2617 * by the statement instance in "domain" in "prog".
2619 static __isl_give isl_union_set *accessed_by_domain(
2620 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2622 isl_union_map *access;
2623 isl_union_set *arrays;
2625 access = isl_union_map_union(isl_union_map_copy(prog->read),
2626 isl_union_map_copy(prog->may_write));
2627 access = isl_union_map_intersect_domain(access, domain);
2628 arrays = isl_union_map_range(access);
2629 arrays = isl_union_set_apply(arrays,
2630 isl_union_map_copy(prog->to_outer));
2632 return arrays;
2635 /* Return the number of outer band members of the band node "node"
2636 * that are marked coincident.
2638 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2640 int i, n;
2642 n = isl_schedule_node_band_n_member(node);
2644 for (i = 0; i < n; ++i)
2645 if (!isl_schedule_node_band_member_get_coincident(node, i))
2646 break;
2648 return i;
2651 /* If the band node "node" has more than "n" members, then split off
2652 * the first "n" of them.
2654 static __isl_give isl_schedule_node *split_band(
2655 __isl_take isl_schedule_node *node, int n)
2657 int dim;
2659 dim = isl_schedule_node_band_n_member(node);
2660 if (n < dim)
2661 node = isl_schedule_node_band_split(node, n);
2663 return node;
2666 /* Scale a band node that may have been split by split_band.
2667 * "sizes" are the scaling factors for the original node.
2668 * "node" either points to the original band node, or the outer
2669 * of the two pieces after splitting.
2671 * If the number of elements in "node" is smaller than the number of
2672 * elements in "sizes", then some splitting has occurred and we split
2673 * "sizes" in the same way.
2675 static __isl_give isl_schedule_node *scale_band(
2676 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2678 int n, dim;
2680 n = isl_multi_val_dim(sizes, isl_dim_set);
2681 dim = isl_schedule_node_band_n_member(node);
2682 if (n > dim) {
2683 isl_multi_val *sizes2;
2685 sizes2 = isl_multi_val_copy(sizes);
2686 sizes = isl_multi_val_drop_dims(sizes,
2687 isl_dim_set, dim, n - dim);
2688 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2689 node = isl_schedule_node_child(node, 0);
2690 node = isl_schedule_node_band_scale(node, sizes2);
2691 node = isl_schedule_node_parent(node);
2694 return isl_schedule_node_band_scale(node, sizes);
2697 /* Return an isl_multi_aff, with as elements the parameters in "space"
2698 * that have the names specified by the elements in "names".
2699 * If (some of) these parameters do not already appear in "space",
2700 * then they are added first.
2702 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2703 __isl_keep isl_id_list *names)
2705 int i, n;
2706 isl_local_space *ls;
2707 isl_multi_aff *ma;
2709 if (!names)
2710 space = isl_space_free(space);
2712 n = isl_id_list_n_id(names);
2713 for (i = 0; i < n; ++i) {
2714 int pos;
2715 isl_id *id;
2717 id = isl_id_list_get_id(names, i);
2718 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2719 if (pos >= 0) {
2720 isl_id_free(id);
2721 continue;
2723 pos = isl_space_dim(space, isl_dim_param);
2724 space = isl_space_add_dims(space, isl_dim_param, 1);
2725 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2727 ma = isl_multi_aff_zero(isl_space_copy(space));
2728 ls = isl_local_space_from_space(isl_space_domain(space));
2729 for (i = 0; i < n; ++i) {
2730 int pos;
2731 isl_id *id;
2732 isl_aff *aff;
2734 id = isl_id_list_get_id(names, i);
2735 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2736 isl_id_free(id);
2737 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2738 isl_dim_param, pos);
2739 ma = isl_multi_aff_set_aff(ma, i, aff);
2741 isl_local_space_free(ls);
2743 return ma;
2746 /* Return constraints on the domain elements that equate a sequence of
2747 * parameters called "names", to the partial schedule
2748 * of "node" modulo the integers in "size".
2749 * The number of elements in the array "size" should be equal
2750 * to the number of elements in "names".
2751 * The number of members of the band node "node" should be smaller
2752 * than or equal to this number. If it is smaller, then the first
2753 * elements of "names" are equated to zero.
2755 static __isl_give isl_union_set *set_schedule_modulo(
2756 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
2757 int *size)
2759 int n, n_zero;
2760 isl_space *space;
2761 isl_multi_aff *ma;
2762 isl_multi_union_pw_aff *mupa, *mupa2;
2763 isl_multi_val *mv;
2764 isl_union_set *domain;
2766 if (!node)
2767 return NULL;
2768 n = isl_id_list_n_id(names);
2769 if (n == 0)
2770 return isl_schedule_node_get_universe_domain(node);
2771 n_zero = n - isl_schedule_node_band_n_member(node);
2773 mupa = isl_schedule_node_band_get_partial_schedule(node);
2774 mv = construct_band_tiles_sizes(node, size + n_zero);
2775 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
2777 space = isl_multi_union_pw_aff_get_space(mupa);
2778 space = isl_space_params(space);
2779 space = isl_space_set_from_params(space);
2780 space = isl_space_add_dims(space, isl_dim_set, n_zero);
2781 ma = isl_multi_aff_zero(space);
2783 domain = isl_schedule_node_get_universe_domain(node);
2784 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
2785 isl_union_set_copy(domain), ma);
2786 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
2788 space = isl_multi_union_pw_aff_get_space(mupa);
2789 ma = parameter_vector(space, names);
2791 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
2792 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
2794 return isl_multi_union_pw_aff_zero_union_set(mupa);
2797 /* Insert a context node at "node" introducing the block and thread
2798 * identifiers along with their bounds, which are stored in kernel->grid_size
2799 * and kernel->block_dim.
2800 * Note that the bounds on the block identifiers may implicitly impose
2801 * constraints on the parameters. A guard needs to be inserted
2802 * in the schedule tree to ensure that those bounds hold at "node".
2803 * This guard is inserted in insert_guard.
2805 static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
2806 __isl_take isl_schedule_node *node)
2808 isl_set *context;
2810 context = isl_set_universe(isl_set_get_space(kernel->context));
2812 context = add_bounded_parameters_dynamic(context,
2813 kernel->grid_size, kernel->block_ids);
2814 context = add_bounded_parameters(context,
2815 kernel->block_dim, kernel->thread_ids);
2817 node = isl_schedule_node_insert_context(node, context);
2819 return node;
2822 /* Insert a guard that eliminates kernel launches where the kernel
2823 * obviously does not have any work to do.
2825 * In particular, eliminate kernel launches where there are obviously
2826 * zero blocks.
2827 * Use the same block size constraints that are used to create the context
2828 * to ensure that all constraints implicit in the constructed context
2829 * are imposed by the guard.
2831 * Additionally, add other constraints that are valid
2832 * for each executed instance ("context"), as long as this does not result
2833 * in a disjunction.
2835 static __isl_give isl_schedule_node *insert_guard(
2836 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
2837 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
2839 unsigned nparam, n;
2840 isl_set *guard;
2841 isl_id_list *ids;
2843 guard = isl_set_copy(context);
2844 guard = isl_set_compute_divs(guard);
2845 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
2847 nparam = isl_set_dim(guard, isl_dim_param);
2848 n = isl_multi_pw_aff_dim(size, isl_dim_out);
2849 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
2850 guard = add_bounded_parameters_dynamic(guard, size, ids);
2851 isl_id_list_free(ids);
2852 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
2854 node = isl_schedule_node_insert_guard(node, guard);
2856 return node;
2859 /* Does any array reference group mapping require the band that is mapped
2860 * to threads to be unrolled?
2862 static int kernel_requires_unroll(struct ppcg_kernel *kernel)
2864 int i, j;
2866 for (i = 0; i < kernel->n_array; ++i) {
2867 struct gpu_local_array_info *array = &kernel->array[i];
2869 for (j = 0; j < array->n_group; ++j) {
2870 struct gpu_array_ref_group *group = array->groups[j];
2871 if (gpu_array_ref_group_requires_unroll(group))
2872 return 1;
2876 return 0;
2879 /* Mark the given band node "node" for unrolling by the AST generator and
2880 * then sink it to the leaves of the schedule tree.
2881 * All dimensions of "node" are assumed to be coincident, such that this
2882 * sinking is a valid operation.
2884 static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
2886 int i, n;
2888 n = isl_schedule_node_band_n_member(node);
2889 for (i = 0; i < n; ++i)
2890 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
2891 isl_ast_loop_unroll);
2893 node = isl_schedule_node_band_sink(node);
2895 return node;
2898 /* Insert a synchronization node in the schedule tree of "node"
2899 * after the core computation of "kernel" at the level of the band
2900 * that is mapped to threads, except if that level is equal to
2901 * that of the band that is mapped to blocks or if there are no writes
2902 * to global or shared memory in the core computation that require
2903 * synchronization.
2904 * If there are any writes to shared memory and the shared memory
2905 * copying is performed at the same level, then synchronization
2906 * is needed between the core and the copying anyway, so we might
2907 * as well add it here. If the copying is performed at a higher
2908 * level, then different iterations of intermediate schedule dimensions
2909 * may have a different mapping from between shared memory elements and
2910 * threads, such that synchronization is required after the core.
2911 * "node" is assumed to point to the kernel node.
2913 static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
2914 __isl_take isl_schedule_node *node)
2916 int kernel_depth;
2917 int need_sync;
2919 need_sync = any_global_or_shared_sync_writes(kernel);
2920 if (need_sync < 0)
2921 return isl_schedule_node_free(node);
2922 if (!need_sync)
2923 return node;
2925 kernel_depth = isl_schedule_node_get_schedule_depth(node);
2927 node = gpu_tree_move_down_to_thread(node, kernel->core);
2928 if (kernel_depth == isl_schedule_node_get_schedule_depth(node))
2929 return gpu_tree_move_up_to_kernel(node);
2931 node = gpu_tree_ensure_following_sync(node, kernel);
2933 node = gpu_tree_move_up_to_kernel(node);
2935 return node;
2938 /* Return a read ("read" is 1) or write access relation for "group"
2939 * with those accesses removed that are only needed to communicate data
2940 * within the subtree of the schedule rooted at "node".
2941 * Furthermore, include the prefix schedule at "node".
2942 * That is, return a relation of the form
2944 * S -> [D -> A]
2946 * with D the outer schedule dimensions at "node".
2948 static __isl_give isl_union_map *anchored_non_local_accesses(
2949 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2950 __isl_take isl_schedule_node *node, int read)
2952 isl_union_map *access;
2953 isl_union_map *prefix;
2955 access = gpu_array_ref_group_access_relation(group, read, !read);
2956 access = remove_local_accesses_group(kernel, group, access, node, read);
2957 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
2958 access = isl_union_map_range_product(prefix, access);
2960 return access;
2963 /* Given an array reference group "group", create a mapping
2965 * read[D -> A] -> [D -> A]
2967 * if "read" is set or
2969 * write[D -> A] -> [D -> A]
2971 * if "read" is not set.
2972 * D corresponds to the outer group->depth dimensions of
2973 * the kernel schedule.
2975 static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
2976 struct gpu_array_ref_group *group, int read)
2978 isl_space *space;
2979 isl_id *id;
2981 space = isl_space_copy(group->array->space);
2982 space = isl_space_from_range(space);
2983 space = isl_space_add_dims(space, isl_dim_in, group->depth);
2984 space = isl_space_wrap(space);
2985 space = isl_space_map_from_set(space);
2987 id = isl_id_alloc(ctx, read ? "read" : "write", group);
2988 space = isl_space_set_tuple_id(space, isl_dim_in, id);
2990 return isl_multi_aff_identity(space);
2993 /* If any writes in "group" require synchronization, then make sure
2994 * that there is a synchronization node for "kernel" after the node
2995 * following "node" in a sequence.
2997 * If "shared" is set and no synchronization is needed for
2998 * the writes to global memory, then add synchronization before
2999 * the kernel to protect shared memory from being overwritten
3000 * by the next iteration of the core computation.
3001 * No additional synchronization is needed to protect against
3002 * the next copy into shared memory because each element of
3003 * the shared memory tile is always copied by the same thread.
3005 static __isl_give isl_schedule_node *add_group_write_sync(
3006 __isl_take isl_schedule_node *node, struct ppcg_kernel *kernel,
3007 struct gpu_array_ref_group *group, int shared)
3009 int need_sync;
3011 need_sync = any_sync_writes_in_group(kernel, group);
3012 if (need_sync < 0)
3013 return isl_schedule_node_free(node);
3014 if (need_sync) {
3015 node = isl_schedule_node_parent(node);
3016 node = isl_schedule_node_next_sibling(node);
3017 node = isl_schedule_node_child(node, 0);
3018 node = gpu_tree_ensure_following_sync(node, kernel);
3019 } else if (shared) {
3020 node = isl_schedule_node_parent(node);
3021 node = isl_schedule_node_parent(node);
3022 node = gpu_tree_move_down_to_depth(node, group->depth,
3023 kernel->core);
3024 node = gpu_tree_move_left_to_sync(node, kernel);
3027 return node;
3030 /* Add copy statements to the schedule tree of "node"
3031 * for reading from global memory to private memory (if "read" is set) or
3032 * for writing back from private memory to global memory
3033 * (if "read" is not set) for the array reference group "group" that
3034 * is mapped to private memory.
3035 * On input, "node" points to the kernel node, and it is moved
3036 * back there on output.
3038 * The copies are performed in the order of the array elements.
3039 * The copy statement instances include a reference to the outer
3040 * group->depth dimensions of the kernel schedule for ease of
3041 * combining them with the group tiling.
3043 * That is, the extra schedule is of the form
3045 * type[D -> A] -> A
3047 * where D corresponds to the outer group->depth dimensions of
3048 * the kernel schedule and A to the global array.
3049 * This schedule is unrolled because registers are not addressable.
3051 * The copying is inserted in the schedule tree through an extension
3052 * of the form
3054 * D -> type[D -> A]
3056 * where the extra domain elements type[D -> A] are those accessed
3057 * by the group.
3058 * A filter is inserted on type[D -> A] to ensure that the element
3059 * is read/written by the same thread that needs the element.
3060 * This filter is obtained by applying
3062 * S -> type[D -> A]
3064 * to the thread filter for the core statements.
3066 * The extension is inserted before the core computation in case of a read
3067 * and after the core computation in case of a write.
3068 * In the latter case, we also make sure that there is a synchronization
3069 * node after the write to global memory, unless this write is performed
3070 * at the outer level of the kernel.
3071 * In principle, this synchronization could be inserted higher
3072 * in the schedule tree depending on where the corresponding reads
3073 * from global memory are performed.
3075 static __isl_give isl_schedule_node *add_copies_group_private(
3076 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3077 __isl_take isl_schedule_node *node, int read)
3079 isl_union_map *access;
3080 isl_union_map *prefix;
3081 isl_union_set *domain;
3082 isl_space *space;
3083 isl_multi_aff *from_access;
3084 isl_multi_pw_aff *mpa;
3085 isl_multi_union_pw_aff *mupa;
3086 isl_schedule_node *graft;
3087 isl_union_set *filter;
3088 int kernel_depth;
3089 int empty;
3091 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3092 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3094 access = anchored_non_local_accesses(kernel, group, node, read);
3095 empty = isl_union_map_is_empty(access);
3096 if (empty < 0 || empty) {
3097 isl_union_map_free(access);
3098 if (empty < 0)
3099 return isl_schedule_node_free(node);
3100 return gpu_tree_move_up_to_kernel(node);
3103 from_access = create_from_access(kernel->ctx, group, read);
3104 space = isl_space_domain(isl_multi_aff_get_space(from_access));
3105 access = isl_union_map_preimage_range_multi_aff(access, from_access);
3107 filter = isl_union_set_copy(kernel->thread_filter);
3108 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
3109 filter = isl_union_set_detect_equalities(filter);
3110 filter = isl_union_set_coalesce(filter);
3112 domain = isl_union_map_range(access);
3113 access = isl_union_set_wrapped_domain_map(domain);
3114 access = isl_union_map_reverse(access);
3115 access = isl_union_map_coalesce(access);
3116 graft = isl_schedule_node_from_extension(access);
3118 space = isl_space_map_from_set(space);
3119 mpa = isl_multi_pw_aff_identity(space);
3120 mpa = isl_multi_pw_aff_range_factor_range(mpa);
3121 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3123 graft = isl_schedule_node_child(graft, 0);
3124 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3125 graft = unroll(graft);
3127 graft = isl_schedule_node_insert_filter(graft, filter);
3129 graft = isl_schedule_node_parent(graft);
3131 if (read)
3132 node = isl_schedule_node_graft_before(node, graft);
3133 else {
3134 node = isl_schedule_node_graft_after(node, graft);
3135 if (kernel_depth < group->depth)
3136 node = add_group_write_sync(node, kernel, group, 0);
3139 node = gpu_tree_move_up_to_kernel(node);
3141 return node;
3144 /* Add copy statements to the schedule tree of "node"
3145 * for reading from global memory to shared memory (if "read" is set) or
3146 * for writing back from shared memory to global memory
3147 * (if "read" is not set) for the array reference group "group" that
3148 * is mapped to shared memory.
3149 * On input, "node" points to the kernel node, and it is moved
3150 * back there on output.
3152 * The copies are performed in the order of the corresponding shared
3153 * memory tile.
3154 * The copy statement instances include a reference to the outer
3155 * group->depth dimensions of the kernel schedule for ease of
3156 * combining them with the group tiling.
3158 * If we are performing a read from global memory to shared memory and
3159 * if the array involved is not a scalar, then we copy
3160 * the entire tile to shared memory. This may result in some extra
3161 * elements getting copied, but it should lead to simpler code
3162 * (which means that fewer registers may be needed) and less divergence.
3164 * Otherwise, we only copy the elements that will be read or have been written
3165 * in the kernel.
3167 * That is, the extra schedule is of the form
3169 * type[D -> A] -> T
3171 * where D corresponds to the outer group->depth dimensions of
3172 * the kernel schedule, A to the global array and T is the corresponding
3173 * shared memory tile.
3175 * The copying is inserted in the schedule tree through an extension
3176 * of the form
3178 * D -> type[D -> A]
3180 * where the extra domain elements type[D -> A] are those accessed
3181 * by the group. In the case of read from a non-scalar, this set
3182 * is replaced by the entire shared memory tile.
3184 * A filter is inserted on type[D -> A] to map the copy instances
3185 * to the threads. In particular, the thread identifiers are
3186 * equated to the position inside the shared memory tile (T)
3187 * modulo the block size.
3188 * We try to align the innermost tile dimension with the innermost
3189 * thread identifier (x) as a heuristic to improve coalescing.
3190 * In particular, if the dimension of the tile is greater than
3191 * the dimension of the block, then the schedule mapping to the tile
3192 * is broken up into two pieces and the filter is applied to the inner part.
3193 * If, on the other hand, the dimension of the tile is smaller than
3194 * the dimension of the block, then the initial thread identifiers
3195 * are equated to zero and the remaining thread identifiers are
3196 * matched to the memory tile.
3198 * The extension is inserted before the core computation in case of a read
3199 * and after the core computation in case of a write.
3200 * In the case of a read, we first need to make sure there is some
3201 * synchronization before the core computation such that we can put the read
3202 * from global memory to shared memory before that synchronization.
3203 * This ensures that all threads have finished copying into shared memory
3204 * before the shared memory is used.
3205 * We also need to make sure that there is a synchronization node after
3206 * the core computation to ensure that the next load into shared memory
3207 * only happens after all data has been used. There is no need for
3208 * this synchronization if we are at the outer level since then there
3209 * won't be a next load.
3210 * In the case of a write, we need to make sure there is some synchronization
3211 * after the core computation such taht we can put the write from shared
3212 * memory to global memory after that synchronization.
3213 * Unless we are at the outer level, we also need a synchronization node
3214 * after the write to ensure the data is saved to global memory
3215 * before the next iteration write to the same shared memory.
3216 * It also makes sure the data has arrived in global memory before
3217 * it is read in a subsequent iteration.
3219 static __isl_give isl_schedule_node *add_copies_group_shared(
3220 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3221 __isl_take isl_schedule_node *node, int read)
3223 struct gpu_array_tile *tile;
3224 isl_union_map *access;
3225 isl_union_set *domain;
3226 isl_union_set *sync;
3227 isl_multi_aff *ma;
3228 isl_multi_aff *from_access;
3229 isl_multi_pw_aff *mpa;
3230 isl_multi_union_pw_aff *mupa;
3231 isl_schedule_node *graft;
3232 isl_union_set *filter;
3233 int skip;
3234 int kernel_depth;
3235 int empty;
3237 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3238 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3240 access = anchored_non_local_accesses(kernel, group, node, read);
3241 empty = isl_union_map_is_empty(access);
3242 if (empty < 0 || empty) {
3243 isl_union_map_free(access);
3244 if (empty < 0)
3245 return isl_schedule_node_free(node);
3246 return gpu_tree_move_up_to_kernel(node);
3249 from_access = create_from_access(kernel->ctx, group, read);
3251 tile = gpu_array_ref_group_tile(group);
3252 ma = isl_multi_aff_copy(tile->tiling);
3253 ma = isl_multi_aff_pullback_multi_aff(ma,
3254 isl_multi_aff_copy(from_access));
3255 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3256 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3258 domain = isl_union_map_range(access);
3260 if (read && !gpu_array_is_scalar(group->array)) {
3261 isl_map *map;
3262 isl_union_set_free(domain);
3263 map = group_tile(group);
3264 domain = isl_union_set_from_set(isl_map_wrap(map));
3267 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3268 access = isl_union_set_wrapped_domain_map(domain);
3269 access = isl_union_map_reverse(access);
3270 access = isl_union_map_coalesce(access);
3271 graft = isl_schedule_node_from_extension(access);
3273 graft = isl_schedule_node_child(graft, 0);
3275 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3277 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3278 graft = isl_schedule_node_band_split(graft,
3279 tile->n - kernel->n_block);
3280 graft = isl_schedule_node_child(graft, 0);
3282 if (tile->n < kernel->n_block)
3283 skip = kernel->n_block - tile->n;
3284 else
3285 skip = 0;
3286 filter = set_schedule_modulo(graft, kernel->thread_ids,
3287 kernel->block_dim);
3288 if (!kernel->options->wrap)
3289 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3290 kernel->options);
3291 if (tile->n > kernel->n_block && kernel->n_block > 0)
3292 graft = isl_schedule_node_parent(graft);
3293 graft = isl_schedule_node_insert_filter(graft, filter);
3295 while (graft && isl_schedule_node_has_parent(graft))
3296 graft = isl_schedule_node_parent(graft);
3298 if (read) {
3299 if (kernel_depth < group->depth)
3300 node = gpu_tree_ensure_sync_after_core(node, kernel);
3301 node = gpu_tree_move_left_to_sync(node, kernel);
3302 node = isl_schedule_node_graft_before(node, graft);
3303 } else {
3304 node = gpu_tree_move_right_to_sync(node, kernel);
3305 node = isl_schedule_node_graft_after(node, graft);
3306 if (kernel_depth < group->depth)
3307 node = add_group_write_sync(node, kernel, group, 1);
3310 node = gpu_tree_move_up_to_kernel(node);
3312 return node;
3315 /* Check whether the array reference group "group" is mapped to
3316 * private or shared memory and, if so,
3317 * add copy statements to the schedule tree of "node"
3318 * for reading from global memory to private or shared memory
3319 * (if "read" is set) or for writing back from private or shared memory
3320 * to global memory (if "read" is not set) for this group.
3321 * On input, "node" points to the kernel node, and it is moved
3322 * back there on output.
3324 static __isl_give isl_schedule_node *add_copies_group(
3325 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3326 __isl_take isl_schedule_node *node, int read)
3328 if (group->private_tile)
3329 return add_copies_group_private(kernel, group, node, read);
3330 if (group->shared_tile)
3331 return add_copies_group_shared(kernel, group, node, read);
3332 return node;
3335 /* For each array reference group that is mapped to private or shared memory,
3336 * add copy statements to the schedule tree of "node"
3337 * for reading from global memory to private or shared memory
3338 * and for writing back.
3339 * On input, "node" points to the kernel node, and it is moved
3340 * back there on output.
3342 static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3343 __isl_take isl_schedule_node *node)
3345 int i, j;
3347 for (i = 0; i < kernel->n_array; ++i) {
3348 struct gpu_local_array_info *array = &kernel->array[i];
3350 for (j = 0; j < array->n_group; ++j) {
3351 struct gpu_array_ref_group *group = array->groups[j];
3353 node = add_copies_group(kernel, group, node, 1);
3354 if (!node)
3355 return NULL;
3356 node = add_copies_group(kernel, group, node, 0);
3357 if (!node)
3358 return NULL;
3362 return node;
3365 /* Mark all dimensions in the current band node atomic.
3367 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3369 int i, n;
3371 n = isl_schedule_node_band_n_member(node);
3372 for (i = 0; i < n; ++i)
3373 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
3374 isl_ast_loop_atomic);
3376 return node;
3379 /* Mark "node" atomic, if it is a band node.
3380 * Do the same for all ancestors.
3381 * Return a pointer to "node" (in the updated schedule tree).
3383 static __isl_give isl_schedule_node *atomic_ancestors(
3384 __isl_take isl_schedule_node *node)
3386 int pos;
3388 if (!node)
3389 return NULL;
3390 if (!isl_schedule_node_has_parent(node))
3391 return node;
3393 pos = isl_schedule_node_get_child_position(node);
3394 node = isl_schedule_node_parent(node);
3395 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3396 node = atomic(node);
3397 node = atomic_ancestors(node);
3398 node = isl_schedule_node_child(node, pos);
3400 return node;
3403 /* Collect all write references that require synchronization.
3404 * "node" is assumed to point to the kernel node.
3405 * Each reference is represented by a universe set in a space
3407 * [S[i,j] -> R[]]
3409 * with S[i,j] the statement instance space and R[] the array reference.
3411 * This function should be called before block and thread filters are added.
3413 * Synchronization is needed after a write if there is a subsequent read
3414 * within the same block that may not be performed by the same thread.
3415 * There should not be any dependences between different blocks,
3416 * so we start with the flow dependences within the same kernel invocation
3417 * and we subtract from these those dependences that are mapped
3418 * to the same iteration of the bands where synchronization is inserted.
3419 * We do not remove pairs of instances that are known to map to
3420 * the same thread across different iterations of the intermediate
3421 * bands because the read may be performed by a different thread
3422 * than the one that needs the value if shared memory is involved.
3424 * We also consider all pairs of possible writes that access the same
3425 * memory location and that may be mapped to the same block but not
3426 * to the same iteration of the intermediate bands.
3427 * In theory, it would be possible for one thread to still be in
3428 * a previous iteration of a loop in these bands.
3429 * A write to global memory in this delayed thread could then overwrite
3430 * a write from another thread that has already moved on to
3431 * the next iteration.
3433 * After computing the above writes paired off with reads or writes
3434 * that depend on them, we project onto the domain writes.
3435 * Sychronization is needed after writes to global memory
3436 * through these references.
3438 static __isl_give isl_union_set *compute_sync_writes(
3439 struct ppcg_kernel *kernel, __isl_keep isl_schedule_node *node)
3441 isl_union_map *local;
3442 isl_union_map *may_writes, *shared_access;
3443 isl_union_map *kernel_prefix, *thread_prefix;
3444 isl_union_map *equal;
3445 isl_union_set *wrap;
3446 isl_union_set *domain;
3448 domain = isl_schedule_node_get_universe_domain(node);
3449 kernel_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3450 node = isl_schedule_node_copy(node);
3451 node = gpu_tree_move_down_to_thread(node, kernel->core);
3452 thread_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3453 isl_schedule_node_free(node);
3455 may_writes = isl_union_map_copy(kernel->prog->scop->tagged_may_writes);
3456 may_writes = isl_union_map_curry(may_writes);
3457 may_writes = isl_union_map_intersect_domain(may_writes, domain);
3458 may_writes = isl_union_map_uncurry(may_writes);
3459 shared_access = isl_union_map_copy(may_writes);
3460 shared_access = isl_union_map_apply_range(shared_access,
3461 isl_union_map_reverse(may_writes));
3463 local = isl_union_map_copy(kernel->prog->scop->tagged_dep_flow);
3464 local = isl_union_map_union(local, shared_access);
3465 local = isl_union_map_zip(local);
3467 equal = isl_union_map_apply_range(kernel_prefix,
3468 isl_union_map_reverse(isl_union_map_copy(kernel_prefix)));
3469 wrap = isl_union_map_wrap(equal);
3470 local = isl_union_map_intersect_domain(local, wrap);
3471 equal = isl_union_map_apply_range(thread_prefix,
3472 isl_union_map_reverse(isl_union_map_copy(thread_prefix)));
3473 wrap = isl_union_map_wrap(equal);
3474 local = isl_union_map_subtract_domain(local, wrap);
3476 local = isl_union_map_zip(local);
3477 local = isl_union_map_universe(local);
3479 return isl_union_map_domain(local);
3482 /* Group the domain elements into a single space, named kernelX,
3483 * with X the kernel sequence number "kernel_id".
3485 static __isl_give isl_schedule_node *group_statements(
3486 __isl_take isl_schedule_node *node, int kernel_id)
3488 char buffer[20];
3489 isl_id *id;
3491 if (!node)
3492 return NULL;
3494 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3495 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3496 return isl_schedule_node_group(node, id);
3499 /* Create a ppcg_kernel representing the domain instances that reach "node"
3500 * and insert a mark node pointing to the ppcg_kernel before "node".
3501 * The band that "node" points to is the band that needs to be mapped
3502 * to block identifiers. The band that needs to be mapped to thread
3503 * identifiers should be marked by a "thread" mark by the caller.
3504 * This mark is removed by this function.
3505 * If "scale" is set, then the band that "node" points to is scaled
3506 * by "sizes".
3508 * Mark all outer band nodes as atomic to ensure each kernel is only
3509 * scheduled once.
3510 * If the domain elements that reach "node" live in more than one space,
3511 * then group the domain elements into a single space, named kernelX,
3512 * with X the kernel sequence number.
3514 * Insert a guard node governing the kernel node to ensure that
3515 * no kernels with zero blocks are launched.
3517 * Insert a context node describing the block and thread
3518 * identifiers inside the kernel mark.
3519 * The context node needs to be inserted after the effective block size
3520 * has been determined such that the bounds on the thread identifiers
3521 * would reflect the effective block size.
3522 * Insert a filter node inside the context node mapping the statement
3523 * instances to block identifiers. In particular, the block identifiers
3524 * are equated to the partial schedule of band that was marked for mapping
3525 * to blocks modulo the grid size.
3526 * Insert a filter node inside the "thread" mark mapping the statement
3527 * instances to thread identifiers. In particular, the thread identifiers
3528 * are equated to the partial schedule of band that was marked for mapping
3529 * to threads modulo the block size.
3531 * Compute array reference groups for all arrays, set the local
3532 * array bounds based on the set of domain instances that reach
3533 * the kernel node, check the total amount of shared memory used
3534 * and compute all group tilings.
3535 * The array reference groups are computed after the block filter
3536 * has been inserted because it affects the mapping to shared or
3537 * private memory. This computation also requires the thread filter
3538 * (in the ppcg_kernel object), but this thread filter should not
3539 * have been added to the schedule tree yet since the computation
3540 * requires the schedule of the band that needs to be mapped to
3541 * threads before the privatization is applied.
3543 * If any array reference group requires the band mapped to threads
3544 * to be unrolled, then we perform the required unrolling.
3546 * We save a copy of the schedule that may influence the mappings
3547 * to shared or private memory in kernel->shared_schedule.
3549 * Finally, we add synchronization and copy statements to the schedule tree,
3550 * remove the "thread" mark and create representations for the local
3551 * variables in the kernel.
3553 * We keep a copy of the isl_id that points to the kernel to ensure
3554 * that the kernel does not get destroyed if the schedule node
3555 * is freed due to some error condition.
3557 static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
3558 __isl_take isl_schedule_node *node, int scale,
3559 __isl_keep isl_multi_val *sizes)
3561 struct ppcg_kernel *kernel;
3562 isl_id *id;
3563 isl_schedule_node *node_thread;
3564 isl_union_map *host_schedule;
3565 isl_set *host_domain;
3566 isl_union_set *domain;
3567 int single_statement;
3569 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3570 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3571 if (!kernel)
3572 return isl_schedule_node_free(node);
3574 domain = isl_schedule_node_get_domain(node);
3575 single_statement = isl_union_set_n_set(domain) == 1;
3577 kernel->ctx = gen->ctx;
3578 kernel->prog = gen->prog;
3579 kernel->options = gen->options;
3580 kernel->context = extract_context(node, gen->prog);
3581 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3582 kernel->arrays = accessed_by_domain(isl_union_set_copy(domain),
3583 gen->prog);
3584 kernel->n_grid = n_outer_coincidence(node);
3585 node_thread = isl_schedule_node_copy(node);
3586 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3587 node_thread = isl_schedule_node_child(node_thread, 0);
3588 kernel->n_block = n_outer_coincidence(node_thread);
3589 isl_schedule_node_free(node_thread);
3590 kernel->id = gen->kernel_id++;
3591 read_grid_and_block_sizes(kernel, gen);
3593 kernel->sync_writes = compute_sync_writes(kernel, node);
3595 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3596 host_domain = isl_set_from_union_set(isl_union_map_range(
3597 host_schedule));
3599 node = atomic_ancestors(node);
3601 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3602 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3603 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3605 if (!single_statement)
3606 node = group_statements(node, kernel->id);
3608 node = isl_schedule_node_child(node, 0);
3609 node = split_band(node, kernel->n_grid);
3610 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3611 kernel->n_grid, "b");
3612 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3613 kernel->grid_dim);
3614 kernel->grid_size = extract_grid_size(kernel,
3615 isl_union_set_copy(domain));
3616 if (!kernel->options->wrap)
3617 node = snap_band_to_sizes(node, kernel->grid_dim,
3618 kernel->options);
3619 if (scale)
3620 node = scale_band(node, isl_multi_val_copy(sizes));
3621 node = isl_schedule_node_parent(node);
3622 if (!single_statement)
3623 node = isl_schedule_node_parent(node);
3624 node = insert_guard(node, kernel->context, kernel->grid_size,
3625 gen->prog->scop);
3626 node = gpu_tree_move_down_to_thread(node, kernel->core);
3627 node = isl_schedule_node_child(node, 0);
3628 node = split_band(node, kernel->n_block);
3629 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3630 kernel->n_block, "t");
3631 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3632 kernel->block_dim);
3633 extract_block_size(kernel, domain);
3635 node = gpu_tree_move_up_to_kernel(node);
3636 node = isl_schedule_node_child(node, 0);
3637 node = insert_context(kernel, node);
3638 node = isl_schedule_node_child(node, 0);
3639 node = isl_schedule_node_insert_filter(node,
3640 isl_union_set_copy(kernel->block_filter));
3642 node = gpu_tree_move_up_to_kernel(node);
3644 if (gpu_group_references(kernel, node) < 0)
3645 node = isl_schedule_node_free(node);
3646 localize_bounds(kernel, host_domain);
3647 isl_set_free(host_domain);
3649 check_shared_memory_bound(kernel);
3650 compute_group_tilings(kernel);
3652 node = gpu_tree_move_down_to_thread(node, kernel->core);
3653 node = isl_schedule_node_child(node, 0);
3654 if (!kernel->options->wrap)
3655 node = snap_band_to_sizes(node, kernel->block_dim,
3656 kernel->options);
3657 node = isl_schedule_node_insert_filter(node,
3658 isl_union_set_copy(kernel->thread_filter));
3659 if (kernel_requires_unroll(kernel)) {
3660 node = isl_schedule_node_child(node, 0);
3661 node = unroll(node);
3664 node = gpu_tree_move_up_to_thread(node);
3665 kernel->shared_schedule_dim =
3666 isl_schedule_node_get_schedule_depth(node);
3667 kernel->shared_schedule =
3668 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3670 node = gpu_tree_move_up_to_kernel(node);
3672 node = add_sync(kernel, node);
3673 node = add_copies(kernel, node);
3675 node = gpu_tree_move_down_to_thread(node, kernel->core);
3676 node = isl_schedule_node_delete(node);
3678 node = gpu_tree_move_up_to_kernel(node);
3680 if (create_kernel_vars(kernel) < 0)
3681 node = isl_schedule_node_free(node);
3683 if (!single_statement)
3684 node = isl_schedule_node_parent(node);
3685 node = isl_schedule_node_parent(node);
3687 isl_id_free(id);
3688 return node;
3691 /* Insert a zero-dimensional permutable band at "node".
3693 static __isl_give isl_schedule_node *insert_empty_permutable_band(
3694 __isl_take isl_schedule_node *node)
3696 isl_space *space;
3697 isl_schedule *schedule;
3698 isl_union_set *domain;
3699 isl_multi_union_pw_aff *mupa;
3701 schedule = isl_schedule_node_get_schedule(node);
3702 domain = isl_schedule_get_domain(schedule);
3703 space = isl_union_set_get_space(domain);
3704 isl_union_set_free(domain);
3705 isl_schedule_free(schedule);
3707 space = isl_space_set_from_params(space);
3708 mupa = isl_multi_union_pw_aff_zero(space);
3709 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3710 node = isl_schedule_node_band_set_permutable(node, 1);
3712 return node;
3715 /* If "node" is the outermost permutable band that can be mapped to block and
3716 * thread identifiers in its branch (or a leaf with no such outer bands),
3717 * then mark the band as such, attaching a ppcg_kernel to the mark.
3719 * If "node" originally points to a leaf, then insert a zero-dimensional
3720 * permutable band such that we can assume that "node" always
3721 * points to a band node.
3723 * Tile "node" using user specified tile sizes, after splitting the band
3724 * if the number of specified tile sizes is smaller than the dimension
3725 * of the band. Mark the point band of this tiling as the band that
3726 * needs to be mapped to threads.
3727 * Create a kernel representing the domain instances that reach "node" and
3728 * insert a mark node pointing to the ppcg_kernel before the band node.
3730 static __isl_give isl_schedule_node *mark_outer_permutable(
3731 __isl_take isl_schedule_node *node, void *user)
3733 struct gpu_gen *gen = user;
3734 int outer;
3735 int scale;
3736 int tile_len;
3737 int *tile_size;
3738 isl_id *id;
3739 isl_multi_val *sizes;
3741 outer = is_outer_tilable(node);
3742 if (outer < 0)
3743 return isl_schedule_node_free(node);
3744 if (!outer)
3745 return node;
3747 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
3748 node = insert_empty_permutable_band(node);
3750 tile_len = isl_schedule_node_band_n_member(node);
3751 tile_size = read_tile_sizes(gen, &tile_len);
3752 if (!tile_size)
3753 return isl_schedule_node_free(node);
3754 if (tile_len < isl_schedule_node_band_n_member(node))
3755 node = isl_schedule_node_band_split(node, tile_len);
3756 sizes = construct_band_tiles_sizes(node, tile_size);
3757 node = tile_band(node, isl_multi_val_copy(sizes));
3758 node = isl_schedule_node_child(node, 0);
3759 id = isl_id_alloc(gen->ctx, "thread", NULL);
3760 node = isl_schedule_node_insert_mark(node, id);
3761 node = isl_schedule_node_parent(node);
3763 scale = gen->options->scale_tile_loops;
3764 node = create_kernel(gen, node, scale, sizes);
3765 isl_multi_val_free(sizes);
3766 free(tile_size);
3768 return node;
3771 /* Does the subtree rooted at "node" have any suitably permutable band nodes?
3772 * That is, does it have any nodes that are permutable and that
3773 * have a least one coincident dimension?
3775 static int subtree_has_permutable_bands(__isl_keep isl_schedule_node *node)
3777 int any_parallelism = 0;
3779 if (isl_schedule_node_foreach_descendant(node, &set_permutable,
3780 &any_parallelism) < 0 &&
3781 !any_parallelism)
3782 return -1;
3784 return any_parallelism;
3787 /* Mark all variables that are accessed by the statement instances in "domain"
3788 * and that are local to "prog" as requiring a declaration in the host code.
3790 static int declare_accessed_local_variables(struct gpu_prog *prog,
3791 __isl_keep isl_union_set *domain)
3793 isl_union_set *arrays;
3794 int i;
3796 if (!ppcg_scop_any_hidden_declarations(prog->scop))
3797 return 0;
3798 arrays = accessed_by_domain(isl_union_set_copy(domain), prog);
3800 for (i = 0; i < prog->n_array; ++i) {
3801 isl_space *space;
3802 isl_set *set;
3803 int empty;
3805 if (!prog->array[i].local)
3806 continue;
3807 space = isl_set_get_space(prog->array[i].extent);
3808 set = isl_union_set_extract_set(arrays, space);
3809 empty = isl_set_plain_is_empty(set);
3810 isl_set_free(set);
3811 if (empty < 0)
3812 goto error;
3813 if (!empty)
3814 prog->array[i].declare_local = 1;
3817 isl_union_set_free(arrays);
3818 return 0;
3819 error:
3820 isl_union_set_free(arrays);
3821 return -1;
3824 /* If "node" points to a set node, then separate its children
3825 * into subtrees that have suitably permutable bands and
3826 * those that do not.
3827 * Adjust the schedule tree in order to execute the second group
3828 * after the first group and return a pointer to the first group,
3829 * assuming there are any such subtrees.
3830 * Mark all local variables in "prog" that are accessed by
3831 * the second group as requiring a declaration on the host.
3833 static __isl_give isl_schedule_node *isolate_permutable_subtrees(
3834 __isl_take isl_schedule_node *node, struct gpu_prog *prog)
3836 isl_space *space;
3837 isl_union_set *filter;
3838 int i, n;
3840 if (!node)
3841 return NULL;
3842 if (isl_schedule_node_get_type(node) != isl_schedule_node_set)
3843 return node;
3845 n = isl_schedule_node_n_children(node);
3846 if (n < 0)
3847 return isl_schedule_node_free(node);
3849 node = isl_schedule_node_child(node, 0);
3850 filter = isl_schedule_node_filter_get_filter(node);
3851 node = isl_schedule_node_parent(node);
3852 space = isl_union_set_get_space(filter);
3853 isl_union_set_free(filter);
3854 filter = isl_union_set_empty(space);
3856 for (i = 0; i < n; ++i) {
3857 int parallelism;
3859 node = isl_schedule_node_child(node, i);
3860 parallelism = subtree_has_permutable_bands(node);
3861 if (parallelism < 0) {
3862 node = isl_schedule_node_free(node);
3863 } else if (!parallelism) {
3864 isl_union_set *filter_i;
3865 filter_i = isl_schedule_node_filter_get_filter(node);
3866 filter = isl_union_set_union(filter, filter_i);
3868 node = isl_schedule_node_parent(node);
3871 if (declare_accessed_local_variables(prog, filter) < 0)
3872 node = isl_schedule_node_free(node);
3873 node = isl_schedule_node_order_after(node, filter);
3875 return node;
3878 /* Replace any reference to an array element in the range of "copy"
3879 * by a reference to all array elements (defined by the extent of the array).
3881 static __isl_give isl_union_map *approximate_copy_out(
3882 __isl_take isl_union_map *copy, struct gpu_prog *prog)
3884 int i;
3885 isl_union_map *res;
3887 res = isl_union_map_empty(isl_union_map_get_space(copy));
3889 for (i = 0; i < prog->n_array; ++i) {
3890 isl_space *space;
3891 isl_set *set;
3892 isl_union_map *copy_i;
3893 isl_union_set *extent, *domain;
3895 space = isl_space_copy(prog->array[i].space);
3896 extent = isl_union_set_from_set(isl_set_universe(space));
3897 copy_i = isl_union_map_copy(copy);
3898 copy_i = isl_union_map_intersect_range(copy_i, extent);
3899 set = isl_set_copy(prog->array[i].extent);
3900 extent = isl_union_set_from_set(set);
3901 domain = isl_union_map_domain(copy_i);
3902 copy_i = isl_union_map_from_domain_and_range(domain, extent);
3903 res = isl_union_map_union(res, copy_i);
3906 isl_union_map_free(copy);
3908 return res;
3911 /* Insert "kernel" marks that point to a ppcg_kernel structure
3912 * in front of all outermost tilable band that (by construction)
3913 * have at least one parallel loop.
3915 static __isl_give isl_schedule_node *mark_kernels(struct gpu_gen *gen,
3916 __isl_take isl_schedule_node *node)
3918 return isl_schedule_node_map_descendant(node,
3919 &mark_outer_permutable, gen);
3922 /* Save the schedule "schedule" to a file called "filename".
3923 * The schedule is printed in block style.
3925 static void save_schedule(__isl_keep isl_schedule *schedule,
3926 const char *filename)
3928 FILE *file;
3929 isl_ctx *ctx;
3930 isl_printer *p;
3932 if (!schedule)
3933 return;
3935 file = fopen(filename, "w");
3936 if (!file) {
3937 fprintf(stderr, "Unable to open '%s' for writing\n", filename);
3938 return;
3940 ctx = isl_schedule_get_ctx(schedule);
3941 p = isl_printer_to_file(ctx, file);
3942 p = isl_printer_set_yaml_style(p, ISL_YAML_STYLE_BLOCK);
3943 p = isl_printer_print_schedule(p, schedule);
3944 isl_printer_free(p);
3945 fclose(file);
3948 /* Load and return a schedule from a file called "filename".
3950 static __isl_give isl_schedule *load_schedule(isl_ctx *ctx,
3951 const char *filename)
3953 FILE *file;
3954 isl_schedule *schedule;
3956 file = fopen(filename, "r");
3957 if (!file) {
3958 fprintf(stderr, "Unable to open '%s' for reading\n", filename);
3959 return NULL;
3961 schedule = isl_schedule_read_from_file(ctx, file);
3962 fclose(file);
3964 return schedule;
3967 /* Compute an appropriate schedule based on the accesses in
3968 * gen->read and gen->write.
3970 * We use the dependences in gen->prog->scop to compute
3971 * a schedule that has a parallel loop in each tilable band and
3972 * return this schedule.
3974 * If live range reordering is allowed, then we need to make sure
3975 * that live ranges on arrays are not run in parallel since doing
3976 * so would require array expansion. We therefore add the array
3977 * order dependences to the coincidence dependences. Non-zero array
3978 * order dependences will then prevent a schedule dimension from being
3979 * considered parallel.
3980 * Live ranges derived from scalars are allowed to be run in parallel
3981 * since we force the scalars to be mapped to private memory in
3982 * check_scalar_live_ranges.
3983 * If live range reordering is allowed, then the false dependences
3984 * are not added to the validity constraints as that would prevent
3985 * reordering. Instead, the external false dependences that enforce that reads
3986 * from potentially live-in data precede any later write and
3987 * that writes of potentially live-out data follow any other earlier write
3988 * are added to the validity and the coincidence constraints.
3989 * The false dependences are still added to the proximity constraints
3990 * for consistency with the case where live range reordering is not allowed.
3991 * The coincidence constraints then consist of flow dependences,
3992 * external false dependences and array order dependences.
3993 * The independences can be filtered out from the first two sets.
3994 * They have already been filtered out from the array order dependences
3995 * on a per array basis in collect_order_dependences.
3996 * There is no need for a per array handling of the other two sets
3997 * as there should be no flow or external false dependence on local
3998 * variables that can be filtered out.
4000 static __isl_give isl_schedule *compute_schedule(struct gpu_gen *gen)
4002 isl_union_set *domain;
4003 isl_union_map *dep_raw, *dep;
4004 isl_union_map *validity, *proximity, *coincidence;
4005 isl_schedule_constraints *sc;
4006 isl_schedule *schedule;
4008 domain = isl_union_set_copy(gen->prog->scop->domain);
4009 sc = isl_schedule_constraints_on_domain(domain);
4010 sc = isl_schedule_constraints_set_context(sc,
4011 isl_set_copy(gen->prog->scop->context));
4012 if (gen->options->live_range_reordering) {
4013 sc = isl_schedule_constraints_set_conditional_validity(sc,
4014 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
4015 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
4016 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
4017 validity = isl_union_map_copy(proximity);
4018 validity = isl_union_map_union(validity,
4019 isl_union_map_copy(gen->prog->scop->dep_forced));
4020 proximity = isl_union_map_union(proximity,
4021 isl_union_map_copy(gen->prog->scop->dep_false));
4022 coincidence = isl_union_map_copy(validity);
4023 coincidence = isl_union_map_subtract(coincidence,
4024 isl_union_map_copy(gen->prog->scop->independence));
4025 coincidence = isl_union_map_union(coincidence,
4026 isl_union_map_copy(gen->prog->array_order));
4027 } else {
4028 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4029 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4030 dep = isl_union_map_union(dep, dep_raw);
4031 dep = isl_union_map_coalesce(dep);
4032 proximity = isl_union_map_copy(dep);
4033 coincidence = isl_union_map_copy(dep);
4034 validity = dep;
4036 sc = isl_schedule_constraints_set_validity(sc, validity);
4037 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4038 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4040 if (gen->options->debug->dump_schedule_constraints)
4041 isl_schedule_constraints_dump(sc);
4042 schedule = isl_schedule_constraints_compute_schedule(sc);
4044 return schedule;
4047 /* Obtain a schedule for the scop, either by reading it from
4048 * a file or by computing one.
4050 static __isl_give isl_schedule *get_schedule(struct gpu_gen *gen)
4052 isl_schedule *schedule;
4054 if (gen->options->load_schedule_file) {
4055 schedule = load_schedule(gen->ctx,
4056 gen->options->load_schedule_file);
4057 } else {
4058 schedule = compute_schedule(gen);
4059 if (gen->options->save_schedule_file)
4060 save_schedule(schedule,
4061 gen->options->save_schedule_file);
4063 if (gen->options->debug->dump_schedule)
4064 isl_schedule_dump(schedule);
4066 return schedule;
4069 /* Construct the string "<a>_<b>".
4071 static char *concat(isl_ctx *ctx, const char *a, const char *b)
4073 isl_printer *p;
4074 char *s;
4076 p = isl_printer_to_str(ctx);
4077 p = isl_printer_print_str(p, a);
4078 p = isl_printer_print_str(p, "_");
4079 p = isl_printer_print_str(p, b);
4080 s = isl_printer_get_str(p);
4081 isl_printer_free(p);
4083 return s;
4086 /* For each array in "prog" of which an element appears in "accessed" and
4087 * that is not a read only scalar, create a zero-dimensional universe set
4088 * of which the tuple id has name "<prefix>_<name of array>" and a user
4089 * pointer pointing to the array (gpu_array_info).
4091 * If the array is local to "prog", then make sure it will be declared
4092 * in the host code.
4094 * Return the list of these universe sets.
4096 static __isl_give isl_union_set_list *create_copy_filters(struct gpu_prog *prog,
4097 const char *prefix, __isl_take isl_union_set *accessed)
4099 int i;
4100 isl_ctx *ctx;
4101 isl_union_set_list *filters;
4103 ctx = prog->ctx;
4104 filters = isl_union_set_list_alloc(ctx, 0);
4105 for (i = 0; i < prog->n_array; ++i) {
4106 struct gpu_array_info *array = &prog->array[i];
4107 isl_space *space;
4108 isl_set *accessed_i;
4109 int empty;
4110 char *name;
4111 isl_id *id;
4112 isl_union_set *uset;
4114 if (gpu_array_is_read_only_scalar(array))
4115 continue;
4117 space = isl_space_copy(array->space);
4118 accessed_i = isl_union_set_extract_set(accessed, space);
4119 empty = isl_set_plain_is_empty(accessed_i);
4120 isl_set_free(accessed_i);
4121 if (empty < 0) {
4122 filters = isl_union_set_list_free(filters);
4123 break;
4125 if (empty)
4126 continue;
4128 if (array->local)
4129 array->declare_local = 1;
4131 name = concat(ctx, prefix, array->name);
4132 id = name ? isl_id_alloc(ctx, name, array) : NULL;
4133 free(name);
4134 space = isl_space_set_alloc(ctx, 0, 0);
4135 space = isl_space_set_tuple_id(space, isl_dim_set, id);
4136 uset = isl_union_set_from_set(isl_set_universe(space));
4138 filters = isl_union_set_list_add(filters, uset);
4140 isl_union_set_free(accessed);
4142 return filters;
4145 /* Make sure that code for the statements in "filters" that
4146 * copy arrays to or from the device is only generated when
4147 * the size of the corresponding array is positive.
4148 * That is, add a set node underneath "graft" with "filters" as children
4149 * and for each child add a guard that the selects the parameter
4150 * values for which the corresponding array has a positive size.
4151 * The array is available in the user pointer of the statement identifier.
4152 * "depth" is the schedule depth of the position where "graft"
4153 * will be added.
4155 static __isl_give isl_schedule_node *insert_positive_size_guards(
4156 __isl_take isl_schedule_node *graft,
4157 __isl_take isl_union_set_list *filters, int depth)
4159 int i, n;
4161 graft = isl_schedule_node_child(graft, 0);
4162 graft = isl_schedule_node_insert_set(graft, filters);
4163 n = isl_schedule_node_n_children(graft);
4164 for (i = 0; i < n; ++i) {
4165 isl_union_set *filter;
4166 isl_set *domain, *guard;
4167 isl_id *id;
4168 struct gpu_array_info *array;
4170 graft = isl_schedule_node_child(graft, i);
4171 filter = isl_schedule_node_filter_get_filter(graft);
4172 domain = isl_set_from_union_set(filter);
4173 id = isl_set_get_tuple_id(domain);
4174 array = isl_id_get_user(id);
4175 isl_id_free(id);
4176 isl_set_free(domain);
4177 guard = gpu_array_positive_size_guard(array);
4178 guard = isl_set_from_params(guard);
4179 guard = isl_set_add_dims(guard, isl_dim_set, depth);
4180 graft = isl_schedule_node_child(graft, 0);
4181 graft = isl_schedule_node_insert_guard(graft, guard);
4182 graft = isl_schedule_node_parent(graft);
4183 graft = isl_schedule_node_parent(graft);
4185 graft = isl_schedule_node_parent(graft);
4187 return graft;
4190 /* Create a graft for copying arrays to or from the device,
4191 * whenever the size of the array is strictly positive.
4192 * Each statement is called "<prefix>_<name of array>" and
4193 * the identifier has a user pointer pointing to the array.
4194 * The graft will be added at the position specified by "node".
4195 * "copy" contains the array elements that need to be copied.
4196 * Only arrays of which some elements need to be copied
4197 * will have a corresponding statement in the graph.
4198 * Note though that each such statement will copy the entire array.
4200 static __isl_give isl_schedule_node *create_copy_device(struct gpu_prog *prog,
4201 __isl_keep isl_schedule_node *node, const char *prefix,
4202 __isl_take isl_union_set *copy)
4204 int depth;
4205 isl_ctx *ctx;
4206 isl_space *space;
4207 isl_union_set *all, *domain;
4208 isl_union_set_list *filters;
4209 isl_union_map *extension;
4210 isl_schedule_node *graft;
4212 ctx = prog->ctx;
4213 depth = isl_schedule_node_get_schedule_depth(node);
4214 filters = create_copy_filters(prog, prefix, copy);
4215 all = isl_union_set_list_union(isl_union_set_list_copy(filters));
4217 space = depth < 0 ? NULL : isl_space_set_alloc(ctx, 0, depth);
4218 domain = isl_union_set_from_set(isl_set_universe(space));
4219 extension = isl_union_map_from_domain_and_range(domain, all);
4220 graft = isl_schedule_node_from_extension(extension);
4222 if (!filters)
4223 return isl_schedule_node_free(graft);
4224 if (isl_union_set_list_n_union_set(filters) == 0) {
4225 isl_union_set_list_free(filters);
4226 return graft;
4229 return insert_positive_size_guards(graft, filters, depth);
4232 /* Return (the universe spaces of) the arrays that are declared
4233 * inside the scop corresponding to "prog" and for which all
4234 * potential writes inside the scop form a subset of "domain".
4236 static __isl_give isl_union_set *extract_local_accesses(struct gpu_prog *prog,
4237 __isl_keep isl_union_set *domain)
4239 int i;
4240 isl_union_set *local;
4242 local = isl_union_set_empty(isl_union_set_get_space(domain));
4244 for (i = 0; i < prog->n_array; ++i) {
4245 isl_set *set;
4246 isl_union_map *to_outer;
4247 isl_union_map *may_write;
4248 isl_union_set *write_domain;
4249 isl_union_set *fields;
4250 int subset;
4252 if (!prog->array[i].local)
4253 continue;
4255 set = isl_set_universe(isl_space_copy(prog->array[i].space));
4256 to_outer = isl_union_map_copy(prog->to_outer);
4257 to_outer = isl_union_map_intersect_range(to_outer,
4258 isl_union_set_from_set(isl_set_copy(set)));
4259 fields = isl_union_map_domain(to_outer);
4260 may_write = isl_union_map_copy(prog->may_write);
4261 may_write = isl_union_map_intersect_range(may_write, fields);
4262 write_domain = isl_union_map_domain(may_write);
4263 subset = isl_union_set_is_subset(write_domain, domain);
4264 isl_union_set_free(write_domain);
4266 if (subset < 0) {
4267 isl_set_free(set);
4268 return isl_union_set_free(local);
4269 } else if (subset) {
4270 local = isl_union_set_add_set(local, set);
4271 } else {
4272 isl_set_free(set);
4276 return local;
4279 /* Internal data structure for node_may_persist.
4281 * "tagger" maps tagged iteration domains to the corresponding untagged
4282 * iteration domain.
4284 * "may_persist_flow" is the set of all tagged dataflow dependences
4285 * with those dependences removed that either precede or follow
4286 * the kernel launch in a sequence.
4287 * "inner_band_flow" is the set of all tagged dataflow dependences
4288 * that are local to a given iteration of the outer band nodes
4289 * with respect to the current node.
4290 * "local_flow" is equal to "inner_band_flow", except that the domain
4291 * and the range have been intersected with intermediate filters
4292 * on children of sets or sequences.
4294 struct ppcg_may_persist_data {
4295 isl_union_pw_multi_aff *tagger;
4297 isl_union_map *local_flow;
4298 isl_union_map *inner_band_flow;
4299 isl_union_map *may_persist_flow;
4302 /* Update the information in "data" based on the band ancestor "node".
4304 * In particular, we restrict the dependences in data->local_flow
4305 * to those dependence where the source and the sink occur in
4306 * the same iteration of the given band node.
4307 * We also update data->inner_band_flow to the new value of
4308 * data->local_flow.
4310 static int update_may_persist_at_band(__isl_keep isl_schedule_node *node,
4311 struct ppcg_may_persist_data *data)
4313 isl_multi_union_pw_aff *partial;
4314 isl_union_pw_multi_aff *contraction;
4315 isl_union_map *flow;
4317 if (isl_schedule_node_band_n_member(node) == 0)
4318 return 0;
4320 partial = isl_schedule_node_band_get_partial_schedule(node);
4321 contraction = isl_schedule_node_get_subtree_contraction(node);
4322 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4323 contraction);
4324 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4325 isl_union_pw_multi_aff_copy(data->tagger));
4327 flow = data->local_flow;
4328 flow = isl_union_map_eq_at_multi_union_pw_aff(flow, partial);
4329 data->local_flow = flow;
4331 isl_union_map_free(data->inner_band_flow);
4332 data->inner_band_flow = isl_union_map_copy(data->local_flow);
4334 return 0;
4337 /* Given a set of local reaching domain elements "domain",
4338 * expand them to the corresponding leaf domain elements using "contraction"
4339 * and insert the array references tags using data->tagger.
4341 static __isl_give isl_union_set *expand_and_tag(
4342 __isl_take isl_union_set *domain,
4343 __isl_take isl_union_pw_multi_aff *contraction,
4344 struct ppcg_may_persist_data *data)
4346 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4347 contraction);
4348 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4349 isl_union_pw_multi_aff_copy(data->tagger));
4350 return domain;
4353 /* Given a filter node that is the child of a set or sequence node,
4354 * restrict data->local_flow to refer only to those elements
4355 * in the filter of the node.
4356 * "contraction" maps the leaf domain elements of the schedule tree
4357 * to the corresponding domain elements at (the parent of) "node".
4359 static int filter_flow(__isl_keep isl_schedule_node *node,
4360 struct ppcg_may_persist_data *data,
4361 __isl_take isl_union_pw_multi_aff *contraction)
4363 isl_union_set *filter;
4364 isl_union_map *flow;
4366 flow = data->local_flow;
4367 filter = isl_schedule_node_filter_get_filter(node);
4368 filter = expand_and_tag(filter, contraction, data);
4369 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(filter));
4370 flow = isl_union_map_intersect_range(flow, filter);
4371 data->local_flow = flow;
4373 return 0;
4376 /* Given a filter node "node", collect the filters on all preceding siblings
4377 * (which are also filter nodes), add them to "filters" and return the result.
4379 static __isl_give isl_union_set *add_previous_filters(
4380 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4382 isl_schedule_node *sibling;
4384 sibling = isl_schedule_node_copy(node);
4385 while (sibling && isl_schedule_node_has_previous_sibling(sibling)) {
4386 isl_union_set *filter;
4388 sibling = isl_schedule_node_previous_sibling(sibling);
4389 filter = isl_schedule_node_filter_get_filter(sibling);
4390 filters = isl_union_set_union(filters, filter);
4392 isl_schedule_node_free(sibling);
4393 if (!sibling)
4394 return isl_union_set_free(filters);
4396 return filters;
4399 /* Given a filter node "node", collect the filters on all following siblings
4400 * (which are also filter nodes), add them to "filters" and return the result.
4402 static __isl_give isl_union_set *add_next_filters(
4403 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4405 isl_schedule_node *sibling;
4407 sibling = isl_schedule_node_copy(node);
4408 while (sibling && isl_schedule_node_has_next_sibling(sibling)) {
4409 isl_union_set *filter;
4411 sibling = isl_schedule_node_next_sibling(sibling);
4412 filter = isl_schedule_node_filter_get_filter(sibling);
4413 filters = isl_union_set_union(filters, filter);
4415 isl_schedule_node_free(sibling);
4416 if (!sibling)
4417 return isl_union_set_free(filters);
4419 return filters;
4422 /* Remove those flow dependences from data->may_persist_flow
4423 * that flow between elements of "domain" within the same iteration
4424 * of all outer band nodes.
4425 * "contraction" maps the leaf domain elements of the schedule tree
4426 * to the corresponding elements "domain".
4428 static void remove_external_flow(struct ppcg_may_persist_data *data,
4429 __isl_take isl_union_set *domain,
4430 __isl_keep isl_union_pw_multi_aff *contraction)
4432 isl_union_map *flow;
4434 contraction = isl_union_pw_multi_aff_copy(contraction);
4435 domain = expand_and_tag(domain, contraction, data);
4436 flow = isl_union_map_copy(data->local_flow);
4437 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(domain));
4438 flow = isl_union_map_intersect_range(flow, domain);
4440 data->may_persist_flow = isl_union_map_subtract(data->may_persist_flow,
4441 flow);
4444 /* Update the information in "data" based on the filter ancestor "node".
4445 * We only need to modify anything if the filter is the child
4446 * of a set or sequence node.
4448 * In the case of a sequence, we remove the dependences between
4449 * statement instances that are both executed either before or
4450 * after the subtree that will be mapped to a kernel, within
4451 * the same iteration of outer bands.
4453 * In both cases, we restrict data->local_flow to the current child.
4455 static int update_may_persist_at_filter(__isl_keep isl_schedule_node *node,
4456 struct ppcg_may_persist_data *data)
4458 enum isl_schedule_node_type type;
4459 isl_schedule_node *parent;
4460 isl_space *space;
4461 isl_union_pw_multi_aff *contraction;
4462 isl_union_set *before, *after, *filter;
4463 isl_union_map *flow;
4465 type = isl_schedule_node_get_parent_type(node);
4466 if (type != isl_schedule_node_sequence && type != isl_schedule_node_set)
4467 return 0;
4469 parent = isl_schedule_node_copy(node);
4470 parent = isl_schedule_node_parent(parent);
4471 contraction = isl_schedule_node_get_subtree_contraction(parent);
4472 isl_schedule_node_free(parent);
4474 if (type == isl_schedule_node_set)
4475 return filter_flow(node, data, contraction);
4477 filter = isl_schedule_node_filter_get_filter(node);
4478 space = isl_union_set_get_space(filter);
4479 isl_union_set_free(filter);
4480 before = isl_union_set_empty(space);
4481 after = isl_union_set_copy(before);
4482 before = add_previous_filters(before, node);
4483 after = add_next_filters(after, node);
4485 remove_external_flow(data, before, contraction);
4486 remove_external_flow(data, after, contraction);
4488 return filter_flow(node, data, contraction);
4491 /* Update the information in "data" based on the ancestor "node".
4493 static int update_may_persist_at(__isl_keep isl_schedule_node *node, void *user)
4495 struct ppcg_may_persist_data *data = user;
4497 switch (isl_schedule_node_get_type(node)) {
4498 case isl_schedule_node_error:
4499 return -1;
4500 case isl_schedule_node_context:
4501 case isl_schedule_node_domain:
4502 case isl_schedule_node_expansion:
4503 case isl_schedule_node_extension:
4504 case isl_schedule_node_guard:
4505 case isl_schedule_node_leaf:
4506 case isl_schedule_node_mark:
4507 case isl_schedule_node_sequence:
4508 case isl_schedule_node_set:
4509 break;
4510 case isl_schedule_node_band:
4511 if (update_may_persist_at_band(node, data) < 0)
4512 return -1;
4513 break;
4514 case isl_schedule_node_filter:
4515 if (update_may_persist_at_filter(node, data) < 0)
4516 return -1;
4517 break;
4520 return 0;
4523 /* Determine the set of array elements that may need to be perserved
4524 * by a kernel constructed from the subtree at "node".
4525 * This includes the set of array elements that may need to be preserved
4526 * by the entire scop (prog->may_persist) and the elements for which
4527 * there is a potential flow dependence that may cross a kernel launch.
4529 * To determine the second set, we start from all flow dependences.
4530 * From this set of dependences, we remove those that cannot possibly
4531 * require data to be preserved by a kernel launch.
4532 * In particular, we consider the following sets of dependences.
4533 * - dependences of which the write occurs inside the kernel.
4534 * If the data is needed outside the kernel, then it will
4535 * be copied out immediately after the kernel launch, so there
4536 * is no need for any special care.
4537 * - dependences of which the read occurs inside the kernel and the
4538 * corresponding write occurs inside the same iteration of the
4539 * outer band nodes. This means that the data is needed in
4540 * the first kernel launch after the write, which is already
4541 * taken care of by the standard copy-in. That is, the data
4542 * do not need to be preserved by any intermediate call to
4543 * the same kernel.
4544 * - dependences of which the write and the read either both occur
4545 * before the kernel launch or both occur after the kernel launch,
4546 * within the same iteration of the outer band nodes with respect
4547 * to the sequence that determines the ordering of the dependence
4548 * and the kernel launch. Such flow dependences cannot cross
4549 * any kernel launch.
4551 * For the remaining (tagged) dependences, we take the domain
4552 * (i.e., the tagged writes) and apply the tagged access relation
4553 * to obtain the accessed data elements.
4554 * These are then combined with the elements that may need to be
4555 * preserved by the entire scop.
4557 static __isl_give isl_union_set *node_may_persist(
4558 __isl_keep isl_schedule_node *node, struct gpu_prog *prog)
4560 struct ppcg_may_persist_data data;
4561 isl_schedule_node *root;
4562 isl_union_pw_multi_aff *contraction;
4563 isl_union_set *domain;
4564 isl_union_set *persist;
4565 isl_union_map *flow, *local_flow;
4567 data.tagger = prog->scop->tagger;
4569 flow = isl_union_map_copy(prog->scop->tagged_dep_flow);
4570 data.local_flow = isl_union_map_copy(flow);
4571 data.inner_band_flow = isl_union_map_copy(flow);
4572 data.may_persist_flow = flow;
4573 if (isl_schedule_node_foreach_ancestor_top_down(node,
4574 &update_may_persist_at, &data) < 0)
4575 data.may_persist_flow =
4576 isl_union_map_free(data.may_persist_flow);
4577 flow = data.may_persist_flow;
4578 isl_union_map_free(data.local_flow);
4580 domain = isl_schedule_node_get_domain(node);
4581 contraction = isl_schedule_node_get_subtree_contraction(node);
4582 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4583 contraction);
4584 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4585 isl_union_pw_multi_aff_copy(data.tagger));
4586 flow = isl_union_map_subtract_domain(flow, isl_union_set_copy(domain));
4587 local_flow = data.inner_band_flow;
4588 local_flow = isl_union_map_intersect_range(local_flow, domain);
4589 flow = isl_union_map_subtract(flow, local_flow);
4591 persist = isl_union_map_domain(flow);
4592 persist = isl_union_set_apply(persist,
4593 isl_union_map_copy(prog->scop->tagged_may_writes));
4594 persist = isl_union_set_union(persist,
4595 isl_union_set_copy(prog->may_persist));
4597 return persist;
4600 /* Add nodes for copying outer arrays in and out of the device
4601 * before and after the subtree "node", which contains one or more kernels.
4602 * "domain" contains the original reaching domain elements before
4603 * the kernels were created, i.e., before the contraction that
4604 * may have been performed in creating the kernels has been applied.
4605 * "prefix" contains the prefix schedule at that point, in terms
4606 * of the same original reaching domain elements.
4608 * We first compute the sets of outer array elements that need
4609 * to be copied in and out and then graft in the nodes for
4610 * performing this copying.
4612 * In particular, for each array that is possibly written anywhere in
4613 * the subtree "node" and that may be used after "node"
4614 * or that may be visible outside the corresponding scop,
4615 * we copy out its entire extent.
4617 * Any array elements that is read without first being written inside
4618 * the subtree "node" needs to be copied in.
4619 * Furthermore, if there are any array elements that
4620 * are copied out, but that may not be written inside "node, then
4621 * they also need to be copied in to ensure that the value after execution
4622 * is the same as the value before execution, at least for those array
4623 * elements that may have their values preserved by the scop or that
4624 * may be written before "node" and read after "node".
4625 * In case the array elements are structures, we need to take into
4626 * account that all members of the structures need to be written
4627 * by "node" before we can avoid copying the data structure in.
4629 * Note that the may_write relation is intersected with the domain,
4630 * which has been intersected with the context.
4631 * This helps in those cases where the arrays are declared with a fixed size,
4632 * while the accesses are parametric and the context assigns a fixed value
4633 * to the parameters.
4635 * If an element from a local array is read without first being written,
4636 * then there is no point in copying it in since it cannot have been
4637 * written prior to the scop. Warn about the uninitialized read instead.
4639 static __isl_give isl_schedule_node *add_to_from_device(
4640 __isl_take isl_schedule_node *node, __isl_take isl_union_set *domain,
4641 __isl_take isl_union_map *prefix, struct gpu_prog *prog)
4643 isl_union_set *local;
4644 isl_union_set *to_device, *from_device, *may_persist;
4645 isl_union_map *may_write, *must_write, *copy_out, *not_written;
4646 isl_union_map *read, *copy_in;
4647 isl_union_map *tagged;
4648 isl_union_map *local_uninitialized;
4649 isl_schedule_node *graft;
4651 tagged = isl_union_map_copy(prog->scop->tagged_reads);
4652 tagged = isl_union_map_union(tagged,
4653 isl_union_map_copy(prog->scop->tagged_may_writes));
4655 may_write = isl_union_map_copy(prog->may_write);
4656 may_write = isl_union_map_intersect_domain(may_write,
4657 isl_union_set_copy(domain));
4658 may_write = remove_local_accesses(prog,
4659 isl_union_map_copy(tagged), may_write,
4660 isl_union_map_copy(prefix), 0);
4661 may_write = isl_union_map_apply_range(may_write,
4662 isl_union_map_copy(prog->to_outer));
4663 may_write = isl_union_map_apply_domain(may_write,
4664 isl_union_map_copy(prefix));
4665 may_write = approximate_copy_out(may_write, prog);
4666 copy_out = isl_union_map_copy(may_write);
4667 may_write = isl_union_map_apply_range(may_write,
4668 isl_union_map_copy(prog->to_inner));
4669 must_write = isl_union_map_copy(prog->must_write);
4670 must_write = isl_union_map_apply_domain(must_write,
4671 isl_union_map_copy(prefix));
4672 may_persist = node_may_persist(node, prog);
4673 may_write = isl_union_map_intersect_range(may_write, may_persist);
4674 not_written = isl_union_map_subtract(may_write, must_write);
4676 local = extract_local_accesses(prog, domain);
4677 read = isl_union_map_copy(prog->read);
4678 read = isl_union_map_intersect_domain(read, domain);
4679 read = remove_local_accesses(prog, tagged, read,
4680 isl_union_map_copy(prefix), 1);
4681 local = isl_union_set_apply(local, isl_union_map_copy(prog->to_inner));
4682 local_uninitialized = isl_union_map_copy(prog->scop->live_in);
4683 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4684 local);
4685 local_uninitialized = isl_union_map_intersect(local_uninitialized,
4686 isl_union_map_copy(read));
4687 if (!isl_union_map_is_empty(local_uninitialized)) {
4688 fprintf(stderr,
4689 "possibly uninitialized reads (not copied in):\n");
4690 isl_union_map_dump(local_uninitialized);
4692 read = isl_union_map_subtract(read, local_uninitialized);
4693 read = isl_union_map_apply_domain(read, prefix);
4694 copy_in = isl_union_map_union(read, not_written);
4695 copy_in = isl_union_map_apply_range(copy_in,
4696 isl_union_map_copy(prog->to_outer));
4698 graft = create_copy_device(prog, node, "to_device",
4699 isl_union_map_range(copy_in));
4700 node = isl_schedule_node_graft_before(node, graft);
4701 graft = create_copy_device(prog, node, "from_device",
4702 isl_union_map_range(copy_out));
4703 node = isl_schedule_node_graft_after(node, graft);
4705 return node;
4708 /* Update "schedule" for mapping to a GPU device.
4710 * In particular, insert a context node, create kernels for
4711 * each outermost tilable band and introduce node for copying array
4712 * in and out of the device.
4713 * If the child of the initial root points to a set node,
4714 * then children of this node that do not contain any tilable bands
4715 * are separated from the other children and are not mapped to
4716 * the device.
4718 static __isl_give isl_schedule *map_to_device(struct gpu_gen *gen,
4719 __isl_take isl_schedule *schedule)
4721 isl_schedule_node *node;
4722 isl_set *context;
4723 isl_union_set *domain;
4724 isl_union_map *prefix;
4726 context = isl_set_copy(gen->prog->context);
4727 context = isl_set_from_params(context);
4728 schedule = isl_schedule_insert_context(schedule, context);
4730 node = isl_schedule_get_root(schedule);
4731 isl_schedule_free(schedule);
4732 node = isl_schedule_node_child(node, 0);
4733 if (isl_schedule_node_get_type(node) == isl_schedule_node_context)
4734 node = isl_schedule_node_child(node, 0);
4735 node = isolate_permutable_subtrees(node, gen->prog);
4736 domain = isl_schedule_node_get_domain(node);
4737 prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
4738 node = mark_kernels(gen, node);
4739 node = add_to_from_device(node, domain, prefix, gen->prog);
4740 schedule = isl_schedule_node_get_schedule(node);
4741 isl_schedule_node_free(node);
4743 return schedule;
4746 /* Internal data structure for extract_access.
4747 * "next_access" points to the end of a linked list that is extended
4748 * by extract_access.
4749 * "single_expression" is set if the access expressions belong to
4750 * an expression statement (i.e., a statement without internal control).
4751 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4753 struct ppcg_extract_access_data {
4754 struct gpu_stmt_access **next_access;
4755 int single_expression;
4756 isl_union_map *any_to_outer;
4759 /* Given a tagged access relation to a single array "tagged", extract it
4760 * as a map, taking into account that the input may be empty.
4761 * If the access relation is empty, then it does not contain
4762 * any space information, so we try to recover it from the index
4763 * expression.
4764 * The space of the index expression is of the form I -> A,
4765 * with I the statement instances and A the array, or [I -> F] -> A,
4766 * with F the filters corresponding to arguments.
4767 * We first drop F, if present, obtaining I -> A.
4768 * Then we construct I -> R, with R the reference tag,
4769 * combine the two into I -> [R -> A] and uncurry to obtain
4770 * the final result [I -> R] -> A.
4771 * Note that the index expression may have a lower dimension
4772 * than that of the array, but this dimension is not used
4773 * if the access relation is empty.
4775 static __isl_give isl_map *extract_single_tagged_access(
4776 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
4778 int empty;
4779 isl_id *id;
4780 isl_space *space, *space2;
4781 isl_multi_pw_aff *index;
4783 empty = isl_union_map_is_empty(tagged);
4784 if (empty < 0)
4785 goto error;
4786 if (!empty)
4787 return isl_map_from_union_map(tagged);
4788 isl_union_map_free(tagged);
4790 index = pet_expr_access_get_index(expr);
4791 space = isl_multi_pw_aff_get_space(index);
4792 isl_multi_pw_aff_free(index);
4793 if (isl_space_domain_is_wrapping(space))
4794 space = isl_space_domain_factor_domain(space);
4795 space2 = isl_space_copy(space);
4796 space2 = isl_space_from_domain(isl_space_domain(space));
4797 id = pet_expr_access_get_ref_id(expr);
4798 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
4799 space = isl_space_range_product(space2, space);
4800 space = isl_space_uncurry(space);
4802 return isl_map_empty(space);
4803 error:
4804 isl_union_map_free(tagged);
4805 return NULL;
4808 /* Extract a gpu_stmt_access from "expr", append it to the list
4809 * that ends in *data->next_access and update the end of the list.
4810 * If the access expression performs a write, then it is considered
4811 * exact only if it appears in a single expression statement and
4812 * if its may access relation is equal to its must access relation.
4814 * The combined set of may accesses may be union if member accesses
4815 * are involved, but the entire set is derived from a single reference and
4816 * therefore from a single index expression. These accesses therefore
4817 * all map to the same outer array.
4819 static int extract_access(__isl_keep pet_expr *expr, void *user)
4821 struct ppcg_extract_access_data *data = user;
4822 isl_union_map *tagged;
4823 struct gpu_stmt_access *access;
4824 isl_ctx *ctx = pet_expr_get_ctx(expr);
4825 isl_multi_pw_aff *index;
4827 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4828 assert(access);
4829 access->next = NULL;
4830 access->read = pet_expr_access_is_read(expr);
4831 access->write = pet_expr_access_is_write(expr);
4832 tagged = pet_expr_access_get_tagged_may_read(expr);
4833 tagged = isl_union_map_union(tagged,
4834 pet_expr_access_get_tagged_may_write(expr));
4835 tagged = isl_union_map_apply_range(tagged,
4836 isl_union_map_copy(data->any_to_outer));
4837 if (!access->write) {
4838 access->exact_write = 1;
4839 } else if (!data->single_expression) {
4840 access->exact_write = 0;
4841 } else {
4842 isl_union_map *must, *may;
4843 may = isl_union_map_copy(tagged);
4844 may = isl_union_map_domain_factor_domain(may);
4845 must = pet_expr_access_get_must_write(expr);
4846 access->exact_write = isl_union_map_is_equal(must, may);
4847 isl_union_map_free(must);
4848 isl_union_map_free(may);
4850 index = pet_expr_access_get_index(expr);
4851 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
4852 isl_multi_pw_aff_free(index);
4853 access->ref_id = pet_expr_access_get_ref_id(expr);
4854 access->tagged_access = extract_single_tagged_access(tagged, expr);
4855 access->access = isl_map_copy(access->tagged_access);
4856 access->access = isl_map_domain_factor_domain(access->access);
4858 *data->next_access = access;
4859 data->next_access = &(*data->next_access)->next;
4861 if (!access->access)
4862 return -1;
4864 return 0;
4867 /* Construct a linked list of gpu_stmt_access objects,
4868 * one for each access expression in the statement body.
4869 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4871 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
4872 __isl_keep isl_union_map *any_to_outer)
4874 struct ppcg_extract_access_data data;
4876 stmt->accesses = NULL;
4877 data.next_access = &stmt->accesses;
4878 data.single_expression =
4879 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
4880 data.any_to_outer = any_to_outer;
4881 return pet_tree_foreach_access_expr(stmt->stmt->body,
4882 &extract_access, &data);
4885 /* Return an array of gpu_stmt representing the statements in "scop".
4887 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4888 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
4890 int i;
4891 struct gpu_stmt *stmts;
4893 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
4894 if (!stmts)
4895 return NULL;
4897 for (i = 0; i < scop->pet->n_stmt; ++i) {
4898 struct gpu_stmt *s = &stmts[i];
4900 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
4901 s->stmt = scop->pet->stmts[i];
4902 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
4903 return free_stmts(stmts, i + 1);
4906 return stmts;
4909 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
4911 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
4913 struct gpu_gen *gen = user;
4915 return gen->print(p, gen->prog, gen->tree, &gen->types,
4916 gen->print_user);
4919 /* Generate CUDA code for "scop" and print it to "p".
4920 * After generating an AST for the transformed scop as explained below,
4921 * we call "gen->print" to print the AST in the desired output format
4922 * to "p".
4924 * If it turns out that it does not make sense to generate GPU code,
4925 * then we generate CPU code instead.
4927 * The GPU code is generated in a context where at least one
4928 * statement instance is executed. The corresponding guard (if any) is printed
4929 * around the entire generated GPU code, except for the declaration
4930 * of the arrays that are visible outside of the scop and that therefore
4931 * cannot be declared inside the body of any possible guard.
4933 * We first compute a schedule that respects the dependences
4934 * of the original program and select the outermost bands
4935 * of tilable dimensions that have at least one parallel loop.
4936 * If the --load-schedule is specified, then the loaded schedule
4937 * is used instead of a computed schedule.
4939 * Each of these bands B is then tiled according to "tile" sizes, resulting
4940 * in two nested bands, with a kernel marker on top
4948 * We then split off at most 2 parallel dimensions from the T band and
4949 * at most 3 parallel dimension from the P band
4954 * T1
4956 * T2
4958 * P1
4960 * P2
4962 * A filter is introduced in front of T1 that maps the domain instances
4963 * to block identifiers. Similarly, a filter is introduced in front of P1
4964 * that maps the domain instances to thread identifiers.
4966 * For each iteration of the T2 band and for each array, we compute
4967 * the array elements accessed by that iteration, construct a rectangular
4968 * box around it and shift it to the origin. The result is used
4969 * as shared memory for the array.
4971 * Copying and synchronization statements are added to this schedule tree.
4972 * In principle, these are added in front of the P1 band, but some of
4973 * them may get hoisted up to higher levels.
4975 * The entire AST is then generated from the single resulting schedule tree.
4976 * During the generation the subtrees at kernel nodes (K) are saved
4977 * aside and replaced by kernel calls. The result is printed as host code
4978 * while the saved subtrees are printed as device code.
4980 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
4981 struct gpu_gen *gen, struct ppcg_scop *scop,
4982 struct ppcg_options *options)
4984 struct gpu_prog *prog;
4985 isl_ctx *ctx;
4986 isl_set *context, *guard;
4987 isl_schedule *schedule;
4988 int any_permutable;
4990 if (!scop)
4991 return isl_printer_free(p);
4993 ctx = isl_printer_get_ctx(p);
4994 prog = gpu_prog_alloc(ctx, scop);
4995 if (!prog)
4996 return isl_printer_free(p);
4998 context = isl_set_copy(prog->context);
4999 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5000 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5002 gen->prog = prog;
5003 schedule = get_schedule(gen);
5005 any_permutable = has_any_permutable_node(schedule);
5006 if (any_permutable < 0 || !any_permutable) {
5007 isl_set_free(context);
5008 isl_set_free(guard);
5009 if (any_permutable < 0)
5010 p = isl_printer_free(p);
5011 else
5012 p = print_cpu(p, scop, options);
5013 isl_schedule_free(schedule);
5014 } else {
5015 schedule = map_to_device(gen, schedule);
5016 gen->tree = generate_code(gen, schedule);
5017 p = ppcg_print_exposed_declarations(p, prog->scop);
5018 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5019 isl_ast_node_free(gen->tree);
5022 gpu_prog_free(prog);
5024 return p;
5027 /* Wrapper around generate for use as a ppcg_transform callback.
5029 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5030 struct ppcg_scop *scop, void *user)
5032 struct gpu_gen *gen = user;
5034 return generate(p, gen, scop, gen->options);
5037 /* Transform the code in the file called "input" by replacing
5038 * all scops by corresponding GPU code and write the results to "out".
5040 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5041 struct ppcg_options *options,
5042 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5043 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5044 struct gpu_types *types, void *user), void *user)
5046 struct gpu_gen gen;
5047 int r;
5048 int i;
5050 gen.ctx = ctx;
5051 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5052 gen.options = options;
5053 gen.kernel_id = 0;
5054 gen.print = print;
5055 gen.print_user = user;
5056 gen.types.n = 0;
5057 gen.types.name = NULL;
5059 if (options->debug->dump_sizes) {
5060 isl_space *space = isl_space_params_alloc(ctx, 0);
5061 gen.used_sizes = isl_union_map_empty(space);
5064 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5066 if (options->debug->dump_sizes) {
5067 isl_union_map_dump(gen.used_sizes);
5068 isl_union_map_free(gen.used_sizes);
5071 isl_union_map_free(gen.sizes);
5072 for (i = 0; i < gen.types.n; ++i)
5073 free(gen.types.name[i]);
5074 free(gen.types.name);
5076 return r;
5079 /* Compute the set of inner array elements that may have their values
5080 * preserved by "prog". In particular, collect the array elements of
5081 * arrays that are not local to "prog" and remove those elements that
5082 * are definitely killed or definitely written by "prog".
5084 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5086 int i;
5087 isl_union_set *may_persist, *killed;
5088 isl_union_map *must_kill;
5090 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5091 for (i = 0; i < prog->n_array; ++i) {
5092 isl_set *extent;
5094 if (prog->array[i].local)
5095 continue;
5097 extent = isl_set_copy(prog->array[i].extent);
5098 may_persist = isl_union_set_add_set(may_persist, extent);
5101 may_persist = isl_union_set_intersect_params(may_persist,
5102 isl_set_copy(prog->context));
5103 may_persist = isl_union_set_apply(may_persist,
5104 isl_union_map_copy(prog->to_inner));
5105 must_kill = isl_union_map_copy(prog->tagged_must_kill);
5106 killed = isl_union_map_range(must_kill);
5107 must_kill = isl_union_map_copy(prog->must_write);
5108 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
5110 may_persist = isl_union_set_subtract(may_persist, killed);
5111 return may_persist;
5114 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5116 struct gpu_prog *prog;
5117 isl_space *space;
5118 isl_map *id;
5120 if (!scop)
5121 return NULL;
5123 prog = isl_calloc_type(ctx, struct gpu_prog);
5124 assert(prog);
5126 prog->ctx = ctx;
5127 prog->scop = scop;
5128 prog->context = isl_set_copy(scop->context);
5129 prog->n_stmts = scop->pet->n_stmt;
5130 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5131 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5132 space = isl_union_map_get_space(prog->any_to_outer);
5133 space = isl_space_set_from_params(space);
5134 space = isl_space_add_dims(space, isl_dim_set, 1);
5135 space = isl_space_map_from_set(space);
5136 id = isl_map_identity(space);
5137 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
5138 prog->stmts = extract_stmts(ctx, scop,
5139 prog->context, prog->any_to_outer);
5140 prog->read = isl_union_map_copy(scop->reads);
5141 prog->may_write = isl_union_map_copy(scop->may_writes);
5142 prog->must_write = isl_union_map_copy(scop->must_writes);
5143 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
5144 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
5145 prog->to_outer = isl_union_map_copy(prog->to_inner);
5146 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5148 if (!prog->stmts)
5149 return gpu_prog_free(prog);
5151 if (collect_array_info(prog) < 0)
5152 return gpu_prog_free(prog);
5153 prog->may_persist = compute_may_persist(prog);
5155 return prog;
5158 void *gpu_prog_free(struct gpu_prog *prog)
5160 if (!prog)
5161 return NULL;
5162 free_array_info(prog);
5163 free_stmts(prog->stmts, prog->n_stmts);
5164 isl_union_map_free(prog->any_to_outer);
5165 isl_union_map_free(prog->to_outer);
5166 isl_union_map_free(prog->to_inner);
5167 isl_union_map_free(prog->read);
5168 isl_union_map_free(prog->may_write);
5169 isl_union_map_free(prog->must_write);
5170 isl_union_map_free(prog->tagged_must_kill);
5171 isl_union_map_free(prog->array_order);
5172 isl_union_set_free(prog->may_persist);
5173 isl_set_free(prog->context);
5174 free(prog);
5175 return NULL;