cuda.c: extract out copy_array_{to,from}_device
[ppcg.git] / gpu.c
blobfbec8b5a16d21ab7c3375a35890f213c906ae4b8
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"
36 struct gpu_array_info;
38 /* Collect all references to the given array and store pointers to them
39 * in array->refs.
41 * If the array contains structures, then there is no need to collect
42 * the references since we will not be computing any reference groups.
44 static void collect_references(struct gpu_prog *prog,
45 struct gpu_array_info *array)
47 int i;
48 int n;
50 if (array->has_compound_element)
51 return;
53 n = 0;
54 for (i = 0; i < prog->n_stmts; ++i) {
55 struct gpu_stmt *stmt = &prog->stmts[i];
56 struct gpu_stmt_access *access;
58 for (access = stmt->accesses; access; access = access->next) {
59 const char *name;
60 name = isl_map_get_tuple_name(access->access,
61 isl_dim_out);
62 if (name && !strcmp(array->name, name))
63 n++;
67 array->n_ref = n;
68 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
69 assert(array->refs);
71 n = 0;
72 for (i = 0; i < prog->n_stmts; ++i) {
73 struct gpu_stmt *stmt = &prog->stmts[i];
74 struct gpu_stmt_access *access;
76 for (access = stmt->accesses; access; access = access->next) {
77 const char *name;
78 name = isl_map_get_tuple_name(access->access,
79 isl_dim_out);
80 if (!name || strcmp(array->name, name))
81 continue;
83 array->refs[n++] = access;
88 /* Compute and return the extent of "array", taking into account the set of
89 * accessed elements.
91 * In particular, the extent in the outer dimension is taken
92 * from "accessed", while the extents in the remaining dimensions
93 * are taken from array->extent.
95 * The extent in the outer dimension cannot be taken from array->extent
96 * because that may be unbounded. Furthermore, even if it is bounded,
97 * it may be larger than the piece of the array that is being accessed.
99 static __isl_give isl_set *compute_extent(struct pet_array *array,
100 __isl_keep isl_set *accessed)
102 int n_index;
103 isl_id *id;
104 isl_set *outer;
105 isl_set *extent;
107 extent = isl_set_copy(array->extent);
109 n_index = isl_set_dim(accessed, isl_dim_set);
110 if (n_index == 0)
111 return extent;
113 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
114 outer = isl_set_copy(accessed);
115 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
116 extent = isl_set_flat_product(outer, extent);
117 id = isl_set_get_tuple_id(accessed);
118 extent = isl_set_set_tuple_id(extent, id);
120 return extent;
123 /* Is the array "array" being extracted a read-only scalar?
125 * That is, is "array" a scalar that is never possibly written to.
126 * An array containing structures is never considered to be a scalar.
128 static int is_read_only_scalar(struct gpu_array_info *array,
129 struct gpu_prog *prog)
131 isl_set *space;
132 isl_union_map *write;
133 int empty;
135 if (array->has_compound_element)
136 return 0;
137 if (array->n_index != 0)
138 return 0;
140 write = isl_union_map_copy(prog->may_write);
141 space = isl_set_universe(isl_space_copy(array->space));
142 write = isl_union_map_intersect_range(write,
143 isl_union_set_from_set(space));
144 empty = isl_union_map_is_empty(write);
145 isl_union_map_free(write);
147 return empty;
150 /* Compute bounds on the host array "pa" based on the corresponding
151 * accessed elements in "arrays"
152 * and collect all references to the array.
153 * Store the results in "info".
155 * If the array is zero-dimensional and does not contain structures,
156 * i.e., if the array is a scalar, we check whether it is read-only.
157 * We also check whether the array is accessed at all.
159 static int extract_array_info(struct gpu_prog *prog,
160 struct gpu_array_info *info, struct pet_array *pa,
161 __isl_keep isl_union_set *arrays)
163 int i, empty;
164 const char *name;
165 int n_index;
166 isl_pw_aff **bounds;
167 isl_set *accessed, *extent;
169 n_index = isl_set_dim(pa->extent, isl_dim_set);
170 name = isl_set_get_tuple_name(pa->extent);
171 bounds = isl_alloc_array(prog->ctx, isl_pw_aff *, n_index);
172 if (!bounds)
173 return -1;
175 info->space = isl_set_get_space(pa->extent);
176 info->name = strdup(name);
177 info->n_index = n_index;
178 info->bound = bounds;
179 info->linearize = prog->scop->options->linearize_device_arrays;
181 info->type = strdup(pa->element_type);
182 info->size = pa->element_size;
183 info->local = pa->declared && !pa->exposed;
184 info->has_compound_element = pa->element_is_record;
185 info->read_only_scalar = is_read_only_scalar(info, prog);
187 accessed = isl_union_set_extract_set(arrays,
188 isl_space_copy(info->space));
189 empty = isl_set_is_empty(accessed);
190 extent = compute_extent(pa, accessed);
191 isl_set_free(accessed);
192 info->extent = extent;
193 if (empty < 0)
194 return -1;
195 info->accessed = !empty;
196 for (i = 0; i < n_index; ++i) {
197 isl_set *dom;
198 isl_local_space *ls;
199 isl_aff *one;
200 isl_pw_aff *bound;
202 dom = isl_set_copy(extent);
203 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
204 n_index - (i + 1));
205 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
206 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
207 fprintf(stderr, "unable to determine extent of '%s' "
208 "in dimension %d\n", info->name, i);
209 dom = isl_set_free(dom);
211 bound = isl_set_dim_max(dom, 0);
212 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
213 ls = isl_local_space_from_space(isl_set_get_space(dom));
214 one = isl_aff_zero_on_domain(ls);
215 one = isl_aff_add_constant_si(one, 1);
216 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
217 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
219 bounds[i] = bound;
220 if (!isl_pw_aff_is_cst(bound))
221 info->linearize = 1;
224 collect_references(prog, info);
226 return 0;
229 /* Remove independence from the order constraints "order" on array "array".
230 * Since the pairs of iterations in the filter relation of an independence
231 * are guaranteed to be completely independent by the user, there is
232 * no need to ensure that live ranges are ordered along thong pairs.
233 * We make an exception for local variables, though, as the independence
234 * guarantee does not apply to those.
236 * The order constraints are used in two places.
237 * Those on scalars are used in check_scalar_live_ranges to check if
238 * we need to force the scalar to be private. Any non-local scalar
239 * should not be forced scalar if it only appears in independent loops.
240 * Those on non-scalars are added to the coincidence constraints
241 * in compute_schedule because we do not support any array expansion.
242 * Accesses to non-local arrays should not prevent a loop from being
243 * considered coincident so we should indeed remove those constraints
244 * from the order constraints.
246 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
247 struct gpu_array_info *array, __isl_take isl_union_map *order)
249 int i;
251 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
252 struct pet_independence *pi = prog->scop->pet->independences[i];
253 if (isl_union_set_contains(pi->local, array->space))
254 continue;
256 order = isl_union_map_subtract(order,
257 isl_union_map_copy(pi->filter));
260 return order;
263 /* For each array in "prog", store the (untagged) order dependences
264 * derived from the array in array->dep_order.
265 * In particular, consider all references that access the given array
266 * and take the order dependences that have one of these references
267 * as source. (Since an order dependence relates two references to
268 * the same array, the target of these order dependences will also
269 * be one of these references.)
270 * Additionally, store the union of these array->dep_order relations
271 * for all non-scalar arrays in prog->array_order.
273 void collect_order_dependences(struct gpu_prog *prog)
275 int i;
276 isl_space *space;
277 isl_union_map *accesses;
279 space = isl_union_map_get_space(prog->read);
280 prog->array_order = isl_union_map_empty(space);
282 accesses = isl_union_map_copy(prog->scop->tagged_reads);
283 accesses = isl_union_map_union(accesses,
284 isl_union_map_copy(prog->scop->tagged_may_writes));
285 accesses = isl_union_map_universe(accesses);
286 accesses = isl_union_map_apply_range(accesses,
287 isl_union_map_copy(prog->to_outer));
289 for (i = 0; i < prog->n_array; ++i) {
290 struct gpu_array_info *array = &prog->array[i];
291 isl_set *set;
292 isl_union_set *uset;
293 isl_union_map *order;
295 set = isl_set_universe(isl_space_copy(array->space));
296 uset = isl_union_set_from_set(set);
297 uset = isl_union_map_domain(
298 isl_union_map_intersect_range(isl_union_map_copy(accesses),
299 uset));
300 order = isl_union_map_copy(prog->scop->tagged_dep_order);
301 order = isl_union_map_intersect_domain(order, uset);
302 order = isl_union_map_zip(order);
303 order = isl_union_set_unwrap(isl_union_map_domain(order));
304 order = remove_independences(prog, array, order);
305 array->dep_order = order;
307 if (gpu_array_is_scalar(array) && !array->has_compound_element)
308 continue;
310 prog->array_order = isl_union_map_union(prog->array_order,
311 isl_union_map_copy(array->dep_order));
314 isl_union_map_free(accesses);
317 /* Construct a gpu_array_info for each array referenced by prog->scop and
318 * collect them in prog->array.
320 * The sizes are based on the extents and the set of possibly accessed
321 * elements by "prog".
322 * If there are any member accesses involved, then they are first mapped
323 * to the outer arrays of structs.
325 * If we are allowing live range reordering, then also set
326 * the dep_order field. Otherwise leave it NULL.
328 static int collect_array_info(struct gpu_prog *prog)
330 int i;
331 int r = 0;
332 isl_union_set *arrays;
334 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
335 arrays = isl_union_set_union(arrays,
336 isl_union_map_range(isl_union_map_copy(prog->may_write)));
338 arrays = isl_union_set_apply(arrays,
339 isl_union_map_copy(prog->to_outer));
341 arrays = isl_union_set_coalesce(arrays);
343 prog->n_array = prog->scop->pet->n_array;
344 prog->array = isl_calloc_array(prog->ctx,
345 struct gpu_array_info, prog->n_array);
346 assert(prog->array);
347 for (i = 0; i < prog->scop->pet->n_array; ++i)
348 if (extract_array_info(prog, &prog->array[i],
349 prog->scop->pet->arrays[i], arrays) < 0)
350 r = -1;
352 isl_union_set_free(arrays);
354 if (prog->scop->options->live_range_reordering)
355 collect_order_dependences(prog);
357 return r;
360 static void free_array_info(struct gpu_prog *prog)
362 int i, j;
364 for (i = 0; i < prog->n_array; ++i) {
365 int n_index = prog->array[i].n_index;
366 free(prog->array[i].type);
367 free(prog->array[i].name);
368 for (j = 0; j < n_index; ++j)
369 isl_pw_aff_free(prog->array[i].bound[j]);
370 isl_space_free(prog->array[i].space);
371 isl_set_free(prog->array[i].extent);
372 free(prog->array[i].bound);
373 free(prog->array[i].refs);
374 isl_union_map_free(prog->array[i].dep_order);
376 free(prog->array);
379 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
380 * as an array or through a pointer reference, but as a single data element.
381 * At the moment, scalars are represented as zero-dimensional arrays.
382 * Note that the single data element may be an entire structure.
384 int gpu_array_is_scalar(struct gpu_array_info *array)
386 return array->n_index == 0;
389 /* Is "array" a read-only scalar?
391 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
393 return array->read_only_scalar;
396 /* Return the set of parameter values for which the array has a positive
397 * size in all dimensions.
398 * If the sizes are only valid for some parameter values, then those
399 * constraints are also taken into account.
401 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
403 int i;
404 isl_space *space;
405 isl_set *guard;
407 space = isl_space_params(isl_space_copy(array->space));
408 guard = isl_set_universe(space);
410 for (i = 0; i < array->n_index; ++i) {
411 isl_pw_aff *bound;
412 isl_set *guard_i, *zero;
414 bound = isl_pw_aff_copy(array->bound[i]);
415 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
416 zero = isl_pw_aff_zero_set(bound);
417 guard_i = isl_set_subtract(guard_i, zero);
418 guard = isl_set_intersect(guard, guard_i);
421 return guard;
424 /* Internal data structure for extract_size_of_type.
425 * "type" specifies the name of the space that we want to extract.
426 * "res" is used to store the subset of that space.
428 struct ppcg_extract_size_data {
429 const char *type;
430 isl_set *res;
433 /* This function is called for each set in a union_set.
434 * If the name of the set matches data->type, we store the
435 * set in data->res.
437 static int extract_size_of_type(__isl_take isl_set *size, void *user)
439 struct ppcg_extract_size_data *data = user;
440 const char *name;
442 name = isl_set_get_tuple_name(size);
443 if (name && !strcmp(name, data->type)) {
444 data->res = size;
445 return -1;
448 isl_set_free(size);
449 return 0;
452 /* Given a union map { kernel[i] -> *[...] },
453 * return the range in the space called "type" for the kernel with
454 * sequence number "id".
456 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
457 const char *type, int id)
459 isl_space *space;
460 isl_set *dom;
461 isl_union_set *local_sizes;
462 struct ppcg_extract_size_data data = { type, NULL };
464 if (!sizes)
465 return NULL;
467 space = isl_union_map_get_space(sizes);
468 space = isl_space_set_from_params(space);
469 space = isl_space_add_dims(space, isl_dim_set, 1);
470 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
471 dom = isl_set_universe(space);
472 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
474 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
475 isl_union_map_copy(sizes));
476 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
477 isl_union_set_free(local_sizes);
478 return data.res;
481 /* Given a singleton set, extract the first (at most *len) elements
482 * of the single integer tuple into *sizes and update *len if needed.
484 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
486 int i;
487 int dim;
489 if (!set)
490 return;
492 dim = isl_set_dim(set, isl_dim_set);
493 if (dim < *len)
494 *len = dim;
496 for (i = 0; i < *len; ++i) {
497 isl_val *v;
499 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
500 assert(v);
502 sizes[i] = isl_val_get_num_si(v);
503 isl_val_free(v);
506 isl_set_free(set);
509 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
510 * if the option debug->dump_sizes is set.
512 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
513 int *sizes, int len)
515 int i;
516 isl_space *space;
517 isl_map *map;
519 if (!gen->options->debug->dump_sizes)
520 return;
522 space = isl_union_map_get_space(gen->used_sizes);
523 space = isl_space_set_from_params(space);
524 space = isl_space_add_dims(space, isl_dim_set, 1);
525 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
526 space = isl_space_from_domain(space);
527 space = isl_space_add_dims(space, isl_dim_out, len);
528 space = isl_space_set_tuple_name(space, isl_dim_out, type);
530 map = isl_map_universe(space);
531 map = isl_map_fix_si(map, isl_dim_in, 0, id);
532 for (i = 0; i < len; ++i)
533 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
535 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
538 /* Extract user specified "tile" sizes from the "sizes" command line option,
539 * defaulting to option->tile_size in each dimension.
540 * *tile_len contains the maximum number of tile sizes needed.
541 * Update *tile_len to the number of specified tile sizes, if any, and
542 * return a pointer to the tile sizes (or NULL on error).
543 * Add the effectively used sizes to gen->used_sizes.
545 static int *read_tile_sizes(struct gpu_gen *gen, int *tile_len)
547 int n;
548 int *tile_size;
549 isl_set *size;
551 tile_size = isl_alloc_array(gen->ctx, int, *tile_len);
552 if (!tile_size)
553 return NULL;
554 for (n = 0; n < *tile_len; ++n)
555 tile_size[n] = gen->options->tile_size;
557 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
558 read_sizes_from_set(size, tile_size, tile_len);
559 set_used_sizes(gen, "tile", gen->kernel_id, tile_size, *tile_len);
561 return tile_size;
564 /* Extract user specified "block" sizes from the "sizes" command line option,
565 * after filling in some potentially useful defaults.
567 static void read_block_sizes(struct ppcg_kernel *kernel,
568 __isl_keep isl_union_map *sizes)
570 isl_set *size;
572 if (kernel->n_block > 3)
573 kernel->n_block = 3;
574 switch (kernel->n_block) {
575 case 1:
576 kernel->block_dim[0] = 512;
577 break;
578 case 2:
579 kernel->block_dim[0] = 32;
580 kernel->block_dim[1] = 16;
581 break;
582 default:
583 kernel->block_dim[0] = 32;
584 kernel->block_dim[1] = 4;
585 kernel->block_dim[2] = 4;
586 break;
589 size = extract_sizes(sizes, "block", kernel->id);
590 read_sizes_from_set(size, kernel->block_dim, &kernel->n_block);
593 /* Extract user specified "grid" sizes from the "sizes" command line option,
594 * after filling in some potentially useful defaults.
596 static void read_grid_sizes(struct ppcg_kernel *kernel,
597 __isl_keep isl_union_map *sizes)
599 isl_set *size;
601 if (kernel->n_grid > 2)
602 kernel->n_grid = 2;
603 switch (kernel->n_grid) {
604 case 1:
605 kernel->grid_dim[0] = 32768;
606 break;
607 default:
608 kernel->grid_dim[0] = 256;
609 kernel->grid_dim[1] = 256;
610 break;
613 size = extract_sizes(sizes, "grid", kernel->id);
614 read_sizes_from_set(size, kernel->grid_dim, &kernel->n_grid);
617 /* Extract user specified grid and block sizes from the gen->sizes
618 * command line option after filling in some potentially useful defaults.
619 * Store the extracted sizes in "kernel".
620 * Add the effectively used sizes to gen->used_sizes.
622 static void read_grid_and_block_sizes(struct ppcg_kernel *kernel,
623 struct gpu_gen *gen)
625 read_block_sizes(kernel, gen->sizes);
626 read_grid_sizes(kernel, gen->sizes);
627 set_used_sizes(gen, "block", kernel->id,
628 kernel->block_dim, kernel->n_block);
629 set_used_sizes(gen, "grid", kernel->id,
630 kernel->grid_dim, kernel->n_grid);
633 static void *free_stmts(struct gpu_stmt *stmts, int n)
635 int i;
637 if (!stmts)
638 return NULL;
640 for (i = 0; i < n; ++i) {
641 struct gpu_stmt_access *access, *next;
643 for (access = stmts[i].accesses; access; access = next) {
644 next = access->next;
645 isl_id_free(access->ref_id);
646 isl_map_free(access->access);
647 isl_map_free(access->tagged_access);
648 free(access);
651 isl_id_free(stmts[i].id);
653 free(stmts);
655 return NULL;
658 /* Add parameters p[i] with identifiers "ids" to "set",
659 * with bounds to 0 <= p[i] < size[i].
661 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
662 int *size, __isl_keep isl_id_list *ids)
664 int i, len;
665 unsigned nparam;
667 len = isl_id_list_n_id(ids);
668 nparam = isl_set_dim(set, isl_dim_param);
669 set = isl_set_add_dims(set, isl_dim_param, len);
671 for (i = 0; i < len; ++i) {
672 isl_id *id;
674 id = isl_id_list_get_id(ids, i);
675 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
676 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
677 set = isl_set_upper_bound_si(set, isl_dim_param,
678 nparam + i, size[i] - 1);
681 return set;
684 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
685 * with
687 * { : 0 <= p[i] < size[i] }
689 * or an overapproximation.
691 static __isl_give isl_set *add_bounded_parameters_dynamic(
692 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
693 __isl_keep isl_id_list *ids)
695 int i, len;
696 unsigned nparam;
697 isl_space *space;
698 isl_local_space *ls;
700 len = isl_multi_pw_aff_dim(size, isl_dim_out);
701 nparam = isl_set_dim(set, isl_dim_param);
702 set = isl_set_add_dims(set, isl_dim_param, len);
704 for (i = 0; i < len; ++i) {
705 isl_id *id;
707 id = isl_id_list_get_id(ids, i);
708 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
711 space = isl_space_params(isl_set_get_space(set));
712 ls = isl_local_space_from_space(space);
713 for (i = 0; i < len; ++i) {
714 isl_pw_aff *param, *size_i, *zero;
715 isl_set *bound;
717 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
718 isl_dim_param, nparam + i);
720 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
721 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
722 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
723 set = isl_set_intersect_params(set, bound);
725 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
726 bound = isl_pw_aff_ge_set(param, zero);
727 set = isl_set_intersect_params(set, bound);
729 isl_local_space_free(ls);
731 return set;
734 /* Return the union of all tagged access relations in the group.
736 static __isl_give isl_union_map *group_tagged_access_relation(
737 struct gpu_array_ref_group *group)
739 int i;
740 isl_union_map *access;
742 access = isl_union_map_empty(isl_map_get_space(group->access));
743 for (i = 0; i < group->n_ref; ++i) {
744 isl_map *map_i;
746 map_i = isl_map_copy(group->refs[i]->tagged_access);
747 access = isl_union_map_union(access,
748 isl_union_map_from_map(map_i));
751 return access;
754 /* Return the extent of "array", recomputed from the bounds.
755 * The recomputed extent may be simpler than the original extent.
757 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
759 int i;
760 isl_id *id;
761 isl_space *space;
762 isl_local_space *ls;
763 isl_set *extent;
765 id = isl_set_get_tuple_id(array->extent);
766 space = isl_set_get_space(array->extent);
767 extent = isl_set_universe(isl_space_copy(space));
768 ls = isl_local_space_from_space(space);
769 for (i = 0; i < array->n_index; ++i) {
770 isl_pw_aff *bound;
771 isl_aff *aff;
772 isl_pw_aff *index;
773 isl_set *lt;
775 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
777 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
778 isl_dim_set, i);
779 index = isl_pw_aff_from_aff(aff);
780 bound = isl_pw_aff_copy(array->bound[i]);
781 bound = isl_pw_aff_from_range(bound);
782 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
783 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
784 isl_id_copy(id));
785 lt = isl_pw_aff_lt_set(index, bound);
786 extent = isl_set_intersect(extent, lt);
788 isl_local_space_free(ls);
789 isl_id_free(id);
791 return extent;
794 /* Return a map from the first group->depth dimensions of the computed
795 * schedule to the array tile in
796 * global memory that corresponds to the shared memory copy.
798 * In particular, return a map
800 * { D[i] -> A[a] }
802 * with constraints
804 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
806 * and
808 * 0 <= a <= array_size - 1 (2)
810 * Note that if some stride has been detected (i.e., when
811 * group->shared_tile->bound[i].shift is set), then a in (1) refers
812 * to the shifted and scaled down version.
814 * Constraints (1) are obtained by mapping the size constraints on the
815 * shared/private memory tile back to the access relation.
816 * Constraints (2) are obtained from the (recomputed) extent.
818 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
820 int i;
821 int n_index = group->array->n_index;
822 isl_map *tile;
823 isl_space *space;
824 isl_set *local;
825 isl_set *extent;
827 space = isl_multi_aff_get_space(group->shared_tile->tiling);
828 space = isl_space_range(space);
829 local = isl_set_universe(space);
830 for (i = 0; i < n_index; ++i) {
831 isl_val *bound;
833 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
834 bound = isl_val_copy(group->shared_tile->bound[i].size);
835 bound = isl_val_sub_ui(bound, 1);
836 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
838 local = isl_set_preimage_multi_aff(local,
839 isl_multi_aff_copy(group->shared_tile->tiling));
840 tile = isl_set_unwrap(local);
841 extent = array_extent(group->array);
842 tile = isl_map_intersect_range(tile, extent);
844 return tile;
847 /* Given a mapping "iterator_map" from the AST schedule to a domain,
848 * return the corresponding mapping from the AST schedule to
849 * to the outer kernel->shared_schedule_dim dimensions of
850 * the schedule computed by PPCG for this kernel.
852 * Note that kernel->shared_schedule_dim is at least as large as
853 * the largest depth of any array reference group associated to the kernel.
854 * This is needed as the returned schedule is used to extract a mapping
855 * to the outer group->depth dimensions in transform_index.
857 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(
858 struct ppcg_kernel *kernel, __isl_take isl_pw_multi_aff *iterator_map)
860 isl_union_pw_multi_aff *upma;
861 isl_pw_multi_aff *pma;
862 isl_space *space;
864 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
865 space = isl_space_from_domain(space);
866 space = isl_space_add_dims(space, isl_dim_out,
867 kernel->shared_schedule_dim);
869 upma = isl_union_pw_multi_aff_copy(kernel->shared_schedule);
870 pma = isl_union_pw_multi_aff_extract_pw_multi_aff(upma, space);
871 isl_union_pw_multi_aff_free(upma);
873 return isl_pw_multi_aff_pullback_pw_multi_aff(pma, iterator_map);
876 /* If max_shared_memory is not set to infinity (-1), then make
877 * sure that the total amount of shared memory required by the
878 * array reference groups mapped to shared memory by "kernel"
879 * is no larger than this maximum.
881 * We apply a greedy approach and discard (keep in global memory)
882 * those groups that would result in a total memory size that
883 * is larger than the maximum.
885 * This function should be called after any function that may
886 * affect the decision on whether to place a reference group
887 * in private, shared or global memory.
889 static void check_shared_memory_bound(struct ppcg_kernel *kernel)
891 int i, j;
892 isl_val *left, *size;
894 if (kernel->options->max_shared_memory < 0)
895 return;
897 left = isl_val_int_from_si(kernel->ctx,
898 kernel->options->max_shared_memory);
900 for (i = 0; i < kernel->n_array; ++i) {
901 struct gpu_local_array_info *local = &kernel->array[i];
903 for (j = 0; j < local->n_group; ++j) {
904 struct gpu_array_ref_group *group;
906 group = local->groups[j];
907 if (group->private_tile)
908 continue;
909 if (!group->shared_tile)
910 continue;
912 size = gpu_array_tile_size(group->shared_tile);
913 size = isl_val_mul_ui(size, local->array->size);
915 if (isl_val_le(size, left)) {
916 left = isl_val_sub(left, size);
917 continue;
919 isl_val_free(size);
921 group->shared_tile =
922 gpu_array_tile_free(group->shared_tile);
926 isl_val_free(left);
929 /* Compute a tiling for all the array reference groups in "kernel".
931 static void compute_group_tilings(struct ppcg_kernel *kernel)
933 int i, j;
935 for (i = 0; i < kernel->n_array; ++i) {
936 struct gpu_local_array_info *array = &kernel->array[i];
938 for (j = 0; j < array->n_group; ++j)
939 gpu_array_ref_group_compute_tiling(array->groups[j]);
943 /* Compute the size of a bounding box around the origin and "set",
944 * where "set" is assumed to contain only non-negative elements.
945 * In particular, compute the maximal value of "set" in each direction
946 * and add one.
948 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
949 __isl_take isl_set *context)
951 int i, n;
952 isl_multi_pw_aff *mpa;
954 context = isl_set_params(context);
955 n = isl_set_dim(set, isl_dim_set);
956 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
957 for (i = 0; i < n; ++i) {
958 isl_space *space;
959 isl_aff *one;
960 isl_pw_aff *bound;
962 bound = isl_set_dim_max(isl_set_copy(set), i);
963 bound = isl_pw_aff_coalesce(bound);
964 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
966 space = isl_pw_aff_get_domain_space(bound);
967 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
968 one = isl_aff_add_constant_si(one, 1);
969 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
970 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
972 isl_set_free(set);
973 isl_set_free(context);
975 return mpa;
978 /* Compute the effective grid size as a list of the sizes in each dimension.
980 * The grid size specified by the user or set by default
981 * in read_grid_sizes() and applied by the block filter,
982 * may be too large for the given code in the sense that
983 * it may contain blocks that don't need to execute anything.
984 * We therefore don't return this grid size, but instead the
985 * smallest grid size that ensures that all blocks that actually
986 * execute code are included in the grid.
988 * We first extract a description of the grid, i.e., the possible values
989 * of the block ids, from the domain elements in "domain" and
990 * kernel->block_filter.
991 * The block ids are parameters in kernel->block_filter.
992 * We simply need to change them into set dimensions.
994 * Then, for each block dimension, we compute the maximal value of the block id
995 * and add one.
997 static __isl_give isl_multi_pw_aff *extract_grid_size(
998 struct ppcg_kernel *kernel, __isl_take isl_union_set *domain)
1000 int i;
1001 isl_set *grid;
1003 domain = isl_union_set_intersect(domain,
1004 isl_union_set_copy(kernel->block_filter));
1005 grid = isl_union_set_params(domain);
1006 grid = isl_set_from_params(grid);
1007 grid = isl_set_add_dims(grid, isl_dim_set, kernel->n_grid);
1008 for (i = 0; i < kernel->n_grid; ++i) {
1009 int pos;
1010 isl_id *id;
1012 id = isl_id_list_get_id(kernel->block_ids, i);
1013 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1014 isl_id_free(id);
1015 assert(pos >= 0);
1016 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1017 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1020 return extract_size(grid, isl_set_copy(kernel->context));
1023 /* Compute the size of a fixed bounding box around the origin and "set",
1024 * where "set" is assumed to contain only non-negative elements,
1025 * and store the results in "size".
1026 * In particular, compute the maximal value of "set" in each direction
1027 * and add one.
1029 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1031 int i, n;
1032 isl_local_space *ls;
1033 isl_aff *obj;
1035 n = isl_set_dim(set, isl_dim_set);
1036 ls = isl_local_space_from_space(isl_set_get_space(set));
1037 obj = isl_aff_zero_on_domain(ls);
1038 for (i = 0; i < n; ++i) {
1039 isl_val *max;
1041 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1042 max = isl_set_max_val(set, obj);
1043 size[i] = isl_val_get_num_si(max) + 1;
1044 isl_val_free(max);
1045 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1047 isl_aff_free(obj);
1048 isl_set_free(set);
1051 /* Compute the effective block size as a list of the sizes in each dimension
1052 * and store the sizes in kernel->block_dim.
1054 * The block size specified by the user or set by default
1055 * in read_block_sizes() and applied by the thread filter,
1056 * may be too large for the given code in the sense that
1057 * it may contain threads that don't need to execute anything.
1058 * We therefore update this block size in kernel->block_dim
1059 * to the smallest block size that ensures that all threads
1060 * that actually execute code are included in the block.
1062 * The possible values of the thread ids is obtained from
1063 * the domain elements "domain" and kernel->thread_filter.
1064 * The current implementation eliminates all parameters, ensuring
1065 * that the size is a fixed constant in each dimension.
1066 * In principle we could also compute parametric sizes.
1067 * We would have to make sure to project out all b%d and t%d parameters,
1068 * however.
1070 static void extract_block_size(struct ppcg_kernel *kernel,
1071 __isl_take isl_union_set *domain)
1073 int i;
1074 int nparam;
1075 isl_set *block;
1077 domain = isl_union_set_intersect(domain,
1078 isl_union_set_copy(kernel->thread_filter));
1079 block = isl_union_set_params(domain);
1080 block = isl_set_from_params(block);
1081 block = isl_set_add_dims(block, isl_dim_set, kernel->n_block);
1082 for (i = 0; i < kernel->n_block; ++i) {
1083 int pos;
1084 isl_id *id;
1086 id = isl_id_list_get_id(kernel->thread_ids, i);
1087 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1088 isl_id_free(id);
1089 assert(pos >= 0);
1090 block = isl_set_equate(block, isl_dim_param, pos,
1091 isl_dim_set, i);
1093 nparam = isl_set_dim(block, isl_dim_param);
1094 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1096 extract_fixed_size(block, kernel->block_dim);
1099 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1101 int i, j;
1103 if (!kernel)
1104 return NULL;
1106 isl_id_list_free(kernel->block_ids);
1107 isl_id_list_free(kernel->thread_ids);
1108 isl_multi_pw_aff_free(kernel->grid_size);
1109 isl_set_free(kernel->context);
1110 isl_union_set_free(kernel->core);
1111 isl_union_set_free(kernel->arrays);
1112 isl_space_free(kernel->space);
1113 isl_ast_node_free(kernel->tree);
1114 isl_union_set_free(kernel->block_filter);
1115 isl_union_set_free(kernel->thread_filter);
1116 isl_union_pw_multi_aff_free(kernel->shared_schedule);
1117 isl_union_set_free(kernel->sync_writes);
1119 for (i = 0; i < kernel->n_array; ++i) {
1120 struct gpu_local_array_info *array = &kernel->array[i];
1122 for (j = 0; j < array->n_group; ++j)
1123 gpu_array_ref_group_free(array->groups[j]);
1124 free(array->groups);
1126 isl_pw_aff_list_free(array->bound);
1128 free(kernel->array);
1130 for (i = 0; i < kernel->n_var; ++i) {
1131 free(kernel->var[i].name);
1132 isl_vec_free(kernel->var[i].size);
1134 free(kernel->var);
1136 free(kernel);
1138 return NULL;
1141 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1143 static void ppcg_kernel_free_wrap(void *user)
1145 struct ppcg_kernel *kernel = user;
1147 ppcg_kernel_free(kernel);
1150 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1151 struct ppcg_kernel_var *var)
1153 int j;
1154 struct gpu_array_tile *tile;
1155 isl_printer *p;
1156 char *name;
1158 var->array = group->array;
1160 tile = group->private_tile;
1161 var->type = ppcg_access_private;
1162 if (!tile) {
1163 tile = group->shared_tile;
1164 var->type = ppcg_access_shared;
1167 p = isl_printer_to_str(ctx);
1168 p = gpu_array_ref_group_print_name(group, p);
1169 var->name = isl_printer_get_str(p);
1170 isl_printer_free(p);
1172 var->size = isl_vec_alloc(ctx, group->array->n_index);
1174 for (j = 0; j < group->array->n_index; ++j)
1175 var->size = isl_vec_set_element_val(var->size, j,
1176 isl_val_copy(tile->bound[j].size));
1179 static int create_kernel_vars(struct ppcg_kernel *kernel)
1181 int i, j, n;
1183 n = 0;
1184 for (i = 0; i < kernel->n_array; ++i) {
1185 struct gpu_local_array_info *array = &kernel->array[i];
1187 for (j = 0; j < array->n_group; ++j) {
1188 struct gpu_array_ref_group *group = array->groups[j];
1189 if (group->private_tile || group->shared_tile)
1190 ++n;
1194 kernel->n_var = n;
1195 kernel->var = isl_calloc_array(kernel->ctx, struct ppcg_kernel_var, n);
1196 if (!kernel->var)
1197 return -1;
1199 n = 0;
1200 for (i = 0; i < kernel->n_array; ++i) {
1201 struct gpu_local_array_info *array = &kernel->array[i];
1203 for (j = 0; j < array->n_group; ++j) {
1204 struct gpu_array_ref_group *group = array->groups[j];
1205 if (!group->private_tile && !group->shared_tile)
1206 continue;
1207 create_kernel_var(kernel->ctx, group, &kernel->var[n]);
1208 ++n;
1212 return 0;
1215 /* Replace "pa" by the zero function defined over the universe domain
1216 * in the space of "pa".
1218 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1220 isl_space *space;
1221 isl_aff *zero;
1223 space = isl_space_domain(isl_pw_aff_get_space(pa));
1224 isl_pw_aff_free(pa);
1225 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1227 return isl_pw_aff_from_aff(zero);
1230 /* The sizes of the arrays on the host that have been computed by
1231 * extract_array_info may depend on the parameters. Use the extra
1232 * constraints on the parameters that are valid at "host_domain"
1233 * to simplify these expressions and store the results in kernel->array.
1235 * We only need these localized bounds for arrays that are accessed
1236 * by the current kernel. If we have found at least one reference group
1237 * then the array is accessed by the kernel. If the array has compound
1238 * elements then we skipped the construction of array reference groups.
1240 * The resulting sizes may be functions that are nowhere defined
1241 * in case the access function cannot possibly access anything inside
1242 * the kernel for some reason. If so, they are replaced by the zero
1243 * function. Since the access function cannot actually access anything,
1244 * there is no harm in printing the array sizes as zero.
1246 static void localize_bounds(struct ppcg_kernel *kernel,
1247 __isl_keep isl_set *host_domain)
1249 int i, j;
1250 isl_set *context;
1252 context = isl_set_copy(host_domain);
1253 context = isl_set_params(context);
1255 for (i = 0; i < kernel->n_array; ++i) {
1256 struct gpu_local_array_info *local = &kernel->array[i];
1257 isl_pw_aff_list *bound;
1258 int n_index;
1260 if (local->n_group == 0 && !local->array->has_compound_element)
1261 continue;
1263 n_index = local->array->n_index;
1264 bound = isl_pw_aff_list_alloc(kernel->ctx, n_index);
1266 for (j = 0; j < n_index; ++j) {
1267 isl_pw_aff *pwaff;
1268 int empty;
1270 pwaff = isl_pw_aff_copy(local->array->bound[j]);
1271 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1272 empty = isl_pw_aff_is_empty(pwaff);
1273 if (empty < 0)
1274 pwaff = isl_pw_aff_free(pwaff);
1275 else if (empty)
1276 pwaff = set_universally_zero(pwaff);
1277 bound = isl_pw_aff_list_add(bound, pwaff);
1280 local->n_index = n_index;
1281 local->bound = bound;
1283 isl_set_free(context);
1286 /* Create the array of gpu_local_array_info structures "array"
1287 * inside "kernel". The number of elements in this array is
1288 * the same as the number of arrays in "prog".
1289 * Initialize the "array" field of each local array to point
1290 * to the corresponding array in "prog".
1292 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1293 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1295 int i;
1296 isl_ctx *ctx;
1298 ctx = isl_set_get_ctx(prog->context);
1299 kernel->array = isl_calloc_array(ctx,
1300 struct gpu_local_array_info, prog->n_array);
1301 if (!kernel->array)
1302 return ppcg_kernel_free(kernel);
1303 kernel->n_array = prog->n_array;
1305 for (i = 0; i < prog->n_array; ++i)
1306 kernel->array[i].array = &prog->array[i];
1308 return kernel;
1311 /* Find the element in gen->stmt that has the given "id".
1312 * Return NULL if no such gpu_stmt can be found.
1314 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1316 int i;
1318 for (i = 0; i < prog->n_stmts; ++i) {
1319 if (id == prog->stmts[i].id)
1320 break;
1323 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1326 void ppcg_kernel_stmt_free(void *user)
1328 int i;
1329 struct ppcg_kernel_stmt *stmt = user;
1331 if (!stmt)
1332 return;
1334 switch (stmt->type) {
1335 case ppcg_kernel_copy:
1336 isl_ast_expr_free(stmt->u.c.index);
1337 isl_ast_expr_free(stmt->u.c.local_index);
1338 break;
1339 case ppcg_kernel_domain:
1340 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1341 break;
1342 case ppcg_kernel_sync:
1343 break;
1346 free(stmt);
1349 /* Return the gpu_stmt_access in the list "accesses" that corresponds
1350 * to "ref_id".
1352 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1353 __isl_keep isl_id *ref_id)
1355 struct gpu_stmt_access *access;
1357 for (access = accesses; access; access = access->next)
1358 if (access->ref_id == ref_id)
1359 return access;
1361 return NULL;
1364 /* Return the index of the array called "name" in the list of arrays.
1366 static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1368 int i;
1370 for (i = 0; i < kernel->n_array; ++i)
1371 if (!strcmp(name, kernel->array[i].array->name))
1372 return i;
1374 return -1;
1377 /* Internal data structure for the index and AST expression transformation
1378 * callbacks for pet_stmt_build_ast_exprs.
1380 * "kernel" is the kernel for which are computing AST expressions.
1381 * "accesses" is the list of gpu_stmt_access in the statement.
1382 * "iterator_map" expresses the statement iterators in terms of
1383 * the AST loop iterators.
1384 * "sched2shared" expresses the outer shared_schedule_dim dimensions of
1385 * the kernel schedule in terms of the AST loop iterators.
1387 * The following fields are set in transform_index and used in transform_expr.
1388 * "array" is the array that is being accessed.
1389 * "global" is set if the global array is accessed (rather than
1390 * shared/private memory).
1391 * "local_array" refers to information on the array specialized
1392 * to the current kernel.
1394 struct ppcg_transform_data {
1395 struct ppcg_kernel *kernel;
1396 struct gpu_stmt_access *accesses;
1397 isl_pw_multi_aff *iterator_map;
1398 isl_pw_multi_aff *sched2shared;
1400 struct gpu_array_info *array;
1401 int global;
1402 struct gpu_local_array_info *local_array;
1405 /* Return the name of the outer array (of structs) accessed by "access".
1407 static const char *get_outer_array_name(__isl_keep isl_map *access)
1409 isl_space *space;
1410 const char *name;
1412 space = isl_space_range(isl_map_get_space(access));
1413 while (space && isl_space_is_wrapping(space))
1414 space = isl_space_domain(isl_space_unwrap(space));
1415 name = isl_space_get_tuple_name(space, isl_dim_set);
1416 isl_space_free(space);
1418 return name;
1421 /* Return a pointer to the gpu_array_ref_group in "local"
1422 * that contains the reference "access".
1423 * Return NULL if no such group can be found.
1425 static struct gpu_array_ref_group *find_ref_group(
1426 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1428 int i, j;
1430 for (i = 0; i < local->n_group; ++i) {
1431 struct gpu_array_ref_group *group = local->groups[i];
1433 for (j = 0; j < group->n_ref; ++j)
1434 if (group->refs[j] == access)
1435 return group;
1438 return NULL;
1441 /* Index transformation callback for pet_stmt_build_ast_exprs.
1443 * "index" expresses the array indices in terms of statement iterators
1445 * We first reformulate "index" in terms of the AST loop iterators.
1446 * Then we check if we are accessing the global array or
1447 * a shared/private copy. 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 access = find_access(data->accesses, ref_id);
1502 if (!access)
1503 return index;
1504 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1505 return index;
1507 name = get_outer_array_name(access->access);
1508 i = find_array_index(data->kernel, name);
1509 if (i < 0)
1510 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
1511 "cannot find array",
1512 return isl_multi_pw_aff_free(index));
1513 data->local_array = &data->kernel->array[i];
1514 data->array = data->local_array->array;
1516 group = find_ref_group(data->local_array, access);
1517 if (!group) {
1518 data->global = 1;
1519 return index;
1522 tile = group->private_tile;
1523 if (!tile)
1524 tile = group->shared_tile;
1525 data->global = !tile;
1526 if (!tile)
1527 return index;
1529 space = isl_space_range(isl_multi_pw_aff_get_space(index));
1530 space = isl_space_map_from_set(space);
1531 pma = isl_pw_multi_aff_identity(space);
1532 sched2depth = isl_pw_multi_aff_copy(data->sched2shared);
1533 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1534 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1535 group->depth, dim - group->depth);
1536 pma = isl_pw_multi_aff_product(sched2depth, pma);
1537 tiling = isl_multi_pw_aff_from_multi_aff(
1538 isl_multi_aff_copy(tile->tiling));
1539 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1541 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1542 space = isl_space_map_from_set(space);
1543 mpa = isl_multi_pw_aff_identity(space);
1544 index = isl_multi_pw_aff_range_product(mpa, index);
1545 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1547 return index;
1550 /* Dereference "expr" by adding an index [0].
1551 * The original "expr" is assumed not to have any indices.
1553 * If "expr" is a member access, then the dereferencing needs
1554 * to be applied to the structure argument of this member access.
1556 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1558 isl_ctx *ctx;
1559 isl_ast_expr *arg0, *res;
1560 isl_ast_expr_list *list;
1562 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1563 if (!arg0)
1564 return isl_ast_expr_free(expr);
1565 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1566 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1567 isl_ast_expr *arg;
1569 arg = isl_ast_expr_get_op_arg(arg0, 0);
1570 arg = dereference(arg);
1571 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1572 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1574 return expr;
1576 isl_ast_expr_free(arg0);
1578 ctx = isl_ast_expr_get_ctx(expr);
1579 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1580 list = isl_ast_expr_list_from_ast_expr(res);
1581 res = isl_ast_expr_get_op_arg(expr, 0);
1582 res = isl_ast_expr_access(res, list);
1583 isl_ast_expr_free(expr);
1585 return res;
1588 /* Linearize the index expression "expr" based on the array bounds
1589 * of "array".
1591 * That is, transform expression
1593 * A[i_0][i_1]...[i_n]
1595 * to
1597 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1599 * where b_0, b_1, ..., b_n are the bounds on the array.
1601 * If the base of "expr" is a member access, then the linearization needs
1602 * to be applied to the structure argument of this member access.
1604 * In the base case, if "expr" has no arguments (other than the name of
1605 * the array), then we are passing an entire array to a function.
1606 * In this case, there is nothing to linearize.
1607 * Note that at this point an expression with no arguments can
1608 * only be an entire array because the scalar case and
1609 * the case of single struct are handled by the caller.
1611 * If the number of specified index expressions in "expr"
1612 * is smaller than the dimension of the accessed array,
1613 * then the missing i_j also do not appear in the linearized expression.
1614 * Furthermore, since such an expression does not refer to a single
1615 * element while the default linearized expression would refer to
1616 * a single element, we return the expression
1618 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
1620 * instead. Note that because of the special case handling above,
1621 * we can assume here that here that there is at least one index expression.
1623 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1624 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1626 int i, n;
1627 isl_ctx *ctx;
1628 isl_set *context;
1629 isl_ast_expr *arg0;
1630 isl_ast_expr *res;
1631 isl_ast_expr_list *list;
1632 isl_ast_build *build;
1634 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1635 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1636 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1637 isl_ast_expr *arg;
1639 arg = isl_ast_expr_get_op_arg(arg0, 0);
1640 arg = gpu_local_array_info_linearize_index(array, arg);
1641 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1642 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1644 return expr;
1646 isl_ast_expr_free(arg0);
1648 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1649 return expr;
1651 ctx = isl_ast_expr_get_ctx(expr);
1652 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
1653 build = isl_ast_build_from_context(context);
1655 n = isl_ast_expr_get_op_n_arg(expr);
1656 res = isl_ast_expr_get_op_arg(expr, 1);
1657 for (i = 1; i < array->n_index; ++i) {
1658 isl_pw_aff *bound_i;
1659 isl_ast_expr *expr_i;
1661 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
1662 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
1663 res = isl_ast_expr_mul(res, expr_i);
1665 if (i + 1 >= n)
1666 continue;
1667 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1668 res = isl_ast_expr_add(res, expr_i);
1671 isl_ast_build_free(build);
1673 if (1 + array->n_index > n) {
1674 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1675 } else {
1676 list = isl_ast_expr_list_from_ast_expr(res);
1677 res = isl_ast_expr_get_op_arg(expr, 0);
1678 res = isl_ast_expr_access(res, list);
1681 isl_ast_expr_free(expr);
1683 return res;
1686 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
1688 * If the AST expression refers to an array that is not accessed
1689 * at all, then this means the value of the expression is not used,
1690 * so we might as well print zero (NULL pointer) instead.
1692 * If the AST expression refers to a global scalar that is not
1693 * a read-only scalar, then its address was passed to the kernel and
1694 * we need to dereference it.
1696 * If the AST expression refers to an access to a global array,
1697 * then we linearize the access exploiting the bounds in data->local_array.
1699 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1700 __isl_keep isl_id *id, void *user)
1702 struct ppcg_transform_data *data = user;
1704 if (!data->array)
1705 return expr;
1706 if (!data->array->accessed) {
1707 isl_ctx *ctx;
1709 ctx = isl_ast_expr_get_ctx(expr);
1710 isl_ast_expr_free(expr);
1711 return isl_ast_expr_from_val(isl_val_zero(ctx));
1713 if (gpu_array_is_read_only_scalar(data->array))
1714 return expr;
1715 if (!data->global)
1716 return expr;
1717 if (data->array->n_index == 0)
1718 return dereference(expr);
1719 if (!data->array->linearize)
1720 return expr;
1722 return gpu_local_array_info_linearize_index(data->local_array, expr);
1725 /* This function is called for each instance of a user statement
1726 * in the kernel "kernel", identified by "gpu_stmt".
1728 * We attach a struct ppcg_kernel_stmt to the "node", containing
1729 * a computed AST expression for each access.
1730 * These AST expressions are computed from iterator_map,
1731 * which expresses the domain
1732 * elements in terms of the generated loops, and sched2shared,
1733 * which expresses the outer shared_schedule_dim dimensions of
1734 * the kernel schedule computed by PPCG in terms of the generated loops.
1736 static __isl_give isl_ast_node *create_domain_leaf(
1737 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1738 __isl_keep isl_ast_build *build, struct gpu_stmt *gpu_stmt)
1740 struct ppcg_transform_data data;
1741 struct ppcg_kernel_stmt *stmt;
1742 isl_id *id;
1743 isl_pw_multi_aff *sched2shared;
1744 isl_map *map;
1745 isl_pw_multi_aff *iterator_map;
1746 isl_union_map *schedule;
1748 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1749 if (!stmt)
1750 return isl_ast_node_free(node);
1752 schedule = isl_ast_build_get_schedule(build);
1753 map = isl_map_reverse(isl_map_from_union_map(schedule));
1754 iterator_map = isl_pw_multi_aff_from_map(map);
1755 sched2shared = compute_sched_to_shared(kernel,
1756 isl_pw_multi_aff_copy(iterator_map));
1758 stmt->type = ppcg_kernel_domain;
1759 stmt->u.d.stmt = gpu_stmt;
1761 data.kernel = kernel;
1762 data.accesses = stmt->u.d.stmt->accesses;
1763 data.iterator_map = iterator_map;
1764 data.sched2shared = sched2shared;
1765 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
1766 build, &transform_index, &data,
1767 &transform_expr, &data);
1769 isl_pw_multi_aff_free(iterator_map);
1770 isl_pw_multi_aff_free(sched2shared);
1772 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1773 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1774 return isl_ast_node_set_annotation(node, id);
1777 /* This function is called for each statement node in the AST
1778 * for copying to or from shared/private memory.
1779 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1780 * statement to the node.
1781 * The statement name is "read" or "write", depending on whether we are
1782 * reading from global memory or writing to global memory.
1784 * The schedule is of the form
1786 * type[D -> A] -> L
1788 * where D corresponds to the outer group->depth dimensions of
1789 * the kernel schedule, A to the global array and L to the outer
1790 * generated AST schedule.
1791 * We compute the inverse and strip off the type, resulting in
1793 * L -> [D -> A]
1795 * We combine this mapping with on the one hand the projection
1797 * [D -> A] -> A
1799 * and on the other hand the group tiling
1801 * [D -> A] -> T
1803 * resulting in
1805 * L -> A and L -> T
1807 * and store the corresponding expressions in stmt->index and stmt->local_index,
1808 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1810 static __isl_give isl_ast_node *create_access_leaf(struct ppcg_kernel *kernel,
1811 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1812 __isl_keep isl_ast_build *build)
1814 struct ppcg_kernel_stmt *stmt;
1815 struct gpu_array_tile *tile;
1816 isl_id *id;
1817 isl_ast_expr *expr;
1818 isl_space *space;
1819 isl_map *access;
1820 isl_pw_multi_aff *pma, *pma2;
1821 const char *type;
1823 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1824 if (!stmt)
1825 return isl_ast_node_free(node);
1827 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1828 type = isl_map_get_tuple_name(access, isl_dim_in);
1829 stmt->u.c.read = !strcmp(type, "read");
1830 access = isl_map_reverse(access);
1831 pma = isl_pw_multi_aff_from_map(access);
1832 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1834 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1835 space = isl_space_unwrap(space);
1836 pma2 = isl_pw_multi_aff_range_map(space);
1837 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1838 isl_pw_multi_aff_copy(pma));
1839 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1840 stmt->u.c.index = expr;
1842 tile = gpu_array_ref_group_tile(group);
1843 pma2 = isl_pw_multi_aff_from_multi_aff(
1844 isl_multi_aff_copy(tile->tiling));
1845 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1846 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1847 stmt->u.c.local_index = expr;
1849 stmt->u.c.array = group->array;
1850 stmt->u.c.local_array = group->local_array;
1851 stmt->type = ppcg_kernel_copy;
1853 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1854 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1855 return isl_ast_node_set_annotation(node, id);
1858 /* Create a synchronization ppcg_kernel_stmt and
1859 * attach it to the node "node" representing the synchronization.
1861 static __isl_give isl_ast_node *create_sync_leaf(
1862 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1863 __isl_keep isl_ast_build *build)
1865 struct ppcg_kernel_stmt *stmt;
1866 isl_id *id;
1868 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1869 if (!stmt)
1870 return isl_ast_node_free(node);
1872 stmt->type = ppcg_kernel_sync;
1873 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1874 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1875 return isl_ast_node_set_annotation(node, id);
1878 /* Internal data structure for at_domain.
1880 * "prog" represents the entire scop.
1881 * "kernel" points to the kernel to which the current schedule node
1882 * belongs. It is set by before_mark and reset by after_mark.
1884 struct ppcg_at_domain_data {
1885 struct gpu_prog *prog;
1886 struct ppcg_kernel *kernel;
1889 /* This function is called for each instance of a user statement
1890 * in the kernel. This may be one of the original user statements
1891 * or a statement introduced by PPCG.
1893 * We assume that the original user statements only have a name
1894 * and no user pointer. The statements introduced by PPCG
1895 * on the other hand all have a user pointer.
1897 * If the user statement is one of the original user statements
1898 * (one with no user pointer), then we call create_domain_leaf. Otherwise,
1899 * we check if it is a copy or synchronization statement and
1900 * call the appropriate functions.
1902 static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
1903 __isl_keep isl_ast_build *build, void *user)
1905 struct ppcg_at_domain_data *data = user;
1906 isl_ast_expr *expr, *arg;
1907 isl_id *id;
1908 int is_sync;
1909 const char *name;
1910 void *p;
1912 expr = isl_ast_node_user_get_expr(node);
1913 arg = isl_ast_expr_get_op_arg(expr, 0);
1914 id = isl_ast_expr_get_id(arg);
1915 name = isl_id_get_name(id);
1916 p = isl_id_get_user(id);
1917 isl_ast_expr_free(expr);
1918 isl_ast_expr_free(arg);
1920 if (!p) {
1921 struct gpu_stmt *gpu_stmt;
1923 gpu_stmt = find_stmt(data->prog, id);
1924 isl_id_free(id);
1925 if (!gpu_stmt)
1926 isl_die(data->prog->ctx, isl_error_internal,
1927 "statement not found",
1928 return isl_ast_node_free(node));
1930 return create_domain_leaf(data->kernel, node, build, gpu_stmt);
1933 is_sync = gpu_tree_id_is_sync(id, data->kernel);
1934 isl_id_free(id);
1935 if (is_sync < 0)
1936 return isl_ast_node_free(node);
1937 if (!strcmp(name, "read") || !strcmp(name, "write")) {
1938 struct gpu_array_ref_group *group = p;
1939 return create_access_leaf(data->kernel, group, node, build);
1941 if (!is_sync)
1942 isl_die(data->prog->ctx, isl_error_internal,
1943 "unknown statement type",
1944 return isl_ast_node_free(node));
1945 return create_sync_leaf(data->kernel, node, build);
1948 /* Given a set of wrapped references "ref", return the corresponding
1949 * access relations based on the tagged access relations "tagged".
1951 * The elements of "ref" are of the form
1953 * [D -> R]
1955 * with D an iteration domains and R a reference.
1956 * The elements of "tagged" are of the form
1958 * [D -> R] -> A
1960 * with A an array.
1962 * Extend "tagged" to include the iteration domain in the range, i.e.,
1964 * [D -> R] -> [D -> A]
1966 * apply the result to "ref" and then unwrap the resulting set
1967 * to obtain relations of the form
1969 * D -> A
1971 static __isl_give isl_union_map *wrapped_reference_to_access(
1972 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
1974 isl_union_map *tag2access;
1976 tag2access = isl_union_map_copy(tagged);
1977 tag2access = isl_union_map_universe(tag2access);
1978 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
1979 tag2access = isl_union_map_domain_map(tag2access);
1980 tag2access = isl_union_map_range_product(tag2access, tagged);
1982 ref = isl_union_set_coalesce(ref);
1983 ref = isl_union_set_apply(ref, tag2access);
1985 return isl_union_set_unwrap(ref);
1988 /* Given an access relation "access" from "group", remove those reads
1989 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
1990 * communicate data within the same iteration of "sched".
1992 * If the access is a read then it is either an element of
1994 * live_in union (range flow)
1996 * where live_in and flow may be overapproximations, or
1997 * it reads an uninitialized value (that is not live-in because
1998 * there is an intermediate kill) or it reads a value that was
1999 * written within the same (compound) statement instance.
2000 * If the access is a write then it is either an element of
2002 * live_out union (domain flow)
2004 * or it writes a value that is never read (and is not live-out
2005 * because of an intermediate kill) or only
2006 * within the same (compound) statement instance.
2007 * In both cases, the access relation is also a subset of
2008 * the group access relation.
2010 * The cases where an uninitialized value is read or a value is written
2011 * that is never read or where the dataflow occurs within a statement
2012 * instance are also considered local and may also be removed.
2014 * Essentially, we compute the intersection of "access" with either
2016 * live_in union (range non-local-flow)
2018 * or
2020 * live_out union (domain non-local-flow)
2022 * We first construct a relation "local"
2024 * [[D -> R] -> [D' -> R']]
2026 * of pairs of domain iterations accessing the reference group
2027 * and references in the group that are coscheduled by "sched".
2029 * If this relation does not intersect the dataflow dependences,
2030 * then there is nothing we can possibly remove, unless the dataflow
2031 * dependences themselves only relate a subset of the accesses.
2032 * In particular, the accesses may not be involved in any dataflow
2033 * dependences, either because they are uninitialized reads/dead writes
2034 * or because the dataflow occurs inside a statement instance.
2036 * Since the computation below may break up the access relation
2037 * into smaller pieces, we only perform the intersection with
2038 * the non-local dependent accesses if the local pairs
2039 * intersect the dataflow dependences. Otherwise, we intersect
2040 * with the universe of the non-local dependent accesses.
2041 * This should at least remove accesses from statements that
2042 * do not participate in any dependences.
2044 * In particular, we remove the "local" dataflow dependences from
2045 * the set of all dataflow dependences.
2046 * Note that if the potential dataflow dependences are an overapproximation
2047 * of the actual dataflow dependences, then the result remains an
2048 * overapproximation of the non-local dataflow dependences.
2049 * Copying to/from global memory is only needed for the references
2050 * in the domain/range of the result or for accesses that are live out/in
2051 * for the entire scop.
2053 * We therefore map the domain/range of the "external" relation
2054 * to the corresponding access relation and take the union with
2055 * the live out/in relation.
2057 static __isl_give isl_union_map *remove_local_accesses(
2058 struct gpu_prog *prog, struct gpu_array_ref_group *group,
2059 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2060 int read)
2062 int empty;
2063 isl_union_pw_multi_aff *tagger;
2064 isl_union_set *domain;
2065 isl_union_map *local, *tagged, *external;
2066 isl_union_set *tag_set;
2068 if (isl_union_map_is_empty(access)) {
2069 isl_union_map_free(sched);
2070 return access;
2073 tagged = group_tagged_access_relation(group);
2075 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2076 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2077 tagger = isl_union_pw_multi_aff_intersect_domain(tagger, domain);
2078 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2080 local = isl_union_map_apply_range(sched,
2081 isl_union_map_reverse(isl_union_map_copy(sched)));
2082 local = isl_union_map_intersect(local,
2083 isl_union_map_copy(prog->scop->tagged_dep_flow));
2085 empty = isl_union_map_is_empty(local);
2087 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2088 external = isl_union_map_intersect_params(external,
2089 isl_set_copy(prog->scop->context));
2090 external = isl_union_map_subtract(external, local);
2092 if (read) {
2093 tag_set = isl_union_map_range(external);
2094 external = wrapped_reference_to_access(tag_set, tagged);
2095 external = isl_union_map_union(external,
2096 isl_union_map_copy(prog->scop->live_in));
2097 } else {
2098 tag_set = isl_union_map_domain(external);
2099 external = wrapped_reference_to_access(tag_set, tagged);
2100 external = isl_union_map_union(external,
2101 isl_union_map_copy(prog->scop->live_out));
2104 if (empty < 0)
2105 external = isl_union_map_free(external);
2106 else if (empty)
2107 external = isl_union_map_universe(external);
2109 access = isl_union_map_intersect(access, external);
2111 return access;
2114 /* Given an access relation "access" from "group", remove those reads
2115 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2116 * communicate data within the same iteration of the schedule at the
2117 * position where the copying of the group is inserted.
2118 * "node" points to this position, i.e., the depth at "node"
2119 * is equal to group->depth.
2121 * We extract a schedule that picks out the iterations of the outer
2122 * group->depth dimensions and call remove_local_accesses.
2124 static __isl_give isl_union_map *remove_local_accesses_group(
2125 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2126 __isl_take isl_union_map *access, __isl_keep isl_schedule_node *node,
2127 int read)
2129 isl_union_map *sched;
2131 if (isl_union_map_is_empty(access))
2132 return access;
2134 sched = isl_schedule_node_get_prefix_schedule_relation(node);
2136 return remove_local_accesses(kernel->prog, group, access, sched, read);
2139 /* This function is called before the AST generator starts traversing
2140 * the schedule subtree of a node with mark "mark".
2142 * If the mark is called "kernel", store the kernel pointer in data->kernel
2143 * for use in at_domain.
2145 static int before_mark(__isl_keep isl_id *mark,
2146 __isl_keep isl_ast_build *build, void *user)
2148 struct ppcg_at_domain_data *data = user;
2150 if (!mark)
2151 return -1;
2152 if (!strcmp(isl_id_get_name(mark), "kernel"))
2153 data->kernel = isl_id_get_user(mark);
2154 return 0;
2157 /* This function is called after the AST generator has finished traversing
2158 * the schedule subtree of a mark node. "node" points to the corresponding
2159 * mark AST node.
2161 * If the mark is called "kernel", then replace "node" by a user node
2162 * that "calls" the kernel, representing the launch of the kernel.
2163 * The original "node" is stored inside the kernel object so that
2164 * it can be used to print the device code.
2165 * Note that this assumes that a kernel is only launched once.
2166 * Also clear data->kernel.
2168 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2169 __isl_keep isl_ast_build *build, void *user)
2171 isl_ctx *ctx;
2172 isl_id *id;
2173 isl_ast_expr *expr;
2174 isl_ast_expr_list *list;
2175 struct ppcg_kernel *kernel;
2176 struct ppcg_at_domain_data *data = user;
2178 ctx = isl_ast_node_get_ctx(node);
2179 id = isl_ast_node_mark_get_id(node);
2180 if (!id)
2181 return isl_ast_node_free(node);
2182 if (strcmp(isl_id_get_name(id), "kernel") || !data->kernel) {
2183 isl_id_free(id);
2184 return node;
2186 kernel = data->kernel;
2187 data->kernel = NULL;
2188 kernel->space = isl_ast_build_get_schedule_space(build);
2189 kernel->tree = isl_ast_node_mark_get_node(node);
2190 isl_ast_node_free(node);
2192 expr = isl_ast_expr_from_id(isl_id_copy(id));
2193 list = isl_ast_expr_list_alloc(ctx, 0);
2194 expr = isl_ast_expr_call(expr, list);
2195 node = isl_ast_node_alloc_user(expr);
2196 node = isl_ast_node_set_annotation(node, id);
2198 return node;
2201 static int update_depth(__isl_keep isl_schedule_node *node, void *user)
2203 int *depth = user;
2204 int node_depth;
2206 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2207 return 1;
2208 node_depth = isl_schedule_node_get_schedule_depth(node);
2209 if (node_depth > *depth)
2210 *depth = node_depth;
2212 return 0;
2215 /* Use isl to generate code for both the host and the device
2216 * from "schedule".
2217 * The device code is marked by "kernel" mark nodes in the schedule tree,
2218 * containing a pointer to a ppcg_kernel object.
2219 * The returned AST only contains the AST for the host code.
2220 * The ASTs for the device code are embedded in ppcg_kernel objects
2221 * attached to the leaf nodes that call "kernel".
2223 static __isl_give isl_ast_node *generate_code(struct gpu_gen *gen,
2224 __isl_take isl_schedule *schedule)
2226 struct ppcg_at_domain_data data;
2227 isl_ast_build *build;
2228 isl_ast_node *tree;
2229 isl_id_list *iterators;
2230 int depth;
2232 data.prog = gen->prog;
2233 data.kernel = NULL;
2235 depth = 0;
2236 if (isl_schedule_foreach_schedule_node(schedule, &update_depth,
2237 &depth) < 0)
2238 return NULL;
2239 build = isl_ast_build_alloc(gen->prog->ctx);
2240 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2241 build = isl_ast_build_set_iterators(build, iterators);
2242 build = isl_ast_build_set_at_each_domain(build, &at_domain, &data);
2243 build = isl_ast_build_set_before_each_mark(build, &before_mark, &data);
2244 build = isl_ast_build_set_after_each_mark(build, &after_mark, &data);
2245 if (gen->prog->scop->options->debug->dump_final_schedule)
2246 isl_schedule_dump(schedule);
2247 tree = isl_ast_build_node_from_schedule(build, schedule);
2248 isl_ast_build_free(build);
2250 return tree;
2253 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2255 if (!str)
2256 return NULL;
2257 return isl_union_map_read_from_str(ctx, str);
2260 /* Can "node" be tiled and then mapped to block and thread identifiers?
2261 * That is, is it permutable with at least one coincident dimension?
2263 static int is_permutable(__isl_keep isl_schedule_node *node)
2265 if (!node)
2266 return -1;
2268 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
2269 return 0;
2270 if (!isl_schedule_node_band_get_permutable(node))
2271 return 0;
2272 if (isl_schedule_node_band_n_member(node) < 1)
2273 return 0;
2274 if (!isl_schedule_node_band_member_get_coincident(node, 0))
2275 return 0;
2277 return 1;
2280 /* A isl_schedule_foreach_schedule_node callback
2281 * for setting *any_permutable and aborting the search
2282 * if "node" is a permutable band with coincident dimensions.
2283 * Otherwise, continue searching.
2285 static int set_permutable(__isl_keep isl_schedule_node *node, void *user)
2287 int *any_permutable = user;
2288 int permutable;
2290 permutable = is_permutable(node);
2291 if (permutable < 0)
2292 return -1;
2293 if (!permutable)
2294 return 1;
2296 *any_permutable = 1;
2298 return -1;
2301 /* Does "schedule" contain any permutable band with at least one coincident
2302 * member?
2304 static int has_any_permutable_node(__isl_keep isl_schedule *schedule)
2306 int any_permutable = 0;
2308 if (isl_schedule_foreach_schedule_node(schedule, &set_permutable,
2309 &any_permutable) < 0 &&
2310 !any_permutable)
2311 return -1;
2313 return any_permutable;
2316 /* Is "node" a leaf or can it be tiled and then mapped to
2317 * block and thread identifiers?
2319 static int is_leaf_or_tilable(__isl_keep isl_schedule_node *node)
2321 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
2322 return 1;
2323 return is_permutable(node);
2326 /* Is "node" the outermost node in its branch that can be tiled
2327 * and then mapped to block and thread identifiers?
2328 * If there are no such nodes in the branch and if "node" is a leaf,
2329 * then it is accepted too.
2331 static int is_outer_tilable(__isl_keep isl_schedule_node *node)
2333 int tilable;
2334 isl_schedule_node *ancestor;
2336 tilable = is_leaf_or_tilable(node);
2337 if (tilable < 0)
2338 return -1;
2339 if (!tilable)
2340 return 0;
2342 tilable = 0;
2343 ancestor = isl_schedule_node_copy(node);
2344 while (isl_schedule_node_has_parent(ancestor)) {
2345 ancestor = isl_schedule_node_parent(ancestor);
2347 tilable = is_permutable(ancestor);
2348 if (tilable < 0 || tilable)
2349 break;
2352 isl_schedule_node_free(ancestor);
2353 return tilable < 0 ? -1 : !tilable;
2356 /* Collect the references to all writes in "group".
2357 * Each reference is represented by a universe set in a space
2359 * [S[i,j] -> R[]]
2361 * with S[i,j] the statement instance space and R[] the array reference.
2363 static __isl_give isl_union_set *group_tagged_writes(
2364 struct gpu_array_ref_group *group)
2366 int i;
2367 isl_space *space;
2368 isl_union_set *writes;
2370 space = isl_map_get_space(group->access);
2371 writes = isl_union_set_empty(space);
2372 for (i = 0; i < group->n_ref; ++i) {
2373 isl_space *space;
2374 isl_set *writes_i;
2376 if (!group->refs[i]->write)
2377 continue;
2379 space = isl_map_get_space(group->refs[i]->tagged_access);
2380 space = isl_space_domain(space);
2381 writes_i = isl_set_universe(space);
2382 writes = isl_union_set_add_set(writes, writes_i);
2385 return writes;
2388 /* Is there any write access in "group" that requires synchronization
2389 * on a write to global memory?
2390 * We currently take into account all writes that would require
2391 * synchronization at the thread level depth, but if the copying
2392 * for this group is performed at an outer level, then we do not
2393 * actually need to take into account dependences at intermediate levels.
2395 static int any_sync_writes_in_group(struct ppcg_kernel *kernel,
2396 struct gpu_array_ref_group *group)
2398 isl_union_set *writes;
2399 int empty, disjoint;
2401 empty = isl_union_set_is_empty(kernel->sync_writes);
2402 if (empty < 0)
2403 return -1;
2404 if (empty)
2405 return 0;
2407 writes = group_tagged_writes(group);
2408 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2409 isl_union_set_free(writes);
2411 return disjoint < 0 ? -1 : !disjoint;
2414 /* Collect the references to all writes in "kernel" that write directly
2415 * to global or shared memory, i.e., that are not mapped to private memory.
2416 * Each reference is represented by a universe set in a space
2418 * [S[i,j] -> R[]]
2420 * with S[i,j] the statement instance space and R[] the array reference.
2422 static __isl_give isl_union_set *collect_non_private_tagged_writes(
2423 struct ppcg_kernel *kernel)
2425 isl_union_set *writes;
2426 int i, j;
2428 writes = isl_union_set_empty(isl_union_set_get_space(kernel->arrays));
2430 for (i = 0; i < kernel->n_array; ++i) {
2431 struct gpu_local_array_info *array = &kernel->array[i];
2433 for (j = 0; j < array->n_group; ++j) {
2434 struct gpu_array_ref_group *group = array->groups[j];
2435 isl_union_set *writes_ij;
2437 if (!group->write)
2438 continue;
2439 if (group->private_tile)
2440 continue;
2441 writes_ij = group_tagged_writes(group);
2442 writes = isl_union_set_union(writes, writes_ij);
2446 return writes;
2449 /* Are there any direct writes to global memory that require
2450 * synchronization?
2452 static int any_global_or_shared_sync_writes(struct ppcg_kernel *kernel)
2454 isl_union_set *writes;
2455 int empty, disjoint;
2457 empty = isl_union_set_is_empty(kernel->sync_writes);
2458 if (empty < 0)
2459 return -1;
2460 if (empty)
2461 return 0;
2463 writes = collect_non_private_tagged_writes(kernel);
2464 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2465 isl_union_set_free(writes);
2467 return disjoint < 0 ? -1 : !disjoint;
2470 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
2471 * from the elements in "tile_size".
2473 static __isl_give isl_multi_val *construct_band_tiles_sizes(
2474 __isl_keep isl_schedule_node *node, int *tile_size)
2476 int i, n;
2477 isl_ctx *ctx;
2478 isl_space *space;
2479 isl_multi_val *mv;
2481 if (!node)
2482 return NULL;
2484 ctx = isl_schedule_node_get_ctx(node);
2485 space = isl_schedule_node_band_get_space(node);
2486 n = isl_schedule_node_band_n_member(node);
2487 mv = isl_multi_val_zero(space);
2488 for (i = 0; i < n; ++i) {
2489 isl_val *v;
2491 v = isl_val_int_from_si(ctx, tile_size[i]);
2492 mv = isl_multi_val_set_val(mv, i, v);
2495 return mv;
2498 /* Replace the partial schedule S of the band node "node" by
2500 * floor(S/f)
2502 * or
2504 * f * floor(S/f)
2506 * if scale_tile_loops is set, with f the integers in "factor".
2507 * The list that "factor" points to is assumed to contain at least
2508 * as many elements as the number of members in the band.
2510 static __isl_give isl_schedule_node *snap_band_to_sizes(
2511 __isl_take isl_schedule_node *node, int *factor,
2512 struct ppcg_options *options)
2514 isl_multi_val *mv;
2516 mv = construct_band_tiles_sizes(node, factor);
2517 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2518 if (options->scale_tile_loops)
2519 node = isl_schedule_node_band_scale(node,
2520 isl_multi_val_copy(mv));
2521 isl_multi_val_free(mv);
2523 return node;
2526 /* Tile "band" with tile size specified by "sizes".
2528 * Since the tile loops will be mapped to block ids, we forcibly
2529 * turn off tile loop scaling. We may want to enable tile loop scaling
2530 * at some later point, but then we would have to support the detection
2531 * of strides during the mapping to block ids.
2532 * Similarly, since the point loops will be mapped to thread ids,
2533 * we forcibly shift the point loops so that they start at zero.
2535 static __isl_give isl_schedule_node *tile_band(
2536 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2538 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2539 int scale_tile;
2540 int shift_point;
2542 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2543 isl_options_set_tile_scale_tile_loops(ctx, 0);
2544 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2545 isl_options_set_tile_shift_point_loops(ctx, 1);
2547 node = isl_schedule_node_band_tile(node, sizes);
2549 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2550 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2552 return node;
2555 /* Extract the set of parameter values and outer schedule dimensions
2556 * for which any statement instance
2557 * in the kernel inserted at "node" needs to be executed.
2558 * Intersect the set of parameter values derived from the host schedule
2559 * relation with the context of "prog".
2561 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2562 struct gpu_prog *prog)
2564 isl_union_map *schedule;
2565 isl_union_set *schedule_domain;
2566 isl_set *context;
2567 int empty;
2569 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2570 schedule_domain = isl_union_map_range(schedule);
2571 empty = isl_union_set_is_empty(schedule_domain);
2572 if (empty < 0) {
2573 isl_union_set_free(schedule_domain);
2574 return NULL;
2576 if (empty) {
2577 int depth;
2578 isl_space *space;
2580 space = isl_union_set_get_space(schedule_domain);
2581 isl_union_set_free(schedule_domain);
2582 space = isl_space_set_from_params(space);
2583 depth = isl_schedule_node_get_schedule_depth(node);
2584 space = isl_space_add_dims(space, isl_dim_set, depth);
2585 context = isl_set_empty(space);
2586 } else {
2587 context = isl_set_from_union_set(schedule_domain);
2589 context = isl_set_intersect_params(context,
2590 isl_set_copy(prog->context));
2592 return context;
2595 /* Return the set of outer array elements accessed by
2596 * by the statement instance in "domain" in "prog".
2598 static __isl_give isl_union_set *accessed_by_domain(
2599 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2601 isl_union_map *access;
2602 isl_union_set *arrays;
2604 access = isl_union_map_union(isl_union_map_copy(prog->read),
2605 isl_union_map_copy(prog->may_write));
2606 access = isl_union_map_intersect_domain(access, domain);
2607 arrays = isl_union_map_range(access);
2608 arrays = isl_union_set_apply(arrays,
2609 isl_union_map_copy(prog->to_outer));
2611 return arrays;
2614 /* Return the number of outer band members of the band node "node"
2615 * that are marked coincident.
2617 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2619 int i, n;
2621 n = isl_schedule_node_band_n_member(node);
2623 for (i = 0; i < n; ++i)
2624 if (!isl_schedule_node_band_member_get_coincident(node, i))
2625 break;
2627 return i;
2630 /* If the band node "node" has more than "n" members, then split off
2631 * the first "n" of them.
2633 static __isl_give isl_schedule_node *split_band(
2634 __isl_take isl_schedule_node *node, int n)
2636 int dim;
2638 dim = isl_schedule_node_band_n_member(node);
2639 if (n < dim)
2640 node = isl_schedule_node_band_split(node, n);
2642 return node;
2645 /* Scale a band node that may have been split by split_band.
2646 * "sizes" are the scaling factors for the original node.
2647 * "node" either points to the original band node, or the outer
2648 * of the two pieces after splitting.
2650 * If the number of elements in "node" is smaller than the number of
2651 * elements in "sizes", then some splitting has occurred and we split
2652 * "sizes" in the same way.
2654 static __isl_give isl_schedule_node *scale_band(
2655 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2657 int n, dim;
2659 n = isl_multi_val_dim(sizes, isl_dim_set);
2660 dim = isl_schedule_node_band_n_member(node);
2661 if (n > dim) {
2662 isl_multi_val *sizes2;
2664 sizes2 = isl_multi_val_copy(sizes);
2665 sizes = isl_multi_val_drop_dims(sizes,
2666 isl_dim_set, dim, n - dim);
2667 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2668 node = isl_schedule_node_child(node, 0);
2669 node = isl_schedule_node_band_scale(node, sizes2);
2670 node = isl_schedule_node_parent(node);
2673 return isl_schedule_node_band_scale(node, sizes);
2676 /* Return an isl_multi_aff, with as elements the parameters in "space"
2677 * that have the names specified by the elements in "names".
2678 * If (some of) these parameters do not already appear in "space",
2679 * then they are added first.
2681 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2682 __isl_keep isl_id_list *names)
2684 int i, n;
2685 isl_local_space *ls;
2686 isl_multi_aff *ma;
2688 if (!names)
2689 space = isl_space_free(space);
2691 n = isl_id_list_n_id(names);
2692 for (i = 0; i < n; ++i) {
2693 int pos;
2694 isl_id *id;
2696 id = isl_id_list_get_id(names, i);
2697 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2698 if (pos >= 0) {
2699 isl_id_free(id);
2700 continue;
2702 pos = isl_space_dim(space, isl_dim_param);
2703 space = isl_space_add_dims(space, isl_dim_param, 1);
2704 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2706 ma = isl_multi_aff_zero(isl_space_copy(space));
2707 ls = isl_local_space_from_space(isl_space_domain(space));
2708 for (i = 0; i < n; ++i) {
2709 int pos;
2710 isl_id *id;
2711 isl_aff *aff;
2713 id = isl_id_list_get_id(names, i);
2714 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2715 isl_id_free(id);
2716 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2717 isl_dim_param, pos);
2718 ma = isl_multi_aff_set_aff(ma, i, aff);
2720 isl_local_space_free(ls);
2722 return ma;
2725 /* Return constraints on the domain elements that equate a sequence of
2726 * parameters called "names", to the partial schedule
2727 * of "node" modulo the integers in "size".
2728 * The number of elements in the array "size" should be equal
2729 * to the number of elements in "names".
2730 * The number of members of the band node "node" should be smaller
2731 * than or equal to this number. If it is smaller, then the first
2732 * elements of "names" are equated to zero.
2734 static __isl_give isl_union_set *set_schedule_modulo(
2735 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
2736 int *size)
2738 int n, n_zero;
2739 isl_space *space;
2740 isl_multi_aff *ma;
2741 isl_multi_union_pw_aff *mupa, *mupa2;
2742 isl_multi_val *mv;
2743 isl_union_set *domain;
2745 if (!node)
2746 return NULL;
2747 n = isl_id_list_n_id(names);
2748 if (n == 0)
2749 return isl_schedule_node_get_universe_domain(node);
2750 n_zero = n - isl_schedule_node_band_n_member(node);
2752 mupa = isl_schedule_node_band_get_partial_schedule(node);
2753 mv = construct_band_tiles_sizes(node, size + n_zero);
2754 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
2756 space = isl_multi_union_pw_aff_get_space(mupa);
2757 space = isl_space_params(space);
2758 space = isl_space_set_from_params(space);
2759 space = isl_space_add_dims(space, isl_dim_set, n_zero);
2760 ma = isl_multi_aff_zero(space);
2762 domain = isl_schedule_node_get_universe_domain(node);
2763 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
2764 isl_union_set_copy(domain), ma);
2765 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
2767 space = isl_multi_union_pw_aff_get_space(mupa);
2768 ma = parameter_vector(space, names);
2770 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
2771 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
2773 return isl_multi_union_pw_aff_zero_union_set(mupa);
2776 /* Insert a context node at "node" introducing the block and thread
2777 * identifiers along with their bounds, which are stored in kernel->grid_size
2778 * and kernel->block_dim.
2779 * Note that the bounds on the block identifiers may implicitly impose
2780 * constraints on the parameters. A guard needs to be inserted
2781 * in the schedule tree to ensure that those bounds hold at "node".
2782 * This guard is inserted in insert_guard.
2784 static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
2785 __isl_take isl_schedule_node *node)
2787 isl_set *context;
2789 context = isl_set_universe(isl_set_get_space(kernel->context));
2791 context = add_bounded_parameters_dynamic(context,
2792 kernel->grid_size, kernel->block_ids);
2793 context = add_bounded_parameters(context,
2794 kernel->block_dim, kernel->thread_ids);
2796 node = isl_schedule_node_insert_context(node, context);
2798 return node;
2801 /* Insert a guard that eliminates kernel launches where the kernel
2802 * obviously does not have any work to do.
2804 * In particular, eliminate kernel launches where there are obviously
2805 * zero blocks.
2806 * Use the same block size constraints that are used to create the context
2807 * to ensure that all constraints implicit in the constructed context
2808 * are imposed by the guard.
2810 * Additionally, add other constraints that are valid
2811 * for each executed instance ("context"), as long as this does not result
2812 * in a disjunction.
2814 static __isl_give isl_schedule_node *insert_guard(
2815 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
2816 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
2818 unsigned nparam, n;
2819 isl_set *guard;
2820 isl_id_list *ids;
2822 guard = isl_set_copy(context);
2823 guard = isl_set_compute_divs(guard);
2824 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
2826 nparam = isl_set_dim(guard, isl_dim_param);
2827 n = isl_multi_pw_aff_dim(size, isl_dim_out);
2828 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
2829 guard = add_bounded_parameters_dynamic(guard, size, ids);
2830 isl_id_list_free(ids);
2831 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
2833 node = isl_schedule_node_insert_guard(node, guard);
2835 return node;
2838 /* Does any array reference group mapping require the band that is mapped
2839 * to threads to be unrolled?
2841 static int kernel_requires_unroll(struct ppcg_kernel *kernel)
2843 int i, j;
2845 for (i = 0; i < kernel->n_array; ++i) {
2846 struct gpu_local_array_info *array = &kernel->array[i];
2848 for (j = 0; j < array->n_group; ++j) {
2849 struct gpu_array_ref_group *group = array->groups[j];
2850 if (gpu_array_ref_group_requires_unroll(group))
2851 return 1;
2855 return 0;
2858 /* Mark the given band node "node" for unrolling by the AST generator and
2859 * then sink it to the leaves of the schedule tree.
2860 * All dimensions of "node" are assumed to be coincident, such that this
2861 * sinking is a valid operation.
2863 static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
2865 int i, n;
2867 n = isl_schedule_node_band_n_member(node);
2868 for (i = 0; i < n; ++i)
2869 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
2870 isl_ast_loop_unroll);
2872 node = isl_schedule_node_band_sink(node);
2874 return node;
2877 /* Insert a synchronization node in the schedule tree of "node"
2878 * after the core computation of "kernel" at the level of the band
2879 * that is mapped to threads, except if that level is equal to
2880 * that of the band that is mapped to blocks or if there are no writes
2881 * to global or shared memory in the core computation that require
2882 * synchronization.
2883 * If there are any writes to shared memory and the shared memory
2884 * copying is performed at the same level, then synchronization
2885 * is needed between the core and the copying anyway, so we might
2886 * as well add it here. If the copying is performed at a higher
2887 * level, then different iterations of intermediate schedule dimensions
2888 * may have a different mapping from between shared memory elements and
2889 * threads, such that synchronization is required after the core.
2890 * "node" is assumed to point to the kernel node.
2892 static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
2893 __isl_take isl_schedule_node *node)
2895 int kernel_depth;
2896 int need_sync;
2898 need_sync = any_global_or_shared_sync_writes(kernel);
2899 if (need_sync < 0)
2900 return isl_schedule_node_free(node);
2901 if (!need_sync)
2902 return node;
2904 kernel_depth = isl_schedule_node_get_schedule_depth(node);
2906 node = gpu_tree_move_down_to_thread(node, kernel->core);
2907 if (kernel_depth == isl_schedule_node_get_schedule_depth(node))
2908 return gpu_tree_move_up_to_kernel(node);
2910 node = gpu_tree_ensure_following_sync(node, kernel);
2912 node = gpu_tree_move_up_to_kernel(node);
2914 return node;
2917 /* Return a read ("read" is 1) or write access relation for "group"
2918 * with those accesses removed that are only needed to communicate data
2919 * within the subtree of the schedule rooted at "node".
2920 * Furthermore, include the prefix schedule at "node".
2921 * That is, return a relation of the form
2923 * S -> [D -> A]
2925 * with D the outer schedule dimensions at "node".
2927 static __isl_give isl_union_map *anchored_non_local_accesses(
2928 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2929 __isl_take isl_schedule_node *node, int read)
2931 isl_union_map *access;
2932 isl_union_map *prefix;
2934 access = gpu_array_ref_group_access_relation(group, read, !read);
2935 access = remove_local_accesses_group(kernel, group, access, node, read);
2936 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
2937 access = isl_union_map_range_product(prefix, access);
2939 return access;
2942 /* Given an array reference group "group", create a mapping
2944 * read[D -> A] -> [D -> A]
2946 * if "read" is set or
2948 * write[D -> A] -> [D -> A]
2950 * if "read" is not set.
2951 * D corresponds to the outer group->depth dimensions of
2952 * the kernel schedule.
2954 static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
2955 struct gpu_array_ref_group *group, int read)
2957 isl_space *space;
2958 isl_id *id;
2960 space = isl_space_copy(group->array->space);
2961 space = isl_space_from_range(space);
2962 space = isl_space_add_dims(space, isl_dim_in, group->depth);
2963 space = isl_space_wrap(space);
2964 space = isl_space_map_from_set(space);
2966 id = isl_id_alloc(ctx, read ? "read" : "write", group);
2967 space = isl_space_set_tuple_id(space, isl_dim_in, id);
2969 return isl_multi_aff_identity(space);
2972 /* If any writes in "group" require synchronization, then make sure
2973 * that there is a synchronization node for "kernel" after the node
2974 * following "node" in a sequence.
2976 * If "shared" is set and no synchronization is needed for
2977 * the writes to global memory, then add synchronization before
2978 * the kernel to protect shared memory from being overwritten
2979 * by the next iteration of the core computation.
2980 * No additional synchronization is needed to protect against
2981 * the next copy into shared memory because each element of
2982 * the shared memory tile is always copied by the same thread.
2984 static __isl_give isl_schedule_node *add_group_write_sync(
2985 __isl_take isl_schedule_node *node, struct ppcg_kernel *kernel,
2986 struct gpu_array_ref_group *group, int shared)
2988 int need_sync;
2990 need_sync = any_sync_writes_in_group(kernel, group);
2991 if (need_sync < 0)
2992 return isl_schedule_node_free(node);
2993 if (need_sync) {
2994 node = isl_schedule_node_parent(node);
2995 node = isl_schedule_node_next_sibling(node);
2996 node = isl_schedule_node_child(node, 0);
2997 node = gpu_tree_ensure_following_sync(node, kernel);
2998 } else if (shared) {
2999 node = isl_schedule_node_parent(node);
3000 node = isl_schedule_node_parent(node);
3001 node = gpu_tree_move_down_to_depth(node, group->depth,
3002 kernel->core);
3003 node = gpu_tree_move_left_to_sync(node, kernel);
3006 return node;
3009 /* Add copy statements to the schedule tree of "node"
3010 * for reading from global memory to private memory (if "read" is set) or
3011 * for writing back from private memory to global memory
3012 * (if "read" is not set) for the array reference group "group" that
3013 * is mapped to private memory.
3014 * On input, "node" points to the kernel node, and it is moved
3015 * back there on output.
3017 * The copies are performed in the order of the array elements.
3018 * The copy statement instances include a reference to the outer
3019 * group->depth dimensions of the kernel schedule for ease of
3020 * combining them with the group tiling.
3022 * That is, the extra schedule is of the form
3024 * type[D -> A] -> A
3026 * where D corresponds to the outer group->depth dimensions of
3027 * the kernel schedule and A to the global array.
3028 * This schedule is unrolled because registers are not addressable.
3030 * The copying is inserted in the schedule tree through an extension
3031 * of the form
3033 * D -> type[D -> A]
3035 * where the extra domain elements type[D -> A] are those accessed
3036 * by the group.
3037 * A filter is inserted on type[D -> A] to ensure that the element
3038 * is read/written by the same thread that needs the element.
3039 * This filter is obtained by applying
3041 * S -> type[D -> A]
3043 * to the thread filter for the core statements.
3045 * The extension is inserted before the core computation in case of a read
3046 * and after the core computation in case of a write.
3047 * In the latter case, we also make sure that there is a synchronization
3048 * node after the write to global memory, unless this write is performed
3049 * at the outer level of the kernel.
3050 * In principle, this synchronization could be inserted higher
3051 * in the schedule tree depending on where the corresponding reads
3052 * from global memory are performed.
3054 static __isl_give isl_schedule_node *add_copies_group_private(
3055 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3056 __isl_take isl_schedule_node *node, int read)
3058 isl_union_map *access;
3059 isl_union_map *prefix;
3060 isl_union_set *domain;
3061 isl_space *space;
3062 isl_multi_aff *from_access;
3063 isl_multi_pw_aff *mpa;
3064 isl_multi_union_pw_aff *mupa;
3065 isl_schedule_node *graft;
3066 isl_union_set *filter;
3067 int kernel_depth;
3068 int empty;
3070 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3071 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3073 access = anchored_non_local_accesses(kernel, group, node, read);
3074 empty = isl_union_map_is_empty(access);
3075 if (empty < 0 || empty) {
3076 isl_union_map_free(access);
3077 if (empty < 0)
3078 return isl_schedule_node_free(node);
3079 return gpu_tree_move_up_to_kernel(node);
3082 from_access = create_from_access(kernel->ctx, group, read);
3083 space = isl_space_domain(isl_multi_aff_get_space(from_access));
3084 access = isl_union_map_preimage_range_multi_aff(access, from_access);
3086 filter = isl_union_set_copy(kernel->thread_filter);
3087 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
3088 filter = isl_union_set_detect_equalities(filter);
3089 filter = isl_union_set_coalesce(filter);
3091 domain = isl_union_map_range(access);
3092 access = isl_union_set_wrapped_domain_map(domain);
3093 access = isl_union_map_reverse(access);
3094 access = isl_union_map_coalesce(access);
3095 graft = isl_schedule_node_from_extension(access);
3097 space = isl_space_map_from_set(space);
3098 mpa = isl_multi_pw_aff_identity(space);
3099 mpa = isl_multi_pw_aff_range_factor_range(mpa);
3100 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3102 graft = isl_schedule_node_child(graft, 0);
3103 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3104 graft = unroll(graft);
3106 graft = isl_schedule_node_insert_filter(graft, filter);
3108 graft = isl_schedule_node_parent(graft);
3110 if (read)
3111 node = isl_schedule_node_graft_before(node, graft);
3112 else {
3113 node = isl_schedule_node_graft_after(node, graft);
3114 if (kernel_depth < group->depth)
3115 node = add_group_write_sync(node, kernel, group, 0);
3118 node = gpu_tree_move_up_to_kernel(node);
3120 return node;
3123 /* Add copy statements to the schedule tree of "node"
3124 * for reading from global memory to shared memory (if "read" is set) or
3125 * for writing back from shared memory to global memory
3126 * (if "read" is not set) for the array reference group "group" that
3127 * is mapped to shared memory.
3128 * On input, "node" points to the kernel node, and it is moved
3129 * back there on output.
3131 * The copies are performed in the order of the corresponding shared
3132 * memory tile.
3133 * The copy statement instances include a reference to the outer
3134 * group->depth dimensions of the kernel schedule for ease of
3135 * combining them with the group tiling.
3137 * If we are performing a read from global memory to shared memory and
3138 * if the array involved is not a scalar, then we copy
3139 * the entire tile to shared memory. This may result in some extra
3140 * elements getting copied, but it should lead to simpler code
3141 * (which means that fewer registers may be needed) and less divergence.
3143 * Otherwise, we only copy the elements that will be read or have been written
3144 * in the kernel.
3146 * That is, the extra schedule is of the form
3148 * type[D -> A] -> T
3150 * where D corresponds to the outer group->depth dimensions of
3151 * the kernel schedule, A to the global array and T is the corresponding
3152 * shared memory tile.
3154 * The copying is inserted in the schedule tree through an extension
3155 * of the form
3157 * D -> type[D -> A]
3159 * where the extra domain elements type[D -> A] are those accessed
3160 * by the group. In the case of read from a non-scalar, this set
3161 * is replaced by the entire shared memory tile.
3163 * A filter is inserted on type[D -> A] to map the copy instances
3164 * to the threads. In particular, the thread identifiers are
3165 * equated to the position inside the shared memory tile (T)
3166 * modulo the block size.
3167 * We try to align the innermost tile dimension with the innermost
3168 * thread identifier (x) as a heuristic to improve coalescing.
3169 * In particular, if the dimension of the tile is greater than
3170 * the dimension of the block, then the schedule mapping to the tile
3171 * is broken up into two pieces and the filter is applied to the inner part.
3172 * If, on the other hand, the dimension of the tile is smaller than
3173 * the dimension of the block, then the initial thread identifiers
3174 * are equated to zero and the remaining thread identifiers are
3175 * matched to the memory tile.
3177 * The extension is inserted before the core computation in case of a read
3178 * and after the core computation in case of a write.
3179 * In the case of a read, we first need to make sure there is some
3180 * synchronization before the core computation such that we can put the read
3181 * from global memory to shared memory before that synchronization.
3182 * This ensures that all threads have finished copying into shared memory
3183 * before the shared memory is used.
3184 * We also need to make sure that there is a synchronization node after
3185 * the core computation to ensure that the next load into shared memory
3186 * only happens after all data has been used. There is no need for
3187 * this synchronization if we are at the outer level since then there
3188 * won't be a next load.
3189 * In the case of a write, we need to make sure there is some synchronization
3190 * after the core computation such taht we can put the write from shared
3191 * memory to global memory after that synchronization.
3192 * Unless we are at the outer level, we also need a synchronization node
3193 * after the write to ensure the data is saved to global memory
3194 * before the next iteration write to the same shared memory.
3195 * It also makes sure the data has arrived in global memory before
3196 * it is read in a subsequent iteration.
3198 static __isl_give isl_schedule_node *add_copies_group_shared(
3199 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3200 __isl_take isl_schedule_node *node, int read)
3202 struct gpu_array_tile *tile;
3203 isl_union_map *access;
3204 isl_union_set *domain;
3205 isl_union_set *sync;
3206 isl_multi_aff *ma;
3207 isl_multi_aff *from_access;
3208 isl_multi_pw_aff *mpa;
3209 isl_multi_union_pw_aff *mupa;
3210 isl_schedule_node *graft;
3211 isl_union_set *filter;
3212 int skip;
3213 int kernel_depth;
3214 int empty;
3216 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3217 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3219 access = anchored_non_local_accesses(kernel, group, node, read);
3220 empty = isl_union_map_is_empty(access);
3221 if (empty < 0 || empty) {
3222 isl_union_map_free(access);
3223 if (empty < 0)
3224 return isl_schedule_node_free(node);
3225 return gpu_tree_move_up_to_kernel(node);
3228 from_access = create_from_access(kernel->ctx, group, read);
3230 tile = gpu_array_ref_group_tile(group);
3231 ma = isl_multi_aff_copy(tile->tiling);
3232 ma = isl_multi_aff_pullback_multi_aff(ma,
3233 isl_multi_aff_copy(from_access));
3234 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3235 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3237 domain = isl_union_map_range(access);
3239 if (read && !gpu_array_is_scalar(group->array)) {
3240 isl_map *map;
3241 isl_union_set_free(domain);
3242 map = group_tile(group);
3243 domain = isl_union_set_from_set(isl_map_wrap(map));
3246 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3247 access = isl_union_set_wrapped_domain_map(domain);
3248 access = isl_union_map_reverse(access);
3249 access = isl_union_map_coalesce(access);
3250 graft = isl_schedule_node_from_extension(access);
3252 graft = isl_schedule_node_child(graft, 0);
3254 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3256 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3257 graft = isl_schedule_node_band_split(graft,
3258 tile->n - kernel->n_block);
3259 graft = isl_schedule_node_child(graft, 0);
3261 if (tile->n < kernel->n_block)
3262 skip = kernel->n_block - tile->n;
3263 else
3264 skip = 0;
3265 filter = set_schedule_modulo(graft, kernel->thread_ids,
3266 kernel->block_dim);
3267 if (!kernel->options->wrap)
3268 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3269 kernel->options);
3270 if (tile->n > kernel->n_block && kernel->n_block > 0)
3271 graft = isl_schedule_node_parent(graft);
3272 graft = isl_schedule_node_insert_filter(graft, filter);
3274 while (graft && isl_schedule_node_has_parent(graft))
3275 graft = isl_schedule_node_parent(graft);
3277 if (read) {
3278 if (kernel_depth < group->depth)
3279 node = gpu_tree_ensure_sync_after_core(node, kernel);
3280 node = gpu_tree_move_left_to_sync(node, kernel);
3281 node = isl_schedule_node_graft_before(node, graft);
3282 } else {
3283 node = gpu_tree_move_right_to_sync(node, kernel);
3284 node = isl_schedule_node_graft_after(node, graft);
3285 if (kernel_depth < group->depth)
3286 node = add_group_write_sync(node, kernel, group, 1);
3289 node = gpu_tree_move_up_to_kernel(node);
3291 return node;
3294 /* Check whether the array reference group "group" is mapped to
3295 * private or shared memory and, if so,
3296 * add copy statements to the schedule tree of "node"
3297 * for reading from global memory to private or shared memory
3298 * (if "read" is set) or for writing back from private or shared memory
3299 * to global memory (if "read" is not set) for this group.
3300 * On input, "node" points to the kernel node, and it is moved
3301 * back there on output.
3303 static __isl_give isl_schedule_node *add_copies_group(
3304 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3305 __isl_take isl_schedule_node *node, int read)
3307 if (group->private_tile)
3308 return add_copies_group_private(kernel, group, node, read);
3309 if (group->shared_tile)
3310 return add_copies_group_shared(kernel, group, node, read);
3311 return node;
3314 /* For each array reference group that is mapped to private or shared memory,
3315 * add copy statements to the schedule tree of "node"
3316 * for reading from global memory to private or shared memory
3317 * and for writing back.
3318 * On input, "node" points to the kernel node, and it is moved
3319 * back there on output.
3321 static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3322 __isl_take isl_schedule_node *node)
3324 int i, j;
3326 for (i = 0; i < kernel->n_array; ++i) {
3327 struct gpu_local_array_info *array = &kernel->array[i];
3329 for (j = 0; j < array->n_group; ++j) {
3330 struct gpu_array_ref_group *group = array->groups[j];
3332 node = add_copies_group(kernel, group, node, 1);
3333 if (!node)
3334 return NULL;
3335 node = add_copies_group(kernel, group, node, 0);
3336 if (!node)
3337 return NULL;
3341 return node;
3344 /* Mark all dimensions in the current band node atomic.
3346 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3348 int i, n;
3350 n = isl_schedule_node_band_n_member(node);
3351 for (i = 0; i < n; ++i)
3352 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
3353 isl_ast_loop_atomic);
3355 return node;
3358 /* Mark "node" atomic, if it is a band node.
3359 * Do the same for all ancestors.
3360 * Return a pointer to "node" (in the updated schedule tree).
3362 static __isl_give isl_schedule_node *atomic_ancestors(
3363 __isl_take isl_schedule_node *node)
3365 int pos;
3367 if (!node)
3368 return NULL;
3369 if (!isl_schedule_node_has_parent(node))
3370 return node;
3372 pos = isl_schedule_node_get_child_position(node);
3373 node = isl_schedule_node_parent(node);
3374 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3375 node = atomic(node);
3376 node = atomic_ancestors(node);
3377 node = isl_schedule_node_child(node, pos);
3379 return node;
3382 /* Collect all write references that require synchronization.
3383 * "node" is assumed to point to the kernel node.
3384 * Each reference is represented by a universe set in a space
3386 * [S[i,j] -> R[]]
3388 * with S[i,j] the statement instance space and R[] the array reference.
3390 * This function should be called before block and thread filters are added.
3392 * Synchronization is needed after a write if there is a subsequent read
3393 * within the same block that may not be performed by the same thread.
3394 * There should not be any dependences between different blocks,
3395 * so we start with the flow dependences within the same kernel invocation
3396 * and we subtract from these those dependences that are mapped
3397 * to the same iteration of the bands where synchronization is inserted.
3398 * We do not remove pairs of instances that are known to map to
3399 * the same thread across different iterations of the intermediate
3400 * bands because the read may be performed by a different thread
3401 * than the one that needs the value if shared memory is involved.
3403 * We also consider all pairs of possible writes that access the same
3404 * memory location and that may be mapped to the same block but not
3405 * to the same iteration of the intermediate bands.
3406 * In theory, it would be possible for one thread to still be in
3407 * a previous iteration of a loop in these bands.
3408 * A write to global memory in this delayed thread could then overwrite
3409 * a write from another thread that has already moved on to
3410 * the next iteration.
3412 * After computing the above writes paired off with reads or writes
3413 * that depend on them, we project onto the domain writes.
3414 * Sychronization is needed after writes to global memory
3415 * through these references.
3417 static __isl_give isl_union_set *compute_sync_writes(
3418 struct ppcg_kernel *kernel, __isl_keep isl_schedule_node *node)
3420 isl_union_map *local;
3421 isl_union_map *may_writes, *shared_access;
3422 isl_union_map *kernel_prefix, *thread_prefix;
3423 isl_union_map *equal;
3424 isl_union_set *wrap;
3425 isl_union_set *domain;
3427 domain = isl_schedule_node_get_universe_domain(node);
3428 kernel_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3429 node = isl_schedule_node_copy(node);
3430 node = gpu_tree_move_down_to_thread(node, kernel->core);
3431 thread_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3432 isl_schedule_node_free(node);
3434 may_writes = isl_union_map_copy(kernel->prog->scop->tagged_may_writes);
3435 may_writes = isl_union_map_curry(may_writes);
3436 may_writes = isl_union_map_intersect_domain(may_writes, domain);
3437 may_writes = isl_union_map_uncurry(may_writes);
3438 shared_access = isl_union_map_copy(may_writes);
3439 shared_access = isl_union_map_apply_range(shared_access,
3440 isl_union_map_reverse(may_writes));
3442 local = isl_union_map_copy(kernel->prog->scop->tagged_dep_flow);
3443 local = isl_union_map_union(local, shared_access);
3444 local = isl_union_map_zip(local);
3446 equal = isl_union_map_apply_range(kernel_prefix,
3447 isl_union_map_reverse(isl_union_map_copy(kernel_prefix)));
3448 wrap = isl_union_map_wrap(equal);
3449 local = isl_union_map_intersect_domain(local, wrap);
3450 equal = isl_union_map_apply_range(thread_prefix,
3451 isl_union_map_reverse(isl_union_map_copy(thread_prefix)));
3452 wrap = isl_union_map_wrap(equal);
3453 local = isl_union_map_subtract_domain(local, wrap);
3455 local = isl_union_map_zip(local);
3456 local = isl_union_map_universe(local);
3458 return isl_union_map_domain(local);
3461 /* Group the domain elements into a single space, named kernelX,
3462 * with X the kernel sequence number "kernel_id".
3464 static __isl_give isl_schedule_node *group_statements(
3465 __isl_take isl_schedule_node *node, int kernel_id)
3467 char buffer[20];
3468 isl_id *id;
3470 if (!node)
3471 return NULL;
3473 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3474 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3475 return isl_schedule_node_group(node, id);
3478 /* Create a ppcg_kernel representing the domain instances that reach "node"
3479 * and insert a mark node pointing to the ppcg_kernel before "node".
3480 * The band that "node" points to is the band that needs to be mapped
3481 * to block identifiers. The band that needs to be mapped to thread
3482 * identifiers should be marked by a "thread" mark by the caller.
3483 * This mark is removed by this function.
3484 * If "scale" is set, then the band that "node" points to is scaled
3485 * by "sizes".
3487 * Mark all outer band nodes as atomic to ensure each kernel is only
3488 * scheduled once.
3489 * If the domain elements that reach "node" live in more than one space,
3490 * then group the domain elements into a single space, named kernelX,
3491 * with X the kernel sequence number.
3493 * Insert a guard node governing the kernel node to ensure that
3494 * no kernels with zero blocks are launched.
3496 * Insert a context node describing the block and thread
3497 * identifiers inside the kernel mark.
3498 * The context node needs to be inserted after the effective block size
3499 * has been determined such that the bounds on the thread identifiers
3500 * would reflect the effective block size.
3501 * Insert a filter node inside the context node mapping the statement
3502 * instances to block identifiers. In particular, the block identifiers
3503 * are equated to the partial schedule of band that was marked for mapping
3504 * to blocks modulo the grid size.
3505 * Insert a filter node inside the "thread" mark mapping the statement
3506 * instances to thread identifiers. In particular, the thread identifiers
3507 * are equated to the partial schedule of band that was marked for mapping
3508 * to threads modulo the block size.
3510 * Compute array reference groups for all arrays, set the local
3511 * array bounds based on the set of domain instances that reach
3512 * the kernel node, check the total amount of shared memory used
3513 * and compute all group tilings.
3514 * The array reference groups are computed after the block filter
3515 * has been inserted because it affects the mapping to shared or
3516 * private memory. This computation also requires the thread filter
3517 * (in the ppcg_kernel object), but this thread filter should not
3518 * have been added to the schedule tree yet since the computation
3519 * requires the schedule of the band that needs to be mapped to
3520 * threads before the privatization is applied.
3522 * If any array reference group requires the band mapped to threads
3523 * to be unrolled, then we perform the required unrolling.
3525 * We save a copy of the schedule that may influence the mappings
3526 * to shared or private memory in kernel->shared_schedule.
3528 * Finally, we add synchronization and copy statements to the schedule tree,
3529 * remove the "thread" mark and create representations for the local
3530 * variables in the kernel.
3532 * We keep a copy of the isl_id that points to the kernel to ensure
3533 * that the kernel does not get destroyed if the schedule node
3534 * is freed due to some error condition.
3536 static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
3537 __isl_take isl_schedule_node *node, int scale,
3538 __isl_keep isl_multi_val *sizes)
3540 struct ppcg_kernel *kernel;
3541 isl_id *id;
3542 isl_schedule_node *node_thread;
3543 isl_union_map *host_schedule;
3544 isl_set *host_domain;
3545 isl_union_set *domain;
3546 int single_statement;
3548 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3549 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3550 if (!kernel)
3551 return isl_schedule_node_free(node);
3553 domain = isl_schedule_node_get_domain(node);
3554 single_statement = isl_union_set_n_set(domain) == 1;
3556 kernel->ctx = gen->ctx;
3557 kernel->prog = gen->prog;
3558 kernel->options = gen->options;
3559 kernel->context = extract_context(node, gen->prog);
3560 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3561 kernel->arrays = accessed_by_domain(isl_union_set_copy(domain),
3562 gen->prog);
3563 kernel->n_grid = n_outer_coincidence(node);
3564 node_thread = isl_schedule_node_copy(node);
3565 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3566 node_thread = isl_schedule_node_child(node_thread, 0);
3567 kernel->n_block = n_outer_coincidence(node_thread);
3568 isl_schedule_node_free(node_thread);
3569 kernel->id = gen->kernel_id++;
3570 read_grid_and_block_sizes(kernel, gen);
3572 kernel->sync_writes = compute_sync_writes(kernel, node);
3574 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3575 host_domain = isl_set_from_union_set(isl_union_map_range(
3576 host_schedule));
3578 node = atomic_ancestors(node);
3580 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3581 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3582 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3584 if (!single_statement)
3585 node = group_statements(node, kernel->id);
3587 node = isl_schedule_node_child(node, 0);
3588 node = split_band(node, kernel->n_grid);
3589 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3590 kernel->n_grid, "b");
3591 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3592 kernel->grid_dim);
3593 kernel->grid_size = extract_grid_size(kernel,
3594 isl_union_set_copy(domain));
3595 if (!kernel->options->wrap)
3596 node = snap_band_to_sizes(node, kernel->grid_dim,
3597 kernel->options);
3598 if (scale)
3599 node = scale_band(node, isl_multi_val_copy(sizes));
3600 node = isl_schedule_node_parent(node);
3601 if (!single_statement)
3602 node = isl_schedule_node_parent(node);
3603 node = insert_guard(node, kernel->context, kernel->grid_size,
3604 gen->prog->scop);
3605 node = gpu_tree_move_down_to_thread(node, kernel->core);
3606 node = isl_schedule_node_child(node, 0);
3607 node = split_band(node, kernel->n_block);
3608 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3609 kernel->n_block, "t");
3610 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3611 kernel->block_dim);
3612 extract_block_size(kernel, domain);
3614 node = gpu_tree_move_up_to_kernel(node);
3615 node = isl_schedule_node_child(node, 0);
3616 node = insert_context(kernel, node);
3617 node = isl_schedule_node_child(node, 0);
3618 node = isl_schedule_node_insert_filter(node,
3619 isl_union_set_copy(kernel->block_filter));
3621 node = gpu_tree_move_up_to_kernel(node);
3623 if (gpu_group_references(kernel, node) < 0)
3624 node = isl_schedule_node_free(node);
3625 localize_bounds(kernel, host_domain);
3626 isl_set_free(host_domain);
3628 check_shared_memory_bound(kernel);
3629 compute_group_tilings(kernel);
3631 node = gpu_tree_move_down_to_thread(node, kernel->core);
3632 node = isl_schedule_node_child(node, 0);
3633 if (!kernel->options->wrap)
3634 node = snap_band_to_sizes(node, kernel->block_dim,
3635 kernel->options);
3636 node = isl_schedule_node_insert_filter(node,
3637 isl_union_set_copy(kernel->thread_filter));
3638 if (kernel_requires_unroll(kernel)) {
3639 node = isl_schedule_node_child(node, 0);
3640 node = unroll(node);
3643 node = gpu_tree_move_up_to_thread(node);
3644 kernel->shared_schedule_dim =
3645 isl_schedule_node_get_schedule_depth(node);
3646 kernel->shared_schedule =
3647 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3649 node = gpu_tree_move_up_to_kernel(node);
3651 node = add_sync(kernel, node);
3652 node = add_copies(kernel, node);
3654 node = gpu_tree_move_down_to_thread(node, kernel->core);
3655 node = isl_schedule_node_delete(node);
3657 node = gpu_tree_move_up_to_kernel(node);
3659 if (create_kernel_vars(kernel) < 0)
3660 node = isl_schedule_node_free(node);
3662 if (!single_statement)
3663 node = isl_schedule_node_parent(node);
3664 node = isl_schedule_node_parent(node);
3666 isl_id_free(id);
3667 return node;
3670 /* Insert a zero-dimensional permutable band at "node".
3672 static __isl_give isl_schedule_node *insert_empty_permutable_band(
3673 __isl_take isl_schedule_node *node)
3675 isl_space *space;
3676 isl_schedule *schedule;
3677 isl_union_set *domain;
3678 isl_multi_union_pw_aff *mupa;
3680 schedule = isl_schedule_node_get_schedule(node);
3681 domain = isl_schedule_get_domain(schedule);
3682 space = isl_union_set_get_space(domain);
3683 isl_union_set_free(domain);
3684 isl_schedule_free(schedule);
3686 space = isl_space_set_from_params(space);
3687 mupa = isl_multi_union_pw_aff_zero(space);
3688 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3689 node = isl_schedule_node_band_set_permutable(node, 1);
3691 return node;
3694 /* If "node" is the outermost permutable band that can be mapped to block and
3695 * thread identifiers in its branch (or a leaf with no such outer bands),
3696 * then mark the band as such, attaching a ppcg_kernel to the mark.
3698 * If "node" originally points to a leaf, then insert a zero-dimensional
3699 * permutable band such that we can assume that "node" always
3700 * points to a band node.
3702 * Tile "node" using user specified tile sizes, after splitting the band
3703 * if the number of specified tile sizes is smaller than the dimension
3704 * of the band. Mark the point band of this tiling as the band that
3705 * needs to be mapped to threads.
3706 * Create a kernel representing the domain instances that reach "node" and
3707 * insert a mark node pointing to the ppcg_kernel before the band node.
3709 static __isl_give isl_schedule_node *mark_outer_permutable(
3710 __isl_take isl_schedule_node *node, void *user)
3712 struct gpu_gen *gen = user;
3713 int outer;
3714 int scale;
3715 int tile_len;
3716 int *tile_size;
3717 isl_id *id;
3718 isl_multi_val *sizes;
3720 outer = is_outer_tilable(node);
3721 if (outer < 0)
3722 return isl_schedule_node_free(node);
3723 if (!outer)
3724 return node;
3726 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
3727 node = insert_empty_permutable_band(node);
3729 tile_len = isl_schedule_node_band_n_member(node);
3730 tile_size = read_tile_sizes(gen, &tile_len);
3731 if (!tile_size)
3732 return isl_schedule_node_free(node);
3733 if (tile_len < isl_schedule_node_band_n_member(node))
3734 node = isl_schedule_node_band_split(node, tile_len);
3735 sizes = construct_band_tiles_sizes(node, tile_size);
3736 node = tile_band(node, isl_multi_val_copy(sizes));
3737 node = isl_schedule_node_child(node, 0);
3738 id = isl_id_alloc(gen->ctx, "thread", NULL);
3739 node = isl_schedule_node_insert_mark(node, id);
3740 node = isl_schedule_node_parent(node);
3742 scale = gen->options->scale_tile_loops;
3743 node = create_kernel(gen, node, scale, sizes);
3744 isl_multi_val_free(sizes);
3745 free(tile_size);
3747 return node;
3750 /* Insert "kernel" marks that point to a ppcg_kernel structure
3751 * in front of all outermost tilable band that (by construction)
3752 * have at least one parallel loop.
3754 static __isl_give isl_schedule_node *mark_kernels(struct gpu_gen *gen,
3755 __isl_take isl_schedule_node *node)
3757 return isl_schedule_node_map_descendant(node,
3758 &mark_outer_permutable, gen);
3761 /* Save the schedule "schedule" to a file called "filename".
3762 * The schedule is printed in block style.
3764 static void save_schedule(__isl_keep isl_schedule *schedule,
3765 const char *filename)
3767 FILE *file;
3768 isl_ctx *ctx;
3769 isl_printer *p;
3771 if (!schedule)
3772 return;
3774 file = fopen(filename, "w");
3775 if (!file) {
3776 fprintf(stderr, "Unable to open '%s' for writing\n", filename);
3777 return;
3779 ctx = isl_schedule_get_ctx(schedule);
3780 p = isl_printer_to_file(ctx, file);
3781 p = isl_printer_set_yaml_style(p, ISL_YAML_STYLE_BLOCK);
3782 p = isl_printer_print_schedule(p, schedule);
3783 isl_printer_free(p);
3784 fclose(file);
3787 /* Load and return a schedule from a file called "filename".
3789 static __isl_give isl_schedule *load_schedule(isl_ctx *ctx,
3790 const char *filename)
3792 FILE *file;
3793 isl_schedule *schedule;
3795 file = fopen(filename, "r");
3796 if (!file) {
3797 fprintf(stderr, "Unable to open '%s' for reading\n", filename);
3798 return NULL;
3800 schedule = isl_schedule_read_from_file(ctx, file);
3801 fclose(file);
3803 return schedule;
3806 /* Compute an appropriate schedule based on the accesses in
3807 * gen->read and gen->write.
3809 * We use the dependences in gen->prog->scop to compute
3810 * a schedule that has a parallel loop in each tilable band and
3811 * return this schedule.
3813 * If live range reordering is allowed, then we need to make sure
3814 * that live ranges on arrays are not run in parallel since doing
3815 * so would require array expansion. We therefore add the array
3816 * order dependences to the coincidence dependences. Non-zero array
3817 * order dependences will then prevent a schedule dimension from being
3818 * considered parallel.
3819 * Live ranges derived from scalars are allowed to be run in parallel
3820 * since we force the scalars to be mapped to private memory in
3821 * check_scalar_live_ranges.
3822 * If live range reordering is allowed, then the false dependences
3823 * are not added to the validity constraints as that would prevent
3824 * reordering. Instead, the external false dependences that enforce that reads
3825 * from potentially live-in data precede any later write and
3826 * that writes of potentially live-out data follow any other earlier write
3827 * are added to the validity and the coincidence constraints.
3828 * The false dependences are still added to the proximity constraints
3829 * for consistency with the case where live range reordering is not allowed.
3830 * The coincidence constraints then consist of flow dependences,
3831 * external false dependences and array order dependences.
3832 * The independences can be filtered out from the first two sets.
3833 * They have already been filtered out from the array order dependences
3834 * on a per array basis in collect_order_dependences.
3835 * There is no need for a per array handling of the other two sets
3836 * as there should be no flow or external false dependence on local
3837 * variables that can be filtered out.
3839 static __isl_give isl_schedule *compute_schedule(struct gpu_gen *gen)
3841 isl_union_set *domain;
3842 isl_union_map *dep_raw, *dep;
3843 isl_union_map *validity, *proximity, *coincidence;
3844 isl_schedule_constraints *sc;
3845 isl_schedule *schedule;
3847 domain = isl_union_set_copy(gen->prog->scop->domain);
3848 sc = isl_schedule_constraints_on_domain(domain);
3849 sc = isl_schedule_constraints_set_context(sc,
3850 isl_set_copy(gen->prog->scop->context));
3851 if (gen->options->live_range_reordering) {
3852 sc = isl_schedule_constraints_set_conditional_validity(sc,
3853 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
3854 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
3855 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
3856 validity = isl_union_map_copy(proximity);
3857 validity = isl_union_map_union(validity,
3858 isl_union_map_copy(gen->prog->scop->dep_forced));
3859 proximity = isl_union_map_union(proximity,
3860 isl_union_map_copy(gen->prog->scop->dep_false));
3861 coincidence = isl_union_map_copy(validity);
3862 coincidence = isl_union_map_subtract(coincidence,
3863 isl_union_map_copy(gen->prog->scop->independence));
3864 coincidence = isl_union_map_union(coincidence,
3865 isl_union_map_copy(gen->prog->array_order));
3866 } else {
3867 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
3868 dep = isl_union_map_copy(gen->prog->scop->dep_false);
3869 dep = isl_union_map_union(dep, dep_raw);
3870 dep = isl_union_map_coalesce(dep);
3871 proximity = isl_union_map_copy(dep);
3872 coincidence = isl_union_map_copy(dep);
3873 validity = dep;
3875 sc = isl_schedule_constraints_set_validity(sc, validity);
3876 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
3877 sc = isl_schedule_constraints_set_proximity(sc, proximity);
3879 if (gen->options->debug->dump_schedule_constraints)
3880 isl_schedule_constraints_dump(sc);
3881 schedule = isl_schedule_constraints_compute_schedule(sc);
3883 return schedule;
3886 /* Obtain a schedule for the scop, either by reading it from
3887 * a file or by computing one.
3889 static __isl_give isl_schedule *get_schedule(struct gpu_gen *gen)
3891 isl_schedule *schedule;
3893 if (gen->options->load_schedule_file) {
3894 schedule = load_schedule(gen->ctx,
3895 gen->options->load_schedule_file);
3896 } else {
3897 schedule = compute_schedule(gen);
3898 if (gen->options->save_schedule_file)
3899 save_schedule(schedule,
3900 gen->options->save_schedule_file);
3902 if (gen->options->debug->dump_schedule)
3903 isl_schedule_dump(schedule);
3905 return schedule;
3908 /* Compute the sets of outer array elements that need to be copied in and out.
3910 * In particular, for each array that is possibly written anywhere in
3911 * "prog" and that is visible outside the corresponding scop,
3912 * we copy out its entire extent.
3914 * Any array elements that is read without first being written needs
3915 * to be copied in. Furthermore, if there are any array elements that
3916 * are copied out, but that may not be written inside "prog", then
3917 * they also need to be copied in to ensure that the value after execution
3918 * is the same as the value before execution, at least for those array
3919 * elements that may have their values preserved by the scop.
3920 * In case the array elements are structures, we need to take into
3921 * account that all members of the structures need to be written
3922 * by "prog" before we can avoid copying the data structure in.
3924 * While computing the set of array elements that are copied out but
3925 * not necessarily written, we intersect both sets with the context.
3926 * This helps in those cases where the arrays are declared with a fixed size,
3927 * while the accesses are parametric and the context assigns a fixed value
3928 * to the parameters.
3930 * If an element from a local array is read without first being written,
3931 * then there is no point in copying it in since it cannot have been
3932 * written prior to the scop. Warn about the uninitialized read instead.
3934 static void compute_copy_in_and_out(struct gpu_prog *prog)
3936 int i;
3937 isl_union_set *local;
3938 isl_union_set *may_write, *must_write;
3939 isl_union_set *copy_in, *copy_out;
3940 isl_union_set *not_written;
3941 isl_union_map *uninitialized;
3942 isl_union_map *local_uninitialized;
3944 must_write = isl_union_map_range(
3945 isl_union_map_copy(prog->must_write));
3946 must_write = isl_union_set_intersect_params(must_write,
3947 isl_set_copy(prog->context));
3948 may_write = isl_union_map_range(
3949 isl_union_map_copy(prog->may_write));
3950 may_write = isl_union_set_intersect_params(may_write,
3951 isl_set_copy(prog->context));
3952 may_write = isl_union_set_universe(may_write);
3953 may_write = isl_union_set_apply(may_write,
3954 isl_union_map_copy(prog->to_outer));
3955 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
3956 local = isl_union_set_copy(copy_out);
3958 for (i = 0; i < prog->n_array; ++i) {
3959 isl_space *space;
3960 isl_set *write_i;
3961 int empty;
3963 space = isl_space_copy(prog->array[i].space);
3965 if (prog->array[i].local) {
3966 isl_set *set;
3968 set = isl_set_universe(space);
3969 local = isl_union_set_add_set(local, set);
3970 continue;
3973 write_i = isl_union_set_extract_set(may_write, space);
3974 empty = isl_set_plain_is_empty(write_i);
3975 isl_set_free(write_i);
3976 if (empty)
3977 continue;
3979 write_i = isl_set_copy(prog->array[i].extent);
3980 copy_out = isl_union_set_add_set(copy_out, write_i);
3982 isl_union_set_free(may_write);
3984 copy_out = isl_union_set_intersect_params(copy_out,
3985 isl_set_copy(prog->context));
3987 prog->copy_out = isl_union_set_copy(copy_out);
3989 copy_out = isl_union_set_apply(copy_out,
3990 isl_union_map_copy(prog->to_inner));
3991 copy_out = isl_union_set_intersect(copy_out,
3992 isl_union_set_copy(prog->may_persist));
3993 not_written = isl_union_set_subtract(copy_out, must_write);
3995 uninitialized = isl_union_map_copy(prog->scop->live_in);
3996 local_uninitialized = isl_union_map_copy(uninitialized);
3998 local = isl_union_set_apply(local, isl_union_map_copy(prog->to_inner));
3999 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4000 local);
4001 if (!isl_union_map_is_empty(local_uninitialized)) {
4002 fprintf(stderr,
4003 "possibly uninitialized reads (not copied in):\n");
4004 isl_union_map_dump(local_uninitialized);
4006 uninitialized = isl_union_map_subtract(uninitialized,
4007 local_uninitialized);
4008 copy_in = isl_union_map_range(uninitialized);
4009 copy_in = isl_union_set_union(copy_in, not_written);
4010 copy_in = isl_union_set_apply(copy_in,
4011 isl_union_map_copy(prog->to_outer));
4013 prog->copy_in = copy_in;
4016 /* Update "schedule" for mapping to a GPU device.
4018 * In particular, insert a context node and create kernels for
4019 * each outermost tilable band.
4021 static __isl_give isl_schedule *map_to_device(struct gpu_gen *gen,
4022 __isl_take isl_schedule *schedule)
4024 isl_schedule_node *node;
4025 isl_set *context;
4027 context = isl_set_copy(gen->prog->context);
4028 context = isl_set_from_params(context);
4029 schedule = isl_schedule_insert_context(schedule, context);
4031 node = isl_schedule_get_root(schedule);
4032 isl_schedule_free(schedule);
4033 node = isl_schedule_node_child(node, 0);
4034 if (isl_schedule_node_get_type(node) == isl_schedule_node_context)
4035 node = isl_schedule_node_child(node, 0);
4036 node = mark_kernels(gen, node);
4037 schedule = isl_schedule_node_get_schedule(node);
4038 isl_schedule_node_free(node);
4040 return schedule;
4043 /* Internal data structure for extract_access.
4044 * "next_access" points to the end of a linked list that is extended
4045 * by extract_access.
4046 * "single_expression" is set if the access expressions belong to
4047 * an expression statement (i.e., a statement without internal control).
4048 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4050 struct ppcg_extract_access_data {
4051 struct gpu_stmt_access **next_access;
4052 int single_expression;
4053 isl_union_map *any_to_outer;
4056 /* Given a tagged access relation to a single array "tagged", extract it
4057 * as a map, taking into account that the input may be empty.
4058 * If the access relation is empty, then it does not contain
4059 * any space information, so we try to recover it from the index
4060 * expression.
4061 * The space of the index expression is of the form I -> A,
4062 * with I the statement instances and A the array, or [I -> F] -> A,
4063 * with F the filters corresponding to arguments.
4064 * We first drop F, if present, obtaining I -> A.
4065 * Then we construct I -> R, with R the reference tag,
4066 * combine the two into I -> [R -> A] and uncurry to obtain
4067 * the final result [I -> R] -> A.
4068 * Note that the index expression may have a lower dimension
4069 * than that of the array, but this dimension is not used
4070 * if the access relation is empty.
4072 static __isl_give isl_map *extract_single_tagged_access(
4073 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
4075 int empty;
4076 isl_id *id;
4077 isl_space *space, *space2;
4078 isl_multi_pw_aff *index;
4080 empty = isl_union_map_is_empty(tagged);
4081 if (empty < 0)
4082 goto error;
4083 if (!empty)
4084 return isl_map_from_union_map(tagged);
4085 isl_union_map_free(tagged);
4087 index = pet_expr_access_get_index(expr);
4088 space = isl_multi_pw_aff_get_space(index);
4089 isl_multi_pw_aff_free(index);
4090 if (isl_space_domain_is_wrapping(space))
4091 space = isl_space_domain_factor_domain(space);
4092 space2 = isl_space_copy(space);
4093 space2 = isl_space_from_domain(isl_space_domain(space));
4094 id = pet_expr_access_get_ref_id(expr);
4095 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
4096 space = isl_space_range_product(space2, space);
4097 space = isl_space_uncurry(space);
4099 return isl_map_empty(space);
4100 error:
4101 isl_union_map_free(tagged);
4102 return NULL;
4105 /* Extract a gpu_stmt_access from "expr", append it to the list
4106 * that ends in *data->next_access and update the end of the list.
4107 * If the access expression performs a write, then it is considered
4108 * exact only if it appears in a single expression statement and
4109 * if its may access relation is equal to its must access relation.
4111 * The combined set of may accesses may be union if member accesses
4112 * are involved, but the entire set is derived from a single reference and
4113 * therefore from a single index expression. These accesses therefore
4114 * all map to the same outer array.
4116 static int extract_access(__isl_keep pet_expr *expr, void *user)
4118 struct ppcg_extract_access_data *data = user;
4119 isl_union_map *tagged;
4120 struct gpu_stmt_access *access;
4121 isl_ctx *ctx = pet_expr_get_ctx(expr);
4122 isl_multi_pw_aff *index;
4124 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4125 assert(access);
4126 access->next = NULL;
4127 access->read = pet_expr_access_is_read(expr);
4128 access->write = pet_expr_access_is_write(expr);
4129 tagged = pet_expr_access_get_tagged_may_read(expr);
4130 tagged = isl_union_map_union(tagged,
4131 pet_expr_access_get_tagged_may_write(expr));
4132 tagged = isl_union_map_apply_range(tagged,
4133 isl_union_map_copy(data->any_to_outer));
4134 if (!access->write) {
4135 access->exact_write = 1;
4136 } else if (!data->single_expression) {
4137 access->exact_write = 0;
4138 } else {
4139 isl_union_map *must, *may;
4140 may = isl_union_map_copy(tagged);
4141 may = isl_union_map_domain_factor_domain(may);
4142 must = pet_expr_access_get_must_write(expr);
4143 access->exact_write = isl_union_map_is_equal(must, may);
4144 isl_union_map_free(must);
4145 isl_union_map_free(may);
4147 index = pet_expr_access_get_index(expr);
4148 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
4149 isl_multi_pw_aff_free(index);
4150 access->ref_id = pet_expr_access_get_ref_id(expr);
4151 access->tagged_access = extract_single_tagged_access(tagged, expr);
4152 access->access = isl_map_copy(access->tagged_access);
4153 access->access = isl_map_domain_factor_domain(access->access);
4155 *data->next_access = access;
4156 data->next_access = &(*data->next_access)->next;
4158 if (!access->access)
4159 return -1;
4161 return 0;
4164 /* Construct a linked list of gpu_stmt_access objects,
4165 * one for each access expression in the statement body.
4166 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4168 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
4169 __isl_keep isl_union_map *any_to_outer)
4171 struct ppcg_extract_access_data data;
4173 stmt->accesses = NULL;
4174 data.next_access = &stmt->accesses;
4175 data.single_expression =
4176 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
4177 data.any_to_outer = any_to_outer;
4178 return pet_tree_foreach_access_expr(stmt->stmt->body,
4179 &extract_access, &data);
4182 /* Return an array of gpu_stmt representing the statements in "scop".
4184 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4185 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
4187 int i;
4188 struct gpu_stmt *stmts;
4190 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
4191 if (!stmts)
4192 return NULL;
4194 for (i = 0; i < scop->pet->n_stmt; ++i) {
4195 struct gpu_stmt *s = &stmts[i];
4197 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
4198 s->stmt = scop->pet->stmts[i];
4199 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
4200 return free_stmts(stmts, i + 1);
4203 return stmts;
4206 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
4208 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
4210 struct gpu_gen *gen = user;
4212 return gen->print(p, gen->prog, gen->tree, &gen->types,
4213 gen->print_user);
4216 /* Generate CUDA code for "scop" and print it to "p".
4217 * After generating an AST for the transformed scop as explained below,
4218 * we call "gen->print" to print the AST in the desired output format
4219 * to "p".
4221 * If it turns out that it does not make sense to generate GPU code,
4222 * then we generate CPU code instead.
4224 * The GPU code is generated in a context where at least one
4225 * statement instance is executed. The corresponding guard (if any) is printed
4226 * around the entire generated GPU code, except for the declaration
4227 * of the arrays that are visible outside of the scop and that therefore
4228 * cannot be declared inside the body of any possible guard.
4230 * We first compute a schedule that respects the dependences
4231 * of the original program and select the outermost bands
4232 * of tilable dimensions that have at least one parallel loop.
4233 * If the --load-schedule is specified, then the loaded schedule
4234 * is used instead of a computed schedule.
4236 * Each of these bands B is then tiled according to "tile" sizes, resulting
4237 * in two nested bands, with a kernel marker on top
4245 * We then split off at most 2 parallel dimensions from the T band and
4246 * at most 3 parallel dimension from the P band
4251 * T1
4253 * T2
4255 * P1
4257 * P2
4259 * A filter is introduced in front of T1 that maps the domain instances
4260 * to block identifiers. Similarly, a filter is introduced in front of P1
4261 * that maps the domain instances to thread identifiers.
4263 * For each iteration of the T2 band and for each array, we compute
4264 * the array elements accessed by that iteration, construct a rectangular
4265 * box around it and shift it to the origin. The result is used
4266 * as shared memory for the array.
4268 * Copying and synchronization statements are added to this schedule tree.
4269 * In principle, these are added in front of the P1 band, but some of
4270 * them may get hoisted up to higher levels.
4272 * The entire AST is then generated from the single resulting schedule tree.
4273 * During the generation the subtrees at kernel nodes (K) are saved
4274 * aside and replaced by kernel calls. The result is printed as host code
4275 * while the saved subtrees are printed as device code.
4277 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
4278 struct gpu_gen *gen, struct ppcg_scop *scop,
4279 struct ppcg_options *options)
4281 struct gpu_prog *prog;
4282 isl_ctx *ctx;
4283 isl_set *context, *guard;
4284 isl_schedule *schedule;
4285 int any_permutable;
4287 if (!scop)
4288 return isl_printer_free(p);
4290 ctx = isl_printer_get_ctx(p);
4291 prog = gpu_prog_alloc(ctx, scop);
4292 if (!prog)
4293 return isl_printer_free(p);
4295 context = isl_set_copy(prog->context);
4296 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
4297 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
4299 gen->prog = prog;
4300 schedule = get_schedule(gen);
4302 any_permutable = has_any_permutable_node(schedule);
4303 if (any_permutable < 0 || !any_permutable) {
4304 isl_set_free(context);
4305 isl_set_free(guard);
4306 if (any_permutable < 0)
4307 p = isl_printer_free(p);
4308 else
4309 p = print_cpu(p, scop, options);
4310 isl_schedule_free(schedule);
4311 } else {
4312 compute_copy_in_and_out(prog);
4313 schedule = map_to_device(gen, schedule);
4314 gen->tree = generate_code(gen, schedule);
4315 p = ppcg_print_exposed_declarations(p, prog->scop);
4316 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
4317 isl_ast_node_free(gen->tree);
4320 gpu_prog_free(prog);
4322 return p;
4325 /* Wrapper around generate for use as a ppcg_transform callback.
4327 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
4328 struct ppcg_scop *scop, void *user)
4330 struct gpu_gen *gen = user;
4332 return generate(p, gen, scop, gen->options);
4335 /* Transform the code in the file called "input" by replacing
4336 * all scops by corresponding GPU code and write the results to "out".
4338 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
4339 struct ppcg_options *options,
4340 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
4341 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
4342 struct gpu_types *types, void *user), void *user)
4344 struct gpu_gen gen;
4345 int r;
4346 int i;
4348 gen.ctx = ctx;
4349 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
4350 gen.options = options;
4351 gen.kernel_id = 0;
4352 gen.print = print;
4353 gen.print_user = user;
4354 gen.types.n = 0;
4355 gen.types.name = NULL;
4357 if (options->debug->dump_sizes) {
4358 isl_space *space = isl_space_params_alloc(ctx, 0);
4359 gen.used_sizes = isl_union_map_empty(space);
4362 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
4364 if (options->debug->dump_sizes) {
4365 isl_union_map_dump(gen.used_sizes);
4366 isl_union_map_free(gen.used_sizes);
4369 isl_union_map_free(gen.sizes);
4370 for (i = 0; i < gen.types.n; ++i)
4371 free(gen.types.name[i]);
4372 free(gen.types.name);
4374 return r;
4377 /* Compute the set of inner array elements that may have their values
4378 * preserved by "prog". In particular, collect the array elements of
4379 * arrays that are not local to "prog" and remove those elements that
4380 * are definitely killed or definitely written by "prog".
4382 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
4384 int i;
4385 isl_union_set *may_persist, *killed;
4386 isl_union_map *must_kill;
4388 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
4389 for (i = 0; i < prog->n_array; ++i) {
4390 isl_set *extent;
4392 if (prog->array[i].local)
4393 continue;
4395 extent = isl_set_copy(prog->array[i].extent);
4396 may_persist = isl_union_set_add_set(may_persist, extent);
4399 may_persist = isl_union_set_intersect_params(may_persist,
4400 isl_set_copy(prog->context));
4401 may_persist = isl_union_set_apply(may_persist,
4402 isl_union_map_copy(prog->to_inner));
4403 must_kill = isl_union_map_copy(prog->tagged_must_kill);
4404 killed = isl_union_map_range(must_kill);
4405 must_kill = isl_union_map_copy(prog->must_write);
4406 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
4408 may_persist = isl_union_set_subtract(may_persist, killed);
4409 return may_persist;
4412 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
4414 struct gpu_prog *prog;
4415 isl_space *space;
4416 isl_map *id;
4418 if (!scop)
4419 return NULL;
4421 prog = isl_calloc_type(ctx, struct gpu_prog);
4422 assert(prog);
4424 prog->ctx = ctx;
4425 prog->scop = scop;
4426 prog->context = isl_set_copy(scop->context);
4427 prog->n_stmts = scop->pet->n_stmt;
4428 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
4429 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
4430 space = isl_union_map_get_space(prog->any_to_outer);
4431 space = isl_space_set_from_params(space);
4432 space = isl_space_add_dims(space, isl_dim_set, 1);
4433 space = isl_space_map_from_set(space);
4434 id = isl_map_identity(space);
4435 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
4436 prog->stmts = extract_stmts(ctx, scop,
4437 prog->context, prog->any_to_outer);
4438 prog->read = isl_union_map_copy(scop->reads);
4439 prog->may_write = isl_union_map_copy(scop->may_writes);
4440 prog->must_write = isl_union_map_copy(scop->must_writes);
4441 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
4442 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
4443 prog->to_outer = isl_union_map_copy(prog->to_inner);
4444 prog->to_outer = isl_union_map_reverse(prog->to_outer);
4446 if (!prog->stmts)
4447 return gpu_prog_free(prog);
4449 if (collect_array_info(prog) < 0)
4450 return gpu_prog_free(prog);
4451 prog->may_persist = compute_may_persist(prog);
4453 return prog;
4456 void *gpu_prog_free(struct gpu_prog *prog)
4458 if (!prog)
4459 return NULL;
4460 free_array_info(prog);
4461 free_stmts(prog->stmts, prog->n_stmts);
4462 isl_union_map_free(prog->any_to_outer);
4463 isl_union_map_free(prog->to_outer);
4464 isl_union_map_free(prog->to_inner);
4465 isl_union_set_free(prog->copy_in);
4466 isl_union_set_free(prog->copy_out);
4467 isl_union_map_free(prog->read);
4468 isl_union_map_free(prog->may_write);
4469 isl_union_map_free(prog->must_write);
4470 isl_union_map_free(prog->tagged_must_kill);
4471 isl_union_map_free(prog->array_order);
4472 isl_union_set_free(prog->may_persist);
4473 isl_set_free(prog->context);
4474 free(prog);
4475 return NULL;