gpu: properly handle dereferencing of pointers to struct
[ppcg.git] / gpu.c
blob7f849ac7d61574d7b42bf9e60ff9e1c0ebf613bb
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 and shift 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 * Let D represent the initial shared_len dimensions of the computed schedule.
38 * The spaces of "lb" and "shift" are of the form
40 * D -> [b]
42 struct gpu_array_bound {
43 isl_val *size;
44 isl_aff *lb;
46 isl_val *stride;
47 isl_aff *shift;
50 /* A tile of an array.
52 * n is the dimension of the array.
53 * bound is an array of size "n" representing the lower bound
54 * and size for each index.
56 * tiling maps a tile in the global array to the corresponding
57 * shared/private memory tile and is of the form
59 * { [D[i] -> A[a]] -> T[(a + shift(i))/stride - lb(i)] }
61 * where D represents the initial shared_len dimensions
62 * of the computed schedule.
64 struct gpu_array_tile {
65 int n;
66 struct gpu_array_bound *bound;
67 isl_multi_aff *tiling;
70 struct gpu_array_info;
72 /* A group of array references in a kernel that should be handled together.
73 * If private_tile is not NULL, then it is mapped to registers.
74 * Otherwise, if shared_tile is not NULL, it is mapped to shared memory.
75 * Otherwise, it is accessed from global memory.
77 struct gpu_array_ref_group {
78 /* The references in this group access this array. */
79 struct gpu_array_info *array;
80 /* Position of this group in the list of reference groups of array. */
81 int nr;
83 /* The following fields are use during the construction of the groups.
84 * access is the combined access relation relative to the shared
85 * memory tiling. In particular, the domain of the map corresponds
86 * to the first shared_len dimensions of the computed schedule.
87 * write is set if any access in the group is a write.
88 * exact_write is set if all writes are definite writes.
89 * slice is set if there is at least one access in the group
90 * that refers to more than one element
92 isl_map *access;
93 int write;
94 int exact_write;
95 int slice;
97 /* The shared memory tile, NULL if none. */
98 struct gpu_array_tile *shared_tile;
100 /* The private memory tile, NULL if none. */
101 struct gpu_array_tile *private_tile;
103 /* References in this group; point to elements of a linked list. */
104 int n_ref;
105 struct gpu_stmt_access **refs;
107 /* Last shared memory tile dimension that affects tile of this group. */
108 int last_shared;
111 struct gpu_gen {
112 isl_ctx *ctx;
113 struct ppcg_options *options;
115 /* Callback for printing of AST in appropriate format. */
116 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
117 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
118 struct gpu_types *types, void *user);
119 void *print_user;
121 struct gpu_prog *prog;
122 /* The generated AST. */
123 isl_ast_node *tree;
125 /* The sequence of types for which a definition has been printed. */
126 struct gpu_types types;
128 /* User specified tile, grid and block sizes for each kernel */
129 isl_union_map *sizes;
131 /* Effectively used tile, grid and block sizes for each kernel */
132 isl_union_map *used_sizes;
134 /* Identifier of current kernel. */
135 int kernel_id;
136 /* Pointer to the current kernel. */
137 struct ppcg_kernel *kernel;
138 /* Does the computed schedule exhibit any parallelism? */
139 int any_parallelism;
141 /* First tile dimension. */
142 int tile_first;
143 /* Number of tile dimensions. */
144 int tile_len;
145 /* Number of initial parallel loops among tile dimensions. */
146 int n_parallel;
148 /* Number of dimensions determining shared memory. */
149 int shared_len;
151 /* Number of rows in the untiled schedule. */
152 int untiled_len;
153 /* Number of rows in the tiled schedule. */
154 int tiled_len;
155 /* Number of rows in schedule after tiling/wrapping over threads. */
156 int thread_tiled_len;
158 /* Global untiled schedule. */
159 isl_union_map *sched;
160 /* Local (per kernel launch) tiled schedule. */
161 isl_union_map *tiled_sched;
162 /* Local schedule per shared memory tile loop iteration. */
163 isl_union_map *local_sched;
165 /* Local tiled schedule projected onto the shared tile loops and
166 * the loops that will be wrapped over the threads,
167 * with all shared tile loops parametrized.
169 isl_union_map *shared_sched;
170 /* Projects out the loops that will be wrapped over the threads
171 * from shared_sched.
173 isl_union_map *shared_proj;
175 /* A map that takes the range of shared_sched as input,
176 * wraps the appropriate loops over the threads and then projects
177 * out these loops.
179 isl_map *privatization;
181 /* The array reference group corresponding to copy_sched. */
182 struct gpu_array_ref_group *copy_group;
184 /* Is any array in the current kernel marked force_private? */
185 int any_force_private;
187 /* First loop to unroll (or -1 if none) in the current part of the
188 * schedule.
190 int first_unroll;
192 int n_grid;
193 int n_block;
194 /* Note: in the input file, the sizes of the grid and the blocks
195 * are specified in the order x, y, z, but internally, the sizes
196 * are stored in reverse order, so that the last element always
197 * refers to the x dimension.
199 int grid_dim[2];
200 int block_dim[3];
201 int *tile_size;
204 /* Print the name of the local copy of a given group of array references.
206 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
207 struct gpu_array_ref_group *group)
209 int global = 0;
211 if (group->private_tile)
212 p = isl_printer_print_str(p, "private_");
213 else if (group->shared_tile)
214 p = isl_printer_print_str(p, "shared_");
215 else
216 global = 1;
217 p = isl_printer_print_str(p, group->array->name);
218 if (!global && group->array->n_group > 1) {
219 p = isl_printer_print_str(p, "_");
220 p = isl_printer_print_int(p, group->nr);
223 return p;
226 /* Collect all references to the given array and store pointers to them
227 * in array->refs.
229 * If the array contains structures, then there is no need to collect
230 * the references since we will not be computing any reference groups.
232 static void collect_references(struct gpu_prog *prog,
233 struct gpu_array_info *array)
235 int i;
236 int n;
238 if (array->has_compound_element)
239 return;
241 n = 0;
242 for (i = 0; i < prog->n_stmts; ++i) {
243 struct gpu_stmt *stmt = &prog->stmts[i];
244 struct gpu_stmt_access *access;
246 for (access = stmt->accesses; access; access = access->next) {
247 const char *name;
248 name = isl_map_get_tuple_name(access->access,
249 isl_dim_out);
250 if (name && !strcmp(array->name, name))
251 n++;
255 array->n_ref = n;
256 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
257 assert(array->refs);
259 n = 0;
260 for (i = 0; i < prog->n_stmts; ++i) {
261 struct gpu_stmt *stmt = &prog->stmts[i];
262 struct gpu_stmt_access *access;
264 for (access = stmt->accesses; access; access = access->next) {
265 const char *name;
266 name = isl_map_get_tuple_name(access->access,
267 isl_dim_out);
268 if (!name || strcmp(array->name, name))
269 continue;
271 array->refs[n++] = access;
276 /* Create a gpu_array_tile for an array of dimension "n_index".
278 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
280 int i;
281 struct gpu_array_tile *tile;
283 tile = isl_calloc_type(ctx, struct gpu_array_tile);
284 assert(tile);
286 tile->n = n_index;
288 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
289 assert(tile->bound);
291 for (i = 0; i < n_index; ++i) {
292 tile->bound[i].size = NULL;
293 tile->bound[i].lb = NULL;
294 tile->bound[i].stride = NULL;
295 tile->bound[i].shift = NULL;
298 return tile;
301 static void *free_tile(struct gpu_array_tile *tile)
303 int j;
305 if (!tile)
306 return NULL;
308 for (j = 0; j < tile->n; ++j) {
309 isl_val_free(tile->bound[j].size);
310 isl_val_free(tile->bound[j].stride);
311 isl_aff_free(tile->bound[j].lb);
312 isl_aff_free(tile->bound[j].shift);
314 free(tile->bound);
315 isl_multi_aff_free(tile->tiling);
316 free(tile);
318 return NULL;
321 static struct pet_array *find_array(struct ppcg_scop *scop,
322 __isl_keep isl_set *accessed)
324 int i;
325 isl_id *id;
327 id = isl_set_get_tuple_id(accessed);
329 for (i = 0; i < scop->pet->n_array; ++i) {
330 isl_id *id_i;
332 id_i = isl_set_get_tuple_id(scop->pet->arrays[i]->extent);
333 isl_id_free(id_i);
334 if (id == id_i)
335 break;
337 isl_id_free(id);
339 return i < scop->pet->n_array ? scop->pet->arrays[i] : NULL;
342 /* Compute and return the extent of "array", taking into account the set of
343 * accessed elements.
345 * In particular, the extent in the outer dimension is taken
346 * from "accessed", while then extent in the remaing dimensions
347 * are taken from array->extent.
349 * The extent in the outer dimension cannot be taken from array->extent
350 * because that may be unbounded. Furthermore, even if it is bounded,
351 * it may be larger than the piece of the array that is being accessed.
353 static __isl_give isl_set *compute_extent(struct pet_array *array,
354 __isl_keep isl_set *accessed)
356 int n_index;
357 isl_id *id;
358 isl_set *outer;
359 isl_set *extent;
361 extent = isl_set_copy(array->extent);
363 n_index = isl_set_dim(accessed, isl_dim_set);
364 if (n_index == 0)
365 return extent;
367 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
368 outer = isl_set_copy(accessed);
369 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
370 extent = isl_set_flat_product(outer, extent);
371 id = isl_set_get_tuple_id(accessed);
372 extent = isl_set_set_tuple_id(extent, id);
374 return extent;
377 /* Is the array "array" being extracted a read-only scalar?
379 * That is, is "array" a scalar that is never possibly written to.
380 * An array containing structures is never considered to be a scalar.
382 static int is_read_only_scalar(struct gpu_array_info *array,
383 struct gpu_prog *prog)
385 isl_set *space;
386 isl_union_map *write;
387 int empty;
389 if (array->has_compound_element)
390 return 0;
391 if (array->n_index != 0)
392 return 0;
394 write = isl_union_map_copy(prog->may_write);
395 space = isl_set_universe(isl_space_copy(array->space));
396 write = isl_union_map_intersect_range(write,
397 isl_union_set_from_set(space));
398 empty = isl_union_map_is_empty(write);
399 isl_union_map_free(write);
401 return empty;
404 /* Compute bounds on the host arrays based on the accessed elements
405 * and collect all references to the array.
407 * If the array is zero-dimensional and does not contain structures,
408 * i.e., if the array is a scalar, we check whether it is read-only.
410 static int extract_array_info(__isl_take isl_set *array, void *user)
412 int i;
413 struct gpu_prog *prog = (struct gpu_prog *)user;
414 const char *name;
415 int n_index;
416 isl_pw_aff **bounds;
417 struct pet_array *pa;
418 struct gpu_array_info *info;
419 isl_set *extent;
421 info = &prog->array[prog->n_array];
422 prog->n_array++;
424 n_index = isl_set_dim(array, isl_dim_set);
425 name = isl_set_get_tuple_name(array);
426 bounds = isl_alloc_array(isl_set_get_ctx(array),
427 isl_pw_aff *, n_index);
428 if (!bounds)
429 goto error;
431 info->space = isl_set_get_space(array);
432 info->name = strdup(name);
433 info->n_index = n_index;
434 info->bound = bounds;
435 info->linearize = prog->scop->options->linearize_device_arrays;
437 pa = find_array(prog->scop, array);
438 if (!pa)
439 isl_die(isl_set_get_ctx(array), isl_error_internal,
440 "unable to find array in scop", goto error);
442 info->type = strdup(pa->element_type);
443 info->size = pa->element_size;
444 info->local = pa->declared && !pa->exposed;
445 info->has_compound_element = pa->element_is_record;
446 info->read_only_scalar = is_read_only_scalar(info, prog);
448 extent = compute_extent(pa, array);
449 info->extent = extent;
450 for (i = 0; i < n_index; ++i) {
451 isl_set *dom;
452 isl_local_space *ls;
453 isl_aff *one;
454 isl_pw_aff *bound;
456 dom = isl_set_copy(extent);
457 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
458 n_index - (i + 1));
459 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
460 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
461 fprintf(stderr, "unable to determine extent of '%s' "
462 "in dimension %d\n", info->name, i);
463 dom = isl_set_free(dom);
465 bound = isl_set_dim_max(dom, 0);
466 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
467 ls = isl_local_space_from_space(isl_set_get_space(dom));
468 one = isl_aff_zero_on_domain(ls);
469 one = isl_aff_add_constant_si(one, 1);
470 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
471 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
473 bounds[i] = bound;
474 if (!isl_pw_aff_is_cst(bound))
475 info->linearize = 1;
478 collect_references(prog, info);
480 isl_set_free(array);
481 return 0;
482 error:
483 isl_set_free(array);
484 return -1;
487 /* Remove independence from the order constraints "order" on array "array".
488 * Since the pairs of iterations in the filter relation of an independence
489 * are guaranteed to be completely independent by the user, there is
490 * no need to ensure that live ranges are ordered along thong pairs.
491 * We make an exception for local variables, though, as the independence
492 * guarantee does not apply to those.
494 * The order constraints are used in two places.
495 * Those on scalars are used in check_scalar_live_ranges to check if
496 * we need to force the scalar to be private. Any non-local scalar
497 * should not be forced scalar if it only appears in independent loops.
498 * Those on non-scalars are added to the coincidence constraints
499 * in compute_schedule because we do not support any array expansion.
500 * Accesses to non-local arrays should not prevent a loop from being
501 * considered coincident so we should indeed remove those constraints
502 * from the order constraints.
504 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
505 struct gpu_array_info *array, __isl_take isl_union_map *order)
507 int i;
509 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
510 struct pet_independence *pi = prog->scop->pet->independences[i];
511 if (isl_union_set_contains(pi->local, array->space))
512 continue;
514 order = isl_union_map_subtract(order,
515 isl_union_map_copy(pi->filter));
518 return order;
521 /* For each array in "prog", store the (untagged) order dependences
522 * derived from the array in array->dep_order.
523 * In particular, consider all references that access the given array
524 * and take the order dependences that have one of these references
525 * as source. (Since an order dependence relates two references to
526 * the same array, the target of these order dependences will also
527 * be one of these references.)
528 * Additionally, store the union of these array->dep_order relations
529 * for all non-scalar arrays in prog->array_order.
531 void collect_order_dependences(struct gpu_prog *prog)
533 int i;
534 isl_space *space;
535 isl_union_map *accesses;
537 space = isl_union_map_get_space(prog->read);
538 prog->array_order = isl_union_map_empty(space);
540 accesses = isl_union_map_copy(prog->scop->tagged_reads);
541 accesses = isl_union_map_union(accesses,
542 isl_union_map_copy(prog->scop->tagged_may_writes));
543 accesses = isl_union_map_universe(accesses);
544 accesses = isl_union_map_apply_range(accesses,
545 isl_union_map_copy(prog->to_outer));
547 for (i = 0; i < prog->n_array; ++i) {
548 struct gpu_array_info *array = &prog->array[i];
549 isl_set *set;
550 isl_union_set *uset;
551 isl_union_map *order;
553 set = isl_set_universe(isl_space_copy(array->space));
554 uset = isl_union_set_from_set(set);
555 uset = isl_union_map_domain(
556 isl_union_map_intersect_range(isl_union_map_copy(accesses),
557 uset));
558 order = isl_union_map_copy(prog->scop->tagged_dep_order);
559 order = isl_union_map_intersect_domain(order, uset);
560 order = isl_union_map_zip(order);
561 order = isl_union_set_unwrap(isl_union_map_domain(order));
562 order = remove_independences(prog, array, order);
563 array->dep_order = order;
565 if (gpu_array_is_scalar(array) && !array->has_compound_element)
566 continue;
568 prog->array_order = isl_union_map_union(prog->array_order,
569 isl_union_map_copy(array->dep_order));
572 isl_union_map_free(accesses);
575 /* Construct a gpu_array_info for each array possibly accessed by "prog" and
576 * collect them in prog->array.
578 * If there are any member accesses involved, then they are first mapped
579 * to the outer arrays of structs.
581 * If we are allowing live range reordering, then also set
582 * the dep_order field. Otherwise leave it NULL.
584 static int collect_array_info(struct gpu_prog *prog)
586 int r;
587 isl_union_set *arrays;
589 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
590 arrays = isl_union_set_union(arrays,
591 isl_union_map_range(isl_union_map_copy(prog->may_write)));
593 arrays = isl_union_set_apply(arrays,
594 isl_union_map_copy(prog->to_outer));
596 arrays = isl_union_set_coalesce(arrays);
598 prog->n_array = isl_union_set_n_set(arrays);
599 prog->array = isl_calloc_array(prog->ctx,
600 struct gpu_array_info, prog->n_array);
601 assert(prog->array);
602 prog->n_array = 0;
603 r = isl_union_set_foreach_set(arrays, &extract_array_info, prog);
604 isl_union_set_free(arrays);
606 if (prog->scop->options->live_range_reordering)
607 collect_order_dependences(prog);
609 return r;
612 static void free_array_info(struct gpu_prog *prog)
614 int i, j;
616 for (i = 0; i < prog->n_array; ++i) {
617 int n_index = prog->array[i].n_index;
618 free(prog->array[i].type);
619 free(prog->array[i].name);
620 for (j = 0; j < n_index; ++j)
621 isl_pw_aff_free(prog->array[i].bound[j]);
622 isl_space_free(prog->array[i].space);
623 isl_set_free(prog->array[i].extent);
624 free(prog->array[i].bound);
625 free(prog->array[i].refs);
626 isl_union_map_free(prog->array[i].dep_order);
628 free(prog->array);
631 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
632 * as an array or through a pointer reference, but as a single data element.
633 * At the moment, scalars are represented as zero-dimensional arrays.
634 * Note that the single data element may be an entire structure.
636 int gpu_array_is_scalar(struct gpu_array_info *array)
638 return array->n_index == 0;
641 /* Is "array" a read-only scalar?
643 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
645 return array->read_only_scalar;
648 /* Return the set of parameter values for which the array has a positive
649 * size in all dimensions.
650 * If the sizes are only valid for some parameter values, then those
651 * constraints are also taken into account.
653 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
655 int i;
656 isl_space *space;
657 isl_set *guard;
659 space = isl_space_params(isl_space_copy(array->space));
660 guard = isl_set_universe(space);
662 for (i = 0; i < array->n_index; ++i) {
663 isl_pw_aff *bound;
664 isl_set *guard_i, *zero;
666 bound = isl_pw_aff_copy(array->bound[i]);
667 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
668 zero = isl_pw_aff_zero_set(bound);
669 guard_i = isl_set_subtract(guard_i, zero);
670 guard = isl_set_intersect(guard, guard_i);
673 return guard;
676 /* Internal data structure for extract_size_of_type.
677 * "type" specifies the name of the space that we want to extract.
678 * "res" is used to store the subset of that space.
680 struct ppcg_extract_size_data {
681 const char *type;
682 isl_set *res;
685 /* This function is called for each set in a union_set.
686 * If the name of the set matches data->type, we store the
687 * set in data->res.
689 static int extract_size_of_type(__isl_take isl_set *size, void *user)
691 struct ppcg_extract_size_data *data = user;
692 const char *name;
694 name = isl_set_get_tuple_name(size);
695 if (name && !strcmp(name, data->type)) {
696 data->res = size;
697 return -1;
700 isl_set_free(size);
701 return 0;
704 /* Given a union map { kernel[i] -> *[...] },
705 * return the range in the space called "type" for the kernel with
706 * sequence number "id".
708 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
709 const char *type, int id)
711 isl_space *space;
712 isl_set *dom;
713 isl_union_set *local_sizes;
714 struct ppcg_extract_size_data data = { type, NULL };
716 if (!sizes)
717 return NULL;
719 space = isl_union_map_get_space(sizes);
720 space = isl_space_set_from_params(space);
721 space = isl_space_add_dims(space, isl_dim_set, 1);
722 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
723 dom = isl_set_universe(space);
724 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
726 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
727 isl_union_map_copy(sizes));
728 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
729 isl_union_set_free(local_sizes);
730 return data.res;
733 /* Given a singleton set, extract the first (at most *len) elements
734 * of the single integer tuple into *sizes and update *len if needed.
736 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
738 int i;
739 int dim;
741 if (!set)
742 return;
744 dim = isl_set_dim(set, isl_dim_set);
745 if (dim < *len)
746 *len = dim;
748 for (i = 0; i < *len; ++i) {
749 isl_val *v;
751 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
752 assert(v);
754 sizes[i] = isl_val_get_num_si(v);
755 isl_val_free(v);
758 isl_set_free(set);
761 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
762 * if the option debug->dump_sizes is set.
764 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
765 int *sizes, int len)
767 int i;
768 isl_space *space;
769 isl_map *map;
771 if (!gen->options->debug->dump_sizes)
772 return;
774 space = isl_union_map_get_space(gen->used_sizes);
775 space = isl_space_set_from_params(space);
776 space = isl_space_add_dims(space, isl_dim_set, 1);
777 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
778 space = isl_space_from_domain(space);
779 space = isl_space_add_dims(space, isl_dim_out, len);
780 space = isl_space_set_tuple_name(space, isl_dim_out, type);
782 map = isl_map_universe(space);
783 map = isl_map_fix_si(map, isl_dim_in, 0, id);
784 for (i = 0; i < len; ++i)
785 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
787 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
790 /* Extract user specified "tile" sizes from the "sizes" command line option,
791 * defaulting to option->tile_size in each dimension.
792 * Add the effectively used sizes to gen->used_sizes.
794 static void read_tile_sizes(struct gpu_gen *gen)
796 int n;
797 isl_set *size;
799 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
800 assert(gen->tile_size);
801 for (n = 0; n < gen->tile_len; ++n)
802 gen->tile_size[n] = gen->options->tile_size;
804 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
805 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
806 set_used_sizes(gen, "tile", gen->kernel_id,
807 gen->tile_size, gen->tile_len);
809 if (gen->n_parallel > gen->tile_len)
810 gen->n_parallel = gen->tile_len;
813 /* Extract user specified "block" sizes from the "sizes" command line option,
814 * after filling in some potentially useful defaults.
815 * Add the effectively used sizes to gen->used_sizes.
817 static void read_block_sizes(struct gpu_gen *gen)
819 int n;
820 isl_set *size;
822 n = gen->n_parallel;
823 gen->n_block = (n <= 3) ? n : 3;
824 switch (gen->n_block) {
825 case 1:
826 gen->block_dim[0] = 512;
827 break;
828 case 2:
829 gen->block_dim[0] = 32;
830 gen->block_dim[1] = 16;
831 break;
832 default:
833 gen->block_dim[0] = 32;
834 gen->block_dim[1] = 4;
835 gen->block_dim[2] = 4;
836 break;
839 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
840 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
841 set_used_sizes(gen, "block", gen->kernel_id,
842 gen->block_dim, gen->n_block);
845 /* Extract user specified "grid" sizes from the "sizes" command line option,
846 * after filling in some potentially useful defaults.
847 * Add the effectively used sizes to gen->used_sizes.
849 static void read_grid_sizes(struct gpu_gen *gen)
851 int n = gen->n_parallel;
852 isl_set *size;
854 gen->n_grid = (n <= 2) ? n : 2;
855 switch (gen->n_grid) {
856 case 1:
857 gen->grid_dim[0] = 32768;
858 break;
859 default:
860 gen->grid_dim[0] = 256;
861 gen->grid_dim[1] = 256;
862 break;
865 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
866 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
867 set_used_sizes(gen, "grid", gen->kernel_id, gen->grid_dim, gen->n_grid);
870 /* Extract user specified sizes from the "sizes" command line option
871 * after filling in some potentially useful defaults.
873 static void read_sizes(struct gpu_gen *gen)
875 read_tile_sizes(gen);
876 read_block_sizes(gen);
877 read_grid_sizes(gen);
880 static void *free_stmts(struct gpu_stmt *stmts, int n)
882 int i;
884 if (!stmts)
885 return NULL;
887 for (i = 0; i < n; ++i) {
888 struct gpu_stmt_access *access, *next;
890 for (access = stmts[i].accesses; access; access = next) {
891 next = access->next;
892 isl_id_free(access->ref_id);
893 isl_map_free(access->access);
894 isl_map_free(access->tagged_access);
895 free(access);
898 isl_id_free(stmts[i].id);
900 free(stmts);
902 return NULL;
905 /* Construct a map from a domain of dimensionality "len"
906 * to a domain of dimensionality "len" + "tile_len" that tiles
907 * the "tile_len" coordinates starting at "first".
908 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
909 * "dim" prescribes the parameters.
911 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
912 int first, int tile_len, int *tile_size)
914 int i;
915 isl_basic_map *bmap;
916 isl_constraint *c;
917 isl_local_space *ls;
919 dim = isl_space_add_dims(dim, isl_dim_in, len);
920 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
921 bmap = isl_basic_map_universe(isl_space_copy(dim));
922 ls = isl_local_space_from_space(dim);
924 for (i = 0; i < len - tile_len; ++i) {
925 int j = i < first ? i : i + tile_len;
926 int k = i < first ? i : i + 2 * tile_len;
928 c = isl_equality_alloc(isl_local_space_copy(ls));
929 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
930 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
931 bmap = isl_basic_map_add_constraint(bmap, c);
934 for (i = 0; i < tile_len; ++i) {
935 c = isl_equality_alloc(isl_local_space_copy(ls));
936 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
937 first + i, -1);
938 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
939 first + i, tile_size[i]);
940 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
941 first + i + tile_len, 1);
942 bmap = isl_basic_map_add_constraint(bmap, c);
944 c = isl_inequality_alloc(isl_local_space_copy(ls));
945 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
946 first + i + tile_len, 1);
947 bmap = isl_basic_map_add_constraint(bmap, c);
949 c = isl_inequality_alloc(isl_local_space_copy(ls));
950 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
951 first + i + tile_len, -1);
952 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
953 bmap = isl_basic_map_add_constraint(bmap, c);
956 isl_local_space_free(ls);
958 return isl_map_from_basic_map(bmap);
961 /* Construct a map from a domain of dimensionality "len"
962 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
963 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
964 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
965 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
966 * that are projected out at the end.
967 * "dim" prescribes the parameters.
969 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
970 int first, int wrap_len, int *wrap_size)
972 int i;
973 isl_basic_map *bmap;
974 isl_constraint *c;
975 isl_local_space *ls;
977 dim = isl_space_add_dims(dim, isl_dim_in, len);
978 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
979 bmap = isl_basic_map_universe(isl_space_copy(dim));
980 ls = isl_local_space_from_space(dim);
982 for (i = 0; i < len; ++i) {
983 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
985 c = isl_equality_alloc(isl_local_space_copy(ls));
986 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
987 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
988 bmap = isl_basic_map_add_constraint(bmap, c);
991 for (i = 0; i < wrap_len; ++i) {
992 c = isl_equality_alloc(isl_local_space_copy(ls));
993 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
994 first + i, -1);
995 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
996 first + wrap_len + i, 1);
997 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
998 first + 2 * wrap_len + i, wrap_size[i]);
999 bmap = isl_basic_map_add_constraint(bmap, c);
1001 c = isl_inequality_alloc(isl_local_space_copy(ls));
1002 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1003 first + wrap_len + i, 1);
1004 bmap = isl_basic_map_add_constraint(bmap, c);
1006 c = isl_inequality_alloc(isl_local_space_copy(ls));
1007 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1008 first + wrap_len + i, -1);
1009 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
1010 bmap = isl_basic_map_add_constraint(bmap, c);
1013 isl_local_space_free(ls);
1015 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
1016 first + 2 * wrap_len, wrap_len);
1018 return isl_map_from_basic_map(bmap);
1021 /* Add "n" parameters named prefix%d.
1023 static __isl_give isl_set *add_params( __isl_take isl_set *set,
1024 int n, const char *prefix)
1026 int i;
1027 unsigned nparam;
1028 char name[20];
1030 nparam = isl_set_dim(set, isl_dim_param);
1031 set = isl_set_add_dims(set, isl_dim_param, n);
1033 for (i = 0; i < n; ++i) {
1034 snprintf(name, sizeof(name), "%s%d", prefix, i);
1035 set = isl_set_set_dim_name(set, isl_dim_param,
1036 nparam + i, name);
1039 return set;
1042 /* Equate the "n" dimensions of "set" starting at "first" to
1043 * freshly created parameters named prefix%d.
1045 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
1046 int first, int n, const char *prefix)
1048 int i;
1049 unsigned nparam;
1051 nparam = isl_set_dim(set, isl_dim_param);
1053 set = add_params(set, n, prefix);
1055 for (i = 0; i < n; ++i)
1056 set = isl_set_equate(set, isl_dim_param, nparam + i,
1057 isl_dim_set, first + i);
1059 return set;
1062 /* Given a parameter space "space", create a set of dimension "len"
1063 * of which the "n" dimensions starting at "first" are equated to
1064 * freshly created parameters named prefix%d.
1066 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
1067 int len, int first, int n, const char *prefix)
1069 isl_set *set;
1071 space = isl_space_set_from_params(space);
1072 space = isl_space_add_dims(space, isl_dim_set, len);
1073 set = isl_set_universe(space);
1075 return parametrize(set, first, n, prefix);
1078 /* Tile the B loops over the tile sizes and then tile/wrap
1079 * the T1 loops over the blocks.
1081 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
1082 __isl_take isl_union_map *sched)
1084 isl_space *dim;
1085 isl_map *tiling, *block_tiling;
1087 dim = isl_union_map_get_space(sched);
1088 tiling = tile(isl_space_copy(dim), gen->untiled_len,
1089 gen->tile_first, gen->tile_len, gen->tile_size);
1091 if (gen->options->wrap)
1092 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
1093 gen->tile_first, gen->n_grid, gen->grid_dim);
1094 else
1095 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
1096 gen->tile_first, gen->n_grid, gen->grid_dim);
1098 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
1100 tiling = isl_map_apply_range(tiling, block_tiling);
1102 sched = isl_union_map_apply_range(sched,
1103 isl_union_map_from_map(tiling));
1105 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1107 return sched;
1110 /* Equate the "T1P" iterators in the tiled schedule "sched"
1111 * to the block dimensions.
1113 static __isl_give isl_union_map *parametrize_tiled_schedule(
1114 struct gpu_gen *gen, __isl_take isl_union_map *sched)
1116 isl_space *dim;
1117 isl_set *par;
1119 dim = isl_union_map_get_space(sched);
1120 par = parametrization(dim, gen->tiled_len,
1121 gen->tile_first + gen->n_grid, gen->n_grid, "b");
1122 sched = isl_union_map_intersect_range(sched,
1123 isl_union_set_from_set(par));
1125 return sched;
1128 /* Tile/wrap the P1 loops over the threads.
1130 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
1131 __isl_take isl_union_map *sched)
1133 isl_space *dim;
1134 isl_map *tiling;
1135 isl_set *par;
1137 dim = isl_union_map_get_space(sched);
1139 if (gen->options->wrap)
1140 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
1141 gen->shared_len, gen->n_block, gen->block_dim);
1142 else
1143 tiling = tile(isl_space_copy(dim), gen->tiled_len,
1144 gen->shared_len, gen->n_block, gen->block_dim);
1145 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
1147 sched = isl_union_map_apply_range(sched,
1148 isl_union_map_from_map(tiling));
1150 par = parametrization(dim, gen->thread_tiled_len,
1151 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1152 gen->n_block, "t");
1153 sched = isl_union_map_intersect_range(sched,
1154 isl_union_set_from_set(par));
1156 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1158 return sched;
1161 /* If the user asked for it, scale the shared memory tile loops
1162 * (T1T and T2) of "sched" by gen->tile_size[i].
1163 * If we are not performing "wrapping", then additionally scale the T1P
1164 * loops by gen->grid_dim[i].
1166 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
1167 __isl_take isl_union_map *sched)
1169 int i;
1170 isl_space *dim;
1171 isl_basic_map *scale;
1172 isl_constraint *c;
1173 isl_local_space *ls;
1175 if (!gen->options->scale_tile_loops)
1176 return sched;
1178 dim = isl_union_map_get_space(sched);
1179 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
1180 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
1181 scale = isl_basic_map_universe(isl_space_copy(dim));
1182 ls = isl_local_space_from_space(dim);
1184 for (i = 0; i < gen->tiled_len; ++i) {
1185 int f = 1;
1187 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
1188 f = gen->tile_size[i - gen->tile_first];
1189 if (!gen->options->wrap)
1190 f *= gen->grid_dim[i - gen->tile_first];
1191 } else if (i >= gen->tile_first + gen->n_grid &&
1192 i < gen->tile_first + gen->n_grid + gen->tile_len) {
1193 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
1196 c = isl_equality_alloc(isl_local_space_copy(ls));
1197 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1198 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1199 scale = isl_basic_map_add_constraint(scale, c);
1202 isl_local_space_free(ls);
1204 sched = isl_union_map_apply_range(sched,
1205 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1207 return sched;
1210 /* If we are not performing "wrapping" and if the user asked for it,
1211 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1213 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1214 __isl_take isl_union_map *sched)
1216 int i;
1217 isl_space *dim;
1218 isl_basic_map *scale;
1219 isl_constraint *c;
1220 isl_local_space *ls;
1222 if (gen->options->wrap)
1223 return sched;
1224 if (!gen->options->scale_tile_loops)
1225 return sched;
1227 dim = isl_union_map_get_space(sched);
1228 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1229 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1230 scale = isl_basic_map_universe(isl_space_copy(dim));
1231 ls = isl_local_space_from_space(dim);
1233 for (i = 0; i < gen->thread_tiled_len; ++i) {
1234 int f = 1;
1236 if (i >= gen->shared_len &&
1237 i < gen->shared_len + gen->n_block)
1238 f = gen->block_dim[i - gen->shared_len];
1240 c = isl_equality_alloc(isl_local_space_copy(ls));
1241 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1242 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1243 scale = isl_basic_map_add_constraint(scale, c);
1246 isl_local_space_free(ls);
1248 sched = isl_union_map_apply_range(sched,
1249 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1251 return sched;
1254 /* If we are not performing "wrapping" and if the user asked for it,
1255 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1257 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1258 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1260 int i;
1261 isl_space *dim;
1262 isl_basic_map *scale;
1263 isl_constraint *c;
1264 isl_local_space *ls;
1266 if (gen->options->wrap)
1267 return sched;
1268 if (!gen->options->scale_tile_loops)
1269 return sched;
1271 dim = isl_union_map_get_space(sched);
1272 dim = isl_space_add_dims(dim, isl_dim_in, len);
1273 dim = isl_space_add_dims(dim, isl_dim_out, len);
1274 scale = isl_basic_map_universe(isl_space_copy(dim));
1275 ls = isl_local_space_from_space(dim);
1277 for (i = 0; i < len; ++i) {
1278 int f = 1;
1280 if (i >= first && i < first + n_tile)
1281 f = gen->kernel->block_dim[i - first];
1283 c = isl_equality_alloc(isl_local_space_copy(ls));
1284 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1285 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1286 scale = isl_basic_map_add_constraint(scale, c);
1289 isl_local_space_free(ls);
1291 sched = isl_union_map_apply_range(sched,
1292 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1294 return sched;
1297 /* Add "len" parameters p[i] called prefix%d,
1298 * with bounds to 0 <= p[i] < size[i].
1300 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1301 int len, int *size, const char *prefix)
1303 int i;
1304 unsigned nparam;
1305 isl_space *dim;
1306 isl_basic_set *bset;
1307 isl_constraint *c;
1308 isl_local_space *ls;
1309 char name[20];
1311 nparam = isl_set_dim(set, isl_dim_param);
1312 set = isl_set_add_dims(set, isl_dim_param, len);
1314 for (i = 0; i < len; ++i) {
1315 snprintf(name, sizeof(name), "%s%d", prefix, i);
1316 set = isl_set_set_dim_name(set, isl_dim_param,
1317 nparam + i, name);
1320 dim = isl_set_get_space(set);
1321 bset = isl_basic_set_universe(isl_space_copy(dim));
1322 ls = isl_local_space_from_space(dim);
1324 for (i = 0; i < len; ++i) {
1325 c = isl_inequality_alloc(isl_local_space_copy(ls));
1326 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1327 nparam + i, 1);
1328 bset = isl_basic_set_add_constraint(bset, c);
1330 c = isl_inequality_alloc(isl_local_space_copy(ls));
1331 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1332 nparam + i, -1);
1333 c = isl_constraint_set_constant_si(c, size[i] - 1);
1334 bset = isl_basic_set_add_constraint(bset, c);
1337 isl_local_space_free(ls);
1339 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1342 /* Add "len" parameters p[i] called prefix%d and intersect "set"
1343 * with
1345 * { : 0 <= p[i] < size[i] }
1347 * or an overapproximation.
1349 static __isl_give isl_set *add_bounded_parameters_dynamic(
1350 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1351 const char *prefix)
1353 int i, len;
1354 unsigned nparam;
1355 isl_space *space;
1356 isl_local_space *ls;
1357 char name[20];
1359 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1360 nparam = isl_set_dim(set, isl_dim_param);
1361 set = isl_set_add_dims(set, isl_dim_param, len);
1363 for (i = 0; i < len; ++i) {
1364 snprintf(name, sizeof(name), "%s%d", prefix, i);
1365 set = isl_set_set_dim_name(set, isl_dim_param,
1366 nparam + i, name);
1369 space = isl_space_params(isl_set_get_space(set));
1370 ls = isl_local_space_from_space(space);
1371 for (i = 0; i < len; ++i) {
1372 isl_pw_aff *param, *size_i, *zero;
1373 isl_set *bound;
1375 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1376 isl_dim_param, nparam + i);
1378 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1379 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1380 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
1381 set = isl_set_intersect_params(set, bound);
1383 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1384 bound = isl_pw_aff_ge_set(param, zero);
1385 set = isl_set_intersect_params(set, bound);
1387 isl_local_space_free(ls);
1389 return set;
1392 /* Construct a map from an access to group->array to the corresponding
1393 * shared/private memory tile.
1394 * The map is of the form
1396 * { [D[i] -> A[a]] -> T[t] }
1398 * where D represents the initial shared_len dimensions
1399 * of the computed schedule.
1401 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1403 struct gpu_array_tile *tile;
1404 isl_multi_aff *tiling;
1406 tile = group->private_tile;
1407 if (!tile)
1408 tile = group->shared_tile;
1410 tiling = isl_multi_aff_copy(tile->tiling);
1412 return isl_map_from_multi_aff(tiling);
1415 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1417 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1418 unsigned pos)
1420 isl_val *v;
1421 int fixed;
1423 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1424 if (!v)
1425 return -1;
1426 fixed = isl_val_is_int(v);
1427 isl_val_free(v);
1429 return fixed;
1432 /* Given a schedule that iterates over all elements in a piece of an array,
1433 * perform tiling/wrapping over the threads.
1435 * In particular, we tile the final iterators so that the final thread
1436 * dimension runs over the final array dimension.
1437 * However, if those final iterators have only a single iteration,
1438 * we try to tile earlier iterators instead.
1440 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1441 __isl_take isl_map *sched)
1443 isl_space *dim;
1444 isl_union_map *usched;
1445 isl_map *tiling;
1446 isl_set *par;
1447 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1448 int n_tile;
1449 int first;
1451 n_tile = gen->kernel->n_block;
1452 if (n_tile > nvar) {
1453 int i;
1454 sched = isl_map_insert_dims(sched,
1455 isl_dim_out, 0, n_tile - nvar);
1456 for (i = 0; i < n_tile - nvar; ++i)
1457 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1458 nvar = n_tile;
1461 first = nvar - n_tile;
1463 for (; first > 0; first --)
1464 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1465 break;
1467 dim = isl_map_get_space(sched);
1468 dim = isl_space_params(dim);
1469 if (gen->options->wrap)
1470 tiling = wrap(isl_space_copy(dim), nvar, first,
1471 n_tile, gen->kernel->block_dim);
1472 else
1473 tiling = tile(isl_space_copy(dim), nvar, first,
1474 n_tile, gen->kernel->block_dim);
1475 sched = isl_map_apply_range(sched, tiling);
1477 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1478 sched = isl_map_intersect_range(sched, par);
1480 usched = isl_union_map_from_map(sched);
1481 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1482 first, n_tile);
1483 sched = isl_map_from_union_map(usched);
1485 return sched;
1488 /* Return the union of all read (read = 1) and/or write (write = 1)
1489 * access relations in the group.
1491 static __isl_give isl_union_map *group_access_relation(
1492 struct gpu_array_ref_group *group, int read, int write)
1494 int i;
1495 isl_union_map *access;
1497 access = isl_union_map_empty(isl_map_get_space(group->access));
1498 for (i = 0; i < group->n_ref; ++i) {
1499 isl_map *map_i;
1501 if (!((read && group->refs[i]->read) ||
1502 (write && group->refs[i]->write)))
1503 continue;
1504 map_i = isl_map_copy(group->refs[i]->access);
1505 access = isl_union_map_union(access,
1506 isl_union_map_from_map(map_i));
1509 return access;
1512 /* Return the union of all tagged access relations in the group.
1514 static __isl_give isl_union_map *group_tagged_access_relation(
1515 struct gpu_array_ref_group *group)
1517 int i;
1518 isl_union_map *access;
1520 access = isl_union_map_empty(isl_map_get_space(group->access));
1521 for (i = 0; i < group->n_ref; ++i) {
1522 isl_map *map_i;
1524 map_i = isl_map_copy(group->refs[i]->tagged_access);
1525 access = isl_union_map_union(access,
1526 isl_union_map_from_map(map_i));
1529 return access;
1532 /* Return the extent of "array", recomputed from the bounds.
1533 * The recomputed extent may be simpler than the original extent.
1535 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1537 int i;
1538 isl_id *id;
1539 isl_space *space;
1540 isl_local_space *ls;
1541 isl_set *extent;
1543 id = isl_set_get_tuple_id(array->extent);
1544 space = isl_set_get_space(array->extent);
1545 extent = isl_set_universe(isl_space_copy(space));
1546 ls = isl_local_space_from_space(space);
1547 for (i = 0; i < array->n_index; ++i) {
1548 isl_pw_aff *bound;
1549 isl_aff *aff;
1550 isl_pw_aff *index;
1551 isl_set *lt;
1553 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1555 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1556 isl_dim_set, i);
1557 index = isl_pw_aff_from_aff(aff);
1558 bound = isl_pw_aff_copy(array->bound[i]);
1559 bound = isl_pw_aff_from_range(bound);
1560 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1561 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1562 isl_id_copy(id));
1563 lt = isl_pw_aff_lt_set(index, bound);
1564 extent = isl_set_intersect(extent, lt);
1566 isl_local_space_free(ls);
1567 isl_id_free(id);
1569 return extent;
1572 /* Return a map from the first shared_len dimensions of the computed
1573 * schedule to the array tile in
1574 * global memory that corresponds to the shared memory copy.
1576 * In particular, return a map
1578 * { D[i] -> A[a] }
1580 * with constraints
1582 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1584 * and
1586 * 0 <= a <= array_size - 1 (2)
1588 * Note that if some stride has been detected (i.e., when
1589 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1590 * to the shifted and scaled down version.
1592 * Constraints (1) are obtained by mapping the size constraints on the
1593 * shared/private memory tile back to the access relation.
1594 * Constraints (2) are obtained from the (recomputed) extent.
1596 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1598 int i;
1599 int n_index = group->array->n_index;
1600 isl_map *tile;
1601 isl_space *space;
1602 isl_set *local;
1603 isl_set *extent;
1605 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1606 space = isl_space_range(space);
1607 local = isl_set_universe(space);
1608 for (i = 0; i < n_index; ++i) {
1609 isl_val *bound;
1611 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1612 bound = isl_val_copy(group->shared_tile->bound[i].size);
1613 bound = isl_val_sub_ui(bound, 1);
1614 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1616 local = isl_set_preimage_multi_aff(local,
1617 isl_multi_aff_copy(group->shared_tile->tiling));
1618 tile = isl_set_unwrap(local);
1619 extent = array_extent(group->array);
1620 tile = isl_map_intersect_range(tile, extent);
1622 return tile;
1625 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1626 * return the corresponding mapping from the AST schedule to
1627 * to the first shared_len dimensions of the schedule computed by PPCG.
1629 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1630 __isl_take isl_pw_multi_aff *iterator_map)
1632 isl_union_map *umap;
1633 isl_space *space;
1634 isl_map *map, *sched;;
1636 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1637 space = isl_space_from_domain(space);
1638 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1640 umap = isl_union_map_copy(gen->shared_sched);
1641 umap = isl_union_map_apply_range(umap,
1642 isl_union_map_copy(gen->shared_proj));
1643 map = isl_union_map_extract_map(umap, space);
1644 isl_union_map_free(umap);
1646 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1647 sched = isl_map_detect_equalities(sched);
1649 return isl_pw_multi_aff_from_map(sched);
1652 /* Set unroll[j] if the input dimension j is involved in
1653 * the index expression represented by ma.
1655 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1656 void *user)
1658 int i, j;
1659 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1660 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1661 int *unroll = user;
1663 for (i = 0; i < n_out; ++i) {
1664 isl_aff *aff;
1666 aff = isl_multi_aff_get_aff(ma, i);
1667 for (j = 0; j < n_in; ++j)
1668 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1669 unroll[j] = 1;
1670 isl_aff_free(aff);
1673 isl_set_free(set);
1674 isl_multi_aff_free(ma);
1675 return 0;
1678 /* Given an array pos mapping input dimensions to the corresponding
1679 * output dimension, construct the corresponding map.
1681 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1682 int *pos, int len)
1684 int i;
1685 isl_constraint *c;
1686 isl_basic_map *bmap;
1687 isl_local_space *ls;
1689 dim = isl_space_add_dims(dim, isl_dim_in, len);
1690 dim = isl_space_add_dims(dim, isl_dim_out, len);
1691 bmap = isl_basic_map_universe(isl_space_copy(dim));
1692 ls = isl_local_space_from_space(dim);
1694 for (i = 0; i < len; ++i) {
1695 c = isl_equality_alloc(isl_local_space_copy(ls));
1696 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1697 -1);
1698 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1700 bmap = isl_basic_map_add_constraint(bmap, c);
1702 isl_local_space_free(ls);
1704 return isl_map_from_basic_map(bmap);
1707 /* Remove the private tiles from all array reference groups,
1708 * except for the groups of arrays that are marked force_private.
1710 static void remove_private_tiles(struct gpu_gen *gen)
1712 int i, j;
1714 for (i = 0; i < gen->prog->n_array; ++i) {
1715 struct gpu_array_info *array = &gen->prog->array[i];
1717 if (array->force_private)
1718 continue;
1720 for (j = 0; j < array->n_group; ++j) {
1721 struct gpu_array_ref_group *group = array->groups[j];
1723 group->private_tile = free_tile(group->private_tile);
1728 /* Find all loops involved in any of the index expressions for any of
1729 * the private accesses, move them innermost and then mark them as
1730 * requiring unrolling by setting gen->first_unroll.
1731 * The loops involved should all be parallel because of the checks
1732 * we performed in check_private_group_access. Moving them innermost
1733 * is therefore a valid transformation.
1735 * If any of the arrays are marked force_private, however, then
1736 * those loops may not be parallel with respect to the marked arrays.
1737 * If any of the loops would have to be moved innermost for the
1738 * (non forced) private accesses and if there are any force_private
1739 * arrays, then we revert the decision to map the selected arrays
1740 * to private memory. An alternative solution would be to expand
1741 * the force_private arrays.
1743 * Loops up to gen->shared_len are generated before the mapping to
1744 * threads is applied. They should therefore be ignored.
1746 * We compute the hidden equalities of the schedule first
1747 * since we will need them in our calls to isl_pw_multi_aff_from_map
1748 * and because we want to make sure that the same equalities
1749 * are also available to the code generator.
1751 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1752 __isl_take isl_union_map *sched)
1754 int i, j;
1755 int unroll[gen->thread_tiled_len];
1756 int perm[gen->thread_tiled_len];
1757 isl_space *dim;
1758 isl_map *permute;
1759 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1761 gen->first_unroll = -1;
1763 sched = isl_union_map_detect_equalities(sched);
1764 for (i = 0; i < gen->thread_tiled_len; ++i)
1765 unroll[i] = 0;
1766 for (i = 0; i < gen->prog->n_array; ++i) {
1767 struct gpu_array_info *array = &gen->prog->array[i];
1769 for (j = 0; j < array->n_group; ++j) {
1770 isl_union_map *access;
1771 isl_map *acc;
1772 isl_pw_multi_aff *pma;
1774 if (!array->groups[j]->private_tile)
1775 continue;
1777 access = group_access_relation(array->groups[j], 1, 1);
1778 access = isl_union_map_apply_domain(access,
1779 isl_union_map_copy(sched));
1781 acc = isl_map_from_union_map(access);
1782 pma = isl_pw_multi_aff_from_map(acc);
1783 isl_pw_multi_aff_foreach_piece(pma,
1784 &check_unroll, unroll);
1786 isl_pw_multi_aff_free(pma);
1790 for (i = gen->shared_len; i < len; ++i)
1791 if (unroll[i])
1792 break;
1794 if (i >= len)
1795 return sched;
1797 for (i = len; i < gen->thread_tiled_len; ++i)
1798 if (unroll[i])
1799 return sched;
1801 if (gen->any_force_private) {
1802 remove_private_tiles(gen);
1803 return sched;
1806 j = 0;
1807 for (i = 0; i < gen->shared_len; ++i)
1808 perm[i] = j++;
1809 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1810 if (!unroll[i])
1811 perm[i] = j++;
1812 gen->first_unroll = j - gen->shared_len;
1813 for (i = gen->shared_len; i < len; ++i)
1814 if (unroll[i])
1815 perm[i] = j++;
1817 dim = isl_union_map_get_space(sched);
1818 permute = permutation(dim, perm, gen->thread_tiled_len);
1819 sched = isl_union_map_apply_range(sched,
1820 isl_union_map_from_map(permute));
1822 return sched;
1825 /* Given a constraint
1827 * a(p,i) + j = g f(e)
1829 * or -a(p,i) - j = g f(e) if sign < 0,
1830 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1831 * a(p,i) is assumed to be an expression in only the parameters
1832 * and the input dimensions.
1834 static void extract_stride(__isl_keep isl_constraint *c,
1835 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1837 int i;
1838 isl_val *v;
1839 isl_space *space;
1840 unsigned nparam;
1841 unsigned nvar;
1842 isl_aff *aff;
1844 isl_val_free(bound->stride);
1845 bound->stride = isl_val_copy(stride);
1847 space = isl_constraint_get_space(c);
1848 space = isl_space_domain(space);
1850 nparam = isl_space_dim(space, isl_dim_param);
1851 nvar = isl_space_dim(space, isl_dim_set);
1853 v = isl_constraint_get_constant_val(c);
1854 if (sign < 0)
1855 v = isl_val_neg(v);
1856 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1857 aff = isl_aff_set_constant_val(aff, v);
1859 for (i = 0; i < nparam; ++i) {
1860 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1861 continue;
1862 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1863 if (sign < 0)
1864 v = isl_val_neg(v);
1865 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1868 for (i = 0; i < nvar; ++i) {
1869 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1870 continue;
1871 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1872 if (sign < 0)
1873 v = isl_val_neg(v);
1874 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1877 bound->shift = aff;
1880 /* Given an equality constraint of a map with a single output dimension j,
1881 * check if the constraint is of the form
1883 * a(p,i) + j = g f(e)
1885 * with a(p,i) an expression in the parameters and input dimensions
1886 * and f(e) an expression in the existentially quantified variables.
1887 * If so, and if g is larger than any such g from a previously considered
1888 * constraint, then call extract_stride to record the stride information
1889 * in bound.
1891 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1893 int i;
1894 isl_ctx *ctx;
1895 isl_val *v;
1896 unsigned n_div;
1897 struct gpu_array_bound *bound = user;
1899 ctx = isl_constraint_get_ctx(c);
1900 n_div = isl_constraint_dim(c, isl_dim_div);
1901 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1903 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1904 int s = isl_val_sgn(v);
1905 isl_val *stride = isl_val_zero(ctx);
1907 isl_val_free(v);
1908 for (i = 0; i < n_div; ++i) {
1909 v = isl_constraint_get_coefficient_val(c,
1910 isl_dim_div, i);
1911 stride = isl_val_gcd(stride, v);
1913 if (!isl_val_is_zero(stride) &&
1914 isl_val_gt(stride, bound->stride))
1915 extract_stride(c, bound, stride, s);
1917 isl_val_free(stride);
1918 } else
1919 isl_val_free(v);
1921 isl_constraint_free(c);
1922 return 0;
1925 /* Given contraints on an array index i, check if we can find
1926 * a shift a(p) and a stride g such that
1928 * a(p) + i = 0 mod g
1930 * If so, record the information in bound and apply the mapping
1931 * i -> (i + a(p))/g to the array index in bounds and return
1932 * the new constraints.
1933 * If not, simply return the original constraints.
1935 * If bounds is a subset of the space
1937 * D -> i
1939 * then the bound recorded in bound->shift is of the form
1941 * D -> s(D)
1943 * with s(D) equal to a(p) above.
1944 * Next, we construct a mapping of the form
1946 * [D -> i] -> [D -> (i + S(D))/g]
1948 * This mapping is computed as follows.
1949 * We first introduce "i" in the domain through precomposition
1950 * with [D -> i] -> D obtaining
1952 * [D -> i] -> s(D)
1954 * Adding [D -> i] -> i produces
1956 * [D -> i] -> i + s(D)
1958 * and the domain product with [D -> i] -> D yields
1960 * [D -> i] -> [D -> i + s(D)]
1962 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1964 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1965 __isl_take isl_basic_map *bounds)
1967 isl_space *space;
1968 isl_basic_map *hull;
1969 isl_basic_map *shift, *id, *bmap, *scale;
1970 isl_basic_set *bset;
1971 isl_aff *aff;
1973 bound->stride = NULL;
1975 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1977 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1979 isl_basic_map_free(hull);
1981 if (!bound->stride)
1982 return bounds;
1984 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1985 space = isl_basic_map_get_space(bounds);
1986 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1987 shift = isl_basic_map_apply_range(bmap, shift);
1988 space = isl_basic_map_get_space(bounds);
1989 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1990 shift = isl_basic_map_sum(id, shift);
1991 space = isl_basic_map_get_space(bounds);
1992 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1993 shift = isl_basic_map_range_product(id, shift);
1995 space = isl_space_domain(isl_basic_map_get_space(bounds));
1996 id = isl_basic_map_identity(isl_space_map_from_set(space));
1997 space = isl_space_range(isl_basic_map_get_space(bounds));
1998 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1999 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2000 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
2001 scale = isl_basic_map_from_aff(aff);
2002 scale = isl_basic_map_product(id, scale);
2004 bmap = isl_basic_map_apply_range(shift, scale);
2005 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
2006 bounds = isl_basic_set_unwrap(bset);
2008 return bounds;
2011 /* Data used in compute_array_dim_size and compute_size_in_direction.
2013 * pos is the position of the variable representing the array index,
2014 * i.e., the variable for which want to compute the size. This variable
2015 * is also the last variable in the set.
2017 struct gpu_size_info {
2018 isl_basic_set *bset;
2019 struct gpu_array_bound *bound;
2020 int pos;
2023 /* Given a constraint from the basic set describing the bounds on
2024 * an array index, check if it is a lower bound, say m i >= b(x), and,
2025 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
2026 * upper bound. If so, and if this bound is smaller than any bound
2027 * derived from earlier constraints, set the size to this bound on
2028 * the expression and the lower bound to ceil(b(x)/m).
2030 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
2032 struct gpu_size_info *size = user;
2033 unsigned nparam;
2034 unsigned n_div;
2035 isl_val *v;
2036 isl_aff *aff;
2037 isl_aff *lb;
2039 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
2040 n_div = isl_constraint_dim(c, isl_dim_div);
2042 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
2043 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
2044 isl_constraint_free(c);
2045 return 0;
2048 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
2049 aff = isl_aff_ceil(aff);
2051 lb = isl_aff_copy(aff);
2053 aff = isl_aff_neg(aff);
2054 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
2056 v = isl_basic_set_max_val(size->bset, aff);
2057 isl_aff_free(aff);
2059 if (isl_val_is_int(v)) {
2060 v = isl_val_add_ui(v, 1);
2061 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
2062 isl_val_free(size->bound->size);
2063 size->bound->size = isl_val_copy(v);
2064 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
2065 isl_aff_free(size->bound->lb);
2066 size->bound->lb = isl_aff_copy(lb);
2069 isl_val_free(v);
2070 isl_aff_free(lb);
2072 isl_constraint_free(c);
2074 return 0;
2077 /* Given a basic map "bounds" that maps parameters and input dimensions
2078 * to a single output dimension, look for an expression in the parameters
2079 * and input dimensions such that the range of the output dimension shifted
2080 * by this expression is a constant.
2082 * In particular, we currently only consider lower bounds on the output
2083 * dimension as candidate expressions.
2085 static int compute_array_dim_size(struct gpu_array_bound *bound,
2086 __isl_take isl_basic_map *bounds)
2088 struct gpu_size_info size;
2090 bounds = isl_basic_map_detect_equalities(bounds);
2091 bounds = check_stride(bound, bounds);
2093 bound->size = NULL;
2094 bound->lb = NULL;
2096 size.bound = bound;
2097 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2098 size.bset = isl_basic_map_wrap(bounds);
2099 size.bset = isl_basic_set_flatten(size.bset);
2100 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2101 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2102 &size);
2103 isl_basic_set_free(size.bset);
2105 return bound->size ? 0 : -1;
2108 /* Check if we can find a memory tile for the given array
2109 * based on the given accesses, and if so, put the results in "tile".
2111 * We project the accesses on each index in turn and look for a parametric
2112 * offset such that the size is constant.
2114 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2116 int i;
2118 for (i = 0; i < tile->n; ++i) {
2119 isl_map *access_i;
2120 isl_basic_map *hull;
2122 access_i = isl_map_copy(access);
2123 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2124 access_i = isl_map_project_out(access_i, isl_dim_out,
2125 1, tile->n - (i + 1));
2126 access_i = isl_map_compute_divs(access_i);
2127 hull = isl_map_simple_hull(access_i);
2128 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2129 return 0;
2132 return 1;
2135 /* Construct a map with input the shared tile loops and the loops that
2136 * will be wrapped around the threads that relates these later loops
2137 * to the thread indices and then projects them out.
2139 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2141 isl_map *priv;
2142 isl_map *tiling;
2143 isl_map *proj;
2144 isl_set *par;
2145 isl_space *dim;
2147 dim = isl_union_map_get_space(gen->shared_sched);
2149 if (gen->options->wrap)
2150 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2151 gen->shared_len, gen->n_block, gen->block_dim);
2152 else
2153 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2154 gen->shared_len, gen->n_block, gen->block_dim);
2156 priv = tiling;
2158 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2159 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2160 gen->n_block, "t");
2162 priv = isl_map_align_params(priv, isl_set_get_space(par));
2163 priv = isl_map_intersect_range(priv, par);
2165 dim = isl_map_get_space(priv);
2166 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2167 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2168 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2169 gen->shared_len);
2171 priv = isl_map_apply_range(priv, proj);
2173 return priv;
2176 /* Construct a map from domain_dim to domain_dim that increments
2177 * the dimension at position "pos" and leaves all other dimensions
2178 * constant.
2180 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2182 int i;
2183 int len = isl_space_dim(domain_dim, isl_dim_set);
2184 isl_space *dim;
2185 isl_basic_map *next;
2186 isl_local_space *ls;
2188 dim = isl_space_map_from_set(domain_dim);
2189 next = isl_basic_map_universe(isl_space_copy(dim));
2190 ls = isl_local_space_from_space(dim);
2192 for (i = 0; i < len; ++i) {
2193 isl_constraint *c;
2195 c = isl_equality_alloc(isl_local_space_copy(ls));
2196 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2197 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2198 if (i == pos)
2199 c = isl_constraint_set_constant_si(c, 1);
2200 next = isl_basic_map_add_constraint(next, c);
2203 isl_local_space_free(ls);
2205 return isl_map_from_basic_map(next);
2208 /* Check if the given access is coalesced.
2209 * That is, check whether incrementing the dimension that will get
2210 * wrapped over the last thread index results in incrementing
2211 * the last array index.
2213 * This function is only called for access relations without reuse and
2214 * kernels with at least one block dimension.
2216 static int access_is_coalesced(struct gpu_gen *gen,
2217 __isl_keep isl_union_map *access)
2219 isl_space *dim;
2220 isl_map *access_map;
2221 isl_map *next_thread_x;
2222 isl_map *next_element;
2223 isl_map *map;
2224 int coalesced;
2226 access = isl_union_map_copy(access);
2227 access = isl_union_map_apply_domain(access,
2228 isl_union_map_copy(gen->tiled_sched));
2229 access_map = isl_map_from_union_map(access);
2231 dim = isl_map_get_space(access_map);
2232 dim = isl_space_domain(dim);
2233 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2235 dim = isl_map_get_space(access_map);
2236 dim = isl_space_range(dim);
2237 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2239 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2240 map = isl_map_apply_range(map, access_map);
2242 coalesced = isl_map_is_subset(map, next_element);
2244 isl_map_free(next_element);
2245 isl_map_free(map);
2247 return coalesced;
2250 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2251 * dimensions of the computed schedule, check if it is bijective for
2252 * fixed values of the first gen->shared_len dimensions.
2253 * We perform this check by equating these dimensions to parameters.
2255 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2257 int res;
2258 isl_set *par;
2259 isl_space *space;
2261 access = isl_map_copy(access);
2262 space = isl_space_params(isl_map_get_space(access));
2263 par = parametrization(space, gen->shared_len + gen->n_block,
2264 0, gen->shared_len, "s");
2265 access = isl_map_intersect_domain(access, par);
2266 res = isl_map_is_bijective(access);
2267 isl_map_free(access);
2269 return res;
2272 /* Look for the last shared tile loop that affects the offset of "tile"
2273 * and return the result.
2274 * If there is no such loop, then return the index of the loop
2275 * before the first shared tile loop, in particular gen->tile_first - 1.
2277 static int compute_tile_last_shared(struct gpu_gen *gen,
2278 struct gpu_array_tile *tile)
2280 int i, j;
2282 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2283 for (i = 0; i < tile->n; ++i) {
2284 isl_aff *lb;
2285 isl_aff *shift;
2287 lb = tile->bound[i].lb;
2288 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2289 break;
2291 shift = tile->bound[i].shift;
2292 if (!shift)
2293 continue;
2294 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2295 break;
2297 if (i < tile->n)
2298 break;
2301 return j;
2304 /* Look for the last shared tile loop that affects the offset of the
2305 * shared or private tile and store the result in group->last_shared.
2306 * If there is no such loop, then group->last_shared is set to a value
2307 * before the first shared tile loop, in particular gen->tile_first - 1.
2308 * If there is no tile defined on the array reference group,
2309 * then set group->last_shared to gen->shared_len - 1.
2311 static void set_last_shared(struct gpu_gen *gen,
2312 struct gpu_array_ref_group *group)
2314 struct gpu_array_tile *tile;
2316 group->last_shared = gen->shared_len - 1;
2318 tile = group->private_tile;
2319 if (!tile)
2320 tile = group->shared_tile;
2321 if (!tile)
2322 return;
2324 group->last_shared = compute_tile_last_shared(gen, tile);
2327 /* Compute the size of the tile specified by "tile"
2328 * in number of elements and return the result.
2330 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2332 int i;
2333 isl_val *size;
2335 size = isl_val_one(ctx);
2337 for (i = 0; i < tile->n; ++i)
2338 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2340 return size;
2343 /* If max_shared_memory is not set to infinity (-1), then make
2344 * sure that the total amount of shared memory required by the
2345 * array reference groups mapped to shared memory is no larger
2346 * than this maximum.
2348 * We apply a greedy approach and discard (keep in global memory)
2349 * those groups that would result in a total memory size that
2350 * is larger than the maximum.
2352 * This function should be called after any function that may
2353 * affect the decision on whether to place a reference group
2354 * in private, shared or global memory.
2356 static void check_shared_memory_bound(struct gpu_gen *gen)
2358 int i, j;
2359 isl_val *left, *size;
2361 if (gen->options->max_shared_memory < 0)
2362 return;
2364 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2366 for (i = 0; i < gen->prog->n_array; ++i) {
2367 struct gpu_array_info *array = &gen->prog->array[i];
2369 for (j = 0; j < array->n_group; ++j) {
2370 struct gpu_array_ref_group *group;
2372 group = array->groups[j];
2373 if (group->private_tile)
2374 continue;
2375 if (!group->shared_tile)
2376 continue;
2378 size = tile_size(gen->ctx, group->shared_tile);
2379 size = isl_val_mul_ui(size, array->size);
2381 if (isl_val_le(size, left)) {
2382 left = isl_val_sub(left, size);
2383 continue;
2385 isl_val_free(size);
2387 group->shared_tile = free_tile(group->shared_tile);
2391 isl_val_free(left);
2394 /* Given a description of an array tile "tile" and the "space"
2396 * { D -> A }
2398 * where D represents the first shared_len schedule dimensions
2399 * and A represents the array, construct an isl_multi_aff
2401 * { [D[i] -> A[a]] -> A'[a'] }
2403 * with A' a scaled down copy of A according to the shifts and strides
2404 * in "tile". In particular,
2406 * a' = (a + shift(i))/stride
2408 * "insert_array" represents
2410 * { [D -> A] -> D }
2412 * and is used to insert A into the domain of functions that only
2413 * reference D.
2415 static __isl_give isl_multi_aff *strided_tile(
2416 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2417 __isl_keep isl_multi_aff *insert_array)
2419 int i;
2420 isl_ctx *ctx;
2421 isl_multi_aff *shift;
2422 isl_multi_val *stride;
2423 isl_space *space2;
2424 isl_local_space *ls;
2425 isl_multi_aff *tiling;
2427 ctx = isl_space_get_ctx(space);
2428 space2 = isl_space_domain(isl_space_copy(space));
2429 ls = isl_local_space_from_space(space2);
2430 space2 = isl_space_range(isl_space_copy(space));
2431 stride = isl_multi_val_zero(space2);
2432 shift = isl_multi_aff_zero(isl_space_copy(space));
2434 for (i = 0; i < tile->n; ++i) {
2435 struct gpu_array_bound *bound = &tile->bound[i];
2436 isl_val *stride_i;
2437 isl_aff *shift_i;
2439 if (tile->bound[i].shift) {
2440 stride_i = isl_val_copy(bound->stride);
2441 shift_i = isl_aff_copy(bound->shift);
2442 } else {
2443 stride_i = isl_val_one(ctx);
2444 shift_i = isl_aff_zero_on_domain(
2445 isl_local_space_copy(ls));
2448 stride = isl_multi_val_set_val(stride, i, stride_i);
2449 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2451 isl_local_space_free(ls);
2453 shift = isl_multi_aff_pullback_multi_aff(shift,
2454 isl_multi_aff_copy(insert_array));
2456 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2457 tiling = isl_multi_aff_add(tiling, shift);
2458 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2460 return tiling;
2463 /* Compute a tiling for the array reference group "group".
2465 * The tiling is of the form
2467 * { [D[i] -> A[a]] -> T[t] }
2469 * where D represents the first shared_len schedule dimensions,
2470 * A represents the global array and T represents the shared or
2471 * private memory tile. The name of T is the name of the local
2472 * array.
2474 * If there is any stride in the accesses, then the mapping is
2476 * t = (a + shift(i))/stride - lb(i)
2478 * otherwise, it is simply
2480 * t = a - lb(i)
2482 static void compute_group_tiling(struct gpu_array_ref_group *group)
2484 int i;
2485 struct gpu_array_tile *tile;
2486 struct gpu_array_info *array = group->array;
2487 isl_space *space;
2488 isl_multi_aff *tiling, *lb, *insert_array;
2489 isl_printer *p;
2490 char *local_name;
2492 tile = group->private_tile;
2493 if (!tile)
2494 tile = group->shared_tile;
2495 if (!tile)
2496 return;
2498 space = isl_map_get_space(group->access);
2499 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2501 for (i = 0; i < tile->n; ++i)
2502 if (tile->bound[i].shift)
2503 break;
2505 if (i < tile->n)
2506 tiling = strided_tile(tile, space, insert_array);
2507 else
2508 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2510 lb = isl_multi_aff_zero(space);
2511 for (i = 0; i < tile->n; ++i) {
2512 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2513 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2515 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2517 tiling = isl_multi_aff_sub(tiling, lb);
2519 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2520 p = print_array_name(p, group);
2521 local_name = isl_printer_get_str(p);
2522 isl_printer_free(p);
2523 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2524 free(local_name);
2526 tile->tiling = tiling;
2529 /* Compute a tiling for all the array reference groups.
2531 static void compute_group_tilings(struct gpu_gen *gen)
2533 int i, j;
2535 for (i = 0; i < gen->prog->n_array; ++i) {
2536 struct gpu_array_info *array = &gen->prog->array[i];
2538 for (j = 0; j < array->n_group; ++j)
2539 compute_group_tiling(array->groups[j]);
2543 /* Fill up the groups array with singleton groups, i.e., one group
2544 * per reference, initializing the array, access, write, n_ref and refs fields.
2545 * In particular the access field is initialized to the scheduled
2546 * access relation of the array reference.
2548 * Return the number of elements initialized, i.e., the number of
2549 * active references in the current kernel.
2551 static int populate_array_references(struct gpu_array_info *array,
2552 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2554 int i;
2555 int n;
2556 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2558 n = 0;
2559 for (i = 0; i < array->n_ref; ++i) {
2560 isl_union_map *umap;
2561 isl_map *map;
2562 struct gpu_array_ref_group *group;
2563 struct gpu_stmt_access *access = array->refs[i];
2565 map = isl_map_copy(access->access);
2566 umap = isl_union_map_from_map(map);
2567 umap = isl_union_map_apply_domain(umap,
2568 isl_union_map_copy(sched));
2570 if (isl_union_map_is_empty(umap)) {
2571 isl_union_map_free(umap);
2572 continue;
2575 map = isl_map_from_union_map(umap);
2576 map = isl_map_detect_equalities(map);
2578 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2579 assert(group);
2580 group->array = array;
2581 group->access = map;
2582 group->write = access->write;
2583 group->exact_write = access->exact_write;
2584 group->slice = access->n_index < array->n_index;
2585 group->refs = &array->refs[i];
2586 group->n_ref = 1;
2588 groups[n++] = group;
2591 return n;
2594 /* If group->n_ref == 1, then group->refs was set by
2595 * populate_array_references to point directly into
2596 * group->array->refs and should not be freed.
2597 * If group->n_ref > 1, then group->refs was set by join_groups
2598 * to point to a newly allocated array.
2600 static void free_array_ref_group(struct gpu_array_ref_group *group)
2602 if (!group)
2603 return;
2604 free_tile(group->shared_tile);
2605 free_tile(group->private_tile);
2606 isl_map_free(group->access);
2607 if (group->n_ref > 1)
2608 free(group->refs);
2609 free(group);
2612 /* Given a map where the input dimensions represent the tile loops,
2613 * eliminate the innermost of those that have a fixed value
2614 * until we reach one that does not (obviously) have a fixed value.
2616 static __isl_give isl_map *eliminate_fixed_inner_loops(
2617 __isl_take isl_map *access)
2619 int i, n;
2621 n = isl_map_dim(access, isl_dim_in);
2623 for (i = n - 1; i >= 0; --i) {
2624 if (!map_plain_is_fixed(access, isl_dim_in, i))
2625 break;
2626 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2628 return access;
2631 /* Check if the access relations of group1 and group2 overlap within
2632 * the innermost loop. In particular, ignore any inner dimension
2633 * with a fixed value.
2634 * The copying to and from shared memory will be performed within
2635 * the innermost actual loop so we are only allowed to consider
2636 * the dimensions up to that innermost loop while checking whether
2637 * two access relations overlap.
2639 static int accesses_overlap(struct gpu_array_ref_group *group1,
2640 struct gpu_array_ref_group *group2)
2642 int empty;
2643 isl_map *access1, *access2;
2645 access1 = isl_map_copy(group1->access);
2646 access1 = eliminate_fixed_inner_loops(access1);
2647 access2 = isl_map_copy(group2->access);
2648 access2 = eliminate_fixed_inner_loops(access2);
2649 access1 = isl_map_intersect(access1, access2);
2650 empty = isl_map_is_empty(access1);
2651 isl_map_free(access1);
2653 return !empty;
2656 /* Combine the given two groups into a single group, containing
2657 * the references of both groups.
2659 static struct gpu_array_ref_group *join_groups(
2660 struct gpu_array_ref_group *group1,
2661 struct gpu_array_ref_group *group2)
2663 int i;
2664 isl_ctx *ctx;
2665 struct gpu_array_ref_group *group;
2667 ctx = isl_map_get_ctx(group1->access);
2668 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2669 assert(group);
2670 group->array = group1->array;
2671 group->access = isl_map_union(isl_map_copy(group1->access),
2672 isl_map_copy(group2->access));
2673 group->write = group1->write || group2->write;
2674 group->exact_write = group1->exact_write && group2->exact_write;
2675 group->slice = group1->slice || group2->slice;
2676 group->n_ref = group1->n_ref + group2->n_ref;
2677 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2678 group->n_ref);
2679 assert(group->refs);
2680 for (i = 0; i < group1->n_ref; ++i)
2681 group->refs[i] = group1->refs[i];
2682 for (i = 0; i < group2->n_ref; ++i)
2683 group->refs[group1->n_ref + i] = group2->refs[i];
2685 return group;
2688 /* Combine the given two groups into a single group and free
2689 * the original two groups.
2691 static struct gpu_array_ref_group *join_groups_and_free(
2692 struct gpu_array_ref_group *group1,
2693 struct gpu_array_ref_group *group2)
2695 struct gpu_array_ref_group *group;
2697 group = join_groups(group1, group2);
2698 free_array_ref_group(group1);
2699 free_array_ref_group(group2);
2700 return group;
2703 /* Report that the array reference group with the given access relation
2704 * is not mapped to shared memory in the given kernel because
2705 * it does not exhibit any reuse and is considered to be coalesced.
2707 static void report_no_reuse_and_coalesced(struct ppcg_kernel *kernel,
2708 __isl_keep isl_union_map *access)
2710 isl_ctx *ctx;
2711 isl_printer *p;
2713 ctx = isl_union_map_get_ctx(access);
2714 p = isl_printer_to_file(ctx, stdout);
2715 p = isl_printer_print_str(p, "Array reference group ");
2716 p = isl_printer_print_union_map(p, access);
2717 p = isl_printer_print_str(p,
2718 " not considered for mapping to shared memory in kernel");
2719 p = isl_printer_print_int(p, kernel->id);
2720 p = isl_printer_print_str(p,
2721 " because it exhibits no reuse and is considered to be coalesced");
2722 p = isl_printer_end_line(p);
2723 isl_printer_free(p);
2726 /* Compute the private and/or shared memory tiles for the array
2727 * reference group "group" of array "array".
2728 * Return 0 on success and -1 on error.
2730 * If the array is a read-only scalar or if the user requested
2731 * not to use shared or private memory, then we do not need to do anything.
2733 * If any reference in the reference group accesses more than one element,
2734 * then we would have to make sure that the layout in shared memory
2735 * is the same as that in global memory. Since we do not handle this yet
2736 * (and it may not even be possible), we refuse to map to private or
2737 * shared memory in such cases.
2739 * If the array group involves any may writes (that are not must writes),
2740 * then we would have to make sure that we load the data into shared/private
2741 * memory first in case the data is not written by the kernel
2742 * (but still written back out to global memory).
2743 * Since we don't have any such mechanism at the moment, we don't
2744 * compute shared/private tiles for groups involving may writes.
2746 * We only try to compute a shared memory tile if there is any reuse
2747 * or if the access is not coalesced.
2749 * For computing a private memory tile, we also require that there is
2750 * some reuse. Moreover, we require that the access is private
2751 * to the thread. That is, we check that any given array element
2752 * is only accessed by a single thread.
2753 * We compute an access relation that maps the shared tile loop iterators
2754 * and the shared point loop iterators that will be wrapped over the
2755 * threads to the array elements.
2756 * We actually check that those iterators that will be wrapped
2757 * partition the array space. This check is stricter than necessary
2758 * since several iterations may be mapped onto the same thread
2759 * and then they could be allowed to access the same memory elements,
2760 * but our check does not allow this situation.
2762 * We also check that the index expression only depends on parallel
2763 * loops. That way, we can move those loops innermost and unroll them.
2764 * Again, we use a test that is stricter than necessary.
2765 * We actually check whether the index expression only depends
2766 * on the iterators that are wrapped over the threads.
2767 * These are necessarily parallel, but there may be more parallel loops.
2769 * Combining the injectivity of the first test with the single-valuedness
2770 * of the second test, we simply test for bijectivity.
2772 * If the array is marked force_private, then we bypass all checks
2773 * and assume we can (and should) use registers.
2775 * If it turns out we can (or have to) use registers, we compute
2776 * the private memory tile size using can_tile, after introducing a dependence
2777 * on the thread indices.
2779 static int compute_group_bounds_core(struct gpu_gen *gen,
2780 struct gpu_array_ref_group *group)
2782 isl_ctx *ctx = isl_space_get_ctx(group->array->space);
2783 isl_union_map *access;
2784 int n_index = group->array->n_index;
2785 int no_reuse, coalesced;
2786 isl_map *acc;
2787 int force_private = group->array->force_private;
2788 int use_shared = gen->options->use_shared_memory && gen->n_block > 0;
2789 int use_private = force_private || gen->options->use_private_memory;
2791 if (!use_shared && !use_private)
2792 return 0;
2793 if (gpu_array_is_read_only_scalar(group->array))
2794 return 0;
2795 if (!force_private && !group->exact_write)
2796 return 0;
2797 if (group->slice)
2798 return 0;
2800 access = group_access_relation(group, 1, 1);
2801 no_reuse = isl_union_map_is_injective(access);
2802 if (use_shared && no_reuse)
2803 coalesced = access_is_coalesced(gen, access);
2805 if (gen->options->debug->verbose && use_shared && no_reuse && coalesced)
2806 report_no_reuse_and_coalesced(gen->kernel, access);
2808 if (use_shared && (!no_reuse || !coalesced)) {
2809 group->shared_tile = create_tile(ctx, group->array->n_index);
2810 if (!can_tile(group->access, group->shared_tile))
2811 group->shared_tile = free_tile(group->shared_tile);
2814 if (!force_private && (!use_private || no_reuse)) {
2815 isl_union_map_free(access);
2816 return 0;
2819 access = isl_union_map_apply_domain(access,
2820 isl_union_map_copy(gen->shared_sched));
2822 acc = isl_map_from_union_map(access);
2824 if (!force_private && !access_is_bijective(gen, acc)) {
2825 isl_map_free(acc);
2826 return 0;
2829 group->private_tile = create_tile(gen->ctx, n_index);
2830 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2831 if (!can_tile(acc, group->private_tile))
2832 group->private_tile = free_tile(group->private_tile);
2834 isl_map_free(acc);
2836 if (force_private && !group->private_tile)
2837 isl_die(ctx, isl_error_internal,
2838 "unable to map array reference group to registers",
2839 return -1);
2841 return 0;
2844 /* Compute the private and/or shared memory tiles for the array
2845 * reference group "group" of array "array" and set last_shared.
2846 * Return 0 on success and -1 on error.
2848 static int compute_group_bounds(struct gpu_gen *gen,
2849 struct gpu_array_ref_group *group)
2851 if (compute_group_bounds_core(gen, group) < 0)
2852 return -1;
2853 set_last_shared(gen, group);
2855 return 0;
2858 /* If two groups have overlapping access relations (as determined by
2859 * the "overlap" function) and if one of them involves a write,
2860 * then merge the two groups into one.
2861 * If "compute_bounds" is set, then call compute_group_bounds
2862 * on the merged groups.
2864 * Return the updated number of groups.
2865 * Return -1 on error.
2867 static int group_writes(struct gpu_gen *gen,
2868 int n, struct gpu_array_ref_group **groups,
2869 int (*overlap)(struct gpu_array_ref_group *group1,
2870 struct gpu_array_ref_group *group2), int compute_bounds)
2872 int i, j;
2874 for (i = 0; i < n; ++i) {
2875 for (j = n - 1; j > i; --j) {
2876 if (!groups[i]->write && !groups[j]->write)
2877 continue;
2879 if (!overlap(groups[i], groups[j]))
2880 continue;
2882 groups[i] = join_groups_and_free(groups[i], groups[j]);
2883 if (j != n - 1)
2884 groups[j] = groups[n - 1];
2885 groups[n - 1] = NULL;
2886 n--;
2888 if (compute_bounds &&
2889 compute_group_bounds(gen, groups[i]) < 0)
2890 return -1;
2894 return n;
2897 /* If two groups have overlapping access relations (within the innermost
2898 * loop) and if one of them involves a write, then merge the two groups
2899 * into one.
2901 * Return the updated number of groups.
2903 static int group_overlapping_writes(struct gpu_gen *gen,
2904 int n, struct gpu_array_ref_group **groups)
2906 return group_writes(gen, n, groups, &accesses_overlap, 0);
2909 /* Check if the access relations of group1 and group2 overlap within
2910 * the outermost min(group1->last_shared, group2->last_shared) loops.
2912 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2913 struct gpu_array_ref_group *group2)
2915 int last_shared;
2916 int dim;
2917 int empty;
2918 isl_map *map_i, *map_j, *map;
2920 last_shared = group1->last_shared;
2921 if (group2->last_shared < last_shared)
2922 last_shared = group2->last_shared;
2923 map_i = isl_map_copy(group1->access);
2924 dim = isl_map_dim(map_i, isl_dim_in);
2925 map_i = isl_map_eliminate(map_i, isl_dim_in,
2926 last_shared + 1, dim - (last_shared + 1));
2927 map_j = isl_map_copy(group2->access);
2928 map_j = isl_map_eliminate(map_j, isl_dim_in,
2929 last_shared + 1, dim - (last_shared + 1));
2930 map = isl_map_intersect(map_i, map_j);
2931 empty = isl_map_is_empty(map);
2932 isl_map_free(map);
2934 return !empty;
2937 /* If two groups have overlapping access relations (within the outer
2938 * last_shared loops) and if one of them involves a write,
2939 * then merge the two groups into one.
2941 * Return the updated number of groups.
2943 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2944 struct gpu_array_ref_group **groups)
2946 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2949 /* Is the size of the tile specified by "tile" smaller than the sum of
2950 * the sizes of the tiles specified by "tile1" and "tile2"?
2952 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
2953 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2955 int smaller;
2956 isl_val *size, *size1, *size2;
2958 size = tile_size(ctx, tile);
2959 size1 = tile_size(ctx, tile1);
2960 size2 = tile_size(ctx, tile2);
2962 size = isl_val_sub(size, size1);
2963 size = isl_val_sub(size, size2);
2964 smaller = isl_val_is_neg(size);
2966 isl_val_free(size);
2968 return smaller;
2971 /* Given an initial grouping of array references and shared memory tiles
2972 * for each group that allows for a shared memory tile, merge two groups
2973 * if both have a shared memory tile, the merged group also has
2974 * a shared memory tile and the size of the tile for the merge group
2975 * is smaller than the sum of the tile sizes of the individual groups.
2977 * If merging two groups decreases the "last_shared" dimension of
2978 * one or both of the two groups, then we need to check for overlapping
2979 * writes again.
2981 * Return the number of groups after merging.
2982 * Return -1 on error.
2984 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2985 struct gpu_array_info *array, int n,
2986 struct gpu_array_ref_group **groups)
2988 int i, j;
2989 int recompute_overlap = 0;
2990 isl_ctx *ctx = isl_space_get_ctx(array->space);
2992 for (i = 0; i < n; ++i) {
2993 if (!groups[i]->shared_tile)
2994 continue;
2995 for (j = n - 1; j > i; --j) {
2996 isl_map *map;
2997 int empty;
2998 struct gpu_array_ref_group *group;
3000 if (!groups[j]->shared_tile)
3001 continue;
3003 map = isl_map_intersect(isl_map_copy(groups[i]->access),
3004 isl_map_copy(groups[j]->access));
3005 empty = isl_map_is_empty(map);
3006 isl_map_free(map);
3008 if (empty)
3009 continue;
3011 group = join_groups(groups[i], groups[j]);
3012 if (compute_group_bounds(gen, group) < 0) {
3013 free_array_ref_group(group);
3014 return -1;
3016 if (!group->shared_tile ||
3017 !smaller_tile(ctx, group->shared_tile,
3018 groups[i]->shared_tile,
3019 groups[j]->shared_tile)) {
3020 free_array_ref_group(group);
3021 continue;
3024 if (group->last_shared < groups[i]->last_shared ||
3025 group->last_shared < groups[j]->last_shared)
3026 recompute_overlap = 1;
3027 free_array_ref_group(groups[i]);
3028 free_array_ref_group(groups[j]);
3029 groups[i] = group;
3030 if (j != n - 1)
3031 groups[j] = groups[n - 1];
3032 n--;
3036 if (recompute_overlap)
3037 n = group_last_shared_overlapping_writes(gen, n, groups);
3038 return n;
3041 /* Set array->n_group and array->groups to n and groups.
3043 * Additionally, set the "nr" field of each group
3044 * and the "group" field of each reference in each group.
3046 static void set_array_groups(struct gpu_array_info *array,
3047 int n, struct gpu_array_ref_group **groups)
3049 int i, j;
3051 array->n_group = n;
3052 array->groups = groups;
3054 for (i = 0; i < n; ++i) {
3055 groups[i]->nr = i;
3057 for (j = 0; j < groups[i]->n_ref; ++j)
3058 groups[i]->refs[j]->group = i;
3062 /* Group array references that should be considered together when
3063 * deciding whether to access them from private, shared or global memory.
3064 * Return -1 on error.
3066 * In particular, if two array references overlap and if one of them
3067 * is a write, then the two references are grouped together.
3068 * We first perform an initial grouping based only on the access relation.
3069 * After computing shared and private memory tiles, we check for
3070 * overlapping writes again, but this time taking into account
3071 * the "last_shared" property.
3073 * Furthermore, if two groups admit a shared memory tile and if the
3074 * combination of the two also admits a shared memory tile, we merge
3075 * the two groups.
3077 * If the array contains structures, then there is no need to compute
3078 * reference groups since we do not map such arrays to private or shared
3079 * memory.
3081 static int group_array_references(struct gpu_gen *gen,
3082 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
3084 int i;
3085 int n;
3086 isl_ctx *ctx = isl_union_map_get_ctx(sched);
3087 struct gpu_array_ref_group **groups;
3089 if (array->has_compound_element)
3090 return 0;
3092 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
3093 array->n_ref);
3094 if (!groups)
3095 return -1;
3097 n = populate_array_references(array, sched, groups);
3099 n = group_overlapping_writes(gen, n, groups);
3101 for (i = 0; i < n; ++i)
3102 if (compute_group_bounds(gen, groups[i]) < 0)
3103 n = -1;
3105 n = group_last_shared_overlapping_writes(gen, n, groups);
3107 n = group_common_shared_memory_tile(gen, array, n, groups);
3109 set_array_groups(array, n, groups);
3111 if (n >= 0)
3112 return 0;
3114 for (i = 0; i < array->n_ref; ++i)
3115 free_array_ref_group(groups[i]);
3116 return -1;
3119 /* Take tiled_sched, project it onto the shared tile loops and
3120 * the loops that will be wrapped over the threads and
3121 * store the result in gen->shared_sched.
3122 * Also compute a projection that projects out the loops that will be
3123 * wrapped over the threads and store this projection in gen->shared_proj.
3125 static void compute_shared_sched(struct gpu_gen *gen)
3127 isl_space *dim;
3128 isl_map *proj;
3129 isl_set *par;
3130 isl_union_map *sched;
3132 sched = isl_union_map_copy(gen->tiled_sched);
3134 dim = isl_union_map_get_space(sched);
3135 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
3136 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3138 dim = isl_union_map_get_space(sched);
3139 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
3141 gen->shared_sched = sched;
3142 gen->shared_proj = isl_union_map_from_map(proj);
3145 /* For each scalar in the input program, check if there are any
3146 * order dependences active inside the current kernel, within
3147 * the same iteration of the host schedule.
3148 * If so, mark the scalar as force_private so that it will be
3149 * mapped to a register.
3151 static void check_scalar_live_ranges(struct gpu_gen *gen)
3153 int i;
3154 isl_map *proj;
3155 isl_union_map *sched;
3156 isl_union_set *domain;
3157 isl_union_map *same_host_iteration;
3159 gen->any_force_private = 0;
3161 if (!gen->options->live_range_reordering)
3162 return;
3164 sched = gen->shared_sched;
3165 sched = isl_union_map_universe(isl_union_map_copy(sched));
3166 domain = isl_union_map_domain(sched);
3168 sched = isl_union_map_copy(gen->sched);
3169 proj = projection(isl_union_map_get_space(sched),
3170 gen->untiled_len, gen->tile_first);
3171 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3172 same_host_iteration = isl_union_map_apply_range(sched,
3173 isl_union_map_reverse(isl_union_map_copy(sched)));
3175 for (i = 0; i < gen->prog->n_array; ++i) {
3176 struct gpu_array_info *array = &gen->prog->array[i];
3177 isl_union_map *order;
3179 array->force_private = 0;
3180 if (array->n_index != 0)
3181 continue;
3182 order = isl_union_map_copy(array->dep_order);
3183 order = isl_union_map_intersect_domain(order,
3184 isl_union_set_copy(domain));
3185 order = isl_union_map_intersect_range(order,
3186 isl_union_set_copy(domain));
3187 order = isl_union_map_intersect(order,
3188 isl_union_map_copy(same_host_iteration));
3189 if (!isl_union_map_is_empty(order)) {
3190 array->force_private = 1;
3191 gen->any_force_private = 1;
3193 isl_union_map_free(order);
3196 isl_union_map_free(same_host_iteration);
3197 isl_union_set_free(domain);
3200 /* Group references of all arrays in the program.
3202 static int group_references(struct gpu_gen *gen)
3204 int i;
3205 int r = 0;
3206 isl_union_map *sched;
3208 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3209 isl_union_map_copy(gen->shared_proj));
3211 for (i = 0; i < gen->prog->n_array; ++i) {
3212 r = group_array_references(gen, &gen->prog->array[i], sched);
3213 if (r < 0)
3214 break;
3217 isl_union_map_free(sched);
3219 return r;
3222 /* Free all array information that is local to the current kernel.
3224 static void free_local_array_info(struct gpu_gen *gen)
3226 int i, j;
3228 for (i = 0; i < gen->prog->n_array; ++i) {
3229 struct gpu_array_info *array = &gen->prog->array[i];
3231 for (j = 0; j < array->n_group; ++j)
3232 free_array_ref_group(array->groups[j]);
3233 free(array->groups);
3237 /* Compute the size of a bounding box around the origin and "set",
3238 * where "set" is assumed to contain only non-negative elements.
3239 * In particular, compute the maximal value of "set" in each direction
3240 * and add one.
3242 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
3243 __isl_keep isl_set *context)
3245 int i, n;
3246 isl_multi_pw_aff *mpa;
3248 n = isl_set_dim(set, isl_dim_set);
3249 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
3250 for (i = 0; i < n; ++i) {
3251 isl_space *space;
3252 isl_aff *one;
3253 isl_pw_aff *bound;
3255 bound = isl_set_dim_max(isl_set_copy(set), i);
3256 bound = isl_pw_aff_coalesce(bound);
3257 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
3259 space = isl_pw_aff_get_domain_space(bound);
3260 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
3261 one = isl_aff_add_constant_si(one, 1);
3262 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
3263 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
3265 isl_set_free(set);
3267 return mpa;
3270 /* Compute the effective grid size as a list of the sizes in each dimension.
3272 * The grid size specified by the user or set by default
3273 * in read_grid_sizes() and applied in tile_schedule(),
3274 * may be too large for the given code in the sense that
3275 * it may contain blocks that don't need to execute anything.
3276 * We therefore don't return this grid size, but instead the
3277 * smallest grid size that ensures that all blocks that actually
3278 * execute code are included in the grid.
3280 * We first extract a description of the grid, i.e., the possible values
3281 * of the block ids, from gen->tiled_sched.
3282 * The block ids are parameters in gen->tiled_sched.
3283 * We simply need to change them into set dimensions.
3285 * Then, for each block dimension, we compute the maximal value of the block id
3286 * and add one.
3288 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
3289 struct ppcg_kernel *kernel)
3291 int i;
3292 isl_set *grid;
3294 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
3295 grid = isl_set_from_params(grid);
3296 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
3297 for (i = 0; i < gen->n_grid; ++i) {
3298 int pos;
3299 char name[20];
3301 snprintf(name, sizeof(name), "b%d", i);
3302 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
3303 assert(pos >= 0);
3304 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
3305 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
3308 return extract_size(grid, kernel->context);
3311 /* Compute the size of a fixed bounding box around the origin and "set",
3312 * where "set" is assumed to contain only non-negative elements,
3313 * and store the results in "size".
3314 * In particular, compute the maximal value of "set" in each direction
3315 * and add one.
3317 static void extract_fixed_size(__isl_take isl_set *set, int *size)
3319 int i, n;
3320 isl_local_space *ls;
3321 isl_aff *obj;
3323 n = isl_set_dim(set, isl_dim_set);
3324 ls = isl_local_space_from_space(isl_set_get_space(set));
3325 obj = isl_aff_zero_on_domain(ls);
3326 for (i = 0; i < n; ++i) {
3327 isl_val *max;
3329 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
3330 max = isl_set_max_val(set, obj);
3331 size[i] = isl_val_get_num_si(max) + 1;
3332 isl_val_free(max);
3333 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
3335 isl_aff_free(obj);
3336 isl_set_free(set);
3339 /* Compute the effective block size as a list of the sizes in each dimension
3340 * and store the sizes in kernel->block_dim.
3342 * The block size specified by the user or set by default
3343 * in read_block_sizes() and applied in thread_tile_schedule(),
3344 * may be too large for the given code in the sense that
3345 * it may contain threads that don't need to execute anything.
3346 * We therefore don't store this block size in kernel->block_dim,
3347 * but instead the smallest block size that ensures that all threads
3348 * that actually execute code are included in the block.
3350 * The current implementation eliminates all parameters, ensuring
3351 * that the size is a fixed constant in each dimension.
3352 * In principle we could also compute parametric sizes.
3353 * We would have to make sure to project out all b%d and t%d parameters,
3354 * however.
3356 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3358 int i;
3359 int nparam;
3360 isl_set *block;
3361 isl_multi_pw_aff *mpa;
3363 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3364 block = isl_set_from_params(block);
3365 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3366 kernel->n_block = gen->n_block;
3367 for (i = 0; i < gen->n_block; ++i) {
3368 int pos;
3369 char name[20];
3371 snprintf(name, sizeof(name), "t%d", i);
3372 pos = isl_set_find_dim_by_name(block, isl_dim_param, name);
3373 assert(pos >= 0);
3374 block = isl_set_equate(block, isl_dim_param, pos,
3375 isl_dim_set, i);
3377 nparam = isl_set_dim(block, isl_dim_param);
3378 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3380 extract_fixed_size(block, kernel->block_dim);
3383 void ppcg_kernel_free(void *user)
3385 struct ppcg_kernel *kernel = user;
3386 int i;
3388 if (!kernel)
3389 return;
3391 isl_multi_pw_aff_free(kernel->grid_size);
3392 isl_set_free(kernel->context);
3393 isl_union_set_free(kernel->arrays);
3394 isl_space_free(kernel->space);
3395 isl_ast_node_free(kernel->tree);
3397 for (i = 0; i < kernel->n_array; ++i)
3398 isl_pw_aff_list_free(kernel->array[i].bound);
3399 free(kernel->array);
3401 for (i = 0; i < kernel->n_var; ++i) {
3402 free(kernel->var[i].name);
3403 isl_vec_free(kernel->var[i].size);
3405 free(kernel->var);
3407 free(kernel);
3410 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3411 struct ppcg_kernel_var *var)
3413 int j;
3414 struct gpu_array_tile *tile;
3415 isl_printer *p;
3416 char *name;
3418 var->array = group->array;
3420 tile = group->private_tile;
3421 var->type = ppcg_access_private;
3422 if (!tile) {
3423 tile = group->shared_tile;
3424 var->type = ppcg_access_shared;
3427 p = isl_printer_to_str(ctx);
3428 p = print_array_name(p, group);
3429 var->name = isl_printer_get_str(p);
3430 isl_printer_free(p);
3432 var->size = isl_vec_alloc(ctx, group->array->n_index);
3434 for (j = 0; j < group->array->n_index; ++j)
3435 var->size = isl_vec_set_element_val(var->size, j,
3436 isl_val_copy(tile->bound[j].size));
3439 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3441 int i, j, n;
3443 n = 0;
3444 for (i = 0; i < gen->prog->n_array; ++i) {
3445 struct gpu_array_info *array = &gen->prog->array[i];
3447 for (j = 0; j < array->n_group; ++j) {
3448 struct gpu_array_ref_group *group = array->groups[j];
3449 if (group->private_tile || group->shared_tile)
3450 ++n;
3454 kernel->n_var = n;
3455 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3456 assert(kernel->var);
3458 n = 0;
3459 for (i = 0; i < gen->prog->n_array; ++i) {
3460 struct gpu_array_info *array = &gen->prog->array[i];
3462 for (j = 0; j < array->n_group; ++j) {
3463 struct gpu_array_ref_group *group = array->groups[j];
3464 if (!group->private_tile && !group->shared_tile)
3465 continue;
3466 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3467 ++n;
3472 /* The sizes of the arrays on the host that have been computed by
3473 * extract_array_info may depend on the parameters. Use the extra
3474 * constraints on the parameters that are valid at "host_domain"
3475 * to simplify these expressions and store the results in kernel->array.
3477 * We only need these localized bounds for arrays that are accessed
3478 * by the current kernel. If we have found at least one reference group
3479 * then the array is accessed by the kernel. If the array has compound
3480 * elements then we skipped the construction of array reference groups.
3482 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3483 __isl_keep isl_set *host_domain)
3485 int i, j;
3486 isl_set *context;
3488 kernel->array = isl_calloc_array(gen->ctx,
3489 struct gpu_local_array_info, gen->prog->n_array);
3490 assert(kernel->array);
3491 kernel->n_array = gen->prog->n_array;
3493 context = isl_set_copy(host_domain);
3494 context = isl_set_params(context);
3496 for (i = 0; i < gen->prog->n_array; ++i) {
3497 struct gpu_array_info *array = &gen->prog->array[i];
3498 isl_pw_aff_list *local;
3500 if (array->n_group == 0 && !array->has_compound_element)
3501 continue;
3503 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3505 for (j = 0; j < array->n_index; ++j) {
3506 isl_pw_aff *pwaff;
3508 pwaff = isl_pw_aff_copy(array->bound[j]);
3509 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3510 local = isl_pw_aff_list_add(local, pwaff);
3513 kernel->array[i].n_index = array->n_index;
3514 kernel->array[i].bound = local;
3516 isl_set_free(context);
3519 /* Find the element in gen->stmt that has the given "id".
3520 * Return NULL if no such gpu_stmt can be found.
3522 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3524 int i;
3526 for (i = 0; i < prog->n_stmts; ++i) {
3527 if (id == prog->stmts[i].id)
3528 break;
3531 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3534 /* Set gen->tile_len and gen->n_parallel to those of the statement
3535 * affected by the first map (part of the schedule)
3536 * on which this function is called.
3537 * Because of the way the schedule is constructed, the other statements
3538 * in the list, if any, should have the same values for these properties.
3540 static int extract_tile_len(__isl_take isl_map *map, void *user)
3542 struct gpu_gen *gen = (struct gpu_gen *) user;
3543 isl_id *id;
3544 struct gpu_stmt *stmt;
3546 id = isl_map_get_tuple_id(map, isl_dim_in);
3547 stmt = find_stmt(gen->prog, id);
3548 isl_id_free(id);
3550 isl_map_free(map);
3552 if (!stmt)
3553 isl_die(gen->ctx, isl_error_unknown,
3554 "statement not found", return -1);
3556 gen->tile_len = stmt->tile_len;
3557 gen->n_parallel = stmt->n_parallel;
3559 return -1;
3562 void ppcg_kernel_stmt_free(void *user)
3564 int i;
3565 struct ppcg_kernel_stmt *stmt = user;
3567 if (!stmt)
3568 return;
3570 switch (stmt->type) {
3571 case ppcg_kernel_copy:
3572 isl_ast_expr_free(stmt->u.c.index);
3573 isl_ast_expr_free(stmt->u.c.local_index);
3574 break;
3575 case ppcg_kernel_domain:
3576 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
3577 break;
3578 case ppcg_kernel_sync:
3579 break;
3582 free(stmt);
3585 /* Set the options of "context" to
3587 * { space -> [x] : x >= first }
3589 static __isl_give isl_ast_build *set_unroll(
3590 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3591 int first)
3593 isl_ctx *ctx;
3594 isl_map *unroll;
3595 isl_union_map *opt;
3597 ctx = isl_ast_build_get_ctx(build);
3599 space = isl_space_from_domain(space);
3600 space = isl_space_add_dims(space, isl_dim_out, 1);
3601 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3602 unroll = isl_map_universe(space);
3603 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3604 opt = isl_union_map_from_map(unroll);
3606 build = isl_ast_build_set_options(build, opt);
3608 return build;
3611 /* Return a list of isl_ids of the form "prefix%d".
3613 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3614 int n, const char *prefix)
3616 int i;
3617 char name[10];
3618 isl_id_list *names;
3620 names = isl_id_list_alloc(ctx, n);
3621 for (i = 0; i < n; ++i) {
3622 isl_id *id;
3624 snprintf(name, sizeof(name), "%s%d", prefix, i);
3625 id = isl_id_alloc(ctx, name, NULL);
3626 names = isl_id_list_add(names, id);
3629 return names;
3632 /* Extend the schedule "schedule" with the part of "extension"
3633 * starting at "first" up to "len".
3635 static __isl_give isl_union_map *extend_schedule(
3636 __isl_take isl_union_map *schedule,
3637 __isl_take isl_union_map *extension, int first, int len)
3639 isl_space *space;
3640 isl_map *proj;
3641 isl_union_map *umap;
3642 isl_set *set;
3644 space = isl_union_map_get_space(schedule);
3645 space = isl_space_set_from_params(space);
3646 space = isl_space_add_dims(space, isl_dim_set, len);
3647 proj = isl_set_identity(isl_set_universe(space));
3648 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3649 extension = isl_union_map_apply_range(extension,
3650 isl_union_map_from_map(proj));
3652 schedule = isl_union_map_range_product(schedule, extension);
3654 return schedule;
3657 /* Return the gpu_stmt_access in the list "accesses" that corresponds
3658 * to "ref_id".
3660 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
3661 __isl_keep isl_id *ref_id)
3663 struct gpu_stmt_access *access;
3665 for (access = accesses; access; access = access->next)
3666 if (access->ref_id == ref_id)
3667 return access;
3669 return NULL;
3672 /* Return the index of the array called "name" in the list of arrays.
3674 static int find_array_index(struct gpu_gen *gen, const char *name)
3676 int i;
3678 for (i = 0; i < gen->prog->n_array; ++i)
3679 if (!strcmp(name, gen->prog->array[i].name))
3680 return i;
3682 return -1;
3685 /* Internal data structure for the index and AST expression transformation
3686 * callbacks for pet_stmt_build_ast_exprs.
3688 * "accesses" is the list of gpu_stmt_access in the statement.
3689 * "iterator_map" expresses the statement iterators in terms of
3690 * the AST loop iterators.
3691 * "sched2shared" expresses the first shared_len dimensions of
3692 * the computed schedule in terms of the AST loop iterators.
3694 * The following fields are set in transform_index and used in transform_expr.
3695 * "array" is the array that is being accessed.
3696 * "global" is set if the global array is accessed (rather than
3697 * shared/private memory).
3698 * "local_array" refers to information on the array specialized
3699 * to the current kernel.
3701 struct ppcg_transform_data {
3702 struct gpu_gen *gen;
3703 struct gpu_stmt_access *accesses;
3704 isl_pw_multi_aff *iterator_map;
3705 isl_pw_multi_aff *sched2shared;
3707 struct gpu_array_info *array;
3708 int global;
3709 struct gpu_local_array_info *local_array;
3712 /* Return the name of the outer array (of structs) accessed by "access".
3714 static const char *get_outer_array_name(__isl_keep isl_map *access)
3716 isl_space *space;
3717 const char *name;
3719 space = isl_space_range(isl_map_get_space(access));
3720 while (space && isl_space_is_wrapping(space))
3721 space = isl_space_domain(isl_space_unwrap(space));
3722 name = isl_space_get_tuple_name(space, isl_dim_set);
3723 isl_space_free(space);
3725 return name;
3728 /* Index transformation callback for pet_stmt_build_ast_exprs.
3730 * "index" expresses the array indices in terms of statement iterators
3732 * We first reformulate "index" in terms of the AST loop iterators.
3733 * Then we check if we are accessing the global array or
3734 * a shared/private copy. In the former case, we simply return
3735 * the updated index. If "index" is an affine expression rather
3736 * than an array access, then we also return the updated index here.
3738 * If no reference groups have been computed for the array,
3739 * then we can only be accessing the global array.
3741 * Otherwise, we apply the tiling to the index.
3742 * This tiling is of the form
3744 * [D -> A] -> T
3746 * The index is of the form
3748 * L -> A
3750 * We update the tiling to refer to the AST loop iterators
3752 * [L -> A] -> T
3754 * and modify index to keep track of those iterators
3756 * L -> [L -> A]
3758 * Combining these two yields a tiled index expression in terms
3759 * of the AST loop iterators
3761 * L -> T
3763 static __isl_give isl_multi_pw_aff *transform_index(
3764 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
3765 void *user)
3767 struct ppcg_transform_data *data = user;
3768 struct gpu_stmt_access *access;
3769 struct gpu_array_ref_group *group;
3770 struct gpu_array_tile *tile;
3771 isl_pw_multi_aff *iterator_map;
3772 int i;
3773 const char *name;
3774 isl_space *space;
3775 isl_multi_pw_aff *tiling;
3776 isl_pw_multi_aff *pma;
3777 isl_multi_pw_aff *mpa;
3779 data->array = NULL;
3781 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
3782 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
3784 access = find_access(data->accesses, ref_id);
3785 if (!access)
3786 return index;
3787 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
3788 return index;
3790 name = get_outer_array_name(access->access);
3791 i = find_array_index(data->gen, name);
3792 if (i < 0)
3793 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
3794 "cannot find array",
3795 return isl_multi_pw_aff_free(index));
3796 data->array = &data->gen->prog->array[i];
3797 data->local_array = &data->gen->kernel->array[i];
3799 if (access->group < 0) {
3800 data->global = 1;
3801 return index;
3804 group = data->array->groups[access->group];
3805 tile = group->private_tile;
3806 if (!tile)
3807 tile = group->shared_tile;
3808 data->global = !tile;
3809 if (!tile)
3810 return index;
3812 space = isl_space_range(isl_multi_pw_aff_get_space(index));
3813 space = isl_space_map_from_set(space);
3814 pma = isl_pw_multi_aff_identity(space);
3815 pma = isl_pw_multi_aff_product(
3816 isl_pw_multi_aff_copy(data->sched2shared), pma);
3817 tiling = isl_multi_pw_aff_from_multi_aff(
3818 isl_multi_aff_copy(tile->tiling));
3819 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
3821 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
3822 space = isl_space_map_from_set(space);
3823 mpa = isl_multi_pw_aff_identity(space);
3824 index = isl_multi_pw_aff_range_product(mpa, index);
3825 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
3827 return index;
3830 /* Dereference "expr" by adding an index [0].
3831 * The original "expr" is assumed not to have any indices.
3833 * If "expr" is a member access, then the dereferencing needs
3834 * to be applied to the structure argument of this member access.
3836 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
3838 isl_ctx *ctx;
3839 isl_ast_expr *arg0, *res;
3840 isl_ast_expr_list *list;
3842 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3843 if (!arg0)
3844 return isl_ast_expr_free(expr);
3845 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3846 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3847 isl_ast_expr *arg;
3849 arg = isl_ast_expr_get_op_arg(arg0, 0);
3850 arg = dereference(arg);
3851 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3852 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3854 return expr;
3856 isl_ast_expr_free(arg0);
3858 ctx = isl_ast_expr_get_ctx(expr);
3859 res = isl_ast_expr_from_val(isl_val_zero(ctx));
3860 list = isl_ast_expr_list_from_ast_expr(res);
3861 res = isl_ast_expr_get_op_arg(expr, 0);
3862 res = isl_ast_expr_access(res, list);
3863 isl_ast_expr_free(expr);
3865 return res;
3868 /* Linearize the index expression "expr" based on the array bounds
3869 * of "array".
3871 * That is, transform expression
3873 * A[i_0][i_1]...[i_n]
3875 * to
3877 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
3879 * where b_0, b_1, ..., b_n are the bounds on the array.
3881 * If the base of "expr" is a member access, then the linearization needs
3882 * to be applied to the structure argument of this member access.
3884 * In the base case, if "expr" has no arguments (other than the name of
3885 * the array), then we are passing an entire array to a function.
3886 * In this case, there is nothing to linearize.
3887 * Note that at this point an expression with no arguments can
3888 * only be an entire array because the scalar case and
3889 * the case of single struct are handled by the caller.
3891 * If the number of specified index expressions in "expr"
3892 * is smaller than the dimension of the accessed array,
3893 * then the missing i_j also do not appear in the linearized expression.
3894 * Furthermore, since such an expression does not refer to a single
3895 * element while the default linearized expression would refer to
3896 * a single element, we return the expression
3898 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
3900 * instead. Note that because of the special case handling above,
3901 * we can assume here that here that there is at least one index expression.
3903 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
3904 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
3906 int i, n;
3907 isl_ctx *ctx;
3908 isl_set *context;
3909 isl_ast_expr *arg0;
3910 isl_ast_expr *res;
3911 isl_ast_expr_list *list;
3912 isl_ast_build *build;
3914 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3915 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3916 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3917 isl_ast_expr *arg;
3919 arg = isl_ast_expr_get_op_arg(arg0, 0);
3920 arg = gpu_local_array_info_linearize_index(array, arg);
3921 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3922 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3924 return expr;
3926 isl_ast_expr_free(arg0);
3928 if (isl_ast_expr_get_op_n_arg(expr) == 1)
3929 return expr;
3931 ctx = isl_ast_expr_get_ctx(expr);
3932 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
3933 build = isl_ast_build_from_context(context);
3935 n = isl_ast_expr_get_op_n_arg(expr);
3936 res = isl_ast_expr_get_op_arg(expr, 1);
3937 for (i = 1; i < array->n_index; ++i) {
3938 isl_pw_aff *bound_i;
3939 isl_ast_expr *expr_i;
3941 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
3942 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
3943 res = isl_ast_expr_mul(res, expr_i);
3945 if (i + 1 >= n)
3946 continue;
3947 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
3948 res = isl_ast_expr_add(res, expr_i);
3951 isl_ast_build_free(build);
3953 if (1 + array->n_index > n) {
3954 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
3955 } else {
3956 list = isl_ast_expr_list_from_ast_expr(res);
3957 res = isl_ast_expr_get_op_arg(expr, 0);
3958 res = isl_ast_expr_access(res, list);
3961 isl_ast_expr_free(expr);
3963 return res;
3966 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
3968 * If the AST expression refers to a global scalar that is not
3969 * a read-only scalar, then its address was passed to the kernel and
3970 * we need to dereference it.
3972 * If the AST expression refers to an access to a global array,
3973 * then we linearize the access exploiting the bounds in data->local_array.
3975 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
3976 __isl_keep isl_id *id, void *user)
3978 struct ppcg_transform_data *data = user;
3980 if (!data->array)
3981 return expr;
3982 if (gpu_array_is_read_only_scalar(data->array))
3983 return expr;
3984 if (!data->global)
3985 return expr;
3986 if (data->array->n_index == 0)
3987 return dereference(expr);
3988 if (!data->array->linearize)
3989 return expr;
3991 return gpu_local_array_info_linearize_index(data->local_array, expr);
3994 /* This function is called for each instance of a user statement
3995 * in the kernel.
3997 * We attach a struct ppcg_kernel_stmt to the "node", containing
3998 * a computed AST expression for each access.
3999 * These AST expressions are computed from iterator_map,
4000 * which expresses the domain
4001 * elements in terms of the generated loops, and sched2shared,
4002 * which expresses the first shared_len dimensions of the schedule
4003 * computed by PPCG in terms of the generated loops.
4005 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
4006 __isl_keep isl_ast_build *build, void *user)
4008 struct ppcg_transform_data data;
4009 struct gpu_gen *gen = (struct gpu_gen *) user;
4010 struct ppcg_kernel_stmt *stmt;
4011 isl_id *id;
4012 isl_pw_multi_aff *sched2shared;
4013 isl_map *map;
4014 isl_pw_multi_aff *iterator_map;
4015 isl_ast_expr *expr, *arg;
4016 isl_union_map *schedule;
4018 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4019 if (!stmt)
4020 return isl_ast_node_free(node);
4022 expr = isl_ast_node_user_get_expr(node);
4023 arg = isl_ast_expr_get_op_arg(expr, 0);
4024 id = isl_ast_expr_get_id(arg);
4026 schedule = isl_ast_build_get_schedule(build);
4027 map = isl_map_reverse(isl_map_from_union_map(schedule));
4028 iterator_map = isl_pw_multi_aff_from_map(map);
4029 sched2shared = compute_sched_to_shared(gen,
4030 isl_pw_multi_aff_copy(iterator_map));
4032 stmt->type = ppcg_kernel_domain;
4033 stmt->u.d.stmt = find_stmt(gen->prog, id);
4034 if (!stmt->u.d.stmt)
4035 isl_die(gen->ctx, isl_error_internal,
4036 "statement not found", goto error);
4038 data.gen = gen;
4039 data.accesses = stmt->u.d.stmt->accesses;
4040 data.iterator_map = iterator_map;
4041 data.sched2shared = sched2shared;
4042 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
4043 build, &transform_index, &data,
4044 &transform_expr, &data);
4046 isl_id_free(id);
4047 isl_pw_multi_aff_free(iterator_map);
4048 isl_pw_multi_aff_free(sched2shared);
4049 isl_ast_expr_free(arg);
4050 isl_ast_expr_free(expr);
4052 id = isl_id_alloc(gen->ctx, NULL, stmt);
4053 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4054 return isl_ast_node_set_annotation(node, id);
4055 error:
4056 isl_id_free(id);
4057 isl_pw_multi_aff_free(iterator_map);
4058 ppcg_kernel_stmt_free(stmt);
4059 isl_pw_multi_aff_free(sched2shared);
4060 return isl_ast_node_free(node);
4063 /* This function is called when code has been generated for the shared
4064 * tile loops. The "schedule" refers only to the original statements.
4066 * We extend the schedule with that part of gen->local_sched that hasn't
4067 * been taken into account yet. This introduces parameters referring
4068 * to thread ids in the schedule, so we add them (with the appropriate
4069 * bounds to the context as well).
4070 * Finally, we set the appropriate unrolling options
4071 * if gen->first_unroll is set.
4073 static __isl_give isl_ast_node *create_domain_leaf(
4074 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
4075 void *user)
4077 struct gpu_gen *gen = (struct gpu_gen *) user;
4078 isl_space *space;
4079 isl_union_map *sched;
4080 isl_ast_node *tree;
4081 isl_set *set;
4082 isl_id_list *iterators;
4083 int n;
4085 schedule = extend_schedule(schedule,
4086 isl_union_map_copy(gen->local_sched),
4087 gen->shared_len, gen->thread_tiled_len);
4089 space = isl_ast_build_get_schedule_space(build);
4090 set = isl_set_universe(space);
4091 set = add_bounded_parameters(set, gen->kernel->n_block,
4092 gen->kernel->block_dim, "t");
4093 build = isl_ast_build_restrict(build, set);
4095 n = gen->thread_tiled_len - gen->shared_len;
4097 if (gen->first_unroll >= 0) {
4098 space = isl_space_set_alloc(gen->ctx, 0, n);
4099 build = set_unroll(build, space, gen->first_unroll);
4101 iterators = generate_names(gen->ctx, n, "c");
4102 build = isl_ast_build_set_iterators(build, iterators);
4103 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
4104 tree = isl_ast_build_ast_from_schedule(build, schedule);
4105 isl_ast_build_free(build);
4107 return tree;
4110 /* This function is called for each statement node in the AST of the code
4111 * for copying to or from shared/private memory.
4112 * Attach a pointer to a ppcg_kernel_stmt representing the copy
4113 * statement to the node.
4114 * The statement name is "read" or "write", depending on whether we are
4115 * reading from global memory or writing to global memory.
4116 * The name of the T space is {shared,private}_<array>.
4118 * The schedule is of the form
4120 * type[A -> T] -> L
4122 * where A refers to a piece of an array and T to the corresponding
4123 * shifted tile. We split this schedule into mappings L -> A and L -> T
4124 * and store the corresponding expressions in stmt->index and stmt->local_index,
4125 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
4127 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
4128 __isl_keep isl_ast_build *build, void *user)
4130 struct gpu_gen *gen = (struct gpu_gen *) user;
4131 struct ppcg_kernel_stmt *stmt;
4132 isl_id *id;
4133 isl_ast_expr *expr;
4134 isl_space *space;
4135 isl_map *access, *local_access, *map;
4136 isl_pw_multi_aff *pma;
4137 const char *type;
4138 int array_index;
4140 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4141 if (!stmt)
4142 return isl_ast_node_free(node);
4144 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
4145 type = isl_map_get_tuple_name(access, isl_dim_in);
4146 stmt->u.c.read = !strcmp(type, "read");
4147 access = isl_map_reverse(access);
4148 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
4149 local_access = isl_map_copy(access);
4151 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
4152 id = isl_map_get_tuple_id(access, isl_dim_out);
4153 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4154 access = isl_map_apply_range(access, map);
4155 pma = isl_pw_multi_aff_from_map(access);
4156 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4157 stmt->u.c.index = expr;
4159 map = isl_map_range_map(isl_map_universe(space));
4160 id = isl_map_get_tuple_id(local_access, isl_dim_out);
4161 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4162 local_access = isl_map_apply_range(local_access, map);
4163 pma = isl_pw_multi_aff_from_map(local_access);
4164 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4165 stmt->u.c.local_index = expr;
4167 stmt->u.c.array = gen->copy_group->array;
4168 array_index = stmt->u.c.array - gen->prog->array;
4169 stmt->u.c.local_array = &gen->kernel->array[array_index];
4170 stmt->type = ppcg_kernel_copy;
4172 id = isl_id_alloc(gen->ctx, NULL, stmt);
4173 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4174 return isl_ast_node_set_annotation(node, id);
4177 /* Given a schedule of the form
4179 * [S -> A] -> L
4181 * (with S the first shared_len dimensions of the computed schedule,
4182 * A the array and L the schedule correponding to the generated loops),
4183 * indicating where to copy the array elements that need to be copied,
4184 * construct code for performing the copying.
4186 * "group" is the array reference group that is being copied
4187 * "type" is either "read" or "write"
4188 * private is set if copying needs to be performed to/from registers
4190 * We first construct a mapping to a shifted tile of the array,
4192 * [S -> A] -> T(S,A) (1)
4194 * If private is set, then we also use this mapping as a schedule
4195 * (which is already thread-specific and will be completely unrolled).
4196 * Otherwise, we wrap/tile the range over the threads.
4197 * The result is
4199 * [S -> A] -> T'(S,A)
4201 * Combined with the given schedule, we have
4203 * [S -> A] -> [L -> T'(S,A)] (2)
4205 * From the shifted tile mapping, we construct a mapping
4207 * [S -> A] -> [A -> T(S,A)]
4209 * and apply it to the schedule (2), obtaining
4211 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
4213 * Note that we can project out S because it is uniquely defined by L.
4215 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
4216 __isl_take isl_map *sched,
4217 const char *type, struct gpu_array_ref_group *group,
4218 __isl_take isl_ast_build *build, int private)
4220 isl_space *space;
4221 isl_ast_node *tree;
4222 isl_map *schedule, *shift, *map;
4223 isl_set *set;
4224 isl_id_list *iterators;
4225 int n;
4227 shift = shift_access(group);
4229 schedule = isl_map_copy(shift);
4230 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
4231 if (!private)
4232 schedule = tile_access_schedule(gen, schedule);
4234 n = isl_map_dim(schedule, isl_dim_out);
4235 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
4236 set = add_bounded_parameters(set, gen->kernel->n_block,
4237 gen->kernel->block_dim, "t");
4239 schedule = isl_map_range_product(sched, schedule);
4241 space = isl_space_domain(isl_map_get_space(shift));
4242 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
4243 map = isl_map_range_product(map, shift);
4245 schedule = isl_map_apply_domain(schedule, map);
4247 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
4249 build = isl_ast_build_restrict(build, set);
4251 gen->copy_group = group;
4253 if (private) {
4254 space = isl_space_range(isl_map_get_space(schedule));
4255 space = isl_space_range(isl_space_unwrap(space));
4256 build = set_unroll(build, space, 0);
4258 iterators = generate_names(gen->ctx, n, "c");
4259 build = isl_ast_build_set_iterators(build, iterators);
4260 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
4261 tree = isl_ast_build_ast_from_schedule(build,
4262 isl_union_map_from_map(schedule));
4263 isl_ast_build_free(build);
4265 return tree;
4268 /* Return code for reading into or writing from shared memory
4269 * the given array reference group.
4271 * If we are performing a read from global memory to shared memory and
4272 * if the array involved is not a scalar, then we copy
4273 * the entire tile to shared memory. This may result in some extra
4274 * elements getting copied, but it should lead to simpler code
4275 * (which means that fewer registers may be needed) and less divergence.
4277 * Otherwise, we only copy the elements that will be read or have been written
4278 * in the kernel.
4281 * The input "sched" is of the form.
4283 * type[S -> A] -> L
4285 * with S the first shared_len dimensions of the computed schedule,
4286 * A the array and L the schedule correponding to the generated loops.
4288 * We first drop "type",
4290 * [S -> A] -> L
4292 * If the above conditions are satisfied, we project out A,
4293 * resulting in
4295 * S -> L
4297 * and then introduce the group tile [S -> T], resulting in
4299 * [S -> T] -> L
4301 static __isl_give isl_ast_node *copy_group_shared_accesses(
4302 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4303 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4305 const char *type;
4306 int read;
4307 isl_union_map *access;
4309 type = isl_map_get_tuple_name(sched, isl_dim_in);
4310 read = !strcmp(type, "read");
4312 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4314 if (read && !gpu_array_is_scalar(group->array)) {
4315 isl_space *space;
4316 isl_map *map;
4318 space = isl_space_domain(isl_map_get_space(sched));
4319 space = isl_space_unwrap(space);
4320 map = isl_map_domain_map(isl_map_universe(space));
4321 sched = isl_map_apply_domain(sched, map);
4323 map = group_tile(group);
4324 map = isl_map_reverse(isl_map_domain_map(map));
4325 sched = isl_map_apply_domain(sched, map);
4328 return copy_access(gen, sched, type, group, build, 0);
4331 /* Return code for reading into or writing from private memory
4332 * the given array reference group.
4334 * Let S be the first shared_len dimensions of the computed schedule,
4335 * D the iteration domains, A the array and L the schedule correponding
4336 * to the generated loops.
4337 * "sched" is of the form
4339 * type[S -> A] -> L
4341 * where type is either "read" or "write".
4342 * We apply the privatization D -> S(t), with t the thread ids,
4343 * to the access relation D -> A to obtain the privatized access relation
4345 * S(t) -> A
4347 * We drop the type from "sched" and intersect with the privatized access
4348 * relation to obtain
4350 * [S(t) -> A] -> L
4352 static __isl_give isl_ast_node *copy_group_private_accesses(
4353 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4354 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4356 const char *type;
4357 int read;
4358 isl_union_map *priv;
4359 isl_union_map *access;
4360 isl_map *access_map;
4362 type = isl_map_get_tuple_name(sched, isl_dim_in);
4363 read = !strcmp(type, "read");
4365 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
4366 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
4367 priv);
4369 access = group_access_relation(group, read, !read);
4370 access = isl_union_map_apply_domain(access, priv);
4371 access_map = isl_map_from_union_map(access);
4373 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4374 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
4376 return copy_access(gen, sched, type, group, build, 1);
4379 /* Return code for reading into or writing from shared or private memory.
4381 * "schedule" is of the form
4383 * type[S -> A] -> L
4385 * with S be the first shared_len dimensions of the computed schedule,
4386 * A the array and L the schedule correponding to the generated loops.
4387 * The array reference group is attached to "type".
4389 static __isl_give isl_ast_node *create_access_leaf(
4390 struct gpu_gen *gen, __isl_take isl_map *schedule,
4391 __isl_take isl_ast_build *build)
4393 struct gpu_array_ref_group *group;
4394 isl_id *id;
4396 id = isl_map_get_tuple_id(schedule, isl_dim_in);
4397 group = isl_id_get_user(id);
4398 isl_id_free(id);
4400 if (group->private_tile)
4401 return copy_group_private_accesses(gen, group, schedule,
4402 build);
4403 else
4404 return copy_group_shared_accesses(gen, group, schedule,
4405 build);
4408 /* Create a domain node representing a synchronization.
4410 static __isl_give isl_ast_node *create_sync_leaf(
4411 struct gpu_gen *gen, __isl_take isl_map *schedule,
4412 __isl_take isl_ast_build *build)
4414 struct ppcg_kernel_stmt *stmt;
4415 isl_id *id;
4416 isl_space *space;
4417 isl_ast_node *node;
4418 isl_ast_expr *expr;
4420 isl_map_free(schedule);
4422 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4423 if (!stmt)
4424 return NULL;
4426 stmt->type = ppcg_kernel_sync;
4428 space = isl_ast_build_get_schedule_space(build);
4429 space = isl_space_from_domain(space);
4430 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
4431 expr = isl_ast_build_call_from_pw_multi_aff(build,
4432 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
4433 node = isl_ast_node_alloc_user(expr);
4434 isl_ast_build_free(build);
4436 id = isl_id_alloc(gen->ctx, NULL, stmt);
4437 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4438 return isl_ast_node_set_annotation(node, id);
4441 /* This function is called during the code generation at the point
4442 * where the schedule domain element is completely determined by
4443 * the generated code. The input schedule contains the original
4444 * statements as well as synchronization and copy "statements".
4445 * The latter are scheduled at different points than any of the original
4446 * statements, so they will only arrive here in isolation.
4448 * If the current schedule only refers to a single statement,
4449 * we check if it is a copy or synchronization statement and
4450 * call the appropriate functions.
4451 * Otherwise, we assume we are dealing with the original statements
4452 * and we call create_domain_leaf.
4454 static __isl_give isl_ast_node *create_kernel_leaf(
4455 __isl_take isl_ast_build *build, void *user)
4457 struct gpu_gen *gen = (struct gpu_gen *) user;
4458 isl_map *map;
4459 isl_union_map *schedule;
4460 const char *name;
4462 schedule = isl_ast_build_get_schedule(build);
4464 if (isl_union_map_n_map(schedule) != 1)
4465 return create_domain_leaf(schedule, build, user);
4467 map = isl_map_from_union_map(schedule);
4468 name = isl_map_get_tuple_name(map, isl_dim_in);
4469 if (!strcmp(name, "read") || !strcmp(name, "write"))
4470 return create_access_leaf(gen, map, build);
4471 if (!strcmp(name, "sync"))
4472 return create_sync_leaf(gen, map, build);
4474 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4477 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4478 * have value 0) and all even schedule dimensions as "unroll".
4480 * That is, the options look as follows
4482 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4483 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4485 * The even positions are used to be able to schedule copying blocks
4486 * and synchronization before or after each level of the shared memory
4487 * tile loops and we want to make sure that code for these is generated
4488 * separately (within each level).
4490 static __isl_give isl_ast_build *set_atomic_and_unroll(
4491 __isl_take isl_ast_build *build,
4492 __isl_take isl_space *space, int sched_len)
4494 isl_ctx *ctx;
4495 isl_map *map;
4496 isl_constraint *c;
4497 isl_union_map *opt;
4498 isl_local_space *ls;
4499 int i, n;
4501 ctx = isl_ast_build_get_ctx(build);
4503 space = isl_space_params(space);
4504 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4505 space = isl_space_from_domain(space);
4506 space = isl_space_add_dims(space, isl_dim_out, 2);
4507 map = isl_map_universe(isl_space_copy(space));
4508 for (i = 0; i < sched_len; i += 2)
4509 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4510 ls = isl_local_space_from_space(isl_map_get_space(map));
4511 c = isl_equality_alloc(ls);
4512 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4513 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4514 c = isl_constraint_set_constant_si(c, 1);
4515 map = isl_map_add_constraint(map, c);
4516 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4517 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4518 opt = isl_union_map_from_map(map);
4520 map = isl_map_universe(space);
4521 ls = isl_local_space_from_space(isl_map_get_space(map));
4522 c = isl_equality_alloc(ls);
4523 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4524 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4525 map = isl_map_add_constraint(map, c);
4526 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4527 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4528 opt = isl_union_map_add_map(opt, map);
4530 build = isl_ast_build_set_options(build, opt);
4532 return build;
4535 /* Return a map that maps a space of dimension gen->shared_len
4536 * to its last dimensions starting at gen->tile_first.
4537 * The range is of dimension
4539 * 2 * (gen->shared_len - gen->tile_first) + 1
4541 * The input dimensions are mapped to the odd dimensions in the output,
4542 * while the even dimensions (except 2*pos) are fixed to 0.
4543 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4544 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4545 * are mapped to the output. The remaining input dimensions are projected
4546 * out and the corresponding output dimensions are fixed to 0.
4548 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4549 __isl_take isl_space *space, int pos, int val)
4551 int i, n;
4552 isl_map *proj;
4554 space = isl_space_set_from_params(space);
4555 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4556 space = isl_space_map_from_set(space);
4557 proj = isl_map_identity(space);
4558 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4559 n = gen->shared_len - gen->tile_first;
4560 for (i = 0; i <= n; ++i) {
4561 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4562 if (i == pos)
4563 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4564 else
4565 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4568 if (pos < 0)
4569 return proj;
4571 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4572 gen->shared_len - (gen->tile_first + pos));
4573 for (i = pos; i < n; ++i)
4574 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4576 return proj;
4579 /* Given the AST context schedule "schedule" and the mapping from
4580 * domains to the shared tile loops "shared_sched", add a schedule
4581 * for a synchronization operation at position "val" of loop level "pos".
4583 * schedule is of the form
4585 * D -> L
4587 * (with D the iteration domains and L the already generated loops),
4588 * while shared_sched is of the form
4590 * D -> S
4592 * We combine them into
4594 * L -> S
4596 * apply a mapping
4598 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4600 * and use the result as a schedule for "sync".
4602 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4603 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4604 __isl_keep isl_union_map *shared_sched, int pos, int val)
4606 isl_space *space;
4607 isl_map *proj, *map;
4609 shared_sched = isl_union_map_copy(shared_sched);
4610 schedule = isl_union_map_copy(schedule);
4612 space = isl_union_map_get_space(shared_sched);
4613 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4614 map = isl_map_from_union_map(schedule);
4616 proj = insert_even(gen, space, pos, val);
4617 map = isl_map_apply_range(map, proj);
4618 map = isl_map_from_range(isl_map_wrap(map));
4619 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4621 res = isl_union_map_add_map(res, map);
4623 return res;
4626 /* Given a set of wrapped references "ref", return the corresponding
4627 * access relations based on the tagged access relations "tagged".
4629 * The elements of "ref" are of the form
4631 * [D -> R]
4633 * with D an iteration domains and R a reference.
4634 * The elements of "tagged" are of the form
4636 * [D -> R] -> A
4638 * with A an array.
4640 * Extend "tagged" to include the iteration domain in the range, i.e.,
4642 * [D -> R] -> [D -> A]
4644 * apply the result to "ref" and then unwrap the resulting set
4645 * to obtain relations of the form
4647 * D -> A
4649 static __isl_give isl_union_map *wrapped_reference_to_access(
4650 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
4652 isl_union_map *tag2access;
4654 tag2access = isl_union_map_copy(tagged);
4655 tag2access = isl_union_map_universe(tag2access);
4656 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
4657 tag2access = isl_union_map_domain_map(tag2access);
4658 tag2access = isl_union_map_range_product(tag2access, tagged);
4660 ref = isl_union_set_coalesce(ref);
4661 ref = isl_union_set_apply(ref, tag2access);
4663 return isl_union_set_unwrap(ref);
4666 /* Given an access relation "access" from "group", remove those reads
4667 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
4668 * communicate data within the same iteration of the last_shared dimension
4669 * of the group.
4671 * If the access is a read then it is necessarily an element of
4673 * live_in union (range flow)
4675 * where live_in and flow may be overapproximations.
4676 * If the access is a write then it is necessarily an element of
4678 * live_out union (domain flow)
4680 * In both cases, the access relation is also a subset of
4681 * the group access relation.
4683 * Essentially, we compute the intersection of "access" with either
4685 * live_in union (range non-local-flow)
4687 * or
4689 * live_out union (domain non-local-flow)
4691 * We first construct a relation "local"
4693 * [[D -> R] -> [D' -> R']]
4695 * of pairs of domain iterations accessing the reference group
4696 * and references in the group that are scheduled to the same iteration
4697 * of the last_shared dimension.
4699 * If this relation does not intersect the dataflow dependences,
4700 * then there is nothing we can possibly remove and we simply
4701 * return the input.
4703 * Otherwise, we remove the "local" dataflow dependences from
4704 * the set of all dataflow dependences.
4705 * Note that if the potential dataflow dependences are an overapproximation
4706 * of the actual dataflow dependences, then the result remains an
4707 * overapproximation of the non-local dataflow dependences.
4708 * Copying to/from global memory is only needed for the references
4709 * in the domain/range of the result or for accesses that are live out/in
4710 * for the entire scop.
4712 * We therefore map the domain/range of the "external" relation
4713 * to the corresponding access relation and take the union with
4714 * the live out/in relation.
4716 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
4717 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
4718 int read)
4720 int empty;
4721 isl_union_map *tagger;
4722 isl_union_set *domain;
4723 isl_space *space;
4724 isl_union_map *sched, *local, *tagged, *external;
4725 isl_union_set *tag_set;
4726 isl_map *proj;
4728 if (isl_union_map_is_empty(access))
4729 return access;
4731 tagged = group_tagged_access_relation(group);
4733 sched = isl_union_map_copy(gen->sched);
4735 space = isl_union_map_get_space(sched);
4736 proj = projection(space, gen->untiled_len, group->last_shared + 1);
4737 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4739 tagger = isl_union_map_copy(gen->prog->scop->tagger);
4740 domain = isl_union_map_domain(isl_union_map_copy(tagged));
4741 tagger = isl_union_map_intersect_range(tagger, domain);
4742 sched = isl_union_map_apply_domain(sched, tagger);
4744 local = isl_union_map_apply_range(sched,
4745 isl_union_map_reverse(isl_union_map_copy(sched)));
4746 local = isl_union_map_intersect(local,
4747 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
4749 empty = isl_union_map_is_empty(local);
4750 if (empty < 0 || empty) {
4751 isl_union_map_free(tagged);
4752 isl_union_map_free(local);
4753 if (empty < 0)
4754 return isl_union_map_free(access);
4755 return access;
4758 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
4759 external = isl_union_map_intersect_params(external,
4760 isl_set_copy(gen->prog->scop->context));
4761 external = isl_union_map_subtract(external, local);
4763 if (read) {
4764 tag_set = isl_union_map_range(external);
4765 external = wrapped_reference_to_access(tag_set, tagged);
4766 external = isl_union_map_union(external,
4767 isl_union_map_copy(gen->prog->scop->live_in));
4768 } else {
4769 tag_set = isl_union_map_domain(external);
4770 external = wrapped_reference_to_access(tag_set, tagged);
4771 external = isl_union_map_union(external,
4772 isl_union_map_copy(gen->prog->scop->live_out));
4775 access = isl_union_map_intersect(access, external);
4777 return access;
4780 /* Given the AST context schedule "schedule" and the mapping from
4781 * domains to the shared tile loops "shared_sched", add a schedule
4782 * for copying an array reference group to/from shared/private memory.
4783 * "read" is set if data should be copied from global memory
4784 * to shared/private memory.
4785 * "k" represents the current group
4786 * "s" is the total number of groups
4788 * We schedule an operation before or after the innermost loop
4789 * of "shared_sched" that affects the tile of the array reference group.
4791 * schedule is of the form
4793 * D -> L
4795 * (with D the iteration domains and L the already generated loops),
4796 * while shared_sched is of the form
4798 * D -> S
4800 * We first compute the access relation for the reference group
4802 * D -> A
4804 * and remove from this access relation those reads or writes
4805 * that only needed to communicate data within the same iteration
4806 * of the last_shared dimension of the group.
4807 * We then combine what is left with shared_sched into
4809 * D -> [S -> A]
4811 * If this results in an empty relation, no copying needs to be performed
4812 * at this point.
4813 * Otherwise, we invert the relation and combine it with "schedule" into
4815 * [S -> A] -> L
4817 * The actual additional piece of the schedule is obtained from combining
4819 * [S -> A] -> S
4821 * with a mapping
4823 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4825 * The position of "val" corresponds to the innermost loop that affects
4826 * the tile and the value indicates where the copying is scheduled
4827 * with respect to the actual kernel code (at value 0).
4828 * Reads are schedule before the code, writes to global memory from
4829 * private memory are scheduled at values 1 to s, writes to global
4830 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4832 * If we are scheduling a read from global memory to shared memory,
4833 * we insert a synchronization before the kernel code (at the innermost
4834 * level).
4835 * If we are scheduling a write to global memory, then we add
4836 * a synchronization after all writes (at value 2 *s + 2).
4837 * However, there is no need for a synchronization after the outermost loop.
4838 * A write to global memory from private memory at the innermost level
4839 * does not require a synchronization, because it is covered by
4840 * the synchronization after the kernel inserted by body_schedule.
4842 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4843 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4844 __isl_keep isl_union_map *shared_sched,
4845 struct gpu_array_ref_group *group, int read, int k, int s)
4847 int n;
4848 int pos, val;
4849 isl_space *space;
4850 isl_union_map *access;
4851 isl_map *map, *proj, *access_map;
4852 isl_id *id;
4854 access = group_access_relation(group, read, !read);
4855 access = remove_local_accesses(gen, group, access, read);
4856 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4857 access);
4859 if (isl_union_map_is_empty(access)) {
4860 isl_union_map_free(access);
4861 return res;
4864 access = isl_union_map_reverse(access);
4865 access = isl_union_map_apply_range(access,
4866 isl_union_map_copy(schedule));
4867 access_map = isl_map_from_union_map(access);
4869 space = isl_space_copy(group->array->space);
4870 space = isl_space_from_range(space);
4871 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4872 map = isl_map_domain_map(isl_map_universe(space));
4874 space = isl_union_map_get_space(schedule);
4875 pos = group->last_shared + 1 - gen->tile_first;
4876 assert(pos >= 0);
4877 if (read)
4878 val = -2 - k;
4879 else if (group->private_tile)
4880 val = 1 + k;
4881 else
4882 val = 1 + s + 1 + k;
4883 proj = insert_even(gen, space, pos, val);
4884 map = isl_map_apply_range(map, proj);
4886 access_map = isl_map_range_product(access_map, map);
4888 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4889 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4891 res = isl_union_map_add_map(res, access_map);
4893 n = gen->shared_len - gen->tile_first;
4894 if (read) {
4895 if (!group->private_tile)
4896 res = add_sync_schedule(gen, res, schedule,
4897 shared_sched, n, -1);
4898 } else {
4899 if (pos == 0)
4900 return res;
4901 if (pos == n && group->private_tile)
4902 return res;
4903 res = add_sync_schedule(gen, res, schedule, shared_sched,
4904 pos, 2 * s + 2);
4907 return res;
4910 /* Return a schedule for the shared tile loops based on the current
4911 * AST context schedule.
4913 * We create a "shared_sched" that maps the domains to the first
4914 * shared_len dimensions of the computed schedule, project out the
4915 * first tile_first dimensions (as these are already covered by
4916 * the host code) and insert "statement-level" dimensions at even
4917 * positions so that we can schedule copy blocks and synchronization
4918 * before/after each level.
4920 * In particular, copy blocks are inserted inside the innermost
4921 * level that affect the tile. For the copying to global memory,
4922 * those from private memory are scheduled before those from shared
4923 * memory such that synchronization can be inserted between the two
4924 * at the innermost level.
4925 * Synchronization is inserted at the innermost level before the
4926 * actual kernel code if there is any copying from global memory
4927 * to shared memory. It is inserted unconditionally at the innermost
4928 * level after the actual kernel code and the copying to global memory
4929 * from private memory (if any). Finally, it is inserted after
4930 * any copying to global memory, except at the outermost level
4931 * and at the innermost level if there is no copying from shared
4932 * memory. The copying from private memory is covered by the unconditional
4933 * synchronization at the innermost level.
4935 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4936 __isl_take isl_union_map *schedule)
4938 isl_space *space;
4939 isl_union_map *res;
4940 isl_union_map *shared_sched;
4941 isl_union_map *sched;
4942 isl_map *proj, *map;
4943 int i, j, k, s;
4945 shared_sched = isl_union_map_copy(gen->tiled_sched);
4946 proj = projection(isl_union_map_get_space(shared_sched),
4947 gen->tiled_len, gen->shared_len);
4948 shared_sched = isl_union_map_apply_range(shared_sched,
4949 isl_union_map_from_map(proj));
4950 space = isl_union_map_get_space(shared_sched);
4951 proj = insert_even(gen, space, -1, 0);
4952 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4953 isl_union_map_from_map(proj));
4955 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4957 s = 0;
4958 for (i = 0; i < gen->prog->n_array; ++i)
4959 s += gen->prog->array[i].n_group;
4961 k = 0;
4962 for (i = 0; i < gen->prog->n_array; ++i) {
4963 struct gpu_array_info *array = &gen->prog->array[i];
4965 for (j = 0; j < array->n_group; ++j) {
4966 struct gpu_array_ref_group *group;
4968 group = array->groups[j];
4969 if (!group->private_tile && !group->shared_tile)
4970 continue;
4971 res = add_group_schedule(gen, res, schedule,
4972 shared_sched, group, 0, k, s);
4973 res = add_group_schedule(gen, res, schedule,
4974 shared_sched, group, 1, k, s);
4975 ++k;
4979 res = add_sync_schedule(gen, res, schedule, shared_sched,
4980 gen->shared_len - gen->tile_first, 1 + s);
4982 isl_union_map_free(shared_sched);
4983 isl_union_map_free(schedule);
4985 return res;
4988 /* Generate code for "kernel" in the given "context".
4990 * We first generate code for the shared tile loops (T1T, T1P and T2)
4991 * in a context that includes the block ids.
4992 * Within each iteration of these loops an additional code generation
4993 * is performed (within create_kernel_leaf) for the rest of the schedule
4994 * in a context that includes the thread ids.
4996 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4997 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4998 __isl_keep isl_multi_pw_aff *grid_size)
5000 isl_space *space;
5001 isl_set *set;
5002 isl_id_list *iterators;
5003 isl_union_map *schedule;
5004 isl_ast_node *tree;
5005 int sched_len;
5007 schedule = isl_ast_build_get_schedule(build);
5009 build = isl_ast_build_copy(build);
5010 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
5011 space = isl_ast_build_get_schedule_space(build);
5012 set = isl_set_universe(isl_space_copy(space));
5013 set = add_bounded_parameters_dynamic(set, grid_size, "b");
5014 build = isl_ast_build_restrict(build, set);
5016 schedule = body_schedule(gen, schedule);
5018 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
5020 build = set_atomic_and_unroll(build, space, sched_len);
5021 iterators = generate_names(gen->ctx, sched_len, "g");
5022 build = isl_ast_build_set_iterators(build, iterators);
5023 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
5024 tree = isl_ast_build_ast_from_schedule(build, schedule);
5025 isl_ast_build_free(build);
5027 return tree;
5030 /* Attach "id" to the given node.
5032 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
5033 __isl_keep isl_ast_build *build, void *user)
5035 isl_id *id = user;
5037 node = isl_ast_node_set_annotation(node, id);
5039 return node;
5042 /* Construct an AST node for performing a kernel launch and attach
5043 * the information about the kernel to that node.
5045 * The kernel AST has been constructed in the context of the range
5046 * of "schedule". In particular, the grid size has been computed
5047 * in the context. We therefore still need to make sure that these
5048 * constraints are expressed in the code. We do this by creating a schedule
5050 * kernel[] -> [S -> []]
5052 * where S is the schedule domain, i.e., the range of "schedule".
5053 * The AST generation will then create a single call surrounded by
5054 * all the condition in "S" that have not been expressed yet.
5056 * The kernel information is attached to this node in attach_id.
5058 static __isl_give isl_ast_node *construct_launch(
5059 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
5060 __isl_take struct ppcg_kernel *kernel)
5062 isl_id *id;
5063 isl_ctx *ctx;
5064 isl_union_set *domain;
5065 isl_set *set;
5066 isl_map *map;
5067 isl_ast_node *node;
5069 ctx = isl_ast_build_get_ctx(build);
5071 id = isl_id_alloc(ctx, NULL, kernel);
5072 id = isl_id_set_free_user(id, &ppcg_kernel_free);
5074 domain = isl_union_map_range(schedule);
5075 set = isl_set_from_union_set(domain);
5076 map = isl_map_from_domain(set);
5077 map = isl_map_from_range(isl_map_wrap(map));
5078 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
5079 schedule = isl_union_map_from_map(map);
5081 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
5082 node = isl_ast_build_ast_from_schedule(build, schedule);
5083 isl_ast_build_free(build);
5085 return node;
5088 /* This function is called for each leaf in the AST of the host code.
5089 * We first specialize the schedule to the site of the leaf, compute
5090 * the size of shared memory and then construct the body of the host code
5091 * and the associated kernel.
5093 * The necessary information for printing the kernel launch is
5094 * stored in a struct ppcg_kernel and attached to the leaf node
5095 * created to represent the launch.
5097 static __isl_give isl_ast_node *create_host_leaf(
5098 __isl_take isl_ast_build *build, void *user)
5100 struct gpu_gen *gen = (struct gpu_gen *) user;
5101 isl_id *id;
5102 isl_ast_node *node;
5103 struct ppcg_kernel *kernel;
5104 isl_set *host_domain;
5105 isl_union_map *schedule;
5106 isl_union_map *local_sched;
5107 isl_union_map *access;
5108 isl_union_set *domain;
5109 int i;
5111 schedule = isl_ast_build_get_schedule(build);
5113 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
5114 read_sizes(gen);
5116 domain = isl_union_map_domain(isl_union_map_copy(schedule));
5118 local_sched = isl_union_map_copy(gen->sched);
5119 local_sched = isl_union_map_intersect_domain(local_sched, domain);
5120 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
5121 isl_union_map_copy(gen->prog->may_write));
5122 access = isl_union_map_apply_domain(access,
5123 isl_union_map_copy(local_sched));
5125 gen->tiled_sched = tile_schedule(gen, local_sched);
5126 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
5127 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
5129 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
5130 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
5131 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
5133 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
5134 if (!kernel)
5135 goto error;
5137 kernel->id = gen->kernel_id++;
5138 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
5139 kernel->grid_size = extract_grid_size(gen, kernel);
5140 extract_block_size(gen, kernel);
5141 kernel->arrays = isl_union_map_range(access);
5142 kernel->arrays = isl_union_set_apply(kernel->arrays,
5143 isl_union_map_copy(gen->prog->to_outer));
5144 kernel->space = isl_ast_build_get_schedule_space(build);
5146 compute_shared_sched(gen);
5147 gen->privatization = compute_privatization(gen);
5148 check_scalar_live_ranges(gen);
5149 if (group_references(gen) < 0)
5150 schedule = isl_union_map_free(schedule);
5151 host_domain = isl_set_from_union_set(isl_union_map_range(
5152 isl_union_map_copy(schedule)));
5153 localize_bounds(gen, kernel, host_domain);
5155 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
5156 check_shared_memory_bound(gen);
5157 compute_group_tilings(gen);
5159 kernel->tree = generate_kernel(gen, build, host_domain,
5160 kernel->grid_size);
5161 create_kernel_vars(gen, kernel);
5163 free_local_array_info(gen);
5164 isl_map_free(gen->privatization);
5165 isl_union_map_free(gen->local_sched);
5166 isl_union_map_free(gen->tiled_sched);
5167 isl_union_map_free(gen->shared_sched);
5168 isl_union_map_free(gen->shared_proj);
5169 isl_set_free(host_domain);
5170 free(gen->tile_size);
5172 node = construct_launch(build, schedule, kernel);
5174 return node;
5175 error:
5176 isl_union_map_free(schedule);
5177 return NULL;
5180 /* Use isl to generate code for the outer gen->tile_first loops
5181 * of the global schedule in gen->sched, resulting in the host code.
5182 * Within each iteration of this partial schedule, i.e., for each kernel
5183 * launch, create_host_leaf takes care of generating the kernel code.
5185 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
5187 isl_ast_build *build;
5188 isl_ast_node *tree;
5189 isl_union_map *sched;
5190 isl_map *proj;
5191 isl_id_list *iterators;
5193 sched = isl_union_map_copy(gen->sched);
5194 proj = projection(isl_union_map_get_space(sched),
5195 gen->untiled_len, gen->tile_first);
5196 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
5198 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
5199 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
5200 iterators = generate_names(gen->ctx, gen->tile_first, "h");
5201 build = isl_ast_build_set_iterators(build, iterators);
5202 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
5203 tree = isl_ast_build_ast_from_schedule(build, sched);
5204 isl_ast_build_free(build);
5206 return tree;
5209 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
5211 if (!str)
5212 return NULL;
5213 return isl_union_map_read_from_str(ctx, str);
5216 /* Information about the outermost tilable bands in the forest of bands.
5218 * tile_len and n_parallel are only sets on band_info structures
5219 * that correspond to outermost bands. For other bands (in particular,
5220 * ancestors of the outermost bands), n_parallal is set to 0.
5222 * prefix is the (padded) schedule leading up to the outermost tilable bands.
5224 * tile_first is the number of schedule dimensions in prefix.
5226 * suffix is the schedule of the outermost tilable bands and their descendants.
5228 struct band_info {
5229 struct gpu_gen *gen;
5230 int tile_first;
5231 int tile_len;
5232 int n_parallel;
5233 isl_union_map *prefix;
5234 isl_union_map *suffix;
5237 /* Set tile_len and n_parallel of the statement to that of
5238 * their outermost band, recorded in the band_info.
5240 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
5242 struct band_info *info = user;
5243 struct gpu_stmt *stmt;
5244 isl_id *id;
5246 id = isl_map_get_tuple_id(map, isl_dim_in);
5247 stmt = find_stmt(info->gen->prog, id);
5248 isl_id_free(id);
5250 stmt->tile_len = info->tile_len;
5251 stmt->n_parallel = info->n_parallel;
5253 isl_map_free(map);
5255 return 0;
5258 static void list_select_outer_band(struct gpu_gen *gen,
5259 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
5261 /* Check if this band has any parallel loops. If so, take it as
5262 * the outermost tilable band. If not, continue looking for the
5263 * outermost tilable band in the children of the current band.
5265 static void band_select_outer_band(struct gpu_gen *gen,
5266 __isl_take isl_band *band, int pos, struct band_info *info)
5268 int n = isl_band_n_member(band);
5269 int n_parallel;
5271 for (n_parallel = 0; n_parallel < n; ++n_parallel)
5272 if (!isl_band_member_is_coincident(band, n_parallel))
5273 break;
5275 info->n_parallel = n_parallel;
5276 if (n_parallel) {
5277 gen->any_parallelism = 1;
5278 info->gen = gen;
5279 info->tile_first = pos;
5280 info->tile_len = n;
5281 info->prefix = isl_band_get_prefix_schedule(band);
5282 info->suffix = isl_union_map_flat_range_product(
5283 isl_band_get_partial_schedule(band),
5284 isl_band_get_suffix_schedule(band));
5285 isl_union_map_foreach_map(info->prefix,
5286 &set_stmt_tile_len, info);
5287 } else if (isl_band_has_children(band)) {
5288 isl_band_list *children;
5289 children = isl_band_get_children(band);
5290 list_select_outer_band(gen, children, pos + n, info);
5291 } else {
5292 info->gen = gen;
5293 info->tile_first = pos + n;
5294 info->tile_len = 0;
5295 info->prefix = isl_union_map_flat_range_product(
5296 isl_band_get_prefix_schedule(band),
5297 isl_band_get_partial_schedule(band));
5298 info->suffix = isl_band_get_suffix_schedule(band);
5299 isl_union_map_foreach_map(info->prefix,
5300 &set_stmt_tile_len, info);
5303 isl_band_free(band);
5306 /* Comparison function that returns a non-zero value for band_infos
5307 * with different tile_len fields or different n_parallel fields.
5309 static int cmp_band(const void *p1, const void *p2)
5311 const struct band_info *info1 = p1;
5312 const struct band_info *info2 = p2;
5314 if (info1->tile_len != info2->tile_len)
5315 return info1->tile_len - info2->tile_len;
5317 return info1->n_parallel - info2->n_parallel;
5320 /* Extend "umap" with coordinates with fixed value "val"
5321 * to a total length of "dst_len", assuming the original dimension is "src_len".
5323 static __isl_give isl_union_map *extend_range(
5324 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
5326 isl_space *dim;
5327 isl_map *map;
5328 int i;
5330 dim = isl_union_map_get_space(umap);
5331 map = isl_map_reverse(projection(dim, dst_len, src_len));
5332 for (i = src_len; i < dst_len; ++i)
5333 map = isl_map_fix_si(map, isl_dim_out, i, val);
5335 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
5337 return umap;
5340 /* Group bands with the same values for tile_len and n_parallel.
5341 * The prefix schedule is then extended with a fixed coordinate that
5342 * is different for each such group.
5343 * Note that the actual values for this coordinate are not important.
5344 * The bands have already been effectively separated at a higher level
5345 * or they are independent and may be executed in parallel.
5346 * The list of band_info has been sorted before this functions is called.
5348 static void separate_bands(struct band_info *info, int n)
5350 int i;
5351 int j = 0;
5353 for (i = 0; i < n; ++i) {
5354 int l = info[i].tile_first;
5356 if (i &&
5357 (info[i].tile_len != info[i - 1].tile_len ||
5358 info[i].n_parallel != info[i - 1].n_parallel))
5359 j++;
5361 info[i].prefix = extend_range(info[i].prefix,
5362 l, l + 1, j);
5363 info[i].tile_first = l + 1;
5367 /* Select the outermost bands in the elements of the list, align
5368 * their prefix schedules, separate bands with different values
5369 * for tile_len and/or n_parallel and then combine the resulting
5370 * prefix and suffix schedules into a single pair of prefix and
5371 * suffix schedules for the entire list.
5373 static void list_select_outer_band(struct gpu_gen *gen,
5374 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
5376 isl_band *band;
5377 int i;
5378 int n = isl_band_list_n_band(list);
5379 isl_ctx *ctx = isl_band_list_get_ctx(list);
5380 struct band_info *info;
5381 int max_tile_first;
5382 isl_union_map *prefix;
5383 isl_union_map *suffix;
5385 assert(n >= 1);
5386 info = isl_calloc_array(ctx, struct band_info, n);
5387 assert(info);
5389 max_tile_first = 0;
5390 for (i = 0; i < n; ++i) {
5391 band = isl_band_list_get_band(list, i);
5392 band_select_outer_band(gen, band, pos, &info[i]);
5393 if (info[i].tile_first > max_tile_first)
5394 max_tile_first = info[i].tile_first;
5397 for (i = 0; i < n; ++i) {
5398 if (info[i].tile_first == max_tile_first)
5399 continue;
5400 info[i].prefix = extend_range(info[i].prefix,
5401 info[i].tile_first, max_tile_first, 0);
5402 info[i].tile_first = max_tile_first;
5405 qsort(info, n, sizeof(struct band_info), &cmp_band);
5407 for (i = 0; i < n - 1; ++i)
5408 if (info[i].tile_len != info[i + 1].tile_len ||
5409 info[i].n_parallel != info[i + 1].n_parallel)
5410 break;
5412 if (i < n -1)
5413 separate_bands(info, n);
5415 prefix = info[0].prefix;
5416 suffix = info[0].suffix;
5418 for (i = 1; i < n; ++i) {
5419 prefix = isl_union_map_union(prefix, info[i].prefix);
5420 suffix = isl_union_map_union(suffix, info[i].suffix);
5423 list_info->tile_first = info[0].tile_first;
5424 list_info->tile_len = -1;
5425 list_info->prefix = prefix;
5426 list_info->suffix = suffix;
5428 isl_band_list_free(list);
5429 free(info);
5432 /* Select the outermost tilable band that (by construction)
5433 * has at least one parallel loop.
5434 * The starting position of the aligned band is stored in the pair
5435 * gen->tile_first.
5436 * The sizes and number of parallel loops may be different in different
5437 * parts of the band forest and are therefore stored in the gpu_stmts.
5439 * Return the complete schedule, with the tilable bands aligned
5440 * at gen->tile_first and padded with zero, if needed.
5442 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
5443 __isl_keep isl_schedule *schedule)
5445 isl_band_list *list;
5446 struct band_info info;
5448 gen->n_parallel = 0;
5449 gen->tile_len = -1;
5451 list = isl_schedule_get_band_forest(schedule);
5453 if (isl_band_list_n_band(list) == 0) {
5454 isl_band_list_free(list);
5455 return isl_schedule_get_map(schedule);
5458 list_select_outer_band(gen, list, 0, &info);
5460 gen->tile_first = info.tile_first;
5461 info.suffix = align_range(info.suffix);
5463 return isl_union_map_flat_range_product(info.prefix, info.suffix);
5466 /* Set gen->untiled_len to the number of scheduling dimensions
5467 * for the schedule of the first domain.
5468 * We assume here that this number is the same for all domains.
5470 static int set_untiled_len(__isl_take isl_map *map, void *user)
5472 unsigned *untiled_len = user;
5474 *untiled_len = isl_map_dim(map, isl_dim_out);
5476 isl_map_free(map);
5477 return -1;
5480 /* Compute an appropriate schedule based on the accesses in
5481 * gen->read and gen->write.
5483 * We use the dependences in gen->prog->scop to compute
5484 * a schedule that has a parallel loop in each tilable band.
5485 * Finally, we select the outermost tilable band.
5487 * If live range reordering is allowed, then we need to make sure
5488 * that live ranges on arrays are not run in parallel since doing
5489 * so would require array expansion. We therefore add the array
5490 * order dependences to the coincidence dependences. Non-zero array
5491 * order dependences will then prevent a schedule dimension from being
5492 * considered parallel.
5493 * Live ranges derived from scalars are allowed to be run in parallel
5494 * since we force the scalars to be mapped to private memory in
5495 * check_scalar_live_ranges.
5496 * If live range reordering is allowed, then the false dependences
5497 * are not added to the validity constraints as that would prevent
5498 * reordering. Instead, the external false dependences that enforce that reads
5499 * from potentially live-in data precede any later write and
5500 * that writes of potentially live-out data follow any other earlier write
5501 * are added to the validity and the coincidence constraints.
5502 * The false dependences are still added to the proximity constraints
5503 * for consistency with the case where live range reordering is not allowed.
5504 * The coincidence constraints then consist of flow dependences,
5505 * exernal false dependences and array order dependences.
5506 * The independences can be filtered out from the first two sets.
5507 * They have already been filtered out from the array order dependences
5508 * on a per array basis in collect_order_dependences.
5509 * There is no need for a per array handling of the other two sets
5510 * as there should be no flow or external false dependence on local
5511 * variables that can be filtered out.
5513 static void compute_schedule(struct gpu_gen *gen)
5515 isl_union_set *domain;
5516 isl_union_map *dep_raw, *dep;
5517 isl_union_map *validity, *proximity, *coincidence;
5518 isl_union_map *sched;
5519 isl_schedule_constraints *sc;
5520 isl_schedule *schedule;
5522 domain = isl_union_set_copy(gen->prog->scop->domain);
5523 domain = isl_union_set_intersect_params(domain,
5524 isl_set_copy(gen->prog->scop->context));
5525 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
5526 if (gen->options->live_range_reordering) {
5527 sc = isl_schedule_constraints_set_conditional_validity(sc,
5528 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
5529 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
5530 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
5531 validity = isl_union_map_copy(proximity);
5532 validity = isl_union_map_union(validity,
5533 isl_union_map_copy(gen->prog->scop->dep_external));
5534 proximity = isl_union_map_union(proximity,
5535 isl_union_map_copy(gen->prog->scop->dep_false));
5536 coincidence = isl_union_map_copy(validity);
5537 coincidence = isl_union_map_subtract(coincidence,
5538 isl_union_map_copy(gen->prog->scop->independence));
5539 coincidence = isl_union_map_union(coincidence,
5540 isl_union_map_copy(gen->prog->array_order));
5541 } else {
5542 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
5543 dep = isl_union_map_copy(gen->prog->scop->dep_false);
5544 dep = isl_union_map_union(dep, dep_raw);
5545 dep = isl_union_map_coalesce(dep);
5546 proximity = isl_union_map_copy(dep);
5547 coincidence = isl_union_map_copy(dep);
5548 validity = dep;
5550 sc = isl_schedule_constraints_set_validity(sc, validity);
5551 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
5552 sc = isl_schedule_constraints_set_proximity(sc, proximity);
5554 if (gen->options->debug->dump_schedule_constraints)
5555 isl_schedule_constraints_dump(sc);
5556 schedule = isl_schedule_constraints_compute_schedule(sc);
5557 if (gen->options->debug->dump_schedule)
5558 isl_schedule_dump(schedule);
5560 sched = select_outer_tilable_band(gen, schedule);
5562 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
5563 sched = isl_union_map_intersect_domain(sched, domain);
5564 gen->sched = sched;
5566 isl_schedule_free(schedule);
5569 /* Compute the sets of outer array elements that need to be copied in and out.
5571 * In particular, for each array that is possibly written anywhere in
5572 * gen->prog and that is visible outside the corresponding scop,
5573 * we copy out its entire extent.
5575 * Any array elements that is read without first being written needs
5576 * to be copied in. Furthermore, if there are any array elements that
5577 * are copied out, but that may not be written inside gen->prog, then
5578 * they also need to be copied in to ensure that the value after execution
5579 * is the same as the value before execution.
5580 * In case the array elements are structures, we need to take into
5581 * account that all members of the structures need to be written
5582 * by gen->prog before we can avoid copying the data structure in.
5584 * While computing the set of array elements that are copied out but
5585 * not necessarily written, we intersect both sets with the context.
5586 * This helps in those cases where the arrays are declared with a fixed size,
5587 * while the accesses are parametric and the context assigns a fixed value
5588 * to the parameters.
5590 * If an element from a local array is read without first being written,
5591 * then there is no point in copying it in since it cannot have been
5592 * written prior to the scop. Warn about the uninitialized read instead.
5594 static void compute_copy_in_and_out(struct gpu_gen *gen)
5596 int i;
5597 isl_union_set *local;
5598 isl_union_set *may_write, *must_write;
5599 isl_union_set *copy_in, *copy_out;
5600 isl_union_set *not_written;
5601 isl_union_map *uninitialized;
5602 isl_union_map *local_uninitialized;
5604 must_write = isl_union_map_range(
5605 isl_union_map_copy(gen->prog->must_write));
5606 must_write = isl_union_set_intersect_params(must_write,
5607 isl_set_copy(gen->prog->context));
5608 may_write = isl_union_map_range(
5609 isl_union_map_copy(gen->prog->may_write));
5610 may_write = isl_union_set_intersect_params(may_write,
5611 isl_set_copy(gen->prog->context));
5612 may_write = isl_union_set_universe(may_write);
5613 may_write = isl_union_set_apply(may_write,
5614 isl_union_map_copy(gen->prog->to_outer));
5615 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
5616 local = isl_union_set_copy(copy_out);
5618 for (i = 0; i < gen->prog->n_array; ++i) {
5619 isl_space *space;
5620 isl_set *write_i;
5621 int empty;
5623 space = isl_space_copy(gen->prog->array[i].space);
5625 if (gen->prog->array[i].local) {
5626 isl_set *set;
5628 set = isl_set_universe(space);
5629 local = isl_union_set_add_set(local, set);
5630 continue;
5633 write_i = isl_union_set_extract_set(may_write, space);
5634 empty = isl_set_plain_is_empty(write_i);
5635 isl_set_free(write_i);
5636 if (empty)
5637 continue;
5639 write_i = isl_set_copy(gen->prog->array[i].extent);
5640 copy_out = isl_union_set_add_set(copy_out, write_i);
5642 isl_union_set_free(may_write);
5644 copy_out = isl_union_set_intersect_params(copy_out,
5645 isl_set_copy(gen->prog->context));
5647 gen->prog->copy_out = isl_union_set_copy(copy_out);
5649 copy_out = isl_union_set_apply(copy_out,
5650 isl_union_map_copy(gen->prog->to_inner));
5651 not_written = isl_union_set_subtract(copy_out, must_write);
5653 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
5654 local_uninitialized = isl_union_map_copy(uninitialized);
5656 local = isl_union_set_apply(local,
5657 isl_union_map_copy(gen->prog->to_inner));
5658 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5659 local);
5660 if (!isl_union_map_is_empty(local_uninitialized)) {
5661 fprintf(stderr,
5662 "possibly uninitialized reads (not copied in):\n");
5663 isl_union_map_dump(local_uninitialized);
5665 uninitialized = isl_union_map_subtract(uninitialized,
5666 local_uninitialized);
5667 copy_in = isl_union_map_range(uninitialized);
5668 copy_in = isl_union_set_union(copy_in, not_written);
5669 copy_in = isl_union_set_apply(copy_in,
5670 isl_union_map_copy(gen->prog->to_outer));
5672 gen->prog->copy_in = copy_in;
5675 /* Internal data structure for extract_access.
5676 * "next_access" points to the end of a linked list that is extended
5677 * by extract_access.
5678 * "single_expression" is set if the access expressions belong to
5679 * an expression statement (i.e., a statement without internal control).
5680 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5682 struct ppcg_extract_access_data {
5683 struct gpu_stmt_access **next_access;
5684 int single_expression;
5685 isl_union_map *any_to_outer;
5688 /* Extract a gpu_stmt_access from "expr", append it to the list
5689 * that ends in *data->next_access and update the end of the list.
5690 * If the access expression performs a write, then it is considered
5691 * exact only if it appears in a single expression statement and
5692 * if its may access relation is equal to its must access relation.
5694 * The combined set of may accesses may be union if member accesses
5695 * are involved, but the entire set is derived from a single reference and
5696 * therefore from a single index expression. These accesses therefore
5697 * all map to the same outer array.
5699 static int extract_access(__isl_keep pet_expr *expr, void *user)
5701 struct ppcg_extract_access_data *data = user;
5702 isl_union_map *may, *tagged;
5703 struct gpu_stmt_access *access;
5704 isl_ctx *ctx;
5705 isl_multi_pw_aff *index;
5707 may = pet_expr_access_get_may_read(expr);
5708 may = isl_union_map_union(may, pet_expr_access_get_may_write(expr));
5709 may = isl_union_map_apply_range(may,
5710 isl_union_map_copy(data->any_to_outer));
5711 ctx = isl_union_map_get_ctx(may);
5712 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5713 assert(access);
5714 access->next = NULL;
5715 access->read = pet_expr_access_is_read(expr);
5716 access->write = pet_expr_access_is_write(expr);
5717 tagged = pet_expr_access_get_tagged_may_read(expr);
5718 tagged = isl_union_map_union(tagged,
5719 pet_expr_access_get_tagged_may_write(expr));
5720 tagged = isl_union_map_apply_range(tagged,
5721 isl_union_map_copy(data->any_to_outer));
5722 access->tagged_access = isl_map_from_union_map(tagged);
5723 if (!access->write) {
5724 access->exact_write = 1;
5725 } else if (!data->single_expression) {
5726 access->exact_write = 0;
5727 } else {
5728 isl_union_map *must;
5729 must = pet_expr_access_get_must_write(expr);
5730 access->exact_write = isl_union_map_is_equal(must, may);
5731 isl_union_map_free(must);
5733 access->access = isl_map_from_union_map(may);
5734 index = pet_expr_access_get_index(expr);
5735 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5736 isl_multi_pw_aff_free(index);
5737 access->ref_id = pet_expr_access_get_ref_id(expr);
5738 access->group = -1;
5740 *data->next_access = access;
5741 data->next_access = &(*data->next_access)->next;
5743 return 0;
5746 /* Construct a linked list of gpu_stmt_access objects,
5747 * one for each access expression in the statement body.
5748 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5750 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5751 __isl_keep isl_union_map *any_to_outer)
5753 struct ppcg_extract_access_data data;
5755 stmt->accesses = NULL;
5756 data.next_access = &stmt->accesses;
5757 data.single_expression =
5758 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5759 data.any_to_outer = any_to_outer;
5760 pet_tree_foreach_access_expr(stmt->stmt->body, &extract_access, &data);
5763 /* Return an array of gpu_stmt representing the statements in "scop".
5765 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5766 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
5768 int i;
5769 struct gpu_stmt *stmts;
5771 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5772 if (!stmts)
5773 return NULL;
5775 for (i = 0; i < scop->pet->n_stmt; ++i) {
5776 struct gpu_stmt *s = &stmts[i];
5778 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5779 s->stmt = scop->pet->stmts[i];
5780 pet_stmt_extract_accesses(s, any_to_outer);
5783 return stmts;
5786 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5788 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5790 struct gpu_gen *gen = user;
5792 return gen->print(p, gen->prog, gen->tree, &gen->types,
5793 gen->print_user);
5796 /* Generate CUDA code for "scop" and print it to "p".
5797 * After generating an AST for the transformed scop as explained below,
5798 * we call "gen->print" to print the AST in the desired output format
5799 * to "p".
5801 * If it turns out that it does not make sense to generate GPU code,
5802 * then we generate CPU code instead.
5804 * The GPU code is generated in a context where at least one
5805 * statement instance is executed. The corresponding guard (if any) is printed
5806 * around the entire generated GPU code, except for the declaration
5807 * of the arrays that are visible outside of the scop and that therefore
5808 * cannot be declared inside the body of any possible guard.
5810 * We first compute a schedule that respects the dependences
5811 * of the original program and select the outermost band
5812 * of tilable dimensions that has at least one parallel loop.
5813 * We then have three blocks of dimensions
5815 * H B G
5817 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5818 * in
5820 * H T P G
5822 * For each iteration of the T loop and for each array, we compute
5823 * the array elements accessed by that iteration, construct a rectangular
5824 * box around it and shift it to the origin. The result is used
5825 * as shared memory for the array.
5827 * We then split off at most 2 parallel loops from the T loops and
5828 * at most 3 parallel loops from the P loops
5830 * H T1 T2 P1 P2 G
5832 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5833 * according to "grid"/"block" sizes.
5835 * H T1T T1P T2 P1T P1P P2 G
5837 * Finally, the T1P and P1P iterators are equated to the block and
5838 * thread dimensions respectively and so are effectively removed.
5839 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5840 * are run on the GPU.
5842 * Code is generated in three stages. We first generate code for the
5843 * host (the H loops), with iterators h%d. Then, for each leaf node
5844 * of the resulting AST, we generate code for the shared loops (up to
5845 * and including T2), with iterators g%d and after equating the H loops
5846 * to h%d parameters and the T1P loops to the block dimensions.
5847 * Finally, we generate code for the remaining loops in a similar fashion.
5849 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5850 struct gpu_gen *gen, struct ppcg_scop *scop,
5851 struct ppcg_options *options)
5853 struct gpu_prog *prog;
5854 isl_ctx *ctx;
5855 isl_set *context, *guard;
5857 if (!scop)
5858 return isl_printer_free(p);
5860 ctx = isl_printer_get_ctx(p);
5861 prog = gpu_prog_alloc(ctx, scop);
5862 if (!prog)
5863 return isl_printer_free(p);
5865 context = isl_set_copy(prog->context);
5866 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5867 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5869 gen->prog = prog;
5870 gen->any_parallelism = 0;
5871 compute_schedule(gen);
5873 if (!gen->any_parallelism) {
5874 isl_set_free(context);
5875 isl_set_free(guard);
5876 p = print_cpu(p, scop, options);
5877 } else {
5878 compute_copy_in_and_out(gen);
5879 gen->tree = generate_host_code(gen);
5880 p = ppcg_print_exposed_declarations(p, prog->scop);
5881 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5882 isl_ast_node_free(gen->tree);
5885 isl_union_map_free(gen->sched);
5887 gpu_prog_free(prog);
5889 return p;
5892 /* Wrapper around generate for use as a ppcg_transform callback.
5894 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5895 struct ppcg_scop *scop, void *user)
5897 struct gpu_gen *gen = user;
5899 return generate(p, gen, scop, gen->options);
5902 /* Transform the code in the file called "input" by replacing
5903 * all scops by corresponding GPU code and write the results to "out".
5905 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5906 struct ppcg_options *options,
5907 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5908 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5909 struct gpu_types *types, void *user), void *user)
5911 struct gpu_gen gen;
5912 int r;
5913 int i;
5915 gen.ctx = ctx;
5916 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5917 gen.options = options;
5918 gen.kernel_id = 0;
5919 gen.print = print;
5920 gen.print_user = user;
5921 gen.types.n = 0;
5922 gen.types.name = NULL;
5924 if (options->debug->dump_sizes) {
5925 isl_space *space = isl_space_params_alloc(ctx, 0);
5926 gen.used_sizes = isl_union_map_empty(space);
5929 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5931 if (options->debug->dump_sizes) {
5932 isl_union_map_dump(gen.used_sizes);
5933 isl_union_map_free(gen.used_sizes);
5936 isl_union_map_free(gen.sizes);
5937 for (i = 0; i < gen.types.n; ++i)
5938 free(gen.types.name[i]);
5939 free(gen.types.name);
5941 return r;
5944 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5946 struct gpu_prog *prog;
5947 isl_space *space;
5948 isl_map *id;
5950 if (!scop)
5951 return NULL;
5953 prog = isl_calloc_type(ctx, struct gpu_prog);
5954 assert(prog);
5956 prog->ctx = ctx;
5957 prog->scop = scop;
5958 prog->context = isl_set_copy(scop->context);
5959 prog->n_stmts = scop->pet->n_stmt;
5960 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5961 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5962 space = isl_union_map_get_space(prog->any_to_outer);
5963 space = isl_space_set_from_params(space);
5964 space = isl_space_add_dims(space, isl_dim_set, 1);
5965 space = isl_space_map_from_set(space);
5966 id = isl_map_identity(space);
5967 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
5968 prog->stmts = extract_stmts(ctx, scop,
5969 prog->context, prog->any_to_outer);
5970 prog->read = isl_union_map_copy(scop->reads);
5971 prog->may_write = isl_union_map_copy(scop->may_writes);
5972 prog->must_write = isl_union_map_copy(scop->must_writes);
5973 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
5974 prog->to_outer = isl_union_map_copy(prog->to_inner);
5975 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5977 if (!prog->stmts)
5978 return gpu_prog_free(prog);
5980 if (collect_array_info(prog) < 0)
5981 return gpu_prog_free(prog);
5983 return prog;
5986 void *gpu_prog_free(struct gpu_prog *prog)
5988 if (!prog)
5989 return NULL;
5990 free_array_info(prog);
5991 free_stmts(prog->stmts, prog->n_stmts);
5992 isl_union_map_free(prog->any_to_outer);
5993 isl_union_map_free(prog->to_outer);
5994 isl_union_map_free(prog->to_inner);
5995 isl_union_set_free(prog->copy_in);
5996 isl_union_set_free(prog->copy_out);
5997 isl_union_map_free(prog->read);
5998 isl_union_map_free(prog->may_write);
5999 isl_union_map_free(prog->must_write);
6000 isl_union_map_free(prog->array_order);
6001 isl_set_free(prog->context);
6002 free(prog);
6003 return NULL;