gpu.c: compute_size_in_direction: minor refactoring to improve readability
[ppcg.git] / gpu.c
blob850cbd0360a258d28818d437cea868dccddd5fd6
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;
1935 isl_aff *aff;
1936 isl_aff *lb;
1937 enum isl_lp_result res;
1939 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
1940 n_div = isl_constraint_dim(c, isl_dim_div);
1942 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
1943 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
1944 isl_constraint_free(c);
1945 return 0;
1948 isl_int_init(v);
1950 isl_constraint_get_coefficient(c, isl_dim_set, size->pos, &v);
1952 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
1953 aff = isl_aff_ceil(aff);
1955 lb = isl_aff_copy(aff);
1957 aff = isl_aff_neg(aff);
1958 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
1960 res = isl_basic_set_max(size->bset, aff, &v);
1961 isl_aff_free(aff);
1963 if (res == isl_lp_ok) {
1964 isl_int_add_ui(v, v, 1);
1965 if (isl_int_is_neg(size->bound->size) ||
1966 isl_int_lt(v, size->bound->size)) {
1967 isl_int_set(size->bound->size, v);
1968 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
1969 isl_aff_free(size->bound->lb);
1970 size->bound->lb = isl_aff_copy(lb);
1973 isl_aff_free(lb);
1975 isl_int_clear(v);
1976 isl_constraint_free(c);
1978 return 0;
1981 /* Given a basic map "bounds" that maps parameters and input dimensions
1982 * to a single output dimension, look for an expression in the parameters
1983 * and input dimensions such that the range of the output dimension shifted
1984 * by this expression is a constant.
1986 * In particular, we currently only consider lower bounds on the output
1987 * dimension as candidate expressions.
1989 static int compute_array_dim_size(struct gpu_array_bound *bound,
1990 __isl_take isl_basic_map *bounds)
1992 struct gpu_size_info size;
1994 bounds = isl_basic_map_detect_equalities(bounds);
1995 bounds = check_stride(bound, bounds);
1997 isl_int_set_si(bound->size, -1);
1998 bound->lb = NULL;
2000 size.bound = bound;
2001 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2002 size.bset = isl_basic_map_wrap(bounds);
2003 size.bset = isl_basic_set_flatten(size.bset);
2004 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2005 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2006 &size);
2007 isl_basic_set_free(size.bset);
2009 return isl_int_is_nonneg(bound->size) ? 0 : -1;
2012 /* Check if we can find a memory tile for the given array
2013 * based on the given accesses, and if so, put the results in "tile".
2015 * We project the accesses on each index in turn and look for a parametric
2016 * offset such that the size is constant.
2018 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2020 int i;
2022 for (i = 0; i < tile->n; ++i) {
2023 isl_map *access_i;
2024 isl_basic_map *hull;
2026 access_i = isl_map_copy(access);
2027 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2028 access_i = isl_map_project_out(access_i, isl_dim_out,
2029 1, tile->n - (i + 1));
2030 access_i = isl_map_compute_divs(access_i);
2031 hull = isl_map_simple_hull(access_i);
2032 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2033 return 0;
2036 return 1;
2039 /* Construct a map with input the shared tile loops and the loops that
2040 * will be wrapped around the threads that relates these later loops
2041 * to the thread indices and then projects them out.
2043 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2045 isl_map *priv;
2046 isl_map *tiling;
2047 isl_map *proj;
2048 isl_set *par;
2049 isl_space *dim;
2051 dim = isl_union_map_get_space(gen->shared_sched);
2053 if (gen->options->wrap)
2054 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2055 gen->shared_len, gen->n_block, gen->block_dim);
2056 else
2057 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2058 gen->shared_len, gen->n_block, gen->block_dim);
2060 priv = tiling;
2062 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2063 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2064 gen->n_block, "t");
2066 priv = isl_map_align_params(priv, isl_set_get_space(par));
2067 priv = isl_map_intersect_range(priv, par);
2069 dim = isl_map_get_space(priv);
2070 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2071 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2072 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2073 gen->shared_len);
2075 priv = isl_map_apply_range(priv, proj);
2077 return priv;
2080 /* Construct a map from domain_dim to domain_dim that increments
2081 * the dimension at position "pos" and leaves all other dimensions
2082 * constant.
2084 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2086 int i;
2087 int len = isl_space_dim(domain_dim, isl_dim_set);
2088 isl_space *dim;
2089 isl_basic_map *next;
2090 isl_local_space *ls;
2092 dim = isl_space_map_from_set(domain_dim);
2093 next = isl_basic_map_universe(isl_space_copy(dim));
2094 ls = isl_local_space_from_space(dim);
2096 for (i = 0; i < len; ++i) {
2097 isl_constraint *c;
2099 c = isl_equality_alloc(isl_local_space_copy(ls));
2100 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2101 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2102 if (i == pos)
2103 c = isl_constraint_set_constant_si(c, 1);
2104 next = isl_basic_map_add_constraint(next, c);
2107 isl_local_space_free(ls);
2109 return isl_map_from_basic_map(next);
2112 /* Check if the given access is coalesced.
2113 * That is, check whether incrementing the dimension that will get
2114 * wrapped over the last thread index results in incrementing
2115 * the last array index.
2117 * This function is only called for access relations without reuse.
2119 static int access_is_coalesced(struct gpu_gen *gen,
2120 __isl_keep isl_union_map *access)
2122 isl_space *dim;
2123 isl_map *access_map;
2124 isl_map *next_thread_x;
2125 isl_map *next_element;
2126 isl_map *map;
2127 int coalesced;
2129 access = isl_union_map_copy(access);
2130 access = isl_union_map_apply_domain(access,
2131 isl_union_map_copy(gen->tiled_sched));
2132 access_map = isl_map_from_union_map(access);
2134 dim = isl_map_get_space(access_map);
2135 dim = isl_space_domain(dim);
2136 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2138 dim = isl_map_get_space(access_map);
2139 dim = isl_space_range(dim);
2140 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2142 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2143 map = isl_map_apply_range(map, access_map);
2145 coalesced = isl_map_is_subset(map, next_element);
2147 isl_map_free(next_element);
2148 isl_map_free(map);
2150 return coalesced;
2153 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2154 * dimensions of the computed schedule, check if it is bijective for
2155 * fixed values of the first gen->shared_len dimensions.
2156 * We perform this check by equating these dimensions to parameters.
2158 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2160 int res;
2161 isl_set *par;
2162 isl_space *space;
2164 access = isl_map_copy(access);
2165 space = isl_space_params(isl_map_get_space(access));
2166 par = parametrization(space, gen->shared_len + gen->n_block,
2167 0, gen->shared_len, "s");
2168 access = isl_map_intersect_domain(access, par);
2169 res = isl_map_is_bijective(access);
2170 isl_map_free(access);
2172 return res;
2175 /* Look for the last shared tile loop that affects the offset of "tile"
2176 * and return the result.
2177 * If there is no such loop, then return the index of the loop
2178 * before the first shared tile loop, in particular gen->tile_first - 1.
2180 static int compute_tile_last_shared(struct gpu_gen *gen,
2181 struct gpu_array_tile *tile)
2183 int i, j;
2185 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2186 for (i = 0; i < tile->n; ++i) {
2187 isl_aff *lb;
2188 isl_aff *shift;
2190 lb = tile->bound[i].lb;
2191 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2192 break;
2194 shift = tile->bound[i].shift;
2195 if (!shift)
2196 continue;
2197 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2198 break;
2200 if (i < tile->n)
2201 break;
2204 return j;
2207 /* Look for the last shared tile loop that affects the offset of the
2208 * shared or private tile and store the result in group->last_shared.
2209 * If there is no such loop, then group->last_shared is set to a value
2210 * before the first shared tile loop, in particular gen->tile_first - 1.
2211 * If there is no tile defined on the array reference group,
2212 * then set group->last_shared to gen->shared_len - 1.
2214 static void set_last_shared(struct gpu_gen *gen,
2215 struct gpu_array_ref_group *group)
2217 struct gpu_array_tile *tile;
2219 group->last_shared = gen->shared_len - 1;
2221 tile = group->private_tile;
2222 if (!tile)
2223 tile = group->shared_tile;
2224 if (!tile)
2225 return;
2227 group->last_shared = compute_tile_last_shared(gen, tile);
2230 /* Compute a privatized copy of all access relations from reference groups that
2231 * are mapped to private memory and store the result in gen->privatization.
2233 static void compute_private_access(struct gpu_gen *gen)
2235 int i, j;
2236 isl_union_map *private;
2238 if (!gen->options->use_private_memory)
2239 return;
2241 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2243 for (i = 0; i < gen->prog->n_array; ++i) {
2244 struct gpu_array_info *array = &gen->prog->array[i];
2246 if (gpu_array_is_read_only_scalar(array))
2247 continue;
2249 for (j = 0; j < array->n_group; ++j) {
2250 if (!array->groups[j]->private_tile)
2251 continue;
2253 private = isl_union_map_union(private,
2254 group_access_relation(array->groups[j], 1, 1));
2258 if (isl_union_map_is_empty(private))
2259 isl_union_map_free(private);
2260 else {
2261 isl_union_map *priv;
2263 private = isl_union_map_apply_domain(private,
2264 isl_union_map_copy(gen->shared_sched));
2265 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2266 private = isl_union_map_apply_domain(private, priv);
2267 gen->private_access = private;
2271 /* Compute the size of the tile specified by "tile"
2272 * in number of elements and put the result in *size.
2274 static void tile_size(struct gpu_array_tile *tile, isl_int *size)
2276 int i;
2278 isl_int_set_si(*size, 1);
2280 for (i = 0; i < tile->n; ++i)
2281 isl_int_mul(*size, *size, tile->bound[i].size);
2284 /* If max_shared_memory is not set to infinity (-1), then make
2285 * sure that the total amount of shared memory required by the
2286 * array reference groups mapped to shared memory is no larger
2287 * than this maximum.
2289 * We apply a greedy approach and discard (keep in global memory)
2290 * those groups that would result in a total memory size that
2291 * is larger than the maximum.
2293 static void check_shared_memory_bound(struct gpu_gen *gen)
2295 int i, j;
2296 isl_int left, size;
2298 if (gen->options->max_shared_memory < 0)
2299 return;
2301 isl_int_init(left);
2302 isl_int_init(size);
2303 isl_int_set_si(left, gen->options->max_shared_memory);
2305 for (i = 0; i < gen->prog->n_array; ++i) {
2306 struct gpu_array_info *array = &gen->prog->array[i];
2308 for (j = 0; j < array->n_group; ++j) {
2309 struct gpu_array_ref_group *group;
2311 group = array->groups[j];
2312 if (!group->shared_tile)
2313 continue;
2315 tile_size(group->shared_tile, &size);
2316 isl_int_mul_ui(size, size, array->size);
2318 if (isl_int_le(size, left)) {
2319 isl_int_sub(left, left, size);
2320 continue;
2323 group->shared_tile = free_tile(group->shared_tile);
2327 isl_int_clear(size);
2328 isl_int_clear(left);
2331 /* Fill up the groups array with singleton groups, i.e., one group
2332 * per reference, initializing the array, access, write, n_ref and refs fields.
2333 * In particular the access field is initialized to the scheduled
2334 * access relation of the array reference.
2336 * Return the number of elements initialized, i.e., the number of
2337 * active references in the current kernel.
2339 static int populate_array_references(struct gpu_array_info *array,
2340 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2342 int i;
2343 int n;
2344 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2346 n = 0;
2347 for (i = 0; i < array->n_ref; ++i) {
2348 isl_union_map *umap;
2349 isl_map *map;
2350 struct gpu_array_ref_group *group;
2351 struct gpu_stmt_access *access = array->refs[i];
2353 map = isl_map_copy(access->access);
2354 umap = isl_union_map_from_map(map);
2355 umap = isl_union_map_apply_domain(umap,
2356 isl_union_map_copy(sched));
2358 if (isl_union_map_is_empty(umap)) {
2359 isl_union_map_free(umap);
2360 continue;
2363 map = isl_map_from_union_map(umap);
2364 map = isl_map_detect_equalities(map);
2366 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2367 assert(group);
2368 group->array = array;
2369 group->access = map;
2370 group->write = access->write;
2371 group->refs = &array->refs[i];
2372 group->n_ref = 1;
2374 groups[n++] = group;
2377 return n;
2380 /* If group->n_ref == 1, then group->refs was set by
2381 * populate_array_references to point directly into
2382 * group->array->refs and should not be freed.
2383 * If group->n_ref > 1, then group->refs was set by join_groups
2384 * to point to a newly allocated array.
2386 static void free_array_ref_group(struct gpu_array_ref_group *group)
2388 if (!group)
2389 return;
2390 free_tile(group->shared_tile);
2391 free_tile(group->private_tile);
2392 isl_map_free(group->access);
2393 if (group->n_ref > 1)
2394 free(group->refs);
2395 free(group);
2398 /* Given a map where the input dimensions represent the tile loops,
2399 * eliminate the innermost of those that have a fixed value
2400 * until we reach one that does not (obviously) have a fixed value.
2402 static __isl_give isl_map *eliminate_fixed_inner_loops(
2403 __isl_take isl_map *access)
2405 int i, n;
2407 n = isl_map_dim(access, isl_dim_in);
2409 for (i = n - 1; i >= 0; --i) {
2410 if (!isl_map_plain_is_fixed(access, isl_dim_in, i, NULL))
2411 break;
2412 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2414 return access;
2417 /* Check if the access relations of group1 and group2 overlap within
2418 * the innermost loop. In particular, ignore any inner dimension
2419 * with a fixed value.
2420 * The copying to and from shared memory will be performed within
2421 * the innermost actual loop so we are only allowed to consider
2422 * the dimensions up to that innermost loop while checking whether
2423 * two access relations overlap.
2425 static int accesses_overlap(struct gpu_array_ref_group *group1,
2426 struct gpu_array_ref_group *group2)
2428 int empty;
2429 isl_map *access1, *access2;
2431 access1 = isl_map_copy(group1->access);
2432 access1 = eliminate_fixed_inner_loops(access1);
2433 access2 = isl_map_copy(group2->access);
2434 access2 = eliminate_fixed_inner_loops(access2);
2435 access1 = isl_map_intersect(access1, access2);
2436 empty = isl_map_is_empty(access1);
2437 isl_map_free(access1);
2439 return !empty;
2442 /* Combine the given two groups into a single group, containing
2443 * the references of both groups.
2445 static struct gpu_array_ref_group *join_groups(
2446 struct gpu_array_ref_group *group1,
2447 struct gpu_array_ref_group *group2)
2449 int i;
2450 isl_ctx *ctx;
2451 struct gpu_array_ref_group *group;
2453 ctx = isl_map_get_ctx(group1->access);
2454 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2455 assert(group);
2456 group->array = group1->array;
2457 group->access = isl_map_union(isl_map_copy(group1->access),
2458 isl_map_copy(group2->access));
2459 group->write = group1->write || group2->write;
2460 group->n_ref = group1->n_ref + group2->n_ref;
2461 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2462 group->n_ref);
2463 assert(group->refs);
2464 for (i = 0; i < group1->n_ref; ++i)
2465 group->refs[i] = group1->refs[i];
2466 for (i = 0; i < group2->n_ref; ++i)
2467 group->refs[group1->n_ref + i] = group2->refs[i];
2469 return group;
2472 /* Combine the given two groups into a single group and free
2473 * the original two groups.
2475 static struct gpu_array_ref_group *join_groups_and_free(
2476 struct gpu_array_ref_group *group1,
2477 struct gpu_array_ref_group *group2)
2479 struct gpu_array_ref_group *group;
2481 group = join_groups(group1, group2);
2482 free_array_ref_group(group1);
2483 free_array_ref_group(group2);
2484 return group;
2487 /* Compute the private and/or shared memory tiles for the array
2488 * reference group "group" of array "array".
2490 * If the array is a read-only scalar or if the user requested
2491 * not to use shared or private memory, then we do not need to do anything.
2493 * We only try to compute a shared memory tile if there is any reuse
2494 * or if the access is not coalesced.
2496 * For computing a private memory tile, we also require that there is
2497 * some reuse. Moreover, we require that the access is private
2498 * to the thread. That is, we check that any given array element
2499 * is only accessed by a single thread.
2500 * We compute an access relation that maps the shared tile loop iterators
2501 * and the shared point loop iterators that will be wrapped over the
2502 * threads to the array elements.
2503 * We actually check that those iterators that will be wrapped
2504 * partition the array space. This check is stricter than necessary
2505 * since several iterations may be mapped onto the same thread
2506 * and then they could be allowed to access the same memory elements,
2507 * but our check does not allow this situation.
2509 * We also check that the index expression only depends on parallel
2510 * loops. That way, we can move those loops innermost and unroll them.
2511 * Again, we use a test that is stricter than necessary.
2512 * We actually check whether the index expression only depends
2513 * on the iterators that are wrapped over the threads.
2514 * These are necessarily parallel, but there may be more parallel loops.
2516 * Combining the injectivity of the first test with the single-valuedness
2517 * of the second test, we simply test for bijectivity.
2519 * If it turns out we can use registers, we compute the private memory
2520 * tile size using can_tile, after introducing a dependence
2521 * on the thread indices.
2523 static void compute_group_bounds_core(struct gpu_gen *gen,
2524 struct gpu_array_ref_group *group)
2526 isl_ctx *ctx = isl_space_get_ctx(group->array->dim);
2527 isl_union_map *access;
2528 int n_index = group->array->n_index;
2529 int no_reuse;
2530 isl_map *acc;
2531 int use_shared = gen->options->use_shared_memory;
2532 int use_private = gen->options->use_private_memory;
2534 if (!use_shared && !use_private)
2535 return;
2536 if (gpu_array_is_read_only_scalar(group->array))
2537 return;
2539 access = group_access_relation(group, 1, 1);
2540 no_reuse = isl_union_map_is_injective(access);
2542 if (use_shared && (!no_reuse || !access_is_coalesced(gen, access))) {
2543 group->shared_tile = create_tile(ctx, group->array->n_index);
2544 if (!can_tile(group->access, group->shared_tile))
2545 group->shared_tile = free_tile(group->shared_tile);
2548 if (!use_private || no_reuse) {
2549 isl_union_map_free(access);
2550 return;
2553 access = isl_union_map_apply_domain(access,
2554 isl_union_map_copy(gen->shared_sched));
2556 acc = isl_map_from_union_map(access);
2558 if (!access_is_bijective(gen, acc)) {
2559 isl_map_free(acc);
2560 return;
2563 group->private_tile = create_tile(gen->ctx, n_index);
2564 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2565 if (!can_tile(acc, group->private_tile))
2566 group->private_tile = free_tile(group->private_tile);
2568 isl_map_free(acc);
2571 /* Compute the private and/or shared memory tiles for the array
2572 * reference group "group" of array "array" and set last_shared.
2574 static void compute_group_bounds(struct gpu_gen *gen,
2575 struct gpu_array_ref_group *group)
2577 compute_group_bounds_core(gen, group);
2578 set_last_shared(gen, group);
2581 /* If two groups have overlapping access relations (as determined by
2582 * the "overlap" function) and if one of them involves a write,
2583 * then merge the two groups into one.
2584 * If "compute_bounds" is set, then call compute_group_bounds
2585 * on the merged groups.
2587 * Return the updated number of groups.
2589 static int group_writes(struct gpu_gen *gen,
2590 int n, struct gpu_array_ref_group **groups,
2591 int (*overlap)(struct gpu_array_ref_group *group1,
2592 struct gpu_array_ref_group *group2), int compute_bounds)
2594 int i, j;
2596 for (i = 0; i < n; ++i) {
2597 for (j = n - 1; j > i; --j) {
2598 if (!groups[i]->write && !groups[j]->write)
2599 continue;
2601 if (!overlap(groups[i], groups[j]))
2602 continue;
2604 groups[i] = join_groups_and_free(groups[i], groups[j]);
2605 if (compute_bounds)
2606 compute_group_bounds(gen, groups[i]);
2607 if (j != n - 1)
2608 groups[j] = groups[n - 1];
2609 n--;
2613 return n;
2616 /* If two groups have overlapping access relations (within the innermost
2617 * loop) and if one of them involves a write, then merge the two groups
2618 * into one.
2620 * Return the updated number of groups.
2622 static int group_overlapping_writes(struct gpu_gen *gen,
2623 int n, struct gpu_array_ref_group **groups)
2625 return group_writes(gen, n, groups, &accesses_overlap, 0);
2628 /* Check if the access relations of group1 and group2 overlap within
2629 * the outermost min(group1->last_shared, group2->last_shared) loops.
2631 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2632 struct gpu_array_ref_group *group2)
2634 int last_shared;
2635 int dim;
2636 int empty;
2637 isl_map *map_i, *map_j, *map;
2639 last_shared = group1->last_shared;
2640 if (group2->last_shared < last_shared)
2641 last_shared = group2->last_shared;
2642 map_i = isl_map_copy(group1->access);
2643 dim = isl_map_dim(map_i, isl_dim_in);
2644 map_i = isl_map_eliminate(map_i, isl_dim_in,
2645 last_shared + 1, dim - (last_shared + 1));
2646 map_j = isl_map_copy(group2->access);
2647 map_j = isl_map_eliminate(map_j, isl_dim_in,
2648 last_shared + 1, dim - (last_shared + 1));
2649 map = isl_map_intersect(map_i, map_j);
2650 empty = isl_map_is_empty(map);
2651 isl_map_free(map);
2653 return !empty;
2656 /* If two groups have overlapping access relations (within the outer
2657 * last_shared loops) and if one of them involves a write,
2658 * then merge the two groups into one.
2660 * Return the updated number of groups.
2662 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2663 struct gpu_array_ref_group **groups)
2665 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2668 /* Is the size of the tile specified by "tile" smaller than the sum of
2669 * the sizes of the tiles specified by "tile1" and "tile2"?
2671 static int smaller_tile(struct gpu_array_tile *tile,
2672 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2674 int smaller;
2675 isl_int size, size1, size2;
2677 isl_int_init(size);
2678 isl_int_init(size1);
2679 isl_int_init(size2);
2681 tile_size(tile, &size);
2682 tile_size(tile1, &size1);
2683 tile_size(tile2, &size2);
2685 isl_int_sub(size, size, size1);
2686 isl_int_sub(size, size, size2);
2687 smaller = isl_int_is_neg(size);
2689 isl_int_clear(size2);
2690 isl_int_clear(size1);
2691 isl_int_clear(size);
2693 return smaller;
2696 /* Given an initial grouping of array references and shared memory tiles
2697 * for each group that allows for a shared memory tile, merge two groups
2698 * if both have a shared memory tile, the merged group also has
2699 * a shared memory tile and the size of the tile for the merge group
2700 * is smaller than the sum of the tile sizes of the individual groups.
2702 * If merging two groups decreases the "last_shared" dimension of
2703 * one or both of the two groups, then we need to check for overlapping
2704 * writes again.
2706 * Return the number of groups after merging.
2708 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2709 struct gpu_array_info *array, int n,
2710 struct gpu_array_ref_group **groups)
2712 int i, j;
2713 int recompute_overlap = 0;
2714 isl_ctx *ctx = isl_space_get_ctx(array->dim);
2716 for (i = 0; i < n; ++i) {
2717 if (!groups[i]->shared_tile)
2718 continue;
2719 for (j = n - 1; j > i; --j) {
2720 isl_map *map;
2721 int empty;
2722 struct gpu_array_ref_group *group;
2724 if (!groups[j]->shared_tile)
2725 continue;
2727 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2728 isl_map_copy(groups[j]->access));
2729 empty = isl_map_is_empty(map);
2730 isl_map_free(map);
2732 if (empty)
2733 continue;
2735 group = join_groups(groups[i], groups[j]);
2736 compute_group_bounds(gen, group);
2737 if (!group->shared_tile ||
2738 !smaller_tile(group->shared_tile,
2739 groups[i]->shared_tile,
2740 groups[j]->shared_tile)) {
2741 free_array_ref_group(group);
2742 continue;
2745 if (group->last_shared < groups[i]->last_shared ||
2746 group->last_shared < groups[j]->last_shared)
2747 recompute_overlap = 1;
2748 free_array_ref_group(groups[i]);
2749 free_array_ref_group(groups[j]);
2750 groups[i] = group;
2751 if (j != n - 1)
2752 groups[j] = groups[n - 1];
2753 n--;
2757 if (recompute_overlap)
2758 n = group_last_shared_overlapping_writes(gen, n, groups);
2759 return n;
2762 /* Set array->n_group and array->groups to n and groups.
2764 * Additionally, set the "nr" field of each group
2765 * and the "group" field of each reference in each group.
2767 static void set_array_groups(struct gpu_array_info *array,
2768 int n, struct gpu_array_ref_group **groups)
2770 int i, j;
2772 array->n_group = n;
2773 array->groups = groups;
2775 for (i = 0; i < n; ++i) {
2776 groups[i]->nr = i;
2778 for (j = 0; j < groups[i]->n_ref; ++j)
2779 groups[i]->refs[j]->group = i;
2783 /* Group array references that should be considered together when
2784 * deciding whether to access them from private, shared or global memory.
2786 * In particular, if two array references overlap and if one of them
2787 * is a write, then the two references are grouped together.
2788 * We first perform an initial grouping based only on the access relation.
2789 * After computing shared and private memory tiles, we check for
2790 * overlapping writes again, but this time taking into account
2791 * the "last_shared" property.
2793 * Furthermore, if two groups admit a shared memory tile and if the
2794 * combination of the two also admits a shared memory tile, we merge
2795 * the two groups.
2797 static void group_array_references(struct gpu_gen *gen,
2798 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
2800 int i;
2801 int n;
2802 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2803 struct gpu_array_ref_group **groups;
2805 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
2806 array->n_ref);
2807 assert(groups);
2809 n = populate_array_references(array, sched, groups);
2811 n = group_overlapping_writes(gen, n, groups);
2813 for (i = 0; i < n; ++i)
2814 compute_group_bounds(gen, groups[i]);
2816 n = group_last_shared_overlapping_writes(gen, n, groups);
2818 n = group_common_shared_memory_tile(gen, array, n, groups);
2820 set_array_groups(array, n, groups);
2823 /* Take tiled_sched, project it onto the shared tile loops and
2824 * the loops that will be wrapped over the threads and
2825 * store the result in gen->shared_sched.
2826 * Also compute a projection that projects out the loops that will be
2827 * wrapped over the threads and store this projection in gen->shared_proj.
2829 static void compute_shared_sched(struct gpu_gen *gen)
2831 isl_space *dim;
2832 isl_map *proj;
2833 isl_set *par;
2834 isl_union_map *sched;
2836 sched = isl_union_map_copy(gen->tiled_sched);
2838 dim = isl_union_map_get_space(sched);
2839 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
2840 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
2842 dim = isl_union_map_get_space(sched);
2843 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
2845 gen->shared_sched = sched;
2846 gen->shared_proj = isl_union_map_from_map(proj);
2849 /* Group references of all arrays in the program.
2851 static void group_references(struct gpu_gen *gen)
2853 int i;
2854 isl_union_map *sched;
2856 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2857 isl_union_map_copy(gen->shared_proj));
2859 for (i = 0; i < gen->prog->n_array; ++i)
2860 group_array_references(gen, &gen->prog->array[i], sched);
2862 isl_union_map_free(sched);
2865 /* Free all array information that is local to the current kernel.
2867 static void free_local_array_info(struct gpu_gen *gen)
2869 int i, j;
2871 for (i = 0; i < gen->prog->n_array; ++i) {
2872 struct gpu_array_info *array = &gen->prog->array[i];
2874 for (j = 0; j < array->n_group; ++j)
2875 free_array_ref_group(array->groups[j]);
2876 free(array->groups);
2880 /* Compute the effective grid size as a list of the sizes in each dimension.
2882 * The grid size specified by the user or set by default
2883 * in read_grid_sizes() and applied in tile_schedule(),
2884 * may be too large for the given code in the sense that
2885 * it may contain blocks that don't need to execute anything.
2886 * We therefore don't return this grid size, but instead the
2887 * smallest grid size that ensures that all blocks that actually
2888 * execute code are included in the grid.
2890 * We first extract a description of the grid, i.e., the possible values
2891 * of the block ids, from gen->tiled_sched.
2892 * The block ids are parameters in gen->tiled_sched.
2893 * We simply need to change them into set dimensions.
2895 * Then, for each block dimension, we compute the maximal value of the block id
2896 * and add one.
2898 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
2899 struct ppcg_kernel *kernel)
2901 int i;
2902 isl_set *grid;
2903 isl_multi_pw_aff *mpa;
2905 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
2906 grid = isl_set_from_params(grid);
2907 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
2908 for (i = 0; i < gen->n_grid; ++i) {
2909 int pos;
2910 char name[20];
2912 snprintf(name, sizeof(name), "b%d", i);
2913 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
2914 assert(pos >= 0);
2915 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
2916 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
2919 mpa = isl_multi_pw_aff_zero(isl_set_get_space(grid));
2920 for (i = 0; i < gen->n_grid; ++i) {
2921 isl_space *space;
2922 isl_aff *one;
2923 isl_pw_aff *bound;
2925 bound = isl_set_dim_max(isl_set_copy(grid), i);
2926 bound = isl_pw_aff_coalesce(bound);
2927 bound = isl_pw_aff_gist(bound, isl_set_copy(kernel->context));
2929 space = isl_pw_aff_get_domain_space(bound);
2930 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2931 one = isl_aff_add_constant_si(one, 1);
2932 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
2933 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
2935 isl_set_free(grid);
2937 return mpa;
2940 void ppcg_kernel_free(void *user)
2942 struct ppcg_kernel *kernel = user;
2943 int i;
2945 if (!kernel)
2946 return;
2948 isl_multi_pw_aff_free(kernel->grid_size);
2949 isl_set_free(kernel->context);
2950 isl_union_set_free(kernel->arrays);
2951 isl_space_free(kernel->space);
2952 isl_ast_node_free(kernel->tree);
2954 for (i = 0; i < kernel->n_array; ++i)
2955 isl_pw_aff_list_free(kernel->array[i].bound);
2956 free(kernel->array);
2958 for (i = 0; i < kernel->n_var; ++i) {
2959 free(kernel->var[i].name);
2960 isl_vec_free(kernel->var[i].size);
2962 free(kernel->var);
2964 free(kernel);
2967 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
2968 struct ppcg_kernel_var *var)
2970 int j;
2971 struct gpu_array_tile *tile;
2972 isl_printer *p;
2973 char *name;
2975 var->array = group->array;
2977 tile = group->private_tile;
2978 var->type = ppcg_access_private;
2979 if (!tile) {
2980 tile = group->shared_tile;
2981 var->type = ppcg_access_shared;
2984 p = isl_printer_to_str(ctx);
2985 p = print_array_name(p, group);
2986 var->name = isl_printer_get_str(p);
2987 isl_printer_free(p);
2989 var->size = isl_vec_alloc(ctx, group->array->n_index);
2991 for (j = 0; j < group->array->n_index; ++j)
2992 var->size = isl_vec_set_element(var->size, j,
2993 tile->bound[j].size);
2996 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
2998 int i, j, n;
3000 n = 0;
3001 for (i = 0; i < gen->prog->n_array; ++i) {
3002 struct gpu_array_info *array = &gen->prog->array[i];
3004 for (j = 0; j < array->n_group; ++j) {
3005 struct gpu_array_ref_group *group = array->groups[j];
3006 if (group->private_tile || group->shared_tile)
3007 ++n;
3011 kernel->n_var = n;
3012 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3013 assert(kernel->var);
3015 n = 0;
3016 for (i = 0; i < gen->prog->n_array; ++i) {
3017 struct gpu_array_info *array = &gen->prog->array[i];
3019 for (j = 0; j < array->n_group; ++j) {
3020 struct gpu_array_ref_group *group = array->groups[j];
3021 if (!group->private_tile && !group->shared_tile)
3022 continue;
3023 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3024 ++n;
3029 /* The sizes of the arrays on the host that have been computed by
3030 * extract_array_info may depend on the parameters. Use the extra
3031 * constraints on the parameters that are valid at "host_domain"
3032 * to simplify these expressions and store the results in kernel->array.
3034 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3035 __isl_keep isl_set *host_domain)
3037 int i, j;
3038 isl_set *context;
3040 kernel->array = isl_calloc_array(gen->ctx,
3041 struct gpu_local_array_info, gen->prog->n_array);
3042 assert(kernel->array);
3043 kernel->n_array = gen->prog->n_array;
3045 context = isl_set_copy(host_domain);
3046 context = isl_set_params(context);
3048 for (i = 0; i < gen->prog->n_array; ++i) {
3049 struct gpu_array_info *array = &gen->prog->array[i];
3050 isl_pw_aff_list *local;
3052 if (array->n_group == 0)
3053 continue;
3055 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3057 for (j = 0; j < array->n_index; ++j) {
3058 isl_pw_aff *pwaff;
3060 pwaff = isl_pw_aff_copy(array->bound[j]);
3061 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3062 local = isl_pw_aff_list_add(local, pwaff);
3065 kernel->array[i].bound = local;
3067 isl_set_free(context);
3070 /* Find the element in gen->stmt that has the given "id".
3071 * Return NULL if no such gpu_stmt can be found.
3073 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3075 int i;
3077 for (i = 0; i < prog->n_stmts; ++i) {
3078 if (id == prog->stmts[i].id)
3079 break;
3082 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3085 /* Set gen->tile_len and gen->n_parallel to those of the statement
3086 * affected by the first map (part of the schedule)
3087 * on which this function is called.
3088 * Because of the way the schedule is constructed, the other statements
3089 * in the list, if any, should have the same values for these properties.
3091 static int extract_tile_len(__isl_take isl_map *map, void *user)
3093 struct gpu_gen *gen = (struct gpu_gen *) user;
3094 isl_id *id;
3095 struct gpu_stmt *stmt;
3097 id = isl_map_get_tuple_id(map, isl_dim_in);
3098 stmt = find_stmt(gen->prog, id);
3099 isl_id_free(id);
3101 isl_map_free(map);
3103 if (!stmt)
3104 isl_die(gen->ctx, isl_error_unknown,
3105 "statement not found", return -1);
3107 gen->tile_len = stmt->tile_len;
3108 gen->n_parallel = stmt->n_parallel;
3110 return -1;
3113 void ppcg_kernel_stmt_free(void *user)
3115 int i;
3116 struct ppcg_kernel_stmt *stmt = user;
3118 if (!stmt)
3119 return;
3121 switch (stmt->type) {
3122 case ppcg_kernel_copy:
3123 isl_ast_expr_free(stmt->u.c.index);
3124 isl_ast_expr_free(stmt->u.c.local_index);
3125 break;
3126 case ppcg_kernel_domain:
3127 for (i = 0; i < stmt->u.d.n_access; ++i) {
3128 isl_ast_expr_list_free(stmt->u.d.access[i].index);
3129 free(stmt->u.d.access[i].local_name);
3131 free(stmt->u.d.access);
3132 break;
3133 case ppcg_kernel_sync:
3134 break;
3137 free(stmt);
3140 /* Set the options of "context" to
3142 * { space -> [x] : x >= first }
3144 static __isl_give isl_ast_build *set_unroll(
3145 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3146 int first)
3148 isl_ctx *ctx;
3149 isl_map *unroll;
3150 isl_union_map *opt;
3152 ctx = isl_ast_build_get_ctx(build);
3154 space = isl_space_from_domain(space);
3155 space = isl_space_add_dims(space, isl_dim_out, 1);
3156 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3157 unroll = isl_map_universe(space);
3158 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3159 opt = isl_union_map_from_map(unroll);
3161 build = isl_ast_build_set_options(build, opt);
3163 return build;
3166 /* Return a list of isl_ids of the form "prefix%d".
3168 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3169 int n, const char *prefix)
3171 int i;
3172 char name[10];
3173 isl_id_list *names;
3175 names = isl_id_list_alloc(ctx, n);
3176 for (i = 0; i < n; ++i) {
3177 isl_id *id;
3179 snprintf(name, sizeof(name), "%s%d", prefix, i);
3180 id = isl_id_alloc(ctx, name, NULL);
3181 names = isl_id_list_add(names, id);
3184 return names;
3187 /* Extend the schedule "schedule" with the part of "extension"
3188 * starting at "first" up to "len".
3190 static __isl_give isl_union_map *extend_schedule(
3191 __isl_take isl_union_map *schedule,
3192 __isl_take isl_union_map *extension, int first, int len)
3194 isl_space *space;
3195 isl_map *proj;
3196 isl_union_map *umap;
3197 isl_set *set;
3199 space = isl_union_map_get_space(schedule);
3200 space = isl_space_set_from_params(space);
3201 space = isl_space_add_dims(space, isl_dim_set, len);
3202 proj = isl_set_identity(isl_set_universe(space));
3203 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3204 extension = isl_union_map_apply_range(extension,
3205 isl_union_map_from_map(proj));
3207 schedule = isl_union_map_range_product(schedule, extension);
3209 return schedule;
3212 /* This function is called for each access to an array in each instance
3213 * in the kernel of some statement in the original code.
3214 * Replace that access by an access to global, shared or private memory
3215 * and store the results in *kernel_access.
3217 * Since the array in shared or private memory is just
3218 * a shifted copy of part of the original array, we simply need
3219 * to subtract the lower bound, which was computed in can_tile.
3220 * If any of the indices is strided, then we first add
3221 * shared_tile->bound[i].shift and divide by shared_tile->bound[i].stride.
3223 * If the given array is accessed directly from global memory,
3224 * we don't need to perform any shifting and simply simplify
3225 * the expression in the context of the domain instead.
3227 * If the array space (range of access) has no name, then we are
3228 * accessing an iterator in the original program.
3230 * The input stmt_access->access relation maps the iteration domain
3231 * of the current statement to an array element.
3232 * The first step is to reformulate
3233 * this access relation in terms of the loop iterators of the generated
3234 * code through precomposition with gen->stmt_it.
3236 * The expressions in "tile" are formulated in terms of the first
3237 * gen->shared_len dimensions of the computed schedule using the mapping
3238 * sched2shared which maps the loop iterators to these dimensions.
3240 static void compute_index_expression(struct gpu_gen *gen,
3241 struct ppcg_kernel_access *kernel_access,
3242 struct gpu_stmt_access *stmt_access, __isl_keep isl_map *stmt_it,
3243 __isl_keep isl_map *sched2shared, __isl_keep isl_ast_build *build)
3245 isl_map *access;
3246 isl_pw_multi_aff *pma;
3247 int i;
3248 unsigned n_index;
3249 struct gpu_array_tile *tile = NULL;
3251 if (isl_map_has_tuple_name(stmt_access->access, isl_dim_out)) {
3252 int i;
3253 const char *name;
3254 struct gpu_array_ref_group *group;
3255 isl_printer *p;
3257 name = isl_map_get_tuple_name(stmt_access->access, isl_dim_out);
3259 for (i = 0; i < gen->prog->n_array; ++i) {
3260 if (strcmp(name, gen->prog->array[i].name))
3261 continue;
3262 kernel_access->array = &gen->prog->array[i];
3263 kernel_access->local_array = &gen->kernel->array[i];
3265 assert(kernel_access->array);
3266 group = kernel_access->array->groups[stmt_access->group];
3267 p = isl_printer_to_str(gen->ctx);
3268 p = print_array_name(p, group);
3269 kernel_access->local_name = isl_printer_get_str(p);
3270 isl_printer_free(p);
3271 tile = group->private_tile;
3272 kernel_access->type = ppcg_access_private;
3273 if (!tile) {
3274 tile = group->shared_tile;
3275 kernel_access->type = ppcg_access_shared;
3278 if (!tile)
3279 kernel_access->type = ppcg_access_global;
3281 n_index = isl_map_dim(stmt_access->access, isl_dim_out);
3282 kernel_access->index = isl_ast_expr_list_alloc(gen->ctx, n_index);
3284 if (n_index == 0)
3285 return;
3287 access = isl_map_copy(stmt_access->access);
3288 access = isl_map_apply_range(isl_map_copy(stmt_it), access);
3289 pma = isl_pw_multi_aff_from_map(access);
3290 pma = isl_pw_multi_aff_coalesce(pma);
3292 for (i = 0; i < n_index; ++i) {
3293 isl_set *domain;
3294 isl_pw_aff *index;
3295 isl_ast_expr *expr;
3297 index = isl_pw_multi_aff_get_pw_aff(pma, i);
3299 if (!kernel_access->array) {
3300 } else if (!tile) {
3301 domain = isl_map_domain(isl_map_copy(stmt_it));
3302 index = isl_pw_aff_coalesce(index);
3303 index = isl_pw_aff_gist(index, domain);
3304 } else {
3305 domain = isl_map_domain(isl_map_copy(stmt_it));
3306 index = shift_index(index, kernel_access->array,
3307 &tile->bound[i], domain,
3308 isl_map_copy(sched2shared));
3311 expr = isl_ast_build_expr_from_pw_aff(build, index);
3313 kernel_access->index = isl_ast_expr_list_add(
3314 kernel_access->index, expr);
3317 isl_pw_multi_aff_free(pma);
3320 /* This function is called for each instance of a user statement
3321 * in the kernel.
3323 * We attach a struct ppcg_kernel_stmt to the "node", containing
3324 * local information about the accesses.
3325 * This information is computed from stmt_it, which expresses the domain
3326 * elements in terms of the generated loops, and sched2shared,
3327 * which expresses the first shared_len dimensions of the schedule
3328 * computed by PPCG in terms of the generated loops.
3330 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3331 __isl_keep isl_ast_build *build, void *user)
3333 struct gpu_gen *gen = (struct gpu_gen *) user;
3334 struct ppcg_kernel_stmt *stmt;
3335 isl_id *id;
3336 isl_map *stmt_it, *sched2shared;
3337 isl_ast_expr *expr, *arg;
3338 isl_union_map *schedule;
3339 int i, n;
3340 struct gpu_stmt_access *access;
3342 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3343 if (!stmt)
3344 return isl_ast_node_free(node);
3346 expr = isl_ast_node_user_get_expr(node);
3347 arg = isl_ast_expr_get_op_arg(expr, 0);
3348 id = isl_ast_expr_get_id(arg);
3350 schedule = isl_ast_build_get_schedule(build);
3351 stmt_it = isl_map_reverse(isl_map_from_union_map(schedule));
3352 sched2shared = compute_sched_to_shared(gen, isl_map_copy(stmt_it));
3354 stmt->type = ppcg_kernel_domain;
3355 stmt->u.d.stmt = find_stmt(gen->prog, id);
3356 if (!stmt->u.d.stmt)
3357 goto error;
3359 n = 0;
3360 for (access = stmt->u.d.stmt->accesses; access; access = access->next)
3361 ++n;
3363 stmt->u.d.access = isl_calloc_array(gen->ctx,
3364 struct ppcg_kernel_access, n);
3365 if (!stmt->u.d.access)
3366 goto error;
3368 stmt->u.d.n_access = n;
3370 access = stmt->u.d.stmt->accesses;
3371 for (i = 0; i < n; ++i, access = access->next) {
3372 compute_index_expression(gen, &stmt->u.d.access[i], access,
3373 stmt_it, sched2shared, build);
3376 isl_id_free(id);
3377 isl_map_free(stmt_it);
3378 isl_map_free(sched2shared);
3379 isl_ast_expr_free(arg);
3380 isl_ast_expr_free(expr);
3382 id = isl_id_alloc(gen->ctx, NULL, stmt);
3383 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3384 return isl_ast_node_set_annotation(node, id);
3385 error:
3386 isl_id_free(id);
3387 isl_map_free(stmt_it);
3388 ppcg_kernel_stmt_free(stmt);
3389 isl_map_free(sched2shared);
3390 return isl_ast_node_free(node);
3393 /* This function is called when code has been generated for the shared
3394 * tile loops. The "schedule" refers only to the original statements.
3396 * We extend the schedule with that part of gen->local_sched that hasn't
3397 * been taken into account yet. This introduces parameters referring
3398 * to thread ids in the schedule, so we add them (with the appropriate
3399 * bounds to the context as well).
3400 * Finally, we set the appropriate unrolling options
3401 * if gen->first_unroll is set.
3403 static __isl_give isl_ast_node *create_domain_leaf(
3404 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
3405 void *user)
3407 struct gpu_gen *gen = (struct gpu_gen *) user;
3408 isl_space *space;
3409 isl_union_map *sched;
3410 isl_ast_node *tree;
3411 isl_set *set;
3412 isl_id_list *iterators;
3413 int n;
3415 schedule = extend_schedule(schedule,
3416 isl_union_map_copy(gen->local_sched),
3417 gen->shared_len, gen->thread_tiled_len);
3419 space = isl_ast_build_get_schedule_space(build);
3420 set = isl_set_universe(space);
3421 set = add_bounded_parameters(set, gen->n_block, gen->block_dim, "t");
3422 build = isl_ast_build_restrict(build, set);
3424 n = gen->thread_tiled_len - gen->shared_len;
3426 if (gen->first_unroll >= 0) {
3427 space = isl_space_set_alloc(gen->ctx, 0, n);
3428 build = set_unroll(build, space, gen->first_unroll);
3430 iterators = generate_names(gen->ctx, n, "c");
3431 build = isl_ast_build_set_iterators(build, iterators);
3432 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
3433 tree = isl_ast_build_ast_from_schedule(build, schedule);
3434 isl_ast_build_free(build);
3436 return tree;
3439 /* This function is called for each statement node in the AST of the code
3440 * for copying to or from shared/private memory.
3441 * Attach a pointer to a ppcg_kernel_stmt representing the copy
3442 * statement to the node.
3443 * The statement name is {read,write}_{shared,private}_<array>.
3445 * The schedule is of the form
3447 * [A -> T] -> L
3449 * where A refers to a piece of an array and T to the corresponding
3450 * shifted tile. We split this schedule into mappings L -> A and L -> T
3451 * and store the corresponding expressions in stmt->index and stmt->local_index,
3452 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
3454 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
3455 __isl_keep isl_ast_build *build, void *user)
3457 struct gpu_gen *gen = (struct gpu_gen *) user;
3458 struct ppcg_kernel_stmt *stmt;
3459 isl_id *id;
3460 isl_ast_expr *expr;
3461 isl_space *space;
3462 isl_map *access, *local_access, *map;
3463 isl_pw_multi_aff *pma;
3464 const char *name;
3465 int array_index;
3467 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3468 if (!stmt)
3469 return isl_ast_node_free(node);
3471 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
3472 name = isl_map_get_tuple_name(access, isl_dim_in);
3473 stmt->u.c.read = !strncmp(name, "read", 4);
3474 access = isl_map_reverse(access);
3475 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
3476 local_access = isl_map_copy(access);
3478 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
3479 id = isl_map_get_tuple_id(access, isl_dim_out);
3480 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3481 access = isl_map_apply_range(access, map);
3482 pma = isl_pw_multi_aff_from_map(access);
3483 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3484 stmt->u.c.index = expr;
3486 map = isl_map_range_map(isl_map_universe(space));
3487 id = isl_map_get_tuple_id(local_access, isl_dim_out);
3488 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3489 local_access = isl_map_apply_range(local_access, map);
3490 pma = isl_pw_multi_aff_from_map(local_access);
3491 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3492 stmt->u.c.local_index = expr;
3494 stmt->u.c.array = gen->copy_group->array;
3495 array_index = stmt->u.c.array - gen->prog->array;
3496 stmt->u.c.local_array = &gen->kernel->array[array_index];
3497 stmt->type = ppcg_kernel_copy;
3499 id = isl_id_alloc(gen->ctx, NULL, stmt);
3500 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3501 return isl_ast_node_set_annotation(node, id);
3504 /* Given a schedule of the form
3506 * [S -> A] -> L
3508 * (with S the first shared_len dimensions of the computed schedule,
3509 * A the array and L the schedule correponding to the generated loops),
3510 * indicating where the copying the array elements that need to be copied,
3511 * construct code for performing the copying.
3513 * "group" is the array reference group that is being copied
3514 * "type" is either "read" or "write"
3515 * private is set if copying needs to be performed to/from registers
3517 * We first construct a mapping to a shifted tile of the array,
3519 * [S -> A] -> T(S,A) (1)
3521 * If private is set, then we also use this mapping as a schedule
3522 * (which is already thread-specific and will be completely unrolled).
3523 * Otherwise, we wrap/tile the range over the threads.
3524 * The result is
3526 * [S -> A] -> T'(S,A)
3528 * Combined with the given schedule, we have
3530 * [S -> A] -> [L -> T'(S,A)] (2)
3532 * From the shifted tile mapping, we construct a mapping
3534 * [S -> A] -> [A -> T(S,A)]
3536 * and apply it to the schedule (2), obtaining
3538 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
3540 * Note that we can project out S because it is uniquely defined by L.
3542 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
3543 __isl_take isl_map *sched,
3544 const char *type, struct gpu_array_ref_group *group,
3545 __isl_take isl_ast_build *build, int private)
3547 const char *array_name;
3548 const char *mem = private ? "private" : "shared";
3549 char *name;
3550 isl_space *space;
3551 isl_ast_node *tree;
3552 isl_map *schedule, *shift, *map;
3553 isl_set *set;
3554 isl_id_list *iterators;
3555 int n;
3557 shift = isl_set_unwrap(isl_map_domain(isl_map_copy(sched)));
3558 array_name = isl_map_get_tuple_name(shift, isl_dim_out);
3559 shift = shift_access(shift, group);
3561 schedule = isl_map_copy(shift);
3562 if (!private)
3563 schedule = tile_access_schedule(gen, schedule);
3565 n = isl_map_dim(schedule, isl_dim_out);
3566 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
3567 set = add_bounded_parameters(set, gen->n_block, gen->block_dim, "t");
3569 schedule = isl_map_range_product(sched, schedule);
3571 assert(array_name);
3572 name = isl_alloc_array(gen->ctx, char,
3573 strlen(type) + sizeof("_private_") + strlen(array_name) + 20);
3574 if (group->array->n_group > 1)
3575 sprintf(name, "%s_%s_%s_%d", type, mem, array_name, group->nr);
3576 else
3577 sprintf(name, "%s_%s_%s", type, mem, array_name);
3578 shift = isl_map_set_tuple_name(shift,
3579 isl_dim_out, name + strlen(type) + 1);
3581 space = isl_space_domain(isl_map_get_space(shift));
3582 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
3583 map = isl_map_range_product(map, shift);
3585 schedule = isl_map_apply_domain(schedule, map);
3587 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, name);
3588 free(name);
3590 build = isl_ast_build_restrict(build, set);
3592 gen->copy_group = group;
3594 if (private) {
3595 space = isl_space_range(isl_map_get_space(schedule));
3596 space = isl_space_range(isl_space_unwrap(space));
3597 build = set_unroll(build, space, 0);
3599 iterators = generate_names(gen->ctx, n, "c");
3600 build = isl_ast_build_set_iterators(build, iterators);
3601 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
3602 tree = isl_ast_build_ast_from_schedule(build,
3603 isl_union_map_from_map(schedule));
3604 isl_ast_build_free(build);
3606 return tree;
3609 /* Return code for reading into or writing from shared memory
3610 * the given array reference group.
3612 * If we are performing a read from global memory to shared memory and
3613 * if the array involved is not a scalar, then we copy
3614 * the entire tile to shared memory. This may result in some extra
3615 * elements getting copied, but it should lead to simpler code
3616 * (which means that fewer registers may be needed) and less divergence.
3618 * Otherwise, we only copy the elements that will be read or have been written
3619 * in the kernel.
3622 * The input "sched" is of the form.
3624 * type[S -> A] -> L
3626 * with S the first shared_len dimensions of the computed schedule,
3627 * A the array and L the schedule correponding to the generated loops.
3629 * We first drop "type",
3631 * [S -> A] -> L
3633 * If the above conditions are satisfied, we project out A,
3634 * resulting in
3636 * S -> L
3638 * and then introduce the group tile [S -> T], resulting in
3640 * [S -> T] -> L
3642 static __isl_give isl_ast_node *copy_group_shared_accesses(
3643 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3644 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3646 const char *type;
3647 int read;
3648 isl_union_map *access;
3650 type = isl_map_get_tuple_name(sched, isl_dim_in);
3651 read = !strcmp(type, "read");
3653 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3655 if (read && group->array->n_index > 0) {
3656 isl_space *space;
3657 isl_map *map;
3659 space = isl_space_domain(isl_map_get_space(sched));
3660 space = isl_space_unwrap(space);
3661 map = isl_map_domain_map(isl_map_universe(space));
3662 sched = isl_map_apply_domain(sched, map);
3664 map = group_tile(group);
3665 map = isl_map_reverse(isl_map_domain_map(map));
3666 sched = isl_map_apply_domain(sched, map);
3669 return copy_access(gen, sched, type, group, build, 0);
3672 /* Return code for reading into or writing from private memory
3673 * the given array reference group.
3675 * Let S be the first shared_len dimensions of the computed schedule,
3676 * D the iteration domains, A the array and L the schedule correponding
3677 * to the generated loops.
3678 * "sched" is of the form
3680 * type[S -> A] -> L
3682 * where type is either "read" or "write".
3683 * We apply the privatization D -> S(t), with t the thread ids,
3684 * to the access relation D -> A to obtain the privatized access relation
3686 * S(t) -> A
3688 * We drop the type from "sched" and intersect with the privatized access
3689 * relation to obtain
3691 * [S(t) -> A] -> L
3693 static __isl_give isl_ast_node *copy_group_private_accesses(
3694 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3695 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3697 const char *type;
3698 int read;
3699 isl_union_map *priv;
3700 isl_union_map *access;
3701 isl_map *access_map;
3703 type = isl_map_get_tuple_name(sched, isl_dim_in);
3704 read = !strcmp(type, "read");
3706 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
3707 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3708 priv);
3710 access = group_access_relation(group, read, !read);
3711 access = isl_union_map_apply_domain(access, priv);
3712 access_map = isl_map_from_union_map(access);
3714 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3715 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
3717 return copy_access(gen, sched, type, group, build, 1);
3720 /* Return code for reading into or writing from shared or private memory.
3722 * "schedule" is of the form
3724 * type[S -> A] -> L
3726 * with S be the first shared_len dimensions of the computed schedule,
3727 * A the array and L the schedule correponding to the generated loops.
3728 * The array reference group is attached to "type".
3730 static __isl_give isl_ast_node *create_access_leaf(
3731 struct gpu_gen *gen, __isl_take isl_map *schedule,
3732 __isl_take isl_ast_build *build)
3734 struct gpu_array_ref_group *group;
3735 isl_id *id;
3737 id = isl_map_get_tuple_id(schedule, isl_dim_in);
3738 group = isl_id_get_user(id);
3739 isl_id_free(id);
3741 if (group->private_tile)
3742 return copy_group_private_accesses(gen, group, schedule,
3743 build);
3744 else
3745 return copy_group_shared_accesses(gen, group, schedule,
3746 build);
3749 /* Create a domain node representing a synchronization.
3751 static __isl_give isl_ast_node *create_sync_leaf(
3752 struct gpu_gen *gen, __isl_take isl_map *schedule,
3753 __isl_take isl_ast_build *build)
3755 struct ppcg_kernel_stmt *stmt;
3756 isl_id *id;
3757 isl_space *space;
3758 isl_ast_node *node;
3759 isl_ast_expr *expr;
3761 isl_map_free(schedule);
3763 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3764 if (!stmt)
3765 return NULL;
3767 stmt->type = ppcg_kernel_sync;
3769 space = isl_ast_build_get_schedule_space(build);
3770 space = isl_space_from_domain(space);
3771 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
3772 expr = isl_ast_build_call_from_pw_multi_aff(build,
3773 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
3774 node = isl_ast_node_alloc_user(expr);
3775 isl_ast_build_free(build);
3777 id = isl_id_alloc(gen->ctx, NULL, stmt);
3778 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3779 return isl_ast_node_set_annotation(node, id);
3782 /* This function is called during the code generation at the point
3783 * where the schedule domain element is completely determined by
3784 * the generated code. The input schedule contains the original
3785 * statements as well as synchronization and copy "statements".
3786 * The latter are scheduled at different points than any of the original
3787 * statements, so they will only arrive here in isolation.
3789 * If the current schedule only refers to a single statement,
3790 * we check if it is a copy or synchronization statement and
3791 * call the appropriate functions.
3792 * Otherwise, we assume we are dealing with the original statements
3793 * and we call create_domain_leaf.
3795 static __isl_give isl_ast_node *create_kernel_leaf(
3796 __isl_take isl_ast_build *build, void *user)
3798 struct gpu_gen *gen = (struct gpu_gen *) user;
3799 isl_map *map;
3800 isl_union_map *schedule;
3801 const char *name;
3803 schedule = isl_ast_build_get_schedule(build);
3805 if (isl_union_map_n_map(schedule) != 1)
3806 return create_domain_leaf(schedule, build, user);
3808 map = isl_map_from_union_map(schedule);
3809 name = isl_map_get_tuple_name(map, isl_dim_in);
3810 if (!strcmp(name, "read") || !strcmp(name, "write"))
3811 return create_access_leaf(gen, map, build);
3812 if (!strcmp(name, "sync"))
3813 return create_sync_leaf(gen, map, build);
3815 return create_domain_leaf(isl_union_map_from_map(map), build, user);
3818 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
3819 * have value 0) and all even schedule dimensions as "unroll".
3821 * That is, the options look as follows
3823 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
3824 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
3826 * The even positions are used to be able to schedule copying blocks
3827 * and synchronization before or after each level of the shared memory
3828 * tile loops and we want to make sure that code for these is generated
3829 * separately (within each level).
3831 static __isl_give isl_ast_build *set_atomic_and_unroll(
3832 __isl_take isl_ast_build *build,
3833 __isl_take isl_space *space, int sched_len)
3835 isl_ctx *ctx;
3836 isl_map *map;
3837 isl_constraint *c;
3838 isl_union_map *opt;
3839 isl_local_space *ls;
3840 int i, n;
3842 ctx = isl_ast_build_get_ctx(build);
3844 space = isl_space_params(space);
3845 space = isl_space_add_dims(space, isl_dim_set, sched_len);
3846 space = isl_space_from_domain(space);
3847 space = isl_space_add_dims(space, isl_dim_out, 2);
3848 map = isl_map_universe(isl_space_copy(space));
3849 for (i = 0; i < sched_len; i += 2)
3850 map = isl_map_fix_si(map, isl_dim_in, i, 0);
3851 ls = isl_local_space_from_space(isl_map_get_space(map));
3852 c = isl_equality_alloc(ls);
3853 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3854 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3855 c = isl_constraint_set_constant_si(c, 1);
3856 map = isl_map_add_constraint(map, c);
3857 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3858 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
3859 opt = isl_union_map_from_map(map);
3861 map = isl_map_universe(space);
3862 ls = isl_local_space_from_space(isl_map_get_space(map));
3863 c = isl_equality_alloc(ls);
3864 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3865 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3866 map = isl_map_add_constraint(map, c);
3867 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3868 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
3869 opt = isl_union_map_add_map(opt, map);
3871 build = isl_ast_build_set_options(build, opt);
3873 return build;
3876 /* Return a map that maps a space of dimension gen->shared_len
3877 * to its last dimensions starting at gen->tile_first.
3878 * The range is of dimension
3880 * 2 * (gen->shared_len - gen->tile_first) + 1
3882 * The input dimensions are mapped to the odd dimensions in the output,
3883 * while the even dimensions (except 2*pos) are fixed to 0.
3884 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
3885 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
3886 * are mapped to the output. The remaining input dimensions are projected
3887 * out and the corresponding output dimensions are fixed to 0.
3889 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
3890 __isl_take isl_space *space, int pos, int val)
3892 int i, n;
3893 isl_map *proj;
3895 space = isl_space_set_from_params(space);
3896 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
3897 space = isl_space_map_from_set(space);
3898 proj = isl_map_identity(space);
3899 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
3900 n = gen->shared_len - gen->tile_first;
3901 for (i = 0; i <= n; ++i) {
3902 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
3903 if (i == pos)
3904 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
3905 else
3906 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
3909 if (pos < 0)
3910 return proj;
3912 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
3913 gen->shared_len - (gen->tile_first + pos));
3914 for (i = pos; i < n; ++i)
3915 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
3917 return proj;
3920 /* Given the AST context schedule "schedule" and the mapping from
3921 * domains to the shared tile loops "shared_sched", add a schedule
3922 * for a synchronization operation at position "val" of loop level "pos".
3924 * schedule is of the form
3926 * D -> L
3928 * (with D the iteration domains and L the already generated loops),
3929 * while shared_sched is of the form
3931 * D -> S
3933 * We combine them into
3935 * L -> S
3937 * apply a mapping
3939 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
3941 * and use the result as a schedule for "sync".
3943 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
3944 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
3945 __isl_keep isl_union_map *shared_sched, int pos, int val)
3947 isl_space *space;
3948 isl_map *proj, *map;
3950 shared_sched = isl_union_map_copy(shared_sched);
3951 schedule = isl_union_map_copy(schedule);
3953 space = isl_union_map_get_space(shared_sched);
3954 schedule = isl_union_map_apply_domain(shared_sched, schedule);
3955 map = isl_map_from_union_map(schedule);
3957 proj = insert_even(gen, space, pos, val);
3958 map = isl_map_apply_range(map, proj);
3959 map = isl_map_from_range(isl_map_wrap(map));
3960 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
3962 res = isl_union_map_add_map(res, map);
3964 return res;
3967 /* Given the AST context schedule "schedule" and the mapping from
3968 * domains to the shared tile loops "shared_sched", add a schedule
3969 * for copying an array reference group to/from shared/private memory.
3970 * "read" is set if data should be copied from global memory
3971 * to shared/private memory.
3972 * "k" represents the current group
3973 * "s" is the total number of groups
3975 * We schedule an operation before or after the innermost loop
3976 * of "shared_sched" that affects the tile of the array reference group.
3978 * schedule is of the form
3980 * D -> L
3982 * (with D the iteration domains and L the already generated loops),
3983 * while shared_sched is of the form
3985 * D -> S
3987 * We first compute the access relation for the reference group
3989 * D -> A
3991 * and combine it with shared_sched into
3993 * D -> [S -> A]
3995 * If this results in an empty relation, no copying needs to be performed
3996 * at this point.
3997 * Otherwise, we invert the relation and combine it with "schedule" into
3999 * [S -> A] -> L
4001 * The actual additional piece of the schedule is obtained from combining
4003 * [S -> A] -> S
4005 * with a mapping
4007 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4009 * The position of "val" corresponds to the innermost loop that affects
4010 * the tile and the value indicates where the copying is scheduled
4011 * with respect to the actual kernel code (at value 0).
4012 * Reads are schedule before the code, writes to global memory from
4013 * private memory are scheduled at values 1 to s, writes to global
4014 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4016 * If we are scheduling a read from global memory to shared memory,
4017 * we insert a synchronization before the kernel code (at the innermost
4018 * level).
4019 * If we are scheduling a write to global memory, then we add
4020 * a synchronization after all writes (at value 2 *s + 2).
4021 * However, there is no need for a synchronization after the outermost loop.
4022 * A write to global memory from private memory at the innermost level
4023 * does not require a synchronization, because it is covered by
4024 * the synchronization after the kernel inserted by body_schedule.
4026 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4027 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4028 __isl_keep isl_union_map *shared_sched,
4029 struct gpu_array_ref_group *group, int read, int k, int s)
4031 int n;
4032 int pos, val;
4033 isl_space *space;
4034 isl_union_map *access;
4035 isl_map *map, *proj, *access_map;
4036 isl_id *id;
4038 access = group_access_relation(group, read, !read);
4039 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4040 access);
4042 if (isl_union_map_is_empty(access)) {
4043 isl_union_map_free(access);
4044 return res;
4047 access = isl_union_map_reverse(access);
4048 access = isl_union_map_apply_range(access,
4049 isl_union_map_copy(schedule));
4050 access_map = isl_map_from_union_map(access);
4052 space = isl_space_copy(group->array->dim);
4053 space = isl_space_from_range(space);
4054 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4055 map = isl_map_domain_map(isl_map_universe(space));
4057 space = isl_union_map_get_space(schedule);
4058 pos = group->last_shared + 1 - gen->tile_first;
4059 assert(pos >= 0);
4060 if (read)
4061 val = -2 - k;
4062 else if (group->private_tile)
4063 val = 1 + k;
4064 else
4065 val = 1 + s + 1 + k;
4066 proj = insert_even(gen, space, pos, val);
4067 map = isl_map_apply_range(map, proj);
4069 access_map = isl_map_range_product(access_map, map);
4071 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4072 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4074 res = isl_union_map_add_map(res, access_map);
4076 n = gen->shared_len - gen->tile_first;
4077 if (read) {
4078 if (!group->private_tile)
4079 res = add_sync_schedule(gen, res, schedule,
4080 shared_sched, n, -1);
4081 } else {
4082 if (pos == 0)
4083 return res;
4084 if (pos == n && group->private_tile)
4085 return res;
4086 res = add_sync_schedule(gen, res, schedule, shared_sched,
4087 pos, 2 * s + 2);
4090 return res;
4093 /* Return a schedule for the shared tile loops based on the current
4094 * AST context schedule.
4096 * We create a "shared_sched" that maps the domains to the first
4097 * shared_len dimensions of the computed schedule, project out the
4098 * first tile_first dimensions (as these are already covered by
4099 * the host code) and insert "statement-level" dimensions at even
4100 * positions so that we can schedule copy blocks and synchronization
4101 * before/after each level.
4103 * In particular, copy blocks are inserted inside the innermost
4104 * level that affect the tile. For the copying to global memory,
4105 * those from private memory are scheduled before those from shared
4106 * memory such that synchronization can be inserted between the two
4107 * at the innermost level.
4108 * Synchronization is inserted at the innermost level before the
4109 * actual kernel code if there is any copying from global memory
4110 * to shared memory. It is inserted unconditionally at the innermost
4111 * level after the actual kernel code and the copying to global memory
4112 * from private memory (if any). Finally, it is inserted after
4113 * any copying to global memory, except at the outermost level
4114 * and at the innermost level if there is no copying from shared
4115 * memory. The copying from private memory is covered by the unconditional
4116 * synchronization at the innermost level.
4118 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4119 __isl_take isl_union_map *schedule)
4121 isl_space *space;
4122 isl_union_map *res;
4123 isl_union_map *shared_sched;
4124 isl_union_map *sched;
4125 isl_map *proj, *map;
4126 int i, j, k, s;
4128 shared_sched = isl_union_map_copy(gen->tiled_sched);
4129 proj = projection(isl_union_map_get_space(shared_sched),
4130 gen->tiled_len, gen->shared_len);
4131 shared_sched = isl_union_map_apply_range(shared_sched,
4132 isl_union_map_from_map(proj));
4133 space = isl_union_map_get_space(shared_sched);
4134 proj = insert_even(gen, space, -1, 0);
4135 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4136 isl_union_map_from_map(proj));
4138 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4140 s = 0;
4141 for (i = 0; i < gen->prog->n_array; ++i)
4142 s += gen->prog->array[i].n_group;
4144 k = 0;
4145 for (i = 0; i < gen->prog->n_array; ++i) {
4146 struct gpu_array_info *array = &gen->prog->array[i];
4148 for (j = 0; j < array->n_group; ++j) {
4149 struct gpu_array_ref_group *group;
4151 group = array->groups[j];
4152 if (!group->private_tile && !group->shared_tile)
4153 continue;
4154 res = add_group_schedule(gen, res, schedule,
4155 shared_sched, group, 0, k, s);
4156 res = add_group_schedule(gen, res, schedule,
4157 shared_sched, group, 1, k, s);
4158 ++k;
4162 res = add_sync_schedule(gen, res, schedule, shared_sched,
4163 gen->shared_len - gen->tile_first, 1 + s);
4165 isl_union_map_free(shared_sched);
4166 isl_union_map_free(schedule);
4168 return res;
4171 /* Generate code for "kernel" in the given "context".
4173 * We first generate code for the shared tile loops (T1T, T1P and T2)
4174 * in a context that includes the block ids.
4175 * Within each iteration of these loops an additional code generation
4176 * is performed (within create_kernel_leaf) for the rest of the schedule
4177 * in a context that includes the thread ids.
4179 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4180 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4181 __isl_keep isl_multi_pw_aff *grid_size)
4183 isl_space *space;
4184 isl_set *set;
4185 isl_id_list *iterators;
4186 isl_union_map *schedule;
4187 isl_ast_node *tree;
4188 int sched_len;
4190 schedule = isl_ast_build_get_schedule(build);
4192 build = isl_ast_build_copy(build);
4193 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4194 space = isl_ast_build_get_schedule_space(build);
4195 set = isl_set_universe(isl_space_copy(space));
4196 set = add_bounded_parameters_dynamic(set, grid_size, "b");
4197 build = isl_ast_build_restrict(build, set);
4199 schedule = body_schedule(gen, schedule);
4201 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4203 build = set_atomic_and_unroll(build, space, sched_len);
4204 iterators = generate_names(gen->ctx, sched_len, "g");
4205 build = isl_ast_build_set_iterators(build, iterators);
4206 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4207 tree = isl_ast_build_ast_from_schedule(build, schedule);
4208 isl_ast_build_free(build);
4210 return tree;
4213 /* Attach "id" to the given node.
4215 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4216 __isl_keep isl_ast_build *build, void *user)
4218 isl_id *id = user;
4220 node = isl_ast_node_set_annotation(node, id);
4222 return node;
4225 /* Construct an AST node for performing a kernel launch and attach
4226 * the information about the kernel to that node.
4228 * The kernel AST has been constructed in the context of the range
4229 * of "schedule". In particular, the grid size has been computed
4230 * in the context. We therefore still need to make sure that these
4231 * constraints are expressed in the code. We do this by creating a schedule
4233 * kernel[] -> [S -> []]
4235 * where S is the schedule domain, i.e., the range of "schedule".
4236 * The AST generation will then create a single call surrounded by
4237 * all the condition in "S" that have not been expressed yet.
4239 * The kernel information is attached to this node in attach_id.
4241 static __isl_give isl_ast_node *construct_launch(
4242 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
4243 __isl_take struct ppcg_kernel *kernel)
4245 isl_id *id;
4246 isl_ctx *ctx;
4247 isl_union_set *domain;
4248 isl_set *set;
4249 isl_map *map;
4250 isl_ast_node *node;
4252 ctx = isl_ast_build_get_ctx(build);
4254 id = isl_id_alloc(ctx, NULL, kernel);
4255 id = isl_id_set_free_user(id, &ppcg_kernel_free);
4257 domain = isl_union_map_range(schedule);
4258 set = isl_set_from_union_set(domain);
4259 map = isl_map_from_domain(set);
4260 map = isl_map_from_range(isl_map_wrap(map));
4261 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
4262 schedule = isl_union_map_from_map(map);
4264 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
4265 node = isl_ast_build_ast_from_schedule(build, schedule);
4266 isl_ast_build_free(build);
4268 return node;
4271 /* This function is called for each leaf in the AST of the host code.
4272 * We first specialize the schedule to the site of the leaf, compute
4273 * the size of shared memory and then construct the body of host code
4274 * and the associated kernel.
4276 * The necessary information for printing the kernel launch is
4277 * stored in a struct ppcg_kernel and attached to the leaf node
4278 * created to represent the launch.
4280 static __isl_give isl_ast_node *create_host_leaf(
4281 __isl_take isl_ast_build *build, void *user)
4283 struct gpu_gen *gen = (struct gpu_gen *) user;
4284 isl_id *id;
4285 isl_ast_node *node;
4286 struct ppcg_kernel *kernel;
4287 isl_set *host_domain;
4288 isl_union_map *schedule;
4289 isl_union_map *local_sched;
4290 isl_union_map *access;
4291 isl_union_set *domain;
4292 int i;
4294 schedule = isl_ast_build_get_schedule(build);
4296 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
4297 read_sizes(gen);
4299 domain = isl_union_map_domain(isl_union_map_copy(schedule));
4301 local_sched = isl_union_map_copy(gen->sched);
4302 local_sched = isl_union_map_intersect_domain(local_sched, domain);
4303 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
4304 isl_union_map_copy(gen->prog->write));
4305 access = isl_union_map_apply_domain(access,
4306 isl_union_map_copy(local_sched));
4308 gen->tiled_sched = tile_schedule(gen, local_sched);
4309 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
4310 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
4312 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
4313 if (!kernel)
4314 goto error;
4316 kernel->id = gen->kernel_id++;
4317 kernel->n_block = gen->n_block;
4318 for (i = 0; i < gen->n_block; ++i)
4319 kernel->block_dim[i] = gen->block_dim[i];
4320 kernel->n_grid = gen->n_grid;
4321 for (i = 0; i < gen->n_grid; ++i)
4322 kernel->grid_dim[i] = gen->grid_dim[i];
4323 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
4324 kernel->grid_size = extract_grid_size(gen, kernel);
4325 kernel->arrays = isl_union_map_range(access);
4326 kernel->space = isl_ast_build_get_schedule_space(build);
4328 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
4330 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
4331 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
4333 gen->private_access = NULL;
4334 compute_shared_sched(gen);
4335 gen->privatization = compute_privatization(gen);
4336 group_references(gen);
4337 compute_private_access(gen);
4338 check_shared_memory_bound(gen);
4339 host_domain = isl_set_from_union_set(isl_union_map_range(
4340 isl_union_map_copy(schedule)));
4341 localize_bounds(gen, kernel, host_domain);
4343 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
4345 kernel->tree = generate_kernel(gen, build, host_domain,
4346 kernel->grid_size);
4347 create_kernel_vars(gen, kernel);
4349 free_local_array_info(gen);
4350 isl_map_free(gen->privatization);
4351 isl_union_map_free(gen->private_access);
4352 isl_union_map_free(gen->local_sched);
4353 isl_union_map_free(gen->tiled_sched);
4354 isl_union_map_free(gen->shared_sched);
4355 isl_union_map_free(gen->shared_proj);
4356 isl_set_free(host_domain);
4357 free(gen->tile_size);
4359 node = construct_launch(build, schedule, kernel);
4361 return node;
4362 error:
4363 isl_union_map_free(schedule);
4364 return NULL;
4367 /* Use isl to generate code for the outer gen->tile_first loops
4368 * of the global schedule in gen->sched, resulting in the host code.
4369 * Within each iteration of this partial schedule, i.e., for each kernel
4370 * launch, create_host_leaf takes care of generating the kernel code.
4372 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
4374 isl_ast_build *build;
4375 isl_ast_node *tree;
4376 isl_union_map *sched;
4377 isl_map *proj;
4378 isl_id_list *iterators;
4380 sched = isl_union_map_copy(gen->sched);
4381 proj = projection(isl_union_map_get_space(sched),
4382 gen->untiled_len, gen->tile_first);
4383 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4385 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
4386 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
4387 iterators = generate_names(gen->ctx, gen->tile_first, "h");
4388 build = isl_ast_build_set_iterators(build, iterators);
4389 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
4390 tree = isl_ast_build_ast_from_schedule(build, sched);
4391 isl_ast_build_free(build);
4393 return tree;
4396 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
4398 if (!str)
4399 return NULL;
4400 return isl_union_map_read_from_str(ctx, str);
4403 /* Information about the outermost tilable bands in the forest of bands.
4405 * tile_len and n_parallel are only sets on band_info structures
4406 * that correspond to outermost bands. For other bands (in particular,
4407 * ancestors of the outermost bands), n_parallal is set to 0.
4409 * prefix is the (padded) schedule leading up to the outermost tilable bands.
4411 * tile_first is the number of schedule dimensions in prefix.
4413 * suffix is the schedule of the outermost tilable bands and their descendants.
4415 struct band_info {
4416 struct gpu_gen *gen;
4417 int tile_first;
4418 int tile_len;
4419 int n_parallel;
4420 isl_union_map *prefix;
4421 isl_union_map *suffix;
4424 /* Set tile_len and n_parallel of the statement to that of
4425 * their outermost band, recorded in the band_info.
4427 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
4429 struct band_info *info = user;
4430 struct gpu_stmt *stmt;
4431 isl_id *id;
4433 id = isl_map_get_tuple_id(map, isl_dim_in);
4434 stmt = find_stmt(info->gen->prog, id);
4435 isl_id_free(id);
4437 stmt->tile_len = info->tile_len;
4438 stmt->n_parallel = info->n_parallel;
4440 isl_map_free(map);
4442 return 0;
4445 static void list_select_outer_band(struct gpu_gen *gen,
4446 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
4448 /* Check if this band has any parallel loops. If so, take it as
4449 * the outermost tilable band. If not, continue looking for the
4450 * outermost tilable band in the children of the current band.
4452 static void band_select_outer_band(struct gpu_gen *gen,
4453 __isl_take isl_band *band, int pos, struct band_info *info)
4455 int n = isl_band_n_member(band);
4456 int n_parallel;
4458 for (n_parallel = 0; n_parallel < n; ++n_parallel)
4459 if (!isl_band_member_is_zero_distance(band, n_parallel))
4460 break;
4462 info->n_parallel = n_parallel;
4463 if (n_parallel) {
4464 info->gen = gen;
4465 info->tile_first = pos;
4466 info->tile_len = n;
4467 info->prefix = isl_band_get_prefix_schedule(band);
4468 info->suffix = isl_union_map_flat_range_product(
4469 isl_band_get_partial_schedule(band),
4470 isl_band_get_suffix_schedule(band));
4471 isl_union_map_foreach_map(info->prefix,
4472 &set_stmt_tile_len, info);
4473 } else if (isl_band_has_children(band)) {
4474 isl_band_list *children;
4475 children = isl_band_get_children(band);
4476 list_select_outer_band(gen, children, pos + n, info);
4477 } else {
4478 info->gen = gen;
4479 info->tile_first = pos + n;
4480 info->tile_len = 0;
4481 info->prefix = isl_union_map_flat_range_product(
4482 isl_band_get_prefix_schedule(band),
4483 isl_band_get_partial_schedule(band));
4484 info->suffix = isl_band_get_suffix_schedule(band);
4485 isl_union_map_foreach_map(info->prefix,
4486 &set_stmt_tile_len, info);
4489 isl_band_free(band);
4492 /* Comparison function that returns a non-zero value for band_infos
4493 * with different tile_len fields or different n_parallel fields.
4495 static int cmp_band(const void *p1, const void *p2)
4497 const struct band_info *info1 = p1;
4498 const struct band_info *info2 = p2;
4500 if (info1->tile_len != info2->tile_len)
4501 return info1->tile_len - info2->tile_len;
4503 return info1->n_parallel - info2->n_parallel;
4506 /* Extend "umap" with coordinates with fixed value "val"
4507 * to a total length of "dst_len", assuming the original dimension is "src_len".
4509 static __isl_give isl_union_map *extend_range(
4510 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
4512 isl_space *dim;
4513 isl_map *map;
4514 int i;
4516 dim = isl_union_map_get_space(umap);
4517 map = isl_map_reverse(projection(dim, dst_len, src_len));
4518 for (i = src_len; i < dst_len; ++i)
4519 map = isl_map_fix_si(map, isl_dim_out, i, val);
4521 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
4523 return umap;
4526 /* Group bands with the same values for tile_len and n_parallel.
4527 * The prefix schedule is then extended with a fixed coordinate that
4528 * is different for each such group.
4529 * Note that the actual values for this coordinate are not important.
4530 * The bands have already been effectively separated at a higher level
4531 * or they are independent and may be executed in parallel.
4532 * The list of band_info has been sorted before this functions is called.
4534 static void separate_bands(struct band_info *info, int n)
4536 int i;
4537 int j = 0;
4539 for (i = 0; i < n; ++i) {
4540 int l = info[i].tile_first;
4542 if (i &&
4543 (info[i].tile_len != info[i - 1].tile_len ||
4544 info[i].n_parallel != info[i - 1].n_parallel))
4545 j++;
4547 info[i].prefix = extend_range(info[i].prefix,
4548 l, l + 1, j);
4549 info[i].tile_first = l + 1;
4553 /* Select the outermost bands in the elements of the list, align
4554 * their prefix schedules, separate bands with different values
4555 * for tile_len and/or n_parallel and then combine the resulting
4556 * prefix and suffix schedules into a single pair of prefix and
4557 * suffix schedules for the entire list.
4559 static void list_select_outer_band(struct gpu_gen *gen,
4560 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
4562 isl_band *band;
4563 int i;
4564 int n = isl_band_list_n_band(list);
4565 isl_ctx *ctx = isl_band_list_get_ctx(list);
4566 struct band_info *info;
4567 int max_tile_first;
4568 isl_union_map *prefix;
4569 isl_union_map *suffix;
4571 assert(n >= 1);
4572 info = isl_calloc_array(ctx, struct band_info, n);
4573 assert(info);
4575 max_tile_first = 0;
4576 for (i = 0; i < n; ++i) {
4577 band = isl_band_list_get_band(list, i);
4578 band_select_outer_band(gen, band, pos, &info[i]);
4579 if (info[i].tile_first > max_tile_first)
4580 max_tile_first = info[i].tile_first;
4583 for (i = 0; i < n; ++i) {
4584 if (info[i].tile_first == max_tile_first)
4585 continue;
4586 info[i].prefix = extend_range(info[i].prefix,
4587 info[i].tile_first, max_tile_first, 0);
4588 info[i].tile_first = max_tile_first;
4591 qsort(info, n, sizeof(struct band_info), &cmp_band);
4593 for (i = 0; i < n - 1; ++i)
4594 if (info[i].tile_len != info[i + 1].tile_len ||
4595 info[i].n_parallel != info[i + 1].n_parallel)
4596 break;
4598 if (i < n -1)
4599 separate_bands(info, n);
4601 prefix = info[0].prefix;
4602 suffix = info[0].suffix;
4604 for (i = 1; i < n; ++i) {
4605 prefix = isl_union_map_union(prefix, info[i].prefix);
4606 suffix = isl_union_map_union(suffix, info[i].suffix);
4609 list_info->tile_first = info[0].tile_first;
4610 list_info->tile_len = -1;
4611 list_info->prefix = prefix;
4612 list_info->suffix = suffix;
4614 isl_band_list_free(list);
4615 free(info);
4618 /* Select the outermost tilable band that (by construction)
4619 * has at least one parallel loop.
4620 * The starting position of the aligned band is stored in the pair
4621 * gen->tile_first.
4622 * The sizes and number of parallel loops may be different in different
4623 * parts of the band forest and are therefore stored in the gpu_stmts.
4625 * Return the complete schedule, with the tilable bands aligned
4626 * at gen->tile_first and padded with zero, if needed.
4628 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
4629 __isl_keep isl_schedule *schedule)
4631 isl_band_list *list;
4632 struct band_info info;
4634 gen->n_parallel = 0;
4635 gen->tile_len = -1;
4637 list = isl_schedule_get_band_forest(schedule);
4639 list_select_outer_band(gen, list, 0, &info);
4641 gen->tile_first = info.tile_first;
4642 info.suffix = align_range(info.suffix);
4644 return isl_union_map_flat_range_product(info.prefix, info.suffix);
4647 /* Set gen->untiled_len to the number of scheduling dimensions
4648 * for the schedule of the first domain.
4649 * We assume here that this number is the same for all domains.
4651 static int set_untiled_len(__isl_take isl_map *map, void *user)
4653 unsigned *untiled_len = user;
4655 *untiled_len = isl_map_dim(map, isl_dim_out);
4657 isl_map_free(map);
4658 return -1;
4661 /* Compute an appropriate schedule based on the accesses in
4662 * gen->read and gen->write.
4664 * We use the dependences in gen->prog->scop to compute
4665 * a schedule that has a parallel loop in each tilable band.
4666 * Finally, we select the outermost tilable band.
4668 static void compute_schedule(struct gpu_gen *gen)
4670 isl_union_set *domain;
4671 isl_union_map *dep_raw, *dep;
4672 isl_union_map *sched;
4673 isl_schedule *schedule;
4675 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4677 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4678 dep = isl_union_map_union(dep, dep_raw);
4679 dep = isl_union_map_coalesce(dep);
4681 domain = isl_union_set_copy(gen->prog->scop->domain);
4682 domain = isl_union_set_intersect_params(domain,
4683 isl_set_copy(gen->prog->scop->context));
4684 schedule = isl_union_set_compute_schedule(isl_union_set_copy(domain),
4685 isl_union_map_copy(dep), dep);
4686 if (gen->options->debug->dump_schedule)
4687 isl_schedule_dump(schedule);
4689 sched = select_outer_tilable_band(gen, schedule);
4691 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
4692 sched = isl_union_map_intersect_domain(sched, domain);
4693 gen->sched = sched;
4695 isl_schedule_free(schedule);
4698 /* Compute the sets of array elements that need to be copied in and out.
4700 * In particular, for each array that is written anywhere in gen->prog and
4701 * that is visible outside the corresponding scop, we copy out its entire
4702 * extent.
4704 * Any array elements that is read without first being written needs
4705 * to be copied in. Furthermore, if there are any array elements that
4706 * are copied out, but that are not written inside gen->prog, then
4707 * they also need to be copied in to ensure that the value after execution
4708 * is the same as the value before execution.
4709 * While computing the set of array elements that
4710 * are copied out but not written, we intersect both sets with the context.
4711 * This helps in those cases where the arrays are declared with a fixed size,
4712 * while the accesses are parametric and the context assigns a fixed value
4713 * to the parameters.
4715 static void compute_copy_in_and_out(struct gpu_gen *gen)
4717 int i;
4718 isl_union_set *write;
4719 isl_union_set *copy_in, *copy_out;
4720 isl_union_set *not_written;
4721 isl_union_map *uninitialized;
4723 write = isl_union_map_range(isl_union_map_copy(gen->prog->write));
4724 write = isl_union_set_intersect_params(write,
4725 isl_set_copy(gen->prog->context));
4726 copy_out = isl_union_set_empty(isl_union_set_get_space(write));
4728 for (i = 0; i < gen->prog->n_array; ++i) {
4729 isl_space *space;
4730 isl_set *write_i;
4731 int empty;
4733 if (gen->prog->array[i].local)
4734 continue;
4736 space = isl_space_copy(gen->prog->array[i].dim);
4737 write_i = isl_union_set_extract_set(write, space);
4738 empty = isl_set_fast_is_empty(write_i);
4739 isl_set_free(write_i);
4740 if (empty)
4741 continue;
4743 write_i = isl_set_copy(gen->prog->array[i].extent);
4744 copy_out = isl_union_set_add_set(copy_out, write_i);
4747 copy_out = isl_union_set_intersect_params(copy_out,
4748 isl_set_copy(gen->prog->context));
4750 gen->prog->copy_out = isl_union_set_copy(copy_out);
4752 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
4753 copy_in = isl_union_map_range(uninitialized);
4755 not_written = isl_union_set_subtract(copy_out, write);
4756 copy_in = isl_union_set_union(copy_in, not_written);
4757 gen->prog->copy_in = copy_in;
4760 static struct gpu_stmt_access **expr_extract_access(struct pet_expr *expr,
4761 struct gpu_stmt_access **next_access)
4763 struct gpu_stmt_access *access;
4764 isl_ctx *ctx = isl_map_get_ctx(expr->acc.access);
4766 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4767 assert(access);
4768 access->next = NULL;
4769 access->read = expr->acc.read;
4770 access->write = expr->acc.write;
4771 access->access = isl_map_copy(expr->acc.access);
4773 *next_access = access;
4774 next_access = &(*next_access)->next;
4775 return next_access;
4778 static struct gpu_stmt_access **expr_extract_accesses(struct pet_expr *expr,
4779 struct gpu_stmt_access **next_access)
4781 int i;
4783 for (i = 0; i < expr->n_arg; ++i)
4784 next_access = expr_extract_accesses(expr->args[i],
4785 next_access);
4787 if (expr->type == pet_expr_access)
4788 next_access = expr_extract_access(expr, next_access);
4790 return next_access;
4793 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
4795 struct gpu_stmt_access **next_access = &stmt->accesses;
4797 stmt->accesses = NULL;
4798 expr_extract_accesses(stmt->body, next_access);
4801 /* Return an array of gpu_stmt representing the statements in "scop".
4803 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4804 __isl_keep isl_set *context)
4806 int i;
4807 struct gpu_stmt *stmts;
4809 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
4810 assert(stmts);
4812 for (i = 0; i < scop->n_stmt; ++i) {
4813 struct gpu_stmt *s = &stmts[i];
4815 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
4816 s->body = scop->stmts[i]->body;
4817 pet_stmt_extract_accesses(s);
4820 return stmts;
4823 /* Replace the scop in the "input" file by equivalent code
4824 * that uses the GPU. "scop" is assumed to correspond to this scop.
4826 * We first compute a schedule that respects the dependences
4827 * of the original program and select the outermost band
4828 * of tilable dimensions that has at least one parallel loop.
4829 * We then have three blocks of dimensions
4831 * H B G
4833 * The tilable band "B" is first tiled according to "tile" sizes, resulting
4834 * in
4836 * H T P G
4838 * For each iteration of the T loop and for each array, we compute
4839 * the array elements accessed by that iteration, construct a rectangular
4840 * box around it and shift it to the origin. The result is used
4841 * as shared memory for the array.
4843 * We then split off at most 2 parallel loops from the T loops and
4844 * at most 3 parallel loops from the P loops
4846 * H T1 T2 P1 P2 G
4848 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
4849 * according to "grid"/"block" sizes.
4851 * H T1T T1P T2 P1T P1P P2 G
4853 * Finally, the T1P and P1P iterators are equated to the block and
4854 * thread dimensions respectively and so are effectively removed.
4855 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
4856 * are run on the GPU.
4858 * Code is generated in three stages. We first generate code for the
4859 * host (the H loops), with iterators h%d. Then, for each leaf node
4860 * of the resulting AST, we generate code for the shared loops (up to
4861 * and including T2), with iterators g%d and after equating the H loops
4862 * to h%d parameters and the T1P loops to the block dimensions.
4863 * Finally, we generate code for the remaining loops in a similar fashion.
4865 __isl_give isl_ast_node *generate_gpu(isl_ctx *ctx, struct gpu_prog *prog,
4866 struct ppcg_options *options)
4868 isl_union_map *sched;
4869 struct gpu_gen gen;
4870 isl_ast_node *tree;
4872 if (!prog)
4873 return NULL;
4875 gen.ctx = ctx;
4876 gen.prog = prog;
4877 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
4878 gen.options = options;
4880 compute_schedule(&gen);
4881 compute_copy_in_and_out(&gen);
4883 gen.kernel_id = 0;
4884 tree = generate_host_code(&gen);
4886 clear_gpu_gen(&gen);
4888 return tree;
4891 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
4893 struct gpu_prog *prog;
4895 if (!scop)
4896 return NULL;
4898 prog = isl_calloc_type(ctx, struct gpu_prog);
4899 assert(prog);
4901 prog->ctx = ctx;
4902 prog->scop = scop;
4903 prog->context = isl_set_copy(scop->context);
4904 prog->n_stmts = scop->n_stmt;
4905 prog->stmts = extract_stmts(ctx, scop, prog->context);
4906 prog->read = isl_union_map_copy(scop->reads);
4907 prog->write = isl_union_map_copy(scop->writes);
4909 collect_array_info(prog);
4911 return prog;
4914 void gpu_prog_free(struct gpu_prog *prog)
4916 if (!prog)
4917 return;
4918 free_array_info(prog);
4919 free_stmts(prog->stmts, prog->n_stmts);
4920 isl_union_set_free(prog->copy_in);
4921 isl_union_set_free(prog->copy_out);
4922 isl_union_map_free(prog->read);
4923 isl_union_map_free(prog->write);
4924 isl_set_free(prog->context);
4925 free(prog);