README: -DPOLYBENCH_USE_C99_PROTO should not be used on nvcc command line
[ppcg.git] / gpu.c
blobc8e65f5fb97048b420fdf364e60a2463aeb8d3f2
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.
97 * exact_write is set if all writes are definite writes.
98 * slice is set if there is at least one access in the group
99 * that refers to more than one element
101 isl_map *access;
102 int write;
103 int exact_write;
104 int slice;
106 /* The shared memory tile, NULL if none. */
107 struct gpu_array_tile *shared_tile;
109 /* The private memory tile, NULL if none. */
110 struct gpu_array_tile *private_tile;
112 /* References in this group; point to elements of a linked list. */
113 int n_ref;
114 struct gpu_stmt_access **refs;
116 /* Last shared memory tile dimension that affects tile of this group. */
117 int last_shared;
120 struct gpu_gen {
121 isl_ctx *ctx;
122 struct ppcg_options *options;
124 /* Callback for printing of AST in appropriate format. */
125 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
126 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
127 struct gpu_types *types, void *user);
128 void *print_user;
130 struct gpu_prog *prog;
131 /* The generated AST. */
132 isl_ast_node *tree;
134 /* The sequence of types for which a definition has been printed. */
135 struct gpu_types types;
137 /* User specified tile, grid and block sizes for each kernel */
138 isl_union_map *sizes;
140 /* Effectively used tile, grid and block sizes for each kernel */
141 isl_union_map *used_sizes;
143 /* Identifier of current kernel. */
144 int kernel_id;
145 /* Pointer to the current kernel. */
146 struct ppcg_kernel *kernel;
147 /* Does the computed schedule exhibit any parallelism? */
148 int any_parallelism;
150 /* First tile dimension. */
151 int tile_first;
152 /* Number of tile dimensions. */
153 int tile_len;
154 /* Number of initial parallel loops among tile dimensions. */
155 int n_parallel;
157 /* Number of dimensions determining shared memory. */
158 int shared_len;
160 /* Number of rows in the untiled schedule. */
161 int untiled_len;
162 /* Number of rows in the tiled schedule. */
163 int tiled_len;
164 /* Number of rows in schedule after tiling/wrapping over threads. */
165 int thread_tiled_len;
167 /* Global untiled schedule. */
168 isl_union_map *sched;
169 /* Local (per kernel launch) tiled schedule. */
170 isl_union_map *tiled_sched;
171 /* Local schedule per shared memory tile loop iteration. */
172 isl_union_map *local_sched;
174 /* Local tiled schedule projected onto the shared tile loops and
175 * the loops that will be wrapped over the threads,
176 * with all shared tile loops parametrized.
178 isl_union_map *shared_sched;
179 /* Projects out the loops that will be wrapped over the threads
180 * from shared_sched.
182 isl_union_map *shared_proj;
184 /* A map that takes the range of shared_sched as input,
185 * wraps the appropriate loops over the threads and then projects
186 * out these loops.
188 isl_map *privatization;
190 /* A map from the shared memory tile loops and the thread indices
191 * (as parameters) to the set of accessed memory elements that
192 * will be accessed through private copies.
194 isl_union_map *private_access;
196 /* The schedule for the current private/shared access
197 * (within print_private_access or print_shared_access).
199 isl_map *copy_sched;
200 /* The array reference group corresponding to copy_sched. */
201 struct gpu_array_ref_group *copy_group;
203 /* Is any array in the current kernel marked force_private? */
204 int any_force_private;
206 /* First loop to unroll (or -1 if none) in the current part of the
207 * schedule.
209 int first_unroll;
211 int n_grid;
212 int n_block;
213 /* Note: in the input file, the sizes of the grid and the blocks
214 * are specified in the order x, y, z, but internally, the sizes
215 * are stored in reverse order, so that the last element always
216 * refers to the x dimension.
218 int grid_dim[2];
219 int block_dim[3];
220 int *tile_size;
223 /* Print the name of the local copy of a given group of array references.
225 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
226 struct gpu_array_ref_group *group)
228 int global = 0;
230 if (group->private_tile)
231 p = isl_printer_print_str(p, "private_");
232 else if (group->shared_tile)
233 p = isl_printer_print_str(p, "shared_");
234 else
235 global = 1;
236 p = isl_printer_print_str(p, group->array->name);
237 if (!global && group->array->n_group > 1) {
238 p = isl_printer_print_str(p, "_");
239 p = isl_printer_print_int(p, group->nr);
242 return p;
245 /* Collect all references to the given array and store pointers to them
246 * in array->refs.
248 * If the array contains structures, then there is no need to collect
249 * the references since we will not be computing any reference groups.
251 static void collect_references(struct gpu_prog *prog,
252 struct gpu_array_info *array)
254 int i;
255 int n;
257 if (array->has_compound_element)
258 return;
260 n = 0;
261 for (i = 0; i < prog->n_stmts; ++i) {
262 struct gpu_stmt *stmt = &prog->stmts[i];
263 struct gpu_stmt_access *access;
265 for (access = stmt->accesses; access; access = access->next) {
266 const char *name;
267 name = isl_map_get_tuple_name(access->access,
268 isl_dim_out);
269 if (name && !strcmp(array->name, name))
270 n++;
274 array->n_ref = n;
275 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
276 assert(array->refs);
278 n = 0;
279 for (i = 0; i < prog->n_stmts; ++i) {
280 struct gpu_stmt *stmt = &prog->stmts[i];
281 struct gpu_stmt_access *access;
283 for (access = stmt->accesses; access; access = access->next) {
284 const char *name;
285 name = isl_map_get_tuple_name(access->access,
286 isl_dim_out);
287 if (!name || strcmp(array->name, name))
288 continue;
290 array->refs[n++] = access;
295 /* Create a gpu_array_tile for an array of dimension "n_index".
297 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
299 int i;
300 struct gpu_array_tile *tile;
302 tile = isl_calloc_type(ctx, struct gpu_array_tile);
303 assert(tile);
305 tile->n = n_index;
307 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
308 assert(tile->bound);
310 for (i = 0; i < n_index; ++i) {
311 tile->bound[i].size = NULL;
312 tile->bound[i].lb = NULL;
313 tile->bound[i].stride = NULL;
314 tile->bound[i].shift = NULL;
315 tile->bound[i].shift_map = NULL;
318 return tile;
321 static void *free_tile(struct gpu_array_tile *tile)
323 int j;
325 if (!tile)
326 return NULL;
328 for (j = 0; j < tile->n; ++j) {
329 isl_val_free(tile->bound[j].size);
330 isl_val_free(tile->bound[j].stride);
331 isl_aff_free(tile->bound[j].lb);
332 isl_aff_free(tile->bound[j].shift);
333 isl_basic_map_free(tile->bound[j].shift_map);
335 free(tile->bound);
336 isl_multi_aff_free(tile->tiling);
337 free(tile);
339 return NULL;
342 static struct pet_array *find_array(struct ppcg_scop *scop,
343 __isl_keep isl_set *accessed)
345 int i;
346 isl_id *id;
348 id = isl_set_get_tuple_id(accessed);
350 for (i = 0; i < scop->pet->n_array; ++i) {
351 isl_id *id_i;
353 id_i = isl_set_get_tuple_id(scop->pet->arrays[i]->extent);
354 isl_id_free(id_i);
355 if (id == id_i)
356 break;
358 isl_id_free(id);
360 return i < scop->pet->n_array ? scop->pet->arrays[i] : NULL;
363 /* Compute and return the extent of "array", taking into account the set of
364 * accessed elements.
366 * In particular, the extent in the outer dimension is taken
367 * from "accessed", while then extent in the remaing dimensions
368 * are taken from array->extent.
370 * The extent in the outer dimension cannot be taken from array->extent
371 * because that may be unbounded. Furthermore, even if it is bounded,
372 * it may be larger than the piece of the array that is being accessed.
374 static __isl_give isl_set *compute_extent(struct pet_array *array,
375 __isl_keep isl_set *accessed)
377 int n_index;
378 isl_id *id;
379 isl_set *outer;
380 isl_set *extent;
382 extent = isl_set_copy(array->extent);
384 n_index = isl_set_dim(accessed, isl_dim_set);
385 if (n_index == 0)
386 return extent;
388 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
389 outer = isl_set_copy(accessed);
390 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
391 extent = isl_set_flat_product(outer, extent);
392 id = isl_set_get_tuple_id(accessed);
393 extent = isl_set_set_tuple_id(extent, id);
395 return extent;
398 /* Is the array "array" being extracted a read-only scalar?
400 * That is, is "array" a scalar that is never possibly written to.
401 * An array containing structures is never considered to be a scalar.
403 static int is_read_only_scalar(struct gpu_array_info *array,
404 struct gpu_prog *prog)
406 isl_set *space;
407 isl_union_map *write;
408 int empty;
410 if (array->has_compound_element)
411 return 0;
412 if (array->n_index != 0)
413 return 0;
415 write = isl_union_map_copy(prog->may_write);
416 space = isl_set_universe(isl_space_copy(array->space));
417 write = isl_union_map_intersect_range(write,
418 isl_union_set_from_set(space));
419 empty = isl_union_map_is_empty(write);
420 isl_union_map_free(write);
422 return empty;
425 /* Compute bounds on the host arrays based on the accessed elements
426 * and collect all references to the array.
428 * If the array is zero-dimensional and does not contain structures,
429 * i.e., if the array is a scalar, we check whether it is read-only.
431 static int extract_array_info(__isl_take isl_set *array, void *user)
433 int i;
434 struct gpu_prog *prog = (struct gpu_prog *)user;
435 const char *name;
436 int n_index;
437 isl_pw_aff **bounds;
438 struct pet_array *pa;
439 struct gpu_array_info *info;
440 isl_set *extent;
442 info = &prog->array[prog->n_array];
443 prog->n_array++;
445 n_index = isl_set_dim(array, isl_dim_set);
446 name = isl_set_get_tuple_name(array);
447 bounds = isl_alloc_array(isl_set_get_ctx(array),
448 isl_pw_aff *, n_index);
449 if (!bounds)
450 goto error;
452 info->space = isl_set_get_space(array);
453 info->name = strdup(name);
454 info->n_index = n_index;
455 info->bound = bounds;
456 info->linearize = prog->scop->options->linearize_device_arrays;
458 pa = find_array(prog->scop, array);
459 if (!pa)
460 isl_die(isl_set_get_ctx(array), isl_error_internal,
461 "unable to find array in scop", goto error);
463 info->type = strdup(pa->element_type);
464 info->size = pa->element_size;
465 info->local = pa->declared && !pa->exposed;
466 info->has_compound_element = pa->element_is_record;
467 info->read_only_scalar = is_read_only_scalar(info, prog);
469 extent = compute_extent(pa, array);
470 info->extent = extent;
471 for (i = 0; i < n_index; ++i) {
472 isl_set *dom;
473 isl_local_space *ls;
474 isl_aff *one;
475 isl_pw_aff *bound;
477 dom = isl_set_copy(extent);
478 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
479 n_index - (i + 1));
480 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
481 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
482 fprintf(stderr, "unable to determine extent of '%s' "
483 "in dimension %d\n", info->name, i);
484 dom = isl_set_free(dom);
486 bound = isl_set_dim_max(dom, 0);
487 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
488 ls = isl_local_space_from_space(isl_set_get_space(dom));
489 one = isl_aff_zero_on_domain(ls);
490 one = isl_aff_add_constant_si(one, 1);
491 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
492 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
494 bounds[i] = bound;
495 if (!isl_pw_aff_is_cst(bound))
496 info->linearize = 1;
499 collect_references(prog, info);
501 isl_set_free(array);
502 return 0;
503 error:
504 isl_set_free(array);
505 return -1;
508 /* Remove independence from the order constraints "order" on array "array".
509 * Since the pairs of iterations in the filter relation of an independence
510 * are guaranteed to be completely independent by the user, there is
511 * no need to ensure that live ranges are ordered along thong pairs.
512 * We make an exception for local variables, though, as the independence
513 * guarantee does not apply to those.
515 * The order constraints are used in two places.
516 * Those on scalars are used in check_scalar_live_ranges to check if
517 * we need to force the scalar to be private. Any non-local scalar
518 * should not be forced scalar if it only appears in independent loops.
519 * Those on non-scalars are added to the coincidence constraints
520 * in compute_schedule because we do not support any array expansion.
521 * Accesses to non-local arrays should not prevent a loop from being
522 * considered coincident so we should indeed remove those constraints
523 * from the order constraints.
525 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
526 struct gpu_array_info *array, __isl_take isl_union_map *order)
528 int i;
530 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
531 struct pet_independence *pi = prog->scop->pet->independences[i];
532 if (isl_union_set_contains(pi->local, array->space))
533 continue;
535 order = isl_union_map_subtract(order,
536 isl_union_map_copy(pi->filter));
539 return order;
542 /* For each array in "prog", store the (untagged) order dependences
543 * derived from the array in array->dep_order.
544 * In particular, consider all references that access the given array
545 * and take the order dependences that have one of these references
546 * as source. (Since an order dependence relates two references to
547 * the same array, the target of these order dependences will also
548 * be one of these references.)
549 * Additionally, store the union of these array->dep_order relations
550 * for all non-scalar arrays in prog->array_order.
552 void collect_order_dependences(struct gpu_prog *prog)
554 int i;
555 isl_space *space;
556 isl_union_map *accesses;
558 space = isl_union_map_get_space(prog->read);
559 prog->array_order = isl_union_map_empty(space);
561 accesses = isl_union_map_copy(prog->scop->tagged_reads);
562 accesses = isl_union_map_union(accesses,
563 isl_union_map_copy(prog->scop->tagged_may_writes));
564 accesses = isl_union_map_universe(accesses);
565 accesses = isl_union_map_apply_range(accesses,
566 isl_union_map_copy(prog->to_outer));
568 for (i = 0; i < prog->n_array; ++i) {
569 struct gpu_array_info *array = &prog->array[i];
570 isl_set *set;
571 isl_union_set *uset;
572 isl_union_map *order;
574 set = isl_set_universe(isl_space_copy(array->space));
575 uset = isl_union_set_from_set(set);
576 uset = isl_union_map_domain(
577 isl_union_map_intersect_range(isl_union_map_copy(accesses),
578 uset));
579 order = isl_union_map_copy(prog->scop->tagged_dep_order);
580 order = isl_union_map_intersect_domain(order, uset);
581 order = isl_union_map_zip(order);
582 order = isl_union_set_unwrap(isl_union_map_domain(order));
583 order = remove_independences(prog, array, order);
584 array->dep_order = order;
586 if (gpu_array_is_scalar(array))
587 continue;
589 prog->array_order = isl_union_map_union(prog->array_order,
590 isl_union_map_copy(array->dep_order));
593 isl_union_map_free(accesses);
596 /* Construct a gpu_array_info for each array possibly accessed by "prog" and
597 * collect them in prog->array.
599 * If there are any member accesses involved, then they are first mapped
600 * to the outer arrays of structs.
602 * If we are allowing live range reordering, then also set
603 * the dep_order field. Otherwise leave it NULL.
605 static int collect_array_info(struct gpu_prog *prog)
607 int r;
608 isl_union_set *arrays;
610 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
611 arrays = isl_union_set_union(arrays,
612 isl_union_map_range(isl_union_map_copy(prog->may_write)));
614 arrays = isl_union_set_apply(arrays,
615 isl_union_map_copy(prog->to_outer));
617 arrays = isl_union_set_coalesce(arrays);
619 prog->n_array = isl_union_set_n_set(arrays);
620 prog->array = isl_calloc_array(prog->ctx,
621 struct gpu_array_info, prog->n_array);
622 assert(prog->array);
623 prog->n_array = 0;
624 r = isl_union_set_foreach_set(arrays, &extract_array_info, prog);
625 isl_union_set_free(arrays);
627 if (prog->scop->options->live_range_reordering)
628 collect_order_dependences(prog);
630 return r;
633 static void free_array_info(struct gpu_prog *prog)
635 int i, j;
637 for (i = 0; i < prog->n_array; ++i) {
638 int n_index = prog->array[i].n_index;
639 free(prog->array[i].type);
640 free(prog->array[i].name);
641 for (j = 0; j < n_index; ++j)
642 isl_pw_aff_free(prog->array[i].bound[j]);
643 isl_space_free(prog->array[i].space);
644 isl_set_free(prog->array[i].extent);
645 free(prog->array[i].bound);
646 free(prog->array[i].refs);
647 isl_union_map_free(prog->array[i].dep_order);
649 free(prog->array);
652 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
653 * as an array or through a pointer reference, but as a single data element.
654 * At the moment, scalars are represented as zero-dimensional arrays.
655 * A zero-dimensional array containing structures is not considered
656 * to be a scalar.
658 int gpu_array_is_scalar(struct gpu_array_info *array)
660 return !array->has_compound_element && array->n_index == 0;
663 /* Is "array" a read-only scalar?
665 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
667 return array->read_only_scalar;
670 /* Return the set of parameter values for which the array has a positive
671 * size in all dimensions.
672 * If the sizes are only valid for some parameter values, then those
673 * constraints are also taken into account.
675 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
677 int i;
678 isl_space *space;
679 isl_set *guard;
681 space = isl_space_params(isl_space_copy(array->space));
682 guard = isl_set_universe(space);
684 for (i = 0; i < array->n_index; ++i) {
685 isl_pw_aff *bound;
686 isl_set *guard_i, *zero;
688 bound = isl_pw_aff_copy(array->bound[i]);
689 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
690 zero = isl_pw_aff_zero_set(bound);
691 guard_i = isl_set_subtract(guard_i, zero);
692 guard = isl_set_intersect(guard, guard_i);
695 return guard;
698 /* Internal data structure for extract_size_of_type.
699 * "type" specifies the name of the space that we want to extract.
700 * "res" is used to store the subset of that space.
702 struct ppcg_extract_size_data {
703 const char *type;
704 isl_set *res;
707 /* This function is called for each set in a union_set.
708 * If the name of the set matches data->type, we store the
709 * set in data->res.
711 static int extract_size_of_type(__isl_take isl_set *size, void *user)
713 struct ppcg_extract_size_data *data = user;
714 const char *name;
716 name = isl_set_get_tuple_name(size);
717 if (name && !strcmp(name, data->type)) {
718 data->res = size;
719 return -1;
722 isl_set_free(size);
723 return 0;
726 /* Given a union map { kernel[i] -> *[...] },
727 * return the range in the space called "type" for the kernel with
728 * sequence number "id".
730 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
731 const char *type, int id)
733 isl_space *space;
734 isl_set *dom;
735 isl_union_set *local_sizes;
736 struct ppcg_extract_size_data data = { type, NULL };
738 if (!sizes)
739 return NULL;
741 space = isl_union_map_get_space(sizes);
742 space = isl_space_set_from_params(space);
743 space = isl_space_add_dims(space, isl_dim_set, 1);
744 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
745 dom = isl_set_universe(space);
746 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
748 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
749 isl_union_map_copy(sizes));
750 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
751 isl_union_set_free(local_sizes);
752 return data.res;
755 /* Given a singleton set, extract the first (at most *len) elements
756 * of the single integer tuple into *sizes and update *len if needed.
758 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
760 int i;
761 int dim;
763 if (!set)
764 return;
766 dim = isl_set_dim(set, isl_dim_set);
767 if (dim < *len)
768 *len = dim;
770 for (i = 0; i < *len; ++i) {
771 isl_val *v;
773 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
774 assert(v);
776 sizes[i] = isl_val_get_num_si(v);
777 isl_val_free(v);
780 isl_set_free(set);
783 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
784 * if the option debug->dump_sizes is set.
786 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
787 int *sizes, int len)
789 int i;
790 isl_space *space;
791 isl_map *map;
793 if (!gen->options->debug->dump_sizes)
794 return;
796 space = isl_union_map_get_space(gen->used_sizes);
797 space = isl_space_set_from_params(space);
798 space = isl_space_add_dims(space, isl_dim_set, 1);
799 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
800 space = isl_space_from_domain(space);
801 space = isl_space_add_dims(space, isl_dim_out, len);
802 space = isl_space_set_tuple_name(space, isl_dim_out, type);
804 map = isl_map_universe(space);
805 map = isl_map_fix_si(map, isl_dim_in, 0, id);
806 for (i = 0; i < len; ++i)
807 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
809 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
812 /* Extract user specified "tile" sizes from the "sizes" command line option,
813 * defaulting to option->tile_size in each dimension.
814 * Add the effectively used sizes to gen->used_sizes.
816 static void read_tile_sizes(struct gpu_gen *gen)
818 int n;
819 isl_set *size;
821 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
822 assert(gen->tile_size);
823 for (n = 0; n < gen->tile_len; ++n)
824 gen->tile_size[n] = gen->options->tile_size;
826 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
827 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
828 set_used_sizes(gen, "tile", gen->kernel_id,
829 gen->tile_size, gen->tile_len);
831 if (gen->n_parallel > gen->tile_len)
832 gen->n_parallel = gen->tile_len;
835 /* Extract user specified "block" sizes from the "sizes" command line option,
836 * after filling in some potentially useful defaults.
837 * Add the effectively used sizes to gen->used_sizes.
839 static void read_block_sizes(struct gpu_gen *gen)
841 int n;
842 isl_set *size;
844 n = gen->n_parallel;
845 gen->n_block = (n <= 3) ? n : 3;
846 switch (gen->n_block) {
847 case 1:
848 gen->block_dim[0] = 512;
849 break;
850 case 2:
851 gen->block_dim[0] = 32;
852 gen->block_dim[1] = 16;
853 break;
854 default:
855 gen->block_dim[0] = 32;
856 gen->block_dim[1] = 4;
857 gen->block_dim[2] = 4;
858 break;
861 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
862 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
863 set_used_sizes(gen, "block", gen->kernel_id,
864 gen->block_dim, gen->n_block);
867 /* Extract user specified "grid" sizes from the "sizes" command line option,
868 * after filling in some potentially useful defaults.
869 * Add the effectively used sizes to gen->used_sizes.
871 static void read_grid_sizes(struct gpu_gen *gen)
873 int n = gen->n_parallel;
874 isl_set *size;
876 gen->n_grid = (n <= 2) ? n : 2;
877 switch (gen->n_grid) {
878 case 1:
879 gen->grid_dim[0] = 32768;
880 break;
881 default:
882 gen->grid_dim[0] = 256;
883 gen->grid_dim[1] = 256;
884 break;
887 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
888 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
889 set_used_sizes(gen, "grid", gen->kernel_id, gen->grid_dim, gen->n_grid);
892 /* Extract user specified sizes from the "sizes" command line option
893 * after filling in some potentially useful defaults.
895 static void read_sizes(struct gpu_gen *gen)
897 read_tile_sizes(gen);
898 read_block_sizes(gen);
899 read_grid_sizes(gen);
902 static void *free_stmts(struct gpu_stmt *stmts, int n)
904 int i;
906 if (!stmts)
907 return NULL;
909 for (i = 0; i < n; ++i) {
910 struct gpu_stmt_access *access, *next;
912 for (access = stmts[i].accesses; access; access = next) {
913 next = access->next;
914 isl_id_free(access->ref_id);
915 isl_map_free(access->access);
916 isl_map_free(access->tagged_access);
917 free(access);
920 isl_id_free(stmts[i].id);
922 free(stmts);
924 return NULL;
927 /* Construct a map from a domain of dimensionality "len"
928 * to a domain of dimensionality "len" + "tile_len" that tiles
929 * the "tile_len" coordinates starting at "first".
930 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
931 * "dim" prescribes the parameters.
933 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
934 int first, int tile_len, int *tile_size)
936 int i;
937 isl_basic_map *bmap;
938 isl_constraint *c;
939 isl_local_space *ls;
941 dim = isl_space_add_dims(dim, isl_dim_in, len);
942 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
943 bmap = isl_basic_map_universe(isl_space_copy(dim));
944 ls = isl_local_space_from_space(dim);
946 for (i = 0; i < len - tile_len; ++i) {
947 int j = i < first ? i : i + tile_len;
948 int k = i < first ? i : i + 2 * tile_len;
950 c = isl_equality_alloc(isl_local_space_copy(ls));
951 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
952 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
953 bmap = isl_basic_map_add_constraint(bmap, c);
956 for (i = 0; i < tile_len; ++i) {
957 c = isl_equality_alloc(isl_local_space_copy(ls));
958 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
959 first + i, -1);
960 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
961 first + i, tile_size[i]);
962 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
963 first + i + tile_len, 1);
964 bmap = isl_basic_map_add_constraint(bmap, c);
966 c = isl_inequality_alloc(isl_local_space_copy(ls));
967 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
968 first + i + tile_len, 1);
969 bmap = isl_basic_map_add_constraint(bmap, c);
971 c = isl_inequality_alloc(isl_local_space_copy(ls));
972 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
973 first + i + tile_len, -1);
974 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
975 bmap = isl_basic_map_add_constraint(bmap, c);
978 isl_local_space_free(ls);
980 return isl_map_from_basic_map(bmap);
983 /* Construct a map from a domain of dimensionality "len"
984 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
985 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
986 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
987 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
988 * that are projected out at the end.
989 * "dim" prescribes the parameters.
991 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
992 int first, int wrap_len, int *wrap_size)
994 int i;
995 isl_basic_map *bmap;
996 isl_constraint *c;
997 isl_local_space *ls;
999 dim = isl_space_add_dims(dim, isl_dim_in, len);
1000 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
1001 bmap = isl_basic_map_universe(isl_space_copy(dim));
1002 ls = isl_local_space_from_space(dim);
1004 for (i = 0; i < len; ++i) {
1005 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
1007 c = isl_equality_alloc(isl_local_space_copy(ls));
1008 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
1009 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
1010 bmap = isl_basic_map_add_constraint(bmap, c);
1013 for (i = 0; i < wrap_len; ++i) {
1014 c = isl_equality_alloc(isl_local_space_copy(ls));
1015 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1016 first + i, -1);
1017 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1018 first + wrap_len + i, 1);
1019 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1020 first + 2 * wrap_len + i, wrap_size[i]);
1021 bmap = isl_basic_map_add_constraint(bmap, c);
1023 c = isl_inequality_alloc(isl_local_space_copy(ls));
1024 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1025 first + wrap_len + i, 1);
1026 bmap = isl_basic_map_add_constraint(bmap, c);
1028 c = isl_inequality_alloc(isl_local_space_copy(ls));
1029 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1030 first + wrap_len + i, -1);
1031 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
1032 bmap = isl_basic_map_add_constraint(bmap, c);
1035 isl_local_space_free(ls);
1037 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
1038 first + 2 * wrap_len, wrap_len);
1040 return isl_map_from_basic_map(bmap);
1043 /* Add "n" parameters named prefix%d.
1045 static __isl_give isl_set *add_params( __isl_take isl_set *set,
1046 int n, const char *prefix)
1048 int i;
1049 unsigned nparam;
1050 char name[20];
1052 nparam = isl_set_dim(set, isl_dim_param);
1053 set = isl_set_add_dims(set, isl_dim_param, n);
1055 for (i = 0; i < n; ++i) {
1056 snprintf(name, sizeof(name), "%s%d", prefix, i);
1057 set = isl_set_set_dim_name(set, isl_dim_param,
1058 nparam + i, name);
1061 return set;
1064 /* Equate the "n" dimensions of "set" starting at "first" to
1065 * freshly created parameters named prefix%d.
1067 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
1068 int first, int n, const char *prefix)
1070 int i;
1071 unsigned nparam;
1073 nparam = isl_set_dim(set, isl_dim_param);
1075 set = add_params(set, n, prefix);
1077 for (i = 0; i < n; ++i)
1078 set = isl_set_equate(set, isl_dim_param, nparam + i,
1079 isl_dim_set, first + i);
1081 return set;
1084 /* Given a parameter space "space", create a set of dimension "len"
1085 * of which the "n" dimensions starting at "first" are equated to
1086 * freshly created parameters named prefix%d.
1088 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
1089 int len, int first, int n, const char *prefix)
1091 isl_set *set;
1093 space = isl_space_set_from_params(space);
1094 space = isl_space_add_dims(space, isl_dim_set, len);
1095 set = isl_set_universe(space);
1097 return parametrize(set, first, n, prefix);
1100 /* Tile the B loops over the tile sizes and then tile/wrap
1101 * the T1 loops over the blocks.
1103 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
1104 __isl_take isl_union_map *sched)
1106 isl_space *dim;
1107 isl_map *tiling, *block_tiling;
1109 dim = isl_union_map_get_space(sched);
1110 tiling = tile(isl_space_copy(dim), gen->untiled_len,
1111 gen->tile_first, gen->tile_len, gen->tile_size);
1113 if (gen->options->wrap)
1114 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
1115 gen->tile_first, gen->n_grid, gen->grid_dim);
1116 else
1117 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
1118 gen->tile_first, gen->n_grid, gen->grid_dim);
1120 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
1122 tiling = isl_map_apply_range(tiling, block_tiling);
1124 sched = isl_union_map_apply_range(sched,
1125 isl_union_map_from_map(tiling));
1127 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1129 return sched;
1132 /* Equate the "T1P" iterators in the tiled schedule "sched"
1133 * to the block dimensions.
1135 static __isl_give isl_union_map *parametrize_tiled_schedule(
1136 struct gpu_gen *gen, __isl_take isl_union_map *sched)
1138 isl_space *dim;
1139 isl_set *par;
1141 dim = isl_union_map_get_space(sched);
1142 par = parametrization(dim, gen->tiled_len,
1143 gen->tile_first + gen->n_grid, gen->n_grid, "b");
1144 sched = isl_union_map_intersect_range(sched,
1145 isl_union_set_from_set(par));
1147 return sched;
1150 /* Tile/wrap the P1 loops over the threads.
1152 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
1153 __isl_take isl_union_map *sched)
1155 isl_space *dim;
1156 isl_map *tiling;
1157 isl_set *par;
1159 dim = isl_union_map_get_space(sched);
1161 if (gen->options->wrap)
1162 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
1163 gen->shared_len, gen->n_block, gen->block_dim);
1164 else
1165 tiling = tile(isl_space_copy(dim), gen->tiled_len,
1166 gen->shared_len, gen->n_block, gen->block_dim);
1167 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
1169 sched = isl_union_map_apply_range(sched,
1170 isl_union_map_from_map(tiling));
1172 par = parametrization(dim, gen->thread_tiled_len,
1173 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1174 gen->n_block, "t");
1175 sched = isl_union_map_intersect_range(sched,
1176 isl_union_set_from_set(par));
1178 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1180 return sched;
1183 /* If the user asked for it, scale the shared memory tile loops
1184 * (T1T and T2) of "sched" by gen->tile_size[i].
1185 * If we are not performing "wrapping", then additionally scale the T1P
1186 * loops by gen->grid_dim[i].
1188 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
1189 __isl_take isl_union_map *sched)
1191 int i;
1192 isl_space *dim;
1193 isl_basic_map *scale;
1194 isl_constraint *c;
1195 isl_local_space *ls;
1197 if (!gen->options->scale_tile_loops)
1198 return sched;
1200 dim = isl_union_map_get_space(sched);
1201 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
1202 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
1203 scale = isl_basic_map_universe(isl_space_copy(dim));
1204 ls = isl_local_space_from_space(dim);
1206 for (i = 0; i < gen->tiled_len; ++i) {
1207 int f = 1;
1209 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
1210 f = gen->tile_size[i - gen->tile_first];
1211 if (!gen->options->wrap)
1212 f *= gen->grid_dim[i - gen->tile_first];
1213 } else if (i >= gen->tile_first + gen->n_grid &&
1214 i < gen->tile_first + gen->n_grid + gen->tile_len) {
1215 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
1218 c = isl_equality_alloc(isl_local_space_copy(ls));
1219 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1220 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1221 scale = isl_basic_map_add_constraint(scale, c);
1224 isl_local_space_free(ls);
1226 sched = isl_union_map_apply_range(sched,
1227 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1229 return sched;
1232 /* If we are not performing "wrapping" and if the user asked for it,
1233 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1235 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1236 __isl_take isl_union_map *sched)
1238 int i;
1239 isl_space *dim;
1240 isl_basic_map *scale;
1241 isl_constraint *c;
1242 isl_local_space *ls;
1244 if (gen->options->wrap)
1245 return sched;
1246 if (!gen->options->scale_tile_loops)
1247 return sched;
1249 dim = isl_union_map_get_space(sched);
1250 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1251 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1252 scale = isl_basic_map_universe(isl_space_copy(dim));
1253 ls = isl_local_space_from_space(dim);
1255 for (i = 0; i < gen->thread_tiled_len; ++i) {
1256 int f = 1;
1258 if (i >= gen->shared_len &&
1259 i < gen->shared_len + gen->n_block)
1260 f = gen->block_dim[i - gen->shared_len];
1262 c = isl_equality_alloc(isl_local_space_copy(ls));
1263 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1264 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1265 scale = isl_basic_map_add_constraint(scale, c);
1268 isl_local_space_free(ls);
1270 sched = isl_union_map_apply_range(sched,
1271 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1273 return sched;
1276 /* If we are not performing "wrapping" and if the user asked for it,
1277 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1279 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1280 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1282 int i;
1283 isl_space *dim;
1284 isl_basic_map *scale;
1285 isl_constraint *c;
1286 isl_local_space *ls;
1288 if (gen->options->wrap)
1289 return sched;
1290 if (!gen->options->scale_tile_loops)
1291 return sched;
1293 dim = isl_union_map_get_space(sched);
1294 dim = isl_space_add_dims(dim, isl_dim_in, len);
1295 dim = isl_space_add_dims(dim, isl_dim_out, len);
1296 scale = isl_basic_map_universe(isl_space_copy(dim));
1297 ls = isl_local_space_from_space(dim);
1299 for (i = 0; i < len; ++i) {
1300 int f = 1;
1302 if (i >= first && i < first + n_tile)
1303 f = gen->kernel->block_dim[i - first];
1305 c = isl_equality_alloc(isl_local_space_copy(ls));
1306 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1307 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1308 scale = isl_basic_map_add_constraint(scale, c);
1311 isl_local_space_free(ls);
1313 sched = isl_union_map_apply_range(sched,
1314 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1316 return sched;
1319 /* Add "len" parameters p[i] called prefix%d,
1320 * with bounds to 0 <= p[i] < size[i].
1322 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1323 int len, int *size, const char *prefix)
1325 int i;
1326 unsigned nparam;
1327 isl_space *dim;
1328 isl_basic_set *bset;
1329 isl_constraint *c;
1330 isl_local_space *ls;
1331 char name[20];
1333 nparam = isl_set_dim(set, isl_dim_param);
1334 set = isl_set_add_dims(set, isl_dim_param, len);
1336 for (i = 0; i < len; ++i) {
1337 snprintf(name, sizeof(name), "%s%d", prefix, i);
1338 set = isl_set_set_dim_name(set, isl_dim_param,
1339 nparam + i, name);
1342 dim = isl_set_get_space(set);
1343 bset = isl_basic_set_universe(isl_space_copy(dim));
1344 ls = isl_local_space_from_space(dim);
1346 for (i = 0; i < len; ++i) {
1347 c = isl_inequality_alloc(isl_local_space_copy(ls));
1348 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1349 nparam + i, 1);
1350 bset = isl_basic_set_add_constraint(bset, c);
1352 c = isl_inequality_alloc(isl_local_space_copy(ls));
1353 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1354 nparam + i, -1);
1355 c = isl_constraint_set_constant_si(c, size[i] - 1);
1356 bset = isl_basic_set_add_constraint(bset, c);
1359 isl_local_space_free(ls);
1361 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1364 /* Add "len" parameters p[i] called prefix%d and intersect "set"
1365 * with
1367 * { : 0 <= p[i] < size[i] }
1369 * or an overapproximation.
1371 static __isl_give isl_set *add_bounded_parameters_dynamic(
1372 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1373 const char *prefix)
1375 int i, len;
1376 unsigned nparam;
1377 isl_space *space;
1378 isl_local_space *ls;
1379 char name[20];
1381 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1382 nparam = isl_set_dim(set, isl_dim_param);
1383 set = isl_set_add_dims(set, isl_dim_param, len);
1385 for (i = 0; i < len; ++i) {
1386 snprintf(name, sizeof(name), "%s%d", prefix, i);
1387 set = isl_set_set_dim_name(set, isl_dim_param,
1388 nparam + i, name);
1391 space = isl_space_params(isl_set_get_space(set));
1392 ls = isl_local_space_from_space(space);
1393 for (i = 0; i < len; ++i) {
1394 isl_pw_aff *param, *size_i, *zero;
1395 isl_set *bound;
1397 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1398 isl_dim_param, nparam + i);
1400 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1401 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1402 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
1403 set = isl_set_intersect_params(set, bound);
1405 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1406 bound = isl_pw_aff_ge_set(param, zero);
1407 set = isl_set_intersect_params(set, bound);
1409 isl_local_space_free(ls);
1411 return set;
1414 /* Construct a map from an access to group->array to the corresponding
1415 * shared/private memory tile.
1416 * The map is of the form
1418 * { [D[i] -> A[a]] -> T[t] }
1420 * where D represents the initial shared_len dimensions
1421 * of the computed schedule.
1423 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1425 struct gpu_array_tile *tile;
1426 isl_multi_aff *tiling;
1428 tile = group->private_tile;
1429 if (!tile)
1430 tile = group->shared_tile;
1432 tiling = isl_multi_aff_copy(tile->tiling);
1434 return isl_map_from_multi_aff(tiling);
1437 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1439 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1440 unsigned pos)
1442 isl_val *v;
1443 int fixed;
1445 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1446 if (!v)
1447 return -1;
1448 fixed = isl_val_is_int(v);
1449 isl_val_free(v);
1451 return fixed;
1454 /* Given a schedule that iterates over all elements in a piece of an array,
1455 * perform tiling/wrapping over the threads.
1457 * In particular, we tile the final iterators so that the final thread
1458 * dimension runs over the final array dimension.
1459 * However, if those final iterators have only a single iteration,
1460 * we try to tile earlier iterators instead.
1462 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1463 __isl_take isl_map *sched)
1465 isl_space *dim;
1466 isl_union_map *usched;
1467 isl_map *tiling;
1468 isl_set *par;
1469 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1470 int n_tile;
1471 int first;
1473 n_tile = gen->kernel->n_block;
1474 if (n_tile > nvar) {
1475 int i;
1476 sched = isl_map_insert_dims(sched,
1477 isl_dim_out, 0, n_tile - nvar);
1478 for (i = 0; i < n_tile - nvar; ++i)
1479 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1480 nvar = n_tile;
1483 first = nvar - n_tile;
1485 for (; first > 0; first --)
1486 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1487 break;
1489 dim = isl_map_get_space(sched);
1490 dim = isl_space_params(dim);
1491 if (gen->options->wrap)
1492 tiling = wrap(isl_space_copy(dim), nvar, first,
1493 n_tile, gen->kernel->block_dim);
1494 else
1495 tiling = tile(isl_space_copy(dim), nvar, first,
1496 n_tile, gen->kernel->block_dim);
1497 sched = isl_map_apply_range(sched, tiling);
1499 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1500 sched = isl_map_intersect_range(sched, par);
1502 usched = isl_union_map_from_map(sched);
1503 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1504 first, n_tile);
1505 sched = isl_map_from_union_map(usched);
1507 return sched;
1510 /* Return the union of all read (read = 1) and/or write (write = 1)
1511 * access relations in the group.
1513 static __isl_give isl_union_map *group_access_relation(
1514 struct gpu_array_ref_group *group, int read, int write)
1516 int i;
1517 isl_union_map *access;
1519 access = isl_union_map_empty(isl_map_get_space(group->access));
1520 for (i = 0; i < group->n_ref; ++i) {
1521 isl_map *map_i;
1523 if (!((read && group->refs[i]->read) ||
1524 (write && group->refs[i]->write)))
1525 continue;
1526 map_i = isl_map_copy(group->refs[i]->access);
1527 access = isl_union_map_union(access,
1528 isl_union_map_from_map(map_i));
1531 return access;
1534 /* Return the union of all tagged access relations in the group.
1536 static __isl_give isl_union_map *group_tagged_access_relation(
1537 struct gpu_array_ref_group *group)
1539 int i;
1540 isl_union_map *access;
1542 access = isl_union_map_empty(isl_map_get_space(group->access));
1543 for (i = 0; i < group->n_ref; ++i) {
1544 isl_map *map_i;
1546 map_i = isl_map_copy(group->refs[i]->tagged_access);
1547 access = isl_union_map_union(access,
1548 isl_union_map_from_map(map_i));
1551 return access;
1554 /* Return the extent of "array", recomputed from the bounds.
1555 * The recomputed extent may be simpler than the original extent.
1557 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1559 int i;
1560 isl_id *id;
1561 isl_space *space;
1562 isl_local_space *ls;
1563 isl_set *extent;
1565 id = isl_set_get_tuple_id(array->extent);
1566 space = isl_set_get_space(array->extent);
1567 extent = isl_set_universe(isl_space_copy(space));
1568 ls = isl_local_space_from_space(space);
1569 for (i = 0; i < array->n_index; ++i) {
1570 isl_pw_aff *bound;
1571 isl_aff *aff;
1572 isl_pw_aff *index;
1573 isl_set *lt;
1575 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1577 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1578 isl_dim_set, i);
1579 index = isl_pw_aff_from_aff(aff);
1580 bound = isl_pw_aff_copy(array->bound[i]);
1581 bound = isl_pw_aff_from_range(bound);
1582 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1583 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1584 isl_id_copy(id));
1585 lt = isl_pw_aff_lt_set(index, bound);
1586 extent = isl_set_intersect(extent, lt);
1588 isl_local_space_free(ls);
1589 isl_id_free(id);
1591 return extent;
1594 /* Return a map from the first shared_len dimensions of the computed
1595 * schedule to the array tile in
1596 * global memory that corresponds to the shared memory copy.
1598 * In particular, return a map
1600 * { D[i] -> A[a] }
1602 * with constraints
1604 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1606 * and
1608 * 0 <= a <= array_size - 1 (2)
1610 * Note that if some stride has been detected (i.e., when
1611 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1612 * to the shifted and scaled down version.
1614 * Constraints (1) are obtained by mapping the size constraints on the
1615 * shared/private memory tile back to the access relation.
1616 * Constraints (2) are obtained from the (recomputed) extent.
1618 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1620 int i;
1621 int n_index = group->array->n_index;
1622 isl_map *tile;
1623 isl_space *space;
1624 isl_set *local;
1625 isl_set *extent;
1627 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1628 space = isl_space_range(space);
1629 local = isl_set_universe(space);
1630 for (i = 0; i < n_index; ++i) {
1631 isl_val *bound;
1633 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1634 bound = isl_val_copy(group->shared_tile->bound[i].size);
1635 bound = isl_val_sub_ui(bound, 1);
1636 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1638 local = isl_set_preimage_multi_aff(local,
1639 isl_multi_aff_copy(group->shared_tile->tiling));
1640 tile = isl_set_unwrap(local);
1641 extent = array_extent(group->array);
1642 tile = isl_map_intersect_range(tile, extent);
1644 return tile;
1647 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1648 * return the corresponding mapping from the AST schedule to
1649 * to the first shared_len dimensions of the schedule computed by PPCG.
1651 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1652 __isl_take isl_pw_multi_aff *iterator_map)
1654 isl_union_map *umap;
1655 isl_space *space;
1656 isl_map *map, *sched;;
1658 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1659 space = isl_space_from_domain(space);
1660 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1662 umap = isl_union_map_copy(gen->shared_sched);
1663 umap = isl_union_map_apply_range(umap,
1664 isl_union_map_copy(gen->shared_proj));
1665 map = isl_union_map_extract_map(umap, space);
1666 isl_union_map_free(umap);
1668 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1669 sched = isl_map_detect_equalities(sched);
1671 return isl_pw_multi_aff_from_map(sched);
1674 /* Set unroll[j] if the input dimension j is involved in
1675 * the index expression represented by ma.
1677 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1678 void *user)
1680 int i, j;
1681 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1682 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1683 int *unroll = user;
1685 for (i = 0; i < n_out; ++i) {
1686 isl_aff *aff;
1688 aff = isl_multi_aff_get_aff(ma, i);
1689 for (j = 0; j < n_in; ++j)
1690 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1691 unroll[j] = 1;
1692 isl_aff_free(aff);
1695 isl_set_free(set);
1696 isl_multi_aff_free(ma);
1697 return 0;
1700 /* Given an array pos mapping input dimensions to the corresponding
1701 * output dimension, construct the corresponding map.
1703 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1704 int *pos, int len)
1706 int i;
1707 isl_constraint *c;
1708 isl_basic_map *bmap;
1709 isl_local_space *ls;
1711 dim = isl_space_add_dims(dim, isl_dim_in, len);
1712 dim = isl_space_add_dims(dim, isl_dim_out, len);
1713 bmap = isl_basic_map_universe(isl_space_copy(dim));
1714 ls = isl_local_space_from_space(dim);
1716 for (i = 0; i < len; ++i) {
1717 c = isl_equality_alloc(isl_local_space_copy(ls));
1718 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1719 -1);
1720 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1722 bmap = isl_basic_map_add_constraint(bmap, c);
1724 isl_local_space_free(ls);
1726 return isl_map_from_basic_map(bmap);
1729 /* Remove the private tiles from all array reference groups,
1730 * except for the groups of arrays that are marked force_private.
1732 static void remove_private_tiles(struct gpu_gen *gen)
1734 int i, j;
1736 for (i = 0; i < gen->prog->n_array; ++i) {
1737 struct gpu_array_info *array = &gen->prog->array[i];
1739 if (array->force_private)
1740 continue;
1742 for (j = 0; j < array->n_group; ++j) {
1743 struct gpu_array_ref_group *group = array->groups[j];
1745 group->private_tile = free_tile(group->private_tile);
1750 /* Find all loops involved in any of the index expressions for any of
1751 * the private accesses, move them innermost and then mark them as
1752 * requiring unrolling by setting gen->first_unroll.
1753 * The loops involved should all be parallel because of the checks
1754 * we performed in check_private_group_access. Moving them innermost
1755 * is therefore a valid transformation.
1757 * If any of the arrays are marked force_private, however, then
1758 * those loops may not be parallel with respect to the marked arrays.
1759 * If any of the loops would have to be moved innermost for the
1760 * (non forced) private accesses and if there are any force_private
1761 * arrays, then we revert the decision to map the selected arrays
1762 * to private memory. An alternative solution would be to expand
1763 * the force_private arrays.
1765 * Loops up to gen->shared_len are generated before the mapping to
1766 * threads is applied. They should therefore be ignored.
1768 * We compute the hidden equalities of the schedule first
1769 * since we will need them in our calls to isl_pw_multi_aff_from_map
1770 * and because we want to make sure that the same equalities
1771 * are also available to the code generator.
1773 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1774 __isl_take isl_union_map *sched)
1776 int i, j;
1777 int unroll[gen->thread_tiled_len];
1778 int perm[gen->thread_tiled_len];
1779 isl_space *dim;
1780 isl_map *permute;
1781 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1783 gen->first_unroll = -1;
1785 sched = isl_union_map_detect_equalities(sched);
1786 for (i = 0; i < gen->thread_tiled_len; ++i)
1787 unroll[i] = 0;
1788 for (i = 0; i < gen->prog->n_array; ++i) {
1789 struct gpu_array_info *array = &gen->prog->array[i];
1791 for (j = 0; j < array->n_group; ++j) {
1792 isl_union_map *access;
1793 isl_map *acc;
1794 isl_pw_multi_aff *pma;
1796 if (!array->groups[j]->private_tile)
1797 continue;
1799 access = group_access_relation(array->groups[j], 1, 1);
1800 access = isl_union_map_apply_domain(access,
1801 isl_union_map_copy(sched));
1803 acc = isl_map_from_union_map(access);
1804 pma = isl_pw_multi_aff_from_map(acc);
1805 isl_pw_multi_aff_foreach_piece(pma,
1806 &check_unroll, unroll);
1808 isl_pw_multi_aff_free(pma);
1812 for (i = gen->shared_len; i < len; ++i)
1813 if (unroll[i])
1814 break;
1816 if (i >= len)
1817 return sched;
1819 for (i = len; i < gen->thread_tiled_len; ++i)
1820 if (unroll[i])
1821 return sched;
1823 if (gen->any_force_private) {
1824 remove_private_tiles(gen);
1825 return sched;
1828 j = 0;
1829 for (i = 0; i < gen->shared_len; ++i)
1830 perm[i] = j++;
1831 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1832 if (!unroll[i])
1833 perm[i] = j++;
1834 gen->first_unroll = j - gen->shared_len;
1835 for (i = gen->shared_len; i < len; ++i)
1836 if (unroll[i])
1837 perm[i] = j++;
1839 dim = isl_union_map_get_space(sched);
1840 permute = permutation(dim, perm, gen->thread_tiled_len);
1841 sched = isl_union_map_apply_range(sched,
1842 isl_union_map_from_map(permute));
1844 return sched;
1847 /* Given a constraint
1849 * a(p,i) + j = g f(e)
1851 * or -a(p,i) - j = g f(e) if sign < 0,
1852 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1853 * a(p,i) is assumed to be an expression in only the parameters
1854 * and the input dimensions.
1856 static void extract_stride(__isl_keep isl_constraint *c,
1857 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1859 int i;
1860 isl_val *v;
1861 isl_space *space;
1862 unsigned nparam;
1863 unsigned nvar;
1864 isl_aff *aff;
1866 isl_val_free(bound->stride);
1867 bound->stride = isl_val_copy(stride);
1869 space = isl_constraint_get_space(c);
1870 space = isl_space_domain(space);
1872 nparam = isl_space_dim(space, isl_dim_param);
1873 nvar = isl_space_dim(space, isl_dim_set);
1875 v = isl_constraint_get_constant_val(c);
1876 if (sign < 0)
1877 v = isl_val_neg(v);
1878 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1879 aff = isl_aff_set_constant_val(aff, v);
1881 for (i = 0; i < nparam; ++i) {
1882 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1883 continue;
1884 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1885 if (sign < 0)
1886 v = isl_val_neg(v);
1887 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1890 for (i = 0; i < nvar; ++i) {
1891 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1892 continue;
1893 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1894 if (sign < 0)
1895 v = isl_val_neg(v);
1896 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1899 bound->shift = aff;
1902 /* Given an equality constraint of a map with a single output dimension j,
1903 * check if the constraint is of the form
1905 * a(p,i) + j = g f(e)
1907 * with a(p,i) an expression in the parameters and input dimensions
1908 * and f(e) an expression in the existentially quantified variables.
1909 * If so, and if g is larger than any such g from a previously considered
1910 * constraint, then call extract_stride to record the stride information
1911 * in bound.
1913 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1915 int i;
1916 isl_ctx *ctx;
1917 isl_val *v;
1918 unsigned n_div;
1919 struct gpu_array_bound *bound = user;
1921 ctx = isl_constraint_get_ctx(c);
1922 n_div = isl_constraint_dim(c, isl_dim_div);
1923 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1925 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1926 int s = isl_val_sgn(v);
1927 isl_val *stride = isl_val_zero(ctx);
1929 isl_val_free(v);
1930 for (i = 0; i < n_div; ++i) {
1931 v = isl_constraint_get_coefficient_val(c,
1932 isl_dim_div, i);
1933 stride = isl_val_gcd(stride, v);
1935 if (!isl_val_is_zero(stride) &&
1936 isl_val_gt(stride, bound->stride))
1937 extract_stride(c, bound, stride, s);
1939 isl_val_free(stride);
1940 } else
1941 isl_val_free(v);
1943 isl_constraint_free(c);
1944 return 0;
1947 /* Given contraints on an array index i, check if we can find
1948 * a shift a(p) and a stride g such that
1950 * a(p) + i = 0 mod g
1952 * If so, record the information in bound and apply the mapping
1953 * i -> (i + a(p))/g to the array index in bounds and return
1954 * the new constraints.
1955 * If not, simply return the original constraints.
1957 * If bounds is a subset of the space
1959 * D -> i
1961 * then the bound recorded in bound->shift is of the form
1963 * D -> s(D)
1965 * with s(D) equal to a(p) above.
1966 * The mapping recorded in bound->shift_map is of the form
1968 * [D -> i] -> [D -> (i + S(D))/g]
1970 * This mapping is computed as follows.
1971 * We first introduce "i" in the domain through precomposition
1972 * with [D -> i] -> D obtaining
1974 * [D -> i] -> s(D)
1976 * Adding [D -> i] -> i produces
1978 * [D -> i] -> i + s(D)
1980 * and the domain product with [D -> i] -> D yields
1982 * [D -> i] -> [D -> i + s(D)]
1984 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1986 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1987 __isl_take isl_basic_map *bounds)
1989 isl_space *space;
1990 isl_basic_map *hull;
1991 isl_basic_map *shift, *id, *bmap, *scale;
1992 isl_basic_set *bset;
1993 isl_aff *aff;
1995 bound->stride = NULL;
1997 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1999 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
2001 isl_basic_map_free(hull);
2003 if (!bound->stride)
2004 return bounds;
2006 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
2007 space = isl_basic_map_get_space(bounds);
2008 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
2009 shift = isl_basic_map_apply_range(bmap, shift);
2010 space = isl_basic_map_get_space(bounds);
2011 id = isl_basic_map_range_map(isl_basic_map_universe(space));
2012 shift = isl_basic_map_sum(id, shift);
2013 space = isl_basic_map_get_space(bounds);
2014 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
2015 shift = isl_basic_map_range_product(id, shift);
2017 space = isl_space_domain(isl_basic_map_get_space(bounds));
2018 id = isl_basic_map_identity(isl_space_map_from_set(space));
2019 space = isl_space_range(isl_basic_map_get_space(bounds));
2020 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2021 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2022 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
2023 scale = isl_basic_map_from_aff(aff);
2024 scale = isl_basic_map_product(id, scale);
2026 bound->shift_map = isl_basic_map_apply_range(shift, scale);
2027 bmap = isl_basic_map_copy(bound->shift_map);
2028 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
2029 bounds = isl_basic_set_unwrap(bset);
2031 return bounds;
2034 /* Data used in compute_array_dim_size and compute_size_in_direction.
2036 * pos is the position of the variable representing the array index,
2037 * i.e., the variable for which want to compute the size. This variable
2038 * is also the last variable in the set.
2040 struct gpu_size_info {
2041 isl_basic_set *bset;
2042 struct gpu_array_bound *bound;
2043 int pos;
2046 /* Given a constraint from the basic set describing the bounds on
2047 * an array index, check if it is a lower bound, say m i >= b(x), and,
2048 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
2049 * upper bound. If so, and if this bound is smaller than any bound
2050 * derived from earlier constraints, set the size to this bound on
2051 * the expression and the lower bound to ceil(b(x)/m).
2053 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
2055 struct gpu_size_info *size = user;
2056 unsigned nparam;
2057 unsigned n_div;
2058 isl_val *v;
2059 isl_aff *aff;
2060 isl_aff *lb;
2062 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
2063 n_div = isl_constraint_dim(c, isl_dim_div);
2065 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
2066 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
2067 isl_constraint_free(c);
2068 return 0;
2071 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
2072 aff = isl_aff_ceil(aff);
2074 lb = isl_aff_copy(aff);
2076 aff = isl_aff_neg(aff);
2077 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
2079 v = isl_basic_set_max_val(size->bset, aff);
2080 isl_aff_free(aff);
2082 if (isl_val_is_int(v)) {
2083 v = isl_val_add_ui(v, 1);
2084 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
2085 isl_val_free(size->bound->size);
2086 size->bound->size = isl_val_copy(v);
2087 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
2088 isl_aff_free(size->bound->lb);
2089 size->bound->lb = isl_aff_copy(lb);
2092 isl_val_free(v);
2093 isl_aff_free(lb);
2095 isl_constraint_free(c);
2097 return 0;
2100 /* Given a basic map "bounds" that maps parameters and input dimensions
2101 * to a single output dimension, look for an expression in the parameters
2102 * and input dimensions such that the range of the output dimension shifted
2103 * by this expression is a constant.
2105 * In particular, we currently only consider lower bounds on the output
2106 * dimension as candidate expressions.
2108 static int compute_array_dim_size(struct gpu_array_bound *bound,
2109 __isl_take isl_basic_map *bounds)
2111 struct gpu_size_info size;
2113 bounds = isl_basic_map_detect_equalities(bounds);
2114 bounds = check_stride(bound, bounds);
2116 bound->size = NULL;
2117 bound->lb = NULL;
2119 size.bound = bound;
2120 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2121 size.bset = isl_basic_map_wrap(bounds);
2122 size.bset = isl_basic_set_flatten(size.bset);
2123 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2124 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2125 &size);
2126 isl_basic_set_free(size.bset);
2128 return bound->size ? 0 : -1;
2131 /* Check if we can find a memory tile for the given array
2132 * based on the given accesses, and if so, put the results in "tile".
2134 * We project the accesses on each index in turn and look for a parametric
2135 * offset such that the size is constant.
2137 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2139 int i;
2141 for (i = 0; i < tile->n; ++i) {
2142 isl_map *access_i;
2143 isl_basic_map *hull;
2145 access_i = isl_map_copy(access);
2146 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2147 access_i = isl_map_project_out(access_i, isl_dim_out,
2148 1, tile->n - (i + 1));
2149 access_i = isl_map_compute_divs(access_i);
2150 hull = isl_map_simple_hull(access_i);
2151 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2152 return 0;
2155 return 1;
2158 /* Construct a map with input the shared tile loops and the loops that
2159 * will be wrapped around the threads that relates these later loops
2160 * to the thread indices and then projects them out.
2162 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2164 isl_map *priv;
2165 isl_map *tiling;
2166 isl_map *proj;
2167 isl_set *par;
2168 isl_space *dim;
2170 dim = isl_union_map_get_space(gen->shared_sched);
2172 if (gen->options->wrap)
2173 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2174 gen->shared_len, gen->n_block, gen->block_dim);
2175 else
2176 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2177 gen->shared_len, gen->n_block, gen->block_dim);
2179 priv = tiling;
2181 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2182 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2183 gen->n_block, "t");
2185 priv = isl_map_align_params(priv, isl_set_get_space(par));
2186 priv = isl_map_intersect_range(priv, par);
2188 dim = isl_map_get_space(priv);
2189 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2190 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2191 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2192 gen->shared_len);
2194 priv = isl_map_apply_range(priv, proj);
2196 return priv;
2199 /* Construct a map from domain_dim to domain_dim that increments
2200 * the dimension at position "pos" and leaves all other dimensions
2201 * constant.
2203 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2205 int i;
2206 int len = isl_space_dim(domain_dim, isl_dim_set);
2207 isl_space *dim;
2208 isl_basic_map *next;
2209 isl_local_space *ls;
2211 dim = isl_space_map_from_set(domain_dim);
2212 next = isl_basic_map_universe(isl_space_copy(dim));
2213 ls = isl_local_space_from_space(dim);
2215 for (i = 0; i < len; ++i) {
2216 isl_constraint *c;
2218 c = isl_equality_alloc(isl_local_space_copy(ls));
2219 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2220 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2221 if (i == pos)
2222 c = isl_constraint_set_constant_si(c, 1);
2223 next = isl_basic_map_add_constraint(next, c);
2226 isl_local_space_free(ls);
2228 return isl_map_from_basic_map(next);
2231 /* Check if the given access is coalesced.
2232 * That is, check whether incrementing the dimension that will get
2233 * wrapped over the last thread index results in incrementing
2234 * the last array index.
2236 * This function is only called for access relations without reuse and
2237 * kernels with at least one block dimension.
2239 static int access_is_coalesced(struct gpu_gen *gen,
2240 __isl_keep isl_union_map *access)
2242 isl_space *dim;
2243 isl_map *access_map;
2244 isl_map *next_thread_x;
2245 isl_map *next_element;
2246 isl_map *map;
2247 int coalesced;
2249 access = isl_union_map_copy(access);
2250 access = isl_union_map_apply_domain(access,
2251 isl_union_map_copy(gen->tiled_sched));
2252 access_map = isl_map_from_union_map(access);
2254 dim = isl_map_get_space(access_map);
2255 dim = isl_space_domain(dim);
2256 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2258 dim = isl_map_get_space(access_map);
2259 dim = isl_space_range(dim);
2260 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2262 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2263 map = isl_map_apply_range(map, access_map);
2265 coalesced = isl_map_is_subset(map, next_element);
2267 isl_map_free(next_element);
2268 isl_map_free(map);
2270 return coalesced;
2273 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2274 * dimensions of the computed schedule, check if it is bijective for
2275 * fixed values of the first gen->shared_len dimensions.
2276 * We perform this check by equating these dimensions to parameters.
2278 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2280 int res;
2281 isl_set *par;
2282 isl_space *space;
2284 access = isl_map_copy(access);
2285 space = isl_space_params(isl_map_get_space(access));
2286 par = parametrization(space, gen->shared_len + gen->n_block,
2287 0, gen->shared_len, "s");
2288 access = isl_map_intersect_domain(access, par);
2289 res = isl_map_is_bijective(access);
2290 isl_map_free(access);
2292 return res;
2295 /* Look for the last shared tile loop that affects the offset of "tile"
2296 * and return the result.
2297 * If there is no such loop, then return the index of the loop
2298 * before the first shared tile loop, in particular gen->tile_first - 1.
2300 static int compute_tile_last_shared(struct gpu_gen *gen,
2301 struct gpu_array_tile *tile)
2303 int i, j;
2305 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2306 for (i = 0; i < tile->n; ++i) {
2307 isl_aff *lb;
2308 isl_aff *shift;
2310 lb = tile->bound[i].lb;
2311 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2312 break;
2314 shift = tile->bound[i].shift;
2315 if (!shift)
2316 continue;
2317 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2318 break;
2320 if (i < tile->n)
2321 break;
2324 return j;
2327 /* Look for the last shared tile loop that affects the offset of the
2328 * shared or private tile and store the result in group->last_shared.
2329 * If there is no such loop, then group->last_shared is set to a value
2330 * before the first shared tile loop, in particular gen->tile_first - 1.
2331 * If there is no tile defined on the array reference group,
2332 * then set group->last_shared to gen->shared_len - 1.
2334 static void set_last_shared(struct gpu_gen *gen,
2335 struct gpu_array_ref_group *group)
2337 struct gpu_array_tile *tile;
2339 group->last_shared = gen->shared_len - 1;
2341 tile = group->private_tile;
2342 if (!tile)
2343 tile = group->shared_tile;
2344 if (!tile)
2345 return;
2347 group->last_shared = compute_tile_last_shared(gen, tile);
2350 /* Compute a privatized copy of all access relations from reference groups that
2351 * are mapped to private memory and store the result in gen->privatization.
2353 * Read-only scalars and arrays containing structures are not mapped
2354 * to private memory.
2356 static void compute_private_access(struct gpu_gen *gen)
2358 int i, j;
2359 isl_union_map *private;
2361 if (!gen->options->use_private_memory)
2362 return;
2364 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2366 for (i = 0; i < gen->prog->n_array; ++i) {
2367 struct gpu_array_info *array = &gen->prog->array[i];
2369 if (gpu_array_is_read_only_scalar(array))
2370 continue;
2371 if (array->has_compound_element)
2372 continue;
2374 for (j = 0; j < array->n_group; ++j) {
2375 if (!array->groups[j]->private_tile)
2376 continue;
2378 private = isl_union_map_union(private,
2379 group_access_relation(array->groups[j], 1, 1));
2383 if (isl_union_map_is_empty(private))
2384 isl_union_map_free(private);
2385 else {
2386 isl_union_map *priv;
2388 private = isl_union_map_apply_domain(private,
2389 isl_union_map_copy(gen->shared_sched));
2390 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2391 private = isl_union_map_apply_domain(private, priv);
2392 gen->private_access = private;
2396 /* Compute the size of the tile specified by "tile"
2397 * in number of elements and return the result.
2399 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2401 int i;
2402 isl_val *size;
2404 size = isl_val_one(ctx);
2406 for (i = 0; i < tile->n; ++i)
2407 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2409 return size;
2412 /* If max_shared_memory is not set to infinity (-1), then make
2413 * sure that the total amount of shared memory required by the
2414 * array reference groups mapped to shared memory is no larger
2415 * than this maximum.
2417 * We apply a greedy approach and discard (keep in global memory)
2418 * those groups that would result in a total memory size that
2419 * is larger than the maximum.
2421 * This function should be called after any function that may
2422 * affect the decision on whether to place a reference group
2423 * in private, shared or global memory.
2425 static void check_shared_memory_bound(struct gpu_gen *gen)
2427 int i, j;
2428 isl_val *left, *size;
2430 if (gen->options->max_shared_memory < 0)
2431 return;
2433 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2435 for (i = 0; i < gen->prog->n_array; ++i) {
2436 struct gpu_array_info *array = &gen->prog->array[i];
2438 for (j = 0; j < array->n_group; ++j) {
2439 struct gpu_array_ref_group *group;
2441 group = array->groups[j];
2442 if (group->private_tile)
2443 continue;
2444 if (!group->shared_tile)
2445 continue;
2447 size = tile_size(gen->ctx, group->shared_tile);
2448 size = isl_val_mul_ui(size, array->size);
2450 if (isl_val_le(size, left)) {
2451 left = isl_val_sub(left, size);
2452 continue;
2454 isl_val_free(size);
2456 group->shared_tile = free_tile(group->shared_tile);
2460 isl_val_free(left);
2463 /* Given a description of an array tile "tile" and the "space"
2465 * { D -> A }
2467 * where D represents the first shared_len schedule dimensions
2468 * and A represents the array, construct an isl_multi_aff
2470 * { [D[i] -> A[a]] -> A'[a'] }
2472 * with A' a scaled down copy of A according to the shifts and strides
2473 * in "tile". In particular,
2475 * a' = (a + shift(i))/stride
2477 * "insert_array" represents
2479 * { [D -> A] -> D }
2481 * and is used to insert A into the domain of functions that only
2482 * reference D.
2484 static __isl_give isl_multi_aff *strided_tile(
2485 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2486 __isl_keep isl_multi_aff *insert_array)
2488 int i;
2489 isl_ctx *ctx;
2490 isl_multi_aff *shift;
2491 isl_multi_val *stride;
2492 isl_space *space2;
2493 isl_local_space *ls;
2494 isl_multi_aff *tiling;
2496 ctx = isl_space_get_ctx(space);
2497 space2 = isl_space_domain(isl_space_copy(space));
2498 ls = isl_local_space_from_space(space2);
2499 space2 = isl_space_range(isl_space_copy(space));
2500 stride = isl_multi_val_zero(space2);
2501 shift = isl_multi_aff_zero(isl_space_copy(space));
2503 for (i = 0; i < tile->n; ++i) {
2504 struct gpu_array_bound *bound = &tile->bound[i];
2505 isl_val *stride_i;
2506 isl_aff *shift_i;
2508 if (tile->bound[i].shift) {
2509 stride_i = isl_val_copy(bound->stride);
2510 shift_i = isl_aff_copy(bound->shift);
2511 } else {
2512 stride_i = isl_val_one(ctx);
2513 shift_i = isl_aff_zero_on_domain(
2514 isl_local_space_copy(ls));
2517 stride = isl_multi_val_set_val(stride, i, stride_i);
2518 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2520 isl_local_space_free(ls);
2522 shift = isl_multi_aff_pullback_multi_aff(shift,
2523 isl_multi_aff_copy(insert_array));
2525 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2526 tiling = isl_multi_aff_add(tiling, shift);
2527 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2529 return tiling;
2532 /* Compute a tiling for the array reference group "group".
2534 * The tiling is of the form
2536 * { [D[i] -> A[a]] -> T[t] }
2538 * where D represents the first shared_len schedule dimensions,
2539 * A represents the global array and T represents the shared or
2540 * private memory tile. The name of T is the name of the local
2541 * array.
2543 * If there is any stride in the accesses, then the mapping is
2545 * t = (a + shift(i))/stride - lb(i)
2547 * otherwise, it is simply
2549 * t = a - lb(i)
2551 static void compute_group_tiling(struct gpu_array_ref_group *group)
2553 int i;
2554 struct gpu_array_tile *tile;
2555 struct gpu_array_info *array = group->array;
2556 isl_space *space;
2557 isl_multi_aff *tiling, *lb, *insert_array;
2558 isl_printer *p;
2559 char *local_name;
2561 tile = group->private_tile;
2562 if (!tile)
2563 tile = group->shared_tile;
2564 if (!tile)
2565 return;
2567 space = isl_map_get_space(group->access);
2568 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2570 for (i = 0; i < tile->n; ++i)
2571 if (tile->bound[i].shift)
2572 break;
2574 if (i < tile->n)
2575 tiling = strided_tile(tile, space, insert_array);
2576 else
2577 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2579 lb = isl_multi_aff_zero(space);
2580 for (i = 0; i < tile->n; ++i) {
2581 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2582 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2584 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2586 tiling = isl_multi_aff_sub(tiling, lb);
2588 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2589 p = print_array_name(p, group);
2590 local_name = isl_printer_get_str(p);
2591 isl_printer_free(p);
2592 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2593 free(local_name);
2595 tile->tiling = tiling;
2598 /* Compute a tiling for all the array reference groups.
2600 static void compute_group_tilings(struct gpu_gen *gen)
2602 int i, j;
2604 for (i = 0; i < gen->prog->n_array; ++i) {
2605 struct gpu_array_info *array = &gen->prog->array[i];
2607 for (j = 0; j < array->n_group; ++j)
2608 compute_group_tiling(array->groups[j]);
2612 /* Fill up the groups array with singleton groups, i.e., one group
2613 * per reference, initializing the array, access, write, n_ref and refs fields.
2614 * In particular the access field is initialized to the scheduled
2615 * access relation of the array reference.
2617 * Return the number of elements initialized, i.e., the number of
2618 * active references in the current kernel.
2620 static int populate_array_references(struct gpu_array_info *array,
2621 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2623 int i;
2624 int n;
2625 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2627 n = 0;
2628 for (i = 0; i < array->n_ref; ++i) {
2629 isl_union_map *umap;
2630 isl_map *map;
2631 struct gpu_array_ref_group *group;
2632 struct gpu_stmt_access *access = array->refs[i];
2634 map = isl_map_copy(access->access);
2635 umap = isl_union_map_from_map(map);
2636 umap = isl_union_map_apply_domain(umap,
2637 isl_union_map_copy(sched));
2639 if (isl_union_map_is_empty(umap)) {
2640 isl_union_map_free(umap);
2641 continue;
2644 map = isl_map_from_union_map(umap);
2645 map = isl_map_detect_equalities(map);
2647 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2648 assert(group);
2649 group->array = array;
2650 group->access = map;
2651 group->write = access->write;
2652 group->exact_write = access->exact_write;
2653 group->slice = access->n_index < array->n_index;
2654 group->refs = &array->refs[i];
2655 group->n_ref = 1;
2657 groups[n++] = group;
2660 return n;
2663 /* If group->n_ref == 1, then group->refs was set by
2664 * populate_array_references to point directly into
2665 * group->array->refs and should not be freed.
2666 * If group->n_ref > 1, then group->refs was set by join_groups
2667 * to point to a newly allocated array.
2669 static void free_array_ref_group(struct gpu_array_ref_group *group)
2671 if (!group)
2672 return;
2673 free_tile(group->shared_tile);
2674 free_tile(group->private_tile);
2675 isl_map_free(group->access);
2676 if (group->n_ref > 1)
2677 free(group->refs);
2678 free(group);
2681 /* Given a map where the input dimensions represent the tile loops,
2682 * eliminate the innermost of those that have a fixed value
2683 * until we reach one that does not (obviously) have a fixed value.
2685 static __isl_give isl_map *eliminate_fixed_inner_loops(
2686 __isl_take isl_map *access)
2688 int i, n;
2690 n = isl_map_dim(access, isl_dim_in);
2692 for (i = n - 1; i >= 0; --i) {
2693 if (!map_plain_is_fixed(access, isl_dim_in, i))
2694 break;
2695 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2697 return access;
2700 /* Check if the access relations of group1 and group2 overlap within
2701 * the innermost loop. In particular, ignore any inner dimension
2702 * with a fixed value.
2703 * The copying to and from shared memory will be performed within
2704 * the innermost actual loop so we are only allowed to consider
2705 * the dimensions up to that innermost loop while checking whether
2706 * two access relations overlap.
2708 static int accesses_overlap(struct gpu_array_ref_group *group1,
2709 struct gpu_array_ref_group *group2)
2711 int empty;
2712 isl_map *access1, *access2;
2714 access1 = isl_map_copy(group1->access);
2715 access1 = eliminate_fixed_inner_loops(access1);
2716 access2 = isl_map_copy(group2->access);
2717 access2 = eliminate_fixed_inner_loops(access2);
2718 access1 = isl_map_intersect(access1, access2);
2719 empty = isl_map_is_empty(access1);
2720 isl_map_free(access1);
2722 return !empty;
2725 /* Combine the given two groups into a single group, containing
2726 * the references of both groups.
2728 static struct gpu_array_ref_group *join_groups(
2729 struct gpu_array_ref_group *group1,
2730 struct gpu_array_ref_group *group2)
2732 int i;
2733 isl_ctx *ctx;
2734 struct gpu_array_ref_group *group;
2736 ctx = isl_map_get_ctx(group1->access);
2737 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2738 assert(group);
2739 group->array = group1->array;
2740 group->access = isl_map_union(isl_map_copy(group1->access),
2741 isl_map_copy(group2->access));
2742 group->write = group1->write || group2->write;
2743 group->exact_write = group1->exact_write && group2->exact_write;
2744 group->slice = group1->slice || group2->slice;
2745 group->n_ref = group1->n_ref + group2->n_ref;
2746 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2747 group->n_ref);
2748 assert(group->refs);
2749 for (i = 0; i < group1->n_ref; ++i)
2750 group->refs[i] = group1->refs[i];
2751 for (i = 0; i < group2->n_ref; ++i)
2752 group->refs[group1->n_ref + i] = group2->refs[i];
2754 return group;
2757 /* Combine the given two groups into a single group and free
2758 * the original two groups.
2760 static struct gpu_array_ref_group *join_groups_and_free(
2761 struct gpu_array_ref_group *group1,
2762 struct gpu_array_ref_group *group2)
2764 struct gpu_array_ref_group *group;
2766 group = join_groups(group1, group2);
2767 free_array_ref_group(group1);
2768 free_array_ref_group(group2);
2769 return group;
2772 /* Report that the array reference group with the given access relation
2773 * is not mapped to shared memory in the given kernel because
2774 * it does not exhibit any reuse and is considered to be coalesced.
2776 static void report_no_reuse_and_coalesced(struct ppcg_kernel *kernel,
2777 __isl_keep isl_union_map *access)
2779 isl_ctx *ctx;
2780 isl_printer *p;
2782 ctx = isl_union_map_get_ctx(access);
2783 p = isl_printer_to_file(ctx, stdout);
2784 p = isl_printer_print_str(p, "Array reference group ");
2785 p = isl_printer_print_union_map(p, access);
2786 p = isl_printer_print_str(p,
2787 " not considered for mapping to shared memory in kernel");
2788 p = isl_printer_print_int(p, kernel->id);
2789 p = isl_printer_print_str(p,
2790 " because it exhibits no reuse and is considered to be coalesced");
2791 p = isl_printer_end_line(p);
2792 isl_printer_free(p);
2795 /* Compute the private and/or shared memory tiles for the array
2796 * reference group "group" of array "array".
2797 * Return 0 on success and -1 on error.
2799 * If the array is a read-only scalar or if the user requested
2800 * not to use shared or private memory, then we do not need to do anything.
2802 * If any reference in the reference group accesses more than one element,
2803 * then we would have to make sure that the layout in shared memory
2804 * is the same as that in global memory. Since we do not handle this yet
2805 * (and it may not even be possible), we refuse to map to private or
2806 * shared memory in such cases.
2808 * If the array group involves any may writes (that are not must writes),
2809 * then we would have to make sure that we load the data into shared/private
2810 * memory first in case the data is not written by the kernel
2811 * (but still written back out to global memory).
2812 * Since we don't have any such mechanism at the moment, we don't
2813 * compute shared/private tiles for groups involving may writes.
2815 * We only try to compute a shared memory tile if there is any reuse
2816 * or if the access is not coalesced.
2818 * For computing a private memory tile, we also require that there is
2819 * some reuse. Moreover, we require that the access is private
2820 * to the thread. That is, we check that any given array element
2821 * is only accessed by a single thread.
2822 * We compute an access relation that maps the shared tile loop iterators
2823 * and the shared point loop iterators that will be wrapped over the
2824 * threads to the array elements.
2825 * We actually check that those iterators that will be wrapped
2826 * partition the array space. This check is stricter than necessary
2827 * since several iterations may be mapped onto the same thread
2828 * and then they could be allowed to access the same memory elements,
2829 * but our check does not allow this situation.
2831 * We also check that the index expression only depends on parallel
2832 * loops. That way, we can move those loops innermost and unroll them.
2833 * Again, we use a test that is stricter than necessary.
2834 * We actually check whether the index expression only depends
2835 * on the iterators that are wrapped over the threads.
2836 * These are necessarily parallel, but there may be more parallel loops.
2838 * Combining the injectivity of the first test with the single-valuedness
2839 * of the second test, we simply test for bijectivity.
2841 * If the array is marked force_private, then we bypass all checks
2842 * and assume we can (and should) use registers.
2844 * If it turns out we can (or have to) use registers, we compute
2845 * the private memory tile size using can_tile, after introducing a dependence
2846 * on the thread indices.
2848 static int compute_group_bounds_core(struct gpu_gen *gen,
2849 struct gpu_array_ref_group *group)
2851 isl_ctx *ctx = isl_space_get_ctx(group->array->space);
2852 isl_union_map *access;
2853 int n_index = group->array->n_index;
2854 int no_reuse, coalesced;
2855 isl_map *acc;
2856 int force_private = group->array->force_private;
2857 int use_shared = gen->options->use_shared_memory && gen->n_block > 0;
2858 int use_private = force_private || gen->options->use_private_memory;
2860 if (!use_shared && !use_private)
2861 return 0;
2862 if (gpu_array_is_read_only_scalar(group->array))
2863 return 0;
2864 if (!force_private && !group->exact_write)
2865 return 0;
2866 if (group->slice)
2867 return 0;
2869 access = group_access_relation(group, 1, 1);
2870 no_reuse = isl_union_map_is_injective(access);
2871 if (use_shared && no_reuse)
2872 coalesced = access_is_coalesced(gen, access);
2874 if (gen->options->debug->verbose && use_shared && no_reuse && coalesced)
2875 report_no_reuse_and_coalesced(gen->kernel, access);
2877 if (use_shared && (!no_reuse || !coalesced)) {
2878 group->shared_tile = create_tile(ctx, group->array->n_index);
2879 if (!can_tile(group->access, group->shared_tile))
2880 group->shared_tile = free_tile(group->shared_tile);
2883 if (!force_private && (!use_private || no_reuse)) {
2884 isl_union_map_free(access);
2885 return 0;
2888 access = isl_union_map_apply_domain(access,
2889 isl_union_map_copy(gen->shared_sched));
2891 acc = isl_map_from_union_map(access);
2893 if (!force_private && !access_is_bijective(gen, acc)) {
2894 isl_map_free(acc);
2895 return 0;
2898 group->private_tile = create_tile(gen->ctx, n_index);
2899 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2900 if (!can_tile(acc, group->private_tile))
2901 group->private_tile = free_tile(group->private_tile);
2903 isl_map_free(acc);
2905 if (force_private && !group->private_tile)
2906 isl_die(ctx, isl_error_internal,
2907 "unable to map array reference group to registers",
2908 return -1);
2910 return 0;
2913 /* Compute the private and/or shared memory tiles for the array
2914 * reference group "group" of array "array" and set last_shared.
2915 * Return 0 on success and -1 on error.
2917 static int compute_group_bounds(struct gpu_gen *gen,
2918 struct gpu_array_ref_group *group)
2920 if (compute_group_bounds_core(gen, group) < 0)
2921 return -1;
2922 set_last_shared(gen, group);
2924 return 0;
2927 /* If two groups have overlapping access relations (as determined by
2928 * the "overlap" function) and if one of them involves a write,
2929 * then merge the two groups into one.
2930 * If "compute_bounds" is set, then call compute_group_bounds
2931 * on the merged groups.
2933 * Return the updated number of groups.
2934 * Return -1 on error.
2936 static int group_writes(struct gpu_gen *gen,
2937 int n, struct gpu_array_ref_group **groups,
2938 int (*overlap)(struct gpu_array_ref_group *group1,
2939 struct gpu_array_ref_group *group2), int compute_bounds)
2941 int i, j;
2943 for (i = 0; i < n; ++i) {
2944 for (j = n - 1; j > i; --j) {
2945 if (!groups[i]->write && !groups[j]->write)
2946 continue;
2948 if (!overlap(groups[i], groups[j]))
2949 continue;
2951 groups[i] = join_groups_and_free(groups[i], groups[j]);
2952 if (compute_bounds &&
2953 compute_group_bounds(gen, groups[i]) < 0)
2954 return -1;
2955 if (j != n - 1)
2956 groups[j] = groups[n - 1];
2957 groups[n - 1] = NULL;
2958 n--;
2962 return n;
2965 /* If two groups have overlapping access relations (within the innermost
2966 * loop) and if one of them involves a write, then merge the two groups
2967 * into one.
2969 * Return the updated number of groups.
2971 static int group_overlapping_writes(struct gpu_gen *gen,
2972 int n, struct gpu_array_ref_group **groups)
2974 return group_writes(gen, n, groups, &accesses_overlap, 0);
2977 /* Check if the access relations of group1 and group2 overlap within
2978 * the outermost min(group1->last_shared, group2->last_shared) loops.
2980 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2981 struct gpu_array_ref_group *group2)
2983 int last_shared;
2984 int dim;
2985 int empty;
2986 isl_map *map_i, *map_j, *map;
2988 last_shared = group1->last_shared;
2989 if (group2->last_shared < last_shared)
2990 last_shared = group2->last_shared;
2991 map_i = isl_map_copy(group1->access);
2992 dim = isl_map_dim(map_i, isl_dim_in);
2993 map_i = isl_map_eliminate(map_i, isl_dim_in,
2994 last_shared + 1, dim - (last_shared + 1));
2995 map_j = isl_map_copy(group2->access);
2996 map_j = isl_map_eliminate(map_j, isl_dim_in,
2997 last_shared + 1, dim - (last_shared + 1));
2998 map = isl_map_intersect(map_i, map_j);
2999 empty = isl_map_is_empty(map);
3000 isl_map_free(map);
3002 return !empty;
3005 /* If two groups have overlapping access relations (within the outer
3006 * last_shared loops) and if one of them involves a write,
3007 * then merge the two groups into one.
3009 * Return the updated number of groups.
3011 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
3012 struct gpu_array_ref_group **groups)
3014 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
3017 /* Is the size of the tile specified by "tile" smaller than the sum of
3018 * the sizes of the tiles specified by "tile1" and "tile2"?
3020 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
3021 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
3023 int smaller;
3024 isl_val *size, *size1, *size2;
3026 size = tile_size(ctx, tile);
3027 size1 = tile_size(ctx, tile1);
3028 size2 = tile_size(ctx, tile2);
3030 size = isl_val_sub(size, size1);
3031 size = isl_val_sub(size, size2);
3032 smaller = isl_val_is_neg(size);
3034 isl_val_free(size);
3036 return smaller;
3039 /* Given an initial grouping of array references and shared memory tiles
3040 * for each group that allows for a shared memory tile, merge two groups
3041 * if both have a shared memory tile, the merged group also has
3042 * a shared memory tile and the size of the tile for the merge group
3043 * is smaller than the sum of the tile sizes of the individual groups.
3045 * If merging two groups decreases the "last_shared" dimension of
3046 * one or both of the two groups, then we need to check for overlapping
3047 * writes again.
3049 * Return the number of groups after merging.
3050 * Return -1 on error.
3052 static int group_common_shared_memory_tile(struct gpu_gen *gen,
3053 struct gpu_array_info *array, int n,
3054 struct gpu_array_ref_group **groups)
3056 int i, j;
3057 int recompute_overlap = 0;
3058 isl_ctx *ctx = isl_space_get_ctx(array->space);
3060 for (i = 0; i < n; ++i) {
3061 if (!groups[i]->shared_tile)
3062 continue;
3063 for (j = n - 1; j > i; --j) {
3064 isl_map *map;
3065 int empty;
3066 struct gpu_array_ref_group *group;
3068 if (!groups[j]->shared_tile)
3069 continue;
3071 map = isl_map_intersect(isl_map_copy(groups[i]->access),
3072 isl_map_copy(groups[j]->access));
3073 empty = isl_map_is_empty(map);
3074 isl_map_free(map);
3076 if (empty)
3077 continue;
3079 group = join_groups(groups[i], groups[j]);
3080 if (compute_group_bounds(gen, group) < 0) {
3081 free_array_ref_group(group);
3082 return -1;
3084 if (!group->shared_tile ||
3085 !smaller_tile(ctx, group->shared_tile,
3086 groups[i]->shared_tile,
3087 groups[j]->shared_tile)) {
3088 free_array_ref_group(group);
3089 continue;
3092 if (group->last_shared < groups[i]->last_shared ||
3093 group->last_shared < groups[j]->last_shared)
3094 recompute_overlap = 1;
3095 free_array_ref_group(groups[i]);
3096 free_array_ref_group(groups[j]);
3097 groups[i] = group;
3098 if (j != n - 1)
3099 groups[j] = groups[n - 1];
3100 n--;
3104 if (recompute_overlap)
3105 n = group_last_shared_overlapping_writes(gen, n, groups);
3106 return n;
3109 /* Set array->n_group and array->groups to n and groups.
3111 * Additionally, set the "nr" field of each group
3112 * and the "group" field of each reference in each group.
3114 static void set_array_groups(struct gpu_array_info *array,
3115 int n, struct gpu_array_ref_group **groups)
3117 int i, j;
3119 array->n_group = n;
3120 array->groups = groups;
3122 for (i = 0; i < n; ++i) {
3123 groups[i]->nr = i;
3125 for (j = 0; j < groups[i]->n_ref; ++j)
3126 groups[i]->refs[j]->group = i;
3130 /* Group array references that should be considered together when
3131 * deciding whether to access them from private, shared or global memory.
3132 * Return -1 on error.
3134 * In particular, if two array references overlap and if one of them
3135 * is a write, then the two references are grouped together.
3136 * We first perform an initial grouping based only on the access relation.
3137 * After computing shared and private memory tiles, we check for
3138 * overlapping writes again, but this time taking into account
3139 * the "last_shared" property.
3141 * Furthermore, if two groups admit a shared memory tile and if the
3142 * combination of the two also admits a shared memory tile, we merge
3143 * the two groups.
3145 * If the array contains structures, then there is no need to compute
3146 * reference groups since we do not map such arrays to private or shared
3147 * memory.
3149 static int group_array_references(struct gpu_gen *gen,
3150 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
3152 int i;
3153 int n;
3154 isl_ctx *ctx = isl_union_map_get_ctx(sched);
3155 struct gpu_array_ref_group **groups;
3157 if (array->has_compound_element)
3158 return 0;
3160 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
3161 array->n_ref);
3162 if (!groups)
3163 return -1;
3165 n = populate_array_references(array, sched, groups);
3167 n = group_overlapping_writes(gen, n, groups);
3169 for (i = 0; i < n; ++i)
3170 if (compute_group_bounds(gen, groups[i]) < 0)
3171 n = -1;
3173 n = group_last_shared_overlapping_writes(gen, n, groups);
3175 n = group_common_shared_memory_tile(gen, array, n, groups);
3177 set_array_groups(array, n, groups);
3179 if (n >= 0)
3180 return 0;
3182 for (i = 0; i < array->n_ref; ++i)
3183 free_array_ref_group(groups[i]);
3184 return -1;
3187 /* Take tiled_sched, project it onto the shared tile loops and
3188 * the loops that will be wrapped over the threads and
3189 * store the result in gen->shared_sched.
3190 * Also compute a projection that projects out the loops that will be
3191 * wrapped over the threads and store this projection in gen->shared_proj.
3193 static void compute_shared_sched(struct gpu_gen *gen)
3195 isl_space *dim;
3196 isl_map *proj;
3197 isl_set *par;
3198 isl_union_map *sched;
3200 sched = isl_union_map_copy(gen->tiled_sched);
3202 dim = isl_union_map_get_space(sched);
3203 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
3204 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3206 dim = isl_union_map_get_space(sched);
3207 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
3209 gen->shared_sched = sched;
3210 gen->shared_proj = isl_union_map_from_map(proj);
3213 /* For each scalar in the input program, check if there are any
3214 * order dependences active inside the current kernel, within
3215 * the same iteration of the host schedule.
3216 * If so, mark the scalar as force_private so that it will be
3217 * mapped to a register.
3219 static void check_scalar_live_ranges(struct gpu_gen *gen)
3221 int i;
3222 isl_map *proj;
3223 isl_union_map *sched;
3224 isl_union_set *domain;
3225 isl_union_map *same_host_iteration;
3227 gen->any_force_private = 0;
3229 if (!gen->options->live_range_reordering)
3230 return;
3232 sched = gen->shared_sched;
3233 sched = isl_union_map_universe(isl_union_map_copy(sched));
3234 domain = isl_union_map_domain(sched);
3236 sched = isl_union_map_copy(gen->sched);
3237 proj = projection(isl_union_map_get_space(sched),
3238 gen->untiled_len, gen->tile_first);
3239 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3240 same_host_iteration = isl_union_map_apply_range(sched,
3241 isl_union_map_reverse(isl_union_map_copy(sched)));
3243 for (i = 0; i < gen->prog->n_array; ++i) {
3244 struct gpu_array_info *array = &gen->prog->array[i];
3245 isl_union_map *order;
3247 array->force_private = 0;
3248 if (array->n_index != 0)
3249 continue;
3250 order = isl_union_map_copy(array->dep_order);
3251 order = isl_union_map_intersect_domain(order,
3252 isl_union_set_copy(domain));
3253 order = isl_union_map_intersect_range(order,
3254 isl_union_set_copy(domain));
3255 order = isl_union_map_intersect(order,
3256 isl_union_map_copy(same_host_iteration));
3257 if (!isl_union_map_is_empty(order)) {
3258 array->force_private = 1;
3259 gen->any_force_private = 1;
3261 isl_union_map_free(order);
3264 isl_union_map_free(same_host_iteration);
3265 isl_union_set_free(domain);
3268 /* Group references of all arrays in the program.
3270 static int group_references(struct gpu_gen *gen)
3272 int i;
3273 int r = 0;
3274 isl_union_map *sched;
3276 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3277 isl_union_map_copy(gen->shared_proj));
3279 for (i = 0; i < gen->prog->n_array; ++i) {
3280 r = group_array_references(gen, &gen->prog->array[i], sched);
3281 if (r < 0)
3282 break;
3285 isl_union_map_free(sched);
3287 return r;
3290 /* Free all array information that is local to the current kernel.
3292 static void free_local_array_info(struct gpu_gen *gen)
3294 int i, j;
3296 for (i = 0; i < gen->prog->n_array; ++i) {
3297 struct gpu_array_info *array = &gen->prog->array[i];
3299 for (j = 0; j < array->n_group; ++j)
3300 free_array_ref_group(array->groups[j]);
3301 free(array->groups);
3305 /* Compute the size of a bounding box around the origin and "set",
3306 * where "set" is assumed to contain only non-negative elements.
3307 * In particular, compute the maximal value of "set" in each direction
3308 * and add one.
3310 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
3311 __isl_keep isl_set *context)
3313 int i, n;
3314 isl_multi_pw_aff *mpa;
3316 n = isl_set_dim(set, isl_dim_set);
3317 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
3318 for (i = 0; i < n; ++i) {
3319 isl_space *space;
3320 isl_aff *one;
3321 isl_pw_aff *bound;
3323 bound = isl_set_dim_max(isl_set_copy(set), i);
3324 bound = isl_pw_aff_coalesce(bound);
3325 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
3327 space = isl_pw_aff_get_domain_space(bound);
3328 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
3329 one = isl_aff_add_constant_si(one, 1);
3330 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
3331 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
3333 isl_set_free(set);
3335 return mpa;
3338 /* Compute the effective grid size as a list of the sizes in each dimension.
3340 * The grid size specified by the user or set by default
3341 * in read_grid_sizes() and applied in tile_schedule(),
3342 * may be too large for the given code in the sense that
3343 * it may contain blocks that don't need to execute anything.
3344 * We therefore don't return this grid size, but instead the
3345 * smallest grid size that ensures that all blocks that actually
3346 * execute code are included in the grid.
3348 * We first extract a description of the grid, i.e., the possible values
3349 * of the block ids, from gen->tiled_sched.
3350 * The block ids are parameters in gen->tiled_sched.
3351 * We simply need to change them into set dimensions.
3353 * Then, for each block dimension, we compute the maximal value of the block id
3354 * and add one.
3356 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
3357 struct ppcg_kernel *kernel)
3359 int i;
3360 isl_set *grid;
3362 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
3363 grid = isl_set_from_params(grid);
3364 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
3365 for (i = 0; i < gen->n_grid; ++i) {
3366 int pos;
3367 char name[20];
3369 snprintf(name, sizeof(name), "b%d", i);
3370 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
3371 assert(pos >= 0);
3372 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
3373 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
3376 return extract_size(grid, kernel->context);
3379 /* Compute the size of a fixed bounding box around the origin and "set",
3380 * where "set" is assumed to contain only non-negative elements,
3381 * and store the results in "size".
3382 * In particular, compute the maximal value of "set" in each direction
3383 * and add one.
3385 static void extract_fixed_size(__isl_take isl_set *set, int *size)
3387 int i, n;
3388 isl_local_space *ls;
3389 isl_aff *obj;
3391 n = isl_set_dim(set, isl_dim_set);
3392 ls = isl_local_space_from_space(isl_set_get_space(set));
3393 obj = isl_aff_zero_on_domain(ls);
3394 for (i = 0; i < n; ++i) {
3395 isl_val *max;
3397 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
3398 max = isl_set_max_val(set, obj);
3399 size[i] = isl_val_get_num_si(max) + 1;
3400 isl_val_free(max);
3401 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
3403 isl_aff_free(obj);
3404 isl_set_free(set);
3407 /* Compute the effective block size as a list of the sizes in each dimension
3408 * and store the sizes in kernel->block_dim.
3410 * The block size specified by the user or set by default
3411 * in read_block_sizes() and applied in thread_tile_schedule(),
3412 * may be too large for the given code in the sense that
3413 * it may contain threads that don't need to execute anything.
3414 * We therefore don't store this block size in kernel->block_dim,
3415 * but instead the smallest block size that ensures that all threads
3416 * that actually execute code are included in the block.
3418 * The current implementation eliminates all parameters, ensuring
3419 * that the size is a fixed constant in each dimension.
3420 * In principle we could also compute parametric sizes.
3421 * We would have to make sure to project out all b%d and t%d parameters,
3422 * however.
3424 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3426 int i;
3427 int nparam;
3428 isl_set *block;
3429 isl_multi_pw_aff *mpa;
3431 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3432 block = isl_set_from_params(block);
3433 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3434 kernel->n_block = gen->n_block;
3435 for (i = 0; i < gen->n_block; ++i) {
3436 int pos;
3437 char name[20];
3439 snprintf(name, sizeof(name), "t%d", i);
3440 pos = isl_set_find_dim_by_name(block, isl_dim_param, name);
3441 assert(pos >= 0);
3442 block = isl_set_equate(block, isl_dim_param, pos,
3443 isl_dim_set, i);
3445 nparam = isl_set_dim(block, isl_dim_param);
3446 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3448 extract_fixed_size(block, kernel->block_dim);
3451 void ppcg_kernel_free(void *user)
3453 struct ppcg_kernel *kernel = user;
3454 int i;
3456 if (!kernel)
3457 return;
3459 isl_multi_pw_aff_free(kernel->grid_size);
3460 isl_set_free(kernel->context);
3461 isl_union_set_free(kernel->arrays);
3462 isl_space_free(kernel->space);
3463 isl_ast_node_free(kernel->tree);
3465 for (i = 0; i < kernel->n_array; ++i)
3466 isl_pw_aff_list_free(kernel->array[i].bound);
3467 free(kernel->array);
3469 for (i = 0; i < kernel->n_var; ++i) {
3470 free(kernel->var[i].name);
3471 isl_vec_free(kernel->var[i].size);
3473 free(kernel->var);
3475 free(kernel);
3478 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3479 struct ppcg_kernel_var *var)
3481 int j;
3482 struct gpu_array_tile *tile;
3483 isl_printer *p;
3484 char *name;
3486 var->array = group->array;
3488 tile = group->private_tile;
3489 var->type = ppcg_access_private;
3490 if (!tile) {
3491 tile = group->shared_tile;
3492 var->type = ppcg_access_shared;
3495 p = isl_printer_to_str(ctx);
3496 p = print_array_name(p, group);
3497 var->name = isl_printer_get_str(p);
3498 isl_printer_free(p);
3500 var->size = isl_vec_alloc(ctx, group->array->n_index);
3502 for (j = 0; j < group->array->n_index; ++j)
3503 var->size = isl_vec_set_element_val(var->size, j,
3504 isl_val_copy(tile->bound[j].size));
3507 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3509 int i, j, n;
3511 n = 0;
3512 for (i = 0; i < gen->prog->n_array; ++i) {
3513 struct gpu_array_info *array = &gen->prog->array[i];
3515 for (j = 0; j < array->n_group; ++j) {
3516 struct gpu_array_ref_group *group = array->groups[j];
3517 if (group->private_tile || group->shared_tile)
3518 ++n;
3522 kernel->n_var = n;
3523 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3524 assert(kernel->var);
3526 n = 0;
3527 for (i = 0; i < gen->prog->n_array; ++i) {
3528 struct gpu_array_info *array = &gen->prog->array[i];
3530 for (j = 0; j < array->n_group; ++j) {
3531 struct gpu_array_ref_group *group = array->groups[j];
3532 if (!group->private_tile && !group->shared_tile)
3533 continue;
3534 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3535 ++n;
3540 /* The sizes of the arrays on the host that have been computed by
3541 * extract_array_info may depend on the parameters. Use the extra
3542 * constraints on the parameters that are valid at "host_domain"
3543 * to simplify these expressions and store the results in kernel->array.
3545 * We only need these localized bounds for arrays that are accessed
3546 * by the current kernel. If we have found at least one reference group
3547 * then the array is accessed by the kernel. If the array has compound
3548 * elements then we skipped the construction of array reference groups.
3550 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3551 __isl_keep isl_set *host_domain)
3553 int i, j;
3554 isl_set *context;
3556 kernel->array = isl_calloc_array(gen->ctx,
3557 struct gpu_local_array_info, gen->prog->n_array);
3558 assert(kernel->array);
3559 kernel->n_array = gen->prog->n_array;
3561 context = isl_set_copy(host_domain);
3562 context = isl_set_params(context);
3564 for (i = 0; i < gen->prog->n_array; ++i) {
3565 struct gpu_array_info *array = &gen->prog->array[i];
3566 isl_pw_aff_list *local;
3568 if (array->n_group == 0 && !array->has_compound_element)
3569 continue;
3571 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3573 for (j = 0; j < array->n_index; ++j) {
3574 isl_pw_aff *pwaff;
3576 pwaff = isl_pw_aff_copy(array->bound[j]);
3577 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3578 local = isl_pw_aff_list_add(local, pwaff);
3581 kernel->array[i].n_index = array->n_index;
3582 kernel->array[i].bound = local;
3584 isl_set_free(context);
3587 /* Find the element in gen->stmt that has the given "id".
3588 * Return NULL if no such gpu_stmt can be found.
3590 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3592 int i;
3594 for (i = 0; i < prog->n_stmts; ++i) {
3595 if (id == prog->stmts[i].id)
3596 break;
3599 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3602 /* Set gen->tile_len and gen->n_parallel to those of the statement
3603 * affected by the first map (part of the schedule)
3604 * on which this function is called.
3605 * Because of the way the schedule is constructed, the other statements
3606 * in the list, if any, should have the same values for these properties.
3608 static int extract_tile_len(__isl_take isl_map *map, void *user)
3610 struct gpu_gen *gen = (struct gpu_gen *) user;
3611 isl_id *id;
3612 struct gpu_stmt *stmt;
3614 id = isl_map_get_tuple_id(map, isl_dim_in);
3615 stmt = find_stmt(gen->prog, id);
3616 isl_id_free(id);
3618 isl_map_free(map);
3620 if (!stmt)
3621 isl_die(gen->ctx, isl_error_unknown,
3622 "statement not found", return -1);
3624 gen->tile_len = stmt->tile_len;
3625 gen->n_parallel = stmt->n_parallel;
3627 return -1;
3630 void ppcg_kernel_stmt_free(void *user)
3632 int i;
3633 struct ppcg_kernel_stmt *stmt = user;
3635 if (!stmt)
3636 return;
3638 switch (stmt->type) {
3639 case ppcg_kernel_copy:
3640 isl_ast_expr_free(stmt->u.c.index);
3641 isl_ast_expr_free(stmt->u.c.local_index);
3642 break;
3643 case ppcg_kernel_domain:
3644 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
3645 break;
3646 case ppcg_kernel_sync:
3647 break;
3650 free(stmt);
3653 /* Set the options of "context" to
3655 * { space -> [x] : x >= first }
3657 static __isl_give isl_ast_build *set_unroll(
3658 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3659 int first)
3661 isl_ctx *ctx;
3662 isl_map *unroll;
3663 isl_union_map *opt;
3665 ctx = isl_ast_build_get_ctx(build);
3667 space = isl_space_from_domain(space);
3668 space = isl_space_add_dims(space, isl_dim_out, 1);
3669 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3670 unroll = isl_map_universe(space);
3671 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3672 opt = isl_union_map_from_map(unroll);
3674 build = isl_ast_build_set_options(build, opt);
3676 return build;
3679 /* Return a list of isl_ids of the form "prefix%d".
3681 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3682 int n, const char *prefix)
3684 int i;
3685 char name[10];
3686 isl_id_list *names;
3688 names = isl_id_list_alloc(ctx, n);
3689 for (i = 0; i < n; ++i) {
3690 isl_id *id;
3692 snprintf(name, sizeof(name), "%s%d", prefix, i);
3693 id = isl_id_alloc(ctx, name, NULL);
3694 names = isl_id_list_add(names, id);
3697 return names;
3700 /* Extend the schedule "schedule" with the part of "extension"
3701 * starting at "first" up to "len".
3703 static __isl_give isl_union_map *extend_schedule(
3704 __isl_take isl_union_map *schedule,
3705 __isl_take isl_union_map *extension, int first, int len)
3707 isl_space *space;
3708 isl_map *proj;
3709 isl_union_map *umap;
3710 isl_set *set;
3712 space = isl_union_map_get_space(schedule);
3713 space = isl_space_set_from_params(space);
3714 space = isl_space_add_dims(space, isl_dim_set, len);
3715 proj = isl_set_identity(isl_set_universe(space));
3716 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3717 extension = isl_union_map_apply_range(extension,
3718 isl_union_map_from_map(proj));
3720 schedule = isl_union_map_range_product(schedule, extension);
3722 return schedule;
3725 /* Return the gpu_stmt_access in the list "accesses" that corresponds
3726 * to "ref_id".
3728 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
3729 __isl_keep isl_id *ref_id)
3731 struct gpu_stmt_access *access;
3733 for (access = accesses; access; access = access->next)
3734 if (access->ref_id == ref_id)
3735 return access;
3737 return NULL;
3740 /* Return the index of the array called "name" in the list of arrays.
3742 static int find_array_index(struct gpu_gen *gen, const char *name)
3744 int i;
3746 for (i = 0; i < gen->prog->n_array; ++i)
3747 if (!strcmp(name, gen->prog->array[i].name))
3748 return i;
3750 return -1;
3753 /* Internal data structure for the index and AST expression transformation
3754 * callbacks for pet_stmt_build_ast_exprs.
3756 * "accesses" is the list of gpu_stmt_access in the statement.
3757 * "iterator_map" expresses the statement iterators in terms of
3758 * the AST loop iterators.
3759 * "sched2shared" expresses the first shared_len dimensions of
3760 * the computed schedule in terms of the AST loop iterators.
3762 * The following fields are set in transform_index and used in transform_expr.
3763 * "array" is the array that is being accessed.
3764 * "global" is set if the global array is accessed (rather than
3765 * shared/private memory).
3766 * "local_array" refers to information on the array specialized
3767 * to the current kernel.
3769 struct ppcg_transform_data {
3770 struct gpu_gen *gen;
3771 struct gpu_stmt_access *accesses;
3772 isl_pw_multi_aff *iterator_map;
3773 isl_pw_multi_aff *sched2shared;
3775 struct gpu_array_info *array;
3776 int global;
3777 struct gpu_local_array_info *local_array;
3780 /* Return the name of the outer array (of structs) accessed by "access".
3782 static const char *get_outer_array_name(__isl_keep isl_map *access)
3784 isl_space *space;
3785 const char *name;
3787 space = isl_space_range(isl_map_get_space(access));
3788 while (space && isl_space_is_wrapping(space))
3789 space = isl_space_domain(isl_space_unwrap(space));
3790 name = isl_space_get_tuple_name(space, isl_dim_set);
3791 isl_space_free(space);
3793 return name;
3796 /* Index transformation callback for pet_stmt_build_ast_exprs.
3798 * "index" expresses the array indices in terms of statement iterators
3800 * We first reformulate "index" in terms of the AST loop iterators.
3801 * Then we check if we are accessing the global array or
3802 * a shared/private copy. In the former case, we simply return
3803 * the updated index. If "index" is an affine expression rather
3804 * than an array access, then we also return the updated index here.
3806 * If no reference groups have been computed for the array,
3807 * then we can only be accessing the global array.
3809 * Otherwise, we apply the tiling to the index.
3810 * This tiling is of the form
3812 * [D -> A] -> T
3814 * The index is of the form
3816 * L -> A
3818 * We update the tiling to refer to the AST loop iteratos
3820 * [L -> A] -> T
3822 * and modify index to keep track of those iterators
3824 * L -> [L -> A]
3826 * Combining these two yields a tiled index expression in terms
3827 * of the AST loop iterators
3829 * L -> T
3831 static __isl_give isl_multi_pw_aff *transform_index(
3832 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
3833 void *user)
3835 struct ppcg_transform_data *data = user;
3836 struct gpu_stmt_access *access;
3837 struct gpu_array_ref_group *group;
3838 struct gpu_array_tile *tile;
3839 isl_pw_multi_aff *iterator_map;
3840 int i;
3841 const char *name;
3842 isl_space *space;
3843 isl_multi_pw_aff *tiling;
3844 isl_pw_multi_aff *pma;
3845 isl_multi_pw_aff *mpa;
3847 data->array = NULL;
3849 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
3850 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
3852 access = find_access(data->accesses, ref_id);
3853 if (!access)
3854 return index;
3855 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
3856 return index;
3858 name = get_outer_array_name(access->access);
3859 i = find_array_index(data->gen, name);
3860 if (i < 0)
3861 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
3862 "cannot find array",
3863 return isl_multi_pw_aff_free(index));
3864 data->array = &data->gen->prog->array[i];
3865 data->local_array = &data->gen->kernel->array[i];
3867 if (access->group < 0) {
3868 data->global = 1;
3869 return index;
3872 group = data->array->groups[access->group];
3873 tile = group->private_tile;
3874 if (!tile)
3875 tile = group->shared_tile;
3876 data->global = !tile;
3877 if (!tile)
3878 return index;
3880 space = isl_space_range(isl_multi_pw_aff_get_space(index));
3881 space = isl_space_map_from_set(space);
3882 pma = isl_pw_multi_aff_identity(space);
3883 pma = isl_pw_multi_aff_product(
3884 isl_pw_multi_aff_copy(data->sched2shared), pma);
3885 tiling = isl_multi_pw_aff_from_multi_aff(
3886 isl_multi_aff_copy(tile->tiling));
3887 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
3889 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
3890 space = isl_space_map_from_set(space);
3891 mpa = isl_multi_pw_aff_identity(space);
3892 index = isl_multi_pw_aff_range_product(mpa, index);
3893 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
3895 return index;
3898 /* Dereference "expr" by adding an index [0].
3899 * The original "expr" is assumed not to have any indices.
3901 * If "expr" is a member access, then the dereferencing needs
3902 * to be applied to the structure argument of this member access.
3904 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
3906 isl_ctx *ctx;
3907 isl_ast_expr *res;
3908 isl_ast_expr_list *list;
3910 if (isl_ast_expr_get_op_type(expr) == isl_ast_op_member) {
3911 isl_ast_expr *arg;
3913 arg = isl_ast_expr_get_op_arg(expr, 0);
3914 arg = dereference(arg);
3915 expr = isl_ast_expr_set_op_arg(expr, 0, arg);
3917 return expr;
3920 ctx = isl_ast_expr_get_ctx(expr);
3921 res = isl_ast_expr_from_val(isl_val_zero(ctx));
3922 list = isl_ast_expr_list_from_ast_expr(res);
3923 res = isl_ast_expr_get_op_arg(expr, 0);
3924 res = isl_ast_expr_access(res, list);
3925 isl_ast_expr_free(expr);
3927 return res;
3930 /* Linearize the index expression "expr" based on the array bounds
3931 * of "array".
3933 * That is, transform expression
3935 * A[i_0][i_1]...[i_n]
3937 * to
3939 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
3941 * where b_0, b_1, ..., b_n are the bounds on the array.
3943 * If the base of "expr" is a member access, then the linearization needs
3944 * to be applied to the structure argument of this member access.
3946 * In the base case, if "expr" has no arguments (other than the name of
3947 * the array), then we are passing an entire array to a function.
3948 * In this case, there is nothing to linearize.
3949 * Note that at this point an expression with no arguments can
3950 * only be an entire array because the scalar case and
3951 * the case of single struct are handled by the caller.
3953 * If the number of specified index expressions in "expr"
3954 * is smaller than the dimension of the accessed array,
3955 * then the missing i_j also do not appear in the linearized expression.
3956 * Furthermore, since such an expression does not refer to a single
3957 * element while the default linearized expression would refer to
3958 * a single element, we return the expression
3960 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
3962 * instead. Note that because of the special case handling above,
3963 * we can assume here that here that there is at least one index expression.
3965 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
3966 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
3968 int i, n;
3969 isl_ctx *ctx;
3970 isl_set *context;
3971 isl_ast_expr *arg0;
3972 isl_ast_expr *res;
3973 isl_ast_expr_list *list;
3974 isl_ast_build *build;
3976 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3977 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3978 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3979 isl_ast_expr *arg;
3981 arg = isl_ast_expr_get_op_arg(arg0, 0);
3982 arg = gpu_local_array_info_linearize_index(array, arg);
3983 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3984 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3986 return expr;
3988 isl_ast_expr_free(arg0);
3990 if (isl_ast_expr_get_op_n_arg(expr) == 1)
3991 return expr;
3993 ctx = isl_ast_expr_get_ctx(expr);
3994 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
3995 build = isl_ast_build_from_context(context);
3997 n = isl_ast_expr_get_op_n_arg(expr);
3998 res = isl_ast_expr_get_op_arg(expr, 1);
3999 for (i = 1; i < array->n_index; ++i) {
4000 isl_pw_aff *bound_i;
4001 isl_ast_expr *expr_i;
4003 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
4004 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
4005 res = isl_ast_expr_mul(res, expr_i);
4007 if (i + 1 >= n)
4008 continue;
4009 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
4010 res = isl_ast_expr_add(res, expr_i);
4013 isl_ast_build_free(build);
4015 if (1 + array->n_index > n) {
4016 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
4017 } else {
4018 list = isl_ast_expr_list_from_ast_expr(res);
4019 res = isl_ast_expr_get_op_arg(expr, 0);
4020 res = isl_ast_expr_access(res, list);
4023 isl_ast_expr_free(expr);
4025 return res;
4028 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
4030 * If the AST expression refers to a global scalar that is not
4031 * a read-only scalar, then its address was passed to the kernel and
4032 * we need to dereference it.
4034 * If the AST expression refers to an access to a global array,
4035 * then we linearize the access exploiting the bounds in data->local_array.
4037 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
4038 __isl_keep isl_id *id, void *user)
4040 struct ppcg_transform_data *data = user;
4042 if (!data->array)
4043 return expr;
4044 if (gpu_array_is_read_only_scalar(data->array))
4045 return expr;
4046 if (!data->global)
4047 return expr;
4048 if (data->array->n_index == 0)
4049 return dereference(expr);
4050 if (!data->array->linearize)
4051 return expr;
4053 return gpu_local_array_info_linearize_index(data->local_array, expr);
4056 /* This function is called for each instance of a user statement
4057 * in the kernel.
4059 * We attach a struct ppcg_kernel_stmt to the "node", containing
4060 * a computed AST expression for each access.
4061 * These AST expressions are computed from iterator_map,
4062 * which expresses the domain
4063 * elements in terms of the generated loops, and sched2shared,
4064 * which expresses the first shared_len dimensions of the schedule
4065 * computed by PPCG in terms of the generated loops.
4067 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
4068 __isl_keep isl_ast_build *build, void *user)
4070 struct ppcg_transform_data data;
4071 struct gpu_gen *gen = (struct gpu_gen *) user;
4072 struct ppcg_kernel_stmt *stmt;
4073 isl_id *id;
4074 isl_pw_multi_aff *sched2shared;
4075 isl_map *map;
4076 isl_pw_multi_aff *iterator_map;
4077 isl_ast_expr *expr, *arg;
4078 isl_union_map *schedule;
4079 int i, n;
4081 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4082 if (!stmt)
4083 return isl_ast_node_free(node);
4085 expr = isl_ast_node_user_get_expr(node);
4086 arg = isl_ast_expr_get_op_arg(expr, 0);
4087 id = isl_ast_expr_get_id(arg);
4089 schedule = isl_ast_build_get_schedule(build);
4090 map = isl_map_reverse(isl_map_from_union_map(schedule));
4091 iterator_map = isl_pw_multi_aff_from_map(map);
4092 sched2shared = compute_sched_to_shared(gen,
4093 isl_pw_multi_aff_copy(iterator_map));
4095 stmt->type = ppcg_kernel_domain;
4096 stmt->u.d.stmt = find_stmt(gen->prog, id);
4097 if (!stmt->u.d.stmt)
4098 goto error;
4100 data.gen = gen;
4101 data.accesses = stmt->u.d.stmt->accesses;
4102 data.iterator_map = iterator_map;
4103 data.sched2shared = sched2shared;
4104 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
4105 build, &transform_index, &data,
4106 &transform_expr, &data);
4108 isl_id_free(id);
4109 isl_pw_multi_aff_free(iterator_map);
4110 isl_pw_multi_aff_free(sched2shared);
4111 isl_ast_expr_free(arg);
4112 isl_ast_expr_free(expr);
4114 id = isl_id_alloc(gen->ctx, NULL, stmt);
4115 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4116 return isl_ast_node_set_annotation(node, id);
4117 error:
4118 isl_id_free(id);
4119 isl_pw_multi_aff_free(iterator_map);
4120 ppcg_kernel_stmt_free(stmt);
4121 isl_pw_multi_aff_free(sched2shared);
4122 return isl_ast_node_free(node);
4125 /* This function is called when code has been generated for the shared
4126 * tile loops. The "schedule" refers only to the original statements.
4128 * We extend the schedule with that part of gen->local_sched that hasn't
4129 * been taken into account yet. This introduces parameters referring
4130 * to thread ids in the schedule, so we add them (with the appropriate
4131 * bounds to the context as well).
4132 * Finally, we set the appropriate unrolling options
4133 * if gen->first_unroll is set.
4135 static __isl_give isl_ast_node *create_domain_leaf(
4136 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
4137 void *user)
4139 struct gpu_gen *gen = (struct gpu_gen *) user;
4140 isl_space *space;
4141 isl_union_map *sched;
4142 isl_ast_node *tree;
4143 isl_set *set;
4144 isl_id_list *iterators;
4145 int n;
4147 schedule = extend_schedule(schedule,
4148 isl_union_map_copy(gen->local_sched),
4149 gen->shared_len, gen->thread_tiled_len);
4151 space = isl_ast_build_get_schedule_space(build);
4152 set = isl_set_universe(space);
4153 set = add_bounded_parameters(set, gen->kernel->n_block,
4154 gen->kernel->block_dim, "t");
4155 build = isl_ast_build_restrict(build, set);
4157 n = gen->thread_tiled_len - gen->shared_len;
4159 if (gen->first_unroll >= 0) {
4160 space = isl_space_set_alloc(gen->ctx, 0, n);
4161 build = set_unroll(build, space, gen->first_unroll);
4163 iterators = generate_names(gen->ctx, n, "c");
4164 build = isl_ast_build_set_iterators(build, iterators);
4165 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
4166 tree = isl_ast_build_ast_from_schedule(build, schedule);
4167 isl_ast_build_free(build);
4169 return tree;
4172 /* This function is called for each statement node in the AST of the code
4173 * for copying to or from shared/private memory.
4174 * Attach a pointer to a ppcg_kernel_stmt representing the copy
4175 * statement to the node.
4176 * The statement name is "read" or "write", depending on whether we are
4177 * reading from global memory or writing to global memory.
4178 * The name of the T space is {shared,private}_<array>.
4180 * The schedule is of the form
4182 * type[A -> T] -> L
4184 * where A refers to a piece of an array and T to the corresponding
4185 * shifted tile. We split this schedule into mappings L -> A and L -> T
4186 * and store the corresponding expressions in stmt->index and stmt->local_index,
4187 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
4189 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
4190 __isl_keep isl_ast_build *build, void *user)
4192 struct gpu_gen *gen = (struct gpu_gen *) user;
4193 struct ppcg_kernel_stmt *stmt;
4194 isl_id *id;
4195 isl_ast_expr *expr;
4196 isl_space *space;
4197 isl_map *access, *local_access, *map;
4198 isl_pw_multi_aff *pma;
4199 const char *type;
4200 int array_index;
4202 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4203 if (!stmt)
4204 return isl_ast_node_free(node);
4206 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
4207 type = isl_map_get_tuple_name(access, isl_dim_in);
4208 stmt->u.c.read = !strcmp(type, "read");
4209 access = isl_map_reverse(access);
4210 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
4211 local_access = isl_map_copy(access);
4213 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
4214 id = isl_map_get_tuple_id(access, isl_dim_out);
4215 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4216 access = isl_map_apply_range(access, map);
4217 pma = isl_pw_multi_aff_from_map(access);
4218 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4219 stmt->u.c.index = expr;
4221 map = isl_map_range_map(isl_map_universe(space));
4222 id = isl_map_get_tuple_id(local_access, isl_dim_out);
4223 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4224 local_access = isl_map_apply_range(local_access, map);
4225 pma = isl_pw_multi_aff_from_map(local_access);
4226 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4227 stmt->u.c.local_index = expr;
4229 stmt->u.c.array = gen->copy_group->array;
4230 array_index = stmt->u.c.array - gen->prog->array;
4231 stmt->u.c.local_array = &gen->kernel->array[array_index];
4232 stmt->type = ppcg_kernel_copy;
4234 id = isl_id_alloc(gen->ctx, NULL, stmt);
4235 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4236 return isl_ast_node_set_annotation(node, id);
4239 /* Given a schedule of the form
4241 * [S -> A] -> L
4243 * (with S the first shared_len dimensions of the computed schedule,
4244 * A the array and L the schedule correponding to the generated loops),
4245 * indicating where to copy the array elements that need to be copied,
4246 * construct code for performing the copying.
4248 * "group" is the array reference group that is being copied
4249 * "type" is either "read" or "write"
4250 * private is set if copying needs to be performed to/from registers
4252 * We first construct a mapping to a shifted tile of the array,
4254 * [S -> A] -> T(S,A) (1)
4256 * If private is set, then we also use this mapping as a schedule
4257 * (which is already thread-specific and will be completely unrolled).
4258 * Otherwise, we wrap/tile the range over the threads.
4259 * The result is
4261 * [S -> A] -> T'(S,A)
4263 * Combined with the given schedule, we have
4265 * [S -> A] -> [L -> T'(S,A)] (2)
4267 * From the shifted tile mapping, we construct a mapping
4269 * [S -> A] -> [A -> T(S,A)]
4271 * and apply it to the schedule (2), obtaining
4273 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
4275 * Note that we can project out S because it is uniquely defined by L.
4277 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
4278 __isl_take isl_map *sched,
4279 const char *type, struct gpu_array_ref_group *group,
4280 __isl_take isl_ast_build *build, int private)
4282 isl_space *space;
4283 isl_ast_node *tree;
4284 isl_map *schedule, *shift, *map;
4285 isl_set *set;
4286 isl_id_list *iterators;
4287 int n;
4289 shift = shift_access(group);
4291 schedule = isl_map_copy(shift);
4292 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
4293 if (!private)
4294 schedule = tile_access_schedule(gen, schedule);
4296 n = isl_map_dim(schedule, isl_dim_out);
4297 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
4298 set = add_bounded_parameters(set, gen->kernel->n_block,
4299 gen->kernel->block_dim, "t");
4301 schedule = isl_map_range_product(sched, schedule);
4303 space = isl_space_domain(isl_map_get_space(shift));
4304 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
4305 map = isl_map_range_product(map, shift);
4307 schedule = isl_map_apply_domain(schedule, map);
4309 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
4311 build = isl_ast_build_restrict(build, set);
4313 gen->copy_group = group;
4315 if (private) {
4316 space = isl_space_range(isl_map_get_space(schedule));
4317 space = isl_space_range(isl_space_unwrap(space));
4318 build = set_unroll(build, space, 0);
4320 iterators = generate_names(gen->ctx, n, "c");
4321 build = isl_ast_build_set_iterators(build, iterators);
4322 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
4323 tree = isl_ast_build_ast_from_schedule(build,
4324 isl_union_map_from_map(schedule));
4325 isl_ast_build_free(build);
4327 return tree;
4330 /* Return code for reading into or writing from shared memory
4331 * the given array reference group.
4333 * If we are performing a read from global memory to shared memory and
4334 * if the array involved is not a scalar, then we copy
4335 * the entire tile to shared memory. This may result in some extra
4336 * elements getting copied, but it should lead to simpler code
4337 * (which means that fewer registers may be needed) and less divergence.
4339 * Otherwise, we only copy the elements that will be read or have been written
4340 * in the kernel.
4343 * The input "sched" is of the form.
4345 * type[S -> A] -> L
4347 * with S the first shared_len dimensions of the computed schedule,
4348 * A the array and L the schedule correponding to the generated loops.
4350 * We first drop "type",
4352 * [S -> A] -> L
4354 * If the above conditions are satisfied, we project out A,
4355 * resulting in
4357 * S -> L
4359 * and then introduce the group tile [S -> T], resulting in
4361 * [S -> T] -> L
4363 static __isl_give isl_ast_node *copy_group_shared_accesses(
4364 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4365 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4367 const char *type;
4368 int read;
4369 isl_union_map *access;
4371 type = isl_map_get_tuple_name(sched, isl_dim_in);
4372 read = !strcmp(type, "read");
4374 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4376 if (read && !gpu_array_is_scalar(group->array)) {
4377 isl_space *space;
4378 isl_map *map;
4380 space = isl_space_domain(isl_map_get_space(sched));
4381 space = isl_space_unwrap(space);
4382 map = isl_map_domain_map(isl_map_universe(space));
4383 sched = isl_map_apply_domain(sched, map);
4385 map = group_tile(group);
4386 map = isl_map_reverse(isl_map_domain_map(map));
4387 sched = isl_map_apply_domain(sched, map);
4390 return copy_access(gen, sched, type, group, build, 0);
4393 /* Return code for reading into or writing from private memory
4394 * the given array reference group.
4396 * Let S be the first shared_len dimensions of the computed schedule,
4397 * D the iteration domains, A the array and L the schedule correponding
4398 * to the generated loops.
4399 * "sched" is of the form
4401 * type[S -> A] -> L
4403 * where type is either "read" or "write".
4404 * We apply the privatization D -> S(t), with t the thread ids,
4405 * to the access relation D -> A to obtain the privatized access relation
4407 * S(t) -> A
4409 * We drop the type from "sched" and intersect with the privatized access
4410 * relation to obtain
4412 * [S(t) -> A] -> L
4414 static __isl_give isl_ast_node *copy_group_private_accesses(
4415 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4416 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4418 const char *type;
4419 int read;
4420 isl_union_map *priv;
4421 isl_union_map *access;
4422 isl_map *access_map;
4424 type = isl_map_get_tuple_name(sched, isl_dim_in);
4425 read = !strcmp(type, "read");
4427 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
4428 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
4429 priv);
4431 access = group_access_relation(group, read, !read);
4432 access = isl_union_map_apply_domain(access, priv);
4433 access_map = isl_map_from_union_map(access);
4435 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4436 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
4438 return copy_access(gen, sched, type, group, build, 1);
4441 /* Return code for reading into or writing from shared or private memory.
4443 * "schedule" is of the form
4445 * type[S -> A] -> L
4447 * with S be the first shared_len dimensions of the computed schedule,
4448 * A the array and L the schedule correponding to the generated loops.
4449 * The array reference group is attached to "type".
4451 static __isl_give isl_ast_node *create_access_leaf(
4452 struct gpu_gen *gen, __isl_take isl_map *schedule,
4453 __isl_take isl_ast_build *build)
4455 struct gpu_array_ref_group *group;
4456 isl_id *id;
4458 id = isl_map_get_tuple_id(schedule, isl_dim_in);
4459 group = isl_id_get_user(id);
4460 isl_id_free(id);
4462 if (group->private_tile)
4463 return copy_group_private_accesses(gen, group, schedule,
4464 build);
4465 else
4466 return copy_group_shared_accesses(gen, group, schedule,
4467 build);
4470 /* Create a domain node representing a synchronization.
4472 static __isl_give isl_ast_node *create_sync_leaf(
4473 struct gpu_gen *gen, __isl_take isl_map *schedule,
4474 __isl_take isl_ast_build *build)
4476 struct ppcg_kernel_stmt *stmt;
4477 isl_id *id;
4478 isl_space *space;
4479 isl_ast_node *node;
4480 isl_ast_expr *expr;
4482 isl_map_free(schedule);
4484 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4485 if (!stmt)
4486 return NULL;
4488 stmt->type = ppcg_kernel_sync;
4490 space = isl_ast_build_get_schedule_space(build);
4491 space = isl_space_from_domain(space);
4492 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
4493 expr = isl_ast_build_call_from_pw_multi_aff(build,
4494 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
4495 node = isl_ast_node_alloc_user(expr);
4496 isl_ast_build_free(build);
4498 id = isl_id_alloc(gen->ctx, NULL, stmt);
4499 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4500 return isl_ast_node_set_annotation(node, id);
4503 /* This function is called during the code generation at the point
4504 * where the schedule domain element is completely determined by
4505 * the generated code. The input schedule contains the original
4506 * statements as well as synchronization and copy "statements".
4507 * The latter are scheduled at different points than any of the original
4508 * statements, so they will only arrive here in isolation.
4510 * If the current schedule only refers to a single statement,
4511 * we check if it is a copy or synchronization statement and
4512 * call the appropriate functions.
4513 * Otherwise, we assume we are dealing with the original statements
4514 * and we call create_domain_leaf.
4516 static __isl_give isl_ast_node *create_kernel_leaf(
4517 __isl_take isl_ast_build *build, void *user)
4519 struct gpu_gen *gen = (struct gpu_gen *) user;
4520 isl_map *map;
4521 isl_union_map *schedule;
4522 const char *name;
4524 schedule = isl_ast_build_get_schedule(build);
4526 if (isl_union_map_n_map(schedule) != 1)
4527 return create_domain_leaf(schedule, build, user);
4529 map = isl_map_from_union_map(schedule);
4530 name = isl_map_get_tuple_name(map, isl_dim_in);
4531 if (!strcmp(name, "read") || !strcmp(name, "write"))
4532 return create_access_leaf(gen, map, build);
4533 if (!strcmp(name, "sync"))
4534 return create_sync_leaf(gen, map, build);
4536 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4539 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4540 * have value 0) and all even schedule dimensions as "unroll".
4542 * That is, the options look as follows
4544 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4545 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4547 * The even positions are used to be able to schedule copying blocks
4548 * and synchronization before or after each level of the shared memory
4549 * tile loops and we want to make sure that code for these is generated
4550 * separately (within each level).
4552 static __isl_give isl_ast_build *set_atomic_and_unroll(
4553 __isl_take isl_ast_build *build,
4554 __isl_take isl_space *space, int sched_len)
4556 isl_ctx *ctx;
4557 isl_map *map;
4558 isl_constraint *c;
4559 isl_union_map *opt;
4560 isl_local_space *ls;
4561 int i, n;
4563 ctx = isl_ast_build_get_ctx(build);
4565 space = isl_space_params(space);
4566 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4567 space = isl_space_from_domain(space);
4568 space = isl_space_add_dims(space, isl_dim_out, 2);
4569 map = isl_map_universe(isl_space_copy(space));
4570 for (i = 0; i < sched_len; i += 2)
4571 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4572 ls = isl_local_space_from_space(isl_map_get_space(map));
4573 c = isl_equality_alloc(ls);
4574 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4575 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4576 c = isl_constraint_set_constant_si(c, 1);
4577 map = isl_map_add_constraint(map, c);
4578 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4579 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4580 opt = isl_union_map_from_map(map);
4582 map = isl_map_universe(space);
4583 ls = isl_local_space_from_space(isl_map_get_space(map));
4584 c = isl_equality_alloc(ls);
4585 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4586 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4587 map = isl_map_add_constraint(map, c);
4588 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4589 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4590 opt = isl_union_map_add_map(opt, map);
4592 build = isl_ast_build_set_options(build, opt);
4594 return build;
4597 /* Return a map that maps a space of dimension gen->shared_len
4598 * to its last dimensions starting at gen->tile_first.
4599 * The range is of dimension
4601 * 2 * (gen->shared_len - gen->tile_first) + 1
4603 * The input dimensions are mapped to the odd dimensions in the output,
4604 * while the even dimensions (except 2*pos) are fixed to 0.
4605 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4606 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4607 * are mapped to the output. The remaining input dimensions are projected
4608 * out and the corresponding output dimensions are fixed to 0.
4610 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4611 __isl_take isl_space *space, int pos, int val)
4613 int i, n;
4614 isl_map *proj;
4616 space = isl_space_set_from_params(space);
4617 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4618 space = isl_space_map_from_set(space);
4619 proj = isl_map_identity(space);
4620 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4621 n = gen->shared_len - gen->tile_first;
4622 for (i = 0; i <= n; ++i) {
4623 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4624 if (i == pos)
4625 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4626 else
4627 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4630 if (pos < 0)
4631 return proj;
4633 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4634 gen->shared_len - (gen->tile_first + pos));
4635 for (i = pos; i < n; ++i)
4636 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4638 return proj;
4641 /* Given the AST context schedule "schedule" and the mapping from
4642 * domains to the shared tile loops "shared_sched", add a schedule
4643 * for a synchronization operation at position "val" of loop level "pos".
4645 * schedule is of the form
4647 * D -> L
4649 * (with D the iteration domains and L the already generated loops),
4650 * while shared_sched is of the form
4652 * D -> S
4654 * We combine them into
4656 * L -> S
4658 * apply a mapping
4660 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4662 * and use the result as a schedule for "sync".
4664 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4665 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4666 __isl_keep isl_union_map *shared_sched, int pos, int val)
4668 isl_space *space;
4669 isl_map *proj, *map;
4671 shared_sched = isl_union_map_copy(shared_sched);
4672 schedule = isl_union_map_copy(schedule);
4674 space = isl_union_map_get_space(shared_sched);
4675 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4676 map = isl_map_from_union_map(schedule);
4678 proj = insert_even(gen, space, pos, val);
4679 map = isl_map_apply_range(map, proj);
4680 map = isl_map_from_range(isl_map_wrap(map));
4681 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4683 res = isl_union_map_add_map(res, map);
4685 return res;
4688 /* Given a set of wrapped references "ref", return the corresponding
4689 * access relations based on the tagged access relations "tagged".
4691 * The elements of "ref" are of the form
4693 * [D -> R]
4695 * with D an iteration domains and R a reference.
4696 * The elements of "tagged" are of the form
4698 * [D -> R] -> A
4700 * with A an array.
4702 * Extend "tagged" to include the iteration domain in the range, i.e.,
4704 * [D -> R] -> [D -> A]
4706 * apply the result to "ref" and then unwrap the resulting set
4707 * to obtain relations of the form
4709 * D -> A
4711 static __isl_give isl_union_map *wrapped_reference_to_access(
4712 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
4714 isl_union_map *tag2access;
4716 tag2access = isl_union_map_copy(tagged);
4717 tag2access = isl_union_map_universe(tag2access);
4718 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
4719 tag2access = isl_union_map_domain_map(tag2access);
4720 tag2access = isl_union_map_range_product(tag2access, tagged);
4722 ref = isl_union_set_coalesce(ref);
4723 ref = isl_union_set_apply(ref, tag2access);
4725 return isl_union_set_unwrap(ref);
4728 /* Given an access relation "access" from "group", remove those reads
4729 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
4730 * communicate data within the same iteration of the last_shared dimension
4731 * of the group.
4733 * If the access is a read then it is necessarily an element of
4735 * live_in union (range flow)
4737 * where live_in and flow may be overapproximations.
4738 * If the access is a write then it is necessarily an element of
4740 * live_out union (domain flow)
4742 * In both cases, the access relation is also a subset of
4743 * the group access relation.
4745 * Essentially, we compute the intersection of "access" with either
4747 * live_in union (range non-local-flow)
4749 * or
4751 * live_out union (domain non-local-flow)
4753 * We first construct a relation "local"
4755 * [[D -> R] -> [D' -> R']]
4757 * of pairs of domain iterations accessing the reference group
4758 * and references in the group that are scheduled to the same iteration
4759 * of the last_shared dimension.
4761 * If this relation does not intersect the dataflow dependences,
4762 * then there is nothing we can possibly remove and we simply
4763 * return the input.
4765 * Otherwise, we remove the "local" dataflow dependences from
4766 * the set of all dataflow dependences.
4767 * Note that if the potential dataflow dependences are an overapproximation
4768 * of the actual dataflow dependences, then the result remains an
4769 * overapproximation of the non-local dataflow dependences.
4770 * Copying to/from global memory is only needed for the references
4771 * in the domain/range of the result or for accesses that are live out/in
4772 * for the entire scop.
4774 * We therefore map the domain/range of the "external" relation
4775 * to the corresponding access relation and take the union with
4776 * the live out/in relation.
4778 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
4779 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
4780 int read)
4782 int empty;
4783 isl_union_map *tagger;
4784 isl_union_set *domain;
4785 isl_space *space;
4786 isl_union_map *sched, *local, *tagged, *external;
4787 isl_union_set *tag_set;
4788 isl_map *proj;
4790 if (isl_union_map_is_empty(access))
4791 return access;
4793 tagged = group_tagged_access_relation(group);
4795 sched = isl_union_map_copy(gen->sched);
4797 space = isl_union_map_get_space(sched);
4798 proj = projection(space, gen->untiled_len, group->last_shared + 1);
4799 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4801 tagger = isl_union_map_copy(gen->prog->scop->tagger);
4802 domain = isl_union_map_domain(isl_union_map_copy(tagged));
4803 tagger = isl_union_map_intersect_range(tagger, domain);
4804 sched = isl_union_map_apply_domain(sched, tagger);
4806 local = isl_union_map_apply_range(sched,
4807 isl_union_map_reverse(isl_union_map_copy(sched)));
4808 local = isl_union_map_intersect(local,
4809 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
4811 empty = isl_union_map_is_empty(local);
4812 if (empty < 0 || empty) {
4813 isl_union_map_free(tagged);
4814 isl_union_map_free(local);
4815 if (empty < 0)
4816 return isl_union_map_free(access);
4817 return access;
4820 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
4821 external = isl_union_map_intersect_params(external,
4822 isl_set_copy(gen->prog->scop->context));
4823 external = isl_union_map_subtract(external, local);
4825 if (read) {
4826 tag_set = isl_union_map_range(external);
4827 external = wrapped_reference_to_access(tag_set, tagged);
4828 external = isl_union_map_union(external,
4829 isl_union_map_copy(gen->prog->scop->live_in));
4830 } else {
4831 tag_set = isl_union_map_domain(external);
4832 external = wrapped_reference_to_access(tag_set, tagged);
4833 external = isl_union_map_union(external,
4834 isl_union_map_copy(gen->prog->scop->live_out));
4837 access = isl_union_map_intersect(access, external);
4839 return access;
4842 /* Given the AST context schedule "schedule" and the mapping from
4843 * domains to the shared tile loops "shared_sched", add a schedule
4844 * for copying an array reference group to/from shared/private memory.
4845 * "read" is set if data should be copied from global memory
4846 * to shared/private memory.
4847 * "k" represents the current group
4848 * "s" is the total number of groups
4850 * We schedule an operation before or after the innermost loop
4851 * of "shared_sched" that affects the tile of the array reference group.
4853 * schedule is of the form
4855 * D -> L
4857 * (with D the iteration domains and L the already generated loops),
4858 * while shared_sched is of the form
4860 * D -> S
4862 * We first compute the access relation for the reference group
4864 * D -> A
4866 * and remove from this access relation those reads or writes
4867 * that only needed to communicate data within the same iteration
4868 * of the last_shared dimension of the group.
4869 * We then combine what is left with shared_sched into
4871 * D -> [S -> A]
4873 * If this results in an empty relation, no copying needs to be performed
4874 * at this point.
4875 * Otherwise, we invert the relation and combine it with "schedule" into
4877 * [S -> A] -> L
4879 * The actual additional piece of the schedule is obtained from combining
4881 * [S -> A] -> S
4883 * with a mapping
4885 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4887 * The position of "val" corresponds to the innermost loop that affects
4888 * the tile and the value indicates where the copying is scheduled
4889 * with respect to the actual kernel code (at value 0).
4890 * Reads are schedule before the code, writes to global memory from
4891 * private memory are scheduled at values 1 to s, writes to global
4892 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4894 * If we are scheduling a read from global memory to shared memory,
4895 * we insert a synchronization before the kernel code (at the innermost
4896 * level).
4897 * If we are scheduling a write to global memory, then we add
4898 * a synchronization after all writes (at value 2 *s + 2).
4899 * However, there is no need for a synchronization after the outermost loop.
4900 * A write to global memory from private memory at the innermost level
4901 * does not require a synchronization, because it is covered by
4902 * the synchronization after the kernel inserted by body_schedule.
4904 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4905 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4906 __isl_keep isl_union_map *shared_sched,
4907 struct gpu_array_ref_group *group, int read, int k, int s)
4909 int n;
4910 int pos, val;
4911 isl_space *space;
4912 isl_union_map *access;
4913 isl_map *map, *proj, *access_map;
4914 isl_id *id;
4916 access = group_access_relation(group, read, !read);
4917 access = remove_local_accesses(gen, group, access, read);
4918 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4919 access);
4921 if (isl_union_map_is_empty(access)) {
4922 isl_union_map_free(access);
4923 return res;
4926 access = isl_union_map_reverse(access);
4927 access = isl_union_map_apply_range(access,
4928 isl_union_map_copy(schedule));
4929 access_map = isl_map_from_union_map(access);
4931 space = isl_space_copy(group->array->space);
4932 space = isl_space_from_range(space);
4933 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4934 map = isl_map_domain_map(isl_map_universe(space));
4936 space = isl_union_map_get_space(schedule);
4937 pos = group->last_shared + 1 - gen->tile_first;
4938 assert(pos >= 0);
4939 if (read)
4940 val = -2 - k;
4941 else if (group->private_tile)
4942 val = 1 + k;
4943 else
4944 val = 1 + s + 1 + k;
4945 proj = insert_even(gen, space, pos, val);
4946 map = isl_map_apply_range(map, proj);
4948 access_map = isl_map_range_product(access_map, map);
4950 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4951 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4953 res = isl_union_map_add_map(res, access_map);
4955 n = gen->shared_len - gen->tile_first;
4956 if (read) {
4957 if (!group->private_tile)
4958 res = add_sync_schedule(gen, res, schedule,
4959 shared_sched, n, -1);
4960 } else {
4961 if (pos == 0)
4962 return res;
4963 if (pos == n && group->private_tile)
4964 return res;
4965 res = add_sync_schedule(gen, res, schedule, shared_sched,
4966 pos, 2 * s + 2);
4969 return res;
4972 /* Return a schedule for the shared tile loops based on the current
4973 * AST context schedule.
4975 * We create a "shared_sched" that maps the domains to the first
4976 * shared_len dimensions of the computed schedule, project out the
4977 * first tile_first dimensions (as these are already covered by
4978 * the host code) and insert "statement-level" dimensions at even
4979 * positions so that we can schedule copy blocks and synchronization
4980 * before/after each level.
4982 * In particular, copy blocks are inserted inside the innermost
4983 * level that affect the tile. For the copying to global memory,
4984 * those from private memory are scheduled before those from shared
4985 * memory such that synchronization can be inserted between the two
4986 * at the innermost level.
4987 * Synchronization is inserted at the innermost level before the
4988 * actual kernel code if there is any copying from global memory
4989 * to shared memory. It is inserted unconditionally at the innermost
4990 * level after the actual kernel code and the copying to global memory
4991 * from private memory (if any). Finally, it is inserted after
4992 * any copying to global memory, except at the outermost level
4993 * and at the innermost level if there is no copying from shared
4994 * memory. The copying from private memory is covered by the unconditional
4995 * synchronization at the innermost level.
4997 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4998 __isl_take isl_union_map *schedule)
5000 isl_space *space;
5001 isl_union_map *res;
5002 isl_union_map *shared_sched;
5003 isl_union_map *sched;
5004 isl_map *proj, *map;
5005 int i, j, k, s;
5007 shared_sched = isl_union_map_copy(gen->tiled_sched);
5008 proj = projection(isl_union_map_get_space(shared_sched),
5009 gen->tiled_len, gen->shared_len);
5010 shared_sched = isl_union_map_apply_range(shared_sched,
5011 isl_union_map_from_map(proj));
5012 space = isl_union_map_get_space(shared_sched);
5013 proj = insert_even(gen, space, -1, 0);
5014 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
5015 isl_union_map_from_map(proj));
5017 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
5019 s = 0;
5020 for (i = 0; i < gen->prog->n_array; ++i)
5021 s += gen->prog->array[i].n_group;
5023 k = 0;
5024 for (i = 0; i < gen->prog->n_array; ++i) {
5025 struct gpu_array_info *array = &gen->prog->array[i];
5027 for (j = 0; j < array->n_group; ++j) {
5028 struct gpu_array_ref_group *group;
5030 group = array->groups[j];
5031 if (!group->private_tile && !group->shared_tile)
5032 continue;
5033 res = add_group_schedule(gen, res, schedule,
5034 shared_sched, group, 0, k, s);
5035 res = add_group_schedule(gen, res, schedule,
5036 shared_sched, group, 1, k, s);
5037 ++k;
5041 res = add_sync_schedule(gen, res, schedule, shared_sched,
5042 gen->shared_len - gen->tile_first, 1 + s);
5044 isl_union_map_free(shared_sched);
5045 isl_union_map_free(schedule);
5047 return res;
5050 /* Generate code for "kernel" in the given "context".
5052 * We first generate code for the shared tile loops (T1T, T1P and T2)
5053 * in a context that includes the block ids.
5054 * Within each iteration of these loops an additional code generation
5055 * is performed (within create_kernel_leaf) for the rest of the schedule
5056 * in a context that includes the thread ids.
5058 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
5059 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
5060 __isl_keep isl_multi_pw_aff *grid_size)
5062 isl_space *space;
5063 isl_set *set;
5064 isl_id_list *iterators;
5065 isl_union_map *schedule;
5066 isl_ast_node *tree;
5067 int sched_len;
5069 schedule = isl_ast_build_get_schedule(build);
5071 build = isl_ast_build_copy(build);
5072 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
5073 space = isl_ast_build_get_schedule_space(build);
5074 set = isl_set_universe(isl_space_copy(space));
5075 set = add_bounded_parameters_dynamic(set, grid_size, "b");
5076 build = isl_ast_build_restrict(build, set);
5078 schedule = body_schedule(gen, schedule);
5080 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
5082 build = set_atomic_and_unroll(build, space, sched_len);
5083 iterators = generate_names(gen->ctx, sched_len, "g");
5084 build = isl_ast_build_set_iterators(build, iterators);
5085 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
5086 tree = isl_ast_build_ast_from_schedule(build, schedule);
5087 isl_ast_build_free(build);
5089 return tree;
5092 /* Attach "id" to the given node.
5094 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
5095 __isl_keep isl_ast_build *build, void *user)
5097 isl_id *id = user;
5099 node = isl_ast_node_set_annotation(node, id);
5101 return node;
5104 /* Construct an AST node for performing a kernel launch and attach
5105 * the information about the kernel to that node.
5107 * The kernel AST has been constructed in the context of the range
5108 * of "schedule". In particular, the grid size has been computed
5109 * in the context. We therefore still need to make sure that these
5110 * constraints are expressed in the code. We do this by creating a schedule
5112 * kernel[] -> [S -> []]
5114 * where S is the schedule domain, i.e., the range of "schedule".
5115 * The AST generation will then create a single call surrounded by
5116 * all the condition in "S" that have not been expressed yet.
5118 * The kernel information is attached to this node in attach_id.
5120 static __isl_give isl_ast_node *construct_launch(
5121 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
5122 __isl_take struct ppcg_kernel *kernel)
5124 isl_id *id;
5125 isl_ctx *ctx;
5126 isl_union_set *domain;
5127 isl_set *set;
5128 isl_map *map;
5129 isl_ast_node *node;
5131 ctx = isl_ast_build_get_ctx(build);
5133 id = isl_id_alloc(ctx, NULL, kernel);
5134 id = isl_id_set_free_user(id, &ppcg_kernel_free);
5136 domain = isl_union_map_range(schedule);
5137 set = isl_set_from_union_set(domain);
5138 map = isl_map_from_domain(set);
5139 map = isl_map_from_range(isl_map_wrap(map));
5140 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
5141 schedule = isl_union_map_from_map(map);
5143 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
5144 node = isl_ast_build_ast_from_schedule(build, schedule);
5145 isl_ast_build_free(build);
5147 return node;
5150 /* This function is called for each leaf in the AST of the host code.
5151 * We first specialize the schedule to the site of the leaf, compute
5152 * the size of shared memory and then construct the body of the host code
5153 * and the associated kernel.
5155 * The necessary information for printing the kernel launch is
5156 * stored in a struct ppcg_kernel and attached to the leaf node
5157 * created to represent the launch.
5159 static __isl_give isl_ast_node *create_host_leaf(
5160 __isl_take isl_ast_build *build, void *user)
5162 struct gpu_gen *gen = (struct gpu_gen *) user;
5163 isl_id *id;
5164 isl_ast_node *node;
5165 struct ppcg_kernel *kernel;
5166 isl_set *host_domain;
5167 isl_union_map *schedule;
5168 isl_union_map *local_sched;
5169 isl_union_map *access;
5170 isl_union_set *domain;
5171 int i;
5173 schedule = isl_ast_build_get_schedule(build);
5175 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
5176 read_sizes(gen);
5178 domain = isl_union_map_domain(isl_union_map_copy(schedule));
5180 local_sched = isl_union_map_copy(gen->sched);
5181 local_sched = isl_union_map_intersect_domain(local_sched, domain);
5182 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
5183 isl_union_map_copy(gen->prog->may_write));
5184 access = isl_union_map_apply_domain(access,
5185 isl_union_map_copy(local_sched));
5187 gen->tiled_sched = tile_schedule(gen, local_sched);
5188 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
5189 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
5191 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
5192 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
5193 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
5195 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
5196 if (!kernel)
5197 goto error;
5199 kernel->id = gen->kernel_id++;
5200 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
5201 kernel->grid_size = extract_grid_size(gen, kernel);
5202 extract_block_size(gen, kernel);
5203 kernel->arrays = isl_union_map_range(access);
5204 kernel->arrays = isl_union_set_apply(kernel->arrays,
5205 isl_union_map_copy(gen->prog->to_outer));
5206 kernel->space = isl_ast_build_get_schedule_space(build);
5208 gen->private_access = NULL;
5209 compute_shared_sched(gen);
5210 gen->privatization = compute_privatization(gen);
5211 check_scalar_live_ranges(gen);
5212 if (group_references(gen) < 0)
5213 schedule = isl_union_map_free(schedule);
5214 compute_private_access(gen);
5215 host_domain = isl_set_from_union_set(isl_union_map_range(
5216 isl_union_map_copy(schedule)));
5217 localize_bounds(gen, kernel, host_domain);
5219 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
5220 check_shared_memory_bound(gen);
5221 compute_group_tilings(gen);
5223 kernel->tree = generate_kernel(gen, build, host_domain,
5224 kernel->grid_size);
5225 create_kernel_vars(gen, kernel);
5227 free_local_array_info(gen);
5228 isl_map_free(gen->privatization);
5229 isl_union_map_free(gen->private_access);
5230 isl_union_map_free(gen->local_sched);
5231 isl_union_map_free(gen->tiled_sched);
5232 isl_union_map_free(gen->shared_sched);
5233 isl_union_map_free(gen->shared_proj);
5234 isl_set_free(host_domain);
5235 free(gen->tile_size);
5237 node = construct_launch(build, schedule, kernel);
5239 return node;
5240 error:
5241 isl_union_map_free(schedule);
5242 return NULL;
5245 /* Use isl to generate code for the outer gen->tile_first loops
5246 * of the global schedule in gen->sched, resulting in the host code.
5247 * Within each iteration of this partial schedule, i.e., for each kernel
5248 * launch, create_host_leaf takes care of generating the kernel code.
5250 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
5252 isl_ast_build *build;
5253 isl_ast_node *tree;
5254 isl_union_map *sched;
5255 isl_map *proj;
5256 isl_id_list *iterators;
5258 sched = isl_union_map_copy(gen->sched);
5259 proj = projection(isl_union_map_get_space(sched),
5260 gen->untiled_len, gen->tile_first);
5261 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
5263 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
5264 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
5265 iterators = generate_names(gen->ctx, gen->tile_first, "h");
5266 build = isl_ast_build_set_iterators(build, iterators);
5267 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
5268 tree = isl_ast_build_ast_from_schedule(build, sched);
5269 isl_ast_build_free(build);
5271 return tree;
5274 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
5276 if (!str)
5277 return NULL;
5278 return isl_union_map_read_from_str(ctx, str);
5281 /* Information about the outermost tilable bands in the forest of bands.
5283 * tile_len and n_parallel are only sets on band_info structures
5284 * that correspond to outermost bands. For other bands (in particular,
5285 * ancestors of the outermost bands), n_parallal is set to 0.
5287 * prefix is the (padded) schedule leading up to the outermost tilable bands.
5289 * tile_first is the number of schedule dimensions in prefix.
5291 * suffix is the schedule of the outermost tilable bands and their descendants.
5293 struct band_info {
5294 struct gpu_gen *gen;
5295 int tile_first;
5296 int tile_len;
5297 int n_parallel;
5298 isl_union_map *prefix;
5299 isl_union_map *suffix;
5302 /* Set tile_len and n_parallel of the statement to that of
5303 * their outermost band, recorded in the band_info.
5305 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
5307 struct band_info *info = user;
5308 struct gpu_stmt *stmt;
5309 isl_id *id;
5311 id = isl_map_get_tuple_id(map, isl_dim_in);
5312 stmt = find_stmt(info->gen->prog, id);
5313 isl_id_free(id);
5315 stmt->tile_len = info->tile_len;
5316 stmt->n_parallel = info->n_parallel;
5318 isl_map_free(map);
5320 return 0;
5323 static void list_select_outer_band(struct gpu_gen *gen,
5324 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
5326 /* Check if this band has any parallel loops. If so, take it as
5327 * the outermost tilable band. If not, continue looking for the
5328 * outermost tilable band in the children of the current band.
5330 static void band_select_outer_band(struct gpu_gen *gen,
5331 __isl_take isl_band *band, int pos, struct band_info *info)
5333 int n = isl_band_n_member(band);
5334 int n_parallel;
5336 for (n_parallel = 0; n_parallel < n; ++n_parallel)
5337 if (!isl_band_member_is_coincident(band, n_parallel))
5338 break;
5340 info->n_parallel = n_parallel;
5341 if (n_parallel) {
5342 gen->any_parallelism = 1;
5343 info->gen = gen;
5344 info->tile_first = pos;
5345 info->tile_len = n;
5346 info->prefix = isl_band_get_prefix_schedule(band);
5347 info->suffix = isl_union_map_flat_range_product(
5348 isl_band_get_partial_schedule(band),
5349 isl_band_get_suffix_schedule(band));
5350 isl_union_map_foreach_map(info->prefix,
5351 &set_stmt_tile_len, info);
5352 } else if (isl_band_has_children(band)) {
5353 isl_band_list *children;
5354 children = isl_band_get_children(band);
5355 list_select_outer_band(gen, children, pos + n, info);
5356 } else {
5357 info->gen = gen;
5358 info->tile_first = pos + n;
5359 info->tile_len = 0;
5360 info->prefix = isl_union_map_flat_range_product(
5361 isl_band_get_prefix_schedule(band),
5362 isl_band_get_partial_schedule(band));
5363 info->suffix = isl_band_get_suffix_schedule(band);
5364 isl_union_map_foreach_map(info->prefix,
5365 &set_stmt_tile_len, info);
5368 isl_band_free(band);
5371 /* Comparison function that returns a non-zero value for band_infos
5372 * with different tile_len fields or different n_parallel fields.
5374 static int cmp_band(const void *p1, const void *p2)
5376 const struct band_info *info1 = p1;
5377 const struct band_info *info2 = p2;
5379 if (info1->tile_len != info2->tile_len)
5380 return info1->tile_len - info2->tile_len;
5382 return info1->n_parallel - info2->n_parallel;
5385 /* Extend "umap" with coordinates with fixed value "val"
5386 * to a total length of "dst_len", assuming the original dimension is "src_len".
5388 static __isl_give isl_union_map *extend_range(
5389 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
5391 isl_space *dim;
5392 isl_map *map;
5393 int i;
5395 dim = isl_union_map_get_space(umap);
5396 map = isl_map_reverse(projection(dim, dst_len, src_len));
5397 for (i = src_len; i < dst_len; ++i)
5398 map = isl_map_fix_si(map, isl_dim_out, i, val);
5400 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
5402 return umap;
5405 /* Group bands with the same values for tile_len and n_parallel.
5406 * The prefix schedule is then extended with a fixed coordinate that
5407 * is different for each such group.
5408 * Note that the actual values for this coordinate are not important.
5409 * The bands have already been effectively separated at a higher level
5410 * or they are independent and may be executed in parallel.
5411 * The list of band_info has been sorted before this functions is called.
5413 static void separate_bands(struct band_info *info, int n)
5415 int i;
5416 int j = 0;
5418 for (i = 0; i < n; ++i) {
5419 int l = info[i].tile_first;
5421 if (i &&
5422 (info[i].tile_len != info[i - 1].tile_len ||
5423 info[i].n_parallel != info[i - 1].n_parallel))
5424 j++;
5426 info[i].prefix = extend_range(info[i].prefix,
5427 l, l + 1, j);
5428 info[i].tile_first = l + 1;
5432 /* Select the outermost bands in the elements of the list, align
5433 * their prefix schedules, separate bands with different values
5434 * for tile_len and/or n_parallel and then combine the resulting
5435 * prefix and suffix schedules into a single pair of prefix and
5436 * suffix schedules for the entire list.
5438 static void list_select_outer_band(struct gpu_gen *gen,
5439 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
5441 isl_band *band;
5442 int i;
5443 int n = isl_band_list_n_band(list);
5444 isl_ctx *ctx = isl_band_list_get_ctx(list);
5445 struct band_info *info;
5446 int max_tile_first;
5447 isl_union_map *prefix;
5448 isl_union_map *suffix;
5450 assert(n >= 1);
5451 info = isl_calloc_array(ctx, struct band_info, n);
5452 assert(info);
5454 max_tile_first = 0;
5455 for (i = 0; i < n; ++i) {
5456 band = isl_band_list_get_band(list, i);
5457 band_select_outer_band(gen, band, pos, &info[i]);
5458 if (info[i].tile_first > max_tile_first)
5459 max_tile_first = info[i].tile_first;
5462 for (i = 0; i < n; ++i) {
5463 if (info[i].tile_first == max_tile_first)
5464 continue;
5465 info[i].prefix = extend_range(info[i].prefix,
5466 info[i].tile_first, max_tile_first, 0);
5467 info[i].tile_first = max_tile_first;
5470 qsort(info, n, sizeof(struct band_info), &cmp_band);
5472 for (i = 0; i < n - 1; ++i)
5473 if (info[i].tile_len != info[i + 1].tile_len ||
5474 info[i].n_parallel != info[i + 1].n_parallel)
5475 break;
5477 if (i < n -1)
5478 separate_bands(info, n);
5480 prefix = info[0].prefix;
5481 suffix = info[0].suffix;
5483 for (i = 1; i < n; ++i) {
5484 prefix = isl_union_map_union(prefix, info[i].prefix);
5485 suffix = isl_union_map_union(suffix, info[i].suffix);
5488 list_info->tile_first = info[0].tile_first;
5489 list_info->tile_len = -1;
5490 list_info->prefix = prefix;
5491 list_info->suffix = suffix;
5493 isl_band_list_free(list);
5494 free(info);
5497 /* Select the outermost tilable band that (by construction)
5498 * has at least one parallel loop.
5499 * The starting position of the aligned band is stored in the pair
5500 * gen->tile_first.
5501 * The sizes and number of parallel loops may be different in different
5502 * parts of the band forest and are therefore stored in the gpu_stmts.
5504 * Return the complete schedule, with the tilable bands aligned
5505 * at gen->tile_first and padded with zero, if needed.
5507 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
5508 __isl_keep isl_schedule *schedule)
5510 isl_band_list *list;
5511 struct band_info info;
5513 gen->n_parallel = 0;
5514 gen->tile_len = -1;
5516 list = isl_schedule_get_band_forest(schedule);
5518 if (isl_band_list_n_band(list) == 0) {
5519 isl_band_list_free(list);
5520 return isl_schedule_get_map(schedule);
5523 list_select_outer_band(gen, list, 0, &info);
5525 gen->tile_first = info.tile_first;
5526 info.suffix = align_range(info.suffix);
5528 return isl_union_map_flat_range_product(info.prefix, info.suffix);
5531 /* Set gen->untiled_len to the number of scheduling dimensions
5532 * for the schedule of the first domain.
5533 * We assume here that this number is the same for all domains.
5535 static int set_untiled_len(__isl_take isl_map *map, void *user)
5537 unsigned *untiled_len = user;
5539 *untiled_len = isl_map_dim(map, isl_dim_out);
5541 isl_map_free(map);
5542 return -1;
5545 /* Compute an appropriate schedule based on the accesses in
5546 * gen->read and gen->write.
5548 * We use the dependences in gen->prog->scop to compute
5549 * a schedule that has a parallel loop in each tilable band.
5550 * Finally, we select the outermost tilable band.
5552 * If live range reordering is allowed, then we need to make sure
5553 * that live ranges on arrays are not run in parallel since doing
5554 * so would require array expansion. We therefore add the array
5555 * order dependences to the coincidence dependences. Non-zero array
5556 * order dependences will then prevent a schedule dimension from being
5557 * considered parallel.
5558 * Live ranges derived from scalars are allowed to be run in parallel
5559 * since we force the scalars to be mapped to private memory in
5560 * check_scalar_live_ranges.
5561 * If live range reordering is allowed, then the false dependences
5562 * are not added to the validity constraints as that would prevent
5563 * reordering. Instead, the external false dependences that enforce that reads
5564 * from potentially live-in data precede any later write and
5565 * that writes of potentially live-out data follow any other earlier write
5566 * are added to the validity and the coincidence constraints.
5567 * The false dependences are still added to the proximity constraints
5568 * for consistency with the case where live range reordering is not allowed.
5569 * The coincidence constraints then consist of flow dependences,
5570 * exernal false dependences and array order dependences.
5571 * The independences can be filtered out from the first two sets.
5572 * They have already been filtered out from the array order dependences
5573 * on a per array basis in collect_order_dependences.
5574 * There is no need for a per array handling of the other two sets
5575 * as there should be no flow or external false dependence on local
5576 * variables that can be filtered out.
5578 static void compute_schedule(struct gpu_gen *gen)
5580 isl_union_set *domain;
5581 isl_union_map *dep_raw, *dep;
5582 isl_union_map *validity, *proximity, *coincidence;
5583 isl_union_map *sched;
5584 isl_schedule_constraints *sc;
5585 isl_schedule *schedule;
5587 domain = isl_union_set_copy(gen->prog->scop->domain);
5588 domain = isl_union_set_intersect_params(domain,
5589 isl_set_copy(gen->prog->scop->context));
5590 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
5591 if (gen->options->live_range_reordering) {
5592 sc = isl_schedule_constraints_set_conditional_validity(sc,
5593 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
5594 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
5595 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
5596 validity = isl_union_map_copy(proximity);
5597 validity = isl_union_map_union(validity,
5598 isl_union_map_copy(gen->prog->scop->dep_external));
5599 proximity = isl_union_map_union(proximity,
5600 isl_union_map_copy(gen->prog->scop->dep_false));
5601 coincidence = isl_union_map_copy(validity);
5602 coincidence = isl_union_map_subtract(coincidence,
5603 isl_union_map_copy(gen->prog->scop->independence));
5604 coincidence = isl_union_map_union(coincidence,
5605 isl_union_map_copy(gen->prog->array_order));
5606 } else {
5607 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
5608 dep = isl_union_map_copy(gen->prog->scop->dep_false);
5609 dep = isl_union_map_union(dep, dep_raw);
5610 dep = isl_union_map_coalesce(dep);
5611 proximity = isl_union_map_copy(dep);
5612 coincidence = isl_union_map_copy(dep);
5613 validity = dep;
5615 sc = isl_schedule_constraints_set_validity(sc, validity);
5616 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
5617 sc = isl_schedule_constraints_set_proximity(sc, proximity);
5619 if (gen->options->debug->dump_schedule_constraints)
5620 isl_schedule_constraints_dump(sc);
5621 schedule = isl_schedule_constraints_compute_schedule(sc);
5622 if (gen->options->debug->dump_schedule)
5623 isl_schedule_dump(schedule);
5625 sched = select_outer_tilable_band(gen, schedule);
5627 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
5628 sched = isl_union_map_intersect_domain(sched, domain);
5629 gen->sched = sched;
5631 isl_schedule_free(schedule);
5634 /* Compute the sets of outer array elements that need to be copied in and out.
5636 * In particular, for each array that is possibly written anywhere in
5637 * gen->prog and that is visible outside the corresponding scop,
5638 * we copy out its entire extent.
5640 * Any array elements that is read without first being written needs
5641 * to be copied in. Furthermore, if there are any array elements that
5642 * are copied out, but that may not be written inside gen->prog, then
5643 * they also need to be copied in to ensure that the value after execution
5644 * is the same as the value before execution.
5645 * In case the array elements are structures, we need to take into
5646 * account that all members of the structures need to be written
5647 * by gen->prog before we can avoid copying the data structure in.
5649 * While computing the set of array elements that are copied out but
5650 * not necessarily written, we intersect both sets with the context.
5651 * This helps in those cases where the arrays are declared with a fixed size,
5652 * while the accesses are parametric and the context assigns a fixed value
5653 * to the parameters.
5655 * If an element from a local array is read without first being written,
5656 * then there is no point in copying it in since it cannot have been
5657 * written prior to the scop. Warn about the uninitialized read instead.
5659 static void compute_copy_in_and_out(struct gpu_gen *gen)
5661 int i;
5662 isl_union_set *local;
5663 isl_union_set *may_write, *must_write;
5664 isl_union_set *copy_in, *copy_out;
5665 isl_union_set *not_written;
5666 isl_union_map *uninitialized;
5667 isl_union_map *local_uninitialized;
5669 must_write = isl_union_map_range(
5670 isl_union_map_copy(gen->prog->must_write));
5671 must_write = isl_union_set_intersect_params(must_write,
5672 isl_set_copy(gen->prog->context));
5673 may_write = isl_union_map_range(
5674 isl_union_map_copy(gen->prog->may_write));
5675 may_write = isl_union_set_intersect_params(may_write,
5676 isl_set_copy(gen->prog->context));
5677 may_write = isl_union_set_universe(may_write);
5678 may_write = isl_union_set_apply(may_write,
5679 isl_union_map_copy(gen->prog->to_outer));
5680 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
5681 local = isl_union_set_copy(copy_out);
5683 for (i = 0; i < gen->prog->n_array; ++i) {
5684 isl_space *space;
5685 isl_set *write_i;
5686 int empty;
5688 space = isl_space_copy(gen->prog->array[i].space);
5690 if (gen->prog->array[i].local) {
5691 isl_set *set;
5693 set = isl_set_universe(space);
5694 local = isl_union_set_add_set(local, set);
5695 continue;
5698 write_i = isl_union_set_extract_set(may_write, space);
5699 empty = isl_set_plain_is_empty(write_i);
5700 isl_set_free(write_i);
5701 if (empty)
5702 continue;
5704 write_i = isl_set_copy(gen->prog->array[i].extent);
5705 copy_out = isl_union_set_add_set(copy_out, write_i);
5707 isl_union_set_free(may_write);
5709 copy_out = isl_union_set_intersect_params(copy_out,
5710 isl_set_copy(gen->prog->context));
5712 gen->prog->copy_out = isl_union_set_copy(copy_out);
5714 copy_out = isl_union_set_apply(copy_out,
5715 isl_union_map_copy(gen->prog->to_inner));
5716 not_written = isl_union_set_subtract(copy_out, must_write);
5718 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
5719 local_uninitialized = isl_union_map_copy(uninitialized);
5721 local = isl_union_set_apply(local,
5722 isl_union_map_copy(gen->prog->to_inner));
5723 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5724 local);
5725 if (!isl_union_map_is_empty(local_uninitialized)) {
5726 fprintf(stderr,
5727 "possibly uninitialized reads (not copied in):\n");
5728 isl_union_map_dump(local_uninitialized);
5730 uninitialized = isl_union_map_subtract(uninitialized,
5731 local_uninitialized);
5732 copy_in = isl_union_map_range(uninitialized);
5733 copy_in = isl_union_set_union(copy_in, not_written);
5734 copy_in = isl_union_set_apply(copy_in,
5735 isl_union_map_copy(gen->prog->to_outer));
5737 gen->prog->copy_in = copy_in;
5740 /* Internal data structure for extract_access.
5741 * "next_access" points to the end of a linked list that is extended
5742 * by extract_access.
5743 * "single_expression" is set if the access expressions belong to
5744 * an expression statement (i.e., a statement without internal control).
5745 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5747 struct ppcg_extract_access_data {
5748 struct gpu_stmt_access **next_access;
5749 int single_expression;
5750 isl_union_map *any_to_outer;
5753 /* Extract a gpu_stmt_access from "expr", append it to the list
5754 * that ends in *data->next_access and update the end of the list.
5755 * If the access expression performs a write, then it is considered
5756 * exact only if it appears in a single expression statement and
5757 * if its may access relation is equal to its must access relation.
5759 * The combined set of may accesses may be union if member accesses
5760 * are involved, but the entire set is derived from a single reference and
5761 * therefore from a single index expression. These accesses therefore
5762 * all map to the same outer array.
5764 static int extract_access(__isl_keep pet_expr *expr, void *user)
5766 struct ppcg_extract_access_data *data = user;
5767 isl_union_map *may, *tagged;
5768 struct gpu_stmt_access *access;
5769 isl_ctx *ctx;
5770 isl_multi_pw_aff *index;
5772 may = pet_expr_access_get_may_read(expr);
5773 may = isl_union_map_union(may, pet_expr_access_get_may_write(expr));
5774 may = isl_union_map_apply_range(may,
5775 isl_union_map_copy(data->any_to_outer));
5776 ctx = isl_union_map_get_ctx(may);
5777 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5778 assert(access);
5779 access->next = NULL;
5780 access->read = pet_expr_access_is_read(expr);
5781 access->write = pet_expr_access_is_write(expr);
5782 tagged = pet_expr_access_get_tagged_may_read(expr);
5783 tagged = isl_union_map_union(tagged,
5784 pet_expr_access_get_tagged_may_write(expr));
5785 tagged = isl_union_map_apply_range(tagged,
5786 isl_union_map_copy(data->any_to_outer));
5787 access->tagged_access = isl_map_from_union_map(tagged);
5788 if (!access->write) {
5789 access->exact_write = 1;
5790 } else if (!data->single_expression) {
5791 access->exact_write = 0;
5792 } else {
5793 isl_union_map *must;
5794 must = pet_expr_access_get_must_write(expr);
5795 access->exact_write = isl_union_map_is_equal(must, may);
5796 isl_union_map_free(must);
5798 access->access = isl_map_from_union_map(may);
5799 index = pet_expr_access_get_index(expr);
5800 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5801 isl_multi_pw_aff_free(index);
5802 access->ref_id = pet_expr_access_get_ref_id(expr);
5803 access->group = -1;
5805 *data->next_access = access;
5806 data->next_access = &(*data->next_access)->next;
5808 return 0;
5811 /* Construct a linked list of gpu_stmt_access objects,
5812 * one for each access expression in the statement body.
5813 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5815 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5816 __isl_keep isl_union_map *any_to_outer)
5818 struct ppcg_extract_access_data data;
5820 stmt->accesses = NULL;
5821 data.next_access = &stmt->accesses;
5822 data.single_expression =
5823 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5824 data.any_to_outer = any_to_outer;
5825 pet_tree_foreach_access_expr(stmt->stmt->body, &extract_access, &data);
5828 /* Return an array of gpu_stmt representing the statements in "scop".
5830 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5831 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
5833 int i;
5834 struct gpu_stmt *stmts;
5836 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5837 if (!stmts)
5838 return NULL;
5840 for (i = 0; i < scop->pet->n_stmt; ++i) {
5841 struct gpu_stmt *s = &stmts[i];
5843 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5844 s->stmt = scop->pet->stmts[i];
5845 pet_stmt_extract_accesses(s, any_to_outer);
5848 return stmts;
5851 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5853 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5855 struct gpu_gen *gen = user;
5857 return gen->print(p, gen->prog, gen->tree, &gen->types,
5858 gen->print_user);
5861 /* Generate CUDA code for "scop" and print it to "p".
5862 * After generating an AST for the transformed scop as explained below,
5863 * we call "gen->print" to print the AST in the desired output format
5864 * to "p".
5866 * If it turns out that it does not make sense to generate GPU code,
5867 * then we generate CPU code instead.
5869 * The GPU code is generated in a context where at least one
5870 * statement instance is executed. The corresponding guard (if any) is printed
5871 * around the entire generated GPU code, except for the declaration
5872 * of the arrays that are visible outside of the scop and that therefore
5873 * cannot be declared inside the body of any possible guard.
5875 * We first compute a schedule that respects the dependences
5876 * of the original program and select the outermost band
5877 * of tilable dimensions that has at least one parallel loop.
5878 * We then have three blocks of dimensions
5880 * H B G
5882 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5883 * in
5885 * H T P G
5887 * For each iteration of the T loop and for each array, we compute
5888 * the array elements accessed by that iteration, construct a rectangular
5889 * box around it and shift it to the origin. The result is used
5890 * as shared memory for the array.
5892 * We then split off at most 2 parallel loops from the T loops and
5893 * at most 3 parallel loops from the P loops
5895 * H T1 T2 P1 P2 G
5897 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5898 * according to "grid"/"block" sizes.
5900 * H T1T T1P T2 P1T P1P P2 G
5902 * Finally, the T1P and P1P iterators are equated to the block and
5903 * thread dimensions respectively and so are effectively removed.
5904 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5905 * are run on the GPU.
5907 * Code is generated in three stages. We first generate code for the
5908 * host (the H loops), with iterators h%d. Then, for each leaf node
5909 * of the resulting AST, we generate code for the shared loops (up to
5910 * and including T2), with iterators g%d and after equating the H loops
5911 * to h%d parameters and the T1P loops to the block dimensions.
5912 * Finally, we generate code for the remaining loops in a similar fashion.
5914 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5915 struct gpu_gen *gen, struct ppcg_scop *scop,
5916 struct ppcg_options *options)
5918 struct gpu_prog *prog;
5919 isl_ctx *ctx;
5920 isl_set *context, *guard;
5922 if (!scop)
5923 return isl_printer_free(p);
5925 ctx = isl_printer_get_ctx(p);
5926 prog = gpu_prog_alloc(ctx, scop);
5927 if (!prog)
5928 return isl_printer_free(p);
5930 context = isl_set_copy(prog->context);
5931 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5932 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5934 gen->prog = prog;
5935 gen->any_parallelism = 0;
5936 compute_schedule(gen);
5938 if (!gen->any_parallelism) {
5939 isl_set_free(context);
5940 isl_set_free(guard);
5941 p = print_cpu(p, scop, options);
5942 } else {
5943 compute_copy_in_and_out(gen);
5944 gen->tree = generate_host_code(gen);
5945 p = ppcg_print_exposed_declarations(p, prog->scop);
5946 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5947 isl_ast_node_free(gen->tree);
5950 isl_union_map_free(gen->sched);
5952 gpu_prog_free(prog);
5954 return p;
5957 /* Wrapper around generate for use as a ppcg_transform callback.
5959 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5960 struct ppcg_scop *scop, void *user)
5962 struct gpu_gen *gen = user;
5964 return generate(p, gen, scop, gen->options);
5967 /* Transform the code in the file called "input" by replacing
5968 * all scops by corresponding GPU code and write the results to "out".
5970 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5971 struct ppcg_options *options,
5972 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5973 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5974 struct gpu_types *types, void *user), void *user)
5976 struct gpu_gen gen;
5977 int r;
5978 int i;
5980 gen.ctx = ctx;
5981 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5982 gen.options = options;
5983 gen.kernel_id = 0;
5984 gen.print = print;
5985 gen.print_user = user;
5986 gen.types.n = 0;
5987 gen.types.name = NULL;
5989 if (options->debug->dump_sizes) {
5990 isl_space *space = isl_space_params_alloc(ctx, 0);
5991 gen.used_sizes = isl_union_map_empty(space);
5994 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5996 if (options->debug->dump_sizes) {
5997 isl_union_map_dump(gen.used_sizes);
5998 isl_union_map_free(gen.used_sizes);
6001 isl_union_map_free(gen.sizes);
6002 for (i = 0; i < gen.types.n; ++i)
6003 free(gen.types.name[i]);
6004 free(gen.types.name);
6006 return r;
6009 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
6011 struct gpu_prog *prog;
6012 isl_space *space;
6013 isl_map *id;
6015 if (!scop)
6016 return NULL;
6018 prog = isl_calloc_type(ctx, struct gpu_prog);
6019 assert(prog);
6021 prog->ctx = ctx;
6022 prog->scop = scop;
6023 prog->context = isl_set_copy(scop->context);
6024 prog->n_stmts = scop->pet->n_stmt;
6025 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
6026 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
6027 space = isl_union_map_get_space(prog->any_to_outer);
6028 space = isl_space_set_from_params(space);
6029 space = isl_space_add_dims(space, isl_dim_set, 1);
6030 space = isl_space_map_from_set(space);
6031 id = isl_map_identity(space);
6032 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
6033 prog->stmts = extract_stmts(ctx, scop,
6034 prog->context, prog->any_to_outer);
6035 prog->read = isl_union_map_copy(scop->reads);
6036 prog->may_write = isl_union_map_copy(scop->may_writes);
6037 prog->must_write = isl_union_map_copy(scop->must_writes);
6038 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
6039 prog->to_outer = isl_union_map_copy(prog->to_inner);
6040 prog->to_outer = isl_union_map_reverse(prog->to_outer);
6042 if (!prog->stmts)
6043 return gpu_prog_free(prog);
6045 if (collect_array_info(prog) < 0)
6046 return gpu_prog_free(prog);
6048 return prog;
6051 void *gpu_prog_free(struct gpu_prog *prog)
6053 if (!prog)
6054 return NULL;
6055 free_array_info(prog);
6056 free_stmts(prog->stmts, prog->n_stmts);
6057 isl_union_map_free(prog->any_to_outer);
6058 isl_union_map_free(prog->to_outer);
6059 isl_union_map_free(prog->to_inner);
6060 isl_union_set_free(prog->copy_in);
6061 isl_union_set_free(prog->copy_out);
6062 isl_union_map_free(prog->read);
6063 isl_union_map_free(prog->may_write);
6064 isl_union_map_free(prog->must_write);
6065 isl_union_map_free(prog->array_order);
6066 isl_set_free(prog->context);
6067 free(prog);
6068 return NULL;