gpu.c: extract_array_info: react more gracefully to unexpected events
[ppcg.git] / gpu.c
blobcf60e9154d241225e84e509b89f2027732b78cbb
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012-2013 Ecole Normale Superieure
5 * Use of this software is governed by the MIT license
7 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
8 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
9 * 91893 Orsay, France
10 * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
13 #include <assert.h>
14 #include <stdlib.h>
15 #include <string.h>
17 #include <isl/polynomial.h>
18 #include <isl/union_set.h>
19 #include <isl/aff.h>
20 #include <isl/ilp.h>
21 #include <isl/flow.h>
22 #include <isl/band.h>
23 #include <isl/schedule.h>
24 #include <isl/options.h>
25 #include <isl/ast_build.h>
27 #include "cpu.h"
28 #include "gpu.h"
29 #include "schedule.h"
30 #include "ppcg_options.h"
31 #include "print.h"
33 /* The fields stride, shift and shift_map only contain valid information
34 * if shift != NULL.
35 * If so, they express that current index is such that if you add shift,
36 * then the result is always a multiple of stride.
37 * shift_map contains the mapping
39 * i -> (i + shift)/stride
41 * Let D represent the initial shared_len dimensions of the computed schedule.
42 * The spaces of "lb" and "shift" are of the form
44 * D -> [b]
46 * "shift_map" is of the form
48 * [D -> i] -> [D -> (i + shift(D))/stride]
50 struct gpu_array_bound {
51 isl_val *size;
52 isl_aff *lb;
54 isl_val *stride;
55 isl_aff *shift;
56 isl_basic_map *shift_map;
59 /* A tile of an array.
61 * n is the dimension of the array.
62 * bound is an array of size "n" representing the lower bound
63 * and size for each index.
65 * tiling maps a tile in the global array to the corresponding
66 * shared/private memory tile and is of the form
68 * { [D[i] -> A[a]] -> T[(a + shift(i))/stride - lb(i)] }
70 * where D represents the initial shared_len dimensions
71 * of the computed schedule.
73 struct gpu_array_tile {
74 int n;
75 struct gpu_array_bound *bound;
76 isl_multi_aff *tiling;
79 struct gpu_array_info;
81 /* A group of array references in a kernel that should be handled together.
82 * If private_tile is not NULL, then it is mapped to registers.
83 * Otherwise, if shared_tile is not NULL, it is mapped to shared memory.
84 * Otherwise, it is accessed from global memory.
86 struct gpu_array_ref_group {
87 /* The references in this group access this array. */
88 struct gpu_array_info *array;
89 /* Position of this group in the list of reference groups of array. */
90 int nr;
92 /* The following fields are use during the construction of the groups.
93 * access is the combined access relation relative to the shared
94 * memory tiling. In particular, the domain of the map corresponds
95 * to the first shared_len dimensions of the computed schedule.
96 * write is set if any access in the group is a write.
98 isl_map *access;
99 int write;
101 /* The shared memory tile, NULL if none. */
102 struct gpu_array_tile *shared_tile;
104 /* The private memory tile, NULL if none. */
105 struct gpu_array_tile *private_tile;
107 /* References in this group; point to elements of a linked list. */
108 int n_ref;
109 struct gpu_stmt_access **refs;
111 /* Last shared memory tile dimension that affects tile of this group. */
112 int last_shared;
115 struct gpu_gen {
116 isl_ctx *ctx;
117 struct ppcg_options *options;
119 /* Callback for printing of AST in appropriate format. */
120 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
121 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
122 void *user);
123 void *print_user;
125 struct gpu_prog *prog;
126 /* The generated AST. */
127 isl_ast_node *tree;
129 /* tile, grid and block sizes for each kernel */
130 isl_union_map *sizes;
132 /* Identifier of current kernel. */
133 int kernel_id;
134 /* Pointer to the current kernel. */
135 struct ppcg_kernel *kernel;
136 /* Does the computed schedule exhibit any parallelism? */
137 int any_parallelism;
139 /* First tile dimension. */
140 int tile_first;
141 /* Number of tile dimensions. */
142 int tile_len;
143 /* Number of initial parallel loops among tile dimensions. */
144 int n_parallel;
146 /* Number of dimensions determining shared memory. */
147 int shared_len;
149 /* Number of rows in the untiled schedule. */
150 int untiled_len;
151 /* Number of rows in the tiled schedule. */
152 int tiled_len;
153 /* Number of rows in schedule after tiling/wrapping over threads. */
154 int thread_tiled_len;
156 /* Global untiled schedule. */
157 isl_union_map *sched;
158 /* Local (per kernel launch) tiled schedule. */
159 isl_union_map *tiled_sched;
160 /* Local schedule per shared memory tile loop iteration. */
161 isl_union_map *local_sched;
163 /* Local tiled schedule projected onto the shared tile loops and
164 * the loops that will be wrapped over the threads,
165 * with all shared tile loops parametrized.
167 isl_union_map *shared_sched;
168 /* Projects out the loops that will be wrapped over the threads
169 * from shared_sched.
171 isl_union_map *shared_proj;
173 /* A map that takes the range of shared_sched as input,
174 * wraps the appropriate loops over the threads and then projects
175 * out these loops.
177 isl_map *privatization;
179 /* A map from the shared memory tile loops and the thread indices
180 * (as parameters) to the set of accessed memory elements that
181 * will be accessed through private copies.
183 isl_union_map *private_access;
185 /* The schedule for the current private/shared access
186 * (within print_private_access or print_shared_access).
188 isl_map *copy_sched;
189 /* The array reference group corresponding to copy_sched. */
190 struct gpu_array_ref_group *copy_group;
192 /* First loop to unroll (or -1 if none) in the current part of the
193 * schedule.
195 int first_unroll;
197 int n_grid;
198 int n_block;
199 /* Note: in the input file, the sizes of the grid and the blocks
200 * are specified in the order x, y, z, but internally, the sizes
201 * are stored in reverse order, so that the last element always
202 * refers to the x dimension.
204 int grid_dim[2];
205 int block_dim[3];
206 int *tile_size;
209 /* Print the name of the local copy of a given group of array references.
211 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
212 struct gpu_array_ref_group *group)
214 int global = 0;
216 if (group->private_tile)
217 p = isl_printer_print_str(p, "private_");
218 else if (group->shared_tile)
219 p = isl_printer_print_str(p, "shared_");
220 else
221 global = 1;
222 p = isl_printer_print_str(p, group->array->name);
223 if (!global && group->array->n_group > 1) {
224 p = isl_printer_print_str(p, "_");
225 p = isl_printer_print_int(p, group->nr);
228 return p;
231 /* Collect all references to the given array and store pointers to them
232 * in array->refs.
234 static void collect_references(struct gpu_prog *prog,
235 struct gpu_array_info *array)
237 int i;
238 int n;
240 n = 0;
241 for (i = 0; i < prog->n_stmts; ++i) {
242 struct gpu_stmt *stmt = &prog->stmts[i];
243 struct gpu_stmt_access *access;
245 for (access = stmt->accesses; access; access = access->next) {
246 const char *name;
247 name = isl_map_get_tuple_name(access->access,
248 isl_dim_out);
249 if (name && !strcmp(array->name, name))
250 n++;
254 array->n_ref = n;
255 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
256 assert(array->refs);
258 n = 0;
259 for (i = 0; i < prog->n_stmts; ++i) {
260 struct gpu_stmt *stmt = &prog->stmts[i];
261 struct gpu_stmt_access *access;
263 for (access = stmt->accesses; access; access = access->next) {
264 const char *name;
265 name = isl_map_get_tuple_name(access->access,
266 isl_dim_out);
267 if (!name || strcmp(array->name, name))
268 continue;
270 array->refs[n++] = access;
275 /* Create a gpu_array_tile for an array of dimension "n_index".
277 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
279 int i;
280 struct gpu_array_tile *tile;
282 tile = isl_calloc_type(ctx, struct gpu_array_tile);
283 assert(tile);
285 tile->n = n_index;
287 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
288 assert(tile->bound);
290 for (i = 0; i < n_index; ++i) {
291 tile->bound[i].size = NULL;
292 tile->bound[i].lb = NULL;
293 tile->bound[i].stride = NULL;
294 tile->bound[i].shift = NULL;
295 tile->bound[i].shift_map = NULL;
298 return tile;
301 static void *free_tile(struct gpu_array_tile *tile)
303 int j;
305 if (!tile)
306 return NULL;
308 for (j = 0; j < tile->n; ++j) {
309 isl_val_free(tile->bound[j].size);
310 isl_val_free(tile->bound[j].stride);
311 isl_aff_free(tile->bound[j].lb);
312 isl_aff_free(tile->bound[j].shift);
313 isl_basic_map_free(tile->bound[j].shift_map);
315 free(tile->bound);
316 isl_multi_aff_free(tile->tiling);
317 free(tile);
319 return NULL;
322 static struct pet_array *find_array(struct ppcg_scop *scop,
323 __isl_keep isl_set *accessed)
325 int i;
326 isl_id *id;
328 id = isl_set_get_tuple_id(accessed);
330 for (i = 0; i < scop->n_array; ++i) {
331 isl_id *id_i;
333 id_i = isl_set_get_tuple_id(scop->arrays[i]->extent);
334 isl_id_free(id_i);
335 if (id == id_i)
336 break;
338 isl_id_free(id);
340 return i < scop->n_array ? scop->arrays[i] : NULL;
343 /* Compute and return the extent of "array", taking into account the set of
344 * accessed elements.
346 * In particular, the extent in the outer dimension is taken
347 * from "accessed", while then extent in the remaing dimensions
348 * are taken from array->extent.
350 * The extent in the outer dimension cannot be taken from array->extent
351 * because that may be unbounded. Furthermore, even if it is bounded,
352 * it may be larger than the piece of the array that is being accessed.
354 static __isl_give isl_set *compute_extent(struct pet_array *array,
355 __isl_keep isl_set *accessed)
357 int n_index;
358 isl_id *id;
359 isl_set *outer;
360 isl_set *extent;
362 extent = isl_set_copy(array->extent);
364 n_index = isl_set_dim(accessed, isl_dim_set);
365 if (n_index == 0)
366 return extent;
368 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
369 outer = isl_set_copy(accessed);
370 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
371 extent = isl_set_flat_product(outer, extent);
372 id = isl_set_get_tuple_id(accessed);
373 extent = isl_set_set_tuple_id(extent, id);
375 return extent;
378 /* Compute bounds on the host arrays based on the accessed elements
379 * and collect all references to the array.
381 * If the array is zero-dimensional, i.e., a scalar, we check
382 * whether it is read-only.
384 static int extract_array_info(__isl_take isl_set *array, void *user)
386 int i;
387 struct gpu_prog *prog = (struct gpu_prog *)user;
388 const char *name;
389 int n_index;
390 isl_pw_aff **bounds;
391 struct pet_array *pa;
392 struct gpu_array_info *info;
393 isl_set *extent;
395 info = &prog->array[prog->n_array];
396 prog->n_array++;
398 n_index = isl_set_dim(array, isl_dim_set);
399 name = isl_set_get_tuple_name(array);
400 bounds = isl_alloc_array(isl_set_get_ctx(array),
401 isl_pw_aff *, n_index);
402 if (!bounds)
403 goto error;
405 info->dim = isl_set_get_space(array);
406 info->name = strdup(name);
407 info->n_index = n_index;
408 info->bound = bounds;
410 pa = find_array(prog->scop, array);
411 if (!pa)
412 isl_die(isl_set_get_ctx(array), isl_error_internal,
413 "unable to find array in scop", goto error);
415 info->type = strdup(pa->element_type);
416 info->size = pa->element_size;
417 info->local = pa->declared && !pa->exposed;
419 if (n_index == 0) {
420 isl_set *space;
421 isl_union_map *write;
422 int empty;
424 write = isl_union_map_copy(prog->write);
425 space = isl_set_universe(isl_set_get_space(array));
426 write = isl_union_map_intersect_range(write,
427 isl_union_set_from_set(space));
428 empty = isl_union_map_is_empty(write);
429 isl_union_map_free(write);
431 info->read_only = empty;
434 extent = compute_extent(pa, array);
435 for (i = 0; i < n_index; ++i) {
436 isl_set *dom;
437 isl_local_space *ls;
438 isl_aff *one;
439 isl_pw_aff *bound;
441 bound = isl_set_dim_max(isl_set_copy(extent), i);
442 assert(bound);
443 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
444 ls = isl_local_space_from_space(isl_set_get_space(dom));
445 one = isl_aff_zero_on_domain(ls);
446 one = isl_aff_add_constant_si(one, 1);
447 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
448 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
450 bounds[i] = bound;
452 info->extent = extent;
454 collect_references(prog, info);
456 isl_set_free(array);
457 return 0;
458 error:
459 isl_set_free(array);
460 return -1;
463 /* Construct a gpu_array_info for each array accessed by "prog" and
464 * collect them in prog->array.
466 static int collect_array_info(struct gpu_prog *prog)
468 int r;
469 isl_union_set *arrays;
471 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
472 arrays = isl_union_set_union(arrays,
473 isl_union_map_range(isl_union_map_copy(prog->write)));
474 arrays = isl_union_set_coalesce(arrays);
476 prog->n_array = isl_union_set_n_set(arrays);
477 prog->array = isl_alloc_array(prog->ctx,
478 struct gpu_array_info, prog->n_array);
479 assert(prog->array);
480 prog->n_array = 0;
481 r = isl_union_set_foreach_set(arrays, &extract_array_info, prog);
482 isl_union_set_free(arrays);
484 return r;
487 static void free_array_info(struct gpu_prog *prog)
489 int i, j;
491 for (i = 0; i < prog->n_array; ++i) {
492 int n_index = prog->array[i].n_index;
493 free(prog->array[i].type);
494 free(prog->array[i].name);
495 for (j = 0; j < n_index; ++j)
496 isl_pw_aff_free(prog->array[i].bound[j]);
497 isl_space_free(prog->array[i].dim);
498 isl_set_free(prog->array[i].extent);
499 free(prog->array[i].bound);
500 free(prog->array[i].refs);
502 free(prog->array);
505 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
506 * as an array or through a pointer reference, but as single data element. At
507 * the moment, scalars are represented as zero dimensional arrays.
509 int gpu_array_is_scalar(struct gpu_array_info *array)
511 return (array->n_index == 0);
514 /* Is "array" a read-only scalar?
516 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
518 return gpu_array_is_scalar(array) && array->read_only;
521 /* Internal data structure for extract_size_of_type.
522 * "type" specifies the name of the space that we want to extract.
523 * "res" is used to store the subset of that space.
525 struct ppcg_extract_size_data {
526 const char *type;
527 isl_set *res;
530 /* This function is called for each set in a union_set.
531 * If the name of the set matches data->type, we store the
532 * set in data->res.
534 static int extract_size_of_type(__isl_take isl_set *size, void *user)
536 struct ppcg_extract_size_data *data = user;
537 const char *name;
539 name = isl_set_get_tuple_name(size);
540 if (name && !strcmp(name, data->type)) {
541 data->res = size;
542 return -1;
545 isl_set_free(size);
546 return 0;
549 /* Given a union map { kernel[i] -> *[...] },
550 * return the range in the space called "type" for the kernel with
551 * sequence number "id".
553 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
554 const char *type, int id)
556 isl_space *space;
557 isl_set *dom;
558 isl_union_set *local_sizes;
559 struct ppcg_extract_size_data data = { type, NULL };
561 if (!sizes)
562 return NULL;
564 space = isl_union_map_get_space(sizes);
565 space = isl_space_set_from_params(space);
566 space = isl_space_add_dims(space, isl_dim_set, 1);
567 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
568 dom = isl_set_universe(space);
569 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
571 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
572 isl_union_map_copy(sizes));
573 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
574 isl_union_set_free(local_sizes);
575 return data.res;
578 /* Given a singleton set, extract the first (at most *len) elements
579 * of the single integer tuple into *sizes and update *len if needed.
581 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
583 int i;
584 int dim;
586 if (!set)
587 return;
589 dim = isl_set_dim(set, isl_dim_set);
590 if (dim < *len)
591 *len = dim;
593 for (i = 0; i < *len; ++i) {
594 isl_val *v;
596 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
597 assert(v);
599 sizes[i] = isl_val_get_num_si(v);
600 isl_val_free(v);
603 isl_set_free(set);
606 /* Extract user specified "tile" sizes from the "sizes" command line option,
607 * defaulting to option->tile_size in each dimension.
609 static void read_tile_sizes(struct gpu_gen *gen)
611 int n;
612 isl_set *size;
614 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
615 assert(gen->tile_size);
616 for (n = 0; n < gen->tile_len; ++n)
617 gen->tile_size[n] = gen->options->tile_size;
619 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
620 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
622 if (gen->n_parallel > gen->tile_len)
623 gen->n_parallel = gen->tile_len;
626 /* Extract user specified "block" sizes from the "sizes" command line option,
627 * after filling in some potentially useful defaults.
629 static void read_block_sizes(struct gpu_gen *gen)
631 int n;
632 isl_set *size;
634 n = gen->n_parallel;
635 gen->n_block = (n <= 3) ? n : 3;
636 switch (gen->n_block) {
637 case 1:
638 gen->block_dim[0] = 512;
639 break;
640 case 2:
641 gen->block_dim[0] = 32;
642 gen->block_dim[1] = 16;
643 break;
644 default:
645 gen->block_dim[0] = 32;
646 gen->block_dim[1] = 4;
647 gen->block_dim[2] = 4;
648 break;
651 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
652 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
655 /* Extract user specified "grid" sizes from the "sizes" command line option,
656 * after filling in some potentially useful defaults.
658 static void read_grid_sizes(struct gpu_gen *gen)
660 int n = gen->n_parallel;
661 isl_set *size;
663 gen->n_grid = (n <= 2) ? n : 2;
664 switch (gen->n_grid) {
665 case 1:
666 gen->grid_dim[0] = 32768;
667 break;
668 default:
669 gen->grid_dim[0] = 256;
670 gen->grid_dim[1] = 256;
671 break;
674 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
675 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
678 /* Extract user specified sizes from the "sizes" command line option
679 * after filling in some potentially useful defaults.
681 static void read_sizes(struct gpu_gen *gen)
683 read_tile_sizes(gen);
684 read_block_sizes(gen);
685 read_grid_sizes(gen);
688 static void *free_stmts(struct gpu_stmt *stmts, int n)
690 int i;
692 if (!stmts)
693 return NULL;
695 for (i = 0; i < n; ++i) {
696 struct gpu_stmt_access *access, *next;
698 for (access = stmts[i].accesses; access; access = next) {
699 next = access->next;
700 isl_id_free(access->ref_id);
701 isl_map_free(access->access);
702 free(access);
705 isl_id_free(stmts[i].id);
707 free(stmts);
709 return NULL;
712 /* Construct a map from a domain of dimensionality "len"
713 * to a domain of dimensionality "len" + "tile_len" that tiles
714 * the "tile_len" coordinates starting at "first".
715 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
716 * "dim" prescribes the parameters.
718 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
719 int first, int tile_len, int *tile_size)
721 int i;
722 isl_basic_map *bmap;
723 isl_constraint *c;
724 isl_local_space *ls;
726 dim = isl_space_add_dims(dim, isl_dim_in, len);
727 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
728 bmap = isl_basic_map_universe(isl_space_copy(dim));
729 ls = isl_local_space_from_space(dim);
731 for (i = 0; i < len - tile_len; ++i) {
732 int j = i < first ? i : i + tile_len;
733 int k = i < first ? i : i + 2 * tile_len;
735 c = isl_equality_alloc(isl_local_space_copy(ls));
736 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
737 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
738 bmap = isl_basic_map_add_constraint(bmap, c);
741 for (i = 0; i < tile_len; ++i) {
742 c = isl_equality_alloc(isl_local_space_copy(ls));
743 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
744 first + i, -1);
745 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
746 first + i, tile_size[i]);
747 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
748 first + i + tile_len, 1);
749 bmap = isl_basic_map_add_constraint(bmap, c);
751 c = isl_inequality_alloc(isl_local_space_copy(ls));
752 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
753 first + i + tile_len, 1);
754 bmap = isl_basic_map_add_constraint(bmap, c);
756 c = isl_inequality_alloc(isl_local_space_copy(ls));
757 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
758 first + i + tile_len, -1);
759 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
760 bmap = isl_basic_map_add_constraint(bmap, c);
763 isl_local_space_free(ls);
765 return isl_map_from_basic_map(bmap);
768 /* Construct a map from a domain of dimensionality "len"
769 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
770 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
771 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
772 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
773 * that are projected out at the end.
774 * "dim" prescribes the parameters.
776 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
777 int first, int wrap_len, int *wrap_size)
779 int i;
780 isl_basic_map *bmap;
781 isl_constraint *c;
782 isl_local_space *ls;
784 dim = isl_space_add_dims(dim, isl_dim_in, len);
785 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
786 bmap = isl_basic_map_universe(isl_space_copy(dim));
787 ls = isl_local_space_from_space(dim);
789 for (i = 0; i < len; ++i) {
790 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
792 c = isl_equality_alloc(isl_local_space_copy(ls));
793 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
794 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
795 bmap = isl_basic_map_add_constraint(bmap, c);
798 for (i = 0; i < wrap_len; ++i) {
799 c = isl_equality_alloc(isl_local_space_copy(ls));
800 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
801 first + i, -1);
802 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
803 first + wrap_len + i, 1);
804 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
805 first + 2 * wrap_len + i, wrap_size[i]);
806 bmap = isl_basic_map_add_constraint(bmap, c);
808 c = isl_inequality_alloc(isl_local_space_copy(ls));
809 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
810 first + wrap_len + i, 1);
811 bmap = isl_basic_map_add_constraint(bmap, c);
813 c = isl_inequality_alloc(isl_local_space_copy(ls));
814 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
815 first + wrap_len + i, -1);
816 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
817 bmap = isl_basic_map_add_constraint(bmap, c);
820 isl_local_space_free(ls);
822 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
823 first + 2 * wrap_len, wrap_len);
825 return isl_map_from_basic_map(bmap);
828 /* Add "n" parameters named prefix%d.
830 static __isl_give isl_set *add_params( __isl_take isl_set *set,
831 int n, const char *prefix)
833 int i;
834 unsigned nparam;
835 char name[20];
837 nparam = isl_set_dim(set, isl_dim_param);
838 set = isl_set_add_dims(set, isl_dim_param, n);
840 for (i = 0; i < n; ++i) {
841 snprintf(name, sizeof(name), "%s%d", prefix, i);
842 set = isl_set_set_dim_name(set, isl_dim_param,
843 nparam + i, name);
846 return set;
849 /* Equate the "n" dimensions of "set" starting at "first" to
850 * freshly created parameters named prefix%d.
852 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
853 int first, int n, const char *prefix)
855 int i;
856 unsigned nparam;
858 nparam = isl_set_dim(set, isl_dim_param);
860 set = add_params(set, n, prefix);
862 for (i = 0; i < n; ++i)
863 set = isl_set_equate(set, isl_dim_param, nparam + i,
864 isl_dim_set, first + i);
866 return set;
869 /* Given a parameter space "space", create a set of dimension "len"
870 * of which the "n" dimensions starting at "first" are equated to
871 * freshly created parameters named prefix%d.
873 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
874 int len, int first, int n, const char *prefix)
876 isl_set *set;
878 space = isl_space_set_from_params(space);
879 space = isl_space_add_dims(space, isl_dim_set, len);
880 set = isl_set_universe(space);
882 return parametrize(set, first, n, prefix);
885 /* Tile the B loops over the tile sizes and then tile/wrap
886 * the T1 loops over the blocks.
888 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
889 __isl_take isl_union_map *sched)
891 isl_space *dim;
892 isl_map *tiling, *block_tiling;
894 dim = isl_union_map_get_space(sched);
895 tiling = tile(isl_space_copy(dim), gen->untiled_len,
896 gen->tile_first, gen->tile_len, gen->tile_size);
898 if (gen->options->wrap)
899 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
900 gen->tile_first, gen->n_grid, gen->grid_dim);
901 else
902 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
903 gen->tile_first, gen->n_grid, gen->grid_dim);
905 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
907 tiling = isl_map_apply_range(tiling, block_tiling);
909 sched = isl_union_map_apply_range(sched,
910 isl_union_map_from_map(tiling));
912 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
914 return sched;
917 /* Equate the "T1P" iterators in the tiled schedule "sched"
918 * to the block dimensions.
920 static __isl_give isl_union_map *parametrize_tiled_schedule(
921 struct gpu_gen *gen, __isl_take isl_union_map *sched)
923 isl_space *dim;
924 isl_set *par;
926 dim = isl_union_map_get_space(sched);
927 par = parametrization(dim, gen->tiled_len,
928 gen->tile_first + gen->n_grid, gen->n_grid, "b");
929 sched = isl_union_map_intersect_range(sched,
930 isl_union_set_from_set(par));
932 return sched;
935 /* Tile/wrap the P1 loops over the threads.
937 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
938 __isl_take isl_union_map *sched)
940 isl_space *dim;
941 isl_map *tiling;
942 isl_set *par;
944 dim = isl_union_map_get_space(sched);
946 if (gen->options->wrap)
947 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
948 gen->shared_len, gen->n_block, gen->block_dim);
949 else
950 tiling = tile(isl_space_copy(dim), gen->tiled_len,
951 gen->shared_len, gen->n_block, gen->block_dim);
952 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
954 sched = isl_union_map_apply_range(sched,
955 isl_union_map_from_map(tiling));
957 par = parametrization(dim, gen->thread_tiled_len,
958 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
959 gen->n_block, "t");
960 sched = isl_union_map_intersect_range(sched,
961 isl_union_set_from_set(par));
963 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
965 return sched;
968 /* If the user asked for it, scale the shared memory tile loops
969 * (T1T and T2) of "sched" by gen->tile_size[i].
970 * If we are not performing "wrapping", then additionally scale the T1P
971 * loops by gen->grid_dim[i].
973 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
974 __isl_take isl_union_map *sched)
976 int i;
977 isl_space *dim;
978 isl_basic_map *scale;
979 isl_constraint *c;
980 isl_local_space *ls;
982 if (!gen->options->scale_tile_loops)
983 return sched;
985 dim = isl_union_map_get_space(sched);
986 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
987 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
988 scale = isl_basic_map_universe(isl_space_copy(dim));
989 ls = isl_local_space_from_space(dim);
991 for (i = 0; i < gen->tiled_len; ++i) {
992 int f = 1;
994 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
995 f = gen->tile_size[i - gen->tile_first];
996 if (!gen->options->wrap)
997 f *= gen->grid_dim[i - gen->tile_first];
998 } else if (i >= gen->tile_first + gen->n_grid &&
999 i < gen->tile_first + gen->n_grid + gen->tile_len) {
1000 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
1003 c = isl_equality_alloc(isl_local_space_copy(ls));
1004 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1005 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1006 scale = isl_basic_map_add_constraint(scale, c);
1009 isl_local_space_free(ls);
1011 sched = isl_union_map_apply_range(sched,
1012 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1014 return sched;
1017 /* If we are not performing "wrapping" and if the user asked for it,
1018 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1020 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1021 __isl_take isl_union_map *sched)
1023 int i;
1024 isl_space *dim;
1025 isl_basic_map *scale;
1026 isl_constraint *c;
1027 isl_local_space *ls;
1029 if (gen->options->wrap)
1030 return sched;
1031 if (!gen->options->scale_tile_loops)
1032 return sched;
1034 dim = isl_union_map_get_space(sched);
1035 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1036 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1037 scale = isl_basic_map_universe(isl_space_copy(dim));
1038 ls = isl_local_space_from_space(dim);
1040 for (i = 0; i < gen->thread_tiled_len; ++i) {
1041 int f = 1;
1043 if (i >= gen->shared_len &&
1044 i < gen->shared_len + gen->n_block)
1045 f = gen->block_dim[i - gen->shared_len];
1047 c = isl_equality_alloc(isl_local_space_copy(ls));
1048 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1049 c = 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 /* If we are not performing "wrapping" and if the user asked for it,
1062 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1064 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1065 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1067 int i;
1068 isl_space *dim;
1069 isl_basic_map *scale;
1070 isl_constraint *c;
1071 isl_local_space *ls;
1073 if (gen->options->wrap)
1074 return sched;
1075 if (!gen->options->scale_tile_loops)
1076 return sched;
1078 dim = isl_union_map_get_space(sched);
1079 dim = isl_space_add_dims(dim, isl_dim_in, len);
1080 dim = isl_space_add_dims(dim, isl_dim_out, len);
1081 scale = isl_basic_map_universe(isl_space_copy(dim));
1082 ls = isl_local_space_from_space(dim);
1084 for (i = 0; i < len; ++i) {
1085 int f = 1;
1087 if (i >= first && i < first + n_tile)
1088 f = gen->kernel->block_dim[i - first];
1090 c = isl_equality_alloc(isl_local_space_copy(ls));
1091 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1092 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1093 scale = isl_basic_map_add_constraint(scale, c);
1096 isl_local_space_free(ls);
1098 sched = isl_union_map_apply_range(sched,
1099 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1101 return sched;
1104 /* Add "len" parameters p[i] called prefix%d,
1105 * with bounds to 0 <= p[i] < size[i].
1107 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1108 int len, int *size, const char *prefix)
1110 int i;
1111 unsigned nparam;
1112 isl_space *dim;
1113 isl_basic_set *bset;
1114 isl_constraint *c;
1115 isl_local_space *ls;
1116 char name[20];
1118 nparam = isl_set_dim(set, isl_dim_param);
1119 set = isl_set_add_dims(set, isl_dim_param, len);
1121 for (i = 0; i < len; ++i) {
1122 snprintf(name, sizeof(name), "%s%d", prefix, i);
1123 set = isl_set_set_dim_name(set, isl_dim_param,
1124 nparam + i, name);
1127 dim = isl_set_get_space(set);
1128 bset = isl_basic_set_universe(isl_space_copy(dim));
1129 ls = isl_local_space_from_space(dim);
1131 for (i = 0; i < len; ++i) {
1132 c = isl_inequality_alloc(isl_local_space_copy(ls));
1133 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1134 nparam + i, 1);
1135 bset = isl_basic_set_add_constraint(bset, c);
1137 c = isl_inequality_alloc(isl_local_space_copy(ls));
1138 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1139 nparam + i, -1);
1140 c = isl_constraint_set_constant_si(c, size[i] - 1);
1141 bset = isl_basic_set_add_constraint(bset, c);
1144 isl_local_space_free(ls);
1146 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1149 /* Add "len" parameters p[i] called prefix%d,
1150 * with bounds to 0 <= p[i] < size[i].
1152 static __isl_give isl_set *add_bounded_parameters_dynamic(
1153 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1154 const char *prefix)
1156 int i, len;
1157 unsigned nparam;
1158 isl_space *space;
1159 isl_local_space *ls;
1160 char name[20];
1162 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1163 nparam = isl_set_dim(set, isl_dim_param);
1164 set = isl_set_add_dims(set, isl_dim_param, len);
1166 for (i = 0; i < len; ++i) {
1167 snprintf(name, sizeof(name), "%s%d", prefix, i);
1168 set = isl_set_set_dim_name(set, isl_dim_param,
1169 nparam + i, name);
1172 space = isl_space_params(isl_set_get_space(set));
1173 ls = isl_local_space_from_space(space);
1174 for (i = 0; i < len; ++i) {
1175 isl_pw_aff *param, *size_i, *zero;
1176 isl_set *bound;
1178 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1179 isl_dim_param, nparam + i);
1181 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1182 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1183 set = isl_set_intersect_params(set, bound);
1185 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1186 bound = isl_pw_aff_ge_set(param, zero);
1187 set = isl_set_intersect_params(set, bound);
1189 isl_local_space_free(ls);
1191 return set;
1194 /* Construct a map from an access to group->array to the corresponding
1195 * shared/private memory tile.
1196 * The map is of the form
1198 * { [D[i] -> A[a]] -> T[t] }
1200 * where D represents the initial shared_len dimensions
1201 * of the computed schedule.
1203 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1205 struct gpu_array_tile *tile;
1206 isl_multi_aff *tiling;
1208 tile = group->private_tile;
1209 if (!tile)
1210 tile = group->shared_tile;
1212 tiling = isl_multi_aff_copy(tile->tiling);
1214 return isl_map_from_multi_aff(tiling);
1217 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1219 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1220 unsigned pos)
1222 isl_val *v;
1223 int fixed;
1225 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1226 if (!v)
1227 return -1;
1228 fixed = isl_val_is_int(v);
1229 isl_val_free(v);
1231 return fixed;
1234 /* Given a schedule that iterates over all elements in a piece of an array,
1235 * perform tiling/wrapping over the threads.
1237 * In particular, we tile the final iterators so that the final thread
1238 * dimension runs over the final array dimension.
1239 * However, if those final iterators have only a single iteration,
1240 * we try to tile earlier iterators instead.
1242 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1243 __isl_take isl_map *sched)
1245 isl_space *dim;
1246 isl_union_map *usched;
1247 isl_map *tiling;
1248 isl_set *par;
1249 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1250 int n_tile;
1251 int first;
1253 n_tile = gen->kernel->n_block;
1254 if (n_tile > nvar) {
1255 int i;
1256 sched = isl_map_insert_dims(sched,
1257 isl_dim_out, 0, n_tile - nvar);
1258 for (i = 0; i < n_tile - nvar; ++i)
1259 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1260 nvar = n_tile;
1263 first = nvar - n_tile;
1265 for (; first > 0; first --)
1266 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1267 break;
1269 dim = isl_map_get_space(sched);
1270 dim = isl_space_params(dim);
1271 if (gen->options->wrap)
1272 tiling = wrap(isl_space_copy(dim), nvar, first,
1273 n_tile, gen->kernel->block_dim);
1274 else
1275 tiling = tile(isl_space_copy(dim), nvar, first,
1276 n_tile, gen->kernel->block_dim);
1277 sched = isl_map_apply_range(sched, tiling);
1279 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1280 sched = isl_map_intersect_range(sched, par);
1282 usched = isl_union_map_from_map(sched);
1283 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1284 first, n_tile);
1285 sched = isl_map_from_union_map(usched);
1287 return sched;
1290 /* Return the union of all read (read = 1) and/or write (write = 1)
1291 * access relations in the group.
1293 static __isl_give isl_union_map *group_access_relation(
1294 struct gpu_array_ref_group *group, int read, int write)
1296 int i;
1297 isl_union_map *access;
1299 access = isl_union_map_empty(isl_map_get_space(group->access));
1300 for (i = 0; i < group->n_ref; ++i) {
1301 isl_map *map_i;
1303 if (!((read && group->refs[i]->read) ||
1304 (write && group->refs[i]->write)))
1305 continue;
1306 map_i = isl_map_copy(group->refs[i]->access);
1307 access = isl_union_map_union(access,
1308 isl_union_map_from_map(map_i));
1311 return access;
1314 /* Return the extent of "array", recomputed from the bounds.
1315 * The recomputed extent may be simpler than the original extent.
1317 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1319 int i;
1320 isl_id *id;
1321 isl_space *space;
1322 isl_local_space *ls;
1323 isl_set *extent;
1325 id = isl_set_get_tuple_id(array->extent);
1326 space = isl_set_get_space(array->extent);
1327 extent = isl_set_universe(isl_space_copy(space));
1328 ls = isl_local_space_from_space(space);
1329 for (i = 0; i < array->n_index; ++i) {
1330 isl_pw_aff *bound;
1331 isl_aff *aff;
1332 isl_pw_aff *index;
1333 isl_set *lt;
1335 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1337 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1338 isl_dim_set, i);
1339 index = isl_pw_aff_from_aff(aff);
1340 bound = isl_pw_aff_copy(array->bound[i]);
1341 bound = isl_pw_aff_from_range(bound);
1342 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1343 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1344 isl_id_copy(id));
1345 lt = isl_pw_aff_lt_set(index, bound);
1346 extent = isl_set_intersect(extent, lt);
1348 isl_local_space_free(ls);
1349 isl_id_free(id);
1351 return extent;
1354 /* Return a map from the first shared_len dimensions of the computed
1355 * schedule to the array tile in
1356 * global memory that corresponds to the shared memory copy.
1358 * In particular, return a map
1360 * { D[i] -> A[a] }
1362 * with constraints
1364 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1366 * and
1368 * 0 <= a <= array_size - 1 (2)
1370 * Note that if some stride has been detected (i.e., when
1371 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1372 * to the shifted and scaled down version.
1374 * Constraints (1) are obtained by mapping the size constraints on the
1375 * shared/private memory tile back to the access relation.
1376 * Constraints (2) are obtained from the (recomputed) extent.
1378 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1380 int i;
1381 int n_index = group->array->n_index;
1382 isl_map *tile;
1383 isl_space *space;
1384 isl_set *local;
1385 isl_set *extent;
1387 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1388 space = isl_space_range(space);
1389 local = isl_set_universe(space);
1390 for (i = 0; i < n_index; ++i) {
1391 isl_val *bound;
1393 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1394 bound = isl_val_copy(group->shared_tile->bound[i].size);
1395 bound = isl_val_sub_ui(bound, 1);
1396 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1398 local = isl_set_preimage_multi_aff(local,
1399 isl_multi_aff_copy(group->shared_tile->tiling));
1400 tile = isl_set_unwrap(local);
1401 extent = array_extent(group->array);
1402 tile = isl_map_intersect_range(tile, extent);
1404 return tile;
1407 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1408 * return the corresponding mapping from the AST schedule to
1409 * to the first shared_len dimensions of the schedule computed by PPCG.
1411 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1412 __isl_take isl_pw_multi_aff *iterator_map)
1414 isl_union_map *umap;
1415 isl_space *space;
1416 isl_map *map, *sched;;
1418 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1419 space = isl_space_from_domain(space);
1420 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1422 umap = isl_union_map_copy(gen->shared_sched);
1423 umap = isl_union_map_apply_range(umap,
1424 isl_union_map_copy(gen->shared_proj));
1425 map = isl_union_map_extract_map(umap, space);
1426 isl_union_map_free(umap);
1428 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1429 sched = isl_map_detect_equalities(sched);
1431 return isl_pw_multi_aff_from_map(sched);
1434 /* Set unroll[j] if the input dimension j is involved in
1435 * the index expression represented by ma.
1437 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1438 void *user)
1440 int i, j;
1441 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1442 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1443 int *unroll = user;
1445 for (i = 0; i < n_out; ++i) {
1446 isl_aff *aff;
1448 aff = isl_multi_aff_get_aff(ma, i);
1449 for (j = 0; j < n_in; ++j)
1450 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1451 unroll[j] = 1;
1452 isl_aff_free(aff);
1455 isl_set_free(set);
1456 isl_multi_aff_free(ma);
1457 return 0;
1460 /* Given an array pos mapping input dimensions to the corresponding
1461 * output dimension, construct the corresponding map.
1463 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1464 int *pos, int len)
1466 int i;
1467 isl_constraint *c;
1468 isl_basic_map *bmap;
1469 isl_local_space *ls;
1471 dim = isl_space_add_dims(dim, isl_dim_in, len);
1472 dim = isl_space_add_dims(dim, isl_dim_out, len);
1473 bmap = isl_basic_map_universe(isl_space_copy(dim));
1474 ls = isl_local_space_from_space(dim);
1476 for (i = 0; i < len; ++i) {
1477 c = isl_equality_alloc(isl_local_space_copy(ls));
1478 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1479 -1);
1480 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1482 bmap = isl_basic_map_add_constraint(bmap, c);
1484 isl_local_space_free(ls);
1486 return isl_map_from_basic_map(bmap);
1489 /* Find all loops involved in any of the index expressions for any of
1490 * the private accesses, move them innermost and then mark them as
1491 * requiring unrolling by setting gen->first_unroll.
1492 * The loops involved should all be parallel because of the checks
1493 * we performed in check_private_group_access. Moving them innermost
1494 * is therefore a valid transformation.
1496 * Loops up to gen->shared_len are generated before the mapping to
1497 * threads is applied. They should therefore be ignored.
1499 * We compute the hidden equalities of the schedule first
1500 * since we will need them in our calls to isl_pw_multi_aff_from_map
1501 * and because we want to make sure that the same equalities
1502 * are also available to the code generator.
1504 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1505 __isl_take isl_union_map *sched)
1507 int i, j;
1508 int unroll[gen->thread_tiled_len];
1509 int perm[gen->thread_tiled_len];
1510 isl_space *dim;
1511 isl_map *permute;
1512 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1514 gen->first_unroll = -1;
1516 sched = isl_union_map_detect_equalities(sched);
1517 for (i = 0; i < gen->thread_tiled_len; ++i)
1518 unroll[i] = 0;
1519 for (i = 0; i < gen->prog->n_array; ++i) {
1520 struct gpu_array_info *array = &gen->prog->array[i];
1522 for (j = 0; j < array->n_group; ++j) {
1523 isl_union_map *access;
1524 isl_map *acc;
1525 isl_pw_multi_aff *pma;
1527 if (!array->groups[j]->private_tile)
1528 continue;
1530 access = group_access_relation(array->groups[j], 1, 1);
1531 access = isl_union_map_apply_domain(access,
1532 isl_union_map_copy(sched));
1534 acc = isl_map_from_union_map(access);
1535 pma = isl_pw_multi_aff_from_map(acc);
1536 isl_pw_multi_aff_foreach_piece(pma,
1537 &check_unroll, unroll);
1539 isl_pw_multi_aff_free(pma);
1543 for (i = gen->shared_len; i < len; ++i)
1544 if (unroll[i])
1545 break;
1547 if (i >= len)
1548 return sched;
1550 for (i = len; i < gen->thread_tiled_len; ++i)
1551 if (unroll[i])
1552 return sched;
1554 j = 0;
1555 for (i = 0; i < gen->shared_len; ++i)
1556 perm[i] = j++;
1557 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1558 if (!unroll[i])
1559 perm[i] = j++;
1560 gen->first_unroll = j - gen->shared_len;
1561 for (i = gen->shared_len; i < len; ++i)
1562 if (unroll[i])
1563 perm[i] = j++;
1565 dim = isl_union_map_get_space(sched);
1566 permute = permutation(dim, perm, gen->thread_tiled_len);
1567 sched = isl_union_map_apply_range(sched,
1568 isl_union_map_from_map(permute));
1570 return sched;
1573 /* Given a constraint
1575 * a(p,i) + j = g f(e)
1577 * or -a(p,i) - j = g f(e) if sign < 0,
1578 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1579 * a(p,i) is assumed to be an expression in only the parameters
1580 * and the input dimensions.
1582 static void extract_stride(__isl_keep isl_constraint *c,
1583 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1585 int i;
1586 isl_val *v;
1587 isl_space *space;
1588 unsigned nparam;
1589 unsigned nvar;
1590 isl_aff *aff;
1592 isl_val_free(bound->stride);
1593 bound->stride = isl_val_copy(stride);
1595 space = isl_constraint_get_space(c);
1596 space = isl_space_domain(space);
1598 nparam = isl_space_dim(space, isl_dim_param);
1599 nvar = isl_space_dim(space, isl_dim_set);
1601 v = isl_constraint_get_constant_val(c);
1602 if (sign < 0)
1603 v = isl_val_neg(v);
1604 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1605 aff = isl_aff_set_constant_val(aff, v);
1607 for (i = 0; i < nparam; ++i) {
1608 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1609 continue;
1610 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1611 if (sign < 0)
1612 v = isl_val_neg(v);
1613 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1616 for (i = 0; i < nvar; ++i) {
1617 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1618 continue;
1619 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1620 if (sign < 0)
1621 v = isl_val_neg(v);
1622 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1625 bound->shift = aff;
1628 /* Given an equality constraint of a map with a single output dimension j,
1629 * check if the constraint is of the form
1631 * a(p,i) + j = g f(e)
1633 * with a(p,i) an expression in the parameters and input dimensions
1634 * and f(e) an expression in the existentially quantified variables.
1635 * If so, and if g is larger than any such g from a previously considered
1636 * constraint, then call extract_stride to record the stride information
1637 * in bound.
1639 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1641 int i;
1642 isl_ctx *ctx;
1643 isl_val *v;
1644 unsigned n_div;
1645 struct gpu_array_bound *bound = user;
1647 ctx = isl_constraint_get_ctx(c);
1648 n_div = isl_constraint_dim(c, isl_dim_div);
1649 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1651 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1652 int s = isl_val_sgn(v);
1653 isl_val *stride = isl_val_zero(ctx);
1655 isl_val_free(v);
1656 for (i = 0; i < n_div; ++i) {
1657 v = isl_constraint_get_coefficient_val(c,
1658 isl_dim_div, i);
1659 stride = isl_val_gcd(stride, v);
1661 if (!isl_val_is_zero(stride) &&
1662 isl_val_gt(stride, bound->stride))
1663 extract_stride(c, bound, stride, s);
1665 isl_val_free(stride);
1666 } else
1667 isl_val_free(v);
1669 isl_constraint_free(c);
1670 return 0;
1673 /* Given contraints on an array index i, check if we can find
1674 * a shift a(p) and a stride g such that
1676 * a(p) + i = 0 mod g
1678 * If so, record the information in bound and apply the mapping
1679 * i -> (i + a(p))/g to the array index in bounds and return
1680 * the new constraints.
1681 * If not, simply return the original constraints.
1683 * If bounds is a subset of the space
1685 * D -> i
1687 * then the bound recorded in bound->shift is of the form
1689 * D -> s(D)
1691 * with s(D) equal to a(p) above.
1692 * The mapping recorded in bound->shift_map is of the form
1694 * [D -> i] -> [D -> (i + S(D))/g]
1696 * This mapping is computed as follows.
1697 * We first introduce "i" in the domain through precomposition
1698 * with [D -> i] -> D obtaining
1700 * [D -> i] -> s(D)
1702 * Adding [D -> i] -> i produces
1704 * [D -> i] -> i + s(D)
1706 * and the domain product with [D -> i] -> D yields
1708 * [D -> i] -> [D -> i + s(D)]
1710 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1712 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1713 __isl_take isl_basic_map *bounds)
1715 isl_space *space;
1716 isl_basic_map *hull;
1717 isl_basic_map *shift, *id, *bmap, *scale;
1718 isl_basic_set *bset;
1719 isl_aff *aff;
1721 bound->stride = NULL;
1723 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1725 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1727 isl_basic_map_free(hull);
1729 if (!bound->stride)
1730 return bounds;
1732 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1733 space = isl_basic_map_get_space(bounds);
1734 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1735 shift = isl_basic_map_apply_range(bmap, shift);
1736 space = isl_basic_map_get_space(bounds);
1737 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1738 shift = isl_basic_map_sum(id, shift);
1739 space = isl_basic_map_get_space(bounds);
1740 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1741 shift = isl_basic_map_range_product(id, shift);
1743 space = isl_space_domain(isl_basic_map_get_space(bounds));
1744 id = isl_basic_map_identity(isl_space_map_from_set(space));
1745 space = isl_space_range(isl_basic_map_get_space(bounds));
1746 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1747 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1748 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
1749 scale = isl_basic_map_from_aff(aff);
1750 scale = isl_basic_map_product(id, scale);
1752 bound->shift_map = isl_basic_map_apply_range(shift, scale);
1753 bmap = isl_basic_map_copy(bound->shift_map);
1754 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1755 bounds = isl_basic_set_unwrap(bset);
1757 return bounds;
1760 /* Data used in compute_array_dim_size and compute_size_in_direction.
1762 * pos is the position of the variable representing the array index,
1763 * i.e., the variable for which want to compute the size. This variable
1764 * is also the last variable in the set.
1766 struct gpu_size_info {
1767 isl_basic_set *bset;
1768 struct gpu_array_bound *bound;
1769 int pos;
1772 /* Given a constraint from the basic set describing the bounds on
1773 * an array index, check if it is a lower bound, say m i >= b(x), and,
1774 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
1775 * upper bound. If so, and if this bound is smaller than any bound
1776 * derived from earlier constraints, set the size to this bound on
1777 * the expression and the lower bound to ceil(b(x)/m).
1779 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
1781 struct gpu_size_info *size = user;
1782 unsigned nparam;
1783 unsigned n_div;
1784 isl_val *v;
1785 isl_aff *aff;
1786 isl_aff *lb;
1788 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
1789 n_div = isl_constraint_dim(c, isl_dim_div);
1791 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
1792 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
1793 isl_constraint_free(c);
1794 return 0;
1797 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
1798 aff = isl_aff_ceil(aff);
1800 lb = isl_aff_copy(aff);
1802 aff = isl_aff_neg(aff);
1803 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
1805 v = isl_basic_set_max_val(size->bset, aff);
1806 isl_aff_free(aff);
1808 if (isl_val_is_int(v)) {
1809 v = isl_val_add_ui(v, 1);
1810 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
1811 isl_val_free(size->bound->size);
1812 size->bound->size = isl_val_copy(v);
1813 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
1814 isl_aff_free(size->bound->lb);
1815 size->bound->lb = isl_aff_copy(lb);
1818 isl_val_free(v);
1819 isl_aff_free(lb);
1821 isl_constraint_free(c);
1823 return 0;
1826 /* Given a basic map "bounds" that maps parameters and input dimensions
1827 * to a single output dimension, look for an expression in the parameters
1828 * and input dimensions such that the range of the output dimension shifted
1829 * by this expression is a constant.
1831 * In particular, we currently only consider lower bounds on the output
1832 * dimension as candidate expressions.
1834 static int compute_array_dim_size(struct gpu_array_bound *bound,
1835 __isl_take isl_basic_map *bounds)
1837 struct gpu_size_info size;
1839 bounds = isl_basic_map_detect_equalities(bounds);
1840 bounds = check_stride(bound, bounds);
1842 bound->size = NULL;
1843 bound->lb = NULL;
1845 size.bound = bound;
1846 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
1847 size.bset = isl_basic_map_wrap(bounds);
1848 size.bset = isl_basic_set_flatten(size.bset);
1849 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
1850 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
1851 &size);
1852 isl_basic_set_free(size.bset);
1854 return bound->size ? 0 : -1;
1857 /* Check if we can find a memory tile for the given array
1858 * based on the given accesses, and if so, put the results in "tile".
1860 * We project the accesses on each index in turn and look for a parametric
1861 * offset such that the size is constant.
1863 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
1865 int i;
1867 for (i = 0; i < tile->n; ++i) {
1868 isl_map *access_i;
1869 isl_basic_map *hull;
1871 access_i = isl_map_copy(access);
1872 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
1873 access_i = isl_map_project_out(access_i, isl_dim_out,
1874 1, tile->n - (i + 1));
1875 access_i = isl_map_compute_divs(access_i);
1876 hull = isl_map_simple_hull(access_i);
1877 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
1878 return 0;
1881 return 1;
1884 /* Construct a map with input the shared tile loops and the loops that
1885 * will be wrapped around the threads that relates these later loops
1886 * to the thread indices and then projects them out.
1888 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
1890 isl_map *priv;
1891 isl_map *tiling;
1892 isl_map *proj;
1893 isl_set *par;
1894 isl_space *dim;
1896 dim = isl_union_map_get_space(gen->shared_sched);
1898 if (gen->options->wrap)
1899 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
1900 gen->shared_len, gen->n_block, gen->block_dim);
1901 else
1902 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
1903 gen->shared_len, gen->n_block, gen->block_dim);
1905 priv = tiling;
1907 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
1908 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1909 gen->n_block, "t");
1911 priv = isl_map_align_params(priv, isl_set_get_space(par));
1912 priv = isl_map_intersect_range(priv, par);
1914 dim = isl_map_get_space(priv);
1915 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
1916 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
1917 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
1918 gen->shared_len);
1920 priv = isl_map_apply_range(priv, proj);
1922 return priv;
1925 /* Construct a map from domain_dim to domain_dim that increments
1926 * the dimension at position "pos" and leaves all other dimensions
1927 * constant.
1929 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
1931 int i;
1932 int len = isl_space_dim(domain_dim, isl_dim_set);
1933 isl_space *dim;
1934 isl_basic_map *next;
1935 isl_local_space *ls;
1937 dim = isl_space_map_from_set(domain_dim);
1938 next = isl_basic_map_universe(isl_space_copy(dim));
1939 ls = isl_local_space_from_space(dim);
1941 for (i = 0; i < len; ++i) {
1942 isl_constraint *c;
1944 c = isl_equality_alloc(isl_local_space_copy(ls));
1945 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
1946 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1947 if (i == pos)
1948 c = isl_constraint_set_constant_si(c, 1);
1949 next = isl_basic_map_add_constraint(next, c);
1952 isl_local_space_free(ls);
1954 return isl_map_from_basic_map(next);
1957 /* Check if the given access is coalesced.
1958 * That is, check whether incrementing the dimension that will get
1959 * wrapped over the last thread index results in incrementing
1960 * the last array index.
1962 * This function is only called for access relations without reuse.
1964 static int access_is_coalesced(struct gpu_gen *gen,
1965 __isl_keep isl_union_map *access)
1967 isl_space *dim;
1968 isl_map *access_map;
1969 isl_map *next_thread_x;
1970 isl_map *next_element;
1971 isl_map *map;
1972 int coalesced;
1974 access = isl_union_map_copy(access);
1975 access = isl_union_map_apply_domain(access,
1976 isl_union_map_copy(gen->tiled_sched));
1977 access_map = isl_map_from_union_map(access);
1979 dim = isl_map_get_space(access_map);
1980 dim = isl_space_domain(dim);
1981 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
1983 dim = isl_map_get_space(access_map);
1984 dim = isl_space_range(dim);
1985 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
1987 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
1988 map = isl_map_apply_range(map, access_map);
1990 coalesced = isl_map_is_subset(map, next_element);
1992 isl_map_free(next_element);
1993 isl_map_free(map);
1995 return coalesced;
1998 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
1999 * dimensions of the computed schedule, check if it is bijective for
2000 * fixed values of the first gen->shared_len dimensions.
2001 * We perform this check by equating these dimensions to parameters.
2003 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2005 int res;
2006 isl_set *par;
2007 isl_space *space;
2009 access = isl_map_copy(access);
2010 space = isl_space_params(isl_map_get_space(access));
2011 par = parametrization(space, gen->shared_len + gen->n_block,
2012 0, gen->shared_len, "s");
2013 access = isl_map_intersect_domain(access, par);
2014 res = isl_map_is_bijective(access);
2015 isl_map_free(access);
2017 return res;
2020 /* Look for the last shared tile loop that affects the offset of "tile"
2021 * and return the result.
2022 * If there is no such loop, then return the index of the loop
2023 * before the first shared tile loop, in particular gen->tile_first - 1.
2025 static int compute_tile_last_shared(struct gpu_gen *gen,
2026 struct gpu_array_tile *tile)
2028 int i, j;
2030 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2031 for (i = 0; i < tile->n; ++i) {
2032 isl_aff *lb;
2033 isl_aff *shift;
2035 lb = tile->bound[i].lb;
2036 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2037 break;
2039 shift = tile->bound[i].shift;
2040 if (!shift)
2041 continue;
2042 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2043 break;
2045 if (i < tile->n)
2046 break;
2049 return j;
2052 /* Look for the last shared tile loop that affects the offset of the
2053 * shared or private tile and store the result in group->last_shared.
2054 * If there is no such loop, then group->last_shared is set to a value
2055 * before the first shared tile loop, in particular gen->tile_first - 1.
2056 * If there is no tile defined on the array reference group,
2057 * then set group->last_shared to gen->shared_len - 1.
2059 static void set_last_shared(struct gpu_gen *gen,
2060 struct gpu_array_ref_group *group)
2062 struct gpu_array_tile *tile;
2064 group->last_shared = gen->shared_len - 1;
2066 tile = group->private_tile;
2067 if (!tile)
2068 tile = group->shared_tile;
2069 if (!tile)
2070 return;
2072 group->last_shared = compute_tile_last_shared(gen, tile);
2075 /* Compute a privatized copy of all access relations from reference groups that
2076 * are mapped to private memory and store the result in gen->privatization.
2078 static void compute_private_access(struct gpu_gen *gen)
2080 int i, j;
2081 isl_union_map *private;
2083 if (!gen->options->use_private_memory)
2084 return;
2086 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2088 for (i = 0; i < gen->prog->n_array; ++i) {
2089 struct gpu_array_info *array = &gen->prog->array[i];
2091 if (gpu_array_is_read_only_scalar(array))
2092 continue;
2094 for (j = 0; j < array->n_group; ++j) {
2095 if (!array->groups[j]->private_tile)
2096 continue;
2098 private = isl_union_map_union(private,
2099 group_access_relation(array->groups[j], 1, 1));
2103 if (isl_union_map_is_empty(private))
2104 isl_union_map_free(private);
2105 else {
2106 isl_union_map *priv;
2108 private = isl_union_map_apply_domain(private,
2109 isl_union_map_copy(gen->shared_sched));
2110 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2111 private = isl_union_map_apply_domain(private, priv);
2112 gen->private_access = private;
2116 /* Compute the size of the tile specified by "tile"
2117 * in number of elements and return the result.
2119 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2121 int i;
2122 isl_val *size;
2124 size = isl_val_one(ctx);
2126 for (i = 0; i < tile->n; ++i)
2127 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2129 return size;
2132 /* If max_shared_memory is not set to infinity (-1), then make
2133 * sure that the total amount of shared memory required by the
2134 * array reference groups mapped to shared memory is no larger
2135 * than this maximum.
2137 * We apply a greedy approach and discard (keep in global memory)
2138 * those groups that would result in a total memory size that
2139 * is larger than the maximum.
2141 static void check_shared_memory_bound(struct gpu_gen *gen)
2143 int i, j;
2144 isl_val *left, *size;
2146 if (gen->options->max_shared_memory < 0)
2147 return;
2149 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2151 for (i = 0; i < gen->prog->n_array; ++i) {
2152 struct gpu_array_info *array = &gen->prog->array[i];
2154 for (j = 0; j < array->n_group; ++j) {
2155 struct gpu_array_ref_group *group;
2157 group = array->groups[j];
2158 if (!group->shared_tile)
2159 continue;
2161 size = tile_size(gen->ctx, group->shared_tile);
2162 size = isl_val_mul_ui(size, array->size);
2164 if (isl_val_le(size, left)) {
2165 left = isl_val_sub(left, size);
2166 continue;
2168 isl_val_free(size);
2170 group->shared_tile = free_tile(group->shared_tile);
2174 isl_val_free(left);
2177 /* Given a description of an array tile "tile" and the "space"
2179 * { D -> A }
2181 * where D represents the first shared_len schedule dimensions
2182 * and A represents the array, construct an isl_multi_aff
2184 * { [D[i] -> A[a]] -> A'[a'] }
2186 * with A' a scaled down copy of A according to the shifts and strides
2187 * in "tile". In particular,
2189 * a' = (a + shift(i))/stride
2191 * "insert_array" represents
2193 * { [D -> A] -> D }
2195 * and is used to insert A into the domain of functions that only
2196 * reference D.
2198 static __isl_give isl_multi_aff *strided_tile(
2199 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2200 __isl_keep isl_multi_aff *insert_array)
2202 int i;
2203 isl_ctx *ctx;
2204 isl_multi_aff *shift;
2205 isl_multi_val *stride;
2206 isl_space *space2;
2207 isl_local_space *ls;
2208 isl_multi_aff *tiling;
2210 ctx = isl_space_get_ctx(space);
2211 space2 = isl_space_domain(isl_space_copy(space));
2212 ls = isl_local_space_from_space(space2);
2213 space2 = isl_space_range(isl_space_copy(space));
2214 stride = isl_multi_val_zero(space2);
2215 shift = isl_multi_aff_zero(isl_space_copy(space));
2217 for (i = 0; i < tile->n; ++i) {
2218 struct gpu_array_bound *bound = &tile->bound[i];
2219 isl_val *stride_i;
2220 isl_aff *shift_i;
2222 if (tile->bound[i].shift) {
2223 stride_i = isl_val_copy(bound->stride);
2224 shift_i = isl_aff_copy(bound->shift);
2225 } else {
2226 stride_i = isl_val_one(ctx);
2227 shift_i = isl_aff_zero_on_domain(
2228 isl_local_space_copy(ls));
2231 stride = isl_multi_val_set_val(stride, i, stride_i);
2232 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2234 isl_local_space_free(ls);
2236 shift = isl_multi_aff_pullback_multi_aff(shift,
2237 isl_multi_aff_copy(insert_array));
2239 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2240 tiling = isl_multi_aff_add(tiling, shift);
2241 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2243 return tiling;
2246 /* Compute a tiling for the array reference group "group".
2248 * The tiling is of the form
2250 * { [D[i] -> A[a]] -> T[t] }
2252 * where D represents the first shared_len schedule dimensions,
2253 * A represents the global array and T represents the shared or
2254 * private memory tile. The name of T is the name of the local
2255 * array.
2257 * If there is any stride in the accesses, then the mapping is
2259 * t = (a + shift(i))/stride - lb(i)
2261 * otherwise, it is simply
2263 * t = a - lb(i)
2265 static void compute_group_tiling(struct gpu_array_ref_group *group)
2267 int i;
2268 struct gpu_array_tile *tile;
2269 struct gpu_array_info *array = group->array;
2270 isl_space *space;
2271 isl_multi_aff *tiling, *lb, *insert_array;
2272 isl_printer *p;
2273 char *local_name;
2275 tile = group->private_tile;
2276 if (!tile)
2277 tile = group->shared_tile;
2278 if (!tile)
2279 return;
2281 space = isl_map_get_space(group->access);
2282 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2284 for (i = 0; i < tile->n; ++i)
2285 if (tile->bound[i].shift)
2286 break;
2288 if (i < tile->n)
2289 tiling = strided_tile(tile, space, insert_array);
2290 else
2291 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2293 lb = isl_multi_aff_zero(space);
2294 for (i = 0; i < tile->n; ++i) {
2295 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2296 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2298 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2300 tiling = isl_multi_aff_sub(tiling, lb);
2302 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2303 p = print_array_name(p, group);
2304 local_name = isl_printer_get_str(p);
2305 isl_printer_free(p);
2306 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2307 free(local_name);
2309 tile->tiling = tiling;
2312 /* Compute a tiling for all the array reference groups.
2314 static void compute_group_tilings(struct gpu_gen *gen)
2316 int i, j;
2318 for (i = 0; i < gen->prog->n_array; ++i) {
2319 struct gpu_array_info *array = &gen->prog->array[i];
2321 for (j = 0; j < array->n_group; ++j)
2322 compute_group_tiling(array->groups[j]);
2326 /* Fill up the groups array with singleton groups, i.e., one group
2327 * per reference, initializing the array, access, write, n_ref and refs fields.
2328 * In particular the access field is initialized to the scheduled
2329 * access relation of the array reference.
2331 * Return the number of elements initialized, i.e., the number of
2332 * active references in the current kernel.
2334 static int populate_array_references(struct gpu_array_info *array,
2335 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2337 int i;
2338 int n;
2339 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2341 n = 0;
2342 for (i = 0; i < array->n_ref; ++i) {
2343 isl_union_map *umap;
2344 isl_map *map;
2345 struct gpu_array_ref_group *group;
2346 struct gpu_stmt_access *access = array->refs[i];
2348 map = isl_map_copy(access->access);
2349 umap = isl_union_map_from_map(map);
2350 umap = isl_union_map_apply_domain(umap,
2351 isl_union_map_copy(sched));
2353 if (isl_union_map_is_empty(umap)) {
2354 isl_union_map_free(umap);
2355 continue;
2358 map = isl_map_from_union_map(umap);
2359 map = isl_map_detect_equalities(map);
2361 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2362 assert(group);
2363 group->array = array;
2364 group->access = map;
2365 group->write = access->write;
2366 group->refs = &array->refs[i];
2367 group->n_ref = 1;
2369 groups[n++] = group;
2372 return n;
2375 /* If group->n_ref == 1, then group->refs was set by
2376 * populate_array_references to point directly into
2377 * group->array->refs and should not be freed.
2378 * If group->n_ref > 1, then group->refs was set by join_groups
2379 * to point to a newly allocated array.
2381 static void free_array_ref_group(struct gpu_array_ref_group *group)
2383 if (!group)
2384 return;
2385 free_tile(group->shared_tile);
2386 free_tile(group->private_tile);
2387 isl_map_free(group->access);
2388 if (group->n_ref > 1)
2389 free(group->refs);
2390 free(group);
2393 /* Given a map where the input dimensions represent the tile loops,
2394 * eliminate the innermost of those that have a fixed value
2395 * until we reach one that does not (obviously) have a fixed value.
2397 static __isl_give isl_map *eliminate_fixed_inner_loops(
2398 __isl_take isl_map *access)
2400 int i, n;
2402 n = isl_map_dim(access, isl_dim_in);
2404 for (i = n - 1; i >= 0; --i) {
2405 if (!map_plain_is_fixed(access, isl_dim_in, i))
2406 break;
2407 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2409 return access;
2412 /* Check if the access relations of group1 and group2 overlap within
2413 * the innermost loop. In particular, ignore any inner dimension
2414 * with a fixed value.
2415 * The copying to and from shared memory will be performed within
2416 * the innermost actual loop so we are only allowed to consider
2417 * the dimensions up to that innermost loop while checking whether
2418 * two access relations overlap.
2420 static int accesses_overlap(struct gpu_array_ref_group *group1,
2421 struct gpu_array_ref_group *group2)
2423 int empty;
2424 isl_map *access1, *access2;
2426 access1 = isl_map_copy(group1->access);
2427 access1 = eliminate_fixed_inner_loops(access1);
2428 access2 = isl_map_copy(group2->access);
2429 access2 = eliminate_fixed_inner_loops(access2);
2430 access1 = isl_map_intersect(access1, access2);
2431 empty = isl_map_is_empty(access1);
2432 isl_map_free(access1);
2434 return !empty;
2437 /* Combine the given two groups into a single group, containing
2438 * the references of both groups.
2440 static struct gpu_array_ref_group *join_groups(
2441 struct gpu_array_ref_group *group1,
2442 struct gpu_array_ref_group *group2)
2444 int i;
2445 isl_ctx *ctx;
2446 struct gpu_array_ref_group *group;
2448 ctx = isl_map_get_ctx(group1->access);
2449 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2450 assert(group);
2451 group->array = group1->array;
2452 group->access = isl_map_union(isl_map_copy(group1->access),
2453 isl_map_copy(group2->access));
2454 group->write = group1->write || group2->write;
2455 group->n_ref = group1->n_ref + group2->n_ref;
2456 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2457 group->n_ref);
2458 assert(group->refs);
2459 for (i = 0; i < group1->n_ref; ++i)
2460 group->refs[i] = group1->refs[i];
2461 for (i = 0; i < group2->n_ref; ++i)
2462 group->refs[group1->n_ref + i] = group2->refs[i];
2464 return group;
2467 /* Combine the given two groups into a single group and free
2468 * the original two groups.
2470 static struct gpu_array_ref_group *join_groups_and_free(
2471 struct gpu_array_ref_group *group1,
2472 struct gpu_array_ref_group *group2)
2474 struct gpu_array_ref_group *group;
2476 group = join_groups(group1, group2);
2477 free_array_ref_group(group1);
2478 free_array_ref_group(group2);
2479 return group;
2482 /* Compute the private and/or shared memory tiles for the array
2483 * reference group "group" of array "array".
2485 * If the array is a read-only scalar or if the user requested
2486 * not to use shared or private memory, then we do not need to do anything.
2488 * We only try to compute a shared memory tile if there is any reuse
2489 * or if the access is not coalesced.
2491 * For computing a private memory tile, we also require that there is
2492 * some reuse. Moreover, we require that the access is private
2493 * to the thread. That is, we check that any given array element
2494 * is only accessed by a single thread.
2495 * We compute an access relation that maps the shared tile loop iterators
2496 * and the shared point loop iterators that will be wrapped over the
2497 * threads to the array elements.
2498 * We actually check that those iterators that will be wrapped
2499 * partition the array space. This check is stricter than necessary
2500 * since several iterations may be mapped onto the same thread
2501 * and then they could be allowed to access the same memory elements,
2502 * but our check does not allow this situation.
2504 * We also check that the index expression only depends on parallel
2505 * loops. That way, we can move those loops innermost and unroll them.
2506 * Again, we use a test that is stricter than necessary.
2507 * We actually check whether the index expression only depends
2508 * on the iterators that are wrapped over the threads.
2509 * These are necessarily parallel, but there may be more parallel loops.
2511 * Combining the injectivity of the first test with the single-valuedness
2512 * of the second test, we simply test for bijectivity.
2514 * If it turns out we can use registers, we compute the private memory
2515 * tile size using can_tile, after introducing a dependence
2516 * on the thread indices.
2518 static void compute_group_bounds_core(struct gpu_gen *gen,
2519 struct gpu_array_ref_group *group)
2521 isl_ctx *ctx = isl_space_get_ctx(group->array->dim);
2522 isl_union_map *access;
2523 int n_index = group->array->n_index;
2524 int no_reuse;
2525 isl_map *acc;
2526 int use_shared = gen->options->use_shared_memory;
2527 int use_private = gen->options->use_private_memory;
2529 if (!use_shared && !use_private)
2530 return;
2531 if (gpu_array_is_read_only_scalar(group->array))
2532 return;
2534 access = group_access_relation(group, 1, 1);
2535 no_reuse = isl_union_map_is_injective(access);
2537 if (use_shared && (!no_reuse || !access_is_coalesced(gen, access))) {
2538 group->shared_tile = create_tile(ctx, group->array->n_index);
2539 if (!can_tile(group->access, group->shared_tile))
2540 group->shared_tile = free_tile(group->shared_tile);
2543 if (!use_private || no_reuse) {
2544 isl_union_map_free(access);
2545 return;
2548 access = isl_union_map_apply_domain(access,
2549 isl_union_map_copy(gen->shared_sched));
2551 acc = isl_map_from_union_map(access);
2553 if (!access_is_bijective(gen, acc)) {
2554 isl_map_free(acc);
2555 return;
2558 group->private_tile = create_tile(gen->ctx, n_index);
2559 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2560 if (!can_tile(acc, group->private_tile))
2561 group->private_tile = free_tile(group->private_tile);
2563 isl_map_free(acc);
2566 /* Compute the private and/or shared memory tiles for the array
2567 * reference group "group" of array "array" and set last_shared.
2569 static void compute_group_bounds(struct gpu_gen *gen,
2570 struct gpu_array_ref_group *group)
2572 compute_group_bounds_core(gen, group);
2573 set_last_shared(gen, group);
2576 /* If two groups have overlapping access relations (as determined by
2577 * the "overlap" function) and if one of them involves a write,
2578 * then merge the two groups into one.
2579 * If "compute_bounds" is set, then call compute_group_bounds
2580 * on the merged groups.
2582 * Return the updated number of groups.
2584 static int group_writes(struct gpu_gen *gen,
2585 int n, struct gpu_array_ref_group **groups,
2586 int (*overlap)(struct gpu_array_ref_group *group1,
2587 struct gpu_array_ref_group *group2), int compute_bounds)
2589 int i, j;
2591 for (i = 0; i < n; ++i) {
2592 for (j = n - 1; j > i; --j) {
2593 if (!groups[i]->write && !groups[j]->write)
2594 continue;
2596 if (!overlap(groups[i], groups[j]))
2597 continue;
2599 groups[i] = join_groups_and_free(groups[i], groups[j]);
2600 if (compute_bounds)
2601 compute_group_bounds(gen, groups[i]);
2602 if (j != n - 1)
2603 groups[j] = groups[n - 1];
2604 n--;
2608 return n;
2611 /* If two groups have overlapping access relations (within the innermost
2612 * loop) and if one of them involves a write, then merge the two groups
2613 * into one.
2615 * Return the updated number of groups.
2617 static int group_overlapping_writes(struct gpu_gen *gen,
2618 int n, struct gpu_array_ref_group **groups)
2620 return group_writes(gen, n, groups, &accesses_overlap, 0);
2623 /* Check if the access relations of group1 and group2 overlap within
2624 * the outermost min(group1->last_shared, group2->last_shared) loops.
2626 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2627 struct gpu_array_ref_group *group2)
2629 int last_shared;
2630 int dim;
2631 int empty;
2632 isl_map *map_i, *map_j, *map;
2634 last_shared = group1->last_shared;
2635 if (group2->last_shared < last_shared)
2636 last_shared = group2->last_shared;
2637 map_i = isl_map_copy(group1->access);
2638 dim = isl_map_dim(map_i, isl_dim_in);
2639 map_i = isl_map_eliminate(map_i, isl_dim_in,
2640 last_shared + 1, dim - (last_shared + 1));
2641 map_j = isl_map_copy(group2->access);
2642 map_j = isl_map_eliminate(map_j, isl_dim_in,
2643 last_shared + 1, dim - (last_shared + 1));
2644 map = isl_map_intersect(map_i, map_j);
2645 empty = isl_map_is_empty(map);
2646 isl_map_free(map);
2648 return !empty;
2651 /* If two groups have overlapping access relations (within the outer
2652 * last_shared loops) and if one of them involves a write,
2653 * then merge the two groups into one.
2655 * Return the updated number of groups.
2657 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2658 struct gpu_array_ref_group **groups)
2660 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2663 /* Is the size of the tile specified by "tile" smaller than the sum of
2664 * the sizes of the tiles specified by "tile1" and "tile2"?
2666 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
2667 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2669 int smaller;
2670 isl_val *size, *size1, *size2;
2672 size = tile_size(ctx, tile);
2673 size1 = tile_size(ctx, tile1);
2674 size2 = tile_size(ctx, tile2);
2676 size = isl_val_sub(size, size1);
2677 size = isl_val_sub(size, size2);
2678 smaller = isl_val_is_neg(size);
2680 isl_val_free(size);
2682 return smaller;
2685 /* Given an initial grouping of array references and shared memory tiles
2686 * for each group that allows for a shared memory tile, merge two groups
2687 * if both have a shared memory tile, the merged group also has
2688 * a shared memory tile and the size of the tile for the merge group
2689 * is smaller than the sum of the tile sizes of the individual groups.
2691 * If merging two groups decreases the "last_shared" dimension of
2692 * one or both of the two groups, then we need to check for overlapping
2693 * writes again.
2695 * Return the number of groups after merging.
2697 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2698 struct gpu_array_info *array, int n,
2699 struct gpu_array_ref_group **groups)
2701 int i, j;
2702 int recompute_overlap = 0;
2703 isl_ctx *ctx = isl_space_get_ctx(array->dim);
2705 for (i = 0; i < n; ++i) {
2706 if (!groups[i]->shared_tile)
2707 continue;
2708 for (j = n - 1; j > i; --j) {
2709 isl_map *map;
2710 int empty;
2711 struct gpu_array_ref_group *group;
2713 if (!groups[j]->shared_tile)
2714 continue;
2716 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2717 isl_map_copy(groups[j]->access));
2718 empty = isl_map_is_empty(map);
2719 isl_map_free(map);
2721 if (empty)
2722 continue;
2724 group = join_groups(groups[i], groups[j]);
2725 compute_group_bounds(gen, group);
2726 if (!group->shared_tile ||
2727 !smaller_tile(ctx, group->shared_tile,
2728 groups[i]->shared_tile,
2729 groups[j]->shared_tile)) {
2730 free_array_ref_group(group);
2731 continue;
2734 if (group->last_shared < groups[i]->last_shared ||
2735 group->last_shared < groups[j]->last_shared)
2736 recompute_overlap = 1;
2737 free_array_ref_group(groups[i]);
2738 free_array_ref_group(groups[j]);
2739 groups[i] = group;
2740 if (j != n - 1)
2741 groups[j] = groups[n - 1];
2742 n--;
2746 if (recompute_overlap)
2747 n = group_last_shared_overlapping_writes(gen, n, groups);
2748 return n;
2751 /* Set array->n_group and array->groups to n and groups.
2753 * Additionally, set the "nr" field of each group
2754 * and the "group" field of each reference in each group.
2756 static void set_array_groups(struct gpu_array_info *array,
2757 int n, struct gpu_array_ref_group **groups)
2759 int i, j;
2761 array->n_group = n;
2762 array->groups = groups;
2764 for (i = 0; i < n; ++i) {
2765 groups[i]->nr = i;
2767 for (j = 0; j < groups[i]->n_ref; ++j)
2768 groups[i]->refs[j]->group = i;
2772 /* Group array references that should be considered together when
2773 * deciding whether to access them from private, shared or global memory.
2775 * In particular, if two array references overlap and if one of them
2776 * is a write, then the two references are grouped together.
2777 * We first perform an initial grouping based only on the access relation.
2778 * After computing shared and private memory tiles, we check for
2779 * overlapping writes again, but this time taking into account
2780 * the "last_shared" property.
2782 * Furthermore, if two groups admit a shared memory tile and if the
2783 * combination of the two also admits a shared memory tile, we merge
2784 * the two groups.
2786 static void group_array_references(struct gpu_gen *gen,
2787 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
2789 int i;
2790 int n;
2791 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2792 struct gpu_array_ref_group **groups;
2794 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
2795 array->n_ref);
2796 assert(groups);
2798 n = populate_array_references(array, sched, groups);
2800 n = group_overlapping_writes(gen, n, groups);
2802 for (i = 0; i < n; ++i)
2803 compute_group_bounds(gen, groups[i]);
2805 n = group_last_shared_overlapping_writes(gen, n, groups);
2807 n = group_common_shared_memory_tile(gen, array, n, groups);
2809 set_array_groups(array, n, groups);
2812 /* Take tiled_sched, project it onto the shared tile loops and
2813 * the loops that will be wrapped over the threads and
2814 * store the result in gen->shared_sched.
2815 * Also compute a projection that projects out the loops that will be
2816 * wrapped over the threads and store this projection in gen->shared_proj.
2818 static void compute_shared_sched(struct gpu_gen *gen)
2820 isl_space *dim;
2821 isl_map *proj;
2822 isl_set *par;
2823 isl_union_map *sched;
2825 sched = isl_union_map_copy(gen->tiled_sched);
2827 dim = isl_union_map_get_space(sched);
2828 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
2829 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
2831 dim = isl_union_map_get_space(sched);
2832 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
2834 gen->shared_sched = sched;
2835 gen->shared_proj = isl_union_map_from_map(proj);
2838 /* Group references of all arrays in the program.
2840 static void group_references(struct gpu_gen *gen)
2842 int i;
2843 isl_union_map *sched;
2845 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2846 isl_union_map_copy(gen->shared_proj));
2848 for (i = 0; i < gen->prog->n_array; ++i)
2849 group_array_references(gen, &gen->prog->array[i], sched);
2851 isl_union_map_free(sched);
2854 /* Free all array information that is local to the current kernel.
2856 static void free_local_array_info(struct gpu_gen *gen)
2858 int i, j;
2860 for (i = 0; i < gen->prog->n_array; ++i) {
2861 struct gpu_array_info *array = &gen->prog->array[i];
2863 for (j = 0; j < array->n_group; ++j)
2864 free_array_ref_group(array->groups[j]);
2865 free(array->groups);
2869 /* Compute the size of a bounding box around the origin and "set",
2870 * where "set" is assumed to contain only non-negative elements.
2871 * In particular, compute the maximal value of "set" in each direction
2872 * and add one.
2874 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
2875 __isl_keep isl_set *context)
2877 int i, n;
2878 isl_multi_pw_aff *mpa;
2880 n = isl_set_dim(set, isl_dim_set);
2881 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
2882 for (i = 0; i < n; ++i) {
2883 isl_space *space;
2884 isl_aff *one;
2885 isl_pw_aff *bound;
2887 bound = isl_set_dim_max(isl_set_copy(set), i);
2888 bound = isl_pw_aff_coalesce(bound);
2889 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
2891 space = isl_pw_aff_get_domain_space(bound);
2892 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2893 one = isl_aff_add_constant_si(one, 1);
2894 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
2895 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
2897 isl_set_free(set);
2899 return mpa;
2902 /* Compute the effective grid size as a list of the sizes in each dimension.
2904 * The grid size specified by the user or set by default
2905 * in read_grid_sizes() and applied in tile_schedule(),
2906 * may be too large for the given code in the sense that
2907 * it may contain blocks that don't need to execute anything.
2908 * We therefore don't return this grid size, but instead the
2909 * smallest grid size that ensures that all blocks that actually
2910 * execute code are included in the grid.
2912 * We first extract a description of the grid, i.e., the possible values
2913 * of the block ids, from gen->tiled_sched.
2914 * The block ids are parameters in gen->tiled_sched.
2915 * We simply need to change them into set dimensions.
2917 * Then, for each block dimension, we compute the maximal value of the block id
2918 * and add one.
2920 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
2921 struct ppcg_kernel *kernel)
2923 int i;
2924 isl_set *grid;
2926 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
2927 grid = isl_set_from_params(grid);
2928 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
2929 for (i = 0; i < gen->n_grid; ++i) {
2930 int pos;
2931 char name[20];
2933 snprintf(name, sizeof(name), "b%d", i);
2934 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
2935 assert(pos >= 0);
2936 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
2937 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
2940 return extract_size(grid, kernel->context);
2943 /* Compute the size of a fixed bounding box around the origin and "set",
2944 * where "set" is assumed to contain only non-negative elements,
2945 * and store the results in "size".
2946 * In particular, compute the maximal value of "set" in each direction
2947 * and add one.
2949 static void extract_fixed_size(__isl_take isl_set *set, int *size)
2951 int i, n;
2952 isl_local_space *ls;
2953 isl_aff *obj;
2955 n = isl_set_dim(set, isl_dim_set);
2956 ls = isl_local_space_from_space(isl_set_get_space(set));
2957 obj = isl_aff_zero_on_domain(ls);
2958 for (i = 0; i < n; ++i) {
2959 isl_val *max;
2961 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
2962 max = isl_set_max_val(set, obj);
2963 size[i] = isl_val_get_num_si(max) + 1;
2964 isl_val_free(max);
2965 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
2967 isl_aff_free(obj);
2968 isl_set_free(set);
2971 /* Compute the effective block size as a list of the sizes in each dimension
2972 * and store the sizes in kernel->block_dim.
2974 * The block size specified by the user or set by default
2975 * in read_block_sizes() and applied in thread_tile_schedule(),
2976 * may be too large for the given code in the sense that
2977 * it may contain threads that don't need to execute anything.
2978 * We therefore don't store this block size in kernel->block_dim,
2979 * but instead the smallest block size that ensures that all threads
2980 * that actually execute code are included in the block.
2982 * The current implementation eliminates all parameters, ensuring
2983 * that the size is a fixed constant in each dimension.
2984 * In principle we could also compute parametric sizes.
2985 * We would have to make sure to project out all b%d and t%d parameters,
2986 * however.
2988 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
2990 int i;
2991 int nparam;
2992 isl_set *block;
2993 isl_multi_pw_aff *mpa;
2995 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
2996 block = isl_set_from_params(block);
2997 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
2998 kernel->n_block = gen->n_block;
2999 for (i = 0; i < gen->n_block; ++i) {
3000 int pos;
3001 char name[20];
3003 snprintf(name, sizeof(name), "t%d", i);
3004 pos = isl_set_find_dim_by_name(block, isl_dim_param, name);
3005 assert(pos >= 0);
3006 block = isl_set_equate(block, isl_dim_param, pos,
3007 isl_dim_set, i);
3009 nparam = isl_set_dim(block, isl_dim_param);
3010 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3012 extract_fixed_size(block, kernel->block_dim);
3015 void ppcg_kernel_free(void *user)
3017 struct ppcg_kernel *kernel = user;
3018 int i;
3020 if (!kernel)
3021 return;
3023 isl_multi_pw_aff_free(kernel->grid_size);
3024 isl_set_free(kernel->context);
3025 isl_union_set_free(kernel->arrays);
3026 isl_space_free(kernel->space);
3027 isl_ast_node_free(kernel->tree);
3029 for (i = 0; i < kernel->n_array; ++i)
3030 isl_pw_aff_list_free(kernel->array[i].bound);
3031 free(kernel->array);
3033 for (i = 0; i < kernel->n_var; ++i) {
3034 free(kernel->var[i].name);
3035 isl_vec_free(kernel->var[i].size);
3037 free(kernel->var);
3039 free(kernel);
3042 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3043 struct ppcg_kernel_var *var)
3045 int j;
3046 struct gpu_array_tile *tile;
3047 isl_printer *p;
3048 char *name;
3050 var->array = group->array;
3052 tile = group->private_tile;
3053 var->type = ppcg_access_private;
3054 if (!tile) {
3055 tile = group->shared_tile;
3056 var->type = ppcg_access_shared;
3059 p = isl_printer_to_str(ctx);
3060 p = print_array_name(p, group);
3061 var->name = isl_printer_get_str(p);
3062 isl_printer_free(p);
3064 var->size = isl_vec_alloc(ctx, group->array->n_index);
3066 for (j = 0; j < group->array->n_index; ++j)
3067 var->size = isl_vec_set_element_val(var->size, j,
3068 isl_val_copy(tile->bound[j].size));
3071 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3073 int i, j, n;
3075 n = 0;
3076 for (i = 0; i < gen->prog->n_array; ++i) {
3077 struct gpu_array_info *array = &gen->prog->array[i];
3079 for (j = 0; j < array->n_group; ++j) {
3080 struct gpu_array_ref_group *group = array->groups[j];
3081 if (group->private_tile || group->shared_tile)
3082 ++n;
3086 kernel->n_var = n;
3087 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3088 assert(kernel->var);
3090 n = 0;
3091 for (i = 0; i < gen->prog->n_array; ++i) {
3092 struct gpu_array_info *array = &gen->prog->array[i];
3094 for (j = 0; j < array->n_group; ++j) {
3095 struct gpu_array_ref_group *group = array->groups[j];
3096 if (!group->private_tile && !group->shared_tile)
3097 continue;
3098 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3099 ++n;
3104 /* The sizes of the arrays on the host that have been computed by
3105 * extract_array_info may depend on the parameters. Use the extra
3106 * constraints on the parameters that are valid at "host_domain"
3107 * to simplify these expressions and store the results in kernel->array.
3109 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3110 __isl_keep isl_set *host_domain)
3112 int i, j;
3113 isl_set *context;
3115 kernel->array = isl_calloc_array(gen->ctx,
3116 struct gpu_local_array_info, gen->prog->n_array);
3117 assert(kernel->array);
3118 kernel->n_array = gen->prog->n_array;
3120 context = isl_set_copy(host_domain);
3121 context = isl_set_params(context);
3123 for (i = 0; i < gen->prog->n_array; ++i) {
3124 struct gpu_array_info *array = &gen->prog->array[i];
3125 isl_pw_aff_list *local;
3127 if (array->n_group == 0)
3128 continue;
3130 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3132 for (j = 0; j < array->n_index; ++j) {
3133 isl_pw_aff *pwaff;
3135 pwaff = isl_pw_aff_copy(array->bound[j]);
3136 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3137 local = isl_pw_aff_list_add(local, pwaff);
3140 kernel->array[i].bound = local;
3142 isl_set_free(context);
3145 /* Find the element in gen->stmt that has the given "id".
3146 * Return NULL if no such gpu_stmt can be found.
3148 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3150 int i;
3152 for (i = 0; i < prog->n_stmts; ++i) {
3153 if (id == prog->stmts[i].id)
3154 break;
3157 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3160 /* Set gen->tile_len and gen->n_parallel to those of the statement
3161 * affected by the first map (part of the schedule)
3162 * on which this function is called.
3163 * Because of the way the schedule is constructed, the other statements
3164 * in the list, if any, should have the same values for these properties.
3166 static int extract_tile_len(__isl_take isl_map *map, void *user)
3168 struct gpu_gen *gen = (struct gpu_gen *) user;
3169 isl_id *id;
3170 struct gpu_stmt *stmt;
3172 id = isl_map_get_tuple_id(map, isl_dim_in);
3173 stmt = find_stmt(gen->prog, id);
3174 isl_id_free(id);
3176 isl_map_free(map);
3178 if (!stmt)
3179 isl_die(gen->ctx, isl_error_unknown,
3180 "statement not found", return -1);
3182 gen->tile_len = stmt->tile_len;
3183 gen->n_parallel = stmt->n_parallel;
3185 return -1;
3188 void ppcg_kernel_stmt_free(void *user)
3190 int i;
3191 struct ppcg_kernel_stmt *stmt = user;
3193 if (!stmt)
3194 return;
3196 switch (stmt->type) {
3197 case ppcg_kernel_copy:
3198 isl_ast_expr_free(stmt->u.c.index);
3199 isl_ast_expr_free(stmt->u.c.local_index);
3200 break;
3201 case ppcg_kernel_domain:
3202 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
3203 break;
3204 case ppcg_kernel_sync:
3205 break;
3208 free(stmt);
3211 /* Set the options of "context" to
3213 * { space -> [x] : x >= first }
3215 static __isl_give isl_ast_build *set_unroll(
3216 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3217 int first)
3219 isl_ctx *ctx;
3220 isl_map *unroll;
3221 isl_union_map *opt;
3223 ctx = isl_ast_build_get_ctx(build);
3225 space = isl_space_from_domain(space);
3226 space = isl_space_add_dims(space, isl_dim_out, 1);
3227 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3228 unroll = isl_map_universe(space);
3229 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3230 opt = isl_union_map_from_map(unroll);
3232 build = isl_ast_build_set_options(build, opt);
3234 return build;
3237 /* Return a list of isl_ids of the form "prefix%d".
3239 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3240 int n, const char *prefix)
3242 int i;
3243 char name[10];
3244 isl_id_list *names;
3246 names = isl_id_list_alloc(ctx, n);
3247 for (i = 0; i < n; ++i) {
3248 isl_id *id;
3250 snprintf(name, sizeof(name), "%s%d", prefix, i);
3251 id = isl_id_alloc(ctx, name, NULL);
3252 names = isl_id_list_add(names, id);
3255 return names;
3258 /* Extend the schedule "schedule" with the part of "extension"
3259 * starting at "first" up to "len".
3261 static __isl_give isl_union_map *extend_schedule(
3262 __isl_take isl_union_map *schedule,
3263 __isl_take isl_union_map *extension, int first, int len)
3265 isl_space *space;
3266 isl_map *proj;
3267 isl_union_map *umap;
3268 isl_set *set;
3270 space = isl_union_map_get_space(schedule);
3271 space = isl_space_set_from_params(space);
3272 space = isl_space_add_dims(space, isl_dim_set, len);
3273 proj = isl_set_identity(isl_set_universe(space));
3274 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3275 extension = isl_union_map_apply_range(extension,
3276 isl_union_map_from_map(proj));
3278 schedule = isl_union_map_range_product(schedule, extension);
3280 return schedule;
3283 /* Return the gpu_stmt_access in the list "accesses" that corresponds
3284 * to "ref_id".
3286 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
3287 __isl_keep isl_id *ref_id)
3289 struct gpu_stmt_access *access;
3291 for (access = accesses; access; access = access->next)
3292 if (access->ref_id == ref_id)
3293 return access;
3295 return NULL;
3298 /* Return the index of the array called "name" in the list of arrays.
3300 static int find_array_index(struct gpu_gen *gen, const char *name)
3302 int i;
3304 for (i = 0; i < gen->prog->n_array; ++i)
3305 if (!strcmp(name, gen->prog->array[i].name))
3306 return i;
3308 return -1;
3311 /* Internal data structure for the index and AST expression transformation
3312 * callbacks for pet_stmt_build_ast_exprs.
3314 * "accesses" is the list of gpu_stmt_access in the statement.
3315 * "iterator_map" expresses the statement iterators in terms of
3316 * the AST loop iterators.
3317 * "sched2shared" expresses the first shared_len dimensions of
3318 * the computed schedule in terms of the AST loop iterators.
3320 * The following fields are set in transform_index and used in transform_expr.
3321 * "array" is the array that is being accessed.
3322 * "global" is set if the global array is accessed (rather than
3323 * shared/private memory).
3324 * "local_array" refers to information on the array specialized
3325 * to the current kernel.
3327 struct ppcg_transform_data {
3328 struct gpu_gen *gen;
3329 struct gpu_stmt_access *accesses;
3330 isl_pw_multi_aff *iterator_map;
3331 isl_pw_multi_aff *sched2shared;
3333 struct gpu_array_info *array;
3334 int global;
3335 struct gpu_local_array_info *local_array;
3338 /* Index transformation callback for pet_stmt_build_ast_exprs.
3340 * "index" expresses the array indices in terms of statement iterators
3342 * We first reformulate "index" in terms of the AST loop iterators.
3343 * Then we check if we are accessing the global array or
3344 * a shared/private copy. In the former case, we simply return
3345 * the updated index. If "index" is an affine expression rather
3346 * than an array access, then we also return the updated index here.
3348 * Otherwise, we apply the tiling to the index.
3349 * This tiling is of the form
3351 * [D -> A] -> T
3353 * The index is of the form
3355 * L -> A
3357 * We update the tiling to refer to the AST loop iteratos
3359 * [L -> A] -> T
3361 * and modify index to keep track of those iterators
3363 * L -> [L -> A]
3365 * Combining these two yields a tiled index expression in terms
3366 * of the AST loop iterators
3368 * L -> T
3370 static __isl_give isl_multi_pw_aff *transform_index(
3371 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
3372 void *user)
3374 struct ppcg_transform_data *data = user;
3375 struct gpu_stmt_access *access;
3376 struct gpu_array_ref_group *group;
3377 struct gpu_array_tile *tile;
3378 isl_pw_multi_aff *iterator_map;
3379 int i;
3380 const char *name;
3381 isl_space *space;
3382 isl_multi_pw_aff *tiling;
3383 isl_pw_multi_aff *pma;
3384 isl_multi_pw_aff *mpa;
3386 data->array = NULL;
3388 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
3389 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
3391 access = find_access(data->accesses, ref_id);
3392 if (!access)
3393 return index;
3394 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
3395 return index;
3397 name = isl_map_get_tuple_name(access->access, isl_dim_out);
3398 i = find_array_index(data->gen, name);
3399 if (i < 0)
3400 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
3401 "cannot find array reference group",
3402 return isl_multi_pw_aff_free(index));
3404 data->array = &data->gen->prog->array[i];
3405 data->local_array = &data->gen->kernel->array[i];
3406 group = data->array->groups[access->group];
3407 tile = group->private_tile;
3408 if (!tile)
3409 tile = group->shared_tile;
3410 data->global = !tile;
3411 if (!tile)
3412 return index;
3414 space = isl_space_range(isl_multi_pw_aff_get_space(index));
3415 space = isl_space_map_from_set(space);
3416 pma = isl_pw_multi_aff_identity(space);
3417 pma = isl_pw_multi_aff_product(
3418 isl_pw_multi_aff_copy(data->sched2shared), pma);
3419 tiling = isl_multi_pw_aff_from_multi_aff(
3420 isl_multi_aff_copy(tile->tiling));
3421 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
3423 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
3424 space = isl_space_map_from_set(space);
3425 mpa = isl_multi_pw_aff_identity(space);
3426 index = isl_multi_pw_aff_range_product(mpa, index);
3427 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
3429 return index;
3432 /* Dereference "expr" by adding an index [0].
3433 * The original "expr" is assumed not to have any indices.
3435 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
3437 isl_ctx *ctx;
3438 isl_ast_expr *res;
3439 isl_ast_expr_list *list;
3441 ctx = isl_ast_expr_get_ctx(expr);
3442 res = isl_ast_expr_from_val(isl_val_zero(ctx));
3443 list = isl_ast_expr_list_from_ast_expr(res);
3444 res = isl_ast_expr_get_op_arg(expr, 0);
3445 res = isl_ast_expr_access(res, list);
3446 isl_ast_expr_free(expr);
3448 return res;
3451 /* Linearize the index expression "expr" based on the array bounds
3452 * of "array".
3454 * That is, transform expression
3456 * A[i_0][i_1]...[i_n]
3458 * to
3460 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
3462 * where b_0, b_1, ..., b_n are the bounds on the array.
3464 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
3465 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
3467 int i, n;
3468 isl_ctx *ctx;
3469 isl_set *context;
3470 isl_ast_expr *res;
3471 isl_ast_expr_list *list;
3472 isl_ast_build *build;
3474 ctx = isl_ast_expr_get_ctx(expr);
3475 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
3476 build = isl_ast_build_from_context(context);
3478 n = isl_ast_expr_get_op_n_arg(expr);
3479 res = isl_ast_expr_get_op_arg(expr, 1);
3480 for (i = 2; i < n; ++i) {
3481 isl_pw_aff *bound_i;
3482 isl_ast_expr *expr_i;
3484 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i - 1);
3485 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
3486 res = isl_ast_expr_mul(res, expr_i);
3487 expr_i = isl_ast_expr_get_op_arg(expr, i);
3488 res = isl_ast_expr_add(res, expr_i);
3491 isl_ast_build_free(build);
3493 list = isl_ast_expr_list_from_ast_expr(res);
3494 res = isl_ast_expr_get_op_arg(expr, 0);
3495 res = isl_ast_expr_access(res, list);
3497 isl_ast_expr_free(expr);
3499 return res;
3502 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
3504 * If the AST expression refers to a global scalar that is not
3505 * a read-only scalar, then its address was passed to the kernel and
3506 * we need to dereference it.
3508 * If the AST expression refers to an access to a global array,
3509 * then we linearize the access exploiting the bounds in data->local_array.
3511 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
3512 __isl_keep isl_id *id, void *user)
3514 struct ppcg_transform_data *data = user;
3516 if (!data->array)
3517 return expr;
3518 if (gpu_array_is_read_only_scalar(data->array))
3519 return expr;
3520 if (!data->global)
3521 return expr;
3522 if (data->array->n_index == 0)
3523 return dereference(expr);
3525 return gpu_local_array_info_linearize_index(data->local_array, expr);
3528 /* This function is called for each instance of a user statement
3529 * in the kernel.
3531 * We attach a struct ppcg_kernel_stmt to the "node", containing
3532 * a computed AST expression for each access.
3533 * These AST expressions are computed from iterator_map,
3534 * which expresses the domain
3535 * elements in terms of the generated loops, and sched2shared,
3536 * which expresses the first shared_len dimensions of the schedule
3537 * computed by PPCG in terms of the generated loops.
3539 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3540 __isl_keep isl_ast_build *build, void *user)
3542 struct ppcg_transform_data data;
3543 struct gpu_gen *gen = (struct gpu_gen *) user;
3544 struct ppcg_kernel_stmt *stmt;
3545 isl_id *id;
3546 isl_pw_multi_aff *sched2shared;
3547 isl_map *map;
3548 isl_pw_multi_aff *iterator_map;
3549 isl_ast_expr *expr, *arg;
3550 isl_union_map *schedule;
3551 int i, n;
3552 struct gpu_stmt_access *access;
3554 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3555 if (!stmt)
3556 return isl_ast_node_free(node);
3558 expr = isl_ast_node_user_get_expr(node);
3559 arg = isl_ast_expr_get_op_arg(expr, 0);
3560 id = isl_ast_expr_get_id(arg);
3562 schedule = isl_ast_build_get_schedule(build);
3563 map = isl_map_reverse(isl_map_from_union_map(schedule));
3564 iterator_map = isl_pw_multi_aff_from_map(map);
3565 sched2shared = compute_sched_to_shared(gen,
3566 isl_pw_multi_aff_copy(iterator_map));
3568 stmt->type = ppcg_kernel_domain;
3569 stmt->u.d.stmt = find_stmt(gen->prog, id);
3570 if (!stmt->u.d.stmt)
3571 goto error;
3573 data.gen = gen;
3574 data.accesses = stmt->u.d.stmt->accesses;
3575 data.iterator_map = iterator_map;
3576 data.sched2shared = sched2shared;
3577 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
3578 build, &transform_index, &data,
3579 &transform_expr, &data);
3581 isl_id_free(id);
3582 isl_pw_multi_aff_free(iterator_map);
3583 isl_pw_multi_aff_free(sched2shared);
3584 isl_ast_expr_free(arg);
3585 isl_ast_expr_free(expr);
3587 id = isl_id_alloc(gen->ctx, NULL, stmt);
3588 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3589 return isl_ast_node_set_annotation(node, id);
3590 error:
3591 isl_id_free(id);
3592 isl_pw_multi_aff_free(iterator_map);
3593 ppcg_kernel_stmt_free(stmt);
3594 isl_pw_multi_aff_free(sched2shared);
3595 return isl_ast_node_free(node);
3598 /* This function is called when code has been generated for the shared
3599 * tile loops. The "schedule" refers only to the original statements.
3601 * We extend the schedule with that part of gen->local_sched that hasn't
3602 * been taken into account yet. This introduces parameters referring
3603 * to thread ids in the schedule, so we add them (with the appropriate
3604 * bounds to the context as well).
3605 * Finally, we set the appropriate unrolling options
3606 * if gen->first_unroll is set.
3608 static __isl_give isl_ast_node *create_domain_leaf(
3609 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
3610 void *user)
3612 struct gpu_gen *gen = (struct gpu_gen *) user;
3613 isl_space *space;
3614 isl_union_map *sched;
3615 isl_ast_node *tree;
3616 isl_set *set;
3617 isl_id_list *iterators;
3618 int n;
3620 schedule = extend_schedule(schedule,
3621 isl_union_map_copy(gen->local_sched),
3622 gen->shared_len, gen->thread_tiled_len);
3624 space = isl_ast_build_get_schedule_space(build);
3625 set = isl_set_universe(space);
3626 set = add_bounded_parameters(set, gen->kernel->n_block,
3627 gen->kernel->block_dim, "t");
3628 build = isl_ast_build_restrict(build, set);
3630 n = gen->thread_tiled_len - gen->shared_len;
3632 if (gen->first_unroll >= 0) {
3633 space = isl_space_set_alloc(gen->ctx, 0, n);
3634 build = set_unroll(build, space, gen->first_unroll);
3636 iterators = generate_names(gen->ctx, n, "c");
3637 build = isl_ast_build_set_iterators(build, iterators);
3638 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
3639 tree = isl_ast_build_ast_from_schedule(build, schedule);
3640 isl_ast_build_free(build);
3642 return tree;
3645 /* This function is called for each statement node in the AST of the code
3646 * for copying to or from shared/private memory.
3647 * Attach a pointer to a ppcg_kernel_stmt representing the copy
3648 * statement to the node.
3649 * The statement name is "read" or "write", depending on whether we are
3650 * reading from global memory or writing to global memory.
3651 * The name of the T space is {shared,private}_<array>.
3653 * The schedule is of the form
3655 * type[A -> T] -> L
3657 * where A refers to a piece of an array and T to the corresponding
3658 * shifted tile. We split this schedule into mappings L -> A and L -> T
3659 * and store the corresponding expressions in stmt->index and stmt->local_index,
3660 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
3662 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
3663 __isl_keep isl_ast_build *build, void *user)
3665 struct gpu_gen *gen = (struct gpu_gen *) user;
3666 struct ppcg_kernel_stmt *stmt;
3667 isl_id *id;
3668 isl_ast_expr *expr;
3669 isl_space *space;
3670 isl_map *access, *local_access, *map;
3671 isl_pw_multi_aff *pma;
3672 const char *type;
3673 int array_index;
3675 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3676 if (!stmt)
3677 return isl_ast_node_free(node);
3679 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
3680 type = isl_map_get_tuple_name(access, isl_dim_in);
3681 stmt->u.c.read = !strcmp(type, "read");
3682 access = isl_map_reverse(access);
3683 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
3684 local_access = isl_map_copy(access);
3686 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
3687 id = isl_map_get_tuple_id(access, isl_dim_out);
3688 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3689 access = isl_map_apply_range(access, map);
3690 pma = isl_pw_multi_aff_from_map(access);
3691 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
3692 stmt->u.c.index = expr;
3694 map = isl_map_range_map(isl_map_universe(space));
3695 id = isl_map_get_tuple_id(local_access, isl_dim_out);
3696 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3697 local_access = isl_map_apply_range(local_access, map);
3698 pma = isl_pw_multi_aff_from_map(local_access);
3699 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
3700 stmt->u.c.local_index = expr;
3702 stmt->u.c.array = gen->copy_group->array;
3703 array_index = stmt->u.c.array - gen->prog->array;
3704 stmt->u.c.local_array = &gen->kernel->array[array_index];
3705 stmt->type = ppcg_kernel_copy;
3707 id = isl_id_alloc(gen->ctx, NULL, stmt);
3708 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3709 return isl_ast_node_set_annotation(node, id);
3712 /* Given a schedule of the form
3714 * [S -> A] -> L
3716 * (with S the first shared_len dimensions of the computed schedule,
3717 * A the array and L the schedule correponding to the generated loops),
3718 * indicating where to copy the array elements that need to be copied,
3719 * construct code for performing the copying.
3721 * "group" is the array reference group that is being copied
3722 * "type" is either "read" or "write"
3723 * private is set if copying needs to be performed to/from registers
3725 * We first construct a mapping to a shifted tile of the array,
3727 * [S -> A] -> T(S,A) (1)
3729 * If private is set, then we also use this mapping as a schedule
3730 * (which is already thread-specific and will be completely unrolled).
3731 * Otherwise, we wrap/tile the range over the threads.
3732 * The result is
3734 * [S -> A] -> T'(S,A)
3736 * Combined with the given schedule, we have
3738 * [S -> A] -> [L -> T'(S,A)] (2)
3740 * From the shifted tile mapping, we construct a mapping
3742 * [S -> A] -> [A -> T(S,A)]
3744 * and apply it to the schedule (2), obtaining
3746 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
3748 * Note that we can project out S because it is uniquely defined by L.
3750 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
3751 __isl_take isl_map *sched,
3752 const char *type, struct gpu_array_ref_group *group,
3753 __isl_take isl_ast_build *build, int private)
3755 isl_space *space;
3756 isl_ast_node *tree;
3757 isl_map *schedule, *shift, *map;
3758 isl_set *set;
3759 isl_id_list *iterators;
3760 int n;
3762 shift = shift_access(group);
3764 schedule = isl_map_copy(shift);
3765 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
3766 if (!private)
3767 schedule = tile_access_schedule(gen, schedule);
3769 n = isl_map_dim(schedule, isl_dim_out);
3770 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
3771 set = add_bounded_parameters(set, gen->kernel->n_block,
3772 gen->kernel->block_dim, "t");
3774 schedule = isl_map_range_product(sched, schedule);
3776 space = isl_space_domain(isl_map_get_space(shift));
3777 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
3778 map = isl_map_range_product(map, shift);
3780 schedule = isl_map_apply_domain(schedule, map);
3782 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
3784 build = isl_ast_build_restrict(build, set);
3786 gen->copy_group = group;
3788 if (private) {
3789 space = isl_space_range(isl_map_get_space(schedule));
3790 space = isl_space_range(isl_space_unwrap(space));
3791 build = set_unroll(build, space, 0);
3793 iterators = generate_names(gen->ctx, n, "c");
3794 build = isl_ast_build_set_iterators(build, iterators);
3795 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
3796 tree = isl_ast_build_ast_from_schedule(build,
3797 isl_union_map_from_map(schedule));
3798 isl_ast_build_free(build);
3800 return tree;
3803 /* Return code for reading into or writing from shared memory
3804 * the given array reference group.
3806 * If we are performing a read from global memory to shared memory and
3807 * if the array involved is not a scalar, then we copy
3808 * the entire tile to shared memory. This may result in some extra
3809 * elements getting copied, but it should lead to simpler code
3810 * (which means that fewer registers may be needed) and less divergence.
3812 * Otherwise, we only copy the elements that will be read or have been written
3813 * in the kernel.
3816 * The input "sched" is of the form.
3818 * type[S -> A] -> L
3820 * with S the first shared_len dimensions of the computed schedule,
3821 * A the array and L the schedule correponding to the generated loops.
3823 * We first drop "type",
3825 * [S -> A] -> L
3827 * If the above conditions are satisfied, we project out A,
3828 * resulting in
3830 * S -> L
3832 * and then introduce the group tile [S -> T], resulting in
3834 * [S -> T] -> L
3836 static __isl_give isl_ast_node *copy_group_shared_accesses(
3837 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3838 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3840 const char *type;
3841 int read;
3842 isl_union_map *access;
3844 type = isl_map_get_tuple_name(sched, isl_dim_in);
3845 read = !strcmp(type, "read");
3847 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3849 if (read && !gpu_array_is_scalar(group->array)) {
3850 isl_space *space;
3851 isl_map *map;
3853 space = isl_space_domain(isl_map_get_space(sched));
3854 space = isl_space_unwrap(space);
3855 map = isl_map_domain_map(isl_map_universe(space));
3856 sched = isl_map_apply_domain(sched, map);
3858 map = group_tile(group);
3859 map = isl_map_reverse(isl_map_domain_map(map));
3860 sched = isl_map_apply_domain(sched, map);
3863 return copy_access(gen, sched, type, group, build, 0);
3866 /* Return code for reading into or writing from private memory
3867 * the given array reference group.
3869 * Let S be the first shared_len dimensions of the computed schedule,
3870 * D the iteration domains, A the array and L the schedule correponding
3871 * to the generated loops.
3872 * "sched" is of the form
3874 * type[S -> A] -> L
3876 * where type is either "read" or "write".
3877 * We apply the privatization D -> S(t), with t the thread ids,
3878 * to the access relation D -> A to obtain the privatized access relation
3880 * S(t) -> A
3882 * We drop the type from "sched" and intersect with the privatized access
3883 * relation to obtain
3885 * [S(t) -> A] -> L
3887 static __isl_give isl_ast_node *copy_group_private_accesses(
3888 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3889 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3891 const char *type;
3892 int read;
3893 isl_union_map *priv;
3894 isl_union_map *access;
3895 isl_map *access_map;
3897 type = isl_map_get_tuple_name(sched, isl_dim_in);
3898 read = !strcmp(type, "read");
3900 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
3901 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3902 priv);
3904 access = group_access_relation(group, read, !read);
3905 access = isl_union_map_apply_domain(access, priv);
3906 access_map = isl_map_from_union_map(access);
3908 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3909 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
3911 return copy_access(gen, sched, type, group, build, 1);
3914 /* Return code for reading into or writing from shared or private memory.
3916 * "schedule" is of the form
3918 * type[S -> A] -> L
3920 * with S be the first shared_len dimensions of the computed schedule,
3921 * A the array and L the schedule correponding to the generated loops.
3922 * The array reference group is attached to "type".
3924 static __isl_give isl_ast_node *create_access_leaf(
3925 struct gpu_gen *gen, __isl_take isl_map *schedule,
3926 __isl_take isl_ast_build *build)
3928 struct gpu_array_ref_group *group;
3929 isl_id *id;
3931 id = isl_map_get_tuple_id(schedule, isl_dim_in);
3932 group = isl_id_get_user(id);
3933 isl_id_free(id);
3935 if (group->private_tile)
3936 return copy_group_private_accesses(gen, group, schedule,
3937 build);
3938 else
3939 return copy_group_shared_accesses(gen, group, schedule,
3940 build);
3943 /* Create a domain node representing a synchronization.
3945 static __isl_give isl_ast_node *create_sync_leaf(
3946 struct gpu_gen *gen, __isl_take isl_map *schedule,
3947 __isl_take isl_ast_build *build)
3949 struct ppcg_kernel_stmt *stmt;
3950 isl_id *id;
3951 isl_space *space;
3952 isl_ast_node *node;
3953 isl_ast_expr *expr;
3955 isl_map_free(schedule);
3957 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3958 if (!stmt)
3959 return NULL;
3961 stmt->type = ppcg_kernel_sync;
3963 space = isl_ast_build_get_schedule_space(build);
3964 space = isl_space_from_domain(space);
3965 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
3966 expr = isl_ast_build_call_from_pw_multi_aff(build,
3967 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
3968 node = isl_ast_node_alloc_user(expr);
3969 isl_ast_build_free(build);
3971 id = isl_id_alloc(gen->ctx, NULL, stmt);
3972 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3973 return isl_ast_node_set_annotation(node, id);
3976 /* This function is called during the code generation at the point
3977 * where the schedule domain element is completely determined by
3978 * the generated code. The input schedule contains the original
3979 * statements as well as synchronization and copy "statements".
3980 * The latter are scheduled at different points than any of the original
3981 * statements, so they will only arrive here in isolation.
3983 * If the current schedule only refers to a single statement,
3984 * we check if it is a copy or synchronization statement and
3985 * call the appropriate functions.
3986 * Otherwise, we assume we are dealing with the original statements
3987 * and we call create_domain_leaf.
3989 static __isl_give isl_ast_node *create_kernel_leaf(
3990 __isl_take isl_ast_build *build, void *user)
3992 struct gpu_gen *gen = (struct gpu_gen *) user;
3993 isl_map *map;
3994 isl_union_map *schedule;
3995 const char *name;
3997 schedule = isl_ast_build_get_schedule(build);
3999 if (isl_union_map_n_map(schedule) != 1)
4000 return create_domain_leaf(schedule, build, user);
4002 map = isl_map_from_union_map(schedule);
4003 name = isl_map_get_tuple_name(map, isl_dim_in);
4004 if (!strcmp(name, "read") || !strcmp(name, "write"))
4005 return create_access_leaf(gen, map, build);
4006 if (!strcmp(name, "sync"))
4007 return create_sync_leaf(gen, map, build);
4009 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4012 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4013 * have value 0) and all even schedule dimensions as "unroll".
4015 * That is, the options look as follows
4017 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4018 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4020 * The even positions are used to be able to schedule copying blocks
4021 * and synchronization before or after each level of the shared memory
4022 * tile loops and we want to make sure that code for these is generated
4023 * separately (within each level).
4025 static __isl_give isl_ast_build *set_atomic_and_unroll(
4026 __isl_take isl_ast_build *build,
4027 __isl_take isl_space *space, int sched_len)
4029 isl_ctx *ctx;
4030 isl_map *map;
4031 isl_constraint *c;
4032 isl_union_map *opt;
4033 isl_local_space *ls;
4034 int i, n;
4036 ctx = isl_ast_build_get_ctx(build);
4038 space = isl_space_params(space);
4039 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4040 space = isl_space_from_domain(space);
4041 space = isl_space_add_dims(space, isl_dim_out, 2);
4042 map = isl_map_universe(isl_space_copy(space));
4043 for (i = 0; i < sched_len; i += 2)
4044 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4045 ls = isl_local_space_from_space(isl_map_get_space(map));
4046 c = isl_equality_alloc(ls);
4047 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4048 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4049 c = isl_constraint_set_constant_si(c, 1);
4050 map = isl_map_add_constraint(map, c);
4051 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4052 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4053 opt = isl_union_map_from_map(map);
4055 map = isl_map_universe(space);
4056 ls = isl_local_space_from_space(isl_map_get_space(map));
4057 c = isl_equality_alloc(ls);
4058 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4059 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4060 map = isl_map_add_constraint(map, c);
4061 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4062 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4063 opt = isl_union_map_add_map(opt, map);
4065 build = isl_ast_build_set_options(build, opt);
4067 return build;
4070 /* Return a map that maps a space of dimension gen->shared_len
4071 * to its last dimensions starting at gen->tile_first.
4072 * The range is of dimension
4074 * 2 * (gen->shared_len - gen->tile_first) + 1
4076 * The input dimensions are mapped to the odd dimensions in the output,
4077 * while the even dimensions (except 2*pos) are fixed to 0.
4078 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4079 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4080 * are mapped to the output. The remaining input dimensions are projected
4081 * out and the corresponding output dimensions are fixed to 0.
4083 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4084 __isl_take isl_space *space, int pos, int val)
4086 int i, n;
4087 isl_map *proj;
4089 space = isl_space_set_from_params(space);
4090 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4091 space = isl_space_map_from_set(space);
4092 proj = isl_map_identity(space);
4093 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4094 n = gen->shared_len - gen->tile_first;
4095 for (i = 0; i <= n; ++i) {
4096 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4097 if (i == pos)
4098 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4099 else
4100 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4103 if (pos < 0)
4104 return proj;
4106 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4107 gen->shared_len - (gen->tile_first + pos));
4108 for (i = pos; i < n; ++i)
4109 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4111 return proj;
4114 /* Given the AST context schedule "schedule" and the mapping from
4115 * domains to the shared tile loops "shared_sched", add a schedule
4116 * for a synchronization operation at position "val" of loop level "pos".
4118 * schedule is of the form
4120 * D -> L
4122 * (with D the iteration domains and L the already generated loops),
4123 * while shared_sched is of the form
4125 * D -> S
4127 * We combine them into
4129 * L -> S
4131 * apply a mapping
4133 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4135 * and use the result as a schedule for "sync".
4137 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4138 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4139 __isl_keep isl_union_map *shared_sched, int pos, int val)
4141 isl_space *space;
4142 isl_map *proj, *map;
4144 shared_sched = isl_union_map_copy(shared_sched);
4145 schedule = isl_union_map_copy(schedule);
4147 space = isl_union_map_get_space(shared_sched);
4148 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4149 map = isl_map_from_union_map(schedule);
4151 proj = insert_even(gen, space, pos, val);
4152 map = isl_map_apply_range(map, proj);
4153 map = isl_map_from_range(isl_map_wrap(map));
4154 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4156 res = isl_union_map_add_map(res, map);
4158 return res;
4161 /* Given the AST context schedule "schedule" and the mapping from
4162 * domains to the shared tile loops "shared_sched", add a schedule
4163 * for copying an array reference group to/from shared/private memory.
4164 * "read" is set if data should be copied from global memory
4165 * to shared/private memory.
4166 * "k" represents the current group
4167 * "s" is the total number of groups
4169 * We schedule an operation before or after the innermost loop
4170 * of "shared_sched" that affects the tile of the array reference group.
4172 * schedule is of the form
4174 * D -> L
4176 * (with D the iteration domains and L the already generated loops),
4177 * while shared_sched is of the form
4179 * D -> S
4181 * We first compute the access relation for the reference group
4183 * D -> A
4185 * and combine it with shared_sched into
4187 * D -> [S -> A]
4189 * If this results in an empty relation, no copying needs to be performed
4190 * at this point.
4191 * Otherwise, we invert the relation and combine it with "schedule" into
4193 * [S -> A] -> L
4195 * The actual additional piece of the schedule is obtained from combining
4197 * [S -> A] -> S
4199 * with a mapping
4201 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4203 * The position of "val" corresponds to the innermost loop that affects
4204 * the tile and the value indicates where the copying is scheduled
4205 * with respect to the actual kernel code (at value 0).
4206 * Reads are schedule before the code, writes to global memory from
4207 * private memory are scheduled at values 1 to s, writes to global
4208 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4210 * If we are scheduling a read from global memory to shared memory,
4211 * we insert a synchronization before the kernel code (at the innermost
4212 * level).
4213 * If we are scheduling a write to global memory, then we add
4214 * a synchronization after all writes (at value 2 *s + 2).
4215 * However, there is no need for a synchronization after the outermost loop.
4216 * A write to global memory from private memory at the innermost level
4217 * does not require a synchronization, because it is covered by
4218 * the synchronization after the kernel inserted by body_schedule.
4220 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4221 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4222 __isl_keep isl_union_map *shared_sched,
4223 struct gpu_array_ref_group *group, int read, int k, int s)
4225 int n;
4226 int pos, val;
4227 isl_space *space;
4228 isl_union_map *access;
4229 isl_map *map, *proj, *access_map;
4230 isl_id *id;
4232 access = group_access_relation(group, read, !read);
4233 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4234 access);
4236 if (isl_union_map_is_empty(access)) {
4237 isl_union_map_free(access);
4238 return res;
4241 access = isl_union_map_reverse(access);
4242 access = isl_union_map_apply_range(access,
4243 isl_union_map_copy(schedule));
4244 access_map = isl_map_from_union_map(access);
4246 space = isl_space_copy(group->array->dim);
4247 space = isl_space_from_range(space);
4248 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4249 map = isl_map_domain_map(isl_map_universe(space));
4251 space = isl_union_map_get_space(schedule);
4252 pos = group->last_shared + 1 - gen->tile_first;
4253 assert(pos >= 0);
4254 if (read)
4255 val = -2 - k;
4256 else if (group->private_tile)
4257 val = 1 + k;
4258 else
4259 val = 1 + s + 1 + k;
4260 proj = insert_even(gen, space, pos, val);
4261 map = isl_map_apply_range(map, proj);
4263 access_map = isl_map_range_product(access_map, map);
4265 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4266 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4268 res = isl_union_map_add_map(res, access_map);
4270 n = gen->shared_len - gen->tile_first;
4271 if (read) {
4272 if (!group->private_tile)
4273 res = add_sync_schedule(gen, res, schedule,
4274 shared_sched, n, -1);
4275 } else {
4276 if (pos == 0)
4277 return res;
4278 if (pos == n && group->private_tile)
4279 return res;
4280 res = add_sync_schedule(gen, res, schedule, shared_sched,
4281 pos, 2 * s + 2);
4284 return res;
4287 /* Return a schedule for the shared tile loops based on the current
4288 * AST context schedule.
4290 * We create a "shared_sched" that maps the domains to the first
4291 * shared_len dimensions of the computed schedule, project out the
4292 * first tile_first dimensions (as these are already covered by
4293 * the host code) and insert "statement-level" dimensions at even
4294 * positions so that we can schedule copy blocks and synchronization
4295 * before/after each level.
4297 * In particular, copy blocks are inserted inside the innermost
4298 * level that affect the tile. For the copying to global memory,
4299 * those from private memory are scheduled before those from shared
4300 * memory such that synchronization can be inserted between the two
4301 * at the innermost level.
4302 * Synchronization is inserted at the innermost level before the
4303 * actual kernel code if there is any copying from global memory
4304 * to shared memory. It is inserted unconditionally at the innermost
4305 * level after the actual kernel code and the copying to global memory
4306 * from private memory (if any). Finally, it is inserted after
4307 * any copying to global memory, except at the outermost level
4308 * and at the innermost level if there is no copying from shared
4309 * memory. The copying from private memory is covered by the unconditional
4310 * synchronization at the innermost level.
4312 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4313 __isl_take isl_union_map *schedule)
4315 isl_space *space;
4316 isl_union_map *res;
4317 isl_union_map *shared_sched;
4318 isl_union_map *sched;
4319 isl_map *proj, *map;
4320 int i, j, k, s;
4322 shared_sched = isl_union_map_copy(gen->tiled_sched);
4323 proj = projection(isl_union_map_get_space(shared_sched),
4324 gen->tiled_len, gen->shared_len);
4325 shared_sched = isl_union_map_apply_range(shared_sched,
4326 isl_union_map_from_map(proj));
4327 space = isl_union_map_get_space(shared_sched);
4328 proj = insert_even(gen, space, -1, 0);
4329 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4330 isl_union_map_from_map(proj));
4332 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4334 s = 0;
4335 for (i = 0; i < gen->prog->n_array; ++i)
4336 s += gen->prog->array[i].n_group;
4338 k = 0;
4339 for (i = 0; i < gen->prog->n_array; ++i) {
4340 struct gpu_array_info *array = &gen->prog->array[i];
4342 for (j = 0; j < array->n_group; ++j) {
4343 struct gpu_array_ref_group *group;
4345 group = array->groups[j];
4346 if (!group->private_tile && !group->shared_tile)
4347 continue;
4348 res = add_group_schedule(gen, res, schedule,
4349 shared_sched, group, 0, k, s);
4350 res = add_group_schedule(gen, res, schedule,
4351 shared_sched, group, 1, k, s);
4352 ++k;
4356 res = add_sync_schedule(gen, res, schedule, shared_sched,
4357 gen->shared_len - gen->tile_first, 1 + s);
4359 isl_union_map_free(shared_sched);
4360 isl_union_map_free(schedule);
4362 return res;
4365 /* Generate code for "kernel" in the given "context".
4367 * We first generate code for the shared tile loops (T1T, T1P and T2)
4368 * in a context that includes the block ids.
4369 * Within each iteration of these loops an additional code generation
4370 * is performed (within create_kernel_leaf) for the rest of the schedule
4371 * in a context that includes the thread ids.
4373 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4374 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4375 __isl_keep isl_multi_pw_aff *grid_size)
4377 isl_space *space;
4378 isl_set *set;
4379 isl_id_list *iterators;
4380 isl_union_map *schedule;
4381 isl_ast_node *tree;
4382 int sched_len;
4384 schedule = isl_ast_build_get_schedule(build);
4386 build = isl_ast_build_copy(build);
4387 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4388 space = isl_ast_build_get_schedule_space(build);
4389 set = isl_set_universe(isl_space_copy(space));
4390 set = add_bounded_parameters_dynamic(set, grid_size, "b");
4391 build = isl_ast_build_restrict(build, set);
4393 schedule = body_schedule(gen, schedule);
4395 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4397 build = set_atomic_and_unroll(build, space, sched_len);
4398 iterators = generate_names(gen->ctx, sched_len, "g");
4399 build = isl_ast_build_set_iterators(build, iterators);
4400 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4401 tree = isl_ast_build_ast_from_schedule(build, schedule);
4402 isl_ast_build_free(build);
4404 return tree;
4407 /* Attach "id" to the given node.
4409 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4410 __isl_keep isl_ast_build *build, void *user)
4412 isl_id *id = user;
4414 node = isl_ast_node_set_annotation(node, id);
4416 return node;
4419 /* Construct an AST node for performing a kernel launch and attach
4420 * the information about the kernel to that node.
4422 * The kernel AST has been constructed in the context of the range
4423 * of "schedule". In particular, the grid size has been computed
4424 * in the context. We therefore still need to make sure that these
4425 * constraints are expressed in the code. We do this by creating a schedule
4427 * kernel[] -> [S -> []]
4429 * where S is the schedule domain, i.e., the range of "schedule".
4430 * The AST generation will then create a single call surrounded by
4431 * all the condition in "S" that have not been expressed yet.
4433 * The kernel information is attached to this node in attach_id.
4435 static __isl_give isl_ast_node *construct_launch(
4436 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
4437 __isl_take struct ppcg_kernel *kernel)
4439 isl_id *id;
4440 isl_ctx *ctx;
4441 isl_union_set *domain;
4442 isl_set *set;
4443 isl_map *map;
4444 isl_ast_node *node;
4446 ctx = isl_ast_build_get_ctx(build);
4448 id = isl_id_alloc(ctx, NULL, kernel);
4449 id = isl_id_set_free_user(id, &ppcg_kernel_free);
4451 domain = isl_union_map_range(schedule);
4452 set = isl_set_from_union_set(domain);
4453 map = isl_map_from_domain(set);
4454 map = isl_map_from_range(isl_map_wrap(map));
4455 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
4456 schedule = isl_union_map_from_map(map);
4458 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
4459 node = isl_ast_build_ast_from_schedule(build, schedule);
4460 isl_ast_build_free(build);
4462 return node;
4465 /* This function is called for each leaf in the AST of the host code.
4466 * We first specialize the schedule to the site of the leaf, compute
4467 * the size of shared memory and then construct the body of the host code
4468 * and the associated kernel.
4470 * The necessary information for printing the kernel launch is
4471 * stored in a struct ppcg_kernel and attached to the leaf node
4472 * created to represent the launch.
4474 static __isl_give isl_ast_node *create_host_leaf(
4475 __isl_take isl_ast_build *build, void *user)
4477 struct gpu_gen *gen = (struct gpu_gen *) user;
4478 isl_id *id;
4479 isl_ast_node *node;
4480 struct ppcg_kernel *kernel;
4481 isl_set *host_domain;
4482 isl_union_map *schedule;
4483 isl_union_map *local_sched;
4484 isl_union_map *access;
4485 isl_union_set *domain;
4486 int i;
4488 schedule = isl_ast_build_get_schedule(build);
4490 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
4491 read_sizes(gen);
4493 domain = isl_union_map_domain(isl_union_map_copy(schedule));
4495 local_sched = isl_union_map_copy(gen->sched);
4496 local_sched = isl_union_map_intersect_domain(local_sched, domain);
4497 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
4498 isl_union_map_copy(gen->prog->write));
4499 access = isl_union_map_apply_domain(access,
4500 isl_union_map_copy(local_sched));
4502 gen->tiled_sched = tile_schedule(gen, local_sched);
4503 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
4504 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
4506 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
4507 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
4508 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
4510 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
4511 if (!kernel)
4512 goto error;
4514 kernel->id = gen->kernel_id++;
4515 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
4516 kernel->grid_size = extract_grid_size(gen, kernel);
4517 extract_block_size(gen, kernel);
4518 kernel->arrays = isl_union_map_range(access);
4519 kernel->space = isl_ast_build_get_schedule_space(build);
4521 gen->private_access = NULL;
4522 compute_shared_sched(gen);
4523 gen->privatization = compute_privatization(gen);
4524 group_references(gen);
4525 compute_private_access(gen);
4526 check_shared_memory_bound(gen);
4527 compute_group_tilings(gen);
4528 host_domain = isl_set_from_union_set(isl_union_map_range(
4529 isl_union_map_copy(schedule)));
4530 localize_bounds(gen, kernel, host_domain);
4532 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
4534 kernel->tree = generate_kernel(gen, build, host_domain,
4535 kernel->grid_size);
4536 create_kernel_vars(gen, kernel);
4538 free_local_array_info(gen);
4539 isl_map_free(gen->privatization);
4540 isl_union_map_free(gen->private_access);
4541 isl_union_map_free(gen->local_sched);
4542 isl_union_map_free(gen->tiled_sched);
4543 isl_union_map_free(gen->shared_sched);
4544 isl_union_map_free(gen->shared_proj);
4545 isl_set_free(host_domain);
4546 free(gen->tile_size);
4548 node = construct_launch(build, schedule, kernel);
4550 return node;
4551 error:
4552 isl_union_map_free(schedule);
4553 return NULL;
4556 /* Use isl to generate code for the outer gen->tile_first loops
4557 * of the global schedule in gen->sched, resulting in the host code.
4558 * Within each iteration of this partial schedule, i.e., for each kernel
4559 * launch, create_host_leaf takes care of generating the kernel code.
4561 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
4563 isl_ast_build *build;
4564 isl_ast_node *tree;
4565 isl_union_map *sched;
4566 isl_map *proj;
4567 isl_id_list *iterators;
4569 sched = isl_union_map_copy(gen->sched);
4570 proj = projection(isl_union_map_get_space(sched),
4571 gen->untiled_len, gen->tile_first);
4572 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4574 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
4575 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
4576 iterators = generate_names(gen->ctx, gen->tile_first, "h");
4577 build = isl_ast_build_set_iterators(build, iterators);
4578 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
4579 tree = isl_ast_build_ast_from_schedule(build, sched);
4580 isl_ast_build_free(build);
4582 return tree;
4585 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
4587 if (!str)
4588 return NULL;
4589 return isl_union_map_read_from_str(ctx, str);
4592 /* Information about the outermost tilable bands in the forest of bands.
4594 * tile_len and n_parallel are only sets on band_info structures
4595 * that correspond to outermost bands. For other bands (in particular,
4596 * ancestors of the outermost bands), n_parallal is set to 0.
4598 * prefix is the (padded) schedule leading up to the outermost tilable bands.
4600 * tile_first is the number of schedule dimensions in prefix.
4602 * suffix is the schedule of the outermost tilable bands and their descendants.
4604 struct band_info {
4605 struct gpu_gen *gen;
4606 int tile_first;
4607 int tile_len;
4608 int n_parallel;
4609 isl_union_map *prefix;
4610 isl_union_map *suffix;
4613 /* Set tile_len and n_parallel of the statement to that of
4614 * their outermost band, recorded in the band_info.
4616 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
4618 struct band_info *info = user;
4619 struct gpu_stmt *stmt;
4620 isl_id *id;
4622 id = isl_map_get_tuple_id(map, isl_dim_in);
4623 stmt = find_stmt(info->gen->prog, id);
4624 isl_id_free(id);
4626 stmt->tile_len = info->tile_len;
4627 stmt->n_parallel = info->n_parallel;
4629 isl_map_free(map);
4631 return 0;
4634 static void list_select_outer_band(struct gpu_gen *gen,
4635 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
4637 /* Check if this band has any parallel loops. If so, take it as
4638 * the outermost tilable band. If not, continue looking for the
4639 * outermost tilable band in the children of the current band.
4641 static void band_select_outer_band(struct gpu_gen *gen,
4642 __isl_take isl_band *band, int pos, struct band_info *info)
4644 int n = isl_band_n_member(band);
4645 int n_parallel;
4647 for (n_parallel = 0; n_parallel < n; ++n_parallel)
4648 if (!isl_band_member_is_zero_distance(band, n_parallel))
4649 break;
4651 info->n_parallel = n_parallel;
4652 if (n_parallel) {
4653 gen->any_parallelism = 1;
4654 info->gen = gen;
4655 info->tile_first = pos;
4656 info->tile_len = n;
4657 info->prefix = isl_band_get_prefix_schedule(band);
4658 info->suffix = isl_union_map_flat_range_product(
4659 isl_band_get_partial_schedule(band),
4660 isl_band_get_suffix_schedule(band));
4661 isl_union_map_foreach_map(info->prefix,
4662 &set_stmt_tile_len, info);
4663 } else if (isl_band_has_children(band)) {
4664 isl_band_list *children;
4665 children = isl_band_get_children(band);
4666 list_select_outer_band(gen, children, pos + n, info);
4667 } else {
4668 info->gen = gen;
4669 info->tile_first = pos + n;
4670 info->tile_len = 0;
4671 info->prefix = isl_union_map_flat_range_product(
4672 isl_band_get_prefix_schedule(band),
4673 isl_band_get_partial_schedule(band));
4674 info->suffix = isl_band_get_suffix_schedule(band);
4675 isl_union_map_foreach_map(info->prefix,
4676 &set_stmt_tile_len, info);
4679 isl_band_free(band);
4682 /* Comparison function that returns a non-zero value for band_infos
4683 * with different tile_len fields or different n_parallel fields.
4685 static int cmp_band(const void *p1, const void *p2)
4687 const struct band_info *info1 = p1;
4688 const struct band_info *info2 = p2;
4690 if (info1->tile_len != info2->tile_len)
4691 return info1->tile_len - info2->tile_len;
4693 return info1->n_parallel - info2->n_parallel;
4696 /* Extend "umap" with coordinates with fixed value "val"
4697 * to a total length of "dst_len", assuming the original dimension is "src_len".
4699 static __isl_give isl_union_map *extend_range(
4700 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
4702 isl_space *dim;
4703 isl_map *map;
4704 int i;
4706 dim = isl_union_map_get_space(umap);
4707 map = isl_map_reverse(projection(dim, dst_len, src_len));
4708 for (i = src_len; i < dst_len; ++i)
4709 map = isl_map_fix_si(map, isl_dim_out, i, val);
4711 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
4713 return umap;
4716 /* Group bands with the same values for tile_len and n_parallel.
4717 * The prefix schedule is then extended with a fixed coordinate that
4718 * is different for each such group.
4719 * Note that the actual values for this coordinate are not important.
4720 * The bands have already been effectively separated at a higher level
4721 * or they are independent and may be executed in parallel.
4722 * The list of band_info has been sorted before this functions is called.
4724 static void separate_bands(struct band_info *info, int n)
4726 int i;
4727 int j = 0;
4729 for (i = 0; i < n; ++i) {
4730 int l = info[i].tile_first;
4732 if (i &&
4733 (info[i].tile_len != info[i - 1].tile_len ||
4734 info[i].n_parallel != info[i - 1].n_parallel))
4735 j++;
4737 info[i].prefix = extend_range(info[i].prefix,
4738 l, l + 1, j);
4739 info[i].tile_first = l + 1;
4743 /* Select the outermost bands in the elements of the list, align
4744 * their prefix schedules, separate bands with different values
4745 * for tile_len and/or n_parallel and then combine the resulting
4746 * prefix and suffix schedules into a single pair of prefix and
4747 * suffix schedules for the entire list.
4749 static void list_select_outer_band(struct gpu_gen *gen,
4750 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
4752 isl_band *band;
4753 int i;
4754 int n = isl_band_list_n_band(list);
4755 isl_ctx *ctx = isl_band_list_get_ctx(list);
4756 struct band_info *info;
4757 int max_tile_first;
4758 isl_union_map *prefix;
4759 isl_union_map *suffix;
4761 assert(n >= 1);
4762 info = isl_calloc_array(ctx, struct band_info, n);
4763 assert(info);
4765 max_tile_first = 0;
4766 for (i = 0; i < n; ++i) {
4767 band = isl_band_list_get_band(list, i);
4768 band_select_outer_band(gen, band, pos, &info[i]);
4769 if (info[i].tile_first > max_tile_first)
4770 max_tile_first = info[i].tile_first;
4773 for (i = 0; i < n; ++i) {
4774 if (info[i].tile_first == max_tile_first)
4775 continue;
4776 info[i].prefix = extend_range(info[i].prefix,
4777 info[i].tile_first, max_tile_first, 0);
4778 info[i].tile_first = max_tile_first;
4781 qsort(info, n, sizeof(struct band_info), &cmp_band);
4783 for (i = 0; i < n - 1; ++i)
4784 if (info[i].tile_len != info[i + 1].tile_len ||
4785 info[i].n_parallel != info[i + 1].n_parallel)
4786 break;
4788 if (i < n -1)
4789 separate_bands(info, n);
4791 prefix = info[0].prefix;
4792 suffix = info[0].suffix;
4794 for (i = 1; i < n; ++i) {
4795 prefix = isl_union_map_union(prefix, info[i].prefix);
4796 suffix = isl_union_map_union(suffix, info[i].suffix);
4799 list_info->tile_first = info[0].tile_first;
4800 list_info->tile_len = -1;
4801 list_info->prefix = prefix;
4802 list_info->suffix = suffix;
4804 isl_band_list_free(list);
4805 free(info);
4808 /* Select the outermost tilable band that (by construction)
4809 * has at least one parallel loop.
4810 * The starting position of the aligned band is stored in the pair
4811 * gen->tile_first.
4812 * The sizes and number of parallel loops may be different in different
4813 * parts of the band forest and are therefore stored in the gpu_stmts.
4815 * Return the complete schedule, with the tilable bands aligned
4816 * at gen->tile_first and padded with zero, if needed.
4818 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
4819 __isl_keep isl_schedule *schedule)
4821 isl_band_list *list;
4822 struct band_info info;
4824 gen->n_parallel = 0;
4825 gen->tile_len = -1;
4827 list = isl_schedule_get_band_forest(schedule);
4829 if (isl_band_list_n_band(list) == 0) {
4830 isl_band_list_free(list);
4831 return isl_schedule_get_map(schedule);
4834 list_select_outer_band(gen, list, 0, &info);
4836 gen->tile_first = info.tile_first;
4837 info.suffix = align_range(info.suffix);
4839 return isl_union_map_flat_range_product(info.prefix, info.suffix);
4842 /* Set gen->untiled_len to the number of scheduling dimensions
4843 * for the schedule of the first domain.
4844 * We assume here that this number is the same for all domains.
4846 static int set_untiled_len(__isl_take isl_map *map, void *user)
4848 unsigned *untiled_len = user;
4850 *untiled_len = isl_map_dim(map, isl_dim_out);
4852 isl_map_free(map);
4853 return -1;
4856 /* Compute an appropriate schedule based on the accesses in
4857 * gen->read and gen->write.
4859 * We use the dependences in gen->prog->scop to compute
4860 * a schedule that has a parallel loop in each tilable band.
4861 * Finally, we select the outermost tilable band.
4863 static void compute_schedule(struct gpu_gen *gen)
4865 isl_union_set *domain;
4866 isl_union_map *dep_raw, *dep;
4867 isl_union_map *sched;
4868 isl_schedule *schedule;
4870 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4872 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4873 dep = isl_union_map_union(dep, dep_raw);
4874 dep = isl_union_map_coalesce(dep);
4876 domain = isl_union_set_copy(gen->prog->scop->domain);
4877 domain = isl_union_set_intersect_params(domain,
4878 isl_set_copy(gen->prog->scop->context));
4879 schedule = isl_union_set_compute_schedule(isl_union_set_copy(domain),
4880 isl_union_map_copy(dep), dep);
4881 if (gen->options->debug->dump_schedule)
4882 isl_schedule_dump(schedule);
4884 sched = select_outer_tilable_band(gen, schedule);
4886 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
4887 sched = isl_union_map_intersect_domain(sched, domain);
4888 gen->sched = sched;
4890 isl_schedule_free(schedule);
4893 /* Compute the sets of array elements that need to be copied in and out.
4895 * In particular, for each array that is written anywhere in gen->prog and
4896 * that is visible outside the corresponding scop, we copy out its entire
4897 * extent.
4899 * Any array elements that is read without first being written needs
4900 * to be copied in. Furthermore, if there are any array elements that
4901 * are copied out, but that are not written inside gen->prog, then
4902 * they also need to be copied in to ensure that the value after execution
4903 * is the same as the value before execution.
4904 * While computing the set of array elements that
4905 * are copied out but not written, we intersect both sets with the context.
4906 * This helps in those cases where the arrays are declared with a fixed size,
4907 * while the accesses are parametric and the context assigns a fixed value
4908 * to the parameters.
4910 static void compute_copy_in_and_out(struct gpu_gen *gen)
4912 int i;
4913 isl_union_set *write;
4914 isl_union_set *copy_in, *copy_out;
4915 isl_union_set *not_written;
4916 isl_union_map *uninitialized;
4918 write = isl_union_map_range(isl_union_map_copy(gen->prog->write));
4919 write = isl_union_set_intersect_params(write,
4920 isl_set_copy(gen->prog->context));
4921 copy_out = isl_union_set_empty(isl_union_set_get_space(write));
4923 for (i = 0; i < gen->prog->n_array; ++i) {
4924 isl_space *space;
4925 isl_set *write_i;
4926 int empty;
4928 if (gen->prog->array[i].local)
4929 continue;
4931 space = isl_space_copy(gen->prog->array[i].dim);
4932 write_i = isl_union_set_extract_set(write, space);
4933 empty = isl_set_fast_is_empty(write_i);
4934 isl_set_free(write_i);
4935 if (empty)
4936 continue;
4938 write_i = isl_set_copy(gen->prog->array[i].extent);
4939 copy_out = isl_union_set_add_set(copy_out, write_i);
4942 copy_out = isl_union_set_intersect_params(copy_out,
4943 isl_set_copy(gen->prog->context));
4945 gen->prog->copy_out = isl_union_set_copy(copy_out);
4947 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
4948 copy_in = isl_union_map_range(uninitialized);
4950 not_written = isl_union_set_subtract(copy_out, write);
4951 copy_in = isl_union_set_union(copy_in, not_written);
4952 gen->prog->copy_in = copy_in;
4955 static struct gpu_stmt_access **expr_extract_access(struct pet_expr *expr,
4956 struct gpu_stmt_access **next_access)
4958 struct gpu_stmt_access *access;
4959 isl_ctx *ctx = isl_map_get_ctx(expr->acc.access);
4961 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4962 assert(access);
4963 access->next = NULL;
4964 access->read = expr->acc.read;
4965 access->write = expr->acc.write;
4966 access->access = isl_map_copy(expr->acc.access);
4967 access->ref_id = isl_id_copy(expr->acc.ref_id);
4969 *next_access = access;
4970 next_access = &(*next_access)->next;
4971 return next_access;
4974 static struct gpu_stmt_access **expr_extract_accesses(struct pet_expr *expr,
4975 struct gpu_stmt_access **next_access)
4977 int i;
4979 for (i = 0; i < expr->n_arg; ++i)
4980 next_access = expr_extract_accesses(expr->args[i],
4981 next_access);
4983 if (expr->type == pet_expr_access)
4984 next_access = expr_extract_access(expr, next_access);
4986 return next_access;
4989 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
4991 struct gpu_stmt_access **next_access = &stmt->accesses;
4993 stmt->accesses = NULL;
4994 expr_extract_accesses(stmt->stmt->body, next_access);
4997 /* Return an array of gpu_stmt representing the statements in "scop".
4999 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5000 __isl_keep isl_set *context)
5002 int i;
5003 struct gpu_stmt *stmts;
5005 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
5006 if (!stmts)
5007 return NULL;
5009 for (i = 0; i < scop->n_stmt; ++i) {
5010 struct gpu_stmt *s = &stmts[i];
5012 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
5013 s->stmt = scop->stmts[i];
5014 pet_stmt_extract_accesses(s);
5017 return stmts;
5020 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5022 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5024 struct gpu_gen *gen = user;
5026 return gen->print(p, gen->prog, gen->tree, gen->print_user);
5029 /* Generate CUDA code for "scop" and print it to "p".
5030 * After generating an AST for the transformed scop as explained below,
5031 * we call "gen->print" to print the AST in the desired output format
5032 * to "p".
5034 * If it turns out that it does not make sense to generate GPU code,
5035 * then we generate CPU code instead.
5037 * The GPU code is generated in a context where at least one
5038 * statement instance is executed. The corresponding guard (if any) is printed
5039 * around the entire generated GPU code, except for the declaration
5040 * of the arrays that are visible outside of the scop and that therefore
5041 * cannot be declared inside the body of any possible guard.
5043 * We first compute a schedule that respects the dependences
5044 * of the original program and select the outermost band
5045 * of tilable dimensions that has at least one parallel loop.
5046 * We then have three blocks of dimensions
5048 * H B G
5050 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5051 * in
5053 * H T P G
5055 * For each iteration of the T loop and for each array, we compute
5056 * the array elements accessed by that iteration, construct a rectangular
5057 * box around it and shift it to the origin. The result is used
5058 * as shared memory for the array.
5060 * We then split off at most 2 parallel loops from the T loops and
5061 * at most 3 parallel loops from the P loops
5063 * H T1 T2 P1 P2 G
5065 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5066 * according to "grid"/"block" sizes.
5068 * H T1T T1P T2 P1T P1P P2 G
5070 * Finally, the T1P and P1P iterators are equated to the block and
5071 * thread dimensions respectively and so are effectively removed.
5072 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5073 * are run on the GPU.
5075 * Code is generated in three stages. We first generate code for the
5076 * host (the H loops), with iterators h%d. Then, for each leaf node
5077 * of the resulting AST, we generate code for the shared loops (up to
5078 * and including T2), with iterators g%d and after equating the H loops
5079 * to h%d parameters and the T1P loops to the block dimensions.
5080 * Finally, we generate code for the remaining loops in a similar fashion.
5082 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5083 struct gpu_gen *gen, struct ppcg_scop *scop,
5084 struct ppcg_options *options)
5086 struct gpu_prog *prog;
5087 isl_ctx *ctx;
5088 isl_set *context, *guard;
5090 if (!scop)
5091 return isl_printer_free(p);
5093 ctx = isl_printer_get_ctx(p);
5094 prog = gpu_prog_alloc(ctx, scop);
5095 if (!prog)
5096 return isl_printer_free(p);
5098 context = isl_set_copy(prog->context);
5099 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5100 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5102 gen->prog = prog;
5103 gen->any_parallelism = 0;
5104 compute_schedule(gen);
5106 if (!gen->any_parallelism) {
5107 isl_set_free(context);
5108 isl_set_free(guard);
5109 p = print_cpu(p, scop, options);
5110 } else {
5111 compute_copy_in_and_out(gen);
5112 gen->tree = generate_host_code(gen);
5113 p = ppcg_print_exposed_declarations(p, prog->scop);
5114 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5115 isl_ast_node_free(gen->tree);
5118 isl_union_map_free(gen->sched);
5120 gpu_prog_free(prog);
5122 return p;
5125 /* Wrapper around generate for use as a ppcg_transform callback.
5127 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5128 struct ppcg_scop *scop, void *user)
5130 struct gpu_gen *gen = user;
5132 return generate(p, gen, scop, gen->options);
5135 /* Transform the code in the file called "input" by replacing
5136 * all scops by corresponding GPU code and write the results to "out".
5138 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5139 struct ppcg_options *options,
5140 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5141 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5142 void *user), void *user)
5144 struct gpu_gen gen;
5145 int r;
5147 gen.ctx = ctx;
5148 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5149 gen.options = options;
5150 gen.kernel_id = 0;
5151 gen.print = print;
5152 gen.print_user = user;
5154 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5156 isl_union_map_free(gen.sizes);
5158 return r;
5161 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5163 struct gpu_prog *prog;
5165 if (!scop)
5166 return NULL;
5168 prog = isl_calloc_type(ctx, struct gpu_prog);
5169 assert(prog);
5171 prog->ctx = ctx;
5172 prog->scop = scop;
5173 prog->context = isl_set_copy(scop->context);
5174 prog->n_stmts = scop->n_stmt;
5175 prog->stmts = extract_stmts(ctx, scop, prog->context);
5176 prog->read = isl_union_map_copy(scop->reads);
5177 prog->write = isl_union_map_copy(scop->writes);
5179 if (!prog->stmts)
5180 return gpu_prog_free(prog);
5182 if (collect_array_info(prog) < 0)
5183 return gpu_prog_free(prog);
5185 return prog;
5188 void *gpu_prog_free(struct gpu_prog *prog)
5190 if (!prog)
5191 return NULL;
5192 free_array_info(prog);
5193 free_stmts(prog->stmts, prog->n_stmts);
5194 isl_union_set_free(prog->copy_in);
5195 isl_union_set_free(prog->copy_out);
5196 isl_union_map_free(prog->read);
5197 isl_union_map_free(prog->write);
5198 isl_set_free(prog->context);
5199 free(prog);
5200 return NULL;