gpu.c: compute_schedule: exploit independences
[ppcg.git] / gpu.c
blobd52eabdb37ec2b645ba2d219093d92aa5de5cfda
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.
99 isl_map *access;
100 int write;
101 int exact_write;
103 /* The shared memory tile, NULL if none. */
104 struct gpu_array_tile *shared_tile;
106 /* The private memory tile, NULL if none. */
107 struct gpu_array_tile *private_tile;
109 /* References in this group; point to elements of a linked list. */
110 int n_ref;
111 struct gpu_stmt_access **refs;
113 /* Last shared memory tile dimension that affects tile of this group. */
114 int last_shared;
117 struct gpu_gen {
118 isl_ctx *ctx;
119 struct ppcg_options *options;
121 /* Callback for printing of AST in appropriate format. */
122 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
123 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
124 struct gpu_types *types, void *user);
125 void *print_user;
127 struct gpu_prog *prog;
128 /* The generated AST. */
129 isl_ast_node *tree;
131 /* The sequence of types for which a definition has been printed. */
132 struct gpu_types types;
134 /* tile, grid and block sizes for each kernel */
135 isl_union_map *sizes;
137 /* Identifier of current kernel. */
138 int kernel_id;
139 /* Pointer to the current kernel. */
140 struct ppcg_kernel *kernel;
141 /* Does the computed schedule exhibit any parallelism? */
142 int any_parallelism;
144 /* First tile dimension. */
145 int tile_first;
146 /* Number of tile dimensions. */
147 int tile_len;
148 /* Number of initial parallel loops among tile dimensions. */
149 int n_parallel;
151 /* Number of dimensions determining shared memory. */
152 int shared_len;
154 /* Number of rows in the untiled schedule. */
155 int untiled_len;
156 /* Number of rows in the tiled schedule. */
157 int tiled_len;
158 /* Number of rows in schedule after tiling/wrapping over threads. */
159 int thread_tiled_len;
161 /* Global untiled schedule. */
162 isl_union_map *sched;
163 /* Local (per kernel launch) tiled schedule. */
164 isl_union_map *tiled_sched;
165 /* Local schedule per shared memory tile loop iteration. */
166 isl_union_map *local_sched;
168 /* Local tiled schedule projected onto the shared tile loops and
169 * the loops that will be wrapped over the threads,
170 * with all shared tile loops parametrized.
172 isl_union_map *shared_sched;
173 /* Projects out the loops that will be wrapped over the threads
174 * from shared_sched.
176 isl_union_map *shared_proj;
178 /* A map that takes the range of shared_sched as input,
179 * wraps the appropriate loops over the threads and then projects
180 * out these loops.
182 isl_map *privatization;
184 /* A map from the shared memory tile loops and the thread indices
185 * (as parameters) to the set of accessed memory elements that
186 * will be accessed through private copies.
188 isl_union_map *private_access;
190 /* The schedule for the current private/shared access
191 * (within print_private_access or print_shared_access).
193 isl_map *copy_sched;
194 /* The array reference group corresponding to copy_sched. */
195 struct gpu_array_ref_group *copy_group;
197 /* Is any array in the current kernel marked force_private? */
198 int any_force_private;
200 /* First loop to unroll (or -1 if none) in the current part of the
201 * schedule.
203 int first_unroll;
205 int n_grid;
206 int n_block;
207 /* Note: in the input file, the sizes of the grid and the blocks
208 * are specified in the order x, y, z, but internally, the sizes
209 * are stored in reverse order, so that the last element always
210 * refers to the x dimension.
212 int grid_dim[2];
213 int block_dim[3];
214 int *tile_size;
217 /* Print the name of the local copy of a given group of array references.
219 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
220 struct gpu_array_ref_group *group)
222 int global = 0;
224 if (group->private_tile)
225 p = isl_printer_print_str(p, "private_");
226 else if (group->shared_tile)
227 p = isl_printer_print_str(p, "shared_");
228 else
229 global = 1;
230 p = isl_printer_print_str(p, group->array->name);
231 if (!global && group->array->n_group > 1) {
232 p = isl_printer_print_str(p, "_");
233 p = isl_printer_print_int(p, group->nr);
236 return p;
239 /* Collect all references to the given array and store pointers to them
240 * in array->refs.
242 * If the array contains structures, then there is no need to collect
243 * the references since we will not be computing any reference groups.
245 static void collect_references(struct gpu_prog *prog,
246 struct gpu_array_info *array)
248 int i;
249 int n;
251 if (array->has_compound_element)
252 return;
254 n = 0;
255 for (i = 0; i < prog->n_stmts; ++i) {
256 struct gpu_stmt *stmt = &prog->stmts[i];
257 struct gpu_stmt_access *access;
259 for (access = stmt->accesses; access; access = access->next) {
260 const char *name;
261 name = isl_map_get_tuple_name(access->access,
262 isl_dim_out);
263 if (name && !strcmp(array->name, name))
264 n++;
268 array->n_ref = n;
269 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
270 assert(array->refs);
272 n = 0;
273 for (i = 0; i < prog->n_stmts; ++i) {
274 struct gpu_stmt *stmt = &prog->stmts[i];
275 struct gpu_stmt_access *access;
277 for (access = stmt->accesses; access; access = access->next) {
278 const char *name;
279 name = isl_map_get_tuple_name(access->access,
280 isl_dim_out);
281 if (!name || strcmp(array->name, name))
282 continue;
284 array->refs[n++] = access;
289 /* Create a gpu_array_tile for an array of dimension "n_index".
291 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
293 int i;
294 struct gpu_array_tile *tile;
296 tile = isl_calloc_type(ctx, struct gpu_array_tile);
297 assert(tile);
299 tile->n = n_index;
301 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
302 assert(tile->bound);
304 for (i = 0; i < n_index; ++i) {
305 tile->bound[i].size = NULL;
306 tile->bound[i].lb = NULL;
307 tile->bound[i].stride = NULL;
308 tile->bound[i].shift = NULL;
309 tile->bound[i].shift_map = NULL;
312 return tile;
315 static void *free_tile(struct gpu_array_tile *tile)
317 int j;
319 if (!tile)
320 return NULL;
322 for (j = 0; j < tile->n; ++j) {
323 isl_val_free(tile->bound[j].size);
324 isl_val_free(tile->bound[j].stride);
325 isl_aff_free(tile->bound[j].lb);
326 isl_aff_free(tile->bound[j].shift);
327 isl_basic_map_free(tile->bound[j].shift_map);
329 free(tile->bound);
330 isl_multi_aff_free(tile->tiling);
331 free(tile);
333 return NULL;
336 static struct pet_array *find_array(struct ppcg_scop *scop,
337 __isl_keep isl_set *accessed)
339 int i;
340 isl_id *id;
342 id = isl_set_get_tuple_id(accessed);
344 for (i = 0; i < scop->n_array; ++i) {
345 isl_id *id_i;
347 id_i = isl_set_get_tuple_id(scop->arrays[i]->extent);
348 isl_id_free(id_i);
349 if (id == id_i)
350 break;
352 isl_id_free(id);
354 return i < scop->n_array ? scop->arrays[i] : NULL;
357 /* Compute and return the extent of "array", taking into account the set of
358 * accessed elements.
360 * In particular, the extent in the outer dimension is taken
361 * from "accessed", while then extent in the remaing dimensions
362 * are taken from array->extent.
364 * The extent in the outer dimension cannot be taken from array->extent
365 * because that may be unbounded. Furthermore, even if it is bounded,
366 * it may be larger than the piece of the array that is being accessed.
368 static __isl_give isl_set *compute_extent(struct pet_array *array,
369 __isl_keep isl_set *accessed)
371 int n_index;
372 isl_id *id;
373 isl_set *outer;
374 isl_set *extent;
376 extent = isl_set_copy(array->extent);
378 n_index = isl_set_dim(accessed, isl_dim_set);
379 if (n_index == 0)
380 return extent;
382 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
383 outer = isl_set_copy(accessed);
384 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
385 extent = isl_set_flat_product(outer, extent);
386 id = isl_set_get_tuple_id(accessed);
387 extent = isl_set_set_tuple_id(extent, id);
389 return extent;
392 /* Is the array "array" being extracted a read-only scalar?
394 * That is, is "array" a scalar that is never possibly written to.
395 * An array containing structures is never considered to be a scalar.
397 static int is_read_only_scalar(struct gpu_array_info *array,
398 struct gpu_prog *prog)
400 isl_set *space;
401 isl_union_map *write;
402 int empty;
404 if (array->has_compound_element)
405 return 0;
406 if (array->n_index != 0)
407 return 0;
409 write = isl_union_map_copy(prog->may_write);
410 space = isl_set_universe(isl_space_copy(array->space));
411 write = isl_union_map_intersect_range(write,
412 isl_union_set_from_set(space));
413 empty = isl_union_map_is_empty(write);
414 isl_union_map_free(write);
416 return empty;
419 /* Compute bounds on the host arrays based on the accessed elements
420 * and collect all references to the array.
422 * If the array is zero-dimensional and does not contain structures,
423 * i.e., if the array is a scalar, we check whether it is read-only.
425 static int extract_array_info(__isl_take isl_set *array, void *user)
427 int i;
428 struct gpu_prog *prog = (struct gpu_prog *)user;
429 const char *name;
430 int n_index;
431 isl_pw_aff **bounds;
432 struct pet_array *pa;
433 struct gpu_array_info *info;
434 isl_set *extent;
436 info = &prog->array[prog->n_array];
437 prog->n_array++;
439 n_index = isl_set_dim(array, isl_dim_set);
440 name = isl_set_get_tuple_name(array);
441 bounds = isl_alloc_array(isl_set_get_ctx(array),
442 isl_pw_aff *, n_index);
443 if (!bounds)
444 goto error;
446 info->space = isl_set_get_space(array);
447 info->name = strdup(name);
448 info->n_index = n_index;
449 info->bound = bounds;
450 info->linearize = prog->scop->options->linearize_device_arrays;
452 pa = find_array(prog->scop, array);
453 if (!pa)
454 isl_die(isl_set_get_ctx(array), isl_error_internal,
455 "unable to find array in scop", goto error);
457 info->type = strdup(pa->element_type);
458 info->size = pa->element_size;
459 info->local = pa->declared && !pa->exposed;
460 info->has_compound_element = pa->element_is_record;
461 info->read_only_scalar = is_read_only_scalar(info, prog);
463 extent = compute_extent(pa, array);
464 info->extent = extent;
465 for (i = 0; i < n_index; ++i) {
466 isl_set *dom;
467 isl_local_space *ls;
468 isl_aff *one;
469 isl_pw_aff *bound;
471 dom = isl_set_copy(extent);
472 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
473 n_index - (i + 1));
474 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
475 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
476 fprintf(stderr, "unable to determine extent of '%s' "
477 "in dimension %d\n", info->name, i);
478 dom = isl_set_free(dom);
480 bound = isl_set_dim_max(dom, 0);
481 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
482 ls = isl_local_space_from_space(isl_set_get_space(dom));
483 one = isl_aff_zero_on_domain(ls);
484 one = isl_aff_add_constant_si(one, 1);
485 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
486 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
488 bounds[i] = bound;
489 if (!isl_pw_aff_is_cst(bound))
490 info->linearize = 1;
493 collect_references(prog, info);
495 isl_set_free(array);
496 return 0;
497 error:
498 isl_set_free(array);
499 return -1;
502 /* Compute a mapping from all outer arrays (of structs) in scop
503 * to their innermost arrays.
505 * In particular, for each array of a primitive type, the result
506 * contains the identity mapping on that array.
507 * For each array involving member accesses, the result
508 * contains a mapping from the elements of the outer array of structs
509 * to all corresponding elements of the innermost nested arrays.
511 static __isl_give isl_union_map *compute_to_inner(struct ppcg_scop *scop)
513 int i;
514 isl_union_map *to_inner;
516 to_inner = isl_union_map_empty(isl_set_get_space(scop->context));
518 for (i = 0; i < scop->n_array; ++i) {
519 struct pet_array *array = scop->arrays[i];
520 isl_set *set;
521 isl_map *map;
523 if (array->element_is_record)
524 continue;
526 set = isl_set_copy(array->extent);
527 map = isl_set_identity(isl_set_copy(set));
529 while (set && isl_set_is_wrapping(set)) {
530 isl_id *id;
531 isl_map *wrapped;
533 id = isl_set_get_tuple_id(set);
534 wrapped = isl_set_unwrap(set);
535 wrapped = isl_map_domain_map(wrapped);
536 wrapped = isl_map_set_tuple_id(wrapped, isl_dim_in, id);
537 map = isl_map_apply_domain(map, wrapped);
538 set = isl_map_domain(isl_map_copy(map));
541 map = isl_map_gist_domain(map, set);
543 to_inner = isl_union_map_add_map(to_inner, map);
546 return to_inner;
549 /* Remove independence from the order constraints "order" on array "array".
550 * Since the pairs of iterations in the filter relation of an independence
551 * are guaranteed to be completely independent by the user, there is
552 * no need to ensure that live ranges are ordered along thong pairs.
553 * We make an exception for local variables, though, as the independence
554 * guarantee does not apply to those.
556 * The order constraints are used in two places.
557 * Those on scalars are used in check_scalar_live_ranges to check if
558 * we need to force the scalar to be private. Any non-local scalar
559 * should not be forced scalar if it only appears in independent loops.
560 * Those on non-scalars are added to the coincidence constraints
561 * in compute_schedule because we do not support any array expansion.
562 * Accesses to non-local arrays should not prevent a loop from being
563 * considered coincident so we should indeed remove those constraints
564 * from the order constraints.
566 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
567 struct gpu_array_info *array, __isl_take isl_union_map *order)
569 int i;
571 for (i = 0; i < prog->scop->n_independence; ++i) {
572 struct pet_independence *pi = prog->scop->independences[i];
573 if (isl_union_set_contains(pi->local, array->space))
574 continue;
576 order = isl_union_map_subtract(order,
577 isl_union_map_copy(pi->filter));
580 return order;
583 /* For each array in "prog", store the (untagged) order dependences
584 * derived from the array in array->dep_order.
585 * In particular, consider all references that access the given array
586 * and take the order dependences that have one of these references
587 * as source. (Since an order dependence relates two references to
588 * the same array, the target of these order dependences will also
589 * be one of these references.)
590 * Additionally, store the union of these array->dep_order relations
591 * for all non-scalar arrays in prog->array_order.
593 void collect_order_dependences(struct gpu_prog *prog)
595 int i;
596 isl_space *space;
597 isl_union_map *accesses;
599 space = isl_union_map_get_space(prog->read);
600 prog->array_order = isl_union_map_empty(space);
602 accesses = isl_union_map_copy(prog->scop->tagged_reads);
603 accesses = isl_union_map_union(accesses,
604 isl_union_map_copy(prog->scop->tagged_may_writes));
605 accesses = isl_union_map_universe(accesses);
606 accesses = isl_union_map_apply_range(accesses,
607 isl_union_map_copy(prog->to_outer));
609 for (i = 0; i < prog->n_array; ++i) {
610 struct gpu_array_info *array = &prog->array[i];
611 isl_set *set;
612 isl_union_set *uset;
613 isl_union_map *order;
615 set = isl_set_universe(isl_space_copy(array->space));
616 uset = isl_union_set_from_set(set);
617 uset = isl_union_map_domain(
618 isl_union_map_intersect_range(isl_union_map_copy(accesses),
619 uset));
620 order = isl_union_map_copy(prog->scop->tagged_dep_order);
621 order = isl_union_map_intersect_domain(order, uset);
622 order = isl_union_map_zip(order);
623 order = isl_union_set_unwrap(isl_union_map_domain(order));
624 order = remove_independences(prog, array, order);
625 array->dep_order = order;
627 if (gpu_array_is_scalar(array))
628 continue;
630 prog->array_order = isl_union_map_union(prog->array_order,
631 isl_union_map_copy(array->dep_order));
634 isl_union_map_free(accesses);
637 /* Construct a gpu_array_info for each array possibly accessed by "prog" and
638 * collect them in prog->array.
640 * If there are any member accesses involved, then they are first mapped
641 * to the outer arrays of structs.
643 * If we are allowing live range reordering, then also set
644 * the dep_order field. Otherwise leave it NULL.
646 static int collect_array_info(struct gpu_prog *prog)
648 int r;
649 isl_union_set *arrays;
651 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
652 arrays = isl_union_set_union(arrays,
653 isl_union_map_range(isl_union_map_copy(prog->may_write)));
655 arrays = isl_union_set_apply(arrays,
656 isl_union_map_copy(prog->to_outer));
658 arrays = isl_union_set_coalesce(arrays);
660 prog->n_array = isl_union_set_n_set(arrays);
661 prog->array = isl_calloc_array(prog->ctx,
662 struct gpu_array_info, prog->n_array);
663 assert(prog->array);
664 prog->n_array = 0;
665 r = isl_union_set_foreach_set(arrays, &extract_array_info, prog);
666 isl_union_set_free(arrays);
668 if (prog->scop->options->live_range_reordering)
669 collect_order_dependences(prog);
671 return r;
674 static void free_array_info(struct gpu_prog *prog)
676 int i, j;
678 for (i = 0; i < prog->n_array; ++i) {
679 int n_index = prog->array[i].n_index;
680 free(prog->array[i].type);
681 free(prog->array[i].name);
682 for (j = 0; j < n_index; ++j)
683 isl_pw_aff_free(prog->array[i].bound[j]);
684 isl_space_free(prog->array[i].space);
685 isl_set_free(prog->array[i].extent);
686 free(prog->array[i].bound);
687 free(prog->array[i].refs);
688 isl_union_map_free(prog->array[i].dep_order);
690 free(prog->array);
693 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
694 * as an array or through a pointer reference, but as a single data element.
695 * At the moment, scalars are represented as zero-dimensional arrays.
696 * A zero-dimensional array containing structures is not considered
697 * to be a scalar.
699 int gpu_array_is_scalar(struct gpu_array_info *array)
701 return !array->has_compound_element && array->n_index == 0;
704 /* Is "array" a read-only scalar?
706 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
708 return array->read_only_scalar;
711 /* Return the set of parameter values for which the array has a positive
712 * size in all dimensions.
713 * If the sizes are only valid for some parameter values, then those
714 * constraints are also taken into account.
716 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
718 int i;
719 isl_space *space;
720 isl_set *guard;
722 space = isl_space_params(isl_space_copy(array->space));
723 guard = isl_set_universe(space);
725 for (i = 0; i < array->n_index; ++i) {
726 isl_pw_aff *bound;
727 isl_set *guard_i, *zero;
729 bound = isl_pw_aff_copy(array->bound[i]);
730 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
731 zero = isl_pw_aff_zero_set(bound);
732 guard_i = isl_set_subtract(guard_i, zero);
733 guard = isl_set_intersect(guard, guard_i);
736 return guard;
739 /* Internal data structure for extract_size_of_type.
740 * "type" specifies the name of the space that we want to extract.
741 * "res" is used to store the subset of that space.
743 struct ppcg_extract_size_data {
744 const char *type;
745 isl_set *res;
748 /* This function is called for each set in a union_set.
749 * If the name of the set matches data->type, we store the
750 * set in data->res.
752 static int extract_size_of_type(__isl_take isl_set *size, void *user)
754 struct ppcg_extract_size_data *data = user;
755 const char *name;
757 name = isl_set_get_tuple_name(size);
758 if (name && !strcmp(name, data->type)) {
759 data->res = size;
760 return -1;
763 isl_set_free(size);
764 return 0;
767 /* Given a union map { kernel[i] -> *[...] },
768 * return the range in the space called "type" for the kernel with
769 * sequence number "id".
771 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
772 const char *type, int id)
774 isl_space *space;
775 isl_set *dom;
776 isl_union_set *local_sizes;
777 struct ppcg_extract_size_data data = { type, NULL };
779 if (!sizes)
780 return NULL;
782 space = isl_union_map_get_space(sizes);
783 space = isl_space_set_from_params(space);
784 space = isl_space_add_dims(space, isl_dim_set, 1);
785 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
786 dom = isl_set_universe(space);
787 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
789 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
790 isl_union_map_copy(sizes));
791 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
792 isl_union_set_free(local_sizes);
793 return data.res;
796 /* Given a singleton set, extract the first (at most *len) elements
797 * of the single integer tuple into *sizes and update *len if needed.
799 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
801 int i;
802 int dim;
804 if (!set)
805 return;
807 dim = isl_set_dim(set, isl_dim_set);
808 if (dim < *len)
809 *len = dim;
811 for (i = 0; i < *len; ++i) {
812 isl_val *v;
814 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
815 assert(v);
817 sizes[i] = isl_val_get_num_si(v);
818 isl_val_free(v);
821 isl_set_free(set);
824 /* Extract user specified "tile" sizes from the "sizes" command line option,
825 * defaulting to option->tile_size in each dimension.
827 static void read_tile_sizes(struct gpu_gen *gen)
829 int n;
830 isl_set *size;
832 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
833 assert(gen->tile_size);
834 for (n = 0; n < gen->tile_len; ++n)
835 gen->tile_size[n] = gen->options->tile_size;
837 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
838 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
840 if (gen->n_parallel > gen->tile_len)
841 gen->n_parallel = gen->tile_len;
844 /* Extract user specified "block" sizes from the "sizes" command line option,
845 * after filling in some potentially useful defaults.
847 static void read_block_sizes(struct gpu_gen *gen)
849 int n;
850 isl_set *size;
852 n = gen->n_parallel;
853 gen->n_block = (n <= 3) ? n : 3;
854 switch (gen->n_block) {
855 case 1:
856 gen->block_dim[0] = 512;
857 break;
858 case 2:
859 gen->block_dim[0] = 32;
860 gen->block_dim[1] = 16;
861 break;
862 default:
863 gen->block_dim[0] = 32;
864 gen->block_dim[1] = 4;
865 gen->block_dim[2] = 4;
866 break;
869 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
870 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
873 /* Extract user specified "grid" sizes from the "sizes" command line option,
874 * after filling in some potentially useful defaults.
876 static void read_grid_sizes(struct gpu_gen *gen)
878 int n = gen->n_parallel;
879 isl_set *size;
881 gen->n_grid = (n <= 2) ? n : 2;
882 switch (gen->n_grid) {
883 case 1:
884 gen->grid_dim[0] = 32768;
885 break;
886 default:
887 gen->grid_dim[0] = 256;
888 gen->grid_dim[1] = 256;
889 break;
892 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
893 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
896 /* Extract user specified sizes from the "sizes" command line option
897 * after filling in some potentially useful defaults.
899 static void read_sizes(struct gpu_gen *gen)
901 read_tile_sizes(gen);
902 read_block_sizes(gen);
903 read_grid_sizes(gen);
906 static void *free_stmts(struct gpu_stmt *stmts, int n)
908 int i;
910 if (!stmts)
911 return NULL;
913 for (i = 0; i < n; ++i) {
914 struct gpu_stmt_access *access, *next;
916 for (access = stmts[i].accesses; access; access = next) {
917 next = access->next;
918 isl_id_free(access->ref_id);
919 isl_map_free(access->access);
920 isl_map_free(access->tagged_access);
921 free(access);
924 isl_id_free(stmts[i].id);
926 free(stmts);
928 return NULL;
931 /* Construct a map from a domain of dimensionality "len"
932 * to a domain of dimensionality "len" + "tile_len" that tiles
933 * the "tile_len" coordinates starting at "first".
934 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
935 * "dim" prescribes the parameters.
937 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
938 int first, int tile_len, int *tile_size)
940 int i;
941 isl_basic_map *bmap;
942 isl_constraint *c;
943 isl_local_space *ls;
945 dim = isl_space_add_dims(dim, isl_dim_in, len);
946 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
947 bmap = isl_basic_map_universe(isl_space_copy(dim));
948 ls = isl_local_space_from_space(dim);
950 for (i = 0; i < len - tile_len; ++i) {
951 int j = i < first ? i : i + tile_len;
952 int k = i < first ? i : i + 2 * tile_len;
954 c = isl_equality_alloc(isl_local_space_copy(ls));
955 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
956 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
957 bmap = isl_basic_map_add_constraint(bmap, c);
960 for (i = 0; i < tile_len; ++i) {
961 c = isl_equality_alloc(isl_local_space_copy(ls));
962 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
963 first + i, -1);
964 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
965 first + i, tile_size[i]);
966 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
967 first + i + tile_len, 1);
968 bmap = isl_basic_map_add_constraint(bmap, c);
970 c = isl_inequality_alloc(isl_local_space_copy(ls));
971 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
972 first + i + tile_len, 1);
973 bmap = isl_basic_map_add_constraint(bmap, c);
975 c = isl_inequality_alloc(isl_local_space_copy(ls));
976 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
977 first + i + tile_len, -1);
978 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
979 bmap = isl_basic_map_add_constraint(bmap, c);
982 isl_local_space_free(ls);
984 return isl_map_from_basic_map(bmap);
987 /* Construct a map from a domain of dimensionality "len"
988 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
989 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
990 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
991 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
992 * that are projected out at the end.
993 * "dim" prescribes the parameters.
995 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
996 int first, int wrap_len, int *wrap_size)
998 int i;
999 isl_basic_map *bmap;
1000 isl_constraint *c;
1001 isl_local_space *ls;
1003 dim = isl_space_add_dims(dim, isl_dim_in, len);
1004 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
1005 bmap = isl_basic_map_universe(isl_space_copy(dim));
1006 ls = isl_local_space_from_space(dim);
1008 for (i = 0; i < len; ++i) {
1009 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
1011 c = isl_equality_alloc(isl_local_space_copy(ls));
1012 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
1013 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
1014 bmap = isl_basic_map_add_constraint(bmap, c);
1017 for (i = 0; i < wrap_len; ++i) {
1018 c = isl_equality_alloc(isl_local_space_copy(ls));
1019 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1020 first + i, -1);
1021 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1022 first + wrap_len + i, 1);
1023 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1024 first + 2 * wrap_len + i, wrap_size[i]);
1025 bmap = isl_basic_map_add_constraint(bmap, c);
1027 c = isl_inequality_alloc(isl_local_space_copy(ls));
1028 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1029 first + wrap_len + i, 1);
1030 bmap = isl_basic_map_add_constraint(bmap, c);
1032 c = isl_inequality_alloc(isl_local_space_copy(ls));
1033 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1034 first + wrap_len + i, -1);
1035 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
1036 bmap = isl_basic_map_add_constraint(bmap, c);
1039 isl_local_space_free(ls);
1041 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
1042 first + 2 * wrap_len, wrap_len);
1044 return isl_map_from_basic_map(bmap);
1047 /* Add "n" parameters named prefix%d.
1049 static __isl_give isl_set *add_params( __isl_take isl_set *set,
1050 int n, const char *prefix)
1052 int i;
1053 unsigned nparam;
1054 char name[20];
1056 nparam = isl_set_dim(set, isl_dim_param);
1057 set = isl_set_add_dims(set, isl_dim_param, n);
1059 for (i = 0; i < n; ++i) {
1060 snprintf(name, sizeof(name), "%s%d", prefix, i);
1061 set = isl_set_set_dim_name(set, isl_dim_param,
1062 nparam + i, name);
1065 return set;
1068 /* Equate the "n" dimensions of "set" starting at "first" to
1069 * freshly created parameters named prefix%d.
1071 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
1072 int first, int n, const char *prefix)
1074 int i;
1075 unsigned nparam;
1077 nparam = isl_set_dim(set, isl_dim_param);
1079 set = add_params(set, n, prefix);
1081 for (i = 0; i < n; ++i)
1082 set = isl_set_equate(set, isl_dim_param, nparam + i,
1083 isl_dim_set, first + i);
1085 return set;
1088 /* Given a parameter space "space", create a set of dimension "len"
1089 * of which the "n" dimensions starting at "first" are equated to
1090 * freshly created parameters named prefix%d.
1092 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
1093 int len, int first, int n, const char *prefix)
1095 isl_set *set;
1097 space = isl_space_set_from_params(space);
1098 space = isl_space_add_dims(space, isl_dim_set, len);
1099 set = isl_set_universe(space);
1101 return parametrize(set, first, n, prefix);
1104 /* Tile the B loops over the tile sizes and then tile/wrap
1105 * the T1 loops over the blocks.
1107 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
1108 __isl_take isl_union_map *sched)
1110 isl_space *dim;
1111 isl_map *tiling, *block_tiling;
1113 dim = isl_union_map_get_space(sched);
1114 tiling = tile(isl_space_copy(dim), gen->untiled_len,
1115 gen->tile_first, gen->tile_len, gen->tile_size);
1117 if (gen->options->wrap)
1118 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
1119 gen->tile_first, gen->n_grid, gen->grid_dim);
1120 else
1121 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
1122 gen->tile_first, gen->n_grid, gen->grid_dim);
1124 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
1126 tiling = isl_map_apply_range(tiling, block_tiling);
1128 sched = isl_union_map_apply_range(sched,
1129 isl_union_map_from_map(tiling));
1131 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1133 return sched;
1136 /* Equate the "T1P" iterators in the tiled schedule "sched"
1137 * to the block dimensions.
1139 static __isl_give isl_union_map *parametrize_tiled_schedule(
1140 struct gpu_gen *gen, __isl_take isl_union_map *sched)
1142 isl_space *dim;
1143 isl_set *par;
1145 dim = isl_union_map_get_space(sched);
1146 par = parametrization(dim, gen->tiled_len,
1147 gen->tile_first + gen->n_grid, gen->n_grid, "b");
1148 sched = isl_union_map_intersect_range(sched,
1149 isl_union_set_from_set(par));
1151 return sched;
1154 /* Tile/wrap the P1 loops over the threads.
1156 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
1157 __isl_take isl_union_map *sched)
1159 isl_space *dim;
1160 isl_map *tiling;
1161 isl_set *par;
1163 dim = isl_union_map_get_space(sched);
1165 if (gen->options->wrap)
1166 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
1167 gen->shared_len, gen->n_block, gen->block_dim);
1168 else
1169 tiling = tile(isl_space_copy(dim), gen->tiled_len,
1170 gen->shared_len, gen->n_block, gen->block_dim);
1171 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
1173 sched = isl_union_map_apply_range(sched,
1174 isl_union_map_from_map(tiling));
1176 par = parametrization(dim, gen->thread_tiled_len,
1177 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1178 gen->n_block, "t");
1179 sched = isl_union_map_intersect_range(sched,
1180 isl_union_set_from_set(par));
1182 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1184 return sched;
1187 /* If the user asked for it, scale the shared memory tile loops
1188 * (T1T and T2) of "sched" by gen->tile_size[i].
1189 * If we are not performing "wrapping", then additionally scale the T1P
1190 * loops by gen->grid_dim[i].
1192 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
1193 __isl_take isl_union_map *sched)
1195 int i;
1196 isl_space *dim;
1197 isl_basic_map *scale;
1198 isl_constraint *c;
1199 isl_local_space *ls;
1201 if (!gen->options->scale_tile_loops)
1202 return sched;
1204 dim = isl_union_map_get_space(sched);
1205 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
1206 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
1207 scale = isl_basic_map_universe(isl_space_copy(dim));
1208 ls = isl_local_space_from_space(dim);
1210 for (i = 0; i < gen->tiled_len; ++i) {
1211 int f = 1;
1213 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
1214 f = gen->tile_size[i - gen->tile_first];
1215 if (!gen->options->wrap)
1216 f *= gen->grid_dim[i - gen->tile_first];
1217 } else if (i >= gen->tile_first + gen->n_grid &&
1218 i < gen->tile_first + gen->n_grid + gen->tile_len) {
1219 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
1222 c = isl_equality_alloc(isl_local_space_copy(ls));
1223 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1224 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1225 scale = isl_basic_map_add_constraint(scale, c);
1228 isl_local_space_free(ls);
1230 sched = isl_union_map_apply_range(sched,
1231 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1233 return sched;
1236 /* If we are not performing "wrapping" and if the user asked for it,
1237 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1239 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1240 __isl_take isl_union_map *sched)
1242 int i;
1243 isl_space *dim;
1244 isl_basic_map *scale;
1245 isl_constraint *c;
1246 isl_local_space *ls;
1248 if (gen->options->wrap)
1249 return sched;
1250 if (!gen->options->scale_tile_loops)
1251 return sched;
1253 dim = isl_union_map_get_space(sched);
1254 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1255 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1256 scale = isl_basic_map_universe(isl_space_copy(dim));
1257 ls = isl_local_space_from_space(dim);
1259 for (i = 0; i < gen->thread_tiled_len; ++i) {
1260 int f = 1;
1262 if (i >= gen->shared_len &&
1263 i < gen->shared_len + gen->n_block)
1264 f = gen->block_dim[i - gen->shared_len];
1266 c = isl_equality_alloc(isl_local_space_copy(ls));
1267 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1268 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1269 scale = isl_basic_map_add_constraint(scale, c);
1272 isl_local_space_free(ls);
1274 sched = isl_union_map_apply_range(sched,
1275 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1277 return sched;
1280 /* If we are not performing "wrapping" and if the user asked for it,
1281 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1283 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1284 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1286 int i;
1287 isl_space *dim;
1288 isl_basic_map *scale;
1289 isl_constraint *c;
1290 isl_local_space *ls;
1292 if (gen->options->wrap)
1293 return sched;
1294 if (!gen->options->scale_tile_loops)
1295 return sched;
1297 dim = isl_union_map_get_space(sched);
1298 dim = isl_space_add_dims(dim, isl_dim_in, len);
1299 dim = isl_space_add_dims(dim, isl_dim_out, len);
1300 scale = isl_basic_map_universe(isl_space_copy(dim));
1301 ls = isl_local_space_from_space(dim);
1303 for (i = 0; i < len; ++i) {
1304 int f = 1;
1306 if (i >= first && i < first + n_tile)
1307 f = gen->kernel->block_dim[i - first];
1309 c = isl_equality_alloc(isl_local_space_copy(ls));
1310 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1311 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1312 scale = isl_basic_map_add_constraint(scale, c);
1315 isl_local_space_free(ls);
1317 sched = isl_union_map_apply_range(sched,
1318 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1320 return sched;
1323 /* Add "len" parameters p[i] called prefix%d,
1324 * with bounds to 0 <= p[i] < size[i].
1326 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1327 int len, int *size, const char *prefix)
1329 int i;
1330 unsigned nparam;
1331 isl_space *dim;
1332 isl_basic_set *bset;
1333 isl_constraint *c;
1334 isl_local_space *ls;
1335 char name[20];
1337 nparam = isl_set_dim(set, isl_dim_param);
1338 set = isl_set_add_dims(set, isl_dim_param, len);
1340 for (i = 0; i < len; ++i) {
1341 snprintf(name, sizeof(name), "%s%d", prefix, i);
1342 set = isl_set_set_dim_name(set, isl_dim_param,
1343 nparam + i, name);
1346 dim = isl_set_get_space(set);
1347 bset = isl_basic_set_universe(isl_space_copy(dim));
1348 ls = isl_local_space_from_space(dim);
1350 for (i = 0; i < len; ++i) {
1351 c = isl_inequality_alloc(isl_local_space_copy(ls));
1352 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1353 nparam + i, 1);
1354 bset = isl_basic_set_add_constraint(bset, c);
1356 c = isl_inequality_alloc(isl_local_space_copy(ls));
1357 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1358 nparam + i, -1);
1359 c = isl_constraint_set_constant_si(c, size[i] - 1);
1360 bset = isl_basic_set_add_constraint(bset, c);
1363 isl_local_space_free(ls);
1365 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1368 /* Add "len" parameters p[i] called prefix%d,
1369 * with bounds to 0 <= p[i] < size[i].
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 set = isl_set_intersect_params(set, bound);
1404 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1405 bound = isl_pw_aff_ge_set(param, zero);
1406 set = isl_set_intersect_params(set, bound);
1408 isl_local_space_free(ls);
1410 return set;
1413 /* Construct a map from an access to group->array to the corresponding
1414 * shared/private memory tile.
1415 * The map is of the form
1417 * { [D[i] -> A[a]] -> T[t] }
1419 * where D represents the initial shared_len dimensions
1420 * of the computed schedule.
1422 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1424 struct gpu_array_tile *tile;
1425 isl_multi_aff *tiling;
1427 tile = group->private_tile;
1428 if (!tile)
1429 tile = group->shared_tile;
1431 tiling = isl_multi_aff_copy(tile->tiling);
1433 return isl_map_from_multi_aff(tiling);
1436 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1438 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1439 unsigned pos)
1441 isl_val *v;
1442 int fixed;
1444 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1445 if (!v)
1446 return -1;
1447 fixed = isl_val_is_int(v);
1448 isl_val_free(v);
1450 return fixed;
1453 /* Given a schedule that iterates over all elements in a piece of an array,
1454 * perform tiling/wrapping over the threads.
1456 * In particular, we tile the final iterators so that the final thread
1457 * dimension runs over the final array dimension.
1458 * However, if those final iterators have only a single iteration,
1459 * we try to tile earlier iterators instead.
1461 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1462 __isl_take isl_map *sched)
1464 isl_space *dim;
1465 isl_union_map *usched;
1466 isl_map *tiling;
1467 isl_set *par;
1468 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1469 int n_tile;
1470 int first;
1472 n_tile = gen->kernel->n_block;
1473 if (n_tile > nvar) {
1474 int i;
1475 sched = isl_map_insert_dims(sched,
1476 isl_dim_out, 0, n_tile - nvar);
1477 for (i = 0; i < n_tile - nvar; ++i)
1478 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1479 nvar = n_tile;
1482 first = nvar - n_tile;
1484 for (; first > 0; first --)
1485 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1486 break;
1488 dim = isl_map_get_space(sched);
1489 dim = isl_space_params(dim);
1490 if (gen->options->wrap)
1491 tiling = wrap(isl_space_copy(dim), nvar, first,
1492 n_tile, gen->kernel->block_dim);
1493 else
1494 tiling = tile(isl_space_copy(dim), nvar, first,
1495 n_tile, gen->kernel->block_dim);
1496 sched = isl_map_apply_range(sched, tiling);
1498 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1499 sched = isl_map_intersect_range(sched, par);
1501 usched = isl_union_map_from_map(sched);
1502 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1503 first, n_tile);
1504 sched = isl_map_from_union_map(usched);
1506 return sched;
1509 /* Return the union of all read (read = 1) and/or write (write = 1)
1510 * access relations in the group.
1512 static __isl_give isl_union_map *group_access_relation(
1513 struct gpu_array_ref_group *group, int read, int write)
1515 int i;
1516 isl_union_map *access;
1518 access = isl_union_map_empty(isl_map_get_space(group->access));
1519 for (i = 0; i < group->n_ref; ++i) {
1520 isl_map *map_i;
1522 if (!((read && group->refs[i]->read) ||
1523 (write && group->refs[i]->write)))
1524 continue;
1525 map_i = isl_map_copy(group->refs[i]->access);
1526 access = isl_union_map_union(access,
1527 isl_union_map_from_map(map_i));
1530 return access;
1533 /* Return the union of all tagged access relations in the group.
1535 static __isl_give isl_union_map *group_tagged_access_relation(
1536 struct gpu_array_ref_group *group)
1538 int i;
1539 isl_union_map *access;
1541 access = isl_union_map_empty(isl_map_get_space(group->access));
1542 for (i = 0; i < group->n_ref; ++i) {
1543 isl_map *map_i;
1545 map_i = isl_map_copy(group->refs[i]->tagged_access);
1546 access = isl_union_map_union(access,
1547 isl_union_map_from_map(map_i));
1550 return access;
1553 /* Return the extent of "array", recomputed from the bounds.
1554 * The recomputed extent may be simpler than the original extent.
1556 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1558 int i;
1559 isl_id *id;
1560 isl_space *space;
1561 isl_local_space *ls;
1562 isl_set *extent;
1564 id = isl_set_get_tuple_id(array->extent);
1565 space = isl_set_get_space(array->extent);
1566 extent = isl_set_universe(isl_space_copy(space));
1567 ls = isl_local_space_from_space(space);
1568 for (i = 0; i < array->n_index; ++i) {
1569 isl_pw_aff *bound;
1570 isl_aff *aff;
1571 isl_pw_aff *index;
1572 isl_set *lt;
1574 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1576 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1577 isl_dim_set, i);
1578 index = isl_pw_aff_from_aff(aff);
1579 bound = isl_pw_aff_copy(array->bound[i]);
1580 bound = isl_pw_aff_from_range(bound);
1581 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1582 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1583 isl_id_copy(id));
1584 lt = isl_pw_aff_lt_set(index, bound);
1585 extent = isl_set_intersect(extent, lt);
1587 isl_local_space_free(ls);
1588 isl_id_free(id);
1590 return extent;
1593 /* Return a map from the first shared_len dimensions of the computed
1594 * schedule to the array tile in
1595 * global memory that corresponds to the shared memory copy.
1597 * In particular, return a map
1599 * { D[i] -> A[a] }
1601 * with constraints
1603 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1605 * and
1607 * 0 <= a <= array_size - 1 (2)
1609 * Note that if some stride has been detected (i.e., when
1610 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1611 * to the shifted and scaled down version.
1613 * Constraints (1) are obtained by mapping the size constraints on the
1614 * shared/private memory tile back to the access relation.
1615 * Constraints (2) are obtained from the (recomputed) extent.
1617 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1619 int i;
1620 int n_index = group->array->n_index;
1621 isl_map *tile;
1622 isl_space *space;
1623 isl_set *local;
1624 isl_set *extent;
1626 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1627 space = isl_space_range(space);
1628 local = isl_set_universe(space);
1629 for (i = 0; i < n_index; ++i) {
1630 isl_val *bound;
1632 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1633 bound = isl_val_copy(group->shared_tile->bound[i].size);
1634 bound = isl_val_sub_ui(bound, 1);
1635 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1637 local = isl_set_preimage_multi_aff(local,
1638 isl_multi_aff_copy(group->shared_tile->tiling));
1639 tile = isl_set_unwrap(local);
1640 extent = array_extent(group->array);
1641 tile = isl_map_intersect_range(tile, extent);
1643 return tile;
1646 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1647 * return the corresponding mapping from the AST schedule to
1648 * to the first shared_len dimensions of the schedule computed by PPCG.
1650 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1651 __isl_take isl_pw_multi_aff *iterator_map)
1653 isl_union_map *umap;
1654 isl_space *space;
1655 isl_map *map, *sched;;
1657 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1658 space = isl_space_from_domain(space);
1659 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1661 umap = isl_union_map_copy(gen->shared_sched);
1662 umap = isl_union_map_apply_range(umap,
1663 isl_union_map_copy(gen->shared_proj));
1664 map = isl_union_map_extract_map(umap, space);
1665 isl_union_map_free(umap);
1667 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1668 sched = isl_map_detect_equalities(sched);
1670 return isl_pw_multi_aff_from_map(sched);
1673 /* Set unroll[j] if the input dimension j is involved in
1674 * the index expression represented by ma.
1676 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1677 void *user)
1679 int i, j;
1680 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1681 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1682 int *unroll = user;
1684 for (i = 0; i < n_out; ++i) {
1685 isl_aff *aff;
1687 aff = isl_multi_aff_get_aff(ma, i);
1688 for (j = 0; j < n_in; ++j)
1689 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1690 unroll[j] = 1;
1691 isl_aff_free(aff);
1694 isl_set_free(set);
1695 isl_multi_aff_free(ma);
1696 return 0;
1699 /* Given an array pos mapping input dimensions to the corresponding
1700 * output dimension, construct the corresponding map.
1702 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1703 int *pos, int len)
1705 int i;
1706 isl_constraint *c;
1707 isl_basic_map *bmap;
1708 isl_local_space *ls;
1710 dim = isl_space_add_dims(dim, isl_dim_in, len);
1711 dim = isl_space_add_dims(dim, isl_dim_out, len);
1712 bmap = isl_basic_map_universe(isl_space_copy(dim));
1713 ls = isl_local_space_from_space(dim);
1715 for (i = 0; i < len; ++i) {
1716 c = isl_equality_alloc(isl_local_space_copy(ls));
1717 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1718 -1);
1719 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1721 bmap = isl_basic_map_add_constraint(bmap, c);
1723 isl_local_space_free(ls);
1725 return isl_map_from_basic_map(bmap);
1728 /* Remove the private tiles from all array reference groups,
1729 * except for the groups of arrays that are marked force_private.
1731 static void remove_private_tiles(struct gpu_gen *gen)
1733 int i, j;
1735 for (i = 0; i < gen->prog->n_array; ++i) {
1736 struct gpu_array_info *array = &gen->prog->array[i];
1738 if (array->force_private)
1739 continue;
1741 for (j = 0; j < array->n_group; ++j) {
1742 struct gpu_array_ref_group *group = array->groups[j];
1744 group->private_tile = free_tile(group->private_tile);
1749 /* Find all loops involved in any of the index expressions for any of
1750 * the private accesses, move them innermost and then mark them as
1751 * requiring unrolling by setting gen->first_unroll.
1752 * The loops involved should all be parallel because of the checks
1753 * we performed in check_private_group_access. Moving them innermost
1754 * is therefore a valid transformation.
1756 * If any of the arrays are marked force_private, however, then
1757 * those loops may not be parallel with respect to the marked arrays.
1758 * If any of the loops would have to be moved innermost for the
1759 * (non forced) private accesses and if there are any force_private
1760 * arrays, then we revert the decision to map the selected arrays
1761 * to private memory. An alternative solution would be to expand
1762 * the force_private arrays.
1764 * Loops up to gen->shared_len are generated before the mapping to
1765 * threads is applied. They should therefore be ignored.
1767 * We compute the hidden equalities of the schedule first
1768 * since we will need them in our calls to isl_pw_multi_aff_from_map
1769 * and because we want to make sure that the same equalities
1770 * are also available to the code generator.
1772 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1773 __isl_take isl_union_map *sched)
1775 int i, j;
1776 int unroll[gen->thread_tiled_len];
1777 int perm[gen->thread_tiled_len];
1778 isl_space *dim;
1779 isl_map *permute;
1780 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1782 gen->first_unroll = -1;
1784 sched = isl_union_map_detect_equalities(sched);
1785 for (i = 0; i < gen->thread_tiled_len; ++i)
1786 unroll[i] = 0;
1787 for (i = 0; i < gen->prog->n_array; ++i) {
1788 struct gpu_array_info *array = &gen->prog->array[i];
1790 for (j = 0; j < array->n_group; ++j) {
1791 isl_union_map *access;
1792 isl_map *acc;
1793 isl_pw_multi_aff *pma;
1795 if (!array->groups[j]->private_tile)
1796 continue;
1798 access = group_access_relation(array->groups[j], 1, 1);
1799 access = isl_union_map_apply_domain(access,
1800 isl_union_map_copy(sched));
1802 acc = isl_map_from_union_map(access);
1803 pma = isl_pw_multi_aff_from_map(acc);
1804 isl_pw_multi_aff_foreach_piece(pma,
1805 &check_unroll, unroll);
1807 isl_pw_multi_aff_free(pma);
1811 for (i = gen->shared_len; i < len; ++i)
1812 if (unroll[i])
1813 break;
1815 if (i >= len)
1816 return sched;
1818 for (i = len; i < gen->thread_tiled_len; ++i)
1819 if (unroll[i])
1820 return sched;
1822 if (gen->any_force_private) {
1823 remove_private_tiles(gen);
1824 return sched;
1827 j = 0;
1828 for (i = 0; i < gen->shared_len; ++i)
1829 perm[i] = j++;
1830 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1831 if (!unroll[i])
1832 perm[i] = j++;
1833 gen->first_unroll = j - gen->shared_len;
1834 for (i = gen->shared_len; i < len; ++i)
1835 if (unroll[i])
1836 perm[i] = j++;
1838 dim = isl_union_map_get_space(sched);
1839 permute = permutation(dim, perm, gen->thread_tiled_len);
1840 sched = isl_union_map_apply_range(sched,
1841 isl_union_map_from_map(permute));
1843 return sched;
1846 /* Given a constraint
1848 * a(p,i) + j = g f(e)
1850 * or -a(p,i) - j = g f(e) if sign < 0,
1851 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1852 * a(p,i) is assumed to be an expression in only the parameters
1853 * and the input dimensions.
1855 static void extract_stride(__isl_keep isl_constraint *c,
1856 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1858 int i;
1859 isl_val *v;
1860 isl_space *space;
1861 unsigned nparam;
1862 unsigned nvar;
1863 isl_aff *aff;
1865 isl_val_free(bound->stride);
1866 bound->stride = isl_val_copy(stride);
1868 space = isl_constraint_get_space(c);
1869 space = isl_space_domain(space);
1871 nparam = isl_space_dim(space, isl_dim_param);
1872 nvar = isl_space_dim(space, isl_dim_set);
1874 v = isl_constraint_get_constant_val(c);
1875 if (sign < 0)
1876 v = isl_val_neg(v);
1877 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1878 aff = isl_aff_set_constant_val(aff, v);
1880 for (i = 0; i < nparam; ++i) {
1881 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1882 continue;
1883 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1884 if (sign < 0)
1885 v = isl_val_neg(v);
1886 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1889 for (i = 0; i < nvar; ++i) {
1890 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1891 continue;
1892 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1893 if (sign < 0)
1894 v = isl_val_neg(v);
1895 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1898 bound->shift = aff;
1901 /* Given an equality constraint of a map with a single output dimension j,
1902 * check if the constraint is of the form
1904 * a(p,i) + j = g f(e)
1906 * with a(p,i) an expression in the parameters and input dimensions
1907 * and f(e) an expression in the existentially quantified variables.
1908 * If so, and if g is larger than any such g from a previously considered
1909 * constraint, then call extract_stride to record the stride information
1910 * in bound.
1912 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1914 int i;
1915 isl_ctx *ctx;
1916 isl_val *v;
1917 unsigned n_div;
1918 struct gpu_array_bound *bound = user;
1920 ctx = isl_constraint_get_ctx(c);
1921 n_div = isl_constraint_dim(c, isl_dim_div);
1922 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1924 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1925 int s = isl_val_sgn(v);
1926 isl_val *stride = isl_val_zero(ctx);
1928 isl_val_free(v);
1929 for (i = 0; i < n_div; ++i) {
1930 v = isl_constraint_get_coefficient_val(c,
1931 isl_dim_div, i);
1932 stride = isl_val_gcd(stride, v);
1934 if (!isl_val_is_zero(stride) &&
1935 isl_val_gt(stride, bound->stride))
1936 extract_stride(c, bound, stride, s);
1938 isl_val_free(stride);
1939 } else
1940 isl_val_free(v);
1942 isl_constraint_free(c);
1943 return 0;
1946 /* Given contraints on an array index i, check if we can find
1947 * a shift a(p) and a stride g such that
1949 * a(p) + i = 0 mod g
1951 * If so, record the information in bound and apply the mapping
1952 * i -> (i + a(p))/g to the array index in bounds and return
1953 * the new constraints.
1954 * If not, simply return the original constraints.
1956 * If bounds is a subset of the space
1958 * D -> i
1960 * then the bound recorded in bound->shift is of the form
1962 * D -> s(D)
1964 * with s(D) equal to a(p) above.
1965 * The mapping recorded in bound->shift_map is of the form
1967 * [D -> i] -> [D -> (i + S(D))/g]
1969 * This mapping is computed as follows.
1970 * We first introduce "i" in the domain through precomposition
1971 * with [D -> i] -> D obtaining
1973 * [D -> i] -> s(D)
1975 * Adding [D -> i] -> i produces
1977 * [D -> i] -> i + s(D)
1979 * and the domain product with [D -> i] -> D yields
1981 * [D -> i] -> [D -> i + s(D)]
1983 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1985 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1986 __isl_take isl_basic_map *bounds)
1988 isl_space *space;
1989 isl_basic_map *hull;
1990 isl_basic_map *shift, *id, *bmap, *scale;
1991 isl_basic_set *bset;
1992 isl_aff *aff;
1994 bound->stride = NULL;
1996 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1998 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
2000 isl_basic_map_free(hull);
2002 if (!bound->stride)
2003 return bounds;
2005 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
2006 space = isl_basic_map_get_space(bounds);
2007 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
2008 shift = isl_basic_map_apply_range(bmap, shift);
2009 space = isl_basic_map_get_space(bounds);
2010 id = isl_basic_map_range_map(isl_basic_map_universe(space));
2011 shift = isl_basic_map_sum(id, shift);
2012 space = isl_basic_map_get_space(bounds);
2013 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
2014 shift = isl_basic_map_range_product(id, shift);
2016 space = isl_space_domain(isl_basic_map_get_space(bounds));
2017 id = isl_basic_map_identity(isl_space_map_from_set(space));
2018 space = isl_space_range(isl_basic_map_get_space(bounds));
2019 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2020 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2021 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
2022 scale = isl_basic_map_from_aff(aff);
2023 scale = isl_basic_map_product(id, scale);
2025 bound->shift_map = isl_basic_map_apply_range(shift, scale);
2026 bmap = isl_basic_map_copy(bound->shift_map);
2027 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
2028 bounds = isl_basic_set_unwrap(bset);
2030 return bounds;
2033 /* Data used in compute_array_dim_size and compute_size_in_direction.
2035 * pos is the position of the variable representing the array index,
2036 * i.e., the variable for which want to compute the size. This variable
2037 * is also the last variable in the set.
2039 struct gpu_size_info {
2040 isl_basic_set *bset;
2041 struct gpu_array_bound *bound;
2042 int pos;
2045 /* Given a constraint from the basic set describing the bounds on
2046 * an array index, check if it is a lower bound, say m i >= b(x), and,
2047 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
2048 * upper bound. If so, and if this bound is smaller than any bound
2049 * derived from earlier constraints, set the size to this bound on
2050 * the expression and the lower bound to ceil(b(x)/m).
2052 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
2054 struct gpu_size_info *size = user;
2055 unsigned nparam;
2056 unsigned n_div;
2057 isl_val *v;
2058 isl_aff *aff;
2059 isl_aff *lb;
2061 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
2062 n_div = isl_constraint_dim(c, isl_dim_div);
2064 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
2065 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
2066 isl_constraint_free(c);
2067 return 0;
2070 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
2071 aff = isl_aff_ceil(aff);
2073 lb = isl_aff_copy(aff);
2075 aff = isl_aff_neg(aff);
2076 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
2078 v = isl_basic_set_max_val(size->bset, aff);
2079 isl_aff_free(aff);
2081 if (isl_val_is_int(v)) {
2082 v = isl_val_add_ui(v, 1);
2083 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
2084 isl_val_free(size->bound->size);
2085 size->bound->size = isl_val_copy(v);
2086 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
2087 isl_aff_free(size->bound->lb);
2088 size->bound->lb = isl_aff_copy(lb);
2091 isl_val_free(v);
2092 isl_aff_free(lb);
2094 isl_constraint_free(c);
2096 return 0;
2099 /* Given a basic map "bounds" that maps parameters and input dimensions
2100 * to a single output dimension, look for an expression in the parameters
2101 * and input dimensions such that the range of the output dimension shifted
2102 * by this expression is a constant.
2104 * In particular, we currently only consider lower bounds on the output
2105 * dimension as candidate expressions.
2107 static int compute_array_dim_size(struct gpu_array_bound *bound,
2108 __isl_take isl_basic_map *bounds)
2110 struct gpu_size_info size;
2112 bounds = isl_basic_map_detect_equalities(bounds);
2113 bounds = check_stride(bound, bounds);
2115 bound->size = NULL;
2116 bound->lb = NULL;
2118 size.bound = bound;
2119 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2120 size.bset = isl_basic_map_wrap(bounds);
2121 size.bset = isl_basic_set_flatten(size.bset);
2122 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2123 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2124 &size);
2125 isl_basic_set_free(size.bset);
2127 return bound->size ? 0 : -1;
2130 /* Check if we can find a memory tile for the given array
2131 * based on the given accesses, and if so, put the results in "tile".
2133 * We project the accesses on each index in turn and look for a parametric
2134 * offset such that the size is constant.
2136 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2138 int i;
2140 for (i = 0; i < tile->n; ++i) {
2141 isl_map *access_i;
2142 isl_basic_map *hull;
2144 access_i = isl_map_copy(access);
2145 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2146 access_i = isl_map_project_out(access_i, isl_dim_out,
2147 1, tile->n - (i + 1));
2148 access_i = isl_map_compute_divs(access_i);
2149 hull = isl_map_simple_hull(access_i);
2150 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2151 return 0;
2154 return 1;
2157 /* Construct a map with input the shared tile loops and the loops that
2158 * will be wrapped around the threads that relates these later loops
2159 * to the thread indices and then projects them out.
2161 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2163 isl_map *priv;
2164 isl_map *tiling;
2165 isl_map *proj;
2166 isl_set *par;
2167 isl_space *dim;
2169 dim = isl_union_map_get_space(gen->shared_sched);
2171 if (gen->options->wrap)
2172 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2173 gen->shared_len, gen->n_block, gen->block_dim);
2174 else
2175 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2176 gen->shared_len, gen->n_block, gen->block_dim);
2178 priv = tiling;
2180 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2181 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2182 gen->n_block, "t");
2184 priv = isl_map_align_params(priv, isl_set_get_space(par));
2185 priv = isl_map_intersect_range(priv, par);
2187 dim = isl_map_get_space(priv);
2188 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2189 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2190 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2191 gen->shared_len);
2193 priv = isl_map_apply_range(priv, proj);
2195 return priv;
2198 /* Construct a map from domain_dim to domain_dim that increments
2199 * the dimension at position "pos" and leaves all other dimensions
2200 * constant.
2202 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2204 int i;
2205 int len = isl_space_dim(domain_dim, isl_dim_set);
2206 isl_space *dim;
2207 isl_basic_map *next;
2208 isl_local_space *ls;
2210 dim = isl_space_map_from_set(domain_dim);
2211 next = isl_basic_map_universe(isl_space_copy(dim));
2212 ls = isl_local_space_from_space(dim);
2214 for (i = 0; i < len; ++i) {
2215 isl_constraint *c;
2217 c = isl_equality_alloc(isl_local_space_copy(ls));
2218 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2219 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2220 if (i == pos)
2221 c = isl_constraint_set_constant_si(c, 1);
2222 next = isl_basic_map_add_constraint(next, c);
2225 isl_local_space_free(ls);
2227 return isl_map_from_basic_map(next);
2230 /* Check if the given access is coalesced.
2231 * That is, check whether incrementing the dimension that will get
2232 * wrapped over the last thread index results in incrementing
2233 * the last array index.
2235 * This function is only called for access relations without reuse.
2237 static int access_is_coalesced(struct gpu_gen *gen,
2238 __isl_keep isl_union_map *access)
2240 isl_space *dim;
2241 isl_map *access_map;
2242 isl_map *next_thread_x;
2243 isl_map *next_element;
2244 isl_map *map;
2245 int coalesced;
2247 access = isl_union_map_copy(access);
2248 access = isl_union_map_apply_domain(access,
2249 isl_union_map_copy(gen->tiled_sched));
2250 access_map = isl_map_from_union_map(access);
2252 dim = isl_map_get_space(access_map);
2253 dim = isl_space_domain(dim);
2254 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2256 dim = isl_map_get_space(access_map);
2257 dim = isl_space_range(dim);
2258 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2260 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2261 map = isl_map_apply_range(map, access_map);
2263 coalesced = isl_map_is_subset(map, next_element);
2265 isl_map_free(next_element);
2266 isl_map_free(map);
2268 return coalesced;
2271 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2272 * dimensions of the computed schedule, check if it is bijective for
2273 * fixed values of the first gen->shared_len dimensions.
2274 * We perform this check by equating these dimensions to parameters.
2276 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2278 int res;
2279 isl_set *par;
2280 isl_space *space;
2282 access = isl_map_copy(access);
2283 space = isl_space_params(isl_map_get_space(access));
2284 par = parametrization(space, gen->shared_len + gen->n_block,
2285 0, gen->shared_len, "s");
2286 access = isl_map_intersect_domain(access, par);
2287 res = isl_map_is_bijective(access);
2288 isl_map_free(access);
2290 return res;
2293 /* Look for the last shared tile loop that affects the offset of "tile"
2294 * and return the result.
2295 * If there is no such loop, then return the index of the loop
2296 * before the first shared tile loop, in particular gen->tile_first - 1.
2298 static int compute_tile_last_shared(struct gpu_gen *gen,
2299 struct gpu_array_tile *tile)
2301 int i, j;
2303 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2304 for (i = 0; i < tile->n; ++i) {
2305 isl_aff *lb;
2306 isl_aff *shift;
2308 lb = tile->bound[i].lb;
2309 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2310 break;
2312 shift = tile->bound[i].shift;
2313 if (!shift)
2314 continue;
2315 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2316 break;
2318 if (i < tile->n)
2319 break;
2322 return j;
2325 /* Look for the last shared tile loop that affects the offset of the
2326 * shared or private tile and store the result in group->last_shared.
2327 * If there is no such loop, then group->last_shared is set to a value
2328 * before the first shared tile loop, in particular gen->tile_first - 1.
2329 * If there is no tile defined on the array reference group,
2330 * then set group->last_shared to gen->shared_len - 1.
2332 static void set_last_shared(struct gpu_gen *gen,
2333 struct gpu_array_ref_group *group)
2335 struct gpu_array_tile *tile;
2337 group->last_shared = gen->shared_len - 1;
2339 tile = group->private_tile;
2340 if (!tile)
2341 tile = group->shared_tile;
2342 if (!tile)
2343 return;
2345 group->last_shared = compute_tile_last_shared(gen, tile);
2348 /* Compute a privatized copy of all access relations from reference groups that
2349 * are mapped to private memory and store the result in gen->privatization.
2351 * Read-only scalars and arrays containing structures are not mapped
2352 * to private memory.
2354 static void compute_private_access(struct gpu_gen *gen)
2356 int i, j;
2357 isl_union_map *private;
2359 if (!gen->options->use_private_memory)
2360 return;
2362 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2364 for (i = 0; i < gen->prog->n_array; ++i) {
2365 struct gpu_array_info *array = &gen->prog->array[i];
2367 if (gpu_array_is_read_only_scalar(array))
2368 continue;
2369 if (array->has_compound_element)
2370 continue;
2372 for (j = 0; j < array->n_group; ++j) {
2373 if (!array->groups[j]->private_tile)
2374 continue;
2376 private = isl_union_map_union(private,
2377 group_access_relation(array->groups[j], 1, 1));
2381 if (isl_union_map_is_empty(private))
2382 isl_union_map_free(private);
2383 else {
2384 isl_union_map *priv;
2386 private = isl_union_map_apply_domain(private,
2387 isl_union_map_copy(gen->shared_sched));
2388 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2389 private = isl_union_map_apply_domain(private, priv);
2390 gen->private_access = private;
2394 /* Compute the size of the tile specified by "tile"
2395 * in number of elements and return the result.
2397 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2399 int i;
2400 isl_val *size;
2402 size = isl_val_one(ctx);
2404 for (i = 0; i < tile->n; ++i)
2405 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2407 return size;
2410 /* If max_shared_memory is not set to infinity (-1), then make
2411 * sure that the total amount of shared memory required by the
2412 * array reference groups mapped to shared memory is no larger
2413 * than this maximum.
2415 * We apply a greedy approach and discard (keep in global memory)
2416 * those groups that would result in a total memory size that
2417 * is larger than the maximum.
2419 * This function should be called after any function that may
2420 * affect the decision on whether to place a reference group
2421 * in private, shared or global memory.
2423 static void check_shared_memory_bound(struct gpu_gen *gen)
2425 int i, j;
2426 isl_val *left, *size;
2428 if (gen->options->max_shared_memory < 0)
2429 return;
2431 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2433 for (i = 0; i < gen->prog->n_array; ++i) {
2434 struct gpu_array_info *array = &gen->prog->array[i];
2436 for (j = 0; j < array->n_group; ++j) {
2437 struct gpu_array_ref_group *group;
2439 group = array->groups[j];
2440 if (group->private_tile)
2441 continue;
2442 if (!group->shared_tile)
2443 continue;
2445 size = tile_size(gen->ctx, group->shared_tile);
2446 size = isl_val_mul_ui(size, array->size);
2448 if (isl_val_le(size, left)) {
2449 left = isl_val_sub(left, size);
2450 continue;
2452 isl_val_free(size);
2454 group->shared_tile = free_tile(group->shared_tile);
2458 isl_val_free(left);
2461 /* Given a description of an array tile "tile" and the "space"
2463 * { D -> A }
2465 * where D represents the first shared_len schedule dimensions
2466 * and A represents the array, construct an isl_multi_aff
2468 * { [D[i] -> A[a]] -> A'[a'] }
2470 * with A' a scaled down copy of A according to the shifts and strides
2471 * in "tile". In particular,
2473 * a' = (a + shift(i))/stride
2475 * "insert_array" represents
2477 * { [D -> A] -> D }
2479 * and is used to insert A into the domain of functions that only
2480 * reference D.
2482 static __isl_give isl_multi_aff *strided_tile(
2483 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2484 __isl_keep isl_multi_aff *insert_array)
2486 int i;
2487 isl_ctx *ctx;
2488 isl_multi_aff *shift;
2489 isl_multi_val *stride;
2490 isl_space *space2;
2491 isl_local_space *ls;
2492 isl_multi_aff *tiling;
2494 ctx = isl_space_get_ctx(space);
2495 space2 = isl_space_domain(isl_space_copy(space));
2496 ls = isl_local_space_from_space(space2);
2497 space2 = isl_space_range(isl_space_copy(space));
2498 stride = isl_multi_val_zero(space2);
2499 shift = isl_multi_aff_zero(isl_space_copy(space));
2501 for (i = 0; i < tile->n; ++i) {
2502 struct gpu_array_bound *bound = &tile->bound[i];
2503 isl_val *stride_i;
2504 isl_aff *shift_i;
2506 if (tile->bound[i].shift) {
2507 stride_i = isl_val_copy(bound->stride);
2508 shift_i = isl_aff_copy(bound->shift);
2509 } else {
2510 stride_i = isl_val_one(ctx);
2511 shift_i = isl_aff_zero_on_domain(
2512 isl_local_space_copy(ls));
2515 stride = isl_multi_val_set_val(stride, i, stride_i);
2516 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2518 isl_local_space_free(ls);
2520 shift = isl_multi_aff_pullback_multi_aff(shift,
2521 isl_multi_aff_copy(insert_array));
2523 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2524 tiling = isl_multi_aff_add(tiling, shift);
2525 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2527 return tiling;
2530 /* Compute a tiling for the array reference group "group".
2532 * The tiling is of the form
2534 * { [D[i] -> A[a]] -> T[t] }
2536 * where D represents the first shared_len schedule dimensions,
2537 * A represents the global array and T represents the shared or
2538 * private memory tile. The name of T is the name of the local
2539 * array.
2541 * If there is any stride in the accesses, then the mapping is
2543 * t = (a + shift(i))/stride - lb(i)
2545 * otherwise, it is simply
2547 * t = a - lb(i)
2549 static void compute_group_tiling(struct gpu_array_ref_group *group)
2551 int i;
2552 struct gpu_array_tile *tile;
2553 struct gpu_array_info *array = group->array;
2554 isl_space *space;
2555 isl_multi_aff *tiling, *lb, *insert_array;
2556 isl_printer *p;
2557 char *local_name;
2559 tile = group->private_tile;
2560 if (!tile)
2561 tile = group->shared_tile;
2562 if (!tile)
2563 return;
2565 space = isl_map_get_space(group->access);
2566 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2568 for (i = 0; i < tile->n; ++i)
2569 if (tile->bound[i].shift)
2570 break;
2572 if (i < tile->n)
2573 tiling = strided_tile(tile, space, insert_array);
2574 else
2575 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2577 lb = isl_multi_aff_zero(space);
2578 for (i = 0; i < tile->n; ++i) {
2579 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2580 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2582 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2584 tiling = isl_multi_aff_sub(tiling, lb);
2586 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2587 p = print_array_name(p, group);
2588 local_name = isl_printer_get_str(p);
2589 isl_printer_free(p);
2590 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2591 free(local_name);
2593 tile->tiling = tiling;
2596 /* Compute a tiling for all the array reference groups.
2598 static void compute_group_tilings(struct gpu_gen *gen)
2600 int i, j;
2602 for (i = 0; i < gen->prog->n_array; ++i) {
2603 struct gpu_array_info *array = &gen->prog->array[i];
2605 for (j = 0; j < array->n_group; ++j)
2606 compute_group_tiling(array->groups[j]);
2610 /* Fill up the groups array with singleton groups, i.e., one group
2611 * per reference, initializing the array, access, write, n_ref and refs fields.
2612 * In particular the access field is initialized to the scheduled
2613 * access relation of the array reference.
2615 * Return the number of elements initialized, i.e., the number of
2616 * active references in the current kernel.
2618 static int populate_array_references(struct gpu_array_info *array,
2619 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2621 int i;
2622 int n;
2623 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2625 n = 0;
2626 for (i = 0; i < array->n_ref; ++i) {
2627 isl_union_map *umap;
2628 isl_map *map;
2629 struct gpu_array_ref_group *group;
2630 struct gpu_stmt_access *access = array->refs[i];
2632 map = isl_map_copy(access->access);
2633 umap = isl_union_map_from_map(map);
2634 umap = isl_union_map_apply_domain(umap,
2635 isl_union_map_copy(sched));
2637 if (isl_union_map_is_empty(umap)) {
2638 isl_union_map_free(umap);
2639 continue;
2642 map = isl_map_from_union_map(umap);
2643 map = isl_map_detect_equalities(map);
2645 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2646 assert(group);
2647 group->array = array;
2648 group->access = map;
2649 group->write = access->write;
2650 group->exact_write = access->exact_write;
2651 group->refs = &array->refs[i];
2652 group->n_ref = 1;
2654 groups[n++] = group;
2657 return n;
2660 /* If group->n_ref == 1, then group->refs was set by
2661 * populate_array_references to point directly into
2662 * group->array->refs and should not be freed.
2663 * If group->n_ref > 1, then group->refs was set by join_groups
2664 * to point to a newly allocated array.
2666 static void free_array_ref_group(struct gpu_array_ref_group *group)
2668 if (!group)
2669 return;
2670 free_tile(group->shared_tile);
2671 free_tile(group->private_tile);
2672 isl_map_free(group->access);
2673 if (group->n_ref > 1)
2674 free(group->refs);
2675 free(group);
2678 /* Given a map where the input dimensions represent the tile loops,
2679 * eliminate the innermost of those that have a fixed value
2680 * until we reach one that does not (obviously) have a fixed value.
2682 static __isl_give isl_map *eliminate_fixed_inner_loops(
2683 __isl_take isl_map *access)
2685 int i, n;
2687 n = isl_map_dim(access, isl_dim_in);
2689 for (i = n - 1; i >= 0; --i) {
2690 if (!map_plain_is_fixed(access, isl_dim_in, i))
2691 break;
2692 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2694 return access;
2697 /* Check if the access relations of group1 and group2 overlap within
2698 * the innermost loop. In particular, ignore any inner dimension
2699 * with a fixed value.
2700 * The copying to and from shared memory will be performed within
2701 * the innermost actual loop so we are only allowed to consider
2702 * the dimensions up to that innermost loop while checking whether
2703 * two access relations overlap.
2705 static int accesses_overlap(struct gpu_array_ref_group *group1,
2706 struct gpu_array_ref_group *group2)
2708 int empty;
2709 isl_map *access1, *access2;
2711 access1 = isl_map_copy(group1->access);
2712 access1 = eliminate_fixed_inner_loops(access1);
2713 access2 = isl_map_copy(group2->access);
2714 access2 = eliminate_fixed_inner_loops(access2);
2715 access1 = isl_map_intersect(access1, access2);
2716 empty = isl_map_is_empty(access1);
2717 isl_map_free(access1);
2719 return !empty;
2722 /* Combine the given two groups into a single group, containing
2723 * the references of both groups.
2725 static struct gpu_array_ref_group *join_groups(
2726 struct gpu_array_ref_group *group1,
2727 struct gpu_array_ref_group *group2)
2729 int i;
2730 isl_ctx *ctx;
2731 struct gpu_array_ref_group *group;
2733 ctx = isl_map_get_ctx(group1->access);
2734 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2735 assert(group);
2736 group->array = group1->array;
2737 group->access = isl_map_union(isl_map_copy(group1->access),
2738 isl_map_copy(group2->access));
2739 group->write = group1->write || group2->write;
2740 group->exact_write = group1->exact_write && group2->exact_write;
2741 group->n_ref = group1->n_ref + group2->n_ref;
2742 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2743 group->n_ref);
2744 assert(group->refs);
2745 for (i = 0; i < group1->n_ref; ++i)
2746 group->refs[i] = group1->refs[i];
2747 for (i = 0; i < group2->n_ref; ++i)
2748 group->refs[group1->n_ref + i] = group2->refs[i];
2750 return group;
2753 /* Combine the given two groups into a single group and free
2754 * the original two groups.
2756 static struct gpu_array_ref_group *join_groups_and_free(
2757 struct gpu_array_ref_group *group1,
2758 struct gpu_array_ref_group *group2)
2760 struct gpu_array_ref_group *group;
2762 group = join_groups(group1, group2);
2763 free_array_ref_group(group1);
2764 free_array_ref_group(group2);
2765 return group;
2768 /* Compute the private and/or shared memory tiles for the array
2769 * reference group "group" of array "array".
2770 * Return 0 on success and -1 on error.
2772 * If the array is a read-only scalar or if the user requested
2773 * not to use shared or private memory, then we do not need to do anything.
2775 * If the array group involves any may writes (that are not must writes),
2776 * then we would have to make sure that we load the data into shared/private
2777 * memory first in case the data is not written by the kernel
2778 * (but still written back out to global memory).
2779 * Since we don't have any such mechanism at the moment, we don't
2780 * compute shared/private tiles for groups involving may writes.
2782 * We only try to compute a shared memory tile if there is any reuse
2783 * or if the access is not coalesced.
2785 * For computing a private memory tile, we also require that there is
2786 * some reuse. Moreover, we require that the access is private
2787 * to the thread. That is, we check that any given array element
2788 * is only accessed by a single thread.
2789 * We compute an access relation that maps the shared tile loop iterators
2790 * and the shared point loop iterators that will be wrapped over the
2791 * threads to the array elements.
2792 * We actually check that those iterators that will be wrapped
2793 * partition the array space. This check is stricter than necessary
2794 * since several iterations may be mapped onto the same thread
2795 * and then they could be allowed to access the same memory elements,
2796 * but our check does not allow this situation.
2798 * We also check that the index expression only depends on parallel
2799 * loops. That way, we can move those loops innermost and unroll them.
2800 * Again, we use a test that is stricter than necessary.
2801 * We actually check whether the index expression only depends
2802 * on the iterators that are wrapped over the threads.
2803 * These are necessarily parallel, but there may be more parallel loops.
2805 * Combining the injectivity of the first test with the single-valuedness
2806 * of the second test, we simply test for bijectivity.
2808 * If the array is marked force_private, then we bypass all checks
2809 * and assume we can (and should) use registers.
2811 * If it turns out we can (or have to) use registers, we compute
2812 * the private memory tile size using can_tile, after introducing a dependence
2813 * on the thread indices.
2815 static int compute_group_bounds_core(struct gpu_gen *gen,
2816 struct gpu_array_ref_group *group)
2818 isl_ctx *ctx = isl_space_get_ctx(group->array->space);
2819 isl_union_map *access;
2820 int n_index = group->array->n_index;
2821 int no_reuse;
2822 isl_map *acc;
2823 int force_private = group->array->force_private;
2824 int use_shared = gen->options->use_shared_memory;
2825 int use_private = force_private || gen->options->use_private_memory;
2827 if (!use_shared && !use_private)
2828 return 0;
2829 if (gpu_array_is_read_only_scalar(group->array))
2830 return 0;
2831 if (!force_private && !group->exact_write)
2832 return 0;
2834 access = group_access_relation(group, 1, 1);
2835 no_reuse = isl_union_map_is_injective(access);
2837 if (use_shared && (!no_reuse || !access_is_coalesced(gen, access))) {
2838 group->shared_tile = create_tile(ctx, group->array->n_index);
2839 if (!can_tile(group->access, group->shared_tile))
2840 group->shared_tile = free_tile(group->shared_tile);
2843 if (!force_private && (!use_private || no_reuse)) {
2844 isl_union_map_free(access);
2845 return 0;
2848 access = isl_union_map_apply_domain(access,
2849 isl_union_map_copy(gen->shared_sched));
2851 acc = isl_map_from_union_map(access);
2853 if (!force_private && !access_is_bijective(gen, acc)) {
2854 isl_map_free(acc);
2855 return 0;
2858 group->private_tile = create_tile(gen->ctx, n_index);
2859 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2860 if (!can_tile(acc, group->private_tile))
2861 group->private_tile = free_tile(group->private_tile);
2863 isl_map_free(acc);
2865 if (force_private && !group->private_tile)
2866 isl_die(ctx, isl_error_internal,
2867 "unable to map array reference group to registers",
2868 return -1);
2870 return 0;
2873 /* Compute the private and/or shared memory tiles for the array
2874 * reference group "group" of array "array" and set last_shared.
2875 * Return 0 on success and -1 on error.
2877 static int compute_group_bounds(struct gpu_gen *gen,
2878 struct gpu_array_ref_group *group)
2880 if (compute_group_bounds_core(gen, group) < 0)
2881 return -1;
2882 set_last_shared(gen, group);
2884 return 0;
2887 /* If two groups have overlapping access relations (as determined by
2888 * the "overlap" function) and if one of them involves a write,
2889 * then merge the two groups into one.
2890 * If "compute_bounds" is set, then call compute_group_bounds
2891 * on the merged groups.
2893 * Return the updated number of groups.
2894 * Return -1 on error.
2896 static int group_writes(struct gpu_gen *gen,
2897 int n, struct gpu_array_ref_group **groups,
2898 int (*overlap)(struct gpu_array_ref_group *group1,
2899 struct gpu_array_ref_group *group2), int compute_bounds)
2901 int i, j;
2903 for (i = 0; i < n; ++i) {
2904 for (j = n - 1; j > i; --j) {
2905 if (!groups[i]->write && !groups[j]->write)
2906 continue;
2908 if (!overlap(groups[i], groups[j]))
2909 continue;
2911 groups[i] = join_groups_and_free(groups[i], groups[j]);
2912 if (compute_bounds &&
2913 compute_group_bounds(gen, groups[i]) < 0)
2914 return -1;
2915 if (j != n - 1)
2916 groups[j] = groups[n - 1];
2917 groups[n - 1] = NULL;
2918 n--;
2922 return n;
2925 /* If two groups have overlapping access relations (within the innermost
2926 * loop) and if one of them involves a write, then merge the two groups
2927 * into one.
2929 * Return the updated number of groups.
2931 static int group_overlapping_writes(struct gpu_gen *gen,
2932 int n, struct gpu_array_ref_group **groups)
2934 return group_writes(gen, n, groups, &accesses_overlap, 0);
2937 /* Check if the access relations of group1 and group2 overlap within
2938 * the outermost min(group1->last_shared, group2->last_shared) loops.
2940 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2941 struct gpu_array_ref_group *group2)
2943 int last_shared;
2944 int dim;
2945 int empty;
2946 isl_map *map_i, *map_j, *map;
2948 last_shared = group1->last_shared;
2949 if (group2->last_shared < last_shared)
2950 last_shared = group2->last_shared;
2951 map_i = isl_map_copy(group1->access);
2952 dim = isl_map_dim(map_i, isl_dim_in);
2953 map_i = isl_map_eliminate(map_i, isl_dim_in,
2954 last_shared + 1, dim - (last_shared + 1));
2955 map_j = isl_map_copy(group2->access);
2956 map_j = isl_map_eliminate(map_j, isl_dim_in,
2957 last_shared + 1, dim - (last_shared + 1));
2958 map = isl_map_intersect(map_i, map_j);
2959 empty = isl_map_is_empty(map);
2960 isl_map_free(map);
2962 return !empty;
2965 /* If two groups have overlapping access relations (within the outer
2966 * last_shared loops) and if one of them involves a write,
2967 * then merge the two groups into one.
2969 * Return the updated number of groups.
2971 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2972 struct gpu_array_ref_group **groups)
2974 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2977 /* Is the size of the tile specified by "tile" smaller than the sum of
2978 * the sizes of the tiles specified by "tile1" and "tile2"?
2980 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
2981 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2983 int smaller;
2984 isl_val *size, *size1, *size2;
2986 size = tile_size(ctx, tile);
2987 size1 = tile_size(ctx, tile1);
2988 size2 = tile_size(ctx, tile2);
2990 size = isl_val_sub(size, size1);
2991 size = isl_val_sub(size, size2);
2992 smaller = isl_val_is_neg(size);
2994 isl_val_free(size);
2996 return smaller;
2999 /* Given an initial grouping of array references and shared memory tiles
3000 * for each group that allows for a shared memory tile, merge two groups
3001 * if both have a shared memory tile, the merged group also has
3002 * a shared memory tile and the size of the tile for the merge group
3003 * is smaller than the sum of the tile sizes of the individual groups.
3005 * If merging two groups decreases the "last_shared" dimension of
3006 * one or both of the two groups, then we need to check for overlapping
3007 * writes again.
3009 * Return the number of groups after merging.
3010 * Return -1 on error.
3012 static int group_common_shared_memory_tile(struct gpu_gen *gen,
3013 struct gpu_array_info *array, int n,
3014 struct gpu_array_ref_group **groups)
3016 int i, j;
3017 int recompute_overlap = 0;
3018 isl_ctx *ctx = isl_space_get_ctx(array->space);
3020 for (i = 0; i < n; ++i) {
3021 if (!groups[i]->shared_tile)
3022 continue;
3023 for (j = n - 1; j > i; --j) {
3024 isl_map *map;
3025 int empty;
3026 struct gpu_array_ref_group *group;
3028 if (!groups[j]->shared_tile)
3029 continue;
3031 map = isl_map_intersect(isl_map_copy(groups[i]->access),
3032 isl_map_copy(groups[j]->access));
3033 empty = isl_map_is_empty(map);
3034 isl_map_free(map);
3036 if (empty)
3037 continue;
3039 group = join_groups(groups[i], groups[j]);
3040 if (compute_group_bounds(gen, group) < 0) {
3041 free_array_ref_group(group);
3042 return -1;
3044 if (!group->shared_tile ||
3045 !smaller_tile(ctx, group->shared_tile,
3046 groups[i]->shared_tile,
3047 groups[j]->shared_tile)) {
3048 free_array_ref_group(group);
3049 continue;
3052 if (group->last_shared < groups[i]->last_shared ||
3053 group->last_shared < groups[j]->last_shared)
3054 recompute_overlap = 1;
3055 free_array_ref_group(groups[i]);
3056 free_array_ref_group(groups[j]);
3057 groups[i] = group;
3058 if (j != n - 1)
3059 groups[j] = groups[n - 1];
3060 n--;
3064 if (recompute_overlap)
3065 n = group_last_shared_overlapping_writes(gen, n, groups);
3066 return n;
3069 /* Set array->n_group and array->groups to n and groups.
3071 * Additionally, set the "nr" field of each group
3072 * and the "group" field of each reference in each group.
3074 static void set_array_groups(struct gpu_array_info *array,
3075 int n, struct gpu_array_ref_group **groups)
3077 int i, j;
3079 array->n_group = n;
3080 array->groups = groups;
3082 for (i = 0; i < n; ++i) {
3083 groups[i]->nr = i;
3085 for (j = 0; j < groups[i]->n_ref; ++j)
3086 groups[i]->refs[j]->group = i;
3090 /* Group array references that should be considered together when
3091 * deciding whether to access them from private, shared or global memory.
3092 * Return -1 on error.
3094 * In particular, if two array references overlap and if one of them
3095 * is a write, then the two references are grouped together.
3096 * We first perform an initial grouping based only on the access relation.
3097 * After computing shared and private memory tiles, we check for
3098 * overlapping writes again, but this time taking into account
3099 * the "last_shared" property.
3101 * Furthermore, if two groups admit a shared memory tile and if the
3102 * combination of the two also admits a shared memory tile, we merge
3103 * the two groups.
3105 * If the array contains structures, then there is no need to compute
3106 * reference groups since we do not map such arrays to private or shared
3107 * memory.
3109 static int group_array_references(struct gpu_gen *gen,
3110 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
3112 int i;
3113 int n;
3114 isl_ctx *ctx = isl_union_map_get_ctx(sched);
3115 struct gpu_array_ref_group **groups;
3117 if (array->has_compound_element)
3118 return 0;
3120 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
3121 array->n_ref);
3122 if (!groups)
3123 return -1;
3125 n = populate_array_references(array, sched, groups);
3127 n = group_overlapping_writes(gen, n, groups);
3129 for (i = 0; i < n; ++i)
3130 if (compute_group_bounds(gen, groups[i]) < 0)
3131 n = -1;
3133 n = group_last_shared_overlapping_writes(gen, n, groups);
3135 n = group_common_shared_memory_tile(gen, array, n, groups);
3137 set_array_groups(array, n, groups);
3139 if (n >= 0)
3140 return 0;
3142 for (i = 0; i < array->n_ref; ++i)
3143 free_array_ref_group(groups[i]);
3144 return -1;
3147 /* Take tiled_sched, project it onto the shared tile loops and
3148 * the loops that will be wrapped over the threads and
3149 * store the result in gen->shared_sched.
3150 * Also compute a projection that projects out the loops that will be
3151 * wrapped over the threads and store this projection in gen->shared_proj.
3153 static void compute_shared_sched(struct gpu_gen *gen)
3155 isl_space *dim;
3156 isl_map *proj;
3157 isl_set *par;
3158 isl_union_map *sched;
3160 sched = isl_union_map_copy(gen->tiled_sched);
3162 dim = isl_union_map_get_space(sched);
3163 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
3164 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3166 dim = isl_union_map_get_space(sched);
3167 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
3169 gen->shared_sched = sched;
3170 gen->shared_proj = isl_union_map_from_map(proj);
3173 /* For each scalar in the input program, check if there are any
3174 * order dependences active inside the current kernel, within
3175 * the same iteration of the host schedule.
3176 * If so, mark the scalar as force_private so that it will be
3177 * mapped to a register.
3179 static void check_scalar_live_ranges(struct gpu_gen *gen)
3181 int i;
3182 isl_map *proj;
3183 isl_union_map *sched;
3184 isl_union_set *domain;
3185 isl_union_map *same_host_iteration;
3187 gen->any_force_private = 0;
3189 if (!gen->options->live_range_reordering)
3190 return;
3192 sched = gen->shared_sched;
3193 sched = isl_union_map_universe(isl_union_map_copy(sched));
3194 domain = isl_union_map_domain(sched);
3196 sched = isl_union_map_copy(gen->sched);
3197 proj = projection(isl_union_map_get_space(sched),
3198 gen->untiled_len, gen->tile_first);
3199 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3200 same_host_iteration = isl_union_map_apply_range(sched,
3201 isl_union_map_reverse(isl_union_map_copy(sched)));
3203 for (i = 0; i < gen->prog->n_array; ++i) {
3204 struct gpu_array_info *array = &gen->prog->array[i];
3205 isl_union_map *order;
3207 array->force_private = 0;
3208 if (array->n_index != 0)
3209 continue;
3210 order = isl_union_map_copy(array->dep_order);
3211 order = isl_union_map_intersect_domain(order,
3212 isl_union_set_copy(domain));
3213 order = isl_union_map_intersect_range(order,
3214 isl_union_set_copy(domain));
3215 order = isl_union_map_intersect(order,
3216 isl_union_map_copy(same_host_iteration));
3217 if (!isl_union_map_is_empty(order)) {
3218 array->force_private = 1;
3219 gen->any_force_private = 1;
3221 isl_union_map_free(order);
3224 isl_union_map_free(same_host_iteration);
3225 isl_union_set_free(domain);
3228 /* Group references of all arrays in the program.
3230 static int group_references(struct gpu_gen *gen)
3232 int i;
3233 int r = 0;
3234 isl_union_map *sched;
3236 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3237 isl_union_map_copy(gen->shared_proj));
3239 for (i = 0; i < gen->prog->n_array; ++i) {
3240 r = group_array_references(gen, &gen->prog->array[i], sched);
3241 if (r < 0)
3242 break;
3245 isl_union_map_free(sched);
3247 return r;
3250 /* Free all array information that is local to the current kernel.
3252 static void free_local_array_info(struct gpu_gen *gen)
3254 int i, j;
3256 for (i = 0; i < gen->prog->n_array; ++i) {
3257 struct gpu_array_info *array = &gen->prog->array[i];
3259 for (j = 0; j < array->n_group; ++j)
3260 free_array_ref_group(array->groups[j]);
3261 free(array->groups);
3265 /* Compute the size of a bounding box around the origin and "set",
3266 * where "set" is assumed to contain only non-negative elements.
3267 * In particular, compute the maximal value of "set" in each direction
3268 * and add one.
3270 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
3271 __isl_keep isl_set *context)
3273 int i, n;
3274 isl_multi_pw_aff *mpa;
3276 n = isl_set_dim(set, isl_dim_set);
3277 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
3278 for (i = 0; i < n; ++i) {
3279 isl_space *space;
3280 isl_aff *one;
3281 isl_pw_aff *bound;
3283 bound = isl_set_dim_max(isl_set_copy(set), i);
3284 bound = isl_pw_aff_coalesce(bound);
3285 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
3287 space = isl_pw_aff_get_domain_space(bound);
3288 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
3289 one = isl_aff_add_constant_si(one, 1);
3290 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
3291 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
3293 isl_set_free(set);
3295 return mpa;
3298 /* Compute the effective grid size as a list of the sizes in each dimension.
3300 * The grid size specified by the user or set by default
3301 * in read_grid_sizes() and applied in tile_schedule(),
3302 * may be too large for the given code in the sense that
3303 * it may contain blocks that don't need to execute anything.
3304 * We therefore don't return this grid size, but instead the
3305 * smallest grid size that ensures that all blocks that actually
3306 * execute code are included in the grid.
3308 * We first extract a description of the grid, i.e., the possible values
3309 * of the block ids, from gen->tiled_sched.
3310 * The block ids are parameters in gen->tiled_sched.
3311 * We simply need to change them into set dimensions.
3313 * Then, for each block dimension, we compute the maximal value of the block id
3314 * and add one.
3316 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
3317 struct ppcg_kernel *kernel)
3319 int i;
3320 isl_set *grid;
3322 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
3323 grid = isl_set_from_params(grid);
3324 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
3325 for (i = 0; i < gen->n_grid; ++i) {
3326 int pos;
3327 char name[20];
3329 snprintf(name, sizeof(name), "b%d", i);
3330 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
3331 assert(pos >= 0);
3332 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
3333 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
3336 return extract_size(grid, kernel->context);
3339 /* Compute the size of a fixed bounding box around the origin and "set",
3340 * where "set" is assumed to contain only non-negative elements,
3341 * and store the results in "size".
3342 * In particular, compute the maximal value of "set" in each direction
3343 * and add one.
3345 static void extract_fixed_size(__isl_take isl_set *set, int *size)
3347 int i, n;
3348 isl_local_space *ls;
3349 isl_aff *obj;
3351 n = isl_set_dim(set, isl_dim_set);
3352 ls = isl_local_space_from_space(isl_set_get_space(set));
3353 obj = isl_aff_zero_on_domain(ls);
3354 for (i = 0; i < n; ++i) {
3355 isl_val *max;
3357 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
3358 max = isl_set_max_val(set, obj);
3359 size[i] = isl_val_get_num_si(max) + 1;
3360 isl_val_free(max);
3361 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
3363 isl_aff_free(obj);
3364 isl_set_free(set);
3367 /* Compute the effective block size as a list of the sizes in each dimension
3368 * and store the sizes in kernel->block_dim.
3370 * The block size specified by the user or set by default
3371 * in read_block_sizes() and applied in thread_tile_schedule(),
3372 * may be too large for the given code in the sense that
3373 * it may contain threads that don't need to execute anything.
3374 * We therefore don't store this block size in kernel->block_dim,
3375 * but instead the smallest block size that ensures that all threads
3376 * that actually execute code are included in the block.
3378 * The current implementation eliminates all parameters, ensuring
3379 * that the size is a fixed constant in each dimension.
3380 * In principle we could also compute parametric sizes.
3381 * We would have to make sure to project out all b%d and t%d parameters,
3382 * however.
3384 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3386 int i;
3387 int nparam;
3388 isl_set *block;
3389 isl_multi_pw_aff *mpa;
3391 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3392 block = isl_set_from_params(block);
3393 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3394 kernel->n_block = gen->n_block;
3395 for (i = 0; i < gen->n_block; ++i) {
3396 int pos;
3397 char name[20];
3399 snprintf(name, sizeof(name), "t%d", i);
3400 pos = isl_set_find_dim_by_name(block, isl_dim_param, name);
3401 assert(pos >= 0);
3402 block = isl_set_equate(block, isl_dim_param, pos,
3403 isl_dim_set, i);
3405 nparam = isl_set_dim(block, isl_dim_param);
3406 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3408 extract_fixed_size(block, kernel->block_dim);
3411 void ppcg_kernel_free(void *user)
3413 struct ppcg_kernel *kernel = user;
3414 int i;
3416 if (!kernel)
3417 return;
3419 isl_multi_pw_aff_free(kernel->grid_size);
3420 isl_set_free(kernel->context);
3421 isl_union_set_free(kernel->arrays);
3422 isl_space_free(kernel->space);
3423 isl_ast_node_free(kernel->tree);
3425 for (i = 0; i < kernel->n_array; ++i)
3426 isl_pw_aff_list_free(kernel->array[i].bound);
3427 free(kernel->array);
3429 for (i = 0; i < kernel->n_var; ++i) {
3430 free(kernel->var[i].name);
3431 isl_vec_free(kernel->var[i].size);
3433 free(kernel->var);
3435 free(kernel);
3438 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3439 struct ppcg_kernel_var *var)
3441 int j;
3442 struct gpu_array_tile *tile;
3443 isl_printer *p;
3444 char *name;
3446 var->array = group->array;
3448 tile = group->private_tile;
3449 var->type = ppcg_access_private;
3450 if (!tile) {
3451 tile = group->shared_tile;
3452 var->type = ppcg_access_shared;
3455 p = isl_printer_to_str(ctx);
3456 p = print_array_name(p, group);
3457 var->name = isl_printer_get_str(p);
3458 isl_printer_free(p);
3460 var->size = isl_vec_alloc(ctx, group->array->n_index);
3462 for (j = 0; j < group->array->n_index; ++j)
3463 var->size = isl_vec_set_element_val(var->size, j,
3464 isl_val_copy(tile->bound[j].size));
3467 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3469 int i, j, n;
3471 n = 0;
3472 for (i = 0; i < gen->prog->n_array; ++i) {
3473 struct gpu_array_info *array = &gen->prog->array[i];
3475 for (j = 0; j < array->n_group; ++j) {
3476 struct gpu_array_ref_group *group = array->groups[j];
3477 if (group->private_tile || group->shared_tile)
3478 ++n;
3482 kernel->n_var = n;
3483 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3484 assert(kernel->var);
3486 n = 0;
3487 for (i = 0; i < gen->prog->n_array; ++i) {
3488 struct gpu_array_info *array = &gen->prog->array[i];
3490 for (j = 0; j < array->n_group; ++j) {
3491 struct gpu_array_ref_group *group = array->groups[j];
3492 if (!group->private_tile && !group->shared_tile)
3493 continue;
3494 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3495 ++n;
3500 /* The sizes of the arrays on the host that have been computed by
3501 * extract_array_info may depend on the parameters. Use the extra
3502 * constraints on the parameters that are valid at "host_domain"
3503 * to simplify these expressions and store the results in kernel->array.
3505 * We only need these localized bounds for arrays that are accessed
3506 * by the current kernel. If we have found at least one reference group
3507 * then the array is accessed by the kernel. If the array has compound
3508 * elements then we skipped the construction of array reference groups.
3510 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3511 __isl_keep isl_set *host_domain)
3513 int i, j;
3514 isl_set *context;
3516 kernel->array = isl_calloc_array(gen->ctx,
3517 struct gpu_local_array_info, gen->prog->n_array);
3518 assert(kernel->array);
3519 kernel->n_array = gen->prog->n_array;
3521 context = isl_set_copy(host_domain);
3522 context = isl_set_params(context);
3524 for (i = 0; i < gen->prog->n_array; ++i) {
3525 struct gpu_array_info *array = &gen->prog->array[i];
3526 isl_pw_aff_list *local;
3528 if (array->n_group == 0 && !array->has_compound_element)
3529 continue;
3531 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3533 for (j = 0; j < array->n_index; ++j) {
3534 isl_pw_aff *pwaff;
3536 pwaff = isl_pw_aff_copy(array->bound[j]);
3537 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3538 local = isl_pw_aff_list_add(local, pwaff);
3541 kernel->array[i].bound = local;
3543 isl_set_free(context);
3546 /* Find the element in gen->stmt that has the given "id".
3547 * Return NULL if no such gpu_stmt can be found.
3549 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3551 int i;
3553 for (i = 0; i < prog->n_stmts; ++i) {
3554 if (id == prog->stmts[i].id)
3555 break;
3558 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3561 /* Set gen->tile_len and gen->n_parallel to those of the statement
3562 * affected by the first map (part of the schedule)
3563 * on which this function is called.
3564 * Because of the way the schedule is constructed, the other statements
3565 * in the list, if any, should have the same values for these properties.
3567 static int extract_tile_len(__isl_take isl_map *map, void *user)
3569 struct gpu_gen *gen = (struct gpu_gen *) user;
3570 isl_id *id;
3571 struct gpu_stmt *stmt;
3573 id = isl_map_get_tuple_id(map, isl_dim_in);
3574 stmt = find_stmt(gen->prog, id);
3575 isl_id_free(id);
3577 isl_map_free(map);
3579 if (!stmt)
3580 isl_die(gen->ctx, isl_error_unknown,
3581 "statement not found", return -1);
3583 gen->tile_len = stmt->tile_len;
3584 gen->n_parallel = stmt->n_parallel;
3586 return -1;
3589 void ppcg_kernel_stmt_free(void *user)
3591 int i;
3592 struct ppcg_kernel_stmt *stmt = user;
3594 if (!stmt)
3595 return;
3597 switch (stmt->type) {
3598 case ppcg_kernel_copy:
3599 isl_ast_expr_free(stmt->u.c.index);
3600 isl_ast_expr_free(stmt->u.c.local_index);
3601 break;
3602 case ppcg_kernel_domain:
3603 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
3604 break;
3605 case ppcg_kernel_sync:
3606 break;
3609 free(stmt);
3612 /* Set the options of "context" to
3614 * { space -> [x] : x >= first }
3616 static __isl_give isl_ast_build *set_unroll(
3617 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3618 int first)
3620 isl_ctx *ctx;
3621 isl_map *unroll;
3622 isl_union_map *opt;
3624 ctx = isl_ast_build_get_ctx(build);
3626 space = isl_space_from_domain(space);
3627 space = isl_space_add_dims(space, isl_dim_out, 1);
3628 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3629 unroll = isl_map_universe(space);
3630 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3631 opt = isl_union_map_from_map(unroll);
3633 build = isl_ast_build_set_options(build, opt);
3635 return build;
3638 /* Return a list of isl_ids of the form "prefix%d".
3640 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3641 int n, const char *prefix)
3643 int i;
3644 char name[10];
3645 isl_id_list *names;
3647 names = isl_id_list_alloc(ctx, n);
3648 for (i = 0; i < n; ++i) {
3649 isl_id *id;
3651 snprintf(name, sizeof(name), "%s%d", prefix, i);
3652 id = isl_id_alloc(ctx, name, NULL);
3653 names = isl_id_list_add(names, id);
3656 return names;
3659 /* Extend the schedule "schedule" with the part of "extension"
3660 * starting at "first" up to "len".
3662 static __isl_give isl_union_map *extend_schedule(
3663 __isl_take isl_union_map *schedule,
3664 __isl_take isl_union_map *extension, int first, int len)
3666 isl_space *space;
3667 isl_map *proj;
3668 isl_union_map *umap;
3669 isl_set *set;
3671 space = isl_union_map_get_space(schedule);
3672 space = isl_space_set_from_params(space);
3673 space = isl_space_add_dims(space, isl_dim_set, len);
3674 proj = isl_set_identity(isl_set_universe(space));
3675 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3676 extension = isl_union_map_apply_range(extension,
3677 isl_union_map_from_map(proj));
3679 schedule = isl_union_map_range_product(schedule, extension);
3681 return schedule;
3684 /* Return the gpu_stmt_access in the list "accesses" that corresponds
3685 * to "ref_id".
3687 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
3688 __isl_keep isl_id *ref_id)
3690 struct gpu_stmt_access *access;
3692 for (access = accesses; access; access = access->next)
3693 if (access->ref_id == ref_id)
3694 return access;
3696 return NULL;
3699 /* Return the index of the array called "name" in the list of arrays.
3701 static int find_array_index(struct gpu_gen *gen, const char *name)
3703 int i;
3705 for (i = 0; i < gen->prog->n_array; ++i)
3706 if (!strcmp(name, gen->prog->array[i].name))
3707 return i;
3709 return -1;
3712 /* Internal data structure for the index and AST expression transformation
3713 * callbacks for pet_stmt_build_ast_exprs.
3715 * "accesses" is the list of gpu_stmt_access in the statement.
3716 * "iterator_map" expresses the statement iterators in terms of
3717 * the AST loop iterators.
3718 * "sched2shared" expresses the first shared_len dimensions of
3719 * the computed schedule in terms of the AST loop iterators.
3721 * The following fields are set in transform_index and used in transform_expr.
3722 * "array" is the array that is being accessed.
3723 * "global" is set if the global array is accessed (rather than
3724 * shared/private memory).
3725 * "local_array" refers to information on the array specialized
3726 * to the current kernel.
3728 struct ppcg_transform_data {
3729 struct gpu_gen *gen;
3730 struct gpu_stmt_access *accesses;
3731 isl_pw_multi_aff *iterator_map;
3732 isl_pw_multi_aff *sched2shared;
3734 struct gpu_array_info *array;
3735 int global;
3736 struct gpu_local_array_info *local_array;
3739 /* Return the name of the outer array (of structs) accessed by "access".
3741 static const char *get_outer_array_name(__isl_keep isl_map *access)
3743 isl_space *space;
3744 const char *name;
3746 space = isl_space_range(isl_map_get_space(access));
3747 while (space && isl_space_is_wrapping(space))
3748 space = isl_space_domain(isl_space_unwrap(space));
3749 name = isl_space_get_tuple_name(space, isl_dim_set);
3750 isl_space_free(space);
3752 return name;
3755 /* Index transformation callback for pet_stmt_build_ast_exprs.
3757 * "index" expresses the array indices in terms of statement iterators
3759 * We first reformulate "index" in terms of the AST loop iterators.
3760 * Then we check if we are accessing the global array or
3761 * a shared/private copy. In the former case, we simply return
3762 * the updated index. If "index" is an affine expression rather
3763 * than an array access, then we also return the updated index here.
3765 * If no reference groups have been computed for the array,
3766 * then we can only be accessing the global array.
3768 * Otherwise, we apply the tiling to the index.
3769 * This tiling is of the form
3771 * [D -> A] -> T
3773 * The index is of the form
3775 * L -> A
3777 * We update the tiling to refer to the AST loop iteratos
3779 * [L -> A] -> T
3781 * and modify index to keep track of those iterators
3783 * L -> [L -> A]
3785 * Combining these two yields a tiled index expression in terms
3786 * of the AST loop iterators
3788 * L -> T
3790 static __isl_give isl_multi_pw_aff *transform_index(
3791 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
3792 void *user)
3794 struct ppcg_transform_data *data = user;
3795 struct gpu_stmt_access *access;
3796 struct gpu_array_ref_group *group;
3797 struct gpu_array_tile *tile;
3798 isl_pw_multi_aff *iterator_map;
3799 int i;
3800 const char *name;
3801 isl_space *space;
3802 isl_multi_pw_aff *tiling;
3803 isl_pw_multi_aff *pma;
3804 isl_multi_pw_aff *mpa;
3806 data->array = NULL;
3808 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
3809 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
3811 access = find_access(data->accesses, ref_id);
3812 if (!access)
3813 return index;
3814 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
3815 return index;
3817 name = get_outer_array_name(access->access);
3818 i = find_array_index(data->gen, name);
3819 if (i < 0)
3820 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
3821 "cannot find array",
3822 return isl_multi_pw_aff_free(index));
3823 data->array = &data->gen->prog->array[i];
3824 data->local_array = &data->gen->kernel->array[i];
3826 if (access->group < 0) {
3827 data->global = 1;
3828 return index;
3831 group = data->array->groups[access->group];
3832 tile = group->private_tile;
3833 if (!tile)
3834 tile = group->shared_tile;
3835 data->global = !tile;
3836 if (!tile)
3837 return index;
3839 space = isl_space_range(isl_multi_pw_aff_get_space(index));
3840 space = isl_space_map_from_set(space);
3841 pma = isl_pw_multi_aff_identity(space);
3842 pma = isl_pw_multi_aff_product(
3843 isl_pw_multi_aff_copy(data->sched2shared), pma);
3844 tiling = isl_multi_pw_aff_from_multi_aff(
3845 isl_multi_aff_copy(tile->tiling));
3846 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
3848 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
3849 space = isl_space_map_from_set(space);
3850 mpa = isl_multi_pw_aff_identity(space);
3851 index = isl_multi_pw_aff_range_product(mpa, index);
3852 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
3854 return index;
3857 /* Dereference "expr" by adding an index [0].
3858 * The original "expr" is assumed not to have any indices.
3860 * If "expr" is a member access, then the dereferencing needs
3861 * to be applied to the structure argument of this member access.
3863 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
3865 isl_ctx *ctx;
3866 isl_ast_expr *res;
3867 isl_ast_expr_list *list;
3869 if (isl_ast_expr_get_op_type(expr) == isl_ast_op_member) {
3870 isl_ast_expr *arg;
3872 arg = isl_ast_expr_get_op_arg(expr, 0);
3873 arg = dereference(arg);
3874 expr = isl_ast_expr_set_op_arg(expr, 0, arg);
3876 return expr;
3879 ctx = isl_ast_expr_get_ctx(expr);
3880 res = isl_ast_expr_from_val(isl_val_zero(ctx));
3881 list = isl_ast_expr_list_from_ast_expr(res);
3882 res = isl_ast_expr_get_op_arg(expr, 0);
3883 res = isl_ast_expr_access(res, list);
3884 isl_ast_expr_free(expr);
3886 return res;
3889 /* Linearize the index expression "expr" based on the array bounds
3890 * of "array".
3892 * That is, transform expression
3894 * A[i_0][i_1]...[i_n]
3896 * to
3898 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
3900 * where b_0, b_1, ..., b_n are the bounds on the array.
3902 * If the base of "expr" is a member access, then the linearization needs
3903 * to be applied to the structure argument of this member access.
3905 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
3906 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
3908 int i, n;
3909 isl_ctx *ctx;
3910 isl_set *context;
3911 isl_ast_expr *arg0;
3912 isl_ast_expr *res;
3913 isl_ast_expr_list *list;
3914 isl_ast_build *build;
3916 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3917 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3918 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3919 isl_ast_expr *arg;
3921 arg = isl_ast_expr_get_op_arg(arg0, 0);
3922 arg = gpu_local_array_info_linearize_index(array, arg);
3923 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3924 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3926 return expr;
3928 isl_ast_expr_free(arg0);
3930 ctx = isl_ast_expr_get_ctx(expr);
3931 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
3932 build = isl_ast_build_from_context(context);
3934 n = isl_ast_expr_get_op_n_arg(expr);
3935 res = isl_ast_expr_get_op_arg(expr, 1);
3936 for (i = 2; i < n; ++i) {
3937 isl_pw_aff *bound_i;
3938 isl_ast_expr *expr_i;
3940 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i - 1);
3941 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
3942 res = isl_ast_expr_mul(res, expr_i);
3943 expr_i = isl_ast_expr_get_op_arg(expr, i);
3944 res = isl_ast_expr_add(res, expr_i);
3947 isl_ast_build_free(build);
3949 list = isl_ast_expr_list_from_ast_expr(res);
3950 res = isl_ast_expr_get_op_arg(expr, 0);
3951 res = isl_ast_expr_access(res, list);
3953 isl_ast_expr_free(expr);
3955 return res;
3958 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
3960 * If the AST expression refers to a global scalar that is not
3961 * a read-only scalar, then its address was passed to the kernel and
3962 * we need to dereference it.
3964 * If the AST expression refers to an access to a global array,
3965 * then we linearize the access exploiting the bounds in data->local_array.
3967 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
3968 __isl_keep isl_id *id, void *user)
3970 struct ppcg_transform_data *data = user;
3972 if (!data->array)
3973 return expr;
3974 if (gpu_array_is_read_only_scalar(data->array))
3975 return expr;
3976 if (!data->global)
3977 return expr;
3978 if (data->array->n_index == 0)
3979 return dereference(expr);
3980 if (!data->array->linearize)
3981 return expr;
3983 return gpu_local_array_info_linearize_index(data->local_array, expr);
3986 /* This function is called for each instance of a user statement
3987 * in the kernel.
3989 * We attach a struct ppcg_kernel_stmt to the "node", containing
3990 * a computed AST expression for each access.
3991 * These AST expressions are computed from iterator_map,
3992 * which expresses the domain
3993 * elements in terms of the generated loops, and sched2shared,
3994 * which expresses the first shared_len dimensions of the schedule
3995 * computed by PPCG in terms of the generated loops.
3997 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3998 __isl_keep isl_ast_build *build, void *user)
4000 struct ppcg_transform_data data;
4001 struct gpu_gen *gen = (struct gpu_gen *) user;
4002 struct ppcg_kernel_stmt *stmt;
4003 isl_id *id;
4004 isl_pw_multi_aff *sched2shared;
4005 isl_map *map;
4006 isl_pw_multi_aff *iterator_map;
4007 isl_ast_expr *expr, *arg;
4008 isl_union_map *schedule;
4009 int i, n;
4010 struct gpu_stmt_access *access;
4012 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4013 if (!stmt)
4014 return isl_ast_node_free(node);
4016 expr = isl_ast_node_user_get_expr(node);
4017 arg = isl_ast_expr_get_op_arg(expr, 0);
4018 id = isl_ast_expr_get_id(arg);
4020 schedule = isl_ast_build_get_schedule(build);
4021 map = isl_map_reverse(isl_map_from_union_map(schedule));
4022 iterator_map = isl_pw_multi_aff_from_map(map);
4023 sched2shared = compute_sched_to_shared(gen,
4024 isl_pw_multi_aff_copy(iterator_map));
4026 stmt->type = ppcg_kernel_domain;
4027 stmt->u.d.stmt = find_stmt(gen->prog, id);
4028 if (!stmt->u.d.stmt)
4029 goto error;
4031 data.gen = gen;
4032 data.accesses = stmt->u.d.stmt->accesses;
4033 data.iterator_map = iterator_map;
4034 data.sched2shared = sched2shared;
4035 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
4036 build, &transform_index, &data,
4037 &transform_expr, &data);
4039 isl_id_free(id);
4040 isl_pw_multi_aff_free(iterator_map);
4041 isl_pw_multi_aff_free(sched2shared);
4042 isl_ast_expr_free(arg);
4043 isl_ast_expr_free(expr);
4045 id = isl_id_alloc(gen->ctx, NULL, stmt);
4046 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4047 return isl_ast_node_set_annotation(node, id);
4048 error:
4049 isl_id_free(id);
4050 isl_pw_multi_aff_free(iterator_map);
4051 ppcg_kernel_stmt_free(stmt);
4052 isl_pw_multi_aff_free(sched2shared);
4053 return isl_ast_node_free(node);
4056 /* This function is called when code has been generated for the shared
4057 * tile loops. The "schedule" refers only to the original statements.
4059 * We extend the schedule with that part of gen->local_sched that hasn't
4060 * been taken into account yet. This introduces parameters referring
4061 * to thread ids in the schedule, so we add them (with the appropriate
4062 * bounds to the context as well).
4063 * Finally, we set the appropriate unrolling options
4064 * if gen->first_unroll is set.
4066 static __isl_give isl_ast_node *create_domain_leaf(
4067 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
4068 void *user)
4070 struct gpu_gen *gen = (struct gpu_gen *) user;
4071 isl_space *space;
4072 isl_union_map *sched;
4073 isl_ast_node *tree;
4074 isl_set *set;
4075 isl_id_list *iterators;
4076 int n;
4078 schedule = extend_schedule(schedule,
4079 isl_union_map_copy(gen->local_sched),
4080 gen->shared_len, gen->thread_tiled_len);
4082 space = isl_ast_build_get_schedule_space(build);
4083 set = isl_set_universe(space);
4084 set = add_bounded_parameters(set, gen->kernel->n_block,
4085 gen->kernel->block_dim, "t");
4086 build = isl_ast_build_restrict(build, set);
4088 n = gen->thread_tiled_len - gen->shared_len;
4090 if (gen->first_unroll >= 0) {
4091 space = isl_space_set_alloc(gen->ctx, 0, n);
4092 build = set_unroll(build, space, gen->first_unroll);
4094 iterators = generate_names(gen->ctx, n, "c");
4095 build = isl_ast_build_set_iterators(build, iterators);
4096 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
4097 tree = isl_ast_build_ast_from_schedule(build, schedule);
4098 isl_ast_build_free(build);
4100 return tree;
4103 /* This function is called for each statement node in the AST of the code
4104 * for copying to or from shared/private memory.
4105 * Attach a pointer to a ppcg_kernel_stmt representing the copy
4106 * statement to the node.
4107 * The statement name is "read" or "write", depending on whether we are
4108 * reading from global memory or writing to global memory.
4109 * The name of the T space is {shared,private}_<array>.
4111 * The schedule is of the form
4113 * type[A -> T] -> L
4115 * where A refers to a piece of an array and T to the corresponding
4116 * shifted tile. We split this schedule into mappings L -> A and L -> T
4117 * and store the corresponding expressions in stmt->index and stmt->local_index,
4118 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
4120 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
4121 __isl_keep isl_ast_build *build, void *user)
4123 struct gpu_gen *gen = (struct gpu_gen *) user;
4124 struct ppcg_kernel_stmt *stmt;
4125 isl_id *id;
4126 isl_ast_expr *expr;
4127 isl_space *space;
4128 isl_map *access, *local_access, *map;
4129 isl_pw_multi_aff *pma;
4130 const char *type;
4131 int array_index;
4133 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4134 if (!stmt)
4135 return isl_ast_node_free(node);
4137 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
4138 type = isl_map_get_tuple_name(access, isl_dim_in);
4139 stmt->u.c.read = !strcmp(type, "read");
4140 access = isl_map_reverse(access);
4141 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
4142 local_access = isl_map_copy(access);
4144 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
4145 id = isl_map_get_tuple_id(access, isl_dim_out);
4146 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4147 access = isl_map_apply_range(access, map);
4148 pma = isl_pw_multi_aff_from_map(access);
4149 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4150 stmt->u.c.index = expr;
4152 map = isl_map_range_map(isl_map_universe(space));
4153 id = isl_map_get_tuple_id(local_access, isl_dim_out);
4154 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4155 local_access = isl_map_apply_range(local_access, map);
4156 pma = isl_pw_multi_aff_from_map(local_access);
4157 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4158 stmt->u.c.local_index = expr;
4160 stmt->u.c.array = gen->copy_group->array;
4161 array_index = stmt->u.c.array - gen->prog->array;
4162 stmt->u.c.local_array = &gen->kernel->array[array_index];
4163 stmt->type = ppcg_kernel_copy;
4165 id = isl_id_alloc(gen->ctx, NULL, stmt);
4166 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4167 return isl_ast_node_set_annotation(node, id);
4170 /* Given a schedule of the form
4172 * [S -> A] -> L
4174 * (with S the first shared_len dimensions of the computed schedule,
4175 * A the array and L the schedule correponding to the generated loops),
4176 * indicating where to copy the array elements that need to be copied,
4177 * construct code for performing the copying.
4179 * "group" is the array reference group that is being copied
4180 * "type" is either "read" or "write"
4181 * private is set if copying needs to be performed to/from registers
4183 * We first construct a mapping to a shifted tile of the array,
4185 * [S -> A] -> T(S,A) (1)
4187 * If private is set, then we also use this mapping as a schedule
4188 * (which is already thread-specific and will be completely unrolled).
4189 * Otherwise, we wrap/tile the range over the threads.
4190 * The result is
4192 * [S -> A] -> T'(S,A)
4194 * Combined with the given schedule, we have
4196 * [S -> A] -> [L -> T'(S,A)] (2)
4198 * From the shifted tile mapping, we construct a mapping
4200 * [S -> A] -> [A -> T(S,A)]
4202 * and apply it to the schedule (2), obtaining
4204 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
4206 * Note that we can project out S because it is uniquely defined by L.
4208 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
4209 __isl_take isl_map *sched,
4210 const char *type, struct gpu_array_ref_group *group,
4211 __isl_take isl_ast_build *build, int private)
4213 isl_space *space;
4214 isl_ast_node *tree;
4215 isl_map *schedule, *shift, *map;
4216 isl_set *set;
4217 isl_id_list *iterators;
4218 int n;
4220 shift = shift_access(group);
4222 schedule = isl_map_copy(shift);
4223 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
4224 if (!private)
4225 schedule = tile_access_schedule(gen, schedule);
4227 n = isl_map_dim(schedule, isl_dim_out);
4228 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
4229 set = add_bounded_parameters(set, gen->kernel->n_block,
4230 gen->kernel->block_dim, "t");
4232 schedule = isl_map_range_product(sched, schedule);
4234 space = isl_space_domain(isl_map_get_space(shift));
4235 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
4236 map = isl_map_range_product(map, shift);
4238 schedule = isl_map_apply_domain(schedule, map);
4240 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
4242 build = isl_ast_build_restrict(build, set);
4244 gen->copy_group = group;
4246 if (private) {
4247 space = isl_space_range(isl_map_get_space(schedule));
4248 space = isl_space_range(isl_space_unwrap(space));
4249 build = set_unroll(build, space, 0);
4251 iterators = generate_names(gen->ctx, n, "c");
4252 build = isl_ast_build_set_iterators(build, iterators);
4253 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
4254 tree = isl_ast_build_ast_from_schedule(build,
4255 isl_union_map_from_map(schedule));
4256 isl_ast_build_free(build);
4258 return tree;
4261 /* Return code for reading into or writing from shared memory
4262 * the given array reference group.
4264 * If we are performing a read from global memory to shared memory and
4265 * if the array involved is not a scalar, then we copy
4266 * the entire tile to shared memory. This may result in some extra
4267 * elements getting copied, but it should lead to simpler code
4268 * (which means that fewer registers may be needed) and less divergence.
4270 * Otherwise, we only copy the elements that will be read or have been written
4271 * in the kernel.
4274 * The input "sched" is of the form.
4276 * type[S -> A] -> L
4278 * with S the first shared_len dimensions of the computed schedule,
4279 * A the array and L the schedule correponding to the generated loops.
4281 * We first drop "type",
4283 * [S -> A] -> L
4285 * If the above conditions are satisfied, we project out A,
4286 * resulting in
4288 * S -> L
4290 * and then introduce the group tile [S -> T], resulting in
4292 * [S -> T] -> L
4294 static __isl_give isl_ast_node *copy_group_shared_accesses(
4295 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4296 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4298 const char *type;
4299 int read;
4300 isl_union_map *access;
4302 type = isl_map_get_tuple_name(sched, isl_dim_in);
4303 read = !strcmp(type, "read");
4305 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4307 if (read && !gpu_array_is_scalar(group->array)) {
4308 isl_space *space;
4309 isl_map *map;
4311 space = isl_space_domain(isl_map_get_space(sched));
4312 space = isl_space_unwrap(space);
4313 map = isl_map_domain_map(isl_map_universe(space));
4314 sched = isl_map_apply_domain(sched, map);
4316 map = group_tile(group);
4317 map = isl_map_reverse(isl_map_domain_map(map));
4318 sched = isl_map_apply_domain(sched, map);
4321 return copy_access(gen, sched, type, group, build, 0);
4324 /* Return code for reading into or writing from private memory
4325 * the given array reference group.
4327 * Let S be the first shared_len dimensions of the computed schedule,
4328 * D the iteration domains, A the array and L the schedule correponding
4329 * to the generated loops.
4330 * "sched" is of the form
4332 * type[S -> A] -> L
4334 * where type is either "read" or "write".
4335 * We apply the privatization D -> S(t), with t the thread ids,
4336 * to the access relation D -> A to obtain the privatized access relation
4338 * S(t) -> A
4340 * We drop the type from "sched" and intersect with the privatized access
4341 * relation to obtain
4343 * [S(t) -> A] -> L
4345 static __isl_give isl_ast_node *copy_group_private_accesses(
4346 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4347 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4349 const char *type;
4350 int read;
4351 isl_union_map *priv;
4352 isl_union_map *access;
4353 isl_map *access_map;
4355 type = isl_map_get_tuple_name(sched, isl_dim_in);
4356 read = !strcmp(type, "read");
4358 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
4359 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
4360 priv);
4362 access = group_access_relation(group, read, !read);
4363 access = isl_union_map_apply_domain(access, priv);
4364 access_map = isl_map_from_union_map(access);
4366 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4367 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
4369 return copy_access(gen, sched, type, group, build, 1);
4372 /* Return code for reading into or writing from shared or private memory.
4374 * "schedule" is of the form
4376 * type[S -> A] -> L
4378 * with S be the first shared_len dimensions of the computed schedule,
4379 * A the array and L the schedule correponding to the generated loops.
4380 * The array reference group is attached to "type".
4382 static __isl_give isl_ast_node *create_access_leaf(
4383 struct gpu_gen *gen, __isl_take isl_map *schedule,
4384 __isl_take isl_ast_build *build)
4386 struct gpu_array_ref_group *group;
4387 isl_id *id;
4389 id = isl_map_get_tuple_id(schedule, isl_dim_in);
4390 group = isl_id_get_user(id);
4391 isl_id_free(id);
4393 if (group->private_tile)
4394 return copy_group_private_accesses(gen, group, schedule,
4395 build);
4396 else
4397 return copy_group_shared_accesses(gen, group, schedule,
4398 build);
4401 /* Create a domain node representing a synchronization.
4403 static __isl_give isl_ast_node *create_sync_leaf(
4404 struct gpu_gen *gen, __isl_take isl_map *schedule,
4405 __isl_take isl_ast_build *build)
4407 struct ppcg_kernel_stmt *stmt;
4408 isl_id *id;
4409 isl_space *space;
4410 isl_ast_node *node;
4411 isl_ast_expr *expr;
4413 isl_map_free(schedule);
4415 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4416 if (!stmt)
4417 return NULL;
4419 stmt->type = ppcg_kernel_sync;
4421 space = isl_ast_build_get_schedule_space(build);
4422 space = isl_space_from_domain(space);
4423 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
4424 expr = isl_ast_build_call_from_pw_multi_aff(build,
4425 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
4426 node = isl_ast_node_alloc_user(expr);
4427 isl_ast_build_free(build);
4429 id = isl_id_alloc(gen->ctx, NULL, stmt);
4430 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4431 return isl_ast_node_set_annotation(node, id);
4434 /* This function is called during the code generation at the point
4435 * where the schedule domain element is completely determined by
4436 * the generated code. The input schedule contains the original
4437 * statements as well as synchronization and copy "statements".
4438 * The latter are scheduled at different points than any of the original
4439 * statements, so they will only arrive here in isolation.
4441 * If the current schedule only refers to a single statement,
4442 * we check if it is a copy or synchronization statement and
4443 * call the appropriate functions.
4444 * Otherwise, we assume we are dealing with the original statements
4445 * and we call create_domain_leaf.
4447 static __isl_give isl_ast_node *create_kernel_leaf(
4448 __isl_take isl_ast_build *build, void *user)
4450 struct gpu_gen *gen = (struct gpu_gen *) user;
4451 isl_map *map;
4452 isl_union_map *schedule;
4453 const char *name;
4455 schedule = isl_ast_build_get_schedule(build);
4457 if (isl_union_map_n_map(schedule) != 1)
4458 return create_domain_leaf(schedule, build, user);
4460 map = isl_map_from_union_map(schedule);
4461 name = isl_map_get_tuple_name(map, isl_dim_in);
4462 if (!strcmp(name, "read") || !strcmp(name, "write"))
4463 return create_access_leaf(gen, map, build);
4464 if (!strcmp(name, "sync"))
4465 return create_sync_leaf(gen, map, build);
4467 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4470 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4471 * have value 0) and all even schedule dimensions as "unroll".
4473 * That is, the options look as follows
4475 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4476 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4478 * The even positions are used to be able to schedule copying blocks
4479 * and synchronization before or after each level of the shared memory
4480 * tile loops and we want to make sure that code for these is generated
4481 * separately (within each level).
4483 static __isl_give isl_ast_build *set_atomic_and_unroll(
4484 __isl_take isl_ast_build *build,
4485 __isl_take isl_space *space, int sched_len)
4487 isl_ctx *ctx;
4488 isl_map *map;
4489 isl_constraint *c;
4490 isl_union_map *opt;
4491 isl_local_space *ls;
4492 int i, n;
4494 ctx = isl_ast_build_get_ctx(build);
4496 space = isl_space_params(space);
4497 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4498 space = isl_space_from_domain(space);
4499 space = isl_space_add_dims(space, isl_dim_out, 2);
4500 map = isl_map_universe(isl_space_copy(space));
4501 for (i = 0; i < sched_len; i += 2)
4502 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4503 ls = isl_local_space_from_space(isl_map_get_space(map));
4504 c = isl_equality_alloc(ls);
4505 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4506 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4507 c = isl_constraint_set_constant_si(c, 1);
4508 map = isl_map_add_constraint(map, c);
4509 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4510 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4511 opt = isl_union_map_from_map(map);
4513 map = isl_map_universe(space);
4514 ls = isl_local_space_from_space(isl_map_get_space(map));
4515 c = isl_equality_alloc(ls);
4516 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4517 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4518 map = isl_map_add_constraint(map, c);
4519 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4520 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4521 opt = isl_union_map_add_map(opt, map);
4523 build = isl_ast_build_set_options(build, opt);
4525 return build;
4528 /* Return a map that maps a space of dimension gen->shared_len
4529 * to its last dimensions starting at gen->tile_first.
4530 * The range is of dimension
4532 * 2 * (gen->shared_len - gen->tile_first) + 1
4534 * The input dimensions are mapped to the odd dimensions in the output,
4535 * while the even dimensions (except 2*pos) are fixed to 0.
4536 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4537 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4538 * are mapped to the output. The remaining input dimensions are projected
4539 * out and the corresponding output dimensions are fixed to 0.
4541 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4542 __isl_take isl_space *space, int pos, int val)
4544 int i, n;
4545 isl_map *proj;
4547 space = isl_space_set_from_params(space);
4548 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4549 space = isl_space_map_from_set(space);
4550 proj = isl_map_identity(space);
4551 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4552 n = gen->shared_len - gen->tile_first;
4553 for (i = 0; i <= n; ++i) {
4554 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4555 if (i == pos)
4556 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4557 else
4558 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4561 if (pos < 0)
4562 return proj;
4564 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4565 gen->shared_len - (gen->tile_first + pos));
4566 for (i = pos; i < n; ++i)
4567 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4569 return proj;
4572 /* Given the AST context schedule "schedule" and the mapping from
4573 * domains to the shared tile loops "shared_sched", add a schedule
4574 * for a synchronization operation at position "val" of loop level "pos".
4576 * schedule is of the form
4578 * D -> L
4580 * (with D the iteration domains and L the already generated loops),
4581 * while shared_sched is of the form
4583 * D -> S
4585 * We combine them into
4587 * L -> S
4589 * apply a mapping
4591 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4593 * and use the result as a schedule for "sync".
4595 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4596 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4597 __isl_keep isl_union_map *shared_sched, int pos, int val)
4599 isl_space *space;
4600 isl_map *proj, *map;
4602 shared_sched = isl_union_map_copy(shared_sched);
4603 schedule = isl_union_map_copy(schedule);
4605 space = isl_union_map_get_space(shared_sched);
4606 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4607 map = isl_map_from_union_map(schedule);
4609 proj = insert_even(gen, space, pos, val);
4610 map = isl_map_apply_range(map, proj);
4611 map = isl_map_from_range(isl_map_wrap(map));
4612 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4614 res = isl_union_map_add_map(res, map);
4616 return res;
4619 /* Given a set of wrapped references "ref", return the corresponding
4620 * access relations based on the tagged access relations "tagged".
4622 * The elements of "ref" are of the form
4624 * [D -> R]
4626 * with D an iteration domains and R a reference.
4627 * The elements of "tagged" are of the form
4629 * [D -> R] -> A
4631 * with A an array.
4633 * Extend "tagged" to include the iteration domain in the range, i.e.,
4635 * [D -> R] -> [D -> A]
4637 * apply the result to "ref" and then unwrap the resulting set
4638 * to obtain relations of the form
4640 * D -> A
4642 static __isl_give isl_union_map *wrapped_reference_to_access(
4643 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
4645 isl_union_map *tag2access;
4647 tag2access = isl_union_map_copy(tagged);
4648 tag2access = isl_union_map_universe(tag2access);
4649 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
4650 tag2access = isl_union_map_domain_map(tag2access);
4651 tag2access = isl_union_map_range_product(tag2access, tagged);
4653 ref = isl_union_set_coalesce(ref);
4654 ref = isl_union_set_apply(ref, tag2access);
4656 return isl_union_set_unwrap(ref);
4659 /* Given an access relation "access" from "group", remove those reads
4660 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
4661 * communicate data within the same iteration of the last_shared dimension
4662 * of the group.
4664 * If the access is a read then it is necessarily an element of
4666 * live_in union (range flow)
4668 * where live_in and flow may be overapproximations.
4669 * If the access is a write then it is necessarily an element of
4671 * live_out union (domain flow)
4673 * In both cases, the access relation is also a subset of
4674 * the group access relation.
4676 * Essentially, we compute the intersection of "access" with either
4678 * live_in union (range non-local-flow)
4680 * or
4682 * live_out union (domain non-local-flow)
4684 * We first construct a relation "local"
4686 * [[D -> R] -> [D' -> R']]
4688 * of pairs of domain iterations accessing the reference group
4689 * and references in the group that are scheduled to the same iteration
4690 * of the last_shared dimension.
4692 * If this relation does not intersect the dataflow dependences,
4693 * then there is nothing we can possibly remove and we simply
4694 * return the input.
4696 * Otherwise, we remove the "local" dataflow dependences from
4697 * the set of all dataflow dependences.
4698 * Note that if the potential dataflow dependences are an overapproximation
4699 * of the actual dataflow dependences, then the result remains an
4700 * overapproximation of the non-local dataflow dependences.
4701 * Copying to/from global memory is only needed for the references
4702 * in the domain/range of the result or for accesses that are live out/in
4703 * for the entire scop.
4705 * We therefore map the domain/range of the "external" relation
4706 * to the corresponding access relation and take the union with
4707 * the live out/in relation.
4709 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
4710 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
4711 int read)
4713 int empty;
4714 isl_union_map *tagger;
4715 isl_union_set *domain;
4716 isl_space *space;
4717 isl_union_map *sched, *local, *tagged, *external;
4718 isl_union_set *tag_set;
4719 isl_map *proj;
4721 if (isl_union_map_is_empty(access))
4722 return access;
4724 tagged = group_tagged_access_relation(group);
4726 sched = isl_union_map_copy(gen->sched);
4728 space = isl_union_map_get_space(sched);
4729 proj = projection(space, gen->untiled_len, group->last_shared + 1);
4730 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4732 tagger = isl_union_map_copy(gen->prog->scop->tagger);
4733 domain = isl_union_map_domain(isl_union_map_copy(tagged));
4734 tagger = isl_union_map_intersect_range(tagger, domain);
4735 sched = isl_union_map_apply_domain(sched, tagger);
4737 local = isl_union_map_apply_range(sched,
4738 isl_union_map_reverse(isl_union_map_copy(sched)));
4739 local = isl_union_map_intersect(local,
4740 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
4742 empty = isl_union_map_is_empty(local);
4743 if (empty < 0 || empty) {
4744 isl_union_map_free(tagged);
4745 isl_union_map_free(local);
4746 if (empty < 0)
4747 return isl_union_map_free(access);
4748 return access;
4751 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
4752 external = isl_union_map_intersect_params(external,
4753 isl_set_copy(gen->prog->scop->context));
4754 external = isl_union_map_subtract(external, local);
4756 if (read) {
4757 tag_set = isl_union_map_range(external);
4758 external = wrapped_reference_to_access(tag_set, tagged);
4759 external = isl_union_map_union(external,
4760 isl_union_map_copy(gen->prog->scop->live_in));
4761 } else {
4762 tag_set = isl_union_map_domain(external);
4763 external = wrapped_reference_to_access(tag_set, tagged);
4764 external = isl_union_map_union(external,
4765 isl_union_map_copy(gen->prog->scop->live_out));
4768 access = isl_union_map_intersect(access, external);
4770 return access;
4773 /* Given the AST context schedule "schedule" and the mapping from
4774 * domains to the shared tile loops "shared_sched", add a schedule
4775 * for copying an array reference group to/from shared/private memory.
4776 * "read" is set if data should be copied from global memory
4777 * to shared/private memory.
4778 * "k" represents the current group
4779 * "s" is the total number of groups
4781 * We schedule an operation before or after the innermost loop
4782 * of "shared_sched" that affects the tile of the array reference group.
4784 * schedule is of the form
4786 * D -> L
4788 * (with D the iteration domains and L the already generated loops),
4789 * while shared_sched is of the form
4791 * D -> S
4793 * We first compute the access relation for the reference group
4795 * D -> A
4797 * and remove from this access relation those reads or writes
4798 * that only needed to communicate data within the same iteration
4799 * of the last_shared dimension of the group.
4800 * We then combine what is left with shared_sched into
4802 * D -> [S -> A]
4804 * If this results in an empty relation, no copying needs to be performed
4805 * at this point.
4806 * Otherwise, we invert the relation and combine it with "schedule" into
4808 * [S -> A] -> L
4810 * The actual additional piece of the schedule is obtained from combining
4812 * [S -> A] -> S
4814 * with a mapping
4816 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4818 * The position of "val" corresponds to the innermost loop that affects
4819 * the tile and the value indicates where the copying is scheduled
4820 * with respect to the actual kernel code (at value 0).
4821 * Reads are schedule before the code, writes to global memory from
4822 * private memory are scheduled at values 1 to s, writes to global
4823 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4825 * If we are scheduling a read from global memory to shared memory,
4826 * we insert a synchronization before the kernel code (at the innermost
4827 * level).
4828 * If we are scheduling a write to global memory, then we add
4829 * a synchronization after all writes (at value 2 *s + 2).
4830 * However, there is no need for a synchronization after the outermost loop.
4831 * A write to global memory from private memory at the innermost level
4832 * does not require a synchronization, because it is covered by
4833 * the synchronization after the kernel inserted by body_schedule.
4835 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4836 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4837 __isl_keep isl_union_map *shared_sched,
4838 struct gpu_array_ref_group *group, int read, int k, int s)
4840 int n;
4841 int pos, val;
4842 isl_space *space;
4843 isl_union_map *access;
4844 isl_map *map, *proj, *access_map;
4845 isl_id *id;
4847 access = group_access_relation(group, read, !read);
4848 access = remove_local_accesses(gen, group, access, read);
4849 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4850 access);
4852 if (isl_union_map_is_empty(access)) {
4853 isl_union_map_free(access);
4854 return res;
4857 access = isl_union_map_reverse(access);
4858 access = isl_union_map_apply_range(access,
4859 isl_union_map_copy(schedule));
4860 access_map = isl_map_from_union_map(access);
4862 space = isl_space_copy(group->array->space);
4863 space = isl_space_from_range(space);
4864 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4865 map = isl_map_domain_map(isl_map_universe(space));
4867 space = isl_union_map_get_space(schedule);
4868 pos = group->last_shared + 1 - gen->tile_first;
4869 assert(pos >= 0);
4870 if (read)
4871 val = -2 - k;
4872 else if (group->private_tile)
4873 val = 1 + k;
4874 else
4875 val = 1 + s + 1 + k;
4876 proj = insert_even(gen, space, pos, val);
4877 map = isl_map_apply_range(map, proj);
4879 access_map = isl_map_range_product(access_map, map);
4881 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4882 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4884 res = isl_union_map_add_map(res, access_map);
4886 n = gen->shared_len - gen->tile_first;
4887 if (read) {
4888 if (!group->private_tile)
4889 res = add_sync_schedule(gen, res, schedule,
4890 shared_sched, n, -1);
4891 } else {
4892 if (pos == 0)
4893 return res;
4894 if (pos == n && group->private_tile)
4895 return res;
4896 res = add_sync_schedule(gen, res, schedule, shared_sched,
4897 pos, 2 * s + 2);
4900 return res;
4903 /* Return a schedule for the shared tile loops based on the current
4904 * AST context schedule.
4906 * We create a "shared_sched" that maps the domains to the first
4907 * shared_len dimensions of the computed schedule, project out the
4908 * first tile_first dimensions (as these are already covered by
4909 * the host code) and insert "statement-level" dimensions at even
4910 * positions so that we can schedule copy blocks and synchronization
4911 * before/after each level.
4913 * In particular, copy blocks are inserted inside the innermost
4914 * level that affect the tile. For the copying to global memory,
4915 * those from private memory are scheduled before those from shared
4916 * memory such that synchronization can be inserted between the two
4917 * at the innermost level.
4918 * Synchronization is inserted at the innermost level before the
4919 * actual kernel code if there is any copying from global memory
4920 * to shared memory. It is inserted unconditionally at the innermost
4921 * level after the actual kernel code and the copying to global memory
4922 * from private memory (if any). Finally, it is inserted after
4923 * any copying to global memory, except at the outermost level
4924 * and at the innermost level if there is no copying from shared
4925 * memory. The copying from private memory is covered by the unconditional
4926 * synchronization at the innermost level.
4928 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4929 __isl_take isl_union_map *schedule)
4931 isl_space *space;
4932 isl_union_map *res;
4933 isl_union_map *shared_sched;
4934 isl_union_map *sched;
4935 isl_map *proj, *map;
4936 int i, j, k, s;
4938 shared_sched = isl_union_map_copy(gen->tiled_sched);
4939 proj = projection(isl_union_map_get_space(shared_sched),
4940 gen->tiled_len, gen->shared_len);
4941 shared_sched = isl_union_map_apply_range(shared_sched,
4942 isl_union_map_from_map(proj));
4943 space = isl_union_map_get_space(shared_sched);
4944 proj = insert_even(gen, space, -1, 0);
4945 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4946 isl_union_map_from_map(proj));
4948 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4950 s = 0;
4951 for (i = 0; i < gen->prog->n_array; ++i)
4952 s += gen->prog->array[i].n_group;
4954 k = 0;
4955 for (i = 0; i < gen->prog->n_array; ++i) {
4956 struct gpu_array_info *array = &gen->prog->array[i];
4958 for (j = 0; j < array->n_group; ++j) {
4959 struct gpu_array_ref_group *group;
4961 group = array->groups[j];
4962 if (!group->private_tile && !group->shared_tile)
4963 continue;
4964 res = add_group_schedule(gen, res, schedule,
4965 shared_sched, group, 0, k, s);
4966 res = add_group_schedule(gen, res, schedule,
4967 shared_sched, group, 1, k, s);
4968 ++k;
4972 res = add_sync_schedule(gen, res, schedule, shared_sched,
4973 gen->shared_len - gen->tile_first, 1 + s);
4975 isl_union_map_free(shared_sched);
4976 isl_union_map_free(schedule);
4978 return res;
4981 /* Generate code for "kernel" in the given "context".
4983 * We first generate code for the shared tile loops (T1T, T1P and T2)
4984 * in a context that includes the block ids.
4985 * Within each iteration of these loops an additional code generation
4986 * is performed (within create_kernel_leaf) for the rest of the schedule
4987 * in a context that includes the thread ids.
4989 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4990 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4991 __isl_keep isl_multi_pw_aff *grid_size)
4993 isl_space *space;
4994 isl_set *set;
4995 isl_id_list *iterators;
4996 isl_union_map *schedule;
4997 isl_ast_node *tree;
4998 int sched_len;
5000 schedule = isl_ast_build_get_schedule(build);
5002 build = isl_ast_build_copy(build);
5003 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
5004 space = isl_ast_build_get_schedule_space(build);
5005 set = isl_set_universe(isl_space_copy(space));
5006 set = add_bounded_parameters_dynamic(set, grid_size, "b");
5007 build = isl_ast_build_restrict(build, set);
5009 schedule = body_schedule(gen, schedule);
5011 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
5013 build = set_atomic_and_unroll(build, space, sched_len);
5014 iterators = generate_names(gen->ctx, sched_len, "g");
5015 build = isl_ast_build_set_iterators(build, iterators);
5016 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
5017 tree = isl_ast_build_ast_from_schedule(build, schedule);
5018 isl_ast_build_free(build);
5020 return tree;
5023 /* Attach "id" to the given node.
5025 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
5026 __isl_keep isl_ast_build *build, void *user)
5028 isl_id *id = user;
5030 node = isl_ast_node_set_annotation(node, id);
5032 return node;
5035 /* Construct an AST node for performing a kernel launch and attach
5036 * the information about the kernel to that node.
5038 * The kernel AST has been constructed in the context of the range
5039 * of "schedule". In particular, the grid size has been computed
5040 * in the context. We therefore still need to make sure that these
5041 * constraints are expressed in the code. We do this by creating a schedule
5043 * kernel[] -> [S -> []]
5045 * where S is the schedule domain, i.e., the range of "schedule".
5046 * The AST generation will then create a single call surrounded by
5047 * all the condition in "S" that have not been expressed yet.
5049 * The kernel information is attached to this node in attach_id.
5051 static __isl_give isl_ast_node *construct_launch(
5052 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
5053 __isl_take struct ppcg_kernel *kernel)
5055 isl_id *id;
5056 isl_ctx *ctx;
5057 isl_union_set *domain;
5058 isl_set *set;
5059 isl_map *map;
5060 isl_ast_node *node;
5062 ctx = isl_ast_build_get_ctx(build);
5064 id = isl_id_alloc(ctx, NULL, kernel);
5065 id = isl_id_set_free_user(id, &ppcg_kernel_free);
5067 domain = isl_union_map_range(schedule);
5068 set = isl_set_from_union_set(domain);
5069 map = isl_map_from_domain(set);
5070 map = isl_map_from_range(isl_map_wrap(map));
5071 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
5072 schedule = isl_union_map_from_map(map);
5074 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
5075 node = isl_ast_build_ast_from_schedule(build, schedule);
5076 isl_ast_build_free(build);
5078 return node;
5081 /* This function is called for each leaf in the AST of the host code.
5082 * We first specialize the schedule to the site of the leaf, compute
5083 * the size of shared memory and then construct the body of the host code
5084 * and the associated kernel.
5086 * The necessary information for printing the kernel launch is
5087 * stored in a struct ppcg_kernel and attached to the leaf node
5088 * created to represent the launch.
5090 static __isl_give isl_ast_node *create_host_leaf(
5091 __isl_take isl_ast_build *build, void *user)
5093 struct gpu_gen *gen = (struct gpu_gen *) user;
5094 isl_id *id;
5095 isl_ast_node *node;
5096 struct ppcg_kernel *kernel;
5097 isl_set *host_domain;
5098 isl_union_map *schedule;
5099 isl_union_map *local_sched;
5100 isl_union_map *access;
5101 isl_union_set *domain;
5102 int i;
5104 schedule = isl_ast_build_get_schedule(build);
5106 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
5107 read_sizes(gen);
5109 domain = isl_union_map_domain(isl_union_map_copy(schedule));
5111 local_sched = isl_union_map_copy(gen->sched);
5112 local_sched = isl_union_map_intersect_domain(local_sched, domain);
5113 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
5114 isl_union_map_copy(gen->prog->may_write));
5115 access = isl_union_map_apply_domain(access,
5116 isl_union_map_copy(local_sched));
5118 gen->tiled_sched = tile_schedule(gen, local_sched);
5119 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
5120 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
5122 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
5123 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
5124 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
5126 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
5127 if (!kernel)
5128 goto error;
5130 kernel->id = gen->kernel_id++;
5131 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
5132 kernel->grid_size = extract_grid_size(gen, kernel);
5133 extract_block_size(gen, kernel);
5134 kernel->arrays = isl_union_map_range(access);
5135 kernel->arrays = isl_union_set_apply(kernel->arrays,
5136 isl_union_map_copy(gen->prog->to_outer));
5137 kernel->space = isl_ast_build_get_schedule_space(build);
5139 gen->private_access = NULL;
5140 compute_shared_sched(gen);
5141 gen->privatization = compute_privatization(gen);
5142 check_scalar_live_ranges(gen);
5143 if (group_references(gen) < 0)
5144 schedule = isl_union_map_free(schedule);
5145 compute_private_access(gen);
5146 host_domain = isl_set_from_union_set(isl_union_map_range(
5147 isl_union_map_copy(schedule)));
5148 localize_bounds(gen, kernel, host_domain);
5150 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
5151 check_shared_memory_bound(gen);
5152 compute_group_tilings(gen);
5154 kernel->tree = generate_kernel(gen, build, host_domain,
5155 kernel->grid_size);
5156 create_kernel_vars(gen, kernel);
5158 free_local_array_info(gen);
5159 isl_map_free(gen->privatization);
5160 isl_union_map_free(gen->private_access);
5161 isl_union_map_free(gen->local_sched);
5162 isl_union_map_free(gen->tiled_sched);
5163 isl_union_map_free(gen->shared_sched);
5164 isl_union_map_free(gen->shared_proj);
5165 isl_set_free(host_domain);
5166 free(gen->tile_size);
5168 node = construct_launch(build, schedule, kernel);
5170 return node;
5171 error:
5172 isl_union_map_free(schedule);
5173 return NULL;
5176 /* Use isl to generate code for the outer gen->tile_first loops
5177 * of the global schedule in gen->sched, resulting in the host code.
5178 * Within each iteration of this partial schedule, i.e., for each kernel
5179 * launch, create_host_leaf takes care of generating the kernel code.
5181 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
5183 isl_ast_build *build;
5184 isl_ast_node *tree;
5185 isl_union_map *sched;
5186 isl_map *proj;
5187 isl_id_list *iterators;
5189 sched = isl_union_map_copy(gen->sched);
5190 proj = projection(isl_union_map_get_space(sched),
5191 gen->untiled_len, gen->tile_first);
5192 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
5194 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
5195 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
5196 iterators = generate_names(gen->ctx, gen->tile_first, "h");
5197 build = isl_ast_build_set_iterators(build, iterators);
5198 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
5199 tree = isl_ast_build_ast_from_schedule(build, sched);
5200 isl_ast_build_free(build);
5202 return tree;
5205 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
5207 if (!str)
5208 return NULL;
5209 return isl_union_map_read_from_str(ctx, str);
5212 /* Information about the outermost tilable bands in the forest of bands.
5214 * tile_len and n_parallel are only sets on band_info structures
5215 * that correspond to outermost bands. For other bands (in particular,
5216 * ancestors of the outermost bands), n_parallal is set to 0.
5218 * prefix is the (padded) schedule leading up to the outermost tilable bands.
5220 * tile_first is the number of schedule dimensions in prefix.
5222 * suffix is the schedule of the outermost tilable bands and their descendants.
5224 struct band_info {
5225 struct gpu_gen *gen;
5226 int tile_first;
5227 int tile_len;
5228 int n_parallel;
5229 isl_union_map *prefix;
5230 isl_union_map *suffix;
5233 /* Set tile_len and n_parallel of the statement to that of
5234 * their outermost band, recorded in the band_info.
5236 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
5238 struct band_info *info = user;
5239 struct gpu_stmt *stmt;
5240 isl_id *id;
5242 id = isl_map_get_tuple_id(map, isl_dim_in);
5243 stmt = find_stmt(info->gen->prog, id);
5244 isl_id_free(id);
5246 stmt->tile_len = info->tile_len;
5247 stmt->n_parallel = info->n_parallel;
5249 isl_map_free(map);
5251 return 0;
5254 static void list_select_outer_band(struct gpu_gen *gen,
5255 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
5257 /* Check if this band has any parallel loops. If so, take it as
5258 * the outermost tilable band. If not, continue looking for the
5259 * outermost tilable band in the children of the current band.
5261 static void band_select_outer_band(struct gpu_gen *gen,
5262 __isl_take isl_band *band, int pos, struct band_info *info)
5264 int n = isl_band_n_member(band);
5265 int n_parallel;
5267 for (n_parallel = 0; n_parallel < n; ++n_parallel)
5268 if (!isl_band_member_is_coincident(band, n_parallel))
5269 break;
5271 info->n_parallel = n_parallel;
5272 if (n_parallel) {
5273 gen->any_parallelism = 1;
5274 info->gen = gen;
5275 info->tile_first = pos;
5276 info->tile_len = n;
5277 info->prefix = isl_band_get_prefix_schedule(band);
5278 info->suffix = isl_union_map_flat_range_product(
5279 isl_band_get_partial_schedule(band),
5280 isl_band_get_suffix_schedule(band));
5281 isl_union_map_foreach_map(info->prefix,
5282 &set_stmt_tile_len, info);
5283 } else if (isl_band_has_children(band)) {
5284 isl_band_list *children;
5285 children = isl_band_get_children(band);
5286 list_select_outer_band(gen, children, pos + n, info);
5287 } else {
5288 info->gen = gen;
5289 info->tile_first = pos + n;
5290 info->tile_len = 0;
5291 info->prefix = isl_union_map_flat_range_product(
5292 isl_band_get_prefix_schedule(band),
5293 isl_band_get_partial_schedule(band));
5294 info->suffix = isl_band_get_suffix_schedule(band);
5295 isl_union_map_foreach_map(info->prefix,
5296 &set_stmt_tile_len, info);
5299 isl_band_free(band);
5302 /* Comparison function that returns a non-zero value for band_infos
5303 * with different tile_len fields or different n_parallel fields.
5305 static int cmp_band(const void *p1, const void *p2)
5307 const struct band_info *info1 = p1;
5308 const struct band_info *info2 = p2;
5310 if (info1->tile_len != info2->tile_len)
5311 return info1->tile_len - info2->tile_len;
5313 return info1->n_parallel - info2->n_parallel;
5316 /* Extend "umap" with coordinates with fixed value "val"
5317 * to a total length of "dst_len", assuming the original dimension is "src_len".
5319 static __isl_give isl_union_map *extend_range(
5320 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
5322 isl_space *dim;
5323 isl_map *map;
5324 int i;
5326 dim = isl_union_map_get_space(umap);
5327 map = isl_map_reverse(projection(dim, dst_len, src_len));
5328 for (i = src_len; i < dst_len; ++i)
5329 map = isl_map_fix_si(map, isl_dim_out, i, val);
5331 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
5333 return umap;
5336 /* Group bands with the same values for tile_len and n_parallel.
5337 * The prefix schedule is then extended with a fixed coordinate that
5338 * is different for each such group.
5339 * Note that the actual values for this coordinate are not important.
5340 * The bands have already been effectively separated at a higher level
5341 * or they are independent and may be executed in parallel.
5342 * The list of band_info has been sorted before this functions is called.
5344 static void separate_bands(struct band_info *info, int n)
5346 int i;
5347 int j = 0;
5349 for (i = 0; i < n; ++i) {
5350 int l = info[i].tile_first;
5352 if (i &&
5353 (info[i].tile_len != info[i - 1].tile_len ||
5354 info[i].n_parallel != info[i - 1].n_parallel))
5355 j++;
5357 info[i].prefix = extend_range(info[i].prefix,
5358 l, l + 1, j);
5359 info[i].tile_first = l + 1;
5363 /* Select the outermost bands in the elements of the list, align
5364 * their prefix schedules, separate bands with different values
5365 * for tile_len and/or n_parallel and then combine the resulting
5366 * prefix and suffix schedules into a single pair of prefix and
5367 * suffix schedules for the entire list.
5369 static void list_select_outer_band(struct gpu_gen *gen,
5370 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
5372 isl_band *band;
5373 int i;
5374 int n = isl_band_list_n_band(list);
5375 isl_ctx *ctx = isl_band_list_get_ctx(list);
5376 struct band_info *info;
5377 int max_tile_first;
5378 isl_union_map *prefix;
5379 isl_union_map *suffix;
5381 assert(n >= 1);
5382 info = isl_calloc_array(ctx, struct band_info, n);
5383 assert(info);
5385 max_tile_first = 0;
5386 for (i = 0; i < n; ++i) {
5387 band = isl_band_list_get_band(list, i);
5388 band_select_outer_band(gen, band, pos, &info[i]);
5389 if (info[i].tile_first > max_tile_first)
5390 max_tile_first = info[i].tile_first;
5393 for (i = 0; i < n; ++i) {
5394 if (info[i].tile_first == max_tile_first)
5395 continue;
5396 info[i].prefix = extend_range(info[i].prefix,
5397 info[i].tile_first, max_tile_first, 0);
5398 info[i].tile_first = max_tile_first;
5401 qsort(info, n, sizeof(struct band_info), &cmp_band);
5403 for (i = 0; i < n - 1; ++i)
5404 if (info[i].tile_len != info[i + 1].tile_len ||
5405 info[i].n_parallel != info[i + 1].n_parallel)
5406 break;
5408 if (i < n -1)
5409 separate_bands(info, n);
5411 prefix = info[0].prefix;
5412 suffix = info[0].suffix;
5414 for (i = 1; i < n; ++i) {
5415 prefix = isl_union_map_union(prefix, info[i].prefix);
5416 suffix = isl_union_map_union(suffix, info[i].suffix);
5419 list_info->tile_first = info[0].tile_first;
5420 list_info->tile_len = -1;
5421 list_info->prefix = prefix;
5422 list_info->suffix = suffix;
5424 isl_band_list_free(list);
5425 free(info);
5428 /* Select the outermost tilable band that (by construction)
5429 * has at least one parallel loop.
5430 * The starting position of the aligned band is stored in the pair
5431 * gen->tile_first.
5432 * The sizes and number of parallel loops may be different in different
5433 * parts of the band forest and are therefore stored in the gpu_stmts.
5435 * Return the complete schedule, with the tilable bands aligned
5436 * at gen->tile_first and padded with zero, if needed.
5438 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
5439 __isl_keep isl_schedule *schedule)
5441 isl_band_list *list;
5442 struct band_info info;
5444 gen->n_parallel = 0;
5445 gen->tile_len = -1;
5447 list = isl_schedule_get_band_forest(schedule);
5449 if (isl_band_list_n_band(list) == 0) {
5450 isl_band_list_free(list);
5451 return isl_schedule_get_map(schedule);
5454 list_select_outer_band(gen, list, 0, &info);
5456 gen->tile_first = info.tile_first;
5457 info.suffix = align_range(info.suffix);
5459 return isl_union_map_flat_range_product(info.prefix, info.suffix);
5462 /* Set gen->untiled_len to the number of scheduling dimensions
5463 * for the schedule of the first domain.
5464 * We assume here that this number is the same for all domains.
5466 static int set_untiled_len(__isl_take isl_map *map, void *user)
5468 unsigned *untiled_len = user;
5470 *untiled_len = isl_map_dim(map, isl_dim_out);
5472 isl_map_free(map);
5473 return -1;
5476 /* Compute an appropriate schedule based on the accesses in
5477 * gen->read and gen->write.
5479 * We use the dependences in gen->prog->scop to compute
5480 * a schedule that has a parallel loop in each tilable band.
5481 * Finally, we select the outermost tilable band.
5483 * If live range reordering is allowed, then we need to make sure
5484 * that live ranges on arrays are not run in parallel since doing
5485 * so would require array expansion. We therefore add the array
5486 * order dependences to the coincidence dependences. Non-zero array
5487 * order dependences will then prevent a schedule dimension from being
5488 * considered parallel.
5489 * Live ranges derived from scalars are allowed to be run in parallel
5490 * since we force the scalars to be mapped to private memory in
5491 * check_scalar_live_ranges.
5492 * If live range reordering is allowed, then the false dependences
5493 * are not added to the validity constraints as that would prevent
5494 * reordering. Instead, the external false dependences that enforce that reads
5495 * from potentially live-in data precede any later write and
5496 * that writes of potentially live-out data follow any other earlier write
5497 * are added to the validity and the coincidence constraints.
5498 * The false dependences are still added to the proximity constraints
5499 * for consistency with the case where live range reordering is not allowed.
5500 * The coincidence constraints then consist of flow dependences,
5501 * exernal false dependences and array order dependences.
5502 * The independences can be filtered out from the first two sets.
5503 * They have already been filtered out from the array order dependences
5504 * on a per array basis in collect_order_dependences.
5505 * There is no need for a per array handling of the other two sets
5506 * as there should be no flow or external false dependence on local
5507 * variables that can be filtered out.
5509 static void compute_schedule(struct gpu_gen *gen)
5511 isl_union_set *domain;
5512 isl_union_map *dep_raw, *dep;
5513 isl_union_map *validity, *proximity, *coincidence;
5514 isl_union_map *sched;
5515 isl_schedule_constraints *sc;
5516 isl_schedule *schedule;
5518 domain = isl_union_set_copy(gen->prog->scop->domain);
5519 domain = isl_union_set_intersect_params(domain,
5520 isl_set_copy(gen->prog->scop->context));
5521 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
5522 if (gen->options->live_range_reordering) {
5523 sc = isl_schedule_constraints_set_conditional_validity(sc,
5524 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
5525 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
5526 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
5527 validity = isl_union_map_copy(proximity);
5528 validity = isl_union_map_union(validity,
5529 isl_union_map_copy(gen->prog->scop->dep_external));
5530 proximity = isl_union_map_union(proximity,
5531 isl_union_map_copy(gen->prog->scop->dep_false));
5532 coincidence = isl_union_map_copy(validity);
5533 coincidence = isl_union_map_subtract(coincidence,
5534 isl_union_map_copy(gen->prog->scop->independence));
5535 coincidence = isl_union_map_union(coincidence,
5536 isl_union_map_copy(gen->prog->array_order));
5537 } else {
5538 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
5539 dep = isl_union_map_copy(gen->prog->scop->dep_false);
5540 dep = isl_union_map_union(dep, dep_raw);
5541 dep = isl_union_map_coalesce(dep);
5542 proximity = isl_union_map_copy(dep);
5543 coincidence = isl_union_map_copy(dep);
5544 validity = dep;
5546 sc = isl_schedule_constraints_set_validity(sc, validity);
5547 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
5548 sc = isl_schedule_constraints_set_proximity(sc, proximity);
5550 if (gen->options->debug->dump_schedule_constraints)
5551 isl_schedule_constraints_dump(sc);
5552 schedule = isl_schedule_constraints_compute_schedule(sc);
5553 if (gen->options->debug->dump_schedule)
5554 isl_schedule_dump(schedule);
5556 sched = select_outer_tilable_band(gen, schedule);
5558 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
5559 sched = isl_union_map_intersect_domain(sched, domain);
5560 gen->sched = sched;
5562 isl_schedule_free(schedule);
5565 /* Compute the sets of outer array elements that need to be copied in and out.
5567 * In particular, for each array that is possibly written anywhere in
5568 * gen->prog and that is visible outside the corresponding scop,
5569 * we copy out its entire extent.
5571 * Any array elements that is read without first being written needs
5572 * to be copied in. Furthermore, if there are any array elements that
5573 * are copied out, but that may not be written inside gen->prog, then
5574 * they also need to be copied in to ensure that the value after execution
5575 * is the same as the value before execution.
5576 * In case the array elements are structures, we need to take into
5577 * account that all members of the structures need to be written
5578 * by gen->prog before we can avoid copying the data structure in.
5580 * While computing the set of array elements that are copied out but
5581 * not necessarily written, we intersect both sets with the context.
5582 * This helps in those cases where the arrays are declared with a fixed size,
5583 * while the accesses are parametric and the context assigns a fixed value
5584 * to the parameters.
5586 * If an element from a local array is read without first being written,
5587 * then there is no point in copying it in since it cannot have been
5588 * written prior to the scop. Warn about the uninitialized read instead.
5590 static void compute_copy_in_and_out(struct gpu_gen *gen)
5592 int i;
5593 isl_union_set *local;
5594 isl_union_set *may_write, *must_write;
5595 isl_union_set *copy_in, *copy_out;
5596 isl_union_set *not_written;
5597 isl_union_map *uninitialized;
5598 isl_union_map *local_uninitialized;
5600 must_write = isl_union_map_range(
5601 isl_union_map_copy(gen->prog->must_write));
5602 must_write = isl_union_set_intersect_params(must_write,
5603 isl_set_copy(gen->prog->context));
5604 may_write = isl_union_map_range(
5605 isl_union_map_copy(gen->prog->may_write));
5606 may_write = isl_union_set_intersect_params(may_write,
5607 isl_set_copy(gen->prog->context));
5608 may_write = isl_union_set_universe(may_write);
5609 may_write = isl_union_set_apply(may_write,
5610 isl_union_map_copy(gen->prog->to_outer));
5611 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
5612 local = isl_union_set_copy(copy_out);
5614 for (i = 0; i < gen->prog->n_array; ++i) {
5615 isl_space *space;
5616 isl_set *write_i;
5617 int empty;
5619 space = isl_space_copy(gen->prog->array[i].space);
5621 if (gen->prog->array[i].local) {
5622 isl_set *set;
5624 set = isl_set_universe(space);
5625 local = isl_union_set_add_set(local, set);
5626 continue;
5629 write_i = isl_union_set_extract_set(may_write, space);
5630 empty = isl_set_fast_is_empty(write_i);
5631 isl_set_free(write_i);
5632 if (empty)
5633 continue;
5635 write_i = isl_set_copy(gen->prog->array[i].extent);
5636 copy_out = isl_union_set_add_set(copy_out, write_i);
5638 isl_union_set_free(may_write);
5640 copy_out = isl_union_set_intersect_params(copy_out,
5641 isl_set_copy(gen->prog->context));
5643 gen->prog->copy_out = isl_union_set_copy(copy_out);
5645 copy_out = isl_union_set_apply(copy_out,
5646 isl_union_map_copy(gen->prog->to_inner));
5647 not_written = isl_union_set_subtract(copy_out, must_write);
5649 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
5650 local_uninitialized = isl_union_map_copy(uninitialized);
5652 local = isl_union_set_apply(local,
5653 isl_union_map_copy(gen->prog->to_inner));
5654 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5655 local);
5656 if (!isl_union_map_is_empty(local_uninitialized)) {
5657 fprintf(stderr,
5658 "possibly uninitialized reads (not copied in):\n");
5659 isl_union_map_dump(local_uninitialized);
5661 uninitialized = isl_union_map_subtract(uninitialized,
5662 local_uninitialized);
5663 copy_in = isl_union_map_range(uninitialized);
5664 copy_in = isl_union_set_union(copy_in, not_written);
5665 copy_in = isl_union_set_apply(copy_in,
5666 isl_union_map_copy(gen->prog->to_outer));
5668 gen->prog->copy_in = copy_in;
5671 /* Internal data structure for extract_access.
5672 * "next_access" points to the end of a linked list that is extended
5673 * by extract_access.
5674 * "single_expression" is set if the access expressions belong to
5675 * an expression statement (i.e., a statement without internal control).
5677 struct ppcg_extract_access_data {
5678 struct gpu_stmt_access **next_access;
5679 int single_expression;
5682 /* Extract a gpu_stmt_access from "expr", append it to the list
5683 * that ends in *data->next_access and update the end of the list.
5684 * If the access expression performs a write, then it is considered
5685 * exact only if it appears in a single expression statement and
5686 * if its may access relation is equal to its must access relation.
5688 static int extract_access(__isl_keep pet_expr *expr, void *user)
5690 struct ppcg_extract_access_data *data = user;
5691 isl_map *may;
5692 struct gpu_stmt_access *access;
5693 isl_ctx *ctx;
5695 may = pet_expr_access_get_may_access(expr);
5696 ctx = isl_map_get_ctx(may);
5697 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5698 assert(access);
5699 access->next = NULL;
5700 access->read = pet_expr_access_is_read(expr);
5701 access->write = pet_expr_access_is_write(expr);
5702 access->access = may;
5703 access->tagged_access = pet_expr_access_get_tagged_may_access(expr);
5704 if (!access->write) {
5705 access->exact_write = 1;
5706 } else if (!data->single_expression) {
5707 access->exact_write = 0;
5708 } else {
5709 isl_map *must;
5710 must = pet_expr_access_get_must_access(expr);
5711 access->exact_write = isl_map_is_equal(must, access->access);
5712 isl_map_free(must);
5714 access->ref_id = pet_expr_access_get_ref_id(expr);
5715 access->group = -1;
5717 *data->next_access = access;
5718 data->next_access = &(*data->next_access)->next;
5720 return 0;
5723 /* Construct a linked list of gpu_stmt_access objects,
5724 * one for each access expression in the statement body.
5726 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
5728 struct ppcg_extract_access_data data;
5730 stmt->accesses = NULL;
5731 data.next_access = &stmt->accesses;
5732 data.single_expression =
5733 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5734 pet_tree_foreach_access_expr(stmt->stmt->body, &extract_access, &data);
5737 /* Return an array of gpu_stmt representing the statements in "scop".
5739 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5740 __isl_keep isl_set *context)
5742 int i;
5743 struct gpu_stmt *stmts;
5745 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
5746 if (!stmts)
5747 return NULL;
5749 for (i = 0; i < scop->n_stmt; ++i) {
5750 struct gpu_stmt *s = &stmts[i];
5752 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
5753 s->stmt = scop->stmts[i];
5754 pet_stmt_extract_accesses(s);
5757 return stmts;
5760 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5762 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5764 struct gpu_gen *gen = user;
5766 return gen->print(p, gen->prog, gen->tree, &gen->types,
5767 gen->print_user);
5770 /* Generate CUDA code for "scop" and print it to "p".
5771 * After generating an AST for the transformed scop as explained below,
5772 * we call "gen->print" to print the AST in the desired output format
5773 * to "p".
5775 * If it turns out that it does not make sense to generate GPU code,
5776 * then we generate CPU code instead.
5778 * The GPU code is generated in a context where at least one
5779 * statement instance is executed. The corresponding guard (if any) is printed
5780 * around the entire generated GPU code, except for the declaration
5781 * of the arrays that are visible outside of the scop and that therefore
5782 * cannot be declared inside the body of any possible guard.
5784 * We first compute a schedule that respects the dependences
5785 * of the original program and select the outermost band
5786 * of tilable dimensions that has at least one parallel loop.
5787 * We then have three blocks of dimensions
5789 * H B G
5791 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5792 * in
5794 * H T P G
5796 * For each iteration of the T loop and for each array, we compute
5797 * the array elements accessed by that iteration, construct a rectangular
5798 * box around it and shift it to the origin. The result is used
5799 * as shared memory for the array.
5801 * We then split off at most 2 parallel loops from the T loops and
5802 * at most 3 parallel loops from the P loops
5804 * H T1 T2 P1 P2 G
5806 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5807 * according to "grid"/"block" sizes.
5809 * H T1T T1P T2 P1T P1P P2 G
5811 * Finally, the T1P and P1P iterators are equated to the block and
5812 * thread dimensions respectively and so are effectively removed.
5813 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5814 * are run on the GPU.
5816 * Code is generated in three stages. We first generate code for the
5817 * host (the H loops), with iterators h%d. Then, for each leaf node
5818 * of the resulting AST, we generate code for the shared loops (up to
5819 * and including T2), with iterators g%d and after equating the H loops
5820 * to h%d parameters and the T1P loops to the block dimensions.
5821 * Finally, we generate code for the remaining loops in a similar fashion.
5823 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5824 struct gpu_gen *gen, struct ppcg_scop *scop,
5825 struct ppcg_options *options)
5827 struct gpu_prog *prog;
5828 isl_ctx *ctx;
5829 isl_set *context, *guard;
5831 if (!scop)
5832 return isl_printer_free(p);
5834 ctx = isl_printer_get_ctx(p);
5835 prog = gpu_prog_alloc(ctx, scop);
5836 if (!prog)
5837 return isl_printer_free(p);
5839 context = isl_set_copy(prog->context);
5840 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5841 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5843 gen->prog = prog;
5844 gen->any_parallelism = 0;
5845 compute_schedule(gen);
5847 if (!gen->any_parallelism) {
5848 isl_set_free(context);
5849 isl_set_free(guard);
5850 p = print_cpu(p, scop, options);
5851 } else {
5852 compute_copy_in_and_out(gen);
5853 gen->tree = generate_host_code(gen);
5854 p = ppcg_print_exposed_declarations(p, prog->scop);
5855 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5856 isl_ast_node_free(gen->tree);
5859 isl_union_map_free(gen->sched);
5861 gpu_prog_free(prog);
5863 return p;
5866 /* Wrapper around generate for use as a ppcg_transform callback.
5868 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5869 struct ppcg_scop *scop, void *user)
5871 struct gpu_gen *gen = user;
5873 return generate(p, gen, scop, gen->options);
5876 /* Transform the code in the file called "input" by replacing
5877 * all scops by corresponding GPU code and write the results to "out".
5879 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5880 struct ppcg_options *options,
5881 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5882 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5883 struct gpu_types *types, void *user), void *user)
5885 struct gpu_gen gen;
5886 int r;
5887 int i;
5889 gen.ctx = ctx;
5890 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5891 gen.options = options;
5892 gen.kernel_id = 0;
5893 gen.print = print;
5894 gen.print_user = user;
5895 gen.types.n = 0;
5896 gen.types.name = NULL;
5898 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5900 isl_union_map_free(gen.sizes);
5901 for (i = 0; i < gen.types.n; ++i)
5902 free(gen.types.name[i]);
5903 free(gen.types.name);
5905 return r;
5908 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5910 struct gpu_prog *prog;
5912 if (!scop)
5913 return NULL;
5915 prog = isl_calloc_type(ctx, struct gpu_prog);
5916 assert(prog);
5918 prog->ctx = ctx;
5919 prog->scop = scop;
5920 prog->context = isl_set_copy(scop->context);
5921 prog->n_stmts = scop->n_stmt;
5922 prog->stmts = extract_stmts(ctx, scop, prog->context);
5923 prog->read = isl_union_map_copy(scop->reads);
5924 prog->may_write = isl_union_map_copy(scop->may_writes);
5925 prog->must_write = isl_union_map_copy(scop->must_writes);
5926 prog->to_inner = compute_to_inner(scop);
5927 prog->to_outer = isl_union_map_copy(prog->to_inner);
5928 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5930 if (!prog->stmts)
5931 return gpu_prog_free(prog);
5933 if (collect_array_info(prog) < 0)
5934 return gpu_prog_free(prog);
5936 return prog;
5939 void *gpu_prog_free(struct gpu_prog *prog)
5941 if (!prog)
5942 return NULL;
5943 free_array_info(prog);
5944 free_stmts(prog->stmts, prog->n_stmts);
5945 isl_union_map_free(prog->to_outer);
5946 isl_union_map_free(prog->to_inner);
5947 isl_union_set_free(prog->copy_in);
5948 isl_union_set_free(prog->copy_out);
5949 isl_union_map_free(prog->read);
5950 isl_union_map_free(prog->may_write);
5951 isl_union_map_free(prog->must_write);
5952 isl_union_map_free(prog->array_order);
5953 isl_set_free(prog->context);
5954 free(prog);
5955 return NULL;