README: add PPCG paper bibtex entry
[ppcg.git] / gpu.c
bloba0a24d10d4a500c8a99d842c69cdb71a984d449b
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 struct gpu_array_tile {
67 int n;
68 struct gpu_array_bound *bound;
71 struct gpu_array_info;
73 /* A group of array references in a kernel that should be handled together.
74 * If private_tile is not NULL, then it is mapped to registers.
75 * Otherwise, if shared_tile is not NULL, it is mapped to shared memory.
76 * Otherwise, it is accessed from global memory.
78 struct gpu_array_ref_group {
79 /* The references in this group access this array. */
80 struct gpu_array_info *array;
81 /* Position of this group in the list of reference groups of array. */
82 int nr;
84 /* The following fields are use during the construction of the groups.
85 * access is the combined access relation relative to the shared
86 * memory tiling. In particular, the domain of the map corresponds
87 * to the first shared_len dimensions of the computed schedule.
88 * write is set if any access in the group is a write.
90 isl_map *access;
91 int write;
93 /* The shared memory tile, NULL if none. */
94 struct gpu_array_tile *shared_tile;
96 /* The private memory tile, NULL if none. */
97 struct gpu_array_tile *private_tile;
99 /* References in this group; point to elements of a linked list. */
100 int n_ref;
101 struct gpu_stmt_access **refs;
103 /* Last shared memory tile dimension that affects tile of this group. */
104 int last_shared;
107 struct gpu_gen {
108 isl_ctx *ctx;
109 struct ppcg_options *options;
111 /* Callback for printing of AST in appropriate format. */
112 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
113 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
114 void *user);
115 void *print_user;
117 struct gpu_prog *prog;
118 /* The generated AST. */
119 isl_ast_node *tree;
121 /* tile, grid and block sizes for each kernel */
122 isl_union_map *sizes;
124 /* Identifier of current kernel. */
125 int kernel_id;
126 /* Pointer to the current kernel. */
127 struct ppcg_kernel *kernel;
128 /* Does the computed schedule exhibit any parallelism? */
129 int any_parallelism;
131 /* First tile dimension. */
132 int tile_first;
133 /* Number of tile dimensions. */
134 int tile_len;
135 /* Number of initial parallel loops among tile dimensions. */
136 int n_parallel;
138 /* Number of dimensions determining shared memory. */
139 int shared_len;
141 /* Number of rows in the untiled schedule. */
142 int untiled_len;
143 /* Number of rows in the tiled schedule. */
144 int tiled_len;
145 /* Number of rows in schedule after tiling/wrapping over threads. */
146 int thread_tiled_len;
148 /* Global untiled schedule. */
149 isl_union_map *sched;
150 /* Local (per kernel launch) tiled schedule. */
151 isl_union_map *tiled_sched;
152 /* Local schedule per shared memory tile loop iteration. */
153 isl_union_map *local_sched;
155 /* Local tiled schedule projected onto the shared tile loops and
156 * the loops that will be wrapped over the threads,
157 * with all shared tile loops parametrized.
159 isl_union_map *shared_sched;
160 /* Projects out the loops that will be wrapped over the threads
161 * from shared_sched.
163 isl_union_map *shared_proj;
165 /* A map that takes the range of shared_sched as input,
166 * wraps the appropriate loops over the threads and then projects
167 * out these loops.
169 isl_map *privatization;
171 /* A map from the shared memory tile loops and the thread indices
172 * (as parameters) to the set of accessed memory elements that
173 * will be accessed through private copies.
175 isl_union_map *private_access;
177 /* The schedule for the current private/shared access
178 * (within print_private_access or print_shared_access).
180 isl_map *copy_sched;
181 /* The array reference group corresponding to copy_sched. */
182 struct gpu_array_ref_group *copy_group;
184 /* First loop to unroll (or -1 if none) in the current part of the
185 * schedule.
187 int first_unroll;
189 int n_grid;
190 int n_block;
191 /* Note: in the input file, the sizes of the grid and the blocks
192 * are specified in the order x, y, z, but internally, the sizes
193 * are stored in reverse order, so that the last element always
194 * refers to the x dimension.
196 int grid_dim[2];
197 int block_dim[3];
198 int *tile_size;
201 /* Print the name of the local copy of a given group of array references.
203 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
204 struct gpu_array_ref_group *group)
206 int global = 0;
208 if (group->private_tile)
209 p = isl_printer_print_str(p, "private_");
210 else if (group->shared_tile)
211 p = isl_printer_print_str(p, "shared_");
212 else
213 global = 1;
214 p = isl_printer_print_str(p, group->array->name);
215 if (!global && group->array->n_group > 1) {
216 p = isl_printer_print_str(p, "_");
217 p = isl_printer_print_int(p, group->nr);
220 return p;
223 /* Collect all references to the given array and store pointers to them
224 * in array->refs.
226 static void collect_references(struct gpu_prog *prog,
227 struct gpu_array_info *array)
229 int i;
230 int n;
232 n = 0;
233 for (i = 0; i < prog->n_stmts; ++i) {
234 struct gpu_stmt *stmt = &prog->stmts[i];
235 struct gpu_stmt_access *access;
237 for (access = stmt->accesses; access; access = access->next) {
238 const char *name;
239 name = isl_map_get_tuple_name(access->access,
240 isl_dim_out);
241 if (name && !strcmp(array->name, name))
242 n++;
246 array->n_ref = n;
247 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
248 assert(array->refs);
250 n = 0;
251 for (i = 0; i < prog->n_stmts; ++i) {
252 struct gpu_stmt *stmt = &prog->stmts[i];
253 struct gpu_stmt_access *access;
255 for (access = stmt->accesses; access; access = access->next) {
256 const char *name;
257 name = isl_map_get_tuple_name(access->access,
258 isl_dim_out);
259 if (!name || strcmp(array->name, name))
260 continue;
262 array->refs[n++] = access;
267 /* Create a gpu_array_tile for an array of dimension "n_index".
269 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
271 int i;
272 struct gpu_array_tile *tile;
274 tile = isl_calloc_type(ctx, struct gpu_array_tile);
275 assert(tile);
277 tile->n = n_index;
279 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
280 assert(tile->bound);
282 for (i = 0; i < n_index; ++i) {
283 tile->bound[i].size = NULL;
284 tile->bound[i].lb = NULL;
285 tile->bound[i].stride = NULL;
286 tile->bound[i].shift = NULL;
287 tile->bound[i].shift_map = NULL;
290 return tile;
293 static void *free_tile(struct gpu_array_tile *tile)
295 int j;
297 if (!tile)
298 return NULL;
300 for (j = 0; j < tile->n; ++j) {
301 isl_val_free(tile->bound[j].size);
302 isl_val_free(tile->bound[j].stride);
303 isl_aff_free(tile->bound[j].lb);
304 isl_aff_free(tile->bound[j].shift);
305 isl_basic_map_free(tile->bound[j].shift_map);
307 free(tile->bound);
308 free(tile);
310 return NULL;
313 static struct pet_array *find_array(struct ppcg_scop *scop,
314 __isl_keep isl_set *accessed)
316 int i;
317 isl_id *id;
319 id = isl_set_get_tuple_id(accessed);
321 for (i = 0; i < scop->n_array; ++i) {
322 isl_id *id_i;
324 id_i = isl_set_get_tuple_id(scop->arrays[i]->extent);
325 isl_id_free(id_i);
326 if (id == id_i)
327 break;
329 isl_id_free(id);
331 return i < scop->n_array ? scop->arrays[i] : NULL;
334 /* Compute and return the extent of "array", taking into account the set of
335 * accessed elements.
337 * In particular, the extent in the outer dimension is taken
338 * from "accessed", while then extent in the remaing dimensions
339 * are taken from array->extent.
341 * The extent in the outer dimension cannot be taken from array->extent
342 * because that may be unbounded. Furthermore, even if it is bounded,
343 * it may be larger than the piece of the array that is being accessed.
345 static __isl_give isl_set *compute_extent(struct pet_array *array,
346 __isl_keep isl_set *accessed)
348 int n_index;
349 isl_id *id;
350 isl_set *outer;
351 isl_set *extent;
353 extent = isl_set_copy(array->extent);
355 n_index = isl_set_dim(accessed, isl_dim_set);
356 if (n_index == 0)
357 return extent;
359 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
360 outer = isl_set_copy(accessed);
361 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
362 extent = isl_set_flat_product(outer, extent);
363 id = isl_set_get_tuple_id(accessed);
364 extent = isl_set_set_tuple_id(extent, id);
366 return extent;
369 /* Compute bounds on the host arrays based on the accessed elements
370 * and collect all references to the array.
372 * If the array is zero-dimensional, i.e., a scalar, we check
373 * whether it is read-only.
375 static int extract_array_info(__isl_take isl_set *array, void *user)
377 int i;
378 struct gpu_prog *prog = (struct gpu_prog *)user;
379 const char *name;
380 int n_index;
381 isl_pw_aff **bounds;
382 struct pet_array *pa;
383 isl_set *extent;
385 n_index = isl_set_dim(array, isl_dim_set);
386 name = isl_set_get_tuple_name(array);
387 bounds = isl_alloc_array(isl_set_get_ctx(array),
388 isl_pw_aff *, n_index);
389 assert(bounds);
390 prog->array[prog->n_array].dim = isl_set_get_space(array);
391 prog->array[prog->n_array].name = strdup(name);
392 prog->array[prog->n_array].n_index = n_index;
393 prog->array[prog->n_array].bound = bounds;
395 pa = find_array(prog->scop, array);
396 assert(pa);
398 prog->array[prog->n_array].type = strdup(pa->element_type);
399 prog->array[prog->n_array].size = pa->element_size;
400 prog->array[prog->n_array].local = pa->declared && !pa->exposed;
402 if (n_index == 0) {
403 isl_set *space;
404 isl_union_map *write;
405 int empty;
407 write = isl_union_map_copy(prog->write);
408 space = isl_set_universe(isl_set_get_space(array));
409 write = isl_union_map_intersect_range(write,
410 isl_union_set_from_set(space));
411 empty = isl_union_map_is_empty(write);
412 isl_union_map_free(write);
414 prog->array[prog->n_array].read_only = empty;
417 extent = compute_extent(pa, array);
418 for (i = 0; i < n_index; ++i) {
419 isl_set *dom;
420 isl_local_space *ls;
421 isl_aff *one;
422 isl_pw_aff *bound;
424 bound = isl_set_dim_max(isl_set_copy(extent), i);
425 assert(bound);
426 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
427 ls = isl_local_space_from_space(isl_set_get_space(dom));
428 one = isl_aff_zero_on_domain(ls);
429 one = isl_aff_add_constant_si(one, 1);
430 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
431 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
433 bounds[i] = bound;
435 prog->array[prog->n_array].extent = extent;
437 collect_references(prog, &prog->array[prog->n_array]);
439 prog->n_array++;
441 isl_set_free(array);
442 return 0;
445 void collect_array_info(struct gpu_prog *prog)
447 isl_union_set *arrays;
449 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
450 arrays = isl_union_set_union(arrays,
451 isl_union_map_range(isl_union_map_copy(prog->write)));
452 arrays = isl_union_set_coalesce(arrays);
454 prog->n_array = isl_union_set_n_set(arrays);
455 prog->array = isl_alloc_array(prog->ctx,
456 struct gpu_array_info, prog->n_array);
457 assert(prog->array);
458 prog->n_array = 0;
459 isl_union_set_foreach_set(arrays, &extract_array_info, prog);
460 isl_union_set_free(arrays);
463 static void free_array_info(struct gpu_prog *prog)
465 int i, j;
467 for (i = 0; i < prog->n_array; ++i) {
468 int n_index = prog->array[i].n_index;
469 free(prog->array[i].type);
470 free(prog->array[i].name);
471 for (j = 0; j < n_index; ++j)
472 isl_pw_aff_free(prog->array[i].bound[j]);
473 isl_space_free(prog->array[i].dim);
474 isl_set_free(prog->array[i].extent);
475 free(prog->array[i].bound);
476 free(prog->array[i].refs);
478 free(prog->array);
481 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
482 * as an array or through a pointer reference, but as single data element. At
483 * the moment, scalars are represented as zero dimensional arrays.
485 int gpu_array_is_scalar(struct gpu_array_info *array)
487 return (array->n_index == 0);
490 /* Is "array" a read-only scalar?
492 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
494 return gpu_array_is_scalar(array) && array->read_only;
497 /* Internal data structure for extract_size_of_type.
498 * "type" specifies the name of the space that we want to extract.
499 * "res" is used to store the subset of that space.
501 struct ppcg_extract_size_data {
502 const char *type;
503 isl_set *res;
506 /* This function is called for each set in a union_set.
507 * If the name of the set matches data->type, we store the
508 * set in data->res.
510 static int extract_size_of_type(__isl_take isl_set *size, void *user)
512 struct ppcg_extract_size_data *data = user;
513 const char *name;
515 name = isl_set_get_tuple_name(size);
516 if (name && !strcmp(name, data->type)) {
517 data->res = size;
518 return -1;
521 isl_set_free(size);
522 return 0;
525 /* Given a union map { kernel[i] -> *[...] },
526 * return the range in the space called "type" for the kernel with
527 * sequence number "id".
529 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
530 const char *type, int id)
532 isl_space *space;
533 isl_set *dom;
534 isl_union_set *local_sizes;
535 struct ppcg_extract_size_data data = { type, NULL };
537 if (!sizes)
538 return NULL;
540 space = isl_union_map_get_space(sizes);
541 space = isl_space_set_from_params(space);
542 space = isl_space_add_dims(space, isl_dim_set, 1);
543 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
544 dom = isl_set_universe(space);
545 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
547 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
548 isl_union_map_copy(sizes));
549 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
550 isl_union_set_free(local_sizes);
551 return data.res;
554 /* Given a singleton set, extract the first (at most *len) elements
555 * of the single integer tuple into *sizes and update *len if needed.
557 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
559 int i;
560 int dim;
562 if (!set)
563 return;
565 dim = isl_set_dim(set, isl_dim_set);
566 if (dim < *len)
567 *len = dim;
569 for (i = 0; i < *len; ++i) {
570 isl_val *v;
572 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
573 assert(v);
575 sizes[i] = isl_val_get_num_si(v);
576 isl_val_free(v);
579 isl_set_free(set);
582 /* Extract user specified "tile" sizes from the "sizes" command line option,
583 * defaulting to option->tile_size in each dimension.
585 static void read_tile_sizes(struct gpu_gen *gen)
587 int n;
588 isl_set *size;
590 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
591 assert(gen->tile_size);
592 for (n = 0; n < gen->tile_len; ++n)
593 gen->tile_size[n] = gen->options->tile_size;
595 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
596 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
598 if (gen->n_parallel > gen->tile_len)
599 gen->n_parallel = gen->tile_len;
602 /* Extract user specified "block" sizes from the "sizes" command line option,
603 * after filling in some potentially useful defaults.
605 static void read_block_sizes(struct gpu_gen *gen)
607 int n;
608 isl_set *size;
610 n = gen->n_parallel;
611 gen->n_block = (n <= 3) ? n : 3;
612 switch (gen->n_block) {
613 case 1:
614 gen->block_dim[0] = 512;
615 break;
616 case 2:
617 gen->block_dim[0] = 32;
618 gen->block_dim[1] = 16;
619 break;
620 default:
621 gen->block_dim[0] = 32;
622 gen->block_dim[1] = 4;
623 gen->block_dim[2] = 4;
624 break;
627 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
628 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
631 /* Extract user specified "grid" sizes from the "sizes" command line option,
632 * after filling in some potentially useful defaults.
634 static void read_grid_sizes(struct gpu_gen *gen)
636 int n = gen->n_parallel;
637 isl_set *size;
639 gen->n_grid = (n <= 2) ? n : 2;
640 switch (gen->n_grid) {
641 case 1:
642 gen->grid_dim[0] = 32768;
643 break;
644 default:
645 gen->grid_dim[0] = 256;
646 gen->grid_dim[1] = 256;
647 break;
650 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
651 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
654 /* Extract user specified sizes from the "sizes" command line option
655 * after filling in some potentially useful defaults.
657 static void read_sizes(struct gpu_gen *gen)
659 read_tile_sizes(gen);
660 read_block_sizes(gen);
661 read_grid_sizes(gen);
664 static void *free_stmts(struct gpu_stmt *stmts, int n)
666 int i;
668 if (!stmts)
669 return NULL;
671 for (i = 0; i < n; ++i) {
672 struct gpu_stmt_access *access, *next;
674 for (access = stmts[i].accesses; access; access = next) {
675 next = access->next;
676 isl_map_free(access->access);
677 free(access);
680 isl_id_free(stmts[i].id);
682 free(stmts);
684 return NULL;
687 void clear_gpu_gen(struct gpu_gen *gen)
689 isl_union_map_free(gen->sizes);
690 isl_union_map_free(gen->sched);
693 /* Construct a map from a domain of dimensionality "len"
694 * to a domain of dimensionality "len" + "tile_len" that tiles
695 * the "tile_len" coordinates starting at "first".
696 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
697 * "dim" prescribes the parameters.
699 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
700 int first, int tile_len, int *tile_size)
702 int i;
703 isl_basic_map *bmap;
704 isl_constraint *c;
705 isl_local_space *ls;
707 dim = isl_space_add_dims(dim, isl_dim_in, len);
708 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
709 bmap = isl_basic_map_universe(isl_space_copy(dim));
710 ls = isl_local_space_from_space(dim);
712 for (i = 0; i < len - tile_len; ++i) {
713 int j = i < first ? i : i + tile_len;
714 int k = i < first ? i : i + 2 * tile_len;
716 c = isl_equality_alloc(isl_local_space_copy(ls));
717 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
718 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
719 bmap = isl_basic_map_add_constraint(bmap, c);
722 for (i = 0; i < tile_len; ++i) {
723 c = isl_equality_alloc(isl_local_space_copy(ls));
724 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
725 first + i, -1);
726 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
727 first + i, tile_size[i]);
728 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
729 first + i + tile_len, 1);
730 bmap = isl_basic_map_add_constraint(bmap, c);
732 c = isl_inequality_alloc(isl_local_space_copy(ls));
733 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
734 first + i + tile_len, 1);
735 bmap = isl_basic_map_add_constraint(bmap, c);
737 c = isl_inequality_alloc(isl_local_space_copy(ls));
738 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
739 first + i + tile_len, -1);
740 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
741 bmap = isl_basic_map_add_constraint(bmap, c);
744 isl_local_space_free(ls);
746 return isl_map_from_basic_map(bmap);
749 /* Construct a map from a domain of dimensionality "len"
750 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
751 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
752 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
753 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
754 * that are projected out at the end.
755 * "dim" prescribes the parameters.
757 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
758 int first, int wrap_len, int *wrap_size)
760 int i;
761 isl_basic_map *bmap;
762 isl_constraint *c;
763 isl_local_space *ls;
765 dim = isl_space_add_dims(dim, isl_dim_in, len);
766 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
767 bmap = isl_basic_map_universe(isl_space_copy(dim));
768 ls = isl_local_space_from_space(dim);
770 for (i = 0; i < len; ++i) {
771 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
773 c = isl_equality_alloc(isl_local_space_copy(ls));
774 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
775 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
776 bmap = isl_basic_map_add_constraint(bmap, c);
779 for (i = 0; i < wrap_len; ++i) {
780 c = isl_equality_alloc(isl_local_space_copy(ls));
781 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
782 first + i, -1);
783 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
784 first + wrap_len + i, 1);
785 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
786 first + 2 * wrap_len + i, wrap_size[i]);
787 bmap = isl_basic_map_add_constraint(bmap, c);
789 c = isl_inequality_alloc(isl_local_space_copy(ls));
790 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
791 first + wrap_len + i, 1);
792 bmap = isl_basic_map_add_constraint(bmap, c);
794 c = isl_inequality_alloc(isl_local_space_copy(ls));
795 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
796 first + wrap_len + i, -1);
797 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
798 bmap = isl_basic_map_add_constraint(bmap, c);
801 isl_local_space_free(ls);
803 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
804 first + 2 * wrap_len, wrap_len);
806 return isl_map_from_basic_map(bmap);
809 /* Add "n" parameters named prefix%d.
811 static __isl_give isl_set *add_params( __isl_take isl_set *set,
812 int n, const char *prefix)
814 int i;
815 unsigned nparam;
816 char name[20];
818 nparam = isl_set_dim(set, isl_dim_param);
819 set = isl_set_add_dims(set, isl_dim_param, n);
821 for (i = 0; i < n; ++i) {
822 snprintf(name, sizeof(name), "%s%d", prefix, i);
823 set = isl_set_set_dim_name(set, isl_dim_param,
824 nparam + i, name);
827 return set;
830 /* Equate the "n" dimensions of "set" starting at "first" to
831 * freshly created parameters named prefix%d.
833 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
834 int first, int n, const char *prefix)
836 int i;
837 unsigned nparam;
839 nparam = isl_set_dim(set, isl_dim_param);
841 set = add_params(set, n, prefix);
843 for (i = 0; i < n; ++i)
844 set = isl_set_equate(set, isl_dim_param, nparam + i,
845 isl_dim_set, first + i);
847 return set;
850 /* Given a parameter space "space", create a set of dimension "len"
851 * of which the "n" dimensions starting at "first" are equated to
852 * freshly created parameters named prefix%d.
854 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
855 int len, int first, int n, const char *prefix)
857 isl_set *set;
859 space = isl_space_set_from_params(space);
860 space = isl_space_add_dims(space, isl_dim_set, len);
861 set = isl_set_universe(space);
863 return parametrize(set, first, n, prefix);
866 /* Tile the B loops over the tile sizes and then tile/wrap
867 * the T1 loops over the blocks.
869 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
870 __isl_take isl_union_map *sched)
872 isl_space *dim;
873 isl_map *tiling, *block_tiling;
875 dim = isl_union_map_get_space(sched);
876 tiling = tile(isl_space_copy(dim), gen->untiled_len,
877 gen->tile_first, gen->tile_len, gen->tile_size);
879 if (gen->options->wrap)
880 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
881 gen->tile_first, gen->n_grid, gen->grid_dim);
882 else
883 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
884 gen->tile_first, gen->n_grid, gen->grid_dim);
886 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
888 tiling = isl_map_apply_range(tiling, block_tiling);
890 sched = isl_union_map_apply_range(sched,
891 isl_union_map_from_map(tiling));
893 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
895 return sched;
898 /* Equate the "T1P" iterators in the tiled schedule "sched"
899 * to the block dimensions.
901 static __isl_give isl_union_map *parametrize_tiled_schedule(
902 struct gpu_gen *gen, __isl_take isl_union_map *sched)
904 isl_space *dim;
905 isl_set *par;
907 dim = isl_union_map_get_space(sched);
908 par = parametrization(dim, gen->tiled_len,
909 gen->tile_first + gen->n_grid, gen->n_grid, "b");
910 sched = isl_union_map_intersect_range(sched,
911 isl_union_set_from_set(par));
913 return sched;
916 /* Tile/wrap the P1 loops over the threads.
918 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
919 __isl_take isl_union_map *sched)
921 isl_space *dim;
922 isl_map *tiling;
923 isl_set *par;
925 dim = isl_union_map_get_space(sched);
927 if (gen->options->wrap)
928 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
929 gen->shared_len, gen->n_block, gen->block_dim);
930 else
931 tiling = tile(isl_space_copy(dim), gen->tiled_len,
932 gen->shared_len, gen->n_block, gen->block_dim);
933 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
935 sched = isl_union_map_apply_range(sched,
936 isl_union_map_from_map(tiling));
938 par = parametrization(dim, gen->thread_tiled_len,
939 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
940 gen->n_block, "t");
941 sched = isl_union_map_intersect_range(sched,
942 isl_union_set_from_set(par));
944 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
946 return sched;
949 /* If the user asked for it, scale the shared memory tile loops
950 * (T1T and T2) of "sched" by gen->tile_size[i].
951 * If we are not performing "wrapping", then additionally scale the T1P
952 * loops by gen->grid_dim[i].
954 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
955 __isl_take isl_union_map *sched)
957 int i;
958 isl_space *dim;
959 isl_basic_map *scale;
960 isl_constraint *c;
961 isl_local_space *ls;
963 if (!gen->options->scale_tile_loops)
964 return sched;
966 dim = isl_union_map_get_space(sched);
967 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
968 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
969 scale = isl_basic_map_universe(isl_space_copy(dim));
970 ls = isl_local_space_from_space(dim);
972 for (i = 0; i < gen->tiled_len; ++i) {
973 int f = 1;
975 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
976 f = gen->tile_size[i - gen->tile_first];
977 if (!gen->options->wrap)
978 f *= gen->grid_dim[i - gen->tile_first];
979 } else if (i >= gen->tile_first + gen->n_grid &&
980 i < gen->tile_first + gen->n_grid + gen->tile_len) {
981 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
984 c = isl_equality_alloc(isl_local_space_copy(ls));
985 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
986 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
987 scale = isl_basic_map_add_constraint(scale, c);
990 isl_local_space_free(ls);
992 sched = isl_union_map_apply_range(sched,
993 isl_union_map_from_map(isl_map_from_basic_map(scale)));
995 return sched;
998 /* If we are not performing "wrapping" and if the user asked for it,
999 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1001 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1002 __isl_take isl_union_map *sched)
1004 int i;
1005 isl_space *dim;
1006 isl_basic_map *scale;
1007 isl_constraint *c;
1008 isl_local_space *ls;
1010 if (gen->options->wrap)
1011 return sched;
1012 if (!gen->options->scale_tile_loops)
1013 return sched;
1015 dim = isl_union_map_get_space(sched);
1016 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1017 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1018 scale = isl_basic_map_universe(isl_space_copy(dim));
1019 ls = isl_local_space_from_space(dim);
1021 for (i = 0; i < gen->thread_tiled_len; ++i) {
1022 int f = 1;
1024 if (i >= gen->shared_len &&
1025 i < gen->shared_len + gen->n_block)
1026 f = gen->block_dim[i - gen->shared_len];
1028 c = isl_equality_alloc(isl_local_space_copy(ls));
1029 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1030 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1031 scale = isl_basic_map_add_constraint(scale, c);
1034 isl_local_space_free(ls);
1036 sched = isl_union_map_apply_range(sched,
1037 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1039 return sched;
1042 /* If we are not performing "wrapping" and if the user asked for it,
1043 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1045 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1046 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1048 int i;
1049 isl_space *dim;
1050 isl_basic_map *scale;
1051 isl_constraint *c;
1052 isl_local_space *ls;
1054 if (gen->options->wrap)
1055 return sched;
1056 if (!gen->options->scale_tile_loops)
1057 return sched;
1059 dim = isl_union_map_get_space(sched);
1060 dim = isl_space_add_dims(dim, isl_dim_in, len);
1061 dim = isl_space_add_dims(dim, isl_dim_out, len);
1062 scale = isl_basic_map_universe(isl_space_copy(dim));
1063 ls = isl_local_space_from_space(dim);
1065 for (i = 0; i < len; ++i) {
1066 int f = 1;
1068 if (i >= first && i < first + n_tile)
1069 f = gen->kernel->block_dim[i - first];
1071 c = isl_equality_alloc(isl_local_space_copy(ls));
1072 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1073 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1074 scale = isl_basic_map_add_constraint(scale, c);
1077 isl_local_space_free(ls);
1079 sched = isl_union_map_apply_range(sched,
1080 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1082 return sched;
1085 /* Add "len" parameters p[i] called prefix%d,
1086 * with bounds to 0 <= p[i] < size[i].
1088 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1089 int len, int *size, const char *prefix)
1091 int i;
1092 unsigned nparam;
1093 isl_space *dim;
1094 isl_basic_set *bset;
1095 isl_constraint *c;
1096 isl_local_space *ls;
1097 char name[20];
1099 nparam = isl_set_dim(set, isl_dim_param);
1100 set = isl_set_add_dims(set, isl_dim_param, len);
1102 for (i = 0; i < len; ++i) {
1103 snprintf(name, sizeof(name), "%s%d", prefix, i);
1104 set = isl_set_set_dim_name(set, isl_dim_param,
1105 nparam + i, name);
1108 dim = isl_set_get_space(set);
1109 bset = isl_basic_set_universe(isl_space_copy(dim));
1110 ls = isl_local_space_from_space(dim);
1112 for (i = 0; i < len; ++i) {
1113 c = isl_inequality_alloc(isl_local_space_copy(ls));
1114 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1115 nparam + i, 1);
1116 bset = isl_basic_set_add_constraint(bset, c);
1118 c = isl_inequality_alloc(isl_local_space_copy(ls));
1119 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1120 nparam + i, -1);
1121 c = isl_constraint_set_constant_si(c, size[i] - 1);
1122 bset = isl_basic_set_add_constraint(bset, c);
1125 isl_local_space_free(ls);
1127 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1130 /* Add "len" parameters p[i] called prefix%d,
1131 * with bounds to 0 <= p[i] < size[i].
1133 static __isl_give isl_set *add_bounded_parameters_dynamic(
1134 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1135 const char *prefix)
1137 int i, len;
1138 unsigned nparam;
1139 isl_space *space;
1140 isl_local_space *ls;
1141 char name[20];
1143 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1144 nparam = isl_set_dim(set, isl_dim_param);
1145 set = isl_set_add_dims(set, isl_dim_param, len);
1147 for (i = 0; i < len; ++i) {
1148 snprintf(name, sizeof(name), "%s%d", prefix, i);
1149 set = isl_set_set_dim_name(set, isl_dim_param,
1150 nparam + i, name);
1153 space = isl_space_params(isl_set_get_space(set));
1154 ls = isl_local_space_from_space(space);
1155 for (i = 0; i < len; ++i) {
1156 isl_pw_aff *param, *size_i, *zero;
1157 isl_set *bound;
1159 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1160 isl_dim_param, nparam + i);
1162 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1163 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1164 set = isl_set_intersect_params(set, bound);
1166 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1167 bound = isl_pw_aff_ge_set(param, zero);
1168 set = isl_set_intersect_params(set, bound);
1170 isl_local_space_free(ls);
1172 return set;
1175 /* Given a mapping "sched" of the form
1177 * [D -> A] -> [D -> T(A)]
1179 * apply the mapping encoded in tile->bound[i].shift_map
1180 * to the range of "sched".
1181 * The mappings in tile->bound[i].shift_map are of the form
1183 * [D -> a] -> [D -> s(D,a)]
1185 * We first compose them with a mapping
1187 * [D -> v] -> v
1189 * (If tile->bound[i].shift_map is not set, then it is assumed to be
1190 * an identity mapping and then we use this second mapping instead.)
1191 * This results in
1193 * [D -> a] -> s(D,a)
1195 * We precompose them with a projection on the i th dimension to obtain
1197 * [D -> T] -> s(D,T)
1199 * and collect these into
1201 * [D -> T] -> S(D,T)
1203 * Introducing D in the range yields
1205 * [D -> T] -> [D -> S(D,T)]
1207 * and application to "sched" yields
1209 * [D -> A] -> [D -> S(D,T(A))]
1211 static __isl_give isl_map *pre_shift(__isl_take isl_map *sched,
1212 struct gpu_array_tile *tile)
1214 int i;
1215 isl_ctx *ctx = isl_map_get_ctx(sched);
1216 isl_space *space, *space2;
1217 isl_basic_map *def;
1218 isl_map *map, *id, *pre_shift;
1220 space = isl_space_range(isl_map_get_space(sched));
1221 space2 = isl_space_from_domain(isl_space_copy(space));
1222 pre_shift = isl_map_universe(space2);
1223 space = isl_space_domain(isl_space_unwrap(space));
1224 id = isl_map_identity(isl_space_map_from_set(isl_space_copy(space)));
1225 space = isl_space_from_domain(space);
1226 space = isl_space_add_dims(space, isl_dim_out, 1);
1227 def = isl_basic_map_range_map(isl_basic_map_universe(space));
1229 for (i = 0; i < tile->n; ++i) {
1230 isl_basic_map *bmap, *drop;
1231 isl_map *proj;
1233 space = isl_space_alloc(ctx, 0, tile->n, tile->n);
1234 proj = isl_map_identity(space);
1235 proj = isl_map_project_out(proj, isl_dim_out,
1236 i + 1, tile->n - (i + 1));
1237 proj = isl_map_project_out(proj, isl_dim_out, 0, i);
1238 proj = isl_map_product(isl_map_copy(id), proj);
1240 if (!tile->bound[i].shift_map)
1241 bmap = isl_basic_map_copy(def);
1242 else {
1243 bmap = isl_basic_map_copy(tile->bound[i].shift_map);
1244 bmap = isl_basic_map_apply_range(bmap,
1245 isl_basic_map_copy(def));
1248 map = isl_map_from_basic_map(bmap);
1249 map = isl_map_apply_range(proj, map);
1250 pre_shift = isl_map_flat_range_product(pre_shift, map);
1253 isl_map_free(id);
1254 isl_basic_map_free(def);
1256 space = isl_space_domain(isl_map_get_space(pre_shift));
1257 map = isl_map_domain_map(isl_map_universe(isl_space_unwrap(space)));
1258 pre_shift = isl_map_range_product(map, pre_shift);
1260 sched = isl_map_apply_range(sched, pre_shift);
1262 return sched;
1265 /* Given an access relation to a tile of an array, construct a map that
1266 * maps each element in the space of the access relation
1267 * to a copy of the tile shifted to the origin
1268 * (based on the lower bounds in group->private_tile or group->shared_tile).
1269 * If any of the indices is strided, then
1270 * {private,shared}_tile->bound[i].shift_map is applied to the index first.
1271 * The domain space of the resulting map is that of access "access",
1272 * while the range space is anonymous.
1273 * The resulting map only encodes the mapping to the shift tile and
1274 * not the constraints of "access".
1276 * Let the space of the access relation be
1278 * D -> A
1280 * We first construct an identity relation on a wrapped copy of this space,
1281 * except that it strips off the name of array
1283 * [D -> A] -> [D -> T(A)] (1)
1285 * The bounds in tile->bound[i].lb are of the form
1287 * D -> b(D)
1289 * We collect them into
1291 * D -> B(D)
1293 * and then transform them into
1295 * [D -> T] -> T - B(D) (2)
1297 * Combining those two mappings (1) and (2) yields
1299 * [D -> A] -> T(A) - B(D)
1301 * If there are any strides, then (1) is first transformed into (1')
1303 * [D -> A] -> [D -> T'(A)] (1')
1305 * by a call to pre_shift.
1307 static __isl_give isl_map *shift_access(__isl_take isl_map *access,
1308 struct gpu_array_ref_group *group)
1310 int i;
1311 isl_space *space;
1312 isl_map *id1, *id2;
1313 isl_map *map;
1314 isl_map *shift;
1315 isl_map *sched;
1316 struct gpu_array_tile *tile;
1317 int n_index = group->array->n_index;
1319 tile = group->private_tile;
1320 if (!tile)
1321 tile = group->shared_tile;
1323 space = isl_space_domain(isl_map_get_space(access));
1324 space = isl_space_map_from_set(space);
1325 id1 = isl_map_identity(space);
1326 space = isl_space_range(isl_map_get_space(access));
1327 space = isl_space_map_from_set(space);
1328 space = isl_space_set_tuple_name(space, isl_dim_out, NULL);
1329 id2 = isl_map_identity(space);
1330 sched = isl_map_product(id1, id2);
1332 space = isl_space_unwrap(isl_space_range(isl_map_get_space(sched)));
1333 space = isl_space_from_domain(isl_space_domain(space));
1334 shift = isl_map_universe(space);
1335 for (i = 0; i < n_index; ++i) {
1336 map = isl_map_from_aff(isl_aff_copy(tile->bound[i].lb));
1337 shift = isl_map_flat_range_product(shift, map);
1340 space = isl_space_unwrap(isl_space_range(isl_map_get_space(sched)));
1341 map = isl_map_universe(space);
1342 id1 = isl_map_range_map(isl_map_copy(map));
1343 map = isl_map_domain_map(map);
1344 shift = isl_map_neg(shift);
1345 shift = isl_map_apply_range(map, shift);
1346 shift = isl_map_sum(id1, shift);
1348 for (i = 0; i < n_index; ++i)
1349 if (tile->bound[i].shift_map)
1350 break;
1352 if (i < n_index)
1353 sched = pre_shift(sched, tile);
1355 sched = isl_map_apply_range(sched, shift);
1357 isl_map_free(access);
1359 return sched;
1362 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1364 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1365 unsigned pos)
1367 isl_val *v;
1368 int fixed;
1370 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1371 if (!v)
1372 return -1;
1373 fixed = isl_val_is_int(v);
1374 isl_val_free(v);
1376 return fixed;
1379 /* Given a schedule that iterates over all elements in a piece of an array,
1380 * perform tiling/wrapping over the threads.
1382 * In particular, we tile the final iterators so that the final thread
1383 * dimension runs over the final array dimension.
1384 * However, if those final iterators have only a single iteration,
1385 * we try to tile earlier iterators instead.
1387 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1388 __isl_take isl_map *sched)
1390 isl_space *dim;
1391 isl_union_map *usched;
1392 isl_map *tiling;
1393 isl_set *par;
1394 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1395 int n_tile;
1396 int first;
1398 n_tile = gen->kernel->n_block;
1399 if (n_tile > nvar) {
1400 int i;
1401 sched = isl_map_insert_dims(sched,
1402 isl_dim_out, 0, n_tile - nvar);
1403 for (i = 0; i < n_tile - nvar; ++i)
1404 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1405 nvar = n_tile;
1408 first = nvar - n_tile;
1410 for (; first > 0; first --)
1411 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1412 break;
1414 dim = isl_map_get_space(sched);
1415 dim = isl_space_params(dim);
1416 if (gen->options->wrap)
1417 tiling = wrap(isl_space_copy(dim), nvar, first,
1418 n_tile, gen->kernel->block_dim);
1419 else
1420 tiling = tile(isl_space_copy(dim), nvar, first,
1421 n_tile, gen->kernel->block_dim);
1422 sched = isl_map_apply_range(sched, tiling);
1424 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1425 sched = isl_map_intersect_range(sched, par);
1427 usched = isl_union_map_from_map(sched);
1428 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1429 first, n_tile);
1430 sched = isl_map_from_union_map(usched);
1432 return sched;
1435 /* Given an index expression "pa" into a tile of an array, adjust the expression
1436 * to a shift of the tile to the origin
1437 * (based on the lower bounds in "bound".
1438 * If the index is strided, then we first add
1439 * bound->shift and divide by bound->stride.
1440 * In the end, we compute the gist with respect to "domain".
1442 * All of the input expression "pa", the set "domain" and
1443 * the output are expressed in terms of the AST schedule domain.
1444 * The expressions in "bound" are expressed
1445 * in terms of the first shared_len dimensions of the schedule computed by PPCG.
1446 * The mapping "sched2shared" maps the former domain to the latter domain.
1448 static __isl_give isl_pw_aff *shift_index(__isl_take isl_pw_aff *pa,
1449 struct gpu_array_info *array,
1450 struct gpu_array_bound *bound, __isl_take isl_set *domain,
1451 __isl_take isl_map *sched2shared)
1453 isl_map *map;
1454 isl_pw_aff *tmp;
1455 isl_pw_multi_aff *pma;
1457 if (bound->shift) {
1458 map = isl_map_from_aff(isl_aff_copy(bound->shift));
1459 map = isl_map_apply_range(isl_map_copy(sched2shared), map);
1460 pma = isl_pw_multi_aff_from_map(map);
1461 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1462 isl_pw_multi_aff_free(pma);
1463 pa = isl_pw_aff_add(pa, tmp);
1464 pa = isl_pw_aff_scale_down_val(pa, isl_val_copy(bound->stride));
1468 map = isl_map_from_aff(isl_aff_copy(bound->lb));
1469 map = isl_map_apply_range(sched2shared, map);
1470 pma = isl_pw_multi_aff_from_map(map);
1471 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1472 isl_pw_multi_aff_free(pma);
1473 pa = isl_pw_aff_sub(pa, tmp);
1474 pa = isl_pw_aff_coalesce(pa);
1475 pa = isl_pw_aff_gist(pa, domain);
1477 return pa;
1480 /* Return the union of all read (read = 1) and/or write (write = 1)
1481 * access relations in the group.
1483 static __isl_give isl_union_map *group_access_relation(
1484 struct gpu_array_ref_group *group, int read, int write)
1486 int i;
1487 isl_union_map *access;
1489 access = isl_union_map_empty(isl_map_get_space(group->access));
1490 for (i = 0; i < group->n_ref; ++i) {
1491 isl_map *map_i;
1493 if (!((read && group->refs[i]->read) ||
1494 (write && group->refs[i]->write)))
1495 continue;
1496 map_i = isl_map_copy(group->refs[i]->access);
1497 access = isl_union_map_union(access,
1498 isl_union_map_from_map(map_i));
1501 return access;
1504 /* Return a map from the first shared_len dimensions of the computed
1505 * schedule to the values of the given index "i"
1506 * of the elements in the array tile in global memory that corresponds
1507 * to the shared memory copy.
1508 * In particular, if a is the index, then the range of the map
1510 * { D -> [a] }
1512 * is constrained as follows
1514 * tile_offset(D) <= a <= tile_offset(D) + tile_size - 1 (1)
1516 * and
1518 * 0 <= a <= array_size - 1 (2)
1521 * Note that if some stride has been detected (i.e., when
1522 * group->shared_tile->bound[i].shift is set), then offset and size (i.e.,
1523 * constraints (1)) apply to the shifted and scaled down copy of the tile.
1524 * These constraints therefore have to be mapped back to the original
1525 * array space using the inverse of the shift_map.
1527 static __isl_give isl_map *group_tile_dim(struct gpu_array_ref_group *group,
1528 int i)
1530 isl_aff *aff;
1531 isl_space *space;
1532 isl_map *map, *tile, *gt;
1533 isl_set *bound;
1535 map = isl_map_from_aff(isl_aff_copy(group->shared_tile->bound[i].lb));
1536 space = isl_space_range(isl_map_get_space(map));
1537 map = isl_map_apply_range(map, isl_map_lex_le(isl_space_copy(space)));
1538 tile = map;
1540 aff = isl_aff_copy(group->shared_tile->bound[i].lb);
1541 aff = isl_aff_add_constant_val(aff,
1542 isl_val_copy(group->shared_tile->bound[i].size));
1543 map = isl_map_from_aff(aff);
1544 gt = isl_map_lex_gt(space);
1545 map = isl_map_apply_range(map, isl_map_copy(gt));
1546 tile = isl_map_intersect(tile, map);
1548 if (group->shared_tile->bound[i].shift) {
1549 isl_basic_map *shift;
1550 shift = isl_basic_map_copy(group->shared_tile->bound[i].shift_map);
1551 shift = isl_basic_map_reverse(shift);
1552 tile = isl_set_unwrap(isl_set_apply(isl_map_wrap(tile),
1553 isl_map_from_basic_map(shift)));
1556 tile = isl_map_lower_bound_si(tile, isl_dim_out, 0, 0);
1558 bound = isl_set_from_pw_aff(isl_pw_aff_copy(group->array->bound[i]));
1559 bound = isl_set_apply(bound, gt);
1560 tile = isl_map_intersect_range(tile, bound);
1562 return tile;
1565 /* Return a map from the first shared_len dimensions of the computed
1566 * schedule to the array tile in
1567 * global memory that corresponds to the shared memory copy.
1569 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1571 int i;
1572 int n_index = group->array->n_index;
1573 isl_map *tile;
1575 tile = group_tile_dim(group, 0);
1576 for (i = 1; i < n_index; ++i) {
1577 isl_map *tile_i;
1579 tile_i = group_tile_dim(group, i);
1580 tile = isl_map_flat_range_product(tile, tile_i);
1583 tile = isl_map_set_tuple_name(tile, isl_dim_out, group->array->name);
1585 return tile;
1588 /* Given a mapping "sched" from the AST schedule to a domain,
1589 * return the corresponding mapping from the AST schedule to
1590 * to the first shared_len dimensions of the schedule computed by PPCG.
1592 static __isl_give isl_map *compute_sched_to_shared(struct gpu_gen *gen,
1593 __isl_take isl_map *sched)
1595 isl_union_map *umap;
1596 isl_space *space;
1597 isl_map *map;
1599 space = isl_space_range(isl_map_get_space(sched));
1600 space = isl_space_from_domain(space);
1601 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1603 umap = isl_union_map_copy(gen->shared_sched);
1604 umap = isl_union_map_apply_range(umap,
1605 isl_union_map_copy(gen->shared_proj));
1606 map = isl_union_map_extract_map(umap, space);
1607 isl_union_map_free(umap);
1609 sched = isl_map_apply_range(sched, map);
1610 sched = isl_map_detect_equalities(sched);
1612 return sched;
1615 /* Set unroll[j] if the input dimension j is involved in
1616 * the index expression represented by ma.
1618 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1619 void *user)
1621 int i, j;
1622 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1623 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1624 int *unroll = user;
1626 for (i = 0; i < n_out; ++i) {
1627 isl_aff *aff;
1629 aff = isl_multi_aff_get_aff(ma, i);
1630 for (j = 0; j < n_in; ++j)
1631 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1632 unroll[j] = 1;
1633 isl_aff_free(aff);
1636 isl_set_free(set);
1637 isl_multi_aff_free(ma);
1638 return 0;
1641 /* Given an array pos mapping input dimensions to the corresponding
1642 * output dimension, construct the corresponding map.
1644 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1645 int *pos, int len)
1647 int i;
1648 isl_constraint *c;
1649 isl_basic_map *bmap;
1650 isl_local_space *ls;
1652 dim = isl_space_add_dims(dim, isl_dim_in, len);
1653 dim = isl_space_add_dims(dim, isl_dim_out, len);
1654 bmap = isl_basic_map_universe(isl_space_copy(dim));
1655 ls = isl_local_space_from_space(dim);
1657 for (i = 0; i < len; ++i) {
1658 c = isl_equality_alloc(isl_local_space_copy(ls));
1659 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1660 -1);
1661 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1663 bmap = isl_basic_map_add_constraint(bmap, c);
1665 isl_local_space_free(ls);
1667 return isl_map_from_basic_map(bmap);
1670 /* Find all loops involved in any of the index expressions for any of
1671 * the private accesses, move them innermost and then mark them as
1672 * requiring unrolling by setting gen->first_unroll.
1673 * The loops involved should all be parallel because of the checks
1674 * we performed in check_private_group_access. Moving them innermost
1675 * is therefore a valid transformation.
1677 * Loops up to gen->shared_len are generated before the mapping to
1678 * threads is applied. They should therefore be ignored.
1680 * We compute the hidden equalities of the schedule first
1681 * since we will need them in our calls to isl_pw_multi_aff_from_map
1682 * and because we want to make sure that the same equalities
1683 * are also available to the code generator.
1685 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1686 __isl_take isl_union_map *sched)
1688 int i, j;
1689 int unroll[gen->thread_tiled_len];
1690 int perm[gen->thread_tiled_len];
1691 isl_space *dim;
1692 isl_map *permute;
1693 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1695 gen->first_unroll = -1;
1697 sched = isl_union_map_detect_equalities(sched);
1698 for (i = 0; i < gen->thread_tiled_len; ++i)
1699 unroll[i] = 0;
1700 for (i = 0; i < gen->prog->n_array; ++i) {
1701 struct gpu_array_info *array = &gen->prog->array[i];
1703 for (j = 0; j < array->n_group; ++j) {
1704 isl_union_map *access;
1705 isl_map *acc;
1706 isl_pw_multi_aff *pma;
1708 if (!array->groups[j]->private_tile)
1709 continue;
1711 access = group_access_relation(array->groups[j], 1, 1);
1712 access = isl_union_map_apply_domain(access,
1713 isl_union_map_copy(sched));
1715 acc = isl_map_from_union_map(access);
1716 pma = isl_pw_multi_aff_from_map(acc);
1717 isl_pw_multi_aff_foreach_piece(pma,
1718 &check_unroll, unroll);
1720 isl_pw_multi_aff_free(pma);
1724 for (i = gen->shared_len; i < len; ++i)
1725 if (unroll[i])
1726 break;
1728 if (i >= len)
1729 return sched;
1731 for (i = len; i < gen->thread_tiled_len; ++i)
1732 if (unroll[i])
1733 return sched;
1735 j = 0;
1736 for (i = 0; i < gen->shared_len; ++i)
1737 perm[i] = j++;
1738 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1739 if (!unroll[i])
1740 perm[i] = j++;
1741 gen->first_unroll = j - gen->shared_len;
1742 for (i = gen->shared_len; i < len; ++i)
1743 if (unroll[i])
1744 perm[i] = j++;
1746 dim = isl_union_map_get_space(sched);
1747 permute = permutation(dim, perm, gen->thread_tiled_len);
1748 sched = isl_union_map_apply_range(sched,
1749 isl_union_map_from_map(permute));
1751 return sched;
1754 /* Given a constraint
1756 * a(p,i) + j = g f(e)
1758 * or -a(p,i) - j = g f(e) if sign < 0,
1759 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1760 * a(p,i) is assumed to be an expression in only the parameters
1761 * and the input dimensions.
1763 static void extract_stride(__isl_keep isl_constraint *c,
1764 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1766 int i;
1767 isl_val *v;
1768 isl_space *space;
1769 unsigned nparam;
1770 unsigned nvar;
1771 isl_aff *aff;
1773 isl_val_free(bound->stride);
1774 bound->stride = isl_val_copy(stride);
1776 space = isl_constraint_get_space(c);
1777 space = isl_space_domain(space);
1779 nparam = isl_space_dim(space, isl_dim_param);
1780 nvar = isl_space_dim(space, isl_dim_set);
1782 v = isl_constraint_get_constant_val(c);
1783 if (sign < 0)
1784 v = isl_val_neg(v);
1785 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1786 aff = isl_aff_set_constant_val(aff, v);
1788 for (i = 0; i < nparam; ++i) {
1789 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1790 continue;
1791 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1792 if (sign < 0)
1793 v = isl_val_neg(v);
1794 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1797 for (i = 0; i < nvar; ++i) {
1798 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1799 continue;
1800 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1801 if (sign < 0)
1802 v = isl_val_neg(v);
1803 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1806 bound->shift = aff;
1809 /* Given an equality constraint of a map with a single output dimension j,
1810 * check if the constraint is of the form
1812 * a(p,i) + j = g f(e)
1814 * with a(p,i) an expression in the parameters and input dimensions
1815 * and f(e) an expression in the existentially quantified variables.
1816 * If so, and if g is larger than any such g from a previously considered
1817 * constraint, then call extract_stride to record the stride information
1818 * in bound.
1820 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1822 int i;
1823 isl_ctx *ctx;
1824 isl_val *v;
1825 unsigned n_div;
1826 struct gpu_array_bound *bound = user;
1828 ctx = isl_constraint_get_ctx(c);
1829 n_div = isl_constraint_dim(c, isl_dim_div);
1830 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1832 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1833 int s = isl_val_sgn(v);
1834 isl_val *stride = isl_val_zero(ctx);
1836 isl_val_free(v);
1837 for (i = 0; i < n_div; ++i) {
1838 v = isl_constraint_get_coefficient_val(c,
1839 isl_dim_div, i);
1840 stride = isl_val_gcd(stride, v);
1842 if (!isl_val_is_zero(stride) &&
1843 isl_val_gt(stride, bound->stride))
1844 extract_stride(c, bound, stride, s);
1846 isl_val_free(stride);
1847 } else
1848 isl_val_free(v);
1850 isl_constraint_free(c);
1851 return 0;
1854 /* Given contraints on an array index i, check if we can find
1855 * a shift a(p) and a stride g such that
1857 * a(p) + i = 0 mod g
1859 * If so, record the information in bound and apply the mapping
1860 * i -> (i + a(p))/g to the array index in bounds and return
1861 * the new constraints.
1862 * If not, simply return the original constraints.
1864 * If bounds is a subset of the space
1866 * D -> i
1868 * then the bound recorded in bound->shift is of the form
1870 * D -> s(D)
1872 * with s(D) equal to a(p) above.
1873 * The mapping recorded in bound->shift_map is of the form
1875 * [D -> i] -> [D -> (i + S(D))/g]
1877 * This mapping is computed as follows.
1878 * We first introduce "i" in the domain through precomposition
1879 * with [D -> i] -> D obtaining
1881 * [D -> i] -> s(D)
1883 * Adding [D -> i] -> i produces
1885 * [D -> i] -> i + s(D)
1887 * and the domain product with [D -> i] -> D yields
1889 * [D -> i] -> [D -> i + s(D)]
1891 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1893 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1894 __isl_take isl_basic_map *bounds)
1896 isl_space *space;
1897 isl_basic_map *hull;
1898 isl_basic_map *shift, *id, *bmap, *scale;
1899 isl_basic_set *bset;
1900 isl_aff *aff;
1902 bound->stride = NULL;
1904 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1906 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1908 isl_basic_map_free(hull);
1910 if (!bound->stride)
1911 return bounds;
1913 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1914 space = isl_basic_map_get_space(bounds);
1915 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1916 shift = isl_basic_map_apply_range(bmap, shift);
1917 space = isl_basic_map_get_space(bounds);
1918 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1919 shift = isl_basic_map_sum(id, shift);
1920 space = isl_basic_map_get_space(bounds);
1921 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1922 shift = isl_basic_map_range_product(id, shift);
1924 space = isl_space_domain(isl_basic_map_get_space(bounds));
1925 id = isl_basic_map_identity(isl_space_map_from_set(space));
1926 space = isl_space_range(isl_basic_map_get_space(bounds));
1927 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1928 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1929 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
1930 scale = isl_basic_map_from_aff(aff);
1931 scale = isl_basic_map_product(id, scale);
1933 bound->shift_map = isl_basic_map_apply_range(shift, scale);
1934 bmap = isl_basic_map_copy(bound->shift_map);
1935 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1936 bounds = isl_basic_set_unwrap(bset);
1938 return bounds;
1941 /* Data used in compute_array_dim_size and compute_size_in_direction.
1943 * pos is the position of the variable representing the array index,
1944 * i.e., the variable for which want to compute the size. This variable
1945 * is also the last variable in the set.
1947 struct gpu_size_info {
1948 isl_basic_set *bset;
1949 struct gpu_array_bound *bound;
1950 int pos;
1953 /* Given a constraint from the basic set describing the bounds on
1954 * an array index, check if it is a lower bound, say m i >= b(x), and,
1955 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
1956 * upper bound. If so, and if this bound is smaller than any bound
1957 * derived from earlier constraints, set the size to this bound on
1958 * the expression and the lower bound to ceil(b(x)/m).
1960 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
1962 struct gpu_size_info *size = user;
1963 unsigned nparam;
1964 unsigned n_div;
1965 isl_val *v;
1966 isl_aff *aff;
1967 isl_aff *lb;
1969 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
1970 n_div = isl_constraint_dim(c, isl_dim_div);
1972 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
1973 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
1974 isl_constraint_free(c);
1975 return 0;
1978 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
1979 aff = isl_aff_ceil(aff);
1981 lb = isl_aff_copy(aff);
1983 aff = isl_aff_neg(aff);
1984 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
1986 v = isl_basic_set_max_val(size->bset, aff);
1987 isl_aff_free(aff);
1989 if (isl_val_is_int(v)) {
1990 v = isl_val_add_ui(v, 1);
1991 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
1992 isl_val_free(size->bound->size);
1993 size->bound->size = isl_val_copy(v);
1994 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
1995 isl_aff_free(size->bound->lb);
1996 size->bound->lb = isl_aff_copy(lb);
1999 isl_val_free(v);
2000 isl_aff_free(lb);
2002 isl_constraint_free(c);
2004 return 0;
2007 /* Given a basic map "bounds" that maps parameters and input dimensions
2008 * to a single output dimension, look for an expression in the parameters
2009 * and input dimensions such that the range of the output dimension shifted
2010 * by this expression is a constant.
2012 * In particular, we currently only consider lower bounds on the output
2013 * dimension as candidate expressions.
2015 static int compute_array_dim_size(struct gpu_array_bound *bound,
2016 __isl_take isl_basic_map *bounds)
2018 struct gpu_size_info size;
2020 bounds = isl_basic_map_detect_equalities(bounds);
2021 bounds = check_stride(bound, bounds);
2023 bound->size = NULL;
2024 bound->lb = NULL;
2026 size.bound = bound;
2027 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2028 size.bset = isl_basic_map_wrap(bounds);
2029 size.bset = isl_basic_set_flatten(size.bset);
2030 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2031 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2032 &size);
2033 isl_basic_set_free(size.bset);
2035 return bound->size ? 0 : -1;
2038 /* Check if we can find a memory tile for the given array
2039 * based on the given accesses, and if so, put the results in "tile".
2041 * We project the accesses on each index in turn and look for a parametric
2042 * offset such that the size is constant.
2044 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2046 int i;
2048 for (i = 0; i < tile->n; ++i) {
2049 isl_map *access_i;
2050 isl_basic_map *hull;
2052 access_i = isl_map_copy(access);
2053 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2054 access_i = isl_map_project_out(access_i, isl_dim_out,
2055 1, tile->n - (i + 1));
2056 access_i = isl_map_compute_divs(access_i);
2057 hull = isl_map_simple_hull(access_i);
2058 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2059 return 0;
2062 return 1;
2065 /* Construct a map with input the shared tile loops and the loops that
2066 * will be wrapped around the threads that relates these later loops
2067 * to the thread indices and then projects them out.
2069 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2071 isl_map *priv;
2072 isl_map *tiling;
2073 isl_map *proj;
2074 isl_set *par;
2075 isl_space *dim;
2077 dim = isl_union_map_get_space(gen->shared_sched);
2079 if (gen->options->wrap)
2080 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2081 gen->shared_len, gen->n_block, gen->block_dim);
2082 else
2083 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2084 gen->shared_len, gen->n_block, gen->block_dim);
2086 priv = tiling;
2088 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2089 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2090 gen->n_block, "t");
2092 priv = isl_map_align_params(priv, isl_set_get_space(par));
2093 priv = isl_map_intersect_range(priv, par);
2095 dim = isl_map_get_space(priv);
2096 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2097 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2098 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2099 gen->shared_len);
2101 priv = isl_map_apply_range(priv, proj);
2103 return priv;
2106 /* Construct a map from domain_dim to domain_dim that increments
2107 * the dimension at position "pos" and leaves all other dimensions
2108 * constant.
2110 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2112 int i;
2113 int len = isl_space_dim(domain_dim, isl_dim_set);
2114 isl_space *dim;
2115 isl_basic_map *next;
2116 isl_local_space *ls;
2118 dim = isl_space_map_from_set(domain_dim);
2119 next = isl_basic_map_universe(isl_space_copy(dim));
2120 ls = isl_local_space_from_space(dim);
2122 for (i = 0; i < len; ++i) {
2123 isl_constraint *c;
2125 c = isl_equality_alloc(isl_local_space_copy(ls));
2126 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2127 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2128 if (i == pos)
2129 c = isl_constraint_set_constant_si(c, 1);
2130 next = isl_basic_map_add_constraint(next, c);
2133 isl_local_space_free(ls);
2135 return isl_map_from_basic_map(next);
2138 /* Check if the given access is coalesced.
2139 * That is, check whether incrementing the dimension that will get
2140 * wrapped over the last thread index results in incrementing
2141 * the last array index.
2143 * This function is only called for access relations without reuse.
2145 static int access_is_coalesced(struct gpu_gen *gen,
2146 __isl_keep isl_union_map *access)
2148 isl_space *dim;
2149 isl_map *access_map;
2150 isl_map *next_thread_x;
2151 isl_map *next_element;
2152 isl_map *map;
2153 int coalesced;
2155 access = isl_union_map_copy(access);
2156 access = isl_union_map_apply_domain(access,
2157 isl_union_map_copy(gen->tiled_sched));
2158 access_map = isl_map_from_union_map(access);
2160 dim = isl_map_get_space(access_map);
2161 dim = isl_space_domain(dim);
2162 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2164 dim = isl_map_get_space(access_map);
2165 dim = isl_space_range(dim);
2166 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2168 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2169 map = isl_map_apply_range(map, access_map);
2171 coalesced = isl_map_is_subset(map, next_element);
2173 isl_map_free(next_element);
2174 isl_map_free(map);
2176 return coalesced;
2179 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2180 * dimensions of the computed schedule, check if it is bijective for
2181 * fixed values of the first gen->shared_len dimensions.
2182 * We perform this check by equating these dimensions to parameters.
2184 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2186 int res;
2187 isl_set *par;
2188 isl_space *space;
2190 access = isl_map_copy(access);
2191 space = isl_space_params(isl_map_get_space(access));
2192 par = parametrization(space, gen->shared_len + gen->n_block,
2193 0, gen->shared_len, "s");
2194 access = isl_map_intersect_domain(access, par);
2195 res = isl_map_is_bijective(access);
2196 isl_map_free(access);
2198 return res;
2201 /* Look for the last shared tile loop that affects the offset of "tile"
2202 * and return the result.
2203 * If there is no such loop, then return the index of the loop
2204 * before the first shared tile loop, in particular gen->tile_first - 1.
2206 static int compute_tile_last_shared(struct gpu_gen *gen,
2207 struct gpu_array_tile *tile)
2209 int i, j;
2211 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2212 for (i = 0; i < tile->n; ++i) {
2213 isl_aff *lb;
2214 isl_aff *shift;
2216 lb = tile->bound[i].lb;
2217 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2218 break;
2220 shift = tile->bound[i].shift;
2221 if (!shift)
2222 continue;
2223 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2224 break;
2226 if (i < tile->n)
2227 break;
2230 return j;
2233 /* Look for the last shared tile loop that affects the offset of the
2234 * shared or private tile and store the result in group->last_shared.
2235 * If there is no such loop, then group->last_shared is set to a value
2236 * before the first shared tile loop, in particular gen->tile_first - 1.
2237 * If there is no tile defined on the array reference group,
2238 * then set group->last_shared to gen->shared_len - 1.
2240 static void set_last_shared(struct gpu_gen *gen,
2241 struct gpu_array_ref_group *group)
2243 struct gpu_array_tile *tile;
2245 group->last_shared = gen->shared_len - 1;
2247 tile = group->private_tile;
2248 if (!tile)
2249 tile = group->shared_tile;
2250 if (!tile)
2251 return;
2253 group->last_shared = compute_tile_last_shared(gen, tile);
2256 /* Compute a privatized copy of all access relations from reference groups that
2257 * are mapped to private memory and store the result in gen->privatization.
2259 static void compute_private_access(struct gpu_gen *gen)
2261 int i, j;
2262 isl_union_map *private;
2264 if (!gen->options->use_private_memory)
2265 return;
2267 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2269 for (i = 0; i < gen->prog->n_array; ++i) {
2270 struct gpu_array_info *array = &gen->prog->array[i];
2272 if (gpu_array_is_read_only_scalar(array))
2273 continue;
2275 for (j = 0; j < array->n_group; ++j) {
2276 if (!array->groups[j]->private_tile)
2277 continue;
2279 private = isl_union_map_union(private,
2280 group_access_relation(array->groups[j], 1, 1));
2284 if (isl_union_map_is_empty(private))
2285 isl_union_map_free(private);
2286 else {
2287 isl_union_map *priv;
2289 private = isl_union_map_apply_domain(private,
2290 isl_union_map_copy(gen->shared_sched));
2291 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2292 private = isl_union_map_apply_domain(private, priv);
2293 gen->private_access = private;
2297 /* Compute the size of the tile specified by "tile"
2298 * in number of elements and return the result.
2300 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2302 int i;
2303 isl_val *size;
2305 size = isl_val_one(ctx);
2307 for (i = 0; i < tile->n; ++i)
2308 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2310 return size;
2313 /* If max_shared_memory is not set to infinity (-1), then make
2314 * sure that the total amount of shared memory required by the
2315 * array reference groups mapped to shared memory is no larger
2316 * than this maximum.
2318 * We apply a greedy approach and discard (keep in global memory)
2319 * those groups that would result in a total memory size that
2320 * is larger than the maximum.
2322 static void check_shared_memory_bound(struct gpu_gen *gen)
2324 int i, j;
2325 isl_val *left, *size;
2327 if (gen->options->max_shared_memory < 0)
2328 return;
2330 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2332 for (i = 0; i < gen->prog->n_array; ++i) {
2333 struct gpu_array_info *array = &gen->prog->array[i];
2335 for (j = 0; j < array->n_group; ++j) {
2336 struct gpu_array_ref_group *group;
2338 group = array->groups[j];
2339 if (!group->shared_tile)
2340 continue;
2342 size = tile_size(gen->ctx, group->shared_tile);
2343 size = isl_val_mul_ui(size, array->size);
2345 if (isl_val_le(size, left)) {
2346 left = isl_val_sub(left, size);
2347 continue;
2349 isl_val_free(size);
2351 group->shared_tile = free_tile(group->shared_tile);
2355 isl_val_free(left);
2358 /* Fill up the groups array with singleton groups, i.e., one group
2359 * per reference, initializing the array, access, write, n_ref and refs fields.
2360 * In particular the access field is initialized to the scheduled
2361 * access relation of the array reference.
2363 * Return the number of elements initialized, i.e., the number of
2364 * active references in the current kernel.
2366 static int populate_array_references(struct gpu_array_info *array,
2367 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2369 int i;
2370 int n;
2371 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2373 n = 0;
2374 for (i = 0; i < array->n_ref; ++i) {
2375 isl_union_map *umap;
2376 isl_map *map;
2377 struct gpu_array_ref_group *group;
2378 struct gpu_stmt_access *access = array->refs[i];
2380 map = isl_map_copy(access->access);
2381 umap = isl_union_map_from_map(map);
2382 umap = isl_union_map_apply_domain(umap,
2383 isl_union_map_copy(sched));
2385 if (isl_union_map_is_empty(umap)) {
2386 isl_union_map_free(umap);
2387 continue;
2390 map = isl_map_from_union_map(umap);
2391 map = isl_map_detect_equalities(map);
2393 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2394 assert(group);
2395 group->array = array;
2396 group->access = map;
2397 group->write = access->write;
2398 group->refs = &array->refs[i];
2399 group->n_ref = 1;
2401 groups[n++] = group;
2404 return n;
2407 /* If group->n_ref == 1, then group->refs was set by
2408 * populate_array_references to point directly into
2409 * group->array->refs and should not be freed.
2410 * If group->n_ref > 1, then group->refs was set by join_groups
2411 * to point to a newly allocated array.
2413 static void free_array_ref_group(struct gpu_array_ref_group *group)
2415 if (!group)
2416 return;
2417 free_tile(group->shared_tile);
2418 free_tile(group->private_tile);
2419 isl_map_free(group->access);
2420 if (group->n_ref > 1)
2421 free(group->refs);
2422 free(group);
2425 /* Given a map where the input dimensions represent the tile loops,
2426 * eliminate the innermost of those that have a fixed value
2427 * until we reach one that does not (obviously) have a fixed value.
2429 static __isl_give isl_map *eliminate_fixed_inner_loops(
2430 __isl_take isl_map *access)
2432 int i, n;
2434 n = isl_map_dim(access, isl_dim_in);
2436 for (i = n - 1; i >= 0; --i) {
2437 if (!map_plain_is_fixed(access, isl_dim_in, i))
2438 break;
2439 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2441 return access;
2444 /* Check if the access relations of group1 and group2 overlap within
2445 * the innermost loop. In particular, ignore any inner dimension
2446 * with a fixed value.
2447 * The copying to and from shared memory will be performed within
2448 * the innermost actual loop so we are only allowed to consider
2449 * the dimensions up to that innermost loop while checking whether
2450 * two access relations overlap.
2452 static int accesses_overlap(struct gpu_array_ref_group *group1,
2453 struct gpu_array_ref_group *group2)
2455 int empty;
2456 isl_map *access1, *access2;
2458 access1 = isl_map_copy(group1->access);
2459 access1 = eliminate_fixed_inner_loops(access1);
2460 access2 = isl_map_copy(group2->access);
2461 access2 = eliminate_fixed_inner_loops(access2);
2462 access1 = isl_map_intersect(access1, access2);
2463 empty = isl_map_is_empty(access1);
2464 isl_map_free(access1);
2466 return !empty;
2469 /* Combine the given two groups into a single group, containing
2470 * the references of both groups.
2472 static struct gpu_array_ref_group *join_groups(
2473 struct gpu_array_ref_group *group1,
2474 struct gpu_array_ref_group *group2)
2476 int i;
2477 isl_ctx *ctx;
2478 struct gpu_array_ref_group *group;
2480 ctx = isl_map_get_ctx(group1->access);
2481 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2482 assert(group);
2483 group->array = group1->array;
2484 group->access = isl_map_union(isl_map_copy(group1->access),
2485 isl_map_copy(group2->access));
2486 group->write = group1->write || group2->write;
2487 group->n_ref = group1->n_ref + group2->n_ref;
2488 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2489 group->n_ref);
2490 assert(group->refs);
2491 for (i = 0; i < group1->n_ref; ++i)
2492 group->refs[i] = group1->refs[i];
2493 for (i = 0; i < group2->n_ref; ++i)
2494 group->refs[group1->n_ref + i] = group2->refs[i];
2496 return group;
2499 /* Combine the given two groups into a single group and free
2500 * the original two groups.
2502 static struct gpu_array_ref_group *join_groups_and_free(
2503 struct gpu_array_ref_group *group1,
2504 struct gpu_array_ref_group *group2)
2506 struct gpu_array_ref_group *group;
2508 group = join_groups(group1, group2);
2509 free_array_ref_group(group1);
2510 free_array_ref_group(group2);
2511 return group;
2514 /* Compute the private and/or shared memory tiles for the array
2515 * reference group "group" of array "array".
2517 * If the array is a read-only scalar or if the user requested
2518 * not to use shared or private memory, then we do not need to do anything.
2520 * We only try to compute a shared memory tile if there is any reuse
2521 * or if the access is not coalesced.
2523 * For computing a private memory tile, we also require that there is
2524 * some reuse. Moreover, we require that the access is private
2525 * to the thread. That is, we check that any given array element
2526 * is only accessed by a single thread.
2527 * We compute an access relation that maps the shared tile loop iterators
2528 * and the shared point loop iterators that will be wrapped over the
2529 * threads to the array elements.
2530 * We actually check that those iterators that will be wrapped
2531 * partition the array space. This check is stricter than necessary
2532 * since several iterations may be mapped onto the same thread
2533 * and then they could be allowed to access the same memory elements,
2534 * but our check does not allow this situation.
2536 * We also check that the index expression only depends on parallel
2537 * loops. That way, we can move those loops innermost and unroll them.
2538 * Again, we use a test that is stricter than necessary.
2539 * We actually check whether the index expression only depends
2540 * on the iterators that are wrapped over the threads.
2541 * These are necessarily parallel, but there may be more parallel loops.
2543 * Combining the injectivity of the first test with the single-valuedness
2544 * of the second test, we simply test for bijectivity.
2546 * If it turns out we can use registers, we compute the private memory
2547 * tile size using can_tile, after introducing a dependence
2548 * on the thread indices.
2550 static void compute_group_bounds_core(struct gpu_gen *gen,
2551 struct gpu_array_ref_group *group)
2553 isl_ctx *ctx = isl_space_get_ctx(group->array->dim);
2554 isl_union_map *access;
2555 int n_index = group->array->n_index;
2556 int no_reuse;
2557 isl_map *acc;
2558 int use_shared = gen->options->use_shared_memory;
2559 int use_private = gen->options->use_private_memory;
2561 if (!use_shared && !use_private)
2562 return;
2563 if (gpu_array_is_read_only_scalar(group->array))
2564 return;
2566 access = group_access_relation(group, 1, 1);
2567 no_reuse = isl_union_map_is_injective(access);
2569 if (use_shared && (!no_reuse || !access_is_coalesced(gen, access))) {
2570 group->shared_tile = create_tile(ctx, group->array->n_index);
2571 if (!can_tile(group->access, group->shared_tile))
2572 group->shared_tile = free_tile(group->shared_tile);
2575 if (!use_private || no_reuse) {
2576 isl_union_map_free(access);
2577 return;
2580 access = isl_union_map_apply_domain(access,
2581 isl_union_map_copy(gen->shared_sched));
2583 acc = isl_map_from_union_map(access);
2585 if (!access_is_bijective(gen, acc)) {
2586 isl_map_free(acc);
2587 return;
2590 group->private_tile = create_tile(gen->ctx, n_index);
2591 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2592 if (!can_tile(acc, group->private_tile))
2593 group->private_tile = free_tile(group->private_tile);
2595 isl_map_free(acc);
2598 /* Compute the private and/or shared memory tiles for the array
2599 * reference group "group" of array "array" and set last_shared.
2601 static void compute_group_bounds(struct gpu_gen *gen,
2602 struct gpu_array_ref_group *group)
2604 compute_group_bounds_core(gen, group);
2605 set_last_shared(gen, group);
2608 /* If two groups have overlapping access relations (as determined by
2609 * the "overlap" function) and if one of them involves a write,
2610 * then merge the two groups into one.
2611 * If "compute_bounds" is set, then call compute_group_bounds
2612 * on the merged groups.
2614 * Return the updated number of groups.
2616 static int group_writes(struct gpu_gen *gen,
2617 int n, struct gpu_array_ref_group **groups,
2618 int (*overlap)(struct gpu_array_ref_group *group1,
2619 struct gpu_array_ref_group *group2), int compute_bounds)
2621 int i, j;
2623 for (i = 0; i < n; ++i) {
2624 for (j = n - 1; j > i; --j) {
2625 if (!groups[i]->write && !groups[j]->write)
2626 continue;
2628 if (!overlap(groups[i], groups[j]))
2629 continue;
2631 groups[i] = join_groups_and_free(groups[i], groups[j]);
2632 if (compute_bounds)
2633 compute_group_bounds(gen, groups[i]);
2634 if (j != n - 1)
2635 groups[j] = groups[n - 1];
2636 n--;
2640 return n;
2643 /* If two groups have overlapping access relations (within the innermost
2644 * loop) and if one of them involves a write, then merge the two groups
2645 * into one.
2647 * Return the updated number of groups.
2649 static int group_overlapping_writes(struct gpu_gen *gen,
2650 int n, struct gpu_array_ref_group **groups)
2652 return group_writes(gen, n, groups, &accesses_overlap, 0);
2655 /* Check if the access relations of group1 and group2 overlap within
2656 * the outermost min(group1->last_shared, group2->last_shared) loops.
2658 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2659 struct gpu_array_ref_group *group2)
2661 int last_shared;
2662 int dim;
2663 int empty;
2664 isl_map *map_i, *map_j, *map;
2666 last_shared = group1->last_shared;
2667 if (group2->last_shared < last_shared)
2668 last_shared = group2->last_shared;
2669 map_i = isl_map_copy(group1->access);
2670 dim = isl_map_dim(map_i, isl_dim_in);
2671 map_i = isl_map_eliminate(map_i, isl_dim_in,
2672 last_shared + 1, dim - (last_shared + 1));
2673 map_j = isl_map_copy(group2->access);
2674 map_j = isl_map_eliminate(map_j, isl_dim_in,
2675 last_shared + 1, dim - (last_shared + 1));
2676 map = isl_map_intersect(map_i, map_j);
2677 empty = isl_map_is_empty(map);
2678 isl_map_free(map);
2680 return !empty;
2683 /* If two groups have overlapping access relations (within the outer
2684 * last_shared loops) and if one of them involves a write,
2685 * then merge the two groups into one.
2687 * Return the updated number of groups.
2689 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2690 struct gpu_array_ref_group **groups)
2692 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2695 /* Is the size of the tile specified by "tile" smaller than the sum of
2696 * the sizes of the tiles specified by "tile1" and "tile2"?
2698 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
2699 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2701 int smaller;
2702 isl_val *size, *size1, *size2;
2704 size = tile_size(ctx, tile);
2705 size1 = tile_size(ctx, tile1);
2706 size2 = tile_size(ctx, tile2);
2708 size = isl_val_sub(size, size1);
2709 size = isl_val_sub(size, size2);
2710 smaller = isl_val_is_neg(size);
2712 isl_val_free(size);
2714 return smaller;
2717 /* Given an initial grouping of array references and shared memory tiles
2718 * for each group that allows for a shared memory tile, merge two groups
2719 * if both have a shared memory tile, the merged group also has
2720 * a shared memory tile and the size of the tile for the merge group
2721 * is smaller than the sum of the tile sizes of the individual groups.
2723 * If merging two groups decreases the "last_shared" dimension of
2724 * one or both of the two groups, then we need to check for overlapping
2725 * writes again.
2727 * Return the number of groups after merging.
2729 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2730 struct gpu_array_info *array, int n,
2731 struct gpu_array_ref_group **groups)
2733 int i, j;
2734 int recompute_overlap = 0;
2735 isl_ctx *ctx = isl_space_get_ctx(array->dim);
2737 for (i = 0; i < n; ++i) {
2738 if (!groups[i]->shared_tile)
2739 continue;
2740 for (j = n - 1; j > i; --j) {
2741 isl_map *map;
2742 int empty;
2743 struct gpu_array_ref_group *group;
2745 if (!groups[j]->shared_tile)
2746 continue;
2748 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2749 isl_map_copy(groups[j]->access));
2750 empty = isl_map_is_empty(map);
2751 isl_map_free(map);
2753 if (empty)
2754 continue;
2756 group = join_groups(groups[i], groups[j]);
2757 compute_group_bounds(gen, group);
2758 if (!group->shared_tile ||
2759 !smaller_tile(ctx, group->shared_tile,
2760 groups[i]->shared_tile,
2761 groups[j]->shared_tile)) {
2762 free_array_ref_group(group);
2763 continue;
2766 if (group->last_shared < groups[i]->last_shared ||
2767 group->last_shared < groups[j]->last_shared)
2768 recompute_overlap = 1;
2769 free_array_ref_group(groups[i]);
2770 free_array_ref_group(groups[j]);
2771 groups[i] = group;
2772 if (j != n - 1)
2773 groups[j] = groups[n - 1];
2774 n--;
2778 if (recompute_overlap)
2779 n = group_last_shared_overlapping_writes(gen, n, groups);
2780 return n;
2783 /* Set array->n_group and array->groups to n and groups.
2785 * Additionally, set the "nr" field of each group
2786 * and the "group" field of each reference in each group.
2788 static void set_array_groups(struct gpu_array_info *array,
2789 int n, struct gpu_array_ref_group **groups)
2791 int i, j;
2793 array->n_group = n;
2794 array->groups = groups;
2796 for (i = 0; i < n; ++i) {
2797 groups[i]->nr = i;
2799 for (j = 0; j < groups[i]->n_ref; ++j)
2800 groups[i]->refs[j]->group = i;
2804 /* Group array references that should be considered together when
2805 * deciding whether to access them from private, shared or global memory.
2807 * In particular, if two array references overlap and if one of them
2808 * is a write, then the two references are grouped together.
2809 * We first perform an initial grouping based only on the access relation.
2810 * After computing shared and private memory tiles, we check for
2811 * overlapping writes again, but this time taking into account
2812 * the "last_shared" property.
2814 * Furthermore, if two groups admit a shared memory tile and if the
2815 * combination of the two also admits a shared memory tile, we merge
2816 * the two groups.
2818 static void group_array_references(struct gpu_gen *gen,
2819 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
2821 int i;
2822 int n;
2823 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2824 struct gpu_array_ref_group **groups;
2826 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
2827 array->n_ref);
2828 assert(groups);
2830 n = populate_array_references(array, sched, groups);
2832 n = group_overlapping_writes(gen, n, groups);
2834 for (i = 0; i < n; ++i)
2835 compute_group_bounds(gen, groups[i]);
2837 n = group_last_shared_overlapping_writes(gen, n, groups);
2839 n = group_common_shared_memory_tile(gen, array, n, groups);
2841 set_array_groups(array, n, groups);
2844 /* Take tiled_sched, project it onto the shared tile loops and
2845 * the loops that will be wrapped over the threads and
2846 * store the result in gen->shared_sched.
2847 * Also compute a projection that projects out the loops that will be
2848 * wrapped over the threads and store this projection in gen->shared_proj.
2850 static void compute_shared_sched(struct gpu_gen *gen)
2852 isl_space *dim;
2853 isl_map *proj;
2854 isl_set *par;
2855 isl_union_map *sched;
2857 sched = isl_union_map_copy(gen->tiled_sched);
2859 dim = isl_union_map_get_space(sched);
2860 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
2861 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
2863 dim = isl_union_map_get_space(sched);
2864 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
2866 gen->shared_sched = sched;
2867 gen->shared_proj = isl_union_map_from_map(proj);
2870 /* Group references of all arrays in the program.
2872 static void group_references(struct gpu_gen *gen)
2874 int i;
2875 isl_union_map *sched;
2877 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2878 isl_union_map_copy(gen->shared_proj));
2880 for (i = 0; i < gen->prog->n_array; ++i)
2881 group_array_references(gen, &gen->prog->array[i], sched);
2883 isl_union_map_free(sched);
2886 /* Free all array information that is local to the current kernel.
2888 static void free_local_array_info(struct gpu_gen *gen)
2890 int i, j;
2892 for (i = 0; i < gen->prog->n_array; ++i) {
2893 struct gpu_array_info *array = &gen->prog->array[i];
2895 for (j = 0; j < array->n_group; ++j)
2896 free_array_ref_group(array->groups[j]);
2897 free(array->groups);
2901 /* Compute the size of a bounding box around the origin and "set",
2902 * where "set" is assumed to contain only non-negative elements.
2903 * In particular, compute the maximal value of "set" in each direction
2904 * and add one.
2906 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
2907 __isl_keep isl_set *context)
2909 int i, n;
2910 isl_multi_pw_aff *mpa;
2912 n = isl_set_dim(set, isl_dim_set);
2913 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
2914 for (i = 0; i < n; ++i) {
2915 isl_space *space;
2916 isl_aff *one;
2917 isl_pw_aff *bound;
2919 bound = isl_set_dim_max(isl_set_copy(set), i);
2920 bound = isl_pw_aff_coalesce(bound);
2921 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
2923 space = isl_pw_aff_get_domain_space(bound);
2924 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2925 one = isl_aff_add_constant_si(one, 1);
2926 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
2927 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
2929 isl_set_free(set);
2931 return mpa;
2934 /* Compute the effective grid size as a list of the sizes in each dimension.
2936 * The grid size specified by the user or set by default
2937 * in read_grid_sizes() and applied in tile_schedule(),
2938 * may be too large for the given code in the sense that
2939 * it may contain blocks that don't need to execute anything.
2940 * We therefore don't return this grid size, but instead the
2941 * smallest grid size that ensures that all blocks that actually
2942 * execute code are included in the grid.
2944 * We first extract a description of the grid, i.e., the possible values
2945 * of the block ids, from gen->tiled_sched.
2946 * The block ids are parameters in gen->tiled_sched.
2947 * We simply need to change them into set dimensions.
2949 * Then, for each block dimension, we compute the maximal value of the block id
2950 * and add one.
2952 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
2953 struct ppcg_kernel *kernel)
2955 int i;
2956 isl_set *grid;
2958 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
2959 grid = isl_set_from_params(grid);
2960 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
2961 for (i = 0; i < gen->n_grid; ++i) {
2962 int pos;
2963 char name[20];
2965 snprintf(name, sizeof(name), "b%d", i);
2966 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
2967 assert(pos >= 0);
2968 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
2969 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
2972 return extract_size(grid, kernel->context);
2975 /* Compute the size of a fixed bounding box around the origin and "set",
2976 * where "set" is assumed to contain only non-negative elements,
2977 * and store the results in "size".
2978 * In particular, compute the maximal value of "set" in each direction
2979 * and add one.
2981 static void extract_fixed_size(__isl_take isl_set *set, int *size)
2983 int i, n;
2984 isl_local_space *ls;
2985 isl_aff *obj;
2987 n = isl_set_dim(set, isl_dim_set);
2988 ls = isl_local_space_from_space(isl_set_get_space(set));
2989 obj = isl_aff_zero_on_domain(ls);
2990 for (i = 0; i < n; ++i) {
2991 isl_val *max;
2993 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
2994 max = isl_set_max_val(set, obj);
2995 size[i] = isl_val_get_num_si(max) + 1;
2996 isl_val_free(max);
2997 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
2999 isl_aff_free(obj);
3000 isl_set_free(set);
3003 /* Compute the effective block size as a list of the sizes in each dimension
3004 * and store the sizes in kernel->block_dim.
3006 * The block size specified by the user or set by default
3007 * in read_block_sizes() and applied in thread_tile_schedule(),
3008 * may be too large for the given code in the sense that
3009 * it may contain threads that don't need to execute anything.
3010 * We therefore don't store this block size in kernel->block_dim,
3011 * but instead the smallest block size that ensures that all threads
3012 * that actually execute code are included in the block.
3014 * The current implementation eliminates all parameters, ensuring
3015 * that the size is a fixed constant in each dimension.
3016 * In principle we could also compute parametric sizes.
3017 * We would have to make sure to project out all b%d and t%d parameters,
3018 * however.
3020 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3022 int i;
3023 int nparam;
3024 isl_set *block;
3025 isl_multi_pw_aff *mpa;
3027 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3028 block = isl_set_from_params(block);
3029 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3030 kernel->n_block = gen->n_block;
3031 for (i = 0; i < gen->n_block; ++i) {
3032 int pos;
3033 char name[20];
3035 snprintf(name, sizeof(name), "t%d", i);
3036 pos = isl_set_find_dim_by_name(block, isl_dim_param, name);
3037 assert(pos >= 0);
3038 block = isl_set_equate(block, isl_dim_param, pos,
3039 isl_dim_set, i);
3041 nparam = isl_set_dim(block, isl_dim_param);
3042 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3044 extract_fixed_size(block, kernel->block_dim);
3047 void ppcg_kernel_free(void *user)
3049 struct ppcg_kernel *kernel = user;
3050 int i;
3052 if (!kernel)
3053 return;
3055 isl_multi_pw_aff_free(kernel->grid_size);
3056 isl_set_free(kernel->context);
3057 isl_union_set_free(kernel->arrays);
3058 isl_space_free(kernel->space);
3059 isl_ast_node_free(kernel->tree);
3061 for (i = 0; i < kernel->n_array; ++i)
3062 isl_pw_aff_list_free(kernel->array[i].bound);
3063 free(kernel->array);
3065 for (i = 0; i < kernel->n_var; ++i) {
3066 free(kernel->var[i].name);
3067 isl_vec_free(kernel->var[i].size);
3069 free(kernel->var);
3071 free(kernel);
3074 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3075 struct ppcg_kernel_var *var)
3077 int j;
3078 struct gpu_array_tile *tile;
3079 isl_printer *p;
3080 char *name;
3082 var->array = group->array;
3084 tile = group->private_tile;
3085 var->type = ppcg_access_private;
3086 if (!tile) {
3087 tile = group->shared_tile;
3088 var->type = ppcg_access_shared;
3091 p = isl_printer_to_str(ctx);
3092 p = print_array_name(p, group);
3093 var->name = isl_printer_get_str(p);
3094 isl_printer_free(p);
3096 var->size = isl_vec_alloc(ctx, group->array->n_index);
3098 for (j = 0; j < group->array->n_index; ++j)
3099 var->size = isl_vec_set_element_val(var->size, j,
3100 isl_val_copy(tile->bound[j].size));
3103 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3105 int i, j, n;
3107 n = 0;
3108 for (i = 0; i < gen->prog->n_array; ++i) {
3109 struct gpu_array_info *array = &gen->prog->array[i];
3111 for (j = 0; j < array->n_group; ++j) {
3112 struct gpu_array_ref_group *group = array->groups[j];
3113 if (group->private_tile || group->shared_tile)
3114 ++n;
3118 kernel->n_var = n;
3119 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3120 assert(kernel->var);
3122 n = 0;
3123 for (i = 0; i < gen->prog->n_array; ++i) {
3124 struct gpu_array_info *array = &gen->prog->array[i];
3126 for (j = 0; j < array->n_group; ++j) {
3127 struct gpu_array_ref_group *group = array->groups[j];
3128 if (!group->private_tile && !group->shared_tile)
3129 continue;
3130 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3131 ++n;
3136 /* The sizes of the arrays on the host that have been computed by
3137 * extract_array_info may depend on the parameters. Use the extra
3138 * constraints on the parameters that are valid at "host_domain"
3139 * to simplify these expressions and store the results in kernel->array.
3141 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3142 __isl_keep isl_set *host_domain)
3144 int i, j;
3145 isl_set *context;
3147 kernel->array = isl_calloc_array(gen->ctx,
3148 struct gpu_local_array_info, gen->prog->n_array);
3149 assert(kernel->array);
3150 kernel->n_array = gen->prog->n_array;
3152 context = isl_set_copy(host_domain);
3153 context = isl_set_params(context);
3155 for (i = 0; i < gen->prog->n_array; ++i) {
3156 struct gpu_array_info *array = &gen->prog->array[i];
3157 isl_pw_aff_list *local;
3159 if (array->n_group == 0)
3160 continue;
3162 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3164 for (j = 0; j < array->n_index; ++j) {
3165 isl_pw_aff *pwaff;
3167 pwaff = isl_pw_aff_copy(array->bound[j]);
3168 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3169 local = isl_pw_aff_list_add(local, pwaff);
3172 kernel->array[i].bound = local;
3174 isl_set_free(context);
3177 /* Find the element in gen->stmt that has the given "id".
3178 * Return NULL if no such gpu_stmt can be found.
3180 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3182 int i;
3184 for (i = 0; i < prog->n_stmts; ++i) {
3185 if (id == prog->stmts[i].id)
3186 break;
3189 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3192 /* Set gen->tile_len and gen->n_parallel to those of the statement
3193 * affected by the first map (part of the schedule)
3194 * on which this function is called.
3195 * Because of the way the schedule is constructed, the other statements
3196 * in the list, if any, should have the same values for these properties.
3198 static int extract_tile_len(__isl_take isl_map *map, void *user)
3200 struct gpu_gen *gen = (struct gpu_gen *) user;
3201 isl_id *id;
3202 struct gpu_stmt *stmt;
3204 id = isl_map_get_tuple_id(map, isl_dim_in);
3205 stmt = find_stmt(gen->prog, id);
3206 isl_id_free(id);
3208 isl_map_free(map);
3210 if (!stmt)
3211 isl_die(gen->ctx, isl_error_unknown,
3212 "statement not found", return -1);
3214 gen->tile_len = stmt->tile_len;
3215 gen->n_parallel = stmt->n_parallel;
3217 return -1;
3220 void ppcg_kernel_stmt_free(void *user)
3222 int i;
3223 struct ppcg_kernel_stmt *stmt = user;
3225 if (!stmt)
3226 return;
3228 switch (stmt->type) {
3229 case ppcg_kernel_copy:
3230 isl_ast_expr_free(stmt->u.c.index);
3231 isl_ast_expr_free(stmt->u.c.local_index);
3232 break;
3233 case ppcg_kernel_domain:
3234 for (i = 0; i < stmt->u.d.n_access; ++i) {
3235 isl_ast_expr_list_free(stmt->u.d.access[i].index);
3236 free(stmt->u.d.access[i].local_name);
3238 free(stmt->u.d.access);
3239 break;
3240 case ppcg_kernel_sync:
3241 break;
3244 free(stmt);
3247 /* Set the options of "context" to
3249 * { space -> [x] : x >= first }
3251 static __isl_give isl_ast_build *set_unroll(
3252 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3253 int first)
3255 isl_ctx *ctx;
3256 isl_map *unroll;
3257 isl_union_map *opt;
3259 ctx = isl_ast_build_get_ctx(build);
3261 space = isl_space_from_domain(space);
3262 space = isl_space_add_dims(space, isl_dim_out, 1);
3263 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3264 unroll = isl_map_universe(space);
3265 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3266 opt = isl_union_map_from_map(unroll);
3268 build = isl_ast_build_set_options(build, opt);
3270 return build;
3273 /* Return a list of isl_ids of the form "prefix%d".
3275 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3276 int n, const char *prefix)
3278 int i;
3279 char name[10];
3280 isl_id_list *names;
3282 names = isl_id_list_alloc(ctx, n);
3283 for (i = 0; i < n; ++i) {
3284 isl_id *id;
3286 snprintf(name, sizeof(name), "%s%d", prefix, i);
3287 id = isl_id_alloc(ctx, name, NULL);
3288 names = isl_id_list_add(names, id);
3291 return names;
3294 /* Extend the schedule "schedule" with the part of "extension"
3295 * starting at "first" up to "len".
3297 static __isl_give isl_union_map *extend_schedule(
3298 __isl_take isl_union_map *schedule,
3299 __isl_take isl_union_map *extension, int first, int len)
3301 isl_space *space;
3302 isl_map *proj;
3303 isl_union_map *umap;
3304 isl_set *set;
3306 space = isl_union_map_get_space(schedule);
3307 space = isl_space_set_from_params(space);
3308 space = isl_space_add_dims(space, isl_dim_set, len);
3309 proj = isl_set_identity(isl_set_universe(space));
3310 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3311 extension = isl_union_map_apply_range(extension,
3312 isl_union_map_from_map(proj));
3314 schedule = isl_union_map_range_product(schedule, extension);
3316 return schedule;
3319 /* This function is called for each access to an array in each instance
3320 * in the kernel of some statement in the original code.
3321 * Replace that access by an access to global, shared or private memory
3322 * and store the results in *kernel_access.
3324 * Since the array in shared or private memory is just
3325 * a shifted copy of part of the original array, we simply need
3326 * to subtract the lower bound, which was computed in can_tile.
3327 * If any of the indices is strided, then we first add
3328 * shared_tile->bound[i].shift and divide by shared_tile->bound[i].stride.
3330 * If the given array is accessed directly from global memory,
3331 * we don't need to perform any shifting and simply simplify
3332 * the expression in the context of the domain instead.
3334 * If the array space (range of access) has no name, then we are
3335 * accessing an iterator in the original program.
3337 * The input stmt_access->access relation maps the iteration domain
3338 * of the current statement to an array element.
3339 * The first step is to reformulate
3340 * this access relation in terms of the loop iterators of the generated
3341 * code through precomposition with gen->stmt_it.
3343 * The expressions in "tile" are formulated in terms of the first
3344 * gen->shared_len dimensions of the computed schedule using the mapping
3345 * sched2shared which maps the loop iterators to these dimensions.
3347 static void compute_index_expression(struct gpu_gen *gen,
3348 struct ppcg_kernel_access *kernel_access,
3349 struct gpu_stmt_access *stmt_access, __isl_keep isl_map *stmt_it,
3350 __isl_keep isl_map *sched2shared, __isl_keep isl_ast_build *build)
3352 isl_map *access;
3353 isl_pw_multi_aff *pma;
3354 int i;
3355 unsigned n_index;
3356 struct gpu_array_tile *tile = NULL;
3358 if (isl_map_has_tuple_name(stmt_access->access, isl_dim_out)) {
3359 int i;
3360 const char *name;
3361 struct gpu_array_ref_group *group;
3362 isl_printer *p;
3364 name = isl_map_get_tuple_name(stmt_access->access, isl_dim_out);
3366 for (i = 0; i < gen->prog->n_array; ++i) {
3367 if (strcmp(name, gen->prog->array[i].name))
3368 continue;
3369 kernel_access->array = &gen->prog->array[i];
3370 kernel_access->local_array = &gen->kernel->array[i];
3372 assert(kernel_access->array);
3373 group = kernel_access->array->groups[stmt_access->group];
3374 p = isl_printer_to_str(gen->ctx);
3375 p = print_array_name(p, group);
3376 kernel_access->local_name = isl_printer_get_str(p);
3377 isl_printer_free(p);
3378 tile = group->private_tile;
3379 kernel_access->type = ppcg_access_private;
3380 if (!tile) {
3381 tile = group->shared_tile;
3382 kernel_access->type = ppcg_access_shared;
3385 if (!tile)
3386 kernel_access->type = ppcg_access_global;
3388 n_index = isl_map_dim(stmt_access->access, isl_dim_out);
3389 kernel_access->index = isl_ast_expr_list_alloc(gen->ctx, n_index);
3391 if (n_index == 0)
3392 return;
3394 access = isl_map_copy(stmt_access->access);
3395 access = isl_map_apply_range(isl_map_copy(stmt_it), access);
3396 pma = isl_pw_multi_aff_from_map(access);
3397 pma = isl_pw_multi_aff_coalesce(pma);
3399 for (i = 0; i < n_index; ++i) {
3400 isl_set *domain;
3401 isl_pw_aff *index;
3402 isl_ast_expr *expr;
3404 index = isl_pw_multi_aff_get_pw_aff(pma, i);
3406 if (!kernel_access->array) {
3407 } else if (!tile) {
3408 domain = isl_map_domain(isl_map_copy(stmt_it));
3409 index = isl_pw_aff_coalesce(index);
3410 index = isl_pw_aff_gist(index, domain);
3411 } else {
3412 domain = isl_map_domain(isl_map_copy(stmt_it));
3413 index = shift_index(index, kernel_access->array,
3414 &tile->bound[i], domain,
3415 isl_map_copy(sched2shared));
3418 expr = isl_ast_build_expr_from_pw_aff(build, index);
3420 kernel_access->index = isl_ast_expr_list_add(
3421 kernel_access->index, expr);
3424 isl_pw_multi_aff_free(pma);
3427 /* This function is called for each instance of a user statement
3428 * in the kernel.
3430 * We attach a struct ppcg_kernel_stmt to the "node", containing
3431 * local information about the accesses.
3432 * This information is computed from stmt_it, which expresses the domain
3433 * elements in terms of the generated loops, and sched2shared,
3434 * which expresses the first shared_len dimensions of the schedule
3435 * computed by PPCG in terms of the generated loops.
3437 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3438 __isl_keep isl_ast_build *build, void *user)
3440 struct gpu_gen *gen = (struct gpu_gen *) user;
3441 struct ppcg_kernel_stmt *stmt;
3442 isl_id *id;
3443 isl_map *stmt_it, *sched2shared;
3444 isl_ast_expr *expr, *arg;
3445 isl_union_map *schedule;
3446 int i, n;
3447 struct gpu_stmt_access *access;
3449 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3450 if (!stmt)
3451 return isl_ast_node_free(node);
3453 expr = isl_ast_node_user_get_expr(node);
3454 arg = isl_ast_expr_get_op_arg(expr, 0);
3455 id = isl_ast_expr_get_id(arg);
3457 schedule = isl_ast_build_get_schedule(build);
3458 stmt_it = isl_map_reverse(isl_map_from_union_map(schedule));
3459 sched2shared = compute_sched_to_shared(gen, isl_map_copy(stmt_it));
3461 stmt->type = ppcg_kernel_domain;
3462 stmt->u.d.stmt = find_stmt(gen->prog, id);
3463 if (!stmt->u.d.stmt)
3464 goto error;
3466 n = 0;
3467 for (access = stmt->u.d.stmt->accesses; access; access = access->next)
3468 ++n;
3470 stmt->u.d.access = isl_calloc_array(gen->ctx,
3471 struct ppcg_kernel_access, n);
3472 if (!stmt->u.d.access)
3473 goto error;
3475 stmt->u.d.n_access = n;
3477 access = stmt->u.d.stmt->accesses;
3478 for (i = 0; i < n; ++i, access = access->next) {
3479 compute_index_expression(gen, &stmt->u.d.access[i], access,
3480 stmt_it, sched2shared, build);
3483 isl_id_free(id);
3484 isl_map_free(stmt_it);
3485 isl_map_free(sched2shared);
3486 isl_ast_expr_free(arg);
3487 isl_ast_expr_free(expr);
3489 id = isl_id_alloc(gen->ctx, NULL, stmt);
3490 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3491 return isl_ast_node_set_annotation(node, id);
3492 error:
3493 isl_id_free(id);
3494 isl_map_free(stmt_it);
3495 ppcg_kernel_stmt_free(stmt);
3496 isl_map_free(sched2shared);
3497 return isl_ast_node_free(node);
3500 /* This function is called when code has been generated for the shared
3501 * tile loops. The "schedule" refers only to the original statements.
3503 * We extend the schedule with that part of gen->local_sched that hasn't
3504 * been taken into account yet. This introduces parameters referring
3505 * to thread ids in the schedule, so we add them (with the appropriate
3506 * bounds to the context as well).
3507 * Finally, we set the appropriate unrolling options
3508 * if gen->first_unroll is set.
3510 static __isl_give isl_ast_node *create_domain_leaf(
3511 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
3512 void *user)
3514 struct gpu_gen *gen = (struct gpu_gen *) user;
3515 isl_space *space;
3516 isl_union_map *sched;
3517 isl_ast_node *tree;
3518 isl_set *set;
3519 isl_id_list *iterators;
3520 int n;
3522 schedule = extend_schedule(schedule,
3523 isl_union_map_copy(gen->local_sched),
3524 gen->shared_len, gen->thread_tiled_len);
3526 space = isl_ast_build_get_schedule_space(build);
3527 set = isl_set_universe(space);
3528 set = add_bounded_parameters(set, gen->kernel->n_block,
3529 gen->kernel->block_dim, "t");
3530 build = isl_ast_build_restrict(build, set);
3532 n = gen->thread_tiled_len - gen->shared_len;
3534 if (gen->first_unroll >= 0) {
3535 space = isl_space_set_alloc(gen->ctx, 0, n);
3536 build = set_unroll(build, space, gen->first_unroll);
3538 iterators = generate_names(gen->ctx, n, "c");
3539 build = isl_ast_build_set_iterators(build, iterators);
3540 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
3541 tree = isl_ast_build_ast_from_schedule(build, schedule);
3542 isl_ast_build_free(build);
3544 return tree;
3547 /* This function is called for each statement node in the AST of the code
3548 * for copying to or from shared/private memory.
3549 * Attach a pointer to a ppcg_kernel_stmt representing the copy
3550 * statement to the node.
3551 * The statement name is {read,write}_{shared,private}_<array>.
3553 * The schedule is of the form
3555 * [A -> T] -> L
3557 * where A refers to a piece of an array and T to the corresponding
3558 * shifted tile. We split this schedule into mappings L -> A and L -> T
3559 * and store the corresponding expressions in stmt->index and stmt->local_index,
3560 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
3562 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
3563 __isl_keep isl_ast_build *build, void *user)
3565 struct gpu_gen *gen = (struct gpu_gen *) user;
3566 struct ppcg_kernel_stmt *stmt;
3567 isl_id *id;
3568 isl_ast_expr *expr;
3569 isl_space *space;
3570 isl_map *access, *local_access, *map;
3571 isl_pw_multi_aff *pma;
3572 const char *name;
3573 int array_index;
3575 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3576 if (!stmt)
3577 return isl_ast_node_free(node);
3579 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
3580 name = isl_map_get_tuple_name(access, isl_dim_in);
3581 stmt->u.c.read = !strncmp(name, "read", 4);
3582 access = isl_map_reverse(access);
3583 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
3584 local_access = isl_map_copy(access);
3586 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
3587 id = isl_map_get_tuple_id(access, isl_dim_out);
3588 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3589 access = isl_map_apply_range(access, map);
3590 pma = isl_pw_multi_aff_from_map(access);
3591 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3592 stmt->u.c.index = expr;
3594 map = isl_map_range_map(isl_map_universe(space));
3595 id = isl_map_get_tuple_id(local_access, isl_dim_out);
3596 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3597 local_access = isl_map_apply_range(local_access, map);
3598 pma = isl_pw_multi_aff_from_map(local_access);
3599 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3600 stmt->u.c.local_index = expr;
3602 stmt->u.c.array = gen->copy_group->array;
3603 array_index = stmt->u.c.array - gen->prog->array;
3604 stmt->u.c.local_array = &gen->kernel->array[array_index];
3605 stmt->type = ppcg_kernel_copy;
3607 id = isl_id_alloc(gen->ctx, NULL, stmt);
3608 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3609 return isl_ast_node_set_annotation(node, id);
3612 /* Given a schedule of the form
3614 * [S -> A] -> L
3616 * (with S the first shared_len dimensions of the computed schedule,
3617 * A the array and L the schedule correponding to the generated loops),
3618 * indicating where the copying the array elements that need to be copied,
3619 * construct code for performing the copying.
3621 * "group" is the array reference group that is being copied
3622 * "type" is either "read" or "write"
3623 * private is set if copying needs to be performed to/from registers
3625 * We first construct a mapping to a shifted tile of the array,
3627 * [S -> A] -> T(S,A) (1)
3629 * If private is set, then we also use this mapping as a schedule
3630 * (which is already thread-specific and will be completely unrolled).
3631 * Otherwise, we wrap/tile the range over the threads.
3632 * The result is
3634 * [S -> A] -> T'(S,A)
3636 * Combined with the given schedule, we have
3638 * [S -> A] -> [L -> T'(S,A)] (2)
3640 * From the shifted tile mapping, we construct a mapping
3642 * [S -> A] -> [A -> T(S,A)]
3644 * and apply it to the schedule (2), obtaining
3646 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
3648 * Note that we can project out S because it is uniquely defined by L.
3650 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
3651 __isl_take isl_map *sched,
3652 const char *type, struct gpu_array_ref_group *group,
3653 __isl_take isl_ast_build *build, int private)
3655 const char *array_name;
3656 const char *mem = private ? "private" : "shared";
3657 char *name;
3658 isl_space *space;
3659 isl_ast_node *tree;
3660 isl_map *schedule, *shift, *map;
3661 isl_set *set;
3662 isl_id_list *iterators;
3663 int n;
3665 shift = isl_set_unwrap(isl_map_domain(isl_map_copy(sched)));
3666 array_name = isl_map_get_tuple_name(shift, isl_dim_out);
3667 shift = shift_access(shift, group);
3669 schedule = isl_map_copy(shift);
3670 if (!private)
3671 schedule = tile_access_schedule(gen, schedule);
3673 n = isl_map_dim(schedule, isl_dim_out);
3674 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
3675 set = add_bounded_parameters(set, gen->kernel->n_block,
3676 gen->kernel->block_dim, "t");
3678 schedule = isl_map_range_product(sched, schedule);
3680 assert(array_name);
3681 name = isl_alloc_array(gen->ctx, char,
3682 strlen(type) + sizeof("_private_") + strlen(array_name) + 20);
3683 if (group->array->n_group > 1)
3684 sprintf(name, "%s_%s_%s_%d", type, mem, array_name, group->nr);
3685 else
3686 sprintf(name, "%s_%s_%s", type, mem, array_name);
3687 shift = isl_map_set_tuple_name(shift,
3688 isl_dim_out, name + strlen(type) + 1);
3690 space = isl_space_domain(isl_map_get_space(shift));
3691 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
3692 map = isl_map_range_product(map, shift);
3694 schedule = isl_map_apply_domain(schedule, map);
3696 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, name);
3697 free(name);
3699 build = isl_ast_build_restrict(build, set);
3701 gen->copy_group = group;
3703 if (private) {
3704 space = isl_space_range(isl_map_get_space(schedule));
3705 space = isl_space_range(isl_space_unwrap(space));
3706 build = set_unroll(build, space, 0);
3708 iterators = generate_names(gen->ctx, n, "c");
3709 build = isl_ast_build_set_iterators(build, iterators);
3710 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
3711 tree = isl_ast_build_ast_from_schedule(build,
3712 isl_union_map_from_map(schedule));
3713 isl_ast_build_free(build);
3715 return tree;
3718 /* Return code for reading into or writing from shared memory
3719 * the given array reference group.
3721 * If we are performing a read from global memory to shared memory and
3722 * if the array involved is not a scalar, then we copy
3723 * the entire tile to shared memory. This may result in some extra
3724 * elements getting copied, but it should lead to simpler code
3725 * (which means that fewer registers may be needed) and less divergence.
3727 * Otherwise, we only copy the elements that will be read or have been written
3728 * in the kernel.
3731 * The input "sched" is of the form.
3733 * type[S -> A] -> L
3735 * with S the first shared_len dimensions of the computed schedule,
3736 * A the array and L the schedule correponding to the generated loops.
3738 * We first drop "type",
3740 * [S -> A] -> L
3742 * If the above conditions are satisfied, we project out A,
3743 * resulting in
3745 * S -> L
3747 * and then introduce the group tile [S -> T], resulting in
3749 * [S -> T] -> L
3751 static __isl_give isl_ast_node *copy_group_shared_accesses(
3752 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3753 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3755 const char *type;
3756 int read;
3757 isl_union_map *access;
3759 type = isl_map_get_tuple_name(sched, isl_dim_in);
3760 read = !strcmp(type, "read");
3762 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3764 if (read && group->array->n_index > 0) {
3765 isl_space *space;
3766 isl_map *map;
3768 space = isl_space_domain(isl_map_get_space(sched));
3769 space = isl_space_unwrap(space);
3770 map = isl_map_domain_map(isl_map_universe(space));
3771 sched = isl_map_apply_domain(sched, map);
3773 map = group_tile(group);
3774 map = isl_map_reverse(isl_map_domain_map(map));
3775 sched = isl_map_apply_domain(sched, map);
3778 return copy_access(gen, sched, type, group, build, 0);
3781 /* Return code for reading into or writing from private memory
3782 * the given array reference group.
3784 * Let S be the first shared_len dimensions of the computed schedule,
3785 * D the iteration domains, A the array and L the schedule correponding
3786 * to the generated loops.
3787 * "sched" is of the form
3789 * type[S -> A] -> L
3791 * where type is either "read" or "write".
3792 * We apply the privatization D -> S(t), with t the thread ids,
3793 * to the access relation D -> A to obtain the privatized access relation
3795 * S(t) -> A
3797 * We drop the type from "sched" and intersect with the privatized access
3798 * relation to obtain
3800 * [S(t) -> A] -> L
3802 static __isl_give isl_ast_node *copy_group_private_accesses(
3803 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3804 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3806 const char *type;
3807 int read;
3808 isl_union_map *priv;
3809 isl_union_map *access;
3810 isl_map *access_map;
3812 type = isl_map_get_tuple_name(sched, isl_dim_in);
3813 read = !strcmp(type, "read");
3815 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
3816 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3817 priv);
3819 access = group_access_relation(group, read, !read);
3820 access = isl_union_map_apply_domain(access, priv);
3821 access_map = isl_map_from_union_map(access);
3823 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3824 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
3826 return copy_access(gen, sched, type, group, build, 1);
3829 /* Return code for reading into or writing from shared or private memory.
3831 * "schedule" is of the form
3833 * type[S -> A] -> L
3835 * with S be the first shared_len dimensions of the computed schedule,
3836 * A the array and L the schedule correponding to the generated loops.
3837 * The array reference group is attached to "type".
3839 static __isl_give isl_ast_node *create_access_leaf(
3840 struct gpu_gen *gen, __isl_take isl_map *schedule,
3841 __isl_take isl_ast_build *build)
3843 struct gpu_array_ref_group *group;
3844 isl_id *id;
3846 id = isl_map_get_tuple_id(schedule, isl_dim_in);
3847 group = isl_id_get_user(id);
3848 isl_id_free(id);
3850 if (group->private_tile)
3851 return copy_group_private_accesses(gen, group, schedule,
3852 build);
3853 else
3854 return copy_group_shared_accesses(gen, group, schedule,
3855 build);
3858 /* Create a domain node representing a synchronization.
3860 static __isl_give isl_ast_node *create_sync_leaf(
3861 struct gpu_gen *gen, __isl_take isl_map *schedule,
3862 __isl_take isl_ast_build *build)
3864 struct ppcg_kernel_stmt *stmt;
3865 isl_id *id;
3866 isl_space *space;
3867 isl_ast_node *node;
3868 isl_ast_expr *expr;
3870 isl_map_free(schedule);
3872 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3873 if (!stmt)
3874 return NULL;
3876 stmt->type = ppcg_kernel_sync;
3878 space = isl_ast_build_get_schedule_space(build);
3879 space = isl_space_from_domain(space);
3880 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
3881 expr = isl_ast_build_call_from_pw_multi_aff(build,
3882 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
3883 node = isl_ast_node_alloc_user(expr);
3884 isl_ast_build_free(build);
3886 id = isl_id_alloc(gen->ctx, NULL, stmt);
3887 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3888 return isl_ast_node_set_annotation(node, id);
3891 /* This function is called during the code generation at the point
3892 * where the schedule domain element is completely determined by
3893 * the generated code. The input schedule contains the original
3894 * statements as well as synchronization and copy "statements".
3895 * The latter are scheduled at different points than any of the original
3896 * statements, so they will only arrive here in isolation.
3898 * If the current schedule only refers to a single statement,
3899 * we check if it is a copy or synchronization statement and
3900 * call the appropriate functions.
3901 * Otherwise, we assume we are dealing with the original statements
3902 * and we call create_domain_leaf.
3904 static __isl_give isl_ast_node *create_kernel_leaf(
3905 __isl_take isl_ast_build *build, void *user)
3907 struct gpu_gen *gen = (struct gpu_gen *) user;
3908 isl_map *map;
3909 isl_union_map *schedule;
3910 const char *name;
3912 schedule = isl_ast_build_get_schedule(build);
3914 if (isl_union_map_n_map(schedule) != 1)
3915 return create_domain_leaf(schedule, build, user);
3917 map = isl_map_from_union_map(schedule);
3918 name = isl_map_get_tuple_name(map, isl_dim_in);
3919 if (!strcmp(name, "read") || !strcmp(name, "write"))
3920 return create_access_leaf(gen, map, build);
3921 if (!strcmp(name, "sync"))
3922 return create_sync_leaf(gen, map, build);
3924 return create_domain_leaf(isl_union_map_from_map(map), build, user);
3927 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
3928 * have value 0) and all even schedule dimensions as "unroll".
3930 * That is, the options look as follows
3932 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
3933 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
3935 * The even positions are used to be able to schedule copying blocks
3936 * and synchronization before or after each level of the shared memory
3937 * tile loops and we want to make sure that code for these is generated
3938 * separately (within each level).
3940 static __isl_give isl_ast_build *set_atomic_and_unroll(
3941 __isl_take isl_ast_build *build,
3942 __isl_take isl_space *space, int sched_len)
3944 isl_ctx *ctx;
3945 isl_map *map;
3946 isl_constraint *c;
3947 isl_union_map *opt;
3948 isl_local_space *ls;
3949 int i, n;
3951 ctx = isl_ast_build_get_ctx(build);
3953 space = isl_space_params(space);
3954 space = isl_space_add_dims(space, isl_dim_set, sched_len);
3955 space = isl_space_from_domain(space);
3956 space = isl_space_add_dims(space, isl_dim_out, 2);
3957 map = isl_map_universe(isl_space_copy(space));
3958 for (i = 0; i < sched_len; i += 2)
3959 map = isl_map_fix_si(map, isl_dim_in, i, 0);
3960 ls = isl_local_space_from_space(isl_map_get_space(map));
3961 c = isl_equality_alloc(ls);
3962 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3963 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3964 c = isl_constraint_set_constant_si(c, 1);
3965 map = isl_map_add_constraint(map, c);
3966 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3967 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
3968 opt = isl_union_map_from_map(map);
3970 map = isl_map_universe(space);
3971 ls = isl_local_space_from_space(isl_map_get_space(map));
3972 c = isl_equality_alloc(ls);
3973 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3974 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3975 map = isl_map_add_constraint(map, c);
3976 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3977 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
3978 opt = isl_union_map_add_map(opt, map);
3980 build = isl_ast_build_set_options(build, opt);
3982 return build;
3985 /* Return a map that maps a space of dimension gen->shared_len
3986 * to its last dimensions starting at gen->tile_first.
3987 * The range is of dimension
3989 * 2 * (gen->shared_len - gen->tile_first) + 1
3991 * The input dimensions are mapped to the odd dimensions in the output,
3992 * while the even dimensions (except 2*pos) are fixed to 0.
3993 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
3994 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
3995 * are mapped to the output. The remaining input dimensions are projected
3996 * out and the corresponding output dimensions are fixed to 0.
3998 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
3999 __isl_take isl_space *space, int pos, int val)
4001 int i, n;
4002 isl_map *proj;
4004 space = isl_space_set_from_params(space);
4005 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4006 space = isl_space_map_from_set(space);
4007 proj = isl_map_identity(space);
4008 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4009 n = gen->shared_len - gen->tile_first;
4010 for (i = 0; i <= n; ++i) {
4011 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4012 if (i == pos)
4013 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4014 else
4015 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4018 if (pos < 0)
4019 return proj;
4021 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4022 gen->shared_len - (gen->tile_first + pos));
4023 for (i = pos; i < n; ++i)
4024 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4026 return proj;
4029 /* Given the AST context schedule "schedule" and the mapping from
4030 * domains to the shared tile loops "shared_sched", add a schedule
4031 * for a synchronization operation at position "val" of loop level "pos".
4033 * schedule is of the form
4035 * D -> L
4037 * (with D the iteration domains and L the already generated loops),
4038 * while shared_sched is of the form
4040 * D -> S
4042 * We combine them into
4044 * L -> S
4046 * apply a mapping
4048 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4050 * and use the result as a schedule for "sync".
4052 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4053 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4054 __isl_keep isl_union_map *shared_sched, int pos, int val)
4056 isl_space *space;
4057 isl_map *proj, *map;
4059 shared_sched = isl_union_map_copy(shared_sched);
4060 schedule = isl_union_map_copy(schedule);
4062 space = isl_union_map_get_space(shared_sched);
4063 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4064 map = isl_map_from_union_map(schedule);
4066 proj = insert_even(gen, space, pos, val);
4067 map = isl_map_apply_range(map, proj);
4068 map = isl_map_from_range(isl_map_wrap(map));
4069 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4071 res = isl_union_map_add_map(res, map);
4073 return res;
4076 /* Given the AST context schedule "schedule" and the mapping from
4077 * domains to the shared tile loops "shared_sched", add a schedule
4078 * for copying an array reference group to/from shared/private memory.
4079 * "read" is set if data should be copied from global memory
4080 * to shared/private memory.
4081 * "k" represents the current group
4082 * "s" is the total number of groups
4084 * We schedule an operation before or after the innermost loop
4085 * of "shared_sched" that affects the tile of the array reference group.
4087 * schedule is of the form
4089 * D -> L
4091 * (with D the iteration domains and L the already generated loops),
4092 * while shared_sched is of the form
4094 * D -> S
4096 * We first compute the access relation for the reference group
4098 * D -> A
4100 * and combine it with shared_sched into
4102 * D -> [S -> A]
4104 * If this results in an empty relation, no copying needs to be performed
4105 * at this point.
4106 * Otherwise, we invert the relation and combine it with "schedule" into
4108 * [S -> A] -> L
4110 * The actual additional piece of the schedule is obtained from combining
4112 * [S -> A] -> S
4114 * with a mapping
4116 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4118 * The position of "val" corresponds to the innermost loop that affects
4119 * the tile and the value indicates where the copying is scheduled
4120 * with respect to the actual kernel code (at value 0).
4121 * Reads are schedule before the code, writes to global memory from
4122 * private memory are scheduled at values 1 to s, writes to global
4123 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4125 * If we are scheduling a read from global memory to shared memory,
4126 * we insert a synchronization before the kernel code (at the innermost
4127 * level).
4128 * If we are scheduling a write to global memory, then we add
4129 * a synchronization after all writes (at value 2 *s + 2).
4130 * However, there is no need for a synchronization after the outermost loop.
4131 * A write to global memory from private memory at the innermost level
4132 * does not require a synchronization, because it is covered by
4133 * the synchronization after the kernel inserted by body_schedule.
4135 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4136 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4137 __isl_keep isl_union_map *shared_sched,
4138 struct gpu_array_ref_group *group, int read, int k, int s)
4140 int n;
4141 int pos, val;
4142 isl_space *space;
4143 isl_union_map *access;
4144 isl_map *map, *proj, *access_map;
4145 isl_id *id;
4147 access = group_access_relation(group, read, !read);
4148 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4149 access);
4151 if (isl_union_map_is_empty(access)) {
4152 isl_union_map_free(access);
4153 return res;
4156 access = isl_union_map_reverse(access);
4157 access = isl_union_map_apply_range(access,
4158 isl_union_map_copy(schedule));
4159 access_map = isl_map_from_union_map(access);
4161 space = isl_space_copy(group->array->dim);
4162 space = isl_space_from_range(space);
4163 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4164 map = isl_map_domain_map(isl_map_universe(space));
4166 space = isl_union_map_get_space(schedule);
4167 pos = group->last_shared + 1 - gen->tile_first;
4168 assert(pos >= 0);
4169 if (read)
4170 val = -2 - k;
4171 else if (group->private_tile)
4172 val = 1 + k;
4173 else
4174 val = 1 + s + 1 + k;
4175 proj = insert_even(gen, space, pos, val);
4176 map = isl_map_apply_range(map, proj);
4178 access_map = isl_map_range_product(access_map, map);
4180 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4181 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4183 res = isl_union_map_add_map(res, access_map);
4185 n = gen->shared_len - gen->tile_first;
4186 if (read) {
4187 if (!group->private_tile)
4188 res = add_sync_schedule(gen, res, schedule,
4189 shared_sched, n, -1);
4190 } else {
4191 if (pos == 0)
4192 return res;
4193 if (pos == n && group->private_tile)
4194 return res;
4195 res = add_sync_schedule(gen, res, schedule, shared_sched,
4196 pos, 2 * s + 2);
4199 return res;
4202 /* Return a schedule for the shared tile loops based on the current
4203 * AST context schedule.
4205 * We create a "shared_sched" that maps the domains to the first
4206 * shared_len dimensions of the computed schedule, project out the
4207 * first tile_first dimensions (as these are already covered by
4208 * the host code) and insert "statement-level" dimensions at even
4209 * positions so that we can schedule copy blocks and synchronization
4210 * before/after each level.
4212 * In particular, copy blocks are inserted inside the innermost
4213 * level that affect the tile. For the copying to global memory,
4214 * those from private memory are scheduled before those from shared
4215 * memory such that synchronization can be inserted between the two
4216 * at the innermost level.
4217 * Synchronization is inserted at the innermost level before the
4218 * actual kernel code if there is any copying from global memory
4219 * to shared memory. It is inserted unconditionally at the innermost
4220 * level after the actual kernel code and the copying to global memory
4221 * from private memory (if any). Finally, it is inserted after
4222 * any copying to global memory, except at the outermost level
4223 * and at the innermost level if there is no copying from shared
4224 * memory. The copying from private memory is covered by the unconditional
4225 * synchronization at the innermost level.
4227 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4228 __isl_take isl_union_map *schedule)
4230 isl_space *space;
4231 isl_union_map *res;
4232 isl_union_map *shared_sched;
4233 isl_union_map *sched;
4234 isl_map *proj, *map;
4235 int i, j, k, s;
4237 shared_sched = isl_union_map_copy(gen->tiled_sched);
4238 proj = projection(isl_union_map_get_space(shared_sched),
4239 gen->tiled_len, gen->shared_len);
4240 shared_sched = isl_union_map_apply_range(shared_sched,
4241 isl_union_map_from_map(proj));
4242 space = isl_union_map_get_space(shared_sched);
4243 proj = insert_even(gen, space, -1, 0);
4244 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4245 isl_union_map_from_map(proj));
4247 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4249 s = 0;
4250 for (i = 0; i < gen->prog->n_array; ++i)
4251 s += gen->prog->array[i].n_group;
4253 k = 0;
4254 for (i = 0; i < gen->prog->n_array; ++i) {
4255 struct gpu_array_info *array = &gen->prog->array[i];
4257 for (j = 0; j < array->n_group; ++j) {
4258 struct gpu_array_ref_group *group;
4260 group = array->groups[j];
4261 if (!group->private_tile && !group->shared_tile)
4262 continue;
4263 res = add_group_schedule(gen, res, schedule,
4264 shared_sched, group, 0, k, s);
4265 res = add_group_schedule(gen, res, schedule,
4266 shared_sched, group, 1, k, s);
4267 ++k;
4271 res = add_sync_schedule(gen, res, schedule, shared_sched,
4272 gen->shared_len - gen->tile_first, 1 + s);
4274 isl_union_map_free(shared_sched);
4275 isl_union_map_free(schedule);
4277 return res;
4280 /* Generate code for "kernel" in the given "context".
4282 * We first generate code for the shared tile loops (T1T, T1P and T2)
4283 * in a context that includes the block ids.
4284 * Within each iteration of these loops an additional code generation
4285 * is performed (within create_kernel_leaf) for the rest of the schedule
4286 * in a context that includes the thread ids.
4288 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4289 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4290 __isl_keep isl_multi_pw_aff *grid_size)
4292 isl_space *space;
4293 isl_set *set;
4294 isl_id_list *iterators;
4295 isl_union_map *schedule;
4296 isl_ast_node *tree;
4297 int sched_len;
4299 schedule = isl_ast_build_get_schedule(build);
4301 build = isl_ast_build_copy(build);
4302 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4303 space = isl_ast_build_get_schedule_space(build);
4304 set = isl_set_universe(isl_space_copy(space));
4305 set = add_bounded_parameters_dynamic(set, grid_size, "b");
4306 build = isl_ast_build_restrict(build, set);
4308 schedule = body_schedule(gen, schedule);
4310 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4312 build = set_atomic_and_unroll(build, space, sched_len);
4313 iterators = generate_names(gen->ctx, sched_len, "g");
4314 build = isl_ast_build_set_iterators(build, iterators);
4315 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4316 tree = isl_ast_build_ast_from_schedule(build, schedule);
4317 isl_ast_build_free(build);
4319 return tree;
4322 /* Attach "id" to the given node.
4324 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4325 __isl_keep isl_ast_build *build, void *user)
4327 isl_id *id = user;
4329 node = isl_ast_node_set_annotation(node, id);
4331 return node;
4334 /* Construct an AST node for performing a kernel launch and attach
4335 * the information about the kernel to that node.
4337 * The kernel AST has been constructed in the context of the range
4338 * of "schedule". In particular, the grid size has been computed
4339 * in the context. We therefore still need to make sure that these
4340 * constraints are expressed in the code. We do this by creating a schedule
4342 * kernel[] -> [S -> []]
4344 * where S is the schedule domain, i.e., the range of "schedule".
4345 * The AST generation will then create a single call surrounded by
4346 * all the condition in "S" that have not been expressed yet.
4348 * The kernel information is attached to this node in attach_id.
4350 static __isl_give isl_ast_node *construct_launch(
4351 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
4352 __isl_take struct ppcg_kernel *kernel)
4354 isl_id *id;
4355 isl_ctx *ctx;
4356 isl_union_set *domain;
4357 isl_set *set;
4358 isl_map *map;
4359 isl_ast_node *node;
4361 ctx = isl_ast_build_get_ctx(build);
4363 id = isl_id_alloc(ctx, NULL, kernel);
4364 id = isl_id_set_free_user(id, &ppcg_kernel_free);
4366 domain = isl_union_map_range(schedule);
4367 set = isl_set_from_union_set(domain);
4368 map = isl_map_from_domain(set);
4369 map = isl_map_from_range(isl_map_wrap(map));
4370 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
4371 schedule = isl_union_map_from_map(map);
4373 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
4374 node = isl_ast_build_ast_from_schedule(build, schedule);
4375 isl_ast_build_free(build);
4377 return node;
4380 /* This function is called for each leaf in the AST of the host code.
4381 * We first specialize the schedule to the site of the leaf, compute
4382 * the size of shared memory and then construct the body of host code
4383 * and the associated kernel.
4385 * The necessary information for printing the kernel launch is
4386 * stored in a struct ppcg_kernel and attached to the leaf node
4387 * created to represent the launch.
4389 static __isl_give isl_ast_node *create_host_leaf(
4390 __isl_take isl_ast_build *build, void *user)
4392 struct gpu_gen *gen = (struct gpu_gen *) user;
4393 isl_id *id;
4394 isl_ast_node *node;
4395 struct ppcg_kernel *kernel;
4396 isl_set *host_domain;
4397 isl_union_map *schedule;
4398 isl_union_map *local_sched;
4399 isl_union_map *access;
4400 isl_union_set *domain;
4401 int i;
4403 schedule = isl_ast_build_get_schedule(build);
4405 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
4406 read_sizes(gen);
4408 domain = isl_union_map_domain(isl_union_map_copy(schedule));
4410 local_sched = isl_union_map_copy(gen->sched);
4411 local_sched = isl_union_map_intersect_domain(local_sched, domain);
4412 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
4413 isl_union_map_copy(gen->prog->write));
4414 access = isl_union_map_apply_domain(access,
4415 isl_union_map_copy(local_sched));
4417 gen->tiled_sched = tile_schedule(gen, local_sched);
4418 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
4419 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
4421 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
4422 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
4423 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
4425 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
4426 if (!kernel)
4427 goto error;
4429 kernel->id = gen->kernel_id++;
4430 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
4431 kernel->grid_size = extract_grid_size(gen, kernel);
4432 extract_block_size(gen, kernel);
4433 kernel->arrays = isl_union_map_range(access);
4434 kernel->space = isl_ast_build_get_schedule_space(build);
4436 gen->private_access = NULL;
4437 compute_shared_sched(gen);
4438 gen->privatization = compute_privatization(gen);
4439 group_references(gen);
4440 compute_private_access(gen);
4441 check_shared_memory_bound(gen);
4442 host_domain = isl_set_from_union_set(isl_union_map_range(
4443 isl_union_map_copy(schedule)));
4444 localize_bounds(gen, kernel, host_domain);
4446 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
4448 kernel->tree = generate_kernel(gen, build, host_domain,
4449 kernel->grid_size);
4450 create_kernel_vars(gen, kernel);
4452 free_local_array_info(gen);
4453 isl_map_free(gen->privatization);
4454 isl_union_map_free(gen->private_access);
4455 isl_union_map_free(gen->local_sched);
4456 isl_union_map_free(gen->tiled_sched);
4457 isl_union_map_free(gen->shared_sched);
4458 isl_union_map_free(gen->shared_proj);
4459 isl_set_free(host_domain);
4460 free(gen->tile_size);
4462 node = construct_launch(build, schedule, kernel);
4464 return node;
4465 error:
4466 isl_union_map_free(schedule);
4467 return NULL;
4470 /* Use isl to generate code for the outer gen->tile_first loops
4471 * of the global schedule in gen->sched, resulting in the host code.
4472 * Within each iteration of this partial schedule, i.e., for each kernel
4473 * launch, create_host_leaf takes care of generating the kernel code.
4475 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
4477 isl_ast_build *build;
4478 isl_ast_node *tree;
4479 isl_union_map *sched;
4480 isl_map *proj;
4481 isl_id_list *iterators;
4483 sched = isl_union_map_copy(gen->sched);
4484 proj = projection(isl_union_map_get_space(sched),
4485 gen->untiled_len, gen->tile_first);
4486 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4488 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
4489 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
4490 iterators = generate_names(gen->ctx, gen->tile_first, "h");
4491 build = isl_ast_build_set_iterators(build, iterators);
4492 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
4493 tree = isl_ast_build_ast_from_schedule(build, sched);
4494 isl_ast_build_free(build);
4496 return tree;
4499 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
4501 if (!str)
4502 return NULL;
4503 return isl_union_map_read_from_str(ctx, str);
4506 /* Information about the outermost tilable bands in the forest of bands.
4508 * tile_len and n_parallel are only sets on band_info structures
4509 * that correspond to outermost bands. For other bands (in particular,
4510 * ancestors of the outermost bands), n_parallal is set to 0.
4512 * prefix is the (padded) schedule leading up to the outermost tilable bands.
4514 * tile_first is the number of schedule dimensions in prefix.
4516 * suffix is the schedule of the outermost tilable bands and their descendants.
4518 struct band_info {
4519 struct gpu_gen *gen;
4520 int tile_first;
4521 int tile_len;
4522 int n_parallel;
4523 isl_union_map *prefix;
4524 isl_union_map *suffix;
4527 /* Set tile_len and n_parallel of the statement to that of
4528 * their outermost band, recorded in the band_info.
4530 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
4532 struct band_info *info = user;
4533 struct gpu_stmt *stmt;
4534 isl_id *id;
4536 id = isl_map_get_tuple_id(map, isl_dim_in);
4537 stmt = find_stmt(info->gen->prog, id);
4538 isl_id_free(id);
4540 stmt->tile_len = info->tile_len;
4541 stmt->n_parallel = info->n_parallel;
4543 isl_map_free(map);
4545 return 0;
4548 static void list_select_outer_band(struct gpu_gen *gen,
4549 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
4551 /* Check if this band has any parallel loops. If so, take it as
4552 * the outermost tilable band. If not, continue looking for the
4553 * outermost tilable band in the children of the current band.
4555 static void band_select_outer_band(struct gpu_gen *gen,
4556 __isl_take isl_band *band, int pos, struct band_info *info)
4558 int n = isl_band_n_member(band);
4559 int n_parallel;
4561 for (n_parallel = 0; n_parallel < n; ++n_parallel)
4562 if (!isl_band_member_is_zero_distance(band, n_parallel))
4563 break;
4565 info->n_parallel = n_parallel;
4566 if (n_parallel) {
4567 gen->any_parallelism = 1;
4568 info->gen = gen;
4569 info->tile_first = pos;
4570 info->tile_len = n;
4571 info->prefix = isl_band_get_prefix_schedule(band);
4572 info->suffix = isl_union_map_flat_range_product(
4573 isl_band_get_partial_schedule(band),
4574 isl_band_get_suffix_schedule(band));
4575 isl_union_map_foreach_map(info->prefix,
4576 &set_stmt_tile_len, info);
4577 } else if (isl_band_has_children(band)) {
4578 isl_band_list *children;
4579 children = isl_band_get_children(band);
4580 list_select_outer_band(gen, children, pos + n, info);
4581 } else {
4582 info->gen = gen;
4583 info->tile_first = pos + n;
4584 info->tile_len = 0;
4585 info->prefix = isl_union_map_flat_range_product(
4586 isl_band_get_prefix_schedule(band),
4587 isl_band_get_partial_schedule(band));
4588 info->suffix = isl_band_get_suffix_schedule(band);
4589 isl_union_map_foreach_map(info->prefix,
4590 &set_stmt_tile_len, info);
4593 isl_band_free(band);
4596 /* Comparison function that returns a non-zero value for band_infos
4597 * with different tile_len fields or different n_parallel fields.
4599 static int cmp_band(const void *p1, const void *p2)
4601 const struct band_info *info1 = p1;
4602 const struct band_info *info2 = p2;
4604 if (info1->tile_len != info2->tile_len)
4605 return info1->tile_len - info2->tile_len;
4607 return info1->n_parallel - info2->n_parallel;
4610 /* Extend "umap" with coordinates with fixed value "val"
4611 * to a total length of "dst_len", assuming the original dimension is "src_len".
4613 static __isl_give isl_union_map *extend_range(
4614 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
4616 isl_space *dim;
4617 isl_map *map;
4618 int i;
4620 dim = isl_union_map_get_space(umap);
4621 map = isl_map_reverse(projection(dim, dst_len, src_len));
4622 for (i = src_len; i < dst_len; ++i)
4623 map = isl_map_fix_si(map, isl_dim_out, i, val);
4625 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
4627 return umap;
4630 /* Group bands with the same values for tile_len and n_parallel.
4631 * The prefix schedule is then extended with a fixed coordinate that
4632 * is different for each such group.
4633 * Note that the actual values for this coordinate are not important.
4634 * The bands have already been effectively separated at a higher level
4635 * or they are independent and may be executed in parallel.
4636 * The list of band_info has been sorted before this functions is called.
4638 static void separate_bands(struct band_info *info, int n)
4640 int i;
4641 int j = 0;
4643 for (i = 0; i < n; ++i) {
4644 int l = info[i].tile_first;
4646 if (i &&
4647 (info[i].tile_len != info[i - 1].tile_len ||
4648 info[i].n_parallel != info[i - 1].n_parallel))
4649 j++;
4651 info[i].prefix = extend_range(info[i].prefix,
4652 l, l + 1, j);
4653 info[i].tile_first = l + 1;
4657 /* Select the outermost bands in the elements of the list, align
4658 * their prefix schedules, separate bands with different values
4659 * for tile_len and/or n_parallel and then combine the resulting
4660 * prefix and suffix schedules into a single pair of prefix and
4661 * suffix schedules for the entire list.
4663 static void list_select_outer_band(struct gpu_gen *gen,
4664 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
4666 isl_band *band;
4667 int i;
4668 int n = isl_band_list_n_band(list);
4669 isl_ctx *ctx = isl_band_list_get_ctx(list);
4670 struct band_info *info;
4671 int max_tile_first;
4672 isl_union_map *prefix;
4673 isl_union_map *suffix;
4675 assert(n >= 1);
4676 info = isl_calloc_array(ctx, struct band_info, n);
4677 assert(info);
4679 max_tile_first = 0;
4680 for (i = 0; i < n; ++i) {
4681 band = isl_band_list_get_band(list, i);
4682 band_select_outer_band(gen, band, pos, &info[i]);
4683 if (info[i].tile_first > max_tile_first)
4684 max_tile_first = info[i].tile_first;
4687 for (i = 0; i < n; ++i) {
4688 if (info[i].tile_first == max_tile_first)
4689 continue;
4690 info[i].prefix = extend_range(info[i].prefix,
4691 info[i].tile_first, max_tile_first, 0);
4692 info[i].tile_first = max_tile_first;
4695 qsort(info, n, sizeof(struct band_info), &cmp_band);
4697 for (i = 0; i < n - 1; ++i)
4698 if (info[i].tile_len != info[i + 1].tile_len ||
4699 info[i].n_parallel != info[i + 1].n_parallel)
4700 break;
4702 if (i < n -1)
4703 separate_bands(info, n);
4705 prefix = info[0].prefix;
4706 suffix = info[0].suffix;
4708 for (i = 1; i < n; ++i) {
4709 prefix = isl_union_map_union(prefix, info[i].prefix);
4710 suffix = isl_union_map_union(suffix, info[i].suffix);
4713 list_info->tile_first = info[0].tile_first;
4714 list_info->tile_len = -1;
4715 list_info->prefix = prefix;
4716 list_info->suffix = suffix;
4718 isl_band_list_free(list);
4719 free(info);
4722 /* Select the outermost tilable band that (by construction)
4723 * has at least one parallel loop.
4724 * The starting position of the aligned band is stored in the pair
4725 * gen->tile_first.
4726 * The sizes and number of parallel loops may be different in different
4727 * parts of the band forest and are therefore stored in the gpu_stmts.
4729 * Return the complete schedule, with the tilable bands aligned
4730 * at gen->tile_first and padded with zero, if needed.
4732 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
4733 __isl_keep isl_schedule *schedule)
4735 isl_band_list *list;
4736 struct band_info info;
4738 gen->n_parallel = 0;
4739 gen->tile_len = -1;
4741 list = isl_schedule_get_band_forest(schedule);
4743 list_select_outer_band(gen, list, 0, &info);
4745 gen->tile_first = info.tile_first;
4746 info.suffix = align_range(info.suffix);
4748 return isl_union_map_flat_range_product(info.prefix, info.suffix);
4751 /* Set gen->untiled_len to the number of scheduling dimensions
4752 * for the schedule of the first domain.
4753 * We assume here that this number is the same for all domains.
4755 static int set_untiled_len(__isl_take isl_map *map, void *user)
4757 unsigned *untiled_len = user;
4759 *untiled_len = isl_map_dim(map, isl_dim_out);
4761 isl_map_free(map);
4762 return -1;
4765 /* Compute an appropriate schedule based on the accesses in
4766 * gen->read and gen->write.
4768 * We use the dependences in gen->prog->scop to compute
4769 * a schedule that has a parallel loop in each tilable band.
4770 * Finally, we select the outermost tilable band.
4772 static void compute_schedule(struct gpu_gen *gen)
4774 isl_union_set *domain;
4775 isl_union_map *dep_raw, *dep;
4776 isl_union_map *sched;
4777 isl_schedule *schedule;
4779 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4781 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4782 dep = isl_union_map_union(dep, dep_raw);
4783 dep = isl_union_map_coalesce(dep);
4785 domain = isl_union_set_copy(gen->prog->scop->domain);
4786 domain = isl_union_set_intersect_params(domain,
4787 isl_set_copy(gen->prog->scop->context));
4788 schedule = isl_union_set_compute_schedule(isl_union_set_copy(domain),
4789 isl_union_map_copy(dep), dep);
4790 if (gen->options->debug->dump_schedule)
4791 isl_schedule_dump(schedule);
4793 sched = select_outer_tilable_band(gen, schedule);
4795 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
4796 sched = isl_union_map_intersect_domain(sched, domain);
4797 gen->sched = sched;
4799 isl_schedule_free(schedule);
4802 /* Compute the sets of array elements that need to be copied in and out.
4804 * In particular, for each array that is written anywhere in gen->prog and
4805 * that is visible outside the corresponding scop, we copy out its entire
4806 * extent.
4808 * Any array elements that is read without first being written needs
4809 * to be copied in. Furthermore, if there are any array elements that
4810 * are copied out, but that are not written inside gen->prog, then
4811 * they also need to be copied in to ensure that the value after execution
4812 * is the same as the value before execution.
4813 * While computing the set of array elements that
4814 * are copied out but not written, we intersect both sets with the context.
4815 * This helps in those cases where the arrays are declared with a fixed size,
4816 * while the accesses are parametric and the context assigns a fixed value
4817 * to the parameters.
4819 static void compute_copy_in_and_out(struct gpu_gen *gen)
4821 int i;
4822 isl_union_set *write;
4823 isl_union_set *copy_in, *copy_out;
4824 isl_union_set *not_written;
4825 isl_union_map *uninitialized;
4827 write = isl_union_map_range(isl_union_map_copy(gen->prog->write));
4828 write = isl_union_set_intersect_params(write,
4829 isl_set_copy(gen->prog->context));
4830 copy_out = isl_union_set_empty(isl_union_set_get_space(write));
4832 for (i = 0; i < gen->prog->n_array; ++i) {
4833 isl_space *space;
4834 isl_set *write_i;
4835 int empty;
4837 if (gen->prog->array[i].local)
4838 continue;
4840 space = isl_space_copy(gen->prog->array[i].dim);
4841 write_i = isl_union_set_extract_set(write, space);
4842 empty = isl_set_fast_is_empty(write_i);
4843 isl_set_free(write_i);
4844 if (empty)
4845 continue;
4847 write_i = isl_set_copy(gen->prog->array[i].extent);
4848 copy_out = isl_union_set_add_set(copy_out, write_i);
4851 copy_out = isl_union_set_intersect_params(copy_out,
4852 isl_set_copy(gen->prog->context));
4854 gen->prog->copy_out = isl_union_set_copy(copy_out);
4856 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
4857 copy_in = isl_union_map_range(uninitialized);
4859 not_written = isl_union_set_subtract(copy_out, write);
4860 copy_in = isl_union_set_union(copy_in, not_written);
4861 gen->prog->copy_in = copy_in;
4864 static struct gpu_stmt_access **expr_extract_access(struct pet_expr *expr,
4865 struct gpu_stmt_access **next_access)
4867 struct gpu_stmt_access *access;
4868 isl_ctx *ctx = isl_map_get_ctx(expr->acc.access);
4870 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4871 assert(access);
4872 access->next = NULL;
4873 access->read = expr->acc.read;
4874 access->write = expr->acc.write;
4875 access->access = isl_map_copy(expr->acc.access);
4877 *next_access = access;
4878 next_access = &(*next_access)->next;
4879 return next_access;
4882 static struct gpu_stmt_access **expr_extract_accesses(struct pet_expr *expr,
4883 struct gpu_stmt_access **next_access)
4885 int i;
4887 for (i = 0; i < expr->n_arg; ++i)
4888 next_access = expr_extract_accesses(expr->args[i],
4889 next_access);
4891 if (expr->type == pet_expr_access)
4892 next_access = expr_extract_access(expr, next_access);
4894 return next_access;
4897 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
4899 struct gpu_stmt_access **next_access = &stmt->accesses;
4901 stmt->accesses = NULL;
4902 expr_extract_accesses(stmt->body, next_access);
4905 /* Return an array of gpu_stmt representing the statements in "scop".
4907 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4908 __isl_keep isl_set *context)
4910 int i;
4911 struct gpu_stmt *stmts;
4913 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
4914 if (!stmts)
4915 return NULL;
4917 for (i = 0; i < scop->n_stmt; ++i) {
4918 struct gpu_stmt *s = &stmts[i];
4920 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
4921 s->body = scop->stmts[i]->body;
4922 pet_stmt_extract_accesses(s);
4925 return stmts;
4928 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
4930 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
4932 struct gpu_gen *gen = user;
4934 return gen->print(p, gen->prog, gen->tree, gen->print_user);
4937 /* Replace the scop in the "input" file by equivalent code
4938 * that uses the GPU and print the result to "out".
4939 * "scop" is assumed to correspond to this scop.
4940 * The code before the scop is first copied to "out",
4941 * then the transformed scop is printed and finally
4942 * the code after the scop is copied to "out".
4943 * After generating an AST for the transformed scop as explained below,
4944 * we call "print" to print the AST in the desired output format
4945 * to a printer hooked up to "out".
4947 * If it turns out that it does not make sense to generate GPU code,
4948 * then we generate CPU code instead.
4950 * The GPU code is generated in a context where at least one
4951 * statement instance is executed. The corresponding guard (if any) is printed
4952 * around the entire generated GPU code, except for the declaration
4953 * of the arrays that are visible outside of the scop and that therefore
4954 * cannot be declared inside the body of any possible guard.
4956 * We first compute a schedule that respects the dependences
4957 * of the original program and select the outermost band
4958 * of tilable dimensions that has at least one parallel loop.
4959 * We then have three blocks of dimensions
4961 * H B G
4963 * The tilable band "B" is first tiled according to "tile" sizes, resulting
4964 * in
4966 * H T P G
4968 * For each iteration of the T loop and for each array, we compute
4969 * the array elements accessed by that iteration, construct a rectangular
4970 * box around it and shift it to the origin. The result is used
4971 * as shared memory for the array.
4973 * We then split off at most 2 parallel loops from the T loops and
4974 * at most 3 parallel loops from the P loops
4976 * H T1 T2 P1 P2 G
4978 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
4979 * according to "grid"/"block" sizes.
4981 * H T1T T1P T2 P1T P1P P2 G
4983 * Finally, the T1P and P1P iterators are equated to the block and
4984 * thread dimensions respectively and so are effectively removed.
4985 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
4986 * are run on the GPU.
4988 * Code is generated in three stages. We first generate code for the
4989 * host (the H loops), with iterators h%d. Then, for each leaf node
4990 * of the resulting AST, we generate code for the shared loops (up to
4991 * and including T2), with iterators g%d and after equating the H loops
4992 * to h%d parameters and the T1P loops to the block dimensions.
4993 * Finally, we generate code for the remaining loops in a similar fashion.
4995 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
4996 struct ppcg_scop *scop, struct ppcg_options *options,
4997 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
4998 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
4999 void *user), void *user)
5001 struct gpu_gen gen;
5002 struct gpu_prog *prog;
5003 isl_set *context, *guard;
5004 isl_printer *p;
5005 FILE *in;
5007 if (!scop)
5008 return -1;
5010 in = fopen(input, "r");
5011 copy(in, out, 0, scop->start);
5013 prog = gpu_prog_alloc(ctx, scop);
5014 if (!prog)
5015 return -1;
5017 p = isl_printer_to_file(ctx, out);
5018 p = isl_printer_set_output_format(p, ISL_FORMAT_C);
5020 context = isl_set_copy(prog->context);
5021 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5022 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5024 gen.ctx = ctx;
5025 gen.prog = prog;
5026 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5027 gen.options = options;
5029 gen.any_parallelism = 0;
5030 compute_schedule(&gen);
5032 if (!gen.any_parallelism) {
5033 isl_set_free(context);
5034 isl_set_free(guard);
5035 p = print_cpu(p, scop, options);
5036 } else {
5037 compute_copy_in_and_out(&gen);
5039 gen.kernel_id = 0;
5040 gen.print = print;
5041 gen.print_user = user;
5042 gen.tree = generate_host_code(&gen);
5043 p = ppcg_print_exposed_declarations(p, prog->scop);
5044 p = ppcg_print_guarded(p, guard, context, &print_gpu, &gen);
5045 isl_ast_node_free(gen.tree);
5048 clear_gpu_gen(&gen);
5050 isl_printer_free(p);
5052 gpu_prog_free(prog);
5054 copy(in, out, scop->end, -1);
5055 fclose(in);
5057 return p ? 0 : -1;
5060 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5062 struct gpu_prog *prog;
5064 if (!scop)
5065 return NULL;
5067 prog = isl_calloc_type(ctx, struct gpu_prog);
5068 assert(prog);
5070 prog->ctx = ctx;
5071 prog->scop = scop;
5072 prog->context = isl_set_copy(scop->context);
5073 prog->n_stmts = scop->n_stmt;
5074 prog->stmts = extract_stmts(ctx, scop, prog->context);
5075 prog->read = isl_union_map_copy(scop->reads);
5076 prog->write = isl_union_map_copy(scop->writes);
5078 if (!prog->stmts)
5079 return gpu_prog_free(prog);
5081 collect_array_info(prog);
5083 return prog;
5086 void *gpu_prog_free(struct gpu_prog *prog)
5088 if (!prog)
5089 return NULL;
5090 free_array_info(prog);
5091 free_stmts(prog->stmts, prog->n_stmts);
5092 isl_union_set_free(prog->copy_in);
5093 isl_union_set_free(prog->copy_out);
5094 isl_union_map_free(prog->read);
5095 isl_union_map_free(prog->write);
5096 isl_set_free(prog->context);
5097 free(prog);
5098 return NULL;