gpu.c: group_array_references: take into account "last_shared" for overlap
[ppcg.git] / gpu.c
blobd1c7373fc33555cc8646c02c8172e060b4f353f1
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 bounds on the host arrays based on the accessed elements
321 * and collect all references to the array.
323 * If the array is zero-dimensional, i.e., a scalar, we check
324 * whether it is read-only.
326 static int extract_array_info(__isl_take isl_set *array, void *user)
328 int i;
329 struct gpu_prog *prog = (struct gpu_prog *)user;
330 const char *name;
331 int n_index;
332 isl_pw_aff **bounds;
333 struct pet_array *pa;
335 n_index = isl_set_dim(array, isl_dim_set);
336 name = isl_set_get_tuple_name(array);
337 bounds = isl_alloc_array(isl_set_get_ctx(array),
338 isl_pw_aff *, n_index);
339 assert(bounds);
340 prog->array[prog->n_array].dim = isl_set_get_space(array);
341 prog->array[prog->n_array].name = strdup(name);
342 prog->array[prog->n_array].n_index = n_index;
343 prog->array[prog->n_array].bound = bounds;
345 pa = find_array(prog->scop, array);
346 assert(pa);
348 prog->array[prog->n_array].type = strdup(pa->element_type);
349 prog->array[prog->n_array].size = pa->element_size;
350 prog->array[prog->n_array].local = pa->declared && !pa->exposed;
352 if (n_index == 0) {
353 isl_set *space;
354 isl_union_map *write;
355 int empty;
357 write = isl_union_map_copy(prog->write);
358 space = isl_set_universe(isl_set_get_space(array));
359 write = isl_union_map_intersect_range(write,
360 isl_union_set_from_set(space));
361 empty = isl_union_map_is_empty(write);
362 isl_union_map_free(write);
364 prog->array[prog->n_array].read_only = empty;
367 for (i = 0; i < n_index; ++i) {
368 isl_set *dom;
369 isl_local_space *ls;
370 isl_aff *one;
371 isl_pw_aff *bound;
372 isl_set *size = i == 0 ? array : pa->extent;
374 bound = isl_set_dim_max(isl_set_copy(size), i);
375 assert(bound);
376 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
377 ls = isl_local_space_from_space(isl_set_get_space(dom));
378 one = isl_aff_zero_on_domain(ls);
379 one = isl_aff_add_constant_si(one, 1);
380 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
381 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
383 bounds[i] = bound;
386 collect_references(prog, &prog->array[prog->n_array]);
388 prog->n_array++;
390 isl_set_free(array);
391 return 0;
394 void collect_array_info(struct gpu_prog *prog)
396 isl_union_set *arrays;
398 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
399 arrays = isl_union_set_union(arrays,
400 isl_union_map_range(isl_union_map_copy(prog->write)));
401 arrays = isl_union_set_coalesce(arrays);
403 prog->n_array = isl_union_set_n_set(arrays);
404 prog->array = isl_alloc_array(prog->ctx,
405 struct gpu_array_info, prog->n_array);
406 assert(prog->array);
407 prog->n_array = 0;
408 isl_union_set_foreach_set(arrays, &extract_array_info, prog);
409 isl_union_set_free(arrays);
412 static void free_array_info(struct gpu_prog *prog)
414 int i, j;
416 for (i = 0; i < prog->n_array; ++i) {
417 int n_index = prog->array[i].n_index;
418 free(prog->array[i].type);
419 free(prog->array[i].name);
420 for (j = 0; j < n_index; ++j)
421 isl_pw_aff_free(prog->array[i].bound[j]);
422 isl_space_free(prog->array[i].dim);
423 free(prog->array[i].bound);
424 free(prog->array[i].refs);
426 free(prog->array);
429 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
430 * as an array or through a pointer reference, but as single data element. At
431 * the moment, scalars are represented as zero dimensional arrays.
433 int gpu_array_is_scalar(struct gpu_array_info *array)
435 return (array->n_index == 0);
438 /* Is "array" a read-only scalar?
440 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
442 return gpu_array_is_scalar(array) && array->read_only;
445 /* Internal data structure for extract_size_of_type.
446 * "type" specifies the name of the space that we want to extract.
447 * "res" is used to store the subset of that space.
449 struct ppcg_extract_size_data {
450 const char *type;
451 isl_set *res;
454 /* This function is called for each set in a union_set.
455 * If the name of the set matches data->type, we store the
456 * set in data->res.
458 static int extract_size_of_type(__isl_take isl_set *size, void *user)
460 struct ppcg_extract_size_data *data = user;
461 const char *name;
463 name = isl_set_get_tuple_name(size);
464 if (name && !strcmp(name, data->type)) {
465 data->res = size;
466 return -1;
469 isl_set_free(size);
470 return 0;
473 /* Given a union map { kernel[i] -> *[...] },
474 * return the range in the space called "type" for the kernel with
475 * sequence number "id".
477 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
478 const char *type, int id)
480 isl_space *space;
481 isl_set *dom;
482 isl_union_set *local_sizes;
483 struct ppcg_extract_size_data data = { type, NULL };
485 if (!sizes)
486 return NULL;
488 space = isl_union_map_get_space(sizes);
489 space = isl_space_set_from_params(space);
490 space = isl_space_add_dims(space, isl_dim_set, 1);
491 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
492 dom = isl_set_universe(space);
493 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
495 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
496 isl_union_map_copy(sizes));
497 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
498 isl_union_set_free(local_sizes);
499 return data.res;
502 /* Given a singleton set, extract the first (at most *len) elements
503 * of the single integer tuple into *sizes and update *len if needed.
505 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
507 int i;
508 int dim;
509 isl_int v;
511 if (!set)
512 return;
514 dim = isl_set_dim(set, isl_dim_set);
515 if (dim < *len)
516 *len = dim;
518 isl_int_init(v);
520 for (i = 0; i < *len; ++i) {
521 int ok;
523 ok = isl_set_plain_is_fixed(set, isl_dim_set, i, &v);
524 assert(ok);
526 sizes[i] = isl_int_get_si(v);
529 isl_int_clear(v);
531 isl_set_free(set);
534 /* Extract user specified "tile" sizes from the "sizes" command line option,
535 * defaulting to option->tile_size in each dimension.
537 static void read_tile_sizes(struct gpu_gen *gen)
539 int n;
540 isl_set *size;
542 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
543 assert(gen->tile_size);
544 for (n = 0; n < gen->tile_len; ++n)
545 gen->tile_size[n] = gen->options->tile_size;
547 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
548 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
550 if (gen->n_parallel > gen->tile_len)
551 gen->n_parallel = gen->tile_len;
554 /* Extract user specified "block" sizes from the "sizes" command line option,
555 * after filling in some potentially useful defaults.
557 static void read_block_sizes(struct gpu_gen *gen)
559 int n;
560 isl_set *size;
562 n = gen->n_parallel;
563 gen->n_block = (n <= 3) ? n : 3;
564 switch (gen->n_block) {
565 case 1:
566 gen->block_dim[0] = 512;
567 break;
568 case 2:
569 gen->block_dim[0] = 32;
570 gen->block_dim[1] = 16;
571 break;
572 default:
573 gen->block_dim[0] = 32;
574 gen->block_dim[1] = 4;
575 gen->block_dim[2] = 4;
576 break;
579 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
580 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
583 /* Extract user specified "grid" sizes from the "sizes" command line option,
584 * after filling in some potentially useful defaults.
586 static void read_grid_sizes(struct gpu_gen *gen)
588 int n = gen->n_parallel;
589 isl_set *size;
591 gen->n_grid = (n <= 2) ? n : 2;
592 switch (gen->n_grid) {
593 case 1:
594 gen->grid_dim[0] = 32768;
595 break;
596 default:
597 gen->grid_dim[0] = 256;
598 gen->grid_dim[1] = 256;
599 break;
602 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
603 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
606 /* Extract user specified sizes from the "sizes" command line option
607 * after filling in some potentially useful defaults.
609 static void read_sizes(struct gpu_gen *gen)
611 read_tile_sizes(gen);
612 read_block_sizes(gen);
613 read_grid_sizes(gen);
616 static void free_stmts(struct gpu_stmt *stmts, int n)
618 int i;
620 for (i = 0; i < n; ++i) {
621 struct gpu_stmt_access *access, *next;
623 for (access = stmts[i].accesses; access; access = next) {
624 next = access->next;
625 isl_map_free(access->access);
626 free(access);
629 isl_id_free(stmts[i].id);
631 free(stmts);
634 void clear_gpu_gen(struct gpu_gen *gen)
636 isl_union_map_free(gen->sizes);
637 isl_union_map_free(gen->sched);
640 /* Construct a map from a domain of dimensionality "len"
641 * to a domain of dimensionality "len" + "tile_len" that tiles
642 * the "tile_len" coordinates starting at "first".
643 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
644 * "dim" prescribes the parameters.
646 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
647 int first, int tile_len, int *tile_size)
649 int i;
650 isl_int v;
651 isl_basic_map *bmap;
652 isl_constraint *c;
653 isl_local_space *ls;
655 isl_int_init(v);
657 dim = isl_space_add_dims(dim, isl_dim_in, len);
658 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
659 bmap = isl_basic_map_universe(isl_space_copy(dim));
660 ls = isl_local_space_from_space(dim);
662 for (i = 0; i < len - tile_len; ++i) {
663 int j = i < first ? i : i + tile_len;
664 int k = i < first ? i : i + 2 * tile_len;
666 c = isl_equality_alloc(isl_local_space_copy(ls));
667 isl_int_set_si(v, -1);
668 isl_constraint_set_coefficient(c, isl_dim_in, j, v);
669 isl_int_set_si(v, 1);
670 isl_constraint_set_coefficient(c, isl_dim_out, k, v);
671 bmap = isl_basic_map_add_constraint(bmap, c);
674 for (i = 0; i < tile_len; ++i) {
675 c = isl_equality_alloc(isl_local_space_copy(ls));
676 isl_int_set_si(v, -1);
677 isl_constraint_set_coefficient(c, isl_dim_in, first + i, v);
678 isl_int_set_si(v, tile_size[i]);
679 isl_constraint_set_coefficient(c, isl_dim_out, first + i, v);
680 isl_int_set_si(v, 1);
681 isl_constraint_set_coefficient(c, isl_dim_out,
682 first + i + tile_len, v);
683 bmap = isl_basic_map_add_constraint(bmap, c);
685 c = isl_inequality_alloc(isl_local_space_copy(ls));
686 isl_int_set_si(v, 1);
687 isl_constraint_set_coefficient(c, isl_dim_out,
688 first + i + tile_len, v);
689 bmap = isl_basic_map_add_constraint(bmap, c);
691 c = isl_inequality_alloc(isl_local_space_copy(ls));
692 isl_int_set_si(v, -1);
693 isl_constraint_set_coefficient(c, isl_dim_out,
694 first + i + tile_len, v);
695 isl_int_set_si(v, tile_size[i] - 1);
696 isl_constraint_set_constant(c, v);
697 bmap = isl_basic_map_add_constraint(bmap, c);
700 isl_local_space_free(ls);
701 isl_int_clear(v);
703 return isl_map_from_basic_map(bmap);
706 /* Construct a map from a domain of dimensionality "len"
707 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
708 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
709 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
710 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
711 * that are projected out at the end.
712 * "dim" prescribes the parameters.
714 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
715 int first, int wrap_len, int *wrap_size)
717 int i;
718 isl_basic_map *bmap;
719 isl_constraint *c;
720 isl_local_space *ls;
722 dim = isl_space_add_dims(dim, isl_dim_in, len);
723 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
724 bmap = isl_basic_map_universe(isl_space_copy(dim));
725 ls = isl_local_space_from_space(dim);
727 for (i = 0; i < len; ++i) {
728 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
730 c = isl_equality_alloc(isl_local_space_copy(ls));
731 isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
732 isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
733 bmap = isl_basic_map_add_constraint(bmap, c);
736 for (i = 0; i < wrap_len; ++i) {
737 c = isl_equality_alloc(isl_local_space_copy(ls));
738 isl_constraint_set_coefficient_si(c, isl_dim_out,
739 first + i, -1);
740 isl_constraint_set_coefficient_si(c, isl_dim_out,
741 first + wrap_len + i, 1);
742 isl_constraint_set_coefficient_si(c, isl_dim_out,
743 first + 2 * wrap_len + i, wrap_size[i]);
744 bmap = isl_basic_map_add_constraint(bmap, c);
746 c = isl_inequality_alloc(isl_local_space_copy(ls));
747 isl_constraint_set_coefficient_si(c, isl_dim_out,
748 first + wrap_len + i, 1);
749 bmap = isl_basic_map_add_constraint(bmap, c);
751 c = isl_inequality_alloc(isl_local_space_copy(ls));
752 isl_constraint_set_coefficient_si(c, isl_dim_out,
753 first + wrap_len + i, -1);
754 isl_constraint_set_constant_si(c, wrap_size[i] - 1);
755 bmap = isl_basic_map_add_constraint(bmap, c);
758 isl_local_space_free(ls);
760 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
761 first + 2 * wrap_len, wrap_len);
763 return isl_map_from_basic_map(bmap);
766 /* Add "n" parameters named prefix%d.
768 static __isl_give isl_set *add_params( __isl_take isl_set *set,
769 int n, const char *prefix)
771 int i;
772 unsigned nparam;
773 char name[20];
775 nparam = isl_set_dim(set, isl_dim_param);
776 set = isl_set_add_dims(set, isl_dim_param, n);
778 for (i = 0; i < n; ++i) {
779 snprintf(name, sizeof(name), "%s%d", prefix, i);
780 set = isl_set_set_dim_name(set, isl_dim_param,
781 nparam + i, name);
784 return set;
787 /* Equate the "n" dimensions of "set" starting at "first" to
788 * freshly created parameters named prefix%d.
790 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
791 int first, int n, const char *prefix)
793 int i;
794 unsigned nparam;
795 isl_int v;
796 isl_space *dim;
797 isl_basic_set *bset;
798 isl_constraint *c;
799 isl_local_space *ls;
801 nparam = isl_set_dim(set, isl_dim_param);
803 set = add_params(set, n, prefix);
805 dim = isl_set_get_space(set);
806 bset = isl_basic_set_universe(isl_space_copy(dim));
807 ls = isl_local_space_from_space(dim);
809 isl_int_init(v);
811 for (i = 0; i < n; ++i) {
812 c = isl_equality_alloc(isl_local_space_copy(ls));
813 isl_int_set_si(v, -1);
814 isl_constraint_set_coefficient(c, isl_dim_param, nparam + i, v);
815 isl_int_set_si(v, 1);
816 isl_constraint_set_coefficient(c, isl_dim_set, first + i, v);
817 bset = isl_basic_set_add_constraint(bset, c);
820 isl_int_clear(v);
821 isl_local_space_free(ls);
823 return isl_set_intersect(set, isl_set_from_basic_set(bset));
826 /* Given a parameter space "space", create a set of dimension "len"
827 * of which the "n" dimensions starting at "first" are equated to
828 * freshly created parameters named prefix%d.
830 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
831 int len, int first, int n, const char *prefix)
833 isl_set *set;
835 space = isl_space_set_from_params(space);
836 space = isl_space_add_dims(space, isl_dim_set, len);
837 set = isl_set_universe(space);
839 return parametrize(set, first, n, prefix);
842 /* Tile the B loops over the tile sizes and then tile/wrap
843 * the T1 loops over the blocks.
845 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
846 __isl_take isl_union_map *sched)
848 isl_space *dim;
849 isl_map *tiling, *block_tiling;
851 dim = isl_union_map_get_space(sched);
852 tiling = tile(isl_space_copy(dim), gen->untiled_len,
853 gen->tile_first, gen->tile_len, gen->tile_size);
855 if (gen->options->wrap)
856 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
857 gen->tile_first, gen->n_grid, gen->grid_dim);
858 else
859 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
860 gen->tile_first, gen->n_grid, gen->grid_dim);
862 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
864 tiling = isl_map_apply_range(tiling, block_tiling);
866 sched = isl_union_map_apply_range(sched,
867 isl_union_map_from_map(tiling));
869 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
871 return sched;
874 /* Equate the "T1P" iterators in the tiled schedule "sched"
875 * to the block dimensions.
877 static __isl_give isl_union_map *parametrize_tiled_schedule(
878 struct gpu_gen *gen, __isl_take isl_union_map *sched)
880 isl_space *dim;
881 isl_set *par;
883 dim = isl_union_map_get_space(sched);
884 par = parametrization(dim, gen->tiled_len,
885 gen->tile_first + gen->n_grid, gen->n_grid, "b");
886 sched = isl_union_map_intersect_range(sched,
887 isl_union_set_from_set(par));
889 return sched;
892 /* Tile/wrap the P1 loops over the threads.
894 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
895 __isl_take isl_union_map *sched)
897 isl_space *dim;
898 isl_map *tiling;
899 isl_set *par;
901 dim = isl_union_map_get_space(sched);
903 if (gen->options->wrap)
904 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
905 gen->shared_len, gen->n_block, gen->block_dim);
906 else
907 tiling = tile(isl_space_copy(dim), gen->tiled_len,
908 gen->shared_len, gen->n_block, gen->block_dim);
909 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
911 sched = isl_union_map_apply_range(sched,
912 isl_union_map_from_map(tiling));
914 par = parametrization(dim, gen->thread_tiled_len,
915 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
916 gen->n_block, "t");
917 sched = isl_union_map_intersect_range(sched,
918 isl_union_set_from_set(par));
920 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
922 return sched;
925 /* If the user asked for it, scale the shared memory tile loops
926 * (T1T and T2) of "sched" by gen->tile_size[i].
927 * If we are not performing "wrapping", then additionally scale the T1P
928 * loops by gen->grid_dim[i].
930 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
931 __isl_take isl_union_map *sched)
933 int i;
934 isl_space *dim;
935 isl_basic_map *scale;
936 isl_constraint *c;
937 isl_local_space *ls;
939 if (!gen->options->scale_tile_loops)
940 return sched;
942 dim = isl_union_map_get_space(sched);
943 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
944 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
945 scale = isl_basic_map_universe(isl_space_copy(dim));
946 ls = isl_local_space_from_space(dim);
948 for (i = 0; i < gen->tiled_len; ++i) {
949 int f = 1;
951 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
952 f = gen->tile_size[i - gen->tile_first];
953 if (!gen->options->wrap)
954 f *= gen->grid_dim[i - gen->tile_first];
955 } else if (i >= gen->tile_first + gen->n_grid &&
956 i < gen->tile_first + gen->n_grid + gen->tile_len) {
957 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
960 c = isl_equality_alloc(isl_local_space_copy(ls));
961 isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
962 isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
963 scale = isl_basic_map_add_constraint(scale, c);
966 isl_local_space_free(ls);
968 sched = isl_union_map_apply_range(sched,
969 isl_union_map_from_map(isl_map_from_basic_map(scale)));
971 return sched;
974 /* If we are not performing "wrapping" and if the user asked for it,
975 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
977 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
978 __isl_take isl_union_map *sched)
980 int i;
981 isl_space *dim;
982 isl_basic_map *scale;
983 isl_constraint *c;
984 isl_local_space *ls;
986 if (gen->options->wrap)
987 return sched;
988 if (!gen->options->scale_tile_loops)
989 return sched;
991 dim = isl_union_map_get_space(sched);
992 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
993 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
994 scale = isl_basic_map_universe(isl_space_copy(dim));
995 ls = isl_local_space_from_space(dim);
997 for (i = 0; i < gen->thread_tiled_len; ++i) {
998 int f = 1;
1000 if (i >= gen->shared_len &&
1001 i < gen->shared_len + gen->n_block)
1002 f = gen->block_dim[i - gen->shared_len];
1004 c = isl_equality_alloc(isl_local_space_copy(ls));
1005 isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1006 isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1007 scale = isl_basic_map_add_constraint(scale, c);
1010 isl_local_space_free(ls);
1012 sched = isl_union_map_apply_range(sched,
1013 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1015 return sched;
1018 /* If we are not performing "wrapping" and if the user asked for it,
1019 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1021 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1022 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1024 int i;
1025 isl_space *dim;
1026 isl_basic_map *scale;
1027 isl_constraint *c;
1028 isl_local_space *ls;
1030 if (gen->options->wrap)
1031 return sched;
1032 if (!gen->options->scale_tile_loops)
1033 return sched;
1035 dim = isl_union_map_get_space(sched);
1036 dim = isl_space_add_dims(dim, isl_dim_in, len);
1037 dim = isl_space_add_dims(dim, isl_dim_out, len);
1038 scale = isl_basic_map_universe(isl_space_copy(dim));
1039 ls = isl_local_space_from_space(dim);
1041 for (i = 0; i < len; ++i) {
1042 int f = 1;
1044 if (i >= first && i < first + n_tile)
1045 f = gen->block_dim[i - first];
1047 c = isl_equality_alloc(isl_local_space_copy(ls));
1048 isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1049 isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1050 scale = isl_basic_map_add_constraint(scale, c);
1053 isl_local_space_free(ls);
1055 sched = isl_union_map_apply_range(sched,
1056 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1058 return sched;
1061 /* Add "len" parameters p[i] called prefix%d,
1062 * with bounds to 0 <= p[i] < size[i].
1064 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1065 int len, int *size, const char *prefix)
1067 int i;
1068 unsigned nparam;
1069 isl_int v;
1070 isl_space *dim;
1071 isl_basic_set *bset;
1072 isl_constraint *c;
1073 isl_local_space *ls;
1074 char name[20];
1076 nparam = isl_set_dim(set, isl_dim_param);
1077 set = isl_set_add_dims(set, isl_dim_param, len);
1079 for (i = 0; i < len; ++i) {
1080 snprintf(name, sizeof(name), "%s%d", prefix, i);
1081 set = isl_set_set_dim_name(set, isl_dim_param,
1082 nparam + i, name);
1085 dim = isl_set_get_space(set);
1086 bset = isl_basic_set_universe(isl_space_copy(dim));
1087 ls = isl_local_space_from_space(dim);
1089 isl_int_init(v);
1091 for (i = 0; i < len; ++i) {
1092 c = isl_inequality_alloc(isl_local_space_copy(ls));
1093 isl_int_set_si(v, 1);
1094 isl_constraint_set_coefficient(c, isl_dim_param, nparam + i, v);
1095 bset = isl_basic_set_add_constraint(bset, c);
1097 c = isl_inequality_alloc(isl_local_space_copy(ls));
1098 isl_int_set_si(v, -1);
1099 isl_constraint_set_coefficient(c, isl_dim_param, nparam + i, v);
1100 isl_int_set_si(v, size[i] - 1);
1101 isl_constraint_set_constant(c, v);
1102 bset = isl_basic_set_add_constraint(bset, c);
1105 isl_int_clear(v);
1106 isl_local_space_free(ls);
1108 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1111 /* Add "len" parameters p[i] called prefix%d,
1112 * with bounds to 0 <= p[i] < size[i].
1114 static __isl_give isl_set *add_bounded_parameters_dynamic(
1115 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1116 const char *prefix)
1118 int i, len;
1119 unsigned nparam;
1120 isl_space *space;
1121 isl_local_space *ls;
1122 char name[20];
1124 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1125 nparam = isl_set_dim(set, isl_dim_param);
1126 set = isl_set_add_dims(set, isl_dim_param, len);
1128 for (i = 0; i < len; ++i) {
1129 snprintf(name, sizeof(name), "%s%d", prefix, i);
1130 set = isl_set_set_dim_name(set, isl_dim_param,
1131 nparam + i, name);
1134 space = isl_space_params(isl_set_get_space(set));
1135 ls = isl_local_space_from_space(space);
1136 for (i = 0; i < len; ++i) {
1137 isl_pw_aff *param, *size_i, *zero;
1138 isl_set *bound;
1140 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1141 isl_dim_param, nparam + i);
1143 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1144 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1145 set = isl_set_intersect_params(set, bound);
1147 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1148 bound = isl_pw_aff_ge_set(param, zero);
1149 set = isl_set_intersect_params(set, bound);
1151 isl_local_space_free(ls);
1153 return set;
1156 /* Given a mapping "sched" of the form
1158 * [D -> A] -> [D -> T(A)]
1160 * apply the mapping encoded in tile->bound[i].shift_map
1161 * to the range of "sched".
1162 * The mappings in tile->bound[i].shift_map are of the form
1164 * [D -> a] -> [D -> s(D,a)]
1166 * We first compose them with a mapping
1168 * [D -> v] -> v
1170 * (If tile->bound[i].shift_map is not set, then it is assumed to be
1171 * an identity mapping and then we use this second mapping instead.)
1172 * This results in
1174 * [D -> a] -> s(D,a)
1176 * We precompose them with a projection on the i th dimension to obtain
1178 * [D -> T] -> s(D,T)
1180 * and collect these into
1182 * [D -> T] -> S(D,T)
1184 * Introducing D in the range yields
1186 * [D -> T] -> [D -> S(D,T)]
1188 * and application to "sched" yields
1190 * [D -> A] -> [D -> S(D,T(A))]
1192 static __isl_give isl_map *pre_shift(__isl_take isl_map *sched,
1193 struct gpu_array_tile *tile)
1195 int i;
1196 isl_ctx *ctx = isl_map_get_ctx(sched);
1197 isl_space *space, *space2;
1198 isl_basic_map *def;
1199 isl_map *map, *id, *pre_shift;
1201 space = isl_space_range(isl_map_get_space(sched));
1202 space2 = isl_space_from_domain(isl_space_copy(space));
1203 pre_shift = isl_map_universe(space2);
1204 space = isl_space_domain(isl_space_unwrap(space));
1205 id = isl_map_identity(isl_space_map_from_set(isl_space_copy(space)));
1206 space = isl_space_from_domain(space);
1207 space = isl_space_add_dims(space, isl_dim_out, 1);
1208 def = isl_basic_map_range_map(isl_basic_map_universe(space));
1210 for (i = 0; i < tile->n; ++i) {
1211 isl_basic_map *bmap, *drop;
1212 isl_map *proj;
1214 space = isl_space_alloc(ctx, 0, tile->n, tile->n);
1215 proj = isl_map_identity(space);
1216 proj = isl_map_project_out(proj, isl_dim_out,
1217 i + 1, tile->n - (i + 1));
1218 proj = isl_map_project_out(proj, isl_dim_out, 0, i);
1219 proj = isl_map_product(isl_map_copy(id), proj);
1221 if (!tile->bound[i].shift_map)
1222 bmap = isl_basic_map_copy(def);
1223 else {
1224 bmap = isl_basic_map_copy(tile->bound[i].shift_map);
1225 bmap = isl_basic_map_apply_range(bmap,
1226 isl_basic_map_copy(def));
1229 map = isl_map_from_basic_map(bmap);
1230 map = isl_map_apply_range(proj, map);
1231 pre_shift = isl_map_flat_range_product(pre_shift, map);
1234 isl_map_free(id);
1235 isl_basic_map_free(def);
1237 space = isl_space_domain(isl_map_get_space(pre_shift));
1238 map = isl_map_domain_map(isl_map_universe(isl_space_unwrap(space)));
1239 pre_shift = isl_map_range_product(map, pre_shift);
1241 sched = isl_map_apply_range(sched, pre_shift);
1243 return sched;
1246 /* Given an access relation to a tile of an array, construct a map that
1247 * maps each element in the space of the access relation
1248 * to a copy of the tile shifted to the origin
1249 * (based on the lower bounds in group->private_tile or group->shared_tile).
1250 * If any of the indices is strided, then
1251 * {private,shared}_tile->bound[i].shift_map is applied to the index first.
1252 * The domain space of the resulting map is that of access "access",
1253 * while the range space is anonymous.
1254 * The resulting map only encodes the mapping to the shift tile and
1255 * not the constraints of "access".
1257 * Let the space of the access relation be
1259 * D -> A
1261 * We first construct an identity relation on a wrapped copy of this space,
1262 * except that it strips off the name of array
1264 * [D -> A] -> [D -> T(A)] (1)
1266 * The bounds in tile->bound[i].lb are of the form
1268 * D -> b(D)
1270 * We collect them into
1272 * D -> B(D)
1274 * and then transform them into
1276 * [D -> T] -> T - B(D) (2)
1278 * Combining those two mappings (1) and (2) yields
1280 * [D -> A] -> T(A) - B(D)
1282 * If there are any strides, then (1) is first transformed into (1')
1284 * [D -> A] -> [D -> T'(A)] (1')
1286 * by a call to pre_shift.
1288 static __isl_give isl_map *shift_access(__isl_take isl_map *access,
1289 struct gpu_array_ref_group *group)
1291 int i;
1292 isl_space *space;
1293 isl_map *id1, *id2;
1294 isl_map *map;
1295 isl_map *shift;
1296 isl_map *sched;
1297 struct gpu_array_tile *tile;
1298 int n_index = group->array->n_index;
1300 tile = group->private_tile;
1301 if (!tile)
1302 tile = group->shared_tile;
1304 space = isl_space_domain(isl_map_get_space(access));
1305 space = isl_space_map_from_set(space);
1306 id1 = isl_map_identity(space);
1307 space = isl_space_range(isl_map_get_space(access));
1308 space = isl_space_map_from_set(space);
1309 space = isl_space_set_tuple_name(space, isl_dim_out, NULL);
1310 id2 = isl_map_identity(space);
1311 sched = isl_map_product(id1, id2);
1313 space = isl_space_unwrap(isl_space_range(isl_map_get_space(sched)));
1314 space = isl_space_from_domain(isl_space_domain(space));
1315 shift = isl_map_universe(space);
1316 for (i = 0; i < n_index; ++i) {
1317 map = isl_map_from_aff(isl_aff_copy(tile->bound[i].lb));
1318 shift = isl_map_flat_range_product(shift, map);
1321 space = isl_space_unwrap(isl_space_range(isl_map_get_space(sched)));
1322 map = isl_map_universe(space);
1323 id1 = isl_map_range_map(isl_map_copy(map));
1324 map = isl_map_domain_map(map);
1325 shift = isl_map_neg(shift);
1326 shift = isl_map_apply_range(map, shift);
1327 shift = isl_map_sum(id1, shift);
1329 for (i = 0; i < n_index; ++i)
1330 if (tile->bound[i].shift_map)
1331 break;
1333 if (i < n_index)
1334 sched = pre_shift(sched, tile);
1336 sched = isl_map_apply_range(sched, shift);
1338 isl_map_free(access);
1340 return sched;
1343 /* Given a schedule that iterates over all elements in a piece of an array,
1344 * perform tiling/wrapping over the threads.
1346 * In particular, we tile the final iterators so that the final thread
1347 * dimension runs over the final array dimension.
1348 * However, if those final iterators have only a single iteration,
1349 * we try to tile earlier iterators instead.
1351 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1352 __isl_take isl_map *sched)
1354 isl_space *dim;
1355 isl_union_map *usched;
1356 isl_map *tiling;
1357 isl_set *par;
1358 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1359 int n_tile;
1360 int first;
1362 n_tile = gen->n_block;
1363 if (n_tile > nvar) {
1364 int i;
1365 sched = isl_map_insert_dims(sched,
1366 isl_dim_out, 0, n_tile - nvar);
1367 for (i = 0; i < n_tile - nvar; ++i)
1368 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1369 nvar = n_tile;
1372 first = nvar - n_tile;
1374 for (; first > 0; first --)
1375 if (!isl_map_plain_is_fixed(sched, isl_dim_out,
1376 first + n_tile - 1, NULL))
1377 break;
1379 dim = isl_map_get_space(sched);
1380 dim = isl_space_params(dim);
1381 if (gen->options->wrap)
1382 tiling = wrap(isl_space_copy(dim), nvar, first,
1383 n_tile, gen->block_dim);
1384 else
1385 tiling = tile(isl_space_copy(dim), nvar, first,
1386 n_tile, gen->block_dim);
1387 sched = isl_map_apply_range(sched, tiling);
1389 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1390 sched = isl_map_intersect_range(sched, par);
1392 usched = isl_union_map_from_map(sched);
1393 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1394 first, n_tile);
1395 sched = isl_map_from_union_map(usched);
1397 return sched;
1400 /* Given an index expression "pa" into a tile of an array, adjust the expression
1401 * to a shift of the tile to the origin
1402 * (based on the lower bounds in "bound".
1403 * If the index is strided, then we first add
1404 * bound->shift and divide by bound->stride.
1405 * In the end, we compute the gist with respect to "domain".
1407 * All of the input expression "pa", the set "domain" and
1408 * the output are expressed in terms of the AST schedule domain.
1409 * The expressions in "bound" are expressed
1410 * in terms of the first shared_len dimensions of the schedule computed by PPCG.
1411 * The mapping "sched2shared" maps the former domain to the latter domain.
1413 static __isl_give isl_pw_aff *shift_index(__isl_take isl_pw_aff *pa,
1414 struct gpu_array_info *array,
1415 struct gpu_array_bound *bound, __isl_take isl_set *domain,
1416 __isl_take isl_map *sched2shared)
1418 isl_map *map;
1419 isl_pw_aff *tmp;
1420 isl_pw_multi_aff *pma;
1422 if (bound->shift) {
1423 map = isl_map_from_aff(isl_aff_copy(bound->shift));
1424 map = isl_map_apply_range(isl_map_copy(sched2shared), map);
1425 pma = isl_pw_multi_aff_from_map(map);
1426 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1427 isl_pw_multi_aff_free(pma);
1428 pa = isl_pw_aff_add(pa, tmp);
1429 pa = isl_pw_aff_scale_down(pa, bound->stride);
1433 map = isl_map_from_aff(isl_aff_copy(bound->lb));
1434 map = isl_map_apply_range(sched2shared, map);
1435 pma = isl_pw_multi_aff_from_map(map);
1436 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1437 isl_pw_multi_aff_free(pma);
1438 pa = isl_pw_aff_sub(pa, tmp);
1439 pa = isl_pw_aff_coalesce(pa);
1440 pa = isl_pw_aff_gist(pa, domain);
1442 return pa;
1445 /* Return the union of all read (read = 1) and/or write (write = 1)
1446 * access relations in the group.
1448 static __isl_give isl_union_map *group_access_relation(
1449 struct gpu_array_ref_group *group, int read, int write)
1451 int i;
1452 isl_union_map *access;
1454 access = isl_union_map_empty(isl_map_get_space(group->access));
1455 for (i = 0; i < group->n_ref; ++i) {
1456 isl_map *map_i;
1458 if (!((read && group->refs[i]->read) ||
1459 (write && group->refs[i]->write)))
1460 continue;
1461 map_i = isl_map_copy(group->refs[i]->access);
1462 access = isl_union_map_union(access,
1463 isl_union_map_from_map(map_i));
1466 return access;
1469 /* Return a map from the first shared_len dimensions of the computed
1470 * schedule to the values of the given index "i"
1471 * of the elements in the array tile in global memory that corresponds
1472 * to the shared memory copy.
1473 * In particular, if a is the index, then the range of the map
1475 * { D -> [a] }
1477 * is constrained as follows
1479 * tile_offset(D) <= a <= tile_offset(D) + tile_size - 1 (1)
1481 * and
1483 * 0 <= a <= array_size - 1 (2)
1486 * Note that if some stride has been detected (i.e., when
1487 * group->shared_tile->bound[i].shift is set), then offset and size (i.e.,
1488 * constraints (1)) apply to the shifted and scaled down copy of the tile.
1489 * These constraints therefore have to be mapped back to the original
1490 * array space using the inverse of the shift_map.
1492 static __isl_give isl_map *group_tile_dim(struct gpu_array_ref_group *group,
1493 int i)
1495 isl_aff *aff;
1496 isl_space *space;
1497 isl_map *map, *tile, *gt;
1498 isl_set *bound;
1500 map = isl_map_from_aff(isl_aff_copy(group->shared_tile->bound[i].lb));
1501 space = isl_space_range(isl_map_get_space(map));
1502 map = isl_map_apply_range(map, isl_map_lex_le(isl_space_copy(space)));
1503 tile = map;
1505 aff = isl_aff_copy(group->shared_tile->bound[i].lb);
1506 aff = isl_aff_add_constant(aff, group->shared_tile->bound[i].size);
1507 map = isl_map_from_aff(aff);
1508 gt = isl_map_lex_gt(space);
1509 map = isl_map_apply_range(map, isl_map_copy(gt));
1510 tile = isl_map_intersect(tile, map);
1512 if (group->shared_tile->bound[i].shift) {
1513 isl_basic_map *shift;
1514 shift = isl_basic_map_copy(group->shared_tile->bound[i].shift_map);
1515 shift = isl_basic_map_reverse(shift);
1516 tile = isl_set_unwrap(isl_set_apply(isl_map_wrap(tile),
1517 isl_map_from_basic_map(shift)));
1520 tile = isl_map_lower_bound_si(tile, isl_dim_out, 0, 0);
1522 bound = isl_set_from_pw_aff(isl_pw_aff_copy(group->array->bound[i]));
1523 bound = isl_set_apply(bound, gt);
1524 tile = isl_map_intersect_range(tile, bound);
1526 return tile;
1529 /* Return a map from the first shared_len dimensions of the computed
1530 * schedule to the array tile in
1531 * global memory that corresponds to the shared memory copy.
1533 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1535 int i;
1536 int n_index = group->array->n_index;
1537 isl_map *tile;
1539 tile = group_tile_dim(group, 0);
1540 for (i = 1; i < n_index; ++i) {
1541 isl_map *tile_i;
1543 tile_i = group_tile_dim(group, i);
1544 tile = isl_map_flat_range_product(tile, tile_i);
1547 tile = isl_map_set_tuple_name(tile, isl_dim_out, group->array->name);
1549 return tile;
1552 /* Given a mapping "sched" from the AST schedule to a domain,
1553 * return the corresponding mapping from the AST schedule to
1554 * to the first shared_len dimensions of the schedule computed by PPCG.
1556 static __isl_give isl_map *compute_sched_to_shared(struct gpu_gen *gen,
1557 __isl_take isl_map *sched)
1559 isl_union_map *umap;
1560 isl_space *space;
1561 isl_map *map;
1563 space = isl_space_range(isl_map_get_space(sched));
1564 space = isl_space_from_domain(space);
1565 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1567 umap = isl_union_map_copy(gen->shared_sched);
1568 umap = isl_union_map_apply_range(umap,
1569 isl_union_map_copy(gen->shared_proj));
1570 map = isl_union_map_extract_map(umap, space);
1571 isl_union_map_free(umap);
1573 sched = isl_map_apply_range(sched, map);
1574 sched = isl_map_detect_equalities(sched);
1576 return sched;
1579 /* Set unroll[j] if the input dimension j is involved in
1580 * the index expression represented by ma.
1582 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1583 void *user)
1585 int i, j;
1586 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1587 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1588 int *unroll = user;
1590 for (i = 0; i < n_out; ++i) {
1591 isl_aff *aff;
1593 aff = isl_multi_aff_get_aff(ma, i);
1594 for (j = 0; j < n_in; ++j)
1595 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1596 unroll[j] = 1;
1597 isl_aff_free(aff);
1600 isl_set_free(set);
1601 isl_multi_aff_free(ma);
1602 return 0;
1605 /* Given an array pos mapping input dimensions to the corresponding
1606 * output dimension, construct the corresponding map.
1608 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1609 int *pos, int len)
1611 int i;
1612 isl_constraint *c;
1613 isl_basic_map *bmap;
1614 isl_local_space *ls;
1616 dim = isl_space_add_dims(dim, isl_dim_in, len);
1617 dim = isl_space_add_dims(dim, isl_dim_out, len);
1618 bmap = isl_basic_map_universe(isl_space_copy(dim));
1619 ls = isl_local_space_from_space(dim);
1621 for (i = 0; i < len; ++i) {
1622 c = isl_equality_alloc(isl_local_space_copy(ls));
1623 isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
1624 isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i], 1);
1625 bmap = isl_basic_map_add_constraint(bmap, c);
1627 isl_local_space_free(ls);
1629 return isl_map_from_basic_map(bmap);
1632 /* Find all loops involved in any of the index expressions for any of
1633 * the private accesses, move them innermost and then mark them as
1634 * requiring unrolling by setting gen->first_unroll.
1635 * The loops involved should all be parallel because of the checks
1636 * we performed in check_private_group_access. Moving them innermost
1637 * is therefore a valid transformation.
1639 * Loops up to gen->shared_len are generated before the mapping to
1640 * threads is applied. They should therefore be ignored.
1642 * We compute the hidden equalities of the schedule first
1643 * since we will need them in our calls to isl_pw_multi_aff_from_map
1644 * and because we want to make sure that the same equalities
1645 * are also available to the code generator.
1647 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1648 __isl_take isl_union_map *sched)
1650 int i, j;
1651 int unroll[gen->thread_tiled_len];
1652 int perm[gen->thread_tiled_len];
1653 isl_space *dim;
1654 isl_map *permute;
1655 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1657 gen->first_unroll = -1;
1659 sched = isl_union_map_detect_equalities(sched);
1660 for (i = 0; i < gen->thread_tiled_len; ++i)
1661 unroll[i] = 0;
1662 for (i = 0; i < gen->prog->n_array; ++i) {
1663 struct gpu_array_info *array = &gen->prog->array[i];
1665 for (j = 0; j < array->n_group; ++j) {
1666 isl_union_map *access;
1667 isl_map *acc;
1668 isl_pw_multi_aff *pma;
1670 if (!array->groups[j]->private_tile)
1671 continue;
1673 access = group_access_relation(array->groups[j], 1, 1);
1674 access = isl_union_map_apply_domain(access,
1675 isl_union_map_copy(sched));
1677 acc = isl_map_from_union_map(access);
1678 pma = isl_pw_multi_aff_from_map(acc);
1679 isl_pw_multi_aff_foreach_piece(pma,
1680 &check_unroll, unroll);
1682 isl_pw_multi_aff_free(pma);
1686 for (i = gen->shared_len; i < len; ++i)
1687 if (unroll[i])
1688 break;
1690 if (i >= len)
1691 return sched;
1693 for (i = len; i < gen->thread_tiled_len; ++i)
1694 if (unroll[i])
1695 return sched;
1697 j = 0;
1698 for (i = 0; i < gen->shared_len; ++i)
1699 perm[i] = j++;
1700 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1701 if (!unroll[i])
1702 perm[i] = j++;
1703 gen->first_unroll = j - gen->shared_len;
1704 for (i = gen->shared_len; i < len; ++i)
1705 if (unroll[i])
1706 perm[i] = j++;
1708 dim = isl_union_map_get_space(sched);
1709 permute = permutation(dim, perm, gen->thread_tiled_len);
1710 sched = isl_union_map_apply_range(sched,
1711 isl_union_map_from_map(permute));
1713 return sched;
1716 /* Given a constraint
1718 * a(p,i) + j = g f(e)
1720 * or -a(p,i) - j = g f(e) if sign < 0,
1721 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1722 * a(p,i) is assumed to be an expression in only the parameters
1723 * and the input dimensions.
1725 static void extract_stride(__isl_keep isl_constraint *c,
1726 struct gpu_array_bound *bound, isl_int stride, int sign)
1728 int i;
1729 isl_int v;
1730 isl_space *space;
1731 unsigned nparam;
1732 unsigned nvar;
1733 isl_aff *aff;
1735 isl_int_set(bound->stride, stride);
1737 space = isl_constraint_get_space(c);
1738 space = isl_space_domain(space);
1740 nparam = isl_space_dim(space, isl_dim_param);
1741 nvar = isl_space_dim(space, isl_dim_set);
1743 isl_int_init(v);
1745 isl_constraint_get_constant(c, &v);
1746 if (sign < 0)
1747 isl_int_neg(v, v);
1748 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1749 aff = isl_aff_set_constant(aff, v);
1751 for (i = 0; i < nparam; ++i) {
1752 isl_constraint_get_coefficient(c, isl_dim_param, i, &v);
1753 if (isl_int_is_zero(v))
1754 continue;
1755 if (sign < 0)
1756 isl_int_neg(v, v);
1757 aff = isl_aff_add_coefficient(aff, isl_dim_param, i, v);
1760 for (i = 0; i < nvar; ++i) {
1761 isl_constraint_get_coefficient(c, isl_dim_in, i, &v);
1762 if (isl_int_is_zero(v))
1763 continue;
1764 if (sign < 0)
1765 isl_int_neg(v, v);
1766 aff = isl_aff_add_coefficient(aff, isl_dim_in, i, v);
1769 isl_int_clear(v);
1771 bound->shift = aff;
1774 /* Given an equality constraint of a map with a single output dimension j,
1775 * check if the constraint is of the form
1777 * a(p,i) + j = g f(e)
1779 * with a(p,i) an expression in the parameters and input dimensions
1780 * and f(e) an expression in the existentially quantified variables.
1781 * If so, and if g is larger than any such g from a previously considered
1782 * constraint, then call extract_stride to record the stride information
1783 * in bound.
1785 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1787 int i;
1788 isl_int v, stride;
1789 unsigned n_div;
1790 struct gpu_array_bound *bound = user;
1792 isl_int_init(v);
1793 isl_int_init(stride);
1795 n_div = isl_constraint_dim(c, isl_dim_div);
1796 isl_constraint_get_coefficient(c, isl_dim_out, 0, &v);
1798 if (n_div && (isl_int_is_one(v) || isl_int_is_negone(v))) {
1799 int s = isl_int_sgn(v);
1800 isl_int_set_si(stride, 0);
1801 for (i = 0; i < n_div; ++i) {
1802 isl_constraint_get_coefficient(c, isl_dim_div, i, &v);
1803 isl_int_gcd(stride, stride, v);
1805 if (!isl_int_is_zero(stride) &&
1806 isl_int_gt(stride, bound->stride))
1807 extract_stride(c, bound, stride, s);
1810 isl_int_clear(stride);
1811 isl_int_clear(v);
1813 isl_constraint_free(c);
1814 return 0;
1817 /* Given contraints on an array index i, check if we can find
1818 * a shift a(p) and a stride g such that
1820 * a(p) + i = 0 mod g
1822 * If so, record the information in bound and apply the mapping
1823 * i -> (i + a(p))/g to the array index in bounds and return
1824 * the new constraints.
1825 * If not, simply return the original constraints.
1827 * If bounds is a subset of the space
1829 * D -> i
1831 * then the bound recorded in bound->shift is of the form
1833 * D -> s(D)
1835 * with s(D) equal to a(p) above.
1836 * The mapping recorded in bound->shift_map is of the form
1838 * [D -> i] -> [D -> (i + S(D))/g]
1840 * This mapping is computed as follows.
1841 * We first introduce "i" in the domain through precomposition
1842 * with [D -> i] -> D obtaining
1844 * [D -> i] -> s(D)
1846 * Adding [D -> i] -> i produces
1848 * [D -> i] -> i + s(D)
1850 * and the domain product with [D -> i] -> D yields
1852 * [D -> i] -> [D -> i + s(D)]
1854 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1856 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1857 __isl_take isl_basic_map *bounds)
1859 isl_space *space;
1860 isl_basic_map *hull;
1861 isl_basic_map *shift, *id, *bmap, *scale;
1862 isl_basic_set *bset;
1863 isl_aff *aff;
1865 isl_int_set_si(bound->stride, -1);
1867 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1869 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1871 isl_basic_map_free(hull);
1873 if (isl_int_is_neg(bound->stride))
1874 return bounds;
1876 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1877 space = isl_basic_map_get_space(bounds);
1878 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1879 shift = isl_basic_map_apply_range(bmap, shift);
1880 space = isl_basic_map_get_space(bounds);
1881 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1882 shift = isl_basic_map_sum(id, shift);
1883 space = isl_basic_map_get_space(bounds);
1884 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1885 shift = isl_basic_map_range_product(id, shift);
1887 space = isl_space_domain(isl_basic_map_get_space(bounds));
1888 id = isl_basic_map_identity(isl_space_map_from_set(space));
1889 space = isl_space_range(isl_basic_map_get_space(bounds));
1890 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1891 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1892 aff = isl_aff_scale_down(aff, bound->stride);
1893 scale = isl_basic_map_from_aff(aff);
1894 scale = isl_basic_map_product(id, scale);
1896 bound->shift_map = isl_basic_map_apply_range(shift, scale);
1897 bmap = isl_basic_map_copy(bound->shift_map);
1898 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1899 bounds = isl_basic_set_unwrap(bset);
1901 return bounds;
1904 /* Data used in compute_array_dim_size and compute_size_in_direction.
1906 * pos is the position of the variable representing the array index,
1907 * i.e., the variable for which want to compute the size. This variable
1908 * is also the last variable in the set.
1910 struct gpu_size_info {
1911 isl_basic_set *bset;
1912 struct gpu_array_bound *bound;
1913 int pos;
1916 /* Given a constraint from the basic set describing the bounds on
1917 * an array index, check if it is a lower bound, say m i >= b(x), and,
1918 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
1919 * upper bound. If so, and if this bound is smaller than any bound
1920 * derived from earlier constraints, set the size to this bound on
1921 * the expression and the lower bound to ceil(b(x)/m).
1923 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
1925 struct gpu_size_info *size = user;
1926 unsigned nparam;
1927 unsigned n_div;
1928 isl_int v;
1930 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
1931 n_div = isl_constraint_dim(c, isl_dim_div);
1933 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div)) {
1934 isl_constraint_free(c);
1935 return 0;
1938 isl_int_init(v);
1940 isl_constraint_get_coefficient(c, isl_dim_set, size->pos, &v);
1942 if (isl_int_is_pos(v)) {
1943 isl_aff *aff;
1944 isl_aff *lb;
1945 enum isl_lp_result res;
1947 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
1948 aff = isl_aff_ceil(aff);
1950 lb = isl_aff_copy(aff);
1952 aff = isl_aff_neg(aff);
1953 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
1955 res = isl_basic_set_max(size->bset, aff, &v);
1956 isl_aff_free(aff);
1958 if (res == isl_lp_ok) {
1959 isl_int_add_ui(v, v, 1);
1960 if (isl_int_is_neg(size->bound->size) ||
1961 isl_int_lt(v, size->bound->size)) {
1962 isl_int_set(size->bound->size, v);
1963 lb = isl_aff_drop_dims(lb, isl_dim_in,
1964 size->pos, 1);
1965 isl_aff_free(size->bound->lb);
1966 size->bound->lb = isl_aff_copy(lb);
1969 isl_aff_free(lb);
1972 isl_int_clear(v);
1973 isl_constraint_free(c);
1975 return 0;
1978 /* Given a basic map "bounds" that maps parameters and input dimensions
1979 * to a single output dimension, look for an expression in the parameters
1980 * and input dimensions such that the range of the output dimension shifted
1981 * by this expression is a constant.
1983 * In particular, we currently only consider lower bounds on the output
1984 * dimension as candidate expressions.
1986 static int compute_array_dim_size(struct gpu_array_bound *bound,
1987 __isl_take isl_basic_map *bounds)
1989 struct gpu_size_info size;
1991 bounds = isl_basic_map_detect_equalities(bounds);
1992 bounds = check_stride(bound, bounds);
1994 isl_int_set_si(bound->size, -1);
1995 bound->lb = NULL;
1997 size.bound = bound;
1998 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
1999 size.bset = isl_basic_map_wrap(bounds);
2000 size.bset = isl_basic_set_flatten(size.bset);
2001 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2002 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2003 &size);
2004 isl_basic_set_free(size.bset);
2006 return isl_int_is_nonneg(bound->size) ? 0 : -1;
2009 /* Check if we can find a memory tile for the given array
2010 * based on the given accesses, and if so, put the results in "tile".
2012 * We project the accesses on each index in turn and look for a parametric
2013 * offset such that the size is constant.
2015 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2017 int i;
2019 for (i = 0; i < tile->n; ++i) {
2020 isl_map *access_i;
2021 isl_basic_map *hull;
2023 access_i = isl_map_copy(access);
2024 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2025 access_i = isl_map_project_out(access_i, isl_dim_out,
2026 1, tile->n - (i + 1));
2027 access_i = isl_map_compute_divs(access_i);
2028 hull = isl_map_simple_hull(access_i);
2029 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2030 return 0;
2033 return 1;
2036 /* Construct a map with input the shared tile loops and the loops that
2037 * will be wrapped around the threads that relates these later loops
2038 * to the thread indices and then projects them out.
2040 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2042 isl_map *priv;
2043 isl_map *tiling;
2044 isl_map *proj;
2045 isl_set *par;
2046 isl_space *dim;
2048 dim = isl_union_map_get_space(gen->shared_sched);
2050 if (gen->options->wrap)
2051 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2052 gen->shared_len, gen->n_block, gen->block_dim);
2053 else
2054 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2055 gen->shared_len, gen->n_block, gen->block_dim);
2057 priv = tiling;
2059 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2060 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2061 gen->n_block, "t");
2063 priv = isl_map_align_params(priv, isl_set_get_space(par));
2064 priv = isl_map_intersect_range(priv, par);
2066 dim = isl_map_get_space(priv);
2067 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2068 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2069 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2070 gen->shared_len);
2072 priv = isl_map_apply_range(priv, proj);
2074 return priv;
2077 /* Construct a map from domain_dim to domain_dim that increments
2078 * the dimension at position "pos" and leaves all other dimensions
2079 * constant.
2081 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2083 int i;
2084 int len = isl_space_dim(domain_dim, isl_dim_set);
2085 isl_space *dim;
2086 isl_basic_map *next;
2087 isl_local_space *ls;
2089 dim = isl_space_map_from_set(domain_dim);
2090 next = isl_basic_map_universe(isl_space_copy(dim));
2091 ls = isl_local_space_from_space(dim);
2093 for (i = 0; i < len; ++i) {
2094 isl_constraint *c;
2096 c = isl_equality_alloc(isl_local_space_copy(ls));
2097 isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2098 isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2099 if (i == pos)
2100 isl_constraint_set_constant_si(c, 1);
2101 next = isl_basic_map_add_constraint(next, c);
2104 isl_local_space_free(ls);
2106 return isl_map_from_basic_map(next);
2109 /* Check if the given access is coalesced.
2110 * That is, check whether incrementing the dimension that will get
2111 * wrapped over the last thread index results in incrementing
2112 * the last array index.
2114 * This function is only called for access relations without reuse.
2116 static int access_is_coalesced(struct gpu_gen *gen,
2117 __isl_keep isl_union_map *access)
2119 isl_space *dim;
2120 isl_map *access_map;
2121 isl_map *next_thread_x;
2122 isl_map *next_element;
2123 isl_map *map;
2124 int coalesced;
2126 access = isl_union_map_copy(access);
2127 access = isl_union_map_apply_domain(access,
2128 isl_union_map_copy(gen->tiled_sched));
2129 access_map = isl_map_from_union_map(access);
2131 dim = isl_map_get_space(access_map);
2132 dim = isl_space_domain(dim);
2133 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2135 dim = isl_map_get_space(access_map);
2136 dim = isl_space_range(dim);
2137 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2139 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2140 map = isl_map_apply_range(map, access_map);
2142 coalesced = isl_map_is_subset(map, next_element);
2144 isl_map_free(next_element);
2145 isl_map_free(map);
2147 return coalesced;
2150 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2151 * dimensions of the computed schedule, check if it is bijective for
2152 * fixed values of the first gen->shared_len dimensions.
2153 * We perform this check by equating these dimensions to parameters.
2155 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2157 int res;
2158 isl_set *par;
2159 isl_space *space;
2161 access = isl_map_copy(access);
2162 space = isl_space_params(isl_map_get_space(access));
2163 par = parametrization(space, gen->shared_len + gen->n_block,
2164 0, gen->shared_len, "s");
2165 access = isl_map_intersect_domain(access, par);
2166 res = isl_map_is_bijective(access);
2167 isl_map_free(access);
2169 return res;
2172 /* Look for the last shared tile loop that affects the offset of "tile"
2173 * and return the result.
2174 * If there is no such loop, then return the index of the loop
2175 * before the first shared tile loop, in particular gen->tile_first - 1.
2177 static int compute_tile_last_shared(struct gpu_gen *gen,
2178 struct gpu_array_tile *tile)
2180 int i, j;
2182 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2183 for (i = 0; i < tile->n; ++i) {
2184 isl_aff *lb;
2185 isl_aff *shift;
2187 lb = tile->bound[i].lb;
2188 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2189 break;
2191 shift = tile->bound[i].shift;
2192 if (!shift)
2193 continue;
2194 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2195 break;
2197 if (i < tile->n)
2198 break;
2201 return j;
2204 /* Look for the last shared tile loop that affects the offset of the
2205 * shared or private tile and store the result in group->last_shared.
2206 * If there is no such loop, then group->last_shared is set to a value
2207 * before the first shared tile loop, in particular gen->tile_first - 1.
2208 * If there is no tile defined on the array reference group,
2209 * then set group->last_shared to gen->shared_len - 1.
2211 static void set_last_shared(struct gpu_gen *gen,
2212 struct gpu_array_ref_group *group)
2214 struct gpu_array_tile *tile;
2216 group->last_shared = gen->shared_len - 1;
2218 tile = group->private_tile;
2219 if (!tile)
2220 tile = group->shared_tile;
2221 if (!tile)
2222 return;
2224 group->last_shared = compute_tile_last_shared(gen, tile);
2227 /* Compute a privatized copy of all access relations from reference groups that
2228 * are mapped to private memory and store the result in gen->privatization.
2230 static void compute_private_access(struct gpu_gen *gen)
2232 int i, j;
2233 isl_union_map *private;
2235 if (!gen->options->use_private_memory)
2236 return;
2238 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2240 for (i = 0; i < gen->prog->n_array; ++i) {
2241 struct gpu_array_info *array = &gen->prog->array[i];
2243 if (gpu_array_is_read_only_scalar(array))
2244 continue;
2246 for (j = 0; j < array->n_group; ++j) {
2247 if (!array->groups[j]->private_tile)
2248 continue;
2250 private = isl_union_map_union(private,
2251 group_access_relation(array->groups[j], 1, 1));
2255 if (isl_union_map_is_empty(private))
2256 isl_union_map_free(private);
2257 else {
2258 isl_union_map *priv;
2260 private = isl_union_map_apply_domain(private,
2261 isl_union_map_copy(gen->shared_sched));
2262 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2263 private = isl_union_map_apply_domain(private, priv);
2264 gen->private_access = private;
2268 /* Compute the size of the tile specified by "tile"
2269 * in number of elements and put the result in *size.
2271 static void tile_size(struct gpu_array_tile *tile, isl_int *size)
2273 int i;
2275 isl_int_set_si(*size, 1);
2277 for (i = 0; i < tile->n; ++i)
2278 isl_int_mul(*size, *size, tile->bound[i].size);
2281 /* If max_shared_memory is not set to infinity (-1), then make
2282 * sure that the total amount of shared memory required by the
2283 * array reference groups mapped to shared memory is no larger
2284 * than this maximum.
2286 * We apply a greedy approach and discard (keep in global memory)
2287 * those groups that would result in a total memory size that
2288 * is larger than the maximum.
2290 static void check_shared_memory_bound(struct gpu_gen *gen)
2292 int i, j;
2293 isl_int left, size;
2295 if (gen->options->max_shared_memory < 0)
2296 return;
2298 isl_int_init(left);
2299 isl_int_init(size);
2300 isl_int_set_si(left, gen->options->max_shared_memory);
2302 for (i = 0; i < gen->prog->n_array; ++i) {
2303 struct gpu_array_info *array = &gen->prog->array[i];
2305 for (j = 0; j < array->n_group; ++j) {
2306 struct gpu_array_ref_group *group;
2308 group = array->groups[j];
2309 if (!group->shared_tile)
2310 continue;
2312 tile_size(group->shared_tile, &size);
2313 isl_int_mul_ui(size, size, array->size);
2315 if (isl_int_le(size, left)) {
2316 isl_int_sub(left, left, size);
2317 continue;
2320 group->shared_tile = free_tile(group->shared_tile);
2324 isl_int_clear(size);
2325 isl_int_clear(left);
2328 /* Fill up the groups array with singleton groups, i.e., one group
2329 * per reference, initializing the array, access, write, n_ref and refs fields.
2330 * In particular the access field is initialized to the scheduled
2331 * access relation of the array reference.
2333 * Return the number of elements initialized, i.e., the number of
2334 * active references in the current kernel.
2336 static int populate_array_references(struct gpu_array_info *array,
2337 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2339 int i;
2340 int n;
2341 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2343 n = 0;
2344 for (i = 0; i < array->n_ref; ++i) {
2345 isl_union_map *umap;
2346 isl_map *map;
2347 struct gpu_array_ref_group *group;
2348 struct gpu_stmt_access *access = array->refs[i];
2350 map = isl_map_copy(access->access);
2351 umap = isl_union_map_from_map(map);
2352 umap = isl_union_map_apply_domain(umap,
2353 isl_union_map_copy(sched));
2355 if (isl_union_map_is_empty(umap)) {
2356 isl_union_map_free(umap);
2357 continue;
2360 map = isl_map_from_union_map(umap);
2361 map = isl_map_detect_equalities(map);
2363 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2364 assert(group);
2365 group->array = array;
2366 group->access = map;
2367 group->write = access->write;
2368 group->refs = &array->refs[i];
2369 group->n_ref = 1;
2371 groups[n++] = group;
2374 return n;
2377 /* If group->n_ref == 1, then group->refs was set by
2378 * populate_array_references to point directly into
2379 * group->array->refs and should not be freed.
2380 * If group->n_ref > 1, then group->refs was set by join_groups
2381 * to point to a newly allocated array.
2383 static void free_array_ref_group(struct gpu_array_ref_group *group)
2385 if (!group)
2386 return;
2387 free_tile(group->shared_tile);
2388 free_tile(group->private_tile);
2389 isl_map_free(group->access);
2390 if (group->n_ref > 1)
2391 free(group->refs);
2392 free(group);
2395 /* Given a map where the input dimensions represent the tile loops,
2396 * eliminate the innermost of those that have a fixed value
2397 * until we reach one that does not (obviously) have a fixed value.
2399 static __isl_give isl_map *eliminate_fixed_inner_loops(
2400 __isl_take isl_map *access)
2402 int i, n;
2404 n = isl_map_dim(access, isl_dim_in);
2406 for (i = n - 1; i >= 0; --i) {
2407 if (!isl_map_plain_is_fixed(access, isl_dim_in, i, NULL))
2408 break;
2409 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2411 return access;
2414 /* Check if the access relations of group1 and group2 overlap within
2415 * the innermost loop. In particular, ignore any inner dimension
2416 * with a fixed value.
2417 * The copying to and from shared memory will be performed within
2418 * the innermost actual loop so we are only allowed to consider
2419 * the dimensions up to that innermost loop while checking whether
2420 * two access relations overlap.
2422 static int accesses_overlap(struct gpu_array_ref_group *group1,
2423 struct gpu_array_ref_group *group2)
2425 int empty;
2426 isl_map *access1, *access2;
2428 access1 = isl_map_copy(group1->access);
2429 access1 = eliminate_fixed_inner_loops(access1);
2430 access2 = isl_map_copy(group2->access);
2431 access2 = eliminate_fixed_inner_loops(access2);
2432 access1 = isl_map_intersect(access1, access2);
2433 empty = isl_map_is_empty(access1);
2434 isl_map_free(access1);
2436 return !empty;
2439 /* Combine the given two groups into a single group, containing
2440 * the references of both groups.
2442 static struct gpu_array_ref_group *join_groups(
2443 struct gpu_array_ref_group *group1,
2444 struct gpu_array_ref_group *group2)
2446 int i;
2447 isl_ctx *ctx;
2448 struct gpu_array_ref_group *group;
2450 ctx = isl_map_get_ctx(group1->access);
2451 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2452 assert(group);
2453 group->array = group1->array;
2454 group->access = isl_map_union(isl_map_copy(group1->access),
2455 isl_map_copy(group2->access));
2456 group->write = group1->write || group2->write;
2457 group->n_ref = group1->n_ref + group2->n_ref;
2458 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2459 group->n_ref);
2460 assert(group->refs);
2461 for (i = 0; i < group1->n_ref; ++i)
2462 group->refs[i] = group1->refs[i];
2463 for (i = 0; i < group2->n_ref; ++i)
2464 group->refs[group1->n_ref + i] = group2->refs[i];
2466 return group;
2469 /* Combine the given two groups into a single group and free
2470 * the original two groups.
2472 static struct gpu_array_ref_group *join_groups_and_free(
2473 struct gpu_array_ref_group *group1,
2474 struct gpu_array_ref_group *group2)
2476 struct gpu_array_ref_group *group;
2478 group = join_groups(group1, group2);
2479 free_array_ref_group(group1);
2480 free_array_ref_group(group2);
2481 return group;
2484 /* Compute the private and/or shared memory tiles for the array
2485 * reference group "group" of array "array".
2487 * If the array is a read-only scalar or if the user requested
2488 * not to use shared or private memory, then we do not need to do anything.
2490 * We only try to compute a shared memory tile if there is any reuse
2491 * or if the access is not coalesced.
2493 * For computing a private memory tile, we also require that there is
2494 * some reuse. Moreover, we require that the access is private
2495 * to the thread. That is, we check that any given array element
2496 * is only accessed by a single thread.
2497 * We compute an access relation that maps the shared tile loop iterators
2498 * and the shared point loop iterators that will be wrapped over the
2499 * threads to the array elements.
2500 * We actually check that those iterators that will be wrapped
2501 * partition the array space. This check is stricter than necessary
2502 * since several iterations may be mapped onto the same thread
2503 * and then they could be allowed to access the same memory elements,
2504 * but our check does not allow this situation.
2506 * We also check that the index expression only depends on parallel
2507 * loops. That way, we can move those loops innermost and unroll them.
2508 * Again, we use a test that is stricter than necessary.
2509 * We actually check whether the index expression only depends
2510 * on the iterators that are wrapped over the threads.
2511 * These are necessarily parallel, but there may be more parallel loops.
2513 * Combining the injectivity of the first test with the single-valuedness
2514 * of the second test, we simply test for bijectivity.
2516 * If it turns out we can use registers, we compute the private memory
2517 * tile size using can_tile, after introducing a dependence
2518 * on the thread indices.
2520 static void compute_group_bounds_core(struct gpu_gen *gen,
2521 struct gpu_array_ref_group *group)
2523 isl_ctx *ctx = isl_space_get_ctx(group->array->dim);
2524 isl_union_map *access;
2525 int n_index = group->array->n_index;
2526 int no_reuse;
2527 isl_map *acc;
2529 if (!gen->options->use_shared_memory &&
2530 !gen->options->use_private_memory)
2531 return;
2532 if (gpu_array_is_read_only_scalar(group->array))
2533 return;
2535 access = group_access_relation(group, 1, 1);
2536 no_reuse = isl_union_map_is_injective(access);
2538 if (!no_reuse || !access_is_coalesced(gen, access)) {
2539 group->shared_tile = create_tile(ctx, group->array->n_index);
2540 if (!can_tile(group->access, group->shared_tile))
2541 group->shared_tile = free_tile(group->shared_tile);
2544 if (no_reuse) {
2545 isl_union_map_free(access);
2546 return;
2549 access = isl_union_map_apply_domain(access,
2550 isl_union_map_copy(gen->shared_sched));
2552 acc = isl_map_from_union_map(access);
2554 if (!access_is_bijective(gen, acc)) {
2555 isl_map_free(acc);
2556 return;
2559 group->private_tile = create_tile(gen->ctx, n_index);
2560 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2561 if (!can_tile(acc, group->private_tile))
2562 group->private_tile = free_tile(group->private_tile);
2564 isl_map_free(acc);
2567 /* Compute the private and/or shared memory tiles for the array
2568 * reference group "group" of array "array" and set last_shared.
2570 static void compute_group_bounds(struct gpu_gen *gen,
2571 struct gpu_array_ref_group *group)
2573 compute_group_bounds_core(gen, group);
2574 set_last_shared(gen, group);
2577 /* If two groups have overlapping access relations (as determined by
2578 * the "overlap" function) and if one of them involves a write,
2579 * then merge the two groups into one.
2580 * If "compute_bounds" is set, then call compute_group_bounds
2581 * on the merged groups.
2583 * Return the updated number of groups.
2585 static int group_writes(struct gpu_gen *gen,
2586 int n, struct gpu_array_ref_group **groups,
2587 int (*overlap)(struct gpu_array_ref_group *group1,
2588 struct gpu_array_ref_group *group2), int compute_bounds)
2590 int i, j;
2592 for (i = 0; i < n; ++i) {
2593 for (j = n - 1; j > i; --j) {
2594 if (!groups[i]->write && !groups[j]->write)
2595 continue;
2597 if (!overlap(groups[i], groups[j]))
2598 continue;
2600 groups[i] = join_groups_and_free(groups[i], groups[j]);
2601 if (compute_bounds)
2602 compute_group_bounds(gen, groups[i]);
2603 if (j != n - 1)
2604 groups[j] = groups[n - 1];
2605 n--;
2609 return n;
2612 /* If two groups have overlapping access relations (within the innermost
2613 * loop) and if one of them involves a write, then merge the two groups
2614 * into one.
2616 * Return the updated number of groups.
2618 static int group_overlapping_writes(struct gpu_gen *gen,
2619 int n, struct gpu_array_ref_group **groups)
2621 return group_writes(gen, n, groups, &accesses_overlap, 0);
2624 /* Check if the access relations of group1 and group2 overlap within
2625 * the outermost min(group1->last_shared, group2->last_shared) loops.
2627 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2628 struct gpu_array_ref_group *group2)
2630 int last_shared;
2631 int dim;
2632 int empty;
2633 isl_map *map_i, *map_j, *map;
2635 last_shared = group1->last_shared;
2636 if (group2->last_shared < last_shared)
2637 last_shared = group2->last_shared;
2638 map_i = isl_map_copy(group1->access);
2639 dim = isl_map_dim(map_i, isl_dim_in);
2640 map_i = isl_map_eliminate(map_i, isl_dim_in,
2641 last_shared + 1, dim - (last_shared + 1));
2642 map_j = isl_map_copy(group2->access);
2643 map_j = isl_map_eliminate(map_j, isl_dim_in,
2644 last_shared + 1, dim - (last_shared + 1));
2645 map = isl_map_intersect(map_i, map_j);
2646 empty = isl_map_is_empty(map);
2647 isl_map_free(map);
2649 return !empty;
2652 /* If two groups have overlapping access relations (within the outer
2653 * last_shared loops) and if one of them involves a write,
2654 * then merge the two groups into one.
2656 * Return the updated number of groups.
2658 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2659 struct gpu_array_ref_group **groups)
2661 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2664 /* Is the size of the tile specified by "tile" smaller than the sum of
2665 * the sizes of the tiles specified by "tile1" and "tile2"?
2667 static int smaller_tile(struct gpu_array_tile *tile,
2668 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2670 int smaller;
2671 isl_int size, size1, size2;
2673 isl_int_init(size);
2674 isl_int_init(size1);
2675 isl_int_init(size2);
2677 tile_size(tile, &size);
2678 tile_size(tile1, &size1);
2679 tile_size(tile2, &size2);
2681 isl_int_sub(size, size, size1);
2682 isl_int_sub(size, size, size2);
2683 smaller = isl_int_is_neg(size);
2685 isl_int_clear(size2);
2686 isl_int_clear(size1);
2687 isl_int_clear(size);
2689 return smaller;
2692 /* Given an initial grouping of array references and shared memory tiles
2693 * for each group that allows for a shared memory tile, merge two groups
2694 * if both have a shared memory tile, the merged group also has
2695 * a shared memory tile and the size of the tile for the merge group
2696 * is smaller than the sum of the tile sizes of the individual groups.
2698 * If merging two groups decreases the "last_shared" dimension of
2699 * one or both of the two groups, then we need to check for overlapping
2700 * writes again.
2702 * Return the number of groups after merging.
2704 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2705 struct gpu_array_info *array, int n,
2706 struct gpu_array_ref_group **groups)
2708 int i, j;
2709 int recompute_overlap = 0;
2710 isl_ctx *ctx = isl_space_get_ctx(array->dim);
2712 for (i = 0; i < n; ++i) {
2713 if (!groups[i]->shared_tile)
2714 continue;
2715 for (j = n - 1; j > i; --j) {
2716 isl_map *map;
2717 int empty;
2718 struct gpu_array_ref_group *group;
2720 if (!groups[j]->shared_tile)
2721 continue;
2723 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2724 isl_map_copy(groups[j]->access));
2725 empty = isl_map_is_empty(map);
2726 isl_map_free(map);
2728 if (empty)
2729 continue;
2731 group = join_groups(groups[i], groups[j]);
2732 compute_group_bounds(gen, group);
2733 if (!group->shared_tile ||
2734 !smaller_tile(group->shared_tile,
2735 groups[i]->shared_tile,
2736 groups[j]->shared_tile)) {
2737 free_array_ref_group(group);
2738 continue;
2741 if (group->last_shared < groups[i]->last_shared ||
2742 group->last_shared < groups[j]->last_shared)
2743 recompute_overlap = 1;
2744 free_array_ref_group(groups[i]);
2745 free_array_ref_group(groups[j]);
2746 groups[i] = group;
2747 if (j != n - 1)
2748 groups[j] = groups[n - 1];
2749 n--;
2753 if (recompute_overlap)
2754 n = group_last_shared_overlapping_writes(gen, n, groups);
2755 return n;
2758 /* Set array->n_group and array->groups to n and groups.
2760 * Additionally, set the "nr" field of each group
2761 * and the "group" field of each reference in each group.
2763 static void set_array_groups(struct gpu_array_info *array,
2764 int n, struct gpu_array_ref_group **groups)
2766 int i, j;
2768 array->n_group = n;
2769 array->groups = groups;
2771 for (i = 0; i < n; ++i) {
2772 groups[i]->nr = i;
2774 for (j = 0; j < groups[i]->n_ref; ++j)
2775 groups[i]->refs[j]->group = i;
2779 /* Group array references that should be considered together when
2780 * deciding whether to access them from private, shared or global memory.
2782 * In particular, if two array references overlap and if one of them
2783 * is a write, then the two references are grouped together.
2784 * We first perform an initial grouping based only on the access relation.
2785 * After computing shared and private memory tiles, we check for
2786 * overlapping writes again, but this time taking into account
2787 * the "last_shared" property.
2789 * Furthermore, if two groups admit a shared memory tile and if the
2790 * combination of the two also admits a shared memory tile, we merge
2791 * the two groups.
2793 static void group_array_references(struct gpu_gen *gen,
2794 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
2796 int i;
2797 int n;
2798 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2799 struct gpu_array_ref_group **groups;
2801 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
2802 array->n_ref);
2803 assert(groups);
2805 n = populate_array_references(array, sched, groups);
2807 n = group_overlapping_writes(gen, n, groups);
2809 for (i = 0; i < n; ++i)
2810 compute_group_bounds(gen, groups[i]);
2812 n = group_last_shared_overlapping_writes(gen, n, groups);
2814 n = group_common_shared_memory_tile(gen, array, n, groups);
2816 set_array_groups(array, n, groups);
2819 /* Take tiled_sched, project it onto the shared tile loops and
2820 * the loops that will be wrapped over the threads and
2821 * store the result in gen->shared_sched.
2822 * Also compute a projection that projects out the loops that will be
2823 * wrapped over the threads and store this projection in gen->shared_proj.
2825 static void compute_shared_sched(struct gpu_gen *gen)
2827 isl_space *dim;
2828 isl_map *proj;
2829 isl_set *par;
2830 isl_union_map *sched;
2832 sched = isl_union_map_copy(gen->tiled_sched);
2834 dim = isl_union_map_get_space(sched);
2835 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
2836 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
2838 dim = isl_union_map_get_space(sched);
2839 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
2841 gen->shared_sched = sched;
2842 gen->shared_proj = isl_union_map_from_map(proj);
2845 /* Group references of all arrays in the program.
2847 static void group_references(struct gpu_gen *gen)
2849 int i;
2850 isl_union_map *sched;
2852 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2853 isl_union_map_copy(gen->shared_proj));
2855 for (i = 0; i < gen->prog->n_array; ++i)
2856 group_array_references(gen, &gen->prog->array[i], sched);
2858 isl_union_map_free(sched);
2861 /* Free all array information that is local to the current kernel.
2863 static void free_local_array_info(struct gpu_gen *gen)
2865 int i, j;
2867 for (i = 0; i < gen->prog->n_array; ++i) {
2868 struct gpu_array_info *array = &gen->prog->array[i];
2870 for (j = 0; j < array->n_group; ++j)
2871 free_array_ref_group(array->groups[j]);
2872 free(array->groups);
2876 /* Compute the effective grid size as a list of the sizes in each dimension.
2878 * The grid size specified by the user or set by default
2879 * in read_grid_sizes() and applied in tile_schedule(),
2880 * may be too large for the given code in the sense that
2881 * it may contain blocks that don't need to execute anything.
2882 * We therefore don't return this grid size, but instead the
2883 * smallest grid size that ensures that all blocks that actually
2884 * execute code are included in the grid.
2886 * We first extract a description of the grid, i.e., the possible values
2887 * of the block ids, from gen->tiled_sched.
2888 * The block ids are parameters in gen->tiled_sched.
2889 * We simply need to change them into set dimensions.
2891 * Then, for each block dimension, we compute the maximal value of the block id
2892 * and add one.
2894 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
2895 struct ppcg_kernel *kernel)
2897 int i;
2898 isl_set *grid;
2899 isl_multi_pw_aff *mpa;
2901 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
2902 grid = isl_set_from_params(grid);
2903 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
2904 for (i = 0; i < gen->n_grid; ++i) {
2905 int pos;
2906 char name[20];
2908 snprintf(name, sizeof(name), "b%d", i);
2909 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
2910 assert(pos >= 0);
2911 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
2912 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
2915 mpa = isl_multi_pw_aff_zero(isl_set_get_space(grid));
2916 for (i = 0; i < gen->n_grid; ++i) {
2917 isl_space *space;
2918 isl_aff *one;
2919 isl_pw_aff *bound;
2921 bound = isl_set_dim_max(isl_set_copy(grid), i);
2922 bound = isl_pw_aff_coalesce(bound);
2923 bound = isl_pw_aff_gist(bound, isl_set_copy(kernel->context));
2925 space = isl_pw_aff_get_domain_space(bound);
2926 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2927 one = isl_aff_add_constant_si(one, 1);
2928 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
2929 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
2931 isl_set_free(grid);
2933 return mpa;
2936 void ppcg_kernel_free(void *user)
2938 struct ppcg_kernel *kernel = user;
2939 int i;
2941 if (!kernel)
2942 return;
2944 isl_multi_pw_aff_free(kernel->grid_size);
2945 isl_set_free(kernel->context);
2946 isl_union_set_free(kernel->arrays);
2947 isl_space_free(kernel->space);
2948 isl_ast_node_free(kernel->tree);
2950 for (i = 0; i < kernel->n_array; ++i)
2951 isl_pw_aff_list_free(kernel->array[i].bound);
2952 free(kernel->array);
2954 for (i = 0; i < kernel->n_var; ++i) {
2955 free(kernel->var[i].name);
2956 isl_vec_free(kernel->var[i].size);
2958 free(kernel->var);
2960 free(kernel);
2963 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
2964 struct ppcg_kernel_var *var)
2966 int j;
2967 struct gpu_array_tile *tile;
2968 isl_printer *p;
2969 char *name;
2971 var->array = group->array;
2973 tile = group->private_tile;
2974 var->type = ppcg_access_private;
2975 if (!tile) {
2976 tile = group->shared_tile;
2977 var->type = ppcg_access_shared;
2980 p = isl_printer_to_str(ctx);
2981 p = print_array_name(p, group);
2982 var->name = isl_printer_get_str(p);
2983 isl_printer_free(p);
2985 var->size = isl_vec_alloc(ctx, group->array->n_index);
2987 for (j = 0; j < group->array->n_index; ++j)
2988 var->size = isl_vec_set_element(var->size, j,
2989 tile->bound[j].size);
2992 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
2994 int i, j, n;
2996 n = 0;
2997 for (i = 0; i < gen->prog->n_array; ++i) {
2998 struct gpu_array_info *array = &gen->prog->array[i];
3000 for (j = 0; j < array->n_group; ++j) {
3001 struct gpu_array_ref_group *group = array->groups[j];
3002 if (group->private_tile || group->shared_tile)
3003 ++n;
3007 kernel->n_var = n;
3008 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3009 assert(kernel->var);
3011 n = 0;
3012 for (i = 0; i < gen->prog->n_array; ++i) {
3013 struct gpu_array_info *array = &gen->prog->array[i];
3015 for (j = 0; j < array->n_group; ++j) {
3016 struct gpu_array_ref_group *group = array->groups[j];
3017 if (!group->private_tile && !group->shared_tile)
3018 continue;
3019 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3020 ++n;
3025 /* The sizes of the arrays on the host that have been computed by
3026 * extract_array_info may depend on the parameters. Use the extra
3027 * constraints on the parameters that are valid at "host_domain"
3028 * to simplify these expressions and store the results in kernel->array.
3030 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3031 __isl_keep isl_set *host_domain)
3033 int i, j;
3034 isl_set *context;
3036 kernel->array = isl_calloc_array(gen->ctx,
3037 struct gpu_local_array_info, gen->prog->n_array);
3038 assert(kernel->array);
3039 kernel->n_array = gen->prog->n_array;
3041 context = isl_set_copy(host_domain);
3042 context = isl_set_params(context);
3044 for (i = 0; i < gen->prog->n_array; ++i) {
3045 struct gpu_array_info *array = &gen->prog->array[i];
3046 isl_pw_aff_list *local;
3048 if (array->n_group == 0)
3049 continue;
3051 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3053 for (j = 0; j < array->n_index; ++j) {
3054 isl_pw_aff *pwaff;
3056 pwaff = isl_pw_aff_copy(array->bound[j]);
3057 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3058 local = isl_pw_aff_list_add(local, pwaff);
3061 kernel->array[i].bound = local;
3063 isl_set_free(context);
3066 /* Find the element in gen->stmt that has the given "id".
3067 * Return NULL if no such gpu_stmt can be found.
3069 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3071 int i;
3073 for (i = 0; i < prog->n_stmts; ++i) {
3074 if (id == prog->stmts[i].id)
3075 break;
3078 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3081 /* Set gen->tile_len and gen->n_parallel to those of the statement
3082 * affected by the first map (part of the schedule)
3083 * on which this function is called.
3084 * Because of the way the schedule is constructed, the other statements
3085 * in the list, if any, should have the same values for these properties.
3087 static int extract_tile_len(__isl_take isl_map *map, void *user)
3089 struct gpu_gen *gen = (struct gpu_gen *) user;
3090 isl_id *id;
3091 struct gpu_stmt *stmt;
3093 id = isl_map_get_tuple_id(map, isl_dim_in);
3094 stmt = find_stmt(gen->prog, id);
3095 isl_id_free(id);
3097 isl_map_free(map);
3099 if (!stmt)
3100 isl_die(gen->ctx, isl_error_unknown,
3101 "statement not found", return -1);
3103 gen->tile_len = stmt->tile_len;
3104 gen->n_parallel = stmt->n_parallel;
3106 return -1;
3109 void ppcg_kernel_stmt_free(void *user)
3111 int i;
3112 struct ppcg_kernel_stmt *stmt = user;
3114 if (!stmt)
3115 return;
3117 switch (stmt->type) {
3118 case ppcg_kernel_copy:
3119 isl_ast_expr_free(stmt->u.c.index);
3120 isl_ast_expr_free(stmt->u.c.local_index);
3121 break;
3122 case ppcg_kernel_domain:
3123 for (i = 0; i < stmt->u.d.n_access; ++i) {
3124 isl_ast_expr_list_free(stmt->u.d.access[i].index);
3125 free(stmt->u.d.access[i].local_name);
3127 free(stmt->u.d.access);
3128 break;
3129 case ppcg_kernel_sync:
3130 break;
3133 free(stmt);
3136 /* Set the options of "context" to
3138 * { space -> [x] : x >= first }
3140 static __isl_give isl_ast_build *set_unroll(
3141 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3142 int first)
3144 isl_ctx *ctx;
3145 isl_map *unroll;
3146 isl_union_map *opt;
3148 ctx = isl_ast_build_get_ctx(build);
3150 space = isl_space_from_domain(space);
3151 space = isl_space_add_dims(space, isl_dim_out, 1);
3152 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3153 unroll = isl_map_universe(space);
3154 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3155 opt = isl_union_map_from_map(unroll);
3157 build = isl_ast_build_set_options(build, opt);
3159 return build;
3162 /* Return a list of isl_ids of the form "prefix%d".
3164 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3165 int n, const char *prefix)
3167 int i;
3168 char name[10];
3169 isl_id_list *names;
3171 names = isl_id_list_alloc(ctx, n);
3172 for (i = 0; i < n; ++i) {
3173 isl_id *id;
3175 snprintf(name, sizeof(name), "%s%d", prefix, i);
3176 id = isl_id_alloc(ctx, name, NULL);
3177 names = isl_id_list_add(names, id);
3180 return names;
3183 /* Extend the schedule "schedule" with the part of "extension"
3184 * starting at "first" up to "len".
3186 static __isl_give isl_union_map *extend_schedule(
3187 __isl_take isl_union_map *schedule,
3188 __isl_take isl_union_map *extension, int first, int len)
3190 isl_space *space;
3191 isl_map *proj;
3192 isl_union_map *umap;
3193 isl_set *set;
3195 space = isl_union_map_get_space(schedule);
3196 space = isl_space_set_from_params(space);
3197 space = isl_space_add_dims(space, isl_dim_set, len);
3198 proj = isl_set_identity(isl_set_universe(space));
3199 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3200 extension = isl_union_map_apply_range(extension,
3201 isl_union_map_from_map(proj));
3203 schedule = isl_union_map_range_product(schedule, extension);
3205 return schedule;
3208 /* This function is called for each access to an array in each instance
3209 * in the kernel of some statement in the original code.
3210 * Replace that access by an access to global, shared or private memory
3211 * and store the results in *kernel_access.
3213 * Since the array in shared or private memory is just
3214 * a shifted copy of part of the original array, we simply need
3215 * to subtract the lower bound, which was computed in can_tile.
3216 * If any of the indices is strided, then we first add
3217 * shared_tile->bound[i].shift and divide by shared_tile->bound[i].stride.
3219 * If the given array is accessed directly from global memory,
3220 * we don't need to perform any shifting and simply simplify
3221 * the expression in the context of the domain instead.
3223 * If the array space (range of access) has no name, then we are
3224 * accessing an iterator in the original program.
3226 * The input stmt_access->access relation maps the iteration domain
3227 * of the current statement to an array element.
3228 * The first step is to reformulate
3229 * this access relation in terms of the loop iterators of the generated
3230 * code through precomposition with gen->stmt_it.
3232 * The expressions in "tile" are formulated in terms of the first
3233 * gen->shared_len dimensions of the computed schedule using the mapping
3234 * sched2shared which maps the loop iterators to these dimensions.
3236 static void compute_index_expression(struct gpu_gen *gen,
3237 struct ppcg_kernel_access *kernel_access,
3238 struct gpu_stmt_access *stmt_access, __isl_keep isl_map *stmt_it,
3239 __isl_keep isl_map *sched2shared, __isl_keep isl_ast_build *build)
3241 isl_map *access;
3242 isl_pw_multi_aff *pma;
3243 int i;
3244 unsigned n_index;
3245 struct gpu_array_tile *tile = NULL;
3247 if (isl_map_has_tuple_name(stmt_access->access, isl_dim_out)) {
3248 int i;
3249 const char *name;
3250 struct gpu_array_ref_group *group;
3251 isl_printer *p;
3253 name = isl_map_get_tuple_name(stmt_access->access, isl_dim_out);
3255 for (i = 0; i < gen->prog->n_array; ++i) {
3256 if (strcmp(name, gen->prog->array[i].name))
3257 continue;
3258 kernel_access->array = &gen->prog->array[i];
3259 kernel_access->local_array = &gen->kernel->array[i];
3261 assert(kernel_access->array);
3262 group = kernel_access->array->groups[stmt_access->group];
3263 p = isl_printer_to_str(gen->ctx);
3264 p = print_array_name(p, group);
3265 kernel_access->local_name = isl_printer_get_str(p);
3266 isl_printer_free(p);
3267 tile = group->private_tile;
3268 kernel_access->type = ppcg_access_private;
3269 if (!tile) {
3270 tile = group->shared_tile;
3271 kernel_access->type = ppcg_access_shared;
3274 if (!tile)
3275 kernel_access->type = ppcg_access_global;
3277 n_index = isl_map_dim(stmt_access->access, isl_dim_out);
3278 kernel_access->index = isl_ast_expr_list_alloc(gen->ctx, n_index);
3280 if (n_index == 0)
3281 return;
3283 access = isl_map_copy(stmt_access->access);
3284 access = isl_map_apply_range(isl_map_copy(stmt_it), access);
3285 pma = isl_pw_multi_aff_from_map(access);
3286 pma = isl_pw_multi_aff_coalesce(pma);
3288 for (i = 0; i < n_index; ++i) {
3289 isl_set *domain;
3290 isl_pw_aff *index;
3291 isl_ast_expr *expr;
3293 index = isl_pw_multi_aff_get_pw_aff(pma, i);
3295 if (!kernel_access->array) {
3296 } else if (!tile) {
3297 domain = isl_map_domain(isl_map_copy(stmt_it));
3298 index = isl_pw_aff_coalesce(index);
3299 index = isl_pw_aff_gist(index, domain);
3300 } else {
3301 domain = isl_map_domain(isl_map_copy(stmt_it));
3302 index = shift_index(index, kernel_access->array,
3303 &tile->bound[i], domain,
3304 isl_map_copy(sched2shared));
3307 expr = isl_ast_build_expr_from_pw_aff(build, index);
3309 kernel_access->index = isl_ast_expr_list_add(
3310 kernel_access->index, expr);
3313 isl_pw_multi_aff_free(pma);
3316 /* This function is called for each instance of a user statement
3317 * in the kernel.
3319 * We attach a struct ppcg_kernel_stmt to the "node", containing
3320 * local information about the accesses.
3321 * This information is computed from stmt_it, which expresses the domain
3322 * elements in terms of the generated loops, and sched2shared,
3323 * which expresses the first shared_len dimensions of the schedule
3324 * computed by PPCG in terms of the generated loops.
3326 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3327 __isl_keep isl_ast_build *build, void *user)
3329 struct gpu_gen *gen = (struct gpu_gen *) user;
3330 struct ppcg_kernel_stmt *stmt;
3331 isl_id *id;
3332 isl_map *stmt_it, *sched2shared;
3333 isl_ast_expr *expr, *arg;
3334 isl_union_map *schedule;
3335 int i, n;
3336 struct gpu_stmt_access *access;
3338 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3339 if (!stmt)
3340 return isl_ast_node_free(node);
3342 expr = isl_ast_node_user_get_expr(node);
3343 arg = isl_ast_expr_get_op_arg(expr, 0);
3344 id = isl_ast_expr_get_id(arg);
3346 schedule = isl_ast_build_get_schedule(build);
3347 stmt_it = isl_map_reverse(isl_map_from_union_map(schedule));
3348 sched2shared = compute_sched_to_shared(gen, isl_map_copy(stmt_it));
3350 stmt->type = ppcg_kernel_domain;
3351 stmt->u.d.stmt = find_stmt(gen->prog, id);
3352 if (!stmt->u.d.stmt)
3353 goto error;
3355 n = 0;
3356 for (access = stmt->u.d.stmt->accesses; access; access = access->next)
3357 ++n;
3359 stmt->u.d.access = isl_calloc_array(gen->ctx,
3360 struct ppcg_kernel_access, n);
3361 if (!stmt->u.d.access)
3362 goto error;
3364 stmt->u.d.n_access = n;
3366 access = stmt->u.d.stmt->accesses;
3367 for (i = 0; i < n; ++i, access = access->next) {
3368 compute_index_expression(gen, &stmt->u.d.access[i], access,
3369 stmt_it, sched2shared, build);
3372 isl_id_free(id);
3373 isl_map_free(stmt_it);
3374 isl_map_free(sched2shared);
3375 isl_ast_expr_free(arg);
3376 isl_ast_expr_free(expr);
3378 id = isl_id_alloc(gen->ctx, NULL, stmt);
3379 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3380 return isl_ast_node_set_annotation(node, id);
3381 error:
3382 isl_id_free(id);
3383 isl_map_free(stmt_it);
3384 ppcg_kernel_stmt_free(stmt);
3385 isl_map_free(sched2shared);
3386 return isl_ast_node_free(node);
3389 /* This function is called when code has been generated for the shared
3390 * tile loops. The "schedule" refers only to the original statements.
3392 * We extend the schedule with that part of gen->local_sched that hasn't
3393 * been taken into account yet. This introduces parameters referring
3394 * to thread ids in the schedule, so we add them (with the appropriate
3395 * bounds to the context as well).
3396 * Finally, we set the appropriate unrolling options
3397 * if gen->first_unroll is set.
3399 static __isl_give isl_ast_node *create_domain_leaf(
3400 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
3401 void *user)
3403 struct gpu_gen *gen = (struct gpu_gen *) user;
3404 isl_space *space;
3405 isl_union_map *sched;
3406 isl_ast_node *tree;
3407 isl_set *set;
3408 isl_id_list *iterators;
3409 int n;
3411 schedule = extend_schedule(schedule,
3412 isl_union_map_copy(gen->local_sched),
3413 gen->shared_len, gen->thread_tiled_len);
3415 space = isl_ast_build_get_schedule_space(build);
3416 set = isl_set_universe(space);
3417 set = add_bounded_parameters(set, gen->n_block, gen->block_dim, "t");
3418 build = isl_ast_build_restrict(build, set);
3420 n = gen->thread_tiled_len - gen->shared_len;
3422 if (gen->first_unroll >= 0) {
3423 space = isl_space_set_alloc(gen->ctx, 0, n);
3424 build = set_unroll(build, space, gen->first_unroll);
3426 iterators = generate_names(gen->ctx, n, "c");
3427 build = isl_ast_build_set_iterators(build, iterators);
3428 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
3429 tree = isl_ast_build_ast_from_schedule(build, schedule);
3430 isl_ast_build_free(build);
3432 return tree;
3435 /* This function is called for each leaf in the AST of the code
3436 * for copying to or from shared/private memory.
3437 * The statement name is {read,write}_{shared,private}_<array>.
3439 * The schedule is of the form
3441 * [A -> T] -> L
3443 * where A refers to a piece of an array and T to the corresponding
3444 * shifted tile. We split this schedule into mappings L -> A and L -> T
3445 * and store the corresponding expressions in stmt->index and stmt->local_index,
3446 * where stmt represents the copy statement.
3448 static __isl_give isl_ast_node *create_copy_leaf(
3449 __isl_take isl_ast_build *build, void *user)
3451 struct gpu_gen *gen = (struct gpu_gen *) user;
3452 struct ppcg_kernel_stmt *stmt;
3453 isl_id *id;
3454 isl_ast_expr *expr;
3455 isl_ast_node *node;
3456 isl_space *space;
3457 isl_map *access, *local_access, *map;
3458 isl_pw_multi_aff *pma;
3459 const char *name;
3460 int array_index;
3462 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3463 if (!stmt)
3464 return isl_ast_build_free(build);
3466 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
3467 name = isl_map_get_tuple_name(access, isl_dim_in);
3468 stmt->u.c.read = !strncmp(name, "read", 4);
3469 access = isl_map_reverse(access);
3470 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
3471 local_access = isl_map_copy(access);
3473 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
3474 id = isl_map_get_tuple_id(access, isl_dim_out);
3475 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3476 access = isl_map_apply_range(access, map);
3477 pma = isl_pw_multi_aff_from_map(access);
3478 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3479 stmt->u.c.index = expr;
3481 map = isl_map_range_map(isl_map_universe(space));
3482 id = isl_map_get_tuple_id(local_access, isl_dim_out);
3483 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3484 local_access = isl_map_apply_range(local_access, map);
3485 pma = isl_pw_multi_aff_from_map(local_access);
3486 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3487 stmt->u.c.local_index = expr;
3489 stmt->u.c.array = gen->copy_group->array;
3490 array_index = stmt->u.c.array - gen->prog->array;
3491 stmt->u.c.local_array = &gen->kernel->array[array_index];
3492 stmt->type = ppcg_kernel_copy;
3494 space = isl_ast_build_get_schedule_space(build);
3495 space = isl_space_from_domain(space);
3496 space = isl_space_set_tuple_name(space, isl_dim_out, name);
3497 expr = isl_ast_build_call_from_pw_multi_aff(build,
3498 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
3499 node = isl_ast_node_alloc_user(expr);
3500 isl_ast_build_free(build);
3502 id = isl_id_alloc(gen->ctx, NULL, stmt);
3503 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3504 return isl_ast_node_set_annotation(node, id);
3507 /* Given a schedule of the form
3509 * [S -> A] -> L
3511 * (with S the first shared_len dimensions of the computed schedule,
3512 * A the array and L the schedule correponding to the generated loops),
3513 * indicating where the copying the array elements that need to be copied,
3514 * construct code for performing the copying.
3516 * "group" is the array reference group that is being copied
3517 * "type" is either "read" or "write"
3518 * private is set if copying needs to be performed to/from registers
3520 * We first construct a mapping to a shifted tile of the array,
3522 * [S -> A] -> T(S,A) (1)
3524 * If private is set, then we also use this mapping as a schedule
3525 * (which is already thread-specific and will be completely unrolled).
3526 * Otherwise, we wrap/tile the range over the threads.
3527 * The result is
3529 * [S -> A] -> T'(S,A)
3531 * Combined with the given schedule, we have
3533 * [S -> A] -> [L -> T'(S,A)] (2)
3535 * From the shifted tile mapping, we construct a mapping
3537 * [S -> A] -> [A -> T(S,A)]
3539 * and apply it to the schedule (2), obtaining
3541 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
3543 * Note that we can project out S because it is uniquely defined by L.
3545 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
3546 __isl_take isl_map *sched,
3547 const char *type, struct gpu_array_ref_group *group,
3548 __isl_take isl_ast_build *build, int private)
3550 const char *array_name;
3551 const char *mem = private ? "private" : "shared";
3552 char *name;
3553 isl_space *space;
3554 isl_ast_node *tree;
3555 isl_map *schedule, *shift, *map;
3556 isl_set *set;
3557 isl_id_list *iterators;
3558 int n;
3560 shift = isl_set_unwrap(isl_map_domain(isl_map_copy(sched)));
3561 array_name = isl_map_get_tuple_name(shift, isl_dim_out);
3562 shift = shift_access(shift, group);
3564 schedule = isl_map_copy(shift);
3565 if (!private)
3566 schedule = tile_access_schedule(gen, schedule);
3568 n = isl_map_dim(schedule, isl_dim_out);
3569 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
3570 set = add_bounded_parameters(set, gen->n_block, gen->block_dim, "t");
3572 schedule = isl_map_range_product(sched, schedule);
3574 assert(array_name);
3575 name = isl_alloc_array(gen->ctx, char,
3576 strlen(type) + sizeof("_private_") + strlen(array_name) + 20);
3577 if (group->array->n_group > 1)
3578 sprintf(name, "%s_%s_%s_%d", type, mem, array_name, group->nr);
3579 else
3580 sprintf(name, "%s_%s_%s", type, mem, array_name);
3581 shift = isl_map_set_tuple_name(shift,
3582 isl_dim_out, name + strlen(type) + 1);
3584 space = isl_space_domain(isl_map_get_space(shift));
3585 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
3586 map = isl_map_range_product(map, shift);
3588 schedule = isl_map_apply_domain(schedule, map);
3590 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, name);
3591 free(name);
3593 build = isl_ast_build_restrict(build, set);
3595 gen->copy_group = group;
3597 if (private) {
3598 space = isl_space_range(isl_map_get_space(schedule));
3599 space = isl_space_range(isl_space_unwrap(space));
3600 build = set_unroll(build, space, 0);
3602 iterators = generate_names(gen->ctx, n, "c");
3603 build = isl_ast_build_set_iterators(build, iterators);
3604 build = isl_ast_build_set_create_leaf(build, &create_copy_leaf, gen);
3605 tree = isl_ast_build_ast_from_schedule(build,
3606 isl_union_map_from_map(schedule));
3607 isl_ast_build_free(build);
3609 return tree;
3612 /* Return code for reading into or writing from shared memory
3613 * the given array reference group.
3615 * If we are performing a read from global memory to shared memory and
3616 * if the array involved is not a scalar, then we copy
3617 * the entire tile to shared memory. This may result in some extra
3618 * elements getting copied, but it should lead to simpler code
3619 * (which means that fewer registers may be needed) and less divergence.
3621 * Otherwise, we only copy the elements that will be read or have been written
3622 * in the kernel.
3625 * The input "sched" is of the form.
3627 * type[S -> A] -> L
3629 * with S the first shared_len dimensions of the computed schedule,
3630 * A the array and L the schedule correponding to the generated loops.
3632 * We first drop "type",
3634 * [S -> A] -> L
3636 * If the above conditions are satisfied, we project out A,
3637 * resulting in
3639 * S -> L
3641 * and then introduce the group tile [S -> T], resulting in
3643 * [S -> T] -> L
3645 static __isl_give isl_ast_node *copy_group_shared_accesses(
3646 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3647 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3649 const char *type;
3650 int read;
3651 isl_union_map *access;
3653 type = isl_map_get_tuple_name(sched, isl_dim_in);
3654 read = !strcmp(type, "read");
3656 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3658 if (read && group->array->n_index > 0) {
3659 isl_space *space;
3660 isl_map *map;
3662 space = isl_space_domain(isl_map_get_space(sched));
3663 space = isl_space_unwrap(space);
3664 map = isl_map_domain_map(isl_map_universe(space));
3665 sched = isl_map_apply_domain(sched, map);
3667 map = group_tile(group);
3668 map = isl_map_reverse(isl_map_domain_map(map));
3669 sched = isl_map_apply_domain(sched, map);
3672 return copy_access(gen, sched, type, group, build, 0);
3675 /* Return code for reading into or writing from private memory
3676 * the given array reference group.
3678 * Let S be the first shared_len dimensions of the computed schedule,
3679 * D the iteration domains, A the array and L the schedule correponding
3680 * to the generated loops.
3681 * "sched" is of the form
3683 * type[S -> A] -> L
3685 * where type is either "read" or "write".
3686 * We apply the privatization D -> S(t), with t the thread ids,
3687 * to the access relation D -> A to obtain the privatized access relation
3689 * S(t) -> A
3691 * We drop the type from "sched" and intersect with the privatized access
3692 * relation to obtain
3694 * [S(t) -> A] -> L
3696 static __isl_give isl_ast_node *copy_group_private_accesses(
3697 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3698 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3700 const char *type;
3701 int read;
3702 isl_union_map *priv;
3703 isl_union_map *access;
3704 isl_map *access_map;
3706 type = isl_map_get_tuple_name(sched, isl_dim_in);
3707 read = !strcmp(type, "read");
3709 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
3710 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3711 priv);
3713 access = group_access_relation(group, read, !read);
3714 access = isl_union_map_apply_domain(access, priv);
3715 access_map = isl_map_from_union_map(access);
3717 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3718 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
3720 return copy_access(gen, sched, type, group, build, 1);
3723 /* Return code for reading into or writing from shared or private memory.
3725 * "schedule" is of the form
3727 * type[S -> A] -> L
3729 * with S be the first shared_len dimensions of the computed schedule,
3730 * A the array and L the schedule correponding to the generated loops.
3731 * The array reference group is attached to "type".
3733 static __isl_give isl_ast_node *create_access_leaf(
3734 struct gpu_gen *gen, __isl_take isl_map *schedule,
3735 __isl_take isl_ast_build *build)
3737 struct gpu_array_ref_group *group;
3738 isl_id *id;
3740 id = isl_map_get_tuple_id(schedule, isl_dim_in);
3741 group = isl_id_get_user(id);
3742 isl_id_free(id);
3744 if (group->private_tile)
3745 return copy_group_private_accesses(gen, group, schedule,
3746 build);
3747 else
3748 return copy_group_shared_accesses(gen, group, schedule,
3749 build);
3752 /* Create a domain node representing a synchronization.
3754 static __isl_give isl_ast_node *create_sync_leaf(
3755 struct gpu_gen *gen, __isl_take isl_map *schedule,
3756 __isl_take isl_ast_build *build)
3758 struct ppcg_kernel_stmt *stmt;
3759 isl_id *id;
3760 isl_space *space;
3761 isl_ast_node *node;
3762 isl_ast_expr *expr;
3764 isl_map_free(schedule);
3766 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3767 if (!stmt)
3768 return NULL;
3770 stmt->type = ppcg_kernel_sync;
3772 space = isl_ast_build_get_schedule_space(build);
3773 space = isl_space_from_domain(space);
3774 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
3775 expr = isl_ast_build_call_from_pw_multi_aff(build,
3776 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
3777 node = isl_ast_node_alloc_user(expr);
3778 isl_ast_build_free(build);
3780 id = isl_id_alloc(gen->ctx, NULL, stmt);
3781 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3782 return isl_ast_node_set_annotation(node, id);
3785 /* This function is called during the code generation at the point
3786 * where the schedule domain element is completely determined by
3787 * the generated code. The input schedule contains the original
3788 * statements as well as synchronization and copy "statements".
3789 * The latter are scheduled at different points than any of the original
3790 * statements, so they will only arrive here in isolation.
3792 * If the current schedule only refers to a single statement,
3793 * we check if it is a copy or synchronization statement and
3794 * call the appropriate functions.
3795 * Otherwise, we assume we are dealing with the original statements
3796 * and we call create_domain_leaf.
3798 static __isl_give isl_ast_node *create_kernel_leaf(
3799 __isl_take isl_ast_build *build, void *user)
3801 struct gpu_gen *gen = (struct gpu_gen *) user;
3802 isl_map *map;
3803 isl_union_map *schedule;
3804 const char *name;
3806 schedule = isl_ast_build_get_schedule(build);
3808 if (isl_union_map_n_map(schedule) != 1)
3809 return create_domain_leaf(schedule, build, user);
3811 map = isl_map_from_union_map(schedule);
3812 name = isl_map_get_tuple_name(map, isl_dim_in);
3813 if (!strcmp(name, "read") || !strcmp(name, "write"))
3814 return create_access_leaf(gen, map, build);
3815 if (!strcmp(name, "sync"))
3816 return create_sync_leaf(gen, map, build);
3818 return create_domain_leaf(isl_union_map_from_map(map), build, user);
3821 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
3822 * have value 0) and all even schedule dimensions as "unroll".
3824 * That is, the options look as follows
3826 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
3827 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
3829 * The even positions are used to be able to schedule copying blocks
3830 * and synchronization before or after each level of the shared memory
3831 * tile loops and we want to make sure that code for these is generated
3832 * separately (within each level).
3834 static __isl_give isl_ast_build *set_atomic_and_unroll(
3835 __isl_take isl_ast_build *build,
3836 __isl_take isl_space *space, int sched_len)
3838 isl_ctx *ctx;
3839 isl_map *map;
3840 isl_constraint *c;
3841 isl_union_map *opt;
3842 isl_local_space *ls;
3843 int i, n;
3845 ctx = isl_ast_build_get_ctx(build);
3847 space = isl_space_params(space);
3848 space = isl_space_add_dims(space, isl_dim_set, sched_len);
3849 space = isl_space_from_domain(space);
3850 space = isl_space_add_dims(space, isl_dim_out, 2);
3851 map = isl_map_universe(isl_space_copy(space));
3852 for (i = 0; i < sched_len; i += 2)
3853 map = isl_map_fix_si(map, isl_dim_in, i, 0);
3854 ls = isl_local_space_from_space(isl_map_get_space(map));
3855 c = isl_equality_alloc(ls);
3856 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3857 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3858 c = isl_constraint_set_constant_si(c, 1);
3859 map = isl_map_add_constraint(map, c);
3860 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3861 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
3862 opt = isl_union_map_from_map(map);
3864 map = isl_map_universe(space);
3865 ls = isl_local_space_from_space(isl_map_get_space(map));
3866 c = isl_equality_alloc(ls);
3867 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3868 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3869 map = isl_map_add_constraint(map, c);
3870 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3871 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
3872 opt = isl_union_map_add_map(opt, map);
3874 build = isl_ast_build_set_options(build, opt);
3876 return build;
3879 /* Return a map that maps a space of dimension gen->shared_len
3880 * to its last dimensions starting at gen->tile_first.
3881 * The range is of dimension
3883 * 2 * (gen->shared_len - gen->tile_first) + 1
3885 * The input dimensions are mapped to the odd dimensions in the output,
3886 * while the even dimensions (except 2*pos) are fixed to 0.
3887 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
3888 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
3889 * are mapped to the output. The remaining input dimensions are projected
3890 * out and the corresponding output dimensions are fixed to 0.
3892 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
3893 __isl_take isl_space *space, int pos, int val)
3895 int i, n;
3896 isl_map *proj;
3898 space = isl_space_set_from_params(space);
3899 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
3900 space = isl_space_map_from_set(space);
3901 proj = isl_map_identity(space);
3902 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
3903 n = gen->shared_len - gen->tile_first;
3904 for (i = 0; i <= n; ++i) {
3905 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
3906 if (i == pos)
3907 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
3908 else
3909 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
3912 if (pos < 0)
3913 return proj;
3915 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
3916 gen->shared_len - (gen->tile_first + pos));
3917 for (i = pos; i < n; ++i)
3918 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
3920 return proj;
3923 /* Given the AST context schedule "schedule" and the mapping from
3924 * domains to the shared tile loops "shared_sched", add a schedule
3925 * for a synchronization operation at position "val" of loop level "pos".
3927 * schedule is of the form
3929 * D -> L
3931 * (with D the iteration domains and L the already generated loops),
3932 * while shared_sched is of the form
3934 * D -> S
3936 * We combine them into
3938 * L -> S
3940 * apply a mapping
3942 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
3944 * and use the result as a schedule for "sync".
3946 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
3947 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
3948 __isl_keep isl_union_map *shared_sched, int pos, int val)
3950 isl_space *space;
3951 isl_map *proj, *map;
3953 shared_sched = isl_union_map_copy(shared_sched);
3954 schedule = isl_union_map_copy(schedule);
3956 space = isl_union_map_get_space(shared_sched);
3957 schedule = isl_union_map_apply_domain(shared_sched, schedule);
3958 map = isl_map_from_union_map(schedule);
3960 proj = insert_even(gen, space, pos, val);
3961 map = isl_map_apply_range(map, proj);
3962 map = isl_map_from_range(isl_map_wrap(map));
3963 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
3965 res = isl_union_map_add_map(res, map);
3967 return res;
3970 /* Given the AST context schedule "schedule" and the mapping from
3971 * domains to the shared tile loops "shared_sched", add a schedule
3972 * for copying an array reference group to/from shared/private memory.
3973 * "read" is set if data should be copied from global memory
3974 * to shared/private memory.
3975 * "k" represents the current group
3976 * "s" is the total number of groups
3978 * We schedule an operation before or after the innermost loop
3979 * of "shared_sched" that affects the tile of the array reference group.
3981 * schedule is of the form
3983 * D -> L
3985 * (with D the iteration domains and L the already generated loops),
3986 * while shared_sched is of the form
3988 * D -> S
3990 * We first compute the access relation for the reference group
3992 * D -> A
3994 * and combine it with shared_sched into
3996 * D -> [S -> A]
3998 * If this results in an empty relation, no copying needs to be performed
3999 * at this point.
4000 * Otherwise, we invert the relation and combine it with "schedule" into
4002 * [S -> A] -> L
4004 * The actual additional piece of the schedule is obtained from combining
4006 * [S -> A] -> S
4008 * with a mapping
4010 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4012 * The position of "val" corresponds to the innermost loop that affects
4013 * the tile and the value indicates where the copying is scheduled
4014 * with respect to the actual kernel code (at value 0).
4015 * Reads are schedule before the code, writes to global memory from
4016 * private memory are scheduled at values 1 to s, writes to global
4017 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4019 * If we are scheduling a read from global memory to shared memory,
4020 * we insert a synchronization before the kernel code (at the innermost
4021 * level).
4022 * If we are scheduling a write to global memory, then we add
4023 * a synchronization after all writes (at value 2 *s + 2).
4024 * However, there is no need for a synchronization after the outermost loop.
4025 * A write to global memory from private memory at the innermost level
4026 * does not require a synchronization, because it is covered by
4027 * the synchronization after the kernel inserted by body_schedule.
4029 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4030 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4031 __isl_keep isl_union_map *shared_sched,
4032 struct gpu_array_ref_group *group, int read, int k, int s)
4034 int n;
4035 int pos, val;
4036 isl_space *space;
4037 isl_union_map *access;
4038 isl_map *map, *proj, *access_map;
4039 isl_id *id;
4041 access = group_access_relation(group, read, !read);
4042 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4043 access);
4045 if (isl_union_map_is_empty(access)) {
4046 isl_union_map_free(access);
4047 return res;
4050 access = isl_union_map_reverse(access);
4051 access = isl_union_map_apply_range(access,
4052 isl_union_map_copy(schedule));
4053 access_map = isl_map_from_union_map(access);
4055 space = isl_space_copy(group->array->dim);
4056 space = isl_space_from_range(space);
4057 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4058 map = isl_map_domain_map(isl_map_universe(space));
4060 space = isl_union_map_get_space(schedule);
4061 pos = group->last_shared + 1 - gen->tile_first;
4062 assert(pos >= 0);
4063 if (read)
4064 val = -2 - k;
4065 else if (group->private_tile)
4066 val = 1 + k;
4067 else
4068 val = 1 + s + 1 + k;
4069 proj = insert_even(gen, space, pos, val);
4070 map = isl_map_apply_range(map, proj);
4072 access_map = isl_map_range_product(access_map, map);
4074 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4075 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4077 res = isl_union_map_add_map(res, access_map);
4079 n = gen->shared_len - gen->tile_first;
4080 if (read) {
4081 if (!group->private_tile)
4082 res = add_sync_schedule(gen, res, schedule,
4083 shared_sched, n, -1);
4084 } else {
4085 if (pos == 0)
4086 return res;
4087 if (pos == n && group->private_tile)
4088 return res;
4089 res = add_sync_schedule(gen, res, schedule, shared_sched,
4090 pos, 2 * s + 2);
4093 return res;
4096 /* Return a schedule for the shared tile loops based on the current
4097 * AST context schedule.
4099 * We create a "shared_sched" that maps the domains to the first
4100 * shared_len dimensions of the computed schedule, project out the
4101 * first tile_first dimensions (as these are already covered by
4102 * the host code) and insert "statement-level" dimensions at even
4103 * positions so that we can schedule copy blocks and synchronization
4104 * before/after each level.
4106 * In particular, copy blocks are inserted inside the innermost
4107 * level that affect the tile. For the copying to global memory,
4108 * those from private memory are scheduled before those from shared
4109 * memory such that synchronization can be inserted between the two
4110 * at the innermost level.
4111 * Synchronization is inserted at the innermost level before the
4112 * actual kernel code if there is any copying from global memory
4113 * to shared memory. It is inserted unconditionally at the innermost
4114 * level after the actual kernel code and the copying to global memory
4115 * from private memory (if any). Finally, it is inserted after
4116 * any copying to global memory, except at the outermost level
4117 * and at the innermost level if there is no copying from shared
4118 * memory. The copying from private memory is covered by the unconditional
4119 * synchronization at the innermost level.
4121 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4122 __isl_take isl_union_map *schedule)
4124 isl_space *space;
4125 isl_union_map *res;
4126 isl_union_map *shared_sched;
4127 isl_union_map *sched;
4128 isl_map *proj, *map;
4129 int i, j, k, s;
4131 shared_sched = isl_union_map_copy(gen->tiled_sched);
4132 proj = projection(isl_union_map_get_space(shared_sched),
4133 gen->tiled_len, gen->shared_len);
4134 shared_sched = isl_union_map_apply_range(shared_sched,
4135 isl_union_map_from_map(proj));
4136 space = isl_union_map_get_space(shared_sched);
4137 proj = insert_even(gen, space, -1, 0);
4138 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4139 isl_union_map_from_map(proj));
4141 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4143 s = 0;
4144 for (i = 0; i < gen->prog->n_array; ++i)
4145 s += gen->prog->array[i].n_group;
4147 k = 0;
4148 for (i = 0; i < gen->prog->n_array; ++i) {
4149 struct gpu_array_info *array = &gen->prog->array[i];
4151 for (j = 0; j < array->n_group; ++j) {
4152 struct gpu_array_ref_group *group;
4154 group = array->groups[j];
4155 if (!group->private_tile && !group->shared_tile)
4156 continue;
4157 res = add_group_schedule(gen, res, schedule,
4158 shared_sched, group, 0, k, s);
4159 res = add_group_schedule(gen, res, schedule,
4160 shared_sched, group, 1, k, s);
4161 ++k;
4165 res = add_sync_schedule(gen, res, schedule, shared_sched,
4166 gen->shared_len - gen->tile_first, 1 + s);
4168 isl_union_map_free(shared_sched);
4169 isl_union_map_free(schedule);
4171 return res;
4174 /* Generate code for "kernel" in the given "context".
4176 * We first generate code for the shared tile loops (T1T, T1P and T2)
4177 * in a context that includes the block ids.
4178 * Within each iteration of these loops an additional code generation
4179 * is performed (within create_kernel_leaf) for the rest of the schedule
4180 * in a context that includes the thread ids.
4182 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4183 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4184 __isl_keep isl_multi_pw_aff *grid_size)
4186 isl_space *space;
4187 isl_set *set;
4188 isl_id_list *iterators;
4189 isl_union_map *schedule;
4190 isl_ast_node *tree;
4191 int sched_len;
4193 schedule = isl_ast_build_get_schedule(build);
4195 build = isl_ast_build_copy(build);
4196 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4197 space = isl_ast_build_get_schedule_space(build);
4198 set = isl_set_universe(isl_space_copy(space));
4199 set = add_bounded_parameters_dynamic(set, grid_size, "b");
4200 build = isl_ast_build_restrict(build, set);
4202 schedule = body_schedule(gen, schedule);
4204 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4206 build = set_atomic_and_unroll(build, space, sched_len);
4207 iterators = generate_names(gen->ctx, sched_len, "g");
4208 build = isl_ast_build_set_iterators(build, iterators);
4209 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4210 tree = isl_ast_build_ast_from_schedule(build, schedule);
4211 isl_ast_build_free(build);
4213 return tree;
4216 /* Attach "id" to the given node.
4218 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4219 __isl_keep isl_ast_build *build, void *user)
4221 isl_id *id = user;
4223 node = isl_ast_node_set_annotation(node, id);
4225 return node;
4228 /* Construct an AST node for performing a kernel launch and attach
4229 * the information about the kernel to that node.
4231 * The kernel AST has been constructed in the context of the range
4232 * of "schedule". In particular, the grid size has been computed
4233 * in the context. We therefore still need to make sure that these
4234 * constraints are expressed in the code. We do this by creating a schedule
4236 * kernel[] -> [S -> []]
4238 * where S is the schedule domain, i.e., the range of "schedule".
4239 * The AST generation will then create a single call surrounded by
4240 * all the condition in "S" that have not been expressed yet.
4242 * The kernel information is attached to this node in attach_id.
4244 static __isl_give isl_ast_node *construct_launch(
4245 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
4246 __isl_take struct ppcg_kernel *kernel)
4248 isl_id *id;
4249 isl_ctx *ctx;
4250 isl_union_set *domain;
4251 isl_set *set;
4252 isl_map *map;
4253 isl_ast_node *node;
4255 ctx = isl_ast_build_get_ctx(build);
4257 id = isl_id_alloc(ctx, NULL, kernel);
4258 id = isl_id_set_free_user(id, &ppcg_kernel_free);
4260 domain = isl_union_map_range(schedule);
4261 set = isl_set_from_union_set(domain);
4262 map = isl_map_from_domain(set);
4263 map = isl_map_from_range(isl_map_wrap(map));
4264 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
4265 schedule = isl_union_map_from_map(map);
4267 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
4268 node = isl_ast_build_ast_from_schedule(build, schedule);
4269 isl_ast_build_free(build);
4271 return node;
4274 /* This function is called for each leaf in the AST of the host code.
4275 * We first specialize the schedule to the site of the leaf, compute
4276 * the size of shared memory and then construct the body of host code
4277 * and the associated kernel.
4279 * The necessary information for printing the kernel launch is
4280 * stored in a struct ppcg_kernel and attached to the leaf node
4281 * created to represent the launch.
4283 static __isl_give isl_ast_node *create_host_leaf(
4284 __isl_take isl_ast_build *build, void *user)
4286 struct gpu_gen *gen = (struct gpu_gen *) user;
4287 isl_id *id;
4288 isl_ast_node *node;
4289 struct ppcg_kernel *kernel;
4290 isl_set *host_domain;
4291 isl_union_map *schedule;
4292 isl_union_map *local_sched;
4293 isl_union_map *access;
4294 isl_union_set *domain;
4295 int i;
4297 schedule = isl_ast_build_get_schedule(build);
4299 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
4300 read_sizes(gen);
4302 domain = isl_union_map_domain(isl_union_map_copy(schedule));
4304 local_sched = isl_union_map_copy(gen->sched);
4305 local_sched = isl_union_map_intersect_domain(local_sched, domain);
4306 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
4307 isl_union_map_copy(gen->prog->write));
4308 access = isl_union_map_apply_domain(access,
4309 isl_union_map_copy(local_sched));
4311 gen->tiled_sched = tile_schedule(gen, local_sched);
4312 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
4313 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
4315 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
4316 if (!kernel)
4317 goto error;
4319 kernel->id = gen->kernel_id++;
4320 kernel->n_block = gen->n_block;
4321 for (i = 0; i < gen->n_block; ++i)
4322 kernel->block_dim[i] = gen->block_dim[i];
4323 kernel->n_grid = gen->n_grid;
4324 for (i = 0; i < gen->n_grid; ++i)
4325 kernel->grid_dim[i] = gen->grid_dim[i];
4326 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
4327 kernel->grid_size = extract_grid_size(gen, kernel);
4328 kernel->arrays = isl_union_map_range(access);
4329 kernel->space = isl_ast_build_get_schedule_space(build);
4331 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
4333 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
4334 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
4336 gen->private_access = NULL;
4337 compute_shared_sched(gen);
4338 gen->privatization = compute_privatization(gen);
4339 group_references(gen);
4340 compute_private_access(gen);
4341 check_shared_memory_bound(gen);
4342 host_domain = isl_set_from_union_set(isl_union_map_range(
4343 isl_union_map_copy(schedule)));
4344 localize_bounds(gen, kernel, host_domain);
4346 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
4348 kernel->tree = generate_kernel(gen, build, host_domain,
4349 kernel->grid_size);
4350 create_kernel_vars(gen, kernel);
4352 free_local_array_info(gen);
4353 isl_map_free(gen->privatization);
4354 isl_union_map_free(gen->private_access);
4355 isl_union_map_free(gen->local_sched);
4356 isl_union_map_free(gen->tiled_sched);
4357 isl_union_map_free(gen->shared_sched);
4358 isl_union_map_free(gen->shared_proj);
4359 isl_set_free(host_domain);
4360 free(gen->tile_size);
4362 node = construct_launch(build, schedule, kernel);
4364 return node;
4365 error:
4366 isl_union_map_free(schedule);
4367 return NULL;
4370 /* Use isl to generate code for the outer gen->tile_first loops
4371 * of the global schedule in gen->sched, resulting in the host code.
4372 * Within each iteration of this partial schedule, i.e., for each kernel
4373 * launch, create_host_leaf takes care of generating the kernel code.
4375 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
4377 isl_ast_build *build;
4378 isl_ast_node *tree;
4379 isl_union_map *sched;
4380 isl_map *proj;
4381 isl_id_list *iterators;
4383 sched = isl_union_map_copy(gen->sched);
4384 proj = projection(isl_union_map_get_space(sched),
4385 gen->untiled_len, gen->tile_first);
4386 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4388 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
4389 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
4390 iterators = generate_names(gen->ctx, gen->tile_first, "h");
4391 build = isl_ast_build_set_iterators(build, iterators);
4392 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
4393 tree = isl_ast_build_ast_from_schedule(build, sched);
4394 isl_ast_build_free(build);
4396 return tree;
4399 __isl_give isl_set *add_context_from_str(__isl_take isl_set *set,
4400 const char *str)
4402 isl_ctx *ctx;
4403 isl_set *context;
4405 if (!str)
4406 return set;
4408 ctx = isl_set_get_ctx(set);
4409 context = isl_set_read_from_str(ctx, str);
4410 context = isl_set_align_params(context, isl_set_get_space(set));
4411 set = isl_set_intersect(set, context);
4413 return set;
4416 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
4418 if (!str)
4419 return NULL;
4420 return isl_union_map_read_from_str(ctx, str);
4423 /* Information about the outermost tilable bands in the forest of bands.
4425 * tile_len and n_parallel are only sets on band_info structures
4426 * that correspond to outermost bands. For other bands (in particular,
4427 * ancestors of the outermost bands), n_parallal is set to 0.
4429 * prefix is the (padded) schedule leading up to the outermost tilable bands.
4431 * tile_first is the number of schedule dimensions in prefix.
4433 * suffix is the schedule of the outermost tilable bands and their descendants.
4435 struct band_info {
4436 struct gpu_gen *gen;
4437 int tile_first;
4438 int tile_len;
4439 int n_parallel;
4440 isl_union_map *prefix;
4441 isl_union_map *suffix;
4444 /* Set tile_len and n_parallel of the statement to that of
4445 * their outermost band, recorded in the band_info.
4447 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
4449 struct band_info *info = user;
4450 struct gpu_stmt *stmt;
4451 isl_id *id;
4453 id = isl_map_get_tuple_id(map, isl_dim_in);
4454 stmt = find_stmt(info->gen->prog, id);
4455 isl_id_free(id);
4457 stmt->tile_len = info->tile_len;
4458 stmt->n_parallel = info->n_parallel;
4460 isl_map_free(map);
4462 return 0;
4465 static void list_select_outer_band(struct gpu_gen *gen,
4466 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
4468 /* Check if this band has any parallel loops. If so, take it as
4469 * the outermost tilable band. If not, continue looking for the
4470 * outermost tilable band in the children of the current band.
4472 static void band_select_outer_band(struct gpu_gen *gen,
4473 __isl_take isl_band *band, int pos, struct band_info *info)
4475 int n = isl_band_n_member(band);
4476 int n_parallel;
4478 for (n_parallel = 0; n_parallel < n; ++n_parallel)
4479 if (!isl_band_member_is_zero_distance(band, n_parallel))
4480 break;
4482 info->n_parallel = n_parallel;
4483 if (n_parallel) {
4484 info->gen = gen;
4485 info->tile_first = pos;
4486 info->tile_len = n;
4487 info->prefix = isl_band_get_prefix_schedule(band);
4488 info->suffix = isl_union_map_flat_range_product(
4489 isl_band_get_partial_schedule(band),
4490 isl_band_get_suffix_schedule(band));
4491 isl_union_map_foreach_map(info->prefix,
4492 &set_stmt_tile_len, info);
4493 } else if (isl_band_has_children(band)) {
4494 isl_band_list *children;
4495 children = isl_band_get_children(band);
4496 list_select_outer_band(gen, children, pos + n, info);
4497 } else {
4498 info->gen = gen;
4499 info->tile_first = pos + n;
4500 info->tile_len = 0;
4501 info->prefix = isl_union_map_flat_range_product(
4502 isl_band_get_prefix_schedule(band),
4503 isl_band_get_partial_schedule(band));
4504 info->suffix = isl_band_get_suffix_schedule(band);
4505 isl_union_map_foreach_map(info->prefix,
4506 &set_stmt_tile_len, info);
4509 isl_band_free(band);
4512 /* Comparison function that returns a non-zero value for band_infos
4513 * with different tile_len fields or different n_parallel fields.
4515 static int cmp_band(const void *p1, const void *p2)
4517 const struct band_info *info1 = p1;
4518 const struct band_info *info2 = p2;
4520 if (info1->tile_len != info2->tile_len)
4521 return info1->tile_len - info2->tile_len;
4523 return info1->n_parallel - info2->n_parallel;
4526 /* Extend "umap" with coordinates with fixed value "val"
4527 * to a total length of "dst_len", assuming the original dimension is "src_len".
4529 static __isl_give isl_union_map *extend_range(
4530 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
4532 isl_space *dim;
4533 isl_map *map;
4534 int i;
4536 dim = isl_union_map_get_space(umap);
4537 map = isl_map_reverse(projection(dim, dst_len, src_len));
4538 for (i = src_len; i < dst_len; ++i)
4539 map = isl_map_fix_si(map, isl_dim_out, i, val);
4541 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
4543 return umap;
4546 /* Group bands with the same values for tile_len and n_parallel.
4547 * The prefix schedule is then extended with a fixed coordinate that
4548 * is different for each such group.
4549 * Note that the actual values for this coordinate are not important.
4550 * The bands have already been effectively separated at a higher level
4551 * or they are independent and may be executed in parallel.
4552 * The list of band_info has been sorted before this functions is called.
4554 static void separate_bands(struct band_info *info, int n)
4556 int i;
4557 int j = 0;
4559 for (i = 0; i < n; ++i) {
4560 int l = info[i].tile_first;
4562 if (i &&
4563 (info[i].tile_len != info[i - 1].tile_len ||
4564 info[i].n_parallel != info[i - 1].n_parallel))
4565 j++;
4567 info[i].prefix = extend_range(info[i].prefix,
4568 l, l + 1, j);
4569 info[i].tile_first = l + 1;
4573 /* Select the outermost bands in the elements of the list, align
4574 * their prefix schedules, separate bands with different values
4575 * for tile_len and/or n_parallel and then combine the resulting
4576 * prefix and suffix schedules into a single pair of prefix and
4577 * suffix schedules for the entire list.
4579 static void list_select_outer_band(struct gpu_gen *gen,
4580 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
4582 isl_band *band;
4583 int i;
4584 int n = isl_band_list_n_band(list);
4585 isl_ctx *ctx = isl_band_list_get_ctx(list);
4586 struct band_info *info;
4587 int max_tile_first;
4588 isl_union_map *prefix;
4589 isl_union_map *suffix;
4591 assert(n >= 1);
4592 info = isl_calloc_array(ctx, struct band_info, n);
4593 assert(info);
4595 max_tile_first = 0;
4596 for (i = 0; i < n; ++i) {
4597 band = isl_band_list_get_band(list, i);
4598 band_select_outer_band(gen, band, pos, &info[i]);
4599 if (info[i].tile_first > max_tile_first)
4600 max_tile_first = info[i].tile_first;
4603 for (i = 0; i < n; ++i) {
4604 if (info[i].tile_first == max_tile_first)
4605 continue;
4606 info[i].prefix = extend_range(info[i].prefix,
4607 info[i].tile_first, max_tile_first, 0);
4608 info[i].tile_first = max_tile_first;
4611 qsort(info, n, sizeof(struct band_info), &cmp_band);
4613 for (i = 0; i < n - 1; ++i)
4614 if (info[i].tile_len != info[i + 1].tile_len ||
4615 info[i].n_parallel != info[i + 1].n_parallel)
4616 break;
4618 if (i < n -1)
4619 separate_bands(info, n);
4621 prefix = info[0].prefix;
4622 suffix = info[0].suffix;
4624 for (i = 1; i < n; ++i) {
4625 prefix = isl_union_map_union(prefix, info[i].prefix);
4626 suffix = isl_union_map_union(suffix, info[i].suffix);
4629 list_info->tile_first = info[0].tile_first;
4630 list_info->tile_len = -1;
4631 list_info->prefix = prefix;
4632 list_info->suffix = suffix;
4634 isl_band_list_free(list);
4635 free(info);
4638 /* Select the outermost tilable band that (by construction)
4639 * has at least one parallel loop.
4640 * The starting position of the aligned band is stored in the pair
4641 * gen->tile_first.
4642 * The sizes and number of parallel loops may be different in different
4643 * parts of the band forest and are therefore stored in the gpu_stmts.
4645 * Return the complete schedule, with the tilable bands aligned
4646 * at gen->tile_first and padded with zero, if needed.
4648 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
4649 __isl_keep isl_schedule *schedule)
4651 isl_band_list *list;
4652 struct band_info info;
4654 gen->n_parallel = 0;
4655 gen->tile_len = -1;
4657 list = isl_schedule_get_band_forest(schedule);
4659 list_select_outer_band(gen, list, 0, &info);
4661 gen->tile_first = info.tile_first;
4662 info.suffix = align_range(info.suffix);
4664 return isl_union_map_flat_range_product(info.prefix, info.suffix);
4667 /* Set gen->untiled_len to the number of scheduling dimensions
4668 * for the schedule of the first domain.
4669 * We assume here that this number is the same for all domains.
4671 static int set_untiled_len(__isl_take isl_map *map, void *user)
4673 unsigned *untiled_len = user;
4675 *untiled_len = isl_map_dim(map, isl_dim_out);
4677 isl_map_free(map);
4678 return -1;
4681 /* Compute an appropriate schedule based on the accesses in
4682 * gen->read and gen->write.
4684 * We use the dependences in gen->prog->scop to compute
4685 * a schedule that has a parallel loop in each tilable band.
4686 * Finally, we select the outermost tilable band.
4688 static void compute_schedule(struct gpu_gen *gen)
4690 isl_union_set *domain;
4691 isl_union_map *dep_raw, *dep;
4692 isl_union_map *uninitialized;
4693 isl_union_map *sched;
4694 isl_schedule *schedule;
4696 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4697 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
4699 gen->prog->copy_in = isl_union_map_range(uninitialized);
4701 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4702 dep = isl_union_map_union(dep, dep_raw);
4703 dep = isl_union_map_coalesce(dep);
4705 domain = isl_union_set_copy(gen->prog->scop->domain);
4706 domain = isl_union_set_intersect_params(domain,
4707 isl_set_copy(gen->prog->scop->context));
4708 schedule = isl_union_set_compute_schedule(isl_union_set_copy(domain),
4709 isl_union_map_copy(dep), dep);
4711 sched = select_outer_tilable_band(gen, schedule);
4713 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
4714 sched = isl_union_map_intersect_domain(sched, domain);
4715 gen->sched = sched;
4717 isl_schedule_free(schedule);
4720 static struct gpu_stmt_access **expr_extract_access(struct pet_expr *expr,
4721 struct gpu_stmt_access **next_access)
4723 struct gpu_stmt_access *access;
4724 isl_ctx *ctx = isl_map_get_ctx(expr->acc.access);
4726 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4727 assert(access);
4728 access->next = NULL;
4729 access->read = expr->acc.read;
4730 access->write = expr->acc.write;
4731 access->access = isl_map_copy(expr->acc.access);
4733 *next_access = access;
4734 next_access = &(*next_access)->next;
4735 return next_access;
4738 static struct gpu_stmt_access **expr_extract_accesses(struct pet_expr *expr,
4739 struct gpu_stmt_access **next_access)
4741 int i;
4743 for (i = 0; i < expr->n_arg; ++i)
4744 next_access = expr_extract_accesses(expr->args[i],
4745 next_access);
4747 if (expr->type == pet_expr_access)
4748 next_access = expr_extract_access(expr, next_access);
4750 return next_access;
4753 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
4755 struct gpu_stmt_access **next_access = &stmt->accesses;
4757 stmt->accesses = NULL;
4758 expr_extract_accesses(stmt->body, next_access);
4761 /* Return an array of gpu_stmt representing the statements in "scop".
4763 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4764 __isl_keep isl_set *context)
4766 int i;
4767 struct gpu_stmt *stmts;
4769 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
4770 assert(stmts);
4772 for (i = 0; i < scop->n_stmt; ++i) {
4773 struct gpu_stmt *s = &stmts[i];
4775 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
4776 s->body = scop->stmts[i]->body;
4777 pet_stmt_extract_accesses(s);
4780 return stmts;
4783 /* Replace the scop in the "input" file by equivalent code
4784 * that uses the GPU. "scop" is assumed to correspond to this scop.
4786 * We first compute a schedule that respects the dependences
4787 * of the original program and select the outermost band
4788 * of tilable dimensions that has at least one parallel loop.
4789 * We then have three blocks of dimensions
4791 * H B G
4793 * The tilable band "B" is first tiled according to "tile" sizes, resulting
4794 * in
4796 * H T P G
4798 * For each iteration of the T loop and for each array, we compute
4799 * the array elements accessed by that iteration, construct a rectangular
4800 * box around it and shift it to the origin. The result is used
4801 * as shared memory for the array.
4803 * We then split off at most 2 parallel loops from the T loops and
4804 * at most 3 parallel loops from the P loops
4806 * H T1 T2 P1 P2 G
4808 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
4809 * according to "grid"/"block" sizes.
4811 * H T1T T1P T2 P1T P1P P2 G
4813 * Finally, the T1P and P1P iterators are equated to the block and
4814 * thread dimensions respectively and so are effectively removed.
4815 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
4816 * are run on the GPU.
4818 * Code is generated in three stages. We first generate code for the
4819 * host (the H loops), with iterators h%d. Then, for each leaf node
4820 * of the resulting AST, we generate code for the shared loops (up to
4821 * and including T2), with iterators g%d and after equating the H loops
4822 * to h%d parameters and the T1P loops to the block dimensions.
4823 * Finally, we generate code for the remaining loops in a similar fashion.
4825 __isl_give isl_ast_node *generate_gpu(isl_ctx *ctx, struct gpu_prog *prog,
4826 struct ppcg_options *options)
4828 isl_union_map *sched;
4829 struct gpu_gen gen;
4830 isl_ast_node *tree;
4832 if (!prog)
4833 return NULL;
4835 gen.ctx = ctx;
4836 gen.prog = prog;
4837 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
4838 gen.options = options;
4840 compute_schedule(&gen);
4842 gen.kernel_id = 0;
4843 tree = generate_host_code(&gen);
4845 clear_gpu_gen(&gen);
4847 return tree;
4850 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
4852 struct gpu_prog *prog;
4854 if (!scop)
4855 return NULL;
4857 prog = isl_calloc_type(ctx, struct gpu_prog);
4858 assert(prog);
4860 prog->ctx = ctx;
4861 prog->scop = scop;
4862 prog->context = isl_set_copy(scop->context);
4863 prog->n_stmts = scop->n_stmt;
4864 prog->stmts = extract_stmts(ctx, scop, prog->context);
4865 prog->read = isl_union_map_copy(scop->reads);
4866 prog->write = isl_union_map_copy(scop->writes);
4868 collect_array_info(prog);
4870 return prog;
4873 void gpu_prog_free(struct gpu_prog *prog)
4875 if (!prog)
4876 return;
4877 free_array_info(prog);
4878 free_stmts(prog->stmts, prog->n_stmts);
4879 isl_union_set_free(prog->copy_in);
4880 isl_union_map_free(prog->read);
4881 isl_union_map_free(prog->write);
4882 isl_set_free(prog->context);
4883 free(prog);