cuda.c: print_kernel_vars: take isl_printer instead of FILE
[ppcg.git] / gpu.c
blobe0f77d5d66f998ad56f88387022c6ad8934fa0bb
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012 Ecole Normale Superieure
5 * Use of this software is governed by the GNU LGPLv2.1 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>
16 #include <isl/polynomial.h>
17 #include <isl/union_set.h>
18 #include <isl/aff.h>
19 #include <isl/ilp.h>
20 #include <isl/flow.h>
21 #include <isl/band.h>
22 #include <isl/schedule.h>
23 #include <isl/options.h>
24 #include <isl/ast_build.h>
26 #include "gpu.h"
27 #include "schedule.h"
28 #include "ppcg_options.h"
30 /* The fields stride, shift and shift_map only contain valid information
31 * if shift != NULL.
32 * If so, they express that current index is such that if you add shift,
33 * then the result is always a multiple of stride.
34 * shift_map contains the mapping
36 * i -> (i + shift)/stride
38 * Let D represent the initial shared_len dimensions of the computed schedule.
39 * The spaces of "lb" and "shift" are of the form
41 * D -> [b]
43 * "shift_map" is of the form
45 * [D -> i] -> [D -> (i + shift(D))/stride]
47 struct gpu_array_bound {
48 isl_int size;
49 isl_aff *lb;
51 isl_int stride;
52 isl_aff *shift;
53 isl_basic_map *shift_map;
56 /* A tile of an array.
58 * n is the dimension of the array.
59 * bound is an array of size "n" representing the lower bound
60 * and size for each index.
62 struct gpu_array_tile {
63 int n;
64 struct gpu_array_bound *bound;
67 struct gpu_array_info;
69 /* A group of array references in a kernel that should be handled together.
70 * If private_tile is not NULL, then it is mapped to registers.
71 * Otherwise, if shared_tile is not NULL, it is mapped to shared memory.
72 * Otherwise, it is accessed from global memory.
74 struct gpu_array_ref_group {
75 /* The references in this group access this array. */
76 struct gpu_array_info *array;
77 /* Position of this group in the list of reference groups of array. */
78 int nr;
80 /* The following fields are use during the construction of the groups.
81 * access is the combined access relation relative to the shared
82 * memory tiling. In particular, the domain of the map corresponds
83 * to the first shared_len dimensions of the computed schedule.
84 * write is set if any access in the group is a write.
86 isl_map *access;
87 int write;
89 /* The shared memory tile, NULL if none. */
90 struct gpu_array_tile *shared_tile;
92 /* The private memory tile, NULL if none. */
93 struct gpu_array_tile *private_tile;
95 /* References in this group; point to elements of a linked list. */
96 int n_ref;
97 struct gpu_stmt_access **refs;
99 /* Last shared memory tile dimension that affects tile of this group. */
100 int last_shared;
103 struct gpu_gen {
104 isl_ctx *ctx;
105 struct ppcg_options *options;
107 struct gpu_prog *prog;
109 /* tile, grid and block sizes for each kernel */
110 isl_union_map *sizes;
112 /* Identifier of current kernel. */
113 int kernel_id;
114 /* Pointer to the current kernel. */
115 struct ppcg_kernel *kernel;
117 /* First tile dimension. */
118 int tile_first;
119 /* Number of tile dimensions. */
120 int tile_len;
121 /* Number of initial parallel loops among tile dimensions. */
122 int n_parallel;
124 /* Number of dimensions determining shared memory. */
125 int shared_len;
127 /* Number of rows in the untiled schedule. */
128 int untiled_len;
129 /* Number of rows in the tiled schedule. */
130 int tiled_len;
131 /* Number of rows in schedule after tiling/wrapping over threads. */
132 int thread_tiled_len;
134 /* Global untiled schedule. */
135 isl_union_map *sched;
136 /* Local (per kernel launch) tiled schedule. */
137 isl_union_map *tiled_sched;
138 /* Local schedule per shared memory tile loop iteration. */
139 isl_union_map *local_sched;
141 /* Local tiled schedule projected onto the shared tile loops and
142 * the loops that will be wrapped over the threads,
143 * with all shared tile loops parametrized.
145 isl_union_map *shared_sched;
146 /* Projects out the loops that will be wrapped over the threads
147 * from shared_sched.
149 isl_union_map *shared_proj;
151 /* A map that takes the range of shared_sched as input,
152 * wraps the appropriate loops over the threads and then projects
153 * out these loops.
155 isl_map *privatization;
157 /* A map from the shared memory tile loops and the thread indices
158 * (as parameters) to the set of accessed memory elements that
159 * will be accessed through private copies.
161 isl_union_map *private_access;
163 /* The schedule for the current private/shared access
164 * (within print_private_access or print_shared_access).
166 isl_map *copy_sched;
167 /* The array reference group corresponding to copy_sched. */
168 struct gpu_array_ref_group *copy_group;
170 /* First loop to unroll (or -1 if none) in the current part of the
171 * schedule.
173 int first_unroll;
175 int n_grid;
176 int n_block;
177 /* Note: in the input file, the sizes of the grid and the blocks
178 * are specified in the order x, y, z, but internally, the sizes
179 * are stored in reverse order, so that the last element always
180 * refers to the x dimension.
182 int grid_dim[2];
183 int block_dim[3];
184 int *tile_size;
187 /* Print the name of the local copy of a given group of array references.
189 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
190 struct gpu_array_ref_group *group)
192 int global = 0;
194 if (group->private_tile)
195 p = isl_printer_print_str(p, "private_");
196 else if (group->shared_tile)
197 p = isl_printer_print_str(p, "shared_");
198 else
199 global = 1;
200 p = isl_printer_print_str(p, group->array->name);
201 if (!global && group->array->n_group > 1) {
202 p = isl_printer_print_str(p, "_");
203 p = isl_printer_print_int(p, group->nr);
206 return p;
209 /* Collect all references to the given array and store pointers to them
210 * in array->refs.
212 static void collect_references(struct gpu_prog *prog,
213 struct gpu_array_info *array)
215 int i;
216 int n;
218 n = 0;
219 for (i = 0; i < prog->n_stmts; ++i) {
220 struct gpu_stmt *stmt = &prog->stmts[i];
221 struct gpu_stmt_access *access;
223 for (access = stmt->accesses; access; access = access->next) {
224 const char *name;
225 name = isl_map_get_tuple_name(access->access,
226 isl_dim_out);
227 if (name && !strcmp(array->name, name))
228 n++;
232 array->n_ref = n;
233 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
234 assert(array->refs);
236 n = 0;
237 for (i = 0; i < prog->n_stmts; ++i) {
238 struct gpu_stmt *stmt = &prog->stmts[i];
239 struct gpu_stmt_access *access;
241 for (access = stmt->accesses; access; access = access->next) {
242 const char *name;
243 name = isl_map_get_tuple_name(access->access,
244 isl_dim_out);
245 if (!name || strcmp(array->name, name))
246 continue;
248 array->refs[n++] = access;
253 /* Create a gpu_array_tile for an array of dimension "n_index".
255 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
257 int i;
258 struct gpu_array_tile *tile;
260 tile = isl_calloc_type(ctx, struct gpu_array_tile);
261 assert(tile);
263 tile->n = n_index;
265 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
266 assert(tile->bound);
268 for (i = 0; i < n_index; ++i) {
269 isl_int_init(tile->bound[i].size);
270 tile->bound[i].lb = NULL;
271 isl_int_init(tile->bound[i].stride);
272 tile->bound[i].shift = NULL;
273 tile->bound[i].shift_map = NULL;
276 return tile;
279 static void *free_tile(struct gpu_array_tile *tile)
281 int j;
283 if (!tile)
284 return NULL;
286 for (j = 0; j < tile->n; ++j) {
287 isl_int_clear(tile->bound[j].size);
288 isl_int_clear(tile->bound[j].stride);
289 isl_aff_free(tile->bound[j].lb);
290 isl_aff_free(tile->bound[j].shift);
291 isl_basic_map_free(tile->bound[j].shift_map);
293 free(tile->bound);
294 free(tile);
296 return NULL;
299 static struct pet_array *find_array(struct ppcg_scop *scop,
300 __isl_keep isl_set *accessed)
302 int i;
303 isl_id *id;
305 id = isl_set_get_tuple_id(accessed);
307 for (i = 0; i < scop->n_array; ++i) {
308 isl_id *id_i;
310 id_i = isl_set_get_tuple_id(scop->arrays[i]->extent);
311 isl_id_free(id_i);
312 if (id == id_i)
313 break;
315 isl_id_free(id);
317 return i < scop->n_array ? scop->arrays[i] : NULL;
320 /* Compute and return the extent of "array", taking into account the set of
321 * accessed elements.
323 * In particular, the extent in the outer dimension is taken
324 * from "accessed", while then extent in the remaing dimensions
325 * are taken from array->extent.
327 * The extent in the outer dimension cannot be taken from array->extent
328 * because that may be unbounded. Furthermore, even if it is bounded,
329 * it may be larger than the piece of the array that is being accessed.
331 static __isl_give isl_set *compute_extent(struct pet_array *array,
332 __isl_keep isl_set *accessed)
334 int n_index;
335 isl_id *id;
336 isl_set *outer;
337 isl_set *extent;
339 extent = isl_set_copy(array->extent);
341 n_index = isl_set_dim(accessed, isl_dim_set);
342 if (n_index == 0)
343 return extent;
345 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
346 outer = isl_set_copy(accessed);
347 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
348 extent = isl_set_flat_product(outer, extent);
349 id = isl_set_get_tuple_id(accessed);
350 extent = isl_set_set_tuple_id(extent, id);
352 return extent;
355 /* Compute bounds on the host arrays based on the accessed elements
356 * and collect all references to the array.
358 * If the array is zero-dimensional, i.e., a scalar, we check
359 * whether it is read-only.
361 static int extract_array_info(__isl_take isl_set *array, void *user)
363 int i;
364 struct gpu_prog *prog = (struct gpu_prog *)user;
365 const char *name;
366 int n_index;
367 isl_pw_aff **bounds;
368 struct pet_array *pa;
369 isl_set *extent;
371 n_index = isl_set_dim(array, isl_dim_set);
372 name = isl_set_get_tuple_name(array);
373 bounds = isl_alloc_array(isl_set_get_ctx(array),
374 isl_pw_aff *, n_index);
375 assert(bounds);
376 prog->array[prog->n_array].dim = isl_set_get_space(array);
377 prog->array[prog->n_array].name = strdup(name);
378 prog->array[prog->n_array].n_index = n_index;
379 prog->array[prog->n_array].bound = bounds;
381 pa = find_array(prog->scop, array);
382 assert(pa);
384 prog->array[prog->n_array].type = strdup(pa->element_type);
385 prog->array[prog->n_array].size = pa->element_size;
386 prog->array[prog->n_array].local = pa->declared && !pa->exposed;
388 if (n_index == 0) {
389 isl_set *space;
390 isl_union_map *write;
391 int empty;
393 write = isl_union_map_copy(prog->write);
394 space = isl_set_universe(isl_set_get_space(array));
395 write = isl_union_map_intersect_range(write,
396 isl_union_set_from_set(space));
397 empty = isl_union_map_is_empty(write);
398 isl_union_map_free(write);
400 prog->array[prog->n_array].read_only = empty;
403 extent = compute_extent(pa, array);
404 for (i = 0; i < n_index; ++i) {
405 isl_set *dom;
406 isl_local_space *ls;
407 isl_aff *one;
408 isl_pw_aff *bound;
410 bound = isl_set_dim_max(isl_set_copy(extent), i);
411 assert(bound);
412 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
413 ls = isl_local_space_from_space(isl_set_get_space(dom));
414 one = isl_aff_zero_on_domain(ls);
415 one = isl_aff_add_constant_si(one, 1);
416 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
417 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
419 bounds[i] = bound;
421 prog->array[prog->n_array].extent = extent;
423 collect_references(prog, &prog->array[prog->n_array]);
425 prog->n_array++;
427 isl_set_free(array);
428 return 0;
431 void collect_array_info(struct gpu_prog *prog)
433 isl_union_set *arrays;
435 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
436 arrays = isl_union_set_union(arrays,
437 isl_union_map_range(isl_union_map_copy(prog->write)));
438 arrays = isl_union_set_coalesce(arrays);
440 prog->n_array = isl_union_set_n_set(arrays);
441 prog->array = isl_alloc_array(prog->ctx,
442 struct gpu_array_info, prog->n_array);
443 assert(prog->array);
444 prog->n_array = 0;
445 isl_union_set_foreach_set(arrays, &extract_array_info, prog);
446 isl_union_set_free(arrays);
449 static void free_array_info(struct gpu_prog *prog)
451 int i, j;
453 for (i = 0; i < prog->n_array; ++i) {
454 int n_index = prog->array[i].n_index;
455 free(prog->array[i].type);
456 free(prog->array[i].name);
457 for (j = 0; j < n_index; ++j)
458 isl_pw_aff_free(prog->array[i].bound[j]);
459 isl_space_free(prog->array[i].dim);
460 isl_set_free(prog->array[i].extent);
461 free(prog->array[i].bound);
462 free(prog->array[i].refs);
464 free(prog->array);
467 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
468 * as an array or through a pointer reference, but as single data element. At
469 * the moment, scalars are represented as zero dimensional arrays.
471 int gpu_array_is_scalar(struct gpu_array_info *array)
473 return (array->n_index == 0);
476 /* Is "array" a read-only scalar?
478 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
480 return gpu_array_is_scalar(array) && array->read_only;
483 /* Internal data structure for extract_size_of_type.
484 * "type" specifies the name of the space that we want to extract.
485 * "res" is used to store the subset of that space.
487 struct ppcg_extract_size_data {
488 const char *type;
489 isl_set *res;
492 /* This function is called for each set in a union_set.
493 * If the name of the set matches data->type, we store the
494 * set in data->res.
496 static int extract_size_of_type(__isl_take isl_set *size, void *user)
498 struct ppcg_extract_size_data *data = user;
499 const char *name;
501 name = isl_set_get_tuple_name(size);
502 if (name && !strcmp(name, data->type)) {
503 data->res = size;
504 return -1;
507 isl_set_free(size);
508 return 0;
511 /* Given a union map { kernel[i] -> *[...] },
512 * return the range in the space called "type" for the kernel with
513 * sequence number "id".
515 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
516 const char *type, int id)
518 isl_space *space;
519 isl_set *dom;
520 isl_union_set *local_sizes;
521 struct ppcg_extract_size_data data = { type, NULL };
523 if (!sizes)
524 return NULL;
526 space = isl_union_map_get_space(sizes);
527 space = isl_space_set_from_params(space);
528 space = isl_space_add_dims(space, isl_dim_set, 1);
529 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
530 dom = isl_set_universe(space);
531 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
533 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
534 isl_union_map_copy(sizes));
535 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
536 isl_union_set_free(local_sizes);
537 return data.res;
540 /* Given a singleton set, extract the first (at most *len) elements
541 * of the single integer tuple into *sizes and update *len if needed.
543 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
545 int i;
546 int dim;
547 isl_int v;
549 if (!set)
550 return;
552 dim = isl_set_dim(set, isl_dim_set);
553 if (dim < *len)
554 *len = dim;
556 isl_int_init(v);
558 for (i = 0; i < *len; ++i) {
559 int ok;
561 ok = isl_set_plain_is_fixed(set, isl_dim_set, i, &v);
562 assert(ok);
564 sizes[i] = isl_int_get_si(v);
567 isl_int_clear(v);
569 isl_set_free(set);
572 /* Extract user specified "tile" sizes from the "sizes" command line option,
573 * defaulting to option->tile_size in each dimension.
575 static void read_tile_sizes(struct gpu_gen *gen)
577 int n;
578 isl_set *size;
580 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
581 assert(gen->tile_size);
582 for (n = 0; n < gen->tile_len; ++n)
583 gen->tile_size[n] = gen->options->tile_size;
585 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
586 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
588 if (gen->n_parallel > gen->tile_len)
589 gen->n_parallel = gen->tile_len;
592 /* Extract user specified "block" sizes from the "sizes" command line option,
593 * after filling in some potentially useful defaults.
595 static void read_block_sizes(struct gpu_gen *gen)
597 int n;
598 isl_set *size;
600 n = gen->n_parallel;
601 gen->n_block = (n <= 3) ? n : 3;
602 switch (gen->n_block) {
603 case 1:
604 gen->block_dim[0] = 512;
605 break;
606 case 2:
607 gen->block_dim[0] = 32;
608 gen->block_dim[1] = 16;
609 break;
610 default:
611 gen->block_dim[0] = 32;
612 gen->block_dim[1] = 4;
613 gen->block_dim[2] = 4;
614 break;
617 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
618 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
621 /* Extract user specified "grid" sizes from the "sizes" command line option,
622 * after filling in some potentially useful defaults.
624 static void read_grid_sizes(struct gpu_gen *gen)
626 int n = gen->n_parallel;
627 isl_set *size;
629 gen->n_grid = (n <= 2) ? n : 2;
630 switch (gen->n_grid) {
631 case 1:
632 gen->grid_dim[0] = 32768;
633 break;
634 default:
635 gen->grid_dim[0] = 256;
636 gen->grid_dim[1] = 256;
637 break;
640 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
641 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
644 /* Extract user specified sizes from the "sizes" command line option
645 * after filling in some potentially useful defaults.
647 static void read_sizes(struct gpu_gen *gen)
649 read_tile_sizes(gen);
650 read_block_sizes(gen);
651 read_grid_sizes(gen);
654 static void free_stmts(struct gpu_stmt *stmts, int n)
656 int i;
658 for (i = 0; i < n; ++i) {
659 struct gpu_stmt_access *access, *next;
661 for (access = stmts[i].accesses; access; access = next) {
662 next = access->next;
663 isl_map_free(access->access);
664 free(access);
667 isl_id_free(stmts[i].id);
669 free(stmts);
672 void clear_gpu_gen(struct gpu_gen *gen)
674 isl_union_map_free(gen->sizes);
675 isl_union_map_free(gen->sched);
678 /* Construct a map from a domain of dimensionality "len"
679 * to a domain of dimensionality "len" + "tile_len" that tiles
680 * the "tile_len" coordinates starting at "first".
681 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
682 * "dim" prescribes the parameters.
684 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
685 int first, int tile_len, int *tile_size)
687 int i;
688 isl_basic_map *bmap;
689 isl_constraint *c;
690 isl_local_space *ls;
692 dim = isl_space_add_dims(dim, isl_dim_in, len);
693 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
694 bmap = isl_basic_map_universe(isl_space_copy(dim));
695 ls = isl_local_space_from_space(dim);
697 for (i = 0; i < len - tile_len; ++i) {
698 int j = i < first ? i : i + tile_len;
699 int k = i < first ? i : i + 2 * tile_len;
701 c = isl_equality_alloc(isl_local_space_copy(ls));
702 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
703 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
704 bmap = isl_basic_map_add_constraint(bmap, c);
707 for (i = 0; i < tile_len; ++i) {
708 c = isl_equality_alloc(isl_local_space_copy(ls));
709 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
710 first + i, -1);
711 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
712 first + i, tile_size[i]);
713 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
714 first + i + tile_len, 1);
715 bmap = isl_basic_map_add_constraint(bmap, c);
717 c = isl_inequality_alloc(isl_local_space_copy(ls));
718 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
719 first + i + tile_len, 1);
720 bmap = isl_basic_map_add_constraint(bmap, c);
722 c = isl_inequality_alloc(isl_local_space_copy(ls));
723 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
724 first + i + tile_len, -1);
725 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
726 bmap = isl_basic_map_add_constraint(bmap, c);
729 isl_local_space_free(ls);
731 return isl_map_from_basic_map(bmap);
734 /* Construct a map from a domain of dimensionality "len"
735 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
736 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
737 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
738 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
739 * that are projected out at the end.
740 * "dim" prescribes the parameters.
742 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
743 int first, int wrap_len, int *wrap_size)
745 int i;
746 isl_basic_map *bmap;
747 isl_constraint *c;
748 isl_local_space *ls;
750 dim = isl_space_add_dims(dim, isl_dim_in, len);
751 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
752 bmap = isl_basic_map_universe(isl_space_copy(dim));
753 ls = isl_local_space_from_space(dim);
755 for (i = 0; i < len; ++i) {
756 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
758 c = isl_equality_alloc(isl_local_space_copy(ls));
759 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
760 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
761 bmap = isl_basic_map_add_constraint(bmap, c);
764 for (i = 0; i < wrap_len; ++i) {
765 c = isl_equality_alloc(isl_local_space_copy(ls));
766 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
767 first + i, -1);
768 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
769 first + wrap_len + i, 1);
770 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
771 first + 2 * wrap_len + i, wrap_size[i]);
772 bmap = isl_basic_map_add_constraint(bmap, c);
774 c = isl_inequality_alloc(isl_local_space_copy(ls));
775 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
776 first + wrap_len + i, 1);
777 bmap = isl_basic_map_add_constraint(bmap, c);
779 c = isl_inequality_alloc(isl_local_space_copy(ls));
780 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
781 first + wrap_len + i, -1);
782 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
783 bmap = isl_basic_map_add_constraint(bmap, c);
786 isl_local_space_free(ls);
788 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
789 first + 2 * wrap_len, wrap_len);
791 return isl_map_from_basic_map(bmap);
794 /* Add "n" parameters named prefix%d.
796 static __isl_give isl_set *add_params( __isl_take isl_set *set,
797 int n, const char *prefix)
799 int i;
800 unsigned nparam;
801 char name[20];
803 nparam = isl_set_dim(set, isl_dim_param);
804 set = isl_set_add_dims(set, isl_dim_param, n);
806 for (i = 0; i < n; ++i) {
807 snprintf(name, sizeof(name), "%s%d", prefix, i);
808 set = isl_set_set_dim_name(set, isl_dim_param,
809 nparam + i, name);
812 return set;
815 /* Equate the "n" dimensions of "set" starting at "first" to
816 * freshly created parameters named prefix%d.
818 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
819 int first, int n, const char *prefix)
821 int i;
822 unsigned nparam;
824 nparam = isl_set_dim(set, isl_dim_param);
826 set = add_params(set, n, prefix);
828 for (i = 0; i < n; ++i)
829 set = isl_set_equate(set, isl_dim_param, nparam + i,
830 isl_dim_set, first + i);
832 return set;
835 /* Given a parameter space "space", create a set of dimension "len"
836 * of which the "n" dimensions starting at "first" are equated to
837 * freshly created parameters named prefix%d.
839 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
840 int len, int first, int n, const char *prefix)
842 isl_set *set;
844 space = isl_space_set_from_params(space);
845 space = isl_space_add_dims(space, isl_dim_set, len);
846 set = isl_set_universe(space);
848 return parametrize(set, first, n, prefix);
851 /* Tile the B loops over the tile sizes and then tile/wrap
852 * the T1 loops over the blocks.
854 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
855 __isl_take isl_union_map *sched)
857 isl_space *dim;
858 isl_map *tiling, *block_tiling;
860 dim = isl_union_map_get_space(sched);
861 tiling = tile(isl_space_copy(dim), gen->untiled_len,
862 gen->tile_first, gen->tile_len, gen->tile_size);
864 if (gen->options->wrap)
865 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
866 gen->tile_first, gen->n_grid, gen->grid_dim);
867 else
868 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
869 gen->tile_first, gen->n_grid, gen->grid_dim);
871 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
873 tiling = isl_map_apply_range(tiling, block_tiling);
875 sched = isl_union_map_apply_range(sched,
876 isl_union_map_from_map(tiling));
878 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
880 return sched;
883 /* Equate the "T1P" iterators in the tiled schedule "sched"
884 * to the block dimensions.
886 static __isl_give isl_union_map *parametrize_tiled_schedule(
887 struct gpu_gen *gen, __isl_take isl_union_map *sched)
889 isl_space *dim;
890 isl_set *par;
892 dim = isl_union_map_get_space(sched);
893 par = parametrization(dim, gen->tiled_len,
894 gen->tile_first + gen->n_grid, gen->n_grid, "b");
895 sched = isl_union_map_intersect_range(sched,
896 isl_union_set_from_set(par));
898 return sched;
901 /* Tile/wrap the P1 loops over the threads.
903 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
904 __isl_take isl_union_map *sched)
906 isl_space *dim;
907 isl_map *tiling;
908 isl_set *par;
910 dim = isl_union_map_get_space(sched);
912 if (gen->options->wrap)
913 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
914 gen->shared_len, gen->n_block, gen->block_dim);
915 else
916 tiling = tile(isl_space_copy(dim), gen->tiled_len,
917 gen->shared_len, gen->n_block, gen->block_dim);
918 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
920 sched = isl_union_map_apply_range(sched,
921 isl_union_map_from_map(tiling));
923 par = parametrization(dim, gen->thread_tiled_len,
924 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
925 gen->n_block, "t");
926 sched = isl_union_map_intersect_range(sched,
927 isl_union_set_from_set(par));
929 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
931 return sched;
934 /* If the user asked for it, scale the shared memory tile loops
935 * (T1T and T2) of "sched" by gen->tile_size[i].
936 * If we are not performing "wrapping", then additionally scale the T1P
937 * loops by gen->grid_dim[i].
939 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
940 __isl_take isl_union_map *sched)
942 int i;
943 isl_space *dim;
944 isl_basic_map *scale;
945 isl_constraint *c;
946 isl_local_space *ls;
948 if (!gen->options->scale_tile_loops)
949 return sched;
951 dim = isl_union_map_get_space(sched);
952 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
953 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
954 scale = isl_basic_map_universe(isl_space_copy(dim));
955 ls = isl_local_space_from_space(dim);
957 for (i = 0; i < gen->tiled_len; ++i) {
958 int f = 1;
960 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
961 f = gen->tile_size[i - gen->tile_first];
962 if (!gen->options->wrap)
963 f *= gen->grid_dim[i - gen->tile_first];
964 } else if (i >= gen->tile_first + gen->n_grid &&
965 i < gen->tile_first + gen->n_grid + gen->tile_len) {
966 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
969 c = isl_equality_alloc(isl_local_space_copy(ls));
970 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
971 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
972 scale = isl_basic_map_add_constraint(scale, c);
975 isl_local_space_free(ls);
977 sched = isl_union_map_apply_range(sched,
978 isl_union_map_from_map(isl_map_from_basic_map(scale)));
980 return sched;
983 /* If we are not performing "wrapping" and if the user asked for it,
984 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
986 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
987 __isl_take isl_union_map *sched)
989 int i;
990 isl_space *dim;
991 isl_basic_map *scale;
992 isl_constraint *c;
993 isl_local_space *ls;
995 if (gen->options->wrap)
996 return sched;
997 if (!gen->options->scale_tile_loops)
998 return sched;
1000 dim = isl_union_map_get_space(sched);
1001 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1002 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1003 scale = isl_basic_map_universe(isl_space_copy(dim));
1004 ls = isl_local_space_from_space(dim);
1006 for (i = 0; i < gen->thread_tiled_len; ++i) {
1007 int f = 1;
1009 if (i >= gen->shared_len &&
1010 i < gen->shared_len + gen->n_block)
1011 f = gen->block_dim[i - gen->shared_len];
1013 c = isl_equality_alloc(isl_local_space_copy(ls));
1014 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1015 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1016 scale = isl_basic_map_add_constraint(scale, c);
1019 isl_local_space_free(ls);
1021 sched = isl_union_map_apply_range(sched,
1022 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1024 return sched;
1027 /* If we are not performing "wrapping" and if the user asked for it,
1028 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1030 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1031 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1033 int i;
1034 isl_space *dim;
1035 isl_basic_map *scale;
1036 isl_constraint *c;
1037 isl_local_space *ls;
1039 if (gen->options->wrap)
1040 return sched;
1041 if (!gen->options->scale_tile_loops)
1042 return sched;
1044 dim = isl_union_map_get_space(sched);
1045 dim = isl_space_add_dims(dim, isl_dim_in, len);
1046 dim = isl_space_add_dims(dim, isl_dim_out, len);
1047 scale = isl_basic_map_universe(isl_space_copy(dim));
1048 ls = isl_local_space_from_space(dim);
1050 for (i = 0; i < len; ++i) {
1051 int f = 1;
1053 if (i >= first && i < first + n_tile)
1054 f = gen->block_dim[i - first];
1056 c = isl_equality_alloc(isl_local_space_copy(ls));
1057 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1058 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1059 scale = isl_basic_map_add_constraint(scale, c);
1062 isl_local_space_free(ls);
1064 sched = isl_union_map_apply_range(sched,
1065 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1067 return sched;
1070 /* Add "len" parameters p[i] called prefix%d,
1071 * with bounds to 0 <= p[i] < size[i].
1073 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1074 int len, int *size, const char *prefix)
1076 int i;
1077 unsigned nparam;
1078 isl_space *dim;
1079 isl_basic_set *bset;
1080 isl_constraint *c;
1081 isl_local_space *ls;
1082 char name[20];
1084 nparam = isl_set_dim(set, isl_dim_param);
1085 set = isl_set_add_dims(set, isl_dim_param, len);
1087 for (i = 0; i < len; ++i) {
1088 snprintf(name, sizeof(name), "%s%d", prefix, i);
1089 set = isl_set_set_dim_name(set, isl_dim_param,
1090 nparam + i, name);
1093 dim = isl_set_get_space(set);
1094 bset = isl_basic_set_universe(isl_space_copy(dim));
1095 ls = isl_local_space_from_space(dim);
1097 for (i = 0; i < len; ++i) {
1098 c = isl_inequality_alloc(isl_local_space_copy(ls));
1099 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1100 nparam + i, 1);
1101 bset = isl_basic_set_add_constraint(bset, c);
1103 c = isl_inequality_alloc(isl_local_space_copy(ls));
1104 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1105 nparam + i, -1);
1106 c = isl_constraint_set_constant_si(c, size[i] - 1);
1107 bset = isl_basic_set_add_constraint(bset, c);
1110 isl_local_space_free(ls);
1112 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1115 /* Add "len" parameters p[i] called prefix%d,
1116 * with bounds to 0 <= p[i] < size[i].
1118 static __isl_give isl_set *add_bounded_parameters_dynamic(
1119 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1120 const char *prefix)
1122 int i, len;
1123 unsigned nparam;
1124 isl_space *space;
1125 isl_local_space *ls;
1126 char name[20];
1128 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1129 nparam = isl_set_dim(set, isl_dim_param);
1130 set = isl_set_add_dims(set, isl_dim_param, len);
1132 for (i = 0; i < len; ++i) {
1133 snprintf(name, sizeof(name), "%s%d", prefix, i);
1134 set = isl_set_set_dim_name(set, isl_dim_param,
1135 nparam + i, name);
1138 space = isl_space_params(isl_set_get_space(set));
1139 ls = isl_local_space_from_space(space);
1140 for (i = 0; i < len; ++i) {
1141 isl_pw_aff *param, *size_i, *zero;
1142 isl_set *bound;
1144 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1145 isl_dim_param, nparam + i);
1147 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1148 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1149 set = isl_set_intersect_params(set, bound);
1151 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1152 bound = isl_pw_aff_ge_set(param, zero);
1153 set = isl_set_intersect_params(set, bound);
1155 isl_local_space_free(ls);
1157 return set;
1160 /* Given a mapping "sched" of the form
1162 * [D -> A] -> [D -> T(A)]
1164 * apply the mapping encoded in tile->bound[i].shift_map
1165 * to the range of "sched".
1166 * The mappings in tile->bound[i].shift_map are of the form
1168 * [D -> a] -> [D -> s(D,a)]
1170 * We first compose them with a mapping
1172 * [D -> v] -> v
1174 * (If tile->bound[i].shift_map is not set, then it is assumed to be
1175 * an identity mapping and then we use this second mapping instead.)
1176 * This results in
1178 * [D -> a] -> s(D,a)
1180 * We precompose them with a projection on the i th dimension to obtain
1182 * [D -> T] -> s(D,T)
1184 * and collect these into
1186 * [D -> T] -> S(D,T)
1188 * Introducing D in the range yields
1190 * [D -> T] -> [D -> S(D,T)]
1192 * and application to "sched" yields
1194 * [D -> A] -> [D -> S(D,T(A))]
1196 static __isl_give isl_map *pre_shift(__isl_take isl_map *sched,
1197 struct gpu_array_tile *tile)
1199 int i;
1200 isl_ctx *ctx = isl_map_get_ctx(sched);
1201 isl_space *space, *space2;
1202 isl_basic_map *def;
1203 isl_map *map, *id, *pre_shift;
1205 space = isl_space_range(isl_map_get_space(sched));
1206 space2 = isl_space_from_domain(isl_space_copy(space));
1207 pre_shift = isl_map_universe(space2);
1208 space = isl_space_domain(isl_space_unwrap(space));
1209 id = isl_map_identity(isl_space_map_from_set(isl_space_copy(space)));
1210 space = isl_space_from_domain(space);
1211 space = isl_space_add_dims(space, isl_dim_out, 1);
1212 def = isl_basic_map_range_map(isl_basic_map_universe(space));
1214 for (i = 0; i < tile->n; ++i) {
1215 isl_basic_map *bmap, *drop;
1216 isl_map *proj;
1218 space = isl_space_alloc(ctx, 0, tile->n, tile->n);
1219 proj = isl_map_identity(space);
1220 proj = isl_map_project_out(proj, isl_dim_out,
1221 i + 1, tile->n - (i + 1));
1222 proj = isl_map_project_out(proj, isl_dim_out, 0, i);
1223 proj = isl_map_product(isl_map_copy(id), proj);
1225 if (!tile->bound[i].shift_map)
1226 bmap = isl_basic_map_copy(def);
1227 else {
1228 bmap = isl_basic_map_copy(tile->bound[i].shift_map);
1229 bmap = isl_basic_map_apply_range(bmap,
1230 isl_basic_map_copy(def));
1233 map = isl_map_from_basic_map(bmap);
1234 map = isl_map_apply_range(proj, map);
1235 pre_shift = isl_map_flat_range_product(pre_shift, map);
1238 isl_map_free(id);
1239 isl_basic_map_free(def);
1241 space = isl_space_domain(isl_map_get_space(pre_shift));
1242 map = isl_map_domain_map(isl_map_universe(isl_space_unwrap(space)));
1243 pre_shift = isl_map_range_product(map, pre_shift);
1245 sched = isl_map_apply_range(sched, pre_shift);
1247 return sched;
1250 /* Given an access relation to a tile of an array, construct a map that
1251 * maps each element in the space of the access relation
1252 * to a copy of the tile shifted to the origin
1253 * (based on the lower bounds in group->private_tile or group->shared_tile).
1254 * If any of the indices is strided, then
1255 * {private,shared}_tile->bound[i].shift_map is applied to the index first.
1256 * The domain space of the resulting map is that of access "access",
1257 * while the range space is anonymous.
1258 * The resulting map only encodes the mapping to the shift tile and
1259 * not the constraints of "access".
1261 * Let the space of the access relation be
1263 * D -> A
1265 * We first construct an identity relation on a wrapped copy of this space,
1266 * except that it strips off the name of array
1268 * [D -> A] -> [D -> T(A)] (1)
1270 * The bounds in tile->bound[i].lb are of the form
1272 * D -> b(D)
1274 * We collect them into
1276 * D -> B(D)
1278 * and then transform them into
1280 * [D -> T] -> T - B(D) (2)
1282 * Combining those two mappings (1) and (2) yields
1284 * [D -> A] -> T(A) - B(D)
1286 * If there are any strides, then (1) is first transformed into (1')
1288 * [D -> A] -> [D -> T'(A)] (1')
1290 * by a call to pre_shift.
1292 static __isl_give isl_map *shift_access(__isl_take isl_map *access,
1293 struct gpu_array_ref_group *group)
1295 int i;
1296 isl_space *space;
1297 isl_map *id1, *id2;
1298 isl_map *map;
1299 isl_map *shift;
1300 isl_map *sched;
1301 struct gpu_array_tile *tile;
1302 int n_index = group->array->n_index;
1304 tile = group->private_tile;
1305 if (!tile)
1306 tile = group->shared_tile;
1308 space = isl_space_domain(isl_map_get_space(access));
1309 space = isl_space_map_from_set(space);
1310 id1 = isl_map_identity(space);
1311 space = isl_space_range(isl_map_get_space(access));
1312 space = isl_space_map_from_set(space);
1313 space = isl_space_set_tuple_name(space, isl_dim_out, NULL);
1314 id2 = isl_map_identity(space);
1315 sched = isl_map_product(id1, id2);
1317 space = isl_space_unwrap(isl_space_range(isl_map_get_space(sched)));
1318 space = isl_space_from_domain(isl_space_domain(space));
1319 shift = isl_map_universe(space);
1320 for (i = 0; i < n_index; ++i) {
1321 map = isl_map_from_aff(isl_aff_copy(tile->bound[i].lb));
1322 shift = isl_map_flat_range_product(shift, map);
1325 space = isl_space_unwrap(isl_space_range(isl_map_get_space(sched)));
1326 map = isl_map_universe(space);
1327 id1 = isl_map_range_map(isl_map_copy(map));
1328 map = isl_map_domain_map(map);
1329 shift = isl_map_neg(shift);
1330 shift = isl_map_apply_range(map, shift);
1331 shift = isl_map_sum(id1, shift);
1333 for (i = 0; i < n_index; ++i)
1334 if (tile->bound[i].shift_map)
1335 break;
1337 if (i < n_index)
1338 sched = pre_shift(sched, tile);
1340 sched = isl_map_apply_range(sched, shift);
1342 isl_map_free(access);
1344 return sched;
1347 /* Given a schedule that iterates over all elements in a piece of an array,
1348 * perform tiling/wrapping over the threads.
1350 * In particular, we tile the final iterators so that the final thread
1351 * dimension runs over the final array dimension.
1352 * However, if those final iterators have only a single iteration,
1353 * we try to tile earlier iterators instead.
1355 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1356 __isl_take isl_map *sched)
1358 isl_space *dim;
1359 isl_union_map *usched;
1360 isl_map *tiling;
1361 isl_set *par;
1362 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1363 int n_tile;
1364 int first;
1366 n_tile = gen->n_block;
1367 if (n_tile > nvar) {
1368 int i;
1369 sched = isl_map_insert_dims(sched,
1370 isl_dim_out, 0, n_tile - nvar);
1371 for (i = 0; i < n_tile - nvar; ++i)
1372 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1373 nvar = n_tile;
1376 first = nvar - n_tile;
1378 for (; first > 0; first --)
1379 if (!isl_map_plain_is_fixed(sched, isl_dim_out,
1380 first + n_tile - 1, NULL))
1381 break;
1383 dim = isl_map_get_space(sched);
1384 dim = isl_space_params(dim);
1385 if (gen->options->wrap)
1386 tiling = wrap(isl_space_copy(dim), nvar, first,
1387 n_tile, gen->block_dim);
1388 else
1389 tiling = tile(isl_space_copy(dim), nvar, first,
1390 n_tile, gen->block_dim);
1391 sched = isl_map_apply_range(sched, tiling);
1393 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1394 sched = isl_map_intersect_range(sched, par);
1396 usched = isl_union_map_from_map(sched);
1397 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1398 first, n_tile);
1399 sched = isl_map_from_union_map(usched);
1401 return sched;
1404 /* Given an index expression "pa" into a tile of an array, adjust the expression
1405 * to a shift of the tile to the origin
1406 * (based on the lower bounds in "bound".
1407 * If the index is strided, then we first add
1408 * bound->shift and divide by bound->stride.
1409 * In the end, we compute the gist with respect to "domain".
1411 * All of the input expression "pa", the set "domain" and
1412 * the output are expressed in terms of the AST schedule domain.
1413 * The expressions in "bound" are expressed
1414 * in terms of the first shared_len dimensions of the schedule computed by PPCG.
1415 * The mapping "sched2shared" maps the former domain to the latter domain.
1417 static __isl_give isl_pw_aff *shift_index(__isl_take isl_pw_aff *pa,
1418 struct gpu_array_info *array,
1419 struct gpu_array_bound *bound, __isl_take isl_set *domain,
1420 __isl_take isl_map *sched2shared)
1422 isl_map *map;
1423 isl_pw_aff *tmp;
1424 isl_pw_multi_aff *pma;
1426 if (bound->shift) {
1427 map = isl_map_from_aff(isl_aff_copy(bound->shift));
1428 map = isl_map_apply_range(isl_map_copy(sched2shared), map);
1429 pma = isl_pw_multi_aff_from_map(map);
1430 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1431 isl_pw_multi_aff_free(pma);
1432 pa = isl_pw_aff_add(pa, tmp);
1433 pa = isl_pw_aff_scale_down(pa, bound->stride);
1437 map = isl_map_from_aff(isl_aff_copy(bound->lb));
1438 map = isl_map_apply_range(sched2shared, map);
1439 pma = isl_pw_multi_aff_from_map(map);
1440 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1441 isl_pw_multi_aff_free(pma);
1442 pa = isl_pw_aff_sub(pa, tmp);
1443 pa = isl_pw_aff_coalesce(pa);
1444 pa = isl_pw_aff_gist(pa, domain);
1446 return pa;
1449 /* Return the union of all read (read = 1) and/or write (write = 1)
1450 * access relations in the group.
1452 static __isl_give isl_union_map *group_access_relation(
1453 struct gpu_array_ref_group *group, int read, int write)
1455 int i;
1456 isl_union_map *access;
1458 access = isl_union_map_empty(isl_map_get_space(group->access));
1459 for (i = 0; i < group->n_ref; ++i) {
1460 isl_map *map_i;
1462 if (!((read && group->refs[i]->read) ||
1463 (write && group->refs[i]->write)))
1464 continue;
1465 map_i = isl_map_copy(group->refs[i]->access);
1466 access = isl_union_map_union(access,
1467 isl_union_map_from_map(map_i));
1470 return access;
1473 /* Return a map from the first shared_len dimensions of the computed
1474 * schedule to the values of the given index "i"
1475 * of the elements in the array tile in global memory that corresponds
1476 * to the shared memory copy.
1477 * In particular, if a is the index, then the range of the map
1479 * { D -> [a] }
1481 * is constrained as follows
1483 * tile_offset(D) <= a <= tile_offset(D) + tile_size - 1 (1)
1485 * and
1487 * 0 <= a <= array_size - 1 (2)
1490 * Note that if some stride has been detected (i.e., when
1491 * group->shared_tile->bound[i].shift is set), then offset and size (i.e.,
1492 * constraints (1)) apply to the shifted and scaled down copy of the tile.
1493 * These constraints therefore have to be mapped back to the original
1494 * array space using the inverse of the shift_map.
1496 static __isl_give isl_map *group_tile_dim(struct gpu_array_ref_group *group,
1497 int i)
1499 isl_aff *aff;
1500 isl_space *space;
1501 isl_map *map, *tile, *gt;
1502 isl_set *bound;
1504 map = isl_map_from_aff(isl_aff_copy(group->shared_tile->bound[i].lb));
1505 space = isl_space_range(isl_map_get_space(map));
1506 map = isl_map_apply_range(map, isl_map_lex_le(isl_space_copy(space)));
1507 tile = map;
1509 aff = isl_aff_copy(group->shared_tile->bound[i].lb);
1510 aff = isl_aff_add_constant(aff, group->shared_tile->bound[i].size);
1511 map = isl_map_from_aff(aff);
1512 gt = isl_map_lex_gt(space);
1513 map = isl_map_apply_range(map, isl_map_copy(gt));
1514 tile = isl_map_intersect(tile, map);
1516 if (group->shared_tile->bound[i].shift) {
1517 isl_basic_map *shift;
1518 shift = isl_basic_map_copy(group->shared_tile->bound[i].shift_map);
1519 shift = isl_basic_map_reverse(shift);
1520 tile = isl_set_unwrap(isl_set_apply(isl_map_wrap(tile),
1521 isl_map_from_basic_map(shift)));
1524 tile = isl_map_lower_bound_si(tile, isl_dim_out, 0, 0);
1526 bound = isl_set_from_pw_aff(isl_pw_aff_copy(group->array->bound[i]));
1527 bound = isl_set_apply(bound, gt);
1528 tile = isl_map_intersect_range(tile, bound);
1530 return tile;
1533 /* Return a map from the first shared_len dimensions of the computed
1534 * schedule to the array tile in
1535 * global memory that corresponds to the shared memory copy.
1537 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1539 int i;
1540 int n_index = group->array->n_index;
1541 isl_map *tile;
1543 tile = group_tile_dim(group, 0);
1544 for (i = 1; i < n_index; ++i) {
1545 isl_map *tile_i;
1547 tile_i = group_tile_dim(group, i);
1548 tile = isl_map_flat_range_product(tile, tile_i);
1551 tile = isl_map_set_tuple_name(tile, isl_dim_out, group->array->name);
1553 return tile;
1556 /* Given a mapping "sched" from the AST schedule to a domain,
1557 * return the corresponding mapping from the AST schedule to
1558 * to the first shared_len dimensions of the schedule computed by PPCG.
1560 static __isl_give isl_map *compute_sched_to_shared(struct gpu_gen *gen,
1561 __isl_take isl_map *sched)
1563 isl_union_map *umap;
1564 isl_space *space;
1565 isl_map *map;
1567 space = isl_space_range(isl_map_get_space(sched));
1568 space = isl_space_from_domain(space);
1569 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1571 umap = isl_union_map_copy(gen->shared_sched);
1572 umap = isl_union_map_apply_range(umap,
1573 isl_union_map_copy(gen->shared_proj));
1574 map = isl_union_map_extract_map(umap, space);
1575 isl_union_map_free(umap);
1577 sched = isl_map_apply_range(sched, map);
1578 sched = isl_map_detect_equalities(sched);
1580 return sched;
1583 /* Set unroll[j] if the input dimension j is involved in
1584 * the index expression represented by ma.
1586 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1587 void *user)
1589 int i, j;
1590 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1591 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1592 int *unroll = user;
1594 for (i = 0; i < n_out; ++i) {
1595 isl_aff *aff;
1597 aff = isl_multi_aff_get_aff(ma, i);
1598 for (j = 0; j < n_in; ++j)
1599 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1600 unroll[j] = 1;
1601 isl_aff_free(aff);
1604 isl_set_free(set);
1605 isl_multi_aff_free(ma);
1606 return 0;
1609 /* Given an array pos mapping input dimensions to the corresponding
1610 * output dimension, construct the corresponding map.
1612 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1613 int *pos, int len)
1615 int i;
1616 isl_constraint *c;
1617 isl_basic_map *bmap;
1618 isl_local_space *ls;
1620 dim = isl_space_add_dims(dim, isl_dim_in, len);
1621 dim = isl_space_add_dims(dim, isl_dim_out, len);
1622 bmap = isl_basic_map_universe(isl_space_copy(dim));
1623 ls = isl_local_space_from_space(dim);
1625 for (i = 0; i < len; ++i) {
1626 c = isl_equality_alloc(isl_local_space_copy(ls));
1627 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1628 -1);
1629 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1631 bmap = isl_basic_map_add_constraint(bmap, c);
1633 isl_local_space_free(ls);
1635 return isl_map_from_basic_map(bmap);
1638 /* Find all loops involved in any of the index expressions for any of
1639 * the private accesses, move them innermost and then mark them as
1640 * requiring unrolling by setting gen->first_unroll.
1641 * The loops involved should all be parallel because of the checks
1642 * we performed in check_private_group_access. Moving them innermost
1643 * is therefore a valid transformation.
1645 * Loops up to gen->shared_len are generated before the mapping to
1646 * threads is applied. They should therefore be ignored.
1648 * We compute the hidden equalities of the schedule first
1649 * since we will need them in our calls to isl_pw_multi_aff_from_map
1650 * and because we want to make sure that the same equalities
1651 * are also available to the code generator.
1653 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1654 __isl_take isl_union_map *sched)
1656 int i, j;
1657 int unroll[gen->thread_tiled_len];
1658 int perm[gen->thread_tiled_len];
1659 isl_space *dim;
1660 isl_map *permute;
1661 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1663 gen->first_unroll = -1;
1665 sched = isl_union_map_detect_equalities(sched);
1666 for (i = 0; i < gen->thread_tiled_len; ++i)
1667 unroll[i] = 0;
1668 for (i = 0; i < gen->prog->n_array; ++i) {
1669 struct gpu_array_info *array = &gen->prog->array[i];
1671 for (j = 0; j < array->n_group; ++j) {
1672 isl_union_map *access;
1673 isl_map *acc;
1674 isl_pw_multi_aff *pma;
1676 if (!array->groups[j]->private_tile)
1677 continue;
1679 access = group_access_relation(array->groups[j], 1, 1);
1680 access = isl_union_map_apply_domain(access,
1681 isl_union_map_copy(sched));
1683 acc = isl_map_from_union_map(access);
1684 pma = isl_pw_multi_aff_from_map(acc);
1685 isl_pw_multi_aff_foreach_piece(pma,
1686 &check_unroll, unroll);
1688 isl_pw_multi_aff_free(pma);
1692 for (i = gen->shared_len; i < len; ++i)
1693 if (unroll[i])
1694 break;
1696 if (i >= len)
1697 return sched;
1699 for (i = len; i < gen->thread_tiled_len; ++i)
1700 if (unroll[i])
1701 return sched;
1703 j = 0;
1704 for (i = 0; i < gen->shared_len; ++i)
1705 perm[i] = j++;
1706 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1707 if (!unroll[i])
1708 perm[i] = j++;
1709 gen->first_unroll = j - gen->shared_len;
1710 for (i = gen->shared_len; i < len; ++i)
1711 if (unroll[i])
1712 perm[i] = j++;
1714 dim = isl_union_map_get_space(sched);
1715 permute = permutation(dim, perm, gen->thread_tiled_len);
1716 sched = isl_union_map_apply_range(sched,
1717 isl_union_map_from_map(permute));
1719 return sched;
1722 /* Given a constraint
1724 * a(p,i) + j = g f(e)
1726 * or -a(p,i) - j = g f(e) if sign < 0,
1727 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1728 * a(p,i) is assumed to be an expression in only the parameters
1729 * and the input dimensions.
1731 static void extract_stride(__isl_keep isl_constraint *c,
1732 struct gpu_array_bound *bound, isl_int stride, int sign)
1734 int i;
1735 isl_int v;
1736 isl_space *space;
1737 unsigned nparam;
1738 unsigned nvar;
1739 isl_aff *aff;
1741 isl_int_set(bound->stride, stride);
1743 space = isl_constraint_get_space(c);
1744 space = isl_space_domain(space);
1746 nparam = isl_space_dim(space, isl_dim_param);
1747 nvar = isl_space_dim(space, isl_dim_set);
1749 isl_int_init(v);
1751 isl_constraint_get_constant(c, &v);
1752 if (sign < 0)
1753 isl_int_neg(v, v);
1754 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1755 aff = isl_aff_set_constant(aff, v);
1757 for (i = 0; i < nparam; ++i) {
1758 isl_constraint_get_coefficient(c, isl_dim_param, i, &v);
1759 if (isl_int_is_zero(v))
1760 continue;
1761 if (sign < 0)
1762 isl_int_neg(v, v);
1763 aff = isl_aff_add_coefficient(aff, isl_dim_param, i, v);
1766 for (i = 0; i < nvar; ++i) {
1767 isl_constraint_get_coefficient(c, isl_dim_in, i, &v);
1768 if (isl_int_is_zero(v))
1769 continue;
1770 if (sign < 0)
1771 isl_int_neg(v, v);
1772 aff = isl_aff_add_coefficient(aff, isl_dim_in, i, v);
1775 isl_int_clear(v);
1777 bound->shift = aff;
1780 /* Given an equality constraint of a map with a single output dimension j,
1781 * check if the constraint is of the form
1783 * a(p,i) + j = g f(e)
1785 * with a(p,i) an expression in the parameters and input dimensions
1786 * and f(e) an expression in the existentially quantified variables.
1787 * If so, and if g is larger than any such g from a previously considered
1788 * constraint, then call extract_stride to record the stride information
1789 * in bound.
1791 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1793 int i;
1794 isl_int v, stride;
1795 unsigned n_div;
1796 struct gpu_array_bound *bound = user;
1798 isl_int_init(v);
1799 isl_int_init(stride);
1801 n_div = isl_constraint_dim(c, isl_dim_div);
1802 isl_constraint_get_coefficient(c, isl_dim_out, 0, &v);
1804 if (n_div && (isl_int_is_one(v) || isl_int_is_negone(v))) {
1805 int s = isl_int_sgn(v);
1806 isl_int_set_si(stride, 0);
1807 for (i = 0; i < n_div; ++i) {
1808 isl_constraint_get_coefficient(c, isl_dim_div, i, &v);
1809 isl_int_gcd(stride, stride, v);
1811 if (!isl_int_is_zero(stride) &&
1812 isl_int_gt(stride, bound->stride))
1813 extract_stride(c, bound, stride, s);
1816 isl_int_clear(stride);
1817 isl_int_clear(v);
1819 isl_constraint_free(c);
1820 return 0;
1823 /* Given contraints on an array index i, check if we can find
1824 * a shift a(p) and a stride g such that
1826 * a(p) + i = 0 mod g
1828 * If so, record the information in bound and apply the mapping
1829 * i -> (i + a(p))/g to the array index in bounds and return
1830 * the new constraints.
1831 * If not, simply return the original constraints.
1833 * If bounds is a subset of the space
1835 * D -> i
1837 * then the bound recorded in bound->shift is of the form
1839 * D -> s(D)
1841 * with s(D) equal to a(p) above.
1842 * The mapping recorded in bound->shift_map is of the form
1844 * [D -> i] -> [D -> (i + S(D))/g]
1846 * This mapping is computed as follows.
1847 * We first introduce "i" in the domain through precomposition
1848 * with [D -> i] -> D obtaining
1850 * [D -> i] -> s(D)
1852 * Adding [D -> i] -> i produces
1854 * [D -> i] -> i + s(D)
1856 * and the domain product with [D -> i] -> D yields
1858 * [D -> i] -> [D -> i + s(D)]
1860 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1862 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1863 __isl_take isl_basic_map *bounds)
1865 isl_space *space;
1866 isl_basic_map *hull;
1867 isl_basic_map *shift, *id, *bmap, *scale;
1868 isl_basic_set *bset;
1869 isl_aff *aff;
1871 isl_int_set_si(bound->stride, -1);
1873 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1875 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1877 isl_basic_map_free(hull);
1879 if (isl_int_is_neg(bound->stride))
1880 return bounds;
1882 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1883 space = isl_basic_map_get_space(bounds);
1884 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1885 shift = isl_basic_map_apply_range(bmap, shift);
1886 space = isl_basic_map_get_space(bounds);
1887 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1888 shift = isl_basic_map_sum(id, shift);
1889 space = isl_basic_map_get_space(bounds);
1890 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1891 shift = isl_basic_map_range_product(id, shift);
1893 space = isl_space_domain(isl_basic_map_get_space(bounds));
1894 id = isl_basic_map_identity(isl_space_map_from_set(space));
1895 space = isl_space_range(isl_basic_map_get_space(bounds));
1896 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1897 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1898 aff = isl_aff_scale_down(aff, bound->stride);
1899 scale = isl_basic_map_from_aff(aff);
1900 scale = isl_basic_map_product(id, scale);
1902 bound->shift_map = isl_basic_map_apply_range(shift, scale);
1903 bmap = isl_basic_map_copy(bound->shift_map);
1904 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1905 bounds = isl_basic_set_unwrap(bset);
1907 return bounds;
1910 /* Data used in compute_array_dim_size and compute_size_in_direction.
1912 * pos is the position of the variable representing the array index,
1913 * i.e., the variable for which want to compute the size. This variable
1914 * is also the last variable in the set.
1916 struct gpu_size_info {
1917 isl_basic_set *bset;
1918 struct gpu_array_bound *bound;
1919 int pos;
1922 /* Given a constraint from the basic set describing the bounds on
1923 * an array index, check if it is a lower bound, say m i >= b(x), and,
1924 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
1925 * upper bound. If so, and if this bound is smaller than any bound
1926 * derived from earlier constraints, set the size to this bound on
1927 * the expression and the lower bound to ceil(b(x)/m).
1929 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
1931 struct gpu_size_info *size = user;
1932 unsigned nparam;
1933 unsigned n_div;
1934 isl_int v;
1936 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
1937 n_div = isl_constraint_dim(c, isl_dim_div);
1939 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div)) {
1940 isl_constraint_free(c);
1941 return 0;
1944 isl_int_init(v);
1946 isl_constraint_get_coefficient(c, isl_dim_set, size->pos, &v);
1948 if (isl_int_is_pos(v)) {
1949 isl_aff *aff;
1950 isl_aff *lb;
1951 enum isl_lp_result res;
1953 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
1954 aff = isl_aff_ceil(aff);
1956 lb = isl_aff_copy(aff);
1958 aff = isl_aff_neg(aff);
1959 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
1961 res = isl_basic_set_max(size->bset, aff, &v);
1962 isl_aff_free(aff);
1964 if (res == isl_lp_ok) {
1965 isl_int_add_ui(v, v, 1);
1966 if (isl_int_is_neg(size->bound->size) ||
1967 isl_int_lt(v, size->bound->size)) {
1968 isl_int_set(size->bound->size, v);
1969 lb = isl_aff_drop_dims(lb, isl_dim_in,
1970 size->pos, 1);
1971 isl_aff_free(size->bound->lb);
1972 size->bound->lb = isl_aff_copy(lb);
1975 isl_aff_free(lb);
1978 isl_int_clear(v);
1979 isl_constraint_free(c);
1981 return 0;
1984 /* Given a basic map "bounds" that maps parameters and input dimensions
1985 * to a single output dimension, look for an expression in the parameters
1986 * and input dimensions such that the range of the output dimension shifted
1987 * by this expression is a constant.
1989 * In particular, we currently only consider lower bounds on the output
1990 * dimension as candidate expressions.
1992 static int compute_array_dim_size(struct gpu_array_bound *bound,
1993 __isl_take isl_basic_map *bounds)
1995 struct gpu_size_info size;
1997 bounds = isl_basic_map_detect_equalities(bounds);
1998 bounds = check_stride(bound, bounds);
2000 isl_int_set_si(bound->size, -1);
2001 bound->lb = NULL;
2003 size.bound = bound;
2004 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2005 size.bset = isl_basic_map_wrap(bounds);
2006 size.bset = isl_basic_set_flatten(size.bset);
2007 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2008 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2009 &size);
2010 isl_basic_set_free(size.bset);
2012 return isl_int_is_nonneg(bound->size) ? 0 : -1;
2015 /* Check if we can find a memory tile for the given array
2016 * based on the given accesses, and if so, put the results in "tile".
2018 * We project the accesses on each index in turn and look for a parametric
2019 * offset such that the size is constant.
2021 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2023 int i;
2025 for (i = 0; i < tile->n; ++i) {
2026 isl_map *access_i;
2027 isl_basic_map *hull;
2029 access_i = isl_map_copy(access);
2030 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2031 access_i = isl_map_project_out(access_i, isl_dim_out,
2032 1, tile->n - (i + 1));
2033 access_i = isl_map_compute_divs(access_i);
2034 hull = isl_map_simple_hull(access_i);
2035 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2036 return 0;
2039 return 1;
2042 /* Construct a map with input the shared tile loops and the loops that
2043 * will be wrapped around the threads that relates these later loops
2044 * to the thread indices and then projects them out.
2046 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2048 isl_map *priv;
2049 isl_map *tiling;
2050 isl_map *proj;
2051 isl_set *par;
2052 isl_space *dim;
2054 dim = isl_union_map_get_space(gen->shared_sched);
2056 if (gen->options->wrap)
2057 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2058 gen->shared_len, gen->n_block, gen->block_dim);
2059 else
2060 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2061 gen->shared_len, gen->n_block, gen->block_dim);
2063 priv = tiling;
2065 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2066 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2067 gen->n_block, "t");
2069 priv = isl_map_align_params(priv, isl_set_get_space(par));
2070 priv = isl_map_intersect_range(priv, par);
2072 dim = isl_map_get_space(priv);
2073 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2074 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2075 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2076 gen->shared_len);
2078 priv = isl_map_apply_range(priv, proj);
2080 return priv;
2083 /* Construct a map from domain_dim to domain_dim that increments
2084 * the dimension at position "pos" and leaves all other dimensions
2085 * constant.
2087 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2089 int i;
2090 int len = isl_space_dim(domain_dim, isl_dim_set);
2091 isl_space *dim;
2092 isl_basic_map *next;
2093 isl_local_space *ls;
2095 dim = isl_space_map_from_set(domain_dim);
2096 next = isl_basic_map_universe(isl_space_copy(dim));
2097 ls = isl_local_space_from_space(dim);
2099 for (i = 0; i < len; ++i) {
2100 isl_constraint *c;
2102 c = isl_equality_alloc(isl_local_space_copy(ls));
2103 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2104 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2105 if (i == pos)
2106 c = isl_constraint_set_constant_si(c, 1);
2107 next = isl_basic_map_add_constraint(next, c);
2110 isl_local_space_free(ls);
2112 return isl_map_from_basic_map(next);
2115 /* Check if the given access is coalesced.
2116 * That is, check whether incrementing the dimension that will get
2117 * wrapped over the last thread index results in incrementing
2118 * the last array index.
2120 * This function is only called for access relations without reuse.
2122 static int access_is_coalesced(struct gpu_gen *gen,
2123 __isl_keep isl_union_map *access)
2125 isl_space *dim;
2126 isl_map *access_map;
2127 isl_map *next_thread_x;
2128 isl_map *next_element;
2129 isl_map *map;
2130 int coalesced;
2132 access = isl_union_map_copy(access);
2133 access = isl_union_map_apply_domain(access,
2134 isl_union_map_copy(gen->tiled_sched));
2135 access_map = isl_map_from_union_map(access);
2137 dim = isl_map_get_space(access_map);
2138 dim = isl_space_domain(dim);
2139 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2141 dim = isl_map_get_space(access_map);
2142 dim = isl_space_range(dim);
2143 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2145 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2146 map = isl_map_apply_range(map, access_map);
2148 coalesced = isl_map_is_subset(map, next_element);
2150 isl_map_free(next_element);
2151 isl_map_free(map);
2153 return coalesced;
2156 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2157 * dimensions of the computed schedule, check if it is bijective for
2158 * fixed values of the first gen->shared_len dimensions.
2159 * We perform this check by equating these dimensions to parameters.
2161 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2163 int res;
2164 isl_set *par;
2165 isl_space *space;
2167 access = isl_map_copy(access);
2168 space = isl_space_params(isl_map_get_space(access));
2169 par = parametrization(space, gen->shared_len + gen->n_block,
2170 0, gen->shared_len, "s");
2171 access = isl_map_intersect_domain(access, par);
2172 res = isl_map_is_bijective(access);
2173 isl_map_free(access);
2175 return res;
2178 /* Look for the last shared tile loop that affects the offset of "tile"
2179 * and return the result.
2180 * If there is no such loop, then return the index of the loop
2181 * before the first shared tile loop, in particular gen->tile_first - 1.
2183 static int compute_tile_last_shared(struct gpu_gen *gen,
2184 struct gpu_array_tile *tile)
2186 int i, j;
2188 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2189 for (i = 0; i < tile->n; ++i) {
2190 isl_aff *lb;
2191 isl_aff *shift;
2193 lb = tile->bound[i].lb;
2194 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2195 break;
2197 shift = tile->bound[i].shift;
2198 if (!shift)
2199 continue;
2200 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2201 break;
2203 if (i < tile->n)
2204 break;
2207 return j;
2210 /* Look for the last shared tile loop that affects the offset of the
2211 * shared or private tile and store the result in group->last_shared.
2212 * If there is no such loop, then group->last_shared is set to a value
2213 * before the first shared tile loop, in particular gen->tile_first - 1.
2214 * If there is no tile defined on the array reference group,
2215 * then set group->last_shared to gen->shared_len - 1.
2217 static void set_last_shared(struct gpu_gen *gen,
2218 struct gpu_array_ref_group *group)
2220 struct gpu_array_tile *tile;
2222 group->last_shared = gen->shared_len - 1;
2224 tile = group->private_tile;
2225 if (!tile)
2226 tile = group->shared_tile;
2227 if (!tile)
2228 return;
2230 group->last_shared = compute_tile_last_shared(gen, tile);
2233 /* Compute a privatized copy of all access relations from reference groups that
2234 * are mapped to private memory and store the result in gen->privatization.
2236 static void compute_private_access(struct gpu_gen *gen)
2238 int i, j;
2239 isl_union_map *private;
2241 if (!gen->options->use_private_memory)
2242 return;
2244 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2246 for (i = 0; i < gen->prog->n_array; ++i) {
2247 struct gpu_array_info *array = &gen->prog->array[i];
2249 if (gpu_array_is_read_only_scalar(array))
2250 continue;
2252 for (j = 0; j < array->n_group; ++j) {
2253 if (!array->groups[j]->private_tile)
2254 continue;
2256 private = isl_union_map_union(private,
2257 group_access_relation(array->groups[j], 1, 1));
2261 if (isl_union_map_is_empty(private))
2262 isl_union_map_free(private);
2263 else {
2264 isl_union_map *priv;
2266 private = isl_union_map_apply_domain(private,
2267 isl_union_map_copy(gen->shared_sched));
2268 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2269 private = isl_union_map_apply_domain(private, priv);
2270 gen->private_access = private;
2274 /* Compute the size of the tile specified by "tile"
2275 * in number of elements and put the result in *size.
2277 static void tile_size(struct gpu_array_tile *tile, isl_int *size)
2279 int i;
2281 isl_int_set_si(*size, 1);
2283 for (i = 0; i < tile->n; ++i)
2284 isl_int_mul(*size, *size, tile->bound[i].size);
2287 /* If max_shared_memory is not set to infinity (-1), then make
2288 * sure that the total amount of shared memory required by the
2289 * array reference groups mapped to shared memory is no larger
2290 * than this maximum.
2292 * We apply a greedy approach and discard (keep in global memory)
2293 * those groups that would result in a total memory size that
2294 * is larger than the maximum.
2296 static void check_shared_memory_bound(struct gpu_gen *gen)
2298 int i, j;
2299 isl_int left, size;
2301 if (gen->options->max_shared_memory < 0)
2302 return;
2304 isl_int_init(left);
2305 isl_int_init(size);
2306 isl_int_set_si(left, gen->options->max_shared_memory);
2308 for (i = 0; i < gen->prog->n_array; ++i) {
2309 struct gpu_array_info *array = &gen->prog->array[i];
2311 for (j = 0; j < array->n_group; ++j) {
2312 struct gpu_array_ref_group *group;
2314 group = array->groups[j];
2315 if (!group->shared_tile)
2316 continue;
2318 tile_size(group->shared_tile, &size);
2319 isl_int_mul_ui(size, size, array->size);
2321 if (isl_int_le(size, left)) {
2322 isl_int_sub(left, left, size);
2323 continue;
2326 group->shared_tile = free_tile(group->shared_tile);
2330 isl_int_clear(size);
2331 isl_int_clear(left);
2334 /* Fill up the groups array with singleton groups, i.e., one group
2335 * per reference, initializing the array, access, write, n_ref and refs fields.
2336 * In particular the access field is initialized to the scheduled
2337 * access relation of the array reference.
2339 * Return the number of elements initialized, i.e., the number of
2340 * active references in the current kernel.
2342 static int populate_array_references(struct gpu_array_info *array,
2343 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2345 int i;
2346 int n;
2347 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2349 n = 0;
2350 for (i = 0; i < array->n_ref; ++i) {
2351 isl_union_map *umap;
2352 isl_map *map;
2353 struct gpu_array_ref_group *group;
2354 struct gpu_stmt_access *access = array->refs[i];
2356 map = isl_map_copy(access->access);
2357 umap = isl_union_map_from_map(map);
2358 umap = isl_union_map_apply_domain(umap,
2359 isl_union_map_copy(sched));
2361 if (isl_union_map_is_empty(umap)) {
2362 isl_union_map_free(umap);
2363 continue;
2366 map = isl_map_from_union_map(umap);
2367 map = isl_map_detect_equalities(map);
2369 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2370 assert(group);
2371 group->array = array;
2372 group->access = map;
2373 group->write = access->write;
2374 group->refs = &array->refs[i];
2375 group->n_ref = 1;
2377 groups[n++] = group;
2380 return n;
2383 /* If group->n_ref == 1, then group->refs was set by
2384 * populate_array_references to point directly into
2385 * group->array->refs and should not be freed.
2386 * If group->n_ref > 1, then group->refs was set by join_groups
2387 * to point to a newly allocated array.
2389 static void free_array_ref_group(struct gpu_array_ref_group *group)
2391 if (!group)
2392 return;
2393 free_tile(group->shared_tile);
2394 free_tile(group->private_tile);
2395 isl_map_free(group->access);
2396 if (group->n_ref > 1)
2397 free(group->refs);
2398 free(group);
2401 /* Given a map where the input dimensions represent the tile loops,
2402 * eliminate the innermost of those that have a fixed value
2403 * until we reach one that does not (obviously) have a fixed value.
2405 static __isl_give isl_map *eliminate_fixed_inner_loops(
2406 __isl_take isl_map *access)
2408 int i, n;
2410 n = isl_map_dim(access, isl_dim_in);
2412 for (i = n - 1; i >= 0; --i) {
2413 if (!isl_map_plain_is_fixed(access, isl_dim_in, i, NULL))
2414 break;
2415 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2417 return access;
2420 /* Check if the access relations of group1 and group2 overlap within
2421 * the innermost loop. In particular, ignore any inner dimension
2422 * with a fixed value.
2423 * The copying to and from shared memory will be performed within
2424 * the innermost actual loop so we are only allowed to consider
2425 * the dimensions up to that innermost loop while checking whether
2426 * two access relations overlap.
2428 static int accesses_overlap(struct gpu_array_ref_group *group1,
2429 struct gpu_array_ref_group *group2)
2431 int empty;
2432 isl_map *access1, *access2;
2434 access1 = isl_map_copy(group1->access);
2435 access1 = eliminate_fixed_inner_loops(access1);
2436 access2 = isl_map_copy(group2->access);
2437 access2 = eliminate_fixed_inner_loops(access2);
2438 access1 = isl_map_intersect(access1, access2);
2439 empty = isl_map_is_empty(access1);
2440 isl_map_free(access1);
2442 return !empty;
2445 /* Combine the given two groups into a single group, containing
2446 * the references of both groups.
2448 static struct gpu_array_ref_group *join_groups(
2449 struct gpu_array_ref_group *group1,
2450 struct gpu_array_ref_group *group2)
2452 int i;
2453 isl_ctx *ctx;
2454 struct gpu_array_ref_group *group;
2456 ctx = isl_map_get_ctx(group1->access);
2457 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2458 assert(group);
2459 group->array = group1->array;
2460 group->access = isl_map_union(isl_map_copy(group1->access),
2461 isl_map_copy(group2->access));
2462 group->write = group1->write || group2->write;
2463 group->n_ref = group1->n_ref + group2->n_ref;
2464 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2465 group->n_ref);
2466 assert(group->refs);
2467 for (i = 0; i < group1->n_ref; ++i)
2468 group->refs[i] = group1->refs[i];
2469 for (i = 0; i < group2->n_ref; ++i)
2470 group->refs[group1->n_ref + i] = group2->refs[i];
2472 return group;
2475 /* Combine the given two groups into a single group and free
2476 * the original two groups.
2478 static struct gpu_array_ref_group *join_groups_and_free(
2479 struct gpu_array_ref_group *group1,
2480 struct gpu_array_ref_group *group2)
2482 struct gpu_array_ref_group *group;
2484 group = join_groups(group1, group2);
2485 free_array_ref_group(group1);
2486 free_array_ref_group(group2);
2487 return group;
2490 /* Compute the private and/or shared memory tiles for the array
2491 * reference group "group" of array "array".
2493 * If the array is a read-only scalar or if the user requested
2494 * not to use shared or private memory, then we do not need to do anything.
2496 * We only try to compute a shared memory tile if there is any reuse
2497 * or if the access is not coalesced.
2499 * For computing a private memory tile, we also require that there is
2500 * some reuse. Moreover, we require that the access is private
2501 * to the thread. That is, we check that any given array element
2502 * is only accessed by a single thread.
2503 * We compute an access relation that maps the shared tile loop iterators
2504 * and the shared point loop iterators that will be wrapped over the
2505 * threads to the array elements.
2506 * We actually check that those iterators that will be wrapped
2507 * partition the array space. This check is stricter than necessary
2508 * since several iterations may be mapped onto the same thread
2509 * and then they could be allowed to access the same memory elements,
2510 * but our check does not allow this situation.
2512 * We also check that the index expression only depends on parallel
2513 * loops. That way, we can move those loops innermost and unroll them.
2514 * Again, we use a test that is stricter than necessary.
2515 * We actually check whether the index expression only depends
2516 * on the iterators that are wrapped over the threads.
2517 * These are necessarily parallel, but there may be more parallel loops.
2519 * Combining the injectivity of the first test with the single-valuedness
2520 * of the second test, we simply test for bijectivity.
2522 * If it turns out we can use registers, we compute the private memory
2523 * tile size using can_tile, after introducing a dependence
2524 * on the thread indices.
2526 static void compute_group_bounds_core(struct gpu_gen *gen,
2527 struct gpu_array_ref_group *group)
2529 isl_ctx *ctx = isl_space_get_ctx(group->array->dim);
2530 isl_union_map *access;
2531 int n_index = group->array->n_index;
2532 int no_reuse;
2533 isl_map *acc;
2534 int use_shared = gen->options->use_shared_memory;
2535 int use_private = gen->options->use_private_memory;
2537 if (!use_shared && !use_private)
2538 return;
2539 if (gpu_array_is_read_only_scalar(group->array))
2540 return;
2542 access = group_access_relation(group, 1, 1);
2543 no_reuse = isl_union_map_is_injective(access);
2545 if (use_shared && (!no_reuse || !access_is_coalesced(gen, access))) {
2546 group->shared_tile = create_tile(ctx, group->array->n_index);
2547 if (!can_tile(group->access, group->shared_tile))
2548 group->shared_tile = free_tile(group->shared_tile);
2551 if (!use_private || no_reuse) {
2552 isl_union_map_free(access);
2553 return;
2556 access = isl_union_map_apply_domain(access,
2557 isl_union_map_copy(gen->shared_sched));
2559 acc = isl_map_from_union_map(access);
2561 if (!access_is_bijective(gen, acc)) {
2562 isl_map_free(acc);
2563 return;
2566 group->private_tile = create_tile(gen->ctx, n_index);
2567 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2568 if (!can_tile(acc, group->private_tile))
2569 group->private_tile = free_tile(group->private_tile);
2571 isl_map_free(acc);
2574 /* Compute the private and/or shared memory tiles for the array
2575 * reference group "group" of array "array" and set last_shared.
2577 static void compute_group_bounds(struct gpu_gen *gen,
2578 struct gpu_array_ref_group *group)
2580 compute_group_bounds_core(gen, group);
2581 set_last_shared(gen, group);
2584 /* If two groups have overlapping access relations (as determined by
2585 * the "overlap" function) and if one of them involves a write,
2586 * then merge the two groups into one.
2587 * If "compute_bounds" is set, then call compute_group_bounds
2588 * on the merged groups.
2590 * Return the updated number of groups.
2592 static int group_writes(struct gpu_gen *gen,
2593 int n, struct gpu_array_ref_group **groups,
2594 int (*overlap)(struct gpu_array_ref_group *group1,
2595 struct gpu_array_ref_group *group2), int compute_bounds)
2597 int i, j;
2599 for (i = 0; i < n; ++i) {
2600 for (j = n - 1; j > i; --j) {
2601 if (!groups[i]->write && !groups[j]->write)
2602 continue;
2604 if (!overlap(groups[i], groups[j]))
2605 continue;
2607 groups[i] = join_groups_and_free(groups[i], groups[j]);
2608 if (compute_bounds)
2609 compute_group_bounds(gen, groups[i]);
2610 if (j != n - 1)
2611 groups[j] = groups[n - 1];
2612 n--;
2616 return n;
2619 /* If two groups have overlapping access relations (within the innermost
2620 * loop) and if one of them involves a write, then merge the two groups
2621 * into one.
2623 * Return the updated number of groups.
2625 static int group_overlapping_writes(struct gpu_gen *gen,
2626 int n, struct gpu_array_ref_group **groups)
2628 return group_writes(gen, n, groups, &accesses_overlap, 0);
2631 /* Check if the access relations of group1 and group2 overlap within
2632 * the outermost min(group1->last_shared, group2->last_shared) loops.
2634 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2635 struct gpu_array_ref_group *group2)
2637 int last_shared;
2638 int dim;
2639 int empty;
2640 isl_map *map_i, *map_j, *map;
2642 last_shared = group1->last_shared;
2643 if (group2->last_shared < last_shared)
2644 last_shared = group2->last_shared;
2645 map_i = isl_map_copy(group1->access);
2646 dim = isl_map_dim(map_i, isl_dim_in);
2647 map_i = isl_map_eliminate(map_i, isl_dim_in,
2648 last_shared + 1, dim - (last_shared + 1));
2649 map_j = isl_map_copy(group2->access);
2650 map_j = isl_map_eliminate(map_j, isl_dim_in,
2651 last_shared + 1, dim - (last_shared + 1));
2652 map = isl_map_intersect(map_i, map_j);
2653 empty = isl_map_is_empty(map);
2654 isl_map_free(map);
2656 return !empty;
2659 /* If two groups have overlapping access relations (within the outer
2660 * last_shared loops) and if one of them involves a write,
2661 * then merge the two groups into one.
2663 * Return the updated number of groups.
2665 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2666 struct gpu_array_ref_group **groups)
2668 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2671 /* Is the size of the tile specified by "tile" smaller than the sum of
2672 * the sizes of the tiles specified by "tile1" and "tile2"?
2674 static int smaller_tile(struct gpu_array_tile *tile,
2675 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2677 int smaller;
2678 isl_int size, size1, size2;
2680 isl_int_init(size);
2681 isl_int_init(size1);
2682 isl_int_init(size2);
2684 tile_size(tile, &size);
2685 tile_size(tile1, &size1);
2686 tile_size(tile2, &size2);
2688 isl_int_sub(size, size, size1);
2689 isl_int_sub(size, size, size2);
2690 smaller = isl_int_is_neg(size);
2692 isl_int_clear(size2);
2693 isl_int_clear(size1);
2694 isl_int_clear(size);
2696 return smaller;
2699 /* Given an initial grouping of array references and shared memory tiles
2700 * for each group that allows for a shared memory tile, merge two groups
2701 * if both have a shared memory tile, the merged group also has
2702 * a shared memory tile and the size of the tile for the merge group
2703 * is smaller than the sum of the tile sizes of the individual groups.
2705 * If merging two groups decreases the "last_shared" dimension of
2706 * one or both of the two groups, then we need to check for overlapping
2707 * writes again.
2709 * Return the number of groups after merging.
2711 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2712 struct gpu_array_info *array, int n,
2713 struct gpu_array_ref_group **groups)
2715 int i, j;
2716 int recompute_overlap = 0;
2717 isl_ctx *ctx = isl_space_get_ctx(array->dim);
2719 for (i = 0; i < n; ++i) {
2720 if (!groups[i]->shared_tile)
2721 continue;
2722 for (j = n - 1; j > i; --j) {
2723 isl_map *map;
2724 int empty;
2725 struct gpu_array_ref_group *group;
2727 if (!groups[j]->shared_tile)
2728 continue;
2730 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2731 isl_map_copy(groups[j]->access));
2732 empty = isl_map_is_empty(map);
2733 isl_map_free(map);
2735 if (empty)
2736 continue;
2738 group = join_groups(groups[i], groups[j]);
2739 compute_group_bounds(gen, group);
2740 if (!group->shared_tile ||
2741 !smaller_tile(group->shared_tile,
2742 groups[i]->shared_tile,
2743 groups[j]->shared_tile)) {
2744 free_array_ref_group(group);
2745 continue;
2748 if (group->last_shared < groups[i]->last_shared ||
2749 group->last_shared < groups[j]->last_shared)
2750 recompute_overlap = 1;
2751 free_array_ref_group(groups[i]);
2752 free_array_ref_group(groups[j]);
2753 groups[i] = group;
2754 if (j != n - 1)
2755 groups[j] = groups[n - 1];
2756 n--;
2760 if (recompute_overlap)
2761 n = group_last_shared_overlapping_writes(gen, n, groups);
2762 return n;
2765 /* Set array->n_group and array->groups to n and groups.
2767 * Additionally, set the "nr" field of each group
2768 * and the "group" field of each reference in each group.
2770 static void set_array_groups(struct gpu_array_info *array,
2771 int n, struct gpu_array_ref_group **groups)
2773 int i, j;
2775 array->n_group = n;
2776 array->groups = groups;
2778 for (i = 0; i < n; ++i) {
2779 groups[i]->nr = i;
2781 for (j = 0; j < groups[i]->n_ref; ++j)
2782 groups[i]->refs[j]->group = i;
2786 /* Group array references that should be considered together when
2787 * deciding whether to access them from private, shared or global memory.
2789 * In particular, if two array references overlap and if one of them
2790 * is a write, then the two references are grouped together.
2791 * We first perform an initial grouping based only on the access relation.
2792 * After computing shared and private memory tiles, we check for
2793 * overlapping writes again, but this time taking into account
2794 * the "last_shared" property.
2796 * Furthermore, if two groups admit a shared memory tile and if the
2797 * combination of the two also admits a shared memory tile, we merge
2798 * the two groups.
2800 static void group_array_references(struct gpu_gen *gen,
2801 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
2803 int i;
2804 int n;
2805 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2806 struct gpu_array_ref_group **groups;
2808 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
2809 array->n_ref);
2810 assert(groups);
2812 n = populate_array_references(array, sched, groups);
2814 n = group_overlapping_writes(gen, n, groups);
2816 for (i = 0; i < n; ++i)
2817 compute_group_bounds(gen, groups[i]);
2819 n = group_last_shared_overlapping_writes(gen, n, groups);
2821 n = group_common_shared_memory_tile(gen, array, n, groups);
2823 set_array_groups(array, n, groups);
2826 /* Take tiled_sched, project it onto the shared tile loops and
2827 * the loops that will be wrapped over the threads and
2828 * store the result in gen->shared_sched.
2829 * Also compute a projection that projects out the loops that will be
2830 * wrapped over the threads and store this projection in gen->shared_proj.
2832 static void compute_shared_sched(struct gpu_gen *gen)
2834 isl_space *dim;
2835 isl_map *proj;
2836 isl_set *par;
2837 isl_union_map *sched;
2839 sched = isl_union_map_copy(gen->tiled_sched);
2841 dim = isl_union_map_get_space(sched);
2842 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
2843 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
2845 dim = isl_union_map_get_space(sched);
2846 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
2848 gen->shared_sched = sched;
2849 gen->shared_proj = isl_union_map_from_map(proj);
2852 /* Group references of all arrays in the program.
2854 static void group_references(struct gpu_gen *gen)
2856 int i;
2857 isl_union_map *sched;
2859 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2860 isl_union_map_copy(gen->shared_proj));
2862 for (i = 0; i < gen->prog->n_array; ++i)
2863 group_array_references(gen, &gen->prog->array[i], sched);
2865 isl_union_map_free(sched);
2868 /* Free all array information that is local to the current kernel.
2870 static void free_local_array_info(struct gpu_gen *gen)
2872 int i, j;
2874 for (i = 0; i < gen->prog->n_array; ++i) {
2875 struct gpu_array_info *array = &gen->prog->array[i];
2877 for (j = 0; j < array->n_group; ++j)
2878 free_array_ref_group(array->groups[j]);
2879 free(array->groups);
2883 /* Compute the effective grid size as a list of the sizes in each dimension.
2885 * The grid size specified by the user or set by default
2886 * in read_grid_sizes() and applied in tile_schedule(),
2887 * may be too large for the given code in the sense that
2888 * it may contain blocks that don't need to execute anything.
2889 * We therefore don't return this grid size, but instead the
2890 * smallest grid size that ensures that all blocks that actually
2891 * execute code are included in the grid.
2893 * We first extract a description of the grid, i.e., the possible values
2894 * of the block ids, from gen->tiled_sched.
2895 * The block ids are parameters in gen->tiled_sched.
2896 * We simply need to change them into set dimensions.
2898 * Then, for each block dimension, we compute the maximal value of the block id
2899 * and add one.
2901 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
2902 struct ppcg_kernel *kernel)
2904 int i;
2905 isl_set *grid;
2906 isl_multi_pw_aff *mpa;
2908 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
2909 grid = isl_set_from_params(grid);
2910 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
2911 for (i = 0; i < gen->n_grid; ++i) {
2912 int pos;
2913 char name[20];
2915 snprintf(name, sizeof(name), "b%d", i);
2916 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
2917 assert(pos >= 0);
2918 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
2919 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
2922 mpa = isl_multi_pw_aff_zero(isl_set_get_space(grid));
2923 for (i = 0; i < gen->n_grid; ++i) {
2924 isl_space *space;
2925 isl_aff *one;
2926 isl_pw_aff *bound;
2928 bound = isl_set_dim_max(isl_set_copy(grid), i);
2929 bound = isl_pw_aff_coalesce(bound);
2930 bound = isl_pw_aff_gist(bound, isl_set_copy(kernel->context));
2932 space = isl_pw_aff_get_domain_space(bound);
2933 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2934 one = isl_aff_add_constant_si(one, 1);
2935 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
2936 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
2938 isl_set_free(grid);
2940 return mpa;
2943 void ppcg_kernel_free(void *user)
2945 struct ppcg_kernel *kernel = user;
2946 int i;
2948 if (!kernel)
2949 return;
2951 isl_multi_pw_aff_free(kernel->grid_size);
2952 isl_set_free(kernel->context);
2953 isl_union_set_free(kernel->arrays);
2954 isl_space_free(kernel->space);
2955 isl_ast_node_free(kernel->tree);
2957 for (i = 0; i < kernel->n_array; ++i)
2958 isl_pw_aff_list_free(kernel->array[i].bound);
2959 free(kernel->array);
2961 for (i = 0; i < kernel->n_var; ++i) {
2962 free(kernel->var[i].name);
2963 isl_vec_free(kernel->var[i].size);
2965 free(kernel->var);
2967 free(kernel);
2970 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
2971 struct ppcg_kernel_var *var)
2973 int j;
2974 struct gpu_array_tile *tile;
2975 isl_printer *p;
2976 char *name;
2978 var->array = group->array;
2980 tile = group->private_tile;
2981 var->type = ppcg_access_private;
2982 if (!tile) {
2983 tile = group->shared_tile;
2984 var->type = ppcg_access_shared;
2987 p = isl_printer_to_str(ctx);
2988 p = print_array_name(p, group);
2989 var->name = isl_printer_get_str(p);
2990 isl_printer_free(p);
2992 var->size = isl_vec_alloc(ctx, group->array->n_index);
2994 for (j = 0; j < group->array->n_index; ++j)
2995 var->size = isl_vec_set_element(var->size, j,
2996 tile->bound[j].size);
2999 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3001 int i, j, n;
3003 n = 0;
3004 for (i = 0; i < gen->prog->n_array; ++i) {
3005 struct gpu_array_info *array = &gen->prog->array[i];
3007 for (j = 0; j < array->n_group; ++j) {
3008 struct gpu_array_ref_group *group = array->groups[j];
3009 if (group->private_tile || group->shared_tile)
3010 ++n;
3014 kernel->n_var = n;
3015 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3016 assert(kernel->var);
3018 n = 0;
3019 for (i = 0; i < gen->prog->n_array; ++i) {
3020 struct gpu_array_info *array = &gen->prog->array[i];
3022 for (j = 0; j < array->n_group; ++j) {
3023 struct gpu_array_ref_group *group = array->groups[j];
3024 if (!group->private_tile && !group->shared_tile)
3025 continue;
3026 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3027 ++n;
3032 /* The sizes of the arrays on the host that have been computed by
3033 * extract_array_info may depend on the parameters. Use the extra
3034 * constraints on the parameters that are valid at "host_domain"
3035 * to simplify these expressions and store the results in kernel->array.
3037 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3038 __isl_keep isl_set *host_domain)
3040 int i, j;
3041 isl_set *context;
3043 kernel->array = isl_calloc_array(gen->ctx,
3044 struct gpu_local_array_info, gen->prog->n_array);
3045 assert(kernel->array);
3046 kernel->n_array = gen->prog->n_array;
3048 context = isl_set_copy(host_domain);
3049 context = isl_set_params(context);
3051 for (i = 0; i < gen->prog->n_array; ++i) {
3052 struct gpu_array_info *array = &gen->prog->array[i];
3053 isl_pw_aff_list *local;
3055 if (array->n_group == 0)
3056 continue;
3058 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3060 for (j = 0; j < array->n_index; ++j) {
3061 isl_pw_aff *pwaff;
3063 pwaff = isl_pw_aff_copy(array->bound[j]);
3064 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3065 local = isl_pw_aff_list_add(local, pwaff);
3068 kernel->array[i].bound = local;
3070 isl_set_free(context);
3073 /* Find the element in gen->stmt that has the given "id".
3074 * Return NULL if no such gpu_stmt can be found.
3076 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3078 int i;
3080 for (i = 0; i < prog->n_stmts; ++i) {
3081 if (id == prog->stmts[i].id)
3082 break;
3085 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3088 /* Set gen->tile_len and gen->n_parallel to those of the statement
3089 * affected by the first map (part of the schedule)
3090 * on which this function is called.
3091 * Because of the way the schedule is constructed, the other statements
3092 * in the list, if any, should have the same values for these properties.
3094 static int extract_tile_len(__isl_take isl_map *map, void *user)
3096 struct gpu_gen *gen = (struct gpu_gen *) user;
3097 isl_id *id;
3098 struct gpu_stmt *stmt;
3100 id = isl_map_get_tuple_id(map, isl_dim_in);
3101 stmt = find_stmt(gen->prog, id);
3102 isl_id_free(id);
3104 isl_map_free(map);
3106 if (!stmt)
3107 isl_die(gen->ctx, isl_error_unknown,
3108 "statement not found", return -1);
3110 gen->tile_len = stmt->tile_len;
3111 gen->n_parallel = stmt->n_parallel;
3113 return -1;
3116 void ppcg_kernel_stmt_free(void *user)
3118 int i;
3119 struct ppcg_kernel_stmt *stmt = user;
3121 if (!stmt)
3122 return;
3124 switch (stmt->type) {
3125 case ppcg_kernel_copy:
3126 isl_ast_expr_free(stmt->u.c.index);
3127 isl_ast_expr_free(stmt->u.c.local_index);
3128 break;
3129 case ppcg_kernel_domain:
3130 for (i = 0; i < stmt->u.d.n_access; ++i) {
3131 isl_ast_expr_list_free(stmt->u.d.access[i].index);
3132 free(stmt->u.d.access[i].local_name);
3134 free(stmt->u.d.access);
3135 break;
3136 case ppcg_kernel_sync:
3137 break;
3140 free(stmt);
3143 /* Set the options of "context" to
3145 * { space -> [x] : x >= first }
3147 static __isl_give isl_ast_build *set_unroll(
3148 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3149 int first)
3151 isl_ctx *ctx;
3152 isl_map *unroll;
3153 isl_union_map *opt;
3155 ctx = isl_ast_build_get_ctx(build);
3157 space = isl_space_from_domain(space);
3158 space = isl_space_add_dims(space, isl_dim_out, 1);
3159 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3160 unroll = isl_map_universe(space);
3161 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3162 opt = isl_union_map_from_map(unroll);
3164 build = isl_ast_build_set_options(build, opt);
3166 return build;
3169 /* Return a list of isl_ids of the form "prefix%d".
3171 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3172 int n, const char *prefix)
3174 int i;
3175 char name[10];
3176 isl_id_list *names;
3178 names = isl_id_list_alloc(ctx, n);
3179 for (i = 0; i < n; ++i) {
3180 isl_id *id;
3182 snprintf(name, sizeof(name), "%s%d", prefix, i);
3183 id = isl_id_alloc(ctx, name, NULL);
3184 names = isl_id_list_add(names, id);
3187 return names;
3190 /* Extend the schedule "schedule" with the part of "extension"
3191 * starting at "first" up to "len".
3193 static __isl_give isl_union_map *extend_schedule(
3194 __isl_take isl_union_map *schedule,
3195 __isl_take isl_union_map *extension, int first, int len)
3197 isl_space *space;
3198 isl_map *proj;
3199 isl_union_map *umap;
3200 isl_set *set;
3202 space = isl_union_map_get_space(schedule);
3203 space = isl_space_set_from_params(space);
3204 space = isl_space_add_dims(space, isl_dim_set, len);
3205 proj = isl_set_identity(isl_set_universe(space));
3206 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3207 extension = isl_union_map_apply_range(extension,
3208 isl_union_map_from_map(proj));
3210 schedule = isl_union_map_range_product(schedule, extension);
3212 return schedule;
3215 /* This function is called for each access to an array in each instance
3216 * in the kernel of some statement in the original code.
3217 * Replace that access by an access to global, shared or private memory
3218 * and store the results in *kernel_access.
3220 * Since the array in shared or private memory is just
3221 * a shifted copy of part of the original array, we simply need
3222 * to subtract the lower bound, which was computed in can_tile.
3223 * If any of the indices is strided, then we first add
3224 * shared_tile->bound[i].shift and divide by shared_tile->bound[i].stride.
3226 * If the given array is accessed directly from global memory,
3227 * we don't need to perform any shifting and simply simplify
3228 * the expression in the context of the domain instead.
3230 * If the array space (range of access) has no name, then we are
3231 * accessing an iterator in the original program.
3233 * The input stmt_access->access relation maps the iteration domain
3234 * of the current statement to an array element.
3235 * The first step is to reformulate
3236 * this access relation in terms of the loop iterators of the generated
3237 * code through precomposition with gen->stmt_it.
3239 * The expressions in "tile" are formulated in terms of the first
3240 * gen->shared_len dimensions of the computed schedule using the mapping
3241 * sched2shared which maps the loop iterators to these dimensions.
3243 static void compute_index_expression(struct gpu_gen *gen,
3244 struct ppcg_kernel_access *kernel_access,
3245 struct gpu_stmt_access *stmt_access, __isl_keep isl_map *stmt_it,
3246 __isl_keep isl_map *sched2shared, __isl_keep isl_ast_build *build)
3248 isl_map *access;
3249 isl_pw_multi_aff *pma;
3250 int i;
3251 unsigned n_index;
3252 struct gpu_array_tile *tile = NULL;
3254 if (isl_map_has_tuple_name(stmt_access->access, isl_dim_out)) {
3255 int i;
3256 const char *name;
3257 struct gpu_array_ref_group *group;
3258 isl_printer *p;
3260 name = isl_map_get_tuple_name(stmt_access->access, isl_dim_out);
3262 for (i = 0; i < gen->prog->n_array; ++i) {
3263 if (strcmp(name, gen->prog->array[i].name))
3264 continue;
3265 kernel_access->array = &gen->prog->array[i];
3266 kernel_access->local_array = &gen->kernel->array[i];
3268 assert(kernel_access->array);
3269 group = kernel_access->array->groups[stmt_access->group];
3270 p = isl_printer_to_str(gen->ctx);
3271 p = print_array_name(p, group);
3272 kernel_access->local_name = isl_printer_get_str(p);
3273 isl_printer_free(p);
3274 tile = group->private_tile;
3275 kernel_access->type = ppcg_access_private;
3276 if (!tile) {
3277 tile = group->shared_tile;
3278 kernel_access->type = ppcg_access_shared;
3281 if (!tile)
3282 kernel_access->type = ppcg_access_global;
3284 n_index = isl_map_dim(stmt_access->access, isl_dim_out);
3285 kernel_access->index = isl_ast_expr_list_alloc(gen->ctx, n_index);
3287 if (n_index == 0)
3288 return;
3290 access = isl_map_copy(stmt_access->access);
3291 access = isl_map_apply_range(isl_map_copy(stmt_it), access);
3292 pma = isl_pw_multi_aff_from_map(access);
3293 pma = isl_pw_multi_aff_coalesce(pma);
3295 for (i = 0; i < n_index; ++i) {
3296 isl_set *domain;
3297 isl_pw_aff *index;
3298 isl_ast_expr *expr;
3300 index = isl_pw_multi_aff_get_pw_aff(pma, i);
3302 if (!kernel_access->array) {
3303 } else if (!tile) {
3304 domain = isl_map_domain(isl_map_copy(stmt_it));
3305 index = isl_pw_aff_coalesce(index);
3306 index = isl_pw_aff_gist(index, domain);
3307 } else {
3308 domain = isl_map_domain(isl_map_copy(stmt_it));
3309 index = shift_index(index, kernel_access->array,
3310 &tile->bound[i], domain,
3311 isl_map_copy(sched2shared));
3314 expr = isl_ast_build_expr_from_pw_aff(build, index);
3316 kernel_access->index = isl_ast_expr_list_add(
3317 kernel_access->index, expr);
3320 isl_pw_multi_aff_free(pma);
3323 /* This function is called for each instance of a user statement
3324 * in the kernel.
3326 * We attach a struct ppcg_kernel_stmt to the "node", containing
3327 * local information about the accesses.
3328 * This information is computed from stmt_it, which expresses the domain
3329 * elements in terms of the generated loops, and sched2shared,
3330 * which expresses the first shared_len dimensions of the schedule
3331 * computed by PPCG in terms of the generated loops.
3333 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3334 __isl_keep isl_ast_build *build, void *user)
3336 struct gpu_gen *gen = (struct gpu_gen *) user;
3337 struct ppcg_kernel_stmt *stmt;
3338 isl_id *id;
3339 isl_map *stmt_it, *sched2shared;
3340 isl_ast_expr *expr, *arg;
3341 isl_union_map *schedule;
3342 int i, n;
3343 struct gpu_stmt_access *access;
3345 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3346 if (!stmt)
3347 return isl_ast_node_free(node);
3349 expr = isl_ast_node_user_get_expr(node);
3350 arg = isl_ast_expr_get_op_arg(expr, 0);
3351 id = isl_ast_expr_get_id(arg);
3353 schedule = isl_ast_build_get_schedule(build);
3354 stmt_it = isl_map_reverse(isl_map_from_union_map(schedule));
3355 sched2shared = compute_sched_to_shared(gen, isl_map_copy(stmt_it));
3357 stmt->type = ppcg_kernel_domain;
3358 stmt->u.d.stmt = find_stmt(gen->prog, id);
3359 if (!stmt->u.d.stmt)
3360 goto error;
3362 n = 0;
3363 for (access = stmt->u.d.stmt->accesses; access; access = access->next)
3364 ++n;
3366 stmt->u.d.access = isl_calloc_array(gen->ctx,
3367 struct ppcg_kernel_access, n);
3368 if (!stmt->u.d.access)
3369 goto error;
3371 stmt->u.d.n_access = n;
3373 access = stmt->u.d.stmt->accesses;
3374 for (i = 0; i < n; ++i, access = access->next) {
3375 compute_index_expression(gen, &stmt->u.d.access[i], access,
3376 stmt_it, sched2shared, build);
3379 isl_id_free(id);
3380 isl_map_free(stmt_it);
3381 isl_map_free(sched2shared);
3382 isl_ast_expr_free(arg);
3383 isl_ast_expr_free(expr);
3385 id = isl_id_alloc(gen->ctx, NULL, stmt);
3386 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3387 return isl_ast_node_set_annotation(node, id);
3388 error:
3389 isl_id_free(id);
3390 isl_map_free(stmt_it);
3391 ppcg_kernel_stmt_free(stmt);
3392 isl_map_free(sched2shared);
3393 return isl_ast_node_free(node);
3396 /* This function is called when code has been generated for the shared
3397 * tile loops. The "schedule" refers only to the original statements.
3399 * We extend the schedule with that part of gen->local_sched that hasn't
3400 * been taken into account yet. This introduces parameters referring
3401 * to thread ids in the schedule, so we add them (with the appropriate
3402 * bounds to the context as well).
3403 * Finally, we set the appropriate unrolling options
3404 * if gen->first_unroll is set.
3406 static __isl_give isl_ast_node *create_domain_leaf(
3407 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
3408 void *user)
3410 struct gpu_gen *gen = (struct gpu_gen *) user;
3411 isl_space *space;
3412 isl_union_map *sched;
3413 isl_ast_node *tree;
3414 isl_set *set;
3415 isl_id_list *iterators;
3416 int n;
3418 schedule = extend_schedule(schedule,
3419 isl_union_map_copy(gen->local_sched),
3420 gen->shared_len, gen->thread_tiled_len);
3422 space = isl_ast_build_get_schedule_space(build);
3423 set = isl_set_universe(space);
3424 set = add_bounded_parameters(set, gen->n_block, gen->block_dim, "t");
3425 build = isl_ast_build_restrict(build, set);
3427 n = gen->thread_tiled_len - gen->shared_len;
3429 if (gen->first_unroll >= 0) {
3430 space = isl_space_set_alloc(gen->ctx, 0, n);
3431 build = set_unroll(build, space, gen->first_unroll);
3433 iterators = generate_names(gen->ctx, n, "c");
3434 build = isl_ast_build_set_iterators(build, iterators);
3435 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
3436 tree = isl_ast_build_ast_from_schedule(build, schedule);
3437 isl_ast_build_free(build);
3439 return tree;
3442 /* This function is called for each statement node in the AST of the code
3443 * for copying to or from shared/private memory.
3444 * Attach a pointer to a ppcg_kernel_stmt representing the copy
3445 * statement to the node.
3446 * The statement name is {read,write}_{shared,private}_<array>.
3448 * The schedule is of the form
3450 * [A -> T] -> L
3452 * where A refers to a piece of an array and T to the corresponding
3453 * shifted tile. We split this schedule into mappings L -> A and L -> T
3454 * and store the corresponding expressions in stmt->index and stmt->local_index,
3455 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
3457 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
3458 __isl_keep isl_ast_build *build, void *user)
3460 struct gpu_gen *gen = (struct gpu_gen *) user;
3461 struct ppcg_kernel_stmt *stmt;
3462 isl_id *id;
3463 isl_ast_expr *expr;
3464 isl_space *space;
3465 isl_map *access, *local_access, *map;
3466 isl_pw_multi_aff *pma;
3467 const char *name;
3468 int array_index;
3470 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3471 if (!stmt)
3472 return isl_ast_node_free(node);
3474 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
3475 name = isl_map_get_tuple_name(access, isl_dim_in);
3476 stmt->u.c.read = !strncmp(name, "read", 4);
3477 access = isl_map_reverse(access);
3478 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
3479 local_access = isl_map_copy(access);
3481 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
3482 id = isl_map_get_tuple_id(access, isl_dim_out);
3483 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3484 access = isl_map_apply_range(access, map);
3485 pma = isl_pw_multi_aff_from_map(access);
3486 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3487 stmt->u.c.index = expr;
3489 map = isl_map_range_map(isl_map_universe(space));
3490 id = isl_map_get_tuple_id(local_access, isl_dim_out);
3491 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3492 local_access = isl_map_apply_range(local_access, map);
3493 pma = isl_pw_multi_aff_from_map(local_access);
3494 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3495 stmt->u.c.local_index = expr;
3497 stmt->u.c.array = gen->copy_group->array;
3498 array_index = stmt->u.c.array - gen->prog->array;
3499 stmt->u.c.local_array = &gen->kernel->array[array_index];
3500 stmt->type = ppcg_kernel_copy;
3502 id = isl_id_alloc(gen->ctx, NULL, stmt);
3503 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3504 return isl_ast_node_set_annotation(node, id);
3507 /* Given a schedule of the form
3509 * [S -> A] -> L
3511 * (with S the first shared_len dimensions of the computed schedule,
3512 * A the array and L the schedule correponding to the generated loops),
3513 * indicating where the copying the array elements that need to be copied,
3514 * construct code for performing the copying.
3516 * "group" is the array reference group that is being copied
3517 * "type" is either "read" or "write"
3518 * private is set if copying needs to be performed to/from registers
3520 * We first construct a mapping to a shifted tile of the array,
3522 * [S -> A] -> T(S,A) (1)
3524 * If private is set, then we also use this mapping as a schedule
3525 * (which is already thread-specific and will be completely unrolled).
3526 * Otherwise, we wrap/tile the range over the threads.
3527 * The result is
3529 * [S -> A] -> T'(S,A)
3531 * Combined with the given schedule, we have
3533 * [S -> A] -> [L -> T'(S,A)] (2)
3535 * From the shifted tile mapping, we construct a mapping
3537 * [S -> A] -> [A -> T(S,A)]
3539 * and apply it to the schedule (2), obtaining
3541 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
3543 * Note that we can project out S because it is uniquely defined by L.
3545 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
3546 __isl_take isl_map *sched,
3547 const char *type, struct gpu_array_ref_group *group,
3548 __isl_take isl_ast_build *build, int private)
3550 const char *array_name;
3551 const char *mem = private ? "private" : "shared";
3552 char *name;
3553 isl_space *space;
3554 isl_ast_node *tree;
3555 isl_map *schedule, *shift, *map;
3556 isl_set *set;
3557 isl_id_list *iterators;
3558 int n;
3560 shift = isl_set_unwrap(isl_map_domain(isl_map_copy(sched)));
3561 array_name = isl_map_get_tuple_name(shift, isl_dim_out);
3562 shift = shift_access(shift, group);
3564 schedule = isl_map_copy(shift);
3565 if (!private)
3566 schedule = tile_access_schedule(gen, schedule);
3568 n = isl_map_dim(schedule, isl_dim_out);
3569 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
3570 set = add_bounded_parameters(set, gen->n_block, gen->block_dim, "t");
3572 schedule = isl_map_range_product(sched, schedule);
3574 assert(array_name);
3575 name = isl_alloc_array(gen->ctx, char,
3576 strlen(type) + sizeof("_private_") + strlen(array_name) + 20);
3577 if (group->array->n_group > 1)
3578 sprintf(name, "%s_%s_%s_%d", type, mem, array_name, group->nr);
3579 else
3580 sprintf(name, "%s_%s_%s", type, mem, array_name);
3581 shift = isl_map_set_tuple_name(shift,
3582 isl_dim_out, name + strlen(type) + 1);
3584 space = isl_space_domain(isl_map_get_space(shift));
3585 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
3586 map = isl_map_range_product(map, shift);
3588 schedule = isl_map_apply_domain(schedule, map);
3590 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, name);
3591 free(name);
3593 build = isl_ast_build_restrict(build, set);
3595 gen->copy_group = group;
3597 if (private) {
3598 space = isl_space_range(isl_map_get_space(schedule));
3599 space = isl_space_range(isl_space_unwrap(space));
3600 build = set_unroll(build, space, 0);
3602 iterators = generate_names(gen->ctx, n, "c");
3603 build = isl_ast_build_set_iterators(build, iterators);
3604 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
3605 tree = isl_ast_build_ast_from_schedule(build,
3606 isl_union_map_from_map(schedule));
3607 isl_ast_build_free(build);
3609 return tree;
3612 /* Return code for reading into or writing from shared memory
3613 * the given array reference group.
3615 * If we are performing a read from global memory to shared memory and
3616 * if the array involved is not a scalar, then we copy
3617 * the entire tile to shared memory. This may result in some extra
3618 * elements getting copied, but it should lead to simpler code
3619 * (which means that fewer registers may be needed) and less divergence.
3621 * Otherwise, we only copy the elements that will be read or have been written
3622 * in the kernel.
3625 * The input "sched" is of the form.
3627 * type[S -> A] -> L
3629 * with S the first shared_len dimensions of the computed schedule,
3630 * A the array and L the schedule correponding to the generated loops.
3632 * We first drop "type",
3634 * [S -> A] -> L
3636 * If the above conditions are satisfied, we project out A,
3637 * resulting in
3639 * S -> L
3641 * and then introduce the group tile [S -> T], resulting in
3643 * [S -> T] -> L
3645 static __isl_give isl_ast_node *copy_group_shared_accesses(
3646 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3647 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3649 const char *type;
3650 int read;
3651 isl_union_map *access;
3653 type = isl_map_get_tuple_name(sched, isl_dim_in);
3654 read = !strcmp(type, "read");
3656 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3658 if (read && group->array->n_index > 0) {
3659 isl_space *space;
3660 isl_map *map;
3662 space = isl_space_domain(isl_map_get_space(sched));
3663 space = isl_space_unwrap(space);
3664 map = isl_map_domain_map(isl_map_universe(space));
3665 sched = isl_map_apply_domain(sched, map);
3667 map = group_tile(group);
3668 map = isl_map_reverse(isl_map_domain_map(map));
3669 sched = isl_map_apply_domain(sched, map);
3672 return copy_access(gen, sched, type, group, build, 0);
3675 /* Return code for reading into or writing from private memory
3676 * the given array reference group.
3678 * Let S be the first shared_len dimensions of the computed schedule,
3679 * D the iteration domains, A the array and L the schedule correponding
3680 * to the generated loops.
3681 * "sched" is of the form
3683 * type[S -> A] -> L
3685 * where type is either "read" or "write".
3686 * We apply the privatization D -> S(t), with t the thread ids,
3687 * to the access relation D -> A to obtain the privatized access relation
3689 * S(t) -> A
3691 * We drop the type from "sched" and intersect with the privatized access
3692 * relation to obtain
3694 * [S(t) -> A] -> L
3696 static __isl_give isl_ast_node *copy_group_private_accesses(
3697 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3698 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3700 const char *type;
3701 int read;
3702 isl_union_map *priv;
3703 isl_union_map *access;
3704 isl_map *access_map;
3706 type = isl_map_get_tuple_name(sched, isl_dim_in);
3707 read = !strcmp(type, "read");
3709 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
3710 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3711 priv);
3713 access = group_access_relation(group, read, !read);
3714 access = isl_union_map_apply_domain(access, priv);
3715 access_map = isl_map_from_union_map(access);
3717 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3718 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
3720 return copy_access(gen, sched, type, group, build, 1);
3723 /* Return code for reading into or writing from shared or private memory.
3725 * "schedule" is of the form
3727 * type[S -> A] -> L
3729 * with S be the first shared_len dimensions of the computed schedule,
3730 * A the array and L the schedule correponding to the generated loops.
3731 * The array reference group is attached to "type".
3733 static __isl_give isl_ast_node *create_access_leaf(
3734 struct gpu_gen *gen, __isl_take isl_map *schedule,
3735 __isl_take isl_ast_build *build)
3737 struct gpu_array_ref_group *group;
3738 isl_id *id;
3740 id = isl_map_get_tuple_id(schedule, isl_dim_in);
3741 group = isl_id_get_user(id);
3742 isl_id_free(id);
3744 if (group->private_tile)
3745 return copy_group_private_accesses(gen, group, schedule,
3746 build);
3747 else
3748 return copy_group_shared_accesses(gen, group, schedule,
3749 build);
3752 /* Create a domain node representing a synchronization.
3754 static __isl_give isl_ast_node *create_sync_leaf(
3755 struct gpu_gen *gen, __isl_take isl_map *schedule,
3756 __isl_take isl_ast_build *build)
3758 struct ppcg_kernel_stmt *stmt;
3759 isl_id *id;
3760 isl_space *space;
3761 isl_ast_node *node;
3762 isl_ast_expr *expr;
3764 isl_map_free(schedule);
3766 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3767 if (!stmt)
3768 return NULL;
3770 stmt->type = ppcg_kernel_sync;
3772 space = isl_ast_build_get_schedule_space(build);
3773 space = isl_space_from_domain(space);
3774 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
3775 expr = isl_ast_build_call_from_pw_multi_aff(build,
3776 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
3777 node = isl_ast_node_alloc_user(expr);
3778 isl_ast_build_free(build);
3780 id = isl_id_alloc(gen->ctx, NULL, stmt);
3781 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3782 return isl_ast_node_set_annotation(node, id);
3785 /* This function is called during the code generation at the point
3786 * where the schedule domain element is completely determined by
3787 * the generated code. The input schedule contains the original
3788 * statements as well as synchronization and copy "statements".
3789 * The latter are scheduled at different points than any of the original
3790 * statements, so they will only arrive here in isolation.
3792 * If the current schedule only refers to a single statement,
3793 * we check if it is a copy or synchronization statement and
3794 * call the appropriate functions.
3795 * Otherwise, we assume we are dealing with the original statements
3796 * and we call create_domain_leaf.
3798 static __isl_give isl_ast_node *create_kernel_leaf(
3799 __isl_take isl_ast_build *build, void *user)
3801 struct gpu_gen *gen = (struct gpu_gen *) user;
3802 isl_map *map;
3803 isl_union_map *schedule;
3804 const char *name;
3806 schedule = isl_ast_build_get_schedule(build);
3808 if (isl_union_map_n_map(schedule) != 1)
3809 return create_domain_leaf(schedule, build, user);
3811 map = isl_map_from_union_map(schedule);
3812 name = isl_map_get_tuple_name(map, isl_dim_in);
3813 if (!strcmp(name, "read") || !strcmp(name, "write"))
3814 return create_access_leaf(gen, map, build);
3815 if (!strcmp(name, "sync"))
3816 return create_sync_leaf(gen, map, build);
3818 return create_domain_leaf(isl_union_map_from_map(map), build, user);
3821 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
3822 * have value 0) and all even schedule dimensions as "unroll".
3824 * That is, the options look as follows
3826 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
3827 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
3829 * The even positions are used to be able to schedule copying blocks
3830 * and synchronization before or after each level of the shared memory
3831 * tile loops and we want to make sure that code for these is generated
3832 * separately (within each level).
3834 static __isl_give isl_ast_build *set_atomic_and_unroll(
3835 __isl_take isl_ast_build *build,
3836 __isl_take isl_space *space, int sched_len)
3838 isl_ctx *ctx;
3839 isl_map *map;
3840 isl_constraint *c;
3841 isl_union_map *opt;
3842 isl_local_space *ls;
3843 int i, n;
3845 ctx = isl_ast_build_get_ctx(build);
3847 space = isl_space_params(space);
3848 space = isl_space_add_dims(space, isl_dim_set, sched_len);
3849 space = isl_space_from_domain(space);
3850 space = isl_space_add_dims(space, isl_dim_out, 2);
3851 map = isl_map_universe(isl_space_copy(space));
3852 for (i = 0; i < sched_len; i += 2)
3853 map = isl_map_fix_si(map, isl_dim_in, i, 0);
3854 ls = isl_local_space_from_space(isl_map_get_space(map));
3855 c = isl_equality_alloc(ls);
3856 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3857 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3858 c = isl_constraint_set_constant_si(c, 1);
3859 map = isl_map_add_constraint(map, c);
3860 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3861 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
3862 opt = isl_union_map_from_map(map);
3864 map = isl_map_universe(space);
3865 ls = isl_local_space_from_space(isl_map_get_space(map));
3866 c = isl_equality_alloc(ls);
3867 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3868 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3869 map = isl_map_add_constraint(map, c);
3870 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3871 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
3872 opt = isl_union_map_add_map(opt, map);
3874 build = isl_ast_build_set_options(build, opt);
3876 return build;
3879 /* Return a map that maps a space of dimension gen->shared_len
3880 * to its last dimensions starting at gen->tile_first.
3881 * The range is of dimension
3883 * 2 * (gen->shared_len - gen->tile_first) + 1
3885 * The input dimensions are mapped to the odd dimensions in the output,
3886 * while the even dimensions (except 2*pos) are fixed to 0.
3887 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
3888 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
3889 * are mapped to the output. The remaining input dimensions are projected
3890 * out and the corresponding output dimensions are fixed to 0.
3892 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
3893 __isl_take isl_space *space, int pos, int val)
3895 int i, n;
3896 isl_map *proj;
3898 space = isl_space_set_from_params(space);
3899 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
3900 space = isl_space_map_from_set(space);
3901 proj = isl_map_identity(space);
3902 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
3903 n = gen->shared_len - gen->tile_first;
3904 for (i = 0; i <= n; ++i) {
3905 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
3906 if (i == pos)
3907 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
3908 else
3909 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
3912 if (pos < 0)
3913 return proj;
3915 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
3916 gen->shared_len - (gen->tile_first + pos));
3917 for (i = pos; i < n; ++i)
3918 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
3920 return proj;
3923 /* Given the AST context schedule "schedule" and the mapping from
3924 * domains to the shared tile loops "shared_sched", add a schedule
3925 * for a synchronization operation at position "val" of loop level "pos".
3927 * schedule is of the form
3929 * D -> L
3931 * (with D the iteration domains and L the already generated loops),
3932 * while shared_sched is of the form
3934 * D -> S
3936 * We combine them into
3938 * L -> S
3940 * apply a mapping
3942 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
3944 * and use the result as a schedule for "sync".
3946 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
3947 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
3948 __isl_keep isl_union_map *shared_sched, int pos, int val)
3950 isl_space *space;
3951 isl_map *proj, *map;
3953 shared_sched = isl_union_map_copy(shared_sched);
3954 schedule = isl_union_map_copy(schedule);
3956 space = isl_union_map_get_space(shared_sched);
3957 schedule = isl_union_map_apply_domain(shared_sched, schedule);
3958 map = isl_map_from_union_map(schedule);
3960 proj = insert_even(gen, space, pos, val);
3961 map = isl_map_apply_range(map, proj);
3962 map = isl_map_from_range(isl_map_wrap(map));
3963 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
3965 res = isl_union_map_add_map(res, map);
3967 return res;
3970 /* Given the AST context schedule "schedule" and the mapping from
3971 * domains to the shared tile loops "shared_sched", add a schedule
3972 * for copying an array reference group to/from shared/private memory.
3973 * "read" is set if data should be copied from global memory
3974 * to shared/private memory.
3975 * "k" represents the current group
3976 * "s" is the total number of groups
3978 * We schedule an operation before or after the innermost loop
3979 * of "shared_sched" that affects the tile of the array reference group.
3981 * schedule is of the form
3983 * D -> L
3985 * (with D the iteration domains and L the already generated loops),
3986 * while shared_sched is of the form
3988 * D -> S
3990 * We first compute the access relation for the reference group
3992 * D -> A
3994 * and combine it with shared_sched into
3996 * D -> [S -> A]
3998 * If this results in an empty relation, no copying needs to be performed
3999 * at this point.
4000 * Otherwise, we invert the relation and combine it with "schedule" into
4002 * [S -> A] -> L
4004 * The actual additional piece of the schedule is obtained from combining
4006 * [S -> A] -> S
4008 * with a mapping
4010 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4012 * The position of "val" corresponds to the innermost loop that affects
4013 * the tile and the value indicates where the copying is scheduled
4014 * with respect to the actual kernel code (at value 0).
4015 * Reads are schedule before the code, writes to global memory from
4016 * private memory are scheduled at values 1 to s, writes to global
4017 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4019 * If we are scheduling a read from global memory to shared memory,
4020 * we insert a synchronization before the kernel code (at the innermost
4021 * level).
4022 * If we are scheduling a write to global memory, then we add
4023 * a synchronization after all writes (at value 2 *s + 2).
4024 * However, there is no need for a synchronization after the outermost loop.
4025 * A write to global memory from private memory at the innermost level
4026 * does not require a synchronization, because it is covered by
4027 * the synchronization after the kernel inserted by body_schedule.
4029 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4030 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4031 __isl_keep isl_union_map *shared_sched,
4032 struct gpu_array_ref_group *group, int read, int k, int s)
4034 int n;
4035 int pos, val;
4036 isl_space *space;
4037 isl_union_map *access;
4038 isl_map *map, *proj, *access_map;
4039 isl_id *id;
4041 access = group_access_relation(group, read, !read);
4042 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4043 access);
4045 if (isl_union_map_is_empty(access)) {
4046 isl_union_map_free(access);
4047 return res;
4050 access = isl_union_map_reverse(access);
4051 access = isl_union_map_apply_range(access,
4052 isl_union_map_copy(schedule));
4053 access_map = isl_map_from_union_map(access);
4055 space = isl_space_copy(group->array->dim);
4056 space = isl_space_from_range(space);
4057 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4058 map = isl_map_domain_map(isl_map_universe(space));
4060 space = isl_union_map_get_space(schedule);
4061 pos = group->last_shared + 1 - gen->tile_first;
4062 assert(pos >= 0);
4063 if (read)
4064 val = -2 - k;
4065 else if (group->private_tile)
4066 val = 1 + k;
4067 else
4068 val = 1 + s + 1 + k;
4069 proj = insert_even(gen, space, pos, val);
4070 map = isl_map_apply_range(map, proj);
4072 access_map = isl_map_range_product(access_map, map);
4074 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4075 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4077 res = isl_union_map_add_map(res, access_map);
4079 n = gen->shared_len - gen->tile_first;
4080 if (read) {
4081 if (!group->private_tile)
4082 res = add_sync_schedule(gen, res, schedule,
4083 shared_sched, n, -1);
4084 } else {
4085 if (pos == 0)
4086 return res;
4087 if (pos == n && group->private_tile)
4088 return res;
4089 res = add_sync_schedule(gen, res, schedule, shared_sched,
4090 pos, 2 * s + 2);
4093 return res;
4096 /* Return a schedule for the shared tile loops based on the current
4097 * AST context schedule.
4099 * We create a "shared_sched" that maps the domains to the first
4100 * shared_len dimensions of the computed schedule, project out the
4101 * first tile_first dimensions (as these are already covered by
4102 * the host code) and insert "statement-level" dimensions at even
4103 * positions so that we can schedule copy blocks and synchronization
4104 * before/after each level.
4106 * In particular, copy blocks are inserted inside the innermost
4107 * level that affect the tile. For the copying to global memory,
4108 * those from private memory are scheduled before those from shared
4109 * memory such that synchronization can be inserted between the two
4110 * at the innermost level.
4111 * Synchronization is inserted at the innermost level before the
4112 * actual kernel code if there is any copying from global memory
4113 * to shared memory. It is inserted unconditionally at the innermost
4114 * level after the actual kernel code and the copying to global memory
4115 * from private memory (if any). Finally, it is inserted after
4116 * any copying to global memory, except at the outermost level
4117 * and at the innermost level if there is no copying from shared
4118 * memory. The copying from private memory is covered by the unconditional
4119 * synchronization at the innermost level.
4121 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4122 __isl_take isl_union_map *schedule)
4124 isl_space *space;
4125 isl_union_map *res;
4126 isl_union_map *shared_sched;
4127 isl_union_map *sched;
4128 isl_map *proj, *map;
4129 int i, j, k, s;
4131 shared_sched = isl_union_map_copy(gen->tiled_sched);
4132 proj = projection(isl_union_map_get_space(shared_sched),
4133 gen->tiled_len, gen->shared_len);
4134 shared_sched = isl_union_map_apply_range(shared_sched,
4135 isl_union_map_from_map(proj));
4136 space = isl_union_map_get_space(shared_sched);
4137 proj = insert_even(gen, space, -1, 0);
4138 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4139 isl_union_map_from_map(proj));
4141 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4143 s = 0;
4144 for (i = 0; i < gen->prog->n_array; ++i)
4145 s += gen->prog->array[i].n_group;
4147 k = 0;
4148 for (i = 0; i < gen->prog->n_array; ++i) {
4149 struct gpu_array_info *array = &gen->prog->array[i];
4151 for (j = 0; j < array->n_group; ++j) {
4152 struct gpu_array_ref_group *group;
4154 group = array->groups[j];
4155 if (!group->private_tile && !group->shared_tile)
4156 continue;
4157 res = add_group_schedule(gen, res, schedule,
4158 shared_sched, group, 0, k, s);
4159 res = add_group_schedule(gen, res, schedule,
4160 shared_sched, group, 1, k, s);
4161 ++k;
4165 res = add_sync_schedule(gen, res, schedule, shared_sched,
4166 gen->shared_len - gen->tile_first, 1 + s);
4168 isl_union_map_free(shared_sched);
4169 isl_union_map_free(schedule);
4171 return res;
4174 /* Generate code for "kernel" in the given "context".
4176 * We first generate code for the shared tile loops (T1T, T1P and T2)
4177 * in a context that includes the block ids.
4178 * Within each iteration of these loops an additional code generation
4179 * is performed (within create_kernel_leaf) for the rest of the schedule
4180 * in a context that includes the thread ids.
4182 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4183 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4184 __isl_keep isl_multi_pw_aff *grid_size)
4186 isl_space *space;
4187 isl_set *set;
4188 isl_id_list *iterators;
4189 isl_union_map *schedule;
4190 isl_ast_node *tree;
4191 int sched_len;
4193 schedule = isl_ast_build_get_schedule(build);
4195 build = isl_ast_build_copy(build);
4196 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4197 space = isl_ast_build_get_schedule_space(build);
4198 set = isl_set_universe(isl_space_copy(space));
4199 set = add_bounded_parameters_dynamic(set, grid_size, "b");
4200 build = isl_ast_build_restrict(build, set);
4202 schedule = body_schedule(gen, schedule);
4204 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4206 build = set_atomic_and_unroll(build, space, sched_len);
4207 iterators = generate_names(gen->ctx, sched_len, "g");
4208 build = isl_ast_build_set_iterators(build, iterators);
4209 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4210 tree = isl_ast_build_ast_from_schedule(build, schedule);
4211 isl_ast_build_free(build);
4213 return tree;
4216 /* Attach "id" to the given node.
4218 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4219 __isl_keep isl_ast_build *build, void *user)
4221 isl_id *id = user;
4223 node = isl_ast_node_set_annotation(node, id);
4225 return node;
4228 /* Construct an AST node for performing a kernel launch and attach
4229 * the information about the kernel to that node.
4231 * The kernel AST has been constructed in the context of the range
4232 * of "schedule". In particular, the grid size has been computed
4233 * in the context. We therefore still need to make sure that these
4234 * constraints are expressed in the code. We do this by creating a schedule
4236 * kernel[] -> [S -> []]
4238 * where S is the schedule domain, i.e., the range of "schedule".
4239 * The AST generation will then create a single call surrounded by
4240 * all the condition in "S" that have not been expressed yet.
4242 * The kernel information is attached to this node in attach_id.
4244 static __isl_give isl_ast_node *construct_launch(
4245 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
4246 __isl_take struct ppcg_kernel *kernel)
4248 isl_id *id;
4249 isl_ctx *ctx;
4250 isl_union_set *domain;
4251 isl_set *set;
4252 isl_map *map;
4253 isl_ast_node *node;
4255 ctx = isl_ast_build_get_ctx(build);
4257 id = isl_id_alloc(ctx, NULL, kernel);
4258 id = isl_id_set_free_user(id, &ppcg_kernel_free);
4260 domain = isl_union_map_range(schedule);
4261 set = isl_set_from_union_set(domain);
4262 map = isl_map_from_domain(set);
4263 map = isl_map_from_range(isl_map_wrap(map));
4264 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
4265 schedule = isl_union_map_from_map(map);
4267 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
4268 node = isl_ast_build_ast_from_schedule(build, schedule);
4269 isl_ast_build_free(build);
4271 return node;
4274 /* This function is called for each leaf in the AST of the host code.
4275 * We first specialize the schedule to the site of the leaf, compute
4276 * the size of shared memory and then construct the body of host code
4277 * and the associated kernel.
4279 * The necessary information for printing the kernel launch is
4280 * stored in a struct ppcg_kernel and attached to the leaf node
4281 * created to represent the launch.
4283 static __isl_give isl_ast_node *create_host_leaf(
4284 __isl_take isl_ast_build *build, void *user)
4286 struct gpu_gen *gen = (struct gpu_gen *) user;
4287 isl_id *id;
4288 isl_ast_node *node;
4289 struct ppcg_kernel *kernel;
4290 isl_set *host_domain;
4291 isl_union_map *schedule;
4292 isl_union_map *local_sched;
4293 isl_union_map *access;
4294 isl_union_set *domain;
4295 int i;
4297 schedule = isl_ast_build_get_schedule(build);
4299 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
4300 read_sizes(gen);
4302 domain = isl_union_map_domain(isl_union_map_copy(schedule));
4304 local_sched = isl_union_map_copy(gen->sched);
4305 local_sched = isl_union_map_intersect_domain(local_sched, domain);
4306 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
4307 isl_union_map_copy(gen->prog->write));
4308 access = isl_union_map_apply_domain(access,
4309 isl_union_map_copy(local_sched));
4311 gen->tiled_sched = tile_schedule(gen, local_sched);
4312 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
4313 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
4315 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
4316 if (!kernel)
4317 goto error;
4319 kernel->id = gen->kernel_id++;
4320 kernel->n_block = gen->n_block;
4321 for (i = 0; i < gen->n_block; ++i)
4322 kernel->block_dim[i] = gen->block_dim[i];
4323 kernel->n_grid = gen->n_grid;
4324 for (i = 0; i < gen->n_grid; ++i)
4325 kernel->grid_dim[i] = gen->grid_dim[i];
4326 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
4327 kernel->grid_size = extract_grid_size(gen, kernel);
4328 kernel->arrays = isl_union_map_range(access);
4329 kernel->space = isl_ast_build_get_schedule_space(build);
4331 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
4333 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
4334 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
4336 gen->private_access = NULL;
4337 compute_shared_sched(gen);
4338 gen->privatization = compute_privatization(gen);
4339 group_references(gen);
4340 compute_private_access(gen);
4341 check_shared_memory_bound(gen);
4342 host_domain = isl_set_from_union_set(isl_union_map_range(
4343 isl_union_map_copy(schedule)));
4344 localize_bounds(gen, kernel, host_domain);
4346 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
4348 kernel->tree = generate_kernel(gen, build, host_domain,
4349 kernel->grid_size);
4350 create_kernel_vars(gen, kernel);
4352 free_local_array_info(gen);
4353 isl_map_free(gen->privatization);
4354 isl_union_map_free(gen->private_access);
4355 isl_union_map_free(gen->local_sched);
4356 isl_union_map_free(gen->tiled_sched);
4357 isl_union_map_free(gen->shared_sched);
4358 isl_union_map_free(gen->shared_proj);
4359 isl_set_free(host_domain);
4360 free(gen->tile_size);
4362 node = construct_launch(build, schedule, kernel);
4364 return node;
4365 error:
4366 isl_union_map_free(schedule);
4367 return NULL;
4370 /* Use isl to generate code for the outer gen->tile_first loops
4371 * of the global schedule in gen->sched, resulting in the host code.
4372 * Within each iteration of this partial schedule, i.e., for each kernel
4373 * launch, create_host_leaf takes care of generating the kernel code.
4375 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
4377 isl_ast_build *build;
4378 isl_ast_node *tree;
4379 isl_union_map *sched;
4380 isl_map *proj;
4381 isl_id_list *iterators;
4383 sched = isl_union_map_copy(gen->sched);
4384 proj = projection(isl_union_map_get_space(sched),
4385 gen->untiled_len, gen->tile_first);
4386 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4388 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
4389 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
4390 iterators = generate_names(gen->ctx, gen->tile_first, "h");
4391 build = isl_ast_build_set_iterators(build, iterators);
4392 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
4393 tree = isl_ast_build_ast_from_schedule(build, sched);
4394 isl_ast_build_free(build);
4396 return tree;
4399 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
4401 if (!str)
4402 return NULL;
4403 return isl_union_map_read_from_str(ctx, str);
4406 /* Information about the outermost tilable bands in the forest of bands.
4408 * tile_len and n_parallel are only sets on band_info structures
4409 * that correspond to outermost bands. For other bands (in particular,
4410 * ancestors of the outermost bands), n_parallal is set to 0.
4412 * prefix is the (padded) schedule leading up to the outermost tilable bands.
4414 * tile_first is the number of schedule dimensions in prefix.
4416 * suffix is the schedule of the outermost tilable bands and their descendants.
4418 struct band_info {
4419 struct gpu_gen *gen;
4420 int tile_first;
4421 int tile_len;
4422 int n_parallel;
4423 isl_union_map *prefix;
4424 isl_union_map *suffix;
4427 /* Set tile_len and n_parallel of the statement to that of
4428 * their outermost band, recorded in the band_info.
4430 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
4432 struct band_info *info = user;
4433 struct gpu_stmt *stmt;
4434 isl_id *id;
4436 id = isl_map_get_tuple_id(map, isl_dim_in);
4437 stmt = find_stmt(info->gen->prog, id);
4438 isl_id_free(id);
4440 stmt->tile_len = info->tile_len;
4441 stmt->n_parallel = info->n_parallel;
4443 isl_map_free(map);
4445 return 0;
4448 static void list_select_outer_band(struct gpu_gen *gen,
4449 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
4451 /* Check if this band has any parallel loops. If so, take it as
4452 * the outermost tilable band. If not, continue looking for the
4453 * outermost tilable band in the children of the current band.
4455 static void band_select_outer_band(struct gpu_gen *gen,
4456 __isl_take isl_band *band, int pos, struct band_info *info)
4458 int n = isl_band_n_member(band);
4459 int n_parallel;
4461 for (n_parallel = 0; n_parallel < n; ++n_parallel)
4462 if (!isl_band_member_is_zero_distance(band, n_parallel))
4463 break;
4465 info->n_parallel = n_parallel;
4466 if (n_parallel) {
4467 info->gen = gen;
4468 info->tile_first = pos;
4469 info->tile_len = n;
4470 info->prefix = isl_band_get_prefix_schedule(band);
4471 info->suffix = isl_union_map_flat_range_product(
4472 isl_band_get_partial_schedule(band),
4473 isl_band_get_suffix_schedule(band));
4474 isl_union_map_foreach_map(info->prefix,
4475 &set_stmt_tile_len, info);
4476 } else if (isl_band_has_children(band)) {
4477 isl_band_list *children;
4478 children = isl_band_get_children(band);
4479 list_select_outer_band(gen, children, pos + n, info);
4480 } else {
4481 info->gen = gen;
4482 info->tile_first = pos + n;
4483 info->tile_len = 0;
4484 info->prefix = isl_union_map_flat_range_product(
4485 isl_band_get_prefix_schedule(band),
4486 isl_band_get_partial_schedule(band));
4487 info->suffix = isl_band_get_suffix_schedule(band);
4488 isl_union_map_foreach_map(info->prefix,
4489 &set_stmt_tile_len, info);
4492 isl_band_free(band);
4495 /* Comparison function that returns a non-zero value for band_infos
4496 * with different tile_len fields or different n_parallel fields.
4498 static int cmp_band(const void *p1, const void *p2)
4500 const struct band_info *info1 = p1;
4501 const struct band_info *info2 = p2;
4503 if (info1->tile_len != info2->tile_len)
4504 return info1->tile_len - info2->tile_len;
4506 return info1->n_parallel - info2->n_parallel;
4509 /* Extend "umap" with coordinates with fixed value "val"
4510 * to a total length of "dst_len", assuming the original dimension is "src_len".
4512 static __isl_give isl_union_map *extend_range(
4513 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
4515 isl_space *dim;
4516 isl_map *map;
4517 int i;
4519 dim = isl_union_map_get_space(umap);
4520 map = isl_map_reverse(projection(dim, dst_len, src_len));
4521 for (i = src_len; i < dst_len; ++i)
4522 map = isl_map_fix_si(map, isl_dim_out, i, val);
4524 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
4526 return umap;
4529 /* Group bands with the same values for tile_len and n_parallel.
4530 * The prefix schedule is then extended with a fixed coordinate that
4531 * is different for each such group.
4532 * Note that the actual values for this coordinate are not important.
4533 * The bands have already been effectively separated at a higher level
4534 * or they are independent and may be executed in parallel.
4535 * The list of band_info has been sorted before this functions is called.
4537 static void separate_bands(struct band_info *info, int n)
4539 int i;
4540 int j = 0;
4542 for (i = 0; i < n; ++i) {
4543 int l = info[i].tile_first;
4545 if (i &&
4546 (info[i].tile_len != info[i - 1].tile_len ||
4547 info[i].n_parallel != info[i - 1].n_parallel))
4548 j++;
4550 info[i].prefix = extend_range(info[i].prefix,
4551 l, l + 1, j);
4552 info[i].tile_first = l + 1;
4556 /* Select the outermost bands in the elements of the list, align
4557 * their prefix schedules, separate bands with different values
4558 * for tile_len and/or n_parallel and then combine the resulting
4559 * prefix and suffix schedules into a single pair of prefix and
4560 * suffix schedules for the entire list.
4562 static void list_select_outer_band(struct gpu_gen *gen,
4563 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
4565 isl_band *band;
4566 int i;
4567 int n = isl_band_list_n_band(list);
4568 isl_ctx *ctx = isl_band_list_get_ctx(list);
4569 struct band_info *info;
4570 int max_tile_first;
4571 isl_union_map *prefix;
4572 isl_union_map *suffix;
4574 assert(n >= 1);
4575 info = isl_calloc_array(ctx, struct band_info, n);
4576 assert(info);
4578 max_tile_first = 0;
4579 for (i = 0; i < n; ++i) {
4580 band = isl_band_list_get_band(list, i);
4581 band_select_outer_band(gen, band, pos, &info[i]);
4582 if (info[i].tile_first > max_tile_first)
4583 max_tile_first = info[i].tile_first;
4586 for (i = 0; i < n; ++i) {
4587 if (info[i].tile_first == max_tile_first)
4588 continue;
4589 info[i].prefix = extend_range(info[i].prefix,
4590 info[i].tile_first, max_tile_first, 0);
4591 info[i].tile_first = max_tile_first;
4594 qsort(info, n, sizeof(struct band_info), &cmp_band);
4596 for (i = 0; i < n - 1; ++i)
4597 if (info[i].tile_len != info[i + 1].tile_len ||
4598 info[i].n_parallel != info[i + 1].n_parallel)
4599 break;
4601 if (i < n -1)
4602 separate_bands(info, n);
4604 prefix = info[0].prefix;
4605 suffix = info[0].suffix;
4607 for (i = 1; i < n; ++i) {
4608 prefix = isl_union_map_union(prefix, info[i].prefix);
4609 suffix = isl_union_map_union(suffix, info[i].suffix);
4612 list_info->tile_first = info[0].tile_first;
4613 list_info->tile_len = -1;
4614 list_info->prefix = prefix;
4615 list_info->suffix = suffix;
4617 isl_band_list_free(list);
4618 free(info);
4621 /* Select the outermost tilable band that (by construction)
4622 * has at least one parallel loop.
4623 * The starting position of the aligned band is stored in the pair
4624 * gen->tile_first.
4625 * The sizes and number of parallel loops may be different in different
4626 * parts of the band forest and are therefore stored in the gpu_stmts.
4628 * Return the complete schedule, with the tilable bands aligned
4629 * at gen->tile_first and padded with zero, if needed.
4631 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
4632 __isl_keep isl_schedule *schedule)
4634 isl_band_list *list;
4635 struct band_info info;
4637 gen->n_parallel = 0;
4638 gen->tile_len = -1;
4640 list = isl_schedule_get_band_forest(schedule);
4642 list_select_outer_band(gen, list, 0, &info);
4644 gen->tile_first = info.tile_first;
4645 info.suffix = align_range(info.suffix);
4647 return isl_union_map_flat_range_product(info.prefix, info.suffix);
4650 /* Set gen->untiled_len to the number of scheduling dimensions
4651 * for the schedule of the first domain.
4652 * We assume here that this number is the same for all domains.
4654 static int set_untiled_len(__isl_take isl_map *map, void *user)
4656 unsigned *untiled_len = user;
4658 *untiled_len = isl_map_dim(map, isl_dim_out);
4660 isl_map_free(map);
4661 return -1;
4664 /* Compute an appropriate schedule based on the accesses in
4665 * gen->read and gen->write.
4667 * We use the dependences in gen->prog->scop to compute
4668 * a schedule that has a parallel loop in each tilable band.
4669 * Finally, we select the outermost tilable band.
4671 static void compute_schedule(struct gpu_gen *gen)
4673 isl_union_set *domain;
4674 isl_union_map *dep_raw, *dep;
4675 isl_union_map *sched;
4676 isl_schedule *schedule;
4678 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4680 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4681 dep = isl_union_map_union(dep, dep_raw);
4682 dep = isl_union_map_coalesce(dep);
4684 domain = isl_union_set_copy(gen->prog->scop->domain);
4685 domain = isl_union_set_intersect_params(domain,
4686 isl_set_copy(gen->prog->scop->context));
4687 schedule = isl_union_set_compute_schedule(isl_union_set_copy(domain),
4688 isl_union_map_copy(dep), dep);
4689 if (gen->options->debug->dump_schedule)
4690 isl_schedule_dump(schedule);
4692 sched = select_outer_tilable_band(gen, schedule);
4694 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
4695 sched = isl_union_map_intersect_domain(sched, domain);
4696 gen->sched = sched;
4698 isl_schedule_free(schedule);
4701 /* Compute the sets of array elements that need to be copied in and out.
4703 * In particular, for each array that is written anywhere in gen->prog and
4704 * that is visible outside the corresponding scop, we copy out its entire
4705 * extent.
4707 * Any array elements that is read without first being written needs
4708 * to be copied in. Furthermore, if there are any array elements that
4709 * are copied out, but that are not written inside gen->prog, then
4710 * they also need to be copied in to ensure that the value after execution
4711 * is the same as the value before execution.
4712 * While computing the set of array elements that
4713 * are copied out but not written, we intersect both sets with the context.
4714 * This helps in those cases where the arrays are declared with a fixed size,
4715 * while the accesses are parametric and the context assigns a fixed value
4716 * to the parameters.
4718 static void compute_copy_in_and_out(struct gpu_gen *gen)
4720 int i;
4721 isl_union_set *write;
4722 isl_union_set *copy_in, *copy_out;
4723 isl_union_set *not_written;
4724 isl_union_map *uninitialized;
4726 write = isl_union_map_range(isl_union_map_copy(gen->prog->write));
4727 write = isl_union_set_intersect_params(write,
4728 isl_set_copy(gen->prog->context));
4729 copy_out = isl_union_set_empty(isl_union_set_get_space(write));
4731 for (i = 0; i < gen->prog->n_array; ++i) {
4732 isl_space *space;
4733 isl_set *write_i;
4734 int empty;
4736 if (gen->prog->array[i].local)
4737 continue;
4739 space = isl_space_copy(gen->prog->array[i].dim);
4740 write_i = isl_union_set_extract_set(write, space);
4741 empty = isl_set_fast_is_empty(write_i);
4742 isl_set_free(write_i);
4743 if (empty)
4744 continue;
4746 write_i = isl_set_copy(gen->prog->array[i].extent);
4747 copy_out = isl_union_set_add_set(copy_out, write_i);
4750 copy_out = isl_union_set_intersect_params(copy_out,
4751 isl_set_copy(gen->prog->context));
4753 gen->prog->copy_out = isl_union_set_copy(copy_out);
4755 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
4756 copy_in = isl_union_map_range(uninitialized);
4758 not_written = isl_union_set_subtract(copy_out, write);
4759 copy_in = isl_union_set_union(copy_in, not_written);
4760 gen->prog->copy_in = copy_in;
4763 static struct gpu_stmt_access **expr_extract_access(struct pet_expr *expr,
4764 struct gpu_stmt_access **next_access)
4766 struct gpu_stmt_access *access;
4767 isl_ctx *ctx = isl_map_get_ctx(expr->acc.access);
4769 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4770 assert(access);
4771 access->next = NULL;
4772 access->read = expr->acc.read;
4773 access->write = expr->acc.write;
4774 access->access = isl_map_copy(expr->acc.access);
4776 *next_access = access;
4777 next_access = &(*next_access)->next;
4778 return next_access;
4781 static struct gpu_stmt_access **expr_extract_accesses(struct pet_expr *expr,
4782 struct gpu_stmt_access **next_access)
4784 int i;
4786 for (i = 0; i < expr->n_arg; ++i)
4787 next_access = expr_extract_accesses(expr->args[i],
4788 next_access);
4790 if (expr->type == pet_expr_access)
4791 next_access = expr_extract_access(expr, next_access);
4793 return next_access;
4796 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
4798 struct gpu_stmt_access **next_access = &stmt->accesses;
4800 stmt->accesses = NULL;
4801 expr_extract_accesses(stmt->body, next_access);
4804 /* Return an array of gpu_stmt representing the statements in "scop".
4806 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4807 __isl_keep isl_set *context)
4809 int i;
4810 struct gpu_stmt *stmts;
4812 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
4813 assert(stmts);
4815 for (i = 0; i < scop->n_stmt; ++i) {
4816 struct gpu_stmt *s = &stmts[i];
4818 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
4819 s->body = scop->stmts[i]->body;
4820 pet_stmt_extract_accesses(s);
4823 return stmts;
4826 /* Replace the scop in the "input" file by equivalent code
4827 * that uses the GPU. "scop" is assumed to correspond to this scop.
4829 * We first compute a schedule that respects the dependences
4830 * of the original program and select the outermost band
4831 * of tilable dimensions that has at least one parallel loop.
4832 * We then have three blocks of dimensions
4834 * H B G
4836 * The tilable band "B" is first tiled according to "tile" sizes, resulting
4837 * in
4839 * H T P G
4841 * For each iteration of the T loop and for each array, we compute
4842 * the array elements accessed by that iteration, construct a rectangular
4843 * box around it and shift it to the origin. The result is used
4844 * as shared memory for the array.
4846 * We then split off at most 2 parallel loops from the T loops and
4847 * at most 3 parallel loops from the P loops
4849 * H T1 T2 P1 P2 G
4851 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
4852 * according to "grid"/"block" sizes.
4854 * H T1T T1P T2 P1T P1P P2 G
4856 * Finally, the T1P and P1P iterators are equated to the block and
4857 * thread dimensions respectively and so are effectively removed.
4858 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
4859 * are run on the GPU.
4861 * Code is generated in three stages. We first generate code for the
4862 * host (the H loops), with iterators h%d. Then, for each leaf node
4863 * of the resulting AST, we generate code for the shared loops (up to
4864 * and including T2), with iterators g%d and after equating the H loops
4865 * to h%d parameters and the T1P loops to the block dimensions.
4866 * Finally, we generate code for the remaining loops in a similar fashion.
4868 __isl_give isl_ast_node *generate_gpu(isl_ctx *ctx, struct gpu_prog *prog,
4869 struct ppcg_options *options)
4871 isl_union_map *sched;
4872 struct gpu_gen gen;
4873 isl_ast_node *tree;
4875 if (!prog)
4876 return NULL;
4878 gen.ctx = ctx;
4879 gen.prog = prog;
4880 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
4881 gen.options = options;
4883 compute_schedule(&gen);
4884 compute_copy_in_and_out(&gen);
4886 gen.kernel_id = 0;
4887 tree = generate_host_code(&gen);
4889 clear_gpu_gen(&gen);
4891 return tree;
4894 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
4896 struct gpu_prog *prog;
4898 if (!scop)
4899 return NULL;
4901 prog = isl_calloc_type(ctx, struct gpu_prog);
4902 assert(prog);
4904 prog->ctx = ctx;
4905 prog->scop = scop;
4906 prog->context = isl_set_copy(scop->context);
4907 prog->n_stmts = scop->n_stmt;
4908 prog->stmts = extract_stmts(ctx, scop, prog->context);
4909 prog->read = isl_union_map_copy(scop->reads);
4910 prog->write = isl_union_map_copy(scop->writes);
4912 collect_array_info(prog);
4914 return prog;
4917 void gpu_prog_free(struct gpu_prog *prog)
4919 if (!prog)
4920 return;
4921 free_array_info(prog);
4922 free_stmts(prog->stmts, prog->n_stmts);
4923 isl_union_set_free(prog->copy_in);
4924 isl_union_set_free(prog->copy_out);
4925 isl_union_map_free(prog->read);
4926 isl_union_map_free(prog->write);
4927 isl_set_free(prog->context);
4928 free(prog);