gpu_stmt_access: keep track of reference id
[ppcg.git] / gpu.c
blob05531627bcc2fc2ad258fa9de58b4e707df713a8
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"
32 #include "rewrite.h"
34 /* The fields stride, shift and shift_map only contain valid information
35 * if shift != NULL.
36 * If so, they express that current index is such that if you add shift,
37 * then the result is always a multiple of stride.
38 * shift_map contains the mapping
40 * i -> (i + shift)/stride
42 * Let D represent the initial shared_len dimensions of the computed schedule.
43 * The spaces of "lb" and "shift" are of the form
45 * D -> [b]
47 * "shift_map" is of the form
49 * [D -> i] -> [D -> (i + shift(D))/stride]
51 struct gpu_array_bound {
52 isl_val *size;
53 isl_aff *lb;
55 isl_val *stride;
56 isl_aff *shift;
57 isl_basic_map *shift_map;
60 /* A tile of an array.
62 * n is the dimension of the array.
63 * bound is an array of size "n" representing the lower bound
64 * and size for each index.
66 * tiling maps a tile in the global array to the correspondin
67 * shared/private memory tile and is of the form
69 * { [D[i] -> A[a]] -> T[(a + shift(i))/stride - lb(i)] }
71 * where D represents the initial shared_len dimensions
72 * of the computed schedule.
74 struct gpu_array_tile {
75 int n;
76 struct gpu_array_bound *bound;
77 isl_multi_aff *tiling;
80 struct gpu_array_info;
82 /* A group of array references in a kernel that should be handled together.
83 * If private_tile is not NULL, then it is mapped to registers.
84 * Otherwise, if shared_tile is not NULL, it is mapped to shared memory.
85 * Otherwise, it is accessed from global memory.
87 struct gpu_array_ref_group {
88 /* The references in this group access this array. */
89 struct gpu_array_info *array;
90 /* Position of this group in the list of reference groups of array. */
91 int nr;
93 /* The following fields are use during the construction of the groups.
94 * access is the combined access relation relative to the shared
95 * memory tiling. In particular, the domain of the map corresponds
96 * to the first shared_len dimensions of the computed schedule.
97 * write is set if any access in the group is a write.
99 isl_map *access;
100 int write;
102 /* The shared memory tile, NULL if none. */
103 struct gpu_array_tile *shared_tile;
105 /* The private memory tile, NULL if none. */
106 struct gpu_array_tile *private_tile;
108 /* References in this group; point to elements of a linked list. */
109 int n_ref;
110 struct gpu_stmt_access **refs;
112 /* Last shared memory tile dimension that affects tile of this group. */
113 int last_shared;
116 struct gpu_gen {
117 isl_ctx *ctx;
118 struct ppcg_options *options;
120 /* Callback for printing of AST in appropriate format. */
121 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
122 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
123 void *user);
124 void *print_user;
126 struct gpu_prog *prog;
127 /* The generated AST. */
128 isl_ast_node *tree;
130 /* tile, grid and block sizes for each kernel */
131 isl_union_map *sizes;
133 /* Identifier of current kernel. */
134 int kernel_id;
135 /* Pointer to the current kernel. */
136 struct ppcg_kernel *kernel;
137 /* Does the computed schedule exhibit any parallelism? */
138 int any_parallelism;
140 /* First tile dimension. */
141 int tile_first;
142 /* Number of tile dimensions. */
143 int tile_len;
144 /* Number of initial parallel loops among tile dimensions. */
145 int n_parallel;
147 /* Number of dimensions determining shared memory. */
148 int shared_len;
150 /* Number of rows in the untiled schedule. */
151 int untiled_len;
152 /* Number of rows in the tiled schedule. */
153 int tiled_len;
154 /* Number of rows in schedule after tiling/wrapping over threads. */
155 int thread_tiled_len;
157 /* Global untiled schedule. */
158 isl_union_map *sched;
159 /* Local (per kernel launch) tiled schedule. */
160 isl_union_map *tiled_sched;
161 /* Local schedule per shared memory tile loop iteration. */
162 isl_union_map *local_sched;
164 /* Local tiled schedule projected onto the shared tile loops and
165 * the loops that will be wrapped over the threads,
166 * with all shared tile loops parametrized.
168 isl_union_map *shared_sched;
169 /* Projects out the loops that will be wrapped over the threads
170 * from shared_sched.
172 isl_union_map *shared_proj;
174 /* A map that takes the range of shared_sched as input,
175 * wraps the appropriate loops over the threads and then projects
176 * out these loops.
178 isl_map *privatization;
180 /* A map from the shared memory tile loops and the thread indices
181 * (as parameters) to the set of accessed memory elements that
182 * will be accessed through private copies.
184 isl_union_map *private_access;
186 /* The schedule for the current private/shared access
187 * (within print_private_access or print_shared_access).
189 isl_map *copy_sched;
190 /* The array reference group corresponding to copy_sched. */
191 struct gpu_array_ref_group *copy_group;
193 /* First loop to unroll (or -1 if none) in the current part of the
194 * schedule.
196 int first_unroll;
198 int n_grid;
199 int n_block;
200 /* Note: in the input file, the sizes of the grid and the blocks
201 * are specified in the order x, y, z, but internally, the sizes
202 * are stored in reverse order, so that the last element always
203 * refers to the x dimension.
205 int grid_dim[2];
206 int block_dim[3];
207 int *tile_size;
210 /* Print the name of the local copy of a given group of array references.
212 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
213 struct gpu_array_ref_group *group)
215 int global = 0;
217 if (group->private_tile)
218 p = isl_printer_print_str(p, "private_");
219 else if (group->shared_tile)
220 p = isl_printer_print_str(p, "shared_");
221 else
222 global = 1;
223 p = isl_printer_print_str(p, group->array->name);
224 if (!global && group->array->n_group > 1) {
225 p = isl_printer_print_str(p, "_");
226 p = isl_printer_print_int(p, group->nr);
229 return p;
232 /* Collect all references to the given array and store pointers to them
233 * in array->refs.
235 static void collect_references(struct gpu_prog *prog,
236 struct gpu_array_info *array)
238 int i;
239 int n;
241 n = 0;
242 for (i = 0; i < prog->n_stmts; ++i) {
243 struct gpu_stmt *stmt = &prog->stmts[i];
244 struct gpu_stmt_access *access;
246 for (access = stmt->accesses; access; access = access->next) {
247 const char *name;
248 name = isl_map_get_tuple_name(access->access,
249 isl_dim_out);
250 if (name && !strcmp(array->name, name))
251 n++;
255 array->n_ref = n;
256 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
257 assert(array->refs);
259 n = 0;
260 for (i = 0; i < prog->n_stmts; ++i) {
261 struct gpu_stmt *stmt = &prog->stmts[i];
262 struct gpu_stmt_access *access;
264 for (access = stmt->accesses; access; access = access->next) {
265 const char *name;
266 name = isl_map_get_tuple_name(access->access,
267 isl_dim_out);
268 if (!name || strcmp(array->name, name))
269 continue;
271 array->refs[n++] = access;
276 /* Create a gpu_array_tile for an array of dimension "n_index".
278 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
280 int i;
281 struct gpu_array_tile *tile;
283 tile = isl_calloc_type(ctx, struct gpu_array_tile);
284 assert(tile);
286 tile->n = n_index;
288 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
289 assert(tile->bound);
291 for (i = 0; i < n_index; ++i) {
292 tile->bound[i].size = NULL;
293 tile->bound[i].lb = NULL;
294 tile->bound[i].stride = NULL;
295 tile->bound[i].shift = NULL;
296 tile->bound[i].shift_map = NULL;
299 return tile;
302 static void *free_tile(struct gpu_array_tile *tile)
304 int j;
306 if (!tile)
307 return NULL;
309 for (j = 0; j < tile->n; ++j) {
310 isl_val_free(tile->bound[j].size);
311 isl_val_free(tile->bound[j].stride);
312 isl_aff_free(tile->bound[j].lb);
313 isl_aff_free(tile->bound[j].shift);
314 isl_basic_map_free(tile->bound[j].shift_map);
316 free(tile->bound);
317 isl_multi_aff_free(tile->tiling);
318 free(tile);
320 return NULL;
323 static struct pet_array *find_array(struct ppcg_scop *scop,
324 __isl_keep isl_set *accessed)
326 int i;
327 isl_id *id;
329 id = isl_set_get_tuple_id(accessed);
331 for (i = 0; i < scop->n_array; ++i) {
332 isl_id *id_i;
334 id_i = isl_set_get_tuple_id(scop->arrays[i]->extent);
335 isl_id_free(id_i);
336 if (id == id_i)
337 break;
339 isl_id_free(id);
341 return i < scop->n_array ? scop->arrays[i] : NULL;
344 /* Compute and return the extent of "array", taking into account the set of
345 * accessed elements.
347 * In particular, the extent in the outer dimension is taken
348 * from "accessed", while then extent in the remaing dimensions
349 * are taken from array->extent.
351 * The extent in the outer dimension cannot be taken from array->extent
352 * because that may be unbounded. Furthermore, even if it is bounded,
353 * it may be larger than the piece of the array that is being accessed.
355 static __isl_give isl_set *compute_extent(struct pet_array *array,
356 __isl_keep isl_set *accessed)
358 int n_index;
359 isl_id *id;
360 isl_set *outer;
361 isl_set *extent;
363 extent = isl_set_copy(array->extent);
365 n_index = isl_set_dim(accessed, isl_dim_set);
366 if (n_index == 0)
367 return extent;
369 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
370 outer = isl_set_copy(accessed);
371 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
372 extent = isl_set_flat_product(outer, extent);
373 id = isl_set_get_tuple_id(accessed);
374 extent = isl_set_set_tuple_id(extent, id);
376 return extent;
379 /* Compute bounds on the host arrays based on the accessed elements
380 * and collect all references to the array.
382 * If the array is zero-dimensional, i.e., a scalar, we check
383 * whether it is read-only.
385 static int extract_array_info(__isl_take isl_set *array, void *user)
387 int i;
388 struct gpu_prog *prog = (struct gpu_prog *)user;
389 const char *name;
390 int n_index;
391 isl_pw_aff **bounds;
392 struct pet_array *pa;
393 isl_set *extent;
395 n_index = isl_set_dim(array, isl_dim_set);
396 name = isl_set_get_tuple_name(array);
397 bounds = isl_alloc_array(isl_set_get_ctx(array),
398 isl_pw_aff *, n_index);
399 assert(bounds);
400 prog->array[prog->n_array].dim = isl_set_get_space(array);
401 prog->array[prog->n_array].name = strdup(name);
402 prog->array[prog->n_array].n_index = n_index;
403 prog->array[prog->n_array].bound = bounds;
405 pa = find_array(prog->scop, array);
406 assert(pa);
408 prog->array[prog->n_array].type = strdup(pa->element_type);
409 prog->array[prog->n_array].size = pa->element_size;
410 prog->array[prog->n_array].local = pa->declared && !pa->exposed;
412 if (n_index == 0) {
413 isl_set *space;
414 isl_union_map *write;
415 int empty;
417 write = isl_union_map_copy(prog->write);
418 space = isl_set_universe(isl_set_get_space(array));
419 write = isl_union_map_intersect_range(write,
420 isl_union_set_from_set(space));
421 empty = isl_union_map_is_empty(write);
422 isl_union_map_free(write);
424 prog->array[prog->n_array].read_only = empty;
427 extent = compute_extent(pa, array);
428 for (i = 0; i < n_index; ++i) {
429 isl_set *dom;
430 isl_local_space *ls;
431 isl_aff *one;
432 isl_pw_aff *bound;
434 bound = isl_set_dim_max(isl_set_copy(extent), i);
435 assert(bound);
436 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
437 ls = isl_local_space_from_space(isl_set_get_space(dom));
438 one = isl_aff_zero_on_domain(ls);
439 one = isl_aff_add_constant_si(one, 1);
440 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
441 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
443 bounds[i] = bound;
445 prog->array[prog->n_array].extent = extent;
447 collect_references(prog, &prog->array[prog->n_array]);
449 prog->n_array++;
451 isl_set_free(array);
452 return 0;
455 void collect_array_info(struct gpu_prog *prog)
457 isl_union_set *arrays;
459 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
460 arrays = isl_union_set_union(arrays,
461 isl_union_map_range(isl_union_map_copy(prog->write)));
462 arrays = isl_union_set_coalesce(arrays);
464 prog->n_array = isl_union_set_n_set(arrays);
465 prog->array = isl_alloc_array(prog->ctx,
466 struct gpu_array_info, prog->n_array);
467 assert(prog->array);
468 prog->n_array = 0;
469 isl_union_set_foreach_set(arrays, &extract_array_info, prog);
470 isl_union_set_free(arrays);
473 static void free_array_info(struct gpu_prog *prog)
475 int i, j;
477 for (i = 0; i < prog->n_array; ++i) {
478 int n_index = prog->array[i].n_index;
479 free(prog->array[i].type);
480 free(prog->array[i].name);
481 for (j = 0; j < n_index; ++j)
482 isl_pw_aff_free(prog->array[i].bound[j]);
483 isl_space_free(prog->array[i].dim);
484 isl_set_free(prog->array[i].extent);
485 free(prog->array[i].bound);
486 free(prog->array[i].refs);
488 free(prog->array);
491 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
492 * as an array or through a pointer reference, but as single data element. At
493 * the moment, scalars are represented as zero dimensional arrays.
495 int gpu_array_is_scalar(struct gpu_array_info *array)
497 return (array->n_index == 0);
500 /* Is "array" a read-only scalar?
502 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
504 return gpu_array_is_scalar(array) && array->read_only;
507 /* Internal data structure for extract_size_of_type.
508 * "type" specifies the name of the space that we want to extract.
509 * "res" is used to store the subset of that space.
511 struct ppcg_extract_size_data {
512 const char *type;
513 isl_set *res;
516 /* This function is called for each set in a union_set.
517 * If the name of the set matches data->type, we store the
518 * set in data->res.
520 static int extract_size_of_type(__isl_take isl_set *size, void *user)
522 struct ppcg_extract_size_data *data = user;
523 const char *name;
525 name = isl_set_get_tuple_name(size);
526 if (name && !strcmp(name, data->type)) {
527 data->res = size;
528 return -1;
531 isl_set_free(size);
532 return 0;
535 /* Given a union map { kernel[i] -> *[...] },
536 * return the range in the space called "type" for the kernel with
537 * sequence number "id".
539 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
540 const char *type, int id)
542 isl_space *space;
543 isl_set *dom;
544 isl_union_set *local_sizes;
545 struct ppcg_extract_size_data data = { type, NULL };
547 if (!sizes)
548 return NULL;
550 space = isl_union_map_get_space(sizes);
551 space = isl_space_set_from_params(space);
552 space = isl_space_add_dims(space, isl_dim_set, 1);
553 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
554 dom = isl_set_universe(space);
555 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
557 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
558 isl_union_map_copy(sizes));
559 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
560 isl_union_set_free(local_sizes);
561 return data.res;
564 /* Given a singleton set, extract the first (at most *len) elements
565 * of the single integer tuple into *sizes and update *len if needed.
567 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
569 int i;
570 int dim;
572 if (!set)
573 return;
575 dim = isl_set_dim(set, isl_dim_set);
576 if (dim < *len)
577 *len = dim;
579 for (i = 0; i < *len; ++i) {
580 isl_val *v;
582 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
583 assert(v);
585 sizes[i] = isl_val_get_num_si(v);
586 isl_val_free(v);
589 isl_set_free(set);
592 /* Extract user specified "tile" sizes from the "sizes" command line option,
593 * defaulting to option->tile_size in each dimension.
595 static void read_tile_sizes(struct gpu_gen *gen)
597 int n;
598 isl_set *size;
600 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
601 assert(gen->tile_size);
602 for (n = 0; n < gen->tile_len; ++n)
603 gen->tile_size[n] = gen->options->tile_size;
605 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
606 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
608 if (gen->n_parallel > gen->tile_len)
609 gen->n_parallel = gen->tile_len;
612 /* Extract user specified "block" sizes from the "sizes" command line option,
613 * after filling in some potentially useful defaults.
615 static void read_block_sizes(struct gpu_gen *gen)
617 int n;
618 isl_set *size;
620 n = gen->n_parallel;
621 gen->n_block = (n <= 3) ? n : 3;
622 switch (gen->n_block) {
623 case 1:
624 gen->block_dim[0] = 512;
625 break;
626 case 2:
627 gen->block_dim[0] = 32;
628 gen->block_dim[1] = 16;
629 break;
630 default:
631 gen->block_dim[0] = 32;
632 gen->block_dim[1] = 4;
633 gen->block_dim[2] = 4;
634 break;
637 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
638 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
641 /* Extract user specified "grid" sizes from the "sizes" command line option,
642 * after filling in some potentially useful defaults.
644 static void read_grid_sizes(struct gpu_gen *gen)
646 int n = gen->n_parallel;
647 isl_set *size;
649 gen->n_grid = (n <= 2) ? n : 2;
650 switch (gen->n_grid) {
651 case 1:
652 gen->grid_dim[0] = 32768;
653 break;
654 default:
655 gen->grid_dim[0] = 256;
656 gen->grid_dim[1] = 256;
657 break;
660 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
661 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
664 /* Extract user specified sizes from the "sizes" command line option
665 * after filling in some potentially useful defaults.
667 static void read_sizes(struct gpu_gen *gen)
669 read_tile_sizes(gen);
670 read_block_sizes(gen);
671 read_grid_sizes(gen);
674 static void *free_stmts(struct gpu_stmt *stmts, int n)
676 int i;
678 if (!stmts)
679 return NULL;
681 for (i = 0; i < n; ++i) {
682 struct gpu_stmt_access *access, *next;
684 for (access = stmts[i].accesses; access; access = next) {
685 next = access->next;
686 isl_id_free(access->ref_id);
687 isl_map_free(access->access);
688 free(access);
691 isl_id_free(stmts[i].id);
693 free(stmts);
695 return NULL;
698 void clear_gpu_gen(struct gpu_gen *gen)
700 isl_union_map_free(gen->sizes);
701 isl_union_map_free(gen->sched);
704 /* Construct a map from a domain of dimensionality "len"
705 * to a domain of dimensionality "len" + "tile_len" that tiles
706 * the "tile_len" coordinates starting at "first".
707 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
708 * "dim" prescribes the parameters.
710 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
711 int first, int tile_len, int *tile_size)
713 int i;
714 isl_basic_map *bmap;
715 isl_constraint *c;
716 isl_local_space *ls;
718 dim = isl_space_add_dims(dim, isl_dim_in, len);
719 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
720 bmap = isl_basic_map_universe(isl_space_copy(dim));
721 ls = isl_local_space_from_space(dim);
723 for (i = 0; i < len - tile_len; ++i) {
724 int j = i < first ? i : i + tile_len;
725 int k = i < first ? i : i + 2 * tile_len;
727 c = isl_equality_alloc(isl_local_space_copy(ls));
728 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
729 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
730 bmap = isl_basic_map_add_constraint(bmap, c);
733 for (i = 0; i < tile_len; ++i) {
734 c = isl_equality_alloc(isl_local_space_copy(ls));
735 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
736 first + i, -1);
737 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
738 first + i, tile_size[i]);
739 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
740 first + i + tile_len, 1);
741 bmap = isl_basic_map_add_constraint(bmap, c);
743 c = isl_inequality_alloc(isl_local_space_copy(ls));
744 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
745 first + i + tile_len, 1);
746 bmap = isl_basic_map_add_constraint(bmap, c);
748 c = isl_inequality_alloc(isl_local_space_copy(ls));
749 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
750 first + i + tile_len, -1);
751 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
752 bmap = isl_basic_map_add_constraint(bmap, c);
755 isl_local_space_free(ls);
757 return isl_map_from_basic_map(bmap);
760 /* Construct a map from a domain of dimensionality "len"
761 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
762 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
763 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
764 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
765 * that are projected out at the end.
766 * "dim" prescribes the parameters.
768 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
769 int first, int wrap_len, int *wrap_size)
771 int i;
772 isl_basic_map *bmap;
773 isl_constraint *c;
774 isl_local_space *ls;
776 dim = isl_space_add_dims(dim, isl_dim_in, len);
777 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
778 bmap = isl_basic_map_universe(isl_space_copy(dim));
779 ls = isl_local_space_from_space(dim);
781 for (i = 0; i < len; ++i) {
782 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
784 c = isl_equality_alloc(isl_local_space_copy(ls));
785 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
786 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
787 bmap = isl_basic_map_add_constraint(bmap, c);
790 for (i = 0; i < wrap_len; ++i) {
791 c = isl_equality_alloc(isl_local_space_copy(ls));
792 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
793 first + i, -1);
794 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
795 first + wrap_len + i, 1);
796 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
797 first + 2 * wrap_len + i, wrap_size[i]);
798 bmap = isl_basic_map_add_constraint(bmap, c);
800 c = isl_inequality_alloc(isl_local_space_copy(ls));
801 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
802 first + wrap_len + i, 1);
803 bmap = isl_basic_map_add_constraint(bmap, c);
805 c = isl_inequality_alloc(isl_local_space_copy(ls));
806 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
807 first + wrap_len + i, -1);
808 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
809 bmap = isl_basic_map_add_constraint(bmap, c);
812 isl_local_space_free(ls);
814 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
815 first + 2 * wrap_len, wrap_len);
817 return isl_map_from_basic_map(bmap);
820 /* Add "n" parameters named prefix%d.
822 static __isl_give isl_set *add_params( __isl_take isl_set *set,
823 int n, const char *prefix)
825 int i;
826 unsigned nparam;
827 char name[20];
829 nparam = isl_set_dim(set, isl_dim_param);
830 set = isl_set_add_dims(set, isl_dim_param, n);
832 for (i = 0; i < n; ++i) {
833 snprintf(name, sizeof(name), "%s%d", prefix, i);
834 set = isl_set_set_dim_name(set, isl_dim_param,
835 nparam + i, name);
838 return set;
841 /* Equate the "n" dimensions of "set" starting at "first" to
842 * freshly created parameters named prefix%d.
844 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
845 int first, int n, const char *prefix)
847 int i;
848 unsigned nparam;
850 nparam = isl_set_dim(set, isl_dim_param);
852 set = add_params(set, n, prefix);
854 for (i = 0; i < n; ++i)
855 set = isl_set_equate(set, isl_dim_param, nparam + i,
856 isl_dim_set, first + i);
858 return set;
861 /* Given a parameter space "space", create a set of dimension "len"
862 * of which the "n" dimensions starting at "first" are equated to
863 * freshly created parameters named prefix%d.
865 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
866 int len, int first, int n, const char *prefix)
868 isl_set *set;
870 space = isl_space_set_from_params(space);
871 space = isl_space_add_dims(space, isl_dim_set, len);
872 set = isl_set_universe(space);
874 return parametrize(set, first, n, prefix);
877 /* Tile the B loops over the tile sizes and then tile/wrap
878 * the T1 loops over the blocks.
880 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
881 __isl_take isl_union_map *sched)
883 isl_space *dim;
884 isl_map *tiling, *block_tiling;
886 dim = isl_union_map_get_space(sched);
887 tiling = tile(isl_space_copy(dim), gen->untiled_len,
888 gen->tile_first, gen->tile_len, gen->tile_size);
890 if (gen->options->wrap)
891 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
892 gen->tile_first, gen->n_grid, gen->grid_dim);
893 else
894 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
895 gen->tile_first, gen->n_grid, gen->grid_dim);
897 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
899 tiling = isl_map_apply_range(tiling, block_tiling);
901 sched = isl_union_map_apply_range(sched,
902 isl_union_map_from_map(tiling));
904 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
906 return sched;
909 /* Equate the "T1P" iterators in the tiled schedule "sched"
910 * to the block dimensions.
912 static __isl_give isl_union_map *parametrize_tiled_schedule(
913 struct gpu_gen *gen, __isl_take isl_union_map *sched)
915 isl_space *dim;
916 isl_set *par;
918 dim = isl_union_map_get_space(sched);
919 par = parametrization(dim, gen->tiled_len,
920 gen->tile_first + gen->n_grid, gen->n_grid, "b");
921 sched = isl_union_map_intersect_range(sched,
922 isl_union_set_from_set(par));
924 return sched;
927 /* Tile/wrap the P1 loops over the threads.
929 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
930 __isl_take isl_union_map *sched)
932 isl_space *dim;
933 isl_map *tiling;
934 isl_set *par;
936 dim = isl_union_map_get_space(sched);
938 if (gen->options->wrap)
939 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
940 gen->shared_len, gen->n_block, gen->block_dim);
941 else
942 tiling = tile(isl_space_copy(dim), gen->tiled_len,
943 gen->shared_len, gen->n_block, gen->block_dim);
944 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
946 sched = isl_union_map_apply_range(sched,
947 isl_union_map_from_map(tiling));
949 par = parametrization(dim, gen->thread_tiled_len,
950 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
951 gen->n_block, "t");
952 sched = isl_union_map_intersect_range(sched,
953 isl_union_set_from_set(par));
955 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
957 return sched;
960 /* If the user asked for it, scale the shared memory tile loops
961 * (T1T and T2) of "sched" by gen->tile_size[i].
962 * If we are not performing "wrapping", then additionally scale the T1P
963 * loops by gen->grid_dim[i].
965 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
966 __isl_take isl_union_map *sched)
968 int i;
969 isl_space *dim;
970 isl_basic_map *scale;
971 isl_constraint *c;
972 isl_local_space *ls;
974 if (!gen->options->scale_tile_loops)
975 return sched;
977 dim = isl_union_map_get_space(sched);
978 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
979 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
980 scale = isl_basic_map_universe(isl_space_copy(dim));
981 ls = isl_local_space_from_space(dim);
983 for (i = 0; i < gen->tiled_len; ++i) {
984 int f = 1;
986 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
987 f = gen->tile_size[i - gen->tile_first];
988 if (!gen->options->wrap)
989 f *= gen->grid_dim[i - gen->tile_first];
990 } else if (i >= gen->tile_first + gen->n_grid &&
991 i < gen->tile_first + gen->n_grid + gen->tile_len) {
992 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
995 c = isl_equality_alloc(isl_local_space_copy(ls));
996 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
997 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
998 scale = isl_basic_map_add_constraint(scale, c);
1001 isl_local_space_free(ls);
1003 sched = isl_union_map_apply_range(sched,
1004 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1006 return sched;
1009 /* If we are not performing "wrapping" and if the user asked for it,
1010 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1012 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1013 __isl_take isl_union_map *sched)
1015 int i;
1016 isl_space *dim;
1017 isl_basic_map *scale;
1018 isl_constraint *c;
1019 isl_local_space *ls;
1021 if (gen->options->wrap)
1022 return sched;
1023 if (!gen->options->scale_tile_loops)
1024 return sched;
1026 dim = isl_union_map_get_space(sched);
1027 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1028 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1029 scale = isl_basic_map_universe(isl_space_copy(dim));
1030 ls = isl_local_space_from_space(dim);
1032 for (i = 0; i < gen->thread_tiled_len; ++i) {
1033 int f = 1;
1035 if (i >= gen->shared_len &&
1036 i < gen->shared_len + gen->n_block)
1037 f = gen->block_dim[i - gen->shared_len];
1039 c = isl_equality_alloc(isl_local_space_copy(ls));
1040 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1041 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1042 scale = isl_basic_map_add_constraint(scale, c);
1045 isl_local_space_free(ls);
1047 sched = isl_union_map_apply_range(sched,
1048 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1050 return sched;
1053 /* If we are not performing "wrapping" and if the user asked for it,
1054 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1056 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1057 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1059 int i;
1060 isl_space *dim;
1061 isl_basic_map *scale;
1062 isl_constraint *c;
1063 isl_local_space *ls;
1065 if (gen->options->wrap)
1066 return sched;
1067 if (!gen->options->scale_tile_loops)
1068 return sched;
1070 dim = isl_union_map_get_space(sched);
1071 dim = isl_space_add_dims(dim, isl_dim_in, len);
1072 dim = isl_space_add_dims(dim, isl_dim_out, len);
1073 scale = isl_basic_map_universe(isl_space_copy(dim));
1074 ls = isl_local_space_from_space(dim);
1076 for (i = 0; i < len; ++i) {
1077 int f = 1;
1079 if (i >= first && i < first + n_tile)
1080 f = gen->kernel->block_dim[i - first];
1082 c = isl_equality_alloc(isl_local_space_copy(ls));
1083 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1084 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1085 scale = isl_basic_map_add_constraint(scale, c);
1088 isl_local_space_free(ls);
1090 sched = isl_union_map_apply_range(sched,
1091 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1093 return sched;
1096 /* Add "len" parameters p[i] called prefix%d,
1097 * with bounds to 0 <= p[i] < size[i].
1099 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1100 int len, int *size, const char *prefix)
1102 int i;
1103 unsigned nparam;
1104 isl_space *dim;
1105 isl_basic_set *bset;
1106 isl_constraint *c;
1107 isl_local_space *ls;
1108 char name[20];
1110 nparam = isl_set_dim(set, isl_dim_param);
1111 set = isl_set_add_dims(set, isl_dim_param, len);
1113 for (i = 0; i < len; ++i) {
1114 snprintf(name, sizeof(name), "%s%d", prefix, i);
1115 set = isl_set_set_dim_name(set, isl_dim_param,
1116 nparam + i, name);
1119 dim = isl_set_get_space(set);
1120 bset = isl_basic_set_universe(isl_space_copy(dim));
1121 ls = isl_local_space_from_space(dim);
1123 for (i = 0; i < len; ++i) {
1124 c = isl_inequality_alloc(isl_local_space_copy(ls));
1125 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1126 nparam + i, 1);
1127 bset = isl_basic_set_add_constraint(bset, c);
1129 c = isl_inequality_alloc(isl_local_space_copy(ls));
1130 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1131 nparam + i, -1);
1132 c = isl_constraint_set_constant_si(c, size[i] - 1);
1133 bset = isl_basic_set_add_constraint(bset, c);
1136 isl_local_space_free(ls);
1138 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1141 /* Add "len" parameters p[i] called prefix%d,
1142 * with bounds to 0 <= p[i] < size[i].
1144 static __isl_give isl_set *add_bounded_parameters_dynamic(
1145 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1146 const char *prefix)
1148 int i, len;
1149 unsigned nparam;
1150 isl_space *space;
1151 isl_local_space *ls;
1152 char name[20];
1154 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1155 nparam = isl_set_dim(set, isl_dim_param);
1156 set = isl_set_add_dims(set, isl_dim_param, len);
1158 for (i = 0; i < len; ++i) {
1159 snprintf(name, sizeof(name), "%s%d", prefix, i);
1160 set = isl_set_set_dim_name(set, isl_dim_param,
1161 nparam + i, name);
1164 space = isl_space_params(isl_set_get_space(set));
1165 ls = isl_local_space_from_space(space);
1166 for (i = 0; i < len; ++i) {
1167 isl_pw_aff *param, *size_i, *zero;
1168 isl_set *bound;
1170 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1171 isl_dim_param, nparam + i);
1173 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1174 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1175 set = isl_set_intersect_params(set, bound);
1177 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1178 bound = isl_pw_aff_ge_set(param, zero);
1179 set = isl_set_intersect_params(set, bound);
1181 isl_local_space_free(ls);
1183 return set;
1186 /* Construct a map from an access to group->array to the corresponding
1187 * shared/private memory tile.
1188 * The map is of the form
1190 * { [D[i] -> A[a]] -> T[t] }
1192 * where D represents the initial shared_len dimensions
1193 * of the computed schedule.
1195 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1197 struct gpu_array_tile *tile;
1198 isl_multi_aff *tiling;
1200 tile = group->private_tile;
1201 if (!tile)
1202 tile = group->shared_tile;
1204 tiling = isl_multi_aff_copy(tile->tiling);
1206 return isl_map_from_multi_aff(tiling);
1209 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1211 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1212 unsigned pos)
1214 isl_val *v;
1215 int fixed;
1217 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1218 if (!v)
1219 return -1;
1220 fixed = isl_val_is_int(v);
1221 isl_val_free(v);
1223 return fixed;
1226 /* Given a schedule that iterates over all elements in a piece of an array,
1227 * perform tiling/wrapping over the threads.
1229 * In particular, we tile the final iterators so that the final thread
1230 * dimension runs over the final array dimension.
1231 * However, if those final iterators have only a single iteration,
1232 * we try to tile earlier iterators instead.
1234 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1235 __isl_take isl_map *sched)
1237 isl_space *dim;
1238 isl_union_map *usched;
1239 isl_map *tiling;
1240 isl_set *par;
1241 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1242 int n_tile;
1243 int first;
1245 n_tile = gen->kernel->n_block;
1246 if (n_tile > nvar) {
1247 int i;
1248 sched = isl_map_insert_dims(sched,
1249 isl_dim_out, 0, n_tile - nvar);
1250 for (i = 0; i < n_tile - nvar; ++i)
1251 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1252 nvar = n_tile;
1255 first = nvar - n_tile;
1257 for (; first > 0; first --)
1258 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1259 break;
1261 dim = isl_map_get_space(sched);
1262 dim = isl_space_params(dim);
1263 if (gen->options->wrap)
1264 tiling = wrap(isl_space_copy(dim), nvar, first,
1265 n_tile, gen->kernel->block_dim);
1266 else
1267 tiling = tile(isl_space_copy(dim), nvar, first,
1268 n_tile, gen->kernel->block_dim);
1269 sched = isl_map_apply_range(sched, tiling);
1271 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1272 sched = isl_map_intersect_range(sched, par);
1274 usched = isl_union_map_from_map(sched);
1275 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1276 first, n_tile);
1277 sched = isl_map_from_union_map(usched);
1279 return sched;
1282 /* Given an index expression "pa" into a tile of an array, adjust the expression
1283 * to a shift of the tile to the origin
1284 * (based on the lower bounds in "bound".
1285 * If the index is strided, then we first add
1286 * bound->shift and divide by bound->stride.
1287 * In the end, we compute the gist with respect to "domain".
1289 * All of the input expression "pa", the set "domain" and
1290 * the output are expressed in terms of the AST schedule domain.
1291 * The expressions in "bound" are expressed
1292 * in terms of the first shared_len dimensions of the schedule computed by PPCG.
1293 * The mapping "sched2shared" maps the former domain to the latter domain.
1295 static __isl_give isl_pw_aff *shift_index(__isl_take isl_pw_aff *pa,
1296 struct gpu_array_info *array,
1297 struct gpu_array_bound *bound, __isl_take isl_set *domain,
1298 __isl_take isl_map *sched2shared)
1300 isl_map *map;
1301 isl_pw_aff *tmp;
1302 isl_pw_multi_aff *pma;
1304 if (bound->shift) {
1305 map = isl_map_from_aff(isl_aff_copy(bound->shift));
1306 map = isl_map_apply_range(isl_map_copy(sched2shared), map);
1307 pma = isl_pw_multi_aff_from_map(map);
1308 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1309 isl_pw_multi_aff_free(pma);
1310 pa = isl_pw_aff_add(pa, tmp);
1311 pa = isl_pw_aff_scale_down_val(pa, isl_val_copy(bound->stride));
1315 map = isl_map_from_aff(isl_aff_copy(bound->lb));
1316 map = isl_map_apply_range(sched2shared, map);
1317 pma = isl_pw_multi_aff_from_map(map);
1318 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1319 isl_pw_multi_aff_free(pma);
1320 pa = isl_pw_aff_sub(pa, tmp);
1321 pa = isl_pw_aff_coalesce(pa);
1322 pa = isl_pw_aff_gist(pa, domain);
1324 return pa;
1327 /* Return the union of all read (read = 1) and/or write (write = 1)
1328 * access relations in the group.
1330 static __isl_give isl_union_map *group_access_relation(
1331 struct gpu_array_ref_group *group, int read, int write)
1333 int i;
1334 isl_union_map *access;
1336 access = isl_union_map_empty(isl_map_get_space(group->access));
1337 for (i = 0; i < group->n_ref; ++i) {
1338 isl_map *map_i;
1340 if (!((read && group->refs[i]->read) ||
1341 (write && group->refs[i]->write)))
1342 continue;
1343 map_i = isl_map_copy(group->refs[i]->access);
1344 access = isl_union_map_union(access,
1345 isl_union_map_from_map(map_i));
1348 return access;
1351 /* Return the extent of "array", recomputed from the bounds.
1352 * The recomputed extent may be simpler than the original extent.
1354 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1356 int i;
1357 isl_id *id;
1358 isl_space *space;
1359 isl_local_space *ls;
1360 isl_set *extent;
1362 id = isl_set_get_tuple_id(array->extent);
1363 space = isl_set_get_space(array->extent);
1364 extent = isl_set_universe(isl_space_copy(space));
1365 ls = isl_local_space_from_space(space);
1366 for (i = 0; i < array->n_index; ++i) {
1367 isl_pw_aff *bound;
1368 isl_aff *aff;
1369 isl_pw_aff *index;
1370 isl_set *lt;
1372 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1374 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1375 isl_dim_set, i);
1376 index = isl_pw_aff_from_aff(aff);
1377 bound = isl_pw_aff_copy(array->bound[i]);
1378 bound = isl_pw_aff_from_range(bound);
1379 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1380 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1381 isl_id_copy(id));
1382 lt = isl_pw_aff_lt_set(index, bound);
1383 extent = isl_set_intersect(extent, lt);
1385 isl_local_space_free(ls);
1386 isl_id_free(id);
1388 return extent;
1391 /* Return a map from the first shared_len dimensions of the computed
1392 * schedule to the array tile in
1393 * global memory that corresponds to the shared memory copy.
1395 * In particular, return a map
1397 * { D[i] -> A[a] }
1399 * with constraints
1401 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1403 * and
1405 * 0 <= a <= array_size - 1 (2)
1407 * Note that if some stride has been detected (i.e., when
1408 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1409 * to the shifted and scaled down version.
1411 * Constraints (1) are obtained by mapping the size constraints on the
1412 * shared/private memory tile back to the access relation.
1413 * Constraints (2) are obtained from the (recomputed) extent.
1415 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1417 int i;
1418 int n_index = group->array->n_index;
1419 isl_map *tile;
1420 isl_space *space;
1421 isl_set *local;
1422 isl_set *extent;
1424 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1425 space = isl_space_range(space);
1426 local = isl_set_universe(space);
1427 for (i = 0; i < n_index; ++i) {
1428 isl_val *bound;
1430 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1431 bound = isl_val_copy(group->shared_tile->bound[i].size);
1432 bound = isl_val_sub_ui(bound, 1);
1433 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1435 local = isl_set_preimage_multi_aff(local,
1436 isl_multi_aff_copy(group->shared_tile->tiling));
1437 tile = isl_set_unwrap(local);
1438 extent = array_extent(group->array);
1439 tile = isl_map_intersect_range(tile, extent);
1441 return tile;
1444 /* Given a mapping "sched" from the AST schedule to a domain,
1445 * return the corresponding mapping from the AST schedule to
1446 * to the first shared_len dimensions of the schedule computed by PPCG.
1448 static __isl_give isl_map *compute_sched_to_shared(struct gpu_gen *gen,
1449 __isl_take isl_map *sched)
1451 isl_union_map *umap;
1452 isl_space *space;
1453 isl_map *map;
1455 space = isl_space_range(isl_map_get_space(sched));
1456 space = isl_space_from_domain(space);
1457 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1459 umap = isl_union_map_copy(gen->shared_sched);
1460 umap = isl_union_map_apply_range(umap,
1461 isl_union_map_copy(gen->shared_proj));
1462 map = isl_union_map_extract_map(umap, space);
1463 isl_union_map_free(umap);
1465 sched = isl_map_apply_range(sched, map);
1466 sched = isl_map_detect_equalities(sched);
1468 return sched;
1471 /* Set unroll[j] if the input dimension j is involved in
1472 * the index expression represented by ma.
1474 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1475 void *user)
1477 int i, j;
1478 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1479 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1480 int *unroll = user;
1482 for (i = 0; i < n_out; ++i) {
1483 isl_aff *aff;
1485 aff = isl_multi_aff_get_aff(ma, i);
1486 for (j = 0; j < n_in; ++j)
1487 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1488 unroll[j] = 1;
1489 isl_aff_free(aff);
1492 isl_set_free(set);
1493 isl_multi_aff_free(ma);
1494 return 0;
1497 /* Given an array pos mapping input dimensions to the corresponding
1498 * output dimension, construct the corresponding map.
1500 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1501 int *pos, int len)
1503 int i;
1504 isl_constraint *c;
1505 isl_basic_map *bmap;
1506 isl_local_space *ls;
1508 dim = isl_space_add_dims(dim, isl_dim_in, len);
1509 dim = isl_space_add_dims(dim, isl_dim_out, len);
1510 bmap = isl_basic_map_universe(isl_space_copy(dim));
1511 ls = isl_local_space_from_space(dim);
1513 for (i = 0; i < len; ++i) {
1514 c = isl_equality_alloc(isl_local_space_copy(ls));
1515 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1516 -1);
1517 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1519 bmap = isl_basic_map_add_constraint(bmap, c);
1521 isl_local_space_free(ls);
1523 return isl_map_from_basic_map(bmap);
1526 /* Find all loops involved in any of the index expressions for any of
1527 * the private accesses, move them innermost and then mark them as
1528 * requiring unrolling by setting gen->first_unroll.
1529 * The loops involved should all be parallel because of the checks
1530 * we performed in check_private_group_access. Moving them innermost
1531 * is therefore a valid transformation.
1533 * Loops up to gen->shared_len are generated before the mapping to
1534 * threads is applied. They should therefore be ignored.
1536 * We compute the hidden equalities of the schedule first
1537 * since we will need them in our calls to isl_pw_multi_aff_from_map
1538 * and because we want to make sure that the same equalities
1539 * are also available to the code generator.
1541 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1542 __isl_take isl_union_map *sched)
1544 int i, j;
1545 int unroll[gen->thread_tiled_len];
1546 int perm[gen->thread_tiled_len];
1547 isl_space *dim;
1548 isl_map *permute;
1549 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1551 gen->first_unroll = -1;
1553 sched = isl_union_map_detect_equalities(sched);
1554 for (i = 0; i < gen->thread_tiled_len; ++i)
1555 unroll[i] = 0;
1556 for (i = 0; i < gen->prog->n_array; ++i) {
1557 struct gpu_array_info *array = &gen->prog->array[i];
1559 for (j = 0; j < array->n_group; ++j) {
1560 isl_union_map *access;
1561 isl_map *acc;
1562 isl_pw_multi_aff *pma;
1564 if (!array->groups[j]->private_tile)
1565 continue;
1567 access = group_access_relation(array->groups[j], 1, 1);
1568 access = isl_union_map_apply_domain(access,
1569 isl_union_map_copy(sched));
1571 acc = isl_map_from_union_map(access);
1572 pma = isl_pw_multi_aff_from_map(acc);
1573 isl_pw_multi_aff_foreach_piece(pma,
1574 &check_unroll, unroll);
1576 isl_pw_multi_aff_free(pma);
1580 for (i = gen->shared_len; i < len; ++i)
1581 if (unroll[i])
1582 break;
1584 if (i >= len)
1585 return sched;
1587 for (i = len; i < gen->thread_tiled_len; ++i)
1588 if (unroll[i])
1589 return sched;
1591 j = 0;
1592 for (i = 0; i < gen->shared_len; ++i)
1593 perm[i] = j++;
1594 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1595 if (!unroll[i])
1596 perm[i] = j++;
1597 gen->first_unroll = j - gen->shared_len;
1598 for (i = gen->shared_len; i < len; ++i)
1599 if (unroll[i])
1600 perm[i] = j++;
1602 dim = isl_union_map_get_space(sched);
1603 permute = permutation(dim, perm, gen->thread_tiled_len);
1604 sched = isl_union_map_apply_range(sched,
1605 isl_union_map_from_map(permute));
1607 return sched;
1610 /* Given a constraint
1612 * a(p,i) + j = g f(e)
1614 * or -a(p,i) - j = g f(e) if sign < 0,
1615 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1616 * a(p,i) is assumed to be an expression in only the parameters
1617 * and the input dimensions.
1619 static void extract_stride(__isl_keep isl_constraint *c,
1620 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1622 int i;
1623 isl_val *v;
1624 isl_space *space;
1625 unsigned nparam;
1626 unsigned nvar;
1627 isl_aff *aff;
1629 isl_val_free(bound->stride);
1630 bound->stride = isl_val_copy(stride);
1632 space = isl_constraint_get_space(c);
1633 space = isl_space_domain(space);
1635 nparam = isl_space_dim(space, isl_dim_param);
1636 nvar = isl_space_dim(space, isl_dim_set);
1638 v = isl_constraint_get_constant_val(c);
1639 if (sign < 0)
1640 v = isl_val_neg(v);
1641 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1642 aff = isl_aff_set_constant_val(aff, v);
1644 for (i = 0; i < nparam; ++i) {
1645 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1646 continue;
1647 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1648 if (sign < 0)
1649 v = isl_val_neg(v);
1650 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1653 for (i = 0; i < nvar; ++i) {
1654 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1655 continue;
1656 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1657 if (sign < 0)
1658 v = isl_val_neg(v);
1659 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1662 bound->shift = aff;
1665 /* Given an equality constraint of a map with a single output dimension j,
1666 * check if the constraint is of the form
1668 * a(p,i) + j = g f(e)
1670 * with a(p,i) an expression in the parameters and input dimensions
1671 * and f(e) an expression in the existentially quantified variables.
1672 * If so, and if g is larger than any such g from a previously considered
1673 * constraint, then call extract_stride to record the stride information
1674 * in bound.
1676 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1678 int i;
1679 isl_ctx *ctx;
1680 isl_val *v;
1681 unsigned n_div;
1682 struct gpu_array_bound *bound = user;
1684 ctx = isl_constraint_get_ctx(c);
1685 n_div = isl_constraint_dim(c, isl_dim_div);
1686 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1688 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1689 int s = isl_val_sgn(v);
1690 isl_val *stride = isl_val_zero(ctx);
1692 isl_val_free(v);
1693 for (i = 0; i < n_div; ++i) {
1694 v = isl_constraint_get_coefficient_val(c,
1695 isl_dim_div, i);
1696 stride = isl_val_gcd(stride, v);
1698 if (!isl_val_is_zero(stride) &&
1699 isl_val_gt(stride, bound->stride))
1700 extract_stride(c, bound, stride, s);
1702 isl_val_free(stride);
1703 } else
1704 isl_val_free(v);
1706 isl_constraint_free(c);
1707 return 0;
1710 /* Given contraints on an array index i, check if we can find
1711 * a shift a(p) and a stride g such that
1713 * a(p) + i = 0 mod g
1715 * If so, record the information in bound and apply the mapping
1716 * i -> (i + a(p))/g to the array index in bounds and return
1717 * the new constraints.
1718 * If not, simply return the original constraints.
1720 * If bounds is a subset of the space
1722 * D -> i
1724 * then the bound recorded in bound->shift is of the form
1726 * D -> s(D)
1728 * with s(D) equal to a(p) above.
1729 * The mapping recorded in bound->shift_map is of the form
1731 * [D -> i] -> [D -> (i + S(D))/g]
1733 * This mapping is computed as follows.
1734 * We first introduce "i" in the domain through precomposition
1735 * with [D -> i] -> D obtaining
1737 * [D -> i] -> s(D)
1739 * Adding [D -> i] -> i produces
1741 * [D -> i] -> i + s(D)
1743 * and the domain product with [D -> i] -> D yields
1745 * [D -> i] -> [D -> i + s(D)]
1747 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1749 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1750 __isl_take isl_basic_map *bounds)
1752 isl_space *space;
1753 isl_basic_map *hull;
1754 isl_basic_map *shift, *id, *bmap, *scale;
1755 isl_basic_set *bset;
1756 isl_aff *aff;
1758 bound->stride = NULL;
1760 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1762 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1764 isl_basic_map_free(hull);
1766 if (!bound->stride)
1767 return bounds;
1769 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1770 space = isl_basic_map_get_space(bounds);
1771 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1772 shift = isl_basic_map_apply_range(bmap, shift);
1773 space = isl_basic_map_get_space(bounds);
1774 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1775 shift = isl_basic_map_sum(id, shift);
1776 space = isl_basic_map_get_space(bounds);
1777 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1778 shift = isl_basic_map_range_product(id, shift);
1780 space = isl_space_domain(isl_basic_map_get_space(bounds));
1781 id = isl_basic_map_identity(isl_space_map_from_set(space));
1782 space = isl_space_range(isl_basic_map_get_space(bounds));
1783 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1784 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1785 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
1786 scale = isl_basic_map_from_aff(aff);
1787 scale = isl_basic_map_product(id, scale);
1789 bound->shift_map = isl_basic_map_apply_range(shift, scale);
1790 bmap = isl_basic_map_copy(bound->shift_map);
1791 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1792 bounds = isl_basic_set_unwrap(bset);
1794 return bounds;
1797 /* Data used in compute_array_dim_size and compute_size_in_direction.
1799 * pos is the position of the variable representing the array index,
1800 * i.e., the variable for which want to compute the size. This variable
1801 * is also the last variable in the set.
1803 struct gpu_size_info {
1804 isl_basic_set *bset;
1805 struct gpu_array_bound *bound;
1806 int pos;
1809 /* Given a constraint from the basic set describing the bounds on
1810 * an array index, check if it is a lower bound, say m i >= b(x), and,
1811 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
1812 * upper bound. If so, and if this bound is smaller than any bound
1813 * derived from earlier constraints, set the size to this bound on
1814 * the expression and the lower bound to ceil(b(x)/m).
1816 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
1818 struct gpu_size_info *size = user;
1819 unsigned nparam;
1820 unsigned n_div;
1821 isl_val *v;
1822 isl_aff *aff;
1823 isl_aff *lb;
1825 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
1826 n_div = isl_constraint_dim(c, isl_dim_div);
1828 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
1829 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
1830 isl_constraint_free(c);
1831 return 0;
1834 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
1835 aff = isl_aff_ceil(aff);
1837 lb = isl_aff_copy(aff);
1839 aff = isl_aff_neg(aff);
1840 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
1842 v = isl_basic_set_max_val(size->bset, aff);
1843 isl_aff_free(aff);
1845 if (isl_val_is_int(v)) {
1846 v = isl_val_add_ui(v, 1);
1847 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
1848 isl_val_free(size->bound->size);
1849 size->bound->size = isl_val_copy(v);
1850 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
1851 isl_aff_free(size->bound->lb);
1852 size->bound->lb = isl_aff_copy(lb);
1855 isl_val_free(v);
1856 isl_aff_free(lb);
1858 isl_constraint_free(c);
1860 return 0;
1863 /* Given a basic map "bounds" that maps parameters and input dimensions
1864 * to a single output dimension, look for an expression in the parameters
1865 * and input dimensions such that the range of the output dimension shifted
1866 * by this expression is a constant.
1868 * In particular, we currently only consider lower bounds on the output
1869 * dimension as candidate expressions.
1871 static int compute_array_dim_size(struct gpu_array_bound *bound,
1872 __isl_take isl_basic_map *bounds)
1874 struct gpu_size_info size;
1876 bounds = isl_basic_map_detect_equalities(bounds);
1877 bounds = check_stride(bound, bounds);
1879 bound->size = NULL;
1880 bound->lb = NULL;
1882 size.bound = bound;
1883 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
1884 size.bset = isl_basic_map_wrap(bounds);
1885 size.bset = isl_basic_set_flatten(size.bset);
1886 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
1887 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
1888 &size);
1889 isl_basic_set_free(size.bset);
1891 return bound->size ? 0 : -1;
1894 /* Check if we can find a memory tile for the given array
1895 * based on the given accesses, and if so, put the results in "tile".
1897 * We project the accesses on each index in turn and look for a parametric
1898 * offset such that the size is constant.
1900 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
1902 int i;
1904 for (i = 0; i < tile->n; ++i) {
1905 isl_map *access_i;
1906 isl_basic_map *hull;
1908 access_i = isl_map_copy(access);
1909 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
1910 access_i = isl_map_project_out(access_i, isl_dim_out,
1911 1, tile->n - (i + 1));
1912 access_i = isl_map_compute_divs(access_i);
1913 hull = isl_map_simple_hull(access_i);
1914 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
1915 return 0;
1918 return 1;
1921 /* Construct a map with input the shared tile loops and the loops that
1922 * will be wrapped around the threads that relates these later loops
1923 * to the thread indices and then projects them out.
1925 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
1927 isl_map *priv;
1928 isl_map *tiling;
1929 isl_map *proj;
1930 isl_set *par;
1931 isl_space *dim;
1933 dim = isl_union_map_get_space(gen->shared_sched);
1935 if (gen->options->wrap)
1936 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
1937 gen->shared_len, gen->n_block, gen->block_dim);
1938 else
1939 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
1940 gen->shared_len, gen->n_block, gen->block_dim);
1942 priv = tiling;
1944 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
1945 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1946 gen->n_block, "t");
1948 priv = isl_map_align_params(priv, isl_set_get_space(par));
1949 priv = isl_map_intersect_range(priv, par);
1951 dim = isl_map_get_space(priv);
1952 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
1953 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
1954 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
1955 gen->shared_len);
1957 priv = isl_map_apply_range(priv, proj);
1959 return priv;
1962 /* Construct a map from domain_dim to domain_dim that increments
1963 * the dimension at position "pos" and leaves all other dimensions
1964 * constant.
1966 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
1968 int i;
1969 int len = isl_space_dim(domain_dim, isl_dim_set);
1970 isl_space *dim;
1971 isl_basic_map *next;
1972 isl_local_space *ls;
1974 dim = isl_space_map_from_set(domain_dim);
1975 next = isl_basic_map_universe(isl_space_copy(dim));
1976 ls = isl_local_space_from_space(dim);
1978 for (i = 0; i < len; ++i) {
1979 isl_constraint *c;
1981 c = isl_equality_alloc(isl_local_space_copy(ls));
1982 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
1983 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1984 if (i == pos)
1985 c = isl_constraint_set_constant_si(c, 1);
1986 next = isl_basic_map_add_constraint(next, c);
1989 isl_local_space_free(ls);
1991 return isl_map_from_basic_map(next);
1994 /* Check if the given access is coalesced.
1995 * That is, check whether incrementing the dimension that will get
1996 * wrapped over the last thread index results in incrementing
1997 * the last array index.
1999 * This function is only called for access relations without reuse.
2001 static int access_is_coalesced(struct gpu_gen *gen,
2002 __isl_keep isl_union_map *access)
2004 isl_space *dim;
2005 isl_map *access_map;
2006 isl_map *next_thread_x;
2007 isl_map *next_element;
2008 isl_map *map;
2009 int coalesced;
2011 access = isl_union_map_copy(access);
2012 access = isl_union_map_apply_domain(access,
2013 isl_union_map_copy(gen->tiled_sched));
2014 access_map = isl_map_from_union_map(access);
2016 dim = isl_map_get_space(access_map);
2017 dim = isl_space_domain(dim);
2018 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2020 dim = isl_map_get_space(access_map);
2021 dim = isl_space_range(dim);
2022 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2024 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2025 map = isl_map_apply_range(map, access_map);
2027 coalesced = isl_map_is_subset(map, next_element);
2029 isl_map_free(next_element);
2030 isl_map_free(map);
2032 return coalesced;
2035 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2036 * dimensions of the computed schedule, check if it is bijective for
2037 * fixed values of the first gen->shared_len dimensions.
2038 * We perform this check by equating these dimensions to parameters.
2040 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2042 int res;
2043 isl_set *par;
2044 isl_space *space;
2046 access = isl_map_copy(access);
2047 space = isl_space_params(isl_map_get_space(access));
2048 par = parametrization(space, gen->shared_len + gen->n_block,
2049 0, gen->shared_len, "s");
2050 access = isl_map_intersect_domain(access, par);
2051 res = isl_map_is_bijective(access);
2052 isl_map_free(access);
2054 return res;
2057 /* Look for the last shared tile loop that affects the offset of "tile"
2058 * and return the result.
2059 * If there is no such loop, then return the index of the loop
2060 * before the first shared tile loop, in particular gen->tile_first - 1.
2062 static int compute_tile_last_shared(struct gpu_gen *gen,
2063 struct gpu_array_tile *tile)
2065 int i, j;
2067 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2068 for (i = 0; i < tile->n; ++i) {
2069 isl_aff *lb;
2070 isl_aff *shift;
2072 lb = tile->bound[i].lb;
2073 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2074 break;
2076 shift = tile->bound[i].shift;
2077 if (!shift)
2078 continue;
2079 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2080 break;
2082 if (i < tile->n)
2083 break;
2086 return j;
2089 /* Look for the last shared tile loop that affects the offset of the
2090 * shared or private tile and store the result in group->last_shared.
2091 * If there is no such loop, then group->last_shared is set to a value
2092 * before the first shared tile loop, in particular gen->tile_first - 1.
2093 * If there is no tile defined on the array reference group,
2094 * then set group->last_shared to gen->shared_len - 1.
2096 static void set_last_shared(struct gpu_gen *gen,
2097 struct gpu_array_ref_group *group)
2099 struct gpu_array_tile *tile;
2101 group->last_shared = gen->shared_len - 1;
2103 tile = group->private_tile;
2104 if (!tile)
2105 tile = group->shared_tile;
2106 if (!tile)
2107 return;
2109 group->last_shared = compute_tile_last_shared(gen, tile);
2112 /* Compute a privatized copy of all access relations from reference groups that
2113 * are mapped to private memory and store the result in gen->privatization.
2115 static void compute_private_access(struct gpu_gen *gen)
2117 int i, j;
2118 isl_union_map *private;
2120 if (!gen->options->use_private_memory)
2121 return;
2123 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2125 for (i = 0; i < gen->prog->n_array; ++i) {
2126 struct gpu_array_info *array = &gen->prog->array[i];
2128 if (gpu_array_is_read_only_scalar(array))
2129 continue;
2131 for (j = 0; j < array->n_group; ++j) {
2132 if (!array->groups[j]->private_tile)
2133 continue;
2135 private = isl_union_map_union(private,
2136 group_access_relation(array->groups[j], 1, 1));
2140 if (isl_union_map_is_empty(private))
2141 isl_union_map_free(private);
2142 else {
2143 isl_union_map *priv;
2145 private = isl_union_map_apply_domain(private,
2146 isl_union_map_copy(gen->shared_sched));
2147 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2148 private = isl_union_map_apply_domain(private, priv);
2149 gen->private_access = private;
2153 /* Compute the size of the tile specified by "tile"
2154 * in number of elements and return the result.
2156 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2158 int i;
2159 isl_val *size;
2161 size = isl_val_one(ctx);
2163 for (i = 0; i < tile->n; ++i)
2164 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2166 return size;
2169 /* If max_shared_memory is not set to infinity (-1), then make
2170 * sure that the total amount of shared memory required by the
2171 * array reference groups mapped to shared memory is no larger
2172 * than this maximum.
2174 * We apply a greedy approach and discard (keep in global memory)
2175 * those groups that would result in a total memory size that
2176 * is larger than the maximum.
2178 static void check_shared_memory_bound(struct gpu_gen *gen)
2180 int i, j;
2181 isl_val *left, *size;
2183 if (gen->options->max_shared_memory < 0)
2184 return;
2186 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2188 for (i = 0; i < gen->prog->n_array; ++i) {
2189 struct gpu_array_info *array = &gen->prog->array[i];
2191 for (j = 0; j < array->n_group; ++j) {
2192 struct gpu_array_ref_group *group;
2194 group = array->groups[j];
2195 if (!group->shared_tile)
2196 continue;
2198 size = tile_size(gen->ctx, group->shared_tile);
2199 size = isl_val_mul_ui(size, array->size);
2201 if (isl_val_le(size, left)) {
2202 left = isl_val_sub(left, size);
2203 continue;
2205 isl_val_free(size);
2207 group->shared_tile = free_tile(group->shared_tile);
2211 isl_val_free(left);
2214 /* Given a description of an array tile "tile" and the "space"
2216 * { D -> A }
2218 * where D represents the first shared_len schedule dimensions
2219 * and A represents the array, construct an isl_multi_aff
2221 * { [D[i] -> A[a]] -> A'[a'] }
2223 * with A' a scaled down copy of A according to the shifts and strides
2224 * in "tile". In particular,
2226 * a' = (a + shift(i))/stride
2228 * "insert_array" represents
2230 * { [D -> A] -> D }
2232 * and is used to insert A into the domain of functions that only
2233 * reference D.
2235 static __isl_give isl_multi_aff *strided_tile(
2236 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2237 __isl_keep isl_multi_aff *insert_array)
2239 int i;
2240 isl_ctx *ctx;
2241 isl_multi_aff *shift;
2242 isl_multi_val *stride;
2243 isl_space *space2;
2244 isl_local_space *ls;
2245 isl_multi_aff *tiling;
2247 ctx = isl_space_get_ctx(space);
2248 space2 = isl_space_domain(isl_space_copy(space));
2249 ls = isl_local_space_from_space(space2);
2250 space2 = isl_space_range(isl_space_copy(space));
2251 stride = isl_multi_val_zero(space2);
2252 shift = isl_multi_aff_zero(isl_space_copy(space));
2254 for (i = 0; i < tile->n; ++i) {
2255 struct gpu_array_bound *bound = &tile->bound[i];
2256 isl_val *stride_i;
2257 isl_aff *shift_i;
2259 if (tile->bound[i].shift) {
2260 stride_i = isl_val_copy(bound->stride);
2261 shift_i = isl_aff_copy(bound->shift);
2262 } else {
2263 stride_i = isl_val_one(ctx);
2264 shift_i = isl_aff_zero_on_domain(
2265 isl_local_space_copy(ls));
2268 stride = isl_multi_val_set_val(stride, i, stride_i);
2269 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2271 isl_local_space_free(ls);
2273 shift = isl_multi_aff_pullback_multi_aff(shift,
2274 isl_multi_aff_copy(insert_array));
2276 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2277 tiling = isl_multi_aff_add(tiling, shift);
2278 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2280 return tiling;
2283 /* Compute a tiling for the array reference group "group".
2285 * The tiling is of the form
2287 * { [D[i] -> A[a]] -> T[t] }
2289 * where D represents the first shared_len schedule dimensions,
2290 * A represents the global array and T represents the shared or
2291 * private memory tile. The name of T is the name of the local
2292 * array.
2294 * If there is any stride in the accesses, then the mapping is
2296 * t = (a + shift(i))/stride - lb(i)
2298 * otherwise, it is simply
2300 * t = a - lb(i)
2302 static void compute_group_tiling(struct gpu_array_ref_group *group)
2304 int i;
2305 struct gpu_array_tile *tile;
2306 struct gpu_array_info *array = group->array;
2307 isl_space *space;
2308 isl_multi_aff *tiling, *lb, *insert_array;
2309 isl_printer *p;
2310 char *local_name;
2312 tile = group->private_tile;
2313 if (!tile)
2314 tile = group->shared_tile;
2315 if (!tile)
2316 return;
2318 space = isl_map_get_space(group->access);
2319 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2321 for (i = 0; i < tile->n; ++i)
2322 if (tile->bound[i].shift)
2323 break;
2325 if (i < tile->n)
2326 tiling = strided_tile(tile, space, insert_array);
2327 else
2328 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2330 lb = isl_multi_aff_zero(space);
2331 for (i = 0; i < tile->n; ++i) {
2332 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2333 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2335 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2337 tiling = isl_multi_aff_sub(tiling, lb);
2339 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2340 p = print_array_name(p, group);
2341 local_name = isl_printer_get_str(p);
2342 isl_printer_free(p);
2343 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2344 free(local_name);
2346 tile->tiling = tiling;
2349 /* Compute a tiling for all the array reference groups.
2351 static void compute_group_tilings(struct gpu_gen *gen)
2353 int i, j;
2355 for (i = 0; i < gen->prog->n_array; ++i) {
2356 struct gpu_array_info *array = &gen->prog->array[i];
2358 for (j = 0; j < array->n_group; ++j)
2359 compute_group_tiling(array->groups[j]);
2363 /* Fill up the groups array with singleton groups, i.e., one group
2364 * per reference, initializing the array, access, write, n_ref and refs fields.
2365 * In particular the access field is initialized to the scheduled
2366 * access relation of the array reference.
2368 * Return the number of elements initialized, i.e., the number of
2369 * active references in the current kernel.
2371 static int populate_array_references(struct gpu_array_info *array,
2372 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2374 int i;
2375 int n;
2376 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2378 n = 0;
2379 for (i = 0; i < array->n_ref; ++i) {
2380 isl_union_map *umap;
2381 isl_map *map;
2382 struct gpu_array_ref_group *group;
2383 struct gpu_stmt_access *access = array->refs[i];
2385 map = isl_map_copy(access->access);
2386 umap = isl_union_map_from_map(map);
2387 umap = isl_union_map_apply_domain(umap,
2388 isl_union_map_copy(sched));
2390 if (isl_union_map_is_empty(umap)) {
2391 isl_union_map_free(umap);
2392 continue;
2395 map = isl_map_from_union_map(umap);
2396 map = isl_map_detect_equalities(map);
2398 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2399 assert(group);
2400 group->array = array;
2401 group->access = map;
2402 group->write = access->write;
2403 group->refs = &array->refs[i];
2404 group->n_ref = 1;
2406 groups[n++] = group;
2409 return n;
2412 /* If group->n_ref == 1, then group->refs was set by
2413 * populate_array_references to point directly into
2414 * group->array->refs and should not be freed.
2415 * If group->n_ref > 1, then group->refs was set by join_groups
2416 * to point to a newly allocated array.
2418 static void free_array_ref_group(struct gpu_array_ref_group *group)
2420 if (!group)
2421 return;
2422 free_tile(group->shared_tile);
2423 free_tile(group->private_tile);
2424 isl_map_free(group->access);
2425 if (group->n_ref > 1)
2426 free(group->refs);
2427 free(group);
2430 /* Given a map where the input dimensions represent the tile loops,
2431 * eliminate the innermost of those that have a fixed value
2432 * until we reach one that does not (obviously) have a fixed value.
2434 static __isl_give isl_map *eliminate_fixed_inner_loops(
2435 __isl_take isl_map *access)
2437 int i, n;
2439 n = isl_map_dim(access, isl_dim_in);
2441 for (i = n - 1; i >= 0; --i) {
2442 if (!map_plain_is_fixed(access, isl_dim_in, i))
2443 break;
2444 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2446 return access;
2449 /* Check if the access relations of group1 and group2 overlap within
2450 * the innermost loop. In particular, ignore any inner dimension
2451 * with a fixed value.
2452 * The copying to and from shared memory will be performed within
2453 * the innermost actual loop so we are only allowed to consider
2454 * the dimensions up to that innermost loop while checking whether
2455 * two access relations overlap.
2457 static int accesses_overlap(struct gpu_array_ref_group *group1,
2458 struct gpu_array_ref_group *group2)
2460 int empty;
2461 isl_map *access1, *access2;
2463 access1 = isl_map_copy(group1->access);
2464 access1 = eliminate_fixed_inner_loops(access1);
2465 access2 = isl_map_copy(group2->access);
2466 access2 = eliminate_fixed_inner_loops(access2);
2467 access1 = isl_map_intersect(access1, access2);
2468 empty = isl_map_is_empty(access1);
2469 isl_map_free(access1);
2471 return !empty;
2474 /* Combine the given two groups into a single group, containing
2475 * the references of both groups.
2477 static struct gpu_array_ref_group *join_groups(
2478 struct gpu_array_ref_group *group1,
2479 struct gpu_array_ref_group *group2)
2481 int i;
2482 isl_ctx *ctx;
2483 struct gpu_array_ref_group *group;
2485 ctx = isl_map_get_ctx(group1->access);
2486 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2487 assert(group);
2488 group->array = group1->array;
2489 group->access = isl_map_union(isl_map_copy(group1->access),
2490 isl_map_copy(group2->access));
2491 group->write = group1->write || group2->write;
2492 group->n_ref = group1->n_ref + group2->n_ref;
2493 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2494 group->n_ref);
2495 assert(group->refs);
2496 for (i = 0; i < group1->n_ref; ++i)
2497 group->refs[i] = group1->refs[i];
2498 for (i = 0; i < group2->n_ref; ++i)
2499 group->refs[group1->n_ref + i] = group2->refs[i];
2501 return group;
2504 /* Combine the given two groups into a single group and free
2505 * the original two groups.
2507 static struct gpu_array_ref_group *join_groups_and_free(
2508 struct gpu_array_ref_group *group1,
2509 struct gpu_array_ref_group *group2)
2511 struct gpu_array_ref_group *group;
2513 group = join_groups(group1, group2);
2514 free_array_ref_group(group1);
2515 free_array_ref_group(group2);
2516 return group;
2519 /* Compute the private and/or shared memory tiles for the array
2520 * reference group "group" of array "array".
2522 * If the array is a read-only scalar or if the user requested
2523 * not to use shared or private memory, then we do not need to do anything.
2525 * We only try to compute a shared memory tile if there is any reuse
2526 * or if the access is not coalesced.
2528 * For computing a private memory tile, we also require that there is
2529 * some reuse. Moreover, we require that the access is private
2530 * to the thread. That is, we check that any given array element
2531 * is only accessed by a single thread.
2532 * We compute an access relation that maps the shared tile loop iterators
2533 * and the shared point loop iterators that will be wrapped over the
2534 * threads to the array elements.
2535 * We actually check that those iterators that will be wrapped
2536 * partition the array space. This check is stricter than necessary
2537 * since several iterations may be mapped onto the same thread
2538 * and then they could be allowed to access the same memory elements,
2539 * but our check does not allow this situation.
2541 * We also check that the index expression only depends on parallel
2542 * loops. That way, we can move those loops innermost and unroll them.
2543 * Again, we use a test that is stricter than necessary.
2544 * We actually check whether the index expression only depends
2545 * on the iterators that are wrapped over the threads.
2546 * These are necessarily parallel, but there may be more parallel loops.
2548 * Combining the injectivity of the first test with the single-valuedness
2549 * of the second test, we simply test for bijectivity.
2551 * If it turns out we can use registers, we compute the private memory
2552 * tile size using can_tile, after introducing a dependence
2553 * on the thread indices.
2555 static void compute_group_bounds_core(struct gpu_gen *gen,
2556 struct gpu_array_ref_group *group)
2558 isl_ctx *ctx = isl_space_get_ctx(group->array->dim);
2559 isl_union_map *access;
2560 int n_index = group->array->n_index;
2561 int no_reuse;
2562 isl_map *acc;
2563 int use_shared = gen->options->use_shared_memory;
2564 int use_private = gen->options->use_private_memory;
2566 if (!use_shared && !use_private)
2567 return;
2568 if (gpu_array_is_read_only_scalar(group->array))
2569 return;
2571 access = group_access_relation(group, 1, 1);
2572 no_reuse = isl_union_map_is_injective(access);
2574 if (use_shared && (!no_reuse || !access_is_coalesced(gen, access))) {
2575 group->shared_tile = create_tile(ctx, group->array->n_index);
2576 if (!can_tile(group->access, group->shared_tile))
2577 group->shared_tile = free_tile(group->shared_tile);
2580 if (!use_private || no_reuse) {
2581 isl_union_map_free(access);
2582 return;
2585 access = isl_union_map_apply_domain(access,
2586 isl_union_map_copy(gen->shared_sched));
2588 acc = isl_map_from_union_map(access);
2590 if (!access_is_bijective(gen, acc)) {
2591 isl_map_free(acc);
2592 return;
2595 group->private_tile = create_tile(gen->ctx, n_index);
2596 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2597 if (!can_tile(acc, group->private_tile))
2598 group->private_tile = free_tile(group->private_tile);
2600 isl_map_free(acc);
2603 /* Compute the private and/or shared memory tiles for the array
2604 * reference group "group" of array "array" and set last_shared.
2606 static void compute_group_bounds(struct gpu_gen *gen,
2607 struct gpu_array_ref_group *group)
2609 compute_group_bounds_core(gen, group);
2610 set_last_shared(gen, group);
2613 /* If two groups have overlapping access relations (as determined by
2614 * the "overlap" function) and if one of them involves a write,
2615 * then merge the two groups into one.
2616 * If "compute_bounds" is set, then call compute_group_bounds
2617 * on the merged groups.
2619 * Return the updated number of groups.
2621 static int group_writes(struct gpu_gen *gen,
2622 int n, struct gpu_array_ref_group **groups,
2623 int (*overlap)(struct gpu_array_ref_group *group1,
2624 struct gpu_array_ref_group *group2), int compute_bounds)
2626 int i, j;
2628 for (i = 0; i < n; ++i) {
2629 for (j = n - 1; j > i; --j) {
2630 if (!groups[i]->write && !groups[j]->write)
2631 continue;
2633 if (!overlap(groups[i], groups[j]))
2634 continue;
2636 groups[i] = join_groups_and_free(groups[i], groups[j]);
2637 if (compute_bounds)
2638 compute_group_bounds(gen, groups[i]);
2639 if (j != n - 1)
2640 groups[j] = groups[n - 1];
2641 n--;
2645 return n;
2648 /* If two groups have overlapping access relations (within the innermost
2649 * loop) and if one of them involves a write, then merge the two groups
2650 * into one.
2652 * Return the updated number of groups.
2654 static int group_overlapping_writes(struct gpu_gen *gen,
2655 int n, struct gpu_array_ref_group **groups)
2657 return group_writes(gen, n, groups, &accesses_overlap, 0);
2660 /* Check if the access relations of group1 and group2 overlap within
2661 * the outermost min(group1->last_shared, group2->last_shared) loops.
2663 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2664 struct gpu_array_ref_group *group2)
2666 int last_shared;
2667 int dim;
2668 int empty;
2669 isl_map *map_i, *map_j, *map;
2671 last_shared = group1->last_shared;
2672 if (group2->last_shared < last_shared)
2673 last_shared = group2->last_shared;
2674 map_i = isl_map_copy(group1->access);
2675 dim = isl_map_dim(map_i, isl_dim_in);
2676 map_i = isl_map_eliminate(map_i, isl_dim_in,
2677 last_shared + 1, dim - (last_shared + 1));
2678 map_j = isl_map_copy(group2->access);
2679 map_j = isl_map_eliminate(map_j, isl_dim_in,
2680 last_shared + 1, dim - (last_shared + 1));
2681 map = isl_map_intersect(map_i, map_j);
2682 empty = isl_map_is_empty(map);
2683 isl_map_free(map);
2685 return !empty;
2688 /* If two groups have overlapping access relations (within the outer
2689 * last_shared loops) and if one of them involves a write,
2690 * then merge the two groups into one.
2692 * Return the updated number of groups.
2694 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2695 struct gpu_array_ref_group **groups)
2697 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2700 /* Is the size of the tile specified by "tile" smaller than the sum of
2701 * the sizes of the tiles specified by "tile1" and "tile2"?
2703 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
2704 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2706 int smaller;
2707 isl_val *size, *size1, *size2;
2709 size = tile_size(ctx, tile);
2710 size1 = tile_size(ctx, tile1);
2711 size2 = tile_size(ctx, tile2);
2713 size = isl_val_sub(size, size1);
2714 size = isl_val_sub(size, size2);
2715 smaller = isl_val_is_neg(size);
2717 isl_val_free(size);
2719 return smaller;
2722 /* Given an initial grouping of array references and shared memory tiles
2723 * for each group that allows for a shared memory tile, merge two groups
2724 * if both have a shared memory tile, the merged group also has
2725 * a shared memory tile and the size of the tile for the merge group
2726 * is smaller than the sum of the tile sizes of the individual groups.
2728 * If merging two groups decreases the "last_shared" dimension of
2729 * one or both of the two groups, then we need to check for overlapping
2730 * writes again.
2732 * Return the number of groups after merging.
2734 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2735 struct gpu_array_info *array, int n,
2736 struct gpu_array_ref_group **groups)
2738 int i, j;
2739 int recompute_overlap = 0;
2740 isl_ctx *ctx = isl_space_get_ctx(array->dim);
2742 for (i = 0; i < n; ++i) {
2743 if (!groups[i]->shared_tile)
2744 continue;
2745 for (j = n - 1; j > i; --j) {
2746 isl_map *map;
2747 int empty;
2748 struct gpu_array_ref_group *group;
2750 if (!groups[j]->shared_tile)
2751 continue;
2753 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2754 isl_map_copy(groups[j]->access));
2755 empty = isl_map_is_empty(map);
2756 isl_map_free(map);
2758 if (empty)
2759 continue;
2761 group = join_groups(groups[i], groups[j]);
2762 compute_group_bounds(gen, group);
2763 if (!group->shared_tile ||
2764 !smaller_tile(ctx, group->shared_tile,
2765 groups[i]->shared_tile,
2766 groups[j]->shared_tile)) {
2767 free_array_ref_group(group);
2768 continue;
2771 if (group->last_shared < groups[i]->last_shared ||
2772 group->last_shared < groups[j]->last_shared)
2773 recompute_overlap = 1;
2774 free_array_ref_group(groups[i]);
2775 free_array_ref_group(groups[j]);
2776 groups[i] = group;
2777 if (j != n - 1)
2778 groups[j] = groups[n - 1];
2779 n--;
2783 if (recompute_overlap)
2784 n = group_last_shared_overlapping_writes(gen, n, groups);
2785 return n;
2788 /* Set array->n_group and array->groups to n and groups.
2790 * Additionally, set the "nr" field of each group
2791 * and the "group" field of each reference in each group.
2793 static void set_array_groups(struct gpu_array_info *array,
2794 int n, struct gpu_array_ref_group **groups)
2796 int i, j;
2798 array->n_group = n;
2799 array->groups = groups;
2801 for (i = 0; i < n; ++i) {
2802 groups[i]->nr = i;
2804 for (j = 0; j < groups[i]->n_ref; ++j)
2805 groups[i]->refs[j]->group = i;
2809 /* Group array references that should be considered together when
2810 * deciding whether to access them from private, shared or global memory.
2812 * In particular, if two array references overlap and if one of them
2813 * is a write, then the two references are grouped together.
2814 * We first perform an initial grouping based only on the access relation.
2815 * After computing shared and private memory tiles, we check for
2816 * overlapping writes again, but this time taking into account
2817 * the "last_shared" property.
2819 * Furthermore, if two groups admit a shared memory tile and if the
2820 * combination of the two also admits a shared memory tile, we merge
2821 * the two groups.
2823 static void group_array_references(struct gpu_gen *gen,
2824 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
2826 int i;
2827 int n;
2828 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2829 struct gpu_array_ref_group **groups;
2831 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
2832 array->n_ref);
2833 assert(groups);
2835 n = populate_array_references(array, sched, groups);
2837 n = group_overlapping_writes(gen, n, groups);
2839 for (i = 0; i < n; ++i)
2840 compute_group_bounds(gen, groups[i]);
2842 n = group_last_shared_overlapping_writes(gen, n, groups);
2844 n = group_common_shared_memory_tile(gen, array, n, groups);
2846 set_array_groups(array, n, groups);
2849 /* Take tiled_sched, project it onto the shared tile loops and
2850 * the loops that will be wrapped over the threads and
2851 * store the result in gen->shared_sched.
2852 * Also compute a projection that projects out the loops that will be
2853 * wrapped over the threads and store this projection in gen->shared_proj.
2855 static void compute_shared_sched(struct gpu_gen *gen)
2857 isl_space *dim;
2858 isl_map *proj;
2859 isl_set *par;
2860 isl_union_map *sched;
2862 sched = isl_union_map_copy(gen->tiled_sched);
2864 dim = isl_union_map_get_space(sched);
2865 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
2866 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
2868 dim = isl_union_map_get_space(sched);
2869 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
2871 gen->shared_sched = sched;
2872 gen->shared_proj = isl_union_map_from_map(proj);
2875 /* Group references of all arrays in the program.
2877 static void group_references(struct gpu_gen *gen)
2879 int i;
2880 isl_union_map *sched;
2882 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2883 isl_union_map_copy(gen->shared_proj));
2885 for (i = 0; i < gen->prog->n_array; ++i)
2886 group_array_references(gen, &gen->prog->array[i], sched);
2888 isl_union_map_free(sched);
2891 /* Free all array information that is local to the current kernel.
2893 static void free_local_array_info(struct gpu_gen *gen)
2895 int i, j;
2897 for (i = 0; i < gen->prog->n_array; ++i) {
2898 struct gpu_array_info *array = &gen->prog->array[i];
2900 for (j = 0; j < array->n_group; ++j)
2901 free_array_ref_group(array->groups[j]);
2902 free(array->groups);
2906 /* Compute the size of a bounding box around the origin and "set",
2907 * where "set" is assumed to contain only non-negative elements.
2908 * In particular, compute the maximal value of "set" in each direction
2909 * and add one.
2911 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
2912 __isl_keep isl_set *context)
2914 int i, n;
2915 isl_multi_pw_aff *mpa;
2917 n = isl_set_dim(set, isl_dim_set);
2918 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
2919 for (i = 0; i < n; ++i) {
2920 isl_space *space;
2921 isl_aff *one;
2922 isl_pw_aff *bound;
2924 bound = isl_set_dim_max(isl_set_copy(set), i);
2925 bound = isl_pw_aff_coalesce(bound);
2926 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
2928 space = isl_pw_aff_get_domain_space(bound);
2929 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2930 one = isl_aff_add_constant_si(one, 1);
2931 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
2932 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
2934 isl_set_free(set);
2936 return mpa;
2939 /* Compute the effective grid size as a list of the sizes in each dimension.
2941 * The grid size specified by the user or set by default
2942 * in read_grid_sizes() and applied in tile_schedule(),
2943 * may be too large for the given code in the sense that
2944 * it may contain blocks that don't need to execute anything.
2945 * We therefore don't return this grid size, but instead the
2946 * smallest grid size that ensures that all blocks that actually
2947 * execute code are included in the grid.
2949 * We first extract a description of the grid, i.e., the possible values
2950 * of the block ids, from gen->tiled_sched.
2951 * The block ids are parameters in gen->tiled_sched.
2952 * We simply need to change them into set dimensions.
2954 * Then, for each block dimension, we compute the maximal value of the block id
2955 * and add one.
2957 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
2958 struct ppcg_kernel *kernel)
2960 int i;
2961 isl_set *grid;
2963 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
2964 grid = isl_set_from_params(grid);
2965 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
2966 for (i = 0; i < gen->n_grid; ++i) {
2967 int pos;
2968 char name[20];
2970 snprintf(name, sizeof(name), "b%d", i);
2971 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
2972 assert(pos >= 0);
2973 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
2974 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
2977 return extract_size(grid, kernel->context);
2980 /* Compute the size of a fixed bounding box around the origin and "set",
2981 * where "set" is assumed to contain only non-negative elements,
2982 * and store the results in "size".
2983 * In particular, compute the maximal value of "set" in each direction
2984 * and add one.
2986 static void extract_fixed_size(__isl_take isl_set *set, int *size)
2988 int i, n;
2989 isl_local_space *ls;
2990 isl_aff *obj;
2992 n = isl_set_dim(set, isl_dim_set);
2993 ls = isl_local_space_from_space(isl_set_get_space(set));
2994 obj = isl_aff_zero_on_domain(ls);
2995 for (i = 0; i < n; ++i) {
2996 isl_val *max;
2998 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
2999 max = isl_set_max_val(set, obj);
3000 size[i] = isl_val_get_num_si(max) + 1;
3001 isl_val_free(max);
3002 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
3004 isl_aff_free(obj);
3005 isl_set_free(set);
3008 /* Compute the effective block size as a list of the sizes in each dimension
3009 * and store the sizes in kernel->block_dim.
3011 * The block size specified by the user or set by default
3012 * in read_block_sizes() and applied in thread_tile_schedule(),
3013 * may be too large for the given code in the sense that
3014 * it may contain threads that don't need to execute anything.
3015 * We therefore don't store this block size in kernel->block_dim,
3016 * but instead the smallest block size that ensures that all threads
3017 * that actually execute code are included in the block.
3019 * The current implementation eliminates all parameters, ensuring
3020 * that the size is a fixed constant in each dimension.
3021 * In principle we could also compute parametric sizes.
3022 * We would have to make sure to project out all b%d and t%d parameters,
3023 * however.
3025 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3027 int i;
3028 int nparam;
3029 isl_set *block;
3030 isl_multi_pw_aff *mpa;
3032 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3033 block = isl_set_from_params(block);
3034 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3035 kernel->n_block = gen->n_block;
3036 for (i = 0; i < gen->n_block; ++i) {
3037 int pos;
3038 char name[20];
3040 snprintf(name, sizeof(name), "t%d", i);
3041 pos = isl_set_find_dim_by_name(block, isl_dim_param, name);
3042 assert(pos >= 0);
3043 block = isl_set_equate(block, isl_dim_param, pos,
3044 isl_dim_set, i);
3046 nparam = isl_set_dim(block, isl_dim_param);
3047 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3049 extract_fixed_size(block, kernel->block_dim);
3052 void ppcg_kernel_free(void *user)
3054 struct ppcg_kernel *kernel = user;
3055 int i;
3057 if (!kernel)
3058 return;
3060 isl_multi_pw_aff_free(kernel->grid_size);
3061 isl_set_free(kernel->context);
3062 isl_union_set_free(kernel->arrays);
3063 isl_space_free(kernel->space);
3064 isl_ast_node_free(kernel->tree);
3066 for (i = 0; i < kernel->n_array; ++i)
3067 isl_pw_aff_list_free(kernel->array[i].bound);
3068 free(kernel->array);
3070 for (i = 0; i < kernel->n_var; ++i) {
3071 free(kernel->var[i].name);
3072 isl_vec_free(kernel->var[i].size);
3074 free(kernel->var);
3076 free(kernel);
3079 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3080 struct ppcg_kernel_var *var)
3082 int j;
3083 struct gpu_array_tile *tile;
3084 isl_printer *p;
3085 char *name;
3087 var->array = group->array;
3089 tile = group->private_tile;
3090 var->type = ppcg_access_private;
3091 if (!tile) {
3092 tile = group->shared_tile;
3093 var->type = ppcg_access_shared;
3096 p = isl_printer_to_str(ctx);
3097 p = print_array_name(p, group);
3098 var->name = isl_printer_get_str(p);
3099 isl_printer_free(p);
3101 var->size = isl_vec_alloc(ctx, group->array->n_index);
3103 for (j = 0; j < group->array->n_index; ++j)
3104 var->size = isl_vec_set_element_val(var->size, j,
3105 isl_val_copy(tile->bound[j].size));
3108 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3110 int i, j, n;
3112 n = 0;
3113 for (i = 0; i < gen->prog->n_array; ++i) {
3114 struct gpu_array_info *array = &gen->prog->array[i];
3116 for (j = 0; j < array->n_group; ++j) {
3117 struct gpu_array_ref_group *group = array->groups[j];
3118 if (group->private_tile || group->shared_tile)
3119 ++n;
3123 kernel->n_var = n;
3124 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3125 assert(kernel->var);
3127 n = 0;
3128 for (i = 0; i < gen->prog->n_array; ++i) {
3129 struct gpu_array_info *array = &gen->prog->array[i];
3131 for (j = 0; j < array->n_group; ++j) {
3132 struct gpu_array_ref_group *group = array->groups[j];
3133 if (!group->private_tile && !group->shared_tile)
3134 continue;
3135 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3136 ++n;
3141 /* The sizes of the arrays on the host that have been computed by
3142 * extract_array_info may depend on the parameters. Use the extra
3143 * constraints on the parameters that are valid at "host_domain"
3144 * to simplify these expressions and store the results in kernel->array.
3146 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3147 __isl_keep isl_set *host_domain)
3149 int i, j;
3150 isl_set *context;
3152 kernel->array = isl_calloc_array(gen->ctx,
3153 struct gpu_local_array_info, gen->prog->n_array);
3154 assert(kernel->array);
3155 kernel->n_array = gen->prog->n_array;
3157 context = isl_set_copy(host_domain);
3158 context = isl_set_params(context);
3160 for (i = 0; i < gen->prog->n_array; ++i) {
3161 struct gpu_array_info *array = &gen->prog->array[i];
3162 isl_pw_aff_list *local;
3164 if (array->n_group == 0)
3165 continue;
3167 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3169 for (j = 0; j < array->n_index; ++j) {
3170 isl_pw_aff *pwaff;
3172 pwaff = isl_pw_aff_copy(array->bound[j]);
3173 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3174 local = isl_pw_aff_list_add(local, pwaff);
3177 kernel->array[i].bound = local;
3179 isl_set_free(context);
3182 /* Find the element in gen->stmt that has the given "id".
3183 * Return NULL if no such gpu_stmt can be found.
3185 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3187 int i;
3189 for (i = 0; i < prog->n_stmts; ++i) {
3190 if (id == prog->stmts[i].id)
3191 break;
3194 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3197 /* Set gen->tile_len and gen->n_parallel to those of the statement
3198 * affected by the first map (part of the schedule)
3199 * on which this function is called.
3200 * Because of the way the schedule is constructed, the other statements
3201 * in the list, if any, should have the same values for these properties.
3203 static int extract_tile_len(__isl_take isl_map *map, void *user)
3205 struct gpu_gen *gen = (struct gpu_gen *) user;
3206 isl_id *id;
3207 struct gpu_stmt *stmt;
3209 id = isl_map_get_tuple_id(map, isl_dim_in);
3210 stmt = find_stmt(gen->prog, id);
3211 isl_id_free(id);
3213 isl_map_free(map);
3215 if (!stmt)
3216 isl_die(gen->ctx, isl_error_unknown,
3217 "statement not found", return -1);
3219 gen->tile_len = stmt->tile_len;
3220 gen->n_parallel = stmt->n_parallel;
3222 return -1;
3225 void ppcg_kernel_stmt_free(void *user)
3227 int i;
3228 struct ppcg_kernel_stmt *stmt = user;
3230 if (!stmt)
3231 return;
3233 switch (stmt->type) {
3234 case ppcg_kernel_copy:
3235 isl_ast_expr_free(stmt->u.c.index);
3236 isl_ast_expr_free(stmt->u.c.local_index);
3237 break;
3238 case ppcg_kernel_domain:
3239 for (i = 0; i < stmt->u.d.n_access; ++i) {
3240 isl_ast_expr_list_free(stmt->u.d.access[i].index);
3241 free(stmt->u.d.access[i].local_name);
3243 free(stmt->u.d.access);
3244 break;
3245 case ppcg_kernel_sync:
3246 break;
3249 free(stmt);
3252 /* Set the options of "context" to
3254 * { space -> [x] : x >= first }
3256 static __isl_give isl_ast_build *set_unroll(
3257 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3258 int first)
3260 isl_ctx *ctx;
3261 isl_map *unroll;
3262 isl_union_map *opt;
3264 ctx = isl_ast_build_get_ctx(build);
3266 space = isl_space_from_domain(space);
3267 space = isl_space_add_dims(space, isl_dim_out, 1);
3268 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3269 unroll = isl_map_universe(space);
3270 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3271 opt = isl_union_map_from_map(unroll);
3273 build = isl_ast_build_set_options(build, opt);
3275 return build;
3278 /* Return a list of isl_ids of the form "prefix%d".
3280 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3281 int n, const char *prefix)
3283 int i;
3284 char name[10];
3285 isl_id_list *names;
3287 names = isl_id_list_alloc(ctx, n);
3288 for (i = 0; i < n; ++i) {
3289 isl_id *id;
3291 snprintf(name, sizeof(name), "%s%d", prefix, i);
3292 id = isl_id_alloc(ctx, name, NULL);
3293 names = isl_id_list_add(names, id);
3296 return names;
3299 /* Extend the schedule "schedule" with the part of "extension"
3300 * starting at "first" up to "len".
3302 static __isl_give isl_union_map *extend_schedule(
3303 __isl_take isl_union_map *schedule,
3304 __isl_take isl_union_map *extension, int first, int len)
3306 isl_space *space;
3307 isl_map *proj;
3308 isl_union_map *umap;
3309 isl_set *set;
3311 space = isl_union_map_get_space(schedule);
3312 space = isl_space_set_from_params(space);
3313 space = isl_space_add_dims(space, isl_dim_set, len);
3314 proj = isl_set_identity(isl_set_universe(space));
3315 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3316 extension = isl_union_map_apply_range(extension,
3317 isl_union_map_from_map(proj));
3319 schedule = isl_union_map_range_product(schedule, extension);
3321 return schedule;
3324 /* This function is called for each access to an array in each instance
3325 * in the kernel of some statement in the original code.
3326 * Replace that access by an access to global, shared or private memory
3327 * and store the results in *kernel_access.
3329 * Since the array in shared or private memory is just
3330 * a shifted copy of part of the original array, we simply need
3331 * to subtract the lower bound, which was computed in can_tile.
3332 * If any of the indices is strided, then we first add
3333 * shared_tile->bound[i].shift and divide by shared_tile->bound[i].stride.
3335 * If the given array is accessed directly from global memory,
3336 * we don't need to perform any shifting and simply simplify
3337 * the expression in the context of the domain instead.
3339 * If the array space (range of access) has no name, then we are
3340 * accessing an iterator in the original program.
3342 * The input stmt_access->access relation maps the iteration domain
3343 * of the current statement to an array element.
3344 * The first step is to reformulate
3345 * this access relation in terms of the loop iterators of the generated
3346 * code through precomposition with gen->stmt_it.
3348 * The expressions in "tile" are formulated in terms of the first
3349 * gen->shared_len dimensions of the computed schedule using the mapping
3350 * sched2shared which maps the loop iterators to these dimensions.
3352 static void compute_index_expression(struct gpu_gen *gen,
3353 struct ppcg_kernel_access *kernel_access,
3354 struct gpu_stmt_access *stmt_access, __isl_keep isl_map *stmt_it,
3355 __isl_keep isl_map *sched2shared, __isl_keep isl_ast_build *build)
3357 isl_map *access;
3358 isl_pw_multi_aff *pma;
3359 int i;
3360 unsigned n_index;
3361 struct gpu_array_tile *tile = NULL;
3363 if (isl_map_has_tuple_name(stmt_access->access, isl_dim_out)) {
3364 int i;
3365 const char *name;
3366 struct gpu_array_ref_group *group;
3367 isl_printer *p;
3369 name = isl_map_get_tuple_name(stmt_access->access, isl_dim_out);
3371 for (i = 0; i < gen->prog->n_array; ++i) {
3372 if (strcmp(name, gen->prog->array[i].name))
3373 continue;
3374 kernel_access->array = &gen->prog->array[i];
3375 kernel_access->local_array = &gen->kernel->array[i];
3377 assert(kernel_access->array);
3378 group = kernel_access->array->groups[stmt_access->group];
3379 p = isl_printer_to_str(gen->ctx);
3380 p = print_array_name(p, group);
3381 kernel_access->local_name = isl_printer_get_str(p);
3382 isl_printer_free(p);
3383 tile = group->private_tile;
3384 kernel_access->type = ppcg_access_private;
3385 if (!tile) {
3386 tile = group->shared_tile;
3387 kernel_access->type = ppcg_access_shared;
3390 if (!tile)
3391 kernel_access->type = ppcg_access_global;
3393 n_index = isl_map_dim(stmt_access->access, isl_dim_out);
3394 kernel_access->index = isl_ast_expr_list_alloc(gen->ctx, n_index);
3396 if (n_index == 0)
3397 return;
3399 access = isl_map_copy(stmt_access->access);
3400 access = isl_map_apply_range(isl_map_copy(stmt_it), access);
3401 pma = isl_pw_multi_aff_from_map(access);
3402 pma = isl_pw_multi_aff_coalesce(pma);
3404 for (i = 0; i < n_index; ++i) {
3405 isl_set *domain;
3406 isl_pw_aff *index;
3407 isl_ast_expr *expr;
3409 index = isl_pw_multi_aff_get_pw_aff(pma, i);
3411 if (!kernel_access->array) {
3412 } else if (!tile) {
3413 domain = isl_map_domain(isl_map_copy(stmt_it));
3414 index = isl_pw_aff_coalesce(index);
3415 index = isl_pw_aff_gist(index, domain);
3416 } else {
3417 domain = isl_map_domain(isl_map_copy(stmt_it));
3418 index = shift_index(index, kernel_access->array,
3419 &tile->bound[i], domain,
3420 isl_map_copy(sched2shared));
3423 expr = isl_ast_build_expr_from_pw_aff(build, index);
3425 kernel_access->index = isl_ast_expr_list_add(
3426 kernel_access->index, expr);
3429 isl_pw_multi_aff_free(pma);
3432 /* This function is called for each instance of a user statement
3433 * in the kernel.
3435 * We attach a struct ppcg_kernel_stmt to the "node", containing
3436 * local information about the accesses.
3437 * This information is computed from stmt_it, which expresses the domain
3438 * elements in terms of the generated loops, and sched2shared,
3439 * which expresses the first shared_len dimensions of the schedule
3440 * computed by PPCG in terms of the generated loops.
3442 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3443 __isl_keep isl_ast_build *build, void *user)
3445 struct gpu_gen *gen = (struct gpu_gen *) user;
3446 struct ppcg_kernel_stmt *stmt;
3447 isl_id *id;
3448 isl_map *stmt_it, *sched2shared;
3449 isl_ast_expr *expr, *arg;
3450 isl_union_map *schedule;
3451 int i, n;
3452 struct gpu_stmt_access *access;
3454 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3455 if (!stmt)
3456 return isl_ast_node_free(node);
3458 expr = isl_ast_node_user_get_expr(node);
3459 arg = isl_ast_expr_get_op_arg(expr, 0);
3460 id = isl_ast_expr_get_id(arg);
3462 schedule = isl_ast_build_get_schedule(build);
3463 stmt_it = isl_map_reverse(isl_map_from_union_map(schedule));
3464 sched2shared = compute_sched_to_shared(gen, isl_map_copy(stmt_it));
3466 stmt->type = ppcg_kernel_domain;
3467 stmt->u.d.stmt = find_stmt(gen->prog, id);
3468 if (!stmt->u.d.stmt)
3469 goto error;
3471 n = 0;
3472 for (access = stmt->u.d.stmt->accesses; access; access = access->next)
3473 ++n;
3475 stmt->u.d.access = isl_calloc_array(gen->ctx,
3476 struct ppcg_kernel_access, n);
3477 if (!stmt->u.d.access)
3478 goto error;
3480 stmt->u.d.n_access = n;
3482 access = stmt->u.d.stmt->accesses;
3483 for (i = 0; i < n; ++i, access = access->next) {
3484 compute_index_expression(gen, &stmt->u.d.access[i], access,
3485 stmt_it, sched2shared, build);
3488 isl_id_free(id);
3489 isl_map_free(stmt_it);
3490 isl_map_free(sched2shared);
3491 isl_ast_expr_free(arg);
3492 isl_ast_expr_free(expr);
3494 id = isl_id_alloc(gen->ctx, NULL, stmt);
3495 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3496 return isl_ast_node_set_annotation(node, id);
3497 error:
3498 isl_id_free(id);
3499 isl_map_free(stmt_it);
3500 ppcg_kernel_stmt_free(stmt);
3501 isl_map_free(sched2shared);
3502 return isl_ast_node_free(node);
3505 /* This function is called when code has been generated for the shared
3506 * tile loops. The "schedule" refers only to the original statements.
3508 * We extend the schedule with that part of gen->local_sched that hasn't
3509 * been taken into account yet. This introduces parameters referring
3510 * to thread ids in the schedule, so we add them (with the appropriate
3511 * bounds to the context as well).
3512 * Finally, we set the appropriate unrolling options
3513 * if gen->first_unroll is set.
3515 static __isl_give isl_ast_node *create_domain_leaf(
3516 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
3517 void *user)
3519 struct gpu_gen *gen = (struct gpu_gen *) user;
3520 isl_space *space;
3521 isl_union_map *sched;
3522 isl_ast_node *tree;
3523 isl_set *set;
3524 isl_id_list *iterators;
3525 int n;
3527 schedule = extend_schedule(schedule,
3528 isl_union_map_copy(gen->local_sched),
3529 gen->shared_len, gen->thread_tiled_len);
3531 space = isl_ast_build_get_schedule_space(build);
3532 set = isl_set_universe(space);
3533 set = add_bounded_parameters(set, gen->kernel->n_block,
3534 gen->kernel->block_dim, "t");
3535 build = isl_ast_build_restrict(build, set);
3537 n = gen->thread_tiled_len - gen->shared_len;
3539 if (gen->first_unroll >= 0) {
3540 space = isl_space_set_alloc(gen->ctx, 0, n);
3541 build = set_unroll(build, space, gen->first_unroll);
3543 iterators = generate_names(gen->ctx, n, "c");
3544 build = isl_ast_build_set_iterators(build, iterators);
3545 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
3546 tree = isl_ast_build_ast_from_schedule(build, schedule);
3547 isl_ast_build_free(build);
3549 return tree;
3552 /* This function is called for each statement node in the AST of the code
3553 * for copying to or from shared/private memory.
3554 * Attach a pointer to a ppcg_kernel_stmt representing the copy
3555 * statement to the node.
3556 * The statement name is "read" or "write", depending on whether we are
3557 * reading from global memory or writing to global memory.
3558 * The name of the T space is {shared,private}_<array>.
3560 * The schedule is of the form
3562 * type[A -> T] -> L
3564 * where A refers to a piece of an array and T to the corresponding
3565 * shifted tile. We split this schedule into mappings L -> A and L -> T
3566 * and store the corresponding expressions in stmt->index and stmt->local_index,
3567 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
3569 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
3570 __isl_keep isl_ast_build *build, void *user)
3572 struct gpu_gen *gen = (struct gpu_gen *) user;
3573 struct ppcg_kernel_stmt *stmt;
3574 isl_id *id;
3575 isl_ast_expr *expr;
3576 isl_space *space;
3577 isl_map *access, *local_access, *map;
3578 isl_pw_multi_aff *pma;
3579 const char *type;
3580 int array_index;
3582 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3583 if (!stmt)
3584 return isl_ast_node_free(node);
3586 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
3587 type = isl_map_get_tuple_name(access, isl_dim_in);
3588 stmt->u.c.read = !strcmp(type, "read");
3589 access = isl_map_reverse(access);
3590 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
3591 local_access = isl_map_copy(access);
3593 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
3594 id = isl_map_get_tuple_id(access, isl_dim_out);
3595 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3596 access = isl_map_apply_range(access, map);
3597 pma = isl_pw_multi_aff_from_map(access);
3598 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3599 stmt->u.c.index = expr;
3601 map = isl_map_range_map(isl_map_universe(space));
3602 id = isl_map_get_tuple_id(local_access, isl_dim_out);
3603 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3604 local_access = isl_map_apply_range(local_access, map);
3605 pma = isl_pw_multi_aff_from_map(local_access);
3606 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3607 stmt->u.c.local_index = expr;
3609 stmt->u.c.array = gen->copy_group->array;
3610 array_index = stmt->u.c.array - gen->prog->array;
3611 stmt->u.c.local_array = &gen->kernel->array[array_index];
3612 stmt->type = ppcg_kernel_copy;
3614 id = isl_id_alloc(gen->ctx, NULL, stmt);
3615 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3616 return isl_ast_node_set_annotation(node, id);
3619 /* Given a schedule of the form
3621 * [S -> A] -> L
3623 * (with S the first shared_len dimensions of the computed schedule,
3624 * A the array and L the schedule correponding to the generated loops),
3625 * indicating where the copying the array elements that need to be copied,
3626 * construct code for performing the copying.
3628 * "group" is the array reference group that is being copied
3629 * "type" is either "read" or "write"
3630 * private is set if copying needs to be performed to/from registers
3632 * We first construct a mapping to a shifted tile of the array,
3634 * [S -> A] -> T(S,A) (1)
3636 * If private is set, then we also use this mapping as a schedule
3637 * (which is already thread-specific and will be completely unrolled).
3638 * Otherwise, we wrap/tile the range over the threads.
3639 * The result is
3641 * [S -> A] -> T'(S,A)
3643 * Combined with the given schedule, we have
3645 * [S -> A] -> [L -> T'(S,A)] (2)
3647 * From the shifted tile mapping, we construct a mapping
3649 * [S -> A] -> [A -> T(S,A)]
3651 * and apply it to the schedule (2), obtaining
3653 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
3655 * Note that we can project out S because it is uniquely defined by L.
3657 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
3658 __isl_take isl_map *sched,
3659 const char *type, struct gpu_array_ref_group *group,
3660 __isl_take isl_ast_build *build, int private)
3662 isl_space *space;
3663 isl_ast_node *tree;
3664 isl_map *schedule, *shift, *map;
3665 isl_set *set;
3666 isl_id_list *iterators;
3667 int n;
3669 shift = shift_access(group);
3671 schedule = isl_map_copy(shift);
3672 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
3673 if (!private)
3674 schedule = tile_access_schedule(gen, schedule);
3676 n = isl_map_dim(schedule, isl_dim_out);
3677 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
3678 set = add_bounded_parameters(set, gen->kernel->n_block,
3679 gen->kernel->block_dim, "t");
3681 schedule = isl_map_range_product(sched, schedule);
3683 space = isl_space_domain(isl_map_get_space(shift));
3684 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
3685 map = isl_map_range_product(map, shift);
3687 schedule = isl_map_apply_domain(schedule, map);
3689 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
3691 build = isl_ast_build_restrict(build, set);
3693 gen->copy_group = group;
3695 if (private) {
3696 space = isl_space_range(isl_map_get_space(schedule));
3697 space = isl_space_range(isl_space_unwrap(space));
3698 build = set_unroll(build, space, 0);
3700 iterators = generate_names(gen->ctx, n, "c");
3701 build = isl_ast_build_set_iterators(build, iterators);
3702 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
3703 tree = isl_ast_build_ast_from_schedule(build,
3704 isl_union_map_from_map(schedule));
3705 isl_ast_build_free(build);
3707 return tree;
3710 /* Return code for reading into or writing from shared memory
3711 * the given array reference group.
3713 * If we are performing a read from global memory to shared memory and
3714 * if the array involved is not a scalar, then we copy
3715 * the entire tile to shared memory. This may result in some extra
3716 * elements getting copied, but it should lead to simpler code
3717 * (which means that fewer registers may be needed) and less divergence.
3719 * Otherwise, we only copy the elements that will be read or have been written
3720 * in the kernel.
3723 * The input "sched" is of the form.
3725 * type[S -> A] -> L
3727 * with S the first shared_len dimensions of the computed schedule,
3728 * A the array and L the schedule correponding to the generated loops.
3730 * We first drop "type",
3732 * [S -> A] -> L
3734 * If the above conditions are satisfied, we project out A,
3735 * resulting in
3737 * S -> L
3739 * and then introduce the group tile [S -> T], resulting in
3741 * [S -> T] -> L
3743 static __isl_give isl_ast_node *copy_group_shared_accesses(
3744 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3745 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3747 const char *type;
3748 int read;
3749 isl_union_map *access;
3751 type = isl_map_get_tuple_name(sched, isl_dim_in);
3752 read = !strcmp(type, "read");
3754 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3756 if (read && group->array->n_index > 0) {
3757 isl_space *space;
3758 isl_map *map;
3760 space = isl_space_domain(isl_map_get_space(sched));
3761 space = isl_space_unwrap(space);
3762 map = isl_map_domain_map(isl_map_universe(space));
3763 sched = isl_map_apply_domain(sched, map);
3765 map = group_tile(group);
3766 map = isl_map_reverse(isl_map_domain_map(map));
3767 sched = isl_map_apply_domain(sched, map);
3770 return copy_access(gen, sched, type, group, build, 0);
3773 /* Return code for reading into or writing from private memory
3774 * the given array reference group.
3776 * Let S be the first shared_len dimensions of the computed schedule,
3777 * D the iteration domains, A the array and L the schedule correponding
3778 * to the generated loops.
3779 * "sched" is of the form
3781 * type[S -> A] -> L
3783 * where type is either "read" or "write".
3784 * We apply the privatization D -> S(t), with t the thread ids,
3785 * to the access relation D -> A to obtain the privatized access relation
3787 * S(t) -> A
3789 * We drop the type from "sched" and intersect with the privatized access
3790 * relation to obtain
3792 * [S(t) -> A] -> L
3794 static __isl_give isl_ast_node *copy_group_private_accesses(
3795 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3796 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3798 const char *type;
3799 int read;
3800 isl_union_map *priv;
3801 isl_union_map *access;
3802 isl_map *access_map;
3804 type = isl_map_get_tuple_name(sched, isl_dim_in);
3805 read = !strcmp(type, "read");
3807 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
3808 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3809 priv);
3811 access = group_access_relation(group, read, !read);
3812 access = isl_union_map_apply_domain(access, priv);
3813 access_map = isl_map_from_union_map(access);
3815 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3816 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
3818 return copy_access(gen, sched, type, group, build, 1);
3821 /* Return code for reading into or writing from shared or private memory.
3823 * "schedule" is of the form
3825 * type[S -> A] -> L
3827 * with S be the first shared_len dimensions of the computed schedule,
3828 * A the array and L the schedule correponding to the generated loops.
3829 * The array reference group is attached to "type".
3831 static __isl_give isl_ast_node *create_access_leaf(
3832 struct gpu_gen *gen, __isl_take isl_map *schedule,
3833 __isl_take isl_ast_build *build)
3835 struct gpu_array_ref_group *group;
3836 isl_id *id;
3838 id = isl_map_get_tuple_id(schedule, isl_dim_in);
3839 group = isl_id_get_user(id);
3840 isl_id_free(id);
3842 if (group->private_tile)
3843 return copy_group_private_accesses(gen, group, schedule,
3844 build);
3845 else
3846 return copy_group_shared_accesses(gen, group, schedule,
3847 build);
3850 /* Create a domain node representing a synchronization.
3852 static __isl_give isl_ast_node *create_sync_leaf(
3853 struct gpu_gen *gen, __isl_take isl_map *schedule,
3854 __isl_take isl_ast_build *build)
3856 struct ppcg_kernel_stmt *stmt;
3857 isl_id *id;
3858 isl_space *space;
3859 isl_ast_node *node;
3860 isl_ast_expr *expr;
3862 isl_map_free(schedule);
3864 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3865 if (!stmt)
3866 return NULL;
3868 stmt->type = ppcg_kernel_sync;
3870 space = isl_ast_build_get_schedule_space(build);
3871 space = isl_space_from_domain(space);
3872 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
3873 expr = isl_ast_build_call_from_pw_multi_aff(build,
3874 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
3875 node = isl_ast_node_alloc_user(expr);
3876 isl_ast_build_free(build);
3878 id = isl_id_alloc(gen->ctx, NULL, stmt);
3879 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3880 return isl_ast_node_set_annotation(node, id);
3883 /* This function is called during the code generation at the point
3884 * where the schedule domain element is completely determined by
3885 * the generated code. The input schedule contains the original
3886 * statements as well as synchronization and copy "statements".
3887 * The latter are scheduled at different points than any of the original
3888 * statements, so they will only arrive here in isolation.
3890 * If the current schedule only refers to a single statement,
3891 * we check if it is a copy or synchronization statement and
3892 * call the appropriate functions.
3893 * Otherwise, we assume we are dealing with the original statements
3894 * and we call create_domain_leaf.
3896 static __isl_give isl_ast_node *create_kernel_leaf(
3897 __isl_take isl_ast_build *build, void *user)
3899 struct gpu_gen *gen = (struct gpu_gen *) user;
3900 isl_map *map;
3901 isl_union_map *schedule;
3902 const char *name;
3904 schedule = isl_ast_build_get_schedule(build);
3906 if (isl_union_map_n_map(schedule) != 1)
3907 return create_domain_leaf(schedule, build, user);
3909 map = isl_map_from_union_map(schedule);
3910 name = isl_map_get_tuple_name(map, isl_dim_in);
3911 if (!strcmp(name, "read") || !strcmp(name, "write"))
3912 return create_access_leaf(gen, map, build);
3913 if (!strcmp(name, "sync"))
3914 return create_sync_leaf(gen, map, build);
3916 return create_domain_leaf(isl_union_map_from_map(map), build, user);
3919 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
3920 * have value 0) and all even schedule dimensions as "unroll".
3922 * That is, the options look as follows
3924 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
3925 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
3927 * The even positions are used to be able to schedule copying blocks
3928 * and synchronization before or after each level of the shared memory
3929 * tile loops and we want to make sure that code for these is generated
3930 * separately (within each level).
3932 static __isl_give isl_ast_build *set_atomic_and_unroll(
3933 __isl_take isl_ast_build *build,
3934 __isl_take isl_space *space, int sched_len)
3936 isl_ctx *ctx;
3937 isl_map *map;
3938 isl_constraint *c;
3939 isl_union_map *opt;
3940 isl_local_space *ls;
3941 int i, n;
3943 ctx = isl_ast_build_get_ctx(build);
3945 space = isl_space_params(space);
3946 space = isl_space_add_dims(space, isl_dim_set, sched_len);
3947 space = isl_space_from_domain(space);
3948 space = isl_space_add_dims(space, isl_dim_out, 2);
3949 map = isl_map_universe(isl_space_copy(space));
3950 for (i = 0; i < sched_len; i += 2)
3951 map = isl_map_fix_si(map, isl_dim_in, i, 0);
3952 ls = isl_local_space_from_space(isl_map_get_space(map));
3953 c = isl_equality_alloc(ls);
3954 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3955 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3956 c = isl_constraint_set_constant_si(c, 1);
3957 map = isl_map_add_constraint(map, c);
3958 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3959 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
3960 opt = isl_union_map_from_map(map);
3962 map = isl_map_universe(space);
3963 ls = isl_local_space_from_space(isl_map_get_space(map));
3964 c = isl_equality_alloc(ls);
3965 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3966 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3967 map = isl_map_add_constraint(map, c);
3968 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3969 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
3970 opt = isl_union_map_add_map(opt, map);
3972 build = isl_ast_build_set_options(build, opt);
3974 return build;
3977 /* Return a map that maps a space of dimension gen->shared_len
3978 * to its last dimensions starting at gen->tile_first.
3979 * The range is of dimension
3981 * 2 * (gen->shared_len - gen->tile_first) + 1
3983 * The input dimensions are mapped to the odd dimensions in the output,
3984 * while the even dimensions (except 2*pos) are fixed to 0.
3985 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
3986 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
3987 * are mapped to the output. The remaining input dimensions are projected
3988 * out and the corresponding output dimensions are fixed to 0.
3990 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
3991 __isl_take isl_space *space, int pos, int val)
3993 int i, n;
3994 isl_map *proj;
3996 space = isl_space_set_from_params(space);
3997 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
3998 space = isl_space_map_from_set(space);
3999 proj = isl_map_identity(space);
4000 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4001 n = gen->shared_len - gen->tile_first;
4002 for (i = 0; i <= n; ++i) {
4003 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4004 if (i == pos)
4005 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4006 else
4007 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4010 if (pos < 0)
4011 return proj;
4013 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4014 gen->shared_len - (gen->tile_first + pos));
4015 for (i = pos; i < n; ++i)
4016 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4018 return proj;
4021 /* Given the AST context schedule "schedule" and the mapping from
4022 * domains to the shared tile loops "shared_sched", add a schedule
4023 * for a synchronization operation at position "val" of loop level "pos".
4025 * schedule is of the form
4027 * D -> L
4029 * (with D the iteration domains and L the already generated loops),
4030 * while shared_sched is of the form
4032 * D -> S
4034 * We combine them into
4036 * L -> S
4038 * apply a mapping
4040 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4042 * and use the result as a schedule for "sync".
4044 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4045 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4046 __isl_keep isl_union_map *shared_sched, int pos, int val)
4048 isl_space *space;
4049 isl_map *proj, *map;
4051 shared_sched = isl_union_map_copy(shared_sched);
4052 schedule = isl_union_map_copy(schedule);
4054 space = isl_union_map_get_space(shared_sched);
4055 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4056 map = isl_map_from_union_map(schedule);
4058 proj = insert_even(gen, space, pos, val);
4059 map = isl_map_apply_range(map, proj);
4060 map = isl_map_from_range(isl_map_wrap(map));
4061 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4063 res = isl_union_map_add_map(res, map);
4065 return res;
4068 /* Given the AST context schedule "schedule" and the mapping from
4069 * domains to the shared tile loops "shared_sched", add a schedule
4070 * for copying an array reference group to/from shared/private memory.
4071 * "read" is set if data should be copied from global memory
4072 * to shared/private memory.
4073 * "k" represents the current group
4074 * "s" is the total number of groups
4076 * We schedule an operation before or after the innermost loop
4077 * of "shared_sched" that affects the tile of the array reference group.
4079 * schedule is of the form
4081 * D -> L
4083 * (with D the iteration domains and L the already generated loops),
4084 * while shared_sched is of the form
4086 * D -> S
4088 * We first compute the access relation for the reference group
4090 * D -> A
4092 * and combine it with shared_sched into
4094 * D -> [S -> A]
4096 * If this results in an empty relation, no copying needs to be performed
4097 * at this point.
4098 * Otherwise, we invert the relation and combine it with "schedule" into
4100 * [S -> A] -> L
4102 * The actual additional piece of the schedule is obtained from combining
4104 * [S -> A] -> S
4106 * with a mapping
4108 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4110 * The position of "val" corresponds to the innermost loop that affects
4111 * the tile and the value indicates where the copying is scheduled
4112 * with respect to the actual kernel code (at value 0).
4113 * Reads are schedule before the code, writes to global memory from
4114 * private memory are scheduled at values 1 to s, writes to global
4115 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4117 * If we are scheduling a read from global memory to shared memory,
4118 * we insert a synchronization before the kernel code (at the innermost
4119 * level).
4120 * If we are scheduling a write to global memory, then we add
4121 * a synchronization after all writes (at value 2 *s + 2).
4122 * However, there is no need for a synchronization after the outermost loop.
4123 * A write to global memory from private memory at the innermost level
4124 * does not require a synchronization, because it is covered by
4125 * the synchronization after the kernel inserted by body_schedule.
4127 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4128 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4129 __isl_keep isl_union_map *shared_sched,
4130 struct gpu_array_ref_group *group, int read, int k, int s)
4132 int n;
4133 int pos, val;
4134 isl_space *space;
4135 isl_union_map *access;
4136 isl_map *map, *proj, *access_map;
4137 isl_id *id;
4139 access = group_access_relation(group, read, !read);
4140 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4141 access);
4143 if (isl_union_map_is_empty(access)) {
4144 isl_union_map_free(access);
4145 return res;
4148 access = isl_union_map_reverse(access);
4149 access = isl_union_map_apply_range(access,
4150 isl_union_map_copy(schedule));
4151 access_map = isl_map_from_union_map(access);
4153 space = isl_space_copy(group->array->dim);
4154 space = isl_space_from_range(space);
4155 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4156 map = isl_map_domain_map(isl_map_universe(space));
4158 space = isl_union_map_get_space(schedule);
4159 pos = group->last_shared + 1 - gen->tile_first;
4160 assert(pos >= 0);
4161 if (read)
4162 val = -2 - k;
4163 else if (group->private_tile)
4164 val = 1 + k;
4165 else
4166 val = 1 + s + 1 + k;
4167 proj = insert_even(gen, space, pos, val);
4168 map = isl_map_apply_range(map, proj);
4170 access_map = isl_map_range_product(access_map, map);
4172 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4173 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4175 res = isl_union_map_add_map(res, access_map);
4177 n = gen->shared_len - gen->tile_first;
4178 if (read) {
4179 if (!group->private_tile)
4180 res = add_sync_schedule(gen, res, schedule,
4181 shared_sched, n, -1);
4182 } else {
4183 if (pos == 0)
4184 return res;
4185 if (pos == n && group->private_tile)
4186 return res;
4187 res = add_sync_schedule(gen, res, schedule, shared_sched,
4188 pos, 2 * s + 2);
4191 return res;
4194 /* Return a schedule for the shared tile loops based on the current
4195 * AST context schedule.
4197 * We create a "shared_sched" that maps the domains to the first
4198 * shared_len dimensions of the computed schedule, project out the
4199 * first tile_first dimensions (as these are already covered by
4200 * the host code) and insert "statement-level" dimensions at even
4201 * positions so that we can schedule copy blocks and synchronization
4202 * before/after each level.
4204 * In particular, copy blocks are inserted inside the innermost
4205 * level that affect the tile. For the copying to global memory,
4206 * those from private memory are scheduled before those from shared
4207 * memory such that synchronization can be inserted between the two
4208 * at the innermost level.
4209 * Synchronization is inserted at the innermost level before the
4210 * actual kernel code if there is any copying from global memory
4211 * to shared memory. It is inserted unconditionally at the innermost
4212 * level after the actual kernel code and the copying to global memory
4213 * from private memory (if any). Finally, it is inserted after
4214 * any copying to global memory, except at the outermost level
4215 * and at the innermost level if there is no copying from shared
4216 * memory. The copying from private memory is covered by the unconditional
4217 * synchronization at the innermost level.
4219 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4220 __isl_take isl_union_map *schedule)
4222 isl_space *space;
4223 isl_union_map *res;
4224 isl_union_map *shared_sched;
4225 isl_union_map *sched;
4226 isl_map *proj, *map;
4227 int i, j, k, s;
4229 shared_sched = isl_union_map_copy(gen->tiled_sched);
4230 proj = projection(isl_union_map_get_space(shared_sched),
4231 gen->tiled_len, gen->shared_len);
4232 shared_sched = isl_union_map_apply_range(shared_sched,
4233 isl_union_map_from_map(proj));
4234 space = isl_union_map_get_space(shared_sched);
4235 proj = insert_even(gen, space, -1, 0);
4236 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4237 isl_union_map_from_map(proj));
4239 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4241 s = 0;
4242 for (i = 0; i < gen->prog->n_array; ++i)
4243 s += gen->prog->array[i].n_group;
4245 k = 0;
4246 for (i = 0; i < gen->prog->n_array; ++i) {
4247 struct gpu_array_info *array = &gen->prog->array[i];
4249 for (j = 0; j < array->n_group; ++j) {
4250 struct gpu_array_ref_group *group;
4252 group = array->groups[j];
4253 if (!group->private_tile && !group->shared_tile)
4254 continue;
4255 res = add_group_schedule(gen, res, schedule,
4256 shared_sched, group, 0, k, s);
4257 res = add_group_schedule(gen, res, schedule,
4258 shared_sched, group, 1, k, s);
4259 ++k;
4263 res = add_sync_schedule(gen, res, schedule, shared_sched,
4264 gen->shared_len - gen->tile_first, 1 + s);
4266 isl_union_map_free(shared_sched);
4267 isl_union_map_free(schedule);
4269 return res;
4272 /* Generate code for "kernel" in the given "context".
4274 * We first generate code for the shared tile loops (T1T, T1P and T2)
4275 * in a context that includes the block ids.
4276 * Within each iteration of these loops an additional code generation
4277 * is performed (within create_kernel_leaf) for the rest of the schedule
4278 * in a context that includes the thread ids.
4280 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4281 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4282 __isl_keep isl_multi_pw_aff *grid_size)
4284 isl_space *space;
4285 isl_set *set;
4286 isl_id_list *iterators;
4287 isl_union_map *schedule;
4288 isl_ast_node *tree;
4289 int sched_len;
4291 schedule = isl_ast_build_get_schedule(build);
4293 build = isl_ast_build_copy(build);
4294 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4295 space = isl_ast_build_get_schedule_space(build);
4296 set = isl_set_universe(isl_space_copy(space));
4297 set = add_bounded_parameters_dynamic(set, grid_size, "b");
4298 build = isl_ast_build_restrict(build, set);
4300 schedule = body_schedule(gen, schedule);
4302 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4304 build = set_atomic_and_unroll(build, space, sched_len);
4305 iterators = generate_names(gen->ctx, sched_len, "g");
4306 build = isl_ast_build_set_iterators(build, iterators);
4307 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4308 tree = isl_ast_build_ast_from_schedule(build, schedule);
4309 isl_ast_build_free(build);
4311 return tree;
4314 /* Attach "id" to the given node.
4316 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4317 __isl_keep isl_ast_build *build, void *user)
4319 isl_id *id = user;
4321 node = isl_ast_node_set_annotation(node, id);
4323 return node;
4326 /* Construct an AST node for performing a kernel launch and attach
4327 * the information about the kernel to that node.
4329 * The kernel AST has been constructed in the context of the range
4330 * of "schedule". In particular, the grid size has been computed
4331 * in the context. We therefore still need to make sure that these
4332 * constraints are expressed in the code. We do this by creating a schedule
4334 * kernel[] -> [S -> []]
4336 * where S is the schedule domain, i.e., the range of "schedule".
4337 * The AST generation will then create a single call surrounded by
4338 * all the condition in "S" that have not been expressed yet.
4340 * The kernel information is attached to this node in attach_id.
4342 static __isl_give isl_ast_node *construct_launch(
4343 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
4344 __isl_take struct ppcg_kernel *kernel)
4346 isl_id *id;
4347 isl_ctx *ctx;
4348 isl_union_set *domain;
4349 isl_set *set;
4350 isl_map *map;
4351 isl_ast_node *node;
4353 ctx = isl_ast_build_get_ctx(build);
4355 id = isl_id_alloc(ctx, NULL, kernel);
4356 id = isl_id_set_free_user(id, &ppcg_kernel_free);
4358 domain = isl_union_map_range(schedule);
4359 set = isl_set_from_union_set(domain);
4360 map = isl_map_from_domain(set);
4361 map = isl_map_from_range(isl_map_wrap(map));
4362 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
4363 schedule = isl_union_map_from_map(map);
4365 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
4366 node = isl_ast_build_ast_from_schedule(build, schedule);
4367 isl_ast_build_free(build);
4369 return node;
4372 /* This function is called for each leaf in the AST of the host code.
4373 * We first specialize the schedule to the site of the leaf, compute
4374 * the size of shared memory and then construct the body of host code
4375 * and the associated kernel.
4377 * The necessary information for printing the kernel launch is
4378 * stored in a struct ppcg_kernel and attached to the leaf node
4379 * created to represent the launch.
4381 static __isl_give isl_ast_node *create_host_leaf(
4382 __isl_take isl_ast_build *build, void *user)
4384 struct gpu_gen *gen = (struct gpu_gen *) user;
4385 isl_id *id;
4386 isl_ast_node *node;
4387 struct ppcg_kernel *kernel;
4388 isl_set *host_domain;
4389 isl_union_map *schedule;
4390 isl_union_map *local_sched;
4391 isl_union_map *access;
4392 isl_union_set *domain;
4393 int i;
4395 schedule = isl_ast_build_get_schedule(build);
4397 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
4398 read_sizes(gen);
4400 domain = isl_union_map_domain(isl_union_map_copy(schedule));
4402 local_sched = isl_union_map_copy(gen->sched);
4403 local_sched = isl_union_map_intersect_domain(local_sched, domain);
4404 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
4405 isl_union_map_copy(gen->prog->write));
4406 access = isl_union_map_apply_domain(access,
4407 isl_union_map_copy(local_sched));
4409 gen->tiled_sched = tile_schedule(gen, local_sched);
4410 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
4411 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
4413 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
4414 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
4415 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
4417 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
4418 if (!kernel)
4419 goto error;
4421 kernel->id = gen->kernel_id++;
4422 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
4423 kernel->grid_size = extract_grid_size(gen, kernel);
4424 extract_block_size(gen, kernel);
4425 kernel->arrays = isl_union_map_range(access);
4426 kernel->space = isl_ast_build_get_schedule_space(build);
4428 gen->private_access = NULL;
4429 compute_shared_sched(gen);
4430 gen->privatization = compute_privatization(gen);
4431 group_references(gen);
4432 compute_private_access(gen);
4433 check_shared_memory_bound(gen);
4434 compute_group_tilings(gen);
4435 host_domain = isl_set_from_union_set(isl_union_map_range(
4436 isl_union_map_copy(schedule)));
4437 localize_bounds(gen, kernel, host_domain);
4439 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
4441 kernel->tree = generate_kernel(gen, build, host_domain,
4442 kernel->grid_size);
4443 create_kernel_vars(gen, kernel);
4445 free_local_array_info(gen);
4446 isl_map_free(gen->privatization);
4447 isl_union_map_free(gen->private_access);
4448 isl_union_map_free(gen->local_sched);
4449 isl_union_map_free(gen->tiled_sched);
4450 isl_union_map_free(gen->shared_sched);
4451 isl_union_map_free(gen->shared_proj);
4452 isl_set_free(host_domain);
4453 free(gen->tile_size);
4455 node = construct_launch(build, schedule, kernel);
4457 return node;
4458 error:
4459 isl_union_map_free(schedule);
4460 return NULL;
4463 /* Use isl to generate code for the outer gen->tile_first loops
4464 * of the global schedule in gen->sched, resulting in the host code.
4465 * Within each iteration of this partial schedule, i.e., for each kernel
4466 * launch, create_host_leaf takes care of generating the kernel code.
4468 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
4470 isl_ast_build *build;
4471 isl_ast_node *tree;
4472 isl_union_map *sched;
4473 isl_map *proj;
4474 isl_id_list *iterators;
4476 sched = isl_union_map_copy(gen->sched);
4477 proj = projection(isl_union_map_get_space(sched),
4478 gen->untiled_len, gen->tile_first);
4479 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4481 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
4482 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
4483 iterators = generate_names(gen->ctx, gen->tile_first, "h");
4484 build = isl_ast_build_set_iterators(build, iterators);
4485 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
4486 tree = isl_ast_build_ast_from_schedule(build, sched);
4487 isl_ast_build_free(build);
4489 return tree;
4492 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
4494 if (!str)
4495 return NULL;
4496 return isl_union_map_read_from_str(ctx, str);
4499 /* Information about the outermost tilable bands in the forest of bands.
4501 * tile_len and n_parallel are only sets on band_info structures
4502 * that correspond to outermost bands. For other bands (in particular,
4503 * ancestors of the outermost bands), n_parallal is set to 0.
4505 * prefix is the (padded) schedule leading up to the outermost tilable bands.
4507 * tile_first is the number of schedule dimensions in prefix.
4509 * suffix is the schedule of the outermost tilable bands and their descendants.
4511 struct band_info {
4512 struct gpu_gen *gen;
4513 int tile_first;
4514 int tile_len;
4515 int n_parallel;
4516 isl_union_map *prefix;
4517 isl_union_map *suffix;
4520 /* Set tile_len and n_parallel of the statement to that of
4521 * their outermost band, recorded in the band_info.
4523 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
4525 struct band_info *info = user;
4526 struct gpu_stmt *stmt;
4527 isl_id *id;
4529 id = isl_map_get_tuple_id(map, isl_dim_in);
4530 stmt = find_stmt(info->gen->prog, id);
4531 isl_id_free(id);
4533 stmt->tile_len = info->tile_len;
4534 stmt->n_parallel = info->n_parallel;
4536 isl_map_free(map);
4538 return 0;
4541 static void list_select_outer_band(struct gpu_gen *gen,
4542 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
4544 /* Check if this band has any parallel loops. If so, take it as
4545 * the outermost tilable band. If not, continue looking for the
4546 * outermost tilable band in the children of the current band.
4548 static void band_select_outer_band(struct gpu_gen *gen,
4549 __isl_take isl_band *band, int pos, struct band_info *info)
4551 int n = isl_band_n_member(band);
4552 int n_parallel;
4554 for (n_parallel = 0; n_parallel < n; ++n_parallel)
4555 if (!isl_band_member_is_zero_distance(band, n_parallel))
4556 break;
4558 info->n_parallel = n_parallel;
4559 if (n_parallel) {
4560 gen->any_parallelism = 1;
4561 info->gen = gen;
4562 info->tile_first = pos;
4563 info->tile_len = n;
4564 info->prefix = isl_band_get_prefix_schedule(band);
4565 info->suffix = isl_union_map_flat_range_product(
4566 isl_band_get_partial_schedule(band),
4567 isl_band_get_suffix_schedule(band));
4568 isl_union_map_foreach_map(info->prefix,
4569 &set_stmt_tile_len, info);
4570 } else if (isl_band_has_children(band)) {
4571 isl_band_list *children;
4572 children = isl_band_get_children(band);
4573 list_select_outer_band(gen, children, pos + n, info);
4574 } else {
4575 info->gen = gen;
4576 info->tile_first = pos + n;
4577 info->tile_len = 0;
4578 info->prefix = isl_union_map_flat_range_product(
4579 isl_band_get_prefix_schedule(band),
4580 isl_band_get_partial_schedule(band));
4581 info->suffix = isl_band_get_suffix_schedule(band);
4582 isl_union_map_foreach_map(info->prefix,
4583 &set_stmt_tile_len, info);
4586 isl_band_free(band);
4589 /* Comparison function that returns a non-zero value for band_infos
4590 * with different tile_len fields or different n_parallel fields.
4592 static int cmp_band(const void *p1, const void *p2)
4594 const struct band_info *info1 = p1;
4595 const struct band_info *info2 = p2;
4597 if (info1->tile_len != info2->tile_len)
4598 return info1->tile_len - info2->tile_len;
4600 return info1->n_parallel - info2->n_parallel;
4603 /* Extend "umap" with coordinates with fixed value "val"
4604 * to a total length of "dst_len", assuming the original dimension is "src_len".
4606 static __isl_give isl_union_map *extend_range(
4607 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
4609 isl_space *dim;
4610 isl_map *map;
4611 int i;
4613 dim = isl_union_map_get_space(umap);
4614 map = isl_map_reverse(projection(dim, dst_len, src_len));
4615 for (i = src_len; i < dst_len; ++i)
4616 map = isl_map_fix_si(map, isl_dim_out, i, val);
4618 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
4620 return umap;
4623 /* Group bands with the same values for tile_len and n_parallel.
4624 * The prefix schedule is then extended with a fixed coordinate that
4625 * is different for each such group.
4626 * Note that the actual values for this coordinate are not important.
4627 * The bands have already been effectively separated at a higher level
4628 * or they are independent and may be executed in parallel.
4629 * The list of band_info has been sorted before this functions is called.
4631 static void separate_bands(struct band_info *info, int n)
4633 int i;
4634 int j = 0;
4636 for (i = 0; i < n; ++i) {
4637 int l = info[i].tile_first;
4639 if (i &&
4640 (info[i].tile_len != info[i - 1].tile_len ||
4641 info[i].n_parallel != info[i - 1].n_parallel))
4642 j++;
4644 info[i].prefix = extend_range(info[i].prefix,
4645 l, l + 1, j);
4646 info[i].tile_first = l + 1;
4650 /* Select the outermost bands in the elements of the list, align
4651 * their prefix schedules, separate bands with different values
4652 * for tile_len and/or n_parallel and then combine the resulting
4653 * prefix and suffix schedules into a single pair of prefix and
4654 * suffix schedules for the entire list.
4656 static void list_select_outer_band(struct gpu_gen *gen,
4657 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
4659 isl_band *band;
4660 int i;
4661 int n = isl_band_list_n_band(list);
4662 isl_ctx *ctx = isl_band_list_get_ctx(list);
4663 struct band_info *info;
4664 int max_tile_first;
4665 isl_union_map *prefix;
4666 isl_union_map *suffix;
4668 assert(n >= 1);
4669 info = isl_calloc_array(ctx, struct band_info, n);
4670 assert(info);
4672 max_tile_first = 0;
4673 for (i = 0; i < n; ++i) {
4674 band = isl_band_list_get_band(list, i);
4675 band_select_outer_band(gen, band, pos, &info[i]);
4676 if (info[i].tile_first > max_tile_first)
4677 max_tile_first = info[i].tile_first;
4680 for (i = 0; i < n; ++i) {
4681 if (info[i].tile_first == max_tile_first)
4682 continue;
4683 info[i].prefix = extend_range(info[i].prefix,
4684 info[i].tile_first, max_tile_first, 0);
4685 info[i].tile_first = max_tile_first;
4688 qsort(info, n, sizeof(struct band_info), &cmp_band);
4690 for (i = 0; i < n - 1; ++i)
4691 if (info[i].tile_len != info[i + 1].tile_len ||
4692 info[i].n_parallel != info[i + 1].n_parallel)
4693 break;
4695 if (i < n -1)
4696 separate_bands(info, n);
4698 prefix = info[0].prefix;
4699 suffix = info[0].suffix;
4701 for (i = 1; i < n; ++i) {
4702 prefix = isl_union_map_union(prefix, info[i].prefix);
4703 suffix = isl_union_map_union(suffix, info[i].suffix);
4706 list_info->tile_first = info[0].tile_first;
4707 list_info->tile_len = -1;
4708 list_info->prefix = prefix;
4709 list_info->suffix = suffix;
4711 isl_band_list_free(list);
4712 free(info);
4715 /* Select the outermost tilable band that (by construction)
4716 * has at least one parallel loop.
4717 * The starting position of the aligned band is stored in the pair
4718 * gen->tile_first.
4719 * The sizes and number of parallel loops may be different in different
4720 * parts of the band forest and are therefore stored in the gpu_stmts.
4722 * Return the complete schedule, with the tilable bands aligned
4723 * at gen->tile_first and padded with zero, if needed.
4725 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
4726 __isl_keep isl_schedule *schedule)
4728 isl_band_list *list;
4729 struct band_info info;
4731 gen->n_parallel = 0;
4732 gen->tile_len = -1;
4734 list = isl_schedule_get_band_forest(schedule);
4736 list_select_outer_band(gen, list, 0, &info);
4738 gen->tile_first = info.tile_first;
4739 info.suffix = align_range(info.suffix);
4741 return isl_union_map_flat_range_product(info.prefix, info.suffix);
4744 /* Set gen->untiled_len to the number of scheduling dimensions
4745 * for the schedule of the first domain.
4746 * We assume here that this number is the same for all domains.
4748 static int set_untiled_len(__isl_take isl_map *map, void *user)
4750 unsigned *untiled_len = user;
4752 *untiled_len = isl_map_dim(map, isl_dim_out);
4754 isl_map_free(map);
4755 return -1;
4758 /* Compute an appropriate schedule based on the accesses in
4759 * gen->read and gen->write.
4761 * We use the dependences in gen->prog->scop to compute
4762 * a schedule that has a parallel loop in each tilable band.
4763 * Finally, we select the outermost tilable band.
4765 static void compute_schedule(struct gpu_gen *gen)
4767 isl_union_set *domain;
4768 isl_union_map *dep_raw, *dep;
4769 isl_union_map *sched;
4770 isl_schedule *schedule;
4772 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4774 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4775 dep = isl_union_map_union(dep, dep_raw);
4776 dep = isl_union_map_coalesce(dep);
4778 domain = isl_union_set_copy(gen->prog->scop->domain);
4779 domain = isl_union_set_intersect_params(domain,
4780 isl_set_copy(gen->prog->scop->context));
4781 schedule = isl_union_set_compute_schedule(isl_union_set_copy(domain),
4782 isl_union_map_copy(dep), dep);
4783 if (gen->options->debug->dump_schedule)
4784 isl_schedule_dump(schedule);
4786 sched = select_outer_tilable_band(gen, schedule);
4788 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
4789 sched = isl_union_map_intersect_domain(sched, domain);
4790 gen->sched = sched;
4792 isl_schedule_free(schedule);
4795 /* Compute the sets of array elements that need to be copied in and out.
4797 * In particular, for each array that is written anywhere in gen->prog and
4798 * that is visible outside the corresponding scop, we copy out its entire
4799 * extent.
4801 * Any array elements that is read without first being written needs
4802 * to be copied in. Furthermore, if there are any array elements that
4803 * are copied out, but that are not written inside gen->prog, then
4804 * they also need to be copied in to ensure that the value after execution
4805 * is the same as the value before execution.
4806 * While computing the set of array elements that
4807 * are copied out but not written, we intersect both sets with the context.
4808 * This helps in those cases where the arrays are declared with a fixed size,
4809 * while the accesses are parametric and the context assigns a fixed value
4810 * to the parameters.
4812 static void compute_copy_in_and_out(struct gpu_gen *gen)
4814 int i;
4815 isl_union_set *write;
4816 isl_union_set *copy_in, *copy_out;
4817 isl_union_set *not_written;
4818 isl_union_map *uninitialized;
4820 write = isl_union_map_range(isl_union_map_copy(gen->prog->write));
4821 write = isl_union_set_intersect_params(write,
4822 isl_set_copy(gen->prog->context));
4823 copy_out = isl_union_set_empty(isl_union_set_get_space(write));
4825 for (i = 0; i < gen->prog->n_array; ++i) {
4826 isl_space *space;
4827 isl_set *write_i;
4828 int empty;
4830 if (gen->prog->array[i].local)
4831 continue;
4833 space = isl_space_copy(gen->prog->array[i].dim);
4834 write_i = isl_union_set_extract_set(write, space);
4835 empty = isl_set_fast_is_empty(write_i);
4836 isl_set_free(write_i);
4837 if (empty)
4838 continue;
4840 write_i = isl_set_copy(gen->prog->array[i].extent);
4841 copy_out = isl_union_set_add_set(copy_out, write_i);
4844 copy_out = isl_union_set_intersect_params(copy_out,
4845 isl_set_copy(gen->prog->context));
4847 gen->prog->copy_out = isl_union_set_copy(copy_out);
4849 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
4850 copy_in = isl_union_map_range(uninitialized);
4852 not_written = isl_union_set_subtract(copy_out, write);
4853 copy_in = isl_union_set_union(copy_in, not_written);
4854 gen->prog->copy_in = copy_in;
4857 static struct gpu_stmt_access **expr_extract_access(struct pet_expr *expr,
4858 struct gpu_stmt_access **next_access)
4860 struct gpu_stmt_access *access;
4861 isl_ctx *ctx = isl_map_get_ctx(expr->acc.access);
4863 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4864 assert(access);
4865 access->next = NULL;
4866 access->read = expr->acc.read;
4867 access->write = expr->acc.write;
4868 access->access = isl_map_copy(expr->acc.access);
4869 access->ref_id = isl_id_copy(expr->acc.ref_id);
4871 *next_access = access;
4872 next_access = &(*next_access)->next;
4873 return next_access;
4876 static struct gpu_stmt_access **expr_extract_accesses(struct pet_expr *expr,
4877 struct gpu_stmt_access **next_access)
4879 int i;
4881 for (i = 0; i < expr->n_arg; ++i)
4882 next_access = expr_extract_accesses(expr->args[i],
4883 next_access);
4885 if (expr->type == pet_expr_access)
4886 next_access = expr_extract_access(expr, next_access);
4888 return next_access;
4891 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
4893 struct gpu_stmt_access **next_access = &stmt->accesses;
4895 stmt->accesses = NULL;
4896 expr_extract_accesses(stmt->body, next_access);
4899 /* Return an array of gpu_stmt representing the statements in "scop".
4901 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4902 __isl_keep isl_set *context)
4904 int i;
4905 struct gpu_stmt *stmts;
4907 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
4908 if (!stmts)
4909 return NULL;
4911 for (i = 0; i < scop->n_stmt; ++i) {
4912 struct gpu_stmt *s = &stmts[i];
4914 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
4915 s->body = scop->stmts[i]->body;
4916 pet_stmt_extract_accesses(s);
4919 return stmts;
4922 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
4924 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
4926 struct gpu_gen *gen = user;
4928 return gen->print(p, gen->prog, gen->tree, gen->print_user);
4931 /* Replace the scop in the "input" file by equivalent code
4932 * that uses the GPU and print the result to "out".
4933 * "scop" is assumed to correspond to this scop.
4934 * The code before the scop is first copied to "out",
4935 * then the transformed scop is printed and finally
4936 * the code after the scop is copied to "out".
4937 * After generating an AST for the transformed scop as explained below,
4938 * we call "print" to print the AST in the desired output format
4939 * to a printer hooked up to "out".
4941 * If it turns out that it does not make sense to generate GPU code,
4942 * then we generate CPU code instead.
4944 * The GPU code is generated in a context where at least one
4945 * statement instance is executed. The corresponding guard (if any) is printed
4946 * around the entire generated GPU code, except for the declaration
4947 * of the arrays that are visible outside of the scop and that therefore
4948 * cannot be declared inside the body of any possible guard.
4950 * We first compute a schedule that respects the dependences
4951 * of the original program and select the outermost band
4952 * of tilable dimensions that has at least one parallel loop.
4953 * We then have three blocks of dimensions
4955 * H B G
4957 * The tilable band "B" is first tiled according to "tile" sizes, resulting
4958 * in
4960 * H T P G
4962 * For each iteration of the T loop and for each array, we compute
4963 * the array elements accessed by that iteration, construct a rectangular
4964 * box around it and shift it to the origin. The result is used
4965 * as shared memory for the array.
4967 * We then split off at most 2 parallel loops from the T loops and
4968 * at most 3 parallel loops from the P loops
4970 * H T1 T2 P1 P2 G
4972 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
4973 * according to "grid"/"block" sizes.
4975 * H T1T T1P T2 P1T P1P P2 G
4977 * Finally, the T1P and P1P iterators are equated to the block and
4978 * thread dimensions respectively and so are effectively removed.
4979 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
4980 * are run on the GPU.
4982 * Code is generated in three stages. We first generate code for the
4983 * host (the H loops), with iterators h%d. Then, for each leaf node
4984 * of the resulting AST, we generate code for the shared loops (up to
4985 * and including T2), with iterators g%d and after equating the H loops
4986 * to h%d parameters and the T1P loops to the block dimensions.
4987 * Finally, we generate code for the remaining loops in a similar fashion.
4989 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
4990 struct ppcg_scop *scop, struct ppcg_options *options,
4991 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
4992 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
4993 void *user), void *user)
4995 struct gpu_gen gen;
4996 struct gpu_prog *prog;
4997 isl_set *context, *guard;
4998 isl_printer *p;
4999 FILE *in;
5001 if (!scop)
5002 return -1;
5004 in = fopen(input, "r");
5005 copy(in, out, 0, scop->start);
5007 prog = gpu_prog_alloc(ctx, scop);
5008 if (!prog)
5009 return -1;
5011 p = isl_printer_to_file(ctx, out);
5012 p = isl_printer_set_output_format(p, ISL_FORMAT_C);
5014 context = isl_set_copy(prog->context);
5015 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5016 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5018 gen.ctx = ctx;
5019 gen.prog = prog;
5020 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5021 gen.options = options;
5023 gen.any_parallelism = 0;
5024 compute_schedule(&gen);
5026 if (!gen.any_parallelism) {
5027 isl_set_free(context);
5028 isl_set_free(guard);
5029 p = print_cpu(p, scop, options);
5030 } else {
5031 compute_copy_in_and_out(&gen);
5033 gen.kernel_id = 0;
5034 gen.print = print;
5035 gen.print_user = user;
5036 gen.tree = generate_host_code(&gen);
5037 p = ppcg_print_exposed_declarations(p, prog->scop);
5038 p = ppcg_print_guarded(p, guard, context, &print_gpu, &gen);
5039 isl_ast_node_free(gen.tree);
5042 clear_gpu_gen(&gen);
5044 isl_printer_free(p);
5046 gpu_prog_free(prog);
5048 copy(in, out, scop->end, -1);
5049 fclose(in);
5051 return p ? 0 : -1;
5054 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5056 struct gpu_prog *prog;
5058 if (!scop)
5059 return NULL;
5061 prog = isl_calloc_type(ctx, struct gpu_prog);
5062 assert(prog);
5064 prog->ctx = ctx;
5065 prog->scop = scop;
5066 prog->context = isl_set_copy(scop->context);
5067 prog->n_stmts = scop->n_stmt;
5068 prog->stmts = extract_stmts(ctx, scop, prog->context);
5069 prog->read = isl_union_map_copy(scop->reads);
5070 prog->write = isl_union_map_copy(scop->writes);
5072 if (!prog->stmts)
5073 return gpu_prog_free(prog);
5075 collect_array_info(prog);
5077 return prog;
5080 void *gpu_prog_free(struct gpu_prog *prog)
5082 if (!prog)
5083 return NULL;
5084 free_array_info(prog);
5085 free_stmts(prog->stmts, prog->n_stmts);
5086 isl_union_set_free(prog->copy_in);
5087 isl_union_set_free(prog->copy_out);
5088 isl_union_map_free(prog->read);
5089 isl_union_map_free(prog->write);
5090 isl_set_free(prog->context);
5091 free(prog);
5092 return NULL;