README: add a note about additional variables in the generated code
[ppcg.git] / gpu.c
blobd47c9f4a7addd082b4be94e171b0206fc42ba782
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012-2013 Ecole Normale Superieure
5 * Use of this software is governed by the MIT license
7 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
8 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
9 * 91893 Orsay, France
10 * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
13 #include <assert.h>
14 #include <stdlib.h>
15 #include <string.h>
17 #include <isl/polynomial.h>
18 #include <isl/union_set.h>
19 #include <isl/aff.h>
20 #include <isl/ilp.h>
21 #include <isl/flow.h>
22 #include <isl/band.h>
23 #include <isl/schedule.h>
24 #include <isl/options.h>
25 #include <isl/ast_build.h>
27 #include "cpu.h"
28 #include "gpu.h"
29 #include "schedule.h"
30 #include "ppcg_options.h"
31 #include "print.h"
33 /* The fields stride, shift and shift_map only contain valid information
34 * if shift != NULL.
35 * If so, they express that current index is such that if you add shift,
36 * then the result is always a multiple of stride.
37 * shift_map contains the mapping
39 * i -> (i + shift)/stride
41 * Let D represent the initial shared_len dimensions of the computed schedule.
42 * The spaces of "lb" and "shift" are of the form
44 * D -> [b]
46 * "shift_map" is of the form
48 * [D -> i] -> [D -> (i + shift(D))/stride]
50 struct gpu_array_bound {
51 isl_val *size;
52 isl_aff *lb;
54 isl_val *stride;
55 isl_aff *shift;
56 isl_basic_map *shift_map;
59 /* A tile of an array.
61 * n is the dimension of the array.
62 * bound is an array of size "n" representing the lower bound
63 * and size for each index.
65 * tiling maps a tile in the global array to the corresponding
66 * shared/private memory tile and is of the form
68 * { [D[i] -> A[a]] -> T[(a + shift(i))/stride - lb(i)] }
70 * where D represents the initial shared_len dimensions
71 * of the computed schedule.
73 struct gpu_array_tile {
74 int n;
75 struct gpu_array_bound *bound;
76 isl_multi_aff *tiling;
79 struct gpu_array_info;
81 /* A group of array references in a kernel that should be handled together.
82 * If private_tile is not NULL, then it is mapped to registers.
83 * Otherwise, if shared_tile is not NULL, it is mapped to shared memory.
84 * Otherwise, it is accessed from global memory.
86 struct gpu_array_ref_group {
87 /* The references in this group access this array. */
88 struct gpu_array_info *array;
89 /* Position of this group in the list of reference groups of array. */
90 int nr;
92 /* The following fields are use during the construction of the groups.
93 * access is the combined access relation relative to the shared
94 * memory tiling. In particular, the domain of the map corresponds
95 * to the first shared_len dimensions of the computed schedule.
96 * write is set if any access in the group is a write.
97 * exact_write is set if all writes are definite writes.
99 isl_map *access;
100 int write;
101 int exact_write;
103 /* The shared memory tile, NULL if none. */
104 struct gpu_array_tile *shared_tile;
106 /* The private memory tile, NULL if none. */
107 struct gpu_array_tile *private_tile;
109 /* References in this group; point to elements of a linked list. */
110 int n_ref;
111 struct gpu_stmt_access **refs;
113 /* Last shared memory tile dimension that affects tile of this group. */
114 int last_shared;
117 struct gpu_gen {
118 isl_ctx *ctx;
119 struct ppcg_options *options;
121 /* Callback for printing of AST in appropriate format. */
122 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
123 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
124 struct gpu_types *types, void *user);
125 void *print_user;
127 struct gpu_prog *prog;
128 /* The generated AST. */
129 isl_ast_node *tree;
131 /* The sequence of types for which a definition has been printed. */
132 struct gpu_types types;
134 /* tile, grid and block sizes for each kernel */
135 isl_union_map *sizes;
137 /* Identifier of current kernel. */
138 int kernel_id;
139 /* Pointer to the current kernel. */
140 struct ppcg_kernel *kernel;
141 /* Does the computed schedule exhibit any parallelism? */
142 int any_parallelism;
144 /* First tile dimension. */
145 int tile_first;
146 /* Number of tile dimensions. */
147 int tile_len;
148 /* Number of initial parallel loops among tile dimensions. */
149 int n_parallel;
151 /* Number of dimensions determining shared memory. */
152 int shared_len;
154 /* Number of rows in the untiled schedule. */
155 int untiled_len;
156 /* Number of rows in the tiled schedule. */
157 int tiled_len;
158 /* Number of rows in schedule after tiling/wrapping over threads. */
159 int thread_tiled_len;
161 /* Global untiled schedule. */
162 isl_union_map *sched;
163 /* Local (per kernel launch) tiled schedule. */
164 isl_union_map *tiled_sched;
165 /* Local schedule per shared memory tile loop iteration. */
166 isl_union_map *local_sched;
168 /* Local tiled schedule projected onto the shared tile loops and
169 * the loops that will be wrapped over the threads,
170 * with all shared tile loops parametrized.
172 isl_union_map *shared_sched;
173 /* Projects out the loops that will be wrapped over the threads
174 * from shared_sched.
176 isl_union_map *shared_proj;
178 /* A map that takes the range of shared_sched as input,
179 * wraps the appropriate loops over the threads and then projects
180 * out these loops.
182 isl_map *privatization;
184 /* A map from the shared memory tile loops and the thread indices
185 * (as parameters) to the set of accessed memory elements that
186 * will be accessed through private copies.
188 isl_union_map *private_access;
190 /* The schedule for the current private/shared access
191 * (within print_private_access or print_shared_access).
193 isl_map *copy_sched;
194 /* The array reference group corresponding to copy_sched. */
195 struct gpu_array_ref_group *copy_group;
197 /* Is any array in the current kernel marked force_private? */
198 int any_force_private;
200 /* First loop to unroll (or -1 if none) in the current part of the
201 * schedule.
203 int first_unroll;
205 int n_grid;
206 int n_block;
207 /* Note: in the input file, the sizes of the grid and the blocks
208 * are specified in the order x, y, z, but internally, the sizes
209 * are stored in reverse order, so that the last element always
210 * refers to the x dimension.
212 int grid_dim[2];
213 int block_dim[3];
214 int *tile_size;
217 /* Print the name of the local copy of a given group of array references.
219 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
220 struct gpu_array_ref_group *group)
222 int global = 0;
224 if (group->private_tile)
225 p = isl_printer_print_str(p, "private_");
226 else if (group->shared_tile)
227 p = isl_printer_print_str(p, "shared_");
228 else
229 global = 1;
230 p = isl_printer_print_str(p, group->array->name);
231 if (!global && group->array->n_group > 1) {
232 p = isl_printer_print_str(p, "_");
233 p = isl_printer_print_int(p, group->nr);
236 return p;
239 /* Collect all references to the given array and store pointers to them
240 * in array->refs.
242 * If the array contains structures, then there is no need to collect
243 * the references since we will not be computing any reference groups.
245 static void collect_references(struct gpu_prog *prog,
246 struct gpu_array_info *array)
248 int i;
249 int n;
251 if (array->has_compound_element)
252 return;
254 n = 0;
255 for (i = 0; i < prog->n_stmts; ++i) {
256 struct gpu_stmt *stmt = &prog->stmts[i];
257 struct gpu_stmt_access *access;
259 for (access = stmt->accesses; access; access = access->next) {
260 const char *name;
261 name = isl_map_get_tuple_name(access->access,
262 isl_dim_out);
263 if (name && !strcmp(array->name, name))
264 n++;
268 array->n_ref = n;
269 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
270 assert(array->refs);
272 n = 0;
273 for (i = 0; i < prog->n_stmts; ++i) {
274 struct gpu_stmt *stmt = &prog->stmts[i];
275 struct gpu_stmt_access *access;
277 for (access = stmt->accesses; access; access = access->next) {
278 const char *name;
279 name = isl_map_get_tuple_name(access->access,
280 isl_dim_out);
281 if (!name || strcmp(array->name, name))
282 continue;
284 array->refs[n++] = access;
289 /* Create a gpu_array_tile for an array of dimension "n_index".
291 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
293 int i;
294 struct gpu_array_tile *tile;
296 tile = isl_calloc_type(ctx, struct gpu_array_tile);
297 assert(tile);
299 tile->n = n_index;
301 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
302 assert(tile->bound);
304 for (i = 0; i < n_index; ++i) {
305 tile->bound[i].size = NULL;
306 tile->bound[i].lb = NULL;
307 tile->bound[i].stride = NULL;
308 tile->bound[i].shift = NULL;
309 tile->bound[i].shift_map = NULL;
312 return tile;
315 static void *free_tile(struct gpu_array_tile *tile)
317 int j;
319 if (!tile)
320 return NULL;
322 for (j = 0; j < tile->n; ++j) {
323 isl_val_free(tile->bound[j].size);
324 isl_val_free(tile->bound[j].stride);
325 isl_aff_free(tile->bound[j].lb);
326 isl_aff_free(tile->bound[j].shift);
327 isl_basic_map_free(tile->bound[j].shift_map);
329 free(tile->bound);
330 isl_multi_aff_free(tile->tiling);
331 free(tile);
333 return NULL;
336 static struct pet_array *find_array(struct ppcg_scop *scop,
337 __isl_keep isl_set *accessed)
339 int i;
340 isl_id *id;
342 id = isl_set_get_tuple_id(accessed);
344 for (i = 0; i < scop->n_array; ++i) {
345 isl_id *id_i;
347 id_i = isl_set_get_tuple_id(scop->arrays[i]->extent);
348 isl_id_free(id_i);
349 if (id == id_i)
350 break;
352 isl_id_free(id);
354 return i < scop->n_array ? scop->arrays[i] : NULL;
357 /* Compute and return the extent of "array", taking into account the set of
358 * accessed elements.
360 * In particular, the extent in the outer dimension is taken
361 * from "accessed", while then extent in the remaing dimensions
362 * are taken from array->extent.
364 * The extent in the outer dimension cannot be taken from array->extent
365 * because that may be unbounded. Furthermore, even if it is bounded,
366 * it may be larger than the piece of the array that is being accessed.
368 static __isl_give isl_set *compute_extent(struct pet_array *array,
369 __isl_keep isl_set *accessed)
371 int n_index;
372 isl_id *id;
373 isl_set *outer;
374 isl_set *extent;
376 extent = isl_set_copy(array->extent);
378 n_index = isl_set_dim(accessed, isl_dim_set);
379 if (n_index == 0)
380 return extent;
382 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
383 outer = isl_set_copy(accessed);
384 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
385 extent = isl_set_flat_product(outer, extent);
386 id = isl_set_get_tuple_id(accessed);
387 extent = isl_set_set_tuple_id(extent, id);
389 return extent;
392 /* Is the array "array" being extracted a read-only scalar?
394 * That is, is "array" a scalar that is never possibly written to.
395 * An array containing structures is never considered to be a scalar.
397 static int is_read_only_scalar(struct gpu_array_info *array,
398 struct gpu_prog *prog)
400 isl_set *space;
401 isl_union_map *write;
402 int empty;
404 if (array->has_compound_element)
405 return 0;
406 if (array->n_index != 0)
407 return 0;
409 write = isl_union_map_copy(prog->may_write);
410 space = isl_set_universe(isl_space_copy(array->space));
411 write = isl_union_map_intersect_range(write,
412 isl_union_set_from_set(space));
413 empty = isl_union_map_is_empty(write);
414 isl_union_map_free(write);
416 return empty;
419 /* Compute bounds on the host arrays based on the accessed elements
420 * and collect all references to the array.
422 * If the array is zero-dimensional and does not contain structures,
423 * i.e., if the array is a scalar, we check whether it is read-only.
425 static int extract_array_info(__isl_take isl_set *array, void *user)
427 int i;
428 struct gpu_prog *prog = (struct gpu_prog *)user;
429 const char *name;
430 int n_index;
431 isl_pw_aff **bounds;
432 struct pet_array *pa;
433 struct gpu_array_info *info;
434 isl_set *extent;
436 info = &prog->array[prog->n_array];
437 prog->n_array++;
439 n_index = isl_set_dim(array, isl_dim_set);
440 name = isl_set_get_tuple_name(array);
441 bounds = isl_alloc_array(isl_set_get_ctx(array),
442 isl_pw_aff *, n_index);
443 if (!bounds)
444 goto error;
446 info->space = isl_set_get_space(array);
447 info->name = strdup(name);
448 info->n_index = n_index;
449 info->bound = bounds;
450 info->linearize = prog->scop->options->linearize_device_arrays;
452 pa = find_array(prog->scop, array);
453 if (!pa)
454 isl_die(isl_set_get_ctx(array), isl_error_internal,
455 "unable to find array in scop", goto error);
457 info->type = strdup(pa->element_type);
458 info->size = pa->element_size;
459 info->local = pa->declared && !pa->exposed;
460 info->has_compound_element = pa->element_is_record;
461 info->read_only_scalar = is_read_only_scalar(info, prog);
463 extent = compute_extent(pa, array);
464 info->extent = extent;
465 for (i = 0; i < n_index; ++i) {
466 isl_set *dom;
467 isl_local_space *ls;
468 isl_aff *one;
469 isl_pw_aff *bound;
471 dom = isl_set_copy(extent);
472 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
473 n_index - (i + 1));
474 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
475 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
476 fprintf(stderr, "unable to determine extent of '%s' "
477 "in dimension %d\n", info->name, i);
478 dom = isl_set_free(dom);
480 bound = isl_set_dim_max(dom, 0);
481 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
482 ls = isl_local_space_from_space(isl_set_get_space(dom));
483 one = isl_aff_zero_on_domain(ls);
484 one = isl_aff_add_constant_si(one, 1);
485 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
486 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
488 bounds[i] = bound;
489 if (!isl_pw_aff_is_cst(bound))
490 info->linearize = 1;
493 collect_references(prog, info);
495 isl_set_free(array);
496 return 0;
497 error:
498 isl_set_free(array);
499 return -1;
502 /* Compute a mapping from all outer arrays (of structs) in scop
503 * to their innermost arrays.
505 * In particular, for each array of a primitive type, the result
506 * contains the identity mapping on that array.
507 * For each array involving member accesses, the result
508 * contains a mapping from the elements of the outer array of structs
509 * to all corresponding elements of the innermost nested arrays.
511 static __isl_give isl_union_map *compute_to_inner(struct ppcg_scop *scop)
513 int i;
514 isl_union_map *to_inner;
516 to_inner = isl_union_map_empty(isl_set_get_space(scop->context));
518 for (i = 0; i < scop->n_array; ++i) {
519 struct pet_array *array = scop->arrays[i];
520 isl_set *set;
521 isl_map *map;
523 if (array->element_is_record)
524 continue;
526 set = isl_set_copy(array->extent);
527 map = isl_set_identity(isl_set_copy(set));
529 while (set && isl_set_is_wrapping(set)) {
530 isl_id *id;
531 isl_map *wrapped;
533 id = isl_set_get_tuple_id(set);
534 wrapped = isl_set_unwrap(set);
535 wrapped = isl_map_domain_map(wrapped);
536 wrapped = isl_map_set_tuple_id(wrapped, isl_dim_in, id);
537 map = isl_map_apply_domain(map, wrapped);
538 set = isl_map_domain(isl_map_copy(map));
541 map = isl_map_gist_domain(map, set);
543 to_inner = isl_union_map_add_map(to_inner, map);
546 return to_inner;
549 /* For each array in "prog", store the (untagged) order dependences
550 * derived from the array in array->dep_order.
551 * In particular, consider all references that access the given array
552 * and take the order dependences that have one of these references
553 * as source. (Since an order dependence relates two references to
554 * the same array, the target of these order dependences will also
555 * be one of these references.)
556 * Additionally, store the union of these array->dep_order relations
557 * for all non-scalar arrays in prog->array_order.
559 void collect_order_dependences(struct gpu_prog *prog)
561 int i;
562 isl_space *space;
563 isl_union_map *accesses;
565 space = isl_union_map_get_space(prog->read);
566 prog->array_order = isl_union_map_empty(space);
568 accesses = isl_union_map_copy(prog->scop->tagged_reads);
569 accesses = isl_union_map_union(accesses,
570 isl_union_map_copy(prog->scop->tagged_may_writes));
571 accesses = isl_union_map_universe(accesses);
572 accesses = isl_union_map_apply_range(accesses,
573 isl_union_map_copy(prog->to_outer));
575 for (i = 0; i < prog->n_array; ++i) {
576 struct gpu_array_info *array = &prog->array[i];
577 isl_set *set;
578 isl_union_set *uset;
579 isl_union_map *order;
581 set = isl_set_universe(isl_space_copy(array->space));
582 uset = isl_union_set_from_set(set);
583 uset = isl_union_map_domain(
584 isl_union_map_intersect_range(isl_union_map_copy(accesses),
585 uset));
586 order = isl_union_map_copy(prog->scop->tagged_dep_order);
587 order = isl_union_map_intersect_domain(order, uset);
588 order = isl_union_map_zip(order);
589 order = isl_union_set_unwrap(isl_union_map_domain(order));
590 array->dep_order = order;
592 if (gpu_array_is_scalar(array))
593 continue;
595 prog->array_order = isl_union_map_union(prog->array_order,
596 isl_union_map_copy(array->dep_order));
599 isl_union_map_free(accesses);
602 /* Construct a gpu_array_info for each array possibly accessed by "prog" and
603 * collect them in prog->array.
605 * If there are any member accesses involved, then they are first mapped
606 * to the outer arrays of structs.
608 * If we are allowing live range reordering, then also set
609 * the dep_order field. Otherwise leave it NULL.
611 static int collect_array_info(struct gpu_prog *prog)
613 int r;
614 isl_union_set *arrays;
616 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
617 arrays = isl_union_set_union(arrays,
618 isl_union_map_range(isl_union_map_copy(prog->may_write)));
620 arrays = isl_union_set_apply(arrays,
621 isl_union_map_copy(prog->to_outer));
623 arrays = isl_union_set_coalesce(arrays);
625 prog->n_array = isl_union_set_n_set(arrays);
626 prog->array = isl_calloc_array(prog->ctx,
627 struct gpu_array_info, prog->n_array);
628 assert(prog->array);
629 prog->n_array = 0;
630 r = isl_union_set_foreach_set(arrays, &extract_array_info, prog);
631 isl_union_set_free(arrays);
633 if (prog->scop->options->live_range_reordering)
634 collect_order_dependences(prog);
636 return r;
639 static void free_array_info(struct gpu_prog *prog)
641 int i, j;
643 for (i = 0; i < prog->n_array; ++i) {
644 int n_index = prog->array[i].n_index;
645 free(prog->array[i].type);
646 free(prog->array[i].name);
647 for (j = 0; j < n_index; ++j)
648 isl_pw_aff_free(prog->array[i].bound[j]);
649 isl_space_free(prog->array[i].space);
650 isl_set_free(prog->array[i].extent);
651 free(prog->array[i].bound);
652 free(prog->array[i].refs);
653 isl_union_map_free(prog->array[i].dep_order);
655 free(prog->array);
658 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
659 * as an array or through a pointer reference, but as a single data element.
660 * At the moment, scalars are represented as zero-dimensional arrays.
661 * A zero-dimensional array containing structures is not considered
662 * to be a scalar.
664 int gpu_array_is_scalar(struct gpu_array_info *array)
666 return !array->has_compound_element && array->n_index == 0;
669 /* Is "array" a read-only scalar?
671 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
673 return array->read_only_scalar;
676 /* Return the set of parameter values for which the array has a positive
677 * size in all dimensions.
678 * If the sizes are only valid for some parameter values, then those
679 * constraints are also taken into account.
681 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
683 int i;
684 isl_space *space;
685 isl_set *guard;
687 space = isl_space_params(isl_space_copy(array->space));
688 guard = isl_set_universe(space);
690 for (i = 0; i < array->n_index; ++i) {
691 isl_pw_aff *bound;
692 isl_set *guard_i, *zero;
694 bound = isl_pw_aff_copy(array->bound[i]);
695 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
696 zero = isl_pw_aff_zero_set(bound);
697 guard_i = isl_set_subtract(guard_i, zero);
698 guard = isl_set_intersect(guard, guard_i);
701 return guard;
704 /* Internal data structure for extract_size_of_type.
705 * "type" specifies the name of the space that we want to extract.
706 * "res" is used to store the subset of that space.
708 struct ppcg_extract_size_data {
709 const char *type;
710 isl_set *res;
713 /* This function is called for each set in a union_set.
714 * If the name of the set matches data->type, we store the
715 * set in data->res.
717 static int extract_size_of_type(__isl_take isl_set *size, void *user)
719 struct ppcg_extract_size_data *data = user;
720 const char *name;
722 name = isl_set_get_tuple_name(size);
723 if (name && !strcmp(name, data->type)) {
724 data->res = size;
725 return -1;
728 isl_set_free(size);
729 return 0;
732 /* Given a union map { kernel[i] -> *[...] },
733 * return the range in the space called "type" for the kernel with
734 * sequence number "id".
736 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
737 const char *type, int id)
739 isl_space *space;
740 isl_set *dom;
741 isl_union_set *local_sizes;
742 struct ppcg_extract_size_data data = { type, NULL };
744 if (!sizes)
745 return NULL;
747 space = isl_union_map_get_space(sizes);
748 space = isl_space_set_from_params(space);
749 space = isl_space_add_dims(space, isl_dim_set, 1);
750 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
751 dom = isl_set_universe(space);
752 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
754 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
755 isl_union_map_copy(sizes));
756 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
757 isl_union_set_free(local_sizes);
758 return data.res;
761 /* Given a singleton set, extract the first (at most *len) elements
762 * of the single integer tuple into *sizes and update *len if needed.
764 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
766 int i;
767 int dim;
769 if (!set)
770 return;
772 dim = isl_set_dim(set, isl_dim_set);
773 if (dim < *len)
774 *len = dim;
776 for (i = 0; i < *len; ++i) {
777 isl_val *v;
779 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
780 assert(v);
782 sizes[i] = isl_val_get_num_si(v);
783 isl_val_free(v);
786 isl_set_free(set);
789 /* Extract user specified "tile" sizes from the "sizes" command line option,
790 * defaulting to option->tile_size in each dimension.
792 static void read_tile_sizes(struct gpu_gen *gen)
794 int n;
795 isl_set *size;
797 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
798 assert(gen->tile_size);
799 for (n = 0; n < gen->tile_len; ++n)
800 gen->tile_size[n] = gen->options->tile_size;
802 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
803 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
805 if (gen->n_parallel > gen->tile_len)
806 gen->n_parallel = gen->tile_len;
809 /* Extract user specified "block" sizes from the "sizes" command line option,
810 * after filling in some potentially useful defaults.
812 static void read_block_sizes(struct gpu_gen *gen)
814 int n;
815 isl_set *size;
817 n = gen->n_parallel;
818 gen->n_block = (n <= 3) ? n : 3;
819 switch (gen->n_block) {
820 case 1:
821 gen->block_dim[0] = 512;
822 break;
823 case 2:
824 gen->block_dim[0] = 32;
825 gen->block_dim[1] = 16;
826 break;
827 default:
828 gen->block_dim[0] = 32;
829 gen->block_dim[1] = 4;
830 gen->block_dim[2] = 4;
831 break;
834 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
835 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
838 /* Extract user specified "grid" sizes from the "sizes" command line option,
839 * after filling in some potentially useful defaults.
841 static void read_grid_sizes(struct gpu_gen *gen)
843 int n = gen->n_parallel;
844 isl_set *size;
846 gen->n_grid = (n <= 2) ? n : 2;
847 switch (gen->n_grid) {
848 case 1:
849 gen->grid_dim[0] = 32768;
850 break;
851 default:
852 gen->grid_dim[0] = 256;
853 gen->grid_dim[1] = 256;
854 break;
857 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
858 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
861 /* Extract user specified sizes from the "sizes" command line option
862 * after filling in some potentially useful defaults.
864 static void read_sizes(struct gpu_gen *gen)
866 read_tile_sizes(gen);
867 read_block_sizes(gen);
868 read_grid_sizes(gen);
871 static void *free_stmts(struct gpu_stmt *stmts, int n)
873 int i;
875 if (!stmts)
876 return NULL;
878 for (i = 0; i < n; ++i) {
879 struct gpu_stmt_access *access, *next;
881 for (access = stmts[i].accesses; access; access = next) {
882 next = access->next;
883 isl_id_free(access->ref_id);
884 isl_map_free(access->access);
885 isl_map_free(access->tagged_access);
886 free(access);
889 isl_id_free(stmts[i].id);
891 free(stmts);
893 return NULL;
896 /* Construct a map from a domain of dimensionality "len"
897 * to a domain of dimensionality "len" + "tile_len" that tiles
898 * the "tile_len" coordinates starting at "first".
899 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
900 * "dim" prescribes the parameters.
902 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
903 int first, int tile_len, int *tile_size)
905 int i;
906 isl_basic_map *bmap;
907 isl_constraint *c;
908 isl_local_space *ls;
910 dim = isl_space_add_dims(dim, isl_dim_in, len);
911 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
912 bmap = isl_basic_map_universe(isl_space_copy(dim));
913 ls = isl_local_space_from_space(dim);
915 for (i = 0; i < len - tile_len; ++i) {
916 int j = i < first ? i : i + tile_len;
917 int k = i < first ? i : i + 2 * tile_len;
919 c = isl_equality_alloc(isl_local_space_copy(ls));
920 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
921 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
922 bmap = isl_basic_map_add_constraint(bmap, c);
925 for (i = 0; i < tile_len; ++i) {
926 c = isl_equality_alloc(isl_local_space_copy(ls));
927 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
928 first + i, -1);
929 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
930 first + i, tile_size[i]);
931 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
932 first + i + tile_len, 1);
933 bmap = isl_basic_map_add_constraint(bmap, c);
935 c = isl_inequality_alloc(isl_local_space_copy(ls));
936 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
937 first + i + tile_len, 1);
938 bmap = isl_basic_map_add_constraint(bmap, c);
940 c = isl_inequality_alloc(isl_local_space_copy(ls));
941 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
942 first + i + tile_len, -1);
943 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
944 bmap = isl_basic_map_add_constraint(bmap, c);
947 isl_local_space_free(ls);
949 return isl_map_from_basic_map(bmap);
952 /* Construct a map from a domain of dimensionality "len"
953 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
954 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
955 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
956 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
957 * that are projected out at the end.
958 * "dim" prescribes the parameters.
960 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
961 int first, int wrap_len, int *wrap_size)
963 int i;
964 isl_basic_map *bmap;
965 isl_constraint *c;
966 isl_local_space *ls;
968 dim = isl_space_add_dims(dim, isl_dim_in, len);
969 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
970 bmap = isl_basic_map_universe(isl_space_copy(dim));
971 ls = isl_local_space_from_space(dim);
973 for (i = 0; i < len; ++i) {
974 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
976 c = isl_equality_alloc(isl_local_space_copy(ls));
977 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
978 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
979 bmap = isl_basic_map_add_constraint(bmap, c);
982 for (i = 0; i < wrap_len; ++i) {
983 c = isl_equality_alloc(isl_local_space_copy(ls));
984 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
985 first + i, -1);
986 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
987 first + wrap_len + i, 1);
988 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
989 first + 2 * wrap_len + i, wrap_size[i]);
990 bmap = isl_basic_map_add_constraint(bmap, c);
992 c = isl_inequality_alloc(isl_local_space_copy(ls));
993 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
994 first + wrap_len + i, 1);
995 bmap = isl_basic_map_add_constraint(bmap, c);
997 c = isl_inequality_alloc(isl_local_space_copy(ls));
998 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
999 first + wrap_len + i, -1);
1000 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
1001 bmap = isl_basic_map_add_constraint(bmap, c);
1004 isl_local_space_free(ls);
1006 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
1007 first + 2 * wrap_len, wrap_len);
1009 return isl_map_from_basic_map(bmap);
1012 /* Add "n" parameters named prefix%d.
1014 static __isl_give isl_set *add_params( __isl_take isl_set *set,
1015 int n, const char *prefix)
1017 int i;
1018 unsigned nparam;
1019 char name[20];
1021 nparam = isl_set_dim(set, isl_dim_param);
1022 set = isl_set_add_dims(set, isl_dim_param, n);
1024 for (i = 0; i < n; ++i) {
1025 snprintf(name, sizeof(name), "%s%d", prefix, i);
1026 set = isl_set_set_dim_name(set, isl_dim_param,
1027 nparam + i, name);
1030 return set;
1033 /* Equate the "n" dimensions of "set" starting at "first" to
1034 * freshly created parameters named prefix%d.
1036 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
1037 int first, int n, const char *prefix)
1039 int i;
1040 unsigned nparam;
1042 nparam = isl_set_dim(set, isl_dim_param);
1044 set = add_params(set, n, prefix);
1046 for (i = 0; i < n; ++i)
1047 set = isl_set_equate(set, isl_dim_param, nparam + i,
1048 isl_dim_set, first + i);
1050 return set;
1053 /* Given a parameter space "space", create a set of dimension "len"
1054 * of which the "n" dimensions starting at "first" are equated to
1055 * freshly created parameters named prefix%d.
1057 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
1058 int len, int first, int n, const char *prefix)
1060 isl_set *set;
1062 space = isl_space_set_from_params(space);
1063 space = isl_space_add_dims(space, isl_dim_set, len);
1064 set = isl_set_universe(space);
1066 return parametrize(set, first, n, prefix);
1069 /* Tile the B loops over the tile sizes and then tile/wrap
1070 * the T1 loops over the blocks.
1072 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
1073 __isl_take isl_union_map *sched)
1075 isl_space *dim;
1076 isl_map *tiling, *block_tiling;
1078 dim = isl_union_map_get_space(sched);
1079 tiling = tile(isl_space_copy(dim), gen->untiled_len,
1080 gen->tile_first, gen->tile_len, gen->tile_size);
1082 if (gen->options->wrap)
1083 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
1084 gen->tile_first, gen->n_grid, gen->grid_dim);
1085 else
1086 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
1087 gen->tile_first, gen->n_grid, gen->grid_dim);
1089 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
1091 tiling = isl_map_apply_range(tiling, block_tiling);
1093 sched = isl_union_map_apply_range(sched,
1094 isl_union_map_from_map(tiling));
1096 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1098 return sched;
1101 /* Equate the "T1P" iterators in the tiled schedule "sched"
1102 * to the block dimensions.
1104 static __isl_give isl_union_map *parametrize_tiled_schedule(
1105 struct gpu_gen *gen, __isl_take isl_union_map *sched)
1107 isl_space *dim;
1108 isl_set *par;
1110 dim = isl_union_map_get_space(sched);
1111 par = parametrization(dim, gen->tiled_len,
1112 gen->tile_first + gen->n_grid, gen->n_grid, "b");
1113 sched = isl_union_map_intersect_range(sched,
1114 isl_union_set_from_set(par));
1116 return sched;
1119 /* Tile/wrap the P1 loops over the threads.
1121 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
1122 __isl_take isl_union_map *sched)
1124 isl_space *dim;
1125 isl_map *tiling;
1126 isl_set *par;
1128 dim = isl_union_map_get_space(sched);
1130 if (gen->options->wrap)
1131 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
1132 gen->shared_len, gen->n_block, gen->block_dim);
1133 else
1134 tiling = tile(isl_space_copy(dim), gen->tiled_len,
1135 gen->shared_len, gen->n_block, gen->block_dim);
1136 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
1138 sched = isl_union_map_apply_range(sched,
1139 isl_union_map_from_map(tiling));
1141 par = parametrization(dim, gen->thread_tiled_len,
1142 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1143 gen->n_block, "t");
1144 sched = isl_union_map_intersect_range(sched,
1145 isl_union_set_from_set(par));
1147 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1149 return sched;
1152 /* If the user asked for it, scale the shared memory tile loops
1153 * (T1T and T2) of "sched" by gen->tile_size[i].
1154 * If we are not performing "wrapping", then additionally scale the T1P
1155 * loops by gen->grid_dim[i].
1157 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
1158 __isl_take isl_union_map *sched)
1160 int i;
1161 isl_space *dim;
1162 isl_basic_map *scale;
1163 isl_constraint *c;
1164 isl_local_space *ls;
1166 if (!gen->options->scale_tile_loops)
1167 return sched;
1169 dim = isl_union_map_get_space(sched);
1170 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
1171 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
1172 scale = isl_basic_map_universe(isl_space_copy(dim));
1173 ls = isl_local_space_from_space(dim);
1175 for (i = 0; i < gen->tiled_len; ++i) {
1176 int f = 1;
1178 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
1179 f = gen->tile_size[i - gen->tile_first];
1180 if (!gen->options->wrap)
1181 f *= gen->grid_dim[i - gen->tile_first];
1182 } else if (i >= gen->tile_first + gen->n_grid &&
1183 i < gen->tile_first + gen->n_grid + gen->tile_len) {
1184 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
1187 c = isl_equality_alloc(isl_local_space_copy(ls));
1188 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1189 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1190 scale = isl_basic_map_add_constraint(scale, c);
1193 isl_local_space_free(ls);
1195 sched = isl_union_map_apply_range(sched,
1196 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1198 return sched;
1201 /* If we are not performing "wrapping" and if the user asked for it,
1202 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1204 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1205 __isl_take isl_union_map *sched)
1207 int i;
1208 isl_space *dim;
1209 isl_basic_map *scale;
1210 isl_constraint *c;
1211 isl_local_space *ls;
1213 if (gen->options->wrap)
1214 return sched;
1215 if (!gen->options->scale_tile_loops)
1216 return sched;
1218 dim = isl_union_map_get_space(sched);
1219 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1220 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1221 scale = isl_basic_map_universe(isl_space_copy(dim));
1222 ls = isl_local_space_from_space(dim);
1224 for (i = 0; i < gen->thread_tiled_len; ++i) {
1225 int f = 1;
1227 if (i >= gen->shared_len &&
1228 i < gen->shared_len + gen->n_block)
1229 f = gen->block_dim[i - gen->shared_len];
1231 c = isl_equality_alloc(isl_local_space_copy(ls));
1232 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1233 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1234 scale = isl_basic_map_add_constraint(scale, c);
1237 isl_local_space_free(ls);
1239 sched = isl_union_map_apply_range(sched,
1240 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1242 return sched;
1245 /* If we are not performing "wrapping" and if the user asked for it,
1246 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1248 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1249 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1251 int i;
1252 isl_space *dim;
1253 isl_basic_map *scale;
1254 isl_constraint *c;
1255 isl_local_space *ls;
1257 if (gen->options->wrap)
1258 return sched;
1259 if (!gen->options->scale_tile_loops)
1260 return sched;
1262 dim = isl_union_map_get_space(sched);
1263 dim = isl_space_add_dims(dim, isl_dim_in, len);
1264 dim = isl_space_add_dims(dim, isl_dim_out, len);
1265 scale = isl_basic_map_universe(isl_space_copy(dim));
1266 ls = isl_local_space_from_space(dim);
1268 for (i = 0; i < len; ++i) {
1269 int f = 1;
1271 if (i >= first && i < first + n_tile)
1272 f = gen->kernel->block_dim[i - first];
1274 c = isl_equality_alloc(isl_local_space_copy(ls));
1275 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1276 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1277 scale = isl_basic_map_add_constraint(scale, c);
1280 isl_local_space_free(ls);
1282 sched = isl_union_map_apply_range(sched,
1283 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1285 return sched;
1288 /* Add "len" parameters p[i] called prefix%d,
1289 * with bounds to 0 <= p[i] < size[i].
1291 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1292 int len, int *size, const char *prefix)
1294 int i;
1295 unsigned nparam;
1296 isl_space *dim;
1297 isl_basic_set *bset;
1298 isl_constraint *c;
1299 isl_local_space *ls;
1300 char name[20];
1302 nparam = isl_set_dim(set, isl_dim_param);
1303 set = isl_set_add_dims(set, isl_dim_param, len);
1305 for (i = 0; i < len; ++i) {
1306 snprintf(name, sizeof(name), "%s%d", prefix, i);
1307 set = isl_set_set_dim_name(set, isl_dim_param,
1308 nparam + i, name);
1311 dim = isl_set_get_space(set);
1312 bset = isl_basic_set_universe(isl_space_copy(dim));
1313 ls = isl_local_space_from_space(dim);
1315 for (i = 0; i < len; ++i) {
1316 c = isl_inequality_alloc(isl_local_space_copy(ls));
1317 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1318 nparam + i, 1);
1319 bset = isl_basic_set_add_constraint(bset, c);
1321 c = isl_inequality_alloc(isl_local_space_copy(ls));
1322 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1323 nparam + i, -1);
1324 c = isl_constraint_set_constant_si(c, size[i] - 1);
1325 bset = isl_basic_set_add_constraint(bset, c);
1328 isl_local_space_free(ls);
1330 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1333 /* Add "len" parameters p[i] called prefix%d,
1334 * with bounds to 0 <= p[i] < size[i].
1336 static __isl_give isl_set *add_bounded_parameters_dynamic(
1337 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1338 const char *prefix)
1340 int i, len;
1341 unsigned nparam;
1342 isl_space *space;
1343 isl_local_space *ls;
1344 char name[20];
1346 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1347 nparam = isl_set_dim(set, isl_dim_param);
1348 set = isl_set_add_dims(set, isl_dim_param, len);
1350 for (i = 0; i < len; ++i) {
1351 snprintf(name, sizeof(name), "%s%d", prefix, i);
1352 set = isl_set_set_dim_name(set, isl_dim_param,
1353 nparam + i, name);
1356 space = isl_space_params(isl_set_get_space(set));
1357 ls = isl_local_space_from_space(space);
1358 for (i = 0; i < len; ++i) {
1359 isl_pw_aff *param, *size_i, *zero;
1360 isl_set *bound;
1362 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1363 isl_dim_param, nparam + i);
1365 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1366 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1367 set = isl_set_intersect_params(set, bound);
1369 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1370 bound = isl_pw_aff_ge_set(param, zero);
1371 set = isl_set_intersect_params(set, bound);
1373 isl_local_space_free(ls);
1375 return set;
1378 /* Construct a map from an access to group->array to the corresponding
1379 * shared/private memory tile.
1380 * The map is of the form
1382 * { [D[i] -> A[a]] -> T[t] }
1384 * where D represents the initial shared_len dimensions
1385 * of the computed schedule.
1387 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1389 struct gpu_array_tile *tile;
1390 isl_multi_aff *tiling;
1392 tile = group->private_tile;
1393 if (!tile)
1394 tile = group->shared_tile;
1396 tiling = isl_multi_aff_copy(tile->tiling);
1398 return isl_map_from_multi_aff(tiling);
1401 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1403 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1404 unsigned pos)
1406 isl_val *v;
1407 int fixed;
1409 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1410 if (!v)
1411 return -1;
1412 fixed = isl_val_is_int(v);
1413 isl_val_free(v);
1415 return fixed;
1418 /* Given a schedule that iterates over all elements in a piece of an array,
1419 * perform tiling/wrapping over the threads.
1421 * In particular, we tile the final iterators so that the final thread
1422 * dimension runs over the final array dimension.
1423 * However, if those final iterators have only a single iteration,
1424 * we try to tile earlier iterators instead.
1426 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1427 __isl_take isl_map *sched)
1429 isl_space *dim;
1430 isl_union_map *usched;
1431 isl_map *tiling;
1432 isl_set *par;
1433 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1434 int n_tile;
1435 int first;
1437 n_tile = gen->kernel->n_block;
1438 if (n_tile > nvar) {
1439 int i;
1440 sched = isl_map_insert_dims(sched,
1441 isl_dim_out, 0, n_tile - nvar);
1442 for (i = 0; i < n_tile - nvar; ++i)
1443 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1444 nvar = n_tile;
1447 first = nvar - n_tile;
1449 for (; first > 0; first --)
1450 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1451 break;
1453 dim = isl_map_get_space(sched);
1454 dim = isl_space_params(dim);
1455 if (gen->options->wrap)
1456 tiling = wrap(isl_space_copy(dim), nvar, first,
1457 n_tile, gen->kernel->block_dim);
1458 else
1459 tiling = tile(isl_space_copy(dim), nvar, first,
1460 n_tile, gen->kernel->block_dim);
1461 sched = isl_map_apply_range(sched, tiling);
1463 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1464 sched = isl_map_intersect_range(sched, par);
1466 usched = isl_union_map_from_map(sched);
1467 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1468 first, n_tile);
1469 sched = isl_map_from_union_map(usched);
1471 return sched;
1474 /* Return the union of all read (read = 1) and/or write (write = 1)
1475 * access relations in the group.
1477 static __isl_give isl_union_map *group_access_relation(
1478 struct gpu_array_ref_group *group, int read, int write)
1480 int i;
1481 isl_union_map *access;
1483 access = isl_union_map_empty(isl_map_get_space(group->access));
1484 for (i = 0; i < group->n_ref; ++i) {
1485 isl_map *map_i;
1487 if (!((read && group->refs[i]->read) ||
1488 (write && group->refs[i]->write)))
1489 continue;
1490 map_i = isl_map_copy(group->refs[i]->access);
1491 access = isl_union_map_union(access,
1492 isl_union_map_from_map(map_i));
1495 return access;
1498 /* Return the union of all tagged access relations in the group.
1500 static __isl_give isl_union_map *group_tagged_access_relation(
1501 struct gpu_array_ref_group *group)
1503 int i;
1504 isl_union_map *access;
1506 access = isl_union_map_empty(isl_map_get_space(group->access));
1507 for (i = 0; i < group->n_ref; ++i) {
1508 isl_map *map_i;
1510 map_i = isl_map_copy(group->refs[i]->tagged_access);
1511 access = isl_union_map_union(access,
1512 isl_union_map_from_map(map_i));
1515 return access;
1518 /* Return the extent of "array", recomputed from the bounds.
1519 * The recomputed extent may be simpler than the original extent.
1521 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1523 int i;
1524 isl_id *id;
1525 isl_space *space;
1526 isl_local_space *ls;
1527 isl_set *extent;
1529 id = isl_set_get_tuple_id(array->extent);
1530 space = isl_set_get_space(array->extent);
1531 extent = isl_set_universe(isl_space_copy(space));
1532 ls = isl_local_space_from_space(space);
1533 for (i = 0; i < array->n_index; ++i) {
1534 isl_pw_aff *bound;
1535 isl_aff *aff;
1536 isl_pw_aff *index;
1537 isl_set *lt;
1539 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1541 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1542 isl_dim_set, i);
1543 index = isl_pw_aff_from_aff(aff);
1544 bound = isl_pw_aff_copy(array->bound[i]);
1545 bound = isl_pw_aff_from_range(bound);
1546 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1547 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1548 isl_id_copy(id));
1549 lt = isl_pw_aff_lt_set(index, bound);
1550 extent = isl_set_intersect(extent, lt);
1552 isl_local_space_free(ls);
1553 isl_id_free(id);
1555 return extent;
1558 /* Return a map from the first shared_len dimensions of the computed
1559 * schedule to the array tile in
1560 * global memory that corresponds to the shared memory copy.
1562 * In particular, return a map
1564 * { D[i] -> A[a] }
1566 * with constraints
1568 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1570 * and
1572 * 0 <= a <= array_size - 1 (2)
1574 * Note that if some stride has been detected (i.e., when
1575 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1576 * to the shifted and scaled down version.
1578 * Constraints (1) are obtained by mapping the size constraints on the
1579 * shared/private memory tile back to the access relation.
1580 * Constraints (2) are obtained from the (recomputed) extent.
1582 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1584 int i;
1585 int n_index = group->array->n_index;
1586 isl_map *tile;
1587 isl_space *space;
1588 isl_set *local;
1589 isl_set *extent;
1591 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1592 space = isl_space_range(space);
1593 local = isl_set_universe(space);
1594 for (i = 0; i < n_index; ++i) {
1595 isl_val *bound;
1597 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1598 bound = isl_val_copy(group->shared_tile->bound[i].size);
1599 bound = isl_val_sub_ui(bound, 1);
1600 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1602 local = isl_set_preimage_multi_aff(local,
1603 isl_multi_aff_copy(group->shared_tile->tiling));
1604 tile = isl_set_unwrap(local);
1605 extent = array_extent(group->array);
1606 tile = isl_map_intersect_range(tile, extent);
1608 return tile;
1611 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1612 * return the corresponding mapping from the AST schedule to
1613 * to the first shared_len dimensions of the schedule computed by PPCG.
1615 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1616 __isl_take isl_pw_multi_aff *iterator_map)
1618 isl_union_map *umap;
1619 isl_space *space;
1620 isl_map *map, *sched;;
1622 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1623 space = isl_space_from_domain(space);
1624 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1626 umap = isl_union_map_copy(gen->shared_sched);
1627 umap = isl_union_map_apply_range(umap,
1628 isl_union_map_copy(gen->shared_proj));
1629 map = isl_union_map_extract_map(umap, space);
1630 isl_union_map_free(umap);
1632 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1633 sched = isl_map_detect_equalities(sched);
1635 return isl_pw_multi_aff_from_map(sched);
1638 /* Set unroll[j] if the input dimension j is involved in
1639 * the index expression represented by ma.
1641 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1642 void *user)
1644 int i, j;
1645 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1646 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1647 int *unroll = user;
1649 for (i = 0; i < n_out; ++i) {
1650 isl_aff *aff;
1652 aff = isl_multi_aff_get_aff(ma, i);
1653 for (j = 0; j < n_in; ++j)
1654 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1655 unroll[j] = 1;
1656 isl_aff_free(aff);
1659 isl_set_free(set);
1660 isl_multi_aff_free(ma);
1661 return 0;
1664 /* Given an array pos mapping input dimensions to the corresponding
1665 * output dimension, construct the corresponding map.
1667 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1668 int *pos, int len)
1670 int i;
1671 isl_constraint *c;
1672 isl_basic_map *bmap;
1673 isl_local_space *ls;
1675 dim = isl_space_add_dims(dim, isl_dim_in, len);
1676 dim = isl_space_add_dims(dim, isl_dim_out, len);
1677 bmap = isl_basic_map_universe(isl_space_copy(dim));
1678 ls = isl_local_space_from_space(dim);
1680 for (i = 0; i < len; ++i) {
1681 c = isl_equality_alloc(isl_local_space_copy(ls));
1682 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1683 -1);
1684 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1686 bmap = isl_basic_map_add_constraint(bmap, c);
1688 isl_local_space_free(ls);
1690 return isl_map_from_basic_map(bmap);
1693 /* Remove the private tiles from all array reference groups,
1694 * except for the groups of arrays that are marked force_private.
1696 static void remove_private_tiles(struct gpu_gen *gen)
1698 int i, j;
1700 for (i = 0; i < gen->prog->n_array; ++i) {
1701 struct gpu_array_info *array = &gen->prog->array[i];
1703 if (array->force_private)
1704 continue;
1706 for (j = 0; j < array->n_group; ++j) {
1707 struct gpu_array_ref_group *group = array->groups[j];
1709 group->private_tile = free_tile(group->private_tile);
1714 /* Find all loops involved in any of the index expressions for any of
1715 * the private accesses, move them innermost and then mark them as
1716 * requiring unrolling by setting gen->first_unroll.
1717 * The loops involved should all be parallel because of the checks
1718 * we performed in check_private_group_access. Moving them innermost
1719 * is therefore a valid transformation.
1721 * If any of the arrays are marked force_private, however, then
1722 * those loops may not be parallel with respect to the marked arrays.
1723 * If any of the loops would have to be moved innermost for the
1724 * (non forced) private accesses and if there are any force_private
1725 * arrays, then we revert the decision to map the selected arrays
1726 * to private memory. An alternative solution would be to expand
1727 * the force_private arrays.
1729 * Loops up to gen->shared_len are generated before the mapping to
1730 * threads is applied. They should therefore be ignored.
1732 * We compute the hidden equalities of the schedule first
1733 * since we will need them in our calls to isl_pw_multi_aff_from_map
1734 * and because we want to make sure that the same equalities
1735 * are also available to the code generator.
1737 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1738 __isl_take isl_union_map *sched)
1740 int i, j;
1741 int unroll[gen->thread_tiled_len];
1742 int perm[gen->thread_tiled_len];
1743 isl_space *dim;
1744 isl_map *permute;
1745 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1747 gen->first_unroll = -1;
1749 sched = isl_union_map_detect_equalities(sched);
1750 for (i = 0; i < gen->thread_tiled_len; ++i)
1751 unroll[i] = 0;
1752 for (i = 0; i < gen->prog->n_array; ++i) {
1753 struct gpu_array_info *array = &gen->prog->array[i];
1755 for (j = 0; j < array->n_group; ++j) {
1756 isl_union_map *access;
1757 isl_map *acc;
1758 isl_pw_multi_aff *pma;
1760 if (!array->groups[j]->private_tile)
1761 continue;
1763 access = group_access_relation(array->groups[j], 1, 1);
1764 access = isl_union_map_apply_domain(access,
1765 isl_union_map_copy(sched));
1767 acc = isl_map_from_union_map(access);
1768 pma = isl_pw_multi_aff_from_map(acc);
1769 isl_pw_multi_aff_foreach_piece(pma,
1770 &check_unroll, unroll);
1772 isl_pw_multi_aff_free(pma);
1776 for (i = gen->shared_len; i < len; ++i)
1777 if (unroll[i])
1778 break;
1780 if (i >= len)
1781 return sched;
1783 for (i = len; i < gen->thread_tiled_len; ++i)
1784 if (unroll[i])
1785 return sched;
1787 if (gen->any_force_private) {
1788 remove_private_tiles(gen);
1789 return sched;
1792 j = 0;
1793 for (i = 0; i < gen->shared_len; ++i)
1794 perm[i] = j++;
1795 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1796 if (!unroll[i])
1797 perm[i] = j++;
1798 gen->first_unroll = j - gen->shared_len;
1799 for (i = gen->shared_len; i < len; ++i)
1800 if (unroll[i])
1801 perm[i] = j++;
1803 dim = isl_union_map_get_space(sched);
1804 permute = permutation(dim, perm, gen->thread_tiled_len);
1805 sched = isl_union_map_apply_range(sched,
1806 isl_union_map_from_map(permute));
1808 return sched;
1811 /* Given a constraint
1813 * a(p,i) + j = g f(e)
1815 * or -a(p,i) - j = g f(e) if sign < 0,
1816 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1817 * a(p,i) is assumed to be an expression in only the parameters
1818 * and the input dimensions.
1820 static void extract_stride(__isl_keep isl_constraint *c,
1821 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1823 int i;
1824 isl_val *v;
1825 isl_space *space;
1826 unsigned nparam;
1827 unsigned nvar;
1828 isl_aff *aff;
1830 isl_val_free(bound->stride);
1831 bound->stride = isl_val_copy(stride);
1833 space = isl_constraint_get_space(c);
1834 space = isl_space_domain(space);
1836 nparam = isl_space_dim(space, isl_dim_param);
1837 nvar = isl_space_dim(space, isl_dim_set);
1839 v = isl_constraint_get_constant_val(c);
1840 if (sign < 0)
1841 v = isl_val_neg(v);
1842 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1843 aff = isl_aff_set_constant_val(aff, v);
1845 for (i = 0; i < nparam; ++i) {
1846 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1847 continue;
1848 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1849 if (sign < 0)
1850 v = isl_val_neg(v);
1851 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1854 for (i = 0; i < nvar; ++i) {
1855 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1856 continue;
1857 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1858 if (sign < 0)
1859 v = isl_val_neg(v);
1860 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1863 bound->shift = aff;
1866 /* Given an equality constraint of a map with a single output dimension j,
1867 * check if the constraint is of the form
1869 * a(p,i) + j = g f(e)
1871 * with a(p,i) an expression in the parameters and input dimensions
1872 * and f(e) an expression in the existentially quantified variables.
1873 * If so, and if g is larger than any such g from a previously considered
1874 * constraint, then call extract_stride to record the stride information
1875 * in bound.
1877 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1879 int i;
1880 isl_ctx *ctx;
1881 isl_val *v;
1882 unsigned n_div;
1883 struct gpu_array_bound *bound = user;
1885 ctx = isl_constraint_get_ctx(c);
1886 n_div = isl_constraint_dim(c, isl_dim_div);
1887 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1889 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1890 int s = isl_val_sgn(v);
1891 isl_val *stride = isl_val_zero(ctx);
1893 isl_val_free(v);
1894 for (i = 0; i < n_div; ++i) {
1895 v = isl_constraint_get_coefficient_val(c,
1896 isl_dim_div, i);
1897 stride = isl_val_gcd(stride, v);
1899 if (!isl_val_is_zero(stride) &&
1900 isl_val_gt(stride, bound->stride))
1901 extract_stride(c, bound, stride, s);
1903 isl_val_free(stride);
1904 } else
1905 isl_val_free(v);
1907 isl_constraint_free(c);
1908 return 0;
1911 /* Given contraints on an array index i, check if we can find
1912 * a shift a(p) and a stride g such that
1914 * a(p) + i = 0 mod g
1916 * If so, record the information in bound and apply the mapping
1917 * i -> (i + a(p))/g to the array index in bounds and return
1918 * the new constraints.
1919 * If not, simply return the original constraints.
1921 * If bounds is a subset of the space
1923 * D -> i
1925 * then the bound recorded in bound->shift is of the form
1927 * D -> s(D)
1929 * with s(D) equal to a(p) above.
1930 * The mapping recorded in bound->shift_map is of the form
1932 * [D -> i] -> [D -> (i + S(D))/g]
1934 * This mapping is computed as follows.
1935 * We first introduce "i" in the domain through precomposition
1936 * with [D -> i] -> D obtaining
1938 * [D -> i] -> s(D)
1940 * Adding [D -> i] -> i produces
1942 * [D -> i] -> i + s(D)
1944 * and the domain product with [D -> i] -> D yields
1946 * [D -> i] -> [D -> i + s(D)]
1948 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1950 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1951 __isl_take isl_basic_map *bounds)
1953 isl_space *space;
1954 isl_basic_map *hull;
1955 isl_basic_map *shift, *id, *bmap, *scale;
1956 isl_basic_set *bset;
1957 isl_aff *aff;
1959 bound->stride = NULL;
1961 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1963 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1965 isl_basic_map_free(hull);
1967 if (!bound->stride)
1968 return bounds;
1970 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1971 space = isl_basic_map_get_space(bounds);
1972 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1973 shift = isl_basic_map_apply_range(bmap, shift);
1974 space = isl_basic_map_get_space(bounds);
1975 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1976 shift = isl_basic_map_sum(id, shift);
1977 space = isl_basic_map_get_space(bounds);
1978 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1979 shift = isl_basic_map_range_product(id, shift);
1981 space = isl_space_domain(isl_basic_map_get_space(bounds));
1982 id = isl_basic_map_identity(isl_space_map_from_set(space));
1983 space = isl_space_range(isl_basic_map_get_space(bounds));
1984 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1985 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1986 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
1987 scale = isl_basic_map_from_aff(aff);
1988 scale = isl_basic_map_product(id, scale);
1990 bound->shift_map = isl_basic_map_apply_range(shift, scale);
1991 bmap = isl_basic_map_copy(bound->shift_map);
1992 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1993 bounds = isl_basic_set_unwrap(bset);
1995 return bounds;
1998 /* Data used in compute_array_dim_size and compute_size_in_direction.
2000 * pos is the position of the variable representing the array index,
2001 * i.e., the variable for which want to compute the size. This variable
2002 * is also the last variable in the set.
2004 struct gpu_size_info {
2005 isl_basic_set *bset;
2006 struct gpu_array_bound *bound;
2007 int pos;
2010 /* Given a constraint from the basic set describing the bounds on
2011 * an array index, check if it is a lower bound, say m i >= b(x), and,
2012 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
2013 * upper bound. If so, and if this bound is smaller than any bound
2014 * derived from earlier constraints, set the size to this bound on
2015 * the expression and the lower bound to ceil(b(x)/m).
2017 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
2019 struct gpu_size_info *size = user;
2020 unsigned nparam;
2021 unsigned n_div;
2022 isl_val *v;
2023 isl_aff *aff;
2024 isl_aff *lb;
2026 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
2027 n_div = isl_constraint_dim(c, isl_dim_div);
2029 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
2030 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
2031 isl_constraint_free(c);
2032 return 0;
2035 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
2036 aff = isl_aff_ceil(aff);
2038 lb = isl_aff_copy(aff);
2040 aff = isl_aff_neg(aff);
2041 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
2043 v = isl_basic_set_max_val(size->bset, aff);
2044 isl_aff_free(aff);
2046 if (isl_val_is_int(v)) {
2047 v = isl_val_add_ui(v, 1);
2048 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
2049 isl_val_free(size->bound->size);
2050 size->bound->size = isl_val_copy(v);
2051 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
2052 isl_aff_free(size->bound->lb);
2053 size->bound->lb = isl_aff_copy(lb);
2056 isl_val_free(v);
2057 isl_aff_free(lb);
2059 isl_constraint_free(c);
2061 return 0;
2064 /* Given a basic map "bounds" that maps parameters and input dimensions
2065 * to a single output dimension, look for an expression in the parameters
2066 * and input dimensions such that the range of the output dimension shifted
2067 * by this expression is a constant.
2069 * In particular, we currently only consider lower bounds on the output
2070 * dimension as candidate expressions.
2072 static int compute_array_dim_size(struct gpu_array_bound *bound,
2073 __isl_take isl_basic_map *bounds)
2075 struct gpu_size_info size;
2077 bounds = isl_basic_map_detect_equalities(bounds);
2078 bounds = check_stride(bound, bounds);
2080 bound->size = NULL;
2081 bound->lb = NULL;
2083 size.bound = bound;
2084 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2085 size.bset = isl_basic_map_wrap(bounds);
2086 size.bset = isl_basic_set_flatten(size.bset);
2087 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2088 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2089 &size);
2090 isl_basic_set_free(size.bset);
2092 return bound->size ? 0 : -1;
2095 /* Check if we can find a memory tile for the given array
2096 * based on the given accesses, and if so, put the results in "tile".
2098 * We project the accesses on each index in turn and look for a parametric
2099 * offset such that the size is constant.
2101 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2103 int i;
2105 for (i = 0; i < tile->n; ++i) {
2106 isl_map *access_i;
2107 isl_basic_map *hull;
2109 access_i = isl_map_copy(access);
2110 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2111 access_i = isl_map_project_out(access_i, isl_dim_out,
2112 1, tile->n - (i + 1));
2113 access_i = isl_map_compute_divs(access_i);
2114 hull = isl_map_simple_hull(access_i);
2115 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2116 return 0;
2119 return 1;
2122 /* Construct a map with input the shared tile loops and the loops that
2123 * will be wrapped around the threads that relates these later loops
2124 * to the thread indices and then projects them out.
2126 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2128 isl_map *priv;
2129 isl_map *tiling;
2130 isl_map *proj;
2131 isl_set *par;
2132 isl_space *dim;
2134 dim = isl_union_map_get_space(gen->shared_sched);
2136 if (gen->options->wrap)
2137 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2138 gen->shared_len, gen->n_block, gen->block_dim);
2139 else
2140 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2141 gen->shared_len, gen->n_block, gen->block_dim);
2143 priv = tiling;
2145 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2146 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2147 gen->n_block, "t");
2149 priv = isl_map_align_params(priv, isl_set_get_space(par));
2150 priv = isl_map_intersect_range(priv, par);
2152 dim = isl_map_get_space(priv);
2153 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2154 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2155 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2156 gen->shared_len);
2158 priv = isl_map_apply_range(priv, proj);
2160 return priv;
2163 /* Construct a map from domain_dim to domain_dim that increments
2164 * the dimension at position "pos" and leaves all other dimensions
2165 * constant.
2167 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2169 int i;
2170 int len = isl_space_dim(domain_dim, isl_dim_set);
2171 isl_space *dim;
2172 isl_basic_map *next;
2173 isl_local_space *ls;
2175 dim = isl_space_map_from_set(domain_dim);
2176 next = isl_basic_map_universe(isl_space_copy(dim));
2177 ls = isl_local_space_from_space(dim);
2179 for (i = 0; i < len; ++i) {
2180 isl_constraint *c;
2182 c = isl_equality_alloc(isl_local_space_copy(ls));
2183 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2184 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2185 if (i == pos)
2186 c = isl_constraint_set_constant_si(c, 1);
2187 next = isl_basic_map_add_constraint(next, c);
2190 isl_local_space_free(ls);
2192 return isl_map_from_basic_map(next);
2195 /* Check if the given access is coalesced.
2196 * That is, check whether incrementing the dimension that will get
2197 * wrapped over the last thread index results in incrementing
2198 * the last array index.
2200 * This function is only called for access relations without reuse.
2202 static int access_is_coalesced(struct gpu_gen *gen,
2203 __isl_keep isl_union_map *access)
2205 isl_space *dim;
2206 isl_map *access_map;
2207 isl_map *next_thread_x;
2208 isl_map *next_element;
2209 isl_map *map;
2210 int coalesced;
2212 access = isl_union_map_copy(access);
2213 access = isl_union_map_apply_domain(access,
2214 isl_union_map_copy(gen->tiled_sched));
2215 access_map = isl_map_from_union_map(access);
2217 dim = isl_map_get_space(access_map);
2218 dim = isl_space_domain(dim);
2219 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2221 dim = isl_map_get_space(access_map);
2222 dim = isl_space_range(dim);
2223 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2225 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2226 map = isl_map_apply_range(map, access_map);
2228 coalesced = isl_map_is_subset(map, next_element);
2230 isl_map_free(next_element);
2231 isl_map_free(map);
2233 return coalesced;
2236 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2237 * dimensions of the computed schedule, check if it is bijective for
2238 * fixed values of the first gen->shared_len dimensions.
2239 * We perform this check by equating these dimensions to parameters.
2241 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2243 int res;
2244 isl_set *par;
2245 isl_space *space;
2247 access = isl_map_copy(access);
2248 space = isl_space_params(isl_map_get_space(access));
2249 par = parametrization(space, gen->shared_len + gen->n_block,
2250 0, gen->shared_len, "s");
2251 access = isl_map_intersect_domain(access, par);
2252 res = isl_map_is_bijective(access);
2253 isl_map_free(access);
2255 return res;
2258 /* Look for the last shared tile loop that affects the offset of "tile"
2259 * and return the result.
2260 * If there is no such loop, then return the index of the loop
2261 * before the first shared tile loop, in particular gen->tile_first - 1.
2263 static int compute_tile_last_shared(struct gpu_gen *gen,
2264 struct gpu_array_tile *tile)
2266 int i, j;
2268 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2269 for (i = 0; i < tile->n; ++i) {
2270 isl_aff *lb;
2271 isl_aff *shift;
2273 lb = tile->bound[i].lb;
2274 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2275 break;
2277 shift = tile->bound[i].shift;
2278 if (!shift)
2279 continue;
2280 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2281 break;
2283 if (i < tile->n)
2284 break;
2287 return j;
2290 /* Look for the last shared tile loop that affects the offset of the
2291 * shared or private tile and store the result in group->last_shared.
2292 * If there is no such loop, then group->last_shared is set to a value
2293 * before the first shared tile loop, in particular gen->tile_first - 1.
2294 * If there is no tile defined on the array reference group,
2295 * then set group->last_shared to gen->shared_len - 1.
2297 static void set_last_shared(struct gpu_gen *gen,
2298 struct gpu_array_ref_group *group)
2300 struct gpu_array_tile *tile;
2302 group->last_shared = gen->shared_len - 1;
2304 tile = group->private_tile;
2305 if (!tile)
2306 tile = group->shared_tile;
2307 if (!tile)
2308 return;
2310 group->last_shared = compute_tile_last_shared(gen, tile);
2313 /* Compute a privatized copy of all access relations from reference groups that
2314 * are mapped to private memory and store the result in gen->privatization.
2316 * Read-only scalars and arrays containing structures are not mapped
2317 * to private memory.
2319 static void compute_private_access(struct gpu_gen *gen)
2321 int i, j;
2322 isl_union_map *private;
2324 if (!gen->options->use_private_memory)
2325 return;
2327 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2329 for (i = 0; i < gen->prog->n_array; ++i) {
2330 struct gpu_array_info *array = &gen->prog->array[i];
2332 if (gpu_array_is_read_only_scalar(array))
2333 continue;
2334 if (array->has_compound_element)
2335 continue;
2337 for (j = 0; j < array->n_group; ++j) {
2338 if (!array->groups[j]->private_tile)
2339 continue;
2341 private = isl_union_map_union(private,
2342 group_access_relation(array->groups[j], 1, 1));
2346 if (isl_union_map_is_empty(private))
2347 isl_union_map_free(private);
2348 else {
2349 isl_union_map *priv;
2351 private = isl_union_map_apply_domain(private,
2352 isl_union_map_copy(gen->shared_sched));
2353 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2354 private = isl_union_map_apply_domain(private, priv);
2355 gen->private_access = private;
2359 /* Compute the size of the tile specified by "tile"
2360 * in number of elements and return the result.
2362 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2364 int i;
2365 isl_val *size;
2367 size = isl_val_one(ctx);
2369 for (i = 0; i < tile->n; ++i)
2370 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2372 return size;
2375 /* If max_shared_memory is not set to infinity (-1), then make
2376 * sure that the total amount of shared memory required by the
2377 * array reference groups mapped to shared memory is no larger
2378 * than this maximum.
2380 * We apply a greedy approach and discard (keep in global memory)
2381 * those groups that would result in a total memory size that
2382 * is larger than the maximum.
2384 * This function should be called after any function that may
2385 * affect the decision on whether to place a reference group
2386 * in private, shared or global memory.
2388 static void check_shared_memory_bound(struct gpu_gen *gen)
2390 int i, j;
2391 isl_val *left, *size;
2393 if (gen->options->max_shared_memory < 0)
2394 return;
2396 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2398 for (i = 0; i < gen->prog->n_array; ++i) {
2399 struct gpu_array_info *array = &gen->prog->array[i];
2401 for (j = 0; j < array->n_group; ++j) {
2402 struct gpu_array_ref_group *group;
2404 group = array->groups[j];
2405 if (group->private_tile)
2406 continue;
2407 if (!group->shared_tile)
2408 continue;
2410 size = tile_size(gen->ctx, group->shared_tile);
2411 size = isl_val_mul_ui(size, array->size);
2413 if (isl_val_le(size, left)) {
2414 left = isl_val_sub(left, size);
2415 continue;
2417 isl_val_free(size);
2419 group->shared_tile = free_tile(group->shared_tile);
2423 isl_val_free(left);
2426 /* Given a description of an array tile "tile" and the "space"
2428 * { D -> A }
2430 * where D represents the first shared_len schedule dimensions
2431 * and A represents the array, construct an isl_multi_aff
2433 * { [D[i] -> A[a]] -> A'[a'] }
2435 * with A' a scaled down copy of A according to the shifts and strides
2436 * in "tile". In particular,
2438 * a' = (a + shift(i))/stride
2440 * "insert_array" represents
2442 * { [D -> A] -> D }
2444 * and is used to insert A into the domain of functions that only
2445 * reference D.
2447 static __isl_give isl_multi_aff *strided_tile(
2448 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2449 __isl_keep isl_multi_aff *insert_array)
2451 int i;
2452 isl_ctx *ctx;
2453 isl_multi_aff *shift;
2454 isl_multi_val *stride;
2455 isl_space *space2;
2456 isl_local_space *ls;
2457 isl_multi_aff *tiling;
2459 ctx = isl_space_get_ctx(space);
2460 space2 = isl_space_domain(isl_space_copy(space));
2461 ls = isl_local_space_from_space(space2);
2462 space2 = isl_space_range(isl_space_copy(space));
2463 stride = isl_multi_val_zero(space2);
2464 shift = isl_multi_aff_zero(isl_space_copy(space));
2466 for (i = 0; i < tile->n; ++i) {
2467 struct gpu_array_bound *bound = &tile->bound[i];
2468 isl_val *stride_i;
2469 isl_aff *shift_i;
2471 if (tile->bound[i].shift) {
2472 stride_i = isl_val_copy(bound->stride);
2473 shift_i = isl_aff_copy(bound->shift);
2474 } else {
2475 stride_i = isl_val_one(ctx);
2476 shift_i = isl_aff_zero_on_domain(
2477 isl_local_space_copy(ls));
2480 stride = isl_multi_val_set_val(stride, i, stride_i);
2481 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2483 isl_local_space_free(ls);
2485 shift = isl_multi_aff_pullback_multi_aff(shift,
2486 isl_multi_aff_copy(insert_array));
2488 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2489 tiling = isl_multi_aff_add(tiling, shift);
2490 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2492 return tiling;
2495 /* Compute a tiling for the array reference group "group".
2497 * The tiling is of the form
2499 * { [D[i] -> A[a]] -> T[t] }
2501 * where D represents the first shared_len schedule dimensions,
2502 * A represents the global array and T represents the shared or
2503 * private memory tile. The name of T is the name of the local
2504 * array.
2506 * If there is any stride in the accesses, then the mapping is
2508 * t = (a + shift(i))/stride - lb(i)
2510 * otherwise, it is simply
2512 * t = a - lb(i)
2514 static void compute_group_tiling(struct gpu_array_ref_group *group)
2516 int i;
2517 struct gpu_array_tile *tile;
2518 struct gpu_array_info *array = group->array;
2519 isl_space *space;
2520 isl_multi_aff *tiling, *lb, *insert_array;
2521 isl_printer *p;
2522 char *local_name;
2524 tile = group->private_tile;
2525 if (!tile)
2526 tile = group->shared_tile;
2527 if (!tile)
2528 return;
2530 space = isl_map_get_space(group->access);
2531 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2533 for (i = 0; i < tile->n; ++i)
2534 if (tile->bound[i].shift)
2535 break;
2537 if (i < tile->n)
2538 tiling = strided_tile(tile, space, insert_array);
2539 else
2540 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2542 lb = isl_multi_aff_zero(space);
2543 for (i = 0; i < tile->n; ++i) {
2544 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2545 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2547 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2549 tiling = isl_multi_aff_sub(tiling, lb);
2551 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2552 p = print_array_name(p, group);
2553 local_name = isl_printer_get_str(p);
2554 isl_printer_free(p);
2555 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2556 free(local_name);
2558 tile->tiling = tiling;
2561 /* Compute a tiling for all the array reference groups.
2563 static void compute_group_tilings(struct gpu_gen *gen)
2565 int i, j;
2567 for (i = 0; i < gen->prog->n_array; ++i) {
2568 struct gpu_array_info *array = &gen->prog->array[i];
2570 for (j = 0; j < array->n_group; ++j)
2571 compute_group_tiling(array->groups[j]);
2575 /* Fill up the groups array with singleton groups, i.e., one group
2576 * per reference, initializing the array, access, write, n_ref and refs fields.
2577 * In particular the access field is initialized to the scheduled
2578 * access relation of the array reference.
2580 * Return the number of elements initialized, i.e., the number of
2581 * active references in the current kernel.
2583 static int populate_array_references(struct gpu_array_info *array,
2584 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2586 int i;
2587 int n;
2588 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2590 n = 0;
2591 for (i = 0; i < array->n_ref; ++i) {
2592 isl_union_map *umap;
2593 isl_map *map;
2594 struct gpu_array_ref_group *group;
2595 struct gpu_stmt_access *access = array->refs[i];
2597 map = isl_map_copy(access->access);
2598 umap = isl_union_map_from_map(map);
2599 umap = isl_union_map_apply_domain(umap,
2600 isl_union_map_copy(sched));
2602 if (isl_union_map_is_empty(umap)) {
2603 isl_union_map_free(umap);
2604 continue;
2607 map = isl_map_from_union_map(umap);
2608 map = isl_map_detect_equalities(map);
2610 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2611 assert(group);
2612 group->array = array;
2613 group->access = map;
2614 group->write = access->write;
2615 group->exact_write = access->exact_write;
2616 group->refs = &array->refs[i];
2617 group->n_ref = 1;
2619 groups[n++] = group;
2622 return n;
2625 /* If group->n_ref == 1, then group->refs was set by
2626 * populate_array_references to point directly into
2627 * group->array->refs and should not be freed.
2628 * If group->n_ref > 1, then group->refs was set by join_groups
2629 * to point to a newly allocated array.
2631 static void free_array_ref_group(struct gpu_array_ref_group *group)
2633 if (!group)
2634 return;
2635 free_tile(group->shared_tile);
2636 free_tile(group->private_tile);
2637 isl_map_free(group->access);
2638 if (group->n_ref > 1)
2639 free(group->refs);
2640 free(group);
2643 /* Given a map where the input dimensions represent the tile loops,
2644 * eliminate the innermost of those that have a fixed value
2645 * until we reach one that does not (obviously) have a fixed value.
2647 static __isl_give isl_map *eliminate_fixed_inner_loops(
2648 __isl_take isl_map *access)
2650 int i, n;
2652 n = isl_map_dim(access, isl_dim_in);
2654 for (i = n - 1; i >= 0; --i) {
2655 if (!map_plain_is_fixed(access, isl_dim_in, i))
2656 break;
2657 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2659 return access;
2662 /* Check if the access relations of group1 and group2 overlap within
2663 * the innermost loop. In particular, ignore any inner dimension
2664 * with a fixed value.
2665 * The copying to and from shared memory will be performed within
2666 * the innermost actual loop so we are only allowed to consider
2667 * the dimensions up to that innermost loop while checking whether
2668 * two access relations overlap.
2670 static int accesses_overlap(struct gpu_array_ref_group *group1,
2671 struct gpu_array_ref_group *group2)
2673 int empty;
2674 isl_map *access1, *access2;
2676 access1 = isl_map_copy(group1->access);
2677 access1 = eliminate_fixed_inner_loops(access1);
2678 access2 = isl_map_copy(group2->access);
2679 access2 = eliminate_fixed_inner_loops(access2);
2680 access1 = isl_map_intersect(access1, access2);
2681 empty = isl_map_is_empty(access1);
2682 isl_map_free(access1);
2684 return !empty;
2687 /* Combine the given two groups into a single group, containing
2688 * the references of both groups.
2690 static struct gpu_array_ref_group *join_groups(
2691 struct gpu_array_ref_group *group1,
2692 struct gpu_array_ref_group *group2)
2694 int i;
2695 isl_ctx *ctx;
2696 struct gpu_array_ref_group *group;
2698 ctx = isl_map_get_ctx(group1->access);
2699 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2700 assert(group);
2701 group->array = group1->array;
2702 group->access = isl_map_union(isl_map_copy(group1->access),
2703 isl_map_copy(group2->access));
2704 group->write = group1->write || group2->write;
2705 group->exact_write = group1->exact_write && group2->exact_write;
2706 group->n_ref = group1->n_ref + group2->n_ref;
2707 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2708 group->n_ref);
2709 assert(group->refs);
2710 for (i = 0; i < group1->n_ref; ++i)
2711 group->refs[i] = group1->refs[i];
2712 for (i = 0; i < group2->n_ref; ++i)
2713 group->refs[group1->n_ref + i] = group2->refs[i];
2715 return group;
2718 /* Combine the given two groups into a single group and free
2719 * the original two groups.
2721 static struct gpu_array_ref_group *join_groups_and_free(
2722 struct gpu_array_ref_group *group1,
2723 struct gpu_array_ref_group *group2)
2725 struct gpu_array_ref_group *group;
2727 group = join_groups(group1, group2);
2728 free_array_ref_group(group1);
2729 free_array_ref_group(group2);
2730 return group;
2733 /* Compute the private and/or shared memory tiles for the array
2734 * reference group "group" of array "array".
2735 * Return 0 on success and -1 on error.
2737 * If the array is a read-only scalar or if the user requested
2738 * not to use shared or private memory, then we do not need to do anything.
2740 * If the array group involves any may writes (that are not must writes),
2741 * then we would have to make sure that we load the data into shared/private
2742 * memory first in case the data is not written by the kernel
2743 * (but still written back out to global memory).
2744 * Since we don't have any such mechanism at the moment, we don't
2745 * compute shared/private tiles for groups involving may writes.
2747 * We only try to compute a shared memory tile if there is any reuse
2748 * or if the access is not coalesced.
2750 * For computing a private memory tile, we also require that there is
2751 * some reuse. Moreover, we require that the access is private
2752 * to the thread. That is, we check that any given array element
2753 * is only accessed by a single thread.
2754 * We compute an access relation that maps the shared tile loop iterators
2755 * and the shared point loop iterators that will be wrapped over the
2756 * threads to the array elements.
2757 * We actually check that those iterators that will be wrapped
2758 * partition the array space. This check is stricter than necessary
2759 * since several iterations may be mapped onto the same thread
2760 * and then they could be allowed to access the same memory elements,
2761 * but our check does not allow this situation.
2763 * We also check that the index expression only depends on parallel
2764 * loops. That way, we can move those loops innermost and unroll them.
2765 * Again, we use a test that is stricter than necessary.
2766 * We actually check whether the index expression only depends
2767 * on the iterators that are wrapped over the threads.
2768 * These are necessarily parallel, but there may be more parallel loops.
2770 * Combining the injectivity of the first test with the single-valuedness
2771 * of the second test, we simply test for bijectivity.
2773 * If the array is marked force_private, then we bypass all checks
2774 * and assume we can (and should) use registers.
2776 * If it turns out we can (or have to) use registers, we compute
2777 * the private memory tile size using can_tile, after introducing a dependence
2778 * on the thread indices.
2780 static int compute_group_bounds_core(struct gpu_gen *gen,
2781 struct gpu_array_ref_group *group)
2783 isl_ctx *ctx = isl_space_get_ctx(group->array->space);
2784 isl_union_map *access;
2785 int n_index = group->array->n_index;
2786 int no_reuse;
2787 isl_map *acc;
2788 int force_private = group->array->force_private;
2789 int use_shared = gen->options->use_shared_memory;
2790 int use_private = force_private || gen->options->use_private_memory;
2792 if (!use_shared && !use_private)
2793 return 0;
2794 if (gpu_array_is_read_only_scalar(group->array))
2795 return 0;
2796 if (!force_private && !group->exact_write)
2797 return 0;
2799 access = group_access_relation(group, 1, 1);
2800 no_reuse = isl_union_map_is_injective(access);
2802 if (use_shared && (!no_reuse || !access_is_coalesced(gen, access))) {
2803 group->shared_tile = create_tile(ctx, group->array->n_index);
2804 if (!can_tile(group->access, group->shared_tile))
2805 group->shared_tile = free_tile(group->shared_tile);
2808 if (!force_private && (!use_private || no_reuse)) {
2809 isl_union_map_free(access);
2810 return 0;
2813 access = isl_union_map_apply_domain(access,
2814 isl_union_map_copy(gen->shared_sched));
2816 acc = isl_map_from_union_map(access);
2818 if (!force_private && !access_is_bijective(gen, acc)) {
2819 isl_map_free(acc);
2820 return 0;
2823 group->private_tile = create_tile(gen->ctx, n_index);
2824 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2825 if (!can_tile(acc, group->private_tile))
2826 group->private_tile = free_tile(group->private_tile);
2828 isl_map_free(acc);
2830 if (force_private && !group->private_tile)
2831 isl_die(ctx, isl_error_internal,
2832 "unable to map array reference group to registers",
2833 return -1);
2835 return 0;
2838 /* Compute the private and/or shared memory tiles for the array
2839 * reference group "group" of array "array" and set last_shared.
2840 * Return 0 on success and -1 on error.
2842 static int compute_group_bounds(struct gpu_gen *gen,
2843 struct gpu_array_ref_group *group)
2845 if (compute_group_bounds_core(gen, group) < 0)
2846 return -1;
2847 set_last_shared(gen, group);
2849 return 0;
2852 /* If two groups have overlapping access relations (as determined by
2853 * the "overlap" function) and if one of them involves a write,
2854 * then merge the two groups into one.
2855 * If "compute_bounds" is set, then call compute_group_bounds
2856 * on the merged groups.
2858 * Return the updated number of groups.
2859 * Return -1 on error.
2861 static int group_writes(struct gpu_gen *gen,
2862 int n, struct gpu_array_ref_group **groups,
2863 int (*overlap)(struct gpu_array_ref_group *group1,
2864 struct gpu_array_ref_group *group2), int compute_bounds)
2866 int i, j;
2868 for (i = 0; i < n; ++i) {
2869 for (j = n - 1; j > i; --j) {
2870 if (!groups[i]->write && !groups[j]->write)
2871 continue;
2873 if (!overlap(groups[i], groups[j]))
2874 continue;
2876 groups[i] = join_groups_and_free(groups[i], groups[j]);
2877 if (compute_bounds &&
2878 compute_group_bounds(gen, groups[i]) < 0)
2879 return -1;
2880 if (j != n - 1)
2881 groups[j] = groups[n - 1];
2882 groups[n - 1] = NULL;
2883 n--;
2887 return n;
2890 /* If two groups have overlapping access relations (within the innermost
2891 * loop) and if one of them involves a write, then merge the two groups
2892 * into one.
2894 * Return the updated number of groups.
2896 static int group_overlapping_writes(struct gpu_gen *gen,
2897 int n, struct gpu_array_ref_group **groups)
2899 return group_writes(gen, n, groups, &accesses_overlap, 0);
2902 /* Check if the access relations of group1 and group2 overlap within
2903 * the outermost min(group1->last_shared, group2->last_shared) loops.
2905 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2906 struct gpu_array_ref_group *group2)
2908 int last_shared;
2909 int dim;
2910 int empty;
2911 isl_map *map_i, *map_j, *map;
2913 last_shared = group1->last_shared;
2914 if (group2->last_shared < last_shared)
2915 last_shared = group2->last_shared;
2916 map_i = isl_map_copy(group1->access);
2917 dim = isl_map_dim(map_i, isl_dim_in);
2918 map_i = isl_map_eliminate(map_i, isl_dim_in,
2919 last_shared + 1, dim - (last_shared + 1));
2920 map_j = isl_map_copy(group2->access);
2921 map_j = isl_map_eliminate(map_j, isl_dim_in,
2922 last_shared + 1, dim - (last_shared + 1));
2923 map = isl_map_intersect(map_i, map_j);
2924 empty = isl_map_is_empty(map);
2925 isl_map_free(map);
2927 return !empty;
2930 /* If two groups have overlapping access relations (within the outer
2931 * last_shared loops) and if one of them involves a write,
2932 * then merge the two groups into one.
2934 * Return the updated number of groups.
2936 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2937 struct gpu_array_ref_group **groups)
2939 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2942 /* Is the size of the tile specified by "tile" smaller than the sum of
2943 * the sizes of the tiles specified by "tile1" and "tile2"?
2945 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
2946 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2948 int smaller;
2949 isl_val *size, *size1, *size2;
2951 size = tile_size(ctx, tile);
2952 size1 = tile_size(ctx, tile1);
2953 size2 = tile_size(ctx, tile2);
2955 size = isl_val_sub(size, size1);
2956 size = isl_val_sub(size, size2);
2957 smaller = isl_val_is_neg(size);
2959 isl_val_free(size);
2961 return smaller;
2964 /* Given an initial grouping of array references and shared memory tiles
2965 * for each group that allows for a shared memory tile, merge two groups
2966 * if both have a shared memory tile, the merged group also has
2967 * a shared memory tile and the size of the tile for the merge group
2968 * is smaller than the sum of the tile sizes of the individual groups.
2970 * If merging two groups decreases the "last_shared" dimension of
2971 * one or both of the two groups, then we need to check for overlapping
2972 * writes again.
2974 * Return the number of groups after merging.
2975 * Return -1 on error.
2977 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2978 struct gpu_array_info *array, int n,
2979 struct gpu_array_ref_group **groups)
2981 int i, j;
2982 int recompute_overlap = 0;
2983 isl_ctx *ctx = isl_space_get_ctx(array->space);
2985 for (i = 0; i < n; ++i) {
2986 if (!groups[i]->shared_tile)
2987 continue;
2988 for (j = n - 1; j > i; --j) {
2989 isl_map *map;
2990 int empty;
2991 struct gpu_array_ref_group *group;
2993 if (!groups[j]->shared_tile)
2994 continue;
2996 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2997 isl_map_copy(groups[j]->access));
2998 empty = isl_map_is_empty(map);
2999 isl_map_free(map);
3001 if (empty)
3002 continue;
3004 group = join_groups(groups[i], groups[j]);
3005 if (compute_group_bounds(gen, group) < 0) {
3006 free_array_ref_group(group);
3007 return -1;
3009 if (!group->shared_tile ||
3010 !smaller_tile(ctx, group->shared_tile,
3011 groups[i]->shared_tile,
3012 groups[j]->shared_tile)) {
3013 free_array_ref_group(group);
3014 continue;
3017 if (group->last_shared < groups[i]->last_shared ||
3018 group->last_shared < groups[j]->last_shared)
3019 recompute_overlap = 1;
3020 free_array_ref_group(groups[i]);
3021 free_array_ref_group(groups[j]);
3022 groups[i] = group;
3023 if (j != n - 1)
3024 groups[j] = groups[n - 1];
3025 n--;
3029 if (recompute_overlap)
3030 n = group_last_shared_overlapping_writes(gen, n, groups);
3031 return n;
3034 /* Set array->n_group and array->groups to n and groups.
3036 * Additionally, set the "nr" field of each group
3037 * and the "group" field of each reference in each group.
3039 static void set_array_groups(struct gpu_array_info *array,
3040 int n, struct gpu_array_ref_group **groups)
3042 int i, j;
3044 array->n_group = n;
3045 array->groups = groups;
3047 for (i = 0; i < n; ++i) {
3048 groups[i]->nr = i;
3050 for (j = 0; j < groups[i]->n_ref; ++j)
3051 groups[i]->refs[j]->group = i;
3055 /* Group array references that should be considered together when
3056 * deciding whether to access them from private, shared or global memory.
3057 * Return -1 on error.
3059 * In particular, if two array references overlap and if one of them
3060 * is a write, then the two references are grouped together.
3061 * We first perform an initial grouping based only on the access relation.
3062 * After computing shared and private memory tiles, we check for
3063 * overlapping writes again, but this time taking into account
3064 * the "last_shared" property.
3066 * Furthermore, if two groups admit a shared memory tile and if the
3067 * combination of the two also admits a shared memory tile, we merge
3068 * the two groups.
3070 * If the array contains structures, then there is no need to compute
3071 * reference groups since we do not map such arrays to private or shared
3072 * memory.
3074 static int group_array_references(struct gpu_gen *gen,
3075 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
3077 int i;
3078 int n;
3079 isl_ctx *ctx = isl_union_map_get_ctx(sched);
3080 struct gpu_array_ref_group **groups;
3082 if (array->has_compound_element)
3083 return 0;
3085 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
3086 array->n_ref);
3087 if (!groups)
3088 return -1;
3090 n = populate_array_references(array, sched, groups);
3092 n = group_overlapping_writes(gen, n, groups);
3094 for (i = 0; i < n; ++i)
3095 if (compute_group_bounds(gen, groups[i]) < 0)
3096 n = -1;
3098 n = group_last_shared_overlapping_writes(gen, n, groups);
3100 n = group_common_shared_memory_tile(gen, array, n, groups);
3102 set_array_groups(array, n, groups);
3104 if (n >= 0)
3105 return 0;
3107 for (i = 0; i < array->n_ref; ++i)
3108 free_array_ref_group(groups[i]);
3109 return -1;
3112 /* Take tiled_sched, project it onto the shared tile loops and
3113 * the loops that will be wrapped over the threads and
3114 * store the result in gen->shared_sched.
3115 * Also compute a projection that projects out the loops that will be
3116 * wrapped over the threads and store this projection in gen->shared_proj.
3118 static void compute_shared_sched(struct gpu_gen *gen)
3120 isl_space *dim;
3121 isl_map *proj;
3122 isl_set *par;
3123 isl_union_map *sched;
3125 sched = isl_union_map_copy(gen->tiled_sched);
3127 dim = isl_union_map_get_space(sched);
3128 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
3129 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3131 dim = isl_union_map_get_space(sched);
3132 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
3134 gen->shared_sched = sched;
3135 gen->shared_proj = isl_union_map_from_map(proj);
3138 /* For each scalar in the input program, check if there are any
3139 * order dependences active inside the current kernel, within
3140 * the same iteration of the host schedule.
3141 * If so, mark the scalar as force_private so that it will be
3142 * mapped to a register.
3144 static void check_scalar_live_ranges(struct gpu_gen *gen)
3146 int i;
3147 isl_map *proj;
3148 isl_union_map *sched;
3149 isl_union_set *domain;
3150 isl_union_map *same_host_iteration;
3152 gen->any_force_private = 0;
3154 if (!gen->options->live_range_reordering)
3155 return;
3157 sched = gen->shared_sched;
3158 sched = isl_union_map_universe(isl_union_map_copy(sched));
3159 domain = isl_union_map_domain(sched);
3161 sched = isl_union_map_copy(gen->sched);
3162 proj = projection(isl_union_map_get_space(sched),
3163 gen->untiled_len, gen->tile_first);
3164 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3165 same_host_iteration = isl_union_map_apply_range(sched,
3166 isl_union_map_reverse(isl_union_map_copy(sched)));
3168 for (i = 0; i < gen->prog->n_array; ++i) {
3169 struct gpu_array_info *array = &gen->prog->array[i];
3170 isl_union_map *order;
3172 array->force_private = 0;
3173 if (array->n_index != 0)
3174 continue;
3175 order = isl_union_map_copy(array->dep_order);
3176 order = isl_union_map_intersect_domain(order,
3177 isl_union_set_copy(domain));
3178 order = isl_union_map_intersect_range(order,
3179 isl_union_set_copy(domain));
3180 order = isl_union_map_intersect(order,
3181 isl_union_map_copy(same_host_iteration));
3182 if (!isl_union_map_is_empty(order)) {
3183 array->force_private = 1;
3184 gen->any_force_private = 1;
3186 isl_union_map_free(order);
3189 isl_union_map_free(same_host_iteration);
3190 isl_union_set_free(domain);
3193 /* Group references of all arrays in the program.
3195 static int group_references(struct gpu_gen *gen)
3197 int i;
3198 int r = 0;
3199 isl_union_map *sched;
3201 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3202 isl_union_map_copy(gen->shared_proj));
3204 for (i = 0; i < gen->prog->n_array; ++i) {
3205 r = group_array_references(gen, &gen->prog->array[i], sched);
3206 if (r < 0)
3207 break;
3210 isl_union_map_free(sched);
3212 return r;
3215 /* Free all array information that is local to the current kernel.
3217 static void free_local_array_info(struct gpu_gen *gen)
3219 int i, j;
3221 for (i = 0; i < gen->prog->n_array; ++i) {
3222 struct gpu_array_info *array = &gen->prog->array[i];
3224 for (j = 0; j < array->n_group; ++j)
3225 free_array_ref_group(array->groups[j]);
3226 free(array->groups);
3230 /* Compute the size of a bounding box around the origin and "set",
3231 * where "set" is assumed to contain only non-negative elements.
3232 * In particular, compute the maximal value of "set" in each direction
3233 * and add one.
3235 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
3236 __isl_keep isl_set *context)
3238 int i, n;
3239 isl_multi_pw_aff *mpa;
3241 n = isl_set_dim(set, isl_dim_set);
3242 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
3243 for (i = 0; i < n; ++i) {
3244 isl_space *space;
3245 isl_aff *one;
3246 isl_pw_aff *bound;
3248 bound = isl_set_dim_max(isl_set_copy(set), i);
3249 bound = isl_pw_aff_coalesce(bound);
3250 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
3252 space = isl_pw_aff_get_domain_space(bound);
3253 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
3254 one = isl_aff_add_constant_si(one, 1);
3255 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
3256 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
3258 isl_set_free(set);
3260 return mpa;
3263 /* Compute the effective grid size as a list of the sizes in each dimension.
3265 * The grid size specified by the user or set by default
3266 * in read_grid_sizes() and applied in tile_schedule(),
3267 * may be too large for the given code in the sense that
3268 * it may contain blocks that don't need to execute anything.
3269 * We therefore don't return this grid size, but instead the
3270 * smallest grid size that ensures that all blocks that actually
3271 * execute code are included in the grid.
3273 * We first extract a description of the grid, i.e., the possible values
3274 * of the block ids, from gen->tiled_sched.
3275 * The block ids are parameters in gen->tiled_sched.
3276 * We simply need to change them into set dimensions.
3278 * Then, for each block dimension, we compute the maximal value of the block id
3279 * and add one.
3281 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
3282 struct ppcg_kernel *kernel)
3284 int i;
3285 isl_set *grid;
3287 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
3288 grid = isl_set_from_params(grid);
3289 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
3290 for (i = 0; i < gen->n_grid; ++i) {
3291 int pos;
3292 char name[20];
3294 snprintf(name, sizeof(name), "b%d", i);
3295 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
3296 assert(pos >= 0);
3297 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
3298 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
3301 return extract_size(grid, kernel->context);
3304 /* Compute the size of a fixed bounding box around the origin and "set",
3305 * where "set" is assumed to contain only non-negative elements,
3306 * and store the results in "size".
3307 * In particular, compute the maximal value of "set" in each direction
3308 * and add one.
3310 static void extract_fixed_size(__isl_take isl_set *set, int *size)
3312 int i, n;
3313 isl_local_space *ls;
3314 isl_aff *obj;
3316 n = isl_set_dim(set, isl_dim_set);
3317 ls = isl_local_space_from_space(isl_set_get_space(set));
3318 obj = isl_aff_zero_on_domain(ls);
3319 for (i = 0; i < n; ++i) {
3320 isl_val *max;
3322 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
3323 max = isl_set_max_val(set, obj);
3324 size[i] = isl_val_get_num_si(max) + 1;
3325 isl_val_free(max);
3326 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
3328 isl_aff_free(obj);
3329 isl_set_free(set);
3332 /* Compute the effective block size as a list of the sizes in each dimension
3333 * and store the sizes in kernel->block_dim.
3335 * The block size specified by the user or set by default
3336 * in read_block_sizes() and applied in thread_tile_schedule(),
3337 * may be too large for the given code in the sense that
3338 * it may contain threads that don't need to execute anything.
3339 * We therefore don't store this block size in kernel->block_dim,
3340 * but instead the smallest block size that ensures that all threads
3341 * that actually execute code are included in the block.
3343 * The current implementation eliminates all parameters, ensuring
3344 * that the size is a fixed constant in each dimension.
3345 * In principle we could also compute parametric sizes.
3346 * We would have to make sure to project out all b%d and t%d parameters,
3347 * however.
3349 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3351 int i;
3352 int nparam;
3353 isl_set *block;
3354 isl_multi_pw_aff *mpa;
3356 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3357 block = isl_set_from_params(block);
3358 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3359 kernel->n_block = gen->n_block;
3360 for (i = 0; i < gen->n_block; ++i) {
3361 int pos;
3362 char name[20];
3364 snprintf(name, sizeof(name), "t%d", i);
3365 pos = isl_set_find_dim_by_name(block, isl_dim_param, name);
3366 assert(pos >= 0);
3367 block = isl_set_equate(block, isl_dim_param, pos,
3368 isl_dim_set, i);
3370 nparam = isl_set_dim(block, isl_dim_param);
3371 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3373 extract_fixed_size(block, kernel->block_dim);
3376 void ppcg_kernel_free(void *user)
3378 struct ppcg_kernel *kernel = user;
3379 int i;
3381 if (!kernel)
3382 return;
3384 isl_multi_pw_aff_free(kernel->grid_size);
3385 isl_set_free(kernel->context);
3386 isl_union_set_free(kernel->arrays);
3387 isl_space_free(kernel->space);
3388 isl_ast_node_free(kernel->tree);
3390 for (i = 0; i < kernel->n_array; ++i)
3391 isl_pw_aff_list_free(kernel->array[i].bound);
3392 free(kernel->array);
3394 for (i = 0; i < kernel->n_var; ++i) {
3395 free(kernel->var[i].name);
3396 isl_vec_free(kernel->var[i].size);
3398 free(kernel->var);
3400 free(kernel);
3403 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3404 struct ppcg_kernel_var *var)
3406 int j;
3407 struct gpu_array_tile *tile;
3408 isl_printer *p;
3409 char *name;
3411 var->array = group->array;
3413 tile = group->private_tile;
3414 var->type = ppcg_access_private;
3415 if (!tile) {
3416 tile = group->shared_tile;
3417 var->type = ppcg_access_shared;
3420 p = isl_printer_to_str(ctx);
3421 p = print_array_name(p, group);
3422 var->name = isl_printer_get_str(p);
3423 isl_printer_free(p);
3425 var->size = isl_vec_alloc(ctx, group->array->n_index);
3427 for (j = 0; j < group->array->n_index; ++j)
3428 var->size = isl_vec_set_element_val(var->size, j,
3429 isl_val_copy(tile->bound[j].size));
3432 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3434 int i, j, n;
3436 n = 0;
3437 for (i = 0; i < gen->prog->n_array; ++i) {
3438 struct gpu_array_info *array = &gen->prog->array[i];
3440 for (j = 0; j < array->n_group; ++j) {
3441 struct gpu_array_ref_group *group = array->groups[j];
3442 if (group->private_tile || group->shared_tile)
3443 ++n;
3447 kernel->n_var = n;
3448 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3449 assert(kernel->var);
3451 n = 0;
3452 for (i = 0; i < gen->prog->n_array; ++i) {
3453 struct gpu_array_info *array = &gen->prog->array[i];
3455 for (j = 0; j < array->n_group; ++j) {
3456 struct gpu_array_ref_group *group = array->groups[j];
3457 if (!group->private_tile && !group->shared_tile)
3458 continue;
3459 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3460 ++n;
3465 /* The sizes of the arrays on the host that have been computed by
3466 * extract_array_info may depend on the parameters. Use the extra
3467 * constraints on the parameters that are valid at "host_domain"
3468 * to simplify these expressions and store the results in kernel->array.
3470 * We only need these localized bounds for arrays that are accessed
3471 * by the current kernel. If we have found at least one reference group
3472 * then the array is accessed by the kernel. If the array has compound
3473 * elements then we skipped the construction of array reference groups.
3475 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3476 __isl_keep isl_set *host_domain)
3478 int i, j;
3479 isl_set *context;
3481 kernel->array = isl_calloc_array(gen->ctx,
3482 struct gpu_local_array_info, gen->prog->n_array);
3483 assert(kernel->array);
3484 kernel->n_array = gen->prog->n_array;
3486 context = isl_set_copy(host_domain);
3487 context = isl_set_params(context);
3489 for (i = 0; i < gen->prog->n_array; ++i) {
3490 struct gpu_array_info *array = &gen->prog->array[i];
3491 isl_pw_aff_list *local;
3493 if (array->n_group == 0 && !array->has_compound_element)
3494 continue;
3496 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3498 for (j = 0; j < array->n_index; ++j) {
3499 isl_pw_aff *pwaff;
3501 pwaff = isl_pw_aff_copy(array->bound[j]);
3502 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3503 local = isl_pw_aff_list_add(local, pwaff);
3506 kernel->array[i].bound = local;
3508 isl_set_free(context);
3511 /* Find the element in gen->stmt that has the given "id".
3512 * Return NULL if no such gpu_stmt can be found.
3514 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3516 int i;
3518 for (i = 0; i < prog->n_stmts; ++i) {
3519 if (id == prog->stmts[i].id)
3520 break;
3523 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3526 /* Set gen->tile_len and gen->n_parallel to those of the statement
3527 * affected by the first map (part of the schedule)
3528 * on which this function is called.
3529 * Because of the way the schedule is constructed, the other statements
3530 * in the list, if any, should have the same values for these properties.
3532 static int extract_tile_len(__isl_take isl_map *map, void *user)
3534 struct gpu_gen *gen = (struct gpu_gen *) user;
3535 isl_id *id;
3536 struct gpu_stmt *stmt;
3538 id = isl_map_get_tuple_id(map, isl_dim_in);
3539 stmt = find_stmt(gen->prog, id);
3540 isl_id_free(id);
3542 isl_map_free(map);
3544 if (!stmt)
3545 isl_die(gen->ctx, isl_error_unknown,
3546 "statement not found", return -1);
3548 gen->tile_len = stmt->tile_len;
3549 gen->n_parallel = stmt->n_parallel;
3551 return -1;
3554 void ppcg_kernel_stmt_free(void *user)
3556 int i;
3557 struct ppcg_kernel_stmt *stmt = user;
3559 if (!stmt)
3560 return;
3562 switch (stmt->type) {
3563 case ppcg_kernel_copy:
3564 isl_ast_expr_free(stmt->u.c.index);
3565 isl_ast_expr_free(stmt->u.c.local_index);
3566 break;
3567 case ppcg_kernel_domain:
3568 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
3569 break;
3570 case ppcg_kernel_sync:
3571 break;
3574 free(stmt);
3577 /* Set the options of "context" to
3579 * { space -> [x] : x >= first }
3581 static __isl_give isl_ast_build *set_unroll(
3582 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3583 int first)
3585 isl_ctx *ctx;
3586 isl_map *unroll;
3587 isl_union_map *opt;
3589 ctx = isl_ast_build_get_ctx(build);
3591 space = isl_space_from_domain(space);
3592 space = isl_space_add_dims(space, isl_dim_out, 1);
3593 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3594 unroll = isl_map_universe(space);
3595 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3596 opt = isl_union_map_from_map(unroll);
3598 build = isl_ast_build_set_options(build, opt);
3600 return build;
3603 /* Return a list of isl_ids of the form "prefix%d".
3605 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3606 int n, const char *prefix)
3608 int i;
3609 char name[10];
3610 isl_id_list *names;
3612 names = isl_id_list_alloc(ctx, n);
3613 for (i = 0; i < n; ++i) {
3614 isl_id *id;
3616 snprintf(name, sizeof(name), "%s%d", prefix, i);
3617 id = isl_id_alloc(ctx, name, NULL);
3618 names = isl_id_list_add(names, id);
3621 return names;
3624 /* Extend the schedule "schedule" with the part of "extension"
3625 * starting at "first" up to "len".
3627 static __isl_give isl_union_map *extend_schedule(
3628 __isl_take isl_union_map *schedule,
3629 __isl_take isl_union_map *extension, int first, int len)
3631 isl_space *space;
3632 isl_map *proj;
3633 isl_union_map *umap;
3634 isl_set *set;
3636 space = isl_union_map_get_space(schedule);
3637 space = isl_space_set_from_params(space);
3638 space = isl_space_add_dims(space, isl_dim_set, len);
3639 proj = isl_set_identity(isl_set_universe(space));
3640 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3641 extension = isl_union_map_apply_range(extension,
3642 isl_union_map_from_map(proj));
3644 schedule = isl_union_map_range_product(schedule, extension);
3646 return schedule;
3649 /* Return the gpu_stmt_access in the list "accesses" that corresponds
3650 * to "ref_id".
3652 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
3653 __isl_keep isl_id *ref_id)
3655 struct gpu_stmt_access *access;
3657 for (access = accesses; access; access = access->next)
3658 if (access->ref_id == ref_id)
3659 return access;
3661 return NULL;
3664 /* Return the index of the array called "name" in the list of arrays.
3666 static int find_array_index(struct gpu_gen *gen, const char *name)
3668 int i;
3670 for (i = 0; i < gen->prog->n_array; ++i)
3671 if (!strcmp(name, gen->prog->array[i].name))
3672 return i;
3674 return -1;
3677 /* Internal data structure for the index and AST expression transformation
3678 * callbacks for pet_stmt_build_ast_exprs.
3680 * "accesses" is the list of gpu_stmt_access in the statement.
3681 * "iterator_map" expresses the statement iterators in terms of
3682 * the AST loop iterators.
3683 * "sched2shared" expresses the first shared_len dimensions of
3684 * the computed schedule in terms of the AST loop iterators.
3686 * The following fields are set in transform_index and used in transform_expr.
3687 * "array" is the array that is being accessed.
3688 * "global" is set if the global array is accessed (rather than
3689 * shared/private memory).
3690 * "local_array" refers to information on the array specialized
3691 * to the current kernel.
3693 struct ppcg_transform_data {
3694 struct gpu_gen *gen;
3695 struct gpu_stmt_access *accesses;
3696 isl_pw_multi_aff *iterator_map;
3697 isl_pw_multi_aff *sched2shared;
3699 struct gpu_array_info *array;
3700 int global;
3701 struct gpu_local_array_info *local_array;
3704 /* Return the name of the outer array (of structs) accessed by "access".
3706 static const char *get_outer_array_name(__isl_keep isl_map *access)
3708 isl_space *space;
3709 const char *name;
3711 space = isl_space_range(isl_map_get_space(access));
3712 while (space && isl_space_is_wrapping(space))
3713 space = isl_space_domain(isl_space_unwrap(space));
3714 name = isl_space_get_tuple_name(space, isl_dim_set);
3715 isl_space_free(space);
3717 return name;
3720 /* Index transformation callback for pet_stmt_build_ast_exprs.
3722 * "index" expresses the array indices in terms of statement iterators
3724 * We first reformulate "index" in terms of the AST loop iterators.
3725 * Then we check if we are accessing the global array or
3726 * a shared/private copy. In the former case, we simply return
3727 * the updated index. If "index" is an affine expression rather
3728 * than an array access, then we also return the updated index here.
3730 * If no reference groups have been computed for the array,
3731 * then we can only be accessing the global array.
3733 * Otherwise, we apply the tiling to the index.
3734 * This tiling is of the form
3736 * [D -> A] -> T
3738 * The index is of the form
3740 * L -> A
3742 * We update the tiling to refer to the AST loop iteratos
3744 * [L -> A] -> T
3746 * and modify index to keep track of those iterators
3748 * L -> [L -> A]
3750 * Combining these two yields a tiled index expression in terms
3751 * of the AST loop iterators
3753 * L -> T
3755 static __isl_give isl_multi_pw_aff *transform_index(
3756 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
3757 void *user)
3759 struct ppcg_transform_data *data = user;
3760 struct gpu_stmt_access *access;
3761 struct gpu_array_ref_group *group;
3762 struct gpu_array_tile *tile;
3763 isl_pw_multi_aff *iterator_map;
3764 int i;
3765 const char *name;
3766 isl_space *space;
3767 isl_multi_pw_aff *tiling;
3768 isl_pw_multi_aff *pma;
3769 isl_multi_pw_aff *mpa;
3771 data->array = NULL;
3773 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
3774 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
3776 access = find_access(data->accesses, ref_id);
3777 if (!access)
3778 return index;
3779 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
3780 return index;
3782 name = get_outer_array_name(access->access);
3783 i = find_array_index(data->gen, name);
3784 if (i < 0)
3785 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
3786 "cannot find array",
3787 return isl_multi_pw_aff_free(index));
3788 data->array = &data->gen->prog->array[i];
3789 data->local_array = &data->gen->kernel->array[i];
3791 if (access->group < 0) {
3792 data->global = 1;
3793 return index;
3796 group = data->array->groups[access->group];
3797 tile = group->private_tile;
3798 if (!tile)
3799 tile = group->shared_tile;
3800 data->global = !tile;
3801 if (!tile)
3802 return index;
3804 space = isl_space_range(isl_multi_pw_aff_get_space(index));
3805 space = isl_space_map_from_set(space);
3806 pma = isl_pw_multi_aff_identity(space);
3807 pma = isl_pw_multi_aff_product(
3808 isl_pw_multi_aff_copy(data->sched2shared), pma);
3809 tiling = isl_multi_pw_aff_from_multi_aff(
3810 isl_multi_aff_copy(tile->tiling));
3811 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
3813 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
3814 space = isl_space_map_from_set(space);
3815 mpa = isl_multi_pw_aff_identity(space);
3816 index = isl_multi_pw_aff_range_product(mpa, index);
3817 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
3819 return index;
3822 /* Dereference "expr" by adding an index [0].
3823 * The original "expr" is assumed not to have any indices.
3825 * If "expr" is a member access, then the dereferencing needs
3826 * to be applied to the structure argument of this member access.
3828 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
3830 isl_ctx *ctx;
3831 isl_ast_expr *res;
3832 isl_ast_expr_list *list;
3834 if (isl_ast_expr_get_op_type(expr) == isl_ast_op_member) {
3835 isl_ast_expr *arg;
3837 arg = isl_ast_expr_get_op_arg(expr, 0);
3838 arg = dereference(arg);
3839 expr = isl_ast_expr_set_op_arg(expr, 0, arg);
3841 return expr;
3844 ctx = isl_ast_expr_get_ctx(expr);
3845 res = isl_ast_expr_from_val(isl_val_zero(ctx));
3846 list = isl_ast_expr_list_from_ast_expr(res);
3847 res = isl_ast_expr_get_op_arg(expr, 0);
3848 res = isl_ast_expr_access(res, list);
3849 isl_ast_expr_free(expr);
3851 return res;
3854 /* Linearize the index expression "expr" based on the array bounds
3855 * of "array".
3857 * That is, transform expression
3859 * A[i_0][i_1]...[i_n]
3861 * to
3863 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
3865 * where b_0, b_1, ..., b_n are the bounds on the array.
3867 * If the base of "expr" is a member access, then the linearization needs
3868 * to be applied to the structure argument of this member access.
3870 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
3871 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
3873 int i, n;
3874 isl_ctx *ctx;
3875 isl_set *context;
3876 isl_ast_expr *arg0;
3877 isl_ast_expr *res;
3878 isl_ast_expr_list *list;
3879 isl_ast_build *build;
3881 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3882 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3883 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3884 isl_ast_expr *arg;
3886 arg = isl_ast_expr_get_op_arg(arg0, 0);
3887 arg = gpu_local_array_info_linearize_index(array, arg);
3888 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3889 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3891 return expr;
3893 isl_ast_expr_free(arg0);
3895 ctx = isl_ast_expr_get_ctx(expr);
3896 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
3897 build = isl_ast_build_from_context(context);
3899 n = isl_ast_expr_get_op_n_arg(expr);
3900 res = isl_ast_expr_get_op_arg(expr, 1);
3901 for (i = 2; i < n; ++i) {
3902 isl_pw_aff *bound_i;
3903 isl_ast_expr *expr_i;
3905 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i - 1);
3906 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
3907 res = isl_ast_expr_mul(res, expr_i);
3908 expr_i = isl_ast_expr_get_op_arg(expr, i);
3909 res = isl_ast_expr_add(res, expr_i);
3912 isl_ast_build_free(build);
3914 list = isl_ast_expr_list_from_ast_expr(res);
3915 res = isl_ast_expr_get_op_arg(expr, 0);
3916 res = isl_ast_expr_access(res, list);
3918 isl_ast_expr_free(expr);
3920 return res;
3923 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
3925 * If the AST expression refers to a global scalar that is not
3926 * a read-only scalar, then its address was passed to the kernel and
3927 * we need to dereference it.
3929 * If the AST expression refers to an access to a global array,
3930 * then we linearize the access exploiting the bounds in data->local_array.
3932 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
3933 __isl_keep isl_id *id, void *user)
3935 struct ppcg_transform_data *data = user;
3937 if (!data->array)
3938 return expr;
3939 if (gpu_array_is_read_only_scalar(data->array))
3940 return expr;
3941 if (!data->global)
3942 return expr;
3943 if (data->array->n_index == 0)
3944 return dereference(expr);
3945 if (!data->array->linearize)
3946 return expr;
3948 return gpu_local_array_info_linearize_index(data->local_array, expr);
3951 /* This function is called for each instance of a user statement
3952 * in the kernel.
3954 * We attach a struct ppcg_kernel_stmt to the "node", containing
3955 * a computed AST expression for each access.
3956 * These AST expressions are computed from iterator_map,
3957 * which expresses the domain
3958 * elements in terms of the generated loops, and sched2shared,
3959 * which expresses the first shared_len dimensions of the schedule
3960 * computed by PPCG in terms of the generated loops.
3962 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3963 __isl_keep isl_ast_build *build, void *user)
3965 struct ppcg_transform_data data;
3966 struct gpu_gen *gen = (struct gpu_gen *) user;
3967 struct ppcg_kernel_stmt *stmt;
3968 isl_id *id;
3969 isl_pw_multi_aff *sched2shared;
3970 isl_map *map;
3971 isl_pw_multi_aff *iterator_map;
3972 isl_ast_expr *expr, *arg;
3973 isl_union_map *schedule;
3974 int i, n;
3975 struct gpu_stmt_access *access;
3977 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3978 if (!stmt)
3979 return isl_ast_node_free(node);
3981 expr = isl_ast_node_user_get_expr(node);
3982 arg = isl_ast_expr_get_op_arg(expr, 0);
3983 id = isl_ast_expr_get_id(arg);
3985 schedule = isl_ast_build_get_schedule(build);
3986 map = isl_map_reverse(isl_map_from_union_map(schedule));
3987 iterator_map = isl_pw_multi_aff_from_map(map);
3988 sched2shared = compute_sched_to_shared(gen,
3989 isl_pw_multi_aff_copy(iterator_map));
3991 stmt->type = ppcg_kernel_domain;
3992 stmt->u.d.stmt = find_stmt(gen->prog, id);
3993 if (!stmt->u.d.stmt)
3994 goto error;
3996 data.gen = gen;
3997 data.accesses = stmt->u.d.stmt->accesses;
3998 data.iterator_map = iterator_map;
3999 data.sched2shared = sched2shared;
4000 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
4001 build, &transform_index, &data,
4002 &transform_expr, &data);
4004 isl_id_free(id);
4005 isl_pw_multi_aff_free(iterator_map);
4006 isl_pw_multi_aff_free(sched2shared);
4007 isl_ast_expr_free(arg);
4008 isl_ast_expr_free(expr);
4010 id = isl_id_alloc(gen->ctx, NULL, stmt);
4011 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4012 return isl_ast_node_set_annotation(node, id);
4013 error:
4014 isl_id_free(id);
4015 isl_pw_multi_aff_free(iterator_map);
4016 ppcg_kernel_stmt_free(stmt);
4017 isl_pw_multi_aff_free(sched2shared);
4018 return isl_ast_node_free(node);
4021 /* This function is called when code has been generated for the shared
4022 * tile loops. The "schedule" refers only to the original statements.
4024 * We extend the schedule with that part of gen->local_sched that hasn't
4025 * been taken into account yet. This introduces parameters referring
4026 * to thread ids in the schedule, so we add them (with the appropriate
4027 * bounds to the context as well).
4028 * Finally, we set the appropriate unrolling options
4029 * if gen->first_unroll is set.
4031 static __isl_give isl_ast_node *create_domain_leaf(
4032 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
4033 void *user)
4035 struct gpu_gen *gen = (struct gpu_gen *) user;
4036 isl_space *space;
4037 isl_union_map *sched;
4038 isl_ast_node *tree;
4039 isl_set *set;
4040 isl_id_list *iterators;
4041 int n;
4043 schedule = extend_schedule(schedule,
4044 isl_union_map_copy(gen->local_sched),
4045 gen->shared_len, gen->thread_tiled_len);
4047 space = isl_ast_build_get_schedule_space(build);
4048 set = isl_set_universe(space);
4049 set = add_bounded_parameters(set, gen->kernel->n_block,
4050 gen->kernel->block_dim, "t");
4051 build = isl_ast_build_restrict(build, set);
4053 n = gen->thread_tiled_len - gen->shared_len;
4055 if (gen->first_unroll >= 0) {
4056 space = isl_space_set_alloc(gen->ctx, 0, n);
4057 build = set_unroll(build, space, gen->first_unroll);
4059 iterators = generate_names(gen->ctx, n, "c");
4060 build = isl_ast_build_set_iterators(build, iterators);
4061 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
4062 tree = isl_ast_build_ast_from_schedule(build, schedule);
4063 isl_ast_build_free(build);
4065 return tree;
4068 /* This function is called for each statement node in the AST of the code
4069 * for copying to or from shared/private memory.
4070 * Attach a pointer to a ppcg_kernel_stmt representing the copy
4071 * statement to the node.
4072 * The statement name is "read" or "write", depending on whether we are
4073 * reading from global memory or writing to global memory.
4074 * The name of the T space is {shared,private}_<array>.
4076 * The schedule is of the form
4078 * type[A -> T] -> L
4080 * where A refers to a piece of an array and T to the corresponding
4081 * shifted tile. We split this schedule into mappings L -> A and L -> T
4082 * and store the corresponding expressions in stmt->index and stmt->local_index,
4083 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
4085 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
4086 __isl_keep isl_ast_build *build, void *user)
4088 struct gpu_gen *gen = (struct gpu_gen *) user;
4089 struct ppcg_kernel_stmt *stmt;
4090 isl_id *id;
4091 isl_ast_expr *expr;
4092 isl_space *space;
4093 isl_map *access, *local_access, *map;
4094 isl_pw_multi_aff *pma;
4095 const char *type;
4096 int array_index;
4098 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4099 if (!stmt)
4100 return isl_ast_node_free(node);
4102 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
4103 type = isl_map_get_tuple_name(access, isl_dim_in);
4104 stmt->u.c.read = !strcmp(type, "read");
4105 access = isl_map_reverse(access);
4106 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
4107 local_access = isl_map_copy(access);
4109 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
4110 id = isl_map_get_tuple_id(access, isl_dim_out);
4111 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4112 access = isl_map_apply_range(access, map);
4113 pma = isl_pw_multi_aff_from_map(access);
4114 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4115 stmt->u.c.index = expr;
4117 map = isl_map_range_map(isl_map_universe(space));
4118 id = isl_map_get_tuple_id(local_access, isl_dim_out);
4119 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4120 local_access = isl_map_apply_range(local_access, map);
4121 pma = isl_pw_multi_aff_from_map(local_access);
4122 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4123 stmt->u.c.local_index = expr;
4125 stmt->u.c.array = gen->copy_group->array;
4126 array_index = stmt->u.c.array - gen->prog->array;
4127 stmt->u.c.local_array = &gen->kernel->array[array_index];
4128 stmt->type = ppcg_kernel_copy;
4130 id = isl_id_alloc(gen->ctx, NULL, stmt);
4131 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4132 return isl_ast_node_set_annotation(node, id);
4135 /* Given a schedule of the form
4137 * [S -> A] -> L
4139 * (with S the first shared_len dimensions of the computed schedule,
4140 * A the array and L the schedule correponding to the generated loops),
4141 * indicating where to copy the array elements that need to be copied,
4142 * construct code for performing the copying.
4144 * "group" is the array reference group that is being copied
4145 * "type" is either "read" or "write"
4146 * private is set if copying needs to be performed to/from registers
4148 * We first construct a mapping to a shifted tile of the array,
4150 * [S -> A] -> T(S,A) (1)
4152 * If private is set, then we also use this mapping as a schedule
4153 * (which is already thread-specific and will be completely unrolled).
4154 * Otherwise, we wrap/tile the range over the threads.
4155 * The result is
4157 * [S -> A] -> T'(S,A)
4159 * Combined with the given schedule, we have
4161 * [S -> A] -> [L -> T'(S,A)] (2)
4163 * From the shifted tile mapping, we construct a mapping
4165 * [S -> A] -> [A -> T(S,A)]
4167 * and apply it to the schedule (2), obtaining
4169 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
4171 * Note that we can project out S because it is uniquely defined by L.
4173 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
4174 __isl_take isl_map *sched,
4175 const char *type, struct gpu_array_ref_group *group,
4176 __isl_take isl_ast_build *build, int private)
4178 isl_space *space;
4179 isl_ast_node *tree;
4180 isl_map *schedule, *shift, *map;
4181 isl_set *set;
4182 isl_id_list *iterators;
4183 int n;
4185 shift = shift_access(group);
4187 schedule = isl_map_copy(shift);
4188 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
4189 if (!private)
4190 schedule = tile_access_schedule(gen, schedule);
4192 n = isl_map_dim(schedule, isl_dim_out);
4193 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
4194 set = add_bounded_parameters(set, gen->kernel->n_block,
4195 gen->kernel->block_dim, "t");
4197 schedule = isl_map_range_product(sched, schedule);
4199 space = isl_space_domain(isl_map_get_space(shift));
4200 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
4201 map = isl_map_range_product(map, shift);
4203 schedule = isl_map_apply_domain(schedule, map);
4205 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
4207 build = isl_ast_build_restrict(build, set);
4209 gen->copy_group = group;
4211 if (private) {
4212 space = isl_space_range(isl_map_get_space(schedule));
4213 space = isl_space_range(isl_space_unwrap(space));
4214 build = set_unroll(build, space, 0);
4216 iterators = generate_names(gen->ctx, n, "c");
4217 build = isl_ast_build_set_iterators(build, iterators);
4218 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
4219 tree = isl_ast_build_ast_from_schedule(build,
4220 isl_union_map_from_map(schedule));
4221 isl_ast_build_free(build);
4223 return tree;
4226 /* Return code for reading into or writing from shared memory
4227 * the given array reference group.
4229 * If we are performing a read from global memory to shared memory and
4230 * if the array involved is not a scalar, then we copy
4231 * the entire tile to shared memory. This may result in some extra
4232 * elements getting copied, but it should lead to simpler code
4233 * (which means that fewer registers may be needed) and less divergence.
4235 * Otherwise, we only copy the elements that will be read or have been written
4236 * in the kernel.
4239 * The input "sched" is of the form.
4241 * type[S -> A] -> L
4243 * with S the first shared_len dimensions of the computed schedule,
4244 * A the array and L the schedule correponding to the generated loops.
4246 * We first drop "type",
4248 * [S -> A] -> L
4250 * If the above conditions are satisfied, we project out A,
4251 * resulting in
4253 * S -> L
4255 * and then introduce the group tile [S -> T], resulting in
4257 * [S -> T] -> L
4259 static __isl_give isl_ast_node *copy_group_shared_accesses(
4260 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4261 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4263 const char *type;
4264 int read;
4265 isl_union_map *access;
4267 type = isl_map_get_tuple_name(sched, isl_dim_in);
4268 read = !strcmp(type, "read");
4270 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4272 if (read && !gpu_array_is_scalar(group->array)) {
4273 isl_space *space;
4274 isl_map *map;
4276 space = isl_space_domain(isl_map_get_space(sched));
4277 space = isl_space_unwrap(space);
4278 map = isl_map_domain_map(isl_map_universe(space));
4279 sched = isl_map_apply_domain(sched, map);
4281 map = group_tile(group);
4282 map = isl_map_reverse(isl_map_domain_map(map));
4283 sched = isl_map_apply_domain(sched, map);
4286 return copy_access(gen, sched, type, group, build, 0);
4289 /* Return code for reading into or writing from private memory
4290 * the given array reference group.
4292 * Let S be the first shared_len dimensions of the computed schedule,
4293 * D the iteration domains, A the array and L the schedule correponding
4294 * to the generated loops.
4295 * "sched" is of the form
4297 * type[S -> A] -> L
4299 * where type is either "read" or "write".
4300 * We apply the privatization D -> S(t), with t the thread ids,
4301 * to the access relation D -> A to obtain the privatized access relation
4303 * S(t) -> A
4305 * We drop the type from "sched" and intersect with the privatized access
4306 * relation to obtain
4308 * [S(t) -> A] -> L
4310 static __isl_give isl_ast_node *copy_group_private_accesses(
4311 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4312 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4314 const char *type;
4315 int read;
4316 isl_union_map *priv;
4317 isl_union_map *access;
4318 isl_map *access_map;
4320 type = isl_map_get_tuple_name(sched, isl_dim_in);
4321 read = !strcmp(type, "read");
4323 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
4324 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
4325 priv);
4327 access = group_access_relation(group, read, !read);
4328 access = isl_union_map_apply_domain(access, priv);
4329 access_map = isl_map_from_union_map(access);
4331 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4332 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
4334 return copy_access(gen, sched, type, group, build, 1);
4337 /* Return code for reading into or writing from shared or private memory.
4339 * "schedule" is of the form
4341 * type[S -> A] -> L
4343 * with S be the first shared_len dimensions of the computed schedule,
4344 * A the array and L the schedule correponding to the generated loops.
4345 * The array reference group is attached to "type".
4347 static __isl_give isl_ast_node *create_access_leaf(
4348 struct gpu_gen *gen, __isl_take isl_map *schedule,
4349 __isl_take isl_ast_build *build)
4351 struct gpu_array_ref_group *group;
4352 isl_id *id;
4354 id = isl_map_get_tuple_id(schedule, isl_dim_in);
4355 group = isl_id_get_user(id);
4356 isl_id_free(id);
4358 if (group->private_tile)
4359 return copy_group_private_accesses(gen, group, schedule,
4360 build);
4361 else
4362 return copy_group_shared_accesses(gen, group, schedule,
4363 build);
4366 /* Create a domain node representing a synchronization.
4368 static __isl_give isl_ast_node *create_sync_leaf(
4369 struct gpu_gen *gen, __isl_take isl_map *schedule,
4370 __isl_take isl_ast_build *build)
4372 struct ppcg_kernel_stmt *stmt;
4373 isl_id *id;
4374 isl_space *space;
4375 isl_ast_node *node;
4376 isl_ast_expr *expr;
4378 isl_map_free(schedule);
4380 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4381 if (!stmt)
4382 return NULL;
4384 stmt->type = ppcg_kernel_sync;
4386 space = isl_ast_build_get_schedule_space(build);
4387 space = isl_space_from_domain(space);
4388 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
4389 expr = isl_ast_build_call_from_pw_multi_aff(build,
4390 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
4391 node = isl_ast_node_alloc_user(expr);
4392 isl_ast_build_free(build);
4394 id = isl_id_alloc(gen->ctx, NULL, stmt);
4395 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4396 return isl_ast_node_set_annotation(node, id);
4399 /* This function is called during the code generation at the point
4400 * where the schedule domain element is completely determined by
4401 * the generated code. The input schedule contains the original
4402 * statements as well as synchronization and copy "statements".
4403 * The latter are scheduled at different points than any of the original
4404 * statements, so they will only arrive here in isolation.
4406 * If the current schedule only refers to a single statement,
4407 * we check if it is a copy or synchronization statement and
4408 * call the appropriate functions.
4409 * Otherwise, we assume we are dealing with the original statements
4410 * and we call create_domain_leaf.
4412 static __isl_give isl_ast_node *create_kernel_leaf(
4413 __isl_take isl_ast_build *build, void *user)
4415 struct gpu_gen *gen = (struct gpu_gen *) user;
4416 isl_map *map;
4417 isl_union_map *schedule;
4418 const char *name;
4420 schedule = isl_ast_build_get_schedule(build);
4422 if (isl_union_map_n_map(schedule) != 1)
4423 return create_domain_leaf(schedule, build, user);
4425 map = isl_map_from_union_map(schedule);
4426 name = isl_map_get_tuple_name(map, isl_dim_in);
4427 if (!strcmp(name, "read") || !strcmp(name, "write"))
4428 return create_access_leaf(gen, map, build);
4429 if (!strcmp(name, "sync"))
4430 return create_sync_leaf(gen, map, build);
4432 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4435 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4436 * have value 0) and all even schedule dimensions as "unroll".
4438 * That is, the options look as follows
4440 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4441 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4443 * The even positions are used to be able to schedule copying blocks
4444 * and synchronization before or after each level of the shared memory
4445 * tile loops and we want to make sure that code for these is generated
4446 * separately (within each level).
4448 static __isl_give isl_ast_build *set_atomic_and_unroll(
4449 __isl_take isl_ast_build *build,
4450 __isl_take isl_space *space, int sched_len)
4452 isl_ctx *ctx;
4453 isl_map *map;
4454 isl_constraint *c;
4455 isl_union_map *opt;
4456 isl_local_space *ls;
4457 int i, n;
4459 ctx = isl_ast_build_get_ctx(build);
4461 space = isl_space_params(space);
4462 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4463 space = isl_space_from_domain(space);
4464 space = isl_space_add_dims(space, isl_dim_out, 2);
4465 map = isl_map_universe(isl_space_copy(space));
4466 for (i = 0; i < sched_len; i += 2)
4467 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4468 ls = isl_local_space_from_space(isl_map_get_space(map));
4469 c = isl_equality_alloc(ls);
4470 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4471 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4472 c = isl_constraint_set_constant_si(c, 1);
4473 map = isl_map_add_constraint(map, c);
4474 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4475 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4476 opt = isl_union_map_from_map(map);
4478 map = isl_map_universe(space);
4479 ls = isl_local_space_from_space(isl_map_get_space(map));
4480 c = isl_equality_alloc(ls);
4481 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4482 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4483 map = isl_map_add_constraint(map, c);
4484 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4485 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4486 opt = isl_union_map_add_map(opt, map);
4488 build = isl_ast_build_set_options(build, opt);
4490 return build;
4493 /* Return a map that maps a space of dimension gen->shared_len
4494 * to its last dimensions starting at gen->tile_first.
4495 * The range is of dimension
4497 * 2 * (gen->shared_len - gen->tile_first) + 1
4499 * The input dimensions are mapped to the odd dimensions in the output,
4500 * while the even dimensions (except 2*pos) are fixed to 0.
4501 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4502 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4503 * are mapped to the output. The remaining input dimensions are projected
4504 * out and the corresponding output dimensions are fixed to 0.
4506 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4507 __isl_take isl_space *space, int pos, int val)
4509 int i, n;
4510 isl_map *proj;
4512 space = isl_space_set_from_params(space);
4513 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4514 space = isl_space_map_from_set(space);
4515 proj = isl_map_identity(space);
4516 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4517 n = gen->shared_len - gen->tile_first;
4518 for (i = 0; i <= n; ++i) {
4519 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4520 if (i == pos)
4521 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4522 else
4523 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4526 if (pos < 0)
4527 return proj;
4529 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4530 gen->shared_len - (gen->tile_first + pos));
4531 for (i = pos; i < n; ++i)
4532 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4534 return proj;
4537 /* Given the AST context schedule "schedule" and the mapping from
4538 * domains to the shared tile loops "shared_sched", add a schedule
4539 * for a synchronization operation at position "val" of loop level "pos".
4541 * schedule is of the form
4543 * D -> L
4545 * (with D the iteration domains and L the already generated loops),
4546 * while shared_sched is of the form
4548 * D -> S
4550 * We combine them into
4552 * L -> S
4554 * apply a mapping
4556 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4558 * and use the result as a schedule for "sync".
4560 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4561 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4562 __isl_keep isl_union_map *shared_sched, int pos, int val)
4564 isl_space *space;
4565 isl_map *proj, *map;
4567 shared_sched = isl_union_map_copy(shared_sched);
4568 schedule = isl_union_map_copy(schedule);
4570 space = isl_union_map_get_space(shared_sched);
4571 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4572 map = isl_map_from_union_map(schedule);
4574 proj = insert_even(gen, space, pos, val);
4575 map = isl_map_apply_range(map, proj);
4576 map = isl_map_from_range(isl_map_wrap(map));
4577 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4579 res = isl_union_map_add_map(res, map);
4581 return res;
4584 /* Given a set of wrapped references "ref", return the corresponding
4585 * access relations based on the tagged access relations "tagged".
4587 * The elements of "ref" are of the form
4589 * [D -> R]
4591 * with D an iteration domains and R a reference.
4592 * The elements of "tagged" are of the form
4594 * [D -> R] -> A
4596 * with A an array.
4598 * Extend "tagged" to include the iteration domain in the range, i.e.,
4600 * [D -> R] -> [D -> A]
4602 * apply the result to "ref" and then unwrap the resulting set
4603 * to obtain relations of the form
4605 * D -> A
4607 static __isl_give isl_union_map *wrapped_reference_to_access(
4608 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
4610 isl_union_map *tag2access;
4612 tag2access = isl_union_map_copy(tagged);
4613 tag2access = isl_union_map_universe(tag2access);
4614 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
4615 tag2access = isl_union_map_domain_map(tag2access);
4616 tag2access = isl_union_map_range_product(tag2access, tagged);
4618 ref = isl_union_set_coalesce(ref);
4619 ref = isl_union_set_apply(ref, tag2access);
4621 return isl_union_set_unwrap(ref);
4624 /* Given an access relation "access" from "group", remove those reads
4625 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
4626 * communicate data within the same iteration of the last_shared dimension
4627 * of the group.
4629 * If the access is a read then it is necessarily an element of
4631 * live_in union (range flow)
4633 * where live_in and flow may be overapproximations.
4634 * If the access is a write then it is necessarily an element of
4636 * live_out union (domain flow)
4638 * In both cases, the access relation is also a subset of
4639 * the group access relation.
4641 * Essentially, we compute the intersection of "access" with either
4643 * live_in union (range non-local-flow)
4645 * or
4647 * live_out union (domain non-local-flow)
4649 * We first construct a relation "local"
4651 * [[D -> R] -> [D' -> R']]
4653 * of pairs of domain iterations accessing the reference group
4654 * and references in the group that are scheduled to the same iteration
4655 * of the last_shared dimension.
4657 * If this relation does not intersect the dataflow dependences,
4658 * then there is nothing we can possibly remove and we simply
4659 * return the input.
4661 * Otherwise, we remove the "local" dataflow dependences from
4662 * the set of all dataflow dependences.
4663 * Note that if the potential dataflow dependences are an overapproximation
4664 * of the actual dataflow dependences, then the result remains an
4665 * overapproximation of the non-local dataflow dependences.
4666 * Copying to/from global memory is only needed for the references
4667 * in the domain/range of the result or for accesses that are live out/in
4668 * for the entire scop.
4670 * We therefore map the domain/range of the "external" relation
4671 * to the corresponding access relation and take the union with
4672 * the live out/in relation.
4674 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
4675 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
4676 int read)
4678 int empty;
4679 isl_union_map *tagger;
4680 isl_union_set *domain;
4681 isl_space *space;
4682 isl_union_map *sched, *local, *tagged, *external;
4683 isl_union_set *tag_set;
4684 isl_map *proj;
4686 if (isl_union_map_is_empty(access))
4687 return access;
4689 tagged = group_tagged_access_relation(group);
4691 sched = isl_union_map_copy(gen->sched);
4693 space = isl_union_map_get_space(sched);
4694 proj = projection(space, gen->untiled_len, group->last_shared + 1);
4695 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4697 tagger = isl_union_map_copy(gen->prog->scop->tagger);
4698 domain = isl_union_map_domain(isl_union_map_copy(tagged));
4699 tagger = isl_union_map_intersect_range(tagger, domain);
4700 sched = isl_union_map_apply_domain(sched, tagger);
4702 local = isl_union_map_apply_range(sched,
4703 isl_union_map_reverse(isl_union_map_copy(sched)));
4704 local = isl_union_map_intersect(local,
4705 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
4707 empty = isl_union_map_is_empty(local);
4708 if (empty < 0 || empty) {
4709 isl_union_map_free(tagged);
4710 isl_union_map_free(local);
4711 if (empty < 0)
4712 return isl_union_map_free(access);
4713 return access;
4716 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
4717 external = isl_union_map_intersect_params(external,
4718 isl_set_copy(gen->prog->scop->context));
4719 external = isl_union_map_subtract(external, local);
4721 if (read) {
4722 tag_set = isl_union_map_range(external);
4723 external = wrapped_reference_to_access(tag_set, tagged);
4724 external = isl_union_map_union(external,
4725 isl_union_map_copy(gen->prog->scop->live_in));
4726 } else {
4727 tag_set = isl_union_map_domain(external);
4728 external = wrapped_reference_to_access(tag_set, tagged);
4729 external = isl_union_map_union(external,
4730 isl_union_map_copy(gen->prog->scop->live_out));
4733 access = isl_union_map_intersect(access, external);
4735 return access;
4738 /* Given the AST context schedule "schedule" and the mapping from
4739 * domains to the shared tile loops "shared_sched", add a schedule
4740 * for copying an array reference group to/from shared/private memory.
4741 * "read" is set if data should be copied from global memory
4742 * to shared/private memory.
4743 * "k" represents the current group
4744 * "s" is the total number of groups
4746 * We schedule an operation before or after the innermost loop
4747 * of "shared_sched" that affects the tile of the array reference group.
4749 * schedule is of the form
4751 * D -> L
4753 * (with D the iteration domains and L the already generated loops),
4754 * while shared_sched is of the form
4756 * D -> S
4758 * We first compute the access relation for the reference group
4760 * D -> A
4762 * and remove from this access relation those reads or writes
4763 * that only needed to communicate data within the same iteration
4764 * of the last_shared dimension of the group.
4765 * We then combine what is left with shared_sched into
4767 * D -> [S -> A]
4769 * If this results in an empty relation, no copying needs to be performed
4770 * at this point.
4771 * Otherwise, we invert the relation and combine it with "schedule" into
4773 * [S -> A] -> L
4775 * The actual additional piece of the schedule is obtained from combining
4777 * [S -> A] -> S
4779 * with a mapping
4781 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4783 * The position of "val" corresponds to the innermost loop that affects
4784 * the tile and the value indicates where the copying is scheduled
4785 * with respect to the actual kernel code (at value 0).
4786 * Reads are schedule before the code, writes to global memory from
4787 * private memory are scheduled at values 1 to s, writes to global
4788 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4790 * If we are scheduling a read from global memory to shared memory,
4791 * we insert a synchronization before the kernel code (at the innermost
4792 * level).
4793 * If we are scheduling a write to global memory, then we add
4794 * a synchronization after all writes (at value 2 *s + 2).
4795 * However, there is no need for a synchronization after the outermost loop.
4796 * A write to global memory from private memory at the innermost level
4797 * does not require a synchronization, because it is covered by
4798 * the synchronization after the kernel inserted by body_schedule.
4800 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4801 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4802 __isl_keep isl_union_map *shared_sched,
4803 struct gpu_array_ref_group *group, int read, int k, int s)
4805 int n;
4806 int pos, val;
4807 isl_space *space;
4808 isl_union_map *access;
4809 isl_map *map, *proj, *access_map;
4810 isl_id *id;
4812 access = group_access_relation(group, read, !read);
4813 access = remove_local_accesses(gen, group, access, read);
4814 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4815 access);
4817 if (isl_union_map_is_empty(access)) {
4818 isl_union_map_free(access);
4819 return res;
4822 access = isl_union_map_reverse(access);
4823 access = isl_union_map_apply_range(access,
4824 isl_union_map_copy(schedule));
4825 access_map = isl_map_from_union_map(access);
4827 space = isl_space_copy(group->array->space);
4828 space = isl_space_from_range(space);
4829 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4830 map = isl_map_domain_map(isl_map_universe(space));
4832 space = isl_union_map_get_space(schedule);
4833 pos = group->last_shared + 1 - gen->tile_first;
4834 assert(pos >= 0);
4835 if (read)
4836 val = -2 - k;
4837 else if (group->private_tile)
4838 val = 1 + k;
4839 else
4840 val = 1 + s + 1 + k;
4841 proj = insert_even(gen, space, pos, val);
4842 map = isl_map_apply_range(map, proj);
4844 access_map = isl_map_range_product(access_map, map);
4846 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4847 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4849 res = isl_union_map_add_map(res, access_map);
4851 n = gen->shared_len - gen->tile_first;
4852 if (read) {
4853 if (!group->private_tile)
4854 res = add_sync_schedule(gen, res, schedule,
4855 shared_sched, n, -1);
4856 } else {
4857 if (pos == 0)
4858 return res;
4859 if (pos == n && group->private_tile)
4860 return res;
4861 res = add_sync_schedule(gen, res, schedule, shared_sched,
4862 pos, 2 * s + 2);
4865 return res;
4868 /* Return a schedule for the shared tile loops based on the current
4869 * AST context schedule.
4871 * We create a "shared_sched" that maps the domains to the first
4872 * shared_len dimensions of the computed schedule, project out the
4873 * first tile_first dimensions (as these are already covered by
4874 * the host code) and insert "statement-level" dimensions at even
4875 * positions so that we can schedule copy blocks and synchronization
4876 * before/after each level.
4878 * In particular, copy blocks are inserted inside the innermost
4879 * level that affect the tile. For the copying to global memory,
4880 * those from private memory are scheduled before those from shared
4881 * memory such that synchronization can be inserted between the two
4882 * at the innermost level.
4883 * Synchronization is inserted at the innermost level before the
4884 * actual kernel code if there is any copying from global memory
4885 * to shared memory. It is inserted unconditionally at the innermost
4886 * level after the actual kernel code and the copying to global memory
4887 * from private memory (if any). Finally, it is inserted after
4888 * any copying to global memory, except at the outermost level
4889 * and at the innermost level if there is no copying from shared
4890 * memory. The copying from private memory is covered by the unconditional
4891 * synchronization at the innermost level.
4893 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4894 __isl_take isl_union_map *schedule)
4896 isl_space *space;
4897 isl_union_map *res;
4898 isl_union_map *shared_sched;
4899 isl_union_map *sched;
4900 isl_map *proj, *map;
4901 int i, j, k, s;
4903 shared_sched = isl_union_map_copy(gen->tiled_sched);
4904 proj = projection(isl_union_map_get_space(shared_sched),
4905 gen->tiled_len, gen->shared_len);
4906 shared_sched = isl_union_map_apply_range(shared_sched,
4907 isl_union_map_from_map(proj));
4908 space = isl_union_map_get_space(shared_sched);
4909 proj = insert_even(gen, space, -1, 0);
4910 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4911 isl_union_map_from_map(proj));
4913 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4915 s = 0;
4916 for (i = 0; i < gen->prog->n_array; ++i)
4917 s += gen->prog->array[i].n_group;
4919 k = 0;
4920 for (i = 0; i < gen->prog->n_array; ++i) {
4921 struct gpu_array_info *array = &gen->prog->array[i];
4923 for (j = 0; j < array->n_group; ++j) {
4924 struct gpu_array_ref_group *group;
4926 group = array->groups[j];
4927 if (!group->private_tile && !group->shared_tile)
4928 continue;
4929 res = add_group_schedule(gen, res, schedule,
4930 shared_sched, group, 0, k, s);
4931 res = add_group_schedule(gen, res, schedule,
4932 shared_sched, group, 1, k, s);
4933 ++k;
4937 res = add_sync_schedule(gen, res, schedule, shared_sched,
4938 gen->shared_len - gen->tile_first, 1 + s);
4940 isl_union_map_free(shared_sched);
4941 isl_union_map_free(schedule);
4943 return res;
4946 /* Generate code for "kernel" in the given "context".
4948 * We first generate code for the shared tile loops (T1T, T1P and T2)
4949 * in a context that includes the block ids.
4950 * Within each iteration of these loops an additional code generation
4951 * is performed (within create_kernel_leaf) for the rest of the schedule
4952 * in a context that includes the thread ids.
4954 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4955 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4956 __isl_keep isl_multi_pw_aff *grid_size)
4958 isl_space *space;
4959 isl_set *set;
4960 isl_id_list *iterators;
4961 isl_union_map *schedule;
4962 isl_ast_node *tree;
4963 int sched_len;
4965 schedule = isl_ast_build_get_schedule(build);
4967 build = isl_ast_build_copy(build);
4968 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4969 space = isl_ast_build_get_schedule_space(build);
4970 set = isl_set_universe(isl_space_copy(space));
4971 set = add_bounded_parameters_dynamic(set, grid_size, "b");
4972 build = isl_ast_build_restrict(build, set);
4974 schedule = body_schedule(gen, schedule);
4976 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4978 build = set_atomic_and_unroll(build, space, sched_len);
4979 iterators = generate_names(gen->ctx, sched_len, "g");
4980 build = isl_ast_build_set_iterators(build, iterators);
4981 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4982 tree = isl_ast_build_ast_from_schedule(build, schedule);
4983 isl_ast_build_free(build);
4985 return tree;
4988 /* Attach "id" to the given node.
4990 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4991 __isl_keep isl_ast_build *build, void *user)
4993 isl_id *id = user;
4995 node = isl_ast_node_set_annotation(node, id);
4997 return node;
5000 /* Construct an AST node for performing a kernel launch and attach
5001 * the information about the kernel to that node.
5003 * The kernel AST has been constructed in the context of the range
5004 * of "schedule". In particular, the grid size has been computed
5005 * in the context. We therefore still need to make sure that these
5006 * constraints are expressed in the code. We do this by creating a schedule
5008 * kernel[] -> [S -> []]
5010 * where S is the schedule domain, i.e., the range of "schedule".
5011 * The AST generation will then create a single call surrounded by
5012 * all the condition in "S" that have not been expressed yet.
5014 * The kernel information is attached to this node in attach_id.
5016 static __isl_give isl_ast_node *construct_launch(
5017 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
5018 __isl_take struct ppcg_kernel *kernel)
5020 isl_id *id;
5021 isl_ctx *ctx;
5022 isl_union_set *domain;
5023 isl_set *set;
5024 isl_map *map;
5025 isl_ast_node *node;
5027 ctx = isl_ast_build_get_ctx(build);
5029 id = isl_id_alloc(ctx, NULL, kernel);
5030 id = isl_id_set_free_user(id, &ppcg_kernel_free);
5032 domain = isl_union_map_range(schedule);
5033 set = isl_set_from_union_set(domain);
5034 map = isl_map_from_domain(set);
5035 map = isl_map_from_range(isl_map_wrap(map));
5036 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
5037 schedule = isl_union_map_from_map(map);
5039 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
5040 node = isl_ast_build_ast_from_schedule(build, schedule);
5041 isl_ast_build_free(build);
5043 return node;
5046 /* This function is called for each leaf in the AST of the host code.
5047 * We first specialize the schedule to the site of the leaf, compute
5048 * the size of shared memory and then construct the body of the host code
5049 * and the associated kernel.
5051 * The necessary information for printing the kernel launch is
5052 * stored in a struct ppcg_kernel and attached to the leaf node
5053 * created to represent the launch.
5055 static __isl_give isl_ast_node *create_host_leaf(
5056 __isl_take isl_ast_build *build, void *user)
5058 struct gpu_gen *gen = (struct gpu_gen *) user;
5059 isl_id *id;
5060 isl_ast_node *node;
5061 struct ppcg_kernel *kernel;
5062 isl_set *host_domain;
5063 isl_union_map *schedule;
5064 isl_union_map *local_sched;
5065 isl_union_map *access;
5066 isl_union_set *domain;
5067 int i;
5069 schedule = isl_ast_build_get_schedule(build);
5071 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
5072 read_sizes(gen);
5074 domain = isl_union_map_domain(isl_union_map_copy(schedule));
5076 local_sched = isl_union_map_copy(gen->sched);
5077 local_sched = isl_union_map_intersect_domain(local_sched, domain);
5078 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
5079 isl_union_map_copy(gen->prog->may_write));
5080 access = isl_union_map_apply_domain(access,
5081 isl_union_map_copy(local_sched));
5083 gen->tiled_sched = tile_schedule(gen, local_sched);
5084 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
5085 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
5087 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
5088 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
5089 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
5091 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
5092 if (!kernel)
5093 goto error;
5095 kernel->id = gen->kernel_id++;
5096 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
5097 kernel->grid_size = extract_grid_size(gen, kernel);
5098 extract_block_size(gen, kernel);
5099 kernel->arrays = isl_union_map_range(access);
5100 kernel->arrays = isl_union_set_apply(kernel->arrays,
5101 isl_union_map_copy(gen->prog->to_outer));
5102 kernel->space = isl_ast_build_get_schedule_space(build);
5104 gen->private_access = NULL;
5105 compute_shared_sched(gen);
5106 gen->privatization = compute_privatization(gen);
5107 check_scalar_live_ranges(gen);
5108 if (group_references(gen) < 0)
5109 schedule = isl_union_map_free(schedule);
5110 compute_private_access(gen);
5111 host_domain = isl_set_from_union_set(isl_union_map_range(
5112 isl_union_map_copy(schedule)));
5113 localize_bounds(gen, kernel, host_domain);
5115 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
5116 check_shared_memory_bound(gen);
5117 compute_group_tilings(gen);
5119 kernel->tree = generate_kernel(gen, build, host_domain,
5120 kernel->grid_size);
5121 create_kernel_vars(gen, kernel);
5123 free_local_array_info(gen);
5124 isl_map_free(gen->privatization);
5125 isl_union_map_free(gen->private_access);
5126 isl_union_map_free(gen->local_sched);
5127 isl_union_map_free(gen->tiled_sched);
5128 isl_union_map_free(gen->shared_sched);
5129 isl_union_map_free(gen->shared_proj);
5130 isl_set_free(host_domain);
5131 free(gen->tile_size);
5133 node = construct_launch(build, schedule, kernel);
5135 return node;
5136 error:
5137 isl_union_map_free(schedule);
5138 return NULL;
5141 /* Use isl to generate code for the outer gen->tile_first loops
5142 * of the global schedule in gen->sched, resulting in the host code.
5143 * Within each iteration of this partial schedule, i.e., for each kernel
5144 * launch, create_host_leaf takes care of generating the kernel code.
5146 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
5148 isl_ast_build *build;
5149 isl_ast_node *tree;
5150 isl_union_map *sched;
5151 isl_map *proj;
5152 isl_id_list *iterators;
5154 sched = isl_union_map_copy(gen->sched);
5155 proj = projection(isl_union_map_get_space(sched),
5156 gen->untiled_len, gen->tile_first);
5157 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
5159 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
5160 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
5161 iterators = generate_names(gen->ctx, gen->tile_first, "h");
5162 build = isl_ast_build_set_iterators(build, iterators);
5163 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
5164 tree = isl_ast_build_ast_from_schedule(build, sched);
5165 isl_ast_build_free(build);
5167 return tree;
5170 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
5172 if (!str)
5173 return NULL;
5174 return isl_union_map_read_from_str(ctx, str);
5177 /* Information about the outermost tilable bands in the forest of bands.
5179 * tile_len and n_parallel are only sets on band_info structures
5180 * that correspond to outermost bands. For other bands (in particular,
5181 * ancestors of the outermost bands), n_parallal is set to 0.
5183 * prefix is the (padded) schedule leading up to the outermost tilable bands.
5185 * tile_first is the number of schedule dimensions in prefix.
5187 * suffix is the schedule of the outermost tilable bands and their descendants.
5189 struct band_info {
5190 struct gpu_gen *gen;
5191 int tile_first;
5192 int tile_len;
5193 int n_parallel;
5194 isl_union_map *prefix;
5195 isl_union_map *suffix;
5198 /* Set tile_len and n_parallel of the statement to that of
5199 * their outermost band, recorded in the band_info.
5201 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
5203 struct band_info *info = user;
5204 struct gpu_stmt *stmt;
5205 isl_id *id;
5207 id = isl_map_get_tuple_id(map, isl_dim_in);
5208 stmt = find_stmt(info->gen->prog, id);
5209 isl_id_free(id);
5211 stmt->tile_len = info->tile_len;
5212 stmt->n_parallel = info->n_parallel;
5214 isl_map_free(map);
5216 return 0;
5219 static void list_select_outer_band(struct gpu_gen *gen,
5220 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
5222 /* Check if this band has any parallel loops. If so, take it as
5223 * the outermost tilable band. If not, continue looking for the
5224 * outermost tilable band in the children of the current band.
5226 static void band_select_outer_band(struct gpu_gen *gen,
5227 __isl_take isl_band *band, int pos, struct band_info *info)
5229 int n = isl_band_n_member(band);
5230 int n_parallel;
5232 for (n_parallel = 0; n_parallel < n; ++n_parallel)
5233 if (!isl_band_member_is_coincident(band, n_parallel))
5234 break;
5236 info->n_parallel = n_parallel;
5237 if (n_parallel) {
5238 gen->any_parallelism = 1;
5239 info->gen = gen;
5240 info->tile_first = pos;
5241 info->tile_len = n;
5242 info->prefix = isl_band_get_prefix_schedule(band);
5243 info->suffix = isl_union_map_flat_range_product(
5244 isl_band_get_partial_schedule(band),
5245 isl_band_get_suffix_schedule(band));
5246 isl_union_map_foreach_map(info->prefix,
5247 &set_stmt_tile_len, info);
5248 } else if (isl_band_has_children(band)) {
5249 isl_band_list *children;
5250 children = isl_band_get_children(band);
5251 list_select_outer_band(gen, children, pos + n, info);
5252 } else {
5253 info->gen = gen;
5254 info->tile_first = pos + n;
5255 info->tile_len = 0;
5256 info->prefix = isl_union_map_flat_range_product(
5257 isl_band_get_prefix_schedule(band),
5258 isl_band_get_partial_schedule(band));
5259 info->suffix = isl_band_get_suffix_schedule(band);
5260 isl_union_map_foreach_map(info->prefix,
5261 &set_stmt_tile_len, info);
5264 isl_band_free(band);
5267 /* Comparison function that returns a non-zero value for band_infos
5268 * with different tile_len fields or different n_parallel fields.
5270 static int cmp_band(const void *p1, const void *p2)
5272 const struct band_info *info1 = p1;
5273 const struct band_info *info2 = p2;
5275 if (info1->tile_len != info2->tile_len)
5276 return info1->tile_len - info2->tile_len;
5278 return info1->n_parallel - info2->n_parallel;
5281 /* Extend "umap" with coordinates with fixed value "val"
5282 * to a total length of "dst_len", assuming the original dimension is "src_len".
5284 static __isl_give isl_union_map *extend_range(
5285 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
5287 isl_space *dim;
5288 isl_map *map;
5289 int i;
5291 dim = isl_union_map_get_space(umap);
5292 map = isl_map_reverse(projection(dim, dst_len, src_len));
5293 for (i = src_len; i < dst_len; ++i)
5294 map = isl_map_fix_si(map, isl_dim_out, i, val);
5296 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
5298 return umap;
5301 /* Group bands with the same values for tile_len and n_parallel.
5302 * The prefix schedule is then extended with a fixed coordinate that
5303 * is different for each such group.
5304 * Note that the actual values for this coordinate are not important.
5305 * The bands have already been effectively separated at a higher level
5306 * or they are independent and may be executed in parallel.
5307 * The list of band_info has been sorted before this functions is called.
5309 static void separate_bands(struct band_info *info, int n)
5311 int i;
5312 int j = 0;
5314 for (i = 0; i < n; ++i) {
5315 int l = info[i].tile_first;
5317 if (i &&
5318 (info[i].tile_len != info[i - 1].tile_len ||
5319 info[i].n_parallel != info[i - 1].n_parallel))
5320 j++;
5322 info[i].prefix = extend_range(info[i].prefix,
5323 l, l + 1, j);
5324 info[i].tile_first = l + 1;
5328 /* Select the outermost bands in the elements of the list, align
5329 * their prefix schedules, separate bands with different values
5330 * for tile_len and/or n_parallel and then combine the resulting
5331 * prefix and suffix schedules into a single pair of prefix and
5332 * suffix schedules for the entire list.
5334 static void list_select_outer_band(struct gpu_gen *gen,
5335 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
5337 isl_band *band;
5338 int i;
5339 int n = isl_band_list_n_band(list);
5340 isl_ctx *ctx = isl_band_list_get_ctx(list);
5341 struct band_info *info;
5342 int max_tile_first;
5343 isl_union_map *prefix;
5344 isl_union_map *suffix;
5346 assert(n >= 1);
5347 info = isl_calloc_array(ctx, struct band_info, n);
5348 assert(info);
5350 max_tile_first = 0;
5351 for (i = 0; i < n; ++i) {
5352 band = isl_band_list_get_band(list, i);
5353 band_select_outer_band(gen, band, pos, &info[i]);
5354 if (info[i].tile_first > max_tile_first)
5355 max_tile_first = info[i].tile_first;
5358 for (i = 0; i < n; ++i) {
5359 if (info[i].tile_first == max_tile_first)
5360 continue;
5361 info[i].prefix = extend_range(info[i].prefix,
5362 info[i].tile_first, max_tile_first, 0);
5363 info[i].tile_first = max_tile_first;
5366 qsort(info, n, sizeof(struct band_info), &cmp_band);
5368 for (i = 0; i < n - 1; ++i)
5369 if (info[i].tile_len != info[i + 1].tile_len ||
5370 info[i].n_parallel != info[i + 1].n_parallel)
5371 break;
5373 if (i < n -1)
5374 separate_bands(info, n);
5376 prefix = info[0].prefix;
5377 suffix = info[0].suffix;
5379 for (i = 1; i < n; ++i) {
5380 prefix = isl_union_map_union(prefix, info[i].prefix);
5381 suffix = isl_union_map_union(suffix, info[i].suffix);
5384 list_info->tile_first = info[0].tile_first;
5385 list_info->tile_len = -1;
5386 list_info->prefix = prefix;
5387 list_info->suffix = suffix;
5389 isl_band_list_free(list);
5390 free(info);
5393 /* Select the outermost tilable band that (by construction)
5394 * has at least one parallel loop.
5395 * The starting position of the aligned band is stored in the pair
5396 * gen->tile_first.
5397 * The sizes and number of parallel loops may be different in different
5398 * parts of the band forest and are therefore stored in the gpu_stmts.
5400 * Return the complete schedule, with the tilable bands aligned
5401 * at gen->tile_first and padded with zero, if needed.
5403 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
5404 __isl_keep isl_schedule *schedule)
5406 isl_band_list *list;
5407 struct band_info info;
5409 gen->n_parallel = 0;
5410 gen->tile_len = -1;
5412 list = isl_schedule_get_band_forest(schedule);
5414 if (isl_band_list_n_band(list) == 0) {
5415 isl_band_list_free(list);
5416 return isl_schedule_get_map(schedule);
5419 list_select_outer_band(gen, list, 0, &info);
5421 gen->tile_first = info.tile_first;
5422 info.suffix = align_range(info.suffix);
5424 return isl_union_map_flat_range_product(info.prefix, info.suffix);
5427 /* Set gen->untiled_len to the number of scheduling dimensions
5428 * for the schedule of the first domain.
5429 * We assume here that this number is the same for all domains.
5431 static int set_untiled_len(__isl_take isl_map *map, void *user)
5433 unsigned *untiled_len = user;
5435 *untiled_len = isl_map_dim(map, isl_dim_out);
5437 isl_map_free(map);
5438 return -1;
5441 /* Compute an appropriate schedule based on the accesses in
5442 * gen->read and gen->write.
5444 * We use the dependences in gen->prog->scop to compute
5445 * a schedule that has a parallel loop in each tilable band.
5446 * Finally, we select the outermost tilable band.
5448 * If live range reordering is allowed, then we need to make sure
5449 * that live ranges on arrays are not run in parallel since doing
5450 * so would require array expansion. We therefore add the array
5451 * order dependences to the coincidence dependences. Non-zero array
5452 * order dependences will then prevent a schedule dimension from being
5453 * considered parallel.
5454 * Live ranges derived from scalars are allowed to be run in parallel
5455 * since we force the scalars to be mapped to private memory in
5456 * check_scalar_live_ranges.
5457 * If live range reordering is allowed, then the false dependences
5458 * are not added to the validity constraints as that would prevent
5459 * reordering. Instead, the external false dependences that enforce that reads
5460 * from potentially live-in data precede any later write and
5461 * that writes of potentially live-out data follow any other earlier write
5462 * are added to the validity constraints.
5463 * The false dependences are still added to the proximity constraints
5464 * for consistency with the case where live range reordering is not allowed.
5466 static void compute_schedule(struct gpu_gen *gen)
5468 isl_union_set *domain;
5469 isl_union_map *dep_raw, *dep;
5470 isl_union_map *validity, *proximity, *coincidence;
5471 isl_union_map *sched;
5472 isl_schedule_constraints *sc;
5473 isl_schedule *schedule;
5475 domain = isl_union_set_copy(gen->prog->scop->domain);
5476 domain = isl_union_set_intersect_params(domain,
5477 isl_set_copy(gen->prog->scop->context));
5478 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
5479 if (gen->options->live_range_reordering) {
5480 sc = isl_schedule_constraints_set_conditional_validity(sc,
5481 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
5482 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
5483 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
5484 validity = isl_union_map_copy(proximity);
5485 validity = isl_union_map_union(validity,
5486 isl_union_map_copy(gen->prog->scop->dep_external));
5487 proximity = isl_union_map_union(proximity,
5488 isl_union_map_copy(gen->prog->scop->dep_false));
5489 coincidence = isl_union_map_copy(validity);
5490 coincidence = isl_union_map_union(coincidence,
5491 isl_union_map_copy(gen->prog->array_order));
5492 } else {
5493 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
5494 dep = isl_union_map_copy(gen->prog->scop->dep_false);
5495 dep = isl_union_map_union(dep, dep_raw);
5496 dep = isl_union_map_coalesce(dep);
5497 proximity = isl_union_map_copy(dep);
5498 coincidence = isl_union_map_copy(dep);
5499 validity = dep;
5501 sc = isl_schedule_constraints_set_validity(sc, validity);
5502 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
5503 sc = isl_schedule_constraints_set_proximity(sc, proximity);
5505 if (gen->options->debug->dump_schedule_constraints)
5506 isl_schedule_constraints_dump(sc);
5507 schedule = isl_schedule_constraints_compute_schedule(sc);
5508 if (gen->options->debug->dump_schedule)
5509 isl_schedule_dump(schedule);
5511 sched = select_outer_tilable_band(gen, schedule);
5513 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
5514 sched = isl_union_map_intersect_domain(sched, domain);
5515 gen->sched = sched;
5517 isl_schedule_free(schedule);
5520 /* Compute the sets of outer array elements that need to be copied in and out.
5522 * In particular, for each array that is possibly written anywhere in
5523 * gen->prog and that is visible outside the corresponding scop,
5524 * we copy out its entire extent.
5526 * Any array elements that is read without first being written needs
5527 * to be copied in. Furthermore, if there are any array elements that
5528 * are copied out, but that may not be written inside gen->prog, then
5529 * they also need to be copied in to ensure that the value after execution
5530 * is the same as the value before execution.
5531 * In case the array elements are structures, we need to take into
5532 * account that all members of the structures need to be written
5533 * by gen->prog before we can avoid copying the data structure in.
5535 * While computing the set of array elements that are copied out but
5536 * not necessarily written, we intersect both sets with the context.
5537 * This helps in those cases where the arrays are declared with a fixed size,
5538 * while the accesses are parametric and the context assigns a fixed value
5539 * to the parameters.
5541 * If an element from a local array is read without first being written,
5542 * then there is no point in copying it in since it cannot have been
5543 * written prior to the scop. Warn about the uninitialized read instead.
5545 static void compute_copy_in_and_out(struct gpu_gen *gen)
5547 int i;
5548 isl_union_set *local;
5549 isl_union_set *may_write, *must_write;
5550 isl_union_set *copy_in, *copy_out;
5551 isl_union_set *not_written;
5552 isl_union_map *uninitialized;
5553 isl_union_map *local_uninitialized;
5555 must_write = isl_union_map_range(
5556 isl_union_map_copy(gen->prog->must_write));
5557 must_write = isl_union_set_intersect_params(must_write,
5558 isl_set_copy(gen->prog->context));
5559 may_write = isl_union_map_range(
5560 isl_union_map_copy(gen->prog->may_write));
5561 may_write = isl_union_set_intersect_params(may_write,
5562 isl_set_copy(gen->prog->context));
5563 may_write = isl_union_set_universe(may_write);
5564 may_write = isl_union_set_apply(may_write,
5565 isl_union_map_copy(gen->prog->to_outer));
5566 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
5567 local = isl_union_set_copy(copy_out);
5569 for (i = 0; i < gen->prog->n_array; ++i) {
5570 isl_space *space;
5571 isl_set *write_i;
5572 int empty;
5574 space = isl_space_copy(gen->prog->array[i].space);
5576 if (gen->prog->array[i].local) {
5577 isl_set *set;
5579 set = isl_set_universe(space);
5580 local = isl_union_set_add_set(local, set);
5581 continue;
5584 write_i = isl_union_set_extract_set(may_write, space);
5585 empty = isl_set_fast_is_empty(write_i);
5586 isl_set_free(write_i);
5587 if (empty)
5588 continue;
5590 write_i = isl_set_copy(gen->prog->array[i].extent);
5591 copy_out = isl_union_set_add_set(copy_out, write_i);
5593 isl_union_set_free(may_write);
5595 copy_out = isl_union_set_intersect_params(copy_out,
5596 isl_set_copy(gen->prog->context));
5598 gen->prog->copy_out = isl_union_set_copy(copy_out);
5600 copy_out = isl_union_set_apply(copy_out,
5601 isl_union_map_copy(gen->prog->to_inner));
5602 not_written = isl_union_set_subtract(copy_out, must_write);
5604 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
5605 local_uninitialized = isl_union_map_copy(uninitialized);
5607 local = isl_union_set_apply(local,
5608 isl_union_map_copy(gen->prog->to_inner));
5609 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5610 local);
5611 if (!isl_union_map_is_empty(local_uninitialized)) {
5612 fprintf(stderr,
5613 "possibly uninitialized reads (not copied in):\n");
5614 isl_union_map_dump(local_uninitialized);
5616 uninitialized = isl_union_map_subtract(uninitialized,
5617 local_uninitialized);
5618 copy_in = isl_union_map_range(uninitialized);
5619 copy_in = isl_union_set_union(copy_in, not_written);
5620 copy_in = isl_union_set_apply(copy_in,
5621 isl_union_map_copy(gen->prog->to_outer));
5623 gen->prog->copy_in = copy_in;
5626 /* Extract a gpu_stmt_access from "expr", append it to the list
5627 * that ends in *next_access and return the updated end of the list.
5629 static struct gpu_stmt_access **expr_extract_access(struct pet_expr *expr,
5630 struct gpu_stmt_access **next_access)
5632 struct gpu_stmt_access *access;
5633 isl_ctx *ctx = isl_map_get_ctx(expr->acc.access);
5635 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5636 assert(access);
5637 access->next = NULL;
5638 access->read = expr->acc.read;
5639 access->write = expr->acc.write;
5640 access->access = pet_expr_access_get_may_access(expr);
5641 access->tagged_access = pet_expr_access_get_tagged_may_access(expr);
5642 access->exact_write = !expr->acc.write ||
5643 isl_map_is_equal(expr->acc.access, access->access);
5644 access->ref_id = isl_id_copy(expr->acc.ref_id);
5645 access->group = -1;
5647 *next_access = access;
5648 next_access = &(*next_access)->next;
5649 return next_access;
5652 static struct gpu_stmt_access **expr_extract_accesses(struct pet_expr *expr,
5653 struct gpu_stmt_access **next_access)
5655 int i;
5657 for (i = 0; i < expr->n_arg; ++i)
5658 next_access = expr_extract_accesses(expr->args[i],
5659 next_access);
5661 if (expr->type == pet_expr_access)
5662 next_access = expr_extract_access(expr, next_access);
5664 return next_access;
5667 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
5669 struct gpu_stmt_access **next_access = &stmt->accesses;
5671 stmt->accesses = NULL;
5672 expr_extract_accesses(stmt->stmt->body, next_access);
5675 /* Return an array of gpu_stmt representing the statements in "scop".
5677 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5678 __isl_keep isl_set *context)
5680 int i;
5681 struct gpu_stmt *stmts;
5683 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
5684 if (!stmts)
5685 return NULL;
5687 for (i = 0; i < scop->n_stmt; ++i) {
5688 struct gpu_stmt *s = &stmts[i];
5690 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
5691 s->stmt = scop->stmts[i];
5692 pet_stmt_extract_accesses(s);
5695 return stmts;
5698 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5700 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5702 struct gpu_gen *gen = user;
5704 return gen->print(p, gen->prog, gen->tree, &gen->types,
5705 gen->print_user);
5708 /* Generate CUDA code for "scop" and print it to "p".
5709 * After generating an AST for the transformed scop as explained below,
5710 * we call "gen->print" to print the AST in the desired output format
5711 * to "p".
5713 * If it turns out that it does not make sense to generate GPU code,
5714 * then we generate CPU code instead.
5716 * The GPU code is generated in a context where at least one
5717 * statement instance is executed. The corresponding guard (if any) is printed
5718 * around the entire generated GPU code, except for the declaration
5719 * of the arrays that are visible outside of the scop and that therefore
5720 * cannot be declared inside the body of any possible guard.
5722 * We first compute a schedule that respects the dependences
5723 * of the original program and select the outermost band
5724 * of tilable dimensions that has at least one parallel loop.
5725 * We then have three blocks of dimensions
5727 * H B G
5729 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5730 * in
5732 * H T P G
5734 * For each iteration of the T loop and for each array, we compute
5735 * the array elements accessed by that iteration, construct a rectangular
5736 * box around it and shift it to the origin. The result is used
5737 * as shared memory for the array.
5739 * We then split off at most 2 parallel loops from the T loops and
5740 * at most 3 parallel loops from the P loops
5742 * H T1 T2 P1 P2 G
5744 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5745 * according to "grid"/"block" sizes.
5747 * H T1T T1P T2 P1T P1P P2 G
5749 * Finally, the T1P and P1P iterators are equated to the block and
5750 * thread dimensions respectively and so are effectively removed.
5751 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5752 * are run on the GPU.
5754 * Code is generated in three stages. We first generate code for the
5755 * host (the H loops), with iterators h%d. Then, for each leaf node
5756 * of the resulting AST, we generate code for the shared loops (up to
5757 * and including T2), with iterators g%d and after equating the H loops
5758 * to h%d parameters and the T1P loops to the block dimensions.
5759 * Finally, we generate code for the remaining loops in a similar fashion.
5761 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5762 struct gpu_gen *gen, struct ppcg_scop *scop,
5763 struct ppcg_options *options)
5765 struct gpu_prog *prog;
5766 isl_ctx *ctx;
5767 isl_set *context, *guard;
5769 if (!scop)
5770 return isl_printer_free(p);
5772 ctx = isl_printer_get_ctx(p);
5773 prog = gpu_prog_alloc(ctx, scop);
5774 if (!prog)
5775 return isl_printer_free(p);
5777 context = isl_set_copy(prog->context);
5778 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5779 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5781 gen->prog = prog;
5782 gen->any_parallelism = 0;
5783 compute_schedule(gen);
5785 if (!gen->any_parallelism) {
5786 isl_set_free(context);
5787 isl_set_free(guard);
5788 p = print_cpu(p, scop, options);
5789 } else {
5790 compute_copy_in_and_out(gen);
5791 gen->tree = generate_host_code(gen);
5792 p = ppcg_print_exposed_declarations(p, prog->scop);
5793 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5794 isl_ast_node_free(gen->tree);
5797 isl_union_map_free(gen->sched);
5799 gpu_prog_free(prog);
5801 return p;
5804 /* Wrapper around generate for use as a ppcg_transform callback.
5806 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5807 struct ppcg_scop *scop, void *user)
5809 struct gpu_gen *gen = user;
5811 return generate(p, gen, scop, gen->options);
5814 /* Transform the code in the file called "input" by replacing
5815 * all scops by corresponding GPU code and write the results to "out".
5817 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5818 struct ppcg_options *options,
5819 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5820 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5821 struct gpu_types *types, void *user), void *user)
5823 struct gpu_gen gen;
5824 int r;
5825 int i;
5827 gen.ctx = ctx;
5828 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5829 gen.options = options;
5830 gen.kernel_id = 0;
5831 gen.print = print;
5832 gen.print_user = user;
5833 gen.types.n = 0;
5834 gen.types.name = NULL;
5836 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5838 isl_union_map_free(gen.sizes);
5839 for (i = 0; i < gen.types.n; ++i)
5840 free(gen.types.name[i]);
5841 free(gen.types.name);
5843 return r;
5846 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5848 struct gpu_prog *prog;
5850 if (!scop)
5851 return NULL;
5853 prog = isl_calloc_type(ctx, struct gpu_prog);
5854 assert(prog);
5856 prog->ctx = ctx;
5857 prog->scop = scop;
5858 prog->context = isl_set_copy(scop->context);
5859 prog->n_stmts = scop->n_stmt;
5860 prog->stmts = extract_stmts(ctx, scop, prog->context);
5861 prog->read = isl_union_map_copy(scop->reads);
5862 prog->may_write = isl_union_map_copy(scop->may_writes);
5863 prog->must_write = isl_union_map_copy(scop->must_writes);
5864 prog->to_inner = compute_to_inner(scop);
5865 prog->to_outer = isl_union_map_copy(prog->to_inner);
5866 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5868 if (!prog->stmts)
5869 return gpu_prog_free(prog);
5871 if (collect_array_info(prog) < 0)
5872 return gpu_prog_free(prog);
5874 return prog;
5877 void *gpu_prog_free(struct gpu_prog *prog)
5879 if (!prog)
5880 return NULL;
5881 free_array_info(prog);
5882 free_stmts(prog->stmts, prog->n_stmts);
5883 isl_union_map_free(prog->to_outer);
5884 isl_union_map_free(prog->to_inner);
5885 isl_union_set_free(prog->copy_in);
5886 isl_union_set_free(prog->copy_out);
5887 isl_union_map_free(prog->read);
5888 isl_union_map_free(prog->may_write);
5889 isl_union_map_free(prog->must_write);
5890 isl_union_map_free(prog->array_order);
5891 isl_set_free(prog->context);
5892 free(prog);
5893 return NULL;