gpu: avoid copying in data from local arrays
[ppcg.git] / gpu.c
blobcf271f001892eb4fc369cea67a67a39362f08095
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012-2013 Ecole Normale Superieure
5 * Use of this software is governed by the MIT license
7 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
8 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
9 * 91893 Orsay, France
10 * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
13 #include <assert.h>
14 #include <stdlib.h>
15 #include <string.h>
17 #include <isl/polynomial.h>
18 #include <isl/union_set.h>
19 #include <isl/aff.h>
20 #include <isl/ilp.h>
21 #include <isl/flow.h>
22 #include <isl/band.h>
23 #include <isl/schedule.h>
24 #include <isl/options.h>
25 #include <isl/ast_build.h>
27 #include "cpu.h"
28 #include "gpu.h"
29 #include "schedule.h"
30 #include "ppcg_options.h"
31 #include "print.h"
33 /* The fields stride, shift and shift_map only contain valid information
34 * if shift != NULL.
35 * If so, they express that current index is such that if you add shift,
36 * then the result is always a multiple of stride.
37 * shift_map contains the mapping
39 * i -> (i + shift)/stride
41 * Let D represent the initial shared_len dimensions of the computed schedule.
42 * The spaces of "lb" and "shift" are of the form
44 * D -> [b]
46 * "shift_map" is of the form
48 * [D -> i] -> [D -> (i + shift(D))/stride]
50 struct gpu_array_bound {
51 isl_val *size;
52 isl_aff *lb;
54 isl_val *stride;
55 isl_aff *shift;
56 isl_basic_map *shift_map;
59 /* A tile of an array.
61 * n is the dimension of the array.
62 * bound is an array of size "n" representing the lower bound
63 * and size for each index.
65 * tiling maps a tile in the global array to the corresponding
66 * shared/private memory tile and is of the form
68 * { [D[i] -> A[a]] -> T[(a + shift(i))/stride - lb(i)] }
70 * where D represents the initial shared_len dimensions
71 * of the computed schedule.
73 struct gpu_array_tile {
74 int n;
75 struct gpu_array_bound *bound;
76 isl_multi_aff *tiling;
79 struct gpu_array_info;
81 /* A group of array references in a kernel that should be handled together.
82 * If private_tile is not NULL, then it is mapped to registers.
83 * Otherwise, if shared_tile is not NULL, it is mapped to shared memory.
84 * Otherwise, it is accessed from global memory.
86 struct gpu_array_ref_group {
87 /* The references in this group access this array. */
88 struct gpu_array_info *array;
89 /* Position of this group in the list of reference groups of array. */
90 int nr;
92 /* The following fields are use during the construction of the groups.
93 * access is the combined access relation relative to the shared
94 * memory tiling. In particular, the domain of the map corresponds
95 * to the first shared_len dimensions of the computed schedule.
96 * write is set if any access in the group is a write.
98 isl_map *access;
99 int write;
101 /* The shared memory tile, NULL if none. */
102 struct gpu_array_tile *shared_tile;
104 /* The private memory tile, NULL if none. */
105 struct gpu_array_tile *private_tile;
107 /* References in this group; point to elements of a linked list. */
108 int n_ref;
109 struct gpu_stmt_access **refs;
111 /* Last shared memory tile dimension that affects tile of this group. */
112 int last_shared;
115 struct gpu_gen {
116 isl_ctx *ctx;
117 struct ppcg_options *options;
119 /* Callback for printing of AST in appropriate format. */
120 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
121 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
122 void *user);
123 void *print_user;
125 struct gpu_prog *prog;
126 /* The generated AST. */
127 isl_ast_node *tree;
129 /* tile, grid and block sizes for each kernel */
130 isl_union_map *sizes;
132 /* Identifier of current kernel. */
133 int kernel_id;
134 /* Pointer to the current kernel. */
135 struct ppcg_kernel *kernel;
136 /* Does the computed schedule exhibit any parallelism? */
137 int any_parallelism;
139 /* First tile dimension. */
140 int tile_first;
141 /* Number of tile dimensions. */
142 int tile_len;
143 /* Number of initial parallel loops among tile dimensions. */
144 int n_parallel;
146 /* Number of dimensions determining shared memory. */
147 int shared_len;
149 /* Number of rows in the untiled schedule. */
150 int untiled_len;
151 /* Number of rows in the tiled schedule. */
152 int tiled_len;
153 /* Number of rows in schedule after tiling/wrapping over threads. */
154 int thread_tiled_len;
156 /* Global untiled schedule. */
157 isl_union_map *sched;
158 /* Local (per kernel launch) tiled schedule. */
159 isl_union_map *tiled_sched;
160 /* Local schedule per shared memory tile loop iteration. */
161 isl_union_map *local_sched;
163 /* Local tiled schedule projected onto the shared tile loops and
164 * the loops that will be wrapped over the threads,
165 * with all shared tile loops parametrized.
167 isl_union_map *shared_sched;
168 /* Projects out the loops that will be wrapped over the threads
169 * from shared_sched.
171 isl_union_map *shared_proj;
173 /* A map that takes the range of shared_sched as input,
174 * wraps the appropriate loops over the threads and then projects
175 * out these loops.
177 isl_map *privatization;
179 /* A map from the shared memory tile loops and the thread indices
180 * (as parameters) to the set of accessed memory elements that
181 * will be accessed through private copies.
183 isl_union_map *private_access;
185 /* The schedule for the current private/shared access
186 * (within print_private_access or print_shared_access).
188 isl_map *copy_sched;
189 /* The array reference group corresponding to copy_sched. */
190 struct gpu_array_ref_group *copy_group;
192 /* First loop to unroll (or -1 if none) in the current part of the
193 * schedule.
195 int first_unroll;
197 int n_grid;
198 int n_block;
199 /* Note: in the input file, the sizes of the grid and the blocks
200 * are specified in the order x, y, z, but internally, the sizes
201 * are stored in reverse order, so that the last element always
202 * refers to the x dimension.
204 int grid_dim[2];
205 int block_dim[3];
206 int *tile_size;
209 /* Print the name of the local copy of a given group of array references.
211 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
212 struct gpu_array_ref_group *group)
214 int global = 0;
216 if (group->private_tile)
217 p = isl_printer_print_str(p, "private_");
218 else if (group->shared_tile)
219 p = isl_printer_print_str(p, "shared_");
220 else
221 global = 1;
222 p = isl_printer_print_str(p, group->array->name);
223 if (!global && group->array->n_group > 1) {
224 p = isl_printer_print_str(p, "_");
225 p = isl_printer_print_int(p, group->nr);
228 return p;
231 /* Collect all references to the given array and store pointers to them
232 * in array->refs.
234 static void collect_references(struct gpu_prog *prog,
235 struct gpu_array_info *array)
237 int i;
238 int n;
240 n = 0;
241 for (i = 0; i < prog->n_stmts; ++i) {
242 struct gpu_stmt *stmt = &prog->stmts[i];
243 struct gpu_stmt_access *access;
245 for (access = stmt->accesses; access; access = access->next) {
246 const char *name;
247 name = isl_map_get_tuple_name(access->access,
248 isl_dim_out);
249 if (name && !strcmp(array->name, name))
250 n++;
254 array->n_ref = n;
255 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
256 assert(array->refs);
258 n = 0;
259 for (i = 0; i < prog->n_stmts; ++i) {
260 struct gpu_stmt *stmt = &prog->stmts[i];
261 struct gpu_stmt_access *access;
263 for (access = stmt->accesses; access; access = access->next) {
264 const char *name;
265 name = isl_map_get_tuple_name(access->access,
266 isl_dim_out);
267 if (!name || strcmp(array->name, name))
268 continue;
270 array->refs[n++] = access;
275 /* Create a gpu_array_tile for an array of dimension "n_index".
277 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
279 int i;
280 struct gpu_array_tile *tile;
282 tile = isl_calloc_type(ctx, struct gpu_array_tile);
283 assert(tile);
285 tile->n = n_index;
287 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
288 assert(tile->bound);
290 for (i = 0; i < n_index; ++i) {
291 tile->bound[i].size = NULL;
292 tile->bound[i].lb = NULL;
293 tile->bound[i].stride = NULL;
294 tile->bound[i].shift = NULL;
295 tile->bound[i].shift_map = NULL;
298 return tile;
301 static void *free_tile(struct gpu_array_tile *tile)
303 int j;
305 if (!tile)
306 return NULL;
308 for (j = 0; j < tile->n; ++j) {
309 isl_val_free(tile->bound[j].size);
310 isl_val_free(tile->bound[j].stride);
311 isl_aff_free(tile->bound[j].lb);
312 isl_aff_free(tile->bound[j].shift);
313 isl_basic_map_free(tile->bound[j].shift_map);
315 free(tile->bound);
316 isl_multi_aff_free(tile->tiling);
317 free(tile);
319 return NULL;
322 static struct pet_array *find_array(struct ppcg_scop *scop,
323 __isl_keep isl_set *accessed)
325 int i;
326 isl_id *id;
328 id = isl_set_get_tuple_id(accessed);
330 for (i = 0; i < scop->n_array; ++i) {
331 isl_id *id_i;
333 id_i = isl_set_get_tuple_id(scop->arrays[i]->extent);
334 isl_id_free(id_i);
335 if (id == id_i)
336 break;
338 isl_id_free(id);
340 return i < scop->n_array ? scop->arrays[i] : NULL;
343 /* Compute and return the extent of "array", taking into account the set of
344 * accessed elements.
346 * In particular, the extent in the outer dimension is taken
347 * from "accessed", while then extent in the remaing dimensions
348 * are taken from array->extent.
350 * The extent in the outer dimension cannot be taken from array->extent
351 * because that may be unbounded. Furthermore, even if it is bounded,
352 * it may be larger than the piece of the array that is being accessed.
354 static __isl_give isl_set *compute_extent(struct pet_array *array,
355 __isl_keep isl_set *accessed)
357 int n_index;
358 isl_id *id;
359 isl_set *outer;
360 isl_set *extent;
362 extent = isl_set_copy(array->extent);
364 n_index = isl_set_dim(accessed, isl_dim_set);
365 if (n_index == 0)
366 return extent;
368 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
369 outer = isl_set_copy(accessed);
370 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
371 extent = isl_set_flat_product(outer, extent);
372 id = isl_set_get_tuple_id(accessed);
373 extent = isl_set_set_tuple_id(extent, id);
375 return extent;
378 /* Is the array "array" being extracted a read-only scalar?
380 * That is, is "array" a scalar that is never written to.
382 static int is_read_only_scalar(struct gpu_array_info *array,
383 struct gpu_prog *prog)
385 isl_set *space;
386 isl_union_map *write;
387 int empty;
389 if (array->n_index != 0)
390 return 0;
392 write = isl_union_map_copy(prog->write);
393 space = isl_set_universe(isl_space_copy(array->space));
394 write = isl_union_map_intersect_range(write,
395 isl_union_set_from_set(space));
396 empty = isl_union_map_is_empty(write);
397 isl_union_map_free(write);
399 return empty;
402 /* Compute bounds on the host arrays based on the accessed elements
403 * and collect all references to the array.
405 * If the array is zero-dimensional, i.e., a scalar, we check
406 * whether it is read-only.
408 static int extract_array_info(__isl_take isl_set *array, void *user)
410 int i;
411 struct gpu_prog *prog = (struct gpu_prog *)user;
412 const char *name;
413 int n_index;
414 isl_pw_aff **bounds;
415 struct pet_array *pa;
416 struct gpu_array_info *info;
417 isl_set *extent;
419 info = &prog->array[prog->n_array];
420 prog->n_array++;
422 n_index = isl_set_dim(array, isl_dim_set);
423 name = isl_set_get_tuple_name(array);
424 bounds = isl_alloc_array(isl_set_get_ctx(array),
425 isl_pw_aff *, n_index);
426 if (!bounds)
427 goto error;
429 info->space = isl_set_get_space(array);
430 info->name = strdup(name);
431 info->n_index = n_index;
432 info->bound = bounds;
433 info->linearize = prog->scop->options->linearize_device_arrays;
435 pa = find_array(prog->scop, array);
436 if (!pa)
437 isl_die(isl_set_get_ctx(array), isl_error_internal,
438 "unable to find array in scop", goto error);
440 info->type = strdup(pa->element_type);
441 info->size = pa->element_size;
442 info->local = pa->declared && !pa->exposed;
443 info->read_only_scalar = is_read_only_scalar(info, prog);
445 extent = compute_extent(pa, array);
446 for (i = 0; i < n_index; ++i) {
447 isl_set *dom;
448 isl_local_space *ls;
449 isl_aff *one;
450 isl_pw_aff *bound;
452 bound = isl_set_dim_max(isl_set_copy(extent), i);
453 assert(bound);
454 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
455 ls = isl_local_space_from_space(isl_set_get_space(dom));
456 one = isl_aff_zero_on_domain(ls);
457 one = isl_aff_add_constant_si(one, 1);
458 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
459 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
461 bounds[i] = bound;
462 if (!isl_pw_aff_is_cst(bound))
463 info->linearize = 1;
465 info->extent = extent;
467 collect_references(prog, info);
469 isl_set_free(array);
470 return 0;
471 error:
472 isl_set_free(array);
473 return -1;
476 /* Construct a gpu_array_info for each array accessed by "prog" and
477 * collect them in prog->array.
479 static int collect_array_info(struct gpu_prog *prog)
481 int r;
482 isl_union_set *arrays;
484 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
485 arrays = isl_union_set_union(arrays,
486 isl_union_map_range(isl_union_map_copy(prog->write)));
487 arrays = isl_union_set_coalesce(arrays);
489 prog->n_array = isl_union_set_n_set(arrays);
490 prog->array = isl_alloc_array(prog->ctx,
491 struct gpu_array_info, prog->n_array);
492 assert(prog->array);
493 prog->n_array = 0;
494 r = isl_union_set_foreach_set(arrays, &extract_array_info, prog);
495 isl_union_set_free(arrays);
497 return r;
500 static void free_array_info(struct gpu_prog *prog)
502 int i, j;
504 for (i = 0; i < prog->n_array; ++i) {
505 int n_index = prog->array[i].n_index;
506 free(prog->array[i].type);
507 free(prog->array[i].name);
508 for (j = 0; j < n_index; ++j)
509 isl_pw_aff_free(prog->array[i].bound[j]);
510 isl_space_free(prog->array[i].space);
511 isl_set_free(prog->array[i].extent);
512 free(prog->array[i].bound);
513 free(prog->array[i].refs);
515 free(prog->array);
518 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
519 * as an array or through a pointer reference, but as single data element. At
520 * the moment, scalars are represented as zero dimensional arrays.
522 int gpu_array_is_scalar(struct gpu_array_info *array)
524 return (array->n_index == 0);
527 /* Is "array" a read-only scalar?
529 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
531 return array->read_only_scalar;
534 /* Internal data structure for extract_size_of_type.
535 * "type" specifies the name of the space that we want to extract.
536 * "res" is used to store the subset of that space.
538 struct ppcg_extract_size_data {
539 const char *type;
540 isl_set *res;
543 /* This function is called for each set in a union_set.
544 * If the name of the set matches data->type, we store the
545 * set in data->res.
547 static int extract_size_of_type(__isl_take isl_set *size, void *user)
549 struct ppcg_extract_size_data *data = user;
550 const char *name;
552 name = isl_set_get_tuple_name(size);
553 if (name && !strcmp(name, data->type)) {
554 data->res = size;
555 return -1;
558 isl_set_free(size);
559 return 0;
562 /* Given a union map { kernel[i] -> *[...] },
563 * return the range in the space called "type" for the kernel with
564 * sequence number "id".
566 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
567 const char *type, int id)
569 isl_space *space;
570 isl_set *dom;
571 isl_union_set *local_sizes;
572 struct ppcg_extract_size_data data = { type, NULL };
574 if (!sizes)
575 return NULL;
577 space = isl_union_map_get_space(sizes);
578 space = isl_space_set_from_params(space);
579 space = isl_space_add_dims(space, isl_dim_set, 1);
580 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
581 dom = isl_set_universe(space);
582 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
584 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
585 isl_union_map_copy(sizes));
586 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
587 isl_union_set_free(local_sizes);
588 return data.res;
591 /* Given a singleton set, extract the first (at most *len) elements
592 * of the single integer tuple into *sizes and update *len if needed.
594 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
596 int i;
597 int dim;
599 if (!set)
600 return;
602 dim = isl_set_dim(set, isl_dim_set);
603 if (dim < *len)
604 *len = dim;
606 for (i = 0; i < *len; ++i) {
607 isl_val *v;
609 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
610 assert(v);
612 sizes[i] = isl_val_get_num_si(v);
613 isl_val_free(v);
616 isl_set_free(set);
619 /* Extract user specified "tile" sizes from the "sizes" command line option,
620 * defaulting to option->tile_size in each dimension.
622 static void read_tile_sizes(struct gpu_gen *gen)
624 int n;
625 isl_set *size;
627 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
628 assert(gen->tile_size);
629 for (n = 0; n < gen->tile_len; ++n)
630 gen->tile_size[n] = gen->options->tile_size;
632 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
633 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
635 if (gen->n_parallel > gen->tile_len)
636 gen->n_parallel = gen->tile_len;
639 /* Extract user specified "block" sizes from the "sizes" command line option,
640 * after filling in some potentially useful defaults.
642 static void read_block_sizes(struct gpu_gen *gen)
644 int n;
645 isl_set *size;
647 n = gen->n_parallel;
648 gen->n_block = (n <= 3) ? n : 3;
649 switch (gen->n_block) {
650 case 1:
651 gen->block_dim[0] = 512;
652 break;
653 case 2:
654 gen->block_dim[0] = 32;
655 gen->block_dim[1] = 16;
656 break;
657 default:
658 gen->block_dim[0] = 32;
659 gen->block_dim[1] = 4;
660 gen->block_dim[2] = 4;
661 break;
664 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
665 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
668 /* Extract user specified "grid" sizes from the "sizes" command line option,
669 * after filling in some potentially useful defaults.
671 static void read_grid_sizes(struct gpu_gen *gen)
673 int n = gen->n_parallel;
674 isl_set *size;
676 gen->n_grid = (n <= 2) ? n : 2;
677 switch (gen->n_grid) {
678 case 1:
679 gen->grid_dim[0] = 32768;
680 break;
681 default:
682 gen->grid_dim[0] = 256;
683 gen->grid_dim[1] = 256;
684 break;
687 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
688 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
691 /* Extract user specified sizes from the "sizes" command line option
692 * after filling in some potentially useful defaults.
694 static void read_sizes(struct gpu_gen *gen)
696 read_tile_sizes(gen);
697 read_block_sizes(gen);
698 read_grid_sizes(gen);
701 static void *free_stmts(struct gpu_stmt *stmts, int n)
703 int i;
705 if (!stmts)
706 return NULL;
708 for (i = 0; i < n; ++i) {
709 struct gpu_stmt_access *access, *next;
711 for (access = stmts[i].accesses; access; access = next) {
712 next = access->next;
713 isl_id_free(access->ref_id);
714 isl_map_free(access->access);
715 free(access);
718 isl_id_free(stmts[i].id);
720 free(stmts);
722 return NULL;
725 /* Construct a map from a domain of dimensionality "len"
726 * to a domain of dimensionality "len" + "tile_len" that tiles
727 * the "tile_len" coordinates starting at "first".
728 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
729 * "dim" prescribes the parameters.
731 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
732 int first, int tile_len, int *tile_size)
734 int i;
735 isl_basic_map *bmap;
736 isl_constraint *c;
737 isl_local_space *ls;
739 dim = isl_space_add_dims(dim, isl_dim_in, len);
740 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
741 bmap = isl_basic_map_universe(isl_space_copy(dim));
742 ls = isl_local_space_from_space(dim);
744 for (i = 0; i < len - tile_len; ++i) {
745 int j = i < first ? i : i + tile_len;
746 int k = i < first ? i : i + 2 * tile_len;
748 c = isl_equality_alloc(isl_local_space_copy(ls));
749 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
750 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
751 bmap = isl_basic_map_add_constraint(bmap, c);
754 for (i = 0; i < tile_len; ++i) {
755 c = isl_equality_alloc(isl_local_space_copy(ls));
756 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
757 first + i, -1);
758 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
759 first + i, tile_size[i]);
760 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
761 first + i + tile_len, 1);
762 bmap = isl_basic_map_add_constraint(bmap, c);
764 c = isl_inequality_alloc(isl_local_space_copy(ls));
765 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
766 first + i + tile_len, 1);
767 bmap = isl_basic_map_add_constraint(bmap, c);
769 c = isl_inequality_alloc(isl_local_space_copy(ls));
770 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
771 first + i + tile_len, -1);
772 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
773 bmap = isl_basic_map_add_constraint(bmap, c);
776 isl_local_space_free(ls);
778 return isl_map_from_basic_map(bmap);
781 /* Construct a map from a domain of dimensionality "len"
782 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
783 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
784 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
785 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
786 * that are projected out at the end.
787 * "dim" prescribes the parameters.
789 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
790 int first, int wrap_len, int *wrap_size)
792 int i;
793 isl_basic_map *bmap;
794 isl_constraint *c;
795 isl_local_space *ls;
797 dim = isl_space_add_dims(dim, isl_dim_in, len);
798 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
799 bmap = isl_basic_map_universe(isl_space_copy(dim));
800 ls = isl_local_space_from_space(dim);
802 for (i = 0; i < len; ++i) {
803 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
805 c = isl_equality_alloc(isl_local_space_copy(ls));
806 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
807 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
808 bmap = isl_basic_map_add_constraint(bmap, c);
811 for (i = 0; i < wrap_len; ++i) {
812 c = isl_equality_alloc(isl_local_space_copy(ls));
813 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
814 first + i, -1);
815 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
816 first + wrap_len + i, 1);
817 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
818 first + 2 * wrap_len + i, wrap_size[i]);
819 bmap = isl_basic_map_add_constraint(bmap, c);
821 c = isl_inequality_alloc(isl_local_space_copy(ls));
822 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
823 first + wrap_len + i, 1);
824 bmap = isl_basic_map_add_constraint(bmap, c);
826 c = isl_inequality_alloc(isl_local_space_copy(ls));
827 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
828 first + wrap_len + i, -1);
829 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
830 bmap = isl_basic_map_add_constraint(bmap, c);
833 isl_local_space_free(ls);
835 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
836 first + 2 * wrap_len, wrap_len);
838 return isl_map_from_basic_map(bmap);
841 /* Add "n" parameters named prefix%d.
843 static __isl_give isl_set *add_params( __isl_take isl_set *set,
844 int n, const char *prefix)
846 int i;
847 unsigned nparam;
848 char name[20];
850 nparam = isl_set_dim(set, isl_dim_param);
851 set = isl_set_add_dims(set, isl_dim_param, n);
853 for (i = 0; i < n; ++i) {
854 snprintf(name, sizeof(name), "%s%d", prefix, i);
855 set = isl_set_set_dim_name(set, isl_dim_param,
856 nparam + i, name);
859 return set;
862 /* Equate the "n" dimensions of "set" starting at "first" to
863 * freshly created parameters named prefix%d.
865 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
866 int first, int n, const char *prefix)
868 int i;
869 unsigned nparam;
871 nparam = isl_set_dim(set, isl_dim_param);
873 set = add_params(set, n, prefix);
875 for (i = 0; i < n; ++i)
876 set = isl_set_equate(set, isl_dim_param, nparam + i,
877 isl_dim_set, first + i);
879 return set;
882 /* Given a parameter space "space", create a set of dimension "len"
883 * of which the "n" dimensions starting at "first" are equated to
884 * freshly created parameters named prefix%d.
886 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
887 int len, int first, int n, const char *prefix)
889 isl_set *set;
891 space = isl_space_set_from_params(space);
892 space = isl_space_add_dims(space, isl_dim_set, len);
893 set = isl_set_universe(space);
895 return parametrize(set, first, n, prefix);
898 /* Tile the B loops over the tile sizes and then tile/wrap
899 * the T1 loops over the blocks.
901 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
902 __isl_take isl_union_map *sched)
904 isl_space *dim;
905 isl_map *tiling, *block_tiling;
907 dim = isl_union_map_get_space(sched);
908 tiling = tile(isl_space_copy(dim), gen->untiled_len,
909 gen->tile_first, gen->tile_len, gen->tile_size);
911 if (gen->options->wrap)
912 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
913 gen->tile_first, gen->n_grid, gen->grid_dim);
914 else
915 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
916 gen->tile_first, gen->n_grid, gen->grid_dim);
918 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
920 tiling = isl_map_apply_range(tiling, block_tiling);
922 sched = isl_union_map_apply_range(sched,
923 isl_union_map_from_map(tiling));
925 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
927 return sched;
930 /* Equate the "T1P" iterators in the tiled schedule "sched"
931 * to the block dimensions.
933 static __isl_give isl_union_map *parametrize_tiled_schedule(
934 struct gpu_gen *gen, __isl_take isl_union_map *sched)
936 isl_space *dim;
937 isl_set *par;
939 dim = isl_union_map_get_space(sched);
940 par = parametrization(dim, gen->tiled_len,
941 gen->tile_first + gen->n_grid, gen->n_grid, "b");
942 sched = isl_union_map_intersect_range(sched,
943 isl_union_set_from_set(par));
945 return sched;
948 /* Tile/wrap the P1 loops over the threads.
950 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
951 __isl_take isl_union_map *sched)
953 isl_space *dim;
954 isl_map *tiling;
955 isl_set *par;
957 dim = isl_union_map_get_space(sched);
959 if (gen->options->wrap)
960 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
961 gen->shared_len, gen->n_block, gen->block_dim);
962 else
963 tiling = tile(isl_space_copy(dim), gen->tiled_len,
964 gen->shared_len, gen->n_block, gen->block_dim);
965 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
967 sched = isl_union_map_apply_range(sched,
968 isl_union_map_from_map(tiling));
970 par = parametrization(dim, gen->thread_tiled_len,
971 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
972 gen->n_block, "t");
973 sched = isl_union_map_intersect_range(sched,
974 isl_union_set_from_set(par));
976 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
978 return sched;
981 /* If the user asked for it, scale the shared memory tile loops
982 * (T1T and T2) of "sched" by gen->tile_size[i].
983 * If we are not performing "wrapping", then additionally scale the T1P
984 * loops by gen->grid_dim[i].
986 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
987 __isl_take isl_union_map *sched)
989 int i;
990 isl_space *dim;
991 isl_basic_map *scale;
992 isl_constraint *c;
993 isl_local_space *ls;
995 if (!gen->options->scale_tile_loops)
996 return sched;
998 dim = isl_union_map_get_space(sched);
999 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
1000 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
1001 scale = isl_basic_map_universe(isl_space_copy(dim));
1002 ls = isl_local_space_from_space(dim);
1004 for (i = 0; i < gen->tiled_len; ++i) {
1005 int f = 1;
1007 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
1008 f = gen->tile_size[i - gen->tile_first];
1009 if (!gen->options->wrap)
1010 f *= gen->grid_dim[i - gen->tile_first];
1011 } else if (i >= gen->tile_first + gen->n_grid &&
1012 i < gen->tile_first + gen->n_grid + gen->tile_len) {
1013 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
1016 c = isl_equality_alloc(isl_local_space_copy(ls));
1017 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1018 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1019 scale = isl_basic_map_add_constraint(scale, c);
1022 isl_local_space_free(ls);
1024 sched = isl_union_map_apply_range(sched,
1025 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1027 return sched;
1030 /* If we are not performing "wrapping" and if the user asked for it,
1031 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1033 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1034 __isl_take isl_union_map *sched)
1036 int i;
1037 isl_space *dim;
1038 isl_basic_map *scale;
1039 isl_constraint *c;
1040 isl_local_space *ls;
1042 if (gen->options->wrap)
1043 return sched;
1044 if (!gen->options->scale_tile_loops)
1045 return sched;
1047 dim = isl_union_map_get_space(sched);
1048 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1049 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1050 scale = isl_basic_map_universe(isl_space_copy(dim));
1051 ls = isl_local_space_from_space(dim);
1053 for (i = 0; i < gen->thread_tiled_len; ++i) {
1054 int f = 1;
1056 if (i >= gen->shared_len &&
1057 i < gen->shared_len + gen->n_block)
1058 f = gen->block_dim[i - gen->shared_len];
1060 c = isl_equality_alloc(isl_local_space_copy(ls));
1061 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1062 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1063 scale = isl_basic_map_add_constraint(scale, c);
1066 isl_local_space_free(ls);
1068 sched = isl_union_map_apply_range(sched,
1069 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1071 return sched;
1074 /* If we are not performing "wrapping" and if the user asked for it,
1075 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1077 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1078 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1080 int i;
1081 isl_space *dim;
1082 isl_basic_map *scale;
1083 isl_constraint *c;
1084 isl_local_space *ls;
1086 if (gen->options->wrap)
1087 return sched;
1088 if (!gen->options->scale_tile_loops)
1089 return sched;
1091 dim = isl_union_map_get_space(sched);
1092 dim = isl_space_add_dims(dim, isl_dim_in, len);
1093 dim = isl_space_add_dims(dim, isl_dim_out, len);
1094 scale = isl_basic_map_universe(isl_space_copy(dim));
1095 ls = isl_local_space_from_space(dim);
1097 for (i = 0; i < len; ++i) {
1098 int f = 1;
1100 if (i >= first && i < first + n_tile)
1101 f = gen->kernel->block_dim[i - first];
1103 c = isl_equality_alloc(isl_local_space_copy(ls));
1104 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1105 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1106 scale = isl_basic_map_add_constraint(scale, c);
1109 isl_local_space_free(ls);
1111 sched = isl_union_map_apply_range(sched,
1112 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1114 return sched;
1117 /* Add "len" parameters p[i] called prefix%d,
1118 * with bounds to 0 <= p[i] < size[i].
1120 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1121 int len, int *size, const char *prefix)
1123 int i;
1124 unsigned nparam;
1125 isl_space *dim;
1126 isl_basic_set *bset;
1127 isl_constraint *c;
1128 isl_local_space *ls;
1129 char name[20];
1131 nparam = isl_set_dim(set, isl_dim_param);
1132 set = isl_set_add_dims(set, isl_dim_param, len);
1134 for (i = 0; i < len; ++i) {
1135 snprintf(name, sizeof(name), "%s%d", prefix, i);
1136 set = isl_set_set_dim_name(set, isl_dim_param,
1137 nparam + i, name);
1140 dim = isl_set_get_space(set);
1141 bset = isl_basic_set_universe(isl_space_copy(dim));
1142 ls = isl_local_space_from_space(dim);
1144 for (i = 0; i < len; ++i) {
1145 c = isl_inequality_alloc(isl_local_space_copy(ls));
1146 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1147 nparam + i, 1);
1148 bset = isl_basic_set_add_constraint(bset, c);
1150 c = isl_inequality_alloc(isl_local_space_copy(ls));
1151 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1152 nparam + i, -1);
1153 c = isl_constraint_set_constant_si(c, size[i] - 1);
1154 bset = isl_basic_set_add_constraint(bset, c);
1157 isl_local_space_free(ls);
1159 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1162 /* Add "len" parameters p[i] called prefix%d,
1163 * with bounds to 0 <= p[i] < size[i].
1165 static __isl_give isl_set *add_bounded_parameters_dynamic(
1166 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1167 const char *prefix)
1169 int i, len;
1170 unsigned nparam;
1171 isl_space *space;
1172 isl_local_space *ls;
1173 char name[20];
1175 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1176 nparam = isl_set_dim(set, isl_dim_param);
1177 set = isl_set_add_dims(set, isl_dim_param, len);
1179 for (i = 0; i < len; ++i) {
1180 snprintf(name, sizeof(name), "%s%d", prefix, i);
1181 set = isl_set_set_dim_name(set, isl_dim_param,
1182 nparam + i, name);
1185 space = isl_space_params(isl_set_get_space(set));
1186 ls = isl_local_space_from_space(space);
1187 for (i = 0; i < len; ++i) {
1188 isl_pw_aff *param, *size_i, *zero;
1189 isl_set *bound;
1191 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1192 isl_dim_param, nparam + i);
1194 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1195 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1196 set = isl_set_intersect_params(set, bound);
1198 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1199 bound = isl_pw_aff_ge_set(param, zero);
1200 set = isl_set_intersect_params(set, bound);
1202 isl_local_space_free(ls);
1204 return set;
1207 /* Construct a map from an access to group->array to the corresponding
1208 * shared/private memory tile.
1209 * The map is of the form
1211 * { [D[i] -> A[a]] -> T[t] }
1213 * where D represents the initial shared_len dimensions
1214 * of the computed schedule.
1216 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1218 struct gpu_array_tile *tile;
1219 isl_multi_aff *tiling;
1221 tile = group->private_tile;
1222 if (!tile)
1223 tile = group->shared_tile;
1225 tiling = isl_multi_aff_copy(tile->tiling);
1227 return isl_map_from_multi_aff(tiling);
1230 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1232 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1233 unsigned pos)
1235 isl_val *v;
1236 int fixed;
1238 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1239 if (!v)
1240 return -1;
1241 fixed = isl_val_is_int(v);
1242 isl_val_free(v);
1244 return fixed;
1247 /* Given a schedule that iterates over all elements in a piece of an array,
1248 * perform tiling/wrapping over the threads.
1250 * In particular, we tile the final iterators so that the final thread
1251 * dimension runs over the final array dimension.
1252 * However, if those final iterators have only a single iteration,
1253 * we try to tile earlier iterators instead.
1255 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1256 __isl_take isl_map *sched)
1258 isl_space *dim;
1259 isl_union_map *usched;
1260 isl_map *tiling;
1261 isl_set *par;
1262 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1263 int n_tile;
1264 int first;
1266 n_tile = gen->kernel->n_block;
1267 if (n_tile > nvar) {
1268 int i;
1269 sched = isl_map_insert_dims(sched,
1270 isl_dim_out, 0, n_tile - nvar);
1271 for (i = 0; i < n_tile - nvar; ++i)
1272 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1273 nvar = n_tile;
1276 first = nvar - n_tile;
1278 for (; first > 0; first --)
1279 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1280 break;
1282 dim = isl_map_get_space(sched);
1283 dim = isl_space_params(dim);
1284 if (gen->options->wrap)
1285 tiling = wrap(isl_space_copy(dim), nvar, first,
1286 n_tile, gen->kernel->block_dim);
1287 else
1288 tiling = tile(isl_space_copy(dim), nvar, first,
1289 n_tile, gen->kernel->block_dim);
1290 sched = isl_map_apply_range(sched, tiling);
1292 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1293 sched = isl_map_intersect_range(sched, par);
1295 usched = isl_union_map_from_map(sched);
1296 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1297 first, n_tile);
1298 sched = isl_map_from_union_map(usched);
1300 return sched;
1303 /* Return the union of all read (read = 1) and/or write (write = 1)
1304 * access relations in the group.
1306 static __isl_give isl_union_map *group_access_relation(
1307 struct gpu_array_ref_group *group, int read, int write)
1309 int i;
1310 isl_union_map *access;
1312 access = isl_union_map_empty(isl_map_get_space(group->access));
1313 for (i = 0; i < group->n_ref; ++i) {
1314 isl_map *map_i;
1316 if (!((read && group->refs[i]->read) ||
1317 (write && group->refs[i]->write)))
1318 continue;
1319 map_i = isl_map_copy(group->refs[i]->access);
1320 access = isl_union_map_union(access,
1321 isl_union_map_from_map(map_i));
1324 return access;
1327 /* Return the extent of "array", recomputed from the bounds.
1328 * The recomputed extent may be simpler than the original extent.
1330 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1332 int i;
1333 isl_id *id;
1334 isl_space *space;
1335 isl_local_space *ls;
1336 isl_set *extent;
1338 id = isl_set_get_tuple_id(array->extent);
1339 space = isl_set_get_space(array->extent);
1340 extent = isl_set_universe(isl_space_copy(space));
1341 ls = isl_local_space_from_space(space);
1342 for (i = 0; i < array->n_index; ++i) {
1343 isl_pw_aff *bound;
1344 isl_aff *aff;
1345 isl_pw_aff *index;
1346 isl_set *lt;
1348 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1350 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1351 isl_dim_set, i);
1352 index = isl_pw_aff_from_aff(aff);
1353 bound = isl_pw_aff_copy(array->bound[i]);
1354 bound = isl_pw_aff_from_range(bound);
1355 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1356 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1357 isl_id_copy(id));
1358 lt = isl_pw_aff_lt_set(index, bound);
1359 extent = isl_set_intersect(extent, lt);
1361 isl_local_space_free(ls);
1362 isl_id_free(id);
1364 return extent;
1367 /* Return a map from the first shared_len dimensions of the computed
1368 * schedule to the array tile in
1369 * global memory that corresponds to the shared memory copy.
1371 * In particular, return a map
1373 * { D[i] -> A[a] }
1375 * with constraints
1377 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1379 * and
1381 * 0 <= a <= array_size - 1 (2)
1383 * Note that if some stride has been detected (i.e., when
1384 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1385 * to the shifted and scaled down version.
1387 * Constraints (1) are obtained by mapping the size constraints on the
1388 * shared/private memory tile back to the access relation.
1389 * Constraints (2) are obtained from the (recomputed) extent.
1391 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1393 int i;
1394 int n_index = group->array->n_index;
1395 isl_map *tile;
1396 isl_space *space;
1397 isl_set *local;
1398 isl_set *extent;
1400 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1401 space = isl_space_range(space);
1402 local = isl_set_universe(space);
1403 for (i = 0; i < n_index; ++i) {
1404 isl_val *bound;
1406 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1407 bound = isl_val_copy(group->shared_tile->bound[i].size);
1408 bound = isl_val_sub_ui(bound, 1);
1409 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1411 local = isl_set_preimage_multi_aff(local,
1412 isl_multi_aff_copy(group->shared_tile->tiling));
1413 tile = isl_set_unwrap(local);
1414 extent = array_extent(group->array);
1415 tile = isl_map_intersect_range(tile, extent);
1417 return tile;
1420 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1421 * return the corresponding mapping from the AST schedule to
1422 * to the first shared_len dimensions of the schedule computed by PPCG.
1424 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1425 __isl_take isl_pw_multi_aff *iterator_map)
1427 isl_union_map *umap;
1428 isl_space *space;
1429 isl_map *map, *sched;;
1431 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1432 space = isl_space_from_domain(space);
1433 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1435 umap = isl_union_map_copy(gen->shared_sched);
1436 umap = isl_union_map_apply_range(umap,
1437 isl_union_map_copy(gen->shared_proj));
1438 map = isl_union_map_extract_map(umap, space);
1439 isl_union_map_free(umap);
1441 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1442 sched = isl_map_detect_equalities(sched);
1444 return isl_pw_multi_aff_from_map(sched);
1447 /* Set unroll[j] if the input dimension j is involved in
1448 * the index expression represented by ma.
1450 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1451 void *user)
1453 int i, j;
1454 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1455 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1456 int *unroll = user;
1458 for (i = 0; i < n_out; ++i) {
1459 isl_aff *aff;
1461 aff = isl_multi_aff_get_aff(ma, i);
1462 for (j = 0; j < n_in; ++j)
1463 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1464 unroll[j] = 1;
1465 isl_aff_free(aff);
1468 isl_set_free(set);
1469 isl_multi_aff_free(ma);
1470 return 0;
1473 /* Given an array pos mapping input dimensions to the corresponding
1474 * output dimension, construct the corresponding map.
1476 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1477 int *pos, int len)
1479 int i;
1480 isl_constraint *c;
1481 isl_basic_map *bmap;
1482 isl_local_space *ls;
1484 dim = isl_space_add_dims(dim, isl_dim_in, len);
1485 dim = isl_space_add_dims(dim, isl_dim_out, len);
1486 bmap = isl_basic_map_universe(isl_space_copy(dim));
1487 ls = isl_local_space_from_space(dim);
1489 for (i = 0; i < len; ++i) {
1490 c = isl_equality_alloc(isl_local_space_copy(ls));
1491 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1492 -1);
1493 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1495 bmap = isl_basic_map_add_constraint(bmap, c);
1497 isl_local_space_free(ls);
1499 return isl_map_from_basic_map(bmap);
1502 /* Find all loops involved in any of the index expressions for any of
1503 * the private accesses, move them innermost and then mark them as
1504 * requiring unrolling by setting gen->first_unroll.
1505 * The loops involved should all be parallel because of the checks
1506 * we performed in check_private_group_access. Moving them innermost
1507 * is therefore a valid transformation.
1509 * Loops up to gen->shared_len are generated before the mapping to
1510 * threads is applied. They should therefore be ignored.
1512 * We compute the hidden equalities of the schedule first
1513 * since we will need them in our calls to isl_pw_multi_aff_from_map
1514 * and because we want to make sure that the same equalities
1515 * are also available to the code generator.
1517 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1518 __isl_take isl_union_map *sched)
1520 int i, j;
1521 int unroll[gen->thread_tiled_len];
1522 int perm[gen->thread_tiled_len];
1523 isl_space *dim;
1524 isl_map *permute;
1525 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1527 gen->first_unroll = -1;
1529 sched = isl_union_map_detect_equalities(sched);
1530 for (i = 0; i < gen->thread_tiled_len; ++i)
1531 unroll[i] = 0;
1532 for (i = 0; i < gen->prog->n_array; ++i) {
1533 struct gpu_array_info *array = &gen->prog->array[i];
1535 for (j = 0; j < array->n_group; ++j) {
1536 isl_union_map *access;
1537 isl_map *acc;
1538 isl_pw_multi_aff *pma;
1540 if (!array->groups[j]->private_tile)
1541 continue;
1543 access = group_access_relation(array->groups[j], 1, 1);
1544 access = isl_union_map_apply_domain(access,
1545 isl_union_map_copy(sched));
1547 acc = isl_map_from_union_map(access);
1548 pma = isl_pw_multi_aff_from_map(acc);
1549 isl_pw_multi_aff_foreach_piece(pma,
1550 &check_unroll, unroll);
1552 isl_pw_multi_aff_free(pma);
1556 for (i = gen->shared_len; i < len; ++i)
1557 if (unroll[i])
1558 break;
1560 if (i >= len)
1561 return sched;
1563 for (i = len; i < gen->thread_tiled_len; ++i)
1564 if (unroll[i])
1565 return sched;
1567 j = 0;
1568 for (i = 0; i < gen->shared_len; ++i)
1569 perm[i] = j++;
1570 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1571 if (!unroll[i])
1572 perm[i] = j++;
1573 gen->first_unroll = j - gen->shared_len;
1574 for (i = gen->shared_len; i < len; ++i)
1575 if (unroll[i])
1576 perm[i] = j++;
1578 dim = isl_union_map_get_space(sched);
1579 permute = permutation(dim, perm, gen->thread_tiled_len);
1580 sched = isl_union_map_apply_range(sched,
1581 isl_union_map_from_map(permute));
1583 return sched;
1586 /* Given a constraint
1588 * a(p,i) + j = g f(e)
1590 * or -a(p,i) - j = g f(e) if sign < 0,
1591 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1592 * a(p,i) is assumed to be an expression in only the parameters
1593 * and the input dimensions.
1595 static void extract_stride(__isl_keep isl_constraint *c,
1596 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1598 int i;
1599 isl_val *v;
1600 isl_space *space;
1601 unsigned nparam;
1602 unsigned nvar;
1603 isl_aff *aff;
1605 isl_val_free(bound->stride);
1606 bound->stride = isl_val_copy(stride);
1608 space = isl_constraint_get_space(c);
1609 space = isl_space_domain(space);
1611 nparam = isl_space_dim(space, isl_dim_param);
1612 nvar = isl_space_dim(space, isl_dim_set);
1614 v = isl_constraint_get_constant_val(c);
1615 if (sign < 0)
1616 v = isl_val_neg(v);
1617 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1618 aff = isl_aff_set_constant_val(aff, v);
1620 for (i = 0; i < nparam; ++i) {
1621 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1622 continue;
1623 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1624 if (sign < 0)
1625 v = isl_val_neg(v);
1626 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1629 for (i = 0; i < nvar; ++i) {
1630 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1631 continue;
1632 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1633 if (sign < 0)
1634 v = isl_val_neg(v);
1635 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1638 bound->shift = aff;
1641 /* Given an equality constraint of a map with a single output dimension j,
1642 * check if the constraint is of the form
1644 * a(p,i) + j = g f(e)
1646 * with a(p,i) an expression in the parameters and input dimensions
1647 * and f(e) an expression in the existentially quantified variables.
1648 * If so, and if g is larger than any such g from a previously considered
1649 * constraint, then call extract_stride to record the stride information
1650 * in bound.
1652 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1654 int i;
1655 isl_ctx *ctx;
1656 isl_val *v;
1657 unsigned n_div;
1658 struct gpu_array_bound *bound = user;
1660 ctx = isl_constraint_get_ctx(c);
1661 n_div = isl_constraint_dim(c, isl_dim_div);
1662 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1664 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1665 int s = isl_val_sgn(v);
1666 isl_val *stride = isl_val_zero(ctx);
1668 isl_val_free(v);
1669 for (i = 0; i < n_div; ++i) {
1670 v = isl_constraint_get_coefficient_val(c,
1671 isl_dim_div, i);
1672 stride = isl_val_gcd(stride, v);
1674 if (!isl_val_is_zero(stride) &&
1675 isl_val_gt(stride, bound->stride))
1676 extract_stride(c, bound, stride, s);
1678 isl_val_free(stride);
1679 } else
1680 isl_val_free(v);
1682 isl_constraint_free(c);
1683 return 0;
1686 /* Given contraints on an array index i, check if we can find
1687 * a shift a(p) and a stride g such that
1689 * a(p) + i = 0 mod g
1691 * If so, record the information in bound and apply the mapping
1692 * i -> (i + a(p))/g to the array index in bounds and return
1693 * the new constraints.
1694 * If not, simply return the original constraints.
1696 * If bounds is a subset of the space
1698 * D -> i
1700 * then the bound recorded in bound->shift is of the form
1702 * D -> s(D)
1704 * with s(D) equal to a(p) above.
1705 * The mapping recorded in bound->shift_map is of the form
1707 * [D -> i] -> [D -> (i + S(D))/g]
1709 * This mapping is computed as follows.
1710 * We first introduce "i" in the domain through precomposition
1711 * with [D -> i] -> D obtaining
1713 * [D -> i] -> s(D)
1715 * Adding [D -> i] -> i produces
1717 * [D -> i] -> i + s(D)
1719 * and the domain product with [D -> i] -> D yields
1721 * [D -> i] -> [D -> i + s(D)]
1723 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1725 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1726 __isl_take isl_basic_map *bounds)
1728 isl_space *space;
1729 isl_basic_map *hull;
1730 isl_basic_map *shift, *id, *bmap, *scale;
1731 isl_basic_set *bset;
1732 isl_aff *aff;
1734 bound->stride = NULL;
1736 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1738 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1740 isl_basic_map_free(hull);
1742 if (!bound->stride)
1743 return bounds;
1745 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1746 space = isl_basic_map_get_space(bounds);
1747 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1748 shift = isl_basic_map_apply_range(bmap, shift);
1749 space = isl_basic_map_get_space(bounds);
1750 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1751 shift = isl_basic_map_sum(id, shift);
1752 space = isl_basic_map_get_space(bounds);
1753 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1754 shift = isl_basic_map_range_product(id, shift);
1756 space = isl_space_domain(isl_basic_map_get_space(bounds));
1757 id = isl_basic_map_identity(isl_space_map_from_set(space));
1758 space = isl_space_range(isl_basic_map_get_space(bounds));
1759 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1760 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1761 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
1762 scale = isl_basic_map_from_aff(aff);
1763 scale = isl_basic_map_product(id, scale);
1765 bound->shift_map = isl_basic_map_apply_range(shift, scale);
1766 bmap = isl_basic_map_copy(bound->shift_map);
1767 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1768 bounds = isl_basic_set_unwrap(bset);
1770 return bounds;
1773 /* Data used in compute_array_dim_size and compute_size_in_direction.
1775 * pos is the position of the variable representing the array index,
1776 * i.e., the variable for which want to compute the size. This variable
1777 * is also the last variable in the set.
1779 struct gpu_size_info {
1780 isl_basic_set *bset;
1781 struct gpu_array_bound *bound;
1782 int pos;
1785 /* Given a constraint from the basic set describing the bounds on
1786 * an array index, check if it is a lower bound, say m i >= b(x), and,
1787 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
1788 * upper bound. If so, and if this bound is smaller than any bound
1789 * derived from earlier constraints, set the size to this bound on
1790 * the expression and the lower bound to ceil(b(x)/m).
1792 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
1794 struct gpu_size_info *size = user;
1795 unsigned nparam;
1796 unsigned n_div;
1797 isl_val *v;
1798 isl_aff *aff;
1799 isl_aff *lb;
1801 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
1802 n_div = isl_constraint_dim(c, isl_dim_div);
1804 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
1805 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
1806 isl_constraint_free(c);
1807 return 0;
1810 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
1811 aff = isl_aff_ceil(aff);
1813 lb = isl_aff_copy(aff);
1815 aff = isl_aff_neg(aff);
1816 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
1818 v = isl_basic_set_max_val(size->bset, aff);
1819 isl_aff_free(aff);
1821 if (isl_val_is_int(v)) {
1822 v = isl_val_add_ui(v, 1);
1823 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
1824 isl_val_free(size->bound->size);
1825 size->bound->size = isl_val_copy(v);
1826 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
1827 isl_aff_free(size->bound->lb);
1828 size->bound->lb = isl_aff_copy(lb);
1831 isl_val_free(v);
1832 isl_aff_free(lb);
1834 isl_constraint_free(c);
1836 return 0;
1839 /* Given a basic map "bounds" that maps parameters and input dimensions
1840 * to a single output dimension, look for an expression in the parameters
1841 * and input dimensions such that the range of the output dimension shifted
1842 * by this expression is a constant.
1844 * In particular, we currently only consider lower bounds on the output
1845 * dimension as candidate expressions.
1847 static int compute_array_dim_size(struct gpu_array_bound *bound,
1848 __isl_take isl_basic_map *bounds)
1850 struct gpu_size_info size;
1852 bounds = isl_basic_map_detect_equalities(bounds);
1853 bounds = check_stride(bound, bounds);
1855 bound->size = NULL;
1856 bound->lb = NULL;
1858 size.bound = bound;
1859 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
1860 size.bset = isl_basic_map_wrap(bounds);
1861 size.bset = isl_basic_set_flatten(size.bset);
1862 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
1863 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
1864 &size);
1865 isl_basic_set_free(size.bset);
1867 return bound->size ? 0 : -1;
1870 /* Check if we can find a memory tile for the given array
1871 * based on the given accesses, and if so, put the results in "tile".
1873 * We project the accesses on each index in turn and look for a parametric
1874 * offset such that the size is constant.
1876 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
1878 int i;
1880 for (i = 0; i < tile->n; ++i) {
1881 isl_map *access_i;
1882 isl_basic_map *hull;
1884 access_i = isl_map_copy(access);
1885 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
1886 access_i = isl_map_project_out(access_i, isl_dim_out,
1887 1, tile->n - (i + 1));
1888 access_i = isl_map_compute_divs(access_i);
1889 hull = isl_map_simple_hull(access_i);
1890 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
1891 return 0;
1894 return 1;
1897 /* Construct a map with input the shared tile loops and the loops that
1898 * will be wrapped around the threads that relates these later loops
1899 * to the thread indices and then projects them out.
1901 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
1903 isl_map *priv;
1904 isl_map *tiling;
1905 isl_map *proj;
1906 isl_set *par;
1907 isl_space *dim;
1909 dim = isl_union_map_get_space(gen->shared_sched);
1911 if (gen->options->wrap)
1912 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
1913 gen->shared_len, gen->n_block, gen->block_dim);
1914 else
1915 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
1916 gen->shared_len, gen->n_block, gen->block_dim);
1918 priv = tiling;
1920 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
1921 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1922 gen->n_block, "t");
1924 priv = isl_map_align_params(priv, isl_set_get_space(par));
1925 priv = isl_map_intersect_range(priv, par);
1927 dim = isl_map_get_space(priv);
1928 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
1929 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
1930 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
1931 gen->shared_len);
1933 priv = isl_map_apply_range(priv, proj);
1935 return priv;
1938 /* Construct a map from domain_dim to domain_dim that increments
1939 * the dimension at position "pos" and leaves all other dimensions
1940 * constant.
1942 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
1944 int i;
1945 int len = isl_space_dim(domain_dim, isl_dim_set);
1946 isl_space *dim;
1947 isl_basic_map *next;
1948 isl_local_space *ls;
1950 dim = isl_space_map_from_set(domain_dim);
1951 next = isl_basic_map_universe(isl_space_copy(dim));
1952 ls = isl_local_space_from_space(dim);
1954 for (i = 0; i < len; ++i) {
1955 isl_constraint *c;
1957 c = isl_equality_alloc(isl_local_space_copy(ls));
1958 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
1959 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1960 if (i == pos)
1961 c = isl_constraint_set_constant_si(c, 1);
1962 next = isl_basic_map_add_constraint(next, c);
1965 isl_local_space_free(ls);
1967 return isl_map_from_basic_map(next);
1970 /* Check if the given access is coalesced.
1971 * That is, check whether incrementing the dimension that will get
1972 * wrapped over the last thread index results in incrementing
1973 * the last array index.
1975 * This function is only called for access relations without reuse.
1977 static int access_is_coalesced(struct gpu_gen *gen,
1978 __isl_keep isl_union_map *access)
1980 isl_space *dim;
1981 isl_map *access_map;
1982 isl_map *next_thread_x;
1983 isl_map *next_element;
1984 isl_map *map;
1985 int coalesced;
1987 access = isl_union_map_copy(access);
1988 access = isl_union_map_apply_domain(access,
1989 isl_union_map_copy(gen->tiled_sched));
1990 access_map = isl_map_from_union_map(access);
1992 dim = isl_map_get_space(access_map);
1993 dim = isl_space_domain(dim);
1994 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
1996 dim = isl_map_get_space(access_map);
1997 dim = isl_space_range(dim);
1998 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2000 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2001 map = isl_map_apply_range(map, access_map);
2003 coalesced = isl_map_is_subset(map, next_element);
2005 isl_map_free(next_element);
2006 isl_map_free(map);
2008 return coalesced;
2011 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2012 * dimensions of the computed schedule, check if it is bijective for
2013 * fixed values of the first gen->shared_len dimensions.
2014 * We perform this check by equating these dimensions to parameters.
2016 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2018 int res;
2019 isl_set *par;
2020 isl_space *space;
2022 access = isl_map_copy(access);
2023 space = isl_space_params(isl_map_get_space(access));
2024 par = parametrization(space, gen->shared_len + gen->n_block,
2025 0, gen->shared_len, "s");
2026 access = isl_map_intersect_domain(access, par);
2027 res = isl_map_is_bijective(access);
2028 isl_map_free(access);
2030 return res;
2033 /* Look for the last shared tile loop that affects the offset of "tile"
2034 * and return the result.
2035 * If there is no such loop, then return the index of the loop
2036 * before the first shared tile loop, in particular gen->tile_first - 1.
2038 static int compute_tile_last_shared(struct gpu_gen *gen,
2039 struct gpu_array_tile *tile)
2041 int i, j;
2043 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2044 for (i = 0; i < tile->n; ++i) {
2045 isl_aff *lb;
2046 isl_aff *shift;
2048 lb = tile->bound[i].lb;
2049 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2050 break;
2052 shift = tile->bound[i].shift;
2053 if (!shift)
2054 continue;
2055 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2056 break;
2058 if (i < tile->n)
2059 break;
2062 return j;
2065 /* Look for the last shared tile loop that affects the offset of the
2066 * shared or private tile and store the result in group->last_shared.
2067 * If there is no such loop, then group->last_shared is set to a value
2068 * before the first shared tile loop, in particular gen->tile_first - 1.
2069 * If there is no tile defined on the array reference group,
2070 * then set group->last_shared to gen->shared_len - 1.
2072 static void set_last_shared(struct gpu_gen *gen,
2073 struct gpu_array_ref_group *group)
2075 struct gpu_array_tile *tile;
2077 group->last_shared = gen->shared_len - 1;
2079 tile = group->private_tile;
2080 if (!tile)
2081 tile = group->shared_tile;
2082 if (!tile)
2083 return;
2085 group->last_shared = compute_tile_last_shared(gen, tile);
2088 /* Compute a privatized copy of all access relations from reference groups that
2089 * are mapped to private memory and store the result in gen->privatization.
2091 static void compute_private_access(struct gpu_gen *gen)
2093 int i, j;
2094 isl_union_map *private;
2096 if (!gen->options->use_private_memory)
2097 return;
2099 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2101 for (i = 0; i < gen->prog->n_array; ++i) {
2102 struct gpu_array_info *array = &gen->prog->array[i];
2104 if (gpu_array_is_read_only_scalar(array))
2105 continue;
2107 for (j = 0; j < array->n_group; ++j) {
2108 if (!array->groups[j]->private_tile)
2109 continue;
2111 private = isl_union_map_union(private,
2112 group_access_relation(array->groups[j], 1, 1));
2116 if (isl_union_map_is_empty(private))
2117 isl_union_map_free(private);
2118 else {
2119 isl_union_map *priv;
2121 private = isl_union_map_apply_domain(private,
2122 isl_union_map_copy(gen->shared_sched));
2123 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2124 private = isl_union_map_apply_domain(private, priv);
2125 gen->private_access = private;
2129 /* Compute the size of the tile specified by "tile"
2130 * in number of elements and return the result.
2132 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2134 int i;
2135 isl_val *size;
2137 size = isl_val_one(ctx);
2139 for (i = 0; i < tile->n; ++i)
2140 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2142 return size;
2145 /* If max_shared_memory is not set to infinity (-1), then make
2146 * sure that the total amount of shared memory required by the
2147 * array reference groups mapped to shared memory is no larger
2148 * than this maximum.
2150 * We apply a greedy approach and discard (keep in global memory)
2151 * those groups that would result in a total memory size that
2152 * is larger than the maximum.
2154 static void check_shared_memory_bound(struct gpu_gen *gen)
2156 int i, j;
2157 isl_val *left, *size;
2159 if (gen->options->max_shared_memory < 0)
2160 return;
2162 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2164 for (i = 0; i < gen->prog->n_array; ++i) {
2165 struct gpu_array_info *array = &gen->prog->array[i];
2167 for (j = 0; j < array->n_group; ++j) {
2168 struct gpu_array_ref_group *group;
2170 group = array->groups[j];
2171 if (group->private_tile)
2172 continue;
2173 if (!group->shared_tile)
2174 continue;
2176 size = tile_size(gen->ctx, group->shared_tile);
2177 size = isl_val_mul_ui(size, array->size);
2179 if (isl_val_le(size, left)) {
2180 left = isl_val_sub(left, size);
2181 continue;
2183 isl_val_free(size);
2185 group->shared_tile = free_tile(group->shared_tile);
2189 isl_val_free(left);
2192 /* Given a description of an array tile "tile" and the "space"
2194 * { D -> A }
2196 * where D represents the first shared_len schedule dimensions
2197 * and A represents the array, construct an isl_multi_aff
2199 * { [D[i] -> A[a]] -> A'[a'] }
2201 * with A' a scaled down copy of A according to the shifts and strides
2202 * in "tile". In particular,
2204 * a' = (a + shift(i))/stride
2206 * "insert_array" represents
2208 * { [D -> A] -> D }
2210 * and is used to insert A into the domain of functions that only
2211 * reference D.
2213 static __isl_give isl_multi_aff *strided_tile(
2214 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2215 __isl_keep isl_multi_aff *insert_array)
2217 int i;
2218 isl_ctx *ctx;
2219 isl_multi_aff *shift;
2220 isl_multi_val *stride;
2221 isl_space *space2;
2222 isl_local_space *ls;
2223 isl_multi_aff *tiling;
2225 ctx = isl_space_get_ctx(space);
2226 space2 = isl_space_domain(isl_space_copy(space));
2227 ls = isl_local_space_from_space(space2);
2228 space2 = isl_space_range(isl_space_copy(space));
2229 stride = isl_multi_val_zero(space2);
2230 shift = isl_multi_aff_zero(isl_space_copy(space));
2232 for (i = 0; i < tile->n; ++i) {
2233 struct gpu_array_bound *bound = &tile->bound[i];
2234 isl_val *stride_i;
2235 isl_aff *shift_i;
2237 if (tile->bound[i].shift) {
2238 stride_i = isl_val_copy(bound->stride);
2239 shift_i = isl_aff_copy(bound->shift);
2240 } else {
2241 stride_i = isl_val_one(ctx);
2242 shift_i = isl_aff_zero_on_domain(
2243 isl_local_space_copy(ls));
2246 stride = isl_multi_val_set_val(stride, i, stride_i);
2247 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2249 isl_local_space_free(ls);
2251 shift = isl_multi_aff_pullback_multi_aff(shift,
2252 isl_multi_aff_copy(insert_array));
2254 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2255 tiling = isl_multi_aff_add(tiling, shift);
2256 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2258 return tiling;
2261 /* Compute a tiling for the array reference group "group".
2263 * The tiling is of the form
2265 * { [D[i] -> A[a]] -> T[t] }
2267 * where D represents the first shared_len schedule dimensions,
2268 * A represents the global array and T represents the shared or
2269 * private memory tile. The name of T is the name of the local
2270 * array.
2272 * If there is any stride in the accesses, then the mapping is
2274 * t = (a + shift(i))/stride - lb(i)
2276 * otherwise, it is simply
2278 * t = a - lb(i)
2280 static void compute_group_tiling(struct gpu_array_ref_group *group)
2282 int i;
2283 struct gpu_array_tile *tile;
2284 struct gpu_array_info *array = group->array;
2285 isl_space *space;
2286 isl_multi_aff *tiling, *lb, *insert_array;
2287 isl_printer *p;
2288 char *local_name;
2290 tile = group->private_tile;
2291 if (!tile)
2292 tile = group->shared_tile;
2293 if (!tile)
2294 return;
2296 space = isl_map_get_space(group->access);
2297 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2299 for (i = 0; i < tile->n; ++i)
2300 if (tile->bound[i].shift)
2301 break;
2303 if (i < tile->n)
2304 tiling = strided_tile(tile, space, insert_array);
2305 else
2306 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2308 lb = isl_multi_aff_zero(space);
2309 for (i = 0; i < tile->n; ++i) {
2310 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2311 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2313 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2315 tiling = isl_multi_aff_sub(tiling, lb);
2317 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2318 p = print_array_name(p, group);
2319 local_name = isl_printer_get_str(p);
2320 isl_printer_free(p);
2321 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2322 free(local_name);
2324 tile->tiling = tiling;
2327 /* Compute a tiling for all the array reference groups.
2329 static void compute_group_tilings(struct gpu_gen *gen)
2331 int i, j;
2333 for (i = 0; i < gen->prog->n_array; ++i) {
2334 struct gpu_array_info *array = &gen->prog->array[i];
2336 for (j = 0; j < array->n_group; ++j)
2337 compute_group_tiling(array->groups[j]);
2341 /* Fill up the groups array with singleton groups, i.e., one group
2342 * per reference, initializing the array, access, write, n_ref and refs fields.
2343 * In particular the access field is initialized to the scheduled
2344 * access relation of the array reference.
2346 * Return the number of elements initialized, i.e., the number of
2347 * active references in the current kernel.
2349 static int populate_array_references(struct gpu_array_info *array,
2350 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2352 int i;
2353 int n;
2354 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2356 n = 0;
2357 for (i = 0; i < array->n_ref; ++i) {
2358 isl_union_map *umap;
2359 isl_map *map;
2360 struct gpu_array_ref_group *group;
2361 struct gpu_stmt_access *access = array->refs[i];
2363 map = isl_map_copy(access->access);
2364 umap = isl_union_map_from_map(map);
2365 umap = isl_union_map_apply_domain(umap,
2366 isl_union_map_copy(sched));
2368 if (isl_union_map_is_empty(umap)) {
2369 isl_union_map_free(umap);
2370 continue;
2373 map = isl_map_from_union_map(umap);
2374 map = isl_map_detect_equalities(map);
2376 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2377 assert(group);
2378 group->array = array;
2379 group->access = map;
2380 group->write = access->write;
2381 group->refs = &array->refs[i];
2382 group->n_ref = 1;
2384 groups[n++] = group;
2387 return n;
2390 /* If group->n_ref == 1, then group->refs was set by
2391 * populate_array_references to point directly into
2392 * group->array->refs and should not be freed.
2393 * If group->n_ref > 1, then group->refs was set by join_groups
2394 * to point to a newly allocated array.
2396 static void free_array_ref_group(struct gpu_array_ref_group *group)
2398 if (!group)
2399 return;
2400 free_tile(group->shared_tile);
2401 free_tile(group->private_tile);
2402 isl_map_free(group->access);
2403 if (group->n_ref > 1)
2404 free(group->refs);
2405 free(group);
2408 /* Given a map where the input dimensions represent the tile loops,
2409 * eliminate the innermost of those that have a fixed value
2410 * until we reach one that does not (obviously) have a fixed value.
2412 static __isl_give isl_map *eliminate_fixed_inner_loops(
2413 __isl_take isl_map *access)
2415 int i, n;
2417 n = isl_map_dim(access, isl_dim_in);
2419 for (i = n - 1; i >= 0; --i) {
2420 if (!map_plain_is_fixed(access, isl_dim_in, i))
2421 break;
2422 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2424 return access;
2427 /* Check if the access relations of group1 and group2 overlap within
2428 * the innermost loop. In particular, ignore any inner dimension
2429 * with a fixed value.
2430 * The copying to and from shared memory will be performed within
2431 * the innermost actual loop so we are only allowed to consider
2432 * the dimensions up to that innermost loop while checking whether
2433 * two access relations overlap.
2435 static int accesses_overlap(struct gpu_array_ref_group *group1,
2436 struct gpu_array_ref_group *group2)
2438 int empty;
2439 isl_map *access1, *access2;
2441 access1 = isl_map_copy(group1->access);
2442 access1 = eliminate_fixed_inner_loops(access1);
2443 access2 = isl_map_copy(group2->access);
2444 access2 = eliminate_fixed_inner_loops(access2);
2445 access1 = isl_map_intersect(access1, access2);
2446 empty = isl_map_is_empty(access1);
2447 isl_map_free(access1);
2449 return !empty;
2452 /* Combine the given two groups into a single group, containing
2453 * the references of both groups.
2455 static struct gpu_array_ref_group *join_groups(
2456 struct gpu_array_ref_group *group1,
2457 struct gpu_array_ref_group *group2)
2459 int i;
2460 isl_ctx *ctx;
2461 struct gpu_array_ref_group *group;
2463 ctx = isl_map_get_ctx(group1->access);
2464 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2465 assert(group);
2466 group->array = group1->array;
2467 group->access = isl_map_union(isl_map_copy(group1->access),
2468 isl_map_copy(group2->access));
2469 group->write = group1->write || group2->write;
2470 group->n_ref = group1->n_ref + group2->n_ref;
2471 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2472 group->n_ref);
2473 assert(group->refs);
2474 for (i = 0; i < group1->n_ref; ++i)
2475 group->refs[i] = group1->refs[i];
2476 for (i = 0; i < group2->n_ref; ++i)
2477 group->refs[group1->n_ref + i] = group2->refs[i];
2479 return group;
2482 /* Combine the given two groups into a single group and free
2483 * the original two groups.
2485 static struct gpu_array_ref_group *join_groups_and_free(
2486 struct gpu_array_ref_group *group1,
2487 struct gpu_array_ref_group *group2)
2489 struct gpu_array_ref_group *group;
2491 group = join_groups(group1, group2);
2492 free_array_ref_group(group1);
2493 free_array_ref_group(group2);
2494 return group;
2497 /* Compute the private and/or shared memory tiles for the array
2498 * reference group "group" of array "array".
2500 * If the array is a read-only scalar or if the user requested
2501 * not to use shared or private memory, then we do not need to do anything.
2503 * We only try to compute a shared memory tile if there is any reuse
2504 * or if the access is not coalesced.
2506 * For computing a private memory tile, we also require that there is
2507 * some reuse. Moreover, we require that the access is private
2508 * to the thread. That is, we check that any given array element
2509 * is only accessed by a single thread.
2510 * We compute an access relation that maps the shared tile loop iterators
2511 * and the shared point loop iterators that will be wrapped over the
2512 * threads to the array elements.
2513 * We actually check that those iterators that will be wrapped
2514 * partition the array space. This check is stricter than necessary
2515 * since several iterations may be mapped onto the same thread
2516 * and then they could be allowed to access the same memory elements,
2517 * but our check does not allow this situation.
2519 * We also check that the index expression only depends on parallel
2520 * loops. That way, we can move those loops innermost and unroll them.
2521 * Again, we use a test that is stricter than necessary.
2522 * We actually check whether the index expression only depends
2523 * on the iterators that are wrapped over the threads.
2524 * These are necessarily parallel, but there may be more parallel loops.
2526 * Combining the injectivity of the first test with the single-valuedness
2527 * of the second test, we simply test for bijectivity.
2529 * If it turns out we can use registers, we compute the private memory
2530 * tile size using can_tile, after introducing a dependence
2531 * on the thread indices.
2533 static void compute_group_bounds_core(struct gpu_gen *gen,
2534 struct gpu_array_ref_group *group)
2536 isl_ctx *ctx = isl_space_get_ctx(group->array->space);
2537 isl_union_map *access;
2538 int n_index = group->array->n_index;
2539 int no_reuse;
2540 isl_map *acc;
2541 int use_shared = gen->options->use_shared_memory;
2542 int use_private = gen->options->use_private_memory;
2544 if (!use_shared && !use_private)
2545 return;
2546 if (gpu_array_is_read_only_scalar(group->array))
2547 return;
2549 access = group_access_relation(group, 1, 1);
2550 no_reuse = isl_union_map_is_injective(access);
2552 if (use_shared && (!no_reuse || !access_is_coalesced(gen, access))) {
2553 group->shared_tile = create_tile(ctx, group->array->n_index);
2554 if (!can_tile(group->access, group->shared_tile))
2555 group->shared_tile = free_tile(group->shared_tile);
2558 if (!use_private || no_reuse) {
2559 isl_union_map_free(access);
2560 return;
2563 access = isl_union_map_apply_domain(access,
2564 isl_union_map_copy(gen->shared_sched));
2566 acc = isl_map_from_union_map(access);
2568 if (!access_is_bijective(gen, acc)) {
2569 isl_map_free(acc);
2570 return;
2573 group->private_tile = create_tile(gen->ctx, n_index);
2574 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2575 if (!can_tile(acc, group->private_tile))
2576 group->private_tile = free_tile(group->private_tile);
2578 isl_map_free(acc);
2581 /* Compute the private and/or shared memory tiles for the array
2582 * reference group "group" of array "array" and set last_shared.
2584 static void compute_group_bounds(struct gpu_gen *gen,
2585 struct gpu_array_ref_group *group)
2587 compute_group_bounds_core(gen, group);
2588 set_last_shared(gen, group);
2591 /* If two groups have overlapping access relations (as determined by
2592 * the "overlap" function) and if one of them involves a write,
2593 * then merge the two groups into one.
2594 * If "compute_bounds" is set, then call compute_group_bounds
2595 * on the merged groups.
2597 * Return the updated number of groups.
2599 static int group_writes(struct gpu_gen *gen,
2600 int n, struct gpu_array_ref_group **groups,
2601 int (*overlap)(struct gpu_array_ref_group *group1,
2602 struct gpu_array_ref_group *group2), int compute_bounds)
2604 int i, j;
2606 for (i = 0; i < n; ++i) {
2607 for (j = n - 1; j > i; --j) {
2608 if (!groups[i]->write && !groups[j]->write)
2609 continue;
2611 if (!overlap(groups[i], groups[j]))
2612 continue;
2614 groups[i] = join_groups_and_free(groups[i], groups[j]);
2615 if (compute_bounds)
2616 compute_group_bounds(gen, groups[i]);
2617 if (j != n - 1)
2618 groups[j] = groups[n - 1];
2619 n--;
2623 return n;
2626 /* If two groups have overlapping access relations (within the innermost
2627 * loop) and if one of them involves a write, then merge the two groups
2628 * into one.
2630 * Return the updated number of groups.
2632 static int group_overlapping_writes(struct gpu_gen *gen,
2633 int n, struct gpu_array_ref_group **groups)
2635 return group_writes(gen, n, groups, &accesses_overlap, 0);
2638 /* Check if the access relations of group1 and group2 overlap within
2639 * the outermost min(group1->last_shared, group2->last_shared) loops.
2641 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2642 struct gpu_array_ref_group *group2)
2644 int last_shared;
2645 int dim;
2646 int empty;
2647 isl_map *map_i, *map_j, *map;
2649 last_shared = group1->last_shared;
2650 if (group2->last_shared < last_shared)
2651 last_shared = group2->last_shared;
2652 map_i = isl_map_copy(group1->access);
2653 dim = isl_map_dim(map_i, isl_dim_in);
2654 map_i = isl_map_eliminate(map_i, isl_dim_in,
2655 last_shared + 1, dim - (last_shared + 1));
2656 map_j = isl_map_copy(group2->access);
2657 map_j = isl_map_eliminate(map_j, isl_dim_in,
2658 last_shared + 1, dim - (last_shared + 1));
2659 map = isl_map_intersect(map_i, map_j);
2660 empty = isl_map_is_empty(map);
2661 isl_map_free(map);
2663 return !empty;
2666 /* If two groups have overlapping access relations (within the outer
2667 * last_shared loops) and if one of them involves a write,
2668 * then merge the two groups into one.
2670 * Return the updated number of groups.
2672 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2673 struct gpu_array_ref_group **groups)
2675 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2678 /* Is the size of the tile specified by "tile" smaller than the sum of
2679 * the sizes of the tiles specified by "tile1" and "tile2"?
2681 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
2682 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2684 int smaller;
2685 isl_val *size, *size1, *size2;
2687 size = tile_size(ctx, tile);
2688 size1 = tile_size(ctx, tile1);
2689 size2 = tile_size(ctx, tile2);
2691 size = isl_val_sub(size, size1);
2692 size = isl_val_sub(size, size2);
2693 smaller = isl_val_is_neg(size);
2695 isl_val_free(size);
2697 return smaller;
2700 /* Given an initial grouping of array references and shared memory tiles
2701 * for each group that allows for a shared memory tile, merge two groups
2702 * if both have a shared memory tile, the merged group also has
2703 * a shared memory tile and the size of the tile for the merge group
2704 * is smaller than the sum of the tile sizes of the individual groups.
2706 * If merging two groups decreases the "last_shared" dimension of
2707 * one or both of the two groups, then we need to check for overlapping
2708 * writes again.
2710 * Return the number of groups after merging.
2712 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2713 struct gpu_array_info *array, int n,
2714 struct gpu_array_ref_group **groups)
2716 int i, j;
2717 int recompute_overlap = 0;
2718 isl_ctx *ctx = isl_space_get_ctx(array->space);
2720 for (i = 0; i < n; ++i) {
2721 if (!groups[i]->shared_tile)
2722 continue;
2723 for (j = n - 1; j > i; --j) {
2724 isl_map *map;
2725 int empty;
2726 struct gpu_array_ref_group *group;
2728 if (!groups[j]->shared_tile)
2729 continue;
2731 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2732 isl_map_copy(groups[j]->access));
2733 empty = isl_map_is_empty(map);
2734 isl_map_free(map);
2736 if (empty)
2737 continue;
2739 group = join_groups(groups[i], groups[j]);
2740 compute_group_bounds(gen, group);
2741 if (!group->shared_tile ||
2742 !smaller_tile(ctx, group->shared_tile,
2743 groups[i]->shared_tile,
2744 groups[j]->shared_tile)) {
2745 free_array_ref_group(group);
2746 continue;
2749 if (group->last_shared < groups[i]->last_shared ||
2750 group->last_shared < groups[j]->last_shared)
2751 recompute_overlap = 1;
2752 free_array_ref_group(groups[i]);
2753 free_array_ref_group(groups[j]);
2754 groups[i] = group;
2755 if (j != n - 1)
2756 groups[j] = groups[n - 1];
2757 n--;
2761 if (recompute_overlap)
2762 n = group_last_shared_overlapping_writes(gen, n, groups);
2763 return n;
2766 /* Set array->n_group and array->groups to n and groups.
2768 * Additionally, set the "nr" field of each group
2769 * and the "group" field of each reference in each group.
2771 static void set_array_groups(struct gpu_array_info *array,
2772 int n, struct gpu_array_ref_group **groups)
2774 int i, j;
2776 array->n_group = n;
2777 array->groups = groups;
2779 for (i = 0; i < n; ++i) {
2780 groups[i]->nr = i;
2782 for (j = 0; j < groups[i]->n_ref; ++j)
2783 groups[i]->refs[j]->group = i;
2787 /* Group array references that should be considered together when
2788 * deciding whether to access them from private, shared or global memory.
2790 * In particular, if two array references overlap and if one of them
2791 * is a write, then the two references are grouped together.
2792 * We first perform an initial grouping based only on the access relation.
2793 * After computing shared and private memory tiles, we check for
2794 * overlapping writes again, but this time taking into account
2795 * the "last_shared" property.
2797 * Furthermore, if two groups admit a shared memory tile and if the
2798 * combination of the two also admits a shared memory tile, we merge
2799 * the two groups.
2801 static void group_array_references(struct gpu_gen *gen,
2802 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
2804 int i;
2805 int n;
2806 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2807 struct gpu_array_ref_group **groups;
2809 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
2810 array->n_ref);
2811 assert(groups);
2813 n = populate_array_references(array, sched, groups);
2815 n = group_overlapping_writes(gen, n, groups);
2817 for (i = 0; i < n; ++i)
2818 compute_group_bounds(gen, groups[i]);
2820 n = group_last_shared_overlapping_writes(gen, n, groups);
2822 n = group_common_shared_memory_tile(gen, array, n, groups);
2824 set_array_groups(array, n, groups);
2827 /* Take tiled_sched, project it onto the shared tile loops and
2828 * the loops that will be wrapped over the threads and
2829 * store the result in gen->shared_sched.
2830 * Also compute a projection that projects out the loops that will be
2831 * wrapped over the threads and store this projection in gen->shared_proj.
2833 static void compute_shared_sched(struct gpu_gen *gen)
2835 isl_space *dim;
2836 isl_map *proj;
2837 isl_set *par;
2838 isl_union_map *sched;
2840 sched = isl_union_map_copy(gen->tiled_sched);
2842 dim = isl_union_map_get_space(sched);
2843 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
2844 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
2846 dim = isl_union_map_get_space(sched);
2847 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
2849 gen->shared_sched = sched;
2850 gen->shared_proj = isl_union_map_from_map(proj);
2853 /* Group references of all arrays in the program.
2855 static void group_references(struct gpu_gen *gen)
2857 int i;
2858 isl_union_map *sched;
2860 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2861 isl_union_map_copy(gen->shared_proj));
2863 for (i = 0; i < gen->prog->n_array; ++i)
2864 group_array_references(gen, &gen->prog->array[i], sched);
2866 isl_union_map_free(sched);
2869 /* Free all array information that is local to the current kernel.
2871 static void free_local_array_info(struct gpu_gen *gen)
2873 int i, j;
2875 for (i = 0; i < gen->prog->n_array; ++i) {
2876 struct gpu_array_info *array = &gen->prog->array[i];
2878 for (j = 0; j < array->n_group; ++j)
2879 free_array_ref_group(array->groups[j]);
2880 free(array->groups);
2884 /* Compute the size of a bounding box around the origin and "set",
2885 * where "set" is assumed to contain only non-negative elements.
2886 * In particular, compute the maximal value of "set" in each direction
2887 * and add one.
2889 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
2890 __isl_keep isl_set *context)
2892 int i, n;
2893 isl_multi_pw_aff *mpa;
2895 n = isl_set_dim(set, isl_dim_set);
2896 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
2897 for (i = 0; i < n; ++i) {
2898 isl_space *space;
2899 isl_aff *one;
2900 isl_pw_aff *bound;
2902 bound = isl_set_dim_max(isl_set_copy(set), i);
2903 bound = isl_pw_aff_coalesce(bound);
2904 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
2906 space = isl_pw_aff_get_domain_space(bound);
2907 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2908 one = isl_aff_add_constant_si(one, 1);
2909 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
2910 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
2912 isl_set_free(set);
2914 return mpa;
2917 /* Compute the effective grid size as a list of the sizes in each dimension.
2919 * The grid size specified by the user or set by default
2920 * in read_grid_sizes() and applied in tile_schedule(),
2921 * may be too large for the given code in the sense that
2922 * it may contain blocks that don't need to execute anything.
2923 * We therefore don't return this grid size, but instead the
2924 * smallest grid size that ensures that all blocks that actually
2925 * execute code are included in the grid.
2927 * We first extract a description of the grid, i.e., the possible values
2928 * of the block ids, from gen->tiled_sched.
2929 * The block ids are parameters in gen->tiled_sched.
2930 * We simply need to change them into set dimensions.
2932 * Then, for each block dimension, we compute the maximal value of the block id
2933 * and add one.
2935 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
2936 struct ppcg_kernel *kernel)
2938 int i;
2939 isl_set *grid;
2941 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
2942 grid = isl_set_from_params(grid);
2943 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
2944 for (i = 0; i < gen->n_grid; ++i) {
2945 int pos;
2946 char name[20];
2948 snprintf(name, sizeof(name), "b%d", i);
2949 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
2950 assert(pos >= 0);
2951 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
2952 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
2955 return extract_size(grid, kernel->context);
2958 /* Compute the size of a fixed bounding box around the origin and "set",
2959 * where "set" is assumed to contain only non-negative elements,
2960 * and store the results in "size".
2961 * In particular, compute the maximal value of "set" in each direction
2962 * and add one.
2964 static void extract_fixed_size(__isl_take isl_set *set, int *size)
2966 int i, n;
2967 isl_local_space *ls;
2968 isl_aff *obj;
2970 n = isl_set_dim(set, isl_dim_set);
2971 ls = isl_local_space_from_space(isl_set_get_space(set));
2972 obj = isl_aff_zero_on_domain(ls);
2973 for (i = 0; i < n; ++i) {
2974 isl_val *max;
2976 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
2977 max = isl_set_max_val(set, obj);
2978 size[i] = isl_val_get_num_si(max) + 1;
2979 isl_val_free(max);
2980 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
2982 isl_aff_free(obj);
2983 isl_set_free(set);
2986 /* Compute the effective block size as a list of the sizes in each dimension
2987 * and store the sizes in kernel->block_dim.
2989 * The block size specified by the user or set by default
2990 * in read_block_sizes() and applied in thread_tile_schedule(),
2991 * may be too large for the given code in the sense that
2992 * it may contain threads that don't need to execute anything.
2993 * We therefore don't store this block size in kernel->block_dim,
2994 * but instead the smallest block size that ensures that all threads
2995 * that actually execute code are included in the block.
2997 * The current implementation eliminates all parameters, ensuring
2998 * that the size is a fixed constant in each dimension.
2999 * In principle we could also compute parametric sizes.
3000 * We would have to make sure to project out all b%d and t%d parameters,
3001 * however.
3003 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3005 int i;
3006 int nparam;
3007 isl_set *block;
3008 isl_multi_pw_aff *mpa;
3010 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3011 block = isl_set_from_params(block);
3012 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3013 kernel->n_block = gen->n_block;
3014 for (i = 0; i < gen->n_block; ++i) {
3015 int pos;
3016 char name[20];
3018 snprintf(name, sizeof(name), "t%d", i);
3019 pos = isl_set_find_dim_by_name(block, isl_dim_param, name);
3020 assert(pos >= 0);
3021 block = isl_set_equate(block, isl_dim_param, pos,
3022 isl_dim_set, i);
3024 nparam = isl_set_dim(block, isl_dim_param);
3025 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3027 extract_fixed_size(block, kernel->block_dim);
3030 void ppcg_kernel_free(void *user)
3032 struct ppcg_kernel *kernel = user;
3033 int i;
3035 if (!kernel)
3036 return;
3038 isl_multi_pw_aff_free(kernel->grid_size);
3039 isl_set_free(kernel->context);
3040 isl_union_set_free(kernel->arrays);
3041 isl_space_free(kernel->space);
3042 isl_ast_node_free(kernel->tree);
3044 for (i = 0; i < kernel->n_array; ++i)
3045 isl_pw_aff_list_free(kernel->array[i].bound);
3046 free(kernel->array);
3048 for (i = 0; i < kernel->n_var; ++i) {
3049 free(kernel->var[i].name);
3050 isl_vec_free(kernel->var[i].size);
3052 free(kernel->var);
3054 free(kernel);
3057 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3058 struct ppcg_kernel_var *var)
3060 int j;
3061 struct gpu_array_tile *tile;
3062 isl_printer *p;
3063 char *name;
3065 var->array = group->array;
3067 tile = group->private_tile;
3068 var->type = ppcg_access_private;
3069 if (!tile) {
3070 tile = group->shared_tile;
3071 var->type = ppcg_access_shared;
3074 p = isl_printer_to_str(ctx);
3075 p = print_array_name(p, group);
3076 var->name = isl_printer_get_str(p);
3077 isl_printer_free(p);
3079 var->size = isl_vec_alloc(ctx, group->array->n_index);
3081 for (j = 0; j < group->array->n_index; ++j)
3082 var->size = isl_vec_set_element_val(var->size, j,
3083 isl_val_copy(tile->bound[j].size));
3086 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3088 int i, j, n;
3090 n = 0;
3091 for (i = 0; i < gen->prog->n_array; ++i) {
3092 struct gpu_array_info *array = &gen->prog->array[i];
3094 for (j = 0; j < array->n_group; ++j) {
3095 struct gpu_array_ref_group *group = array->groups[j];
3096 if (group->private_tile || group->shared_tile)
3097 ++n;
3101 kernel->n_var = n;
3102 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3103 assert(kernel->var);
3105 n = 0;
3106 for (i = 0; i < gen->prog->n_array; ++i) {
3107 struct gpu_array_info *array = &gen->prog->array[i];
3109 for (j = 0; j < array->n_group; ++j) {
3110 struct gpu_array_ref_group *group = array->groups[j];
3111 if (!group->private_tile && !group->shared_tile)
3112 continue;
3113 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3114 ++n;
3119 /* The sizes of the arrays on the host that have been computed by
3120 * extract_array_info may depend on the parameters. Use the extra
3121 * constraints on the parameters that are valid at "host_domain"
3122 * to simplify these expressions and store the results in kernel->array.
3124 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3125 __isl_keep isl_set *host_domain)
3127 int i, j;
3128 isl_set *context;
3130 kernel->array = isl_calloc_array(gen->ctx,
3131 struct gpu_local_array_info, gen->prog->n_array);
3132 assert(kernel->array);
3133 kernel->n_array = gen->prog->n_array;
3135 context = isl_set_copy(host_domain);
3136 context = isl_set_params(context);
3138 for (i = 0; i < gen->prog->n_array; ++i) {
3139 struct gpu_array_info *array = &gen->prog->array[i];
3140 isl_pw_aff_list *local;
3142 if (array->n_group == 0)
3143 continue;
3145 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3147 for (j = 0; j < array->n_index; ++j) {
3148 isl_pw_aff *pwaff;
3150 pwaff = isl_pw_aff_copy(array->bound[j]);
3151 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3152 local = isl_pw_aff_list_add(local, pwaff);
3155 kernel->array[i].bound = local;
3157 isl_set_free(context);
3160 /* Find the element in gen->stmt that has the given "id".
3161 * Return NULL if no such gpu_stmt can be found.
3163 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3165 int i;
3167 for (i = 0; i < prog->n_stmts; ++i) {
3168 if (id == prog->stmts[i].id)
3169 break;
3172 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3175 /* Set gen->tile_len and gen->n_parallel to those of the statement
3176 * affected by the first map (part of the schedule)
3177 * on which this function is called.
3178 * Because of the way the schedule is constructed, the other statements
3179 * in the list, if any, should have the same values for these properties.
3181 static int extract_tile_len(__isl_take isl_map *map, void *user)
3183 struct gpu_gen *gen = (struct gpu_gen *) user;
3184 isl_id *id;
3185 struct gpu_stmt *stmt;
3187 id = isl_map_get_tuple_id(map, isl_dim_in);
3188 stmt = find_stmt(gen->prog, id);
3189 isl_id_free(id);
3191 isl_map_free(map);
3193 if (!stmt)
3194 isl_die(gen->ctx, isl_error_unknown,
3195 "statement not found", return -1);
3197 gen->tile_len = stmt->tile_len;
3198 gen->n_parallel = stmt->n_parallel;
3200 return -1;
3203 void ppcg_kernel_stmt_free(void *user)
3205 int i;
3206 struct ppcg_kernel_stmt *stmt = user;
3208 if (!stmt)
3209 return;
3211 switch (stmt->type) {
3212 case ppcg_kernel_copy:
3213 isl_ast_expr_free(stmt->u.c.index);
3214 isl_ast_expr_free(stmt->u.c.local_index);
3215 break;
3216 case ppcg_kernel_domain:
3217 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
3218 break;
3219 case ppcg_kernel_sync:
3220 break;
3223 free(stmt);
3226 /* Set the options of "context" to
3228 * { space -> [x] : x >= first }
3230 static __isl_give isl_ast_build *set_unroll(
3231 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3232 int first)
3234 isl_ctx *ctx;
3235 isl_map *unroll;
3236 isl_union_map *opt;
3238 ctx = isl_ast_build_get_ctx(build);
3240 space = isl_space_from_domain(space);
3241 space = isl_space_add_dims(space, isl_dim_out, 1);
3242 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3243 unroll = isl_map_universe(space);
3244 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3245 opt = isl_union_map_from_map(unroll);
3247 build = isl_ast_build_set_options(build, opt);
3249 return build;
3252 /* Return a list of isl_ids of the form "prefix%d".
3254 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3255 int n, const char *prefix)
3257 int i;
3258 char name[10];
3259 isl_id_list *names;
3261 names = isl_id_list_alloc(ctx, n);
3262 for (i = 0; i < n; ++i) {
3263 isl_id *id;
3265 snprintf(name, sizeof(name), "%s%d", prefix, i);
3266 id = isl_id_alloc(ctx, name, NULL);
3267 names = isl_id_list_add(names, id);
3270 return names;
3273 /* Extend the schedule "schedule" with the part of "extension"
3274 * starting at "first" up to "len".
3276 static __isl_give isl_union_map *extend_schedule(
3277 __isl_take isl_union_map *schedule,
3278 __isl_take isl_union_map *extension, int first, int len)
3280 isl_space *space;
3281 isl_map *proj;
3282 isl_union_map *umap;
3283 isl_set *set;
3285 space = isl_union_map_get_space(schedule);
3286 space = isl_space_set_from_params(space);
3287 space = isl_space_add_dims(space, isl_dim_set, len);
3288 proj = isl_set_identity(isl_set_universe(space));
3289 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3290 extension = isl_union_map_apply_range(extension,
3291 isl_union_map_from_map(proj));
3293 schedule = isl_union_map_range_product(schedule, extension);
3295 return schedule;
3298 /* Return the gpu_stmt_access in the list "accesses" that corresponds
3299 * to "ref_id".
3301 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
3302 __isl_keep isl_id *ref_id)
3304 struct gpu_stmt_access *access;
3306 for (access = accesses; access; access = access->next)
3307 if (access->ref_id == ref_id)
3308 return access;
3310 return NULL;
3313 /* Return the index of the array called "name" in the list of arrays.
3315 static int find_array_index(struct gpu_gen *gen, const char *name)
3317 int i;
3319 for (i = 0; i < gen->prog->n_array; ++i)
3320 if (!strcmp(name, gen->prog->array[i].name))
3321 return i;
3323 return -1;
3326 /* Internal data structure for the index and AST expression transformation
3327 * callbacks for pet_stmt_build_ast_exprs.
3329 * "accesses" is the list of gpu_stmt_access in the statement.
3330 * "iterator_map" expresses the statement iterators in terms of
3331 * the AST loop iterators.
3332 * "sched2shared" expresses the first shared_len dimensions of
3333 * the computed schedule in terms of the AST loop iterators.
3335 * The following fields are set in transform_index and used in transform_expr.
3336 * "array" is the array that is being accessed.
3337 * "global" is set if the global array is accessed (rather than
3338 * shared/private memory).
3339 * "local_array" refers to information on the array specialized
3340 * to the current kernel.
3342 struct ppcg_transform_data {
3343 struct gpu_gen *gen;
3344 struct gpu_stmt_access *accesses;
3345 isl_pw_multi_aff *iterator_map;
3346 isl_pw_multi_aff *sched2shared;
3348 struct gpu_array_info *array;
3349 int global;
3350 struct gpu_local_array_info *local_array;
3353 /* Index transformation callback for pet_stmt_build_ast_exprs.
3355 * "index" expresses the array indices in terms of statement iterators
3357 * We first reformulate "index" in terms of the AST loop iterators.
3358 * Then we check if we are accessing the global array or
3359 * a shared/private copy. In the former case, we simply return
3360 * the updated index. If "index" is an affine expression rather
3361 * than an array access, then we also return the updated index here.
3363 * Otherwise, we apply the tiling to the index.
3364 * This tiling is of the form
3366 * [D -> A] -> T
3368 * The index is of the form
3370 * L -> A
3372 * We update the tiling to refer to the AST loop iteratos
3374 * [L -> A] -> T
3376 * and modify index to keep track of those iterators
3378 * L -> [L -> A]
3380 * Combining these two yields a tiled index expression in terms
3381 * of the AST loop iterators
3383 * L -> T
3385 static __isl_give isl_multi_pw_aff *transform_index(
3386 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
3387 void *user)
3389 struct ppcg_transform_data *data = user;
3390 struct gpu_stmt_access *access;
3391 struct gpu_array_ref_group *group;
3392 struct gpu_array_tile *tile;
3393 isl_pw_multi_aff *iterator_map;
3394 int i;
3395 const char *name;
3396 isl_space *space;
3397 isl_multi_pw_aff *tiling;
3398 isl_pw_multi_aff *pma;
3399 isl_multi_pw_aff *mpa;
3401 data->array = NULL;
3403 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
3404 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
3406 access = find_access(data->accesses, ref_id);
3407 if (!access)
3408 return index;
3409 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
3410 return index;
3412 name = isl_map_get_tuple_name(access->access, isl_dim_out);
3413 i = find_array_index(data->gen, name);
3414 if (i < 0)
3415 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
3416 "cannot find array reference group",
3417 return isl_multi_pw_aff_free(index));
3419 data->array = &data->gen->prog->array[i];
3420 data->local_array = &data->gen->kernel->array[i];
3421 group = data->array->groups[access->group];
3422 tile = group->private_tile;
3423 if (!tile)
3424 tile = group->shared_tile;
3425 data->global = !tile;
3426 if (!tile)
3427 return index;
3429 space = isl_space_range(isl_multi_pw_aff_get_space(index));
3430 space = isl_space_map_from_set(space);
3431 pma = isl_pw_multi_aff_identity(space);
3432 pma = isl_pw_multi_aff_product(
3433 isl_pw_multi_aff_copy(data->sched2shared), pma);
3434 tiling = isl_multi_pw_aff_from_multi_aff(
3435 isl_multi_aff_copy(tile->tiling));
3436 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
3438 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
3439 space = isl_space_map_from_set(space);
3440 mpa = isl_multi_pw_aff_identity(space);
3441 index = isl_multi_pw_aff_range_product(mpa, index);
3442 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
3444 return index;
3447 /* Dereference "expr" by adding an index [0].
3448 * The original "expr" is assumed not to have any indices.
3450 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
3452 isl_ctx *ctx;
3453 isl_ast_expr *res;
3454 isl_ast_expr_list *list;
3456 ctx = isl_ast_expr_get_ctx(expr);
3457 res = isl_ast_expr_from_val(isl_val_zero(ctx));
3458 list = isl_ast_expr_list_from_ast_expr(res);
3459 res = isl_ast_expr_get_op_arg(expr, 0);
3460 res = isl_ast_expr_access(res, list);
3461 isl_ast_expr_free(expr);
3463 return res;
3466 /* Linearize the index expression "expr" based on the array bounds
3467 * of "array".
3469 * That is, transform expression
3471 * A[i_0][i_1]...[i_n]
3473 * to
3475 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
3477 * where b_0, b_1, ..., b_n are the bounds on the array.
3479 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
3480 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
3482 int i, n;
3483 isl_ctx *ctx;
3484 isl_set *context;
3485 isl_ast_expr *res;
3486 isl_ast_expr_list *list;
3487 isl_ast_build *build;
3489 ctx = isl_ast_expr_get_ctx(expr);
3490 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
3491 build = isl_ast_build_from_context(context);
3493 n = isl_ast_expr_get_op_n_arg(expr);
3494 res = isl_ast_expr_get_op_arg(expr, 1);
3495 for (i = 2; i < n; ++i) {
3496 isl_pw_aff *bound_i;
3497 isl_ast_expr *expr_i;
3499 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i - 1);
3500 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
3501 res = isl_ast_expr_mul(res, expr_i);
3502 expr_i = isl_ast_expr_get_op_arg(expr, i);
3503 res = isl_ast_expr_add(res, expr_i);
3506 isl_ast_build_free(build);
3508 list = isl_ast_expr_list_from_ast_expr(res);
3509 res = isl_ast_expr_get_op_arg(expr, 0);
3510 res = isl_ast_expr_access(res, list);
3512 isl_ast_expr_free(expr);
3514 return res;
3517 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
3519 * If the AST expression refers to a global scalar that is not
3520 * a read-only scalar, then its address was passed to the kernel and
3521 * we need to dereference it.
3523 * If the AST expression refers to an access to a global array,
3524 * then we linearize the access exploiting the bounds in data->local_array.
3526 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
3527 __isl_keep isl_id *id, void *user)
3529 struct ppcg_transform_data *data = user;
3531 if (!data->array)
3532 return expr;
3533 if (gpu_array_is_read_only_scalar(data->array))
3534 return expr;
3535 if (!data->global)
3536 return expr;
3537 if (data->array->n_index == 0)
3538 return dereference(expr);
3539 if (!data->array->linearize)
3540 return expr;
3542 return gpu_local_array_info_linearize_index(data->local_array, expr);
3545 /* This function is called for each instance of a user statement
3546 * in the kernel.
3548 * We attach a struct ppcg_kernel_stmt to the "node", containing
3549 * a computed AST expression for each access.
3550 * These AST expressions are computed from iterator_map,
3551 * which expresses the domain
3552 * elements in terms of the generated loops, and sched2shared,
3553 * which expresses the first shared_len dimensions of the schedule
3554 * computed by PPCG in terms of the generated loops.
3556 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3557 __isl_keep isl_ast_build *build, void *user)
3559 struct ppcg_transform_data data;
3560 struct gpu_gen *gen = (struct gpu_gen *) user;
3561 struct ppcg_kernel_stmt *stmt;
3562 isl_id *id;
3563 isl_pw_multi_aff *sched2shared;
3564 isl_map *map;
3565 isl_pw_multi_aff *iterator_map;
3566 isl_ast_expr *expr, *arg;
3567 isl_union_map *schedule;
3568 int i, n;
3569 struct gpu_stmt_access *access;
3571 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3572 if (!stmt)
3573 return isl_ast_node_free(node);
3575 expr = isl_ast_node_user_get_expr(node);
3576 arg = isl_ast_expr_get_op_arg(expr, 0);
3577 id = isl_ast_expr_get_id(arg);
3579 schedule = isl_ast_build_get_schedule(build);
3580 map = isl_map_reverse(isl_map_from_union_map(schedule));
3581 iterator_map = isl_pw_multi_aff_from_map(map);
3582 sched2shared = compute_sched_to_shared(gen,
3583 isl_pw_multi_aff_copy(iterator_map));
3585 stmt->type = ppcg_kernel_domain;
3586 stmt->u.d.stmt = find_stmt(gen->prog, id);
3587 if (!stmt->u.d.stmt)
3588 goto error;
3590 data.gen = gen;
3591 data.accesses = stmt->u.d.stmt->accesses;
3592 data.iterator_map = iterator_map;
3593 data.sched2shared = sched2shared;
3594 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
3595 build, &transform_index, &data,
3596 &transform_expr, &data);
3598 isl_id_free(id);
3599 isl_pw_multi_aff_free(iterator_map);
3600 isl_pw_multi_aff_free(sched2shared);
3601 isl_ast_expr_free(arg);
3602 isl_ast_expr_free(expr);
3604 id = isl_id_alloc(gen->ctx, NULL, stmt);
3605 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3606 return isl_ast_node_set_annotation(node, id);
3607 error:
3608 isl_id_free(id);
3609 isl_pw_multi_aff_free(iterator_map);
3610 ppcg_kernel_stmt_free(stmt);
3611 isl_pw_multi_aff_free(sched2shared);
3612 return isl_ast_node_free(node);
3615 /* This function is called when code has been generated for the shared
3616 * tile loops. The "schedule" refers only to the original statements.
3618 * We extend the schedule with that part of gen->local_sched that hasn't
3619 * been taken into account yet. This introduces parameters referring
3620 * to thread ids in the schedule, so we add them (with the appropriate
3621 * bounds to the context as well).
3622 * Finally, we set the appropriate unrolling options
3623 * if gen->first_unroll is set.
3625 static __isl_give isl_ast_node *create_domain_leaf(
3626 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
3627 void *user)
3629 struct gpu_gen *gen = (struct gpu_gen *) user;
3630 isl_space *space;
3631 isl_union_map *sched;
3632 isl_ast_node *tree;
3633 isl_set *set;
3634 isl_id_list *iterators;
3635 int n;
3637 schedule = extend_schedule(schedule,
3638 isl_union_map_copy(gen->local_sched),
3639 gen->shared_len, gen->thread_tiled_len);
3641 space = isl_ast_build_get_schedule_space(build);
3642 set = isl_set_universe(space);
3643 set = add_bounded_parameters(set, gen->kernel->n_block,
3644 gen->kernel->block_dim, "t");
3645 build = isl_ast_build_restrict(build, set);
3647 n = gen->thread_tiled_len - gen->shared_len;
3649 if (gen->first_unroll >= 0) {
3650 space = isl_space_set_alloc(gen->ctx, 0, n);
3651 build = set_unroll(build, space, gen->first_unroll);
3653 iterators = generate_names(gen->ctx, n, "c");
3654 build = isl_ast_build_set_iterators(build, iterators);
3655 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
3656 tree = isl_ast_build_ast_from_schedule(build, schedule);
3657 isl_ast_build_free(build);
3659 return tree;
3662 /* This function is called for each statement node in the AST of the code
3663 * for copying to or from shared/private memory.
3664 * Attach a pointer to a ppcg_kernel_stmt representing the copy
3665 * statement to the node.
3666 * The statement name is "read" or "write", depending on whether we are
3667 * reading from global memory or writing to global memory.
3668 * The name of the T space is {shared,private}_<array>.
3670 * The schedule is of the form
3672 * type[A -> T] -> L
3674 * where A refers to a piece of an array and T to the corresponding
3675 * shifted tile. We split this schedule into mappings L -> A and L -> T
3676 * and store the corresponding expressions in stmt->index and stmt->local_index,
3677 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
3679 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
3680 __isl_keep isl_ast_build *build, void *user)
3682 struct gpu_gen *gen = (struct gpu_gen *) user;
3683 struct ppcg_kernel_stmt *stmt;
3684 isl_id *id;
3685 isl_ast_expr *expr;
3686 isl_space *space;
3687 isl_map *access, *local_access, *map;
3688 isl_pw_multi_aff *pma;
3689 const char *type;
3690 int array_index;
3692 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3693 if (!stmt)
3694 return isl_ast_node_free(node);
3696 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
3697 type = isl_map_get_tuple_name(access, isl_dim_in);
3698 stmt->u.c.read = !strcmp(type, "read");
3699 access = isl_map_reverse(access);
3700 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
3701 local_access = isl_map_copy(access);
3703 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
3704 id = isl_map_get_tuple_id(access, isl_dim_out);
3705 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3706 access = isl_map_apply_range(access, map);
3707 pma = isl_pw_multi_aff_from_map(access);
3708 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
3709 stmt->u.c.index = expr;
3711 map = isl_map_range_map(isl_map_universe(space));
3712 id = isl_map_get_tuple_id(local_access, isl_dim_out);
3713 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3714 local_access = isl_map_apply_range(local_access, map);
3715 pma = isl_pw_multi_aff_from_map(local_access);
3716 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
3717 stmt->u.c.local_index = expr;
3719 stmt->u.c.array = gen->copy_group->array;
3720 array_index = stmt->u.c.array - gen->prog->array;
3721 stmt->u.c.local_array = &gen->kernel->array[array_index];
3722 stmt->type = ppcg_kernel_copy;
3724 id = isl_id_alloc(gen->ctx, NULL, stmt);
3725 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3726 return isl_ast_node_set_annotation(node, id);
3729 /* Given a schedule of the form
3731 * [S -> A] -> L
3733 * (with S the first shared_len dimensions of the computed schedule,
3734 * A the array and L the schedule correponding to the generated loops),
3735 * indicating where to copy the array elements that need to be copied,
3736 * construct code for performing the copying.
3738 * "group" is the array reference group that is being copied
3739 * "type" is either "read" or "write"
3740 * private is set if copying needs to be performed to/from registers
3742 * We first construct a mapping to a shifted tile of the array,
3744 * [S -> A] -> T(S,A) (1)
3746 * If private is set, then we also use this mapping as a schedule
3747 * (which is already thread-specific and will be completely unrolled).
3748 * Otherwise, we wrap/tile the range over the threads.
3749 * The result is
3751 * [S -> A] -> T'(S,A)
3753 * Combined with the given schedule, we have
3755 * [S -> A] -> [L -> T'(S,A)] (2)
3757 * From the shifted tile mapping, we construct a mapping
3759 * [S -> A] -> [A -> T(S,A)]
3761 * and apply it to the schedule (2), obtaining
3763 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
3765 * Note that we can project out S because it is uniquely defined by L.
3767 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
3768 __isl_take isl_map *sched,
3769 const char *type, struct gpu_array_ref_group *group,
3770 __isl_take isl_ast_build *build, int private)
3772 isl_space *space;
3773 isl_ast_node *tree;
3774 isl_map *schedule, *shift, *map;
3775 isl_set *set;
3776 isl_id_list *iterators;
3777 int n;
3779 shift = shift_access(group);
3781 schedule = isl_map_copy(shift);
3782 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
3783 if (!private)
3784 schedule = tile_access_schedule(gen, schedule);
3786 n = isl_map_dim(schedule, isl_dim_out);
3787 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
3788 set = add_bounded_parameters(set, gen->kernel->n_block,
3789 gen->kernel->block_dim, "t");
3791 schedule = isl_map_range_product(sched, schedule);
3793 space = isl_space_domain(isl_map_get_space(shift));
3794 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
3795 map = isl_map_range_product(map, shift);
3797 schedule = isl_map_apply_domain(schedule, map);
3799 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
3801 build = isl_ast_build_restrict(build, set);
3803 gen->copy_group = group;
3805 if (private) {
3806 space = isl_space_range(isl_map_get_space(schedule));
3807 space = isl_space_range(isl_space_unwrap(space));
3808 build = set_unroll(build, space, 0);
3810 iterators = generate_names(gen->ctx, n, "c");
3811 build = isl_ast_build_set_iterators(build, iterators);
3812 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
3813 tree = isl_ast_build_ast_from_schedule(build,
3814 isl_union_map_from_map(schedule));
3815 isl_ast_build_free(build);
3817 return tree;
3820 /* Return code for reading into or writing from shared memory
3821 * the given array reference group.
3823 * If we are performing a read from global memory to shared memory and
3824 * if the array involved is not a scalar, then we copy
3825 * the entire tile to shared memory. This may result in some extra
3826 * elements getting copied, but it should lead to simpler code
3827 * (which means that fewer registers may be needed) and less divergence.
3829 * Otherwise, we only copy the elements that will be read or have been written
3830 * in the kernel.
3833 * The input "sched" is of the form.
3835 * type[S -> A] -> L
3837 * with S the first shared_len dimensions of the computed schedule,
3838 * A the array and L the schedule correponding to the generated loops.
3840 * We first drop "type",
3842 * [S -> A] -> L
3844 * If the above conditions are satisfied, we project out A,
3845 * resulting in
3847 * S -> L
3849 * and then introduce the group tile [S -> T], resulting in
3851 * [S -> T] -> L
3853 static __isl_give isl_ast_node *copy_group_shared_accesses(
3854 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3855 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3857 const char *type;
3858 int read;
3859 isl_union_map *access;
3861 type = isl_map_get_tuple_name(sched, isl_dim_in);
3862 read = !strcmp(type, "read");
3864 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3866 if (read && !gpu_array_is_scalar(group->array)) {
3867 isl_space *space;
3868 isl_map *map;
3870 space = isl_space_domain(isl_map_get_space(sched));
3871 space = isl_space_unwrap(space);
3872 map = isl_map_domain_map(isl_map_universe(space));
3873 sched = isl_map_apply_domain(sched, map);
3875 map = group_tile(group);
3876 map = isl_map_reverse(isl_map_domain_map(map));
3877 sched = isl_map_apply_domain(sched, map);
3880 return copy_access(gen, sched, type, group, build, 0);
3883 /* Return code for reading into or writing from private memory
3884 * the given array reference group.
3886 * Let S be the first shared_len dimensions of the computed schedule,
3887 * D the iteration domains, A the array and L the schedule correponding
3888 * to the generated loops.
3889 * "sched" is of the form
3891 * type[S -> A] -> L
3893 * where type is either "read" or "write".
3894 * We apply the privatization D -> S(t), with t the thread ids,
3895 * to the access relation D -> A to obtain the privatized access relation
3897 * S(t) -> A
3899 * We drop the type from "sched" and intersect with the privatized access
3900 * relation to obtain
3902 * [S(t) -> A] -> L
3904 static __isl_give isl_ast_node *copy_group_private_accesses(
3905 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3906 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3908 const char *type;
3909 int read;
3910 isl_union_map *priv;
3911 isl_union_map *access;
3912 isl_map *access_map;
3914 type = isl_map_get_tuple_name(sched, isl_dim_in);
3915 read = !strcmp(type, "read");
3917 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
3918 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3919 priv);
3921 access = group_access_relation(group, read, !read);
3922 access = isl_union_map_apply_domain(access, priv);
3923 access_map = isl_map_from_union_map(access);
3925 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3926 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
3928 return copy_access(gen, sched, type, group, build, 1);
3931 /* Return code for reading into or writing from shared or private memory.
3933 * "schedule" is of the form
3935 * type[S -> A] -> L
3937 * with S be the first shared_len dimensions of the computed schedule,
3938 * A the array and L the schedule correponding to the generated loops.
3939 * The array reference group is attached to "type".
3941 static __isl_give isl_ast_node *create_access_leaf(
3942 struct gpu_gen *gen, __isl_take isl_map *schedule,
3943 __isl_take isl_ast_build *build)
3945 struct gpu_array_ref_group *group;
3946 isl_id *id;
3948 id = isl_map_get_tuple_id(schedule, isl_dim_in);
3949 group = isl_id_get_user(id);
3950 isl_id_free(id);
3952 if (group->private_tile)
3953 return copy_group_private_accesses(gen, group, schedule,
3954 build);
3955 else
3956 return copy_group_shared_accesses(gen, group, schedule,
3957 build);
3960 /* Create a domain node representing a synchronization.
3962 static __isl_give isl_ast_node *create_sync_leaf(
3963 struct gpu_gen *gen, __isl_take isl_map *schedule,
3964 __isl_take isl_ast_build *build)
3966 struct ppcg_kernel_stmt *stmt;
3967 isl_id *id;
3968 isl_space *space;
3969 isl_ast_node *node;
3970 isl_ast_expr *expr;
3972 isl_map_free(schedule);
3974 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3975 if (!stmt)
3976 return NULL;
3978 stmt->type = ppcg_kernel_sync;
3980 space = isl_ast_build_get_schedule_space(build);
3981 space = isl_space_from_domain(space);
3982 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
3983 expr = isl_ast_build_call_from_pw_multi_aff(build,
3984 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
3985 node = isl_ast_node_alloc_user(expr);
3986 isl_ast_build_free(build);
3988 id = isl_id_alloc(gen->ctx, NULL, stmt);
3989 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3990 return isl_ast_node_set_annotation(node, id);
3993 /* This function is called during the code generation at the point
3994 * where the schedule domain element is completely determined by
3995 * the generated code. The input schedule contains the original
3996 * statements as well as synchronization and copy "statements".
3997 * The latter are scheduled at different points than any of the original
3998 * statements, so they will only arrive here in isolation.
4000 * If the current schedule only refers to a single statement,
4001 * we check if it is a copy or synchronization statement and
4002 * call the appropriate functions.
4003 * Otherwise, we assume we are dealing with the original statements
4004 * and we call create_domain_leaf.
4006 static __isl_give isl_ast_node *create_kernel_leaf(
4007 __isl_take isl_ast_build *build, void *user)
4009 struct gpu_gen *gen = (struct gpu_gen *) user;
4010 isl_map *map;
4011 isl_union_map *schedule;
4012 const char *name;
4014 schedule = isl_ast_build_get_schedule(build);
4016 if (isl_union_map_n_map(schedule) != 1)
4017 return create_domain_leaf(schedule, build, user);
4019 map = isl_map_from_union_map(schedule);
4020 name = isl_map_get_tuple_name(map, isl_dim_in);
4021 if (!strcmp(name, "read") || !strcmp(name, "write"))
4022 return create_access_leaf(gen, map, build);
4023 if (!strcmp(name, "sync"))
4024 return create_sync_leaf(gen, map, build);
4026 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4029 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4030 * have value 0) and all even schedule dimensions as "unroll".
4032 * That is, the options look as follows
4034 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4035 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4037 * The even positions are used to be able to schedule copying blocks
4038 * and synchronization before or after each level of the shared memory
4039 * tile loops and we want to make sure that code for these is generated
4040 * separately (within each level).
4042 static __isl_give isl_ast_build *set_atomic_and_unroll(
4043 __isl_take isl_ast_build *build,
4044 __isl_take isl_space *space, int sched_len)
4046 isl_ctx *ctx;
4047 isl_map *map;
4048 isl_constraint *c;
4049 isl_union_map *opt;
4050 isl_local_space *ls;
4051 int i, n;
4053 ctx = isl_ast_build_get_ctx(build);
4055 space = isl_space_params(space);
4056 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4057 space = isl_space_from_domain(space);
4058 space = isl_space_add_dims(space, isl_dim_out, 2);
4059 map = isl_map_universe(isl_space_copy(space));
4060 for (i = 0; i < sched_len; i += 2)
4061 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4062 ls = isl_local_space_from_space(isl_map_get_space(map));
4063 c = isl_equality_alloc(ls);
4064 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4065 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4066 c = isl_constraint_set_constant_si(c, 1);
4067 map = isl_map_add_constraint(map, c);
4068 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4069 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4070 opt = isl_union_map_from_map(map);
4072 map = isl_map_universe(space);
4073 ls = isl_local_space_from_space(isl_map_get_space(map));
4074 c = isl_equality_alloc(ls);
4075 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4076 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4077 map = isl_map_add_constraint(map, c);
4078 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4079 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4080 opt = isl_union_map_add_map(opt, map);
4082 build = isl_ast_build_set_options(build, opt);
4084 return build;
4087 /* Return a map that maps a space of dimension gen->shared_len
4088 * to its last dimensions starting at gen->tile_first.
4089 * The range is of dimension
4091 * 2 * (gen->shared_len - gen->tile_first) + 1
4093 * The input dimensions are mapped to the odd dimensions in the output,
4094 * while the even dimensions (except 2*pos) are fixed to 0.
4095 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4096 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4097 * are mapped to the output. The remaining input dimensions are projected
4098 * out and the corresponding output dimensions are fixed to 0.
4100 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4101 __isl_take isl_space *space, int pos, int val)
4103 int i, n;
4104 isl_map *proj;
4106 space = isl_space_set_from_params(space);
4107 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4108 space = isl_space_map_from_set(space);
4109 proj = isl_map_identity(space);
4110 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4111 n = gen->shared_len - gen->tile_first;
4112 for (i = 0; i <= n; ++i) {
4113 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4114 if (i == pos)
4115 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4116 else
4117 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4120 if (pos < 0)
4121 return proj;
4123 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4124 gen->shared_len - (gen->tile_first + pos));
4125 for (i = pos; i < n; ++i)
4126 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4128 return proj;
4131 /* Given the AST context schedule "schedule" and the mapping from
4132 * domains to the shared tile loops "shared_sched", add a schedule
4133 * for a synchronization operation at position "val" of loop level "pos".
4135 * schedule is of the form
4137 * D -> L
4139 * (with D the iteration domains and L the already generated loops),
4140 * while shared_sched is of the form
4142 * D -> S
4144 * We combine them into
4146 * L -> S
4148 * apply a mapping
4150 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4152 * and use the result as a schedule for "sync".
4154 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4155 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4156 __isl_keep isl_union_map *shared_sched, int pos, int val)
4158 isl_space *space;
4159 isl_map *proj, *map;
4161 shared_sched = isl_union_map_copy(shared_sched);
4162 schedule = isl_union_map_copy(schedule);
4164 space = isl_union_map_get_space(shared_sched);
4165 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4166 map = isl_map_from_union_map(schedule);
4168 proj = insert_even(gen, space, pos, val);
4169 map = isl_map_apply_range(map, proj);
4170 map = isl_map_from_range(isl_map_wrap(map));
4171 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4173 res = isl_union_map_add_map(res, map);
4175 return res;
4178 /* Given the AST context schedule "schedule" and the mapping from
4179 * domains to the shared tile loops "shared_sched", add a schedule
4180 * for copying an array reference group to/from shared/private memory.
4181 * "read" is set if data should be copied from global memory
4182 * to shared/private memory.
4183 * "k" represents the current group
4184 * "s" is the total number of groups
4186 * We schedule an operation before or after the innermost loop
4187 * of "shared_sched" that affects the tile of the array reference group.
4189 * schedule is of the form
4191 * D -> L
4193 * (with D the iteration domains and L the already generated loops),
4194 * while shared_sched is of the form
4196 * D -> S
4198 * We first compute the access relation for the reference group
4200 * D -> A
4202 * and combine it with shared_sched into
4204 * D -> [S -> A]
4206 * If this results in an empty relation, no copying needs to be performed
4207 * at this point.
4208 * Otherwise, we invert the relation and combine it with "schedule" into
4210 * [S -> A] -> L
4212 * The actual additional piece of the schedule is obtained from combining
4214 * [S -> A] -> S
4216 * with a mapping
4218 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4220 * The position of "val" corresponds to the innermost loop that affects
4221 * the tile and the value indicates where the copying is scheduled
4222 * with respect to the actual kernel code (at value 0).
4223 * Reads are schedule before the code, writes to global memory from
4224 * private memory are scheduled at values 1 to s, writes to global
4225 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4227 * If we are scheduling a read from global memory to shared memory,
4228 * we insert a synchronization before the kernel code (at the innermost
4229 * level).
4230 * If we are scheduling a write to global memory, then we add
4231 * a synchronization after all writes (at value 2 *s + 2).
4232 * However, there is no need for a synchronization after the outermost loop.
4233 * A write to global memory from private memory at the innermost level
4234 * does not require a synchronization, because it is covered by
4235 * the synchronization after the kernel inserted by body_schedule.
4237 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4238 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4239 __isl_keep isl_union_map *shared_sched,
4240 struct gpu_array_ref_group *group, int read, int k, int s)
4242 int n;
4243 int pos, val;
4244 isl_space *space;
4245 isl_union_map *access;
4246 isl_map *map, *proj, *access_map;
4247 isl_id *id;
4249 access = group_access_relation(group, read, !read);
4250 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4251 access);
4253 if (isl_union_map_is_empty(access)) {
4254 isl_union_map_free(access);
4255 return res;
4258 access = isl_union_map_reverse(access);
4259 access = isl_union_map_apply_range(access,
4260 isl_union_map_copy(schedule));
4261 access_map = isl_map_from_union_map(access);
4263 space = isl_space_copy(group->array->space);
4264 space = isl_space_from_range(space);
4265 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4266 map = isl_map_domain_map(isl_map_universe(space));
4268 space = isl_union_map_get_space(schedule);
4269 pos = group->last_shared + 1 - gen->tile_first;
4270 assert(pos >= 0);
4271 if (read)
4272 val = -2 - k;
4273 else if (group->private_tile)
4274 val = 1 + k;
4275 else
4276 val = 1 + s + 1 + k;
4277 proj = insert_even(gen, space, pos, val);
4278 map = isl_map_apply_range(map, proj);
4280 access_map = isl_map_range_product(access_map, map);
4282 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4283 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4285 res = isl_union_map_add_map(res, access_map);
4287 n = gen->shared_len - gen->tile_first;
4288 if (read) {
4289 if (!group->private_tile)
4290 res = add_sync_schedule(gen, res, schedule,
4291 shared_sched, n, -1);
4292 } else {
4293 if (pos == 0)
4294 return res;
4295 if (pos == n && group->private_tile)
4296 return res;
4297 res = add_sync_schedule(gen, res, schedule, shared_sched,
4298 pos, 2 * s + 2);
4301 return res;
4304 /* Return a schedule for the shared tile loops based on the current
4305 * AST context schedule.
4307 * We create a "shared_sched" that maps the domains to the first
4308 * shared_len dimensions of the computed schedule, project out the
4309 * first tile_first dimensions (as these are already covered by
4310 * the host code) and insert "statement-level" dimensions at even
4311 * positions so that we can schedule copy blocks and synchronization
4312 * before/after each level.
4314 * In particular, copy blocks are inserted inside the innermost
4315 * level that affect the tile. For the copying to global memory,
4316 * those from private memory are scheduled before those from shared
4317 * memory such that synchronization can be inserted between the two
4318 * at the innermost level.
4319 * Synchronization is inserted at the innermost level before the
4320 * actual kernel code if there is any copying from global memory
4321 * to shared memory. It is inserted unconditionally at the innermost
4322 * level after the actual kernel code and the copying to global memory
4323 * from private memory (if any). Finally, it is inserted after
4324 * any copying to global memory, except at the outermost level
4325 * and at the innermost level if there is no copying from shared
4326 * memory. The copying from private memory is covered by the unconditional
4327 * synchronization at the innermost level.
4329 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4330 __isl_take isl_union_map *schedule)
4332 isl_space *space;
4333 isl_union_map *res;
4334 isl_union_map *shared_sched;
4335 isl_union_map *sched;
4336 isl_map *proj, *map;
4337 int i, j, k, s;
4339 shared_sched = isl_union_map_copy(gen->tiled_sched);
4340 proj = projection(isl_union_map_get_space(shared_sched),
4341 gen->tiled_len, gen->shared_len);
4342 shared_sched = isl_union_map_apply_range(shared_sched,
4343 isl_union_map_from_map(proj));
4344 space = isl_union_map_get_space(shared_sched);
4345 proj = insert_even(gen, space, -1, 0);
4346 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4347 isl_union_map_from_map(proj));
4349 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4351 s = 0;
4352 for (i = 0; i < gen->prog->n_array; ++i)
4353 s += gen->prog->array[i].n_group;
4355 k = 0;
4356 for (i = 0; i < gen->prog->n_array; ++i) {
4357 struct gpu_array_info *array = &gen->prog->array[i];
4359 for (j = 0; j < array->n_group; ++j) {
4360 struct gpu_array_ref_group *group;
4362 group = array->groups[j];
4363 if (!group->private_tile && !group->shared_tile)
4364 continue;
4365 res = add_group_schedule(gen, res, schedule,
4366 shared_sched, group, 0, k, s);
4367 res = add_group_schedule(gen, res, schedule,
4368 shared_sched, group, 1, k, s);
4369 ++k;
4373 res = add_sync_schedule(gen, res, schedule, shared_sched,
4374 gen->shared_len - gen->tile_first, 1 + s);
4376 isl_union_map_free(shared_sched);
4377 isl_union_map_free(schedule);
4379 return res;
4382 /* Generate code for "kernel" in the given "context".
4384 * We first generate code for the shared tile loops (T1T, T1P and T2)
4385 * in a context that includes the block ids.
4386 * Within each iteration of these loops an additional code generation
4387 * is performed (within create_kernel_leaf) for the rest of the schedule
4388 * in a context that includes the thread ids.
4390 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4391 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4392 __isl_keep isl_multi_pw_aff *grid_size)
4394 isl_space *space;
4395 isl_set *set;
4396 isl_id_list *iterators;
4397 isl_union_map *schedule;
4398 isl_ast_node *tree;
4399 int sched_len;
4401 schedule = isl_ast_build_get_schedule(build);
4403 build = isl_ast_build_copy(build);
4404 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4405 space = isl_ast_build_get_schedule_space(build);
4406 set = isl_set_universe(isl_space_copy(space));
4407 set = add_bounded_parameters_dynamic(set, grid_size, "b");
4408 build = isl_ast_build_restrict(build, set);
4410 schedule = body_schedule(gen, schedule);
4412 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4414 build = set_atomic_and_unroll(build, space, sched_len);
4415 iterators = generate_names(gen->ctx, sched_len, "g");
4416 build = isl_ast_build_set_iterators(build, iterators);
4417 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4418 tree = isl_ast_build_ast_from_schedule(build, schedule);
4419 isl_ast_build_free(build);
4421 return tree;
4424 /* Attach "id" to the given node.
4426 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4427 __isl_keep isl_ast_build *build, void *user)
4429 isl_id *id = user;
4431 node = isl_ast_node_set_annotation(node, id);
4433 return node;
4436 /* Construct an AST node for performing a kernel launch and attach
4437 * the information about the kernel to that node.
4439 * The kernel AST has been constructed in the context of the range
4440 * of "schedule". In particular, the grid size has been computed
4441 * in the context. We therefore still need to make sure that these
4442 * constraints are expressed in the code. We do this by creating a schedule
4444 * kernel[] -> [S -> []]
4446 * where S is the schedule domain, i.e., the range of "schedule".
4447 * The AST generation will then create a single call surrounded by
4448 * all the condition in "S" that have not been expressed yet.
4450 * The kernel information is attached to this node in attach_id.
4452 static __isl_give isl_ast_node *construct_launch(
4453 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
4454 __isl_take struct ppcg_kernel *kernel)
4456 isl_id *id;
4457 isl_ctx *ctx;
4458 isl_union_set *domain;
4459 isl_set *set;
4460 isl_map *map;
4461 isl_ast_node *node;
4463 ctx = isl_ast_build_get_ctx(build);
4465 id = isl_id_alloc(ctx, NULL, kernel);
4466 id = isl_id_set_free_user(id, &ppcg_kernel_free);
4468 domain = isl_union_map_range(schedule);
4469 set = isl_set_from_union_set(domain);
4470 map = isl_map_from_domain(set);
4471 map = isl_map_from_range(isl_map_wrap(map));
4472 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
4473 schedule = isl_union_map_from_map(map);
4475 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
4476 node = isl_ast_build_ast_from_schedule(build, schedule);
4477 isl_ast_build_free(build);
4479 return node;
4482 /* This function is called for each leaf in the AST of the host code.
4483 * We first specialize the schedule to the site of the leaf, compute
4484 * the size of shared memory and then construct the body of the host code
4485 * and the associated kernel.
4487 * The necessary information for printing the kernel launch is
4488 * stored in a struct ppcg_kernel and attached to the leaf node
4489 * created to represent the launch.
4491 static __isl_give isl_ast_node *create_host_leaf(
4492 __isl_take isl_ast_build *build, void *user)
4494 struct gpu_gen *gen = (struct gpu_gen *) user;
4495 isl_id *id;
4496 isl_ast_node *node;
4497 struct ppcg_kernel *kernel;
4498 isl_set *host_domain;
4499 isl_union_map *schedule;
4500 isl_union_map *local_sched;
4501 isl_union_map *access;
4502 isl_union_set *domain;
4503 int i;
4505 schedule = isl_ast_build_get_schedule(build);
4507 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
4508 read_sizes(gen);
4510 domain = isl_union_map_domain(isl_union_map_copy(schedule));
4512 local_sched = isl_union_map_copy(gen->sched);
4513 local_sched = isl_union_map_intersect_domain(local_sched, domain);
4514 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
4515 isl_union_map_copy(gen->prog->write));
4516 access = isl_union_map_apply_domain(access,
4517 isl_union_map_copy(local_sched));
4519 gen->tiled_sched = tile_schedule(gen, local_sched);
4520 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
4521 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
4523 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
4524 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
4525 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
4527 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
4528 if (!kernel)
4529 goto error;
4531 kernel->id = gen->kernel_id++;
4532 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
4533 kernel->grid_size = extract_grid_size(gen, kernel);
4534 extract_block_size(gen, kernel);
4535 kernel->arrays = isl_union_map_range(access);
4536 kernel->space = isl_ast_build_get_schedule_space(build);
4538 gen->private_access = NULL;
4539 compute_shared_sched(gen);
4540 gen->privatization = compute_privatization(gen);
4541 group_references(gen);
4542 compute_private_access(gen);
4543 check_shared_memory_bound(gen);
4544 compute_group_tilings(gen);
4545 host_domain = isl_set_from_union_set(isl_union_map_range(
4546 isl_union_map_copy(schedule)));
4547 localize_bounds(gen, kernel, host_domain);
4549 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
4551 kernel->tree = generate_kernel(gen, build, host_domain,
4552 kernel->grid_size);
4553 create_kernel_vars(gen, kernel);
4555 free_local_array_info(gen);
4556 isl_map_free(gen->privatization);
4557 isl_union_map_free(gen->private_access);
4558 isl_union_map_free(gen->local_sched);
4559 isl_union_map_free(gen->tiled_sched);
4560 isl_union_map_free(gen->shared_sched);
4561 isl_union_map_free(gen->shared_proj);
4562 isl_set_free(host_domain);
4563 free(gen->tile_size);
4565 node = construct_launch(build, schedule, kernel);
4567 return node;
4568 error:
4569 isl_union_map_free(schedule);
4570 return NULL;
4573 /* Use isl to generate code for the outer gen->tile_first loops
4574 * of the global schedule in gen->sched, resulting in the host code.
4575 * Within each iteration of this partial schedule, i.e., for each kernel
4576 * launch, create_host_leaf takes care of generating the kernel code.
4578 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
4580 isl_ast_build *build;
4581 isl_ast_node *tree;
4582 isl_union_map *sched;
4583 isl_map *proj;
4584 isl_id_list *iterators;
4586 sched = isl_union_map_copy(gen->sched);
4587 proj = projection(isl_union_map_get_space(sched),
4588 gen->untiled_len, gen->tile_first);
4589 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4591 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
4592 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
4593 iterators = generate_names(gen->ctx, gen->tile_first, "h");
4594 build = isl_ast_build_set_iterators(build, iterators);
4595 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
4596 tree = isl_ast_build_ast_from_schedule(build, sched);
4597 isl_ast_build_free(build);
4599 return tree;
4602 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
4604 if (!str)
4605 return NULL;
4606 return isl_union_map_read_from_str(ctx, str);
4609 /* Information about the outermost tilable bands in the forest of bands.
4611 * tile_len and n_parallel are only sets on band_info structures
4612 * that correspond to outermost bands. For other bands (in particular,
4613 * ancestors of the outermost bands), n_parallal is set to 0.
4615 * prefix is the (padded) schedule leading up to the outermost tilable bands.
4617 * tile_first is the number of schedule dimensions in prefix.
4619 * suffix is the schedule of the outermost tilable bands and their descendants.
4621 struct band_info {
4622 struct gpu_gen *gen;
4623 int tile_first;
4624 int tile_len;
4625 int n_parallel;
4626 isl_union_map *prefix;
4627 isl_union_map *suffix;
4630 /* Set tile_len and n_parallel of the statement to that of
4631 * their outermost band, recorded in the band_info.
4633 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
4635 struct band_info *info = user;
4636 struct gpu_stmt *stmt;
4637 isl_id *id;
4639 id = isl_map_get_tuple_id(map, isl_dim_in);
4640 stmt = find_stmt(info->gen->prog, id);
4641 isl_id_free(id);
4643 stmt->tile_len = info->tile_len;
4644 stmt->n_parallel = info->n_parallel;
4646 isl_map_free(map);
4648 return 0;
4651 static void list_select_outer_band(struct gpu_gen *gen,
4652 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
4654 /* Check if this band has any parallel loops. If so, take it as
4655 * the outermost tilable band. If not, continue looking for the
4656 * outermost tilable band in the children of the current band.
4658 static void band_select_outer_band(struct gpu_gen *gen,
4659 __isl_take isl_band *band, int pos, struct band_info *info)
4661 int n = isl_band_n_member(band);
4662 int n_parallel;
4664 for (n_parallel = 0; n_parallel < n; ++n_parallel)
4665 if (!isl_band_member_is_zero_distance(band, n_parallel))
4666 break;
4668 info->n_parallel = n_parallel;
4669 if (n_parallel) {
4670 gen->any_parallelism = 1;
4671 info->gen = gen;
4672 info->tile_first = pos;
4673 info->tile_len = n;
4674 info->prefix = isl_band_get_prefix_schedule(band);
4675 info->suffix = isl_union_map_flat_range_product(
4676 isl_band_get_partial_schedule(band),
4677 isl_band_get_suffix_schedule(band));
4678 isl_union_map_foreach_map(info->prefix,
4679 &set_stmt_tile_len, info);
4680 } else if (isl_band_has_children(band)) {
4681 isl_band_list *children;
4682 children = isl_band_get_children(band);
4683 list_select_outer_band(gen, children, pos + n, info);
4684 } else {
4685 info->gen = gen;
4686 info->tile_first = pos + n;
4687 info->tile_len = 0;
4688 info->prefix = isl_union_map_flat_range_product(
4689 isl_band_get_prefix_schedule(band),
4690 isl_band_get_partial_schedule(band));
4691 info->suffix = isl_band_get_suffix_schedule(band);
4692 isl_union_map_foreach_map(info->prefix,
4693 &set_stmt_tile_len, info);
4696 isl_band_free(band);
4699 /* Comparison function that returns a non-zero value for band_infos
4700 * with different tile_len fields or different n_parallel fields.
4702 static int cmp_band(const void *p1, const void *p2)
4704 const struct band_info *info1 = p1;
4705 const struct band_info *info2 = p2;
4707 if (info1->tile_len != info2->tile_len)
4708 return info1->tile_len - info2->tile_len;
4710 return info1->n_parallel - info2->n_parallel;
4713 /* Extend "umap" with coordinates with fixed value "val"
4714 * to a total length of "dst_len", assuming the original dimension is "src_len".
4716 static __isl_give isl_union_map *extend_range(
4717 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
4719 isl_space *dim;
4720 isl_map *map;
4721 int i;
4723 dim = isl_union_map_get_space(umap);
4724 map = isl_map_reverse(projection(dim, dst_len, src_len));
4725 for (i = src_len; i < dst_len; ++i)
4726 map = isl_map_fix_si(map, isl_dim_out, i, val);
4728 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
4730 return umap;
4733 /* Group bands with the same values for tile_len and n_parallel.
4734 * The prefix schedule is then extended with a fixed coordinate that
4735 * is different for each such group.
4736 * Note that the actual values for this coordinate are not important.
4737 * The bands have already been effectively separated at a higher level
4738 * or they are independent and may be executed in parallel.
4739 * The list of band_info has been sorted before this functions is called.
4741 static void separate_bands(struct band_info *info, int n)
4743 int i;
4744 int j = 0;
4746 for (i = 0; i < n; ++i) {
4747 int l = info[i].tile_first;
4749 if (i &&
4750 (info[i].tile_len != info[i - 1].tile_len ||
4751 info[i].n_parallel != info[i - 1].n_parallel))
4752 j++;
4754 info[i].prefix = extend_range(info[i].prefix,
4755 l, l + 1, j);
4756 info[i].tile_first = l + 1;
4760 /* Select the outermost bands in the elements of the list, align
4761 * their prefix schedules, separate bands with different values
4762 * for tile_len and/or n_parallel and then combine the resulting
4763 * prefix and suffix schedules into a single pair of prefix and
4764 * suffix schedules for the entire list.
4766 static void list_select_outer_band(struct gpu_gen *gen,
4767 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
4769 isl_band *band;
4770 int i;
4771 int n = isl_band_list_n_band(list);
4772 isl_ctx *ctx = isl_band_list_get_ctx(list);
4773 struct band_info *info;
4774 int max_tile_first;
4775 isl_union_map *prefix;
4776 isl_union_map *suffix;
4778 assert(n >= 1);
4779 info = isl_calloc_array(ctx, struct band_info, n);
4780 assert(info);
4782 max_tile_first = 0;
4783 for (i = 0; i < n; ++i) {
4784 band = isl_band_list_get_band(list, i);
4785 band_select_outer_band(gen, band, pos, &info[i]);
4786 if (info[i].tile_first > max_tile_first)
4787 max_tile_first = info[i].tile_first;
4790 for (i = 0; i < n; ++i) {
4791 if (info[i].tile_first == max_tile_first)
4792 continue;
4793 info[i].prefix = extend_range(info[i].prefix,
4794 info[i].tile_first, max_tile_first, 0);
4795 info[i].tile_first = max_tile_first;
4798 qsort(info, n, sizeof(struct band_info), &cmp_band);
4800 for (i = 0; i < n - 1; ++i)
4801 if (info[i].tile_len != info[i + 1].tile_len ||
4802 info[i].n_parallel != info[i + 1].n_parallel)
4803 break;
4805 if (i < n -1)
4806 separate_bands(info, n);
4808 prefix = info[0].prefix;
4809 suffix = info[0].suffix;
4811 for (i = 1; i < n; ++i) {
4812 prefix = isl_union_map_union(prefix, info[i].prefix);
4813 suffix = isl_union_map_union(suffix, info[i].suffix);
4816 list_info->tile_first = info[0].tile_first;
4817 list_info->tile_len = -1;
4818 list_info->prefix = prefix;
4819 list_info->suffix = suffix;
4821 isl_band_list_free(list);
4822 free(info);
4825 /* Select the outermost tilable band that (by construction)
4826 * has at least one parallel loop.
4827 * The starting position of the aligned band is stored in the pair
4828 * gen->tile_first.
4829 * The sizes and number of parallel loops may be different in different
4830 * parts of the band forest and are therefore stored in the gpu_stmts.
4832 * Return the complete schedule, with the tilable bands aligned
4833 * at gen->tile_first and padded with zero, if needed.
4835 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
4836 __isl_keep isl_schedule *schedule)
4838 isl_band_list *list;
4839 struct band_info info;
4841 gen->n_parallel = 0;
4842 gen->tile_len = -1;
4844 list = isl_schedule_get_band_forest(schedule);
4846 if (isl_band_list_n_band(list) == 0) {
4847 isl_band_list_free(list);
4848 return isl_schedule_get_map(schedule);
4851 list_select_outer_band(gen, list, 0, &info);
4853 gen->tile_first = info.tile_first;
4854 info.suffix = align_range(info.suffix);
4856 return isl_union_map_flat_range_product(info.prefix, info.suffix);
4859 /* Set gen->untiled_len to the number of scheduling dimensions
4860 * for the schedule of the first domain.
4861 * We assume here that this number is the same for all domains.
4863 static int set_untiled_len(__isl_take isl_map *map, void *user)
4865 unsigned *untiled_len = user;
4867 *untiled_len = isl_map_dim(map, isl_dim_out);
4869 isl_map_free(map);
4870 return -1;
4873 /* Compute an appropriate schedule based on the accesses in
4874 * gen->read and gen->write.
4876 * We use the dependences in gen->prog->scop to compute
4877 * a schedule that has a parallel loop in each tilable band.
4878 * Finally, we select the outermost tilable band.
4880 static void compute_schedule(struct gpu_gen *gen)
4882 isl_union_set *domain;
4883 isl_union_map *dep_raw, *dep;
4884 isl_union_map *sched;
4885 isl_schedule *schedule;
4887 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4889 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4890 dep = isl_union_map_union(dep, dep_raw);
4891 dep = isl_union_map_coalesce(dep);
4893 domain = isl_union_set_copy(gen->prog->scop->domain);
4894 domain = isl_union_set_intersect_params(domain,
4895 isl_set_copy(gen->prog->scop->context));
4896 schedule = isl_union_set_compute_schedule(isl_union_set_copy(domain),
4897 isl_union_map_copy(dep), dep);
4898 if (gen->options->debug->dump_schedule)
4899 isl_schedule_dump(schedule);
4901 sched = select_outer_tilable_band(gen, schedule);
4903 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
4904 sched = isl_union_map_intersect_domain(sched, domain);
4905 gen->sched = sched;
4907 isl_schedule_free(schedule);
4910 /* Compute the sets of array elements that need to be copied in and out.
4912 * In particular, for each array that is written anywhere in gen->prog and
4913 * that is visible outside the corresponding scop, we copy out its entire
4914 * extent.
4916 * Any array elements that is read without first being written needs
4917 * to be copied in. Furthermore, if there are any array elements that
4918 * are copied out, but that are not written inside gen->prog, then
4919 * they also need to be copied in to ensure that the value after execution
4920 * is the same as the value before execution.
4921 * While computing the set of array elements that
4922 * are copied out but not written, we intersect both sets with the context.
4923 * This helps in those cases where the arrays are declared with a fixed size,
4924 * while the accesses are parametric and the context assigns a fixed value
4925 * to the parameters.
4927 * If an element from a local array is read without first being written,
4928 * then there is no point in copying it in since it cannot have been
4929 * written prior to the scop. Warn about the uninitialized read instead.
4931 static void compute_copy_in_and_out(struct gpu_gen *gen)
4933 int i;
4934 isl_union_set *local;
4935 isl_union_set *write;
4936 isl_union_set *copy_in, *copy_out;
4937 isl_union_set *not_written;
4938 isl_union_map *uninitialized;
4939 isl_union_map *local_uninitialized;
4941 write = isl_union_map_range(isl_union_map_copy(gen->prog->write));
4942 write = isl_union_set_intersect_params(write,
4943 isl_set_copy(gen->prog->context));
4944 copy_out = isl_union_set_empty(isl_union_set_get_space(write));
4945 local = isl_union_set_copy(copy_out);
4947 for (i = 0; i < gen->prog->n_array; ++i) {
4948 isl_space *space;
4949 isl_set *write_i;
4950 int empty;
4952 space = isl_space_copy(gen->prog->array[i].space);
4954 if (gen->prog->array[i].local) {
4955 isl_set *set;
4957 set = isl_set_universe(space);
4958 local = isl_union_set_add_set(local, set);
4959 continue;
4962 write_i = isl_union_set_extract_set(write, space);
4963 empty = isl_set_fast_is_empty(write_i);
4964 isl_set_free(write_i);
4965 if (empty)
4966 continue;
4968 write_i = isl_set_copy(gen->prog->array[i].extent);
4969 copy_out = isl_union_set_add_set(copy_out, write_i);
4972 copy_out = isl_union_set_intersect_params(copy_out,
4973 isl_set_copy(gen->prog->context));
4975 gen->prog->copy_out = isl_union_set_copy(copy_out);
4977 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
4978 local_uninitialized = isl_union_map_copy(uninitialized);
4980 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4981 local);
4982 if (!isl_union_map_is_empty(local_uninitialized)) {
4983 fprintf(stderr, "uninitialized reads (not copied in):\n");
4984 isl_union_map_dump(local_uninitialized);
4986 uninitialized = isl_union_map_subtract(uninitialized,
4987 local_uninitialized);
4988 copy_in = isl_union_map_range(uninitialized);
4990 not_written = isl_union_set_subtract(copy_out, write);
4991 copy_in = isl_union_set_union(copy_in, not_written);
4992 gen->prog->copy_in = copy_in;
4995 static struct gpu_stmt_access **expr_extract_access(struct pet_expr *expr,
4996 struct gpu_stmt_access **next_access)
4998 struct gpu_stmt_access *access;
4999 isl_ctx *ctx = isl_map_get_ctx(expr->acc.access);
5001 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5002 assert(access);
5003 access->next = NULL;
5004 access->read = expr->acc.read;
5005 access->write = expr->acc.write;
5006 access->access = isl_map_copy(expr->acc.access);
5007 access->ref_id = isl_id_copy(expr->acc.ref_id);
5009 *next_access = access;
5010 next_access = &(*next_access)->next;
5011 return next_access;
5014 static struct gpu_stmt_access **expr_extract_accesses(struct pet_expr *expr,
5015 struct gpu_stmt_access **next_access)
5017 int i;
5019 for (i = 0; i < expr->n_arg; ++i)
5020 next_access = expr_extract_accesses(expr->args[i],
5021 next_access);
5023 if (expr->type == pet_expr_access)
5024 next_access = expr_extract_access(expr, next_access);
5026 return next_access;
5029 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
5031 struct gpu_stmt_access **next_access = &stmt->accesses;
5033 stmt->accesses = NULL;
5034 expr_extract_accesses(stmt->stmt->body, next_access);
5037 /* Return an array of gpu_stmt representing the statements in "scop".
5039 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5040 __isl_keep isl_set *context)
5042 int i;
5043 struct gpu_stmt *stmts;
5045 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
5046 if (!stmts)
5047 return NULL;
5049 for (i = 0; i < scop->n_stmt; ++i) {
5050 struct gpu_stmt *s = &stmts[i];
5052 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
5053 s->stmt = scop->stmts[i];
5054 pet_stmt_extract_accesses(s);
5057 return stmts;
5060 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5062 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5064 struct gpu_gen *gen = user;
5066 return gen->print(p, gen->prog, gen->tree, gen->print_user);
5069 /* Generate CUDA code for "scop" and print it to "p".
5070 * After generating an AST for the transformed scop as explained below,
5071 * we call "gen->print" to print the AST in the desired output format
5072 * to "p".
5074 * If it turns out that it does not make sense to generate GPU code,
5075 * then we generate CPU code instead.
5077 * The GPU code is generated in a context where at least one
5078 * statement instance is executed. The corresponding guard (if any) is printed
5079 * around the entire generated GPU code, except for the declaration
5080 * of the arrays that are visible outside of the scop and that therefore
5081 * cannot be declared inside the body of any possible guard.
5083 * We first compute a schedule that respects the dependences
5084 * of the original program and select the outermost band
5085 * of tilable dimensions that has at least one parallel loop.
5086 * We then have three blocks of dimensions
5088 * H B G
5090 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5091 * in
5093 * H T P G
5095 * For each iteration of the T loop and for each array, we compute
5096 * the array elements accessed by that iteration, construct a rectangular
5097 * box around it and shift it to the origin. The result is used
5098 * as shared memory for the array.
5100 * We then split off at most 2 parallel loops from the T loops and
5101 * at most 3 parallel loops from the P loops
5103 * H T1 T2 P1 P2 G
5105 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5106 * according to "grid"/"block" sizes.
5108 * H T1T T1P T2 P1T P1P P2 G
5110 * Finally, the T1P and P1P iterators are equated to the block and
5111 * thread dimensions respectively and so are effectively removed.
5112 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5113 * are run on the GPU.
5115 * Code is generated in three stages. We first generate code for the
5116 * host (the H loops), with iterators h%d. Then, for each leaf node
5117 * of the resulting AST, we generate code for the shared loops (up to
5118 * and including T2), with iterators g%d and after equating the H loops
5119 * to h%d parameters and the T1P loops to the block dimensions.
5120 * Finally, we generate code for the remaining loops in a similar fashion.
5122 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5123 struct gpu_gen *gen, struct ppcg_scop *scop,
5124 struct ppcg_options *options)
5126 struct gpu_prog *prog;
5127 isl_ctx *ctx;
5128 isl_set *context, *guard;
5130 if (!scop)
5131 return isl_printer_free(p);
5133 ctx = isl_printer_get_ctx(p);
5134 prog = gpu_prog_alloc(ctx, scop);
5135 if (!prog)
5136 return isl_printer_free(p);
5138 context = isl_set_copy(prog->context);
5139 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5140 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5142 gen->prog = prog;
5143 gen->any_parallelism = 0;
5144 compute_schedule(gen);
5146 if (!gen->any_parallelism) {
5147 isl_set_free(context);
5148 isl_set_free(guard);
5149 p = print_cpu(p, scop, options);
5150 } else {
5151 compute_copy_in_and_out(gen);
5152 gen->tree = generate_host_code(gen);
5153 p = ppcg_print_exposed_declarations(p, prog->scop);
5154 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5155 isl_ast_node_free(gen->tree);
5158 isl_union_map_free(gen->sched);
5160 gpu_prog_free(prog);
5162 return p;
5165 /* Wrapper around generate for use as a ppcg_transform callback.
5167 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5168 struct ppcg_scop *scop, void *user)
5170 struct gpu_gen *gen = user;
5172 return generate(p, gen, scop, gen->options);
5175 /* Transform the code in the file called "input" by replacing
5176 * all scops by corresponding GPU code and write the results to "out".
5178 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5179 struct ppcg_options *options,
5180 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5181 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5182 void *user), void *user)
5184 struct gpu_gen gen;
5185 int r;
5187 gen.ctx = ctx;
5188 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5189 gen.options = options;
5190 gen.kernel_id = 0;
5191 gen.print = print;
5192 gen.print_user = user;
5194 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5196 isl_union_map_free(gen.sizes);
5198 return r;
5201 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5203 struct gpu_prog *prog;
5205 if (!scop)
5206 return NULL;
5208 prog = isl_calloc_type(ctx, struct gpu_prog);
5209 assert(prog);
5211 prog->ctx = ctx;
5212 prog->scop = scop;
5213 prog->context = isl_set_copy(scop->context);
5214 prog->n_stmts = scop->n_stmt;
5215 prog->stmts = extract_stmts(ctx, scop, prog->context);
5216 prog->read = isl_union_map_copy(scop->reads);
5217 prog->write = isl_union_map_copy(scop->writes);
5219 if (!prog->stmts)
5220 return gpu_prog_free(prog);
5222 if (collect_array_info(prog) < 0)
5223 return gpu_prog_free(prog);
5225 return prog;
5228 void *gpu_prog_free(struct gpu_prog *prog)
5230 if (!prog)
5231 return NULL;
5232 free_array_info(prog);
5233 free_stmts(prog->stmts, prog->n_stmts);
5234 isl_union_set_free(prog->copy_in);
5235 isl_union_set_free(prog->copy_out);
5236 isl_union_map_free(prog->read);
5237 isl_union_map_free(prog->write);
5238 isl_set_free(prog->context);
5239 free(prog);
5240 return NULL;