gpu_group.c: join_groups: improve error handling
[ppcg.git] / gpu.c
bloba4ad78c6660c4bdd39d38f4fcec5316bfc5859e8
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. If the array has compound
1250 * elements then we skipped the construction of array reference groups.
1252 * The resulting sizes may be functions that are nowhere defined
1253 * in case the access function cannot possibly access anything inside
1254 * the kernel for some reason. If so, they are replaced by the zero
1255 * function. Since the access function cannot actually access anything,
1256 * there is no harm in printing the array sizes as zero.
1258 static void localize_bounds(struct ppcg_kernel *kernel,
1259 __isl_keep isl_set *host_domain)
1261 int i, j;
1262 isl_set *context;
1264 context = isl_set_copy(host_domain);
1265 context = isl_set_params(context);
1267 for (i = 0; i < kernel->n_array; ++i) {
1268 struct gpu_local_array_info *local = &kernel->array[i];
1269 isl_pw_aff_list *bound;
1270 int n_index;
1272 if (local->n_group == 0 && !local->array->has_compound_element)
1273 continue;
1275 n_index = local->array->n_index;
1276 bound = isl_pw_aff_list_alloc(kernel->ctx, n_index);
1278 for (j = 0; j < n_index; ++j) {
1279 isl_pw_aff *pwaff;
1280 int empty;
1282 pwaff = isl_pw_aff_copy(local->array->bound[j]);
1283 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1284 empty = isl_pw_aff_is_empty(pwaff);
1285 if (empty < 0)
1286 pwaff = isl_pw_aff_free(pwaff);
1287 else if (empty)
1288 pwaff = set_universally_zero(pwaff);
1289 bound = isl_pw_aff_list_add(bound, pwaff);
1292 local->n_index = n_index;
1293 local->bound = bound;
1295 isl_set_free(context);
1298 /* Create the array of gpu_local_array_info structures "array"
1299 * inside "kernel". The number of elements in this array is
1300 * the same as the number of arrays in "prog".
1301 * Initialize the "array" field of each local array to point
1302 * to the corresponding array in "prog".
1304 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1305 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1307 int i;
1308 isl_ctx *ctx;
1310 ctx = isl_set_get_ctx(prog->context);
1311 kernel->array = isl_calloc_array(ctx,
1312 struct gpu_local_array_info, prog->n_array);
1313 if (!kernel->array)
1314 return ppcg_kernel_free(kernel);
1315 kernel->n_array = prog->n_array;
1317 for (i = 0; i < prog->n_array; ++i)
1318 kernel->array[i].array = &prog->array[i];
1320 return kernel;
1323 /* Find the element in gen->stmt that has the given "id".
1324 * Return NULL if no such gpu_stmt can be found.
1326 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1328 int i;
1330 for (i = 0; i < prog->n_stmts; ++i) {
1331 if (id == prog->stmts[i].id)
1332 break;
1335 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1338 void ppcg_kernel_stmt_free(void *user)
1340 int i;
1341 struct ppcg_kernel_stmt *stmt = user;
1343 if (!stmt)
1344 return;
1346 switch (stmt->type) {
1347 case ppcg_kernel_copy:
1348 isl_ast_expr_free(stmt->u.c.index);
1349 isl_ast_expr_free(stmt->u.c.local_index);
1350 break;
1351 case ppcg_kernel_domain:
1352 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1353 break;
1354 case ppcg_kernel_sync:
1355 break;
1358 free(stmt);
1361 /* Return the gpu_stmt_access in the list "accesses" that corresponds
1362 * to "ref_id".
1364 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1365 __isl_keep isl_id *ref_id)
1367 struct gpu_stmt_access *access;
1369 for (access = accesses; access; access = access->next)
1370 if (access->ref_id == ref_id)
1371 return access;
1373 return NULL;
1376 /* Return the index of the array called "name" in the list of arrays.
1378 static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1380 int i;
1382 for (i = 0; i < kernel->n_array; ++i)
1383 if (!strcmp(name, kernel->array[i].array->name))
1384 return i;
1386 return -1;
1389 /* Internal data structure for the index and AST expression transformation
1390 * callbacks for pet_stmt_build_ast_exprs.
1392 * "kernel" is the kernel for which are computing AST expressions and
1393 * may be NULL if we are not inside a kernel.
1394 * "accesses" is the list of gpu_stmt_access in the statement.
1395 * "iterator_map" expresses the statement iterators in terms of
1396 * the AST loop iterators.
1397 * "sched2shared" expresses the outer shared_schedule_dim dimensions of
1398 * the kernel schedule in terms of the AST loop iterators and
1399 * may be NULL if we are not inside a kernel.
1401 * The following fields are set in transform_index and used in transform_expr.
1402 * "array" is the array that is being accessed.
1403 * "global" is set if the global array is accessed (rather than
1404 * shared/private memory).
1405 * "local_array" refers to information on the array specialized
1406 * to the current kernel.
1408 struct ppcg_transform_data {
1409 struct ppcg_kernel *kernel;
1410 struct gpu_stmt_access *accesses;
1411 isl_pw_multi_aff *iterator_map;
1412 isl_pw_multi_aff *sched2shared;
1414 struct gpu_array_info *array;
1415 int global;
1416 struct gpu_local_array_info *local_array;
1419 /* Return a pointer to the gpu_array_ref_group in "local"
1420 * that contains the reference "access".
1421 * Return NULL if no such group can be found.
1423 static struct gpu_array_ref_group *find_ref_group(
1424 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1426 int i, j;
1428 for (i = 0; i < local->n_group; ++i) {
1429 struct gpu_array_ref_group *group = local->groups[i];
1431 for (j = 0; j < group->n_ref; ++j)
1432 if (group->refs[j] == access)
1433 return group;
1436 return NULL;
1439 /* Index transformation callback for pet_stmt_build_ast_exprs.
1441 * "index" expresses the array indices in terms of statement iterators
1443 * We first reformulate "index" in terms of the AST loop iterators.
1444 * Then we check if we are accessing the global array or
1445 * a shared/private copy. In particular, if we are not inside a kernel
1446 * then we must be accessing a global array.
1447 * In the former case, we simply return
1448 * the updated index. If "index" is an affine expression rather
1449 * than an array access, then we also return the updated index here.
1451 * If no reference groups have been computed for the array,
1452 * then we can only be accessing the global array.
1454 * Otherwise, we apply the tiling to the index.
1455 * This tiling is of the form
1457 * [D -> A] -> T
1459 * where D corresponds to the outer group->depth dimensions of
1460 * the kernel schedule.
1461 * The index is of the form
1463 * L -> A
1465 * We update the tiling to refer to the AST loop iterators
1467 * [L -> A] -> T
1469 * and modify index to keep track of those iterators
1471 * L -> [L -> A]
1473 * Combining these two yields a tiled index expression in terms
1474 * of the AST loop iterators
1476 * L -> T
1478 static __isl_give isl_multi_pw_aff *transform_index(
1479 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
1480 void *user)
1482 struct ppcg_transform_data *data = user;
1483 struct gpu_stmt_access *access;
1484 struct gpu_array_ref_group *group;
1485 struct gpu_array_tile *tile;
1486 isl_pw_multi_aff *iterator_map;
1487 int i;
1488 int dim;
1489 const char *name;
1490 isl_space *space;
1491 isl_multi_pw_aff *tiling;
1492 isl_pw_multi_aff *pma;
1493 isl_multi_pw_aff *mpa;
1494 isl_pw_multi_aff *sched2depth;
1496 data->array = NULL;
1498 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
1499 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
1501 if (!data->kernel)
1502 return index;
1504 access = find_access(data->accesses, ref_id);
1505 if (!access)
1506 return index;
1507 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1508 return index;
1510 name = get_outer_array_name(access->access);
1511 i = find_array_index(data->kernel, name);
1512 if (i < 0)
1513 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
1514 "cannot find array",
1515 return isl_multi_pw_aff_free(index));
1516 data->local_array = &data->kernel->array[i];
1517 data->array = data->local_array->array;
1519 group = find_ref_group(data->local_array, access);
1520 if (!group) {
1521 data->global = 1;
1522 return index;
1525 tile = group->private_tile;
1526 if (!tile)
1527 tile = group->shared_tile;
1528 data->global = !tile;
1529 if (!tile)
1530 return index;
1532 space = isl_space_range(isl_multi_pw_aff_get_space(index));
1533 space = isl_space_map_from_set(space);
1534 pma = isl_pw_multi_aff_identity(space);
1535 sched2depth = isl_pw_multi_aff_copy(data->sched2shared);
1536 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1537 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1538 group->depth, dim - group->depth);
1539 pma = isl_pw_multi_aff_product(sched2depth, pma);
1540 tiling = isl_multi_pw_aff_from_multi_aff(
1541 isl_multi_aff_copy(tile->tiling));
1542 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1544 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1545 space = isl_space_map_from_set(space);
1546 mpa = isl_multi_pw_aff_identity(space);
1547 index = isl_multi_pw_aff_range_product(mpa, index);
1548 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1550 return index;
1553 /* Dereference "expr" by adding an index [0].
1554 * The original "expr" is assumed not to have any indices.
1556 * If "expr" is a member access, then the dereferencing needs
1557 * to be applied to the structure argument of this member access.
1559 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1561 isl_ctx *ctx;
1562 isl_ast_expr *arg0, *res;
1563 isl_ast_expr_list *list;
1565 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1566 if (!arg0)
1567 return isl_ast_expr_free(expr);
1568 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1569 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1570 isl_ast_expr *arg;
1572 arg = isl_ast_expr_get_op_arg(arg0, 0);
1573 arg = dereference(arg);
1574 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1575 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1577 return expr;
1579 isl_ast_expr_free(arg0);
1581 ctx = isl_ast_expr_get_ctx(expr);
1582 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1583 list = isl_ast_expr_list_from_ast_expr(res);
1584 res = isl_ast_expr_get_op_arg(expr, 0);
1585 res = isl_ast_expr_access(res, list);
1586 isl_ast_expr_free(expr);
1588 return res;
1591 /* Linearize the index expression "expr" based on the array bounds
1592 * of "array".
1594 * That is, transform expression
1596 * A[i_0][i_1]...[i_n]
1598 * to
1600 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1602 * where b_0, b_1, ..., b_n are the bounds on the array.
1604 * If the base of "expr" is a member access, then the linearization needs
1605 * to be applied to the structure argument of this member access.
1607 * In the base case, if "expr" has no arguments (other than the name of
1608 * the array), then we are passing an entire array to a function.
1609 * In this case, there is nothing to linearize.
1610 * Note that at this point an expression with no arguments can
1611 * only be an entire array because the scalar case and
1612 * the case of single struct are handled by the caller.
1614 * If the number of specified index expressions in "expr"
1615 * is smaller than the dimension of the accessed array,
1616 * then the missing i_j also do not appear in the linearized expression.
1617 * Furthermore, since such an expression does not refer to a single
1618 * element while the default linearized expression would refer to
1619 * a single element, we return the expression
1621 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
1623 * instead. Note that because of the special case handling above,
1624 * we can assume here that here that there is at least one index expression.
1626 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1627 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1629 int i, n;
1630 isl_ctx *ctx;
1631 isl_set *context;
1632 isl_ast_expr *arg0;
1633 isl_ast_expr *res;
1634 isl_ast_expr_list *list;
1635 isl_ast_build *build;
1637 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1638 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1639 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1640 isl_ast_expr *arg;
1642 arg = isl_ast_expr_get_op_arg(arg0, 0);
1643 arg = gpu_local_array_info_linearize_index(array, arg);
1644 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1645 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1647 return expr;
1649 isl_ast_expr_free(arg0);
1651 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1652 return expr;
1654 ctx = isl_ast_expr_get_ctx(expr);
1655 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
1656 build = isl_ast_build_from_context(context);
1658 n = isl_ast_expr_get_op_n_arg(expr);
1659 res = isl_ast_expr_get_op_arg(expr, 1);
1660 for (i = 1; i < array->n_index; ++i) {
1661 isl_pw_aff *bound_i;
1662 isl_ast_expr *expr_i;
1664 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
1665 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
1666 res = isl_ast_expr_mul(res, expr_i);
1668 if (i + 1 >= n)
1669 continue;
1670 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1671 res = isl_ast_expr_add(res, expr_i);
1674 isl_ast_build_free(build);
1676 if (1 + array->n_index > n) {
1677 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1678 } else {
1679 list = isl_ast_expr_list_from_ast_expr(res);
1680 res = isl_ast_expr_get_op_arg(expr, 0);
1681 res = isl_ast_expr_access(res, list);
1684 isl_ast_expr_free(expr);
1686 return res;
1689 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
1691 * If the AST expression refers to an array that is not accessed
1692 * at all, then this means the value of the expression is not used,
1693 * so we might as well print zero (NULL pointer) instead.
1695 * If the AST expression refers to a global scalar that is not
1696 * a read-only scalar, then its address was passed to the kernel and
1697 * we need to dereference it.
1699 * If the AST expression refers to an access to a global array,
1700 * then we linearize the access exploiting the bounds in data->local_array.
1702 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1703 __isl_keep isl_id *id, void *user)
1705 struct ppcg_transform_data *data = user;
1707 if (!data->array)
1708 return expr;
1709 if (!data->array->accessed) {
1710 isl_ctx *ctx;
1712 ctx = isl_ast_expr_get_ctx(expr);
1713 isl_ast_expr_free(expr);
1714 return isl_ast_expr_from_val(isl_val_zero(ctx));
1716 if (gpu_array_is_read_only_scalar(data->array))
1717 return expr;
1718 if (!data->global)
1719 return expr;
1720 if (data->array->n_index == 0)
1721 return dereference(expr);
1722 if (!data->array->linearize)
1723 return expr;
1725 return gpu_local_array_info_linearize_index(data->local_array, expr);
1728 /* This function is called for each instance of a user statement
1729 * in the kernel "kernel", identified by "gpu_stmt".
1730 * "kernel" may be NULL if we are not inside a kernel.
1732 * We attach a struct ppcg_kernel_stmt to the "node", containing
1733 * a computed AST expression for each access, through an annotation
1734 * with name "user".
1735 * These AST expressions are computed from iterator_map,
1736 * which expresses the domain
1737 * elements in terms of the generated loops, and sched2shared,
1738 * which expresses the outer shared_schedule_dim dimensions of
1739 * the kernel schedule computed by PPCG in terms of the generated loops.
1741 static __isl_give isl_ast_node *create_domain_leaf(
1742 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1743 __isl_keep isl_ast_build *build, struct gpu_stmt *gpu_stmt)
1745 struct ppcg_transform_data data;
1746 struct ppcg_kernel_stmt *stmt;
1747 isl_ctx *ctx;
1748 isl_id *id;
1749 isl_pw_multi_aff *sched2shared;
1750 isl_map *map;
1751 isl_pw_multi_aff *iterator_map;
1752 isl_union_map *schedule;
1754 if (!node)
1755 return NULL;
1756 ctx = isl_ast_node_get_ctx(node);
1758 stmt = isl_calloc_type(ctx, struct ppcg_kernel_stmt);
1759 if (!stmt)
1760 return isl_ast_node_free(node);
1762 schedule = isl_ast_build_get_schedule(build);
1763 map = isl_map_reverse(isl_map_from_union_map(schedule));
1764 iterator_map = isl_pw_multi_aff_from_map(map);
1765 if (kernel)
1766 sched2shared = compute_sched_to_shared(kernel,
1767 isl_pw_multi_aff_copy(iterator_map));
1768 else
1769 sched2shared = NULL;
1771 stmt->type = ppcg_kernel_domain;
1772 stmt->u.d.stmt = gpu_stmt;
1774 data.kernel = kernel;
1775 data.accesses = stmt->u.d.stmt->accesses;
1776 data.iterator_map = iterator_map;
1777 data.sched2shared = sched2shared;
1778 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
1779 build, &transform_index, &data,
1780 &transform_expr, &data);
1782 isl_pw_multi_aff_free(iterator_map);
1783 isl_pw_multi_aff_free(sched2shared);
1785 id = isl_id_alloc(ctx, "user", stmt);
1786 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1787 return isl_ast_node_set_annotation(node, id);
1790 /* This function is called for each statement node in the AST
1791 * for copying to or from shared/private memory.
1792 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1793 * statement to the node.
1794 * The statement name is "read" or "write", depending on whether we are
1795 * reading from global memory or writing to global memory.
1797 * The schedule is of the form
1799 * type[D -> A] -> L
1801 * where D corresponds to the outer group->depth dimensions of
1802 * the kernel schedule, A to the global array and L to the outer
1803 * generated AST schedule.
1804 * We compute the inverse and strip off the type, resulting in
1806 * L -> [D -> A]
1808 * We combine this mapping with on the one hand the projection
1810 * [D -> A] -> A
1812 * and on the other hand the group tiling
1814 * [D -> A] -> T
1816 * resulting in
1818 * L -> A and L -> T
1820 * and store the corresponding expressions in stmt->index and stmt->local_index,
1821 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1823 static __isl_give isl_ast_node *create_access_leaf(struct ppcg_kernel *kernel,
1824 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1825 __isl_keep isl_ast_build *build)
1827 struct ppcg_kernel_stmt *stmt;
1828 struct gpu_array_tile *tile;
1829 isl_id *id;
1830 isl_ast_expr *expr;
1831 isl_space *space;
1832 isl_map *access;
1833 isl_pw_multi_aff *pma, *pma2;
1834 const char *type;
1836 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1837 if (!stmt)
1838 return isl_ast_node_free(node);
1840 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1841 type = isl_map_get_tuple_name(access, isl_dim_in);
1842 stmt->u.c.read = !strcmp(type, "read");
1843 access = isl_map_reverse(access);
1844 pma = isl_pw_multi_aff_from_map(access);
1845 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1847 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1848 space = isl_space_unwrap(space);
1849 pma2 = isl_pw_multi_aff_range_map(space);
1850 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1851 isl_pw_multi_aff_copy(pma));
1852 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1853 stmt->u.c.index = expr;
1855 tile = gpu_array_ref_group_tile(group);
1856 pma2 = isl_pw_multi_aff_from_multi_aff(
1857 isl_multi_aff_copy(tile->tiling));
1858 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1859 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1860 stmt->u.c.local_index = expr;
1862 stmt->u.c.array = group->array;
1863 stmt->u.c.local_array = group->local_array;
1864 stmt->type = ppcg_kernel_copy;
1866 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1867 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1868 return isl_ast_node_set_annotation(node, id);
1871 /* Create a synchronization ppcg_kernel_stmt and
1872 * attach it to the node "node" representing the synchronization.
1874 static __isl_give isl_ast_node *create_sync_leaf(
1875 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1876 __isl_keep isl_ast_build *build)
1878 struct ppcg_kernel_stmt *stmt;
1879 isl_id *id;
1881 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1882 if (!stmt)
1883 return isl_ast_node_free(node);
1885 stmt->type = ppcg_kernel_sync;
1886 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1887 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1888 return isl_ast_node_set_annotation(node, id);
1891 /* Internal data structure for at_domain.
1893 * "prog" represents the entire scop.
1894 * "kernel" points to the kernel to which the current schedule node
1895 * belongs. It is set by before_mark and reset by after_mark.
1896 * It may be NULL if we are outside any kernel.
1898 struct ppcg_at_domain_data {
1899 struct gpu_prog *prog;
1900 struct ppcg_kernel *kernel;
1903 /* This function is called for each instance of a user statement
1904 * in the kernel. This may be one of the original user statements
1905 * or a statement introduced by PPCG.
1907 * We assume that the original user statements only have a name
1908 * and no user pointer. The statements introduced by PPCG
1909 * on the other hand all have a user pointer.
1911 * If the user statement is one of the original user statements
1912 * (one with no user pointer), then we call create_domain_leaf. Otherwise,
1913 * we check if it is a copy or synchronization statement and
1914 * call the appropriate functions.
1915 * Statements that copy an array to/from the device do not need
1916 * any further treatment.
1918 static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
1919 __isl_keep isl_ast_build *build, void *user)
1921 struct ppcg_at_domain_data *data = user;
1922 isl_ast_expr *expr, *arg;
1923 isl_id *id;
1924 int is_sync;
1925 const char *name;
1926 void *p;
1928 expr = isl_ast_node_user_get_expr(node);
1929 arg = isl_ast_expr_get_op_arg(expr, 0);
1930 id = isl_ast_expr_get_id(arg);
1931 name = isl_id_get_name(id);
1932 p = isl_id_get_user(id);
1933 isl_ast_expr_free(expr);
1934 isl_ast_expr_free(arg);
1936 if (!p) {
1937 struct gpu_stmt *gpu_stmt;
1939 gpu_stmt = find_stmt(data->prog, id);
1940 isl_id_free(id);
1941 if (!gpu_stmt)
1942 isl_die(data->prog->ctx, isl_error_internal,
1943 "statement not found",
1944 return isl_ast_node_free(node));
1946 return create_domain_leaf(data->kernel, node, build, gpu_stmt);
1949 is_sync = gpu_tree_id_is_sync(id, data->kernel);
1950 isl_id_free(id);
1951 if (!prefixcmp(name, "to_device_") || !prefixcmp(name, "from_device_"))
1952 return node;
1953 if (is_sync < 0)
1954 return isl_ast_node_free(node);
1955 if (!strcmp(name, "read") || !strcmp(name, "write")) {
1956 struct gpu_array_ref_group *group = p;
1957 return create_access_leaf(data->kernel, group, node, build);
1959 if (!is_sync)
1960 isl_die(data->prog->ctx, isl_error_internal,
1961 "unknown statement type",
1962 return isl_ast_node_free(node));
1963 return create_sync_leaf(data->kernel, node, build);
1966 /* Given a set of wrapped references "ref", return the corresponding
1967 * access relations based on the tagged access relations "tagged".
1969 * The elements of "ref" are of the form
1971 * [D -> R]
1973 * with D an iteration domains and R a reference.
1974 * The elements of "tagged" are of the form
1976 * [D -> R] -> A
1978 * with A an array.
1980 * Extend "tagged" to include the iteration domain in the range, i.e.,
1982 * [D -> R] -> [D -> A]
1984 * apply the result to "ref" and then unwrap the resulting set
1985 * to obtain relations of the form
1987 * D -> A
1989 static __isl_give isl_union_map *wrapped_reference_to_access(
1990 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
1992 isl_union_map *tag2access;
1994 tag2access = isl_union_map_copy(tagged);
1995 tag2access = isl_union_map_universe(tag2access);
1996 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
1997 tag2access = isl_union_map_domain_map(tag2access);
1998 tag2access = isl_union_map_range_product(tag2access, tagged);
2000 ref = isl_union_set_coalesce(ref);
2001 ref = isl_union_set_apply(ref, tag2access);
2003 return isl_union_set_unwrap(ref);
2006 /* Given an access relation "access" from one or more array reference groups,
2007 * remove those reads if ("read" is 1) or writes (if "read" is 0)
2008 * that are only needed to communicate data within
2009 * the same iteration of "sched".
2010 * "tagged" contains all tagged access relations to all
2011 * the array reference groups accessed by "access" from statement
2012 * instances scheduled by "sched".
2014 * If the access is a read then it is either an element of
2016 * live_in union (range flow)
2018 * where live_in and flow may be overapproximations, or
2019 * it reads an uninitialized value (that is not live-in because
2020 * there is an intermediate kill) or it reads a value that was
2021 * written within the same (compound) statement instance.
2022 * If the access is a write then it is either an element of
2024 * live_out union (domain flow)
2026 * or it writes a value that is never read (and is not live-out
2027 * because of an intermediate kill) or only
2028 * within the same (compound) statement instance.
2029 * In both cases, the access relation is also a subset of
2030 * the group access relation.
2032 * The cases where an uninitialized value is read or a value is written
2033 * that is never read or where the dataflow occurs within a statement
2034 * instance are also considered local and may also be removed.
2036 * Essentially, we compute the intersection of "access" with either
2038 * live_in union (range non-local-flow)
2040 * or
2042 * live_out union (domain non-local-flow)
2044 * We first construct a relation "local"
2046 * [[D -> R] -> [D' -> R']]
2048 * of pairs of domain iterations accessing the reference group
2049 * and references in the group that are coscheduled by "sched".
2051 * If this relation does not intersect the dataflow dependences,
2052 * then there is nothing we can possibly remove, unless the dataflow
2053 * dependences themselves only relate a subset of the accesses.
2054 * In particular, the accesses may not be involved in any dataflow
2055 * dependences, either because they are uninitialized reads/dead writes
2056 * or because the dataflow occurs inside a statement instance.
2058 * Since the computation below may break up the access relation
2059 * into smaller pieces, we only perform the intersection with
2060 * the non-local dependent accesses if the local pairs
2061 * intersect the dataflow dependences. Otherwise, we intersect
2062 * with the universe of the non-local dependent accesses.
2063 * This should at least remove accesses from statements that
2064 * do not participate in any dependences.
2066 * In particular, we remove the "local" dataflow dependences from
2067 * the set of all dataflow dependences.
2068 * Note that if the potential dataflow dependences are an overapproximation
2069 * of the actual dataflow dependences, then the result remains an
2070 * overapproximation of the non-local dataflow dependences.
2071 * Copying to/from global memory is only needed for the references
2072 * in the domain/range of the result or for accesses that are live out/in
2073 * for the entire scop.
2075 * We therefore map the domain/range of the "external" relation
2076 * to the corresponding access relation and take the union with
2077 * the live out/in relation.
2079 static __isl_give isl_union_map *remove_local_accesses(
2080 struct gpu_prog *prog, __isl_take isl_union_map *tagged,
2081 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2082 int read)
2084 int empty;
2085 isl_union_pw_multi_aff *tagger;
2086 isl_union_set *domain;
2087 isl_union_map *local, *external;
2088 isl_union_set *tag_set;
2090 if (isl_union_map_is_empty(access)) {
2091 isl_union_map_free(sched);
2092 isl_union_map_free(tagged);
2093 return access;
2096 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2097 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2098 tagger = isl_union_pw_multi_aff_intersect_domain(tagger, domain);
2099 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2101 local = isl_union_map_apply_range(sched,
2102 isl_union_map_reverse(isl_union_map_copy(sched)));
2103 local = isl_union_map_intersect(local,
2104 isl_union_map_copy(prog->scop->tagged_dep_flow));
2106 empty = isl_union_map_is_empty(local);
2108 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2109 external = isl_union_map_intersect_params(external,
2110 isl_set_copy(prog->scop->context));
2111 external = isl_union_map_subtract(external, local);
2113 if (read) {
2114 tag_set = isl_union_map_range(external);
2115 external = wrapped_reference_to_access(tag_set, tagged);
2116 external = isl_union_map_union(external,
2117 isl_union_map_copy(prog->scop->live_in));
2118 } else {
2119 tag_set = isl_union_map_domain(external);
2120 external = wrapped_reference_to_access(tag_set, tagged);
2121 external = isl_union_map_union(external,
2122 isl_union_map_copy(prog->scop->live_out));
2125 if (empty < 0)
2126 external = isl_union_map_free(external);
2127 else if (empty)
2128 external = isl_union_map_universe(external);
2130 access = isl_union_map_intersect(access, external);
2132 return access;
2135 /* Given an access relation "access" from "group", remove those reads
2136 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2137 * communicate data within the same iteration of the schedule at the
2138 * position where the copying of the group is inserted.
2139 * "node" points to this position, i.e., the depth at "node"
2140 * is equal to group->depth.
2142 * We extract a schedule that picks out the iterations of the outer
2143 * group->depth dimensions and call remove_local_accesses.
2145 static __isl_give isl_union_map *remove_local_accesses_group(
2146 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2147 __isl_take isl_union_map *access, __isl_keep isl_schedule_node *node,
2148 int read)
2150 isl_union_map *sched, *tagged;
2152 if (isl_union_map_is_empty(access))
2153 return access;
2155 tagged = group_tagged_access_relation(group);
2156 sched = isl_schedule_node_get_prefix_schedule_relation(node);
2158 return remove_local_accesses(kernel->prog, tagged, access, sched, read);
2161 /* This function is called before the AST generator starts traversing
2162 * the schedule subtree of a node with mark "mark".
2164 * If the mark is called "kernel", store the kernel pointer in data->kernel
2165 * for use in at_domain.
2167 static int before_mark(__isl_keep isl_id *mark,
2168 __isl_keep isl_ast_build *build, void *user)
2170 struct ppcg_at_domain_data *data = user;
2172 if (!mark)
2173 return -1;
2174 if (!strcmp(isl_id_get_name(mark), "kernel"))
2175 data->kernel = isl_id_get_user(mark);
2176 return 0;
2179 /* This function is called after the AST generator has finished traversing
2180 * the schedule subtree of a mark node. "node" points to the corresponding
2181 * mark AST node.
2183 * If the mark is called "kernel", then replace "node" by a user node
2184 * that "calls" the kernel, representing the launch of the kernel.
2185 * The original "node" is stored inside the kernel object so that
2186 * it can be used to print the device code.
2187 * Note that this assumes that a kernel is only launched once.
2188 * Also clear data->kernel.
2190 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2191 __isl_keep isl_ast_build *build, void *user)
2193 isl_ctx *ctx;
2194 isl_id *id;
2195 isl_ast_expr *expr;
2196 isl_ast_expr_list *list;
2197 struct ppcg_kernel *kernel;
2198 struct ppcg_at_domain_data *data = user;
2200 ctx = isl_ast_node_get_ctx(node);
2201 id = isl_ast_node_mark_get_id(node);
2202 if (!id)
2203 return isl_ast_node_free(node);
2204 if (strcmp(isl_id_get_name(id), "kernel") || !data->kernel) {
2205 isl_id_free(id);
2206 return node;
2208 kernel = data->kernel;
2209 data->kernel = NULL;
2210 kernel->space = isl_ast_build_get_schedule_space(build);
2211 kernel->tree = isl_ast_node_mark_get_node(node);
2212 isl_ast_node_free(node);
2214 expr = isl_ast_expr_from_id(isl_id_copy(id));
2215 list = isl_ast_expr_list_alloc(ctx, 0);
2216 expr = isl_ast_expr_call(expr, list);
2217 node = isl_ast_node_alloc_user(expr);
2218 node = isl_ast_node_set_annotation(node, id);
2220 return node;
2223 static int update_depth(__isl_keep isl_schedule_node *node, void *user)
2225 int *depth = user;
2226 int node_depth;
2228 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2229 return 1;
2230 node_depth = isl_schedule_node_get_schedule_depth(node);
2231 if (node_depth > *depth)
2232 *depth = node_depth;
2234 return 0;
2237 /* Use isl to generate code for both the host and the device
2238 * from "schedule".
2239 * The device code is marked by "kernel" mark nodes in the schedule tree,
2240 * containing a pointer to a ppcg_kernel object.
2241 * The returned AST only contains the AST for the host code.
2242 * The ASTs for the device code are embedded in ppcg_kernel objects
2243 * attached to the leaf nodes that call "kernel".
2245 static __isl_give isl_ast_node *generate_code(struct gpu_gen *gen,
2246 __isl_take isl_schedule *schedule)
2248 struct ppcg_at_domain_data data;
2249 isl_ast_build *build;
2250 isl_ast_node *tree;
2251 isl_id_list *iterators;
2252 int depth;
2254 data.prog = gen->prog;
2255 data.kernel = NULL;
2257 depth = 0;
2258 if (isl_schedule_foreach_schedule_node(schedule, &update_depth,
2259 &depth) < 0)
2260 return NULL;
2261 build = isl_ast_build_alloc(gen->prog->ctx);
2262 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2263 build = isl_ast_build_set_iterators(build, iterators);
2264 build = isl_ast_build_set_at_each_domain(build, &at_domain, &data);
2265 build = isl_ast_build_set_before_each_mark(build, &before_mark, &data);
2266 build = isl_ast_build_set_after_each_mark(build, &after_mark, &data);
2267 if (gen->prog->scop->options->debug->dump_final_schedule)
2268 isl_schedule_dump(schedule);
2269 tree = isl_ast_build_node_from_schedule(build, schedule);
2270 isl_ast_build_free(build);
2272 return tree;
2275 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2277 if (!str)
2278 return NULL;
2279 return isl_union_map_read_from_str(ctx, str);
2282 /* Can "node" be tiled and then mapped to block and thread identifiers?
2283 * That is, is it permutable with at least one coincident dimension?
2285 static int is_permutable(__isl_keep isl_schedule_node *node)
2287 if (!node)
2288 return -1;
2290 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
2291 return 0;
2292 if (!isl_schedule_node_band_get_permutable(node))
2293 return 0;
2294 if (isl_schedule_node_band_n_member(node) < 1)
2295 return 0;
2296 if (!isl_schedule_node_band_member_get_coincident(node, 0))
2297 return 0;
2299 return 1;
2302 /* A isl_schedule_foreach_schedule_node callback
2303 * for setting *any_permutable and aborting the search
2304 * if "node" is a permutable band with coincident dimensions.
2305 * Otherwise, continue searching.
2307 static int set_permutable(__isl_keep isl_schedule_node *node, void *user)
2309 int *any_permutable = user;
2310 int permutable;
2312 permutable = is_permutable(node);
2313 if (permutable < 0)
2314 return -1;
2315 if (!permutable)
2316 return 1;
2318 *any_permutable = 1;
2320 return -1;
2323 /* Does "schedule" contain any permutable band with at least one coincident
2324 * member?
2326 static int has_any_permutable_node(__isl_keep isl_schedule *schedule)
2328 int any_permutable = 0;
2330 if (isl_schedule_foreach_schedule_node(schedule, &set_permutable,
2331 &any_permutable) < 0 &&
2332 !any_permutable)
2333 return -1;
2335 return any_permutable;
2338 /* Is "node" a leaf or can it be tiled and then mapped to
2339 * block and thread identifiers?
2341 static int is_leaf_or_tilable(__isl_keep isl_schedule_node *node)
2343 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
2344 return 1;
2345 return is_permutable(node);
2348 /* Is "node" the outermost node in its branch that can be tiled
2349 * and then mapped to block and thread identifiers?
2350 * If there are no such nodes in the branch and if "node" is a leaf,
2351 * then it is accepted too.
2353 static int is_outer_tilable(__isl_keep isl_schedule_node *node)
2355 int tilable;
2356 isl_schedule_node *ancestor;
2358 tilable = is_leaf_or_tilable(node);
2359 if (tilable < 0)
2360 return -1;
2361 if (!tilable)
2362 return 0;
2364 tilable = 0;
2365 ancestor = isl_schedule_node_copy(node);
2366 while (isl_schedule_node_has_parent(ancestor)) {
2367 ancestor = isl_schedule_node_parent(ancestor);
2369 tilable = is_permutable(ancestor);
2370 if (tilable < 0 || tilable)
2371 break;
2374 isl_schedule_node_free(ancestor);
2375 return tilable < 0 ? -1 : !tilable;
2378 /* Collect the references to all writes in "group".
2379 * Each reference is represented by a universe set in a space
2381 * [S[i,j] -> R[]]
2383 * with S[i,j] the statement instance space and R[] the array reference.
2385 static __isl_give isl_union_set *group_tagged_writes(
2386 struct gpu_array_ref_group *group)
2388 int i;
2389 isl_space *space;
2390 isl_union_set *writes;
2392 space = isl_map_get_space(group->access);
2393 writes = isl_union_set_empty(space);
2394 for (i = 0; i < group->n_ref; ++i) {
2395 isl_space *space;
2396 isl_set *writes_i;
2398 if (!group->refs[i]->write)
2399 continue;
2401 space = isl_map_get_space(group->refs[i]->tagged_access);
2402 space = isl_space_domain(space);
2403 writes_i = isl_set_universe(space);
2404 writes = isl_union_set_add_set(writes, writes_i);
2407 return writes;
2410 /* Is there any write access in "group" that requires synchronization
2411 * on a write to global memory?
2412 * We currently take into account all writes that would require
2413 * synchronization at the thread level depth, but if the copying
2414 * for this group is performed at an outer level, then we do not
2415 * actually need to take into account dependences at intermediate levels.
2417 static int any_sync_writes_in_group(struct ppcg_kernel *kernel,
2418 struct gpu_array_ref_group *group)
2420 isl_union_set *writes;
2421 int empty, disjoint;
2423 empty = isl_union_set_is_empty(kernel->sync_writes);
2424 if (empty < 0)
2425 return -1;
2426 if (empty)
2427 return 0;
2429 writes = group_tagged_writes(group);
2430 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2431 isl_union_set_free(writes);
2433 return disjoint < 0 ? -1 : !disjoint;
2436 /* Collect the references to all writes in "kernel" that write directly
2437 * to global or shared memory, i.e., that are not mapped to private memory.
2438 * Each reference is represented by a universe set in a space
2440 * [S[i,j] -> R[]]
2442 * with S[i,j] the statement instance space and R[] the array reference.
2444 static __isl_give isl_union_set *collect_non_private_tagged_writes(
2445 struct ppcg_kernel *kernel)
2447 isl_union_set *writes;
2448 int i, j;
2450 writes = isl_union_set_empty(isl_union_set_get_space(kernel->arrays));
2452 for (i = 0; i < kernel->n_array; ++i) {
2453 struct gpu_local_array_info *array = &kernel->array[i];
2455 for (j = 0; j < array->n_group; ++j) {
2456 struct gpu_array_ref_group *group = array->groups[j];
2457 isl_union_set *writes_ij;
2459 if (!group->write)
2460 continue;
2461 if (group->private_tile)
2462 continue;
2463 writes_ij = group_tagged_writes(group);
2464 writes = isl_union_set_union(writes, writes_ij);
2468 return writes;
2471 /* Are there any direct writes to global memory that require
2472 * synchronization?
2474 static int any_global_or_shared_sync_writes(struct ppcg_kernel *kernel)
2476 isl_union_set *writes;
2477 int empty, disjoint;
2479 empty = isl_union_set_is_empty(kernel->sync_writes);
2480 if (empty < 0)
2481 return -1;
2482 if (empty)
2483 return 0;
2485 writes = collect_non_private_tagged_writes(kernel);
2486 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2487 isl_union_set_free(writes);
2489 return disjoint < 0 ? -1 : !disjoint;
2492 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
2493 * from the elements in "tile_size".
2495 static __isl_give isl_multi_val *construct_band_tiles_sizes(
2496 __isl_keep isl_schedule_node *node, int *tile_size)
2498 int i, n;
2499 isl_ctx *ctx;
2500 isl_space *space;
2501 isl_multi_val *mv;
2503 if (!node)
2504 return NULL;
2506 ctx = isl_schedule_node_get_ctx(node);
2507 space = isl_schedule_node_band_get_space(node);
2508 n = isl_schedule_node_band_n_member(node);
2509 mv = isl_multi_val_zero(space);
2510 for (i = 0; i < n; ++i) {
2511 isl_val *v;
2513 v = isl_val_int_from_si(ctx, tile_size[i]);
2514 mv = isl_multi_val_set_val(mv, i, v);
2517 return mv;
2520 /* Replace the partial schedule S of the band node "node" by
2522 * floor(S/f)
2524 * or
2526 * f * floor(S/f)
2528 * if scale_tile_loops is set, with f the integers in "factor".
2529 * The list that "factor" points to is assumed to contain at least
2530 * as many elements as the number of members in the band.
2532 static __isl_give isl_schedule_node *snap_band_to_sizes(
2533 __isl_take isl_schedule_node *node, int *factor,
2534 struct ppcg_options *options)
2536 isl_multi_val *mv;
2538 mv = construct_band_tiles_sizes(node, factor);
2539 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2540 if (options->scale_tile_loops)
2541 node = isl_schedule_node_band_scale(node,
2542 isl_multi_val_copy(mv));
2543 isl_multi_val_free(mv);
2545 return node;
2548 /* Tile "band" with tile size specified by "sizes".
2550 * Since the tile loops will be mapped to block ids, we forcibly
2551 * turn off tile loop scaling. We may want to enable tile loop scaling
2552 * at some later point, but then we would have to support the detection
2553 * of strides during the mapping to block ids.
2554 * Similarly, since the point loops will be mapped to thread ids,
2555 * we forcibly shift the point loops so that they start at zero.
2557 static __isl_give isl_schedule_node *tile_band(
2558 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2560 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2561 int scale_tile;
2562 int shift_point;
2564 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2565 isl_options_set_tile_scale_tile_loops(ctx, 0);
2566 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2567 isl_options_set_tile_shift_point_loops(ctx, 1);
2569 node = isl_schedule_node_band_tile(node, sizes);
2571 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2572 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2574 return node;
2577 /* Extract the set of parameter values and outer schedule dimensions
2578 * for which any statement instance
2579 * in the kernel inserted at "node" needs to be executed.
2580 * Intersect the set of parameter values derived from the host schedule
2581 * relation with the context of "prog".
2583 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2584 struct gpu_prog *prog)
2586 isl_union_map *schedule;
2587 isl_union_set *schedule_domain;
2588 isl_set *context;
2589 int empty;
2591 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2592 schedule_domain = isl_union_map_range(schedule);
2593 empty = isl_union_set_is_empty(schedule_domain);
2594 if (empty < 0) {
2595 isl_union_set_free(schedule_domain);
2596 return NULL;
2598 if (empty) {
2599 int depth;
2600 isl_space *space;
2602 space = isl_union_set_get_space(schedule_domain);
2603 isl_union_set_free(schedule_domain);
2604 space = isl_space_set_from_params(space);
2605 depth = isl_schedule_node_get_schedule_depth(node);
2606 space = isl_space_add_dims(space, isl_dim_set, depth);
2607 context = isl_set_empty(space);
2608 } else {
2609 context = isl_set_from_union_set(schedule_domain);
2611 context = isl_set_intersect_params(context,
2612 isl_set_copy(prog->context));
2614 return context;
2617 /* Return the set of outer array elements accessed by
2618 * by the statement instance in "domain" in "prog".
2620 static __isl_give isl_union_set *accessed_by_domain(
2621 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2623 isl_union_map *access;
2624 isl_union_set *arrays;
2626 access = isl_union_map_union(isl_union_map_copy(prog->read),
2627 isl_union_map_copy(prog->may_write));
2628 access = isl_union_map_intersect_domain(access, domain);
2629 arrays = isl_union_map_range(access);
2630 arrays = isl_union_set_apply(arrays,
2631 isl_union_map_copy(prog->to_outer));
2633 return arrays;
2636 /* Return the number of outer band members of the band node "node"
2637 * that are marked coincident.
2639 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2641 int i, n;
2643 n = isl_schedule_node_band_n_member(node);
2645 for (i = 0; i < n; ++i)
2646 if (!isl_schedule_node_band_member_get_coincident(node, i))
2647 break;
2649 return i;
2652 /* If the band node "node" has more than "n" members, then split off
2653 * the first "n" of them.
2655 static __isl_give isl_schedule_node *split_band(
2656 __isl_take isl_schedule_node *node, int n)
2658 int dim;
2660 dim = isl_schedule_node_band_n_member(node);
2661 if (n < dim)
2662 node = isl_schedule_node_band_split(node, n);
2664 return node;
2667 /* Scale a band node that may have been split by split_band.
2668 * "sizes" are the scaling factors for the original node.
2669 * "node" either points to the original band node, or the outer
2670 * of the two pieces after splitting.
2672 * If the number of elements in "node" is smaller than the number of
2673 * elements in "sizes", then some splitting has occurred and we split
2674 * "sizes" in the same way.
2676 static __isl_give isl_schedule_node *scale_band(
2677 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2679 int n, dim;
2681 n = isl_multi_val_dim(sizes, isl_dim_set);
2682 dim = isl_schedule_node_band_n_member(node);
2683 if (n > dim) {
2684 isl_multi_val *sizes2;
2686 sizes2 = isl_multi_val_copy(sizes);
2687 sizes = isl_multi_val_drop_dims(sizes,
2688 isl_dim_set, dim, n - dim);
2689 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2690 node = isl_schedule_node_child(node, 0);
2691 node = isl_schedule_node_band_scale(node, sizes2);
2692 node = isl_schedule_node_parent(node);
2695 return isl_schedule_node_band_scale(node, sizes);
2698 /* Return an isl_multi_aff, with as elements the parameters in "space"
2699 * that have the names specified by the elements in "names".
2700 * If (some of) these parameters do not already appear in "space",
2701 * then they are added first.
2703 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2704 __isl_keep isl_id_list *names)
2706 int i, n;
2707 isl_local_space *ls;
2708 isl_multi_aff *ma;
2710 if (!names)
2711 space = isl_space_free(space);
2713 n = isl_id_list_n_id(names);
2714 for (i = 0; i < n; ++i) {
2715 int pos;
2716 isl_id *id;
2718 id = isl_id_list_get_id(names, i);
2719 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2720 if (pos >= 0) {
2721 isl_id_free(id);
2722 continue;
2724 pos = isl_space_dim(space, isl_dim_param);
2725 space = isl_space_add_dims(space, isl_dim_param, 1);
2726 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2728 ma = isl_multi_aff_zero(isl_space_copy(space));
2729 ls = isl_local_space_from_space(isl_space_domain(space));
2730 for (i = 0; i < n; ++i) {
2731 int pos;
2732 isl_id *id;
2733 isl_aff *aff;
2735 id = isl_id_list_get_id(names, i);
2736 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2737 isl_id_free(id);
2738 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2739 isl_dim_param, pos);
2740 ma = isl_multi_aff_set_aff(ma, i, aff);
2742 isl_local_space_free(ls);
2744 return ma;
2747 /* Return constraints on the domain elements that equate a sequence of
2748 * parameters called "names", to the partial schedule
2749 * of "node" modulo the integers in "size".
2750 * The number of elements in the array "size" should be equal
2751 * to the number of elements in "names".
2752 * The number of members of the band node "node" should be smaller
2753 * than or equal to this number. If it is smaller, then the first
2754 * elements of "names" are equated to zero.
2756 static __isl_give isl_union_set *set_schedule_modulo(
2757 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
2758 int *size)
2760 int n, n_zero;
2761 isl_space *space;
2762 isl_multi_aff *ma;
2763 isl_multi_union_pw_aff *mupa, *mupa2;
2764 isl_multi_val *mv;
2765 isl_union_set *domain;
2767 if (!node)
2768 return NULL;
2769 n = isl_id_list_n_id(names);
2770 if (n == 0)
2771 return isl_schedule_node_get_universe_domain(node);
2772 n_zero = n - isl_schedule_node_band_n_member(node);
2774 mupa = isl_schedule_node_band_get_partial_schedule(node);
2775 mv = construct_band_tiles_sizes(node, size + n_zero);
2776 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
2778 space = isl_multi_union_pw_aff_get_space(mupa);
2779 space = isl_space_params(space);
2780 space = isl_space_set_from_params(space);
2781 space = isl_space_add_dims(space, isl_dim_set, n_zero);
2782 ma = isl_multi_aff_zero(space);
2784 domain = isl_schedule_node_get_universe_domain(node);
2785 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
2786 isl_union_set_copy(domain), ma);
2787 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
2789 space = isl_multi_union_pw_aff_get_space(mupa);
2790 ma = parameter_vector(space, names);
2792 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
2793 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
2795 return isl_multi_union_pw_aff_zero_union_set(mupa);
2798 /* Insert a context node at "node" introducing the block and thread
2799 * identifiers along with their bounds, which are stored in kernel->grid_size
2800 * and kernel->block_dim.
2801 * Note that the bounds on the block identifiers may implicitly impose
2802 * constraints on the parameters. A guard needs to be inserted
2803 * in the schedule tree to ensure that those bounds hold at "node".
2804 * This guard is inserted in insert_guard.
2806 static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
2807 __isl_take isl_schedule_node *node)
2809 isl_set *context;
2811 context = isl_set_universe(isl_set_get_space(kernel->context));
2813 context = add_bounded_parameters_dynamic(context,
2814 kernel->grid_size, kernel->block_ids);
2815 context = add_bounded_parameters(context,
2816 kernel->block_dim, kernel->thread_ids);
2818 node = isl_schedule_node_insert_context(node, context);
2820 return node;
2823 /* Insert a guard that eliminates kernel launches where the kernel
2824 * obviously does not have any work to do.
2826 * In particular, eliminate kernel launches where there are obviously
2827 * zero blocks.
2828 * Use the same block size constraints that are used to create the context
2829 * to ensure that all constraints implicit in the constructed context
2830 * are imposed by the guard.
2832 * Additionally, add other constraints that are valid
2833 * for each executed instance ("context"), as long as this does not result
2834 * in a disjunction.
2836 static __isl_give isl_schedule_node *insert_guard(
2837 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
2838 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
2840 unsigned nparam, n;
2841 isl_set *guard;
2842 isl_id_list *ids;
2844 guard = isl_set_copy(context);
2845 guard = isl_set_compute_divs(guard);
2846 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
2848 nparam = isl_set_dim(guard, isl_dim_param);
2849 n = isl_multi_pw_aff_dim(size, isl_dim_out);
2850 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
2851 guard = add_bounded_parameters_dynamic(guard, size, ids);
2852 isl_id_list_free(ids);
2853 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
2855 node = isl_schedule_node_insert_guard(node, guard);
2857 return node;
2860 /* Does any array reference group mapping require the band that is mapped
2861 * to threads to be unrolled?
2863 static int kernel_requires_unroll(struct ppcg_kernel *kernel)
2865 int i, j;
2867 for (i = 0; i < kernel->n_array; ++i) {
2868 struct gpu_local_array_info *array = &kernel->array[i];
2870 for (j = 0; j < array->n_group; ++j) {
2871 struct gpu_array_ref_group *group = array->groups[j];
2872 if (gpu_array_ref_group_requires_unroll(group))
2873 return 1;
2877 return 0;
2880 /* Mark the given band node "node" for unrolling by the AST generator and
2881 * then sink it to the leaves of the schedule tree.
2882 * All dimensions of "node" are assumed to be coincident, such that this
2883 * sinking is a valid operation.
2885 static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
2887 int i, n;
2889 n = isl_schedule_node_band_n_member(node);
2890 for (i = 0; i < n; ++i)
2891 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
2892 isl_ast_loop_unroll);
2894 node = isl_schedule_node_band_sink(node);
2896 return node;
2899 /* Insert a synchronization node in the schedule tree of "node"
2900 * after the core computation of "kernel" at the level of the band
2901 * that is mapped to threads, except if that level is equal to
2902 * that of the band that is mapped to blocks or if there are no writes
2903 * to global or shared memory in the core computation that require
2904 * synchronization.
2905 * If there are any writes to shared memory and the shared memory
2906 * copying is performed at the same level, then synchronization
2907 * is needed between the core and the copying anyway, so we might
2908 * as well add it here. If the copying is performed at a higher
2909 * level, then different iterations of intermediate schedule dimensions
2910 * may have a different mapping from between shared memory elements and
2911 * threads, such that synchronization is required after the core.
2912 * "node" is assumed to point to the kernel node.
2914 static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
2915 __isl_take isl_schedule_node *node)
2917 int kernel_depth;
2918 int need_sync;
2920 need_sync = any_global_or_shared_sync_writes(kernel);
2921 if (need_sync < 0)
2922 return isl_schedule_node_free(node);
2923 if (!need_sync)
2924 return node;
2926 kernel_depth = isl_schedule_node_get_schedule_depth(node);
2928 node = gpu_tree_move_down_to_thread(node, kernel->core);
2929 if (kernel_depth == isl_schedule_node_get_schedule_depth(node))
2930 return gpu_tree_move_up_to_kernel(node);
2932 node = gpu_tree_ensure_following_sync(node, kernel);
2934 node = gpu_tree_move_up_to_kernel(node);
2936 return node;
2939 /* Return a read ("read" is 1) or write access relation for "group"
2940 * with those accesses removed that are only needed to communicate data
2941 * within the subtree of the schedule rooted at "node".
2942 * Furthermore, include the prefix schedule at "node".
2943 * That is, return a relation of the form
2945 * S -> [D -> A]
2947 * with D the outer schedule dimensions at "node".
2949 static __isl_give isl_union_map *anchored_non_local_accesses(
2950 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2951 __isl_take isl_schedule_node *node, int read)
2953 isl_union_map *access;
2954 isl_union_map *prefix;
2956 access = gpu_array_ref_group_access_relation(group, read, !read);
2957 access = remove_local_accesses_group(kernel, group, access, node, read);
2958 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
2959 access = isl_union_map_range_product(prefix, access);
2961 return access;
2964 /* Given an array reference group "group", create a mapping
2966 * read[D -> A] -> [D -> A]
2968 * if "read" is set or
2970 * write[D -> A] -> [D -> A]
2972 * if "read" is not set.
2973 * D corresponds to the outer group->depth dimensions of
2974 * the kernel schedule.
2976 static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
2977 struct gpu_array_ref_group *group, int read)
2979 isl_space *space;
2980 isl_id *id;
2982 space = isl_space_copy(group->array->space);
2983 space = isl_space_from_range(space);
2984 space = isl_space_add_dims(space, isl_dim_in, group->depth);
2985 space = isl_space_wrap(space);
2986 space = isl_space_map_from_set(space);
2988 id = isl_id_alloc(ctx, read ? "read" : "write", group);
2989 space = isl_space_set_tuple_id(space, isl_dim_in, id);
2991 return isl_multi_aff_identity(space);
2994 /* If any writes in "group" require synchronization, then make sure
2995 * that there is a synchronization node for "kernel" after the node
2996 * following "node" in a sequence.
2998 * If "shared" is set and no synchronization is needed for
2999 * the writes to global memory, then add synchronization before
3000 * the kernel to protect shared memory from being overwritten
3001 * by the next iteration of the core computation.
3002 * No additional synchronization is needed to protect against
3003 * the next copy into shared memory because each element of
3004 * the shared memory tile is always copied by the same thread.
3006 static __isl_give isl_schedule_node *add_group_write_sync(
3007 __isl_take isl_schedule_node *node, struct ppcg_kernel *kernel,
3008 struct gpu_array_ref_group *group, int shared)
3010 int need_sync;
3012 need_sync = any_sync_writes_in_group(kernel, group);
3013 if (need_sync < 0)
3014 return isl_schedule_node_free(node);
3015 if (need_sync) {
3016 node = isl_schedule_node_parent(node);
3017 node = isl_schedule_node_next_sibling(node);
3018 node = isl_schedule_node_child(node, 0);
3019 node = gpu_tree_ensure_following_sync(node, kernel);
3020 } else if (shared) {
3021 node = isl_schedule_node_parent(node);
3022 node = isl_schedule_node_parent(node);
3023 node = gpu_tree_move_down_to_depth(node, group->depth,
3024 kernel->core);
3025 node = gpu_tree_move_left_to_sync(node, kernel);
3028 return node;
3031 /* Add copy statements to the schedule tree of "node"
3032 * for reading from global memory to private memory (if "read" is set) or
3033 * for writing back from private memory to global memory
3034 * (if "read" is not set) for the array reference group "group" that
3035 * is mapped to private memory.
3036 * On input, "node" points to the kernel node, and it is moved
3037 * back there on output.
3039 * The copies are performed in the order of the array elements.
3040 * The copy statement instances include a reference to the outer
3041 * group->depth dimensions of the kernel schedule for ease of
3042 * combining them with the group tiling.
3044 * That is, the extra schedule is of the form
3046 * type[D -> A] -> A
3048 * where D corresponds to the outer group->depth dimensions of
3049 * the kernel schedule and A to the global array.
3050 * This schedule is unrolled because registers are not addressable.
3052 * The copying is inserted in the schedule tree through an extension
3053 * of the form
3055 * D -> type[D -> A]
3057 * where the extra domain elements type[D -> A] are those accessed
3058 * by the group.
3059 * A filter is inserted on type[D -> A] to ensure that the element
3060 * is read/written by the same thread that needs the element.
3061 * This filter is obtained by applying
3063 * S -> type[D -> A]
3065 * to the thread filter for the core statements.
3067 * The extension is inserted before the core computation in case of a read
3068 * and after the core computation in case of a write.
3069 * In the latter case, we also make sure that there is a synchronization
3070 * node after the write to global memory, unless this write is performed
3071 * at the outer level of the kernel.
3072 * In principle, this synchronization could be inserted higher
3073 * in the schedule tree depending on where the corresponding reads
3074 * from global memory are performed.
3076 static __isl_give isl_schedule_node *add_copies_group_private(
3077 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3078 __isl_take isl_schedule_node *node, int read)
3080 isl_union_map *access;
3081 isl_union_map *prefix;
3082 isl_union_set *domain;
3083 isl_space *space;
3084 isl_multi_aff *from_access;
3085 isl_multi_pw_aff *mpa;
3086 isl_multi_union_pw_aff *mupa;
3087 isl_schedule_node *graft;
3088 isl_union_set *filter;
3089 int kernel_depth;
3090 int empty;
3092 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3093 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3095 access = anchored_non_local_accesses(kernel, group, node, read);
3096 empty = isl_union_map_is_empty(access);
3097 if (empty < 0 || empty) {
3098 isl_union_map_free(access);
3099 if (empty < 0)
3100 return isl_schedule_node_free(node);
3101 return gpu_tree_move_up_to_kernel(node);
3104 from_access = create_from_access(kernel->ctx, group, read);
3105 space = isl_space_domain(isl_multi_aff_get_space(from_access));
3106 access = isl_union_map_preimage_range_multi_aff(access, from_access);
3108 filter = isl_union_set_copy(kernel->thread_filter);
3109 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
3110 filter = isl_union_set_detect_equalities(filter);
3111 filter = isl_union_set_coalesce(filter);
3113 domain = isl_union_map_range(access);
3114 access = isl_union_set_wrapped_domain_map(domain);
3115 access = isl_union_map_reverse(access);
3116 access = isl_union_map_coalesce(access);
3117 graft = isl_schedule_node_from_extension(access);
3119 space = isl_space_map_from_set(space);
3120 mpa = isl_multi_pw_aff_identity(space);
3121 mpa = isl_multi_pw_aff_range_factor_range(mpa);
3122 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3124 graft = isl_schedule_node_child(graft, 0);
3125 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3126 graft = unroll(graft);
3128 graft = isl_schedule_node_insert_filter(graft, filter);
3130 graft = isl_schedule_node_parent(graft);
3132 if (read)
3133 node = isl_schedule_node_graft_before(node, graft);
3134 else {
3135 node = isl_schedule_node_graft_after(node, graft);
3136 if (kernel_depth < group->depth)
3137 node = add_group_write_sync(node, kernel, group, 0);
3140 node = gpu_tree_move_up_to_kernel(node);
3142 return node;
3145 /* Add copy statements to the schedule tree of "node"
3146 * for reading from global memory to shared memory (if "read" is set) or
3147 * for writing back from shared memory to global memory
3148 * (if "read" is not set) for the array reference group "group" that
3149 * is mapped to shared memory.
3150 * On input, "node" points to the kernel node, and it is moved
3151 * back there on output.
3153 * The copies are performed in the order of the corresponding shared
3154 * memory tile.
3155 * The copy statement instances include a reference to the outer
3156 * group->depth dimensions of the kernel schedule for ease of
3157 * combining them with the group tiling.
3159 * If we are performing a read from global memory to shared memory and
3160 * if the array involved is not a scalar, then we copy
3161 * the entire tile to shared memory. This may result in some extra
3162 * elements getting copied, but it should lead to simpler code
3163 * (which means that fewer registers may be needed) and less divergence.
3165 * Otherwise, we only copy the elements that will be read or have been written
3166 * in the kernel.
3168 * That is, the extra schedule is of the form
3170 * type[D -> A] -> T
3172 * where D corresponds to the outer group->depth dimensions of
3173 * the kernel schedule, A to the global array and T is the corresponding
3174 * shared memory tile.
3176 * The copying is inserted in the schedule tree through an extension
3177 * of the form
3179 * D -> type[D -> A]
3181 * where the extra domain elements type[D -> A] are those accessed
3182 * by the group. In the case of read from a non-scalar, this set
3183 * is replaced by the entire shared memory tile.
3185 * A filter is inserted on type[D -> A] to map the copy instances
3186 * to the threads. In particular, the thread identifiers are
3187 * equated to the position inside the shared memory tile (T)
3188 * modulo the block size.
3189 * We try to align the innermost tile dimension with the innermost
3190 * thread identifier (x) as a heuristic to improve coalescing.
3191 * In particular, if the dimension of the tile is greater than
3192 * the dimension of the block, then the schedule mapping to the tile
3193 * is broken up into two pieces and the filter is applied to the inner part.
3194 * If, on the other hand, the dimension of the tile is smaller than
3195 * the dimension of the block, then the initial thread identifiers
3196 * are equated to zero and the remaining thread identifiers are
3197 * matched to the memory tile.
3199 * The extension is inserted before the core computation in case of a read
3200 * and after the core computation in case of a write.
3201 * In the case of a read, we first need to make sure there is some
3202 * synchronization before the core computation such that we can put the read
3203 * from global memory to shared memory before that synchronization.
3204 * This ensures that all threads have finished copying into shared memory
3205 * before the shared memory is used.
3206 * We also need to make sure that there is a synchronization node after
3207 * the core computation to ensure that the next load into shared memory
3208 * only happens after all data has been used. There is no need for
3209 * this synchronization if we are at the outer level since then there
3210 * won't be a next load.
3211 * In the case of a write, we need to make sure there is some synchronization
3212 * after the core computation such taht we can put the write from shared
3213 * memory to global memory after that synchronization.
3214 * Unless we are at the outer level, we also need a synchronization node
3215 * after the write to ensure the data is saved to global memory
3216 * before the next iteration write to the same shared memory.
3217 * It also makes sure the data has arrived in global memory before
3218 * it is read in a subsequent iteration.
3220 static __isl_give isl_schedule_node *add_copies_group_shared(
3221 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3222 __isl_take isl_schedule_node *node, int read)
3224 struct gpu_array_tile *tile;
3225 isl_union_map *access;
3226 isl_union_set *domain;
3227 isl_union_set *sync;
3228 isl_multi_aff *ma;
3229 isl_multi_aff *from_access;
3230 isl_multi_pw_aff *mpa;
3231 isl_multi_union_pw_aff *mupa;
3232 isl_schedule_node *graft;
3233 isl_union_set *filter;
3234 int skip;
3235 int kernel_depth;
3236 int empty;
3238 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3239 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3241 access = anchored_non_local_accesses(kernel, group, node, read);
3242 empty = isl_union_map_is_empty(access);
3243 if (empty < 0 || empty) {
3244 isl_union_map_free(access);
3245 if (empty < 0)
3246 return isl_schedule_node_free(node);
3247 return gpu_tree_move_up_to_kernel(node);
3250 from_access = create_from_access(kernel->ctx, group, read);
3252 tile = gpu_array_ref_group_tile(group);
3253 ma = isl_multi_aff_copy(tile->tiling);
3254 ma = isl_multi_aff_pullback_multi_aff(ma,
3255 isl_multi_aff_copy(from_access));
3256 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3257 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3259 domain = isl_union_map_range(access);
3261 if (read && !gpu_array_is_scalar(group->array)) {
3262 isl_map *map;
3263 isl_union_set_free(domain);
3264 map = group_tile(group);
3265 domain = isl_union_set_from_set(isl_map_wrap(map));
3268 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3269 access = isl_union_set_wrapped_domain_map(domain);
3270 access = isl_union_map_reverse(access);
3271 access = isl_union_map_coalesce(access);
3272 graft = isl_schedule_node_from_extension(access);
3274 graft = isl_schedule_node_child(graft, 0);
3276 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3278 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3279 graft = isl_schedule_node_band_split(graft,
3280 tile->n - kernel->n_block);
3281 graft = isl_schedule_node_child(graft, 0);
3283 if (tile->n < kernel->n_block)
3284 skip = kernel->n_block - tile->n;
3285 else
3286 skip = 0;
3287 filter = set_schedule_modulo(graft, kernel->thread_ids,
3288 kernel->block_dim);
3289 if (!kernel->options->wrap)
3290 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3291 kernel->options);
3292 if (tile->n > kernel->n_block && kernel->n_block > 0)
3293 graft = isl_schedule_node_parent(graft);
3294 graft = isl_schedule_node_insert_filter(graft, filter);
3296 while (graft && isl_schedule_node_has_parent(graft))
3297 graft = isl_schedule_node_parent(graft);
3299 if (read) {
3300 if (kernel_depth < group->depth)
3301 node = gpu_tree_ensure_sync_after_core(node, kernel);
3302 node = gpu_tree_move_left_to_sync(node, kernel);
3303 node = isl_schedule_node_graft_before(node, graft);
3304 } else {
3305 node = gpu_tree_move_right_to_sync(node, kernel);
3306 node = isl_schedule_node_graft_after(node, graft);
3307 if (kernel_depth < group->depth)
3308 node = add_group_write_sync(node, kernel, group, 1);
3311 node = gpu_tree_move_up_to_kernel(node);
3313 return node;
3316 /* Check whether the array reference group "group" is mapped to
3317 * private or shared memory and, if so,
3318 * add copy statements to the schedule tree of "node"
3319 * for reading from global memory to private or shared memory
3320 * (if "read" is set) or for writing back from private or shared memory
3321 * to global memory (if "read" is not set) for this group.
3322 * On input, "node" points to the kernel node, and it is moved
3323 * back there on output.
3325 static __isl_give isl_schedule_node *add_copies_group(
3326 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3327 __isl_take isl_schedule_node *node, int read)
3329 if (group->private_tile)
3330 return add_copies_group_private(kernel, group, node, read);
3331 if (group->shared_tile)
3332 return add_copies_group_shared(kernel, group, node, read);
3333 return node;
3336 /* For each array reference group that is mapped to private or shared memory,
3337 * add copy statements to the schedule tree of "node"
3338 * for reading from global memory to private or shared memory
3339 * and for writing back.
3340 * On input, "node" points to the kernel node, and it is moved
3341 * back there on output.
3343 static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3344 __isl_take isl_schedule_node *node)
3346 int i, j;
3348 for (i = 0; i < kernel->n_array; ++i) {
3349 struct gpu_local_array_info *array = &kernel->array[i];
3351 for (j = 0; j < array->n_group; ++j) {
3352 struct gpu_array_ref_group *group = array->groups[j];
3354 node = add_copies_group(kernel, group, node, 1);
3355 if (!node)
3356 return NULL;
3357 node = add_copies_group(kernel, group, node, 0);
3358 if (!node)
3359 return NULL;
3363 return node;
3366 /* Mark all dimensions in the current band node atomic.
3368 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3370 int i, n;
3372 n = isl_schedule_node_band_n_member(node);
3373 for (i = 0; i < n; ++i)
3374 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
3375 isl_ast_loop_atomic);
3377 return node;
3380 /* Mark "node" atomic, if it is a band node.
3381 * Do the same for all ancestors.
3382 * Return a pointer to "node" (in the updated schedule tree).
3384 static __isl_give isl_schedule_node *atomic_ancestors(
3385 __isl_take isl_schedule_node *node)
3387 int pos;
3389 if (!node)
3390 return NULL;
3391 if (!isl_schedule_node_has_parent(node))
3392 return node;
3394 pos = isl_schedule_node_get_child_position(node);
3395 node = isl_schedule_node_parent(node);
3396 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3397 node = atomic(node);
3398 node = atomic_ancestors(node);
3399 node = isl_schedule_node_child(node, pos);
3401 return node;
3404 /* Collect all write references that require synchronization.
3405 * "node" is assumed to point to the kernel node.
3406 * Each reference is represented by a universe set in a space
3408 * [S[i,j] -> R[]]
3410 * with S[i,j] the statement instance space and R[] the array reference.
3412 * This function should be called before block and thread filters are added.
3414 * Synchronization is needed after a write if there is a subsequent read
3415 * within the same block that may not be performed by the same thread.
3416 * There should not be any dependences between different blocks,
3417 * so we start with the flow dependences within the same kernel invocation
3418 * and we subtract from these those dependences that are mapped
3419 * to the same iteration of the bands where synchronization is inserted.
3420 * We do not remove pairs of instances that are known to map to
3421 * the same thread across different iterations of the intermediate
3422 * bands because the read may be performed by a different thread
3423 * than the one that needs the value if shared memory is involved.
3425 * We also consider all pairs of possible writes that access the same
3426 * memory location and that may be mapped to the same block but not
3427 * to the same iteration of the intermediate bands.
3428 * In theory, it would be possible for one thread to still be in
3429 * a previous iteration of a loop in these bands.
3430 * A write to global memory in this delayed thread could then overwrite
3431 * a write from another thread that has already moved on to
3432 * the next iteration.
3434 * After computing the above writes paired off with reads or writes
3435 * that depend on them, we project onto the domain writes.
3436 * Sychronization is needed after writes to global memory
3437 * through these references.
3439 static __isl_give isl_union_set *compute_sync_writes(
3440 struct ppcg_kernel *kernel, __isl_keep isl_schedule_node *node)
3442 isl_union_map *local;
3443 isl_union_map *may_writes, *shared_access;
3444 isl_union_map *kernel_prefix, *thread_prefix;
3445 isl_union_map *equal;
3446 isl_union_set *wrap;
3447 isl_union_set *domain;
3449 domain = isl_schedule_node_get_universe_domain(node);
3450 kernel_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3451 node = isl_schedule_node_copy(node);
3452 node = gpu_tree_move_down_to_thread(node, kernel->core);
3453 thread_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3454 isl_schedule_node_free(node);
3456 may_writes = isl_union_map_copy(kernel->prog->scop->tagged_may_writes);
3457 may_writes = isl_union_map_curry(may_writes);
3458 may_writes = isl_union_map_intersect_domain(may_writes, domain);
3459 may_writes = isl_union_map_uncurry(may_writes);
3460 shared_access = isl_union_map_copy(may_writes);
3461 shared_access = isl_union_map_apply_range(shared_access,
3462 isl_union_map_reverse(may_writes));
3464 local = isl_union_map_copy(kernel->prog->scop->tagged_dep_flow);
3465 local = isl_union_map_union(local, shared_access);
3466 local = isl_union_map_zip(local);
3468 equal = isl_union_map_apply_range(kernel_prefix,
3469 isl_union_map_reverse(isl_union_map_copy(kernel_prefix)));
3470 wrap = isl_union_map_wrap(equal);
3471 local = isl_union_map_intersect_domain(local, wrap);
3472 equal = isl_union_map_apply_range(thread_prefix,
3473 isl_union_map_reverse(isl_union_map_copy(thread_prefix)));
3474 wrap = isl_union_map_wrap(equal);
3475 local = isl_union_map_subtract_domain(local, wrap);
3477 local = isl_union_map_zip(local);
3478 local = isl_union_map_universe(local);
3480 return isl_union_map_domain(local);
3483 /* Group the domain elements into a single space, named kernelX,
3484 * with X the kernel sequence number "kernel_id".
3486 static __isl_give isl_schedule_node *group_statements(
3487 __isl_take isl_schedule_node *node, int kernel_id)
3489 char buffer[20];
3490 isl_id *id;
3492 if (!node)
3493 return NULL;
3495 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3496 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3497 return isl_schedule_node_group(node, id);
3500 /* Create a ppcg_kernel representing the domain instances that reach "node"
3501 * and insert a mark node pointing to the ppcg_kernel before "node".
3502 * The band that "node" points to is the band that needs to be mapped
3503 * to block identifiers. The band that needs to be mapped to thread
3504 * identifiers should be marked by a "thread" mark by the caller.
3505 * This mark is removed by this function.
3506 * If "scale" is set, then the band that "node" points to is scaled
3507 * by "sizes".
3509 * Mark all outer band nodes as atomic to ensure each kernel is only
3510 * scheduled once.
3511 * If the domain elements that reach "node" live in more than one space,
3512 * then group the domain elements into a single space, named kernelX,
3513 * with X the kernel sequence number.
3515 * Insert a guard node governing the kernel node to ensure that
3516 * no kernels with zero blocks are launched.
3518 * Insert a context node describing the block and thread
3519 * identifiers inside the kernel mark.
3520 * The context node needs to be inserted after the effective block size
3521 * has been determined such that the bounds on the thread identifiers
3522 * would reflect the effective block size.
3523 * Insert a filter node inside the context node mapping the statement
3524 * instances to block identifiers. In particular, the block identifiers
3525 * are equated to the partial schedule of band that was marked for mapping
3526 * to blocks modulo the grid size.
3527 * Insert a filter node inside the "thread" mark mapping the statement
3528 * instances to thread identifiers. In particular, the thread identifiers
3529 * are equated to the partial schedule of band that was marked for mapping
3530 * to threads modulo the block size.
3532 * Compute array reference groups for all arrays, set the local
3533 * array bounds based on the set of domain instances that reach
3534 * the kernel node, check the total amount of shared memory used
3535 * and compute all group tilings.
3536 * The array reference groups are computed after the block filter
3537 * has been inserted because it affects the mapping to shared or
3538 * private memory. This computation also requires the thread filter
3539 * (in the ppcg_kernel object), but this thread filter should not
3540 * have been added to the schedule tree yet since the computation
3541 * requires the schedule of the band that needs to be mapped to
3542 * threads before the privatization is applied.
3544 * If any array reference group requires the band mapped to threads
3545 * to be unrolled, then we perform the required unrolling.
3547 * We save a copy of the schedule that may influence the mappings
3548 * to shared or private memory in kernel->shared_schedule.
3550 * Finally, we add synchronization and copy statements to the schedule tree,
3551 * remove the "thread" mark and create representations for the local
3552 * variables in the kernel.
3554 * We keep a copy of the isl_id that points to the kernel to ensure
3555 * that the kernel does not get destroyed if the schedule node
3556 * is freed due to some error condition.
3558 static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
3559 __isl_take isl_schedule_node *node, int scale,
3560 __isl_keep isl_multi_val *sizes)
3562 struct ppcg_kernel *kernel;
3563 isl_id *id;
3564 isl_schedule_node *node_thread;
3565 isl_union_map *host_schedule;
3566 isl_set *host_domain;
3567 isl_union_set *domain;
3568 int single_statement;
3570 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3571 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3572 if (!kernel)
3573 return isl_schedule_node_free(node);
3575 domain = isl_schedule_node_get_domain(node);
3576 single_statement = isl_union_set_n_set(domain) == 1;
3578 kernel->ctx = gen->ctx;
3579 kernel->prog = gen->prog;
3580 kernel->options = gen->options;
3581 kernel->context = extract_context(node, gen->prog);
3582 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3583 kernel->arrays = accessed_by_domain(isl_union_set_copy(domain),
3584 gen->prog);
3585 kernel->n_grid = n_outer_coincidence(node);
3586 node_thread = isl_schedule_node_copy(node);
3587 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3588 node_thread = isl_schedule_node_child(node_thread, 0);
3589 kernel->n_block = n_outer_coincidence(node_thread);
3590 isl_schedule_node_free(node_thread);
3591 kernel->id = gen->kernel_id++;
3592 read_grid_and_block_sizes(kernel, gen);
3594 kernel->sync_writes = compute_sync_writes(kernel, node);
3596 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3597 host_domain = isl_set_from_union_set(isl_union_map_range(
3598 host_schedule));
3600 node = atomic_ancestors(node);
3602 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3603 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3604 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3606 if (!single_statement)
3607 node = group_statements(node, kernel->id);
3609 node = isl_schedule_node_child(node, 0);
3610 node = split_band(node, kernel->n_grid);
3611 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3612 kernel->n_grid, "b");
3613 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3614 kernel->grid_dim);
3615 kernel->grid_size = extract_grid_size(kernel,
3616 isl_union_set_copy(domain));
3617 if (!kernel->options->wrap)
3618 node = snap_band_to_sizes(node, kernel->grid_dim,
3619 kernel->options);
3620 if (scale)
3621 node = scale_band(node, isl_multi_val_copy(sizes));
3622 node = isl_schedule_node_parent(node);
3623 if (!single_statement)
3624 node = isl_schedule_node_parent(node);
3625 node = insert_guard(node, kernel->context, kernel->grid_size,
3626 gen->prog->scop);
3627 node = gpu_tree_move_down_to_thread(node, kernel->core);
3628 node = isl_schedule_node_child(node, 0);
3629 node = split_band(node, kernel->n_block);
3630 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3631 kernel->n_block, "t");
3632 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3633 kernel->block_dim);
3634 extract_block_size(kernel, domain);
3636 node = gpu_tree_move_up_to_kernel(node);
3637 node = isl_schedule_node_child(node, 0);
3638 node = insert_context(kernel, node);
3639 node = isl_schedule_node_child(node, 0);
3640 node = isl_schedule_node_insert_filter(node,
3641 isl_union_set_copy(kernel->block_filter));
3643 node = gpu_tree_move_up_to_kernel(node);
3645 if (gpu_group_references(kernel, node) < 0)
3646 node = isl_schedule_node_free(node);
3647 localize_bounds(kernel, host_domain);
3648 isl_set_free(host_domain);
3650 check_shared_memory_bound(kernel);
3651 compute_group_tilings(kernel);
3653 node = gpu_tree_move_down_to_thread(node, kernel->core);
3654 node = isl_schedule_node_child(node, 0);
3655 if (!kernel->options->wrap)
3656 node = snap_band_to_sizes(node, kernel->block_dim,
3657 kernel->options);
3658 node = isl_schedule_node_insert_filter(node,
3659 isl_union_set_copy(kernel->thread_filter));
3660 if (kernel_requires_unroll(kernel)) {
3661 node = isl_schedule_node_child(node, 0);
3662 node = unroll(node);
3665 node = gpu_tree_move_up_to_thread(node);
3666 kernel->shared_schedule_dim =
3667 isl_schedule_node_get_schedule_depth(node);
3668 kernel->shared_schedule =
3669 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3671 node = gpu_tree_move_up_to_kernel(node);
3673 node = add_sync(kernel, node);
3674 node = add_copies(kernel, node);
3676 node = gpu_tree_move_down_to_thread(node, kernel->core);
3677 node = isl_schedule_node_delete(node);
3679 node = gpu_tree_move_up_to_kernel(node);
3681 if (create_kernel_vars(kernel) < 0)
3682 node = isl_schedule_node_free(node);
3684 if (!single_statement)
3685 node = isl_schedule_node_parent(node);
3686 node = isl_schedule_node_parent(node);
3688 isl_id_free(id);
3689 return node;
3692 /* Insert a zero-dimensional permutable band at "node".
3694 static __isl_give isl_schedule_node *insert_empty_permutable_band(
3695 __isl_take isl_schedule_node *node)
3697 isl_space *space;
3698 isl_schedule *schedule;
3699 isl_union_set *domain;
3700 isl_multi_union_pw_aff *mupa;
3702 schedule = isl_schedule_node_get_schedule(node);
3703 domain = isl_schedule_get_domain(schedule);
3704 space = isl_union_set_get_space(domain);
3705 isl_union_set_free(domain);
3706 isl_schedule_free(schedule);
3708 space = isl_space_set_from_params(space);
3709 mupa = isl_multi_union_pw_aff_zero(space);
3710 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3711 node = isl_schedule_node_band_set_permutable(node, 1);
3713 return node;
3716 /* If "node" is the outermost permutable band that can be mapped to block and
3717 * thread identifiers in its branch (or a leaf with no such outer bands),
3718 * then mark the band as such, attaching a ppcg_kernel to the mark.
3720 * If "node" originally points to a leaf, then insert a zero-dimensional
3721 * permutable band such that we can assume that "node" always
3722 * points to a band node.
3724 * Tile "node" using user specified tile sizes, after splitting the band
3725 * if the number of specified tile sizes is smaller than the dimension
3726 * of the band. Mark the point band of this tiling as the band that
3727 * needs to be mapped to threads.
3728 * Create a kernel representing the domain instances that reach "node" and
3729 * insert a mark node pointing to the ppcg_kernel before the band node.
3731 static __isl_give isl_schedule_node *mark_outer_permutable(
3732 __isl_take isl_schedule_node *node, void *user)
3734 struct gpu_gen *gen = user;
3735 int outer;
3736 int scale;
3737 int tile_len;
3738 int *tile_size;
3739 isl_id *id;
3740 isl_multi_val *sizes;
3742 outer = is_outer_tilable(node);
3743 if (outer < 0)
3744 return isl_schedule_node_free(node);
3745 if (!outer)
3746 return node;
3748 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
3749 node = insert_empty_permutable_band(node);
3751 tile_len = isl_schedule_node_band_n_member(node);
3752 tile_size = read_tile_sizes(gen, &tile_len);
3753 if (!tile_size)
3754 return isl_schedule_node_free(node);
3755 if (tile_len < isl_schedule_node_band_n_member(node))
3756 node = isl_schedule_node_band_split(node, tile_len);
3757 sizes = construct_band_tiles_sizes(node, tile_size);
3758 node = tile_band(node, isl_multi_val_copy(sizes));
3759 node = isl_schedule_node_child(node, 0);
3760 id = isl_id_alloc(gen->ctx, "thread", NULL);
3761 node = isl_schedule_node_insert_mark(node, id);
3762 node = isl_schedule_node_parent(node);
3764 scale = gen->options->scale_tile_loops;
3765 node = create_kernel(gen, node, scale, sizes);
3766 isl_multi_val_free(sizes);
3767 free(tile_size);
3769 return node;
3772 /* Does the subtree rooted at "node" have any suitably permutable band nodes?
3773 * That is, does it have any nodes that are permutable and that
3774 * have a least one coincident dimension?
3776 static int subtree_has_permutable_bands(__isl_keep isl_schedule_node *node)
3778 int any_parallelism = 0;
3780 if (isl_schedule_node_foreach_descendant(node, &set_permutable,
3781 &any_parallelism) < 0 &&
3782 !any_parallelism)
3783 return -1;
3785 return any_parallelism;
3788 /* Mark all variables that are accessed by the statement instances in "domain"
3789 * and that are local to "prog" as requiring a declaration in the host code.
3791 static int declare_accessed_local_variables(struct gpu_prog *prog,
3792 __isl_keep isl_union_set *domain)
3794 isl_union_set *arrays;
3795 int i;
3797 if (!ppcg_scop_any_hidden_declarations(prog->scop))
3798 return 0;
3799 arrays = accessed_by_domain(isl_union_set_copy(domain), prog);
3801 for (i = 0; i < prog->n_array; ++i) {
3802 isl_space *space;
3803 isl_set *set;
3804 int empty;
3806 if (!prog->array[i].local)
3807 continue;
3808 space = isl_set_get_space(prog->array[i].extent);
3809 set = isl_union_set_extract_set(arrays, space);
3810 empty = isl_set_plain_is_empty(set);
3811 isl_set_free(set);
3812 if (empty < 0)
3813 goto error;
3814 if (!empty)
3815 prog->array[i].declare_local = 1;
3818 isl_union_set_free(arrays);
3819 return 0;
3820 error:
3821 isl_union_set_free(arrays);
3822 return -1;
3825 /* If "node" points to a set node, then separate its children
3826 * into subtrees that have suitably permutable bands and
3827 * those that do not.
3828 * Adjust the schedule tree in order to execute the second group
3829 * after the first group and return a pointer to the first group,
3830 * assuming there are any such subtrees.
3831 * Mark all local variables in "prog" that are accessed by
3832 * the second group as requiring a declaration on the host.
3834 static __isl_give isl_schedule_node *isolate_permutable_subtrees(
3835 __isl_take isl_schedule_node *node, struct gpu_prog *prog)
3837 isl_space *space;
3838 isl_union_set *filter;
3839 int i, n;
3841 if (!node)
3842 return NULL;
3843 if (isl_schedule_node_get_type(node) != isl_schedule_node_set)
3844 return node;
3846 n = isl_schedule_node_n_children(node);
3847 if (n < 0)
3848 return isl_schedule_node_free(node);
3850 node = isl_schedule_node_child(node, 0);
3851 filter = isl_schedule_node_filter_get_filter(node);
3852 node = isl_schedule_node_parent(node);
3853 space = isl_union_set_get_space(filter);
3854 isl_union_set_free(filter);
3855 filter = isl_union_set_empty(space);
3857 for (i = 0; i < n; ++i) {
3858 int parallelism;
3860 node = isl_schedule_node_child(node, i);
3861 parallelism = subtree_has_permutable_bands(node);
3862 if (parallelism < 0) {
3863 node = isl_schedule_node_free(node);
3864 } else if (!parallelism) {
3865 isl_union_set *filter_i;
3866 filter_i = isl_schedule_node_filter_get_filter(node);
3867 filter = isl_union_set_union(filter, filter_i);
3869 node = isl_schedule_node_parent(node);
3872 if (declare_accessed_local_variables(prog, filter) < 0)
3873 node = isl_schedule_node_free(node);
3874 node = isl_schedule_node_order_after(node, filter);
3876 return node;
3879 /* Replace any reference to an array element in the range of "copy"
3880 * by a reference to all array elements (defined by the extent of the array).
3882 static __isl_give isl_union_map *approximate_copy_out(
3883 __isl_take isl_union_map *copy, struct gpu_prog *prog)
3885 int i;
3886 isl_union_map *res;
3888 res = isl_union_map_empty(isl_union_map_get_space(copy));
3890 for (i = 0; i < prog->n_array; ++i) {
3891 isl_space *space;
3892 isl_set *set;
3893 isl_union_map *copy_i;
3894 isl_union_set *extent, *domain;
3896 space = isl_space_copy(prog->array[i].space);
3897 extent = isl_union_set_from_set(isl_set_universe(space));
3898 copy_i = isl_union_map_copy(copy);
3899 copy_i = isl_union_map_intersect_range(copy_i, extent);
3900 set = isl_set_copy(prog->array[i].extent);
3901 extent = isl_union_set_from_set(set);
3902 domain = isl_union_map_domain(copy_i);
3903 copy_i = isl_union_map_from_domain_and_range(domain, extent);
3904 res = isl_union_map_union(res, copy_i);
3907 isl_union_map_free(copy);
3909 return res;
3912 /* Insert "kernel" marks that point to a ppcg_kernel structure
3913 * in front of all outermost tilable band that (by construction)
3914 * have at least one parallel loop.
3916 static __isl_give isl_schedule_node *mark_kernels(struct gpu_gen *gen,
3917 __isl_take isl_schedule_node *node)
3919 return isl_schedule_node_map_descendant(node,
3920 &mark_outer_permutable, gen);
3923 /* Save the schedule "schedule" to a file called "filename".
3924 * The schedule is printed in block style.
3926 static void save_schedule(__isl_keep isl_schedule *schedule,
3927 const char *filename)
3929 FILE *file;
3930 isl_ctx *ctx;
3931 isl_printer *p;
3933 if (!schedule)
3934 return;
3936 file = fopen(filename, "w");
3937 if (!file) {
3938 fprintf(stderr, "Unable to open '%s' for writing\n", filename);
3939 return;
3941 ctx = isl_schedule_get_ctx(schedule);
3942 p = isl_printer_to_file(ctx, file);
3943 p = isl_printer_set_yaml_style(p, ISL_YAML_STYLE_BLOCK);
3944 p = isl_printer_print_schedule(p, schedule);
3945 isl_printer_free(p);
3946 fclose(file);
3949 /* Load and return a schedule from a file called "filename".
3951 static __isl_give isl_schedule *load_schedule(isl_ctx *ctx,
3952 const char *filename)
3954 FILE *file;
3955 isl_schedule *schedule;
3957 file = fopen(filename, "r");
3958 if (!file) {
3959 fprintf(stderr, "Unable to open '%s' for reading\n", filename);
3960 return NULL;
3962 schedule = isl_schedule_read_from_file(ctx, file);
3963 fclose(file);
3965 return schedule;
3968 /* Compute an appropriate schedule based on the accesses in
3969 * gen->read and gen->write.
3971 * We use the dependences in gen->prog->scop to compute
3972 * a schedule that has a parallel loop in each tilable band and
3973 * return this schedule.
3975 * If live range reordering is allowed, then we need to make sure
3976 * that live ranges on arrays are not run in parallel since doing
3977 * so would require array expansion. We therefore add the array
3978 * order dependences to the coincidence dependences. Non-zero array
3979 * order dependences will then prevent a schedule dimension from being
3980 * considered parallel.
3981 * Live ranges derived from scalars are allowed to be run in parallel
3982 * since we force the scalars to be mapped to private memory in
3983 * check_scalar_live_ranges.
3984 * If live range reordering is allowed, then the false dependences
3985 * are not added to the validity constraints as that would prevent
3986 * reordering. Instead, the external false dependences that enforce that reads
3987 * from potentially live-in data precede any later write and
3988 * that writes of potentially live-out data follow any other earlier write
3989 * are added to the validity and the coincidence constraints.
3990 * The false dependences are still added to the proximity constraints
3991 * for consistency with the case where live range reordering is not allowed.
3992 * The coincidence constraints then consist of flow dependences,
3993 * external false dependences and array order dependences.
3994 * The independences can be filtered out from the first two sets.
3995 * They have already been filtered out from the array order dependences
3996 * on a per array basis in collect_order_dependences.
3997 * There is no need for a per array handling of the other two sets
3998 * as there should be no flow or external false dependence on local
3999 * variables that can be filtered out.
4001 static __isl_give isl_schedule *compute_schedule(struct gpu_gen *gen)
4003 isl_union_set *domain;
4004 isl_union_map *dep_raw, *dep;
4005 isl_union_map *validity, *proximity, *coincidence;
4006 isl_schedule_constraints *sc;
4007 isl_schedule *schedule;
4009 domain = isl_union_set_copy(gen->prog->scop->domain);
4010 sc = isl_schedule_constraints_on_domain(domain);
4011 sc = isl_schedule_constraints_set_context(sc,
4012 isl_set_copy(gen->prog->scop->context));
4013 if (gen->options->live_range_reordering) {
4014 sc = isl_schedule_constraints_set_conditional_validity(sc,
4015 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
4016 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
4017 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
4018 validity = isl_union_map_copy(proximity);
4019 validity = isl_union_map_union(validity,
4020 isl_union_map_copy(gen->prog->scop->dep_forced));
4021 proximity = isl_union_map_union(proximity,
4022 isl_union_map_copy(gen->prog->scop->dep_false));
4023 coincidence = isl_union_map_copy(validity);
4024 coincidence = isl_union_map_subtract(coincidence,
4025 isl_union_map_copy(gen->prog->scop->independence));
4026 coincidence = isl_union_map_union(coincidence,
4027 isl_union_map_copy(gen->prog->array_order));
4028 } else {
4029 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4030 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4031 dep = isl_union_map_union(dep, dep_raw);
4032 dep = isl_union_map_coalesce(dep);
4033 proximity = isl_union_map_copy(dep);
4034 coincidence = isl_union_map_copy(dep);
4035 validity = dep;
4037 sc = isl_schedule_constraints_set_validity(sc, validity);
4038 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4039 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4041 if (gen->options->debug->dump_schedule_constraints)
4042 isl_schedule_constraints_dump(sc);
4043 schedule = isl_schedule_constraints_compute_schedule(sc);
4045 return schedule;
4048 /* Obtain a schedule for the scop, either by reading it from
4049 * a file or by computing one.
4051 static __isl_give isl_schedule *get_schedule(struct gpu_gen *gen)
4053 isl_schedule *schedule;
4055 if (gen->options->load_schedule_file) {
4056 schedule = load_schedule(gen->ctx,
4057 gen->options->load_schedule_file);
4058 } else {
4059 schedule = compute_schedule(gen);
4060 if (gen->options->save_schedule_file)
4061 save_schedule(schedule,
4062 gen->options->save_schedule_file);
4064 if (gen->options->debug->dump_schedule)
4065 isl_schedule_dump(schedule);
4067 return schedule;
4070 /* Construct the string "<a>_<b>".
4072 static char *concat(isl_ctx *ctx, const char *a, const char *b)
4074 isl_printer *p;
4075 char *s;
4077 p = isl_printer_to_str(ctx);
4078 p = isl_printer_print_str(p, a);
4079 p = isl_printer_print_str(p, "_");
4080 p = isl_printer_print_str(p, b);
4081 s = isl_printer_get_str(p);
4082 isl_printer_free(p);
4084 return s;
4087 /* For each array in "prog" of which an element appears in "accessed" and
4088 * that is not a read only scalar, create a zero-dimensional universe set
4089 * of which the tuple id has name "<prefix>_<name of array>" and a user
4090 * pointer pointing to the array (gpu_array_info).
4092 * If the array is local to "prog", then make sure it will be declared
4093 * in the host code.
4095 * Return the list of these universe sets.
4097 static __isl_give isl_union_set_list *create_copy_filters(struct gpu_prog *prog,
4098 const char *prefix, __isl_take isl_union_set *accessed)
4100 int i;
4101 isl_ctx *ctx;
4102 isl_union_set_list *filters;
4104 ctx = prog->ctx;
4105 filters = isl_union_set_list_alloc(ctx, 0);
4106 for (i = 0; i < prog->n_array; ++i) {
4107 struct gpu_array_info *array = &prog->array[i];
4108 isl_space *space;
4109 isl_set *accessed_i;
4110 int empty;
4111 char *name;
4112 isl_id *id;
4113 isl_union_set *uset;
4115 if (gpu_array_is_read_only_scalar(array))
4116 continue;
4118 space = isl_space_copy(array->space);
4119 accessed_i = isl_union_set_extract_set(accessed, space);
4120 empty = isl_set_plain_is_empty(accessed_i);
4121 isl_set_free(accessed_i);
4122 if (empty < 0) {
4123 filters = isl_union_set_list_free(filters);
4124 break;
4126 if (empty)
4127 continue;
4129 if (array->local)
4130 array->declare_local = 1;
4132 name = concat(ctx, prefix, array->name);
4133 id = name ? isl_id_alloc(ctx, name, array) : NULL;
4134 free(name);
4135 space = isl_space_set_alloc(ctx, 0, 0);
4136 space = isl_space_set_tuple_id(space, isl_dim_set, id);
4137 uset = isl_union_set_from_set(isl_set_universe(space));
4139 filters = isl_union_set_list_add(filters, uset);
4141 isl_union_set_free(accessed);
4143 return filters;
4146 /* Make sure that code for the statements in "filters" that
4147 * copy arrays to or from the device is only generated when
4148 * the size of the corresponding array is positive.
4149 * That is, add a set node underneath "graft" with "filters" as children
4150 * and for each child add a guard that the selects the parameter
4151 * values for which the corresponding array has a positive size.
4152 * The array is available in the user pointer of the statement identifier.
4153 * "depth" is the schedule depth of the position where "graft"
4154 * will be added.
4156 static __isl_give isl_schedule_node *insert_positive_size_guards(
4157 __isl_take isl_schedule_node *graft,
4158 __isl_take isl_union_set_list *filters, int depth)
4160 int i, n;
4162 graft = isl_schedule_node_child(graft, 0);
4163 graft = isl_schedule_node_insert_set(graft, filters);
4164 n = isl_schedule_node_n_children(graft);
4165 for (i = 0; i < n; ++i) {
4166 isl_union_set *filter;
4167 isl_set *domain, *guard;
4168 isl_id *id;
4169 struct gpu_array_info *array;
4171 graft = isl_schedule_node_child(graft, i);
4172 filter = isl_schedule_node_filter_get_filter(graft);
4173 domain = isl_set_from_union_set(filter);
4174 id = isl_set_get_tuple_id(domain);
4175 array = isl_id_get_user(id);
4176 isl_id_free(id);
4177 isl_set_free(domain);
4178 guard = gpu_array_positive_size_guard(array);
4179 guard = isl_set_from_params(guard);
4180 guard = isl_set_add_dims(guard, isl_dim_set, depth);
4181 graft = isl_schedule_node_child(graft, 0);
4182 graft = isl_schedule_node_insert_guard(graft, guard);
4183 graft = isl_schedule_node_parent(graft);
4184 graft = isl_schedule_node_parent(graft);
4186 graft = isl_schedule_node_parent(graft);
4188 return graft;
4191 /* Create a graft for copying arrays to or from the device,
4192 * whenever the size of the array is strictly positive.
4193 * Each statement is called "<prefix>_<name of array>" and
4194 * the identifier has a user pointer pointing to the array.
4195 * The graft will be added at the position specified by "node".
4196 * "copy" contains the array elements that need to be copied.
4197 * Only arrays of which some elements need to be copied
4198 * will have a corresponding statement in the graph.
4199 * Note though that each such statement will copy the entire array.
4201 static __isl_give isl_schedule_node *create_copy_device(struct gpu_prog *prog,
4202 __isl_keep isl_schedule_node *node, const char *prefix,
4203 __isl_take isl_union_set *copy)
4205 int depth;
4206 isl_ctx *ctx;
4207 isl_space *space;
4208 isl_union_set *all, *domain;
4209 isl_union_set_list *filters;
4210 isl_union_map *extension;
4211 isl_schedule_node *graft;
4213 ctx = prog->ctx;
4214 depth = isl_schedule_node_get_schedule_depth(node);
4215 filters = create_copy_filters(prog, prefix, copy);
4216 all = isl_union_set_list_union(isl_union_set_list_copy(filters));
4218 space = depth < 0 ? NULL : isl_space_set_alloc(ctx, 0, depth);
4219 domain = isl_union_set_from_set(isl_set_universe(space));
4220 extension = isl_union_map_from_domain_and_range(domain, all);
4221 graft = isl_schedule_node_from_extension(extension);
4223 if (!filters)
4224 return isl_schedule_node_free(graft);
4225 if (isl_union_set_list_n_union_set(filters) == 0) {
4226 isl_union_set_list_free(filters);
4227 return graft;
4230 return insert_positive_size_guards(graft, filters, depth);
4233 /* Return (the universe spaces of) the arrays that are declared
4234 * inside the scop corresponding to "prog" and for which all
4235 * potential writes inside the scop form a subset of "domain".
4237 static __isl_give isl_union_set *extract_local_accesses(struct gpu_prog *prog,
4238 __isl_keep isl_union_set *domain)
4240 int i;
4241 isl_union_set *local;
4243 local = isl_union_set_empty(isl_union_set_get_space(domain));
4245 for (i = 0; i < prog->n_array; ++i) {
4246 isl_set *set;
4247 isl_union_map *to_outer;
4248 isl_union_map *may_write;
4249 isl_union_set *write_domain;
4250 isl_union_set *fields;
4251 int subset;
4253 if (!prog->array[i].local)
4254 continue;
4256 set = isl_set_universe(isl_space_copy(prog->array[i].space));
4257 to_outer = isl_union_map_copy(prog->to_outer);
4258 to_outer = isl_union_map_intersect_range(to_outer,
4259 isl_union_set_from_set(isl_set_copy(set)));
4260 fields = isl_union_map_domain(to_outer);
4261 may_write = isl_union_map_copy(prog->may_write);
4262 may_write = isl_union_map_intersect_range(may_write, fields);
4263 write_domain = isl_union_map_domain(may_write);
4264 subset = isl_union_set_is_subset(write_domain, domain);
4265 isl_union_set_free(write_domain);
4267 if (subset < 0) {
4268 isl_set_free(set);
4269 return isl_union_set_free(local);
4270 } else if (subset) {
4271 local = isl_union_set_add_set(local, set);
4272 } else {
4273 isl_set_free(set);
4277 return local;
4280 /* Internal data structure for node_may_persist.
4282 * "tagger" maps tagged iteration domains to the corresponding untagged
4283 * iteration domain.
4285 * "may_persist_flow" is the set of all tagged dataflow dependences
4286 * with those dependences removed that either precede or follow
4287 * the kernel launch in a sequence.
4288 * "inner_band_flow" is the set of all tagged dataflow dependences
4289 * that are local to a given iteration of the outer band nodes
4290 * with respect to the current node.
4291 * "local_flow" is equal to "inner_band_flow", except that the domain
4292 * and the range have been intersected with intermediate filters
4293 * on children of sets or sequences.
4295 struct ppcg_may_persist_data {
4296 isl_union_pw_multi_aff *tagger;
4298 isl_union_map *local_flow;
4299 isl_union_map *inner_band_flow;
4300 isl_union_map *may_persist_flow;
4303 /* Update the information in "data" based on the band ancestor "node".
4305 * In particular, we restrict the dependences in data->local_flow
4306 * to those dependence where the source and the sink occur in
4307 * the same iteration of the given band node.
4308 * We also update data->inner_band_flow to the new value of
4309 * data->local_flow.
4311 static int update_may_persist_at_band(__isl_keep isl_schedule_node *node,
4312 struct ppcg_may_persist_data *data)
4314 isl_multi_union_pw_aff *partial;
4315 isl_union_pw_multi_aff *contraction;
4316 isl_union_map *flow;
4318 if (isl_schedule_node_band_n_member(node) == 0)
4319 return 0;
4321 partial = isl_schedule_node_band_get_partial_schedule(node);
4322 contraction = isl_schedule_node_get_subtree_contraction(node);
4323 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4324 contraction);
4325 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4326 isl_union_pw_multi_aff_copy(data->tagger));
4328 flow = data->local_flow;
4329 flow = isl_union_map_eq_at_multi_union_pw_aff(flow, partial);
4330 data->local_flow = flow;
4332 isl_union_map_free(data->inner_band_flow);
4333 data->inner_band_flow = isl_union_map_copy(data->local_flow);
4335 return 0;
4338 /* Given a set of local reaching domain elements "domain",
4339 * expand them to the corresponding leaf domain elements using "contraction"
4340 * and insert the array references tags using data->tagger.
4342 static __isl_give isl_union_set *expand_and_tag(
4343 __isl_take isl_union_set *domain,
4344 __isl_take isl_union_pw_multi_aff *contraction,
4345 struct ppcg_may_persist_data *data)
4347 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4348 contraction);
4349 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4350 isl_union_pw_multi_aff_copy(data->tagger));
4351 return domain;
4354 /* Given a filter node that is the child of a set or sequence node,
4355 * restrict data->local_flow to refer only to those elements
4356 * in the filter of the node.
4357 * "contraction" maps the leaf domain elements of the schedule tree
4358 * to the corresponding domain elements at (the parent of) "node".
4360 static int filter_flow(__isl_keep isl_schedule_node *node,
4361 struct ppcg_may_persist_data *data,
4362 __isl_take isl_union_pw_multi_aff *contraction)
4364 isl_union_set *filter;
4365 isl_union_map *flow;
4367 flow = data->local_flow;
4368 filter = isl_schedule_node_filter_get_filter(node);
4369 filter = expand_and_tag(filter, contraction, data);
4370 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(filter));
4371 flow = isl_union_map_intersect_range(flow, filter);
4372 data->local_flow = flow;
4374 return 0;
4377 /* Given a filter node "node", collect the filters on all preceding siblings
4378 * (which are also filter nodes), add them to "filters" and return the result.
4380 static __isl_give isl_union_set *add_previous_filters(
4381 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4383 isl_schedule_node *sibling;
4385 sibling = isl_schedule_node_copy(node);
4386 while (sibling && isl_schedule_node_has_previous_sibling(sibling)) {
4387 isl_union_set *filter;
4389 sibling = isl_schedule_node_previous_sibling(sibling);
4390 filter = isl_schedule_node_filter_get_filter(sibling);
4391 filters = isl_union_set_union(filters, filter);
4393 isl_schedule_node_free(sibling);
4394 if (!sibling)
4395 return isl_union_set_free(filters);
4397 return filters;
4400 /* Given a filter node "node", collect the filters on all following siblings
4401 * (which are also filter nodes), add them to "filters" and return the result.
4403 static __isl_give isl_union_set *add_next_filters(
4404 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4406 isl_schedule_node *sibling;
4408 sibling = isl_schedule_node_copy(node);
4409 while (sibling && isl_schedule_node_has_next_sibling(sibling)) {
4410 isl_union_set *filter;
4412 sibling = isl_schedule_node_next_sibling(sibling);
4413 filter = isl_schedule_node_filter_get_filter(sibling);
4414 filters = isl_union_set_union(filters, filter);
4416 isl_schedule_node_free(sibling);
4417 if (!sibling)
4418 return isl_union_set_free(filters);
4420 return filters;
4423 /* Remove those flow dependences from data->may_persist_flow
4424 * that flow between elements of "domain" within the same iteration
4425 * of all outer band nodes.
4426 * "contraction" maps the leaf domain elements of the schedule tree
4427 * to the corresponding elements "domain".
4429 static void remove_external_flow(struct ppcg_may_persist_data *data,
4430 __isl_take isl_union_set *domain,
4431 __isl_keep isl_union_pw_multi_aff *contraction)
4433 isl_union_map *flow;
4435 contraction = isl_union_pw_multi_aff_copy(contraction);
4436 domain = expand_and_tag(domain, contraction, data);
4437 flow = isl_union_map_copy(data->local_flow);
4438 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(domain));
4439 flow = isl_union_map_intersect_range(flow, domain);
4441 data->may_persist_flow = isl_union_map_subtract(data->may_persist_flow,
4442 flow);
4445 /* Update the information in "data" based on the filter ancestor "node".
4446 * We only need to modify anything if the filter is the child
4447 * of a set or sequence node.
4449 * In the case of a sequence, we remove the dependences between
4450 * statement instances that are both executed either before or
4451 * after the subtree that will be mapped to a kernel, within
4452 * the same iteration of outer bands.
4454 * In both cases, we restrict data->local_flow to the current child.
4456 static int update_may_persist_at_filter(__isl_keep isl_schedule_node *node,
4457 struct ppcg_may_persist_data *data)
4459 enum isl_schedule_node_type type;
4460 isl_schedule_node *parent;
4461 isl_space *space;
4462 isl_union_pw_multi_aff *contraction;
4463 isl_union_set *before, *after, *filter;
4464 isl_union_map *flow;
4466 type = isl_schedule_node_get_parent_type(node);
4467 if (type != isl_schedule_node_sequence && type != isl_schedule_node_set)
4468 return 0;
4470 parent = isl_schedule_node_copy(node);
4471 parent = isl_schedule_node_parent(parent);
4472 contraction = isl_schedule_node_get_subtree_contraction(parent);
4473 isl_schedule_node_free(parent);
4475 if (type == isl_schedule_node_set)
4476 return filter_flow(node, data, contraction);
4478 filter = isl_schedule_node_filter_get_filter(node);
4479 space = isl_union_set_get_space(filter);
4480 isl_union_set_free(filter);
4481 before = isl_union_set_empty(space);
4482 after = isl_union_set_copy(before);
4483 before = add_previous_filters(before, node);
4484 after = add_next_filters(after, node);
4486 remove_external_flow(data, before, contraction);
4487 remove_external_flow(data, after, contraction);
4489 return filter_flow(node, data, contraction);
4492 /* Update the information in "data" based on the ancestor "node".
4494 static int update_may_persist_at(__isl_keep isl_schedule_node *node, void *user)
4496 struct ppcg_may_persist_data *data = user;
4498 switch (isl_schedule_node_get_type(node)) {
4499 case isl_schedule_node_error:
4500 return -1;
4501 case isl_schedule_node_context:
4502 case isl_schedule_node_domain:
4503 case isl_schedule_node_expansion:
4504 case isl_schedule_node_extension:
4505 case isl_schedule_node_guard:
4506 case isl_schedule_node_leaf:
4507 case isl_schedule_node_mark:
4508 case isl_schedule_node_sequence:
4509 case isl_schedule_node_set:
4510 break;
4511 case isl_schedule_node_band:
4512 if (update_may_persist_at_band(node, data) < 0)
4513 return -1;
4514 break;
4515 case isl_schedule_node_filter:
4516 if (update_may_persist_at_filter(node, data) < 0)
4517 return -1;
4518 break;
4521 return 0;
4524 /* Determine the set of array elements that may need to be perserved
4525 * by a kernel constructed from the subtree at "node".
4526 * This includes the set of array elements that may need to be preserved
4527 * by the entire scop (prog->may_persist) and the elements for which
4528 * there is a potential flow dependence that may cross a kernel launch.
4530 * To determine the second set, we start from all flow dependences.
4531 * From this set of dependences, we remove those that cannot possibly
4532 * require data to be preserved by a kernel launch.
4533 * In particular, we consider the following sets of dependences.
4534 * - dependences of which the write occurs inside the kernel.
4535 * If the data is needed outside the kernel, then it will
4536 * be copied out immediately after the kernel launch, so there
4537 * is no need for any special care.
4538 * - dependences of which the read occurs inside the kernel and the
4539 * corresponding write occurs inside the same iteration of the
4540 * outer band nodes. This means that the data is needed in
4541 * the first kernel launch after the write, which is already
4542 * taken care of by the standard copy-in. That is, the data
4543 * do not need to be preserved by any intermediate call to
4544 * the same kernel.
4545 * - dependences of which the write and the read either both occur
4546 * before the kernel launch or both occur after the kernel launch,
4547 * within the same iteration of the outer band nodes with respect
4548 * to the sequence that determines the ordering of the dependence
4549 * and the kernel launch. Such flow dependences cannot cross
4550 * any kernel launch.
4552 * For the remaining (tagged) dependences, we take the domain
4553 * (i.e., the tagged writes) and apply the tagged access relation
4554 * to obtain the accessed data elements.
4555 * These are then combined with the elements that may need to be
4556 * preserved by the entire scop.
4558 static __isl_give isl_union_set *node_may_persist(
4559 __isl_keep isl_schedule_node *node, struct gpu_prog *prog)
4561 struct ppcg_may_persist_data data;
4562 isl_schedule_node *root;
4563 isl_union_pw_multi_aff *contraction;
4564 isl_union_set *domain;
4565 isl_union_set *persist;
4566 isl_union_map *flow, *local_flow;
4568 data.tagger = prog->scop->tagger;
4570 flow = isl_union_map_copy(prog->scop->tagged_dep_flow);
4571 data.local_flow = isl_union_map_copy(flow);
4572 data.inner_band_flow = isl_union_map_copy(flow);
4573 data.may_persist_flow = flow;
4574 if (isl_schedule_node_foreach_ancestor_top_down(node,
4575 &update_may_persist_at, &data) < 0)
4576 data.may_persist_flow =
4577 isl_union_map_free(data.may_persist_flow);
4578 flow = data.may_persist_flow;
4579 isl_union_map_free(data.local_flow);
4581 domain = isl_schedule_node_get_domain(node);
4582 contraction = isl_schedule_node_get_subtree_contraction(node);
4583 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4584 contraction);
4585 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4586 isl_union_pw_multi_aff_copy(data.tagger));
4587 flow = isl_union_map_subtract_domain(flow, isl_union_set_copy(domain));
4588 local_flow = data.inner_band_flow;
4589 local_flow = isl_union_map_intersect_range(local_flow, domain);
4590 flow = isl_union_map_subtract(flow, local_flow);
4592 persist = isl_union_map_domain(flow);
4593 persist = isl_union_set_apply(persist,
4594 isl_union_map_copy(prog->scop->tagged_may_writes));
4595 persist = isl_union_set_union(persist,
4596 isl_union_set_copy(prog->may_persist));
4598 return persist;
4601 /* Add nodes for copying outer arrays in and out of the device
4602 * before and after the subtree "node", which contains one or more kernels.
4603 * "domain" contains the original reaching domain elements before
4604 * the kernels were created, i.e., before the contraction that
4605 * may have been performed in creating the kernels has been applied.
4606 * "prefix" contains the prefix schedule at that point, in terms
4607 * of the same original reaching domain elements.
4609 * We first compute the sets of outer array elements that need
4610 * to be copied in and out and then graft in the nodes for
4611 * performing this copying.
4613 * In particular, for each array that is possibly written anywhere in
4614 * the subtree "node" and that may be used after "node"
4615 * or that may be visible outside the corresponding scop,
4616 * we copy out its entire extent.
4618 * Any array elements that is read without first being written inside
4619 * the subtree "node" needs to be copied in.
4620 * Furthermore, if there are any array elements that
4621 * are copied out, but that may not be written inside "node, then
4622 * they also need to be copied in to ensure that the value after execution
4623 * is the same as the value before execution, at least for those array
4624 * elements that may have their values preserved by the scop or that
4625 * may be written before "node" and read after "node".
4626 * In case the array elements are structures, we need to take into
4627 * account that all members of the structures need to be written
4628 * by "node" before we can avoid copying the data structure in.
4630 * Note that the may_write relation is intersected with the domain,
4631 * which has been intersected with the context.
4632 * This helps in those cases where the arrays are declared with a fixed size,
4633 * while the accesses are parametric and the context assigns a fixed value
4634 * to the parameters.
4636 * If an element from a local array is read without first being written,
4637 * then there is no point in copying it in since it cannot have been
4638 * written prior to the scop. Warn about the uninitialized read instead.
4640 static __isl_give isl_schedule_node *add_to_from_device(
4641 __isl_take isl_schedule_node *node, __isl_take isl_union_set *domain,
4642 __isl_take isl_union_map *prefix, struct gpu_prog *prog)
4644 isl_union_set *local;
4645 isl_union_set *to_device, *from_device, *may_persist;
4646 isl_union_map *may_write, *must_write, *copy_out, *not_written;
4647 isl_union_map *read, *copy_in;
4648 isl_union_map *tagged;
4649 isl_union_map *local_uninitialized;
4650 isl_schedule_node *graft;
4652 tagged = isl_union_map_copy(prog->scop->tagged_reads);
4653 tagged = isl_union_map_union(tagged,
4654 isl_union_map_copy(prog->scop->tagged_may_writes));
4656 may_write = isl_union_map_copy(prog->may_write);
4657 may_write = isl_union_map_intersect_domain(may_write,
4658 isl_union_set_copy(domain));
4659 may_write = remove_local_accesses(prog,
4660 isl_union_map_copy(tagged), may_write,
4661 isl_union_map_copy(prefix), 0);
4662 may_write = isl_union_map_apply_range(may_write,
4663 isl_union_map_copy(prog->to_outer));
4664 may_write = isl_union_map_apply_domain(may_write,
4665 isl_union_map_copy(prefix));
4666 may_write = approximate_copy_out(may_write, prog);
4667 copy_out = isl_union_map_copy(may_write);
4668 may_write = isl_union_map_apply_range(may_write,
4669 isl_union_map_copy(prog->to_inner));
4670 must_write = isl_union_map_copy(prog->must_write);
4671 must_write = isl_union_map_apply_domain(must_write,
4672 isl_union_map_copy(prefix));
4673 may_persist = node_may_persist(node, prog);
4674 may_write = isl_union_map_intersect_range(may_write, may_persist);
4675 not_written = isl_union_map_subtract(may_write, must_write);
4677 local = extract_local_accesses(prog, domain);
4678 read = isl_union_map_copy(prog->read);
4679 read = isl_union_map_intersect_domain(read, domain);
4680 read = remove_local_accesses(prog, tagged, read,
4681 isl_union_map_copy(prefix), 1);
4682 local = isl_union_set_apply(local, isl_union_map_copy(prog->to_inner));
4683 local_uninitialized = isl_union_map_copy(prog->scop->live_in);
4684 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4685 local);
4686 local_uninitialized = isl_union_map_intersect(local_uninitialized,
4687 isl_union_map_copy(read));
4688 if (!isl_union_map_is_empty(local_uninitialized)) {
4689 fprintf(stderr,
4690 "possibly uninitialized reads (not copied in):\n");
4691 isl_union_map_dump(local_uninitialized);
4693 read = isl_union_map_subtract(read, local_uninitialized);
4694 read = isl_union_map_apply_domain(read, prefix);
4695 copy_in = isl_union_map_union(read, not_written);
4696 copy_in = isl_union_map_apply_range(copy_in,
4697 isl_union_map_copy(prog->to_outer));
4699 graft = create_copy_device(prog, node, "to_device",
4700 isl_union_map_range(copy_in));
4701 node = isl_schedule_node_graft_before(node, graft);
4702 graft = create_copy_device(prog, node, "from_device",
4703 isl_union_map_range(copy_out));
4704 node = isl_schedule_node_graft_after(node, graft);
4706 return node;
4709 /* Update "schedule" for mapping to a GPU device.
4711 * In particular, insert a context node, create kernels for
4712 * each outermost tilable band and introduce node for copying array
4713 * in and out of the device.
4714 * If the child of the initial root points to a set node,
4715 * then children of this node that do not contain any tilable bands
4716 * are separated from the other children and are not mapped to
4717 * the device.
4719 static __isl_give isl_schedule *map_to_device(struct gpu_gen *gen,
4720 __isl_take isl_schedule *schedule)
4722 isl_schedule_node *node;
4723 isl_set *context;
4724 isl_union_set *domain;
4725 isl_union_map *prefix;
4727 context = isl_set_copy(gen->prog->context);
4728 context = isl_set_from_params(context);
4729 schedule = isl_schedule_insert_context(schedule, context);
4731 node = isl_schedule_get_root(schedule);
4732 isl_schedule_free(schedule);
4733 node = isl_schedule_node_child(node, 0);
4734 if (isl_schedule_node_get_type(node) == isl_schedule_node_context)
4735 node = isl_schedule_node_child(node, 0);
4736 node = isolate_permutable_subtrees(node, gen->prog);
4737 domain = isl_schedule_node_get_domain(node);
4738 prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
4739 node = mark_kernels(gen, node);
4740 node = add_to_from_device(node, domain, prefix, gen->prog);
4741 schedule = isl_schedule_node_get_schedule(node);
4742 isl_schedule_node_free(node);
4744 return schedule;
4747 /* Internal data structure for extract_access.
4748 * "next_access" points to the end of a linked list that is extended
4749 * by extract_access.
4750 * "single_expression" is set if the access expressions belong to
4751 * an expression statement (i.e., a statement without internal control).
4752 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4754 struct ppcg_extract_access_data {
4755 struct gpu_stmt_access **next_access;
4756 int single_expression;
4757 isl_union_map *any_to_outer;
4760 /* Given a tagged access relation to a single array "tagged", extract it
4761 * as a map, taking into account that the input may be empty.
4762 * If the access relation is empty, then it does not contain
4763 * any space information, so we try to recover it from the index
4764 * expression.
4765 * The space of the index expression is of the form I -> A,
4766 * with I the statement instances and A the array, or [I -> F] -> A,
4767 * with F the filters corresponding to arguments.
4768 * We first drop F, if present, obtaining I -> A.
4769 * Then we construct I -> R, with R the reference tag,
4770 * combine the two into I -> [R -> A] and uncurry to obtain
4771 * the final result [I -> R] -> A.
4772 * Note that the index expression may have a lower dimension
4773 * than that of the array, but this dimension is not used
4774 * if the access relation is empty.
4776 static __isl_give isl_map *extract_single_tagged_access(
4777 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
4779 int empty;
4780 isl_id *id;
4781 isl_space *space, *space2;
4782 isl_multi_pw_aff *index;
4784 empty = isl_union_map_is_empty(tagged);
4785 if (empty < 0)
4786 goto error;
4787 if (!empty)
4788 return isl_map_from_union_map(tagged);
4789 isl_union_map_free(tagged);
4791 index = pet_expr_access_get_index(expr);
4792 space = isl_multi_pw_aff_get_space(index);
4793 isl_multi_pw_aff_free(index);
4794 if (isl_space_domain_is_wrapping(space))
4795 space = isl_space_domain_factor_domain(space);
4796 space2 = isl_space_copy(space);
4797 space2 = isl_space_from_domain(isl_space_domain(space));
4798 id = pet_expr_access_get_ref_id(expr);
4799 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
4800 space = isl_space_range_product(space2, space);
4801 space = isl_space_uncurry(space);
4803 return isl_map_empty(space);
4804 error:
4805 isl_union_map_free(tagged);
4806 return NULL;
4809 /* Extract a gpu_stmt_access from "expr", append it to the list
4810 * that ends in *data->next_access and update the end of the list.
4811 * If the access expression performs a write, then it is considered
4812 * exact only if it appears in a single expression statement and
4813 * if its may access relation is equal to its must access relation.
4815 * The combined set of may accesses may be union if member accesses
4816 * are involved, but the entire set is derived from a single reference and
4817 * therefore from a single index expression. These accesses therefore
4818 * all map to the same outer array.
4820 static int extract_access(__isl_keep pet_expr *expr, void *user)
4822 struct ppcg_extract_access_data *data = user;
4823 isl_union_map *tagged;
4824 struct gpu_stmt_access *access;
4825 isl_ctx *ctx = pet_expr_get_ctx(expr);
4826 isl_multi_pw_aff *index;
4828 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4829 assert(access);
4830 access->next = NULL;
4831 access->read = pet_expr_access_is_read(expr);
4832 access->write = pet_expr_access_is_write(expr);
4833 tagged = pet_expr_access_get_tagged_may_read(expr);
4834 tagged = isl_union_map_union(tagged,
4835 pet_expr_access_get_tagged_may_write(expr));
4836 tagged = isl_union_map_apply_range(tagged,
4837 isl_union_map_copy(data->any_to_outer));
4838 if (!access->write) {
4839 access->exact_write = 1;
4840 } else if (!data->single_expression) {
4841 access->exact_write = 0;
4842 } else {
4843 isl_union_map *must, *may;
4844 may = isl_union_map_copy(tagged);
4845 may = isl_union_map_domain_factor_domain(may);
4846 must = pet_expr_access_get_must_write(expr);
4847 access->exact_write = isl_union_map_is_equal(must, may);
4848 isl_union_map_free(must);
4849 isl_union_map_free(may);
4851 index = pet_expr_access_get_index(expr);
4852 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
4853 isl_multi_pw_aff_free(index);
4854 access->ref_id = pet_expr_access_get_ref_id(expr);
4855 access->tagged_access = extract_single_tagged_access(tagged, expr);
4856 access->access = isl_map_copy(access->tagged_access);
4857 access->access = isl_map_domain_factor_domain(access->access);
4859 *data->next_access = access;
4860 data->next_access = &(*data->next_access)->next;
4862 if (!access->access)
4863 return -1;
4865 return 0;
4868 /* Construct a linked list of gpu_stmt_access objects,
4869 * one for each access expression in the statement body.
4870 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4872 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
4873 __isl_keep isl_union_map *any_to_outer)
4875 struct ppcg_extract_access_data data;
4877 stmt->accesses = NULL;
4878 data.next_access = &stmt->accesses;
4879 data.single_expression =
4880 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
4881 data.any_to_outer = any_to_outer;
4882 return pet_tree_foreach_access_expr(stmt->stmt->body,
4883 &extract_access, &data);
4886 /* Return an array of gpu_stmt representing the statements in "scop".
4888 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4889 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
4891 int i;
4892 struct gpu_stmt *stmts;
4894 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
4895 if (!stmts)
4896 return NULL;
4898 for (i = 0; i < scop->pet->n_stmt; ++i) {
4899 struct gpu_stmt *s = &stmts[i];
4901 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
4902 s->stmt = scop->pet->stmts[i];
4903 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
4904 return free_stmts(stmts, i + 1);
4907 return stmts;
4910 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
4912 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
4914 struct gpu_gen *gen = user;
4916 return gen->print(p, gen->prog, gen->tree, &gen->types,
4917 gen->print_user);
4920 /* Generate CUDA code for "scop" and print it to "p".
4921 * After generating an AST for the transformed scop as explained below,
4922 * we call "gen->print" to print the AST in the desired output format
4923 * to "p".
4925 * If it turns out that it does not make sense to generate GPU code,
4926 * then we generate CPU code instead.
4928 * The GPU code is generated in a context where at least one
4929 * statement instance is executed. The corresponding guard (if any) is printed
4930 * around the entire generated GPU code, except for the declaration
4931 * of the arrays that are visible outside of the scop and that therefore
4932 * cannot be declared inside the body of any possible guard.
4934 * We first compute a schedule that respects the dependences
4935 * of the original program and select the outermost bands
4936 * of tilable dimensions that have at least one parallel loop.
4937 * If the --load-schedule is specified, then the loaded schedule
4938 * is used instead of a computed schedule.
4940 * Each of these bands B is then tiled according to "tile" sizes, resulting
4941 * in two nested bands, with a kernel marker on top
4949 * We then split off at most 2 parallel dimensions from the T band and
4950 * at most 3 parallel dimension from the P band
4955 * T1
4957 * T2
4959 * P1
4961 * P2
4963 * A filter is introduced in front of T1 that maps the domain instances
4964 * to block identifiers. Similarly, a filter is introduced in front of P1
4965 * that maps the domain instances to thread identifiers.
4967 * For each iteration of the T2 band and for each array, we compute
4968 * the array elements accessed by that iteration, construct a rectangular
4969 * box around it and shift it to the origin. The result is used
4970 * as shared memory for the array.
4972 * Copying and synchronization statements are added to this schedule tree.
4973 * In principle, these are added in front of the P1 band, but some of
4974 * them may get hoisted up to higher levels.
4976 * The entire AST is then generated from the single resulting schedule tree.
4977 * During the generation the subtrees at kernel nodes (K) are saved
4978 * aside and replaced by kernel calls. The result is printed as host code
4979 * while the saved subtrees are printed as device code.
4981 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
4982 struct gpu_gen *gen, struct ppcg_scop *scop,
4983 struct ppcg_options *options)
4985 struct gpu_prog *prog;
4986 isl_ctx *ctx;
4987 isl_set *context, *guard;
4988 isl_schedule *schedule;
4989 int any_permutable;
4991 if (!scop)
4992 return isl_printer_free(p);
4994 ctx = isl_printer_get_ctx(p);
4995 prog = gpu_prog_alloc(ctx, scop);
4996 if (!prog)
4997 return isl_printer_free(p);
4999 context = isl_set_copy(prog->context);
5000 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5001 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5003 gen->prog = prog;
5004 schedule = get_schedule(gen);
5006 any_permutable = has_any_permutable_node(schedule);
5007 if (any_permutable < 0 || !any_permutable) {
5008 isl_set_free(context);
5009 isl_set_free(guard);
5010 if (any_permutable < 0)
5011 p = isl_printer_free(p);
5012 else
5013 p = print_cpu(p, scop, options);
5014 isl_schedule_free(schedule);
5015 } else {
5016 schedule = map_to_device(gen, schedule);
5017 gen->tree = generate_code(gen, schedule);
5018 p = ppcg_print_exposed_declarations(p, prog->scop);
5019 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5020 isl_ast_node_free(gen->tree);
5023 gpu_prog_free(prog);
5025 return p;
5028 /* Wrapper around generate for use as a ppcg_transform callback.
5030 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5031 struct ppcg_scop *scop, void *user)
5033 struct gpu_gen *gen = user;
5035 return generate(p, gen, scop, gen->options);
5038 /* Transform the code in the file called "input" by replacing
5039 * all scops by corresponding GPU code and write the results to "out".
5041 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5042 struct ppcg_options *options,
5043 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5044 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5045 struct gpu_types *types, void *user), void *user)
5047 struct gpu_gen gen;
5048 int r;
5049 int i;
5051 gen.ctx = ctx;
5052 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5053 gen.options = options;
5054 gen.kernel_id = 0;
5055 gen.print = print;
5056 gen.print_user = user;
5057 gen.types.n = 0;
5058 gen.types.name = NULL;
5060 if (options->debug->dump_sizes) {
5061 isl_space *space = isl_space_params_alloc(ctx, 0);
5062 gen.used_sizes = isl_union_map_empty(space);
5065 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5067 if (options->debug->dump_sizes) {
5068 isl_union_map_dump(gen.used_sizes);
5069 isl_union_map_free(gen.used_sizes);
5072 isl_union_map_free(gen.sizes);
5073 for (i = 0; i < gen.types.n; ++i)
5074 free(gen.types.name[i]);
5075 free(gen.types.name);
5077 return r;
5080 /* Compute the set of inner array elements that may have their values
5081 * preserved by "prog". In particular, collect the array elements of
5082 * arrays that are not local to "prog" and remove those elements that
5083 * are definitely killed or definitely written by "prog".
5085 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5087 int i;
5088 isl_union_set *may_persist, *killed;
5089 isl_union_map *must_kill;
5091 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5092 for (i = 0; i < prog->n_array; ++i) {
5093 isl_set *extent;
5095 if (prog->array[i].local)
5096 continue;
5098 extent = isl_set_copy(prog->array[i].extent);
5099 may_persist = isl_union_set_add_set(may_persist, extent);
5102 may_persist = isl_union_set_intersect_params(may_persist,
5103 isl_set_copy(prog->context));
5104 may_persist = isl_union_set_apply(may_persist,
5105 isl_union_map_copy(prog->to_inner));
5106 must_kill = isl_union_map_copy(prog->tagged_must_kill);
5107 killed = isl_union_map_range(must_kill);
5108 must_kill = isl_union_map_copy(prog->must_write);
5109 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
5111 may_persist = isl_union_set_subtract(may_persist, killed);
5112 return may_persist;
5115 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5117 struct gpu_prog *prog;
5118 isl_space *space;
5119 isl_map *id;
5121 if (!scop)
5122 return NULL;
5124 prog = isl_calloc_type(ctx, struct gpu_prog);
5125 assert(prog);
5127 prog->ctx = ctx;
5128 prog->scop = scop;
5129 prog->context = isl_set_copy(scop->context);
5130 prog->n_stmts = scop->pet->n_stmt;
5131 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5132 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5133 space = isl_union_map_get_space(prog->any_to_outer);
5134 space = isl_space_set_from_params(space);
5135 space = isl_space_add_dims(space, isl_dim_set, 1);
5136 space = isl_space_map_from_set(space);
5137 id = isl_map_identity(space);
5138 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
5139 prog->stmts = extract_stmts(ctx, scop,
5140 prog->context, prog->any_to_outer);
5141 prog->read = isl_union_map_copy(scop->reads);
5142 prog->may_write = isl_union_map_copy(scop->may_writes);
5143 prog->must_write = isl_union_map_copy(scop->must_writes);
5144 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
5145 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
5146 prog->to_outer = isl_union_map_copy(prog->to_inner);
5147 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5149 if (!prog->stmts)
5150 return gpu_prog_free(prog);
5152 if (collect_array_info(prog) < 0)
5153 return gpu_prog_free(prog);
5154 prog->may_persist = compute_may_persist(prog);
5156 return prog;
5159 void *gpu_prog_free(struct gpu_prog *prog)
5161 if (!prog)
5162 return NULL;
5163 free_array_info(prog);
5164 free_stmts(prog->stmts, prog->n_stmts);
5165 isl_union_map_free(prog->any_to_outer);
5166 isl_union_map_free(prog->to_outer);
5167 isl_union_map_free(prog->to_inner);
5168 isl_union_map_free(prog->read);
5169 isl_union_map_free(prog->may_write);
5170 isl_union_map_free(prog->must_write);
5171 isl_union_map_free(prog->tagged_must_kill);
5172 isl_union_map_free(prog->array_order);
5173 isl_union_set_free(prog->may_persist);
5174 isl_set_free(prog->context);
5175 free(prog);
5176 return NULL;