gpu.c: copy_group_shared_accesses: use gpu_array_is_scalar for clarity
[ppcg.git] / gpu.c
blob45b343b9cbcea7f8f3e8c324f85a9568a804e2f2
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/band.h>
23 #include <isl/schedule.h>
24 #include <isl/options.h>
25 #include <isl/ast_build.h>
27 #include "cpu.h"
28 #include "gpu.h"
29 #include "schedule.h"
30 #include "ppcg_options.h"
31 #include "print.h"
33 /* The fields stride, shift and shift_map only contain valid information
34 * if shift != NULL.
35 * If so, they express that current index is such that if you add shift,
36 * then the result is always a multiple of stride.
37 * shift_map contains the mapping
39 * i -> (i + shift)/stride
41 * Let D represent the initial shared_len dimensions of the computed schedule.
42 * The spaces of "lb" and "shift" are of the form
44 * D -> [b]
46 * "shift_map" is of the form
48 * [D -> i] -> [D -> (i + shift(D))/stride]
50 struct gpu_array_bound {
51 isl_val *size;
52 isl_aff *lb;
54 isl_val *stride;
55 isl_aff *shift;
56 isl_basic_map *shift_map;
59 /* A tile of an array.
61 * n is the dimension of the array.
62 * bound is an array of size "n" representing the lower bound
63 * and size for each index.
65 * tiling maps a tile in the global array to the correspondin
66 * shared/private memory tile and is of the form
68 * { [D[i] -> A[a]] -> T[(a + shift(i))/stride - lb(i)] }
70 * where D represents the initial shared_len dimensions
71 * of the computed schedule.
73 struct gpu_array_tile {
74 int n;
75 struct gpu_array_bound *bound;
76 isl_multi_aff *tiling;
79 struct gpu_array_info;
81 /* A group of array references in a kernel that should be handled together.
82 * If private_tile is not NULL, then it is mapped to registers.
83 * Otherwise, if shared_tile is not NULL, it is mapped to shared memory.
84 * Otherwise, it is accessed from global memory.
86 struct gpu_array_ref_group {
87 /* The references in this group access this array. */
88 struct gpu_array_info *array;
89 /* Position of this group in the list of reference groups of array. */
90 int nr;
92 /* The following fields are use during the construction of the groups.
93 * access is the combined access relation relative to the shared
94 * memory tiling. In particular, the domain of the map corresponds
95 * to the first shared_len dimensions of the computed schedule.
96 * write is set if any access in the group is a write.
98 isl_map *access;
99 int write;
101 /* The shared memory tile, NULL if none. */
102 struct gpu_array_tile *shared_tile;
104 /* The private memory tile, NULL if none. */
105 struct gpu_array_tile *private_tile;
107 /* References in this group; point to elements of a linked list. */
108 int n_ref;
109 struct gpu_stmt_access **refs;
111 /* Last shared memory tile dimension that affects tile of this group. */
112 int last_shared;
115 struct gpu_gen {
116 isl_ctx *ctx;
117 struct ppcg_options *options;
119 /* Callback for printing of AST in appropriate format. */
120 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
121 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
122 void *user);
123 void *print_user;
125 struct gpu_prog *prog;
126 /* The generated AST. */
127 isl_ast_node *tree;
129 /* tile, grid and block sizes for each kernel */
130 isl_union_map *sizes;
132 /* Identifier of current kernel. */
133 int kernel_id;
134 /* Pointer to the current kernel. */
135 struct ppcg_kernel *kernel;
136 /* Does the computed schedule exhibit any parallelism? */
137 int any_parallelism;
139 /* First tile dimension. */
140 int tile_first;
141 /* Number of tile dimensions. */
142 int tile_len;
143 /* Number of initial parallel loops among tile dimensions. */
144 int n_parallel;
146 /* Number of dimensions determining shared memory. */
147 int shared_len;
149 /* Number of rows in the untiled schedule. */
150 int untiled_len;
151 /* Number of rows in the tiled schedule. */
152 int tiled_len;
153 /* Number of rows in schedule after tiling/wrapping over threads. */
154 int thread_tiled_len;
156 /* Global untiled schedule. */
157 isl_union_map *sched;
158 /* Local (per kernel launch) tiled schedule. */
159 isl_union_map *tiled_sched;
160 /* Local schedule per shared memory tile loop iteration. */
161 isl_union_map *local_sched;
163 /* Local tiled schedule projected onto the shared tile loops and
164 * the loops that will be wrapped over the threads,
165 * with all shared tile loops parametrized.
167 isl_union_map *shared_sched;
168 /* Projects out the loops that will be wrapped over the threads
169 * from shared_sched.
171 isl_union_map *shared_proj;
173 /* A map that takes the range of shared_sched as input,
174 * wraps the appropriate loops over the threads and then projects
175 * out these loops.
177 isl_map *privatization;
179 /* A map from the shared memory tile loops and the thread indices
180 * (as parameters) to the set of accessed memory elements that
181 * will be accessed through private copies.
183 isl_union_map *private_access;
185 /* The schedule for the current private/shared access
186 * (within print_private_access or print_shared_access).
188 isl_map *copy_sched;
189 /* The array reference group corresponding to copy_sched. */
190 struct gpu_array_ref_group *copy_group;
192 /* First loop to unroll (or -1 if none) in the current part of the
193 * schedule.
195 int first_unroll;
197 int n_grid;
198 int n_block;
199 /* Note: in the input file, the sizes of the grid and the blocks
200 * are specified in the order x, y, z, but internally, the sizes
201 * are stored in reverse order, so that the last element always
202 * refers to the x dimension.
204 int grid_dim[2];
205 int block_dim[3];
206 int *tile_size;
209 /* Print the name of the local copy of a given group of array references.
211 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
212 struct gpu_array_ref_group *group)
214 int global = 0;
216 if (group->private_tile)
217 p = isl_printer_print_str(p, "private_");
218 else if (group->shared_tile)
219 p = isl_printer_print_str(p, "shared_");
220 else
221 global = 1;
222 p = isl_printer_print_str(p, group->array->name);
223 if (!global && group->array->n_group > 1) {
224 p = isl_printer_print_str(p, "_");
225 p = isl_printer_print_int(p, group->nr);
228 return p;
231 /* Collect all references to the given array and store pointers to them
232 * in array->refs.
234 static void collect_references(struct gpu_prog *prog,
235 struct gpu_array_info *array)
237 int i;
238 int n;
240 n = 0;
241 for (i = 0; i < prog->n_stmts; ++i) {
242 struct gpu_stmt *stmt = &prog->stmts[i];
243 struct gpu_stmt_access *access;
245 for (access = stmt->accesses; access; access = access->next) {
246 const char *name;
247 name = isl_map_get_tuple_name(access->access,
248 isl_dim_out);
249 if (name && !strcmp(array->name, name))
250 n++;
254 array->n_ref = n;
255 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
256 assert(array->refs);
258 n = 0;
259 for (i = 0; i < prog->n_stmts; ++i) {
260 struct gpu_stmt *stmt = &prog->stmts[i];
261 struct gpu_stmt_access *access;
263 for (access = stmt->accesses; access; access = access->next) {
264 const char *name;
265 name = isl_map_get_tuple_name(access->access,
266 isl_dim_out);
267 if (!name || strcmp(array->name, name))
268 continue;
270 array->refs[n++] = access;
275 /* Create a gpu_array_tile for an array of dimension "n_index".
277 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
279 int i;
280 struct gpu_array_tile *tile;
282 tile = isl_calloc_type(ctx, struct gpu_array_tile);
283 assert(tile);
285 tile->n = n_index;
287 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
288 assert(tile->bound);
290 for (i = 0; i < n_index; ++i) {
291 tile->bound[i].size = NULL;
292 tile->bound[i].lb = NULL;
293 tile->bound[i].stride = NULL;
294 tile->bound[i].shift = NULL;
295 tile->bound[i].shift_map = NULL;
298 return tile;
301 static void *free_tile(struct gpu_array_tile *tile)
303 int j;
305 if (!tile)
306 return NULL;
308 for (j = 0; j < tile->n; ++j) {
309 isl_val_free(tile->bound[j].size);
310 isl_val_free(tile->bound[j].stride);
311 isl_aff_free(tile->bound[j].lb);
312 isl_aff_free(tile->bound[j].shift);
313 isl_basic_map_free(tile->bound[j].shift_map);
315 free(tile->bound);
316 isl_multi_aff_free(tile->tiling);
317 free(tile);
319 return NULL;
322 static struct pet_array *find_array(struct ppcg_scop *scop,
323 __isl_keep isl_set *accessed)
325 int i;
326 isl_id *id;
328 id = isl_set_get_tuple_id(accessed);
330 for (i = 0; i < scop->n_array; ++i) {
331 isl_id *id_i;
333 id_i = isl_set_get_tuple_id(scop->arrays[i]->extent);
334 isl_id_free(id_i);
335 if (id == id_i)
336 break;
338 isl_id_free(id);
340 return i < scop->n_array ? scop->arrays[i] : NULL;
343 /* Compute and return the extent of "array", taking into account the set of
344 * accessed elements.
346 * In particular, the extent in the outer dimension is taken
347 * from "accessed", while then extent in the remaing dimensions
348 * are taken from array->extent.
350 * The extent in the outer dimension cannot be taken from array->extent
351 * because that may be unbounded. Furthermore, even if it is bounded,
352 * it may be larger than the piece of the array that is being accessed.
354 static __isl_give isl_set *compute_extent(struct pet_array *array,
355 __isl_keep isl_set *accessed)
357 int n_index;
358 isl_id *id;
359 isl_set *outer;
360 isl_set *extent;
362 extent = isl_set_copy(array->extent);
364 n_index = isl_set_dim(accessed, isl_dim_set);
365 if (n_index == 0)
366 return extent;
368 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
369 outer = isl_set_copy(accessed);
370 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
371 extent = isl_set_flat_product(outer, extent);
372 id = isl_set_get_tuple_id(accessed);
373 extent = isl_set_set_tuple_id(extent, id);
375 return extent;
378 /* Compute bounds on the host arrays based on the accessed elements
379 * and collect all references to the array.
381 * If the array is zero-dimensional, i.e., a scalar, we check
382 * whether it is read-only.
384 static int extract_array_info(__isl_take isl_set *array, void *user)
386 int i;
387 struct gpu_prog *prog = (struct gpu_prog *)user;
388 const char *name;
389 int n_index;
390 isl_pw_aff **bounds;
391 struct pet_array *pa;
392 isl_set *extent;
394 n_index = isl_set_dim(array, isl_dim_set);
395 name = isl_set_get_tuple_name(array);
396 bounds = isl_alloc_array(isl_set_get_ctx(array),
397 isl_pw_aff *, n_index);
398 assert(bounds);
399 prog->array[prog->n_array].dim = isl_set_get_space(array);
400 prog->array[prog->n_array].name = strdup(name);
401 prog->array[prog->n_array].n_index = n_index;
402 prog->array[prog->n_array].bound = bounds;
404 pa = find_array(prog->scop, array);
405 assert(pa);
407 prog->array[prog->n_array].type = strdup(pa->element_type);
408 prog->array[prog->n_array].size = pa->element_size;
409 prog->array[prog->n_array].local = pa->declared && !pa->exposed;
411 if (n_index == 0) {
412 isl_set *space;
413 isl_union_map *write;
414 int empty;
416 write = isl_union_map_copy(prog->write);
417 space = isl_set_universe(isl_set_get_space(array));
418 write = isl_union_map_intersect_range(write,
419 isl_union_set_from_set(space));
420 empty = isl_union_map_is_empty(write);
421 isl_union_map_free(write);
423 prog->array[prog->n_array].read_only = empty;
426 extent = compute_extent(pa, array);
427 for (i = 0; i < n_index; ++i) {
428 isl_set *dom;
429 isl_local_space *ls;
430 isl_aff *one;
431 isl_pw_aff *bound;
433 bound = isl_set_dim_max(isl_set_copy(extent), i);
434 assert(bound);
435 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
436 ls = isl_local_space_from_space(isl_set_get_space(dom));
437 one = isl_aff_zero_on_domain(ls);
438 one = isl_aff_add_constant_si(one, 1);
439 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
440 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
442 bounds[i] = bound;
444 prog->array[prog->n_array].extent = extent;
446 collect_references(prog, &prog->array[prog->n_array]);
448 prog->n_array++;
450 isl_set_free(array);
451 return 0;
454 void collect_array_info(struct gpu_prog *prog)
456 isl_union_set *arrays;
458 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
459 arrays = isl_union_set_union(arrays,
460 isl_union_map_range(isl_union_map_copy(prog->write)));
461 arrays = isl_union_set_coalesce(arrays);
463 prog->n_array = isl_union_set_n_set(arrays);
464 prog->array = isl_alloc_array(prog->ctx,
465 struct gpu_array_info, prog->n_array);
466 assert(prog->array);
467 prog->n_array = 0;
468 isl_union_set_foreach_set(arrays, &extract_array_info, prog);
469 isl_union_set_free(arrays);
472 static void free_array_info(struct gpu_prog *prog)
474 int i, j;
476 for (i = 0; i < prog->n_array; ++i) {
477 int n_index = prog->array[i].n_index;
478 free(prog->array[i].type);
479 free(prog->array[i].name);
480 for (j = 0; j < n_index; ++j)
481 isl_pw_aff_free(prog->array[i].bound[j]);
482 isl_space_free(prog->array[i].dim);
483 isl_set_free(prog->array[i].extent);
484 free(prog->array[i].bound);
485 free(prog->array[i].refs);
487 free(prog->array);
490 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
491 * as an array or through a pointer reference, but as single data element. At
492 * the moment, scalars are represented as zero dimensional arrays.
494 int gpu_array_is_scalar(struct gpu_array_info *array)
496 return (array->n_index == 0);
499 /* Is "array" a read-only scalar?
501 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
503 return gpu_array_is_scalar(array) && array->read_only;
506 /* Internal data structure for extract_size_of_type.
507 * "type" specifies the name of the space that we want to extract.
508 * "res" is used to store the subset of that space.
510 struct ppcg_extract_size_data {
511 const char *type;
512 isl_set *res;
515 /* This function is called for each set in a union_set.
516 * If the name of the set matches data->type, we store the
517 * set in data->res.
519 static int extract_size_of_type(__isl_take isl_set *size, void *user)
521 struct ppcg_extract_size_data *data = user;
522 const char *name;
524 name = isl_set_get_tuple_name(size);
525 if (name && !strcmp(name, data->type)) {
526 data->res = size;
527 return -1;
530 isl_set_free(size);
531 return 0;
534 /* Given a union map { kernel[i] -> *[...] },
535 * return the range in the space called "type" for the kernel with
536 * sequence number "id".
538 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
539 const char *type, int id)
541 isl_space *space;
542 isl_set *dom;
543 isl_union_set *local_sizes;
544 struct ppcg_extract_size_data data = { type, NULL };
546 if (!sizes)
547 return NULL;
549 space = isl_union_map_get_space(sizes);
550 space = isl_space_set_from_params(space);
551 space = isl_space_add_dims(space, isl_dim_set, 1);
552 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
553 dom = isl_set_universe(space);
554 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
556 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
557 isl_union_map_copy(sizes));
558 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
559 isl_union_set_free(local_sizes);
560 return data.res;
563 /* Given a singleton set, extract the first (at most *len) elements
564 * of the single integer tuple into *sizes and update *len if needed.
566 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
568 int i;
569 int dim;
571 if (!set)
572 return;
574 dim = isl_set_dim(set, isl_dim_set);
575 if (dim < *len)
576 *len = dim;
578 for (i = 0; i < *len; ++i) {
579 isl_val *v;
581 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
582 assert(v);
584 sizes[i] = isl_val_get_num_si(v);
585 isl_val_free(v);
588 isl_set_free(set);
591 /* Extract user specified "tile" sizes from the "sizes" command line option,
592 * defaulting to option->tile_size in each dimension.
594 static void read_tile_sizes(struct gpu_gen *gen)
596 int n;
597 isl_set *size;
599 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
600 assert(gen->tile_size);
601 for (n = 0; n < gen->tile_len; ++n)
602 gen->tile_size[n] = gen->options->tile_size;
604 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
605 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
607 if (gen->n_parallel > gen->tile_len)
608 gen->n_parallel = gen->tile_len;
611 /* Extract user specified "block" sizes from the "sizes" command line option,
612 * after filling in some potentially useful defaults.
614 static void read_block_sizes(struct gpu_gen *gen)
616 int n;
617 isl_set *size;
619 n = gen->n_parallel;
620 gen->n_block = (n <= 3) ? n : 3;
621 switch (gen->n_block) {
622 case 1:
623 gen->block_dim[0] = 512;
624 break;
625 case 2:
626 gen->block_dim[0] = 32;
627 gen->block_dim[1] = 16;
628 break;
629 default:
630 gen->block_dim[0] = 32;
631 gen->block_dim[1] = 4;
632 gen->block_dim[2] = 4;
633 break;
636 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
637 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
640 /* Extract user specified "grid" sizes from the "sizes" command line option,
641 * after filling in some potentially useful defaults.
643 static void read_grid_sizes(struct gpu_gen *gen)
645 int n = gen->n_parallel;
646 isl_set *size;
648 gen->n_grid = (n <= 2) ? n : 2;
649 switch (gen->n_grid) {
650 case 1:
651 gen->grid_dim[0] = 32768;
652 break;
653 default:
654 gen->grid_dim[0] = 256;
655 gen->grid_dim[1] = 256;
656 break;
659 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
660 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
663 /* Extract user specified sizes from the "sizes" command line option
664 * after filling in some potentially useful defaults.
666 static void read_sizes(struct gpu_gen *gen)
668 read_tile_sizes(gen);
669 read_block_sizes(gen);
670 read_grid_sizes(gen);
673 static void *free_stmts(struct gpu_stmt *stmts, int n)
675 int i;
677 if (!stmts)
678 return NULL;
680 for (i = 0; i < n; ++i) {
681 struct gpu_stmt_access *access, *next;
683 for (access = stmts[i].accesses; access; access = next) {
684 next = access->next;
685 isl_id_free(access->ref_id);
686 isl_map_free(access->access);
687 free(access);
690 isl_id_free(stmts[i].id);
692 free(stmts);
694 return NULL;
697 /* Construct a map from a domain of dimensionality "len"
698 * to a domain of dimensionality "len" + "tile_len" that tiles
699 * the "tile_len" coordinates starting at "first".
700 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
701 * "dim" prescribes the parameters.
703 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
704 int first, int tile_len, int *tile_size)
706 int i;
707 isl_basic_map *bmap;
708 isl_constraint *c;
709 isl_local_space *ls;
711 dim = isl_space_add_dims(dim, isl_dim_in, len);
712 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
713 bmap = isl_basic_map_universe(isl_space_copy(dim));
714 ls = isl_local_space_from_space(dim);
716 for (i = 0; i < len - tile_len; ++i) {
717 int j = i < first ? i : i + tile_len;
718 int k = i < first ? i : i + 2 * tile_len;
720 c = isl_equality_alloc(isl_local_space_copy(ls));
721 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
722 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
723 bmap = isl_basic_map_add_constraint(bmap, c);
726 for (i = 0; i < tile_len; ++i) {
727 c = isl_equality_alloc(isl_local_space_copy(ls));
728 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
729 first + i, -1);
730 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
731 first + i, tile_size[i]);
732 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
733 first + i + tile_len, 1);
734 bmap = isl_basic_map_add_constraint(bmap, c);
736 c = isl_inequality_alloc(isl_local_space_copy(ls));
737 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
738 first + i + tile_len, 1);
739 bmap = isl_basic_map_add_constraint(bmap, c);
741 c = isl_inequality_alloc(isl_local_space_copy(ls));
742 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
743 first + i + tile_len, -1);
744 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
745 bmap = isl_basic_map_add_constraint(bmap, c);
748 isl_local_space_free(ls);
750 return isl_map_from_basic_map(bmap);
753 /* Construct a map from a domain of dimensionality "len"
754 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
755 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
756 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
757 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
758 * that are projected out at the end.
759 * "dim" prescribes the parameters.
761 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
762 int first, int wrap_len, int *wrap_size)
764 int i;
765 isl_basic_map *bmap;
766 isl_constraint *c;
767 isl_local_space *ls;
769 dim = isl_space_add_dims(dim, isl_dim_in, len);
770 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
771 bmap = isl_basic_map_universe(isl_space_copy(dim));
772 ls = isl_local_space_from_space(dim);
774 for (i = 0; i < len; ++i) {
775 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
777 c = isl_equality_alloc(isl_local_space_copy(ls));
778 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
779 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
780 bmap = isl_basic_map_add_constraint(bmap, c);
783 for (i = 0; i < wrap_len; ++i) {
784 c = isl_equality_alloc(isl_local_space_copy(ls));
785 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
786 first + i, -1);
787 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
788 first + wrap_len + i, 1);
789 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
790 first + 2 * wrap_len + i, wrap_size[i]);
791 bmap = isl_basic_map_add_constraint(bmap, c);
793 c = isl_inequality_alloc(isl_local_space_copy(ls));
794 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
795 first + wrap_len + i, 1);
796 bmap = isl_basic_map_add_constraint(bmap, c);
798 c = isl_inequality_alloc(isl_local_space_copy(ls));
799 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
800 first + wrap_len + i, -1);
801 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
802 bmap = isl_basic_map_add_constraint(bmap, c);
805 isl_local_space_free(ls);
807 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
808 first + 2 * wrap_len, wrap_len);
810 return isl_map_from_basic_map(bmap);
813 /* Add "n" parameters named prefix%d.
815 static __isl_give isl_set *add_params( __isl_take isl_set *set,
816 int n, const char *prefix)
818 int i;
819 unsigned nparam;
820 char name[20];
822 nparam = isl_set_dim(set, isl_dim_param);
823 set = isl_set_add_dims(set, isl_dim_param, n);
825 for (i = 0; i < n; ++i) {
826 snprintf(name, sizeof(name), "%s%d", prefix, i);
827 set = isl_set_set_dim_name(set, isl_dim_param,
828 nparam + i, name);
831 return set;
834 /* Equate the "n" dimensions of "set" starting at "first" to
835 * freshly created parameters named prefix%d.
837 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
838 int first, int n, const char *prefix)
840 int i;
841 unsigned nparam;
843 nparam = isl_set_dim(set, isl_dim_param);
845 set = add_params(set, n, prefix);
847 for (i = 0; i < n; ++i)
848 set = isl_set_equate(set, isl_dim_param, nparam + i,
849 isl_dim_set, first + i);
851 return set;
854 /* Given a parameter space "space", create a set of dimension "len"
855 * of which the "n" dimensions starting at "first" are equated to
856 * freshly created parameters named prefix%d.
858 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
859 int len, int first, int n, const char *prefix)
861 isl_set *set;
863 space = isl_space_set_from_params(space);
864 space = isl_space_add_dims(space, isl_dim_set, len);
865 set = isl_set_universe(space);
867 return parametrize(set, first, n, prefix);
870 /* Tile the B loops over the tile sizes and then tile/wrap
871 * the T1 loops over the blocks.
873 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
874 __isl_take isl_union_map *sched)
876 isl_space *dim;
877 isl_map *tiling, *block_tiling;
879 dim = isl_union_map_get_space(sched);
880 tiling = tile(isl_space_copy(dim), gen->untiled_len,
881 gen->tile_first, gen->tile_len, gen->tile_size);
883 if (gen->options->wrap)
884 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
885 gen->tile_first, gen->n_grid, gen->grid_dim);
886 else
887 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
888 gen->tile_first, gen->n_grid, gen->grid_dim);
890 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
892 tiling = isl_map_apply_range(tiling, block_tiling);
894 sched = isl_union_map_apply_range(sched,
895 isl_union_map_from_map(tiling));
897 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
899 return sched;
902 /* Equate the "T1P" iterators in the tiled schedule "sched"
903 * to the block dimensions.
905 static __isl_give isl_union_map *parametrize_tiled_schedule(
906 struct gpu_gen *gen, __isl_take isl_union_map *sched)
908 isl_space *dim;
909 isl_set *par;
911 dim = isl_union_map_get_space(sched);
912 par = parametrization(dim, gen->tiled_len,
913 gen->tile_first + gen->n_grid, gen->n_grid, "b");
914 sched = isl_union_map_intersect_range(sched,
915 isl_union_set_from_set(par));
917 return sched;
920 /* Tile/wrap the P1 loops over the threads.
922 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
923 __isl_take isl_union_map *sched)
925 isl_space *dim;
926 isl_map *tiling;
927 isl_set *par;
929 dim = isl_union_map_get_space(sched);
931 if (gen->options->wrap)
932 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
933 gen->shared_len, gen->n_block, gen->block_dim);
934 else
935 tiling = tile(isl_space_copy(dim), gen->tiled_len,
936 gen->shared_len, gen->n_block, gen->block_dim);
937 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
939 sched = isl_union_map_apply_range(sched,
940 isl_union_map_from_map(tiling));
942 par = parametrization(dim, gen->thread_tiled_len,
943 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
944 gen->n_block, "t");
945 sched = isl_union_map_intersect_range(sched,
946 isl_union_set_from_set(par));
948 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
950 return sched;
953 /* If the user asked for it, scale the shared memory tile loops
954 * (T1T and T2) of "sched" by gen->tile_size[i].
955 * If we are not performing "wrapping", then additionally scale the T1P
956 * loops by gen->grid_dim[i].
958 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
959 __isl_take isl_union_map *sched)
961 int i;
962 isl_space *dim;
963 isl_basic_map *scale;
964 isl_constraint *c;
965 isl_local_space *ls;
967 if (!gen->options->scale_tile_loops)
968 return sched;
970 dim = isl_union_map_get_space(sched);
971 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
972 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
973 scale = isl_basic_map_universe(isl_space_copy(dim));
974 ls = isl_local_space_from_space(dim);
976 for (i = 0; i < gen->tiled_len; ++i) {
977 int f = 1;
979 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
980 f = gen->tile_size[i - gen->tile_first];
981 if (!gen->options->wrap)
982 f *= gen->grid_dim[i - gen->tile_first];
983 } else if (i >= gen->tile_first + gen->n_grid &&
984 i < gen->tile_first + gen->n_grid + gen->tile_len) {
985 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
988 c = isl_equality_alloc(isl_local_space_copy(ls));
989 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
990 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
991 scale = isl_basic_map_add_constraint(scale, c);
994 isl_local_space_free(ls);
996 sched = isl_union_map_apply_range(sched,
997 isl_union_map_from_map(isl_map_from_basic_map(scale)));
999 return sched;
1002 /* If we are not performing "wrapping" and if the user asked for it,
1003 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1005 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1006 __isl_take isl_union_map *sched)
1008 int i;
1009 isl_space *dim;
1010 isl_basic_map *scale;
1011 isl_constraint *c;
1012 isl_local_space *ls;
1014 if (gen->options->wrap)
1015 return sched;
1016 if (!gen->options->scale_tile_loops)
1017 return sched;
1019 dim = isl_union_map_get_space(sched);
1020 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1021 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1022 scale = isl_basic_map_universe(isl_space_copy(dim));
1023 ls = isl_local_space_from_space(dim);
1025 for (i = 0; i < gen->thread_tiled_len; ++i) {
1026 int f = 1;
1028 if (i >= gen->shared_len &&
1029 i < gen->shared_len + gen->n_block)
1030 f = gen->block_dim[i - gen->shared_len];
1032 c = isl_equality_alloc(isl_local_space_copy(ls));
1033 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1034 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1035 scale = isl_basic_map_add_constraint(scale, c);
1038 isl_local_space_free(ls);
1040 sched = isl_union_map_apply_range(sched,
1041 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1043 return sched;
1046 /* If we are not performing "wrapping" and if the user asked for it,
1047 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1049 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1050 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1052 int i;
1053 isl_space *dim;
1054 isl_basic_map *scale;
1055 isl_constraint *c;
1056 isl_local_space *ls;
1058 if (gen->options->wrap)
1059 return sched;
1060 if (!gen->options->scale_tile_loops)
1061 return sched;
1063 dim = isl_union_map_get_space(sched);
1064 dim = isl_space_add_dims(dim, isl_dim_in, len);
1065 dim = isl_space_add_dims(dim, isl_dim_out, len);
1066 scale = isl_basic_map_universe(isl_space_copy(dim));
1067 ls = isl_local_space_from_space(dim);
1069 for (i = 0; i < len; ++i) {
1070 int f = 1;
1072 if (i >= first && i < first + n_tile)
1073 f = gen->kernel->block_dim[i - first];
1075 c = isl_equality_alloc(isl_local_space_copy(ls));
1076 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1077 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1078 scale = isl_basic_map_add_constraint(scale, c);
1081 isl_local_space_free(ls);
1083 sched = isl_union_map_apply_range(sched,
1084 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1086 return sched;
1089 /* Add "len" parameters p[i] called prefix%d,
1090 * with bounds to 0 <= p[i] < size[i].
1092 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1093 int len, int *size, const char *prefix)
1095 int i;
1096 unsigned nparam;
1097 isl_space *dim;
1098 isl_basic_set *bset;
1099 isl_constraint *c;
1100 isl_local_space *ls;
1101 char name[20];
1103 nparam = isl_set_dim(set, isl_dim_param);
1104 set = isl_set_add_dims(set, isl_dim_param, len);
1106 for (i = 0; i < len; ++i) {
1107 snprintf(name, sizeof(name), "%s%d", prefix, i);
1108 set = isl_set_set_dim_name(set, isl_dim_param,
1109 nparam + i, name);
1112 dim = isl_set_get_space(set);
1113 bset = isl_basic_set_universe(isl_space_copy(dim));
1114 ls = isl_local_space_from_space(dim);
1116 for (i = 0; i < len; ++i) {
1117 c = isl_inequality_alloc(isl_local_space_copy(ls));
1118 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1119 nparam + i, 1);
1120 bset = isl_basic_set_add_constraint(bset, c);
1122 c = isl_inequality_alloc(isl_local_space_copy(ls));
1123 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1124 nparam + i, -1);
1125 c = isl_constraint_set_constant_si(c, size[i] - 1);
1126 bset = isl_basic_set_add_constraint(bset, c);
1129 isl_local_space_free(ls);
1131 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1134 /* Add "len" parameters p[i] called prefix%d,
1135 * with bounds to 0 <= p[i] < size[i].
1137 static __isl_give isl_set *add_bounded_parameters_dynamic(
1138 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1139 const char *prefix)
1141 int i, len;
1142 unsigned nparam;
1143 isl_space *space;
1144 isl_local_space *ls;
1145 char name[20];
1147 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1148 nparam = isl_set_dim(set, isl_dim_param);
1149 set = isl_set_add_dims(set, isl_dim_param, len);
1151 for (i = 0; i < len; ++i) {
1152 snprintf(name, sizeof(name), "%s%d", prefix, i);
1153 set = isl_set_set_dim_name(set, isl_dim_param,
1154 nparam + i, name);
1157 space = isl_space_params(isl_set_get_space(set));
1158 ls = isl_local_space_from_space(space);
1159 for (i = 0; i < len; ++i) {
1160 isl_pw_aff *param, *size_i, *zero;
1161 isl_set *bound;
1163 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1164 isl_dim_param, nparam + i);
1166 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1167 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1168 set = isl_set_intersect_params(set, bound);
1170 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1171 bound = isl_pw_aff_ge_set(param, zero);
1172 set = isl_set_intersect_params(set, bound);
1174 isl_local_space_free(ls);
1176 return set;
1179 /* Construct a map from an access to group->array to the corresponding
1180 * shared/private memory tile.
1181 * The map is of the form
1183 * { [D[i] -> A[a]] -> T[t] }
1185 * where D represents the initial shared_len dimensions
1186 * of the computed schedule.
1188 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1190 struct gpu_array_tile *tile;
1191 isl_multi_aff *tiling;
1193 tile = group->private_tile;
1194 if (!tile)
1195 tile = group->shared_tile;
1197 tiling = isl_multi_aff_copy(tile->tiling);
1199 return isl_map_from_multi_aff(tiling);
1202 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1204 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1205 unsigned pos)
1207 isl_val *v;
1208 int fixed;
1210 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1211 if (!v)
1212 return -1;
1213 fixed = isl_val_is_int(v);
1214 isl_val_free(v);
1216 return fixed;
1219 /* Given a schedule that iterates over all elements in a piece of an array,
1220 * perform tiling/wrapping over the threads.
1222 * In particular, we tile the final iterators so that the final thread
1223 * dimension runs over the final array dimension.
1224 * However, if those final iterators have only a single iteration,
1225 * we try to tile earlier iterators instead.
1227 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1228 __isl_take isl_map *sched)
1230 isl_space *dim;
1231 isl_union_map *usched;
1232 isl_map *tiling;
1233 isl_set *par;
1234 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1235 int n_tile;
1236 int first;
1238 n_tile = gen->kernel->n_block;
1239 if (n_tile > nvar) {
1240 int i;
1241 sched = isl_map_insert_dims(sched,
1242 isl_dim_out, 0, n_tile - nvar);
1243 for (i = 0; i < n_tile - nvar; ++i)
1244 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1245 nvar = n_tile;
1248 first = nvar - n_tile;
1250 for (; first > 0; first --)
1251 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1252 break;
1254 dim = isl_map_get_space(sched);
1255 dim = isl_space_params(dim);
1256 if (gen->options->wrap)
1257 tiling = wrap(isl_space_copy(dim), nvar, first,
1258 n_tile, gen->kernel->block_dim);
1259 else
1260 tiling = tile(isl_space_copy(dim), nvar, first,
1261 n_tile, gen->kernel->block_dim);
1262 sched = isl_map_apply_range(sched, tiling);
1264 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1265 sched = isl_map_intersect_range(sched, par);
1267 usched = isl_union_map_from_map(sched);
1268 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1269 first, n_tile);
1270 sched = isl_map_from_union_map(usched);
1272 return sched;
1275 /* Return the union of all read (read = 1) and/or write (write = 1)
1276 * access relations in the group.
1278 static __isl_give isl_union_map *group_access_relation(
1279 struct gpu_array_ref_group *group, int read, int write)
1281 int i;
1282 isl_union_map *access;
1284 access = isl_union_map_empty(isl_map_get_space(group->access));
1285 for (i = 0; i < group->n_ref; ++i) {
1286 isl_map *map_i;
1288 if (!((read && group->refs[i]->read) ||
1289 (write && group->refs[i]->write)))
1290 continue;
1291 map_i = isl_map_copy(group->refs[i]->access);
1292 access = isl_union_map_union(access,
1293 isl_union_map_from_map(map_i));
1296 return access;
1299 /* Return the extent of "array", recomputed from the bounds.
1300 * The recomputed extent may be simpler than the original extent.
1302 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1304 int i;
1305 isl_id *id;
1306 isl_space *space;
1307 isl_local_space *ls;
1308 isl_set *extent;
1310 id = isl_set_get_tuple_id(array->extent);
1311 space = isl_set_get_space(array->extent);
1312 extent = isl_set_universe(isl_space_copy(space));
1313 ls = isl_local_space_from_space(space);
1314 for (i = 0; i < array->n_index; ++i) {
1315 isl_pw_aff *bound;
1316 isl_aff *aff;
1317 isl_pw_aff *index;
1318 isl_set *lt;
1320 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1322 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1323 isl_dim_set, i);
1324 index = isl_pw_aff_from_aff(aff);
1325 bound = isl_pw_aff_copy(array->bound[i]);
1326 bound = isl_pw_aff_from_range(bound);
1327 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1328 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1329 isl_id_copy(id));
1330 lt = isl_pw_aff_lt_set(index, bound);
1331 extent = isl_set_intersect(extent, lt);
1333 isl_local_space_free(ls);
1334 isl_id_free(id);
1336 return extent;
1339 /* Return a map from the first shared_len dimensions of the computed
1340 * schedule to the array tile in
1341 * global memory that corresponds to the shared memory copy.
1343 * In particular, return a map
1345 * { D[i] -> A[a] }
1347 * with constraints
1349 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1351 * and
1353 * 0 <= a <= array_size - 1 (2)
1355 * Note that if some stride has been detected (i.e., when
1356 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1357 * to the shifted and scaled down version.
1359 * Constraints (1) are obtained by mapping the size constraints on the
1360 * shared/private memory tile back to the access relation.
1361 * Constraints (2) are obtained from the (recomputed) extent.
1363 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1365 int i;
1366 int n_index = group->array->n_index;
1367 isl_map *tile;
1368 isl_space *space;
1369 isl_set *local;
1370 isl_set *extent;
1372 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1373 space = isl_space_range(space);
1374 local = isl_set_universe(space);
1375 for (i = 0; i < n_index; ++i) {
1376 isl_val *bound;
1378 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1379 bound = isl_val_copy(group->shared_tile->bound[i].size);
1380 bound = isl_val_sub_ui(bound, 1);
1381 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1383 local = isl_set_preimage_multi_aff(local,
1384 isl_multi_aff_copy(group->shared_tile->tiling));
1385 tile = isl_set_unwrap(local);
1386 extent = array_extent(group->array);
1387 tile = isl_map_intersect_range(tile, extent);
1389 return tile;
1392 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1393 * return the corresponding mapping from the AST schedule to
1394 * to the first shared_len dimensions of the schedule computed by PPCG.
1396 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1397 __isl_take isl_pw_multi_aff *iterator_map)
1399 isl_union_map *umap;
1400 isl_space *space;
1401 isl_map *map, *sched;;
1403 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1404 space = isl_space_from_domain(space);
1405 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1407 umap = isl_union_map_copy(gen->shared_sched);
1408 umap = isl_union_map_apply_range(umap,
1409 isl_union_map_copy(gen->shared_proj));
1410 map = isl_union_map_extract_map(umap, space);
1411 isl_union_map_free(umap);
1413 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1414 sched = isl_map_detect_equalities(sched);
1416 return isl_pw_multi_aff_from_map(sched);
1419 /* Set unroll[j] if the input dimension j is involved in
1420 * the index expression represented by ma.
1422 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1423 void *user)
1425 int i, j;
1426 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1427 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1428 int *unroll = user;
1430 for (i = 0; i < n_out; ++i) {
1431 isl_aff *aff;
1433 aff = isl_multi_aff_get_aff(ma, i);
1434 for (j = 0; j < n_in; ++j)
1435 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1436 unroll[j] = 1;
1437 isl_aff_free(aff);
1440 isl_set_free(set);
1441 isl_multi_aff_free(ma);
1442 return 0;
1445 /* Given an array pos mapping input dimensions to the corresponding
1446 * output dimension, construct the corresponding map.
1448 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1449 int *pos, int len)
1451 int i;
1452 isl_constraint *c;
1453 isl_basic_map *bmap;
1454 isl_local_space *ls;
1456 dim = isl_space_add_dims(dim, isl_dim_in, len);
1457 dim = isl_space_add_dims(dim, isl_dim_out, len);
1458 bmap = isl_basic_map_universe(isl_space_copy(dim));
1459 ls = isl_local_space_from_space(dim);
1461 for (i = 0; i < len; ++i) {
1462 c = isl_equality_alloc(isl_local_space_copy(ls));
1463 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1464 -1);
1465 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1467 bmap = isl_basic_map_add_constraint(bmap, c);
1469 isl_local_space_free(ls);
1471 return isl_map_from_basic_map(bmap);
1474 /* Find all loops involved in any of the index expressions for any of
1475 * the private accesses, move them innermost and then mark them as
1476 * requiring unrolling by setting gen->first_unroll.
1477 * The loops involved should all be parallel because of the checks
1478 * we performed in check_private_group_access. Moving them innermost
1479 * is therefore a valid transformation.
1481 * Loops up to gen->shared_len are generated before the mapping to
1482 * threads is applied. They should therefore be ignored.
1484 * We compute the hidden equalities of the schedule first
1485 * since we will need them in our calls to isl_pw_multi_aff_from_map
1486 * and because we want to make sure that the same equalities
1487 * are also available to the code generator.
1489 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1490 __isl_take isl_union_map *sched)
1492 int i, j;
1493 int unroll[gen->thread_tiled_len];
1494 int perm[gen->thread_tiled_len];
1495 isl_space *dim;
1496 isl_map *permute;
1497 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1499 gen->first_unroll = -1;
1501 sched = isl_union_map_detect_equalities(sched);
1502 for (i = 0; i < gen->thread_tiled_len; ++i)
1503 unroll[i] = 0;
1504 for (i = 0; i < gen->prog->n_array; ++i) {
1505 struct gpu_array_info *array = &gen->prog->array[i];
1507 for (j = 0; j < array->n_group; ++j) {
1508 isl_union_map *access;
1509 isl_map *acc;
1510 isl_pw_multi_aff *pma;
1512 if (!array->groups[j]->private_tile)
1513 continue;
1515 access = group_access_relation(array->groups[j], 1, 1);
1516 access = isl_union_map_apply_domain(access,
1517 isl_union_map_copy(sched));
1519 acc = isl_map_from_union_map(access);
1520 pma = isl_pw_multi_aff_from_map(acc);
1521 isl_pw_multi_aff_foreach_piece(pma,
1522 &check_unroll, unroll);
1524 isl_pw_multi_aff_free(pma);
1528 for (i = gen->shared_len; i < len; ++i)
1529 if (unroll[i])
1530 break;
1532 if (i >= len)
1533 return sched;
1535 for (i = len; i < gen->thread_tiled_len; ++i)
1536 if (unroll[i])
1537 return sched;
1539 j = 0;
1540 for (i = 0; i < gen->shared_len; ++i)
1541 perm[i] = j++;
1542 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1543 if (!unroll[i])
1544 perm[i] = j++;
1545 gen->first_unroll = j - gen->shared_len;
1546 for (i = gen->shared_len; i < len; ++i)
1547 if (unroll[i])
1548 perm[i] = j++;
1550 dim = isl_union_map_get_space(sched);
1551 permute = permutation(dim, perm, gen->thread_tiled_len);
1552 sched = isl_union_map_apply_range(sched,
1553 isl_union_map_from_map(permute));
1555 return sched;
1558 /* Given a constraint
1560 * a(p,i) + j = g f(e)
1562 * or -a(p,i) - j = g f(e) if sign < 0,
1563 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1564 * a(p,i) is assumed to be an expression in only the parameters
1565 * and the input dimensions.
1567 static void extract_stride(__isl_keep isl_constraint *c,
1568 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1570 int i;
1571 isl_val *v;
1572 isl_space *space;
1573 unsigned nparam;
1574 unsigned nvar;
1575 isl_aff *aff;
1577 isl_val_free(bound->stride);
1578 bound->stride = isl_val_copy(stride);
1580 space = isl_constraint_get_space(c);
1581 space = isl_space_domain(space);
1583 nparam = isl_space_dim(space, isl_dim_param);
1584 nvar = isl_space_dim(space, isl_dim_set);
1586 v = isl_constraint_get_constant_val(c);
1587 if (sign < 0)
1588 v = isl_val_neg(v);
1589 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1590 aff = isl_aff_set_constant_val(aff, v);
1592 for (i = 0; i < nparam; ++i) {
1593 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1594 continue;
1595 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1596 if (sign < 0)
1597 v = isl_val_neg(v);
1598 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1601 for (i = 0; i < nvar; ++i) {
1602 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1603 continue;
1604 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1605 if (sign < 0)
1606 v = isl_val_neg(v);
1607 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1610 bound->shift = aff;
1613 /* Given an equality constraint of a map with a single output dimension j,
1614 * check if the constraint is of the form
1616 * a(p,i) + j = g f(e)
1618 * with a(p,i) an expression in the parameters and input dimensions
1619 * and f(e) an expression in the existentially quantified variables.
1620 * If so, and if g is larger than any such g from a previously considered
1621 * constraint, then call extract_stride to record the stride information
1622 * in bound.
1624 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1626 int i;
1627 isl_ctx *ctx;
1628 isl_val *v;
1629 unsigned n_div;
1630 struct gpu_array_bound *bound = user;
1632 ctx = isl_constraint_get_ctx(c);
1633 n_div = isl_constraint_dim(c, isl_dim_div);
1634 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1636 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1637 int s = isl_val_sgn(v);
1638 isl_val *stride = isl_val_zero(ctx);
1640 isl_val_free(v);
1641 for (i = 0; i < n_div; ++i) {
1642 v = isl_constraint_get_coefficient_val(c,
1643 isl_dim_div, i);
1644 stride = isl_val_gcd(stride, v);
1646 if (!isl_val_is_zero(stride) &&
1647 isl_val_gt(stride, bound->stride))
1648 extract_stride(c, bound, stride, s);
1650 isl_val_free(stride);
1651 } else
1652 isl_val_free(v);
1654 isl_constraint_free(c);
1655 return 0;
1658 /* Given contraints on an array index i, check if we can find
1659 * a shift a(p) and a stride g such that
1661 * a(p) + i = 0 mod g
1663 * If so, record the information in bound and apply the mapping
1664 * i -> (i + a(p))/g to the array index in bounds and return
1665 * the new constraints.
1666 * If not, simply return the original constraints.
1668 * If bounds is a subset of the space
1670 * D -> i
1672 * then the bound recorded in bound->shift is of the form
1674 * D -> s(D)
1676 * with s(D) equal to a(p) above.
1677 * The mapping recorded in bound->shift_map is of the form
1679 * [D -> i] -> [D -> (i + S(D))/g]
1681 * This mapping is computed as follows.
1682 * We first introduce "i" in the domain through precomposition
1683 * with [D -> i] -> D obtaining
1685 * [D -> i] -> s(D)
1687 * Adding [D -> i] -> i produces
1689 * [D -> i] -> i + s(D)
1691 * and the domain product with [D -> i] -> D yields
1693 * [D -> i] -> [D -> i + s(D)]
1695 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1697 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1698 __isl_take isl_basic_map *bounds)
1700 isl_space *space;
1701 isl_basic_map *hull;
1702 isl_basic_map *shift, *id, *bmap, *scale;
1703 isl_basic_set *bset;
1704 isl_aff *aff;
1706 bound->stride = NULL;
1708 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1710 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1712 isl_basic_map_free(hull);
1714 if (!bound->stride)
1715 return bounds;
1717 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1718 space = isl_basic_map_get_space(bounds);
1719 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1720 shift = isl_basic_map_apply_range(bmap, shift);
1721 space = isl_basic_map_get_space(bounds);
1722 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1723 shift = isl_basic_map_sum(id, shift);
1724 space = isl_basic_map_get_space(bounds);
1725 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1726 shift = isl_basic_map_range_product(id, shift);
1728 space = isl_space_domain(isl_basic_map_get_space(bounds));
1729 id = isl_basic_map_identity(isl_space_map_from_set(space));
1730 space = isl_space_range(isl_basic_map_get_space(bounds));
1731 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1732 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1733 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
1734 scale = isl_basic_map_from_aff(aff);
1735 scale = isl_basic_map_product(id, scale);
1737 bound->shift_map = isl_basic_map_apply_range(shift, scale);
1738 bmap = isl_basic_map_copy(bound->shift_map);
1739 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1740 bounds = isl_basic_set_unwrap(bset);
1742 return bounds;
1745 /* Data used in compute_array_dim_size and compute_size_in_direction.
1747 * pos is the position of the variable representing the array index,
1748 * i.e., the variable for which want to compute the size. This variable
1749 * is also the last variable in the set.
1751 struct gpu_size_info {
1752 isl_basic_set *bset;
1753 struct gpu_array_bound *bound;
1754 int pos;
1757 /* Given a constraint from the basic set describing the bounds on
1758 * an array index, check if it is a lower bound, say m i >= b(x), and,
1759 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
1760 * upper bound. If so, and if this bound is smaller than any bound
1761 * derived from earlier constraints, set the size to this bound on
1762 * the expression and the lower bound to ceil(b(x)/m).
1764 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
1766 struct gpu_size_info *size = user;
1767 unsigned nparam;
1768 unsigned n_div;
1769 isl_val *v;
1770 isl_aff *aff;
1771 isl_aff *lb;
1773 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
1774 n_div = isl_constraint_dim(c, isl_dim_div);
1776 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
1777 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
1778 isl_constraint_free(c);
1779 return 0;
1782 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
1783 aff = isl_aff_ceil(aff);
1785 lb = isl_aff_copy(aff);
1787 aff = isl_aff_neg(aff);
1788 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
1790 v = isl_basic_set_max_val(size->bset, aff);
1791 isl_aff_free(aff);
1793 if (isl_val_is_int(v)) {
1794 v = isl_val_add_ui(v, 1);
1795 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
1796 isl_val_free(size->bound->size);
1797 size->bound->size = isl_val_copy(v);
1798 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
1799 isl_aff_free(size->bound->lb);
1800 size->bound->lb = isl_aff_copy(lb);
1803 isl_val_free(v);
1804 isl_aff_free(lb);
1806 isl_constraint_free(c);
1808 return 0;
1811 /* Given a basic map "bounds" that maps parameters and input dimensions
1812 * to a single output dimension, look for an expression in the parameters
1813 * and input dimensions such that the range of the output dimension shifted
1814 * by this expression is a constant.
1816 * In particular, we currently only consider lower bounds on the output
1817 * dimension as candidate expressions.
1819 static int compute_array_dim_size(struct gpu_array_bound *bound,
1820 __isl_take isl_basic_map *bounds)
1822 struct gpu_size_info size;
1824 bounds = isl_basic_map_detect_equalities(bounds);
1825 bounds = check_stride(bound, bounds);
1827 bound->size = NULL;
1828 bound->lb = NULL;
1830 size.bound = bound;
1831 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
1832 size.bset = isl_basic_map_wrap(bounds);
1833 size.bset = isl_basic_set_flatten(size.bset);
1834 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
1835 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
1836 &size);
1837 isl_basic_set_free(size.bset);
1839 return bound->size ? 0 : -1;
1842 /* Check if we can find a memory tile for the given array
1843 * based on the given accesses, and if so, put the results in "tile".
1845 * We project the accesses on each index in turn and look for a parametric
1846 * offset such that the size is constant.
1848 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
1850 int i;
1852 for (i = 0; i < tile->n; ++i) {
1853 isl_map *access_i;
1854 isl_basic_map *hull;
1856 access_i = isl_map_copy(access);
1857 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
1858 access_i = isl_map_project_out(access_i, isl_dim_out,
1859 1, tile->n - (i + 1));
1860 access_i = isl_map_compute_divs(access_i);
1861 hull = isl_map_simple_hull(access_i);
1862 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
1863 return 0;
1866 return 1;
1869 /* Construct a map with input the shared tile loops and the loops that
1870 * will be wrapped around the threads that relates these later loops
1871 * to the thread indices and then projects them out.
1873 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
1875 isl_map *priv;
1876 isl_map *tiling;
1877 isl_map *proj;
1878 isl_set *par;
1879 isl_space *dim;
1881 dim = isl_union_map_get_space(gen->shared_sched);
1883 if (gen->options->wrap)
1884 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
1885 gen->shared_len, gen->n_block, gen->block_dim);
1886 else
1887 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
1888 gen->shared_len, gen->n_block, gen->block_dim);
1890 priv = tiling;
1892 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
1893 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1894 gen->n_block, "t");
1896 priv = isl_map_align_params(priv, isl_set_get_space(par));
1897 priv = isl_map_intersect_range(priv, par);
1899 dim = isl_map_get_space(priv);
1900 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
1901 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
1902 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
1903 gen->shared_len);
1905 priv = isl_map_apply_range(priv, proj);
1907 return priv;
1910 /* Construct a map from domain_dim to domain_dim that increments
1911 * the dimension at position "pos" and leaves all other dimensions
1912 * constant.
1914 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
1916 int i;
1917 int len = isl_space_dim(domain_dim, isl_dim_set);
1918 isl_space *dim;
1919 isl_basic_map *next;
1920 isl_local_space *ls;
1922 dim = isl_space_map_from_set(domain_dim);
1923 next = isl_basic_map_universe(isl_space_copy(dim));
1924 ls = isl_local_space_from_space(dim);
1926 for (i = 0; i < len; ++i) {
1927 isl_constraint *c;
1929 c = isl_equality_alloc(isl_local_space_copy(ls));
1930 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
1931 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1932 if (i == pos)
1933 c = isl_constraint_set_constant_si(c, 1);
1934 next = isl_basic_map_add_constraint(next, c);
1937 isl_local_space_free(ls);
1939 return isl_map_from_basic_map(next);
1942 /* Check if the given access is coalesced.
1943 * That is, check whether incrementing the dimension that will get
1944 * wrapped over the last thread index results in incrementing
1945 * the last array index.
1947 * This function is only called for access relations without reuse.
1949 static int access_is_coalesced(struct gpu_gen *gen,
1950 __isl_keep isl_union_map *access)
1952 isl_space *dim;
1953 isl_map *access_map;
1954 isl_map *next_thread_x;
1955 isl_map *next_element;
1956 isl_map *map;
1957 int coalesced;
1959 access = isl_union_map_copy(access);
1960 access = isl_union_map_apply_domain(access,
1961 isl_union_map_copy(gen->tiled_sched));
1962 access_map = isl_map_from_union_map(access);
1964 dim = isl_map_get_space(access_map);
1965 dim = isl_space_domain(dim);
1966 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
1968 dim = isl_map_get_space(access_map);
1969 dim = isl_space_range(dim);
1970 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
1972 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
1973 map = isl_map_apply_range(map, access_map);
1975 coalesced = isl_map_is_subset(map, next_element);
1977 isl_map_free(next_element);
1978 isl_map_free(map);
1980 return coalesced;
1983 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
1984 * dimensions of the computed schedule, check if it is bijective for
1985 * fixed values of the first gen->shared_len dimensions.
1986 * We perform this check by equating these dimensions to parameters.
1988 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
1990 int res;
1991 isl_set *par;
1992 isl_space *space;
1994 access = isl_map_copy(access);
1995 space = isl_space_params(isl_map_get_space(access));
1996 par = parametrization(space, gen->shared_len + gen->n_block,
1997 0, gen->shared_len, "s");
1998 access = isl_map_intersect_domain(access, par);
1999 res = isl_map_is_bijective(access);
2000 isl_map_free(access);
2002 return res;
2005 /* Look for the last shared tile loop that affects the offset of "tile"
2006 * and return the result.
2007 * If there is no such loop, then return the index of the loop
2008 * before the first shared tile loop, in particular gen->tile_first - 1.
2010 static int compute_tile_last_shared(struct gpu_gen *gen,
2011 struct gpu_array_tile *tile)
2013 int i, j;
2015 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2016 for (i = 0; i < tile->n; ++i) {
2017 isl_aff *lb;
2018 isl_aff *shift;
2020 lb = tile->bound[i].lb;
2021 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2022 break;
2024 shift = tile->bound[i].shift;
2025 if (!shift)
2026 continue;
2027 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2028 break;
2030 if (i < tile->n)
2031 break;
2034 return j;
2037 /* Look for the last shared tile loop that affects the offset of the
2038 * shared or private tile and store the result in group->last_shared.
2039 * If there is no such loop, then group->last_shared is set to a value
2040 * before the first shared tile loop, in particular gen->tile_first - 1.
2041 * If there is no tile defined on the array reference group,
2042 * then set group->last_shared to gen->shared_len - 1.
2044 static void set_last_shared(struct gpu_gen *gen,
2045 struct gpu_array_ref_group *group)
2047 struct gpu_array_tile *tile;
2049 group->last_shared = gen->shared_len - 1;
2051 tile = group->private_tile;
2052 if (!tile)
2053 tile = group->shared_tile;
2054 if (!tile)
2055 return;
2057 group->last_shared = compute_tile_last_shared(gen, tile);
2060 /* Compute a privatized copy of all access relations from reference groups that
2061 * are mapped to private memory and store the result in gen->privatization.
2063 static void compute_private_access(struct gpu_gen *gen)
2065 int i, j;
2066 isl_union_map *private;
2068 if (!gen->options->use_private_memory)
2069 return;
2071 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2073 for (i = 0; i < gen->prog->n_array; ++i) {
2074 struct gpu_array_info *array = &gen->prog->array[i];
2076 if (gpu_array_is_read_only_scalar(array))
2077 continue;
2079 for (j = 0; j < array->n_group; ++j) {
2080 if (!array->groups[j]->private_tile)
2081 continue;
2083 private = isl_union_map_union(private,
2084 group_access_relation(array->groups[j], 1, 1));
2088 if (isl_union_map_is_empty(private))
2089 isl_union_map_free(private);
2090 else {
2091 isl_union_map *priv;
2093 private = isl_union_map_apply_domain(private,
2094 isl_union_map_copy(gen->shared_sched));
2095 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2096 private = isl_union_map_apply_domain(private, priv);
2097 gen->private_access = private;
2101 /* Compute the size of the tile specified by "tile"
2102 * in number of elements and return the result.
2104 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2106 int i;
2107 isl_val *size;
2109 size = isl_val_one(ctx);
2111 for (i = 0; i < tile->n; ++i)
2112 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2114 return size;
2117 /* If max_shared_memory is not set to infinity (-1), then make
2118 * sure that the total amount of shared memory required by the
2119 * array reference groups mapped to shared memory is no larger
2120 * than this maximum.
2122 * We apply a greedy approach and discard (keep in global memory)
2123 * those groups that would result in a total memory size that
2124 * is larger than the maximum.
2126 static void check_shared_memory_bound(struct gpu_gen *gen)
2128 int i, j;
2129 isl_val *left, *size;
2131 if (gen->options->max_shared_memory < 0)
2132 return;
2134 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2136 for (i = 0; i < gen->prog->n_array; ++i) {
2137 struct gpu_array_info *array = &gen->prog->array[i];
2139 for (j = 0; j < array->n_group; ++j) {
2140 struct gpu_array_ref_group *group;
2142 group = array->groups[j];
2143 if (!group->shared_tile)
2144 continue;
2146 size = tile_size(gen->ctx, group->shared_tile);
2147 size = isl_val_mul_ui(size, array->size);
2149 if (isl_val_le(size, left)) {
2150 left = isl_val_sub(left, size);
2151 continue;
2153 isl_val_free(size);
2155 group->shared_tile = free_tile(group->shared_tile);
2159 isl_val_free(left);
2162 /* Given a description of an array tile "tile" and the "space"
2164 * { D -> A }
2166 * where D represents the first shared_len schedule dimensions
2167 * and A represents the array, construct an isl_multi_aff
2169 * { [D[i] -> A[a]] -> A'[a'] }
2171 * with A' a scaled down copy of A according to the shifts and strides
2172 * in "tile". In particular,
2174 * a' = (a + shift(i))/stride
2176 * "insert_array" represents
2178 * { [D -> A] -> D }
2180 * and is used to insert A into the domain of functions that only
2181 * reference D.
2183 static __isl_give isl_multi_aff *strided_tile(
2184 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2185 __isl_keep isl_multi_aff *insert_array)
2187 int i;
2188 isl_ctx *ctx;
2189 isl_multi_aff *shift;
2190 isl_multi_val *stride;
2191 isl_space *space2;
2192 isl_local_space *ls;
2193 isl_multi_aff *tiling;
2195 ctx = isl_space_get_ctx(space);
2196 space2 = isl_space_domain(isl_space_copy(space));
2197 ls = isl_local_space_from_space(space2);
2198 space2 = isl_space_range(isl_space_copy(space));
2199 stride = isl_multi_val_zero(space2);
2200 shift = isl_multi_aff_zero(isl_space_copy(space));
2202 for (i = 0; i < tile->n; ++i) {
2203 struct gpu_array_bound *bound = &tile->bound[i];
2204 isl_val *stride_i;
2205 isl_aff *shift_i;
2207 if (tile->bound[i].shift) {
2208 stride_i = isl_val_copy(bound->stride);
2209 shift_i = isl_aff_copy(bound->shift);
2210 } else {
2211 stride_i = isl_val_one(ctx);
2212 shift_i = isl_aff_zero_on_domain(
2213 isl_local_space_copy(ls));
2216 stride = isl_multi_val_set_val(stride, i, stride_i);
2217 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2219 isl_local_space_free(ls);
2221 shift = isl_multi_aff_pullback_multi_aff(shift,
2222 isl_multi_aff_copy(insert_array));
2224 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2225 tiling = isl_multi_aff_add(tiling, shift);
2226 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2228 return tiling;
2231 /* Compute a tiling for the array reference group "group".
2233 * The tiling is of the form
2235 * { [D[i] -> A[a]] -> T[t] }
2237 * where D represents the first shared_len schedule dimensions,
2238 * A represents the global array and T represents the shared or
2239 * private memory tile. The name of T is the name of the local
2240 * array.
2242 * If there is any stride in the accesses, then the mapping is
2244 * t = (a + shift(i))/stride - lb(i)
2246 * otherwise, it is simply
2248 * t = a - lb(i)
2250 static void compute_group_tiling(struct gpu_array_ref_group *group)
2252 int i;
2253 struct gpu_array_tile *tile;
2254 struct gpu_array_info *array = group->array;
2255 isl_space *space;
2256 isl_multi_aff *tiling, *lb, *insert_array;
2257 isl_printer *p;
2258 char *local_name;
2260 tile = group->private_tile;
2261 if (!tile)
2262 tile = group->shared_tile;
2263 if (!tile)
2264 return;
2266 space = isl_map_get_space(group->access);
2267 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2269 for (i = 0; i < tile->n; ++i)
2270 if (tile->bound[i].shift)
2271 break;
2273 if (i < tile->n)
2274 tiling = strided_tile(tile, space, insert_array);
2275 else
2276 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2278 lb = isl_multi_aff_zero(space);
2279 for (i = 0; i < tile->n; ++i) {
2280 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2281 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2283 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2285 tiling = isl_multi_aff_sub(tiling, lb);
2287 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2288 p = print_array_name(p, group);
2289 local_name = isl_printer_get_str(p);
2290 isl_printer_free(p);
2291 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2292 free(local_name);
2294 tile->tiling = tiling;
2297 /* Compute a tiling for all the array reference groups.
2299 static void compute_group_tilings(struct gpu_gen *gen)
2301 int i, j;
2303 for (i = 0; i < gen->prog->n_array; ++i) {
2304 struct gpu_array_info *array = &gen->prog->array[i];
2306 for (j = 0; j < array->n_group; ++j)
2307 compute_group_tiling(array->groups[j]);
2311 /* Fill up the groups array with singleton groups, i.e., one group
2312 * per reference, initializing the array, access, write, n_ref and refs fields.
2313 * In particular the access field is initialized to the scheduled
2314 * access relation of the array reference.
2316 * Return the number of elements initialized, i.e., the number of
2317 * active references in the current kernel.
2319 static int populate_array_references(struct gpu_array_info *array,
2320 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2322 int i;
2323 int n;
2324 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2326 n = 0;
2327 for (i = 0; i < array->n_ref; ++i) {
2328 isl_union_map *umap;
2329 isl_map *map;
2330 struct gpu_array_ref_group *group;
2331 struct gpu_stmt_access *access = array->refs[i];
2333 map = isl_map_copy(access->access);
2334 umap = isl_union_map_from_map(map);
2335 umap = isl_union_map_apply_domain(umap,
2336 isl_union_map_copy(sched));
2338 if (isl_union_map_is_empty(umap)) {
2339 isl_union_map_free(umap);
2340 continue;
2343 map = isl_map_from_union_map(umap);
2344 map = isl_map_detect_equalities(map);
2346 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2347 assert(group);
2348 group->array = array;
2349 group->access = map;
2350 group->write = access->write;
2351 group->refs = &array->refs[i];
2352 group->n_ref = 1;
2354 groups[n++] = group;
2357 return n;
2360 /* If group->n_ref == 1, then group->refs was set by
2361 * populate_array_references to point directly into
2362 * group->array->refs and should not be freed.
2363 * If group->n_ref > 1, then group->refs was set by join_groups
2364 * to point to a newly allocated array.
2366 static void free_array_ref_group(struct gpu_array_ref_group *group)
2368 if (!group)
2369 return;
2370 free_tile(group->shared_tile);
2371 free_tile(group->private_tile);
2372 isl_map_free(group->access);
2373 if (group->n_ref > 1)
2374 free(group->refs);
2375 free(group);
2378 /* Given a map where the input dimensions represent the tile loops,
2379 * eliminate the innermost of those that have a fixed value
2380 * until we reach one that does not (obviously) have a fixed value.
2382 static __isl_give isl_map *eliminate_fixed_inner_loops(
2383 __isl_take isl_map *access)
2385 int i, n;
2387 n = isl_map_dim(access, isl_dim_in);
2389 for (i = n - 1; i >= 0; --i) {
2390 if (!map_plain_is_fixed(access, isl_dim_in, i))
2391 break;
2392 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2394 return access;
2397 /* Check if the access relations of group1 and group2 overlap within
2398 * the innermost loop. In particular, ignore any inner dimension
2399 * with a fixed value.
2400 * The copying to and from shared memory will be performed within
2401 * the innermost actual loop so we are only allowed to consider
2402 * the dimensions up to that innermost loop while checking whether
2403 * two access relations overlap.
2405 static int accesses_overlap(struct gpu_array_ref_group *group1,
2406 struct gpu_array_ref_group *group2)
2408 int empty;
2409 isl_map *access1, *access2;
2411 access1 = isl_map_copy(group1->access);
2412 access1 = eliminate_fixed_inner_loops(access1);
2413 access2 = isl_map_copy(group2->access);
2414 access2 = eliminate_fixed_inner_loops(access2);
2415 access1 = isl_map_intersect(access1, access2);
2416 empty = isl_map_is_empty(access1);
2417 isl_map_free(access1);
2419 return !empty;
2422 /* Combine the given two groups into a single group, containing
2423 * the references of both groups.
2425 static struct gpu_array_ref_group *join_groups(
2426 struct gpu_array_ref_group *group1,
2427 struct gpu_array_ref_group *group2)
2429 int i;
2430 isl_ctx *ctx;
2431 struct gpu_array_ref_group *group;
2433 ctx = isl_map_get_ctx(group1->access);
2434 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2435 assert(group);
2436 group->array = group1->array;
2437 group->access = isl_map_union(isl_map_copy(group1->access),
2438 isl_map_copy(group2->access));
2439 group->write = group1->write || group2->write;
2440 group->n_ref = group1->n_ref + group2->n_ref;
2441 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2442 group->n_ref);
2443 assert(group->refs);
2444 for (i = 0; i < group1->n_ref; ++i)
2445 group->refs[i] = group1->refs[i];
2446 for (i = 0; i < group2->n_ref; ++i)
2447 group->refs[group1->n_ref + i] = group2->refs[i];
2449 return group;
2452 /* Combine the given two groups into a single group and free
2453 * the original two groups.
2455 static struct gpu_array_ref_group *join_groups_and_free(
2456 struct gpu_array_ref_group *group1,
2457 struct gpu_array_ref_group *group2)
2459 struct gpu_array_ref_group *group;
2461 group = join_groups(group1, group2);
2462 free_array_ref_group(group1);
2463 free_array_ref_group(group2);
2464 return group;
2467 /* Compute the private and/or shared memory tiles for the array
2468 * reference group "group" of array "array".
2470 * If the array is a read-only scalar or if the user requested
2471 * not to use shared or private memory, then we do not need to do anything.
2473 * We only try to compute a shared memory tile if there is any reuse
2474 * or if the access is not coalesced.
2476 * For computing a private memory tile, we also require that there is
2477 * some reuse. Moreover, we require that the access is private
2478 * to the thread. That is, we check that any given array element
2479 * is only accessed by a single thread.
2480 * We compute an access relation that maps the shared tile loop iterators
2481 * and the shared point loop iterators that will be wrapped over the
2482 * threads to the array elements.
2483 * We actually check that those iterators that will be wrapped
2484 * partition the array space. This check is stricter than necessary
2485 * since several iterations may be mapped onto the same thread
2486 * and then they could be allowed to access the same memory elements,
2487 * but our check does not allow this situation.
2489 * We also check that the index expression only depends on parallel
2490 * loops. That way, we can move those loops innermost and unroll them.
2491 * Again, we use a test that is stricter than necessary.
2492 * We actually check whether the index expression only depends
2493 * on the iterators that are wrapped over the threads.
2494 * These are necessarily parallel, but there may be more parallel loops.
2496 * Combining the injectivity of the first test with the single-valuedness
2497 * of the second test, we simply test for bijectivity.
2499 * If it turns out we can use registers, we compute the private memory
2500 * tile size using can_tile, after introducing a dependence
2501 * on the thread indices.
2503 static void compute_group_bounds_core(struct gpu_gen *gen,
2504 struct gpu_array_ref_group *group)
2506 isl_ctx *ctx = isl_space_get_ctx(group->array->dim);
2507 isl_union_map *access;
2508 int n_index = group->array->n_index;
2509 int no_reuse;
2510 isl_map *acc;
2511 int use_shared = gen->options->use_shared_memory;
2512 int use_private = gen->options->use_private_memory;
2514 if (!use_shared && !use_private)
2515 return;
2516 if (gpu_array_is_read_only_scalar(group->array))
2517 return;
2519 access = group_access_relation(group, 1, 1);
2520 no_reuse = isl_union_map_is_injective(access);
2522 if (use_shared && (!no_reuse || !access_is_coalesced(gen, access))) {
2523 group->shared_tile = create_tile(ctx, group->array->n_index);
2524 if (!can_tile(group->access, group->shared_tile))
2525 group->shared_tile = free_tile(group->shared_tile);
2528 if (!use_private || no_reuse) {
2529 isl_union_map_free(access);
2530 return;
2533 access = isl_union_map_apply_domain(access,
2534 isl_union_map_copy(gen->shared_sched));
2536 acc = isl_map_from_union_map(access);
2538 if (!access_is_bijective(gen, acc)) {
2539 isl_map_free(acc);
2540 return;
2543 group->private_tile = create_tile(gen->ctx, n_index);
2544 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2545 if (!can_tile(acc, group->private_tile))
2546 group->private_tile = free_tile(group->private_tile);
2548 isl_map_free(acc);
2551 /* Compute the private and/or shared memory tiles for the array
2552 * reference group "group" of array "array" and set last_shared.
2554 static void compute_group_bounds(struct gpu_gen *gen,
2555 struct gpu_array_ref_group *group)
2557 compute_group_bounds_core(gen, group);
2558 set_last_shared(gen, group);
2561 /* If two groups have overlapping access relations (as determined by
2562 * the "overlap" function) and if one of them involves a write,
2563 * then merge the two groups into one.
2564 * If "compute_bounds" is set, then call compute_group_bounds
2565 * on the merged groups.
2567 * Return the updated number of groups.
2569 static int group_writes(struct gpu_gen *gen,
2570 int n, struct gpu_array_ref_group **groups,
2571 int (*overlap)(struct gpu_array_ref_group *group1,
2572 struct gpu_array_ref_group *group2), int compute_bounds)
2574 int i, j;
2576 for (i = 0; i < n; ++i) {
2577 for (j = n - 1; j > i; --j) {
2578 if (!groups[i]->write && !groups[j]->write)
2579 continue;
2581 if (!overlap(groups[i], groups[j]))
2582 continue;
2584 groups[i] = join_groups_and_free(groups[i], groups[j]);
2585 if (compute_bounds)
2586 compute_group_bounds(gen, groups[i]);
2587 if (j != n - 1)
2588 groups[j] = groups[n - 1];
2589 n--;
2593 return n;
2596 /* If two groups have overlapping access relations (within the innermost
2597 * loop) and if one of them involves a write, then merge the two groups
2598 * into one.
2600 * Return the updated number of groups.
2602 static int group_overlapping_writes(struct gpu_gen *gen,
2603 int n, struct gpu_array_ref_group **groups)
2605 return group_writes(gen, n, groups, &accesses_overlap, 0);
2608 /* Check if the access relations of group1 and group2 overlap within
2609 * the outermost min(group1->last_shared, group2->last_shared) loops.
2611 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2612 struct gpu_array_ref_group *group2)
2614 int last_shared;
2615 int dim;
2616 int empty;
2617 isl_map *map_i, *map_j, *map;
2619 last_shared = group1->last_shared;
2620 if (group2->last_shared < last_shared)
2621 last_shared = group2->last_shared;
2622 map_i = isl_map_copy(group1->access);
2623 dim = isl_map_dim(map_i, isl_dim_in);
2624 map_i = isl_map_eliminate(map_i, isl_dim_in,
2625 last_shared + 1, dim - (last_shared + 1));
2626 map_j = isl_map_copy(group2->access);
2627 map_j = isl_map_eliminate(map_j, isl_dim_in,
2628 last_shared + 1, dim - (last_shared + 1));
2629 map = isl_map_intersect(map_i, map_j);
2630 empty = isl_map_is_empty(map);
2631 isl_map_free(map);
2633 return !empty;
2636 /* If two groups have overlapping access relations (within the outer
2637 * last_shared loops) and if one of them involves a write,
2638 * then merge the two groups into one.
2640 * Return the updated number of groups.
2642 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2643 struct gpu_array_ref_group **groups)
2645 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2648 /* Is the size of the tile specified by "tile" smaller than the sum of
2649 * the sizes of the tiles specified by "tile1" and "tile2"?
2651 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
2652 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2654 int smaller;
2655 isl_val *size, *size1, *size2;
2657 size = tile_size(ctx, tile);
2658 size1 = tile_size(ctx, tile1);
2659 size2 = tile_size(ctx, tile2);
2661 size = isl_val_sub(size, size1);
2662 size = isl_val_sub(size, size2);
2663 smaller = isl_val_is_neg(size);
2665 isl_val_free(size);
2667 return smaller;
2670 /* Given an initial grouping of array references and shared memory tiles
2671 * for each group that allows for a shared memory tile, merge two groups
2672 * if both have a shared memory tile, the merged group also has
2673 * a shared memory tile and the size of the tile for the merge group
2674 * is smaller than the sum of the tile sizes of the individual groups.
2676 * If merging two groups decreases the "last_shared" dimension of
2677 * one or both of the two groups, then we need to check for overlapping
2678 * writes again.
2680 * Return the number of groups after merging.
2682 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2683 struct gpu_array_info *array, int n,
2684 struct gpu_array_ref_group **groups)
2686 int i, j;
2687 int recompute_overlap = 0;
2688 isl_ctx *ctx = isl_space_get_ctx(array->dim);
2690 for (i = 0; i < n; ++i) {
2691 if (!groups[i]->shared_tile)
2692 continue;
2693 for (j = n - 1; j > i; --j) {
2694 isl_map *map;
2695 int empty;
2696 struct gpu_array_ref_group *group;
2698 if (!groups[j]->shared_tile)
2699 continue;
2701 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2702 isl_map_copy(groups[j]->access));
2703 empty = isl_map_is_empty(map);
2704 isl_map_free(map);
2706 if (empty)
2707 continue;
2709 group = join_groups(groups[i], groups[j]);
2710 compute_group_bounds(gen, group);
2711 if (!group->shared_tile ||
2712 !smaller_tile(ctx, group->shared_tile,
2713 groups[i]->shared_tile,
2714 groups[j]->shared_tile)) {
2715 free_array_ref_group(group);
2716 continue;
2719 if (group->last_shared < groups[i]->last_shared ||
2720 group->last_shared < groups[j]->last_shared)
2721 recompute_overlap = 1;
2722 free_array_ref_group(groups[i]);
2723 free_array_ref_group(groups[j]);
2724 groups[i] = group;
2725 if (j != n - 1)
2726 groups[j] = groups[n - 1];
2727 n--;
2731 if (recompute_overlap)
2732 n = group_last_shared_overlapping_writes(gen, n, groups);
2733 return n;
2736 /* Set array->n_group and array->groups to n and groups.
2738 * Additionally, set the "nr" field of each group
2739 * and the "group" field of each reference in each group.
2741 static void set_array_groups(struct gpu_array_info *array,
2742 int n, struct gpu_array_ref_group **groups)
2744 int i, j;
2746 array->n_group = n;
2747 array->groups = groups;
2749 for (i = 0; i < n; ++i) {
2750 groups[i]->nr = i;
2752 for (j = 0; j < groups[i]->n_ref; ++j)
2753 groups[i]->refs[j]->group = i;
2757 /* Group array references that should be considered together when
2758 * deciding whether to access them from private, shared or global memory.
2760 * In particular, if two array references overlap and if one of them
2761 * is a write, then the two references are grouped together.
2762 * We first perform an initial grouping based only on the access relation.
2763 * After computing shared and private memory tiles, we check for
2764 * overlapping writes again, but this time taking into account
2765 * the "last_shared" property.
2767 * Furthermore, if two groups admit a shared memory tile and if the
2768 * combination of the two also admits a shared memory tile, we merge
2769 * the two groups.
2771 static void group_array_references(struct gpu_gen *gen,
2772 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
2774 int i;
2775 int n;
2776 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2777 struct gpu_array_ref_group **groups;
2779 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
2780 array->n_ref);
2781 assert(groups);
2783 n = populate_array_references(array, sched, groups);
2785 n = group_overlapping_writes(gen, n, groups);
2787 for (i = 0; i < n; ++i)
2788 compute_group_bounds(gen, groups[i]);
2790 n = group_last_shared_overlapping_writes(gen, n, groups);
2792 n = group_common_shared_memory_tile(gen, array, n, groups);
2794 set_array_groups(array, n, groups);
2797 /* Take tiled_sched, project it onto the shared tile loops and
2798 * the loops that will be wrapped over the threads and
2799 * store the result in gen->shared_sched.
2800 * Also compute a projection that projects out the loops that will be
2801 * wrapped over the threads and store this projection in gen->shared_proj.
2803 static void compute_shared_sched(struct gpu_gen *gen)
2805 isl_space *dim;
2806 isl_map *proj;
2807 isl_set *par;
2808 isl_union_map *sched;
2810 sched = isl_union_map_copy(gen->tiled_sched);
2812 dim = isl_union_map_get_space(sched);
2813 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
2814 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
2816 dim = isl_union_map_get_space(sched);
2817 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
2819 gen->shared_sched = sched;
2820 gen->shared_proj = isl_union_map_from_map(proj);
2823 /* Group references of all arrays in the program.
2825 static void group_references(struct gpu_gen *gen)
2827 int i;
2828 isl_union_map *sched;
2830 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2831 isl_union_map_copy(gen->shared_proj));
2833 for (i = 0; i < gen->prog->n_array; ++i)
2834 group_array_references(gen, &gen->prog->array[i], sched);
2836 isl_union_map_free(sched);
2839 /* Free all array information that is local to the current kernel.
2841 static void free_local_array_info(struct gpu_gen *gen)
2843 int i, j;
2845 for (i = 0; i < gen->prog->n_array; ++i) {
2846 struct gpu_array_info *array = &gen->prog->array[i];
2848 for (j = 0; j < array->n_group; ++j)
2849 free_array_ref_group(array->groups[j]);
2850 free(array->groups);
2854 /* Compute the size of a bounding box around the origin and "set",
2855 * where "set" is assumed to contain only non-negative elements.
2856 * In particular, compute the maximal value of "set" in each direction
2857 * and add one.
2859 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
2860 __isl_keep isl_set *context)
2862 int i, n;
2863 isl_multi_pw_aff *mpa;
2865 n = isl_set_dim(set, isl_dim_set);
2866 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
2867 for (i = 0; i < n; ++i) {
2868 isl_space *space;
2869 isl_aff *one;
2870 isl_pw_aff *bound;
2872 bound = isl_set_dim_max(isl_set_copy(set), i);
2873 bound = isl_pw_aff_coalesce(bound);
2874 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
2876 space = isl_pw_aff_get_domain_space(bound);
2877 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2878 one = isl_aff_add_constant_si(one, 1);
2879 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
2880 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
2882 isl_set_free(set);
2884 return mpa;
2887 /* Compute the effective grid size as a list of the sizes in each dimension.
2889 * The grid size specified by the user or set by default
2890 * in read_grid_sizes() and applied in tile_schedule(),
2891 * may be too large for the given code in the sense that
2892 * it may contain blocks that don't need to execute anything.
2893 * We therefore don't return this grid size, but instead the
2894 * smallest grid size that ensures that all blocks that actually
2895 * execute code are included in the grid.
2897 * We first extract a description of the grid, i.e., the possible values
2898 * of the block ids, from gen->tiled_sched.
2899 * The block ids are parameters in gen->tiled_sched.
2900 * We simply need to change them into set dimensions.
2902 * Then, for each block dimension, we compute the maximal value of the block id
2903 * and add one.
2905 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
2906 struct ppcg_kernel *kernel)
2908 int i;
2909 isl_set *grid;
2911 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
2912 grid = isl_set_from_params(grid);
2913 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
2914 for (i = 0; i < gen->n_grid; ++i) {
2915 int pos;
2916 char name[20];
2918 snprintf(name, sizeof(name), "b%d", i);
2919 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
2920 assert(pos >= 0);
2921 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
2922 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
2925 return extract_size(grid, kernel->context);
2928 /* Compute the size of a fixed bounding box around the origin and "set",
2929 * where "set" is assumed to contain only non-negative elements,
2930 * and store the results in "size".
2931 * In particular, compute the maximal value of "set" in each direction
2932 * and add one.
2934 static void extract_fixed_size(__isl_take isl_set *set, int *size)
2936 int i, n;
2937 isl_local_space *ls;
2938 isl_aff *obj;
2940 n = isl_set_dim(set, isl_dim_set);
2941 ls = isl_local_space_from_space(isl_set_get_space(set));
2942 obj = isl_aff_zero_on_domain(ls);
2943 for (i = 0; i < n; ++i) {
2944 isl_val *max;
2946 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
2947 max = isl_set_max_val(set, obj);
2948 size[i] = isl_val_get_num_si(max) + 1;
2949 isl_val_free(max);
2950 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
2952 isl_aff_free(obj);
2953 isl_set_free(set);
2956 /* Compute the effective block size as a list of the sizes in each dimension
2957 * and store the sizes in kernel->block_dim.
2959 * The block size specified by the user or set by default
2960 * in read_block_sizes() and applied in thread_tile_schedule(),
2961 * may be too large for the given code in the sense that
2962 * it may contain threads that don't need to execute anything.
2963 * We therefore don't store this block size in kernel->block_dim,
2964 * but instead the smallest block size that ensures that all threads
2965 * that actually execute code are included in the block.
2967 * The current implementation eliminates all parameters, ensuring
2968 * that the size is a fixed constant in each dimension.
2969 * In principle we could also compute parametric sizes.
2970 * We would have to make sure to project out all b%d and t%d parameters,
2971 * however.
2973 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
2975 int i;
2976 int nparam;
2977 isl_set *block;
2978 isl_multi_pw_aff *mpa;
2980 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
2981 block = isl_set_from_params(block);
2982 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
2983 kernel->n_block = gen->n_block;
2984 for (i = 0; i < gen->n_block; ++i) {
2985 int pos;
2986 char name[20];
2988 snprintf(name, sizeof(name), "t%d", i);
2989 pos = isl_set_find_dim_by_name(block, isl_dim_param, name);
2990 assert(pos >= 0);
2991 block = isl_set_equate(block, isl_dim_param, pos,
2992 isl_dim_set, i);
2994 nparam = isl_set_dim(block, isl_dim_param);
2995 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
2997 extract_fixed_size(block, kernel->block_dim);
3000 void ppcg_kernel_free(void *user)
3002 struct ppcg_kernel *kernel = user;
3003 int i;
3005 if (!kernel)
3006 return;
3008 isl_multi_pw_aff_free(kernel->grid_size);
3009 isl_set_free(kernel->context);
3010 isl_union_set_free(kernel->arrays);
3011 isl_space_free(kernel->space);
3012 isl_ast_node_free(kernel->tree);
3014 for (i = 0; i < kernel->n_array; ++i)
3015 isl_pw_aff_list_free(kernel->array[i].bound);
3016 free(kernel->array);
3018 for (i = 0; i < kernel->n_var; ++i) {
3019 free(kernel->var[i].name);
3020 isl_vec_free(kernel->var[i].size);
3022 free(kernel->var);
3024 free(kernel);
3027 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3028 struct ppcg_kernel_var *var)
3030 int j;
3031 struct gpu_array_tile *tile;
3032 isl_printer *p;
3033 char *name;
3035 var->array = group->array;
3037 tile = group->private_tile;
3038 var->type = ppcg_access_private;
3039 if (!tile) {
3040 tile = group->shared_tile;
3041 var->type = ppcg_access_shared;
3044 p = isl_printer_to_str(ctx);
3045 p = print_array_name(p, group);
3046 var->name = isl_printer_get_str(p);
3047 isl_printer_free(p);
3049 var->size = isl_vec_alloc(ctx, group->array->n_index);
3051 for (j = 0; j < group->array->n_index; ++j)
3052 var->size = isl_vec_set_element_val(var->size, j,
3053 isl_val_copy(tile->bound[j].size));
3056 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3058 int i, j, n;
3060 n = 0;
3061 for (i = 0; i < gen->prog->n_array; ++i) {
3062 struct gpu_array_info *array = &gen->prog->array[i];
3064 for (j = 0; j < array->n_group; ++j) {
3065 struct gpu_array_ref_group *group = array->groups[j];
3066 if (group->private_tile || group->shared_tile)
3067 ++n;
3071 kernel->n_var = n;
3072 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3073 assert(kernel->var);
3075 n = 0;
3076 for (i = 0; i < gen->prog->n_array; ++i) {
3077 struct gpu_array_info *array = &gen->prog->array[i];
3079 for (j = 0; j < array->n_group; ++j) {
3080 struct gpu_array_ref_group *group = array->groups[j];
3081 if (!group->private_tile && !group->shared_tile)
3082 continue;
3083 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3084 ++n;
3089 /* The sizes of the arrays on the host that have been computed by
3090 * extract_array_info may depend on the parameters. Use the extra
3091 * constraints on the parameters that are valid at "host_domain"
3092 * to simplify these expressions and store the results in kernel->array.
3094 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3095 __isl_keep isl_set *host_domain)
3097 int i, j;
3098 isl_set *context;
3100 kernel->array = isl_calloc_array(gen->ctx,
3101 struct gpu_local_array_info, gen->prog->n_array);
3102 assert(kernel->array);
3103 kernel->n_array = gen->prog->n_array;
3105 context = isl_set_copy(host_domain);
3106 context = isl_set_params(context);
3108 for (i = 0; i < gen->prog->n_array; ++i) {
3109 struct gpu_array_info *array = &gen->prog->array[i];
3110 isl_pw_aff_list *local;
3112 if (array->n_group == 0)
3113 continue;
3115 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3117 for (j = 0; j < array->n_index; ++j) {
3118 isl_pw_aff *pwaff;
3120 pwaff = isl_pw_aff_copy(array->bound[j]);
3121 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3122 local = isl_pw_aff_list_add(local, pwaff);
3125 kernel->array[i].bound = local;
3127 isl_set_free(context);
3130 /* Find the element in gen->stmt that has the given "id".
3131 * Return NULL if no such gpu_stmt can be found.
3133 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3135 int i;
3137 for (i = 0; i < prog->n_stmts; ++i) {
3138 if (id == prog->stmts[i].id)
3139 break;
3142 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3145 /* Set gen->tile_len and gen->n_parallel to those of the statement
3146 * affected by the first map (part of the schedule)
3147 * on which this function is called.
3148 * Because of the way the schedule is constructed, the other statements
3149 * in the list, if any, should have the same values for these properties.
3151 static int extract_tile_len(__isl_take isl_map *map, void *user)
3153 struct gpu_gen *gen = (struct gpu_gen *) user;
3154 isl_id *id;
3155 struct gpu_stmt *stmt;
3157 id = isl_map_get_tuple_id(map, isl_dim_in);
3158 stmt = find_stmt(gen->prog, id);
3159 isl_id_free(id);
3161 isl_map_free(map);
3163 if (!stmt)
3164 isl_die(gen->ctx, isl_error_unknown,
3165 "statement not found", return -1);
3167 gen->tile_len = stmt->tile_len;
3168 gen->n_parallel = stmt->n_parallel;
3170 return -1;
3173 void ppcg_kernel_stmt_free(void *user)
3175 int i;
3176 struct ppcg_kernel_stmt *stmt = user;
3178 if (!stmt)
3179 return;
3181 switch (stmt->type) {
3182 case ppcg_kernel_copy:
3183 isl_ast_expr_free(stmt->u.c.index);
3184 isl_ast_expr_free(stmt->u.c.local_index);
3185 break;
3186 case ppcg_kernel_domain:
3187 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
3188 break;
3189 case ppcg_kernel_sync:
3190 break;
3193 free(stmt);
3196 /* Set the options of "context" to
3198 * { space -> [x] : x >= first }
3200 static __isl_give isl_ast_build *set_unroll(
3201 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3202 int first)
3204 isl_ctx *ctx;
3205 isl_map *unroll;
3206 isl_union_map *opt;
3208 ctx = isl_ast_build_get_ctx(build);
3210 space = isl_space_from_domain(space);
3211 space = isl_space_add_dims(space, isl_dim_out, 1);
3212 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3213 unroll = isl_map_universe(space);
3214 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3215 opt = isl_union_map_from_map(unroll);
3217 build = isl_ast_build_set_options(build, opt);
3219 return build;
3222 /* Return a list of isl_ids of the form "prefix%d".
3224 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3225 int n, const char *prefix)
3227 int i;
3228 char name[10];
3229 isl_id_list *names;
3231 names = isl_id_list_alloc(ctx, n);
3232 for (i = 0; i < n; ++i) {
3233 isl_id *id;
3235 snprintf(name, sizeof(name), "%s%d", prefix, i);
3236 id = isl_id_alloc(ctx, name, NULL);
3237 names = isl_id_list_add(names, id);
3240 return names;
3243 /* Extend the schedule "schedule" with the part of "extension"
3244 * starting at "first" up to "len".
3246 static __isl_give isl_union_map *extend_schedule(
3247 __isl_take isl_union_map *schedule,
3248 __isl_take isl_union_map *extension, int first, int len)
3250 isl_space *space;
3251 isl_map *proj;
3252 isl_union_map *umap;
3253 isl_set *set;
3255 space = isl_union_map_get_space(schedule);
3256 space = isl_space_set_from_params(space);
3257 space = isl_space_add_dims(space, isl_dim_set, len);
3258 proj = isl_set_identity(isl_set_universe(space));
3259 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3260 extension = isl_union_map_apply_range(extension,
3261 isl_union_map_from_map(proj));
3263 schedule = isl_union_map_range_product(schedule, extension);
3265 return schedule;
3268 /* Return the gpu_stmt_access in the list "accesses" that corresponds
3269 * to "ref_id".
3271 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
3272 __isl_keep isl_id *ref_id)
3274 struct gpu_stmt_access *access;
3276 for (access = accesses; access; access = access->next)
3277 if (access->ref_id == ref_id)
3278 return access;
3280 return NULL;
3283 /* Return the index of the array called "name" in the list of arrays.
3285 static int find_array_index(struct gpu_gen *gen, const char *name)
3287 int i;
3289 for (i = 0; i < gen->prog->n_array; ++i)
3290 if (!strcmp(name, gen->prog->array[i].name))
3291 return i;
3293 return -1;
3296 /* Internal data structure for the index and AST expression transformation
3297 * callbacks for pet_stmt_build_ast_exprs.
3299 * "accesses" is the list of gpu_stmt_access in the statement.
3300 * "iterator_map" expresses the statement iterators in terms of
3301 * the AST loop iterators.
3302 * "sched2shared" expresses the first shared_len dimensions of
3303 * the computed schedule in terms of the AST loop iterators.
3305 * The following fields are set in transform_index and used in transform_expr.
3306 * "array" is the array that is being accessed.
3307 * "global" is set if the global array is accessed (rather than
3308 * shared/private memory).
3309 * "local_array" refers to information on the array specialized
3310 * to the current kernel.
3312 struct ppcg_transform_data {
3313 struct gpu_gen *gen;
3314 struct gpu_stmt_access *accesses;
3315 isl_pw_multi_aff *iterator_map;
3316 isl_pw_multi_aff *sched2shared;
3318 struct gpu_array_info *array;
3319 int global;
3320 struct gpu_local_array_info *local_array;
3323 /* Index transformation callback for pet_stmt_build_ast_exprs.
3325 * "index" expresses the array indices in terms of statement iterators
3327 * We first reformulate "index" in terms of the AST loop iterators.
3328 * Then we check if we are accessing the global array or
3329 * a shared/private copy. In the former case, we simply return
3330 * the updated index. If "index" is an affine expression rather
3331 * than an array access, then we also return the updated index here.
3333 * Otherwise, we apply the tiling to the index.
3334 * This tiling is of the form
3336 * [D -> A] -> T
3338 * The index is of the form
3340 * L -> A
3342 * We update the tiling to refer to the AST loop iteratos
3344 * [L -> A] -> T
3346 * and modify index to keep track of those iterators
3348 * L -> [L -> A]
3350 * Combining these two yields a tiled index expression in terms
3351 * of the AST loop iterators
3353 * L -> T
3355 static __isl_give isl_multi_pw_aff *transform_index(
3356 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
3357 void *user)
3359 struct ppcg_transform_data *data = user;
3360 struct gpu_stmt_access *access;
3361 struct gpu_array_ref_group *group;
3362 struct gpu_array_tile *tile;
3363 isl_pw_multi_aff *iterator_map;
3364 int i;
3365 const char *name;
3366 isl_space *space;
3367 isl_multi_pw_aff *tiling;
3368 isl_pw_multi_aff *pma;
3369 isl_multi_pw_aff *mpa;
3371 data->array = NULL;
3373 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
3374 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
3376 access = find_access(data->accesses, ref_id);
3377 if (!access)
3378 return index;
3379 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
3380 return index;
3382 name = isl_map_get_tuple_name(access->access, isl_dim_out);
3383 i = find_array_index(data->gen, name);
3384 if (i < 0)
3385 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
3386 "cannot find array reference group",
3387 return isl_multi_pw_aff_free(index));
3389 data->array = &data->gen->prog->array[i];
3390 data->local_array = &data->gen->kernel->array[i];
3391 group = data->array->groups[access->group];
3392 tile = group->private_tile;
3393 if (!tile)
3394 tile = group->shared_tile;
3395 data->global = !tile;
3396 if (!tile)
3397 return index;
3399 space = isl_space_range(isl_multi_pw_aff_get_space(index));
3400 space = isl_space_map_from_set(space);
3401 pma = isl_pw_multi_aff_identity(space);
3402 pma = isl_pw_multi_aff_product(
3403 isl_pw_multi_aff_copy(data->sched2shared), pma);
3404 tiling = isl_multi_pw_aff_from_multi_aff(
3405 isl_multi_aff_copy(tile->tiling));
3406 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
3408 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
3409 space = isl_space_map_from_set(space);
3410 mpa = isl_multi_pw_aff_identity(space);
3411 index = isl_multi_pw_aff_range_product(mpa, index);
3412 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
3414 return index;
3417 /* Dereference "expr" by adding an index [0].
3418 * The original "expr" is assumed not to have any indices.
3420 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
3422 isl_ctx *ctx;
3423 isl_ast_expr *res;
3424 isl_ast_expr_list *list;
3426 ctx = isl_ast_expr_get_ctx(expr);
3427 res = isl_ast_expr_from_val(isl_val_zero(ctx));
3428 list = isl_ast_expr_list_from_ast_expr(res);
3429 res = isl_ast_expr_get_op_arg(expr, 0);
3430 res = isl_ast_expr_access(res, list);
3431 isl_ast_expr_free(expr);
3433 return res;
3436 /* Linearize the index expression "expr" based on the array bounds
3437 * of "array".
3439 * That is, transform expression
3441 * A[i_0][i_1]...[i_n]
3443 * to
3445 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
3447 * where b_0, b_1, ..., b_n are the bounds on the array.
3449 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
3450 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
3452 int i, n;
3453 isl_ctx *ctx;
3454 isl_set *context;
3455 isl_ast_expr *res;
3456 isl_ast_expr_list *list;
3457 isl_ast_build *build;
3459 ctx = isl_ast_expr_get_ctx(expr);
3460 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
3461 build = isl_ast_build_from_context(context);
3463 n = isl_ast_expr_get_op_n_arg(expr);
3464 res = isl_ast_expr_get_op_arg(expr, 1);
3465 for (i = 2; i < n; ++i) {
3466 isl_pw_aff *bound_i;
3467 isl_ast_expr *expr_i;
3469 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i - 1);
3470 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
3471 res = isl_ast_expr_mul(res, expr_i);
3472 expr_i = isl_ast_expr_get_op_arg(expr, i);
3473 res = isl_ast_expr_add(res, expr_i);
3476 isl_ast_build_free(build);
3478 list = isl_ast_expr_list_from_ast_expr(res);
3479 res = isl_ast_expr_get_op_arg(expr, 0);
3480 res = isl_ast_expr_access(res, list);
3482 isl_ast_expr_free(expr);
3484 return res;
3487 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
3489 * If the AST expression refers to a global scalar that is not
3490 * a read-only scalar, then its address was passed to the kernel and
3491 * we need to dereference it.
3493 * If the AST expression refers to an access to a global array,
3494 * then we linearize the access exploiting the bounds in data->local_array.
3496 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
3497 __isl_keep isl_id *id, void *user)
3499 struct ppcg_transform_data *data = user;
3501 if (!data->array)
3502 return expr;
3503 if (gpu_array_is_read_only_scalar(data->array))
3504 return expr;
3505 if (!data->global)
3506 return expr;
3507 if (data->array->n_index == 0)
3508 return dereference(expr);
3510 return gpu_local_array_info_linearize_index(data->local_array, expr);
3513 /* This function is called for each instance of a user statement
3514 * in the kernel.
3516 * We attach a struct ppcg_kernel_stmt to the "node", containing
3517 * a computed AST expression for each access.
3518 * These AST expressions are computed from iterator_map,
3519 * which expresses the domain
3520 * elements in terms of the generated loops, and sched2shared,
3521 * which expresses the first shared_len dimensions of the schedule
3522 * computed by PPCG in terms of the generated loops.
3524 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3525 __isl_keep isl_ast_build *build, void *user)
3527 struct ppcg_transform_data data;
3528 struct gpu_gen *gen = (struct gpu_gen *) user;
3529 struct ppcg_kernel_stmt *stmt;
3530 isl_id *id;
3531 isl_pw_multi_aff *sched2shared;
3532 isl_map *map;
3533 isl_pw_multi_aff *iterator_map;
3534 isl_ast_expr *expr, *arg;
3535 isl_union_map *schedule;
3536 int i, n;
3537 struct gpu_stmt_access *access;
3539 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3540 if (!stmt)
3541 return isl_ast_node_free(node);
3543 expr = isl_ast_node_user_get_expr(node);
3544 arg = isl_ast_expr_get_op_arg(expr, 0);
3545 id = isl_ast_expr_get_id(arg);
3547 schedule = isl_ast_build_get_schedule(build);
3548 map = isl_map_reverse(isl_map_from_union_map(schedule));
3549 iterator_map = isl_pw_multi_aff_from_map(map);
3550 sched2shared = compute_sched_to_shared(gen,
3551 isl_pw_multi_aff_copy(iterator_map));
3553 stmt->type = ppcg_kernel_domain;
3554 stmt->u.d.stmt = find_stmt(gen->prog, id);
3555 if (!stmt->u.d.stmt)
3556 goto error;
3558 data.gen = gen;
3559 data.accesses = stmt->u.d.stmt->accesses;
3560 data.iterator_map = iterator_map;
3561 data.sched2shared = sched2shared;
3562 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
3563 build, &transform_index, &data,
3564 &transform_expr, &data);
3566 isl_id_free(id);
3567 isl_pw_multi_aff_free(iterator_map);
3568 isl_pw_multi_aff_free(sched2shared);
3569 isl_ast_expr_free(arg);
3570 isl_ast_expr_free(expr);
3572 id = isl_id_alloc(gen->ctx, NULL, stmt);
3573 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3574 return isl_ast_node_set_annotation(node, id);
3575 error:
3576 isl_id_free(id);
3577 isl_pw_multi_aff_free(iterator_map);
3578 ppcg_kernel_stmt_free(stmt);
3579 isl_pw_multi_aff_free(sched2shared);
3580 return isl_ast_node_free(node);
3583 /* This function is called when code has been generated for the shared
3584 * tile loops. The "schedule" refers only to the original statements.
3586 * We extend the schedule with that part of gen->local_sched that hasn't
3587 * been taken into account yet. This introduces parameters referring
3588 * to thread ids in the schedule, so we add them (with the appropriate
3589 * bounds to the context as well).
3590 * Finally, we set the appropriate unrolling options
3591 * if gen->first_unroll is set.
3593 static __isl_give isl_ast_node *create_domain_leaf(
3594 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
3595 void *user)
3597 struct gpu_gen *gen = (struct gpu_gen *) user;
3598 isl_space *space;
3599 isl_union_map *sched;
3600 isl_ast_node *tree;
3601 isl_set *set;
3602 isl_id_list *iterators;
3603 int n;
3605 schedule = extend_schedule(schedule,
3606 isl_union_map_copy(gen->local_sched),
3607 gen->shared_len, gen->thread_tiled_len);
3609 space = isl_ast_build_get_schedule_space(build);
3610 set = isl_set_universe(space);
3611 set = add_bounded_parameters(set, gen->kernel->n_block,
3612 gen->kernel->block_dim, "t");
3613 build = isl_ast_build_restrict(build, set);
3615 n = gen->thread_tiled_len - gen->shared_len;
3617 if (gen->first_unroll >= 0) {
3618 space = isl_space_set_alloc(gen->ctx, 0, n);
3619 build = set_unroll(build, space, gen->first_unroll);
3621 iterators = generate_names(gen->ctx, n, "c");
3622 build = isl_ast_build_set_iterators(build, iterators);
3623 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
3624 tree = isl_ast_build_ast_from_schedule(build, schedule);
3625 isl_ast_build_free(build);
3627 return tree;
3630 /* This function is called for each statement node in the AST of the code
3631 * for copying to or from shared/private memory.
3632 * Attach a pointer to a ppcg_kernel_stmt representing the copy
3633 * statement to the node.
3634 * The statement name is "read" or "write", depending on whether we are
3635 * reading from global memory or writing to global memory.
3636 * The name of the T space is {shared,private}_<array>.
3638 * The schedule is of the form
3640 * type[A -> T] -> L
3642 * where A refers to a piece of an array and T to the corresponding
3643 * shifted tile. We split this schedule into mappings L -> A and L -> T
3644 * and store the corresponding expressions in stmt->index and stmt->local_index,
3645 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
3647 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
3648 __isl_keep isl_ast_build *build, void *user)
3650 struct gpu_gen *gen = (struct gpu_gen *) user;
3651 struct ppcg_kernel_stmt *stmt;
3652 isl_id *id;
3653 isl_ast_expr *expr;
3654 isl_space *space;
3655 isl_map *access, *local_access, *map;
3656 isl_pw_multi_aff *pma;
3657 const char *type;
3658 int array_index;
3660 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3661 if (!stmt)
3662 return isl_ast_node_free(node);
3664 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
3665 type = isl_map_get_tuple_name(access, isl_dim_in);
3666 stmt->u.c.read = !strcmp(type, "read");
3667 access = isl_map_reverse(access);
3668 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
3669 local_access = isl_map_copy(access);
3671 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
3672 id = isl_map_get_tuple_id(access, isl_dim_out);
3673 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3674 access = isl_map_apply_range(access, map);
3675 pma = isl_pw_multi_aff_from_map(access);
3676 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
3677 stmt->u.c.index = expr;
3679 map = isl_map_range_map(isl_map_universe(space));
3680 id = isl_map_get_tuple_id(local_access, isl_dim_out);
3681 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3682 local_access = isl_map_apply_range(local_access, map);
3683 pma = isl_pw_multi_aff_from_map(local_access);
3684 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
3685 stmt->u.c.local_index = expr;
3687 stmt->u.c.array = gen->copy_group->array;
3688 array_index = stmt->u.c.array - gen->prog->array;
3689 stmt->u.c.local_array = &gen->kernel->array[array_index];
3690 stmt->type = ppcg_kernel_copy;
3692 id = isl_id_alloc(gen->ctx, NULL, stmt);
3693 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3694 return isl_ast_node_set_annotation(node, id);
3697 /* Given a schedule of the form
3699 * [S -> A] -> L
3701 * (with S the first shared_len dimensions of the computed schedule,
3702 * A the array and L the schedule correponding to the generated loops),
3703 * indicating where the copying the array elements that need to be copied,
3704 * construct code for performing the copying.
3706 * "group" is the array reference group that is being copied
3707 * "type" is either "read" or "write"
3708 * private is set if copying needs to be performed to/from registers
3710 * We first construct a mapping to a shifted tile of the array,
3712 * [S -> A] -> T(S,A) (1)
3714 * If private is set, then we also use this mapping as a schedule
3715 * (which is already thread-specific and will be completely unrolled).
3716 * Otherwise, we wrap/tile the range over the threads.
3717 * The result is
3719 * [S -> A] -> T'(S,A)
3721 * Combined with the given schedule, we have
3723 * [S -> A] -> [L -> T'(S,A)] (2)
3725 * From the shifted tile mapping, we construct a mapping
3727 * [S -> A] -> [A -> T(S,A)]
3729 * and apply it to the schedule (2), obtaining
3731 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
3733 * Note that we can project out S because it is uniquely defined by L.
3735 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
3736 __isl_take isl_map *sched,
3737 const char *type, struct gpu_array_ref_group *group,
3738 __isl_take isl_ast_build *build, int private)
3740 isl_space *space;
3741 isl_ast_node *tree;
3742 isl_map *schedule, *shift, *map;
3743 isl_set *set;
3744 isl_id_list *iterators;
3745 int n;
3747 shift = shift_access(group);
3749 schedule = isl_map_copy(shift);
3750 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
3751 if (!private)
3752 schedule = tile_access_schedule(gen, schedule);
3754 n = isl_map_dim(schedule, isl_dim_out);
3755 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
3756 set = add_bounded_parameters(set, gen->kernel->n_block,
3757 gen->kernel->block_dim, "t");
3759 schedule = isl_map_range_product(sched, schedule);
3761 space = isl_space_domain(isl_map_get_space(shift));
3762 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
3763 map = isl_map_range_product(map, shift);
3765 schedule = isl_map_apply_domain(schedule, map);
3767 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
3769 build = isl_ast_build_restrict(build, set);
3771 gen->copy_group = group;
3773 if (private) {
3774 space = isl_space_range(isl_map_get_space(schedule));
3775 space = isl_space_range(isl_space_unwrap(space));
3776 build = set_unroll(build, space, 0);
3778 iterators = generate_names(gen->ctx, n, "c");
3779 build = isl_ast_build_set_iterators(build, iterators);
3780 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
3781 tree = isl_ast_build_ast_from_schedule(build,
3782 isl_union_map_from_map(schedule));
3783 isl_ast_build_free(build);
3785 return tree;
3788 /* Return code for reading into or writing from shared memory
3789 * the given array reference group.
3791 * If we are performing a read from global memory to shared memory and
3792 * if the array involved is not a scalar, then we copy
3793 * the entire tile to shared memory. This may result in some extra
3794 * elements getting copied, but it should lead to simpler code
3795 * (which means that fewer registers may be needed) and less divergence.
3797 * Otherwise, we only copy the elements that will be read or have been written
3798 * in the kernel.
3801 * The input "sched" is of the form.
3803 * type[S -> A] -> L
3805 * with S the first shared_len dimensions of the computed schedule,
3806 * A the array and L the schedule correponding to the generated loops.
3808 * We first drop "type",
3810 * [S -> A] -> L
3812 * If the above conditions are satisfied, we project out A,
3813 * resulting in
3815 * S -> L
3817 * and then introduce the group tile [S -> T], resulting in
3819 * [S -> T] -> L
3821 static __isl_give isl_ast_node *copy_group_shared_accesses(
3822 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3823 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3825 const char *type;
3826 int read;
3827 isl_union_map *access;
3829 type = isl_map_get_tuple_name(sched, isl_dim_in);
3830 read = !strcmp(type, "read");
3832 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3834 if (read && !gpu_array_is_scalar(group->array)) {
3835 isl_space *space;
3836 isl_map *map;
3838 space = isl_space_domain(isl_map_get_space(sched));
3839 space = isl_space_unwrap(space);
3840 map = isl_map_domain_map(isl_map_universe(space));
3841 sched = isl_map_apply_domain(sched, map);
3843 map = group_tile(group);
3844 map = isl_map_reverse(isl_map_domain_map(map));
3845 sched = isl_map_apply_domain(sched, map);
3848 return copy_access(gen, sched, type, group, build, 0);
3851 /* Return code for reading into or writing from private memory
3852 * the given array reference group.
3854 * Let S be the first shared_len dimensions of the computed schedule,
3855 * D the iteration domains, A the array and L the schedule correponding
3856 * to the generated loops.
3857 * "sched" is of the form
3859 * type[S -> A] -> L
3861 * where type is either "read" or "write".
3862 * We apply the privatization D -> S(t), with t the thread ids,
3863 * to the access relation D -> A to obtain the privatized access relation
3865 * S(t) -> A
3867 * We drop the type from "sched" and intersect with the privatized access
3868 * relation to obtain
3870 * [S(t) -> A] -> L
3872 static __isl_give isl_ast_node *copy_group_private_accesses(
3873 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3874 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3876 const char *type;
3877 int read;
3878 isl_union_map *priv;
3879 isl_union_map *access;
3880 isl_map *access_map;
3882 type = isl_map_get_tuple_name(sched, isl_dim_in);
3883 read = !strcmp(type, "read");
3885 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
3886 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3887 priv);
3889 access = group_access_relation(group, read, !read);
3890 access = isl_union_map_apply_domain(access, priv);
3891 access_map = isl_map_from_union_map(access);
3893 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3894 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
3896 return copy_access(gen, sched, type, group, build, 1);
3899 /* Return code for reading into or writing from shared or private memory.
3901 * "schedule" is of the form
3903 * type[S -> A] -> L
3905 * with S be the first shared_len dimensions of the computed schedule,
3906 * A the array and L the schedule correponding to the generated loops.
3907 * The array reference group is attached to "type".
3909 static __isl_give isl_ast_node *create_access_leaf(
3910 struct gpu_gen *gen, __isl_take isl_map *schedule,
3911 __isl_take isl_ast_build *build)
3913 struct gpu_array_ref_group *group;
3914 isl_id *id;
3916 id = isl_map_get_tuple_id(schedule, isl_dim_in);
3917 group = isl_id_get_user(id);
3918 isl_id_free(id);
3920 if (group->private_tile)
3921 return copy_group_private_accesses(gen, group, schedule,
3922 build);
3923 else
3924 return copy_group_shared_accesses(gen, group, schedule,
3925 build);
3928 /* Create a domain node representing a synchronization.
3930 static __isl_give isl_ast_node *create_sync_leaf(
3931 struct gpu_gen *gen, __isl_take isl_map *schedule,
3932 __isl_take isl_ast_build *build)
3934 struct ppcg_kernel_stmt *stmt;
3935 isl_id *id;
3936 isl_space *space;
3937 isl_ast_node *node;
3938 isl_ast_expr *expr;
3940 isl_map_free(schedule);
3942 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3943 if (!stmt)
3944 return NULL;
3946 stmt->type = ppcg_kernel_sync;
3948 space = isl_ast_build_get_schedule_space(build);
3949 space = isl_space_from_domain(space);
3950 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
3951 expr = isl_ast_build_call_from_pw_multi_aff(build,
3952 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
3953 node = isl_ast_node_alloc_user(expr);
3954 isl_ast_build_free(build);
3956 id = isl_id_alloc(gen->ctx, NULL, stmt);
3957 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3958 return isl_ast_node_set_annotation(node, id);
3961 /* This function is called during the code generation at the point
3962 * where the schedule domain element is completely determined by
3963 * the generated code. The input schedule contains the original
3964 * statements as well as synchronization and copy "statements".
3965 * The latter are scheduled at different points than any of the original
3966 * statements, so they will only arrive here in isolation.
3968 * If the current schedule only refers to a single statement,
3969 * we check if it is a copy or synchronization statement and
3970 * call the appropriate functions.
3971 * Otherwise, we assume we are dealing with the original statements
3972 * and we call create_domain_leaf.
3974 static __isl_give isl_ast_node *create_kernel_leaf(
3975 __isl_take isl_ast_build *build, void *user)
3977 struct gpu_gen *gen = (struct gpu_gen *) user;
3978 isl_map *map;
3979 isl_union_map *schedule;
3980 const char *name;
3982 schedule = isl_ast_build_get_schedule(build);
3984 if (isl_union_map_n_map(schedule) != 1)
3985 return create_domain_leaf(schedule, build, user);
3987 map = isl_map_from_union_map(schedule);
3988 name = isl_map_get_tuple_name(map, isl_dim_in);
3989 if (!strcmp(name, "read") || !strcmp(name, "write"))
3990 return create_access_leaf(gen, map, build);
3991 if (!strcmp(name, "sync"))
3992 return create_sync_leaf(gen, map, build);
3994 return create_domain_leaf(isl_union_map_from_map(map), build, user);
3997 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
3998 * have value 0) and all even schedule dimensions as "unroll".
4000 * That is, the options look as follows
4002 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4003 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4005 * The even positions are used to be able to schedule copying blocks
4006 * and synchronization before or after each level of the shared memory
4007 * tile loops and we want to make sure that code for these is generated
4008 * separately (within each level).
4010 static __isl_give isl_ast_build *set_atomic_and_unroll(
4011 __isl_take isl_ast_build *build,
4012 __isl_take isl_space *space, int sched_len)
4014 isl_ctx *ctx;
4015 isl_map *map;
4016 isl_constraint *c;
4017 isl_union_map *opt;
4018 isl_local_space *ls;
4019 int i, n;
4021 ctx = isl_ast_build_get_ctx(build);
4023 space = isl_space_params(space);
4024 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4025 space = isl_space_from_domain(space);
4026 space = isl_space_add_dims(space, isl_dim_out, 2);
4027 map = isl_map_universe(isl_space_copy(space));
4028 for (i = 0; i < sched_len; i += 2)
4029 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4030 ls = isl_local_space_from_space(isl_map_get_space(map));
4031 c = isl_equality_alloc(ls);
4032 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4033 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4034 c = isl_constraint_set_constant_si(c, 1);
4035 map = isl_map_add_constraint(map, c);
4036 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4037 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4038 opt = isl_union_map_from_map(map);
4040 map = isl_map_universe(space);
4041 ls = isl_local_space_from_space(isl_map_get_space(map));
4042 c = isl_equality_alloc(ls);
4043 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4044 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4045 map = isl_map_add_constraint(map, c);
4046 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4047 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4048 opt = isl_union_map_add_map(opt, map);
4050 build = isl_ast_build_set_options(build, opt);
4052 return build;
4055 /* Return a map that maps a space of dimension gen->shared_len
4056 * to its last dimensions starting at gen->tile_first.
4057 * The range is of dimension
4059 * 2 * (gen->shared_len - gen->tile_first) + 1
4061 * The input dimensions are mapped to the odd dimensions in the output,
4062 * while the even dimensions (except 2*pos) are fixed to 0.
4063 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4064 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4065 * are mapped to the output. The remaining input dimensions are projected
4066 * out and the corresponding output dimensions are fixed to 0.
4068 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4069 __isl_take isl_space *space, int pos, int val)
4071 int i, n;
4072 isl_map *proj;
4074 space = isl_space_set_from_params(space);
4075 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4076 space = isl_space_map_from_set(space);
4077 proj = isl_map_identity(space);
4078 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4079 n = gen->shared_len - gen->tile_first;
4080 for (i = 0; i <= n; ++i) {
4081 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4082 if (i == pos)
4083 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4084 else
4085 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4088 if (pos < 0)
4089 return proj;
4091 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4092 gen->shared_len - (gen->tile_first + pos));
4093 for (i = pos; i < n; ++i)
4094 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4096 return proj;
4099 /* Given the AST context schedule "schedule" and the mapping from
4100 * domains to the shared tile loops "shared_sched", add a schedule
4101 * for a synchronization operation at position "val" of loop level "pos".
4103 * schedule is of the form
4105 * D -> L
4107 * (with D the iteration domains and L the already generated loops),
4108 * while shared_sched is of the form
4110 * D -> S
4112 * We combine them into
4114 * L -> S
4116 * apply a mapping
4118 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4120 * and use the result as a schedule for "sync".
4122 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4123 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4124 __isl_keep isl_union_map *shared_sched, int pos, int val)
4126 isl_space *space;
4127 isl_map *proj, *map;
4129 shared_sched = isl_union_map_copy(shared_sched);
4130 schedule = isl_union_map_copy(schedule);
4132 space = isl_union_map_get_space(shared_sched);
4133 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4134 map = isl_map_from_union_map(schedule);
4136 proj = insert_even(gen, space, pos, val);
4137 map = isl_map_apply_range(map, proj);
4138 map = isl_map_from_range(isl_map_wrap(map));
4139 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4141 res = isl_union_map_add_map(res, map);
4143 return res;
4146 /* Given the AST context schedule "schedule" and the mapping from
4147 * domains to the shared tile loops "shared_sched", add a schedule
4148 * for copying an array reference group to/from shared/private memory.
4149 * "read" is set if data should be copied from global memory
4150 * to shared/private memory.
4151 * "k" represents the current group
4152 * "s" is the total number of groups
4154 * We schedule an operation before or after the innermost loop
4155 * of "shared_sched" that affects the tile of the array reference group.
4157 * schedule is of the form
4159 * D -> L
4161 * (with D the iteration domains and L the already generated loops),
4162 * while shared_sched is of the form
4164 * D -> S
4166 * We first compute the access relation for the reference group
4168 * D -> A
4170 * and combine it with shared_sched into
4172 * D -> [S -> A]
4174 * If this results in an empty relation, no copying needs to be performed
4175 * at this point.
4176 * Otherwise, we invert the relation and combine it with "schedule" into
4178 * [S -> A] -> L
4180 * The actual additional piece of the schedule is obtained from combining
4182 * [S -> A] -> S
4184 * with a mapping
4186 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4188 * The position of "val" corresponds to the innermost loop that affects
4189 * the tile and the value indicates where the copying is scheduled
4190 * with respect to the actual kernel code (at value 0).
4191 * Reads are schedule before the code, writes to global memory from
4192 * private memory are scheduled at values 1 to s, writes to global
4193 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4195 * If we are scheduling a read from global memory to shared memory,
4196 * we insert a synchronization before the kernel code (at the innermost
4197 * level).
4198 * If we are scheduling a write to global memory, then we add
4199 * a synchronization after all writes (at value 2 *s + 2).
4200 * However, there is no need for a synchronization after the outermost loop.
4201 * A write to global memory from private memory at the innermost level
4202 * does not require a synchronization, because it is covered by
4203 * the synchronization after the kernel inserted by body_schedule.
4205 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4206 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4207 __isl_keep isl_union_map *shared_sched,
4208 struct gpu_array_ref_group *group, int read, int k, int s)
4210 int n;
4211 int pos, val;
4212 isl_space *space;
4213 isl_union_map *access;
4214 isl_map *map, *proj, *access_map;
4215 isl_id *id;
4217 access = group_access_relation(group, read, !read);
4218 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4219 access);
4221 if (isl_union_map_is_empty(access)) {
4222 isl_union_map_free(access);
4223 return res;
4226 access = isl_union_map_reverse(access);
4227 access = isl_union_map_apply_range(access,
4228 isl_union_map_copy(schedule));
4229 access_map = isl_map_from_union_map(access);
4231 space = isl_space_copy(group->array->dim);
4232 space = isl_space_from_range(space);
4233 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4234 map = isl_map_domain_map(isl_map_universe(space));
4236 space = isl_union_map_get_space(schedule);
4237 pos = group->last_shared + 1 - gen->tile_first;
4238 assert(pos >= 0);
4239 if (read)
4240 val = -2 - k;
4241 else if (group->private_tile)
4242 val = 1 + k;
4243 else
4244 val = 1 + s + 1 + k;
4245 proj = insert_even(gen, space, pos, val);
4246 map = isl_map_apply_range(map, proj);
4248 access_map = isl_map_range_product(access_map, map);
4250 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4251 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4253 res = isl_union_map_add_map(res, access_map);
4255 n = gen->shared_len - gen->tile_first;
4256 if (read) {
4257 if (!group->private_tile)
4258 res = add_sync_schedule(gen, res, schedule,
4259 shared_sched, n, -1);
4260 } else {
4261 if (pos == 0)
4262 return res;
4263 if (pos == n && group->private_tile)
4264 return res;
4265 res = add_sync_schedule(gen, res, schedule, shared_sched,
4266 pos, 2 * s + 2);
4269 return res;
4272 /* Return a schedule for the shared tile loops based on the current
4273 * AST context schedule.
4275 * We create a "shared_sched" that maps the domains to the first
4276 * shared_len dimensions of the computed schedule, project out the
4277 * first tile_first dimensions (as these are already covered by
4278 * the host code) and insert "statement-level" dimensions at even
4279 * positions so that we can schedule copy blocks and synchronization
4280 * before/after each level.
4282 * In particular, copy blocks are inserted inside the innermost
4283 * level that affect the tile. For the copying to global memory,
4284 * those from private memory are scheduled before those from shared
4285 * memory such that synchronization can be inserted between the two
4286 * at the innermost level.
4287 * Synchronization is inserted at the innermost level before the
4288 * actual kernel code if there is any copying from global memory
4289 * to shared memory. It is inserted unconditionally at the innermost
4290 * level after the actual kernel code and the copying to global memory
4291 * from private memory (if any). Finally, it is inserted after
4292 * any copying to global memory, except at the outermost level
4293 * and at the innermost level if there is no copying from shared
4294 * memory. The copying from private memory is covered by the unconditional
4295 * synchronization at the innermost level.
4297 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4298 __isl_take isl_union_map *schedule)
4300 isl_space *space;
4301 isl_union_map *res;
4302 isl_union_map *shared_sched;
4303 isl_union_map *sched;
4304 isl_map *proj, *map;
4305 int i, j, k, s;
4307 shared_sched = isl_union_map_copy(gen->tiled_sched);
4308 proj = projection(isl_union_map_get_space(shared_sched),
4309 gen->tiled_len, gen->shared_len);
4310 shared_sched = isl_union_map_apply_range(shared_sched,
4311 isl_union_map_from_map(proj));
4312 space = isl_union_map_get_space(shared_sched);
4313 proj = insert_even(gen, space, -1, 0);
4314 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4315 isl_union_map_from_map(proj));
4317 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4319 s = 0;
4320 for (i = 0; i < gen->prog->n_array; ++i)
4321 s += gen->prog->array[i].n_group;
4323 k = 0;
4324 for (i = 0; i < gen->prog->n_array; ++i) {
4325 struct gpu_array_info *array = &gen->prog->array[i];
4327 for (j = 0; j < array->n_group; ++j) {
4328 struct gpu_array_ref_group *group;
4330 group = array->groups[j];
4331 if (!group->private_tile && !group->shared_tile)
4332 continue;
4333 res = add_group_schedule(gen, res, schedule,
4334 shared_sched, group, 0, k, s);
4335 res = add_group_schedule(gen, res, schedule,
4336 shared_sched, group, 1, k, s);
4337 ++k;
4341 res = add_sync_schedule(gen, res, schedule, shared_sched,
4342 gen->shared_len - gen->tile_first, 1 + s);
4344 isl_union_map_free(shared_sched);
4345 isl_union_map_free(schedule);
4347 return res;
4350 /* Generate code for "kernel" in the given "context".
4352 * We first generate code for the shared tile loops (T1T, T1P and T2)
4353 * in a context that includes the block ids.
4354 * Within each iteration of these loops an additional code generation
4355 * is performed (within create_kernel_leaf) for the rest of the schedule
4356 * in a context that includes the thread ids.
4358 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4359 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4360 __isl_keep isl_multi_pw_aff *grid_size)
4362 isl_space *space;
4363 isl_set *set;
4364 isl_id_list *iterators;
4365 isl_union_map *schedule;
4366 isl_ast_node *tree;
4367 int sched_len;
4369 schedule = isl_ast_build_get_schedule(build);
4371 build = isl_ast_build_copy(build);
4372 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4373 space = isl_ast_build_get_schedule_space(build);
4374 set = isl_set_universe(isl_space_copy(space));
4375 set = add_bounded_parameters_dynamic(set, grid_size, "b");
4376 build = isl_ast_build_restrict(build, set);
4378 schedule = body_schedule(gen, schedule);
4380 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4382 build = set_atomic_and_unroll(build, space, sched_len);
4383 iterators = generate_names(gen->ctx, sched_len, "g");
4384 build = isl_ast_build_set_iterators(build, iterators);
4385 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4386 tree = isl_ast_build_ast_from_schedule(build, schedule);
4387 isl_ast_build_free(build);
4389 return tree;
4392 /* Attach "id" to the given node.
4394 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4395 __isl_keep isl_ast_build *build, void *user)
4397 isl_id *id = user;
4399 node = isl_ast_node_set_annotation(node, id);
4401 return node;
4404 /* Construct an AST node for performing a kernel launch and attach
4405 * the information about the kernel to that node.
4407 * The kernel AST has been constructed in the context of the range
4408 * of "schedule". In particular, the grid size has been computed
4409 * in the context. We therefore still need to make sure that these
4410 * constraints are expressed in the code. We do this by creating a schedule
4412 * kernel[] -> [S -> []]
4414 * where S is the schedule domain, i.e., the range of "schedule".
4415 * The AST generation will then create a single call surrounded by
4416 * all the condition in "S" that have not been expressed yet.
4418 * The kernel information is attached to this node in attach_id.
4420 static __isl_give isl_ast_node *construct_launch(
4421 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
4422 __isl_take struct ppcg_kernel *kernel)
4424 isl_id *id;
4425 isl_ctx *ctx;
4426 isl_union_set *domain;
4427 isl_set *set;
4428 isl_map *map;
4429 isl_ast_node *node;
4431 ctx = isl_ast_build_get_ctx(build);
4433 id = isl_id_alloc(ctx, NULL, kernel);
4434 id = isl_id_set_free_user(id, &ppcg_kernel_free);
4436 domain = isl_union_map_range(schedule);
4437 set = isl_set_from_union_set(domain);
4438 map = isl_map_from_domain(set);
4439 map = isl_map_from_range(isl_map_wrap(map));
4440 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
4441 schedule = isl_union_map_from_map(map);
4443 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
4444 node = isl_ast_build_ast_from_schedule(build, schedule);
4445 isl_ast_build_free(build);
4447 return node;
4450 /* This function is called for each leaf in the AST of the host code.
4451 * We first specialize the schedule to the site of the leaf, compute
4452 * the size of shared memory and then construct the body of host code
4453 * and the associated kernel.
4455 * The necessary information for printing the kernel launch is
4456 * stored in a struct ppcg_kernel and attached to the leaf node
4457 * created to represent the launch.
4459 static __isl_give isl_ast_node *create_host_leaf(
4460 __isl_take isl_ast_build *build, void *user)
4462 struct gpu_gen *gen = (struct gpu_gen *) user;
4463 isl_id *id;
4464 isl_ast_node *node;
4465 struct ppcg_kernel *kernel;
4466 isl_set *host_domain;
4467 isl_union_map *schedule;
4468 isl_union_map *local_sched;
4469 isl_union_map *access;
4470 isl_union_set *domain;
4471 int i;
4473 schedule = isl_ast_build_get_schedule(build);
4475 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
4476 read_sizes(gen);
4478 domain = isl_union_map_domain(isl_union_map_copy(schedule));
4480 local_sched = isl_union_map_copy(gen->sched);
4481 local_sched = isl_union_map_intersect_domain(local_sched, domain);
4482 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
4483 isl_union_map_copy(gen->prog->write));
4484 access = isl_union_map_apply_domain(access,
4485 isl_union_map_copy(local_sched));
4487 gen->tiled_sched = tile_schedule(gen, local_sched);
4488 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
4489 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
4491 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
4492 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
4493 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
4495 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
4496 if (!kernel)
4497 goto error;
4499 kernel->id = gen->kernel_id++;
4500 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
4501 kernel->grid_size = extract_grid_size(gen, kernel);
4502 extract_block_size(gen, kernel);
4503 kernel->arrays = isl_union_map_range(access);
4504 kernel->space = isl_ast_build_get_schedule_space(build);
4506 gen->private_access = NULL;
4507 compute_shared_sched(gen);
4508 gen->privatization = compute_privatization(gen);
4509 group_references(gen);
4510 compute_private_access(gen);
4511 check_shared_memory_bound(gen);
4512 compute_group_tilings(gen);
4513 host_domain = isl_set_from_union_set(isl_union_map_range(
4514 isl_union_map_copy(schedule)));
4515 localize_bounds(gen, kernel, host_domain);
4517 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
4519 kernel->tree = generate_kernel(gen, build, host_domain,
4520 kernel->grid_size);
4521 create_kernel_vars(gen, kernel);
4523 free_local_array_info(gen);
4524 isl_map_free(gen->privatization);
4525 isl_union_map_free(gen->private_access);
4526 isl_union_map_free(gen->local_sched);
4527 isl_union_map_free(gen->tiled_sched);
4528 isl_union_map_free(gen->shared_sched);
4529 isl_union_map_free(gen->shared_proj);
4530 isl_set_free(host_domain);
4531 free(gen->tile_size);
4533 node = construct_launch(build, schedule, kernel);
4535 return node;
4536 error:
4537 isl_union_map_free(schedule);
4538 return NULL;
4541 /* Use isl to generate code for the outer gen->tile_first loops
4542 * of the global schedule in gen->sched, resulting in the host code.
4543 * Within each iteration of this partial schedule, i.e., for each kernel
4544 * launch, create_host_leaf takes care of generating the kernel code.
4546 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
4548 isl_ast_build *build;
4549 isl_ast_node *tree;
4550 isl_union_map *sched;
4551 isl_map *proj;
4552 isl_id_list *iterators;
4554 sched = isl_union_map_copy(gen->sched);
4555 proj = projection(isl_union_map_get_space(sched),
4556 gen->untiled_len, gen->tile_first);
4557 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4559 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
4560 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
4561 iterators = generate_names(gen->ctx, gen->tile_first, "h");
4562 build = isl_ast_build_set_iterators(build, iterators);
4563 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
4564 tree = isl_ast_build_ast_from_schedule(build, sched);
4565 isl_ast_build_free(build);
4567 return tree;
4570 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
4572 if (!str)
4573 return NULL;
4574 return isl_union_map_read_from_str(ctx, str);
4577 /* Information about the outermost tilable bands in the forest of bands.
4579 * tile_len and n_parallel are only sets on band_info structures
4580 * that correspond to outermost bands. For other bands (in particular,
4581 * ancestors of the outermost bands), n_parallal is set to 0.
4583 * prefix is the (padded) schedule leading up to the outermost tilable bands.
4585 * tile_first is the number of schedule dimensions in prefix.
4587 * suffix is the schedule of the outermost tilable bands and their descendants.
4589 struct band_info {
4590 struct gpu_gen *gen;
4591 int tile_first;
4592 int tile_len;
4593 int n_parallel;
4594 isl_union_map *prefix;
4595 isl_union_map *suffix;
4598 /* Set tile_len and n_parallel of the statement to that of
4599 * their outermost band, recorded in the band_info.
4601 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
4603 struct band_info *info = user;
4604 struct gpu_stmt *stmt;
4605 isl_id *id;
4607 id = isl_map_get_tuple_id(map, isl_dim_in);
4608 stmt = find_stmt(info->gen->prog, id);
4609 isl_id_free(id);
4611 stmt->tile_len = info->tile_len;
4612 stmt->n_parallel = info->n_parallel;
4614 isl_map_free(map);
4616 return 0;
4619 static void list_select_outer_band(struct gpu_gen *gen,
4620 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
4622 /* Check if this band has any parallel loops. If so, take it as
4623 * the outermost tilable band. If not, continue looking for the
4624 * outermost tilable band in the children of the current band.
4626 static void band_select_outer_band(struct gpu_gen *gen,
4627 __isl_take isl_band *band, int pos, struct band_info *info)
4629 int n = isl_band_n_member(band);
4630 int n_parallel;
4632 for (n_parallel = 0; n_parallel < n; ++n_parallel)
4633 if (!isl_band_member_is_zero_distance(band, n_parallel))
4634 break;
4636 info->n_parallel = n_parallel;
4637 if (n_parallel) {
4638 gen->any_parallelism = 1;
4639 info->gen = gen;
4640 info->tile_first = pos;
4641 info->tile_len = n;
4642 info->prefix = isl_band_get_prefix_schedule(band);
4643 info->suffix = isl_union_map_flat_range_product(
4644 isl_band_get_partial_schedule(band),
4645 isl_band_get_suffix_schedule(band));
4646 isl_union_map_foreach_map(info->prefix,
4647 &set_stmt_tile_len, info);
4648 } else if (isl_band_has_children(band)) {
4649 isl_band_list *children;
4650 children = isl_band_get_children(band);
4651 list_select_outer_band(gen, children, pos + n, info);
4652 } else {
4653 info->gen = gen;
4654 info->tile_first = pos + n;
4655 info->tile_len = 0;
4656 info->prefix = isl_union_map_flat_range_product(
4657 isl_band_get_prefix_schedule(band),
4658 isl_band_get_partial_schedule(band));
4659 info->suffix = isl_band_get_suffix_schedule(band);
4660 isl_union_map_foreach_map(info->prefix,
4661 &set_stmt_tile_len, info);
4664 isl_band_free(band);
4667 /* Comparison function that returns a non-zero value for band_infos
4668 * with different tile_len fields or different n_parallel fields.
4670 static int cmp_band(const void *p1, const void *p2)
4672 const struct band_info *info1 = p1;
4673 const struct band_info *info2 = p2;
4675 if (info1->tile_len != info2->tile_len)
4676 return info1->tile_len - info2->tile_len;
4678 return info1->n_parallel - info2->n_parallel;
4681 /* Extend "umap" with coordinates with fixed value "val"
4682 * to a total length of "dst_len", assuming the original dimension is "src_len".
4684 static __isl_give isl_union_map *extend_range(
4685 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
4687 isl_space *dim;
4688 isl_map *map;
4689 int i;
4691 dim = isl_union_map_get_space(umap);
4692 map = isl_map_reverse(projection(dim, dst_len, src_len));
4693 for (i = src_len; i < dst_len; ++i)
4694 map = isl_map_fix_si(map, isl_dim_out, i, val);
4696 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
4698 return umap;
4701 /* Group bands with the same values for tile_len and n_parallel.
4702 * The prefix schedule is then extended with a fixed coordinate that
4703 * is different for each such group.
4704 * Note that the actual values for this coordinate are not important.
4705 * The bands have already been effectively separated at a higher level
4706 * or they are independent and may be executed in parallel.
4707 * The list of band_info has been sorted before this functions is called.
4709 static void separate_bands(struct band_info *info, int n)
4711 int i;
4712 int j = 0;
4714 for (i = 0; i < n; ++i) {
4715 int l = info[i].tile_first;
4717 if (i &&
4718 (info[i].tile_len != info[i - 1].tile_len ||
4719 info[i].n_parallel != info[i - 1].n_parallel))
4720 j++;
4722 info[i].prefix = extend_range(info[i].prefix,
4723 l, l + 1, j);
4724 info[i].tile_first = l + 1;
4728 /* Select the outermost bands in the elements of the list, align
4729 * their prefix schedules, separate bands with different values
4730 * for tile_len and/or n_parallel and then combine the resulting
4731 * prefix and suffix schedules into a single pair of prefix and
4732 * suffix schedules for the entire list.
4734 static void list_select_outer_band(struct gpu_gen *gen,
4735 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
4737 isl_band *band;
4738 int i;
4739 int n = isl_band_list_n_band(list);
4740 isl_ctx *ctx = isl_band_list_get_ctx(list);
4741 struct band_info *info;
4742 int max_tile_first;
4743 isl_union_map *prefix;
4744 isl_union_map *suffix;
4746 assert(n >= 1);
4747 info = isl_calloc_array(ctx, struct band_info, n);
4748 assert(info);
4750 max_tile_first = 0;
4751 for (i = 0; i < n; ++i) {
4752 band = isl_band_list_get_band(list, i);
4753 band_select_outer_band(gen, band, pos, &info[i]);
4754 if (info[i].tile_first > max_tile_first)
4755 max_tile_first = info[i].tile_first;
4758 for (i = 0; i < n; ++i) {
4759 if (info[i].tile_first == max_tile_first)
4760 continue;
4761 info[i].prefix = extend_range(info[i].prefix,
4762 info[i].tile_first, max_tile_first, 0);
4763 info[i].tile_first = max_tile_first;
4766 qsort(info, n, sizeof(struct band_info), &cmp_band);
4768 for (i = 0; i < n - 1; ++i)
4769 if (info[i].tile_len != info[i + 1].tile_len ||
4770 info[i].n_parallel != info[i + 1].n_parallel)
4771 break;
4773 if (i < n -1)
4774 separate_bands(info, n);
4776 prefix = info[0].prefix;
4777 suffix = info[0].suffix;
4779 for (i = 1; i < n; ++i) {
4780 prefix = isl_union_map_union(prefix, info[i].prefix);
4781 suffix = isl_union_map_union(suffix, info[i].suffix);
4784 list_info->tile_first = info[0].tile_first;
4785 list_info->tile_len = -1;
4786 list_info->prefix = prefix;
4787 list_info->suffix = suffix;
4789 isl_band_list_free(list);
4790 free(info);
4793 /* Select the outermost tilable band that (by construction)
4794 * has at least one parallel loop.
4795 * The starting position of the aligned band is stored in the pair
4796 * gen->tile_first.
4797 * The sizes and number of parallel loops may be different in different
4798 * parts of the band forest and are therefore stored in the gpu_stmts.
4800 * Return the complete schedule, with the tilable bands aligned
4801 * at gen->tile_first and padded with zero, if needed.
4803 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
4804 __isl_keep isl_schedule *schedule)
4806 isl_band_list *list;
4807 struct band_info info;
4809 gen->n_parallel = 0;
4810 gen->tile_len = -1;
4812 list = isl_schedule_get_band_forest(schedule);
4814 if (isl_band_list_n_band(list) == 0) {
4815 isl_band_list_free(list);
4816 return isl_schedule_get_map(schedule);
4819 list_select_outer_band(gen, list, 0, &info);
4821 gen->tile_first = info.tile_first;
4822 info.suffix = align_range(info.suffix);
4824 return isl_union_map_flat_range_product(info.prefix, info.suffix);
4827 /* Set gen->untiled_len to the number of scheduling dimensions
4828 * for the schedule of the first domain.
4829 * We assume here that this number is the same for all domains.
4831 static int set_untiled_len(__isl_take isl_map *map, void *user)
4833 unsigned *untiled_len = user;
4835 *untiled_len = isl_map_dim(map, isl_dim_out);
4837 isl_map_free(map);
4838 return -1;
4841 /* Compute an appropriate schedule based on the accesses in
4842 * gen->read and gen->write.
4844 * We use the dependences in gen->prog->scop to compute
4845 * a schedule that has a parallel loop in each tilable band.
4846 * Finally, we select the outermost tilable band.
4848 static void compute_schedule(struct gpu_gen *gen)
4850 isl_union_set *domain;
4851 isl_union_map *dep_raw, *dep;
4852 isl_union_map *sched;
4853 isl_schedule *schedule;
4855 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4857 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4858 dep = isl_union_map_union(dep, dep_raw);
4859 dep = isl_union_map_coalesce(dep);
4861 domain = isl_union_set_copy(gen->prog->scop->domain);
4862 domain = isl_union_set_intersect_params(domain,
4863 isl_set_copy(gen->prog->scop->context));
4864 schedule = isl_union_set_compute_schedule(isl_union_set_copy(domain),
4865 isl_union_map_copy(dep), dep);
4866 if (gen->options->debug->dump_schedule)
4867 isl_schedule_dump(schedule);
4869 sched = select_outer_tilable_band(gen, schedule);
4871 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
4872 sched = isl_union_map_intersect_domain(sched, domain);
4873 gen->sched = sched;
4875 isl_schedule_free(schedule);
4878 /* Compute the sets of array elements that need to be copied in and out.
4880 * In particular, for each array that is written anywhere in gen->prog and
4881 * that is visible outside the corresponding scop, we copy out its entire
4882 * extent.
4884 * Any array elements that is read without first being written needs
4885 * to be copied in. Furthermore, if there are any array elements that
4886 * are copied out, but that are not written inside gen->prog, then
4887 * they also need to be copied in to ensure that the value after execution
4888 * is the same as the value before execution.
4889 * While computing the set of array elements that
4890 * are copied out but not written, we intersect both sets with the context.
4891 * This helps in those cases where the arrays are declared with a fixed size,
4892 * while the accesses are parametric and the context assigns a fixed value
4893 * to the parameters.
4895 static void compute_copy_in_and_out(struct gpu_gen *gen)
4897 int i;
4898 isl_union_set *write;
4899 isl_union_set *copy_in, *copy_out;
4900 isl_union_set *not_written;
4901 isl_union_map *uninitialized;
4903 write = isl_union_map_range(isl_union_map_copy(gen->prog->write));
4904 write = isl_union_set_intersect_params(write,
4905 isl_set_copy(gen->prog->context));
4906 copy_out = isl_union_set_empty(isl_union_set_get_space(write));
4908 for (i = 0; i < gen->prog->n_array; ++i) {
4909 isl_space *space;
4910 isl_set *write_i;
4911 int empty;
4913 if (gen->prog->array[i].local)
4914 continue;
4916 space = isl_space_copy(gen->prog->array[i].dim);
4917 write_i = isl_union_set_extract_set(write, space);
4918 empty = isl_set_fast_is_empty(write_i);
4919 isl_set_free(write_i);
4920 if (empty)
4921 continue;
4923 write_i = isl_set_copy(gen->prog->array[i].extent);
4924 copy_out = isl_union_set_add_set(copy_out, write_i);
4927 copy_out = isl_union_set_intersect_params(copy_out,
4928 isl_set_copy(gen->prog->context));
4930 gen->prog->copy_out = isl_union_set_copy(copy_out);
4932 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
4933 copy_in = isl_union_map_range(uninitialized);
4935 not_written = isl_union_set_subtract(copy_out, write);
4936 copy_in = isl_union_set_union(copy_in, not_written);
4937 gen->prog->copy_in = copy_in;
4940 static struct gpu_stmt_access **expr_extract_access(struct pet_expr *expr,
4941 struct gpu_stmt_access **next_access)
4943 struct gpu_stmt_access *access;
4944 isl_ctx *ctx = isl_map_get_ctx(expr->acc.access);
4946 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4947 assert(access);
4948 access->next = NULL;
4949 access->read = expr->acc.read;
4950 access->write = expr->acc.write;
4951 access->access = isl_map_copy(expr->acc.access);
4952 access->ref_id = isl_id_copy(expr->acc.ref_id);
4954 *next_access = access;
4955 next_access = &(*next_access)->next;
4956 return next_access;
4959 static struct gpu_stmt_access **expr_extract_accesses(struct pet_expr *expr,
4960 struct gpu_stmt_access **next_access)
4962 int i;
4964 for (i = 0; i < expr->n_arg; ++i)
4965 next_access = expr_extract_accesses(expr->args[i],
4966 next_access);
4968 if (expr->type == pet_expr_access)
4969 next_access = expr_extract_access(expr, next_access);
4971 return next_access;
4974 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
4976 struct gpu_stmt_access **next_access = &stmt->accesses;
4978 stmt->accesses = NULL;
4979 expr_extract_accesses(stmt->stmt->body, next_access);
4982 /* Return an array of gpu_stmt representing the statements in "scop".
4984 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4985 __isl_keep isl_set *context)
4987 int i;
4988 struct gpu_stmt *stmts;
4990 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
4991 if (!stmts)
4992 return NULL;
4994 for (i = 0; i < scop->n_stmt; ++i) {
4995 struct gpu_stmt *s = &stmts[i];
4997 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
4998 s->stmt = scop->stmts[i];
4999 pet_stmt_extract_accesses(s);
5002 return stmts;
5005 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5007 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5009 struct gpu_gen *gen = user;
5011 return gen->print(p, gen->prog, gen->tree, gen->print_user);
5014 /* Generate CUDA code for "scop" and print it to "p".
5015 * After generating an AST for the transformed scop as explained below,
5016 * we call "gen->print" to print the AST in the desired output format
5017 * to "p".
5019 * If it turns out that it does not make sense to generate GPU code,
5020 * then we generate CPU code instead.
5022 * The GPU code is generated in a context where at least one
5023 * statement instance is executed. The corresponding guard (if any) is printed
5024 * around the entire generated GPU code, except for the declaration
5025 * of the arrays that are visible outside of the scop and that therefore
5026 * cannot be declared inside the body of any possible guard.
5028 * We first compute a schedule that respects the dependences
5029 * of the original program and select the outermost band
5030 * of tilable dimensions that has at least one parallel loop.
5031 * We then have three blocks of dimensions
5033 * H B G
5035 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5036 * in
5038 * H T P G
5040 * For each iteration of the T loop and for each array, we compute
5041 * the array elements accessed by that iteration, construct a rectangular
5042 * box around it and shift it to the origin. The result is used
5043 * as shared memory for the array.
5045 * We then split off at most 2 parallel loops from the T loops and
5046 * at most 3 parallel loops from the P loops
5048 * H T1 T2 P1 P2 G
5050 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5051 * according to "grid"/"block" sizes.
5053 * H T1T T1P T2 P1T P1P P2 G
5055 * Finally, the T1P and P1P iterators are equated to the block and
5056 * thread dimensions respectively and so are effectively removed.
5057 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5058 * are run on the GPU.
5060 * Code is generated in three stages. We first generate code for the
5061 * host (the H loops), with iterators h%d. Then, for each leaf node
5062 * of the resulting AST, we generate code for the shared loops (up to
5063 * and including T2), with iterators g%d and after equating the H loops
5064 * to h%d parameters and the T1P loops to the block dimensions.
5065 * Finally, we generate code for the remaining loops in a similar fashion.
5067 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5068 struct gpu_gen *gen, struct ppcg_scop *scop,
5069 struct ppcg_options *options)
5071 struct gpu_prog *prog;
5072 isl_ctx *ctx;
5073 isl_set *context, *guard;
5075 if (!scop)
5076 return isl_printer_free(p);
5078 ctx = isl_printer_get_ctx(p);
5079 prog = gpu_prog_alloc(ctx, scop);
5080 if (!prog)
5081 return isl_printer_free(p);
5083 context = isl_set_copy(prog->context);
5084 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5085 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5087 gen->prog = prog;
5088 gen->any_parallelism = 0;
5089 compute_schedule(gen);
5091 if (!gen->any_parallelism) {
5092 isl_set_free(context);
5093 isl_set_free(guard);
5094 p = print_cpu(p, scop, options);
5095 } else {
5096 compute_copy_in_and_out(gen);
5097 gen->tree = generate_host_code(gen);
5098 p = ppcg_print_exposed_declarations(p, prog->scop);
5099 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5100 isl_ast_node_free(gen->tree);
5103 isl_union_map_free(gen->sched);
5105 gpu_prog_free(prog);
5107 return p;
5110 /* Wrapper around generate for use as a ppcg_transform callback.
5112 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5113 struct ppcg_scop *scop, void *user)
5115 struct gpu_gen *gen = user;
5117 return generate(p, gen, scop, gen->options);
5120 /* Transform the code in the file called "input" by replacing
5121 * all scops by corresponding GPU code and write the results to "out".
5123 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5124 struct ppcg_options *options,
5125 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5126 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5127 void *user), void *user)
5129 struct gpu_gen gen;
5130 int r;
5132 gen.ctx = ctx;
5133 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5134 gen.options = options;
5135 gen.kernel_id = 0;
5136 gen.print = print;
5137 gen.print_user = user;
5139 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5141 isl_union_map_free(gen.sizes);
5143 return r;
5146 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5148 struct gpu_prog *prog;
5150 if (!scop)
5151 return NULL;
5153 prog = isl_calloc_type(ctx, struct gpu_prog);
5154 assert(prog);
5156 prog->ctx = ctx;
5157 prog->scop = scop;
5158 prog->context = isl_set_copy(scop->context);
5159 prog->n_stmts = scop->n_stmt;
5160 prog->stmts = extract_stmts(ctx, scop, prog->context);
5161 prog->read = isl_union_map_copy(scop->reads);
5162 prog->write = isl_union_map_copy(scop->writes);
5164 if (!prog->stmts)
5165 return gpu_prog_free(prog);
5167 collect_array_info(prog);
5169 return prog;
5172 void *gpu_prog_free(struct gpu_prog *prog)
5174 if (!prog)
5175 return NULL;
5176 free_array_info(prog);
5177 free_stmts(prog->stmts, prog->n_stmts);
5178 isl_union_set_free(prog->copy_in);
5179 isl_union_set_free(prog->copy_out);
5180 isl_union_map_free(prog->read);
5181 isl_union_map_free(prog->write);
5182 isl_set_free(prog->context);
5183 free(prog);
5184 return NULL;