add prefixcmp utility function
[ppcg.git] / gpu.c
blob51ab7963505d6f9700d52781f8121268074164fa
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 if (!array)
408 return NULL;
410 space = isl_space_params(isl_space_copy(array->space));
411 guard = isl_set_universe(space);
413 for (i = 0; i < array->n_index; ++i) {
414 isl_pw_aff *bound;
415 isl_set *guard_i, *zero;
417 bound = isl_pw_aff_copy(array->bound[i]);
418 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
419 zero = isl_pw_aff_zero_set(bound);
420 guard_i = isl_set_subtract(guard_i, zero);
421 guard = isl_set_intersect(guard, guard_i);
424 return guard;
427 /* Internal data structure for extract_size_of_type.
428 * "type" specifies the name of the space that we want to extract.
429 * "res" is used to store the subset of that space.
431 struct ppcg_extract_size_data {
432 const char *type;
433 isl_set *res;
436 /* This function is called for each set in a union_set.
437 * If the name of the set matches data->type, we store the
438 * set in data->res.
440 static int extract_size_of_type(__isl_take isl_set *size, void *user)
442 struct ppcg_extract_size_data *data = user;
443 const char *name;
445 name = isl_set_get_tuple_name(size);
446 if (name && !strcmp(name, data->type)) {
447 data->res = size;
448 return -1;
451 isl_set_free(size);
452 return 0;
455 /* Given a union map { kernel[i] -> *[...] },
456 * return the range in the space called "type" for the kernel with
457 * sequence number "id".
459 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
460 const char *type, int id)
462 isl_space *space;
463 isl_set *dom;
464 isl_union_set *local_sizes;
465 struct ppcg_extract_size_data data = { type, NULL };
467 if (!sizes)
468 return NULL;
470 space = isl_union_map_get_space(sizes);
471 space = isl_space_set_from_params(space);
472 space = isl_space_add_dims(space, isl_dim_set, 1);
473 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
474 dom = isl_set_universe(space);
475 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
477 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
478 isl_union_map_copy(sizes));
479 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
480 isl_union_set_free(local_sizes);
481 return data.res;
484 /* Given a singleton set, extract the first (at most *len) elements
485 * of the single integer tuple into *sizes and update *len if needed.
487 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
489 int i;
490 int dim;
492 if (!set)
493 return;
495 dim = isl_set_dim(set, isl_dim_set);
496 if (dim < *len)
497 *len = dim;
499 for (i = 0; i < *len; ++i) {
500 isl_val *v;
502 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
503 assert(v);
505 sizes[i] = isl_val_get_num_si(v);
506 isl_val_free(v);
509 isl_set_free(set);
512 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
513 * if the option debug->dump_sizes is set.
515 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
516 int *sizes, int len)
518 int i;
519 isl_space *space;
520 isl_map *map;
522 if (!gen->options->debug->dump_sizes)
523 return;
525 space = isl_union_map_get_space(gen->used_sizes);
526 space = isl_space_set_from_params(space);
527 space = isl_space_add_dims(space, isl_dim_set, 1);
528 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
529 space = isl_space_from_domain(space);
530 space = isl_space_add_dims(space, isl_dim_out, len);
531 space = isl_space_set_tuple_name(space, isl_dim_out, type);
533 map = isl_map_universe(space);
534 map = isl_map_fix_si(map, isl_dim_in, 0, id);
535 for (i = 0; i < len; ++i)
536 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
538 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
541 /* Extract user specified "tile" sizes from the "sizes" command line option,
542 * defaulting to option->tile_size in each dimension.
543 * *tile_len contains the maximum number of tile sizes needed.
544 * Update *tile_len to the number of specified tile sizes, if any, and
545 * return a pointer to the tile sizes (or NULL on error).
546 * Add the effectively used sizes to gen->used_sizes.
548 static int *read_tile_sizes(struct gpu_gen *gen, int *tile_len)
550 int n;
551 int *tile_size;
552 isl_set *size;
554 tile_size = isl_alloc_array(gen->ctx, int, *tile_len);
555 if (!tile_size)
556 return NULL;
557 for (n = 0; n < *tile_len; ++n)
558 tile_size[n] = gen->options->tile_size;
560 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
561 read_sizes_from_set(size, tile_size, tile_len);
562 set_used_sizes(gen, "tile", gen->kernel_id, tile_size, *tile_len);
564 return tile_size;
567 /* Extract user specified "block" sizes from the "sizes" command line option,
568 * after filling in some potentially useful defaults.
570 static void read_block_sizes(struct ppcg_kernel *kernel,
571 __isl_keep isl_union_map *sizes)
573 isl_set *size;
575 if (kernel->n_block > 3)
576 kernel->n_block = 3;
577 switch (kernel->n_block) {
578 case 1:
579 kernel->block_dim[0] = 512;
580 break;
581 case 2:
582 kernel->block_dim[0] = 32;
583 kernel->block_dim[1] = 16;
584 break;
585 default:
586 kernel->block_dim[0] = 32;
587 kernel->block_dim[1] = 4;
588 kernel->block_dim[2] = 4;
589 break;
592 size = extract_sizes(sizes, "block", kernel->id);
593 read_sizes_from_set(size, kernel->block_dim, &kernel->n_block);
596 /* Extract user specified "grid" sizes from the "sizes" command line option,
597 * after filling in some potentially useful defaults.
599 static void read_grid_sizes(struct ppcg_kernel *kernel,
600 __isl_keep isl_union_map *sizes)
602 isl_set *size;
604 if (kernel->n_grid > 2)
605 kernel->n_grid = 2;
606 switch (kernel->n_grid) {
607 case 1:
608 kernel->grid_dim[0] = 32768;
609 break;
610 default:
611 kernel->grid_dim[0] = 256;
612 kernel->grid_dim[1] = 256;
613 break;
616 size = extract_sizes(sizes, "grid", kernel->id);
617 read_sizes_from_set(size, kernel->grid_dim, &kernel->n_grid);
620 /* Extract user specified grid and block sizes from the gen->sizes
621 * command line option after filling in some potentially useful defaults.
622 * Store the extracted sizes in "kernel".
623 * Add the effectively used sizes to gen->used_sizes.
625 static void read_grid_and_block_sizes(struct ppcg_kernel *kernel,
626 struct gpu_gen *gen)
628 read_block_sizes(kernel, gen->sizes);
629 read_grid_sizes(kernel, gen->sizes);
630 set_used_sizes(gen, "block", kernel->id,
631 kernel->block_dim, kernel->n_block);
632 set_used_sizes(gen, "grid", kernel->id,
633 kernel->grid_dim, kernel->n_grid);
636 static void *free_stmts(struct gpu_stmt *stmts, int n)
638 int i;
640 if (!stmts)
641 return NULL;
643 for (i = 0; i < n; ++i) {
644 struct gpu_stmt_access *access, *next;
646 for (access = stmts[i].accesses; access; access = next) {
647 next = access->next;
648 isl_id_free(access->ref_id);
649 isl_map_free(access->access);
650 isl_map_free(access->tagged_access);
651 free(access);
654 isl_id_free(stmts[i].id);
656 free(stmts);
658 return NULL;
661 /* Add parameters p[i] with identifiers "ids" to "set",
662 * with bounds to 0 <= p[i] < size[i].
664 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
665 int *size, __isl_keep isl_id_list *ids)
667 int i, len;
668 unsigned nparam;
670 len = isl_id_list_n_id(ids);
671 nparam = isl_set_dim(set, isl_dim_param);
672 set = isl_set_add_dims(set, isl_dim_param, len);
674 for (i = 0; i < len; ++i) {
675 isl_id *id;
677 id = isl_id_list_get_id(ids, i);
678 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
679 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
680 set = isl_set_upper_bound_si(set, isl_dim_param,
681 nparam + i, size[i] - 1);
684 return set;
687 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
688 * with
690 * { : 0 <= p[i] < size[i] }
692 * or an overapproximation.
694 static __isl_give isl_set *add_bounded_parameters_dynamic(
695 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
696 __isl_keep isl_id_list *ids)
698 int i, len;
699 unsigned nparam;
700 isl_space *space;
701 isl_local_space *ls;
703 len = isl_multi_pw_aff_dim(size, isl_dim_out);
704 nparam = isl_set_dim(set, isl_dim_param);
705 set = isl_set_add_dims(set, isl_dim_param, len);
707 for (i = 0; i < len; ++i) {
708 isl_id *id;
710 id = isl_id_list_get_id(ids, i);
711 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
714 space = isl_space_params(isl_set_get_space(set));
715 ls = isl_local_space_from_space(space);
716 for (i = 0; i < len; ++i) {
717 isl_pw_aff *param, *size_i, *zero;
718 isl_set *bound;
720 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
721 isl_dim_param, nparam + i);
723 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
724 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
725 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
726 set = isl_set_intersect_params(set, bound);
728 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
729 bound = isl_pw_aff_ge_set(param, zero);
730 set = isl_set_intersect_params(set, bound);
732 isl_local_space_free(ls);
734 return set;
737 /* Return the union of all tagged access relations in the group.
739 static __isl_give isl_union_map *group_tagged_access_relation(
740 struct gpu_array_ref_group *group)
742 int i;
743 isl_union_map *access;
745 access = isl_union_map_empty(isl_map_get_space(group->access));
746 for (i = 0; i < group->n_ref; ++i) {
747 isl_map *map_i;
749 map_i = isl_map_copy(group->refs[i]->tagged_access);
750 access = isl_union_map_union(access,
751 isl_union_map_from_map(map_i));
754 return access;
757 /* Return the extent of "array", recomputed from the bounds.
758 * The recomputed extent may be simpler than the original extent.
760 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
762 int i;
763 isl_id *id;
764 isl_space *space;
765 isl_local_space *ls;
766 isl_set *extent;
768 id = isl_set_get_tuple_id(array->extent);
769 space = isl_set_get_space(array->extent);
770 extent = isl_set_universe(isl_space_copy(space));
771 ls = isl_local_space_from_space(space);
772 for (i = 0; i < array->n_index; ++i) {
773 isl_pw_aff *bound;
774 isl_aff *aff;
775 isl_pw_aff *index;
776 isl_set *lt;
778 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
780 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
781 isl_dim_set, i);
782 index = isl_pw_aff_from_aff(aff);
783 bound = isl_pw_aff_copy(array->bound[i]);
784 bound = isl_pw_aff_from_range(bound);
785 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
786 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
787 isl_id_copy(id));
788 lt = isl_pw_aff_lt_set(index, bound);
789 extent = isl_set_intersect(extent, lt);
791 isl_local_space_free(ls);
792 isl_id_free(id);
794 return extent;
797 /* Return a map from the first group->depth dimensions of the computed
798 * schedule to the array tile in
799 * global memory that corresponds to the shared memory copy.
801 * In particular, return a map
803 * { D[i] -> A[a] }
805 * with constraints
807 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
809 * and
811 * 0 <= a <= array_size - 1 (2)
813 * Note that if some stride has been detected (i.e., when
814 * group->shared_tile->bound[i].shift is set), then a in (1) refers
815 * to the shifted and scaled down version.
817 * Constraints (1) are obtained by mapping the size constraints on the
818 * shared/private memory tile back to the access relation.
819 * Constraints (2) are obtained from the (recomputed) extent.
821 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
823 int i;
824 int n_index = group->array->n_index;
825 isl_map *tile;
826 isl_space *space;
827 isl_set *local;
828 isl_set *extent;
830 space = isl_multi_aff_get_space(group->shared_tile->tiling);
831 space = isl_space_range(space);
832 local = isl_set_universe(space);
833 for (i = 0; i < n_index; ++i) {
834 isl_val *bound;
836 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
837 bound = isl_val_copy(group->shared_tile->bound[i].size);
838 bound = isl_val_sub_ui(bound, 1);
839 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
841 local = isl_set_preimage_multi_aff(local,
842 isl_multi_aff_copy(group->shared_tile->tiling));
843 tile = isl_set_unwrap(local);
844 extent = array_extent(group->array);
845 tile = isl_map_intersect_range(tile, extent);
847 return tile;
850 /* Given a mapping "iterator_map" from the AST schedule to a domain,
851 * return the corresponding mapping from the AST schedule to
852 * to the outer kernel->shared_schedule_dim dimensions of
853 * the schedule computed by PPCG for this kernel.
855 * Note that kernel->shared_schedule_dim is at least as large as
856 * the largest depth of any array reference group associated to the kernel.
857 * This is needed as the returned schedule is used to extract a mapping
858 * to the outer group->depth dimensions in transform_index.
860 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(
861 struct ppcg_kernel *kernel, __isl_take isl_pw_multi_aff *iterator_map)
863 isl_union_pw_multi_aff *upma;
864 isl_pw_multi_aff *pma;
865 isl_space *space;
867 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
868 space = isl_space_from_domain(space);
869 space = isl_space_add_dims(space, isl_dim_out,
870 kernel->shared_schedule_dim);
872 upma = isl_union_pw_multi_aff_copy(kernel->shared_schedule);
873 pma = isl_union_pw_multi_aff_extract_pw_multi_aff(upma, space);
874 isl_union_pw_multi_aff_free(upma);
876 return isl_pw_multi_aff_pullback_pw_multi_aff(pma, iterator_map);
879 /* If max_shared_memory is not set to infinity (-1), then make
880 * sure that the total amount of shared memory required by the
881 * array reference groups mapped to shared memory by "kernel"
882 * is no larger than this maximum.
884 * We apply a greedy approach and discard (keep in global memory)
885 * those groups that would result in a total memory size that
886 * is larger than the maximum.
888 * This function should be called after any function that may
889 * affect the decision on whether to place a reference group
890 * in private, shared or global memory.
892 static void check_shared_memory_bound(struct ppcg_kernel *kernel)
894 int i, j;
895 isl_val *left, *size;
897 if (kernel->options->max_shared_memory < 0)
898 return;
900 left = isl_val_int_from_si(kernel->ctx,
901 kernel->options->max_shared_memory);
903 for (i = 0; i < kernel->n_array; ++i) {
904 struct gpu_local_array_info *local = &kernel->array[i];
906 for (j = 0; j < local->n_group; ++j) {
907 struct gpu_array_ref_group *group;
909 group = local->groups[j];
910 if (group->private_tile)
911 continue;
912 if (!group->shared_tile)
913 continue;
915 size = gpu_array_tile_size(group->shared_tile);
916 size = isl_val_mul_ui(size, local->array->size);
918 if (isl_val_le(size, left)) {
919 left = isl_val_sub(left, size);
920 continue;
922 isl_val_free(size);
924 group->shared_tile =
925 gpu_array_tile_free(group->shared_tile);
929 isl_val_free(left);
932 /* Compute a tiling for all the array reference groups in "kernel".
934 static void compute_group_tilings(struct ppcg_kernel *kernel)
936 int i, j;
938 for (i = 0; i < kernel->n_array; ++i) {
939 struct gpu_local_array_info *array = &kernel->array[i];
941 for (j = 0; j < array->n_group; ++j)
942 gpu_array_ref_group_compute_tiling(array->groups[j]);
946 /* Compute the size of a bounding box around the origin and "set",
947 * where "set" is assumed to contain only non-negative elements.
948 * In particular, compute the maximal value of "set" in each direction
949 * and add one.
951 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
952 __isl_take isl_set *context)
954 int i, n;
955 isl_multi_pw_aff *mpa;
957 context = isl_set_params(context);
958 n = isl_set_dim(set, isl_dim_set);
959 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
960 for (i = 0; i < n; ++i) {
961 isl_space *space;
962 isl_aff *one;
963 isl_pw_aff *bound;
965 bound = isl_set_dim_max(isl_set_copy(set), i);
966 bound = isl_pw_aff_coalesce(bound);
967 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
969 space = isl_pw_aff_get_domain_space(bound);
970 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
971 one = isl_aff_add_constant_si(one, 1);
972 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
973 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
975 isl_set_free(set);
976 isl_set_free(context);
978 return mpa;
981 /* Compute the effective grid size as a list of the sizes in each dimension.
983 * The grid size specified by the user or set by default
984 * in read_grid_sizes() and applied by the block filter,
985 * may be too large for the given code in the sense that
986 * it may contain blocks that don't need to execute anything.
987 * We therefore don't return this grid size, but instead the
988 * smallest grid size that ensures that all blocks that actually
989 * execute code are included in the grid.
991 * We first extract a description of the grid, i.e., the possible values
992 * of the block ids, from the domain elements in "domain" and
993 * kernel->block_filter.
994 * The block ids are parameters in kernel->block_filter.
995 * We simply need to change them into set dimensions.
997 * Then, for each block dimension, we compute the maximal value of the block id
998 * and add one.
1000 static __isl_give isl_multi_pw_aff *extract_grid_size(
1001 struct ppcg_kernel *kernel, __isl_take isl_union_set *domain)
1003 int i;
1004 isl_set *grid;
1006 domain = isl_union_set_intersect(domain,
1007 isl_union_set_copy(kernel->block_filter));
1008 grid = isl_union_set_params(domain);
1009 grid = isl_set_from_params(grid);
1010 grid = isl_set_add_dims(grid, isl_dim_set, kernel->n_grid);
1011 for (i = 0; i < kernel->n_grid; ++i) {
1012 int pos;
1013 isl_id *id;
1015 id = isl_id_list_get_id(kernel->block_ids, i);
1016 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1017 isl_id_free(id);
1018 assert(pos >= 0);
1019 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1020 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1023 return extract_size(grid, isl_set_copy(kernel->context));
1026 /* Compute the size of a fixed bounding box around the origin and "set",
1027 * where "set" is assumed to contain only non-negative elements,
1028 * and store the results in "size".
1029 * In particular, compute the maximal value of "set" in each direction
1030 * and add one.
1032 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1034 int i, n;
1035 isl_local_space *ls;
1036 isl_aff *obj;
1038 n = isl_set_dim(set, isl_dim_set);
1039 ls = isl_local_space_from_space(isl_set_get_space(set));
1040 obj = isl_aff_zero_on_domain(ls);
1041 for (i = 0; i < n; ++i) {
1042 isl_val *max;
1044 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1045 max = isl_set_max_val(set, obj);
1046 size[i] = isl_val_get_num_si(max) + 1;
1047 isl_val_free(max);
1048 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1050 isl_aff_free(obj);
1051 isl_set_free(set);
1054 /* Compute the effective block size as a list of the sizes in each dimension
1055 * and store the sizes in kernel->block_dim.
1057 * The block size specified by the user or set by default
1058 * in read_block_sizes() and applied by the thread filter,
1059 * may be too large for the given code in the sense that
1060 * it may contain threads that don't need to execute anything.
1061 * We therefore update this block size in kernel->block_dim
1062 * to the smallest block size that ensures that all threads
1063 * that actually execute code are included in the block.
1065 * The possible values of the thread ids is obtained from
1066 * the domain elements "domain" and kernel->thread_filter.
1067 * The current implementation eliminates all parameters, ensuring
1068 * that the size is a fixed constant in each dimension.
1069 * In principle we could also compute parametric sizes.
1070 * We would have to make sure to project out all b%d and t%d parameters,
1071 * however.
1073 static void extract_block_size(struct ppcg_kernel *kernel,
1074 __isl_take isl_union_set *domain)
1076 int i;
1077 int nparam;
1078 isl_set *block;
1080 domain = isl_union_set_intersect(domain,
1081 isl_union_set_copy(kernel->thread_filter));
1082 block = isl_union_set_params(domain);
1083 block = isl_set_from_params(block);
1084 block = isl_set_add_dims(block, isl_dim_set, kernel->n_block);
1085 for (i = 0; i < kernel->n_block; ++i) {
1086 int pos;
1087 isl_id *id;
1089 id = isl_id_list_get_id(kernel->thread_ids, i);
1090 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1091 isl_id_free(id);
1092 assert(pos >= 0);
1093 block = isl_set_equate(block, isl_dim_param, pos,
1094 isl_dim_set, i);
1096 nparam = isl_set_dim(block, isl_dim_param);
1097 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1099 extract_fixed_size(block, kernel->block_dim);
1102 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1104 int i, j;
1106 if (!kernel)
1107 return NULL;
1109 isl_id_list_free(kernel->block_ids);
1110 isl_id_list_free(kernel->thread_ids);
1111 isl_multi_pw_aff_free(kernel->grid_size);
1112 isl_set_free(kernel->context);
1113 isl_union_set_free(kernel->core);
1114 isl_union_set_free(kernel->arrays);
1115 isl_space_free(kernel->space);
1116 isl_ast_node_free(kernel->tree);
1117 isl_union_set_free(kernel->block_filter);
1118 isl_union_set_free(kernel->thread_filter);
1119 isl_union_pw_multi_aff_free(kernel->shared_schedule);
1120 isl_union_set_free(kernel->sync_writes);
1122 for (i = 0; i < kernel->n_array; ++i) {
1123 struct gpu_local_array_info *array = &kernel->array[i];
1125 for (j = 0; j < array->n_group; ++j)
1126 gpu_array_ref_group_free(array->groups[j]);
1127 free(array->groups);
1129 isl_pw_aff_list_free(array->bound);
1131 free(kernel->array);
1133 for (i = 0; i < kernel->n_var; ++i) {
1134 free(kernel->var[i].name);
1135 isl_vec_free(kernel->var[i].size);
1137 free(kernel->var);
1139 free(kernel);
1141 return NULL;
1144 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1146 static void ppcg_kernel_free_wrap(void *user)
1148 struct ppcg_kernel *kernel = user;
1150 ppcg_kernel_free(kernel);
1153 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1154 struct ppcg_kernel_var *var)
1156 int j;
1157 struct gpu_array_tile *tile;
1158 isl_printer *p;
1159 char *name;
1161 var->array = group->array;
1163 tile = group->private_tile;
1164 var->type = ppcg_access_private;
1165 if (!tile) {
1166 tile = group->shared_tile;
1167 var->type = ppcg_access_shared;
1170 p = isl_printer_to_str(ctx);
1171 p = gpu_array_ref_group_print_name(group, p);
1172 var->name = isl_printer_get_str(p);
1173 isl_printer_free(p);
1175 var->size = isl_vec_alloc(ctx, group->array->n_index);
1177 for (j = 0; j < group->array->n_index; ++j)
1178 var->size = isl_vec_set_element_val(var->size, j,
1179 isl_val_copy(tile->bound[j].size));
1182 static int create_kernel_vars(struct ppcg_kernel *kernel)
1184 int i, j, n;
1186 n = 0;
1187 for (i = 0; i < kernel->n_array; ++i) {
1188 struct gpu_local_array_info *array = &kernel->array[i];
1190 for (j = 0; j < array->n_group; ++j) {
1191 struct gpu_array_ref_group *group = array->groups[j];
1192 if (group->private_tile || group->shared_tile)
1193 ++n;
1197 kernel->n_var = n;
1198 kernel->var = isl_calloc_array(kernel->ctx, struct ppcg_kernel_var, n);
1199 if (!kernel->var)
1200 return -1;
1202 n = 0;
1203 for (i = 0; i < kernel->n_array; ++i) {
1204 struct gpu_local_array_info *array = &kernel->array[i];
1206 for (j = 0; j < array->n_group; ++j) {
1207 struct gpu_array_ref_group *group = array->groups[j];
1208 if (!group->private_tile && !group->shared_tile)
1209 continue;
1210 create_kernel_var(kernel->ctx, group, &kernel->var[n]);
1211 ++n;
1215 return 0;
1218 /* Replace "pa" by the zero function defined over the universe domain
1219 * in the space of "pa".
1221 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1223 isl_space *space;
1224 isl_aff *zero;
1226 space = isl_space_domain(isl_pw_aff_get_space(pa));
1227 isl_pw_aff_free(pa);
1228 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1230 return isl_pw_aff_from_aff(zero);
1233 /* The sizes of the arrays on the host that have been computed by
1234 * extract_array_info may depend on the parameters. Use the extra
1235 * constraints on the parameters that are valid at "host_domain"
1236 * to simplify these expressions and store the results in kernel->array.
1238 * We only need these localized bounds for arrays that are accessed
1239 * by the current kernel. If we have found at least one reference group
1240 * then the array is accessed by the kernel. If the array has compound
1241 * elements then we skipped the construction of array reference groups.
1243 * The resulting sizes may be functions that are nowhere defined
1244 * in case the access function cannot possibly access anything inside
1245 * the kernel for some reason. If so, they are replaced by the zero
1246 * function. Since the access function cannot actually access anything,
1247 * there is no harm in printing the array sizes as zero.
1249 static void localize_bounds(struct ppcg_kernel *kernel,
1250 __isl_keep isl_set *host_domain)
1252 int i, j;
1253 isl_set *context;
1255 context = isl_set_copy(host_domain);
1256 context = isl_set_params(context);
1258 for (i = 0; i < kernel->n_array; ++i) {
1259 struct gpu_local_array_info *local = &kernel->array[i];
1260 isl_pw_aff_list *bound;
1261 int n_index;
1263 if (local->n_group == 0 && !local->array->has_compound_element)
1264 continue;
1266 n_index = local->array->n_index;
1267 bound = isl_pw_aff_list_alloc(kernel->ctx, n_index);
1269 for (j = 0; j < n_index; ++j) {
1270 isl_pw_aff *pwaff;
1271 int empty;
1273 pwaff = isl_pw_aff_copy(local->array->bound[j]);
1274 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1275 empty = isl_pw_aff_is_empty(pwaff);
1276 if (empty < 0)
1277 pwaff = isl_pw_aff_free(pwaff);
1278 else if (empty)
1279 pwaff = set_universally_zero(pwaff);
1280 bound = isl_pw_aff_list_add(bound, pwaff);
1283 local->n_index = n_index;
1284 local->bound = bound;
1286 isl_set_free(context);
1289 /* Create the array of gpu_local_array_info structures "array"
1290 * inside "kernel". The number of elements in this array is
1291 * the same as the number of arrays in "prog".
1292 * Initialize the "array" field of each local array to point
1293 * to the corresponding array in "prog".
1295 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1296 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1298 int i;
1299 isl_ctx *ctx;
1301 ctx = isl_set_get_ctx(prog->context);
1302 kernel->array = isl_calloc_array(ctx,
1303 struct gpu_local_array_info, prog->n_array);
1304 if (!kernel->array)
1305 return ppcg_kernel_free(kernel);
1306 kernel->n_array = prog->n_array;
1308 for (i = 0; i < prog->n_array; ++i)
1309 kernel->array[i].array = &prog->array[i];
1311 return kernel;
1314 /* Find the element in gen->stmt that has the given "id".
1315 * Return NULL if no such gpu_stmt can be found.
1317 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1319 int i;
1321 for (i = 0; i < prog->n_stmts; ++i) {
1322 if (id == prog->stmts[i].id)
1323 break;
1326 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1329 void ppcg_kernel_stmt_free(void *user)
1331 int i;
1332 struct ppcg_kernel_stmt *stmt = user;
1334 if (!stmt)
1335 return;
1337 switch (stmt->type) {
1338 case ppcg_kernel_copy:
1339 isl_ast_expr_free(stmt->u.c.index);
1340 isl_ast_expr_free(stmt->u.c.local_index);
1341 break;
1342 case ppcg_kernel_domain:
1343 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1344 break;
1345 case ppcg_kernel_sync:
1346 break;
1349 free(stmt);
1352 /* Return the gpu_stmt_access in the list "accesses" that corresponds
1353 * to "ref_id".
1355 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1356 __isl_keep isl_id *ref_id)
1358 struct gpu_stmt_access *access;
1360 for (access = accesses; access; access = access->next)
1361 if (access->ref_id == ref_id)
1362 return access;
1364 return NULL;
1367 /* Return the index of the array called "name" in the list of arrays.
1369 static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1371 int i;
1373 for (i = 0; i < kernel->n_array; ++i)
1374 if (!strcmp(name, kernel->array[i].array->name))
1375 return i;
1377 return -1;
1380 /* Internal data structure for the index and AST expression transformation
1381 * callbacks for pet_stmt_build_ast_exprs.
1383 * "kernel" is the kernel for which are computing AST expressions.
1384 * "accesses" is the list of gpu_stmt_access in the statement.
1385 * "iterator_map" expresses the statement iterators in terms of
1386 * the AST loop iterators.
1387 * "sched2shared" expresses the outer shared_schedule_dim dimensions of
1388 * the kernel schedule in terms of the AST loop iterators.
1390 * The following fields are set in transform_index and used in transform_expr.
1391 * "array" is the array that is being accessed.
1392 * "global" is set if the global array is accessed (rather than
1393 * shared/private memory).
1394 * "local_array" refers to information on the array specialized
1395 * to the current kernel.
1397 struct ppcg_transform_data {
1398 struct ppcg_kernel *kernel;
1399 struct gpu_stmt_access *accesses;
1400 isl_pw_multi_aff *iterator_map;
1401 isl_pw_multi_aff *sched2shared;
1403 struct gpu_array_info *array;
1404 int global;
1405 struct gpu_local_array_info *local_array;
1408 /* Return the name of the outer array (of structs) accessed by "access".
1410 static const char *get_outer_array_name(__isl_keep isl_map *access)
1412 isl_space *space;
1413 const char *name;
1415 space = isl_space_range(isl_map_get_space(access));
1416 while (space && isl_space_is_wrapping(space))
1417 space = isl_space_domain(isl_space_unwrap(space));
1418 name = isl_space_get_tuple_name(space, isl_dim_set);
1419 isl_space_free(space);
1421 return name;
1424 /* Return a pointer to the gpu_array_ref_group in "local"
1425 * that contains the reference "access".
1426 * Return NULL if no such group can be found.
1428 static struct gpu_array_ref_group *find_ref_group(
1429 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1431 int i, j;
1433 for (i = 0; i < local->n_group; ++i) {
1434 struct gpu_array_ref_group *group = local->groups[i];
1436 for (j = 0; j < group->n_ref; ++j)
1437 if (group->refs[j] == access)
1438 return group;
1441 return NULL;
1444 /* Index transformation callback for pet_stmt_build_ast_exprs.
1446 * "index" expresses the array indices in terms of statement iterators
1448 * We first reformulate "index" in terms of the AST loop iterators.
1449 * Then we check if we are accessing the global array or
1450 * a shared/private copy. In the former case, we simply return
1451 * the updated index. If "index" is an affine expression rather
1452 * than an array access, then we also return the updated index here.
1454 * If no reference groups have been computed for the array,
1455 * then we can only be accessing the global array.
1457 * Otherwise, we apply the tiling to the index.
1458 * This tiling is of the form
1460 * [D -> A] -> T
1462 * where D corresponds to the outer group->depth dimensions of
1463 * the kernel schedule.
1464 * The index is of the form
1466 * L -> A
1468 * We update the tiling to refer to the AST loop iterators
1470 * [L -> A] -> T
1472 * and modify index to keep track of those iterators
1474 * L -> [L -> A]
1476 * Combining these two yields a tiled index expression in terms
1477 * of the AST loop iterators
1479 * L -> T
1481 static __isl_give isl_multi_pw_aff *transform_index(
1482 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
1483 void *user)
1485 struct ppcg_transform_data *data = user;
1486 struct gpu_stmt_access *access;
1487 struct gpu_array_ref_group *group;
1488 struct gpu_array_tile *tile;
1489 isl_pw_multi_aff *iterator_map;
1490 int i;
1491 int dim;
1492 const char *name;
1493 isl_space *space;
1494 isl_multi_pw_aff *tiling;
1495 isl_pw_multi_aff *pma;
1496 isl_multi_pw_aff *mpa;
1497 isl_pw_multi_aff *sched2depth;
1499 data->array = NULL;
1501 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
1502 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
1504 access = find_access(data->accesses, ref_id);
1505 if (!access)
1506 return index;
1507 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1508 return index;
1510 name = get_outer_array_name(access->access);
1511 i = find_array_index(data->kernel, name);
1512 if (i < 0)
1513 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
1514 "cannot find array",
1515 return isl_multi_pw_aff_free(index));
1516 data->local_array = &data->kernel->array[i];
1517 data->array = data->local_array->array;
1519 group = find_ref_group(data->local_array, access);
1520 if (!group) {
1521 data->global = 1;
1522 return index;
1525 tile = group->private_tile;
1526 if (!tile)
1527 tile = group->shared_tile;
1528 data->global = !tile;
1529 if (!tile)
1530 return index;
1532 space = isl_space_range(isl_multi_pw_aff_get_space(index));
1533 space = isl_space_map_from_set(space);
1534 pma = isl_pw_multi_aff_identity(space);
1535 sched2depth = isl_pw_multi_aff_copy(data->sched2shared);
1536 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1537 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1538 group->depth, dim - group->depth);
1539 pma = isl_pw_multi_aff_product(sched2depth, pma);
1540 tiling = isl_multi_pw_aff_from_multi_aff(
1541 isl_multi_aff_copy(tile->tiling));
1542 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1544 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1545 space = isl_space_map_from_set(space);
1546 mpa = isl_multi_pw_aff_identity(space);
1547 index = isl_multi_pw_aff_range_product(mpa, index);
1548 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1550 return index;
1553 /* Dereference "expr" by adding an index [0].
1554 * The original "expr" is assumed not to have any indices.
1556 * If "expr" is a member access, then the dereferencing needs
1557 * to be applied to the structure argument of this member access.
1559 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1561 isl_ctx *ctx;
1562 isl_ast_expr *arg0, *res;
1563 isl_ast_expr_list *list;
1565 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1566 if (!arg0)
1567 return isl_ast_expr_free(expr);
1568 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1569 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1570 isl_ast_expr *arg;
1572 arg = isl_ast_expr_get_op_arg(arg0, 0);
1573 arg = dereference(arg);
1574 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1575 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1577 return expr;
1579 isl_ast_expr_free(arg0);
1581 ctx = isl_ast_expr_get_ctx(expr);
1582 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1583 list = isl_ast_expr_list_from_ast_expr(res);
1584 res = isl_ast_expr_get_op_arg(expr, 0);
1585 res = isl_ast_expr_access(res, list);
1586 isl_ast_expr_free(expr);
1588 return res;
1591 /* Linearize the index expression "expr" based on the array bounds
1592 * of "array".
1594 * That is, transform expression
1596 * A[i_0][i_1]...[i_n]
1598 * to
1600 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1602 * where b_0, b_1, ..., b_n are the bounds on the array.
1604 * If the base of "expr" is a member access, then the linearization needs
1605 * to be applied to the structure argument of this member access.
1607 * In the base case, if "expr" has no arguments (other than the name of
1608 * the array), then we are passing an entire array to a function.
1609 * In this case, there is nothing to linearize.
1610 * Note that at this point an expression with no arguments can
1611 * only be an entire array because the scalar case and
1612 * the case of single struct are handled by the caller.
1614 * If the number of specified index expressions in "expr"
1615 * is smaller than the dimension of the accessed array,
1616 * then the missing i_j also do not appear in the linearized expression.
1617 * Furthermore, since such an expression does not refer to a single
1618 * element while the default linearized expression would refer to
1619 * a single element, we return the expression
1621 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
1623 * instead. Note that because of the special case handling above,
1624 * we can assume here that here that there is at least one index expression.
1626 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1627 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1629 int i, n;
1630 isl_ctx *ctx;
1631 isl_set *context;
1632 isl_ast_expr *arg0;
1633 isl_ast_expr *res;
1634 isl_ast_expr_list *list;
1635 isl_ast_build *build;
1637 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1638 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1639 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1640 isl_ast_expr *arg;
1642 arg = isl_ast_expr_get_op_arg(arg0, 0);
1643 arg = gpu_local_array_info_linearize_index(array, arg);
1644 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1645 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1647 return expr;
1649 isl_ast_expr_free(arg0);
1651 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1652 return expr;
1654 ctx = isl_ast_expr_get_ctx(expr);
1655 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
1656 build = isl_ast_build_from_context(context);
1658 n = isl_ast_expr_get_op_n_arg(expr);
1659 res = isl_ast_expr_get_op_arg(expr, 1);
1660 for (i = 1; i < array->n_index; ++i) {
1661 isl_pw_aff *bound_i;
1662 isl_ast_expr *expr_i;
1664 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
1665 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
1666 res = isl_ast_expr_mul(res, expr_i);
1668 if (i + 1 >= n)
1669 continue;
1670 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1671 res = isl_ast_expr_add(res, expr_i);
1674 isl_ast_build_free(build);
1676 if (1 + array->n_index > n) {
1677 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1678 } else {
1679 list = isl_ast_expr_list_from_ast_expr(res);
1680 res = isl_ast_expr_get_op_arg(expr, 0);
1681 res = isl_ast_expr_access(res, list);
1684 isl_ast_expr_free(expr);
1686 return res;
1689 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
1691 * If the AST expression refers to an array that is not accessed
1692 * at all, then this means the value of the expression is not used,
1693 * so we might as well print zero (NULL pointer) instead.
1695 * If the AST expression refers to a global scalar that is not
1696 * a read-only scalar, then its address was passed to the kernel and
1697 * we need to dereference it.
1699 * If the AST expression refers to an access to a global array,
1700 * then we linearize the access exploiting the bounds in data->local_array.
1702 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1703 __isl_keep isl_id *id, void *user)
1705 struct ppcg_transform_data *data = user;
1707 if (!data->array)
1708 return expr;
1709 if (!data->array->accessed) {
1710 isl_ctx *ctx;
1712 ctx = isl_ast_expr_get_ctx(expr);
1713 isl_ast_expr_free(expr);
1714 return isl_ast_expr_from_val(isl_val_zero(ctx));
1716 if (gpu_array_is_read_only_scalar(data->array))
1717 return expr;
1718 if (!data->global)
1719 return expr;
1720 if (data->array->n_index == 0)
1721 return dereference(expr);
1722 if (!data->array->linearize)
1723 return expr;
1725 return gpu_local_array_info_linearize_index(data->local_array, expr);
1728 /* This function is called for each instance of a user statement
1729 * in the kernel "kernel", identified by "gpu_stmt".
1731 * We attach a struct ppcg_kernel_stmt to the "node", containing
1732 * a computed AST expression for each access.
1733 * These AST expressions are computed from iterator_map,
1734 * which expresses the domain
1735 * elements in terms of the generated loops, and sched2shared,
1736 * which expresses the outer shared_schedule_dim dimensions of
1737 * the kernel schedule computed by PPCG in terms of the generated loops.
1739 static __isl_give isl_ast_node *create_domain_leaf(
1740 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1741 __isl_keep isl_ast_build *build, struct gpu_stmt *gpu_stmt)
1743 struct ppcg_transform_data data;
1744 struct ppcg_kernel_stmt *stmt;
1745 isl_id *id;
1746 isl_pw_multi_aff *sched2shared;
1747 isl_map *map;
1748 isl_pw_multi_aff *iterator_map;
1749 isl_union_map *schedule;
1751 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1752 if (!stmt)
1753 return isl_ast_node_free(node);
1755 schedule = isl_ast_build_get_schedule(build);
1756 map = isl_map_reverse(isl_map_from_union_map(schedule));
1757 iterator_map = isl_pw_multi_aff_from_map(map);
1758 sched2shared = compute_sched_to_shared(kernel,
1759 isl_pw_multi_aff_copy(iterator_map));
1761 stmt->type = ppcg_kernel_domain;
1762 stmt->u.d.stmt = gpu_stmt;
1764 data.kernel = kernel;
1765 data.accesses = stmt->u.d.stmt->accesses;
1766 data.iterator_map = iterator_map;
1767 data.sched2shared = sched2shared;
1768 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
1769 build, &transform_index, &data,
1770 &transform_expr, &data);
1772 isl_pw_multi_aff_free(iterator_map);
1773 isl_pw_multi_aff_free(sched2shared);
1775 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1776 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1777 return isl_ast_node_set_annotation(node, id);
1780 /* This function is called for each statement node in the AST
1781 * for copying to or from shared/private memory.
1782 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1783 * statement to the node.
1784 * The statement name is "read" or "write", depending on whether we are
1785 * reading from global memory or writing to global memory.
1787 * The schedule is of the form
1789 * type[D -> A] -> L
1791 * where D corresponds to the outer group->depth dimensions of
1792 * the kernel schedule, A to the global array and L to the outer
1793 * generated AST schedule.
1794 * We compute the inverse and strip off the type, resulting in
1796 * L -> [D -> A]
1798 * We combine this mapping with on the one hand the projection
1800 * [D -> A] -> A
1802 * and on the other hand the group tiling
1804 * [D -> A] -> T
1806 * resulting in
1808 * L -> A and L -> T
1810 * and store the corresponding expressions in stmt->index and stmt->local_index,
1811 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1813 static __isl_give isl_ast_node *create_access_leaf(struct ppcg_kernel *kernel,
1814 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1815 __isl_keep isl_ast_build *build)
1817 struct ppcg_kernel_stmt *stmt;
1818 struct gpu_array_tile *tile;
1819 isl_id *id;
1820 isl_ast_expr *expr;
1821 isl_space *space;
1822 isl_map *access;
1823 isl_pw_multi_aff *pma, *pma2;
1824 const char *type;
1826 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1827 if (!stmt)
1828 return isl_ast_node_free(node);
1830 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1831 type = isl_map_get_tuple_name(access, isl_dim_in);
1832 stmt->u.c.read = !strcmp(type, "read");
1833 access = isl_map_reverse(access);
1834 pma = isl_pw_multi_aff_from_map(access);
1835 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1837 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1838 space = isl_space_unwrap(space);
1839 pma2 = isl_pw_multi_aff_range_map(space);
1840 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1841 isl_pw_multi_aff_copy(pma));
1842 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1843 stmt->u.c.index = expr;
1845 tile = gpu_array_ref_group_tile(group);
1846 pma2 = isl_pw_multi_aff_from_multi_aff(
1847 isl_multi_aff_copy(tile->tiling));
1848 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1849 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1850 stmt->u.c.local_index = expr;
1852 stmt->u.c.array = group->array;
1853 stmt->u.c.local_array = group->local_array;
1854 stmt->type = ppcg_kernel_copy;
1856 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1857 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1858 return isl_ast_node_set_annotation(node, id);
1861 /* Create a synchronization ppcg_kernel_stmt and
1862 * attach it to the node "node" representing the synchronization.
1864 static __isl_give isl_ast_node *create_sync_leaf(
1865 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1866 __isl_keep isl_ast_build *build)
1868 struct ppcg_kernel_stmt *stmt;
1869 isl_id *id;
1871 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1872 if (!stmt)
1873 return isl_ast_node_free(node);
1875 stmt->type = ppcg_kernel_sync;
1876 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1877 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1878 return isl_ast_node_set_annotation(node, id);
1881 /* Internal data structure for at_domain.
1883 * "prog" represents the entire scop.
1884 * "kernel" points to the kernel to which the current schedule node
1885 * belongs. It is set by before_mark and reset by after_mark.
1887 struct ppcg_at_domain_data {
1888 struct gpu_prog *prog;
1889 struct ppcg_kernel *kernel;
1892 /* This function is called for each instance of a user statement
1893 * in the kernel. This may be one of the original user statements
1894 * or a statement introduced by PPCG.
1896 * We assume that the original user statements only have a name
1897 * and no user pointer. The statements introduced by PPCG
1898 * on the other hand all have a user pointer.
1900 * If the user statement is one of the original user statements
1901 * (one with no user pointer), then we call create_domain_leaf. Otherwise,
1902 * we check if it is a copy or synchronization statement and
1903 * call the appropriate functions.
1905 static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
1906 __isl_keep isl_ast_build *build, void *user)
1908 struct ppcg_at_domain_data *data = user;
1909 isl_ast_expr *expr, *arg;
1910 isl_id *id;
1911 int is_sync;
1912 const char *name;
1913 void *p;
1915 expr = isl_ast_node_user_get_expr(node);
1916 arg = isl_ast_expr_get_op_arg(expr, 0);
1917 id = isl_ast_expr_get_id(arg);
1918 name = isl_id_get_name(id);
1919 p = isl_id_get_user(id);
1920 isl_ast_expr_free(expr);
1921 isl_ast_expr_free(arg);
1923 if (!p) {
1924 struct gpu_stmt *gpu_stmt;
1926 gpu_stmt = find_stmt(data->prog, id);
1927 isl_id_free(id);
1928 if (!gpu_stmt)
1929 isl_die(data->prog->ctx, isl_error_internal,
1930 "statement not found",
1931 return isl_ast_node_free(node));
1933 return create_domain_leaf(data->kernel, node, build, gpu_stmt);
1936 is_sync = gpu_tree_id_is_sync(id, data->kernel);
1937 isl_id_free(id);
1938 if (is_sync < 0)
1939 return isl_ast_node_free(node);
1940 if (!strcmp(name, "read") || !strcmp(name, "write")) {
1941 struct gpu_array_ref_group *group = p;
1942 return create_access_leaf(data->kernel, group, node, build);
1944 if (!is_sync)
1945 isl_die(data->prog->ctx, isl_error_internal,
1946 "unknown statement type",
1947 return isl_ast_node_free(node));
1948 return create_sync_leaf(data->kernel, node, build);
1951 /* Given a set of wrapped references "ref", return the corresponding
1952 * access relations based on the tagged access relations "tagged".
1954 * The elements of "ref" are of the form
1956 * [D -> R]
1958 * with D an iteration domains and R a reference.
1959 * The elements of "tagged" are of the form
1961 * [D -> R] -> A
1963 * with A an array.
1965 * Extend "tagged" to include the iteration domain in the range, i.e.,
1967 * [D -> R] -> [D -> A]
1969 * apply the result to "ref" and then unwrap the resulting set
1970 * to obtain relations of the form
1972 * D -> A
1974 static __isl_give isl_union_map *wrapped_reference_to_access(
1975 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
1977 isl_union_map *tag2access;
1979 tag2access = isl_union_map_copy(tagged);
1980 tag2access = isl_union_map_universe(tag2access);
1981 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
1982 tag2access = isl_union_map_domain_map(tag2access);
1983 tag2access = isl_union_map_range_product(tag2access, tagged);
1985 ref = isl_union_set_coalesce(ref);
1986 ref = isl_union_set_apply(ref, tag2access);
1988 return isl_union_set_unwrap(ref);
1991 /* Given an access relation "access" from one or more array reference groups,
1992 * remove those reads if ("read" is 1) or writes (if "read" is 0)
1993 * that are only needed to communicate data within
1994 * the same iteration of "sched".
1995 * "tagged" contains all tagged access relations to all
1996 * the array reference groups accessed by "access" from statement
1997 * instances scheduled by "sched".
1999 * If the access is a read then it is either an element of
2001 * live_in union (range flow)
2003 * where live_in and flow may be overapproximations, or
2004 * it reads an uninitialized value (that is not live-in because
2005 * there is an intermediate kill) or it reads a value that was
2006 * written within the same (compound) statement instance.
2007 * If the access is a write then it is either an element of
2009 * live_out union (domain flow)
2011 * or it writes a value that is never read (and is not live-out
2012 * because of an intermediate kill) or only
2013 * within the same (compound) statement instance.
2014 * In both cases, the access relation is also a subset of
2015 * the group access relation.
2017 * The cases where an uninitialized value is read or a value is written
2018 * that is never read or where the dataflow occurs within a statement
2019 * instance are also considered local and may also be removed.
2021 * Essentially, we compute the intersection of "access" with either
2023 * live_in union (range non-local-flow)
2025 * or
2027 * live_out union (domain non-local-flow)
2029 * We first construct a relation "local"
2031 * [[D -> R] -> [D' -> R']]
2033 * of pairs of domain iterations accessing the reference group
2034 * and references in the group that are coscheduled by "sched".
2036 * If this relation does not intersect the dataflow dependences,
2037 * then there is nothing we can possibly remove, unless the dataflow
2038 * dependences themselves only relate a subset of the accesses.
2039 * In particular, the accesses may not be involved in any dataflow
2040 * dependences, either because they are uninitialized reads/dead writes
2041 * or because the dataflow occurs inside a statement instance.
2043 * Since the computation below may break up the access relation
2044 * into smaller pieces, we only perform the intersection with
2045 * the non-local dependent accesses if the local pairs
2046 * intersect the dataflow dependences. Otherwise, we intersect
2047 * with the universe of the non-local dependent accesses.
2048 * This should at least remove accesses from statements that
2049 * do not participate in any dependences.
2051 * In particular, we remove the "local" dataflow dependences from
2052 * the set of all dataflow dependences.
2053 * Note that if the potential dataflow dependences are an overapproximation
2054 * of the actual dataflow dependences, then the result remains an
2055 * overapproximation of the non-local dataflow dependences.
2056 * Copying to/from global memory is only needed for the references
2057 * in the domain/range of the result or for accesses that are live out/in
2058 * for the entire scop.
2060 * We therefore map the domain/range of the "external" relation
2061 * to the corresponding access relation and take the union with
2062 * the live out/in relation.
2064 static __isl_give isl_union_map *remove_local_accesses(
2065 struct gpu_prog *prog, __isl_take isl_union_map *tagged,
2066 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2067 int read)
2069 int empty;
2070 isl_union_pw_multi_aff *tagger;
2071 isl_union_set *domain;
2072 isl_union_map *local, *external;
2073 isl_union_set *tag_set;
2075 if (isl_union_map_is_empty(access)) {
2076 isl_union_map_free(sched);
2077 isl_union_map_free(tagged);
2078 return access;
2081 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2082 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2083 tagger = isl_union_pw_multi_aff_intersect_domain(tagger, domain);
2084 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2086 local = isl_union_map_apply_range(sched,
2087 isl_union_map_reverse(isl_union_map_copy(sched)));
2088 local = isl_union_map_intersect(local,
2089 isl_union_map_copy(prog->scop->tagged_dep_flow));
2091 empty = isl_union_map_is_empty(local);
2093 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2094 external = isl_union_map_intersect_params(external,
2095 isl_set_copy(prog->scop->context));
2096 external = isl_union_map_subtract(external, local);
2098 if (read) {
2099 tag_set = isl_union_map_range(external);
2100 external = wrapped_reference_to_access(tag_set, tagged);
2101 external = isl_union_map_union(external,
2102 isl_union_map_copy(prog->scop->live_in));
2103 } else {
2104 tag_set = isl_union_map_domain(external);
2105 external = wrapped_reference_to_access(tag_set, tagged);
2106 external = isl_union_map_union(external,
2107 isl_union_map_copy(prog->scop->live_out));
2110 if (empty < 0)
2111 external = isl_union_map_free(external);
2112 else if (empty)
2113 external = isl_union_map_universe(external);
2115 access = isl_union_map_intersect(access, external);
2117 return access;
2120 /* Given an access relation "access" from "group", remove those reads
2121 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2122 * communicate data within the same iteration of the schedule at the
2123 * position where the copying of the group is inserted.
2124 * "node" points to this position, i.e., the depth at "node"
2125 * is equal to group->depth.
2127 * We extract a schedule that picks out the iterations of the outer
2128 * group->depth dimensions and call remove_local_accesses.
2130 static __isl_give isl_union_map *remove_local_accesses_group(
2131 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2132 __isl_take isl_union_map *access, __isl_keep isl_schedule_node *node,
2133 int read)
2135 isl_union_map *sched, *tagged;
2137 if (isl_union_map_is_empty(access))
2138 return access;
2140 tagged = group_tagged_access_relation(group);
2141 sched = isl_schedule_node_get_prefix_schedule_relation(node);
2143 return remove_local_accesses(kernel->prog, tagged, access, sched, read);
2146 /* This function is called before the AST generator starts traversing
2147 * the schedule subtree of a node with mark "mark".
2149 * If the mark is called "kernel", store the kernel pointer in data->kernel
2150 * for use in at_domain.
2152 static int before_mark(__isl_keep isl_id *mark,
2153 __isl_keep isl_ast_build *build, void *user)
2155 struct ppcg_at_domain_data *data = user;
2157 if (!mark)
2158 return -1;
2159 if (!strcmp(isl_id_get_name(mark), "kernel"))
2160 data->kernel = isl_id_get_user(mark);
2161 return 0;
2164 /* This function is called after the AST generator has finished traversing
2165 * the schedule subtree of a mark node. "node" points to the corresponding
2166 * mark AST node.
2168 * If the mark is called "kernel", then replace "node" by a user node
2169 * that "calls" the kernel, representing the launch of the kernel.
2170 * The original "node" is stored inside the kernel object so that
2171 * it can be used to print the device code.
2172 * Note that this assumes that a kernel is only launched once.
2173 * Also clear data->kernel.
2175 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2176 __isl_keep isl_ast_build *build, void *user)
2178 isl_ctx *ctx;
2179 isl_id *id;
2180 isl_ast_expr *expr;
2181 isl_ast_expr_list *list;
2182 struct ppcg_kernel *kernel;
2183 struct ppcg_at_domain_data *data = user;
2185 ctx = isl_ast_node_get_ctx(node);
2186 id = isl_ast_node_mark_get_id(node);
2187 if (!id)
2188 return isl_ast_node_free(node);
2189 if (strcmp(isl_id_get_name(id), "kernel") || !data->kernel) {
2190 isl_id_free(id);
2191 return node;
2193 kernel = data->kernel;
2194 data->kernel = NULL;
2195 kernel->space = isl_ast_build_get_schedule_space(build);
2196 kernel->tree = isl_ast_node_mark_get_node(node);
2197 isl_ast_node_free(node);
2199 expr = isl_ast_expr_from_id(isl_id_copy(id));
2200 list = isl_ast_expr_list_alloc(ctx, 0);
2201 expr = isl_ast_expr_call(expr, list);
2202 node = isl_ast_node_alloc_user(expr);
2203 node = isl_ast_node_set_annotation(node, id);
2205 return node;
2208 static int update_depth(__isl_keep isl_schedule_node *node, void *user)
2210 int *depth = user;
2211 int node_depth;
2213 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2214 return 1;
2215 node_depth = isl_schedule_node_get_schedule_depth(node);
2216 if (node_depth > *depth)
2217 *depth = node_depth;
2219 return 0;
2222 /* Use isl to generate code for both the host and the device
2223 * from "schedule".
2224 * The device code is marked by "kernel" mark nodes in the schedule tree,
2225 * containing a pointer to a ppcg_kernel object.
2226 * The returned AST only contains the AST for the host code.
2227 * The ASTs for the device code are embedded in ppcg_kernel objects
2228 * attached to the leaf nodes that call "kernel".
2230 static __isl_give isl_ast_node *generate_code(struct gpu_gen *gen,
2231 __isl_take isl_schedule *schedule)
2233 struct ppcg_at_domain_data data;
2234 isl_ast_build *build;
2235 isl_ast_node *tree;
2236 isl_id_list *iterators;
2237 int depth;
2239 data.prog = gen->prog;
2240 data.kernel = NULL;
2242 depth = 0;
2243 if (isl_schedule_foreach_schedule_node(schedule, &update_depth,
2244 &depth) < 0)
2245 return NULL;
2246 build = isl_ast_build_alloc(gen->prog->ctx);
2247 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2248 build = isl_ast_build_set_iterators(build, iterators);
2249 build = isl_ast_build_set_at_each_domain(build, &at_domain, &data);
2250 build = isl_ast_build_set_before_each_mark(build, &before_mark, &data);
2251 build = isl_ast_build_set_after_each_mark(build, &after_mark, &data);
2252 if (gen->prog->scop->options->debug->dump_final_schedule)
2253 isl_schedule_dump(schedule);
2254 tree = isl_ast_build_node_from_schedule(build, schedule);
2255 isl_ast_build_free(build);
2257 return tree;
2260 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2262 if (!str)
2263 return NULL;
2264 return isl_union_map_read_from_str(ctx, str);
2267 /* Can "node" be tiled and then mapped to block and thread identifiers?
2268 * That is, is it permutable with at least one coincident dimension?
2270 static int is_permutable(__isl_keep isl_schedule_node *node)
2272 if (!node)
2273 return -1;
2275 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
2276 return 0;
2277 if (!isl_schedule_node_band_get_permutable(node))
2278 return 0;
2279 if (isl_schedule_node_band_n_member(node) < 1)
2280 return 0;
2281 if (!isl_schedule_node_band_member_get_coincident(node, 0))
2282 return 0;
2284 return 1;
2287 /* A isl_schedule_foreach_schedule_node callback
2288 * for setting *any_permutable and aborting the search
2289 * if "node" is a permutable band with coincident dimensions.
2290 * Otherwise, continue searching.
2292 static int set_permutable(__isl_keep isl_schedule_node *node, void *user)
2294 int *any_permutable = user;
2295 int permutable;
2297 permutable = is_permutable(node);
2298 if (permutable < 0)
2299 return -1;
2300 if (!permutable)
2301 return 1;
2303 *any_permutable = 1;
2305 return -1;
2308 /* Does "schedule" contain any permutable band with at least one coincident
2309 * member?
2311 static int has_any_permutable_node(__isl_keep isl_schedule *schedule)
2313 int any_permutable = 0;
2315 if (isl_schedule_foreach_schedule_node(schedule, &set_permutable,
2316 &any_permutable) < 0 &&
2317 !any_permutable)
2318 return -1;
2320 return any_permutable;
2323 /* Is "node" a leaf or can it be tiled and then mapped to
2324 * block and thread identifiers?
2326 static int is_leaf_or_tilable(__isl_keep isl_schedule_node *node)
2328 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
2329 return 1;
2330 return is_permutable(node);
2333 /* Is "node" the outermost node in its branch that can be tiled
2334 * and then mapped to block and thread identifiers?
2335 * If there are no such nodes in the branch and if "node" is a leaf,
2336 * then it is accepted too.
2338 static int is_outer_tilable(__isl_keep isl_schedule_node *node)
2340 int tilable;
2341 isl_schedule_node *ancestor;
2343 tilable = is_leaf_or_tilable(node);
2344 if (tilable < 0)
2345 return -1;
2346 if (!tilable)
2347 return 0;
2349 tilable = 0;
2350 ancestor = isl_schedule_node_copy(node);
2351 while (isl_schedule_node_has_parent(ancestor)) {
2352 ancestor = isl_schedule_node_parent(ancestor);
2354 tilable = is_permutable(ancestor);
2355 if (tilable < 0 || tilable)
2356 break;
2359 isl_schedule_node_free(ancestor);
2360 return tilable < 0 ? -1 : !tilable;
2363 /* Collect the references to all writes in "group".
2364 * Each reference is represented by a universe set in a space
2366 * [S[i,j] -> R[]]
2368 * with S[i,j] the statement instance space and R[] the array reference.
2370 static __isl_give isl_union_set *group_tagged_writes(
2371 struct gpu_array_ref_group *group)
2373 int i;
2374 isl_space *space;
2375 isl_union_set *writes;
2377 space = isl_map_get_space(group->access);
2378 writes = isl_union_set_empty(space);
2379 for (i = 0; i < group->n_ref; ++i) {
2380 isl_space *space;
2381 isl_set *writes_i;
2383 if (!group->refs[i]->write)
2384 continue;
2386 space = isl_map_get_space(group->refs[i]->tagged_access);
2387 space = isl_space_domain(space);
2388 writes_i = isl_set_universe(space);
2389 writes = isl_union_set_add_set(writes, writes_i);
2392 return writes;
2395 /* Is there any write access in "group" that requires synchronization
2396 * on a write to global memory?
2397 * We currently take into account all writes that would require
2398 * synchronization at the thread level depth, but if the copying
2399 * for this group is performed at an outer level, then we do not
2400 * actually need to take into account dependences at intermediate levels.
2402 static int any_sync_writes_in_group(struct ppcg_kernel *kernel,
2403 struct gpu_array_ref_group *group)
2405 isl_union_set *writes;
2406 int empty, disjoint;
2408 empty = isl_union_set_is_empty(kernel->sync_writes);
2409 if (empty < 0)
2410 return -1;
2411 if (empty)
2412 return 0;
2414 writes = group_tagged_writes(group);
2415 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2416 isl_union_set_free(writes);
2418 return disjoint < 0 ? -1 : !disjoint;
2421 /* Collect the references to all writes in "kernel" that write directly
2422 * to global or shared memory, i.e., that are not mapped to private memory.
2423 * Each reference is represented by a universe set in a space
2425 * [S[i,j] -> R[]]
2427 * with S[i,j] the statement instance space and R[] the array reference.
2429 static __isl_give isl_union_set *collect_non_private_tagged_writes(
2430 struct ppcg_kernel *kernel)
2432 isl_union_set *writes;
2433 int i, j;
2435 writes = isl_union_set_empty(isl_union_set_get_space(kernel->arrays));
2437 for (i = 0; i < kernel->n_array; ++i) {
2438 struct gpu_local_array_info *array = &kernel->array[i];
2440 for (j = 0; j < array->n_group; ++j) {
2441 struct gpu_array_ref_group *group = array->groups[j];
2442 isl_union_set *writes_ij;
2444 if (!group->write)
2445 continue;
2446 if (group->private_tile)
2447 continue;
2448 writes_ij = group_tagged_writes(group);
2449 writes = isl_union_set_union(writes, writes_ij);
2453 return writes;
2456 /* Are there any direct writes to global memory that require
2457 * synchronization?
2459 static int any_global_or_shared_sync_writes(struct ppcg_kernel *kernel)
2461 isl_union_set *writes;
2462 int empty, disjoint;
2464 empty = isl_union_set_is_empty(kernel->sync_writes);
2465 if (empty < 0)
2466 return -1;
2467 if (empty)
2468 return 0;
2470 writes = collect_non_private_tagged_writes(kernel);
2471 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2472 isl_union_set_free(writes);
2474 return disjoint < 0 ? -1 : !disjoint;
2477 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
2478 * from the elements in "tile_size".
2480 static __isl_give isl_multi_val *construct_band_tiles_sizes(
2481 __isl_keep isl_schedule_node *node, int *tile_size)
2483 int i, n;
2484 isl_ctx *ctx;
2485 isl_space *space;
2486 isl_multi_val *mv;
2488 if (!node)
2489 return NULL;
2491 ctx = isl_schedule_node_get_ctx(node);
2492 space = isl_schedule_node_band_get_space(node);
2493 n = isl_schedule_node_band_n_member(node);
2494 mv = isl_multi_val_zero(space);
2495 for (i = 0; i < n; ++i) {
2496 isl_val *v;
2498 v = isl_val_int_from_si(ctx, tile_size[i]);
2499 mv = isl_multi_val_set_val(mv, i, v);
2502 return mv;
2505 /* Replace the partial schedule S of the band node "node" by
2507 * floor(S/f)
2509 * or
2511 * f * floor(S/f)
2513 * if scale_tile_loops is set, with f the integers in "factor".
2514 * The list that "factor" points to is assumed to contain at least
2515 * as many elements as the number of members in the band.
2517 static __isl_give isl_schedule_node *snap_band_to_sizes(
2518 __isl_take isl_schedule_node *node, int *factor,
2519 struct ppcg_options *options)
2521 isl_multi_val *mv;
2523 mv = construct_band_tiles_sizes(node, factor);
2524 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2525 if (options->scale_tile_loops)
2526 node = isl_schedule_node_band_scale(node,
2527 isl_multi_val_copy(mv));
2528 isl_multi_val_free(mv);
2530 return node;
2533 /* Tile "band" with tile size specified by "sizes".
2535 * Since the tile loops will be mapped to block ids, we forcibly
2536 * turn off tile loop scaling. We may want to enable tile loop scaling
2537 * at some later point, but then we would have to support the detection
2538 * of strides during the mapping to block ids.
2539 * Similarly, since the point loops will be mapped to thread ids,
2540 * we forcibly shift the point loops so that they start at zero.
2542 static __isl_give isl_schedule_node *tile_band(
2543 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2545 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2546 int scale_tile;
2547 int shift_point;
2549 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2550 isl_options_set_tile_scale_tile_loops(ctx, 0);
2551 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2552 isl_options_set_tile_shift_point_loops(ctx, 1);
2554 node = isl_schedule_node_band_tile(node, sizes);
2556 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2557 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2559 return node;
2562 /* Extract the set of parameter values and outer schedule dimensions
2563 * for which any statement instance
2564 * in the kernel inserted at "node" needs to be executed.
2565 * Intersect the set of parameter values derived from the host schedule
2566 * relation with the context of "prog".
2568 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2569 struct gpu_prog *prog)
2571 isl_union_map *schedule;
2572 isl_union_set *schedule_domain;
2573 isl_set *context;
2574 int empty;
2576 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2577 schedule_domain = isl_union_map_range(schedule);
2578 empty = isl_union_set_is_empty(schedule_domain);
2579 if (empty < 0) {
2580 isl_union_set_free(schedule_domain);
2581 return NULL;
2583 if (empty) {
2584 int depth;
2585 isl_space *space;
2587 space = isl_union_set_get_space(schedule_domain);
2588 isl_union_set_free(schedule_domain);
2589 space = isl_space_set_from_params(space);
2590 depth = isl_schedule_node_get_schedule_depth(node);
2591 space = isl_space_add_dims(space, isl_dim_set, depth);
2592 context = isl_set_empty(space);
2593 } else {
2594 context = isl_set_from_union_set(schedule_domain);
2596 context = isl_set_intersect_params(context,
2597 isl_set_copy(prog->context));
2599 return context;
2602 /* Return the set of outer array elements accessed by
2603 * by the statement instance in "domain" in "prog".
2605 static __isl_give isl_union_set *accessed_by_domain(
2606 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2608 isl_union_map *access;
2609 isl_union_set *arrays;
2611 access = isl_union_map_union(isl_union_map_copy(prog->read),
2612 isl_union_map_copy(prog->may_write));
2613 access = isl_union_map_intersect_domain(access, domain);
2614 arrays = isl_union_map_range(access);
2615 arrays = isl_union_set_apply(arrays,
2616 isl_union_map_copy(prog->to_outer));
2618 return arrays;
2621 /* Return the number of outer band members of the band node "node"
2622 * that are marked coincident.
2624 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2626 int i, n;
2628 n = isl_schedule_node_band_n_member(node);
2630 for (i = 0; i < n; ++i)
2631 if (!isl_schedule_node_band_member_get_coincident(node, i))
2632 break;
2634 return i;
2637 /* If the band node "node" has more than "n" members, then split off
2638 * the first "n" of them.
2640 static __isl_give isl_schedule_node *split_band(
2641 __isl_take isl_schedule_node *node, int n)
2643 int dim;
2645 dim = isl_schedule_node_band_n_member(node);
2646 if (n < dim)
2647 node = isl_schedule_node_band_split(node, n);
2649 return node;
2652 /* Scale a band node that may have been split by split_band.
2653 * "sizes" are the scaling factors for the original node.
2654 * "node" either points to the original band node, or the outer
2655 * of the two pieces after splitting.
2657 * If the number of elements in "node" is smaller than the number of
2658 * elements in "sizes", then some splitting has occurred and we split
2659 * "sizes" in the same way.
2661 static __isl_give isl_schedule_node *scale_band(
2662 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2664 int n, dim;
2666 n = isl_multi_val_dim(sizes, isl_dim_set);
2667 dim = isl_schedule_node_band_n_member(node);
2668 if (n > dim) {
2669 isl_multi_val *sizes2;
2671 sizes2 = isl_multi_val_copy(sizes);
2672 sizes = isl_multi_val_drop_dims(sizes,
2673 isl_dim_set, dim, n - dim);
2674 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2675 node = isl_schedule_node_child(node, 0);
2676 node = isl_schedule_node_band_scale(node, sizes2);
2677 node = isl_schedule_node_parent(node);
2680 return isl_schedule_node_band_scale(node, sizes);
2683 /* Return an isl_multi_aff, with as elements the parameters in "space"
2684 * that have the names specified by the elements in "names".
2685 * If (some of) these parameters do not already appear in "space",
2686 * then they are added first.
2688 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2689 __isl_keep isl_id_list *names)
2691 int i, n;
2692 isl_local_space *ls;
2693 isl_multi_aff *ma;
2695 if (!names)
2696 space = isl_space_free(space);
2698 n = isl_id_list_n_id(names);
2699 for (i = 0; i < n; ++i) {
2700 int pos;
2701 isl_id *id;
2703 id = isl_id_list_get_id(names, i);
2704 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2705 if (pos >= 0) {
2706 isl_id_free(id);
2707 continue;
2709 pos = isl_space_dim(space, isl_dim_param);
2710 space = isl_space_add_dims(space, isl_dim_param, 1);
2711 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2713 ma = isl_multi_aff_zero(isl_space_copy(space));
2714 ls = isl_local_space_from_space(isl_space_domain(space));
2715 for (i = 0; i < n; ++i) {
2716 int pos;
2717 isl_id *id;
2718 isl_aff *aff;
2720 id = isl_id_list_get_id(names, i);
2721 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2722 isl_id_free(id);
2723 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2724 isl_dim_param, pos);
2725 ma = isl_multi_aff_set_aff(ma, i, aff);
2727 isl_local_space_free(ls);
2729 return ma;
2732 /* Return constraints on the domain elements that equate a sequence of
2733 * parameters called "names", to the partial schedule
2734 * of "node" modulo the integers in "size".
2735 * The number of elements in the array "size" should be equal
2736 * to the number of elements in "names".
2737 * The number of members of the band node "node" should be smaller
2738 * than or equal to this number. If it is smaller, then the first
2739 * elements of "names" are equated to zero.
2741 static __isl_give isl_union_set *set_schedule_modulo(
2742 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
2743 int *size)
2745 int n, n_zero;
2746 isl_space *space;
2747 isl_multi_aff *ma;
2748 isl_multi_union_pw_aff *mupa, *mupa2;
2749 isl_multi_val *mv;
2750 isl_union_set *domain;
2752 if (!node)
2753 return NULL;
2754 n = isl_id_list_n_id(names);
2755 if (n == 0)
2756 return isl_schedule_node_get_universe_domain(node);
2757 n_zero = n - isl_schedule_node_band_n_member(node);
2759 mupa = isl_schedule_node_band_get_partial_schedule(node);
2760 mv = construct_band_tiles_sizes(node, size + n_zero);
2761 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
2763 space = isl_multi_union_pw_aff_get_space(mupa);
2764 space = isl_space_params(space);
2765 space = isl_space_set_from_params(space);
2766 space = isl_space_add_dims(space, isl_dim_set, n_zero);
2767 ma = isl_multi_aff_zero(space);
2769 domain = isl_schedule_node_get_universe_domain(node);
2770 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
2771 isl_union_set_copy(domain), ma);
2772 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
2774 space = isl_multi_union_pw_aff_get_space(mupa);
2775 ma = parameter_vector(space, names);
2777 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
2778 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
2780 return isl_multi_union_pw_aff_zero_union_set(mupa);
2783 /* Insert a context node at "node" introducing the block and thread
2784 * identifiers along with their bounds, which are stored in kernel->grid_size
2785 * and kernel->block_dim.
2786 * Note that the bounds on the block identifiers may implicitly impose
2787 * constraints on the parameters. A guard needs to be inserted
2788 * in the schedule tree to ensure that those bounds hold at "node".
2789 * This guard is inserted in insert_guard.
2791 static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
2792 __isl_take isl_schedule_node *node)
2794 isl_set *context;
2796 context = isl_set_universe(isl_set_get_space(kernel->context));
2798 context = add_bounded_parameters_dynamic(context,
2799 kernel->grid_size, kernel->block_ids);
2800 context = add_bounded_parameters(context,
2801 kernel->block_dim, kernel->thread_ids);
2803 node = isl_schedule_node_insert_context(node, context);
2805 return node;
2808 /* Insert a guard that eliminates kernel launches where the kernel
2809 * obviously does not have any work to do.
2811 * In particular, eliminate kernel launches where there are obviously
2812 * zero blocks.
2813 * Use the same block size constraints that are used to create the context
2814 * to ensure that all constraints implicit in the constructed context
2815 * are imposed by the guard.
2817 * Additionally, add other constraints that are valid
2818 * for each executed instance ("context"), as long as this does not result
2819 * in a disjunction.
2821 static __isl_give isl_schedule_node *insert_guard(
2822 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
2823 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
2825 unsigned nparam, n;
2826 isl_set *guard;
2827 isl_id_list *ids;
2829 guard = isl_set_copy(context);
2830 guard = isl_set_compute_divs(guard);
2831 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
2833 nparam = isl_set_dim(guard, isl_dim_param);
2834 n = isl_multi_pw_aff_dim(size, isl_dim_out);
2835 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
2836 guard = add_bounded_parameters_dynamic(guard, size, ids);
2837 isl_id_list_free(ids);
2838 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
2840 node = isl_schedule_node_insert_guard(node, guard);
2842 return node;
2845 /* Does any array reference group mapping require the band that is mapped
2846 * to threads to be unrolled?
2848 static int kernel_requires_unroll(struct ppcg_kernel *kernel)
2850 int i, j;
2852 for (i = 0; i < kernel->n_array; ++i) {
2853 struct gpu_local_array_info *array = &kernel->array[i];
2855 for (j = 0; j < array->n_group; ++j) {
2856 struct gpu_array_ref_group *group = array->groups[j];
2857 if (gpu_array_ref_group_requires_unroll(group))
2858 return 1;
2862 return 0;
2865 /* Mark the given band node "node" for unrolling by the AST generator and
2866 * then sink it to the leaves of the schedule tree.
2867 * All dimensions of "node" are assumed to be coincident, such that this
2868 * sinking is a valid operation.
2870 static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
2872 int i, n;
2874 n = isl_schedule_node_band_n_member(node);
2875 for (i = 0; i < n; ++i)
2876 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
2877 isl_ast_loop_unroll);
2879 node = isl_schedule_node_band_sink(node);
2881 return node;
2884 /* Insert a synchronization node in the schedule tree of "node"
2885 * after the core computation of "kernel" at the level of the band
2886 * that is mapped to threads, except if that level is equal to
2887 * that of the band that is mapped to blocks or if there are no writes
2888 * to global or shared memory in the core computation that require
2889 * synchronization.
2890 * If there are any writes to shared memory and the shared memory
2891 * copying is performed at the same level, then synchronization
2892 * is needed between the core and the copying anyway, so we might
2893 * as well add it here. If the copying is performed at a higher
2894 * level, then different iterations of intermediate schedule dimensions
2895 * may have a different mapping from between shared memory elements and
2896 * threads, such that synchronization is required after the core.
2897 * "node" is assumed to point to the kernel node.
2899 static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
2900 __isl_take isl_schedule_node *node)
2902 int kernel_depth;
2903 int need_sync;
2905 need_sync = any_global_or_shared_sync_writes(kernel);
2906 if (need_sync < 0)
2907 return isl_schedule_node_free(node);
2908 if (!need_sync)
2909 return node;
2911 kernel_depth = isl_schedule_node_get_schedule_depth(node);
2913 node = gpu_tree_move_down_to_thread(node, kernel->core);
2914 if (kernel_depth == isl_schedule_node_get_schedule_depth(node))
2915 return gpu_tree_move_up_to_kernel(node);
2917 node = gpu_tree_ensure_following_sync(node, kernel);
2919 node = gpu_tree_move_up_to_kernel(node);
2921 return node;
2924 /* Return a read ("read" is 1) or write access relation for "group"
2925 * with those accesses removed that are only needed to communicate data
2926 * within the subtree of the schedule rooted at "node".
2927 * Furthermore, include the prefix schedule at "node".
2928 * That is, return a relation of the form
2930 * S -> [D -> A]
2932 * with D the outer schedule dimensions at "node".
2934 static __isl_give isl_union_map *anchored_non_local_accesses(
2935 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2936 __isl_take isl_schedule_node *node, int read)
2938 isl_union_map *access;
2939 isl_union_map *prefix;
2941 access = gpu_array_ref_group_access_relation(group, read, !read);
2942 access = remove_local_accesses_group(kernel, group, access, node, read);
2943 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
2944 access = isl_union_map_range_product(prefix, access);
2946 return access;
2949 /* Given an array reference group "group", create a mapping
2951 * read[D -> A] -> [D -> A]
2953 * if "read" is set or
2955 * write[D -> A] -> [D -> A]
2957 * if "read" is not set.
2958 * D corresponds to the outer group->depth dimensions of
2959 * the kernel schedule.
2961 static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
2962 struct gpu_array_ref_group *group, int read)
2964 isl_space *space;
2965 isl_id *id;
2967 space = isl_space_copy(group->array->space);
2968 space = isl_space_from_range(space);
2969 space = isl_space_add_dims(space, isl_dim_in, group->depth);
2970 space = isl_space_wrap(space);
2971 space = isl_space_map_from_set(space);
2973 id = isl_id_alloc(ctx, read ? "read" : "write", group);
2974 space = isl_space_set_tuple_id(space, isl_dim_in, id);
2976 return isl_multi_aff_identity(space);
2979 /* If any writes in "group" require synchronization, then make sure
2980 * that there is a synchronization node for "kernel" after the node
2981 * following "node" in a sequence.
2983 * If "shared" is set and no synchronization is needed for
2984 * the writes to global memory, then add synchronization before
2985 * the kernel to protect shared memory from being overwritten
2986 * by the next iteration of the core computation.
2987 * No additional synchronization is needed to protect against
2988 * the next copy into shared memory because each element of
2989 * the shared memory tile is always copied by the same thread.
2991 static __isl_give isl_schedule_node *add_group_write_sync(
2992 __isl_take isl_schedule_node *node, struct ppcg_kernel *kernel,
2993 struct gpu_array_ref_group *group, int shared)
2995 int need_sync;
2997 need_sync = any_sync_writes_in_group(kernel, group);
2998 if (need_sync < 0)
2999 return isl_schedule_node_free(node);
3000 if (need_sync) {
3001 node = isl_schedule_node_parent(node);
3002 node = isl_schedule_node_next_sibling(node);
3003 node = isl_schedule_node_child(node, 0);
3004 node = gpu_tree_ensure_following_sync(node, kernel);
3005 } else if (shared) {
3006 node = isl_schedule_node_parent(node);
3007 node = isl_schedule_node_parent(node);
3008 node = gpu_tree_move_down_to_depth(node, group->depth,
3009 kernel->core);
3010 node = gpu_tree_move_left_to_sync(node, kernel);
3013 return node;
3016 /* Add copy statements to the schedule tree of "node"
3017 * for reading from global memory to private memory (if "read" is set) or
3018 * for writing back from private memory to global memory
3019 * (if "read" is not set) for the array reference group "group" that
3020 * is mapped to private memory.
3021 * On input, "node" points to the kernel node, and it is moved
3022 * back there on output.
3024 * The copies are performed in the order of the array elements.
3025 * The copy statement instances include a reference to the outer
3026 * group->depth dimensions of the kernel schedule for ease of
3027 * combining them with the group tiling.
3029 * That is, the extra schedule is of the form
3031 * type[D -> A] -> A
3033 * where D corresponds to the outer group->depth dimensions of
3034 * the kernel schedule and A to the global array.
3035 * This schedule is unrolled because registers are not addressable.
3037 * The copying is inserted in the schedule tree through an extension
3038 * of the form
3040 * D -> type[D -> A]
3042 * where the extra domain elements type[D -> A] are those accessed
3043 * by the group.
3044 * A filter is inserted on type[D -> A] to ensure that the element
3045 * is read/written by the same thread that needs the element.
3046 * This filter is obtained by applying
3048 * S -> type[D -> A]
3050 * to the thread filter for the core statements.
3052 * The extension is inserted before the core computation in case of a read
3053 * and after the core computation in case of a write.
3054 * In the latter case, we also make sure that there is a synchronization
3055 * node after the write to global memory, unless this write is performed
3056 * at the outer level of the kernel.
3057 * In principle, this synchronization could be inserted higher
3058 * in the schedule tree depending on where the corresponding reads
3059 * from global memory are performed.
3061 static __isl_give isl_schedule_node *add_copies_group_private(
3062 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3063 __isl_take isl_schedule_node *node, int read)
3065 isl_union_map *access;
3066 isl_union_map *prefix;
3067 isl_union_set *domain;
3068 isl_space *space;
3069 isl_multi_aff *from_access;
3070 isl_multi_pw_aff *mpa;
3071 isl_multi_union_pw_aff *mupa;
3072 isl_schedule_node *graft;
3073 isl_union_set *filter;
3074 int kernel_depth;
3075 int empty;
3077 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3078 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3080 access = anchored_non_local_accesses(kernel, group, node, read);
3081 empty = isl_union_map_is_empty(access);
3082 if (empty < 0 || empty) {
3083 isl_union_map_free(access);
3084 if (empty < 0)
3085 return isl_schedule_node_free(node);
3086 return gpu_tree_move_up_to_kernel(node);
3089 from_access = create_from_access(kernel->ctx, group, read);
3090 space = isl_space_domain(isl_multi_aff_get_space(from_access));
3091 access = isl_union_map_preimage_range_multi_aff(access, from_access);
3093 filter = isl_union_set_copy(kernel->thread_filter);
3094 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
3095 filter = isl_union_set_detect_equalities(filter);
3096 filter = isl_union_set_coalesce(filter);
3098 domain = isl_union_map_range(access);
3099 access = isl_union_set_wrapped_domain_map(domain);
3100 access = isl_union_map_reverse(access);
3101 access = isl_union_map_coalesce(access);
3102 graft = isl_schedule_node_from_extension(access);
3104 space = isl_space_map_from_set(space);
3105 mpa = isl_multi_pw_aff_identity(space);
3106 mpa = isl_multi_pw_aff_range_factor_range(mpa);
3107 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3109 graft = isl_schedule_node_child(graft, 0);
3110 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3111 graft = unroll(graft);
3113 graft = isl_schedule_node_insert_filter(graft, filter);
3115 graft = isl_schedule_node_parent(graft);
3117 if (read)
3118 node = isl_schedule_node_graft_before(node, graft);
3119 else {
3120 node = isl_schedule_node_graft_after(node, graft);
3121 if (kernel_depth < group->depth)
3122 node = add_group_write_sync(node, kernel, group, 0);
3125 node = gpu_tree_move_up_to_kernel(node);
3127 return node;
3130 /* Add copy statements to the schedule tree of "node"
3131 * for reading from global memory to shared memory (if "read" is set) or
3132 * for writing back from shared memory to global memory
3133 * (if "read" is not set) for the array reference group "group" that
3134 * is mapped to shared memory.
3135 * On input, "node" points to the kernel node, and it is moved
3136 * back there on output.
3138 * The copies are performed in the order of the corresponding shared
3139 * memory tile.
3140 * The copy statement instances include a reference to the outer
3141 * group->depth dimensions of the kernel schedule for ease of
3142 * combining them with the group tiling.
3144 * If we are performing a read from global memory to shared memory and
3145 * if the array involved is not a scalar, then we copy
3146 * the entire tile to shared memory. This may result in some extra
3147 * elements getting copied, but it should lead to simpler code
3148 * (which means that fewer registers may be needed) and less divergence.
3150 * Otherwise, we only copy the elements that will be read or have been written
3151 * in the kernel.
3153 * That is, the extra schedule is of the form
3155 * type[D -> A] -> T
3157 * where D corresponds to the outer group->depth dimensions of
3158 * the kernel schedule, A to the global array and T is the corresponding
3159 * shared memory tile.
3161 * The copying is inserted in the schedule tree through an extension
3162 * of the form
3164 * D -> type[D -> A]
3166 * where the extra domain elements type[D -> A] are those accessed
3167 * by the group. In the case of read from a non-scalar, this set
3168 * is replaced by the entire shared memory tile.
3170 * A filter is inserted on type[D -> A] to map the copy instances
3171 * to the threads. In particular, the thread identifiers are
3172 * equated to the position inside the shared memory tile (T)
3173 * modulo the block size.
3174 * We try to align the innermost tile dimension with the innermost
3175 * thread identifier (x) as a heuristic to improve coalescing.
3176 * In particular, if the dimension of the tile is greater than
3177 * the dimension of the block, then the schedule mapping to the tile
3178 * is broken up into two pieces and the filter is applied to the inner part.
3179 * If, on the other hand, the dimension of the tile is smaller than
3180 * the dimension of the block, then the initial thread identifiers
3181 * are equated to zero and the remaining thread identifiers are
3182 * matched to the memory tile.
3184 * The extension is inserted before the core computation in case of a read
3185 * and after the core computation in case of a write.
3186 * In the case of a read, we first need to make sure there is some
3187 * synchronization before the core computation such that we can put the read
3188 * from global memory to shared memory before that synchronization.
3189 * This ensures that all threads have finished copying into shared memory
3190 * before the shared memory is used.
3191 * We also need to make sure that there is a synchronization node after
3192 * the core computation to ensure that the next load into shared memory
3193 * only happens after all data has been used. There is no need for
3194 * this synchronization if we are at the outer level since then there
3195 * won't be a next load.
3196 * In the case of a write, we need to make sure there is some synchronization
3197 * after the core computation such taht we can put the write from shared
3198 * memory to global memory after that synchronization.
3199 * Unless we are at the outer level, we also need a synchronization node
3200 * after the write to ensure the data is saved to global memory
3201 * before the next iteration write to the same shared memory.
3202 * It also makes sure the data has arrived in global memory before
3203 * it is read in a subsequent iteration.
3205 static __isl_give isl_schedule_node *add_copies_group_shared(
3206 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3207 __isl_take isl_schedule_node *node, int read)
3209 struct gpu_array_tile *tile;
3210 isl_union_map *access;
3211 isl_union_set *domain;
3212 isl_union_set *sync;
3213 isl_multi_aff *ma;
3214 isl_multi_aff *from_access;
3215 isl_multi_pw_aff *mpa;
3216 isl_multi_union_pw_aff *mupa;
3217 isl_schedule_node *graft;
3218 isl_union_set *filter;
3219 int skip;
3220 int kernel_depth;
3221 int empty;
3223 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3224 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3226 access = anchored_non_local_accesses(kernel, group, node, read);
3227 empty = isl_union_map_is_empty(access);
3228 if (empty < 0 || empty) {
3229 isl_union_map_free(access);
3230 if (empty < 0)
3231 return isl_schedule_node_free(node);
3232 return gpu_tree_move_up_to_kernel(node);
3235 from_access = create_from_access(kernel->ctx, group, read);
3237 tile = gpu_array_ref_group_tile(group);
3238 ma = isl_multi_aff_copy(tile->tiling);
3239 ma = isl_multi_aff_pullback_multi_aff(ma,
3240 isl_multi_aff_copy(from_access));
3241 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3242 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3244 domain = isl_union_map_range(access);
3246 if (read && !gpu_array_is_scalar(group->array)) {
3247 isl_map *map;
3248 isl_union_set_free(domain);
3249 map = group_tile(group);
3250 domain = isl_union_set_from_set(isl_map_wrap(map));
3253 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3254 access = isl_union_set_wrapped_domain_map(domain);
3255 access = isl_union_map_reverse(access);
3256 access = isl_union_map_coalesce(access);
3257 graft = isl_schedule_node_from_extension(access);
3259 graft = isl_schedule_node_child(graft, 0);
3261 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3263 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3264 graft = isl_schedule_node_band_split(graft,
3265 tile->n - kernel->n_block);
3266 graft = isl_schedule_node_child(graft, 0);
3268 if (tile->n < kernel->n_block)
3269 skip = kernel->n_block - tile->n;
3270 else
3271 skip = 0;
3272 filter = set_schedule_modulo(graft, kernel->thread_ids,
3273 kernel->block_dim);
3274 if (!kernel->options->wrap)
3275 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3276 kernel->options);
3277 if (tile->n > kernel->n_block && kernel->n_block > 0)
3278 graft = isl_schedule_node_parent(graft);
3279 graft = isl_schedule_node_insert_filter(graft, filter);
3281 while (graft && isl_schedule_node_has_parent(graft))
3282 graft = isl_schedule_node_parent(graft);
3284 if (read) {
3285 if (kernel_depth < group->depth)
3286 node = gpu_tree_ensure_sync_after_core(node, kernel);
3287 node = gpu_tree_move_left_to_sync(node, kernel);
3288 node = isl_schedule_node_graft_before(node, graft);
3289 } else {
3290 node = gpu_tree_move_right_to_sync(node, kernel);
3291 node = isl_schedule_node_graft_after(node, graft);
3292 if (kernel_depth < group->depth)
3293 node = add_group_write_sync(node, kernel, group, 1);
3296 node = gpu_tree_move_up_to_kernel(node);
3298 return node;
3301 /* Check whether the array reference group "group" is mapped to
3302 * private or shared memory and, if so,
3303 * add copy statements to the schedule tree of "node"
3304 * for reading from global memory to private or shared memory
3305 * (if "read" is set) or for writing back from private or shared memory
3306 * to global memory (if "read" is not set) for this group.
3307 * On input, "node" points to the kernel node, and it is moved
3308 * back there on output.
3310 static __isl_give isl_schedule_node *add_copies_group(
3311 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3312 __isl_take isl_schedule_node *node, int read)
3314 if (group->private_tile)
3315 return add_copies_group_private(kernel, group, node, read);
3316 if (group->shared_tile)
3317 return add_copies_group_shared(kernel, group, node, read);
3318 return node;
3321 /* For each array reference group that is mapped to private or shared memory,
3322 * add copy statements to the schedule tree of "node"
3323 * for reading from global memory to private or shared memory
3324 * and for writing back.
3325 * On input, "node" points to the kernel node, and it is moved
3326 * back there on output.
3328 static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3329 __isl_take isl_schedule_node *node)
3331 int i, j;
3333 for (i = 0; i < kernel->n_array; ++i) {
3334 struct gpu_local_array_info *array = &kernel->array[i];
3336 for (j = 0; j < array->n_group; ++j) {
3337 struct gpu_array_ref_group *group = array->groups[j];
3339 node = add_copies_group(kernel, group, node, 1);
3340 if (!node)
3341 return NULL;
3342 node = add_copies_group(kernel, group, node, 0);
3343 if (!node)
3344 return NULL;
3348 return node;
3351 /* Mark all dimensions in the current band node atomic.
3353 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3355 int i, n;
3357 n = isl_schedule_node_band_n_member(node);
3358 for (i = 0; i < n; ++i)
3359 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
3360 isl_ast_loop_atomic);
3362 return node;
3365 /* Mark "node" atomic, if it is a band node.
3366 * Do the same for all ancestors.
3367 * Return a pointer to "node" (in the updated schedule tree).
3369 static __isl_give isl_schedule_node *atomic_ancestors(
3370 __isl_take isl_schedule_node *node)
3372 int pos;
3374 if (!node)
3375 return NULL;
3376 if (!isl_schedule_node_has_parent(node))
3377 return node;
3379 pos = isl_schedule_node_get_child_position(node);
3380 node = isl_schedule_node_parent(node);
3381 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3382 node = atomic(node);
3383 node = atomic_ancestors(node);
3384 node = isl_schedule_node_child(node, pos);
3386 return node;
3389 /* Collect all write references that require synchronization.
3390 * "node" is assumed to point to the kernel node.
3391 * Each reference is represented by a universe set in a space
3393 * [S[i,j] -> R[]]
3395 * with S[i,j] the statement instance space and R[] the array reference.
3397 * This function should be called before block and thread filters are added.
3399 * Synchronization is needed after a write if there is a subsequent read
3400 * within the same block that may not be performed by the same thread.
3401 * There should not be any dependences between different blocks,
3402 * so we start with the flow dependences within the same kernel invocation
3403 * and we subtract from these those dependences that are mapped
3404 * to the same iteration of the bands where synchronization is inserted.
3405 * We do not remove pairs of instances that are known to map to
3406 * the same thread across different iterations of the intermediate
3407 * bands because the read may be performed by a different thread
3408 * than the one that needs the value if shared memory is involved.
3410 * We also consider all pairs of possible writes that access the same
3411 * memory location and that may be mapped to the same block but not
3412 * to the same iteration of the intermediate bands.
3413 * In theory, it would be possible for one thread to still be in
3414 * a previous iteration of a loop in these bands.
3415 * A write to global memory in this delayed thread could then overwrite
3416 * a write from another thread that has already moved on to
3417 * the next iteration.
3419 * After computing the above writes paired off with reads or writes
3420 * that depend on them, we project onto the domain writes.
3421 * Sychronization is needed after writes to global memory
3422 * through these references.
3424 static __isl_give isl_union_set *compute_sync_writes(
3425 struct ppcg_kernel *kernel, __isl_keep isl_schedule_node *node)
3427 isl_union_map *local;
3428 isl_union_map *may_writes, *shared_access;
3429 isl_union_map *kernel_prefix, *thread_prefix;
3430 isl_union_map *equal;
3431 isl_union_set *wrap;
3432 isl_union_set *domain;
3434 domain = isl_schedule_node_get_universe_domain(node);
3435 kernel_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3436 node = isl_schedule_node_copy(node);
3437 node = gpu_tree_move_down_to_thread(node, kernel->core);
3438 thread_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3439 isl_schedule_node_free(node);
3441 may_writes = isl_union_map_copy(kernel->prog->scop->tagged_may_writes);
3442 may_writes = isl_union_map_curry(may_writes);
3443 may_writes = isl_union_map_intersect_domain(may_writes, domain);
3444 may_writes = isl_union_map_uncurry(may_writes);
3445 shared_access = isl_union_map_copy(may_writes);
3446 shared_access = isl_union_map_apply_range(shared_access,
3447 isl_union_map_reverse(may_writes));
3449 local = isl_union_map_copy(kernel->prog->scop->tagged_dep_flow);
3450 local = isl_union_map_union(local, shared_access);
3451 local = isl_union_map_zip(local);
3453 equal = isl_union_map_apply_range(kernel_prefix,
3454 isl_union_map_reverse(isl_union_map_copy(kernel_prefix)));
3455 wrap = isl_union_map_wrap(equal);
3456 local = isl_union_map_intersect_domain(local, wrap);
3457 equal = isl_union_map_apply_range(thread_prefix,
3458 isl_union_map_reverse(isl_union_map_copy(thread_prefix)));
3459 wrap = isl_union_map_wrap(equal);
3460 local = isl_union_map_subtract_domain(local, wrap);
3462 local = isl_union_map_zip(local);
3463 local = isl_union_map_universe(local);
3465 return isl_union_map_domain(local);
3468 /* Group the domain elements into a single space, named kernelX,
3469 * with X the kernel sequence number "kernel_id".
3471 static __isl_give isl_schedule_node *group_statements(
3472 __isl_take isl_schedule_node *node, int kernel_id)
3474 char buffer[20];
3475 isl_id *id;
3477 if (!node)
3478 return NULL;
3480 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3481 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3482 return isl_schedule_node_group(node, id);
3485 /* Create a ppcg_kernel representing the domain instances that reach "node"
3486 * and insert a mark node pointing to the ppcg_kernel before "node".
3487 * The band that "node" points to is the band that needs to be mapped
3488 * to block identifiers. The band that needs to be mapped to thread
3489 * identifiers should be marked by a "thread" mark by the caller.
3490 * This mark is removed by this function.
3491 * If "scale" is set, then the band that "node" points to is scaled
3492 * by "sizes".
3494 * Mark all outer band nodes as atomic to ensure each kernel is only
3495 * scheduled once.
3496 * If the domain elements that reach "node" live in more than one space,
3497 * then group the domain elements into a single space, named kernelX,
3498 * with X the kernel sequence number.
3500 * Insert a guard node governing the kernel node to ensure that
3501 * no kernels with zero blocks are launched.
3503 * Insert a context node describing the block and thread
3504 * identifiers inside the kernel mark.
3505 * The context node needs to be inserted after the effective block size
3506 * has been determined such that the bounds on the thread identifiers
3507 * would reflect the effective block size.
3508 * Insert a filter node inside the context node mapping the statement
3509 * instances to block identifiers. In particular, the block identifiers
3510 * are equated to the partial schedule of band that was marked for mapping
3511 * to blocks modulo the grid size.
3512 * Insert a filter node inside the "thread" mark mapping the statement
3513 * instances to thread identifiers. In particular, the thread identifiers
3514 * are equated to the partial schedule of band that was marked for mapping
3515 * to threads modulo the block size.
3517 * Compute array reference groups for all arrays, set the local
3518 * array bounds based on the set of domain instances that reach
3519 * the kernel node, check the total amount of shared memory used
3520 * and compute all group tilings.
3521 * The array reference groups are computed after the block filter
3522 * has been inserted because it affects the mapping to shared or
3523 * private memory. This computation also requires the thread filter
3524 * (in the ppcg_kernel object), but this thread filter should not
3525 * have been added to the schedule tree yet since the computation
3526 * requires the schedule of the band that needs to be mapped to
3527 * threads before the privatization is applied.
3529 * If any array reference group requires the band mapped to threads
3530 * to be unrolled, then we perform the required unrolling.
3532 * We save a copy of the schedule that may influence the mappings
3533 * to shared or private memory in kernel->shared_schedule.
3535 * Finally, we add synchronization and copy statements to the schedule tree,
3536 * remove the "thread" mark and create representations for the local
3537 * variables in the kernel.
3539 * We keep a copy of the isl_id that points to the kernel to ensure
3540 * that the kernel does not get destroyed if the schedule node
3541 * is freed due to some error condition.
3543 static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
3544 __isl_take isl_schedule_node *node, int scale,
3545 __isl_keep isl_multi_val *sizes)
3547 struct ppcg_kernel *kernel;
3548 isl_id *id;
3549 isl_schedule_node *node_thread;
3550 isl_union_map *host_schedule;
3551 isl_set *host_domain;
3552 isl_union_set *domain;
3553 int single_statement;
3555 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3556 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3557 if (!kernel)
3558 return isl_schedule_node_free(node);
3560 domain = isl_schedule_node_get_domain(node);
3561 single_statement = isl_union_set_n_set(domain) == 1;
3563 kernel->ctx = gen->ctx;
3564 kernel->prog = gen->prog;
3565 kernel->options = gen->options;
3566 kernel->context = extract_context(node, gen->prog);
3567 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3568 kernel->arrays = accessed_by_domain(isl_union_set_copy(domain),
3569 gen->prog);
3570 kernel->n_grid = n_outer_coincidence(node);
3571 node_thread = isl_schedule_node_copy(node);
3572 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3573 node_thread = isl_schedule_node_child(node_thread, 0);
3574 kernel->n_block = n_outer_coincidence(node_thread);
3575 isl_schedule_node_free(node_thread);
3576 kernel->id = gen->kernel_id++;
3577 read_grid_and_block_sizes(kernel, gen);
3579 kernel->sync_writes = compute_sync_writes(kernel, node);
3581 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3582 host_domain = isl_set_from_union_set(isl_union_map_range(
3583 host_schedule));
3585 node = atomic_ancestors(node);
3587 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3588 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3589 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3591 if (!single_statement)
3592 node = group_statements(node, kernel->id);
3594 node = isl_schedule_node_child(node, 0);
3595 node = split_band(node, kernel->n_grid);
3596 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3597 kernel->n_grid, "b");
3598 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3599 kernel->grid_dim);
3600 kernel->grid_size = extract_grid_size(kernel,
3601 isl_union_set_copy(domain));
3602 if (!kernel->options->wrap)
3603 node = snap_band_to_sizes(node, kernel->grid_dim,
3604 kernel->options);
3605 if (scale)
3606 node = scale_band(node, isl_multi_val_copy(sizes));
3607 node = isl_schedule_node_parent(node);
3608 if (!single_statement)
3609 node = isl_schedule_node_parent(node);
3610 node = insert_guard(node, kernel->context, kernel->grid_size,
3611 gen->prog->scop);
3612 node = gpu_tree_move_down_to_thread(node, kernel->core);
3613 node = isl_schedule_node_child(node, 0);
3614 node = split_band(node, kernel->n_block);
3615 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3616 kernel->n_block, "t");
3617 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3618 kernel->block_dim);
3619 extract_block_size(kernel, domain);
3621 node = gpu_tree_move_up_to_kernel(node);
3622 node = isl_schedule_node_child(node, 0);
3623 node = insert_context(kernel, node);
3624 node = isl_schedule_node_child(node, 0);
3625 node = isl_schedule_node_insert_filter(node,
3626 isl_union_set_copy(kernel->block_filter));
3628 node = gpu_tree_move_up_to_kernel(node);
3630 if (gpu_group_references(kernel, node) < 0)
3631 node = isl_schedule_node_free(node);
3632 localize_bounds(kernel, host_domain);
3633 isl_set_free(host_domain);
3635 check_shared_memory_bound(kernel);
3636 compute_group_tilings(kernel);
3638 node = gpu_tree_move_down_to_thread(node, kernel->core);
3639 node = isl_schedule_node_child(node, 0);
3640 if (!kernel->options->wrap)
3641 node = snap_band_to_sizes(node, kernel->block_dim,
3642 kernel->options);
3643 node = isl_schedule_node_insert_filter(node,
3644 isl_union_set_copy(kernel->thread_filter));
3645 if (kernel_requires_unroll(kernel)) {
3646 node = isl_schedule_node_child(node, 0);
3647 node = unroll(node);
3650 node = gpu_tree_move_up_to_thread(node);
3651 kernel->shared_schedule_dim =
3652 isl_schedule_node_get_schedule_depth(node);
3653 kernel->shared_schedule =
3654 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3656 node = gpu_tree_move_up_to_kernel(node);
3658 node = add_sync(kernel, node);
3659 node = add_copies(kernel, node);
3661 node = gpu_tree_move_down_to_thread(node, kernel->core);
3662 node = isl_schedule_node_delete(node);
3664 node = gpu_tree_move_up_to_kernel(node);
3666 if (create_kernel_vars(kernel) < 0)
3667 node = isl_schedule_node_free(node);
3669 if (!single_statement)
3670 node = isl_schedule_node_parent(node);
3671 node = isl_schedule_node_parent(node);
3673 isl_id_free(id);
3674 return node;
3677 /* Insert a zero-dimensional permutable band at "node".
3679 static __isl_give isl_schedule_node *insert_empty_permutable_band(
3680 __isl_take isl_schedule_node *node)
3682 isl_space *space;
3683 isl_schedule *schedule;
3684 isl_union_set *domain;
3685 isl_multi_union_pw_aff *mupa;
3687 schedule = isl_schedule_node_get_schedule(node);
3688 domain = isl_schedule_get_domain(schedule);
3689 space = isl_union_set_get_space(domain);
3690 isl_union_set_free(domain);
3691 isl_schedule_free(schedule);
3693 space = isl_space_set_from_params(space);
3694 mupa = isl_multi_union_pw_aff_zero(space);
3695 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3696 node = isl_schedule_node_band_set_permutable(node, 1);
3698 return node;
3701 /* If "node" is the outermost permutable band that can be mapped to block and
3702 * thread identifiers in its branch (or a leaf with no such outer bands),
3703 * then mark the band as such, attaching a ppcg_kernel to the mark.
3705 * If "node" originally points to a leaf, then insert a zero-dimensional
3706 * permutable band such that we can assume that "node" always
3707 * points to a band node.
3709 * Tile "node" using user specified tile sizes, after splitting the band
3710 * if the number of specified tile sizes is smaller than the dimension
3711 * of the band. Mark the point band of this tiling as the band that
3712 * needs to be mapped to threads.
3713 * Create a kernel representing the domain instances that reach "node" and
3714 * insert a mark node pointing to the ppcg_kernel before the band node.
3716 static __isl_give isl_schedule_node *mark_outer_permutable(
3717 __isl_take isl_schedule_node *node, void *user)
3719 struct gpu_gen *gen = user;
3720 int outer;
3721 int scale;
3722 int tile_len;
3723 int *tile_size;
3724 isl_id *id;
3725 isl_multi_val *sizes;
3727 outer = is_outer_tilable(node);
3728 if (outer < 0)
3729 return isl_schedule_node_free(node);
3730 if (!outer)
3731 return node;
3733 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
3734 node = insert_empty_permutable_band(node);
3736 tile_len = isl_schedule_node_band_n_member(node);
3737 tile_size = read_tile_sizes(gen, &tile_len);
3738 if (!tile_size)
3739 return isl_schedule_node_free(node);
3740 if (tile_len < isl_schedule_node_band_n_member(node))
3741 node = isl_schedule_node_band_split(node, tile_len);
3742 sizes = construct_band_tiles_sizes(node, tile_size);
3743 node = tile_band(node, isl_multi_val_copy(sizes));
3744 node = isl_schedule_node_child(node, 0);
3745 id = isl_id_alloc(gen->ctx, "thread", NULL);
3746 node = isl_schedule_node_insert_mark(node, id);
3747 node = isl_schedule_node_parent(node);
3749 scale = gen->options->scale_tile_loops;
3750 node = create_kernel(gen, node, scale, sizes);
3751 isl_multi_val_free(sizes);
3752 free(tile_size);
3754 return node;
3757 /* Replace any reference to an array element in the range of "copy"
3758 * by a reference to all array elements (defined by the extent of the array).
3760 static __isl_give isl_union_map *approximate_copy_out(
3761 __isl_take isl_union_map *copy, struct gpu_prog *prog)
3763 int i;
3764 isl_union_map *res;
3766 res = isl_union_map_empty(isl_union_map_get_space(copy));
3768 for (i = 0; i < prog->n_array; ++i) {
3769 isl_space *space;
3770 isl_set *set;
3771 isl_union_map *copy_i;
3772 isl_union_set *extent, *domain;
3774 space = isl_space_copy(prog->array[i].space);
3775 extent = isl_union_set_from_set(isl_set_universe(space));
3776 copy_i = isl_union_map_copy(copy);
3777 copy_i = isl_union_map_intersect_range(copy_i, extent);
3778 set = isl_set_copy(prog->array[i].extent);
3779 extent = isl_union_set_from_set(set);
3780 domain = isl_union_map_domain(copy_i);
3781 copy_i = isl_union_map_from_domain_and_range(domain, extent);
3782 res = isl_union_map_union(res, copy_i);
3785 isl_union_map_free(copy);
3787 return res;
3790 /* Insert "kernel" marks that point to a ppcg_kernel structure
3791 * in front of all outermost tilable band that (by construction)
3792 * have at least one parallel loop.
3794 static __isl_give isl_schedule_node *mark_kernels(struct gpu_gen *gen,
3795 __isl_take isl_schedule_node *node)
3797 return isl_schedule_node_map_descendant(node,
3798 &mark_outer_permutable, gen);
3801 /* Save the schedule "schedule" to a file called "filename".
3802 * The schedule is printed in block style.
3804 static void save_schedule(__isl_keep isl_schedule *schedule,
3805 const char *filename)
3807 FILE *file;
3808 isl_ctx *ctx;
3809 isl_printer *p;
3811 if (!schedule)
3812 return;
3814 file = fopen(filename, "w");
3815 if (!file) {
3816 fprintf(stderr, "Unable to open '%s' for writing\n", filename);
3817 return;
3819 ctx = isl_schedule_get_ctx(schedule);
3820 p = isl_printer_to_file(ctx, file);
3821 p = isl_printer_set_yaml_style(p, ISL_YAML_STYLE_BLOCK);
3822 p = isl_printer_print_schedule(p, schedule);
3823 isl_printer_free(p);
3824 fclose(file);
3827 /* Load and return a schedule from a file called "filename".
3829 static __isl_give isl_schedule *load_schedule(isl_ctx *ctx,
3830 const char *filename)
3832 FILE *file;
3833 isl_schedule *schedule;
3835 file = fopen(filename, "r");
3836 if (!file) {
3837 fprintf(stderr, "Unable to open '%s' for reading\n", filename);
3838 return NULL;
3840 schedule = isl_schedule_read_from_file(ctx, file);
3841 fclose(file);
3843 return schedule;
3846 /* Compute an appropriate schedule based on the accesses in
3847 * gen->read and gen->write.
3849 * We use the dependences in gen->prog->scop to compute
3850 * a schedule that has a parallel loop in each tilable band and
3851 * return this schedule.
3853 * If live range reordering is allowed, then we need to make sure
3854 * that live ranges on arrays are not run in parallel since doing
3855 * so would require array expansion. We therefore add the array
3856 * order dependences to the coincidence dependences. Non-zero array
3857 * order dependences will then prevent a schedule dimension from being
3858 * considered parallel.
3859 * Live ranges derived from scalars are allowed to be run in parallel
3860 * since we force the scalars to be mapped to private memory in
3861 * check_scalar_live_ranges.
3862 * If live range reordering is allowed, then the false dependences
3863 * are not added to the validity constraints as that would prevent
3864 * reordering. Instead, the external false dependences that enforce that reads
3865 * from potentially live-in data precede any later write and
3866 * that writes of potentially live-out data follow any other earlier write
3867 * are added to the validity and the coincidence constraints.
3868 * The false dependences are still added to the proximity constraints
3869 * for consistency with the case where live range reordering is not allowed.
3870 * The coincidence constraints then consist of flow dependences,
3871 * external false dependences and array order dependences.
3872 * The independences can be filtered out from the first two sets.
3873 * They have already been filtered out from the array order dependences
3874 * on a per array basis in collect_order_dependences.
3875 * There is no need for a per array handling of the other two sets
3876 * as there should be no flow or external false dependence on local
3877 * variables that can be filtered out.
3879 static __isl_give isl_schedule *compute_schedule(struct gpu_gen *gen)
3881 isl_union_set *domain;
3882 isl_union_map *dep_raw, *dep;
3883 isl_union_map *validity, *proximity, *coincidence;
3884 isl_schedule_constraints *sc;
3885 isl_schedule *schedule;
3887 domain = isl_union_set_copy(gen->prog->scop->domain);
3888 sc = isl_schedule_constraints_on_domain(domain);
3889 sc = isl_schedule_constraints_set_context(sc,
3890 isl_set_copy(gen->prog->scop->context));
3891 if (gen->options->live_range_reordering) {
3892 sc = isl_schedule_constraints_set_conditional_validity(sc,
3893 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
3894 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
3895 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
3896 validity = isl_union_map_copy(proximity);
3897 validity = isl_union_map_union(validity,
3898 isl_union_map_copy(gen->prog->scop->dep_forced));
3899 proximity = isl_union_map_union(proximity,
3900 isl_union_map_copy(gen->prog->scop->dep_false));
3901 coincidence = isl_union_map_copy(validity);
3902 coincidence = isl_union_map_subtract(coincidence,
3903 isl_union_map_copy(gen->prog->scop->independence));
3904 coincidence = isl_union_map_union(coincidence,
3905 isl_union_map_copy(gen->prog->array_order));
3906 } else {
3907 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
3908 dep = isl_union_map_copy(gen->prog->scop->dep_false);
3909 dep = isl_union_map_union(dep, dep_raw);
3910 dep = isl_union_map_coalesce(dep);
3911 proximity = isl_union_map_copy(dep);
3912 coincidence = isl_union_map_copy(dep);
3913 validity = dep;
3915 sc = isl_schedule_constraints_set_validity(sc, validity);
3916 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
3917 sc = isl_schedule_constraints_set_proximity(sc, proximity);
3919 if (gen->options->debug->dump_schedule_constraints)
3920 isl_schedule_constraints_dump(sc);
3921 schedule = isl_schedule_constraints_compute_schedule(sc);
3923 return schedule;
3926 /* Obtain a schedule for the scop, either by reading it from
3927 * a file or by computing one.
3929 static __isl_give isl_schedule *get_schedule(struct gpu_gen *gen)
3931 isl_schedule *schedule;
3933 if (gen->options->load_schedule_file) {
3934 schedule = load_schedule(gen->ctx,
3935 gen->options->load_schedule_file);
3936 } else {
3937 schedule = compute_schedule(gen);
3938 if (gen->options->save_schedule_file)
3939 save_schedule(schedule,
3940 gen->options->save_schedule_file);
3942 if (gen->options->debug->dump_schedule)
3943 isl_schedule_dump(schedule);
3945 return schedule;
3948 /* Return (the universe spaces of) the arrays that are declared
3949 * inside the scop corresponding to "prog" and for which all
3950 * potential writes inside the scop form a subset of "domain".
3952 static __isl_give isl_union_set *extract_local_accesses(struct gpu_prog *prog,
3953 __isl_keep isl_union_set *domain)
3955 int i;
3956 isl_union_set *local;
3958 local = isl_union_set_empty(isl_union_set_get_space(domain));
3960 for (i = 0; i < prog->n_array; ++i) {
3961 isl_set *set;
3962 isl_union_map *to_outer;
3963 isl_union_map *may_write;
3964 isl_union_set *write_domain;
3965 isl_union_set *fields;
3966 int subset;
3968 if (!prog->array[i].local)
3969 continue;
3971 set = isl_set_universe(isl_space_copy(prog->array[i].space));
3972 to_outer = isl_union_map_copy(prog->to_outer);
3973 to_outer = isl_union_map_intersect_range(to_outer,
3974 isl_union_set_from_set(isl_set_copy(set)));
3975 fields = isl_union_map_domain(to_outer);
3976 may_write = isl_union_map_copy(prog->may_write);
3977 may_write = isl_union_map_intersect_range(may_write, fields);
3978 write_domain = isl_union_map_domain(may_write);
3979 subset = isl_union_set_is_subset(write_domain, domain);
3980 isl_union_set_free(write_domain);
3982 if (subset < 0) {
3983 isl_set_free(set);
3984 return isl_union_set_free(local);
3985 } else if (subset) {
3986 local = isl_union_set_add_set(local, set);
3987 } else {
3988 isl_set_free(set);
3992 return local;
3995 /* Internal data structure for node_may_persist.
3997 * "tagger" maps tagged iteration domains to the corresponding untagged
3998 * iteration domain.
4000 * "may_persist_flow" is the set of all tagged dataflow dependences
4001 * with those dependences removed that either precede or follow
4002 * the kernel launch in a sequence.
4003 * "inner_band_flow" is the set of all tagged dataflow dependences
4004 * that are local to a given iteration of the outer band nodes
4005 * with respect to the current node.
4006 * "local_flow" is equal to "inner_band_flow", except that the domain
4007 * and the range have been intersected with intermediate filters
4008 * on children of sets or sequences.
4010 struct ppcg_may_persist_data {
4011 isl_union_pw_multi_aff *tagger;
4013 isl_union_map *local_flow;
4014 isl_union_map *inner_band_flow;
4015 isl_union_map *may_persist_flow;
4018 /* Update the information in "data" based on the band ancestor "node".
4020 * In particular, we restrict the dependences in data->local_flow
4021 * to those dependence where the source and the sink occur in
4022 * the same iteration of the given band node.
4023 * We also update data->inner_band_flow to the new value of
4024 * data->local_flow.
4026 static int update_may_persist_at_band(__isl_keep isl_schedule_node *node,
4027 struct ppcg_may_persist_data *data)
4029 isl_multi_union_pw_aff *partial;
4030 isl_union_pw_multi_aff *contraction;
4031 isl_union_map *flow;
4033 if (isl_schedule_node_band_n_member(node) == 0)
4034 return 0;
4036 partial = isl_schedule_node_band_get_partial_schedule(node);
4037 contraction = isl_schedule_node_get_subtree_contraction(node);
4038 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4039 contraction);
4040 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4041 isl_union_pw_multi_aff_copy(data->tagger));
4043 flow = data->local_flow;
4044 flow = isl_union_map_eq_at_multi_union_pw_aff(flow, partial);
4045 data->local_flow = flow;
4047 isl_union_map_free(data->inner_band_flow);
4048 data->inner_band_flow = isl_union_map_copy(data->local_flow);
4050 return 0;
4053 /* Given a set of local reaching domain elements "domain",
4054 * expand them to the corresponding leaf domain elements using "contraction"
4055 * and insert the array references tags using data->tagger.
4057 static __isl_give isl_union_set *expand_and_tag(
4058 __isl_take isl_union_set *domain,
4059 __isl_take isl_union_pw_multi_aff *contraction,
4060 struct ppcg_may_persist_data *data)
4062 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4063 contraction);
4064 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4065 isl_union_pw_multi_aff_copy(data->tagger));
4066 return domain;
4069 /* Given a filter node that is the child of a set or sequence node,
4070 * restrict data->local_flow to refer only to those elements
4071 * in the filter of the node.
4072 * "contraction" maps the leaf domain elements of the schedule tree
4073 * to the corresponding domain elements at (the parent of) "node".
4075 static int filter_flow(__isl_keep isl_schedule_node *node,
4076 struct ppcg_may_persist_data *data,
4077 __isl_take isl_union_pw_multi_aff *contraction)
4079 isl_union_set *filter;
4080 isl_union_map *flow;
4082 flow = data->local_flow;
4083 filter = isl_schedule_node_filter_get_filter(node);
4084 filter = expand_and_tag(filter, contraction, data);
4085 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(filter));
4086 flow = isl_union_map_intersect_range(flow, filter);
4087 data->local_flow = flow;
4089 return 0;
4092 /* Given a filter node "node", collect the filters on all preceding siblings
4093 * (which are also filter nodes), add them to "filters" and return the result.
4095 static __isl_give isl_union_set *add_previous_filters(
4096 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4098 isl_schedule_node *sibling;
4100 sibling = isl_schedule_node_copy(node);
4101 while (sibling && isl_schedule_node_has_previous_sibling(sibling)) {
4102 isl_union_set *filter;
4104 sibling = isl_schedule_node_previous_sibling(sibling);
4105 filter = isl_schedule_node_filter_get_filter(sibling);
4106 filters = isl_union_set_union(filters, filter);
4108 isl_schedule_node_free(sibling);
4109 if (!sibling)
4110 return isl_union_set_free(filters);
4112 return filters;
4115 /* Given a filter node "node", collect the filters on all following siblings
4116 * (which are also filter nodes), add them to "filters" and return the result.
4118 static __isl_give isl_union_set *add_next_filters(
4119 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4121 isl_schedule_node *sibling;
4123 sibling = isl_schedule_node_copy(node);
4124 while (sibling && isl_schedule_node_has_next_sibling(sibling)) {
4125 isl_union_set *filter;
4127 sibling = isl_schedule_node_next_sibling(sibling);
4128 filter = isl_schedule_node_filter_get_filter(sibling);
4129 filters = isl_union_set_union(filters, filter);
4131 isl_schedule_node_free(sibling);
4132 if (!sibling)
4133 return isl_union_set_free(filters);
4135 return filters;
4138 /* Remove those flow dependences from data->may_persist_flow
4139 * that flow between elements of "domain" within the same iteration
4140 * of all outer band nodes.
4141 * "contraction" maps the leaf domain elements of the schedule tree
4142 * to the corresponding elements "domain".
4144 static void remove_external_flow(struct ppcg_may_persist_data *data,
4145 __isl_take isl_union_set *domain,
4146 __isl_keep isl_union_pw_multi_aff *contraction)
4148 isl_union_map *flow;
4150 contraction = isl_union_pw_multi_aff_copy(contraction);
4151 domain = expand_and_tag(domain, contraction, data);
4152 flow = isl_union_map_copy(data->local_flow);
4153 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(domain));
4154 flow = isl_union_map_intersect_range(flow, domain);
4156 data->may_persist_flow = isl_union_map_subtract(data->may_persist_flow,
4157 flow);
4160 /* Update the information in "data" based on the filter ancestor "node".
4161 * We only need to modify anything if the filter is the child
4162 * of a set or sequence node.
4164 * In the case of a sequence, we remove the dependences between
4165 * statement instances that are both executed either before or
4166 * after the subtree that will be mapped to a kernel, within
4167 * the same iteration of outer bands.
4169 * In both cases, we restrict data->local_flow to the current child.
4171 static int update_may_persist_at_filter(__isl_keep isl_schedule_node *node,
4172 struct ppcg_may_persist_data *data)
4174 enum isl_schedule_node_type type;
4175 isl_schedule_node *parent;
4176 isl_space *space;
4177 isl_union_pw_multi_aff *contraction;
4178 isl_union_set *before, *after, *filter;
4179 isl_union_map *flow;
4181 type = isl_schedule_node_get_parent_type(node);
4182 if (type != isl_schedule_node_sequence && type != isl_schedule_node_set)
4183 return 0;
4185 parent = isl_schedule_node_copy(node);
4186 parent = isl_schedule_node_parent(parent);
4187 contraction = isl_schedule_node_get_subtree_contraction(parent);
4188 isl_schedule_node_free(parent);
4190 if (type == isl_schedule_node_set)
4191 return filter_flow(node, data, contraction);
4193 filter = isl_schedule_node_filter_get_filter(node);
4194 space = isl_union_set_get_space(filter);
4195 isl_union_set_free(filter);
4196 before = isl_union_set_empty(space);
4197 after = isl_union_set_copy(before);
4198 before = add_previous_filters(before, node);
4199 after = add_next_filters(after, node);
4201 remove_external_flow(data, before, contraction);
4202 remove_external_flow(data, after, contraction);
4204 return filter_flow(node, data, contraction);
4207 /* Update the information in "data" based on the ancestor "node".
4209 static int update_may_persist_at(__isl_keep isl_schedule_node *node, void *user)
4211 struct ppcg_may_persist_data *data = user;
4213 switch (isl_schedule_node_get_type(node)) {
4214 case isl_schedule_node_error:
4215 return -1;
4216 case isl_schedule_node_context:
4217 case isl_schedule_node_domain:
4218 case isl_schedule_node_expansion:
4219 case isl_schedule_node_extension:
4220 case isl_schedule_node_guard:
4221 case isl_schedule_node_leaf:
4222 case isl_schedule_node_mark:
4223 case isl_schedule_node_sequence:
4224 case isl_schedule_node_set:
4225 break;
4226 case isl_schedule_node_band:
4227 if (update_may_persist_at_band(node, data) < 0)
4228 return -1;
4229 break;
4230 case isl_schedule_node_filter:
4231 if (update_may_persist_at_filter(node, data) < 0)
4232 return -1;
4233 break;
4236 return 0;
4239 /* Determine the set of array elements that may need to be perserved
4240 * by a kernel constructed from the subtree at "node".
4241 * This includes the set of array elements that may need to be preserved
4242 * by the entire scop (prog->may_persist) and the elements for which
4243 * there is a potential flow dependence that may cross a kernel launch.
4245 * To determine the second set, we start from all flow dependences.
4246 * From this set of dependences, we remove those that cannot possibly
4247 * require data to be preserved by a kernel launch.
4248 * In particular, we consider the following sets of dependences.
4249 * - dependences of which the write occurs inside the kernel.
4250 * If the data is needed outside the kernel, then it will
4251 * be copied out immediately after the kernel launch, so there
4252 * is no need for any special care.
4253 * - dependences of which the read occurs inside the kernel and the
4254 * corresponding write occurs inside the same iteration of the
4255 * outer band nodes. This means that the data is needed in
4256 * the first kernel launch after the write, which is already
4257 * taken care of by the standard copy-in. That is, the data
4258 * do not need to be preserved by any intermediate call to
4259 * the same kernel.
4260 * - dependences of which the write and the read either both occur
4261 * before the kernel launch or both occur after the kernel launch,
4262 * within the same iteration of the outer band nodes with respect
4263 * to the sequence that determines the ordering of the dependence
4264 * and the kernel launch. Such flow dependences cannot cross
4265 * any kernel launch.
4267 * For the remaining (tagged) dependences, we take the domain
4268 * (i.e., the tagged writes) and apply the tagged access relation
4269 * to obtain the accessed data elements.
4270 * These are then combined with the elements that may need to be
4271 * preserved by the entire scop.
4273 static __isl_give isl_union_set *node_may_persist(
4274 __isl_keep isl_schedule_node *node, struct gpu_prog *prog)
4276 struct ppcg_may_persist_data data;
4277 isl_schedule_node *root;
4278 isl_union_pw_multi_aff *contraction;
4279 isl_union_set *domain;
4280 isl_union_set *persist;
4281 isl_union_map *flow, *local_flow;
4283 data.tagger = prog->scop->tagger;
4285 flow = isl_union_map_copy(prog->scop->tagged_dep_flow);
4286 data.local_flow = isl_union_map_copy(flow);
4287 data.inner_band_flow = isl_union_map_copy(flow);
4288 data.may_persist_flow = flow;
4289 if (isl_schedule_node_foreach_ancestor_top_down(node,
4290 &update_may_persist_at, &data) < 0)
4291 data.may_persist_flow =
4292 isl_union_map_free(data.may_persist_flow);
4293 flow = data.may_persist_flow;
4294 isl_union_map_free(data.local_flow);
4296 domain = isl_schedule_node_get_domain(node);
4297 contraction = isl_schedule_node_get_subtree_contraction(node);
4298 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4299 contraction);
4300 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4301 isl_union_pw_multi_aff_copy(data.tagger));
4302 flow = isl_union_map_subtract_domain(flow, isl_union_set_copy(domain));
4303 local_flow = data.inner_band_flow;
4304 local_flow = isl_union_map_intersect_range(local_flow, domain);
4305 flow = isl_union_map_subtract(flow, local_flow);
4307 persist = isl_union_map_domain(flow);
4308 persist = isl_union_set_apply(persist,
4309 isl_union_map_copy(prog->scop->tagged_may_writes));
4310 persist = isl_union_set_union(persist,
4311 isl_union_set_copy(prog->may_persist));
4313 return persist;
4316 /* Compute the sets of outer array elements that need to be copied in and out
4317 * before and after the subtree "node", which will be mapped
4318 * to one or more kernels.
4319 * "domain" contains the original reaching domain elements before
4320 * the kernels were created, i.e., before the contraction that
4321 * may have been performed in creating the kernels has been applied.
4322 * "prefix" contains the prefix schedule at that point, in terms
4323 * of the same original reaching domain elements.
4325 * In particular, for each array that is possibly written anywhere in
4326 * the subtree "node" and that may be used after "node"
4327 * or that may be visible outside the corresponding scop,
4328 * we copy out its entire extent.
4330 * Any array elements that is read without first being written inside
4331 * the subtree "node" needs to be copied in.
4332 * Furthermore, if there are any array elements that
4333 * are copied out, but that may not be written inside "node, then
4334 * they also need to be copied in to ensure that the value after execution
4335 * is the same as the value before execution, at least for those array
4336 * elements that may have their values preserved by the scop or that
4337 * may be written before "node" and read after "node".
4338 * In case the array elements are structures, we need to take into
4339 * account that all members of the structures need to be written
4340 * by "node" before we can avoid copying the data structure in.
4342 * Note that the may_write relation is intersected with the domain,
4343 * which has been intersected with the context.
4344 * This helps in those cases where the arrays are declared with a fixed size,
4345 * while the accesses are parametric and the context assigns a fixed value
4346 * to the parameters.
4348 * If an element from a local array is read without first being written,
4349 * then there is no point in copying it in since it cannot have been
4350 * written prior to the scop. Warn about the uninitialized read instead.
4352 static void compute_copy_in_and_out(__isl_keep isl_schedule_node *node,
4353 __isl_take isl_union_set *domain, __isl_take isl_union_map *prefix,
4354 struct gpu_prog *prog)
4356 isl_union_set *local;
4357 isl_union_set *to_device, *from_device, *may_persist;
4358 isl_union_map *may_write, *must_write, *copy_out, *not_written;
4359 isl_union_map *read, *copy_in;
4360 isl_union_map *tagged;
4361 isl_union_map *local_uninitialized;
4363 tagged = isl_union_map_copy(prog->scop->tagged_reads);
4364 tagged = isl_union_map_union(tagged,
4365 isl_union_map_copy(prog->scop->tagged_may_writes));
4367 may_write = isl_union_map_copy(prog->may_write);
4368 may_write = isl_union_map_intersect_domain(may_write,
4369 isl_union_set_copy(domain));
4370 may_write = remove_local_accesses(prog,
4371 isl_union_map_copy(tagged), may_write,
4372 isl_union_map_copy(prefix), 0);
4373 may_write = isl_union_map_apply_range(may_write,
4374 isl_union_map_copy(prog->to_outer));
4375 may_write = isl_union_map_apply_domain(may_write,
4376 isl_union_map_copy(prefix));
4377 may_write = approximate_copy_out(may_write, prog);
4378 copy_out = isl_union_map_copy(may_write);
4379 may_write = isl_union_map_apply_range(may_write,
4380 isl_union_map_copy(prog->to_inner));
4381 must_write = isl_union_map_copy(prog->must_write);
4382 must_write = isl_union_map_apply_domain(must_write,
4383 isl_union_map_copy(prefix));
4384 may_persist = node_may_persist(node, prog);
4385 may_write = isl_union_map_intersect_range(may_write, may_persist);
4386 not_written = isl_union_map_subtract(may_write, must_write);
4388 local = extract_local_accesses(prog, domain);
4389 read = isl_union_map_copy(prog->read);
4390 read = isl_union_map_intersect_domain(read, domain);
4391 read = remove_local_accesses(prog, tagged, read,
4392 isl_union_map_copy(prefix), 1);
4393 local = isl_union_set_apply(local, isl_union_map_copy(prog->to_inner));
4394 local_uninitialized = isl_union_map_copy(prog->scop->live_in);
4395 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4396 local);
4397 local_uninitialized = isl_union_map_intersect(local_uninitialized,
4398 isl_union_map_copy(read));
4399 if (!isl_union_map_is_empty(local_uninitialized)) {
4400 fprintf(stderr,
4401 "possibly uninitialized reads (not copied in):\n");
4402 isl_union_map_dump(local_uninitialized);
4404 read = isl_union_map_subtract(read, local_uninitialized);
4405 read = isl_union_map_apply_domain(read, prefix);
4406 copy_in = isl_union_map_union(read, not_written);
4407 copy_in = isl_union_map_apply_range(copy_in,
4408 isl_union_map_copy(prog->to_outer));
4410 prog->copy_out = isl_union_map_range(copy_out);
4411 prog->copy_in = isl_union_map_range(copy_in);
4414 /* Update "schedule" for mapping to a GPU device.
4416 * In particular, insert a context node, create kernels for
4417 * each outermost tilable band.
4418 * Also compute the sets of outer array elements that need
4419 * to be copied in and out.
4421 static __isl_give isl_schedule *map_to_device(struct gpu_gen *gen,
4422 __isl_take isl_schedule *schedule)
4424 isl_schedule_node *node;
4425 isl_set *context;
4426 isl_union_set *domain;
4427 isl_union_map *prefix;
4429 context = isl_set_copy(gen->prog->context);
4430 context = isl_set_from_params(context);
4431 schedule = isl_schedule_insert_context(schedule, context);
4433 node = isl_schedule_get_root(schedule);
4434 isl_schedule_free(schedule);
4435 node = isl_schedule_node_child(node, 0);
4436 if (isl_schedule_node_get_type(node) == isl_schedule_node_context)
4437 node = isl_schedule_node_child(node, 0);
4438 domain = isl_schedule_node_get_domain(node);
4439 prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
4440 compute_copy_in_and_out(node, domain, prefix, gen->prog);
4441 node = mark_kernels(gen, node);
4442 schedule = isl_schedule_node_get_schedule(node);
4443 isl_schedule_node_free(node);
4445 return schedule;
4448 /* Internal data structure for extract_access.
4449 * "next_access" points to the end of a linked list that is extended
4450 * by extract_access.
4451 * "single_expression" is set if the access expressions belong to
4452 * an expression statement (i.e., a statement without internal control).
4453 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4455 struct ppcg_extract_access_data {
4456 struct gpu_stmt_access **next_access;
4457 int single_expression;
4458 isl_union_map *any_to_outer;
4461 /* Given a tagged access relation to a single array "tagged", extract it
4462 * as a map, taking into account that the input may be empty.
4463 * If the access relation is empty, then it does not contain
4464 * any space information, so we try to recover it from the index
4465 * expression.
4466 * The space of the index expression is of the form I -> A,
4467 * with I the statement instances and A the array, or [I -> F] -> A,
4468 * with F the filters corresponding to arguments.
4469 * We first drop F, if present, obtaining I -> A.
4470 * Then we construct I -> R, with R the reference tag,
4471 * combine the two into I -> [R -> A] and uncurry to obtain
4472 * the final result [I -> R] -> A.
4473 * Note that the index expression may have a lower dimension
4474 * than that of the array, but this dimension is not used
4475 * if the access relation is empty.
4477 static __isl_give isl_map *extract_single_tagged_access(
4478 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
4480 int empty;
4481 isl_id *id;
4482 isl_space *space, *space2;
4483 isl_multi_pw_aff *index;
4485 empty = isl_union_map_is_empty(tagged);
4486 if (empty < 0)
4487 goto error;
4488 if (!empty)
4489 return isl_map_from_union_map(tagged);
4490 isl_union_map_free(tagged);
4492 index = pet_expr_access_get_index(expr);
4493 space = isl_multi_pw_aff_get_space(index);
4494 isl_multi_pw_aff_free(index);
4495 if (isl_space_domain_is_wrapping(space))
4496 space = isl_space_domain_factor_domain(space);
4497 space2 = isl_space_copy(space);
4498 space2 = isl_space_from_domain(isl_space_domain(space));
4499 id = pet_expr_access_get_ref_id(expr);
4500 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
4501 space = isl_space_range_product(space2, space);
4502 space = isl_space_uncurry(space);
4504 return isl_map_empty(space);
4505 error:
4506 isl_union_map_free(tagged);
4507 return NULL;
4510 /* Extract a gpu_stmt_access from "expr", append it to the list
4511 * that ends in *data->next_access and update the end of the list.
4512 * If the access expression performs a write, then it is considered
4513 * exact only if it appears in a single expression statement and
4514 * if its may access relation is equal to its must access relation.
4516 * The combined set of may accesses may be union if member accesses
4517 * are involved, but the entire set is derived from a single reference and
4518 * therefore from a single index expression. These accesses therefore
4519 * all map to the same outer array.
4521 static int extract_access(__isl_keep pet_expr *expr, void *user)
4523 struct ppcg_extract_access_data *data = user;
4524 isl_union_map *tagged;
4525 struct gpu_stmt_access *access;
4526 isl_ctx *ctx = pet_expr_get_ctx(expr);
4527 isl_multi_pw_aff *index;
4529 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4530 assert(access);
4531 access->next = NULL;
4532 access->read = pet_expr_access_is_read(expr);
4533 access->write = pet_expr_access_is_write(expr);
4534 tagged = pet_expr_access_get_tagged_may_read(expr);
4535 tagged = isl_union_map_union(tagged,
4536 pet_expr_access_get_tagged_may_write(expr));
4537 tagged = isl_union_map_apply_range(tagged,
4538 isl_union_map_copy(data->any_to_outer));
4539 if (!access->write) {
4540 access->exact_write = 1;
4541 } else if (!data->single_expression) {
4542 access->exact_write = 0;
4543 } else {
4544 isl_union_map *must, *may;
4545 may = isl_union_map_copy(tagged);
4546 may = isl_union_map_domain_factor_domain(may);
4547 must = pet_expr_access_get_must_write(expr);
4548 access->exact_write = isl_union_map_is_equal(must, may);
4549 isl_union_map_free(must);
4550 isl_union_map_free(may);
4552 index = pet_expr_access_get_index(expr);
4553 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
4554 isl_multi_pw_aff_free(index);
4555 access->ref_id = pet_expr_access_get_ref_id(expr);
4556 access->tagged_access = extract_single_tagged_access(tagged, expr);
4557 access->access = isl_map_copy(access->tagged_access);
4558 access->access = isl_map_domain_factor_domain(access->access);
4560 *data->next_access = access;
4561 data->next_access = &(*data->next_access)->next;
4563 if (!access->access)
4564 return -1;
4566 return 0;
4569 /* Construct a linked list of gpu_stmt_access objects,
4570 * one for each access expression in the statement body.
4571 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4573 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
4574 __isl_keep isl_union_map *any_to_outer)
4576 struct ppcg_extract_access_data data;
4578 stmt->accesses = NULL;
4579 data.next_access = &stmt->accesses;
4580 data.single_expression =
4581 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
4582 data.any_to_outer = any_to_outer;
4583 return pet_tree_foreach_access_expr(stmt->stmt->body,
4584 &extract_access, &data);
4587 /* Return an array of gpu_stmt representing the statements in "scop".
4589 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4590 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
4592 int i;
4593 struct gpu_stmt *stmts;
4595 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
4596 if (!stmts)
4597 return NULL;
4599 for (i = 0; i < scop->pet->n_stmt; ++i) {
4600 struct gpu_stmt *s = &stmts[i];
4602 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
4603 s->stmt = scop->pet->stmts[i];
4604 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
4605 return free_stmts(stmts, i + 1);
4608 return stmts;
4611 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
4613 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
4615 struct gpu_gen *gen = user;
4617 return gen->print(p, gen->prog, gen->tree, &gen->types,
4618 gen->print_user);
4621 /* Generate CUDA code for "scop" and print it to "p".
4622 * After generating an AST for the transformed scop as explained below,
4623 * we call "gen->print" to print the AST in the desired output format
4624 * to "p".
4626 * If it turns out that it does not make sense to generate GPU code,
4627 * then we generate CPU code instead.
4629 * The GPU code is generated in a context where at least one
4630 * statement instance is executed. The corresponding guard (if any) is printed
4631 * around the entire generated GPU code, except for the declaration
4632 * of the arrays that are visible outside of the scop and that therefore
4633 * cannot be declared inside the body of any possible guard.
4635 * We first compute a schedule that respects the dependences
4636 * of the original program and select the outermost bands
4637 * of tilable dimensions that have at least one parallel loop.
4638 * If the --load-schedule is specified, then the loaded schedule
4639 * is used instead of a computed schedule.
4641 * Each of these bands B is then tiled according to "tile" sizes, resulting
4642 * in two nested bands, with a kernel marker on top
4650 * We then split off at most 2 parallel dimensions from the T band and
4651 * at most 3 parallel dimension from the P band
4656 * T1
4658 * T2
4660 * P1
4662 * P2
4664 * A filter is introduced in front of T1 that maps the domain instances
4665 * to block identifiers. Similarly, a filter is introduced in front of P1
4666 * that maps the domain instances to thread identifiers.
4668 * For each iteration of the T2 band and for each array, we compute
4669 * the array elements accessed by that iteration, construct a rectangular
4670 * box around it and shift it to the origin. The result is used
4671 * as shared memory for the array.
4673 * Copying and synchronization statements are added to this schedule tree.
4674 * In principle, these are added in front of the P1 band, but some of
4675 * them may get hoisted up to higher levels.
4677 * The entire AST is then generated from the single resulting schedule tree.
4678 * During the generation the subtrees at kernel nodes (K) are saved
4679 * aside and replaced by kernel calls. The result is printed as host code
4680 * while the saved subtrees are printed as device code.
4682 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
4683 struct gpu_gen *gen, struct ppcg_scop *scop,
4684 struct ppcg_options *options)
4686 struct gpu_prog *prog;
4687 isl_ctx *ctx;
4688 isl_set *context, *guard;
4689 isl_schedule *schedule;
4690 int any_permutable;
4692 if (!scop)
4693 return isl_printer_free(p);
4695 ctx = isl_printer_get_ctx(p);
4696 prog = gpu_prog_alloc(ctx, scop);
4697 if (!prog)
4698 return isl_printer_free(p);
4700 context = isl_set_copy(prog->context);
4701 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
4702 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
4704 gen->prog = prog;
4705 schedule = get_schedule(gen);
4707 any_permutable = has_any_permutable_node(schedule);
4708 if (any_permutable < 0 || !any_permutable) {
4709 isl_set_free(context);
4710 isl_set_free(guard);
4711 if (any_permutable < 0)
4712 p = isl_printer_free(p);
4713 else
4714 p = print_cpu(p, scop, options);
4715 isl_schedule_free(schedule);
4716 } else {
4717 schedule = map_to_device(gen, schedule);
4718 gen->tree = generate_code(gen, schedule);
4719 p = ppcg_print_exposed_declarations(p, prog->scop);
4720 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
4721 isl_ast_node_free(gen->tree);
4724 gpu_prog_free(prog);
4726 return p;
4729 /* Wrapper around generate for use as a ppcg_transform callback.
4731 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
4732 struct ppcg_scop *scop, void *user)
4734 struct gpu_gen *gen = user;
4736 return generate(p, gen, scop, gen->options);
4739 /* Transform the code in the file called "input" by replacing
4740 * all scops by corresponding GPU code and write the results to "out".
4742 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
4743 struct ppcg_options *options,
4744 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
4745 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
4746 struct gpu_types *types, void *user), void *user)
4748 struct gpu_gen gen;
4749 int r;
4750 int i;
4752 gen.ctx = ctx;
4753 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
4754 gen.options = options;
4755 gen.kernel_id = 0;
4756 gen.print = print;
4757 gen.print_user = user;
4758 gen.types.n = 0;
4759 gen.types.name = NULL;
4761 if (options->debug->dump_sizes) {
4762 isl_space *space = isl_space_params_alloc(ctx, 0);
4763 gen.used_sizes = isl_union_map_empty(space);
4766 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
4768 if (options->debug->dump_sizes) {
4769 isl_union_map_dump(gen.used_sizes);
4770 isl_union_map_free(gen.used_sizes);
4773 isl_union_map_free(gen.sizes);
4774 for (i = 0; i < gen.types.n; ++i)
4775 free(gen.types.name[i]);
4776 free(gen.types.name);
4778 return r;
4781 /* Compute the set of inner array elements that may have their values
4782 * preserved by "prog". In particular, collect the array elements of
4783 * arrays that are not local to "prog" and remove those elements that
4784 * are definitely killed or definitely written by "prog".
4786 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
4788 int i;
4789 isl_union_set *may_persist, *killed;
4790 isl_union_map *must_kill;
4792 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
4793 for (i = 0; i < prog->n_array; ++i) {
4794 isl_set *extent;
4796 if (prog->array[i].local)
4797 continue;
4799 extent = isl_set_copy(prog->array[i].extent);
4800 may_persist = isl_union_set_add_set(may_persist, extent);
4803 may_persist = isl_union_set_intersect_params(may_persist,
4804 isl_set_copy(prog->context));
4805 may_persist = isl_union_set_apply(may_persist,
4806 isl_union_map_copy(prog->to_inner));
4807 must_kill = isl_union_map_copy(prog->tagged_must_kill);
4808 killed = isl_union_map_range(must_kill);
4809 must_kill = isl_union_map_copy(prog->must_write);
4810 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
4812 may_persist = isl_union_set_subtract(may_persist, killed);
4813 return may_persist;
4816 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
4818 struct gpu_prog *prog;
4819 isl_space *space;
4820 isl_map *id;
4822 if (!scop)
4823 return NULL;
4825 prog = isl_calloc_type(ctx, struct gpu_prog);
4826 assert(prog);
4828 prog->ctx = ctx;
4829 prog->scop = scop;
4830 prog->context = isl_set_copy(scop->context);
4831 prog->n_stmts = scop->pet->n_stmt;
4832 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
4833 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
4834 space = isl_union_map_get_space(prog->any_to_outer);
4835 space = isl_space_set_from_params(space);
4836 space = isl_space_add_dims(space, isl_dim_set, 1);
4837 space = isl_space_map_from_set(space);
4838 id = isl_map_identity(space);
4839 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
4840 prog->stmts = extract_stmts(ctx, scop,
4841 prog->context, prog->any_to_outer);
4842 prog->read = isl_union_map_copy(scop->reads);
4843 prog->may_write = isl_union_map_copy(scop->may_writes);
4844 prog->must_write = isl_union_map_copy(scop->must_writes);
4845 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
4846 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
4847 prog->to_outer = isl_union_map_copy(prog->to_inner);
4848 prog->to_outer = isl_union_map_reverse(prog->to_outer);
4850 if (!prog->stmts)
4851 return gpu_prog_free(prog);
4853 if (collect_array_info(prog) < 0)
4854 return gpu_prog_free(prog);
4855 prog->may_persist = compute_may_persist(prog);
4857 return prog;
4860 void *gpu_prog_free(struct gpu_prog *prog)
4862 if (!prog)
4863 return NULL;
4864 free_array_info(prog);
4865 free_stmts(prog->stmts, prog->n_stmts);
4866 isl_union_map_free(prog->any_to_outer);
4867 isl_union_map_free(prog->to_outer);
4868 isl_union_map_free(prog->to_inner);
4869 isl_union_set_free(prog->copy_in);
4870 isl_union_set_free(prog->copy_out);
4871 isl_union_map_free(prog->read);
4872 isl_union_map_free(prog->may_write);
4873 isl_union_map_free(prog->must_write);
4874 isl_union_map_free(prog->tagged_must_kill);
4875 isl_union_map_free(prog->array_order);
4876 isl_union_set_free(prog->may_persist);
4877 isl_set_free(prog->context);
4878 free(prog);
4879 return NULL;