Bug Summary

File:tools/polly/lib/External/ppcg/gpu.c
Warning:line 5022, column 2
Value stored to 'space2' is never read

Annotated Source Code

1/*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012-2013 Ecole Normale Superieure
4 *
5 * Use of this software is governed by the MIT license
6 *
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
11 */
12
13#include <assert.h>
14#include <stdlib.h>
15#include <string.h>
16
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/schedule.h>
23#include <isl/schedule_node.h>
24#include <isl/options.h>
25#include <isl/ast_build.h>
26
27#include "cpu.h"
28#include "gpu.h"
29#include "gpu_array_tile.h"
30#include "gpu_group.h"
31#include "gpu_tree.h"
32#include "schedule.h"
33#include "ppcg_options.h"
34#include "print.h"
35#include "util.h"
36
37struct gpu_array_info;
38
39/* Return the name of the outer array (of structs) accessed by "access".
40 */
41static const char *get_outer_array_name(__isl_keep isl_map *access)
42{
43 isl_space *space;
44 const char *name;
45
46 space = isl_space_range(isl_map_get_space(access));
47 while (space && isl_space_is_wrapping(space))
48 space = isl_space_domain(isl_space_unwrap(space));
49 name = isl_space_get_tuple_name(space, isl_dim_set);
50 isl_space_free(space);
51
52 return name;
53}
54
55/* Collect all references to the given array and store pointers to them
56 * in array->refs.
57 */
58void collect_references(struct gpu_prog *prog,
59 struct gpu_array_info *array)
60{
61 int i;
62 int n;
63
64 n = 0;
65 for (i = 0; i < prog->n_stmts; ++i) {
66 struct gpu_stmt *stmt = &prog->stmts[i];
67 struct gpu_stmt_access *access;
68
69 for (access = stmt->accesses; access; access = access->next) {
70 const char *name;
71 name = get_outer_array_name(access->access);
72 if (name && !strcmp(array->name, name)__extension__ ({ size_t __s1_len, __s2_len; (__builtin_constant_p
(array->name) && __builtin_constant_p (name) &&
(__s1_len = __builtin_strlen (array->name), __s2_len = __builtin_strlen
(name), (!((size_t)(const void *)((array->name) + 1) - (size_t
)(const void *)(array->name) == 1) || __s1_len >= 4) &&
(!((size_t)(const void *)((name) + 1) - (size_t)(const void *
)(name) == 1) || __s2_len >= 4)) ? __builtin_strcmp (array
->name, name) : (__builtin_constant_p (array->name) &&
((size_t)(const void *)((array->name) + 1) - (size_t)(const
void *)(array->name) == 1) && (__s1_len = __builtin_strlen
(array->name), __s1_len < 4) ? (__builtin_constant_p (
name) && ((size_t)(const void *)((name) + 1) - (size_t
)(const void *)(name) == 1) ? __builtin_strcmp (array->name
, name) : (__extension__ ({ const unsigned char *__s2 = (const
unsigned char *) (const char *) (name); int __result = (((const
unsigned char *) (const char *) (array->name))[0] - __s2[
0]); if (__s1_len > 0 && __result == 0) { __result
= (((const unsigned char *) (const char *) (array->name))
[1] - __s2[1]); if (__s1_len > 1 && __result == 0)
{ __result = (((const unsigned char *) (const char *) (array
->name))[2] - __s2[2]); if (__s1_len > 2 && __result
== 0) __result = (((const unsigned char *) (const char *) (array
->name))[3] - __s2[3]); } } __result; }))) : (__builtin_constant_p
(name) && ((size_t)(const void *)((name) + 1) - (size_t
)(const void *)(name) == 1) && (__s2_len = __builtin_strlen
(name), __s2_len < 4) ? (__builtin_constant_p (array->
name) && ((size_t)(const void *)((array->name) + 1
) - (size_t)(const void *)(array->name) == 1) ? __builtin_strcmp
(array->name, name) : -(__extension__ ({ const unsigned char
*__s2 = (const unsigned char *) (const char *) (array->name
); int __result = (((const unsigned char *) (const char *) (name
))[0] - __s2[0]); if (__s2_len > 0 && __result == 0
) { __result = (((const unsigned char *) (const char *) (name
))[1] - __s2[1]); if (__s2_len > 1 && __result == 0
) { __result = (((const unsigned char *) (const char *) (name
))[2] - __s2[2]); if (__s2_len > 2 && __result == 0
) __result = (((const unsigned char *) (const char *) (name))
[3] - __s2[3]); } } __result; }))) : __builtin_strcmp (array->
name, name)))); })
)
73 n++;
74 }
75 }
76
77 array->n_ref = n;
78 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n)((struct gpu_stmt_access * *)isl_malloc_or_die(prog->ctx, (
n)*sizeof(struct gpu_stmt_access *)))
;
79 assert(array->refs)((array->refs) ? (void) (0) : __assert_fail ("array->refs"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/polly/lib/External/ppcg/gpu.c"
, 79, __PRETTY_FUNCTION__))
;
80
81 n = 0;
82 for (i = 0; i < prog->n_stmts; ++i) {
83 struct gpu_stmt *stmt = &prog->stmts[i];
84 struct gpu_stmt_access *access;
85
86 for (access = stmt->accesses; access; access = access->next) {
87 const char *name;
88 name = get_outer_array_name(access->access);
89 if (!name || strcmp(array->name, name)__extension__ ({ size_t __s1_len, __s2_len; (__builtin_constant_p
(array->name) && __builtin_constant_p (name) &&
(__s1_len = __builtin_strlen (array->name), __s2_len = __builtin_strlen
(name), (!((size_t)(const void *)((array->name) + 1) - (size_t
)(const void *)(array->name) == 1) || __s1_len >= 4) &&
(!((size_t)(const void *)((name) + 1) - (size_t)(const void *
)(name) == 1) || __s2_len >= 4)) ? __builtin_strcmp (array
->name, name) : (__builtin_constant_p (array->name) &&
((size_t)(const void *)((array->name) + 1) - (size_t)(const
void *)(array->name) == 1) && (__s1_len = __builtin_strlen
(array->name), __s1_len < 4) ? (__builtin_constant_p (
name) && ((size_t)(const void *)((name) + 1) - (size_t
)(const void *)(name) == 1) ? __builtin_strcmp (array->name
, name) : (__extension__ ({ const unsigned char *__s2 = (const
unsigned char *) (const char *) (name); int __result = (((const
unsigned char *) (const char *) (array->name))[0] - __s2[
0]); if (__s1_len > 0 && __result == 0) { __result
= (((const unsigned char *) (const char *) (array->name))
[1] - __s2[1]); if (__s1_len > 1 && __result == 0)
{ __result = (((const unsigned char *) (const char *) (array
->name))[2] - __s2[2]); if (__s1_len > 2 && __result
== 0) __result = (((const unsigned char *) (const char *) (array
->name))[3] - __s2[3]); } } __result; }))) : (__builtin_constant_p
(name) && ((size_t)(const void *)((name) + 1) - (size_t
)(const void *)(name) == 1) && (__s2_len = __builtin_strlen
(name), __s2_len < 4) ? (__builtin_constant_p (array->
name) && ((size_t)(const void *)((array->name) + 1
) - (size_t)(const void *)(array->name) == 1) ? __builtin_strcmp
(array->name, name) : -(__extension__ ({ const unsigned char
*__s2 = (const unsigned char *) (const char *) (array->name
); int __result = (((const unsigned char *) (const char *) (name
))[0] - __s2[0]); if (__s2_len > 0 && __result == 0
) { __result = (((const unsigned char *) (const char *) (name
))[1] - __s2[1]); if (__s2_len > 1 && __result == 0
) { __result = (((const unsigned char *) (const char *) (name
))[2] - __s2[2]); if (__s2_len > 2 && __result == 0
) __result = (((const unsigned char *) (const char *) (name))
[3] - __s2[3]); } } __result; }))) : __builtin_strcmp (array->
name, name)))); })
)
90 continue;
91
92 array->refs[n++] = access;
93 }
94 }
95}
96
97/* Compute and return the extent of "array", taking into account the set of
98 * accessed elements.
99 *
100 * In particular, the extent in the outer dimension is taken
101 * from "accessed", while the extents in the remaining dimensions
102 * are taken from array->extent.
103 *
104 * The extent in the outer dimension cannot be taken from array->extent
105 * because that may be unbounded. Furthermore, even if it is bounded,
106 * it may be larger than the piece of the array that is being accessed.
107 */
108static __isl_give isl_set *compute_extent(struct pet_array *array,
109 __isl_keep isl_set *accessed)
110{
111 int n_index;
112 isl_id *id;
113 isl_set *outer;
114 isl_set *extent;
115
116 extent = isl_set_copy(array->extent);
117
118 n_index = isl_set_dim(accessed, isl_dim_set);
119 if (n_index == 0)
120 return extent;
121
122 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
123 outer = isl_set_copy(accessed);
124 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
125 extent = isl_set_flat_product(outer, extent);
126 id = isl_set_get_tuple_id(accessed);
127 extent = isl_set_set_tuple_id(extent, id);
128
129 return extent;
130}
131
132/* Is the array "array" being extracted a read-only scalar?
133 *
134 * That is, is "array" a scalar that is never possibly written to.
135 * An array containing structures is never considered to be a scalar.
136 */
137static int is_read_only_scalar(struct gpu_array_info *array,
138 struct gpu_prog *prog)
139{
140 isl_set *space;
141 isl_union_map *write;
142 int empty;
143
144 if (array->has_compound_element)
145 return 0;
146 if (array->n_index != 0)
147 return 0;
148
149 write = isl_union_map_copy(prog->may_write);
150 space = isl_set_universe(isl_space_copy(array->space));
151 write = isl_union_map_intersect_range(write,
152 isl_union_set_from_set(space));
153 empty = isl_union_map_is_empty(write);
154 isl_union_map_free(write);
155
156 return empty;
157}
158
159/* Compute bounds on the host array "pa" based on the corresponding
160 * accessed elements in "arrays"
161 * and collect all references to the array.
162 * Store the results in "info".
163 *
164 * If the array is zero-dimensional and does not contain structures,
165 * i.e., if the array is a scalar, we check whether it is read-only.
166 * We also check whether the array is accessed at all.
167 */
168static int extract_array_info(struct gpu_prog *prog,
169 struct gpu_array_info *info, struct pet_array *pa,
170 __isl_keep isl_union_set *arrays)
171{
172 int i, empty;
173 const char *name;
174 int n_index;
175 isl_pw_aff **bounds;
176 isl_set *accessed, *extent;
177
178 n_index = isl_set_dim(pa->extent, isl_dim_set);
179 name = isl_set_get_tuple_name(pa->extent);
180 bounds = isl_alloc_array(prog->ctx, isl_pw_aff *, n_index)((isl_pw_aff * *)isl_malloc_or_die(prog->ctx, (n_index)*sizeof
(isl_pw_aff *)))
;
181 if (!bounds)
182 return -1;
183
184 info->space = isl_set_get_space(pa->extent);
185 info->name = strdup(name)(__extension__ (__builtin_constant_p (name) && ((size_t
)(const void *)((name) + 1) - (size_t)(const void *)(name) ==
1) ? (((const char *) (name))[0] == '\0' ? (char *) calloc (
(size_t) 1, (size_t) 1) : ({ size_t __len = strlen (name) + 1
; char *__retval = (char *) malloc (__len); if (__retval != (
(void*)0)) __retval = (char *) memcpy (__retval, name, __len)
; __retval; })) : __strdup (name)))
;
186 info->n_index = n_index;
187 info->bound = bounds;
188 info->linearize = prog->scop->options->linearize_device_arrays;
189
190 info->type = strdup(pa->element_type)(__extension__ (__builtin_constant_p (pa->element_type) &&
((size_t)(const void *)((pa->element_type) + 1) - (size_t
)(const void *)(pa->element_type) == 1) ? (((const char *)
(pa->element_type))[0] == '\0' ? (char *) calloc ((size_t
) 1, (size_t) 1) : ({ size_t __len = strlen (pa->element_type
) + 1; char *__retval = (char *) malloc (__len); if (__retval
!= ((void*)0)) __retval = (char *) memcpy (__retval, pa->
element_type, __len); __retval; })) : __strdup (pa->element_type
)))
;
191 info->size = pa->element_size;
192 info->local = pa->declared && !pa->exposed;
193 info->has_compound_element = pa->element_is_record;
194 info->read_only_scalar = is_read_only_scalar(info, prog);
195
196 accessed = isl_union_set_extract_set(arrays,
197 isl_space_copy(info->space));
198 empty = isl_set_is_empty(accessed);
199 extent = compute_extent(pa, accessed);
200 isl_set_free(accessed);
201 info->extent = extent;
202 if (empty < 0)
203 return -1;
204 info->accessed = !empty;
205 for (i = 0; i < n_index; ++i) {
206 isl_set *dom;
207 isl_local_space *ls;
208 isl_aff *one;
209 isl_pw_aff *bound;
210
211 dom = isl_set_copy(extent);
212 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
213 n_index - (i + 1));
214 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
215 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
216 fprintf(stderrstderr, "unable to determine extent of '%s' "
217 "in dimension %d\n", info->name, i);
218 dom = isl_set_free(dom);
219 }
220 bound = isl_set_dim_max(dom, 0);
221 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
222 ls = isl_local_space_from_space(isl_set_get_space(dom));
223 one = isl_aff_zero_on_domain(ls);
224 one = isl_aff_add_constant_si(one, 1);
225 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
226 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
227
228 bounds[i] = bound;
229 if (!isl_pw_aff_is_cst(bound))
230 info->linearize = 1;
231 }
232
233 collect_references(prog, info);
234
235 return 0;
236}
237
238/* Remove independence from the order constraints "order" on array "array".
239 * Since the pairs of iterations in the filter relation of an independence
240 * are guaranteed to be completely independent by the user, there is
241 * no need to ensure that live ranges are ordered along thong pairs.
242 * We make an exception for local variables, though, as the independence
243 * guarantee does not apply to those.
244 *
245 * The order constraints are used in two places.
246 * Those on scalars are used in check_scalar_live_ranges to check if
247 * we need to force the scalar to be private. Any non-local scalar
248 * should not be forced scalar if it only appears in independent loops.
249 * Those on non-scalars are added to the coincidence constraints
250 * in compute_schedule because we do not support any array expansion.
251 * Accesses to non-local arrays should not prevent a loop from being
252 * considered coincident so we should indeed remove those constraints
253 * from the order constraints.
254 */
255static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
256 struct gpu_array_info *array, __isl_take isl_union_map *order)
257{
258 int i;
259
260 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
261 struct pet_independence *pi = prog->scop->pet->independences[i];
262 if (isl_union_set_contains(pi->local, array->space))
263 continue;
264
265 order = isl_union_map_subtract(order,
266 isl_union_map_copy(pi->filter));
267 }
268
269 return order;
270}
271
272/* For each array in "prog", store the (untagged) order dependences
273 * derived from the array in array->dep_order.
274 * In particular, consider all references that access the given array
275 * and take the order dependences that have one of these references
276 * as source. (Since an order dependence relates two references to
277 * the same array, the target of these order dependences will also
278 * be one of these references.)
279 * Additionally, store the union of these array->dep_order relations
280 * for all non-scalar arrays in prog->array_order.
281 */
282void collect_order_dependences(struct gpu_prog *prog)
283{
284 int i;
285 isl_space *space;
286 isl_union_map *accesses;
287
288 space = isl_union_map_get_space(prog->read);
289 prog->array_order = isl_union_map_empty(space);
290
291 accesses = isl_union_map_copy(prog->scop->tagged_reads);
292 accesses = isl_union_map_union(accesses,
293 isl_union_map_copy(prog->scop->tagged_may_writes));
294 accesses = isl_union_map_universe(accesses);
295 accesses = isl_union_map_apply_range(accesses,
296 isl_union_map_copy(prog->to_outer));
297
298 for (i = 0; i < prog->n_array; ++i) {
299 struct gpu_array_info *array = &prog->array[i];
300 isl_set *set;
301 isl_union_set *uset;
302 isl_union_map *order;
303
304 set = isl_set_universe(isl_space_copy(array->space));
305 uset = isl_union_set_from_set(set);
306 uset = isl_union_map_domain(
307 isl_union_map_intersect_range(isl_union_map_copy(accesses),
308 uset));
309 order = isl_union_map_copy(prog->scop->tagged_dep_order);
310 order = isl_union_map_intersect_domain(order, uset);
311 order = isl_union_map_zip(order);
312 order = isl_union_set_unwrap(isl_union_map_domain(order));
313 order = remove_independences(prog, array, order);
314 array->dep_order = order;
315
316 if (gpu_array_is_scalar(array) && !array->has_compound_element)
317 continue;
318
319 prog->array_order = isl_union_map_union(prog->array_order,
320 isl_union_map_copy(array->dep_order));
321 }
322
323 isl_union_map_free(accesses);
324}
325
326/* Construct a gpu_array_info for each array referenced by prog->scop and
327 * collect them in prog->array.
328 *
329 * The sizes are based on the extents and the set of possibly accessed
330 * elements by "prog".
331 * If there are any member accesses involved, then they are first mapped
332 * to the outer arrays of structs.
333 *
334 * If we are allowing live range reordering, then also set
335 * the dep_order field. Otherwise leave it NULL.
336 */
337static int collect_array_info(struct gpu_prog *prog)
338{
339 int i;
340 int r = 0;
341 isl_union_set *arrays;
342
343 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
344 arrays = isl_union_set_union(arrays,
345 isl_union_map_range(isl_union_map_copy(prog->may_write)));
346
347 arrays = isl_union_set_apply(arrays,
348 isl_union_map_copy(prog->to_outer));
349
350 arrays = isl_union_set_coalesce(arrays);
351
352 prog->n_array = prog->scop->pet->n_array;
353 prog->array = isl_calloc_array(prog->ctx,((struct gpu_array_info *)isl_calloc_or_die(prog->ctx, prog
->n_array, sizeof(struct gpu_array_info)))
354 struct gpu_array_info, prog->n_array)((struct gpu_array_info *)isl_calloc_or_die(prog->ctx, prog
->n_array, sizeof(struct gpu_array_info)))
;
355 assert(prog->array)((prog->array) ? (void) (0) : __assert_fail ("prog->array"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/polly/lib/External/ppcg/gpu.c"
, 355, __PRETTY_FUNCTION__))
;
356 for (i = 0; i < prog->scop->pet->n_array; ++i)
357 if (extract_array_info(prog, &prog->array[i],
358 prog->scop->pet->arrays[i], arrays) < 0)
359 r = -1;
360
361 isl_union_set_free(arrays);
362
363 if (prog->scop->options->live_range_reordering)
364 collect_order_dependences(prog);
365
366 return r;
367}
368
369static void free_array_info(struct gpu_prog *prog)
370{
371 int i, j;
372
373 for (i = 0; i < prog->n_array; ++i) {
374 int n_index = prog->array[i].n_index;
375 free(prog->array[i].type);
376 free(prog->array[i].name);
377 for (j = 0; j < n_index; ++j)
378 isl_pw_aff_free(prog->array[i].bound[j]);
379 isl_space_free(prog->array[i].space);
380 isl_set_free(prog->array[i].extent);
381 free(prog->array[i].bound);
382 free(prog->array[i].refs);
383 isl_union_map_free(prog->array[i].dep_order);
384 }
385 free(prog->array);
386}
387
388/* Check if a gpu array is a scalar. A scalar is a value that is not stored
389 * as an array or through a pointer reference, but as a single data element.
390 * At the moment, scalars are represented as zero-dimensional arrays.
391 * Note that the single data element may be an entire structure.
392 */
393int gpu_array_is_scalar(struct gpu_array_info *array)
394{
395 return array->n_index == 0;
396}
397
398/* Is "array" a read-only scalar?
399 */
400int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
401{
402 return array->read_only_scalar;
403}
404
405/* Does "array" need to be allocated on the device?
406 * If it is a read-only scalar, then it will be passed as an argument
407 * to the kernel and therefore does not require any allocation.
408 * If this device memory is not accessed at all, then it does not
409 * need to be allocated either.
410 */
411int gpu_array_requires_device_allocation(struct gpu_array_info *array)
412{
413 if (gpu_array_is_read_only_scalar(array))
414 return 0;
415 if (!array->global)
416 return 0;
417 return 1;
418}
419
420/* Return the set of parameter values for which the array has a positive
421 * size in all dimensions.
422 * If the sizes are only valid for some parameter values, then those
423 * constraints are also taken into account.
424 */
425__isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
426{
427 int i;
428 isl_space *space;
429 isl_set *guard;
430
431 if (!array)
432 return NULL((void*)0);
433
434 space = isl_space_params(isl_space_copy(array->space));
435 guard = isl_set_universe(space);
436
437 for (i = 0; i < array->n_index; ++i) {
438 isl_pw_aff *bound;
439 isl_set *guard_i, *zero;
440
441 bound = isl_pw_aff_copy(array->bound[i]);
442 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
443 zero = isl_pw_aff_zero_set(bound);
444 guard_i = isl_set_subtract(guard_i, zero);
445 guard = isl_set_intersect(guard, guard_i);
446 }
447
448 return guard;
449}
450
451/* Internal data structure for extract_size_of_type.
452 * "type" specifies the name of the space that we want to extract.
453 * "res" is used to store the subset of that space.
454 */
455struct ppcg_extract_size_data {
456 const char *type;
457 isl_set *res;
458};
459
460/* This function is called for each set in a union_set.
461 * If the name of the set matches data->type, we store the
462 * set in data->res.
463 */
464static isl_stat extract_size_of_type(__isl_take isl_set *size, void *user)
465{
466 struct ppcg_extract_size_data *data = user;
467 const char *name;
468
469 name = isl_set_get_tuple_name(size);
470 if (name && !strcmp(name, data->type)__extension__ ({ size_t __s1_len, __s2_len; (__builtin_constant_p
(name) && __builtin_constant_p (data->type) &&
(__s1_len = __builtin_strlen (name), __s2_len = __builtin_strlen
(data->type), (!((size_t)(const void *)((name) + 1) - (size_t
)(const void *)(name) == 1) || __s1_len >= 4) && (
!((size_t)(const void *)((data->type) + 1) - (size_t)(const
void *)(data->type) == 1) || __s2_len >= 4)) ? __builtin_strcmp
(name, data->type) : (__builtin_constant_p (name) &&
((size_t)(const void *)((name) + 1) - (size_t)(const void *)
(name) == 1) && (__s1_len = __builtin_strlen (name), __s1_len
< 4) ? (__builtin_constant_p (data->type) && (
(size_t)(const void *)((data->type) + 1) - (size_t)(const void
*)(data->type) == 1) ? __builtin_strcmp (name, data->type
) : (__extension__ ({ const unsigned char *__s2 = (const unsigned
char *) (const char *) (data->type); int __result = (((const
unsigned char *) (const char *) (name))[0] - __s2[0]); if (__s1_len
> 0 && __result == 0) { __result = (((const unsigned
char *) (const char *) (name))[1] - __s2[1]); if (__s1_len >
1 && __result == 0) { __result = (((const unsigned char
*) (const char *) (name))[2] - __s2[2]); if (__s1_len > 2
&& __result == 0) __result = (((const unsigned char *
) (const char *) (name))[3] - __s2[3]); } } __result; }))) : (
__builtin_constant_p (data->type) && ((size_t)(const
void *)((data->type) + 1) - (size_t)(const void *)(data->
type) == 1) && (__s2_len = __builtin_strlen (data->
type), __s2_len < 4) ? (__builtin_constant_p (name) &&
((size_t)(const void *)((name) + 1) - (size_t)(const void *)
(name) == 1) ? __builtin_strcmp (name, data->type) : -(__extension__
({ const unsigned char *__s2 = (const unsigned char *) (const
char *) (name); int __result = (((const unsigned char *) (const
char *) (data->type))[0] - __s2[0]); if (__s2_len > 0 &&
__result == 0) { __result = (((const unsigned char *) (const
char *) (data->type))[1] - __s2[1]); if (__s2_len > 1 &&
__result == 0) { __result = (((const unsigned char *) (const
char *) (data->type))[2] - __s2[2]); if (__s2_len > 2 &&
__result == 0) __result = (((const unsigned char *) (const char
*) (data->type))[3] - __s2[3]); } } __result; }))) : __builtin_strcmp
(name, data->type)))); })
) {
471 data->res = size;
472 return isl_stat_error;
473 }
474
475 isl_set_free(size);
476 return isl_stat_ok;
477}
478
479/* Given a union map { kernel[i] -> *[...] },
480 * return the range in the space called "type" for the kernel with
481 * sequence number "id".
482 */
483static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
484 const char *type, int id)
485{
486 isl_space *space;
487 isl_set *dom;
488 isl_union_set *local_sizes;
489 struct ppcg_extract_size_data data = { type, NULL((void*)0) };
490
491 if (!sizes)
492 return NULL((void*)0);
493
494 space = isl_union_map_get_space(sizes);
495 space = isl_space_set_from_params(space);
496 space = isl_space_add_dims(space, isl_dim_set, 1);
497 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
498 dom = isl_set_universe(space);
499 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
500
501 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
502 isl_union_map_copy(sizes));
503 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
504 isl_union_set_free(local_sizes);
505 return data.res;
506}
507
508/* Given a singleton set, extract the first (at most *len) elements
509 * of the single integer tuple into *sizes and update *len if needed.
510 */
511static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
512{
513 int i;
514 int dim;
515
516 if (!set)
517 return;
518
519 dim = isl_set_dim(set, isl_dim_set);
520 if (dim < *len)
521 *len = dim;
522
523 for (i = 0; i < *len; ++i) {
524 isl_val *v;
525
526 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
527 assert(v)((v) ? (void) (0) : __assert_fail ("v", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/polly/lib/External/ppcg/gpu.c"
, 527, __PRETTY_FUNCTION__))
;
528
529 sizes[i] = isl_val_get_num_si(v);
530 isl_val_free(v);
531 }
532
533 isl_set_free(set);
534}
535
536/* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
537 * if the option debug->dump_sizes is set.
538 */
539static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
540 int *sizes, int len)
541{
542 int i;
543 isl_space *space;
544 isl_map *map;
545
546 if (!gen->options->debug->dump_sizes)
547 return;
548
549 space = isl_union_map_get_space(gen->used_sizes);
550 space = isl_space_set_from_params(space);
551 space = isl_space_add_dims(space, isl_dim_set, 1);
552 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
553 space = isl_space_from_domain(space);
554 space = isl_space_add_dims(space, isl_dim_out, len);
555 space = isl_space_set_tuple_name(space, isl_dim_out, type);
556
557 map = isl_map_universe(space);
558 map = isl_map_fix_si(map, isl_dim_in, 0, id);
559 for (i = 0; i < len; ++i)
560 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
561
562 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
563}
564
565/* Extract user specified "tile" sizes from the "sizes" command line option,
566 * defaulting to option->tile_size in each dimension.
567 * *tile_len contains the maximum number of tile sizes needed.
568 * Update *tile_len to the number of specified tile sizes, if any, and
569 * return a pointer to the tile sizes (or NULL on error).
570 * Add the effectively used sizes to gen->used_sizes.
571 */
572static int *read_tile_sizes(struct gpu_gen *gen, int *tile_len)
573{
574 int n;
575 int *tile_size;
576 isl_set *size;
577
578 tile_size = isl_alloc_array(gen->ctx, int, *tile_len)((int *)isl_malloc_or_die(gen->ctx, (*tile_len)*sizeof(int
)))
;
579 if (!tile_size)
580 return NULL((void*)0);
581 for (n = 0; n < *tile_len; ++n)
582 tile_size[n] = gen->options->tile_size;
583
584 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
585 read_sizes_from_set(size, tile_size, tile_len);
586 set_used_sizes(gen, "tile", gen->kernel_id, tile_size, *tile_len);
587
588 return tile_size;
589}
590
591/* Extract user specified "block" sizes from the "sizes" command line option,
592 * after filling in some potentially useful defaults.
593 */
594static void read_block_sizes(struct ppcg_kernel *kernel,
595 __isl_keep isl_union_map *sizes)
596{
597 isl_set *size;
598
599 if (kernel->n_block > 3)
600 kernel->n_block = 3;
601 switch (kernel->n_block) {
602 case 1:
603 kernel->block_dim[0] = 512;
604 break;
605 case 2:
606 kernel->block_dim[0] = 32;
607 kernel->block_dim[1] = 16;
608 break;
609 default:
610 kernel->block_dim[0] = 32;
611 kernel->block_dim[1] = 4;
612 kernel->block_dim[2] = 4;
613 break;
614 }
615
616 size = extract_sizes(sizes, "block", kernel->id);
617 read_sizes_from_set(size, kernel->block_dim, &kernel->n_block);
618}
619
620/* Extract user specified "grid" sizes from the "sizes" command line option,
621 * after filling in some potentially useful defaults.
622 */
623static void read_grid_sizes(struct ppcg_kernel *kernel,
624 __isl_keep isl_union_map *sizes)
625{
626 isl_set *size;
627
628 if (kernel->n_grid > 2)
629 kernel->n_grid = 2;
630 switch (kernel->n_grid) {
631 case 1:
632 kernel->grid_dim[0] = 32768;
633 break;
634 default:
635 kernel->grid_dim[0] = 256;
636 kernel->grid_dim[1] = 256;
637 break;
638 }
639
640 size = extract_sizes(sizes, "grid", kernel->id);
641 read_sizes_from_set(size, kernel->grid_dim, &kernel->n_grid);
642}
643
644/* Extract user specified grid and block sizes from the gen->sizes
645 * command line option after filling in some potentially useful defaults.
646 * Store the extracted sizes in "kernel".
647 * Add the effectively used sizes to gen->used_sizes.
648 */
649static void read_grid_and_block_sizes(struct ppcg_kernel *kernel,
650 struct gpu_gen *gen)
651{
652 read_block_sizes(kernel, gen->sizes);
653 read_grid_sizes(kernel, gen->sizes);
654 set_used_sizes(gen, "block", kernel->id,
655 kernel->block_dim, kernel->n_block);
656 set_used_sizes(gen, "grid", kernel->id,
657 kernel->grid_dim, kernel->n_grid);
658}
659
660static void *free_stmts(struct gpu_stmt *stmts, int n)
661{
662 int i;
663
664 if (!stmts)
665 return NULL((void*)0);
666
667 for (i = 0; i < n; ++i) {
668 struct gpu_stmt_access *access, *next;
669
670 for (access = stmts[i].accesses; access; access = next) {
671 next = access->next;
672 isl_id_free(access->ref_id);
673 isl_map_free(access->access);
674 isl_map_free(access->tagged_access);
675 free(access);
676 }
677
678 isl_id_free(stmts[i].id);
679 }
680 free(stmts);
681
682 return NULL((void*)0);
683}
684
685/* Add parameters p[i] with identifiers "ids" to "set",
686 * with bounds to 0 <= p[i] < size[i].
687 */
688__isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
689 int *size, __isl_keep isl_id_list *ids)
690{
691 int i, len;
692 unsigned nparam;
693
694 len = isl_id_list_n_id(ids);
695 nparam = isl_set_dim(set, isl_dim_param);
696 set = isl_set_add_dims(set, isl_dim_param, len);
697
698 for (i = 0; i < len; ++i) {
699 isl_id *id;
700
701 id = isl_id_list_get_id(ids, i);
702 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
703 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
704 set = isl_set_upper_bound_si(set, isl_dim_param,
705 nparam + i, size[i] - 1);
706 }
707
708 return set;
709}
710
711/* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
712 * with
713 *
714 * { : 0 <= p[i] < size[i] }
715 *
716 * or an overapproximation.
717 */
718static __isl_give isl_set *add_bounded_parameters_dynamic(
719 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
720 __isl_keep isl_id_list *ids)
721{
722 int i, len;
723 unsigned nparam;
724 isl_space *space;
725 isl_local_space *ls;
726
727 len = isl_multi_pw_aff_dim(size, isl_dim_out);
728 nparam = isl_set_dim(set, isl_dim_param);
729 set = isl_set_add_dims(set, isl_dim_param, len);
730
731 for (i = 0; i < len; ++i) {
732 isl_id *id;
733
734 id = isl_id_list_get_id(ids, i);
735 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
736 }
737
738 space = isl_space_params(isl_set_get_space(set));
739 ls = isl_local_space_from_space(space);
740 for (i = 0; i < len; ++i) {
741 isl_pw_aff *param, *size_i, *zero;
742 isl_set *bound;
743
744 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
745 isl_dim_param, nparam + i);
746
747 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
748 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
749 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
750 set = isl_set_intersect_params(set, bound);
751
752 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
753 bound = isl_pw_aff_ge_set(param, zero);
754 set = isl_set_intersect_params(set, bound);
755 }
756 isl_local_space_free(ls);
757
758 return set;
759}
760
761/* Return the union of all tagged access relations in the group.
762 */
763static __isl_give isl_union_map *group_tagged_access_relation(
764 struct gpu_array_ref_group *group)
765{
766 int i;
767 isl_union_map *access;
768
769 access = isl_union_map_empty(isl_map_get_space(group->access));
770 for (i = 0; i < group->n_ref; ++i) {
771 isl_map *map_i;
772
773 map_i = isl_map_copy(group->refs[i]->tagged_access);
774 access = isl_union_map_union(access,
775 isl_union_map_from_map(map_i));
776 }
777
778 return access;
779}
780
781/* Return the extent of "array", recomputed from the bounds.
782 * The recomputed extent may be simpler than the original extent.
783 */
784static __isl_give isl_set *array_extent(struct gpu_array_info *array)
785{
786 int i;
787 isl_id *id;
788 isl_space *space;
789 isl_local_space *ls;
790 isl_set *extent;
791
792 id = isl_set_get_tuple_id(array->extent);
793 space = isl_set_get_space(array->extent);
794 extent = isl_set_universe(isl_space_copy(space));
795 ls = isl_local_space_from_space(space);
796 for (i = 0; i < array->n_index; ++i) {
797 isl_pw_aff *bound;
798 isl_aff *aff;
799 isl_pw_aff *index;
800 isl_set *lt;
801
802 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
803
804 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
805 isl_dim_set, i);
806 index = isl_pw_aff_from_aff(aff);
807 bound = isl_pw_aff_copy(array->bound[i]);
808 bound = isl_pw_aff_from_range(bound);
809 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
810 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
811 isl_id_copy(id));
812 lt = isl_pw_aff_lt_set(index, bound);
813 extent = isl_set_intersect(extent, lt);
814 }
815 isl_local_space_free(ls);
816 isl_id_free(id);
817
818 return extent;
819}
820
821/* Return a map from the first group->depth dimensions of the computed
822 * schedule to the array tile in
823 * global memory that corresponds to the shared memory copy.
824 *
825 * In particular, return a map
826 *
827 * { D[i] -> A[a] }
828 *
829 * with constraints
830 *
831 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
832 *
833 * and
834 *
835 * 0 <= a <= array_size - 1 (2)
836 *
837 * Note that if some stride has been detected (i.e., when
838 * group->shared_tile->bound[i].shift is set), then a in (1) refers
839 * to the shifted and scaled down version.
840 *
841 * Constraints (1) are obtained by mapping the size constraints on the
842 * shared/private memory tile back to the access relation.
843 * Constraints (2) are obtained from the (recomputed) extent.
844 */
845static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
846{
847 int i;
848 int n_index = group->array->n_index;
849 isl_map *tile;
850 isl_space *space;
851 isl_set *local;
852 isl_set *extent;
853
854 space = isl_multi_aff_get_space(group->shared_tile->tiling);
855 space = isl_space_range(space);
856 local = isl_set_universe(space);
857 for (i = 0; i < n_index; ++i) {
858 isl_val *bound;
859
860 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
861 bound = isl_val_copy(group->shared_tile->bound[i].size);
862 bound = isl_val_sub_ui(bound, 1);
863 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
864 }
865 local = isl_set_preimage_multi_aff(local,
866 isl_multi_aff_copy(group->shared_tile->tiling));
867 tile = isl_set_unwrap(local);
868 extent = array_extent(group->array);
869 tile = isl_map_intersect_range(tile, extent);
870
871 return tile;
872}
873
874/* Given a mapping "iterator_map" from the AST schedule to a domain,
875 * return the corresponding mapping from the AST schedule to
876 * to the outer kernel->shared_schedule_dim dimensions of
877 * the schedule computed by PPCG for this kernel.
878 *
879 * Note that kernel->shared_schedule_dim is at least as large as
880 * the largest depth of any array reference group associated to the kernel.
881 * This is needed as the returned schedule is used to extract a mapping
882 * to the outer group->depth dimensions in transform_index.
883 */
884static __isl_give isl_pw_multi_aff *compute_sched_to_shared(
885 struct ppcg_kernel *kernel, __isl_take isl_pw_multi_aff *iterator_map)
886{
887 isl_union_pw_multi_aff *upma;
888 isl_pw_multi_aff *pma;
889 isl_space *space;
890
891 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
892 space = isl_space_from_domain(space);
893 space = isl_space_add_dims(space, isl_dim_out,
894 kernel->shared_schedule_dim);
895
896 upma = isl_union_pw_multi_aff_copy(kernel->shared_schedule);
897 pma = isl_union_pw_multi_aff_extract_pw_multi_aff(upma, space);
898 isl_union_pw_multi_aff_free(upma);
899
900 return isl_pw_multi_aff_pullback_pw_multi_aff(pma, iterator_map);
901}
902
903/* If max_shared_memory is not set to infinity (-1), then make
904 * sure that the total amount of shared memory required by the
905 * array reference groups mapped to shared memory by "kernel"
906 * is no larger than this maximum.
907 *
908 * We apply a greedy approach and discard (keep in global memory)
909 * those groups that would result in a total memory size that
910 * is larger than the maximum.
911 *
912 * This function should be called after any function that may
913 * affect the decision on whether to place a reference group
914 * in private, shared or global memory.
915 */
916static void check_shared_memory_bound(struct ppcg_kernel *kernel)
917{
918 int i, j;
919 isl_val *left, *size;
920
921 if (kernel->options->max_shared_memory < 0)
922 return;
923
924 left = isl_val_int_from_si(kernel->ctx,
925 kernel->options->max_shared_memory);
926
927 for (i = 0; i < kernel->n_array; ++i) {
928 struct gpu_local_array_info *local = &kernel->array[i];
929
930 for (j = 0; j < local->n_group; ++j) {
931 struct gpu_array_ref_group *group;
932
933 group = local->groups[j];
934 if (group->private_tile)
935 continue;
936 if (!group->shared_tile)
937 continue;
938
939 size = gpu_array_tile_size(group->shared_tile);
940 size = isl_val_mul_ui(size, local->array->size);
941
942 if (isl_val_le(size, left)) {
943 left = isl_val_sub(left, size);
944 continue;
945 }
946 isl_val_free(size);
947
948 group->shared_tile =
949 gpu_array_tile_free(group->shared_tile);
950 }
951 }
952
953 isl_val_free(left);
954}
955
956/* Mark all arrays of "kernel" that have an array reference group
957 * that is not mapped to private or shared memory as
958 * accessing the corresponding global device memory.
959 */
960static void mark_global_arrays(struct ppcg_kernel *kernel)
961{
962 int i, j;
963
964 for (i = 0; i < kernel->n_array; ++i) {
965 struct gpu_local_array_info *local = &kernel->array[i];
966
967 if (local->global)
968 continue;
969 for (j = 0; j < local->n_group; ++j) {
970 if (gpu_array_ref_group_tile(local->groups[j]))
971 continue;
972
973 local->global = 1;
974 local->array->global = 1;
975 break;
976 }
977 }
978}
979
980/* Compute a tiling for all the array reference groups in "kernel".
981 */
982static void compute_group_tilings(struct ppcg_kernel *kernel)
983{
984 int i, j;
985
986 for (i = 0; i < kernel->n_array; ++i) {
987 struct gpu_local_array_info *array = &kernel->array[i];
988
989 for (j = 0; j < array->n_group; ++j)
990 gpu_array_ref_group_compute_tiling(array->groups[j]);
991 }
992}
993
994/* Compute the size of a bounding box around the origin and "set",
995 * where "set" is assumed to contain only non-negative elements.
996 * In particular, compute the maximal value of "set" in each direction
997 * and add one.
998 */
999static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
1000 __isl_take isl_set *context)
1001{
1002 int i, n;
1003 isl_multi_pw_aff *mpa;
1004
1005 context = isl_set_params(context);
1006 n = isl_set_dim(set, isl_dim_set);
1007 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
1008 for (i = 0; i < n; ++i) {
1009 isl_space *space;
1010 isl_aff *one;
1011 isl_pw_aff *bound;
1012
1013 bound = isl_set_dim_max(isl_set_copy(set), i);
1014 bound = isl_pw_aff_coalesce(bound);
1015 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
1016
1017 space = isl_pw_aff_get_domain_space(bound);
1018 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1019 one = isl_aff_add_constant_si(one, 1);
1020 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
1021 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
1022 }
1023 isl_set_free(set);
1024 isl_set_free(context);
1025
1026 return mpa;
1027}
1028
1029/* Compute the effective grid size as a list of the sizes in each dimension.
1030 *
1031 * The grid size specified by the user or set by default
1032 * in read_grid_sizes() and applied by the block filter,
1033 * may be too large for the given code in the sense that
1034 * it may contain blocks that don't need to execute anything.
1035 * We therefore don't return this grid size, but instead the
1036 * smallest grid size that ensures that all blocks that actually
1037 * execute code are included in the grid.
1038 *
1039 * We first extract a description of the grid, i.e., the possible values
1040 * of the block ids, from the domain elements in "domain" and
1041 * kernel->block_filter.
1042 * The block ids are parameters in kernel->block_filter.
1043 * We simply need to change them into set dimensions.
1044 *
1045 * Then, for each block dimension, we compute the maximal value of the block id
1046 * and add one.
1047 */
1048static __isl_give isl_multi_pw_aff *extract_grid_size(
1049 struct ppcg_kernel *kernel, __isl_take isl_union_set *domain)
1050{
1051 int i;
1052 isl_set *grid;
1053
1054 domain = isl_union_set_intersect(domain,
1055 isl_union_set_copy(kernel->block_filter));
1056 grid = isl_union_set_params(domain);
1057 grid = isl_set_from_params(grid);
1058 grid = isl_set_add_dims(grid, isl_dim_set, kernel->n_grid);
1059 for (i = 0; i < kernel->n_grid; ++i) {
1060 int pos;
1061 isl_id *id;
1062
1063 id = isl_id_list_get_id(kernel->block_ids, i);
1064 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1065 isl_id_free(id);
1066 assert(pos >= 0)((pos >= 0) ? (void) (0) : __assert_fail ("pos >= 0", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/polly/lib/External/ppcg/gpu.c"
, 1066, __PRETTY_FUNCTION__))
;
1067 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1068 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1069 }
1070
1071 return extract_size(grid, isl_set_copy(kernel->context));
1072}
1073
1074/* Compute the size of a fixed bounding box around the origin and "set",
1075 * where "set" is assumed to contain only non-negative elements,
1076 * and store the results in "size".
1077 * In particular, compute the maximal value of "set" in each direction
1078 * and add one.
1079 */
1080static void extract_fixed_size(__isl_take isl_set *set, int *size)
1081{
1082 int i, n;
1083 isl_local_space *ls;
1084 isl_aff *obj;
1085
1086 n = isl_set_dim(set, isl_dim_set);
1087 ls = isl_local_space_from_space(isl_set_get_space(set));
1088 obj = isl_aff_zero_on_domain(ls);
1089 for (i = 0; i < n; ++i) {
1090 isl_val *max;
1091
1092 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1093 max = isl_set_max_val(set, obj);
1094 size[i] = isl_val_get_num_si(max) + 1;
1095 isl_val_free(max);
1096 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1097 }
1098 isl_aff_free(obj);
1099 isl_set_free(set);
1100}
1101
1102/* Compute the effective block size as a list of the sizes in each dimension
1103 * and store the sizes in kernel->block_dim.
1104 *
1105 * The block size specified by the user or set by default
1106 * in read_block_sizes() and applied by the thread filter,
1107 * may be too large for the given code in the sense that
1108 * it may contain threads that don't need to execute anything.
1109 * We therefore update this block size in kernel->block_dim
1110 * to the smallest block size that ensures that all threads
1111 * that actually execute code are included in the block.
1112 *
1113 * The possible values of the thread ids is obtained from
1114 * the domain elements "domain" and kernel->thread_filter.
1115 * The current implementation eliminates all parameters, ensuring
1116 * that the size is a fixed constant in each dimension.
1117 * In principle we could also compute parametric sizes.
1118 * We would have to make sure to project out all b%d and t%d parameters,
1119 * however.
1120 */
1121static void extract_block_size(struct ppcg_kernel *kernel,
1122 __isl_take isl_union_set *domain)
1123{
1124 int i;
1125 int nparam;
1126 isl_set *block;
1127
1128 domain = isl_union_set_intersect(domain,
1129 isl_union_set_copy(kernel->thread_filter));
1130 block = isl_union_set_params(domain);
1131 block = isl_set_from_params(block);
1132 block = isl_set_add_dims(block, isl_dim_set, kernel->n_block);
1133 for (i = 0; i < kernel->n_block; ++i) {
1134 int pos;
1135 isl_id *id;
1136
1137 id = isl_id_list_get_id(kernel->thread_ids, i);
1138 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1139 isl_id_free(id);
1140 assert(pos >= 0)((pos >= 0) ? (void) (0) : __assert_fail ("pos >= 0", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/polly/lib/External/ppcg/gpu.c"
, 1140, __PRETTY_FUNCTION__))
;
1141 block = isl_set_equate(block, isl_dim_param, pos,
1142 isl_dim_set, i);
1143 }
1144 nparam = isl_set_dim(block, isl_dim_param);
1145 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1146
1147 extract_fixed_size(block, kernel->block_dim);
1148}
1149
1150struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1151{
1152 int i, j;
1153
1154 if (!kernel)
1155 return NULL((void*)0);
1156
1157 isl_id_list_free(kernel->block_ids);
1158 isl_id_list_free(kernel->thread_ids);
1159 isl_multi_pw_aff_free(kernel->grid_size);
1160 isl_set_free(kernel->context);
1161 isl_union_set_free(kernel->core);
1162 isl_union_set_free(kernel->arrays);
1163 isl_space_free(kernel->space);
1164 isl_ast_node_free(kernel->tree);
1165 isl_union_set_free(kernel->block_filter);
1166 isl_union_set_free(kernel->thread_filter);
1167 isl_union_pw_multi_aff_free(kernel->shared_schedule);
1168 isl_union_set_free(kernel->sync_writes);
1169
1170 for (i = 0; i < kernel->n_array; ++i) {
1171 struct gpu_local_array_info *array = &kernel->array[i];
1172
1173 for (j = 0; j < array->n_group; ++j)
1174 gpu_array_ref_group_free(array->groups[j]);
1175 free(array->groups);
1176
1177 isl_pw_aff_list_free(array->bound);
1178 }
1179 free(kernel->array);
1180
1181 for (i = 0; i < kernel->n_var; ++i) {
1182 free(kernel->var[i].name);
1183 isl_vec_free(kernel->var[i].size);
1184 }
1185 free(kernel->var);
1186
1187 free(kernel);
1188
1189 return NULL((void*)0);
1190}
1191
1192/* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1193 */
1194static void ppcg_kernel_free_wrap(void *user)
1195{
1196 struct ppcg_kernel *kernel = user;
1197
1198 ppcg_kernel_free(kernel);
1199}
1200
1201static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1202 struct ppcg_kernel_var *var)
1203{
1204 int j;
1205 struct gpu_array_tile *tile;
1206 isl_printer *p;
1207 char *name;
1208
1209 var->array = group->array;
1210
1211 tile = group->private_tile;
1212 var->type = ppcg_access_private;
1213 if (!tile) {
1214 tile = group->shared_tile;
1215 var->type = ppcg_access_shared;
1216 }
1217
1218 p = isl_printer_to_str(ctx);
1219 p = gpu_array_ref_group_print_name(group, p);
1220 var->name = isl_printer_get_str(p);
1221 isl_printer_free(p);
1222
1223 var->size = isl_vec_alloc(ctx, group->array->n_index);
1224
1225 for (j = 0; j < group->array->n_index; ++j)
1226 var->size = isl_vec_set_element_val(var->size, j,
1227 isl_val_copy(tile->bound[j].size));
1228}
1229
1230static int create_kernel_vars(struct ppcg_kernel *kernel)
1231{
1232 int i, j, n;
1233
1234 n = 0;
1235 for (i = 0; i < kernel->n_array; ++i) {
1236 struct gpu_local_array_info *array = &kernel->array[i];
1237
1238 for (j = 0; j < array->n_group; ++j) {
1239 struct gpu_array_ref_group *group = array->groups[j];
1240 if (group->private_tile || group->shared_tile)
1241 ++n;
1242 }
1243 }
1244
1245 kernel->n_var = n;
1246 kernel->var = isl_calloc_array(kernel->ctx, struct ppcg_kernel_var, n)((struct ppcg_kernel_var *)isl_calloc_or_die(kernel->ctx, n
, sizeof(struct ppcg_kernel_var)))
;
1247 if (!kernel->var)
1248 return -1;
1249
1250 n = 0;
1251 for (i = 0; i < kernel->n_array; ++i) {
1252 struct gpu_local_array_info *array = &kernel->array[i];
1253
1254 for (j = 0; j < array->n_group; ++j) {
1255 struct gpu_array_ref_group *group = array->groups[j];
1256 if (!group->private_tile && !group->shared_tile)
1257 continue;
1258 create_kernel_var(kernel->ctx, group, &kernel->var[n]);
1259 ++n;
1260 }
1261 }
1262
1263 return 0;
1264}
1265
1266/* Replace "pa" by the zero function defined over the universe domain
1267 * in the space of "pa".
1268 */
1269static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1270{
1271 isl_space *space;
1272 isl_aff *zero;
1273
1274 space = isl_space_domain(isl_pw_aff_get_space(pa));
1275 isl_pw_aff_free(pa);
1276 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1277
1278 return isl_pw_aff_from_aff(zero);
1279}
1280
1281/* The sizes of the arrays on the host that have been computed by
1282 * extract_array_info may depend on the parameters. Use the extra
1283 * constraints on the parameters that are valid at "host_domain"
1284 * to simplify these expressions and store the results in kernel->array.
1285 *
1286 * We only need these localized bounds for arrays that are accessed
1287 * by the current kernel. If we have found at least one reference group
1288 * then the array is accessed by the kernel.
1289 *
1290 * The resulting sizes may be functions that are nowhere defined
1291 * in case the access function cannot possibly access anything inside
1292 * the kernel for some reason. If so, they are replaced by the zero
1293 * function. Since the access function cannot actually access anything,
1294 * there is no harm in printing the array sizes as zero.
1295 */
1296static void localize_bounds(struct ppcg_kernel *kernel,
1297 __isl_keep isl_set *host_domain)
1298{
1299 int i, j;
1300 isl_set *context;
1301
1302 context = isl_set_copy(host_domain);
1303 context = isl_set_params(context);
1304
1305 for (i = 0; i < kernel->n_array; ++i) {
1306 struct gpu_local_array_info *local = &kernel->array[i];
1307 isl_pw_aff_list *bound;
1308 int n_index;
1309
1310 if (local->n_group == 0)
1311 continue;
1312
1313 n_index = local->array->n_index;
1314 bound = isl_pw_aff_list_alloc(kernel->ctx, n_index);
1315
1316 for (j = 0; j < n_index; ++j) {
1317 isl_pw_aff *pwaff;
1318 int empty;
1319
1320 pwaff = isl_pw_aff_copy(local->array->bound[j]);
1321 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1322 empty = isl_pw_aff_is_empty(pwaff);
1323 if (empty < 0)
1324 pwaff = isl_pw_aff_free(pwaff);
1325 else if (empty)
1326 pwaff = set_universally_zero(pwaff);
1327 bound = isl_pw_aff_list_add(bound, pwaff);
1328 }
1329
1330 local->n_index = n_index;
1331 local->bound = bound;
1332 }
1333 isl_set_free(context);
1334}
1335
1336/* Create the array of gpu_local_array_info structures "array"
1337 * inside "kernel". The number of elements in this array is
1338 * the same as the number of arrays in "prog".
1339 * Initialize the "array" field of each local array to point
1340 * to the corresponding array in "prog".
1341 */
1342static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1343 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1344{
1345 int i;
1346 isl_ctx *ctx;
1347
1348 ctx = isl_set_get_ctx(prog->context);
1349 kernel->array = isl_calloc_array(ctx,((struct gpu_local_array_info *)isl_calloc_or_die(ctx, prog->
n_array, sizeof(struct gpu_local_array_info)))
1350 struct gpu_local_array_info, prog->n_array)((struct gpu_local_array_info *)isl_calloc_or_die(ctx, prog->
n_array, sizeof(struct gpu_local_array_info)))
;
1351 if (!kernel->array)
1352 return ppcg_kernel_free(kernel);
1353 kernel->n_array = prog->n_array;
1354
1355 for (i = 0; i < prog->n_array; ++i)
1356 kernel->array[i].array = &prog->array[i];
1357
1358 return kernel;
1359}
1360
1361/* Does "kernel" need to be passed an argument corresponding to array "i"?
1362 *
1363 * The argument is only needed if the kernel accesses this device memory.
1364 */
1365int ppcg_kernel_requires_array_argument(struct ppcg_kernel *kernel, int i)
1366{
1367 return kernel->array[i].global;
1368}
1369
1370/* Find the element in gen->stmt that has the given "id".
1371 * Return NULL if no such gpu_stmt can be found.
1372 */
1373static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1374{
1375 int i;
1376
1377 for (i = 0; i < prog->n_stmts; ++i) {
1378 if (id == prog->stmts[i].id)
1379 break;
1380 }
1381
1382 return i < prog->n_stmts ? &prog->stmts[i] : NULL((void*)0);
1383}
1384
1385void ppcg_kernel_stmt_free(void *user)
1386{
1387 int i;
1388 struct ppcg_kernel_stmt *stmt = user;
1389
1390 if (!stmt)
1391 return;
1392
1393 switch (stmt->type) {
1394 case ppcg_kernel_copy:
1395 isl_ast_expr_free(stmt->u.c.index);
1396 isl_ast_expr_free(stmt->u.c.local_index);
1397 break;
1398 case ppcg_kernel_domain:
1399 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1400 break;
1401 case ppcg_kernel_sync:
1402 break;
1403 }
1404
1405 free(stmt);
1406}
1407
1408/* Return the gpu_stmt_access in the list "accesses" that corresponds
1409 * to "ref_id".
1410 */
1411static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1412 __isl_keep isl_id *ref_id)
1413{
1414 struct gpu_stmt_access *access;
1415
1416 for (access = accesses; access; access = access->next)
1417 if (access->ref_id == ref_id)
1418 return access;
1419
1420 return NULL((void*)0);
1421}
1422
1423/* Return the index of the array called "name" in the list of arrays.
1424 */
1425static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1426{
1427 int i;
1428
1429 for (i = 0; i < kernel->n_array; ++i)
1430 if (!strcmp(name, kernel->array[i].array->name)__extension__ ({ size_t __s1_len, __s2_len; (__builtin_constant_p
(name) && __builtin_constant_p (kernel->array[i].
array->name) && (__s1_len = __builtin_strlen (name
), __s2_len = __builtin_strlen (kernel->array[i].array->
name), (!((size_t)(const void *)((name) + 1) - (size_t)(const
void *)(name) == 1) || __s1_len >= 4) && (!((size_t
)(const void *)((kernel->array[i].array->name) + 1) - (
size_t)(const void *)(kernel->array[i].array->name) == 1
) || __s2_len >= 4)) ? __builtin_strcmp (name, kernel->
array[i].array->name) : (__builtin_constant_p (name) &&
((size_t)(const void *)((name) + 1) - (size_t)(const void *)
(name) == 1) && (__s1_len = __builtin_strlen (name), __s1_len
< 4) ? (__builtin_constant_p (kernel->array[i].array->
name) && ((size_t)(const void *)((kernel->array[i]
.array->name) + 1) - (size_t)(const void *)(kernel->array
[i].array->name) == 1) ? __builtin_strcmp (name, kernel->
array[i].array->name) : (__extension__ ({ const unsigned char
*__s2 = (const unsigned char *) (const char *) (kernel->array
[i].array->name); int __result = (((const unsigned char *)
(const char *) (name))[0] - __s2[0]); if (__s1_len > 0 &&
__result == 0) { __result = (((const unsigned char *) (const
char *) (name))[1] - __s2[1]); if (__s1_len > 1 &&
__result == 0) { __result = (((const unsigned char *) (const
char *) (name))[2] - __s2[2]); if (__s1_len > 2 &&
__result == 0) __result = (((const unsigned char *) (const char
*) (name))[3] - __s2[3]); } } __result; }))) : (__builtin_constant_p
(kernel->array[i].array->name) && ((size_t)(const
void *)((kernel->array[i].array->name) + 1) - (size_t)
(const void *)(kernel->array[i].array->name) == 1) &&
(__s2_len = __builtin_strlen (kernel->array[i].array->
name), __s2_len < 4) ? (__builtin_constant_p (name) &&
((size_t)(const void *)((name) + 1) - (size_t)(const void *)
(name) == 1) ? __builtin_strcmp (name, kernel->array[i].array
->name) : -(__extension__ ({ const unsigned char *__s2 = (
const unsigned char *) (const char *) (name); int __result = (
((const unsigned char *) (const char *) (kernel->array[i].
array->name))[0] - __s2[0]); if (__s2_len > 0 &&
__result == 0) { __result = (((const unsigned char *) (const
char *) (kernel->array[i].array->name))[1] - __s2[1]);
if (__s2_len > 1 && __result == 0) { __result = (
((const unsigned char *) (const char *) (kernel->array[i].
array->name))[2] - __s2[2]); if (__s2_len > 2 &&
__result == 0) __result = (((const unsigned char *) (const char
*) (kernel->array[i].array->name))[3] - __s2[3]); } } __result
; }))) : __builtin_strcmp (name, kernel->array[i].array->
name)))); })
)
1431 return i;
1432
1433 return -1;
1434}
1435
1436/* Internal data structure for the index and AST expression transformation
1437 * callbacks for pet_stmt_build_ast_exprs.
1438 *
1439 * "kernel" is the kernel for which are computing AST expressions and
1440 * may be NULL if we are not inside a kernel.
1441 * "accesses" is the list of gpu_stmt_access in the statement.
1442 * "iterator_map" expresses the statement iterators in terms of
1443 * the AST loop iterators.
1444 * "sched2shared" expresses the outer shared_schedule_dim dimensions of
1445 * the kernel schedule in terms of the AST loop iterators and
1446 * may be NULL if we are not inside a kernel.
1447 *
1448 * The following fields are set in transform_index and used in transform_expr.
1449 * "array" is the array that is being accessed.
1450 * "global" is set if the global array is accessed (rather than
1451 * shared/private memory).
1452 * "local_array" refers to information on the array specialized
1453 * to the current kernel.
1454 */
1455struct ppcg_transform_data {
1456 struct ppcg_options *options;
1457 struct ppcg_kernel *kernel;
1458 struct gpu_stmt_access *accesses;
1459 isl_pw_multi_aff *iterator_map;
1460 isl_pw_multi_aff *sched2shared;
1461
1462 struct gpu_array_info *array;
1463 int global;
1464 struct gpu_local_array_info *local_array;
1465};
1466
1467/* Return a pointer to the gpu_array_ref_group in "local"
1468 * that contains the reference "access".
1469 * Return NULL if no such group can be found.
1470 */
1471static struct gpu_array_ref_group *find_ref_group(
1472 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1473{
1474 int i, j;
1475
1476 for (i = 0; i < local->n_group; ++i) {
1477 struct gpu_array_ref_group *group = local->groups[i];
1478
1479 for (j = 0; j < group->n_ref; ++j)
1480 if (group->refs[j] == access)
1481 return group;
1482 }
1483
1484 return NULL((void*)0);
1485}
1486
1487/* Index transformation callback for pet_stmt_build_ast_exprs.
1488 *
1489 * "index" expresses the array indices in terms of statement iterators
1490 *
1491 * We first reformulate "index" in terms of the AST loop iterators.
1492 * Then we check if we are accessing the global array or
1493 * a shared/private copy. In particular, if we are not inside a kernel
1494 * then we must be accessing a global array.
1495 * In the former case, we simply return
1496 * the updated index. If "index" is an affine expression rather
1497 * than an array access, then we also return the updated index here.
1498 *
1499 * If no reference groups have been computed for the array,
1500 * then we can only be accessing the global array.
1501 *
1502 * Otherwise, we apply the tiling to the index.
1503 * This tiling is of the form
1504 *
1505 * [D -> A] -> T
1506 *
1507 * where D corresponds to the outer group->depth dimensions of
1508 * the kernel schedule.
1509 * The index is of the form
1510 *
1511 * L -> A
1512 *
1513 * We update the tiling to refer to the AST loop iterators
1514 *
1515 * [L -> A] -> T
1516 *
1517 * and modify index to keep track of those iterators
1518 *
1519 * L -> [L -> A]
1520 *
1521 * Combining these two yields a tiled index expression in terms
1522 * of the AST loop iterators
1523 *
1524 * L -> T
1525 */
1526static __isl_give isl_multi_pw_aff *transform_index(
1527 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
1528 void *user)
1529{
1530 struct ppcg_transform_data *data = user;
1531 struct gpu_stmt_access *access;
1532 struct gpu_array_ref_group *group;
1533 struct gpu_array_tile *tile;
1534 isl_pw_multi_aff *iterator_map;
1535 int i;
1536 int dim;
1537 const char *name;
1538 isl_space *space;
1539 isl_multi_pw_aff *tiling;
1540 isl_pw_multi_aff *pma;
1541 isl_multi_pw_aff *mpa;
1542 isl_pw_multi_aff *sched2depth;
1543
1544 data->array = NULL((void*)0);
1545
1546 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
1547 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
1548
1549 if (!data->kernel)
1550 return index;
1551
1552 access = find_access(data->accesses, ref_id);
1553 if (!access)
1554 return index;
1555 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1556 return index;
1557
1558 name = get_outer_array_name(access->access);
1559 i = find_array_index(data->kernel, name);
1560 if (i < 0)
1561 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,do { isl_handle_error(isl_multi_pw_aff_get_ctx(index), isl_error_internal
, "cannot find array", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/polly/lib/External/ppcg/gpu.c"
, 1563); return isl_multi_pw_aff_free(index); } while (0)
1562 "cannot find array",do { isl_handle_error(isl_multi_pw_aff_get_ctx(index), isl_error_internal
, "cannot find array", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/polly/lib/External/ppcg/gpu.c"
, 1563); return isl_multi_pw_aff_free(index); } while (0)
1563 return isl_multi_pw_aff_free(index))do { isl_handle_error(isl_multi_pw_aff_get_ctx(index), isl_error_internal
, "cannot find array", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/polly/lib/External/ppcg/gpu.c"
, 1563); return isl_multi_pw_aff_free(index); } while (0)
;
1564 data->local_array = &data->kernel->array[i];
1565 data->array = data->local_array->array;
1566
1567 group = find_ref_group(data->local_array, access);
1568 if (!group) {
1569 data->global = 1;
1570 return index;
1571 }
1572
1573 tile = group->private_tile;
1574 if (!tile)
1575 tile = group->shared_tile;
1576 data->global = !tile;
1577 if (!tile)
1578 return index;
1579
1580 space = isl_space_range(isl_multi_pw_aff_get_space(index));
1581 space = isl_space_map_from_set(space);
1582 pma = isl_pw_multi_aff_identity(space);
1583 sched2depth = isl_pw_multi_aff_copy(data->sched2shared);
1584 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1585 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1586 group->depth, dim - group->depth);
1587 pma = isl_pw_multi_aff_product(sched2depth, pma);
1588 tiling = isl_multi_pw_aff_from_multi_aff(
1589 isl_multi_aff_copy(tile->tiling));
1590 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1591
1592 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1593 space = isl_space_map_from_set(space);
1594 mpa = isl_multi_pw_aff_identity(space);
1595 index = isl_multi_pw_aff_range_product(mpa, index);
1596 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1597
1598 return index;
1599}
1600
1601/* Dereference "expr" by adding an index [0].
1602 * The original "expr" is assumed not to have any indices.
1603 *
1604 * If "expr" is a member access, then the dereferencing needs
1605 * to be applied to the structure argument of this member access.
1606 */
1607static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1608{
1609 isl_ctx *ctx;
1610 isl_ast_expr *arg0, *res;
1611 isl_ast_expr_list *list;
1612
1613 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1614 if (!arg0)
1615 return isl_ast_expr_free(expr);
1616 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1617 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1618 isl_ast_expr *arg;
1619
1620 arg = isl_ast_expr_get_op_arg(arg0, 0);
1621 arg = dereference(arg);
1622 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1623 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1624
1625 return expr;
1626 }
1627 isl_ast_expr_free(arg0);
1628
1629 ctx = isl_ast_expr_get_ctx(expr);
1630 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1631 list = isl_ast_expr_list_from_ast_expr(res);
1632 res = isl_ast_expr_get_op_arg(expr, 0);
1633 res = isl_ast_expr_access(res, list);
1634 isl_ast_expr_free(expr);
1635
1636 return res;
1637}
1638
1639/* Linearize the index expression "expr" based on the array bounds
1640 * of "array".
1641 *
1642 * That is, transform expression
1643 *
1644 * A[i_0][i_1]...[i_n]
1645 *
1646 * to
1647 *
1648 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1649 *
1650 * where b_0, b_1, ..., b_n are the bounds on the array.
1651 *
1652 * If the base of "expr" is a member access, then the linearization needs
1653 * to be applied to the structure argument of this member access.
1654 *
1655 * In the base case, if "expr" has no arguments (other than the name of
1656 * the array), then we are passing an entire array to a function.
1657 * In this case, there is nothing to linearize.
1658 * Note that at this point an expression with no arguments can
1659 * only be an entire array because the scalar case and
1660 * the case of single struct are handled by the caller.
1661 *
1662 * If the number of specified index expressions in "expr"
1663 * is smaller than the dimension of the accessed array,
1664 * then the missing i_j also do not appear in the linearized expression.
1665 * Furthermore, since such an expression does not refer to a single
1666 * element while the default linearized expression would refer to
1667 * a single element, we return the expression
1668 *
1669 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
1670 *
1671 * instead. Note that because of the special case handling above,
1672 * we can assume here that here that there is at least one index expression.
1673 */
1674__isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1675 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1676{
1677 int i, n;
1678 isl_ctx *ctx;
1679 isl_set *context;
1680 isl_ast_expr *arg0;
1681 isl_ast_expr *res;
1682 isl_ast_expr_list *list;
1683 isl_ast_build *build;
1684
1685 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1686 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1687 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1688 isl_ast_expr *arg;
1689
1690 arg = isl_ast_expr_get_op_arg(arg0, 0);
1691 arg = gpu_local_array_info_linearize_index(array, arg);
1692 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1693 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1694
1695 return expr;
1696 }
1697 isl_ast_expr_free(arg0);
1698
1699 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1700 return expr;
1701
1702 ctx = isl_ast_expr_get_ctx(expr);
1703 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
1704 build = isl_ast_build_from_context(context);
1705
1706 n = isl_ast_expr_get_op_n_arg(expr);
1707 res = isl_ast_expr_get_op_arg(expr, 1);
1708 for (i = 1; i < array->n_index; ++i) {
1709 isl_pw_aff *bound_i;
1710 isl_ast_expr *expr_i;
1711
1712 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
1713 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
1714 res = isl_ast_expr_mul(res, expr_i);
1715
1716 if (i + 1 >= n)
1717 continue;
1718 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1719 res = isl_ast_expr_add(res, expr_i);
1720 }
1721
1722 isl_ast_build_free(build);
1723
1724 if (1 + array->n_index > n) {
1725 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1726 } else {
1727 list = isl_ast_expr_list_from_ast_expr(res);
1728 res = isl_ast_expr_get_op_arg(expr, 0);
1729 res = isl_ast_expr_access(res, list);
1730 }
1731
1732 isl_ast_expr_free(expr);
1733
1734 return res;
1735}
1736
1737/* AST expression transformation callback for pet_stmt_build_ast_exprs.
1738 *
1739 * If the AST expression refers to an array that is not accessed
1740 * at all, then this means the value of the expression is not used,
1741 * so we might as well print zero (NULL pointer) instead.
1742 *
1743 * If the AST expression refers to a global scalar that is not
1744 * a read-only scalar, then its address was passed to the kernel and
1745 * we need to dereference it.
1746 *
1747 * If the AST expression refers to an access to a global array,
1748 * then we linearize the access exploiting the bounds in data->local_array.
1749 */
1750static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1751 __isl_keep isl_id *id, void *user)
1752{
1753 struct ppcg_transform_data *data = user;
1754
1755 if (!data->array)
1756 return expr;
1757 if (!data->array->accessed) {
1758 isl_ctx *ctx;
1759
1760 ctx = isl_ast_expr_get_ctx(expr);
1761 isl_ast_expr_free(expr);
1762 return isl_ast_expr_from_val(isl_val_zero(ctx));
1763 }
1764 if (gpu_array_is_read_only_scalar(data->array))
1765 return expr;
1766 if (!data->global)
1767 return expr;
1768 if (data->array->n_index == 0)
1769 return dereference(expr);
1770 if (!data->array->linearize)
1771 return expr;
1772
1773 return gpu_local_array_info_linearize_index(data->local_array, expr);
1774}
1775
1776/* This function is called for each instance of a user statement
1777 * in the kernel "kernel", identified by "gpu_stmt".
1778 * "kernel" may be NULL if we are not inside a kernel.
1779 *
1780 * We attach a struct ppcg_kernel_stmt to the "node", containing
1781 * a computed AST expression for each access, through an annotation
1782 * with name "user".
1783 * These AST expressions are computed from iterator_map,
1784 * which expresses the domain
1785 * elements in terms of the generated loops, and sched2shared,
1786 * which expresses the outer shared_schedule_dim dimensions of
1787 * the kernel schedule computed by PPCG in terms of the generated loops.
1788 */
1789static __isl_give isl_ast_node *create_domain_leaf(
1790 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1791 __isl_keep isl_ast_build *build, struct gpu_stmt *gpu_stmt,
1792 struct gpu_gen *gen)
1793{
1794 struct ppcg_transform_data data;
1795 struct ppcg_kernel_stmt *stmt;
1796 isl_ctx *ctx;
1797 isl_id *id;
1798 isl_pw_multi_aff *sched2shared;
1799 isl_map *map;
1800 isl_pw_multi_aff *iterator_map;
1801 isl_union_map *schedule;
1802
1803 if (!node)
1804 return NULL((void*)0);
1805 ctx = isl_ast_node_get_ctx(node);
1806
1807 stmt = isl_calloc_type(ctx, struct ppcg_kernel_stmt)((struct ppcg_kernel_stmt *)isl_calloc_or_die(ctx, 1, sizeof(
struct ppcg_kernel_stmt)))
;
1808 if (!stmt)
1809 return isl_ast_node_free(node);
1810
1811 schedule = isl_ast_build_get_schedule(build);
1812 map = isl_map_reverse(isl_map_from_union_map(schedule));
1813 iterator_map = isl_pw_multi_aff_from_map(map);
1814 if (kernel)
1815 sched2shared = compute_sched_to_shared(kernel,
1816 isl_pw_multi_aff_copy(iterator_map));
1817 else
1818 sched2shared = NULL((void*)0);
1819
1820 stmt->type = ppcg_kernel_domain;
1821 stmt->u.d.stmt = gpu_stmt;
1822
1823 data.kernel = kernel;
1824 data.accesses = stmt->u.d.stmt->accesses;
1825 data.iterator_map = iterator_map;
1826 data.sched2shared = sched2shared;
1827 stmt->u.d.ref2expr = gen->build_ast_expr(stmt->u.d.stmt->stmt,
1828 build, &transform_index, &data,
1829 &transform_expr, &data);
1830 isl_pw_multi_aff_free(iterator_map);
1831 isl_pw_multi_aff_free(sched2shared);
1832
1833 id = isl_id_alloc(ctx, "user", stmt);
1834 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1835 return isl_ast_node_set_annotation(node, id);
1836}
1837
1838/* This function is called for each statement node in the AST
1839 * for copying to or from shared/private memory.
1840 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1841 * statement to the node.
1842 * The statement name is "read" or "write", depending on whether we are
1843 * reading from global memory or writing to global memory.
1844 *
1845 * The schedule is of the form
1846 *
1847 * type[D -> A] -> L
1848 *
1849 * where D corresponds to the outer group->depth dimensions of
1850 * the kernel schedule, A to the global array and L to the outer
1851 * generated AST schedule.
1852 * We compute the inverse and strip off the type, resulting in
1853 *
1854 * L -> [D -> A]
1855 *
1856 * We combine this mapping with on the one hand the projection
1857 *
1858 * [D -> A] -> A
1859 *
1860 * and on the other hand the group tiling
1861 *
1862 * [D -> A] -> T
1863 *
1864 * resulting in
1865 *
1866 * L -> A and L -> T
1867 *
1868 * and store the corresponding expressions in stmt->index and stmt->local_index,
1869 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1870 */
1871static __isl_give isl_ast_node *create_access_leaf(struct ppcg_kernel *kernel,
1872 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1873 __isl_keep isl_ast_build *build)
1874{
1875 struct ppcg_kernel_stmt *stmt;
1876 struct gpu_array_tile *tile;
1877 isl_id *id;
1878 isl_ast_expr *expr;
1879 isl_space *space;
1880 isl_map *access;
1881 isl_pw_multi_aff *pma, *pma2;
1882 const char *type;
1883
1884 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt)((struct ppcg_kernel_stmt *)isl_calloc_or_die(kernel->ctx,
1, sizeof(struct ppcg_kernel_stmt)))
;
1885 if (!stmt)
1886 return isl_ast_node_free(node);
1887
1888 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1889 type = isl_map_get_tuple_name(access, isl_dim_in);
1890 stmt->u.c.read = !strcmp(type, "read")__extension__ ({ size_t __s1_len, __s2_len; (__builtin_constant_p
(type) && __builtin_constant_p ("read") && (
__s1_len = __builtin_strlen (type), __s2_len = __builtin_strlen
("read"), (!((size_t)(const void *)((type) + 1) - (size_t)(const
void *)(type) == 1) || __s1_len >= 4) && (!((size_t
)(const void *)(("read") + 1) - (size_t)(const void *)("read"
) == 1) || __s2_len >= 4)) ? __builtin_strcmp (type, "read"
) : (__builtin_constant_p (type) && ((size_t)(const void
*)((type) + 1) - (size_t)(const void *)(type) == 1) &&
(__s1_len = __builtin_strlen (type), __s1_len < 4) ? (__builtin_constant_p
("read") && ((size_t)(const void *)(("read") + 1) - (
size_t)(const void *)("read") == 1) ? __builtin_strcmp (type,
"read") : (__extension__ ({ const unsigned char *__s2 = (const
unsigned char *) (const char *) ("read"); int __result = (((
const unsigned char *) (const char *) (type))[0] - __s2[0]); if
(__s1_len > 0 && __result == 0) { __result = (((const
unsigned char *) (const char *) (type))[1] - __s2[1]); if (__s1_len
> 1 && __result == 0) { __result = (((const unsigned
char *) (const char *) (type))[2] - __s2[2]); if (__s1_len >
2 && __result == 0) __result = (((const unsigned char
*) (const char *) (type))[3] - __s2[3]); } } __result; }))) :
(__builtin_constant_p ("read") && ((size_t)(const void
*)(("read") + 1) - (size_t)(const void *)("read") == 1) &&
(__s2_len = __builtin_strlen ("read"), __s2_len < 4) ? (__builtin_constant_p
(type) && ((size_t)(const void *)((type) + 1) - (size_t
)(const void *)(type) == 1) ? __builtin_strcmp (type, "read")
: -(__extension__ ({ const unsigned char *__s2 = (const unsigned
char *) (const char *) (type); int __result = (((const unsigned
char *) (const char *) ("read"))[0] - __s2[0]); if (__s2_len
> 0 && __result == 0) { __result = (((const unsigned
char *) (const char *) ("read"))[1] - __s2[1]); if (__s2_len
> 1 && __result == 0) { __result = (((const unsigned
char *) (const char *) ("read"))[2] - __s2[2]); if (__s2_len
> 2 && __result == 0) __result = (((const unsigned
char *) (const char *) ("read"))[3] - __s2[3]); } } __result
; }))) : __builtin_strcmp (type, "read")))); })
;
1891 access = isl_map_reverse(access);
1892 pma = isl_pw_multi_aff_from_map(access);
1893 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1894
1895 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1896 space = isl_space_unwrap(space);
1897 pma2 = isl_pw_multi_aff_range_map(space);
1898 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1899 isl_pw_multi_aff_copy(pma));
1900 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1901 stmt->u.c.index = expr;
1902
1903 tile = gpu_array_ref_group_tile(group);
1904 pma2 = isl_pw_multi_aff_from_multi_aff(
1905 isl_multi_aff_copy(tile->tiling));
1906 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1907 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1908 stmt->u.c.local_index = expr;
1909
1910 stmt->u.c.array = group->array;
1911 stmt->u.c.local_array = group->local_array;
1912 stmt->type = ppcg_kernel_copy;
1913
1914 id = isl_id_alloc(kernel->ctx, NULL((void*)0), stmt);
1915 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1916 return isl_ast_node_set_annotation(node, id);
1917}
1918
1919/* Create a synchronization ppcg_kernel_stmt and
1920 * attach it to the node "node" representing the synchronization.
1921 */
1922static __isl_give isl_ast_node *create_sync_leaf(
1923 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1924 __isl_keep isl_ast_build *build)
1925{
1926 struct ppcg_kernel_stmt *stmt;
1927 isl_id *id;
1928
1929 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt)((struct ppcg_kernel_stmt *)isl_calloc_or_die(kernel->ctx,
1, sizeof(struct ppcg_kernel_stmt)))
;
1930 if (!stmt)
1931 return isl_ast_node_free(node);
1932
1933 stmt->type = ppcg_kernel_sync;
1934 id = isl_id_alloc(kernel->ctx, NULL((void*)0), stmt);
1935 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1936 return isl_ast_node_set_annotation(node, id);
1937}
1938
1939/* Internal data structure for at_domain.
1940 *
1941 * "prog" represents the entire scop.
1942 * "kernel" points to the kernel to which the current schedule node
1943 * belongs. It is set by before_mark and reset by after_mark.
1944 * It may be NULL if we are outside any kernel.
1945 */
1946struct ppcg_at_domain_data {
1947 struct gpu_prog *prog;
1948 struct gpu_gen *gen;
1949 struct ppcg_kernel *kernel;
1950};
1951
1952/* This function is called for each instance of a user statement
1953 * in the kernel. This may be one of the original user statements
1954 * or a statement introduced by PPCG.
1955 *
1956 * We first check if the statement id corresponds to a gpu statement,
1957 * which indicates the statement is an original user statement. Any statement
1958 * that is not an original user statement has been introduced by PPCG and
1959 * requires special handling.
1960 *
1961 * If the user statement is one of the original user statements, then we call
1962 * create_domain_leaf. Otherwise, we check if it is a copy or synchronization
1963 * statement and call the appropriate functions. Statements that copy an array
1964 * to/from the device do not need any further treatment.
1965 */
1966static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
1967 __isl_keep isl_ast_build *build, void *user)
1968{
1969 struct ppcg_at_domain_data *data = user;
1970 struct gpu_stmt *gpu_stmt;
1971 isl_ast_expr *expr, *arg;
1972 isl_id *id;
1973 int is_sync;
1974 const char *name;
1975 void *p;
1976
1977 expr = isl_ast_node_user_get_expr(node);
1978 arg = isl_ast_expr_get_op_arg(expr, 0);
1979 id = isl_ast_expr_get_id(arg);
1980 name = isl_id_get_name(id);
1981 p = isl_id_get_user(id);
1982 isl_ast_expr_free(expr);
1983 isl_ast_expr_free(arg);
1984
1985 gpu_stmt = find_stmt(data->prog, id);
1986 is_sync = gpu_tree_id_is_sync(id, data->kernel);
1987 isl_id_free(id);
1988
1989 if (gpu_stmt)
1990 return create_domain_leaf(data->kernel, node, build, gpu_stmt,
1991 data->gen);
1992
1993 if (!prefixcmp(name, "to_device_") || !prefixcmp(name, "from_device_"))
1994 return node;
1995 if (is_sync < 0)
1996 return isl_ast_node_free(node);
1997 if (!strcmp(name, "read")__extension__ ({ size_t __s1_len, __s2_len; (__builtin_constant_p
(name) && __builtin_constant_p ("read") && (
__s1_len = __builtin_strlen (name), __s2_len = __builtin_strlen
("read"), (!((size_t)(const void *)((name) + 1) - (size_t)(const
void *)(name) == 1) || __s1_len >= 4) && (!((size_t
)(const void *)(("read") + 1) - (size_t)(const void *)("read"
) == 1) || __s2_len >= 4)) ? __builtin_strcmp (name, "read"
) : (__builtin_constant_p (name) && ((size_t)(const void
*)((name) + 1) - (size_t)(const void *)(name) == 1) &&
(__s1_len = __builtin_strlen (name), __s1_len < 4) ? (__builtin_constant_p
("read") && ((size_t)(const void *)(("read") + 1) - (
size_t)(const void *)("read") == 1) ? __builtin_strcmp (name,
"read") : (__extension__ ({ const unsigned char *__s2 = (const
unsigned char *) (const char *) ("read"); int __result = (((
const unsigned char *) (const char *) (name))[0] - __s2[0]); if
(__s1_len > 0 && __result == 0) { __result = (((const
unsigned char *) (const char *) (name))[1] - __s2[1]); if (__s1_len
> 1 && __result == 0) { __result = (((const unsigned
char *) (const char *) (name))[2] - __s2[2]); if (__s1_len >
2 && __result == 0) __result = (((const unsigned char
*) (const char *) (name))[3] - __s2[3]); } } __result; }))) :
(__builtin_constant_p ("read") && ((size_t)(const void
*)(("read") + 1) - (size_t)(const void *)("read") == 1) &&
(__s2_len = __builtin_strlen ("read"), __s2_len < 4) ? (__builtin_constant_p
(name) && ((size_t)(const void *)((name) + 1) - (size_t
)(const void *)(name) == 1) ? __builtin_strcmp (name, "read")
: -(__extension__ ({ const unsigned char *__s2 = (const unsigned
char *) (const char *) (name); int __result = (((const unsigned
char *) (const char *) ("read"))[0] - __s2[0]); if (__s2_len
> 0 && __result == 0) { __result = (((const unsigned
char *) (const char *) ("read"))[1] - __s2[1]); if (__s2_len
> 1 && __result == 0) { __result = (((const unsigned
char *) (const char *) ("read"))[2] - __s2[2]); if (__s2_len
> 2 && __result == 0) __result = (((const unsigned
char *) (const char *) ("read"))[3] - __s2[3]); } } __result
; }))) : __builtin_strcmp (name, "read")))); })
|| !strcmp(name, "write")__extension__ ({ size_t __s1_len, __s2_len; (__builtin_constant_p
(name) && __builtin_constant_p ("write") && (
__s1_len = __builtin_strlen (name), __s2_len = __builtin_strlen
("write"), (!((size_t)(const void *)((name) + 1) - (size_t)(
const void *)(name) == 1) || __s1_len >= 4) && (!(
(size_t)(const void *)(("write") + 1) - (size_t)(const void *
)("write") == 1) || __s2_len >= 4)) ? __builtin_strcmp (name
, "write") : (__builtin_constant_p (name) && ((size_t
)(const void *)((name) + 1) - (size_t)(const void *)(name) ==
1) && (__s1_len = __builtin_strlen (name), __s1_len <
4) ? (__builtin_constant_p ("write") && ((size_t)(const
void *)(("write") + 1) - (size_t)(const void *)("write") == 1
) ? __builtin_strcmp (name, "write") : (__extension__ ({ const
unsigned char *__s2 = (const unsigned char *) (const char *)
("write"); int __result = (((const unsigned char *) (const char
*) (name))[0] - __s2[0]); if (__s1_len > 0 && __result
== 0) { __result = (((const unsigned char *) (const char *) (
name))[1] - __s2[1]); if (__s1_len > 1 && __result
== 0) { __result = (((const unsigned char *) (const char *) (
name))[2] - __s2[2]); if (__s1_len > 2 && __result
== 0) __result = (((const unsigned char *) (const char *) (name
))[3] - __s2[3]); } } __result; }))) : (__builtin_constant_p (
"write") && ((size_t)(const void *)(("write") + 1) - (
size_t)(const void *)("write") == 1) && (__s2_len = __builtin_strlen
("write"), __s2_len < 4) ? (__builtin_constant_p (name) &&
((size_t)(const void *)((name) + 1) - (size_t)(const void *)
(name) == 1) ? __builtin_strcmp (name, "write") : -(__extension__
({ const unsigned char *__s2 = (const unsigned char *) (const
char *) (name); int __result = (((const unsigned char *) (const
char *) ("write"))[0] - __s2[0]); if (__s2_len > 0 &&
__result == 0) { __result = (((const unsigned char *) (const
char *) ("write"))[1] - __s2[1]); if (__s2_len > 1 &&
__result == 0) { __result = (((const unsigned char *) (const
char *) ("write"))[2] - __s2[2]); if (__s2_len > 2 &&
__result == 0) __result = (((const unsigned char *) (const char
*) ("write"))[3] - __s2[3]); } } __result; }))) : __builtin_strcmp
(name, "write")))); })
) {
1998 struct gpu_array_ref_group *group = p;
1999 return create_access_leaf(data->kernel, group, node, build);
2000 }
2001 if (!is_sync)
2002 isl_die(data->prog->ctx, isl_error_internal,do { isl_handle_error(data->prog->ctx, isl_error_internal
, "unknown statement type", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/polly/lib/External/ppcg/gpu.c"
, 2004); return isl_ast_node_free(node); } while (0)
2003 "unknown statement type",do { isl_handle_error(data->prog->ctx, isl_error_internal
, "unknown statement type", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/polly/lib/External/ppcg/gpu.c"
, 2004); return isl_ast_node_free(node); } while (0)
2004 return isl_ast_node_free(node))do { isl_handle_error(data->prog->ctx, isl_error_internal
, "unknown statement type", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/polly/lib/External/ppcg/gpu.c"
, 2004); return isl_ast_node_free(node); } while (0)
;
2005 return create_sync_leaf(data->kernel, node, build);
2006}
2007
2008/* Given a set of wrapped references "ref", return the corresponding
2009 * access relations based on the tagged access relations "tagged".
2010 *
2011 * The elements of "ref" are of the form
2012 *
2013 * [D -> R]
2014 *
2015 * with D an iteration domains and R a reference.
2016 * The elements of "tagged" are of the form
2017 *
2018 * [D -> R] -> A
2019 *
2020 * with A an array.
2021 *
2022 * Extend "tagged" to include the iteration domain in the range, i.e.,
2023 *
2024 * [D -> R] -> [D -> A]
2025 *
2026 * apply the result to "ref" and then unwrap the resulting set
2027 * to obtain relations of the form
2028 *
2029 * D -> A
2030 */
2031static __isl_give isl_union_map *wrapped_reference_to_access(
2032 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
2033{
2034 isl_union_map *tag2access;
2035
2036 tag2access = isl_union_map_copy(tagged);
2037 tag2access = isl_union_map_universe(tag2access);
2038 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
2039 tag2access = isl_union_map_domain_map(tag2access);
2040 tag2access = isl_union_map_range_product(tag2access, tagged);
2041
2042 ref = isl_union_set_coalesce(ref);
2043 ref = isl_union_set_apply(ref, tag2access);
2044
2045 return isl_union_set_unwrap(ref);
2046}
2047
2048/* Given an access relation "access" from one or more array reference groups,
2049 * remove those reads if ("read" is 1) or writes (if "read" is 0)
2050 * that are only needed to communicate data within
2051 * the same iteration of "sched".
2052 * "tagged" contains all tagged access relations to all
2053 * the array reference groups accessed by "access" from statement
2054 * instances scheduled by "sched".
2055 *
2056 * If the access is a read then it is either an element of
2057 *
2058 * live_in union (range flow)
2059 *
2060 * where live_in and flow may be overapproximations, or
2061 * it reads an uninitialized value (that is not live-in because
2062 * there is an intermediate kill) or it reads a value that was
2063 * written within the same (compound) statement instance.
2064 * If the access is a write then it is either an element of
2065 *
2066 * live_out union (domain flow)
2067 *
2068 * or it writes a value that is never read (and is not live-out
2069 * because of an intermediate kill) or only
2070 * within the same (compound) statement instance.
2071 * In both cases, the access relation is also a subset of
2072 * the group access relation.
2073 *
2074 * The cases where an uninitialized value is read or a value is written
2075 * that is never read or where the dataflow occurs within a statement
2076 * instance are also considered local and may also be removed.
2077 *
2078 * Essentially, we compute the intersection of "access" with either
2079 *
2080 * live_in union (range non-local-flow)
2081 *
2082 * or
2083 *
2084 * live_out union (domain non-local-flow)
2085 *
2086 * We first construct a relation "local"
2087 *
2088 * [[D -> R] -> [D' -> R']]
2089 *
2090 * of pairs of domain iterations accessing the reference group
2091 * and references in the group that are coscheduled by "sched".
2092 *
2093 * If this relation does not intersect the dataflow dependences,
2094 * then there is nothing we can possibly remove, unless the dataflow
2095 * dependences themselves only relate a subset of the accesses.
2096 * In particular, the accesses may not be involved in any dataflow
2097 * dependences, either because they are uninitialized reads/dead writes
2098 * or because the dataflow occurs inside a statement instance.
2099 *
2100 * Since the computation below may break up the access relation
2101 * into smaller pieces, we only perform the intersection with
2102 * the non-local dependent accesses if the local pairs
2103 * intersect the dataflow dependences. Otherwise, we intersect
2104 * with the universe of the non-local dependent accesses.
2105 * This should at least remove accesses from statements that
2106 * do not participate in any dependences.
2107 *
2108 * In particular, we remove the "local" dataflow dependences from
2109 * the set of all dataflow dependences, or at least those
2110 * that may contribute to a domain/range that intersects
2111 * the domain of "access".
2112 * Note that if the potential dataflow dependences are an overapproximation
2113 * of the actual dataflow dependences, then the result remains an
2114 * overapproximation of the non-local dataflow dependences.
2115 * Copying to/from global memory is only needed for the references
2116 * in the domain/range of the result or for accesses that are live out/in
2117 * for the entire scop.
2118 *
2119 * We therefore map the domain/range of the "external" relation
2120 * to the corresponding access relation and take the union with
2121 * the live out/in relation.
2122 */
2123static __isl_give isl_union_map *remove_local_accesses(
2124 struct gpu_prog *prog, __isl_take isl_union_map *tagged,
2125 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2126 int read)
2127{
2128 int empty;
2129 isl_union_pw_multi_aff *tagger;
2130 isl_union_set *domain, *access_domain;
2131 isl_union_map *local, *external, *universe;
2132 isl_union_set *tag_set;
2133
2134 if (isl_union_map_is_empty(access)) {
2135 isl_union_map_free(sched);
2136 isl_union_map_free(tagged);
2137 return access;
2138 }
2139
2140 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2141 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2142 tagger = isl_union_pw_multi_aff_intersect_domain(tagger,
2143 isl_union_set_copy(domain));
2144 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2145
2146 local = isl_union_map_apply_range(sched,
2147 isl_union_map_reverse(isl_union_map_copy(sched)));
2148 local = isl_union_map_intersect(local,
2149 isl_union_map_copy(prog->scop->tagged_dep_flow));
2150
2151 empty = isl_union_map_is_empty(local);
2152
2153 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2154 universe = isl_union_map_universe(isl_union_map_copy(access));
2155 access_domain = isl_union_map_domain(universe);
2156 domain = isl_union_set_universe(domain);
2157 universe = isl_union_set_unwrap(domain);
2158 universe = isl_union_map_intersect_domain(universe, access_domain);
2159 domain = isl_union_map_wrap(universe);
2160 if (read)
2161 external = isl_union_map_intersect_range(external, domain);
2162 else
2163 external = isl_union_map_intersect_domain(external, domain);
2164 external = isl_union_map_intersect_params(external,
2165 isl_set_copy(prog->scop->context));
2166 external = isl_union_map_subtract(external, local);
2167
2168 if (read) {
2169 tag_set = isl_union_map_range(external);
2170 external = wrapped_reference_to_access(tag_set, tagged);
2171 external = isl_union_map_union(external,
2172 isl_union_map_copy(prog->scop->live_in));
2173 } else {
2174 tag_set = isl_union_map_domain(external);
2175 external = wrapped_reference_to_access(tag_set, tagged);
2176 external = isl_union_map_union(external,
2177 isl_union_map_copy(prog->scop->live_out));
2178 }
2179
2180 if (empty < 0)
2181 external = isl_union_map_free(external);
2182 else if (empty)
2183 external = isl_union_map_universe(external);
2184
2185 access = isl_union_map_intersect(access, external);
2186
2187 return access;
2188}
2189
2190/* Given an access relation "access" from "group", remove those reads
2191 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2192 * communicate data within the same iteration of the schedule at the
2193 * position where the copying of the group is inserted.
2194 * "node" points to this position, i.e., the depth at "node"
2195 * is equal to group->depth.
2196 *
2197 * We extract a schedule that picks out the iterations of the outer
2198 * group->depth dimensions and call remove_local_accesses.
2199 */
2200static __isl_give isl_union_map *remove_local_accesses_group(
2201 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2202 __isl_take isl_union_map *access, __isl_keep isl_schedule_node *node,
2203 int read)
2204{
2205 isl_union_map *sched, *tagged;
2206
2207 if (isl_union_map_is_empty(access))
2208 return access;
2209
2210 tagged = group_tagged_access_relation(group);
2211 sched = isl_schedule_node_get_prefix_schedule_relation(node);
2212
2213 return remove_local_accesses(kernel->prog, tagged, access, sched, read);
2214}
2215
2216/* This function is called before the AST generator starts traversing
2217 * the schedule subtree of a node with mark "mark".
2218 *
2219 * If the mark is called "kernel", store the kernel pointer in data->kernel
2220 * for use in at_domain.
2221 */
2222static int before_mark(__isl_keep isl_id *mark,
2223 __isl_keep isl_ast_build *build, void *user)
2224{
2225 struct ppcg_at_domain_data *data = user;
2226
2227 if (!mark)
2228 return -1;
2229 if (!strcmp(isl_id_get_name(mark), "kernel")__extension__ ({ size_t __s1_len, __s2_len; (__builtin_constant_p
(isl_id_get_name(mark)) && __builtin_constant_p ("kernel"
) && (__s1_len = __builtin_strlen (isl_id_get_name(mark
)), __s2_len = __builtin_strlen ("kernel"), (!((size_t)(const
void *)((isl_id_get_name(mark)) + 1) - (size_t)(const void *
)(isl_id_get_name(mark)) == 1) || __s1_len >= 4) &&
(!((size_t)(const void *)(("kernel") + 1) - (size_t)(const void
*)("kernel") == 1) || __s2_len >= 4)) ? __builtin_strcmp (
isl_id_get_name(mark), "kernel") : (__builtin_constant_p (isl_id_get_name
(mark)) && ((size_t)(const void *)((isl_id_get_name(mark
)) + 1) - (size_t)(const void *)(isl_id_get_name(mark)) == 1)
&& (__s1_len = __builtin_strlen (isl_id_get_name(mark
)), __s1_len < 4) ? (__builtin_constant_p ("kernel") &&
((size_t)(const void *)(("kernel") + 1) - (size_t)(const void
*)("kernel") == 1) ? __builtin_strcmp (isl_id_get_name(mark)
, "kernel") : (__extension__ ({ const unsigned char *__s2 = (
const unsigned char *) (const char *) ("kernel"); int __result
= (((const unsigned char *) (const char *) (isl_id_get_name(
mark)))[0] - __s2[0]); if (__s1_len > 0 && __result
== 0) { __result = (((const unsigned char *) (const char *) (
isl_id_get_name(mark)))[1] - __s2[1]); if (__s1_len > 1 &&
__result == 0) { __result = (((const unsigned char *) (const
char *) (isl_id_get_name(mark)))[2] - __s2[2]); if (__s1_len
> 2 && __result == 0) __result = (((const unsigned
char *) (const char *) (isl_id_get_name(mark)))[3] - __s2[3]
); } } __result; }))) : (__builtin_constant_p ("kernel") &&
((size_t)(const void *)(("kernel") + 1) - (size_t)(const void
*)("kernel") == 1) && (__s2_len = __builtin_strlen (
"kernel"), __s2_len < 4) ? (__builtin_constant_p (isl_id_get_name
(mark)) && ((size_t)(const void *)((isl_id_get_name(mark
)) + 1) - (size_t)(const void *)(isl_id_get_name(mark)) == 1)
? __builtin_strcmp (isl_id_get_name(mark), "kernel") : -(__extension__
({ const unsigned char *__s2 = (const unsigned char *) (const
char *) (isl_id_get_name(mark)); int __result = (((const unsigned
char *) (const char *) ("kernel"))[0] - __s2[0]); if (__s2_len
> 0 && __result == 0) { __result = (((const unsigned
char *) (const char *) ("kernel"))[1] - __s2[1]); if (__s2_len
> 1 && __result == 0) { __result = (((const unsigned
char *) (const char *) ("kernel"))[2] - __s2[2]); if (__s2_len
> 2 && __result == 0) __result = (((const unsigned
char *) (const char *) ("kernel"))[3] - __s2[3]); } } __result
; }))) : __builtin_strcmp (isl_id_get_name(mark), "kernel")))
); })
)
2230 data->kernel = isl_id_get_user(mark);
2231 return 0;
2232}
2233
2234/* This function is called after the AST generator has finished traversing
2235 * the schedule subtree of a mark node. "node" points to the corresponding
2236 * mark AST node.
2237 *
2238 * If the mark is called "kernel", then replace "node" by a user node
2239 * that "calls" the kernel, representing the launch of the kernel.
2240 * The original "node" is stored inside the kernel object so that
2241 * it can be used to print the device code.
2242 * Note that this assumes that a kernel is only launched once.
2243 * Also clear data->kernel.
2244 */
2245static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2246 __isl_keep isl_ast_build *build, void *user)
2247{
2248 isl_ctx *ctx;
2249 isl_id *id;
2250 isl_ast_expr *expr;
2251 isl_ast_expr_list *list;
2252 struct ppcg_kernel *kernel;
2253 struct ppcg_at_domain_data *data = user;
2254
2255 ctx = isl_ast_node_get_ctx(node);
2256 id = isl_ast_node_mark_get_id(node);
2257 if (!id)
2258 return isl_ast_node_free(node);
2259 if (strcmp(isl_id_get_name(id), "kernel")__extension__ ({ size_t __s1_len, __s2_len; (__builtin_constant_p
(isl_id_get_name(id)) && __builtin_constant_p ("kernel"
) && (__s1_len = __builtin_strlen (isl_id_get_name(id
)), __s2_len = __builtin_strlen ("kernel"), (!((size_t)(const
void *)((isl_id_get_name(id)) + 1) - (size_t)(const void *)(
isl_id_get_name(id)) == 1) || __s1_len >= 4) && (!
((size_t)(const void *)(("kernel") + 1) - (size_t)(const void
*)("kernel") == 1) || __s2_len >= 4)) ? __builtin_strcmp (
isl_id_get_name(id), "kernel") : (__builtin_constant_p (isl_id_get_name
(id)) && ((size_t)(const void *)((isl_id_get_name(id)
) + 1) - (size_t)(const void *)(isl_id_get_name(id)) == 1) &&
(__s1_len = __builtin_strlen (isl_id_get_name(id)), __s1_len
< 4) ? (__builtin_constant_p ("kernel") && ((size_t
)(const void *)(("kernel") + 1) - (size_t)(const void *)("kernel"
) == 1) ? __builtin_strcmp (isl_id_get_name(id), "kernel") : (
__extension__ ({ const unsigned char *__s2 = (const unsigned char
*) (const char *) ("kernel"); int __result = (((const unsigned
char *) (const char *) (isl_id_get_name(id)))[0] - __s2[0]);
if (__s1_len > 0 && __result == 0) { __result = (
((const unsigned char *) (const char *) (isl_id_get_name(id))
)[1] - __s2[1]); if (__s1_len > 1 && __result == 0
) { __result = (((const unsigned char *) (const char *) (isl_id_get_name
(id)))[2] - __s2[2]); if (__s1_len > 2 && __result
== 0) __result = (((const unsigned char *) (const char *) (isl_id_get_name
(id)))[3] - __s2[3]); } } __result; }))) : (__builtin_constant_p
("kernel") && ((size_t)(const void *)(("kernel") + 1
) - (size_t)(const void *)("kernel") == 1) && (__s2_len
= __builtin_strlen ("kernel"), __s2_len < 4) ? (__builtin_constant_p
(isl_id_get_name(id)) && ((size_t)(const void *)((isl_id_get_name
(id)) + 1) - (size_t)(const void *)(isl_id_get_name(id)) == 1
) ? __builtin_strcmp (isl_id_get_name(id), "kernel") : -(__extension__
({ const unsigned char *__s2 = (const unsigned char *) (const
char *) (isl_id_get_name(id)); int __result = (((const unsigned
char *) (const char *) ("kernel"))[0] - __s2[0]); if (__s2_len
> 0 && __result == 0) { __result = (((const unsigned
char *) (const char *) ("kernel"))[1] - __s2[1]); if (__s2_len
> 1 && __result == 0) { __result = (((const unsigned
char *) (const char *) ("kernel"))[2] - __s2[2]); if (__s2_len
> 2 && __result == 0) __result = (((const unsigned
char *) (const char *) ("kernel"))[3] - __s2[3]); } } __result
; }))) : __builtin_strcmp (isl_id_get_name(id), "kernel"))));
})
|| !data->kernel) {
2260 isl_id_free(id);
2261 return node;
2262 }
2263 kernel = data->kernel;
2264 data->kernel = NULL((void*)0);
2265 kernel->space = isl_ast_build_get_schedule_space(build);
2266 kernel->tree = isl_ast_node_mark_get_node(node);
2267 isl_ast_node_free(node);
2268
2269 expr = isl_ast_expr_from_id(isl_id_copy(id));
2270 list = isl_ast_expr_list_alloc(ctx, 0);
2271 expr = isl_ast_expr_call(expr, list);
2272 node = isl_ast_node_alloc_user(expr);
2273 node = isl_ast_node_set_annotation(node, id);
2274
2275 return node;
2276}
2277
2278static isl_bool update_depth(__isl_keep isl_schedule_node *node, void *user)
2279{
2280 int *depth = user;
2281 int node_depth;
2282
2283 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2284 return isl_bool_true;
2285 node_depth = isl_schedule_node_get_schedule_depth(node);
2286 if (node_depth > *depth)
2287 *depth = node_depth;
2288
2289 return isl_bool_false;
2290}
2291
2292/* Use isl to generate code for both the host and the device
2293 * from "schedule".
2294 * The device code is marked by "kernel" mark nodes in the schedule tree,
2295 * containing a pointer to a ppcg_kernel object.
2296 * The returned AST only contains the AST for the host code.
2297 * The ASTs for the device code are embedded in ppcg_kernel objects
2298 * attached to the leaf nodes that call "kernel".
2299 */
2300__isl_give isl_ast_node *generate_code(struct gpu_gen *gen,
2301 __isl_take isl_schedule *schedule)
2302{
2303 struct ppcg_at_domain_data data;
2304 isl_ast_build *build;
2305 isl_ast_node *tree;
2306 isl_id_list *iterators;
2307 int depth;
2308
2309 data.prog = gen->prog;
2310 data.gen = gen;
2311 data.kernel = NULL((void*)0);
2312
2313 depth = 0;
2314 if (isl_schedule_foreach_schedule_node_top_down(schedule, &update_depth,
2315 &depth) < 0)
2316 return NULL((void*)0);
2317 build = isl_ast_build_alloc(gen->prog->ctx);
2318 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2319 build = isl_ast_build_set_iterators(build, iterators);
2320 build = isl_ast_build_set_at_each_domain(build, &at_domain, &data);
2321 build = isl_ast_build_set_before_each_mark(build, &before_mark, &data);
2322 build = isl_ast_build_set_after_each_mark(build, &after_mark, &data);
2323 if (gen->prog->scop->options->debug->dump_final_schedule)
2324 isl_schedule_dump(schedule);
2325 tree = isl_ast_build_node_from_schedule(build, schedule);
2326 isl_ast_build_free(build);
2327
2328 return tree;
2329}
2330
2331__isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2332{
2333 if (!str)
2334 return NULL((void*)0);
2335 return isl_union_map_read_from_str(ctx, str);
2336}
2337
2338/* Can "node" be tiled and then mapped to block and thread identifiers?
2339 * That is, is it permutable with at least one coincident dimension?
2340 */
2341static int is_permutable(__isl_keep isl_schedule_node *node)
2342{
2343 if (!node)
2344 return -1;
2345
2346 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
2347 return 0;
2348 if (!isl_schedule_node_band_get_permutable(node))
2349 return 0;
2350 if (isl_schedule_node_band_n_member(node) < 1)
2351 return 0;
2352 if (!isl_schedule_node_band_member_get_coincident(node, 0))
2353 return 0;
2354
2355 return 1;
2356}
2357
2358/* A isl_schedule_foreach_schedule_node_top_down callback
2359 * for setting *any_permutable and aborting the search
2360 * if "node" is a permutable band with coincident dimensions.
2361 * Otherwise, continue searching.
2362 */
2363static isl_bool set_permutable(__isl_keep isl_schedule_node *node, void *user)
2364{
2365 int *any_permutable = user;
2366 int permutable;
2367
2368 permutable = is_permutable(node);
2369 if (permutable < 0)
2370 return isl_bool_error;
2371 if (!permutable)
2372 return isl_bool_true;
2373
2374 *any_permutable = 1;
2375
2376 return isl_bool_error;
2377}
2378
2379/* Does "schedule" contain any permutable band with at least one coincident
2380 * member?
2381 */
2382int has_any_permutable_node(__isl_keep isl_schedule *schedule)
2383{
2384 int any_permutable = 0;
2385
2386 if (isl_schedule_foreach_schedule_node_top_down(schedule,
2387 &set_permutable, &any_permutable) < 0 &&
2388 !any_permutable)
2389 return -1;
2390
2391 return any_permutable;
2392}
2393
2394/* Is "node" a leaf or can it be tiled and then mapped to
2395 * block and thread identifiers?
2396 */
2397static int is_leaf_or_tilable(__isl_keep isl_schedule_node *node)
2398{
2399 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
2400 return 1;
2401 return is_permutable(node);
2402}
2403
2404/* Is "node" the outermost node in its branch that can be tiled
2405 * and then mapped to block and thread identifiers?
2406 * If there are no such nodes in the branch and if "node" is a leaf,
2407 * then it is accepted too.
2408 */
2409static int is_outer_tilable(__isl_keep isl_schedule_node *node)
2410{
2411 int tilable;
2412 isl_schedule_node *ancestor;
2413
2414 tilable = is_leaf_or_tilable(node);
2415 if (tilable < 0)
2416 return -1;
2417 if (!tilable)
2418 return 0;
2419
2420 tilable = 0;
2421 ancestor = isl_schedule_node_copy(node);
2422 while (isl_schedule_node_has_parent(ancestor)) {
2423 ancestor = isl_schedule_node_parent(ancestor);
2424
2425 tilable = is_permutable(ancestor);
2426 if (tilable < 0 || tilable)
2427 break;
2428 }
2429
2430 isl_schedule_node_free(ancestor);
2431 return tilable < 0 ? -1 : !tilable;
2432}
2433
2434/* Collect the references to all writes in "group".
2435 * Each reference is represented by a universe set in a space
2436 *
2437 * [S[i,j] -> R[]]
2438 *
2439 * with S[i,j] the statement instance space and R[] the array reference.
2440 */
2441static __isl_give isl_union_set *group_tagged_writes(
2442 struct gpu_array_ref_group *group)
2443{
2444 int i;
2445 isl_space *space;
2446 isl_union_set *writes;
2447
2448 space = isl_map_get_space(group->access);
2449 writes = isl_union_set_empty(space);
2450 for (i = 0; i < group->n_ref; ++i) {
2451 isl_space *space;
2452 isl_set *writes_i;
2453
2454 if (!group->refs[i]->write)
2455 continue;
2456
2457 space = isl_map_get_space(group->refs[i]->tagged_access);
2458 space = isl_space_domain(space);
2459 writes_i = isl_set_universe(space);
2460 writes = isl_union_set_add_set(writes, writes_i);
2461 }
2462
2463 return writes;
2464}
2465
2466/* Is there any write access in "group" that requires synchronization
2467 * on a write to global memory?
2468 * We currently take into account all writes that would require
2469 * synchronization at the thread level depth, but if the copying
2470 * for this group is performed at an outer level, then we do not
2471 * actually need to take into account dependences at intermediate levels.
2472 */
2473static int any_sync_writes_in_group(struct ppcg_kernel *kernel,
2474 struct gpu_array_ref_group *group)
2475{
2476 isl_union_set *writes;
2477 int empty, disjoint;
2478
2479 empty = isl_union_set_is_empty(kernel->sync_writes);
2480 if (empty < 0)
2481 return -1;
2482 if (empty)
2483 return 0;
2484
2485 writes = group_tagged_writes(group);
2486 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2487 isl_union_set_free(writes);
2488
2489 return disjoint < 0 ? -1 : !disjoint;
2490}
2491
2492/* Collect the references to all writes in "kernel" that write directly
2493 * to global or shared memory, i.e., that are not mapped to private memory.
2494 * Each reference is represented by a universe set in a space
2495 *
2496 * [S[i,j] -> R[]]
2497 *
2498 * with S[i,j] the statement instance space and R[] the array reference.
2499 */
2500static __isl_give isl_union_set *collect_non_private_tagged_writes(
2501 struct ppcg_kernel *kernel)
2502{
2503 isl_union_set *writes;
2504 int i, j;
2505
2506 writes = isl_union_set_empty(isl_union_set_get_space(kernel->arrays));
2507
2508 for (i = 0; i < kernel->n_array; ++i) {
2509 struct gpu_local_array_info *array = &kernel->array[i];
2510
2511 for (j = 0; j < array->n_group; ++j) {
2512 struct gpu_array_ref_group *group = array->groups[j];
2513 isl_union_set *writes_ij;
2514
2515 if (!group->write)
2516 continue;
2517 if (group->private_tile)
2518 continue;
2519 writes_ij = group_tagged_writes(group);
2520 writes = isl_union_set_union(writes, writes_ij);
2521 }
2522 }
2523
2524 return writes;
2525}
2526
2527/* Are there any direct writes to global memory that require
2528 * synchronization?
2529 */
2530static int any_global_or_shared_sync_writes(struct ppcg_kernel *kernel)
2531{
2532 isl_union_set *writes;
2533 int empty, disjoint;
2534
2535 empty = isl_union_set_is_empty(kernel->sync_writes);
2536 if (empty < 0)
2537 return -1;
2538 if (empty)
2539 return 0;
2540
2541 writes = collect_non_private_tagged_writes(kernel);
2542 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2543 isl_union_set_free(writes);
2544
2545 return disjoint < 0 ? -1 : !disjoint;
2546}
2547
2548/* Construct an isl_multi_val for use as tile sizes for tiling "node"
2549 * from the elements in "tile_size".
2550 */
2551static __isl_give isl_multi_val *construct_band_tiles_sizes(
2552 __isl_keep isl_schedule_node *node, int *tile_size)
2553{
2554 int i, n;
2555 isl_ctx *ctx;
2556 isl_space *space;
2557 isl_multi_val *mv;
2558
2559 if (!node)
2560 return NULL((void*)0);
2561
2562 ctx = isl_schedule_node_get_ctx(node);
2563 space = isl_schedule_node_band_get_space(node);
2564 n = isl_schedule_node_band_n_member(node);
2565 mv = isl_multi_val_zero(space);
2566 for (i = 0; i < n; ++i) {
2567 isl_val *v;
2568
2569 v = isl_val_int_from_si(ctx, tile_size[i]);
2570 mv = isl_multi_val_set_val(mv, i, v);
2571 }
2572
2573 return mv;
2574}
2575
2576/* Replace the partial schedule S of the band node "node" by
2577 *
2578 * floor(S/f)
2579 *
2580 * or
2581 *
2582 * f * floor(S/f)
2583 *
2584 * if scale_tile_loops is set, with f the integers in "factor".
2585 * The list that "factor" points to is assumed to contain at least
2586 * as many elements as the number of members in the band.
2587 */
2588static __isl_give isl_schedule_node *snap_band_to_sizes(
2589 __isl_take isl_schedule_node *node, int *factor,
2590 struct ppcg_options *options)
2591{
2592 isl_multi_val *mv;
2593
2594 mv = construct_band_tiles_sizes(node, factor);
2595 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2596 if (options->scale_tile_loops)
2597 node = isl_schedule_node_band_scale(node,
2598 isl_multi_val_copy(mv));
2599 isl_multi_val_free(mv);
2600
2601 return node;
2602}
2603
2604/* Tile "band" with tile size specified by "sizes".
2605 *
2606 * Since the tile loops will be mapped to block ids, we forcibly
2607 * turn off tile loop scaling. We may want to enable tile loop scaling
2608 * at some later point, but then we would have to support the detection
2609 * of strides during the mapping to block ids.
2610 * Similarly, since the point loops will be mapped to thread ids,
2611 * we forcibly shift the point loops so that they start at zero.
2612 */
2613static __isl_give isl_schedule_node *tile_band(
2614 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2615{
2616 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2617 int scale_tile;
2618 int shift_point;
2619
2620 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2621 isl_options_set_tile_scale_tile_loops(ctx, 0);
2622 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2623 isl_options_set_tile_shift_point_loops(ctx, 1);
2624
2625 node = isl_schedule_node_band_tile(node, sizes);
2626
2627 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2628 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2629
2630 return node;
2631}
2632
2633/* Extract the set of parameter values and outer schedule dimensions
2634 * for which any statement instance
2635 * in the kernel inserted at "node" needs to be executed.
2636 * Intersect the set of parameter values derived from the host schedule
2637 * relation with the context of "prog".
2638 */
2639static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2640 struct gpu_prog *prog)
2641{
2642 isl_union_map *schedule;
2643 isl_union_set *schedule_domain;
2644 isl_set *context;
2645 int empty;
2646
2647 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2648 schedule_domain = isl_union_map_range(schedule);
2649 empty = isl_union_set_is_empty(schedule_domain);
2650 if (empty < 0) {
2651 isl_union_set_free(schedule_domain);
2652 return NULL((void*)0);
2653 }
2654 if (empty) {
2655 int depth;
2656 isl_space *space;
2657
2658 space = isl_union_set_get_space(schedule_domain);
2659 isl_union_set_free(schedule_domain);
2660 space = isl_space_set_from_params(space);
2661 depth = isl_schedule_node_get_schedule_depth(node);
2662 space = isl_space_add_dims(space, isl_dim_set, depth);
2663 context = isl_set_empty(space);
2664 } else {
2665 context = isl_set_from_union_set(schedule_domain);
2666 }
2667 context = isl_set_intersect_params(context,
2668 isl_set_copy(prog->context));
2669
2670 return context;
2671}
2672
2673/* Return the set of outer array elements accessed by
2674 * by the statement instance in "domain" in "prog".
2675 */
2676static __isl_give isl_union_set *accessed_by_domain(
2677 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2678{
2679 isl_union_map *access;
2680 isl_union_set *arrays;
2681
2682 access = isl_union_map_union(isl_union_map_copy(prog->read),
2683 isl_union_map_copy(prog->may_write));
2684 access = isl_union_map_intersect_domain(access, domain);
2685 arrays = isl_union_map_range(access);
2686 arrays = isl_union_set_apply(arrays,
2687 isl_union_map_copy(prog->to_outer));
2688
2689 return arrays;
2690}
2691
2692/* Return the number of outer band members of the band node "node"
2693 * that are marked coincident.
2694 */
2695static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2696{
2697 int i, n;
2698
2699 n = isl_schedule_node_band_n_member(node);
2700
2701 for (i = 0; i < n; ++i)
2702 if (!isl_schedule_node_band_member_get_coincident(node, i))
2703 break;
2704
2705 return i;
2706}
2707
2708/* If the band node "node" has more than "n" members, then split off
2709 * the first "n" of them.
2710 */
2711static __isl_give isl_schedule_node *split_band(
2712 __isl_take isl_schedule_node *node, int n)
2713{
2714 int dim;
2715
2716 dim = isl_schedule_node_band_n_member(node);
2717 if (n < dim)
2718 node = isl_schedule_node_band_split(node, n);
2719
2720 return node;
2721}
2722
2723/* Scale a band node that may have been split by split_band.
2724 * "sizes" are the scaling factors for the original node.
2725 * "node" either points to the original band node, or the outer
2726 * of the two pieces after splitting.
2727 *
2728 * If the number of elements in "node" is smaller than the number of
2729 * elements in "sizes", then some splitting has occurred and we split
2730 * "sizes" in the same way.
2731 */
2732static __isl_give isl_schedule_node *scale_band(
2733 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2734{
2735 int n, dim;
2736
2737 n = isl_multi_val_dim(sizes, isl_dim_set);
2738 dim = isl_schedule_node_band_n_member(node);
2739 if (n > dim) {
2740 isl_multi_val *sizes2;
2741
2742 sizes2 = isl_multi_val_copy(sizes);
2743 sizes = isl_multi_val_drop_dims(sizes,
2744 isl_dim_set, dim, n - dim);
2745 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2746 node = isl_schedule_node_child(node, 0);
2747 node = isl_schedule_node_band_scale(node, sizes2);
2748 node = isl_schedule_node_parent(node);
2749 }
2750
2751 return isl_schedule_node_band_scale(node, sizes);
2752}
2753
2754/* Return an isl_multi_aff, with as elements the parameters in "space"
2755 * that have the names specified by the elements in "names".
2756 * If (some of) these parameters do not already appear in "space",
2757 * then they are added first.
2758 */
2759static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2760 __isl_keep isl_id_list *names)
2761{
2762 int i, n;
2763 isl_local_space *ls;
2764 isl_multi_aff *ma;
2765
2766 if (!names)
2767 space = isl_space_free(space);
2768
2769 n = isl_id_list_n_id(names);
2770 for (i = 0; i < n; ++i) {
2771 int pos;
2772 isl_id *id;
2773
2774 id = isl_id_list_get_id(names, i);
2775 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2776 if (pos >= 0) {
2777 isl_id_free(id);
2778 continue;
2779 }
2780 pos = isl_space_dim(space, isl_dim_param);
2781 space = isl_space_add_dims(space, isl_dim_param, 1);
2782 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2783 }
2784 ma = isl_multi_aff_zero(isl_space_copy(space));
2785 ls = isl_local_space_from_space(isl_space_domain(space));
2786 for (i = 0; i < n; ++i) {
2787 int pos;
2788 isl_id *id;
2789 isl_aff *aff;
2790
2791 id = isl_id_list_get_id(names, i);
2792 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2793 isl_id_free(id);
2794 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2795 isl_dim_param, pos);
2796 ma = isl_multi_aff_set_aff(ma, i, aff);
2797 }
2798 isl_local_space_free(ls);
2799
2800 return ma;
2801}
2802
2803/* Return constraints on the domain elements that equate a sequence of
2804 * parameters called "names", to the partial schedule
2805 * of "node" modulo the integers in "size".
2806 * The number of elements in the array "size" should be equal
2807 * to the number of elements in "names".
2808 * The number of members of the band node "node" should be smaller
2809 * than or equal to this number. If it is smaller, then the first
2810 * elements of "names" are equated to zero.
2811 */
2812static __isl_give isl_union_set *set_schedule_modulo(
2813 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
2814 int *size)
2815{
2816 int n, n_zero;
2817 isl_space *space;
2818 isl_multi_aff *ma;
2819 isl_multi_union_pw_aff *mupa, *mupa2;
2820 isl_multi_val *mv;
2821 isl_union_set *domain;
2822
2823 if (!node)
2824 return NULL((void*)0);
2825 n = isl_id_list_n_id(names);
2826 if (n == 0)
2827 return isl_schedule_node_get_universe_domain(node);
2828 n_zero = n - isl_schedule_node_band_n_member(node);
2829
2830 mupa = isl_schedule_node_band_get_partial_schedule(node);
2831 mv = construct_band_tiles_sizes(node, size + n_zero);
2832 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
2833
2834 space = isl_multi_union_pw_aff_get_space(mupa);
2835 space = isl_space_params(space);
2836 space = isl_space_set_from_params(space);
2837 space = isl_space_add_dims(space, isl_dim_set, n_zero);
2838 ma = isl_multi_aff_zero(space);
2839
2840 domain = isl_schedule_node_get_universe_domain(node);
2841 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
2842 isl_union_set_copy(domain), ma);
2843 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
2844
2845 space = isl_multi_union_pw_aff_get_space(mupa);
2846 ma = parameter_vector(space, names);
2847
2848 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
2849 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
2850
2851 return isl_multi_union_pw_aff_zero_union_set(mupa);
2852}
2853
2854/* Insert a context node at "node" introducing the block and thread
2855 * identifiers along with their bounds, which are stored in kernel->grid_size
2856 * and kernel->block_dim.
2857 * Note that the bounds on the block identifiers may implicitly impose
2858 * constraints on the parameters. A guard needs to be inserted
2859 * in the schedule tree to ensure that those bounds hold at "node".
2860 * This guard is inserted in insert_guard.
2861 */
2862static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
2863 __isl_take isl_schedule_node *node)
2864{
2865 isl_set *context;
2866
2867 context = isl_set_universe(isl_set_get_space(kernel->context));
2868
2869 context = add_bounded_parameters_dynamic(context,
2870 kernel->grid_size, kernel->block_ids);
2871 context = add_bounded_parameters(context,
2872 kernel->block_dim, kernel->thread_ids);
2873
2874 node = isl_schedule_node_insert_context(node, context);
2875
2876 return node;
2877}
2878
2879/* Insert a guard that eliminates kernel launches where the kernel
2880 * obviously does not have any work to do.
2881 *
2882 * In particular, eliminate kernel launches where there are obviously
2883 * zero blocks.
2884 * Use the same block size constraints that are used to create the context
2885 * to ensure that all constraints implicit in the constructed context
2886 * are imposed by the guard.
2887 *
2888 * Additionally, add other constraints that are valid
2889 * for each executed instance ("context"), as long as this does not result
2890 * in a disjunction.
2891 */
2892static __isl_give isl_schedule_node *insert_guard(
2893 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
2894 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
2895{
2896 unsigned nparam, n;
2897 isl_set *guard;
2898 isl_id_list *ids;
2899
2900 guard = isl_set_copy(context);
2901 guard = isl_set_compute_divs(guard);
2902 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
2903
2904 nparam = isl_set_dim(guard, isl_dim_param);
2905 n = isl_multi_pw_aff_dim(size, isl_dim_out);
2906 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
2907 guard = add_bounded_parameters_dynamic(guard, size, ids);
2908 isl_id_list_free(ids);
2909 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
2910
2911 node = isl_schedule_node_insert_guard(node, guard);
2912
2913 return node;
2914}
2915
2916/* Does any array reference group mapping require the band that is mapped
2917 * to threads to be unrolled?
2918 */
2919static int kernel_requires_unroll(struct ppcg_kernel *kernel)
2920{
2921 int i, j;
2922
2923 for (i = 0; i < kernel->n_array; ++i) {
2924 struct gpu_local_array_info *array = &kernel->array[i];
2925
2926 for (j = 0; j < array->n_group; ++j) {
2927 struct gpu_array_ref_group *group = array->groups[j];
2928 if (gpu_array_ref_group_requires_unroll(group))
2929 return 1;
2930 }
2931 }
2932
2933 return 0;
2934}
2935
2936/* Mark the given band node "node" for unrolling by the AST generator and
2937 * then sink it to the leaves of the schedule tree.
2938 * All dimensions of "node" are assumed to be coincident, such that this
2939 * sinking is a valid operation.
2940 */
2941static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
2942{
2943 int i, n;
2944
2945 n = isl_schedule_node_band_n_member(node);
2946 for (i = 0; i < n; ++i)
2947 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
2948 isl_ast_loop_unroll);
2949
2950 node = isl_schedule_node_band_sink(node);
2951
2952 return node;
2953}
2954
2955/* Insert a synchronization node in the schedule tree of "node"
2956 * after the core computation of "kernel" at the level of the band
2957 * that is mapped to threads, except if that level is equal to
2958 * that of the band that is mapped to blocks or if there are no writes
2959 * to global or shared memory in the core computation that require
2960 * synchronization.
2961 * If there are any writes to shared memory and the shared memory
2962 * copying is performed at the same level, then synchronization
2963 * is needed between the core and the copying anyway, so we might
2964 * as well add it here. If the copying is performed at a higher
2965 * level, then different iterations of intermediate schedule dimensions
2966 * may have a different mapping from between shared memory elements and
2967 * threads, such that synchronization is required after the core.
2968 * "node" is assumed to point to the kernel node.
2969 */
2970static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
2971 __isl_take isl_schedule_node *node)
2972{
2973 int kernel_depth;
2974 int need_sync;
2975
2976 need_sync = any_global_or_shared_sync_writes(kernel);
2977 if (need_sync < 0)
2978 return isl_schedule_node_free(node);
2979 if (!need_sync)
2980 return node;
2981
2982 kernel_depth = isl_schedule_node_get_schedule_depth(node);
2983
2984 node = gpu_tree_move_down_to_thread(node, kernel->core);
2985 if (kernel_depth == isl_schedule_node_get_schedule_depth(node))
2986 return gpu_tree_move_up_to_kernel(node);
2987
2988 node = gpu_tree_ensure_following_sync(node, kernel);
2989
2990 node = gpu_tree_move_up_to_kernel(node);
2991
2992 return node;
2993}
2994
2995/* Return a read ("read" is 1) or write access relation for "group"
2996 * with those accesses removed that are only needed to communicate data
2997 * within the subtree of the schedule rooted at "node".
2998 * Furthermore, include the prefix schedule at "node".
2999 * That is, return a relation of the form
3000 *
3001 * S -> [D -> A]
3002 *
3003 * with D the outer schedule dimensions at "node".
3004 */
3005static __isl_give isl_union_map *anchored_non_local_accesses(
3006 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3007 __isl_take isl_schedule_node *node, int read)
3008{
3009 isl_union_map *access;
3010 isl_union_map *prefix;
3011
3012 access = gpu_array_ref_group_access_relation(group, read, !read);
3013 access = remove_local_accesses_group(kernel, group, access, node, read);
3014 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
3015 access = isl_union_map_range_product(prefix, access);
3016
3017 return access;
3018}
3019
3020/* Given an array reference group "group", create a mapping
3021 *
3022 * read[D -> A] -> [D -> A]
3023 *
3024 * if "read" is set or
3025 *
3026 * write[D -> A] -> [D -> A]
3027 *
3028 * if "read" is not set.
3029 * D corresponds to the outer group->depth dimensions of
3030 * the kernel schedule.
3031 */
3032static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
3033 struct gpu_array_ref_group *group, int read)
3034{
3035 isl_space *space;
3036 isl_id *id;
3037
3038 space = isl_space_copy(group->array->space);
3039 space = isl_space_from_range(space);
3040 space = isl_space_add_dims(space, isl_dim_in, group->depth);
3041 space = isl_space_wrap(space);
3042 space = isl_space_map_from_set(space);
3043
3044 id = isl_id_alloc(ctx, read ? "read" : "write", group);
3045 space = isl_space_set_tuple_id(space, isl_dim_in, id);
3046
3047 return isl_multi_aff_identity(space);
3048}
3049
3050/* If any writes in "group" require synchronization, then make sure
3051 * that there is a synchronization node for "kernel" after the node
3052 * following "node" in a sequence.
3053 *
3054 * If "shared" is set and no synchronization is needed for
3055 * the writes to global memory, then add synchronization before
3056 * the kernel to protect shared memory from being overwritten
3057 * by the next iteration of the core computation.
3058 * No additional synchronization is needed to protect against
3059 * the next copy into shared memory because each element of
3060 * the shared memory tile is always copied by the same thread.
3061 */
3062static __isl_give isl_schedule_node *add_group_write_sync(
3063 __isl_take isl_schedule_node *node, struct ppcg_kernel *kernel,
3064 struct gpu_array_ref_group *group, int shared)
3065{
3066 int need_sync;
3067
3068 need_sync = any_sync_writes_in_group(kernel, group);
3069 if (need_sync < 0)
3070 return isl_schedule_node_free(node);
3071 if (need_sync) {
3072 node = isl_schedule_node_parent(node);
3073 node = isl_schedule_node_next_sibling(node);
3074 node = isl_schedule_node_child(node, 0);
3075 node = gpu_tree_ensure_following_sync(node, kernel);
3076 } else if (shared) {
3077 node = isl_schedule_node_parent(node);
3078 node = isl_schedule_node_parent(node);
3079 node = gpu_tree_move_down_to_depth(node, group->depth,
3080 kernel->core);
3081 node = gpu_tree_move_left_to_sync(node, kernel);
3082 }
3083
3084 return node;
3085}
3086
3087/* Add copy statements to the schedule tree of "node"
3088 * for reading from global memory to private memory (if "read" is set) or
3089 * for writing back from private memory to global memory
3090 * (if "read" is not set) for the array reference group "group" that
3091 * is mapped to private memory.
3092 * On input, "node" points to the kernel node, and it is moved
3093 * back there on output.
3094 *
3095 * The copies are performed in the order of the array elements.
3096 * The copy statement instances include a reference to the outer
3097 * group->depth dimensions of the kernel schedule for ease of
3098 * combining them with the group tiling.
3099 *
3100 * That is, the extra schedule is of the form
3101 *
3102 * type[D -> A] -> A
3103 *
3104 * where D corresponds to the outer group->depth dimensions of
3105 * the kernel schedule and A to the global array.
3106 * This schedule is unrolled because registers are not addressable.
3107 *
3108 * The copying is inserted in the schedule tree through an extension
3109 * of the form
3110 *
3111 * D -> type[D -> A]
3112 *
3113 * where the extra domain elements type[D -> A] are those accessed
3114 * by the group.
3115 * A filter is inserted on type[D -> A] to ensure that the element
3116 * is read/written by the same thread that needs the element.
3117 * This filter is obtained by applying
3118 *
3119 * S -> type[D -> A]
3120 *
3121 * to the thread filter for the core statements.
3122 *
3123 * The extension is inserted before the core computation in case of a read
3124 * and after the core computation in case of a write.
3125 * In the latter case, we also make sure that there is a synchronization
3126 * node after the write to global memory, unless this write is performed
3127 * at the outer level of the kernel.
3128 * In principle, this synchronization could be inserted higher
3129 * in the schedule tree depending on where the corresponding reads
3130 * from global memory are performed.
3131 */
3132static __isl_give isl_schedule_node *add_copies_group_private(
3133 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3134 __isl_take isl_schedule_node *node, int read)
3135{
3136 isl_union_map *access;
3137 isl_union_map *prefix;
3138 isl_union_set *domain;
3139 isl_space *space;
3140 isl_multi_aff *from_access;
3141 isl_multi_pw_aff *mpa;
3142 isl_multi_union_pw_aff *mupa;
3143 isl_schedule_node *graft;
3144 isl_union_set *filter;
3145 int kernel_depth;
3146 int empty;
3147
3148 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3149 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3150
3151 access = anchored_non_local_accesses(kernel, group, node, read);
3152 empty = isl_union_map_is_empty(access);
3153 if (empty < 0 || empty) {
3154 isl_union_map_free(access);
3155 if (empty < 0)
3156 return isl_schedule_node_free(node);
3157 return gpu_tree_move_up_to_kernel(node);
3158 }
3159
3160 group->array->global = 1;
3161 group->local_array->global = 1;
3162
3163 from_access = create_from_access(kernel->ctx, group, read);
3164 space = isl_space_domain(isl_multi_aff_get_space(from_access));
3165 access = isl_union_map_preimage_range_multi_aff(access, from_access);
3166
3167 filter = isl_union_set_copy(kernel->thread_filter);
3168 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
3169 filter = isl_union_set_detect_equalities(filter);
3170 filter = isl_union_set_coalesce(filter);
3171
3172 domain = isl_union_map_range(access);
3173 access = isl_union_set_wrapped_domain_map(domain);
3174 access = isl_union_map_reverse(access);
3175 access = isl_union_map_coalesce(access);
3176 graft = isl_schedule_node_from_extension(access);
3177
3178 space = isl_space_map_from_set(space);
3179 mpa = isl_multi_pw_aff_identity(space);
3180 mpa = isl_multi_pw_aff_range_factor_range(mpa);
3181 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3182
3183 graft = isl_schedule_node_child(graft, 0);
3184 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3185 graft = unroll(graft);
3186
3187 graft = isl_schedule_node_insert_filter(graft, filter);
3188
3189 graft = isl_schedule_node_parent(graft);
3190
3191 if (read)
3192 node = isl_schedule_node_graft_before(node, graft);
3193 else {
3194 node = isl_schedule_node_graft_after(node, graft);
3195 if (kernel_depth < group->depth)
3196 node = add_group_write_sync(node, kernel, group, 0);
3197 }
3198
3199 node = gpu_tree_move_up_to_kernel(node);
3200
3201 return node;
3202}
3203
3204/* Add copy statements to the schedule tree of "node"
3205 * for reading from global memory to shared memory (if "read" is set) or
3206 * for writing back from shared memory to global memory
3207 * (if "read" is not set) for the array reference group "group" that
3208 * is mapped to shared memory.
3209 * On input, "node" points to the kernel node, and it is moved
3210 * back there on output.
3211 *
3212 * The copies are performed in the order of the corresponding shared
3213 * memory tile.
3214 * The copy statement instances include a reference to the outer
3215 * group->depth dimensions of the kernel schedule for ease of
3216 * combining them with the group tiling.
3217 *
3218 * If we are performing a read from global memory to shared memory and
3219 * if the array involved is not a scalar, then we copy
3220 * the entire tile to shared memory. This may result in some extra
3221 * elements getting copied, but it should lead to simpler code
3222 * (which means that fewer registers may be needed) and less divergence.
3223 *
3224 * Otherwise, we only copy the elements that will be read or have been written
3225 * in the kernel.
3226 *
3227 * That is, the extra schedule is of the form
3228 *
3229 * type[D -> A] -> T
3230 *
3231 * where D corresponds to the outer group->depth dimensions of
3232 * the kernel schedule, A to the global array and T is the corresponding
3233 * shared memory tile.
3234 *
3235 * The copying is inserted in the schedule tree through an extension
3236 * of the form
3237 *
3238 * D -> type[D -> A]
3239 *
3240 * where the extra domain elements type[D -> A] are those accessed
3241 * by the group. In the case of read from a non-scalar, this set
3242 * is replaced by the entire shared memory tile.
3243 *
3244 * A filter is inserted on type[D -> A] to map the copy instances
3245 * to the threads. In particular, the thread identifiers are
3246 * equated to the position inside the shared memory tile (T)
3247 * modulo the block size.
3248 * We try to align the innermost tile dimension with the innermost
3249 * thread identifier (x) as a heuristic to improve coalescing.
3250 * In particular, if the dimension of the tile is greater than
3251 * the dimension of the block, then the schedule mapping to the tile
3252 * is broken up into two pieces and the filter is applied to the inner part.
3253 * If, on the other hand, the dimension of the tile is smaller than
3254 * the dimension of the block, then the initial thread identifiers
3255 * are equated to zero and the remaining thread identifiers are
3256 * matched to the memory tile.
3257 *
3258 * The extension is inserted before the core computation in case of a read
3259 * and after the core computation in case of a write.
3260 * In the case of a read, we first need to make sure there is some
3261 * synchronization before the core computation such that we can put the read
3262 * from global memory to shared memory before that synchronization.
3263 * This ensures that all threads have finished copying into shared memory
3264 * before the shared memory is used.
3265 * We also need to make sure that there is a synchronization node after
3266 * the core computation to ensure that the next load into shared memory
3267 * only happens after all data has been used. There is no need for
3268 * this synchronization if we are at the outer level since then there
3269 * won't be a next load.
3270 * In the case of a write, we need to make sure there is some synchronization
3271 * after the core computation such taht we can put the write from shared
3272 * memory to global memory after that synchronization.
3273 * Unless we are at the outer level, we also need a synchronization node
3274 * after the write to ensure the data is saved to global memory
3275 * before the next iteration write to the same shared memory.
3276 * It also makes sure the data has arrived in global memory before
3277 * it is read in a subsequent iteration.
3278 */
3279static __isl_give isl_schedule_node *add_copies_group_shared(
3280 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3281 __isl_take isl_schedule_node *node, int read)
3282{
3283 struct gpu_array_tile *tile;
3284 isl_union_map *access;
3285 isl_union_set *domain;
3286 isl_union_set *sync;
3287 isl_multi_aff *ma;
3288 isl_multi_aff *from_access;
3289 isl_multi_pw_aff *mpa;
3290 isl_multi_union_pw_aff *mupa;
3291 isl_schedule_node *graft;
3292 isl_union_set *filter;
3293 int skip;
3294 int kernel_depth;
3295 int empty;
3296
3297 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3298 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3299
3300 access = anchored_non_local_accesses(kernel, group, node, read);
3301 empty = isl_union_map_is_empty(access);
3302 if (empty < 0 || empty) {
3303 isl_union_map_free(access);
3304 if (empty < 0)
3305 return isl_schedule_node_free(node);
3306 return gpu_tree_move_up_to_kernel(node);
3307 }
3308
3309 group->array->global = 1;
3310 group->local_array->global = 1;
3311
3312 from_access = create_from_access(kernel->ctx, group, read);
3313
3314 tile = gpu_array_ref_group_tile(group);
3315 ma = isl_multi_aff_copy(tile->tiling);
3316 ma = isl_multi_aff_pullback_multi_aff(ma,
3317 isl_multi_aff_copy(from_access));
3318 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3319 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3320
3321 domain = isl_union_map_range(access);
3322
3323 if (read && !gpu_array_is_scalar(group->array)) {
3324 isl_map *map;
3325 isl_union_set_free(domain);
3326 map = group_tile(group);
3327 domain = isl_union_set_from_set(isl_map_wrap(map));
3328 }
3329
3330 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3331 access = isl_union_set_wrapped_domain_map(domain);
3332 access = isl_union_map_reverse(access);
3333 access = isl_union_map_coalesce(access);
3334 graft = isl_schedule_node_from_extension(access);
3335
3336 graft = isl_schedule_node_child(graft, 0);
3337
3338 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3339
3340 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3341 graft = isl_schedule_node_band_split(graft,
3342 tile->n - kernel->n_block);
3343 graft = isl_schedule_node_child(graft, 0);
3344 }
3345 if (tile->n < kernel->n_block)
3346 skip = kernel->n_block - tile->n;
3347 else
3348 skip = 0;
3349 filter = set_schedule_modulo(graft, kernel->thread_ids,
3350 kernel->block_dim);
3351 if (!kernel->options->wrap)
3352 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3353 kernel->options);
3354 if (tile->n > kernel->n_block && kernel->n_block > 0)
3355 graft = isl_schedule_node_parent(graft);
3356 graft = isl_schedule_node_insert_filter(graft, filter);
3357
3358 while (graft && isl_schedule_node_has_parent(graft))
3359 graft = isl_schedule_node_parent(graft);
3360
3361 if (read) {
3362 if (kernel_depth < group->depth)
3363 node = gpu_tree_ensure_sync_after_core(node, kernel);
3364 node = gpu_tree_move_left_to_sync(node, kernel);
3365 node = isl_schedule_node_graft_before(node, graft);
3366 } else {
3367 node = gpu_tree_move_right_to_sync(node, kernel);
3368 node = isl_schedule_node_graft_after(node, graft);
3369 if (kernel_depth < group->depth)
3370 node = add_group_write_sync(node, kernel, group, 1);
3371 }
3372
3373 node = gpu_tree_move_up_to_kernel(node);
3374
3375 return node;
3376}
3377
3378/* Check whether the array reference group "group" is mapped to
3379 * private or shared memory and, if so,
3380 * add copy statements to the schedule tree of "node"
3381 * for reading from global memory to private or shared memory
3382 * (if "read" is set) or for writing back from private or shared memory
3383 * to global memory (if "read" is not set) for this group.
3384 * On input, "node" points to the kernel node, and it is moved
3385 * back there on output.
3386 */
3387static __isl_give isl_schedule_node *add_copies_group(
3388 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3389 __isl_take isl_schedule_node *node, int read)
3390{
3391 if (group->private_tile)
3392 return add_copies_group_private(kernel, group, node, read);
3393 if (group->shared_tile)
3394 return add_copies_group_shared(kernel, group, node, read);
3395 return node;
3396}
3397
3398/* For each array reference group that is mapped to private or shared memory,
3399 * add copy statements to the schedule tree of "node"
3400 * for reading from global memory to private or shared memory
3401 * and for writing back.
3402 * On input, "node" points to the kernel node, and it is moved
3403 * back there on output.
3404 */
3405static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3406 __isl_take isl_schedule_node *node)
3407{
3408 int i, j;
3409
3410 for (i = 0; i < kernel->n_array; ++i) {
3411 struct gpu_local_array_info *array = &kernel->array[i];
3412
3413 for (j = 0; j < array->n_group; ++j) {
3414 struct gpu_array_ref_group *group = array->groups[j];
3415
3416 node = add_copies_group(kernel, group, node, 1);
3417 if (!node)
3418 return NULL((void*)0);
3419 node = add_copies_group(kernel, group, node, 0);
3420 if (!node)
3421 return NULL((void*)0);
3422 }
3423 }
3424
3425 return node;
3426}
3427
3428/* Mark all dimensions in the current band node atomic.
3429 */
3430static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3431{
3432 int i, n;
3433
3434 n = isl_schedule_node_band_n_member(node);
3435 for (i = 0; i < n; ++i)
3436 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
3437 isl_ast_loop_atomic);
3438
3439 return node;
3440}
3441
3442/* Mark "node" atomic, if it is a band node.
3443 * Do the same for all ancestors.
3444 * Return a pointer to "node" (in the updated schedule tree).
3445 */
3446static __isl_give isl_schedule_node *atomic_ancestors(
3447 __isl_take isl_schedule_node *node)
3448{
3449 int pos;
3450
3451 if (!node)
3452 return NULL((void*)0);
3453 if (!isl_schedule_node_has_parent(node))
3454 return node;
3455
3456 pos = isl_schedule_node_get_child_position(node);
3457 node = isl_schedule_node_parent(node);
3458 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3459 node = atomic(node);
3460 node = atomic_ancestors(node);
3461 node = isl_schedule_node_child(node, pos);
3462
3463 return node;
3464}
3465
3466/* Collect all write references that require synchronization.
3467 * "node" is assumed to point to the kernel node.
3468 * Each reference is represented by a universe set in a space
3469 *
3470 * [S[i,j] -> R[]]
3471 *
3472 * with S[i,j] the statement instance space and R[] the array reference.
3473 *
3474 * This function should be called before block and thread filters are added.
3475 *
3476 * Synchronization is needed after a write if there is a subsequent read
3477 * within the same block that may not be performed by the same thread.
3478 * There should not be any dependences between different blocks,
3479 * so we start with the flow dependences within the same kernel invocation
3480 * and we subtract from these those dependences that are mapped
3481 * to the same iteration of the bands where synchronization is inserted.
3482 * We do not remove pairs of instances that are known to map to
3483 * the same thread across different iterations of the intermediate
3484 * bands because the read may be performed by a different thread
3485 * than the one that needs the value if shared memory is involved.
3486 *
3487 * We also consider all pairs of possible writes that access the same
3488 * memory location and that may be mapped to the same block but not
3489 * to the same iteration of the intermediate bands.
3490 * In theory, it would be possible for one thread to still be in
3491 * a previous iteration of a loop in these bands.
3492 * A write to global memory in this delayed thread could then overwrite
3493 * a write from another thread that has already moved on to
3494 * the next iteration.
3495 *
3496 * After computing the above writes paired off with reads or writes
3497 * that depend on them, we project onto the domain writes.
3498 * Sychronization is needed after writes to global memory
3499 * through these references.
3500 */
3501static __isl_give isl_union_set *compute_sync_writes(
3502 struct ppcg_kernel *kernel, __isl_keep isl_schedule_node *node)
3503{
3504 isl_union_map *local;
3505 isl_union_map *may_writes, *shared_access;
3506 isl_union_map *kernel_prefix, *thread_prefix;
3507 isl_union_map *equal;
3508 isl_union_set *wrap;
3509 isl_union_set *domain;
3510
3511 domain = isl_schedule_node_get_universe_domain(node);
3512 kernel_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3513 node = isl_schedule_node_copy(node);
3514 node = gpu_tree_move_down_to_thread(node, kernel->core);
3515 thread_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3516 isl_schedule_node_free(node);
3517
3518 may_writes = isl_union_map_copy(kernel->prog->scop->tagged_may_writes);
3519 may_writes = isl_union_map_curry(may_writes);
3520 may_writes = isl_union_map_intersect_domain(may_writes, domain);
3521 may_writes = isl_union_map_uncurry(may_writes);
3522 shared_access = isl_union_map_copy(may_writes);
3523 shared_access = isl_union_map_apply_range(shared_access,
3524 isl_union_map_reverse(may_writes));
3525
3526 local = isl_union_map_copy(kernel->prog->scop->tagged_dep_flow);
3527 local = isl_union_map_union(local, shared_access);
3528 local = isl_union_map_zip(local);
3529
3530 equal = isl_union_map_apply_range(kernel_prefix,
3531 isl_union_map_reverse(isl_union_map_copy(kernel_prefix)));
3532 wrap = isl_union_map_wrap(equal);
3533 local = isl_union_map_intersect_domain(local, wrap);
3534 equal = isl_union_map_apply_range(thread_prefix,
3535 isl_union_map_reverse(isl_union_map_copy(thread_prefix)));
3536 wrap = isl_union_map_wrap(equal);
3537 local = isl_union_map_subtract_domain(local, wrap);
3538
3539 local = isl_union_map_zip(local);
3540 local = isl_union_map_universe(local);
3541
3542 return isl_union_map_domain(local);
3543}
3544
3545/* Group the domain elements into a single space, named kernelX,
3546 * with X the kernel sequence number "kernel_id".
3547 */
3548static __isl_give isl_schedule_node *group_statements(
3549 __isl_take isl_schedule_node *node, int kernel_id)
3550{
3551 char buffer[20];
3552 isl_id *id;
3553
3554 if (!node)
3555 return NULL((void*)0);
3556
3557 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3558 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL((void*)0));
3559 return isl_schedule_node_group(node, id);
3560}
3561
3562/* Create a ppcg_kernel representing the domain instances that reach "node"
3563 * and insert a mark node pointing to the ppcg_kernel before "node".
3564 * The band that "node" points to is the band that needs to be mapped
3565 * to block identifiers. The band that needs to be mapped to thread
3566 * identifiers should be marked by a "thread" mark by the caller.
3567 * This mark is removed by this function.
3568 * If "scale" is set, then the band that "node" points to is scaled
3569 * by "sizes".
3570 *
3571 * Mark all outer band nodes as atomic to ensure each kernel is only
3572 * scheduled once.
3573 * If the domain elements that reach "node" live in more than one space,
3574 * then group the domain elements into a single space, named kernelX,
3575 * with X the kernel sequence number.
3576 *
3577 * Insert a guard node governing the kernel node to ensure that
3578 * no kernels with zero blocks are launched.
3579 *
3580 * Insert a context node describing the block and thread
3581 * identifiers inside the kernel mark.
3582 * The context node needs to be inserted after the effective block size
3583 * has been determined such that the bounds on the thread identifiers
3584 * would reflect the effective block size.
3585 * Insert a filter node inside the context node mapping the statement
3586 * instances to block identifiers. In particular, the block identifiers
3587 * are equated to the partial schedule of band that was marked for mapping
3588 * to blocks modulo the grid size.
3589 * Insert a filter node inside the "thread" mark mapping the statement
3590 * instances to thread identifiers. In particular, the thread identifiers
3591 * are equated to the partial schedule of band that was marked for mapping
3592 * to threads modulo the block size.
3593 *
3594 * Compute array reference groups for all arrays, set the local
3595 * array bounds based on the set of domain instances that reach
3596 * the kernel node, check the total amount of shared memory used
3597 * and compute all group tilings.
3598 * The array reference groups are computed after the block filter
3599 * has been inserted because it affects the mapping to shared or
3600 * private memory. This computation also requires the thread filter
3601 * (in the ppcg_kernel object), but this thread filter should not
3602 * have been added to the schedule tree yet since the computation
3603 * requires the schedule of the band that needs to be mapped to
3604 * threads before the privatization is applied.
3605 *
3606 * If any array reference group requires the band mapped to threads
3607 * to be unrolled, then we perform the required unrolling.
3608 *
3609 * We save a copy of the schedule that may influence the mappings
3610 * to shared or private memory in kernel->shared_schedule.
3611 *
3612 * Finally, we add synchronization and copy statements to the schedule tree,
3613 * remove the "thread" mark and create representations for the local
3614 * variables in the kernel.
3615 *
3616 * We keep a copy of the isl_id that points to the kernel to ensure
3617 * that the kernel does not get destroyed if the schedule node
3618 * is freed due to some error condition.
3619 */
3620static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
3621 __isl_take isl_schedule_node *node, int scale,
3622 __isl_keep isl_multi_val *sizes)
3623{
3624 struct ppcg_kernel *kernel;
3625 isl_id *id;
3626 isl_schedule_node *node_thread;
3627 isl_union_map *host_schedule;
3628 isl_set *host_domain;
3629 isl_union_set *domain;
3630 int single_statement;
3631
3632 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel)((struct ppcg_kernel *)isl_calloc_or_die(gen->ctx, 1, sizeof
(struct ppcg_kernel)))
;
3633 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3634 if (!kernel)
3635 return isl_schedule_node_free(node);
3636
3637 domain = isl_schedule_node_get_domain(node);
3638 single_statement = isl_union_set_n_set(domain) == 1;
3639
3640 kernel->ctx = gen->ctx;
3641 kernel->prog = gen->prog;
3642 kernel->options = gen->options;
3643 kernel->context = extract_context(node, gen->prog);
3644 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3645 kernel->arrays = accessed_by_domain(isl_union_set_copy(domain),
3646 gen->prog);
3647 kernel->n_grid = n_outer_coincidence(node);
3648 node_thread = isl_schedule_node_copy(node);
3649 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3650 node_thread = isl_schedule_node_child(node_thread, 0);
3651 kernel->n_block = n_outer_coincidence(node_thread);
3652 isl_schedule_node_free(node_thread);
3653 kernel->id = gen->kernel_id++;
3654 read_grid_and_block_sizes(kernel, gen);
3655
3656 kernel->sync_writes = compute_sync_writes(kernel, node);
3657
3658 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3659 host_domain = isl_set_from_union_set(isl_union_map_range(
3660 host_schedule));
3661
3662 node = atomic_ancestors(node);
3663
3664 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3665 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3666 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3667
3668 if (!single_statement)
3669 node = group_statements(node, kernel->id);
3670
3671 node = isl_schedule_node_child(node, 0);
3672 node = split_band(node, kernel->n_grid);
3673 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3674 kernel->n_grid, "b");
3675 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3676 kernel->grid_dim);
3677 kernel->grid_size = extract_grid_size(kernel,
3678 isl_union_set_copy(domain));
3679 if (!kernel->options->wrap)
3680 node = snap_band_to_sizes(node, kernel->grid_dim,
3681 kernel->options);
3682 if (scale)
3683 node = scale_band(node, isl_multi_val_copy(sizes));
3684 node = isl_schedule_node_parent(node);
3685 if (!single_statement)
3686 node = isl_schedule_node_parent(node);
3687 node = insert_guard(node, kernel->context, kernel->grid_size,
3688 gen->prog->scop);
3689 node = gpu_tree_move_down_to_thread(node, kernel->core);
3690 node = isl_schedule_node_child(node, 0);
3691 node = split_band(node, kernel->n_block);
3692 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3693 kernel->n_block, "t");
3694 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3695 kernel->block_dim);
3696 extract_block_size(kernel, domain);
3697
3698 node = gpu_tree_move_up_to_kernel(node);
3699 node = isl_schedule_node_child(node, 0);
3700 node = insert_context(kernel, node);
3701 node = isl_schedule_node_child(node, 0);
3702 node = isl_schedule_node_insert_filter(node,
3703 isl_union_set_copy(kernel->block_filter));
3704
3705 node = gpu_tree_move_up_to_kernel(node);
3706
3707 if (gpu_group_references(kernel, node) < 0)
3708 node = isl_schedule_node_free(node);
3709 localize_bounds(kernel, host_domain);
3710 isl_set_free(host_domain);
3711
3712 check_shared_memory_bound(kernel);
3713 mark_global_arrays(kernel);
3714 compute_group_tilings(kernel);
3715
3716 node = gpu_tree_move_down_to_thread(node, kernel->core);
3717 node = isl_schedule_node_child(node, 0);
3718 if (!kernel->options->wrap)
3719 node = snap_band_to_sizes(node, kernel->block_dim,
3720 kernel->options);
3721 node = isl_schedule_node_insert_filter(node,
3722 isl_union_set_copy(kernel->thread_filter));
3723 if (kernel_requires_unroll(kernel)) {
3724 node = isl_schedule_node_child(node, 0);
3725 node = unroll(node);
3726 }
3727
3728 node = gpu_tree_move_up_to_thread(node);
3729 kernel->shared_schedule_dim =
3730 isl_schedule_node_get_schedule_depth(node);
3731 kernel->shared_schedule =
3732 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3733
3734 node = gpu_tree_move_up_to_kernel(node);
3735
3736 node = add_sync(kernel, node);
3737 node = add_copies(kernel, node);
3738
3739 node = gpu_tree_move_down_to_thread(node, kernel->core);
3740 node = isl_schedule_node_delete(node);
3741
3742 node = gpu_tree_move_up_to_kernel(node);
3743
3744 if (create_kernel_vars(kernel) < 0)
3745 node = isl_schedule_node_free(node);
3746
3747 if (!single_statement)
3748 node = isl_schedule_node_parent(node);
3749 node = isl_schedule_node_parent(node);
3750
3751 isl_id_free(id);
3752 return node;
3753}
3754
3755/* Insert a zero-dimensional permutable band at "node".
3756 */
3757static __isl_give isl_schedule_node *insert_empty_permutable_band(
3758 __isl_take isl_schedule_node *node)
3759{
3760 isl_space *space;
3761 isl_schedule *schedule;
3762 isl_union_set *domain;
3763 isl_multi_union_pw_aff *mupa;
3764
3765 schedule = isl_schedule_node_get_schedule(node);
3766 domain = isl_schedule_get_domain(schedule);
3767 space = isl_union_set_get_space(domain);
3768 isl_union_set_free(domain);
3769 isl_schedule_free(schedule);
3770
3771 space = isl_space_set_from_params(space);
3772 mupa = isl_multi_union_pw_aff_zero(space);
3773 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3774 node = isl_schedule_node_band_set_permutable(node, 1);
3775
3776 return node;
3777}
3778
3779/* If "node" is the outermost permutable band that can be mapped to block and
3780 * thread identifiers in its branch (or a leaf with no such outer bands),
3781 * then mark the band as such, attaching a ppcg_kernel to the mark.
3782 *
3783 * If "node" originally points to a leaf, then insert a zero-dimensional
3784 * permutable band such that we can assume that "node" always
3785 * points to a band node.
3786 *
3787 * Tile "node" using user specified tile sizes, after splitting the band
3788 * if the number of specified tile sizes is smaller than the dimension
3789 * of the band. Mark the point band of this tiling as the band that
3790 * needs to be mapped to threads.
3791 * Create a kernel representing the domain instances that reach "node" and
3792 * insert a mark node pointing to the ppcg_kernel before the band node.
3793 */
3794static __isl_give isl_schedule_node *mark_outer_permutable(
3795 __isl_take isl_schedule_node *node, void *user)
3796{
3797 struct gpu_gen *gen = user;
3798 int outer;
3799 int scale;
3800 int tile_len;
3801 int *tile_size;
3802 isl_id *id;
3803 isl_multi_val *sizes;
3804
3805 outer = is_outer_tilable(node);
3806 if (outer < 0)
3807 return isl_schedule_node_free(node);
3808 if (!outer)
3809 return node;
3810
3811 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
3812 node = insert_empty_permutable_band(node);
3813
3814 tile_len = isl_schedule_node_band_n_member(node);
3815 tile_size = read_tile_sizes(gen, &tile_len);
3816 if (!tile_size)
3817 return isl_schedule_node_free(node);
3818 if (tile_len < isl_schedule_node_band_n_member(node))
3819 node = isl_schedule_node_band_split(node, tile_len);
3820 sizes = construct_band_tiles_sizes(node, tile_size);
3821 node = tile_band(node, isl_multi_val_copy(sizes));
3822 node = isl_schedule_node_child(node, 0);
3823 id = isl_id_alloc(gen->ctx, "thread", NULL((void*)0));
3824 node = isl_schedule_node_insert_mark(node, id);
3825 node = isl_schedule_node_parent(node);
3826
3827 scale = gen->options->scale_tile_loops;
3828 node = create_kernel(gen, node, scale, sizes);
3829 isl_multi_val_free(sizes);
3830 free(tile_size);
3831
3832 return node;
3833}
3834
3835/* Does the subtree rooted at "node" have any suitably permutable band nodes?
3836 * That is, does it have any nodes that are permutable and that
3837 * have a least one coincident dimension?
3838 */
3839static int subtree_has_permutable_bands(__isl_keep isl_schedule_node *node)
3840{
3841 int any_parallelism = 0;
3842
3843 if (isl_schedule_node_foreach_descendant_top_down(node, &set_permutable,
3844 &any_parallelism) < 0 &&
3845 !any_parallelism)
3846 return -1;
3847
3848 return any_parallelism;
3849}
3850
3851/* Mark all variables that are accessed by the statement instances in "domain"
3852 * and that are local to "prog" as requiring a declaration in the host code.
3853 */
3854static int declare_accessed_local_variables(struct gpu_prog *prog,
3855 __isl_keep isl_union_set *domain)
3856{
3857 isl_union_set *arrays;
3858 int i;
3859
3860 if (!ppcg_scop_any_hidden_declarations(prog->scop))
3861 return 0;
3862 arrays = accessed_by_domain(isl_union_set_copy(domain), prog);
3863
3864 for (i = 0; i < prog->n_array; ++i) {
3865 isl_space *space;
3866 isl_set *set;
3867 int empty;
3868
3869 if (!prog->array[i].local)
3870 continue;
3871 space = isl_set_get_space(prog->array[i].extent);
3872 set = isl_union_set_extract_set(arrays, space);
3873 empty = isl_set_plain_is_empty(set);
3874 isl_set_free(set);
3875 if (empty < 0)
3876 goto error;
3877 if (!empty)
3878 prog->array[i].declare_local = 1;
3879 }
3880
3881 isl_union_set_free(arrays);
3882 return 0;
3883error:
3884 isl_union_set_free(arrays);
3885 return -1;
3886}
3887
3888/* If "node" points to a set node, then separate its children
3889 * into subtrees that have suitably permutable bands and
3890 * those that do not.
3891 * Adjust the schedule tree in order to execute the second group
3892 * after the first group and return a pointer to the first group,
3893 * assuming there are any such subtrees.
3894 * Mark all local variables in "prog" that are accessed by
3895 * the second group as requiring a declaration on the host.
3896 */
3897static __isl_give isl_schedule_node *isolate_permutable_subtrees(
3898 __isl_take isl_schedule_node *node, struct gpu_prog *prog)
3899{
3900 isl_space *space;
3901 isl_union_set *filter;
3902 int i, n;
3903
3904 if (!node)
3905 return NULL((void*)0);
3906 if (isl_schedule_node_get_type(node) != isl_schedule_node_set)
3907 return node;
3908
3909 n = isl_schedule_node_n_children(node);
3910 if (n < 0)
3911 return isl_schedule_node_free(node);
3912
3913 node = isl_schedule_node_child(node, 0);
3914 filter = isl_schedule_node_filter_get_filter(node);
3915 node = isl_schedule_node_parent(node);
3916 space = isl_union_set_get_space(filter);
3917 isl_union_set_free(filter);
3918 filter = isl_union_set_empty(space);
3919
3920 for (i = 0; i < n; ++i) {
3921 int parallelism;
3922
3923 node = isl_schedule_node_child(node, i);
3924 parallelism = subtree_has_permutable_bands(node);
3925 if (parallelism < 0) {
3926 node = isl_schedule_node_free(node);
3927 } else if (!parallelism) {
3928 isl_union_set *filter_i;
3929 filter_i = isl_schedule_node_filter_get_filter(node);
3930 filter = isl_union_set_union(filter, filter_i);
3931 }
3932 node = isl_schedule_node_parent(node);
3933 }
3934
3935 if (declare_accessed_local_variables(prog, filter) < 0)
3936 node = isl_schedule_node_free(node);
3937 node = isl_schedule_node_order_after(node, filter);
3938
3939 return node;
3940}
3941
3942/* Replace any reference to an array element in the range of "copy"
3943 * by a reference to all array elements (defined by the extent of the array).
3944 */
3945static __isl_give isl_union_map *approximate_copy_out(
3946 __isl_take isl_union_map *copy, struct gpu_prog *prog)
3947{
3948 int i;
3949 isl_union_map *res;
3950
3951 res = isl_union_map_empty(isl_union_map_get_space(copy));
3952
3953 for (i = 0; i < prog->n_array; ++i) {
3954 isl_space *space;
3955 isl_set *set;
3956 isl_union_map *copy_i;
3957 isl_union_set *extent, *domain;
3958
3959 space = isl_space_copy(prog->array[i].space);
3960 extent = isl_union_set_from_set(isl_set_universe(space));
3961 copy_i = isl_union_map_copy(copy);
3962 copy_i = isl_union_map_intersect_range(copy_i, extent);
3963 set = isl_set_copy(prog->array[i].extent);
3964 extent = isl_union_set_from_set(set);
3965 domain = isl_union_map_domain(copy_i);
3966 copy_i = isl_union_map_from_domain_and_range(domain, extent);
3967 res = isl_union_map_union(res, copy_i);
3968 }
3969
3970 isl_union_map_free(copy);
3971
3972 return res;
3973}
3974
3975/* Insert "kernel" marks that point to a ppcg_kernel structure
3976 * in front of all outermost tilable band that (by construction)
3977 * have at least one parallel loop.
3978 */
3979static __isl_give isl_schedule_node *mark_kernels(struct gpu_gen *gen,
3980 __isl_take isl_schedule_node *node)
3981{
3982 return isl_schedule_node_map_descendant_bottom_up(node,
3983 &mark_outer_permutable, gen);
3984}
3985
3986/* Save the schedule "schedule" to a file called "filename".
3987 * The schedule is printed in block style.
3988 */
3989static void save_schedule(__isl_keep isl_schedule *schedule,
3990 const char *filename)
3991{
3992 FILE *file;
3993 isl_ctx *ctx;
3994 isl_printer *p;
3995
3996 if (!schedule)
3997 return;
3998
3999 file = fopen(filename, "w");
4000 if (!file) {
4001 fprintf(stderrstderr, "Unable to open '%s' for writing\n", filename);
4002 return;
4003 }
4004 ctx = isl_schedule_get_ctx(schedule);
4005 p = isl_printer_to_file(ctx, file);
4006 p = isl_printer_set_yaml_style(p, ISL_YAML_STYLE_BLOCK0);
4007 p = isl_printer_print_schedule(p, schedule);
4008 isl_printer_free(p);
4009 fclose(file);
4010}
4011
4012/* Load and return a schedule from a file called "filename".
4013 */
4014static __isl_give isl_schedule *load_schedule(isl_ctx *ctx,
4015 const char *filename)
4016{
4017 FILE *file;
4018 isl_schedule *schedule;
4019
4020 file = fopen(filename, "r");
4021 if (!file) {
4022 fprintf(stderrstderr, "Unable to open '%s' for reading\n", filename);
4023 return NULL((void*)0);
4024 }
4025 schedule = isl_schedule_read_from_file(ctx, file);
4026 fclose(file);
4027
4028 return schedule;
4029}
4030
4031/* Construct schedule constraints from the dependences in prog->scop and
4032 * the array order dependences in prog->array_order.
4033 *
4034 * If live range reordering is allowed, then we need to make sure
4035 * that live ranges on arrays are not run in parallel since doing
4036 * so would require array expansion. We therefore add the array
4037 * order dependences to the coincidence dependences. Non-zero array
4038 * order dependences will then prevent a schedule dimension from being
4039 * considered parallel.
4040 * Live ranges derived from scalars are allowed to be run in parallel
4041 * since we force the scalars to be mapped to private memory in
4042 * check_scalar_live_ranges.
4043 * If live range reordering is allowed, then the false dependences
4044 * are not added to the validity constraints as that would prevent
4045 * reordering. Instead, the external false dependences that enforce that reads
4046 * from potentially live-in data precede any later write and
4047 * that writes of potentially live-out data follow any other earlier write
4048 * are added to the validity and the coincidence constraints.
4049 * The false dependences are still added to the proximity constraints
4050 * for consistency with the case where live range reordering is not allowed.
4051 * The coincidence constraints then consist of flow dependences,
4052 * external false dependences and array order dependences.
4053 * The independences can be filtered out from the first two sets.
4054 * They have already been filtered out from the array order dependences
4055 * on a per array basis in collect_order_dependences.
4056 * There is no need for a per array handling of the other two sets
4057 * as there should be no flow or external false dependence on local
4058 * variables that can be filtered out.
4059 */
4060static __isl_give isl_schedule_constraints *construct_schedule_constraints(
4061 struct gpu_prog *prog)
4062{
4063 isl_union_set *domain;
4064 isl_union_map *dep_raw, *dep;
4065 isl_union_map *validity, *proximity, *coincidence;
4066 isl_schedule_constraints *sc;
4067
4068 domain = isl_union_set_copy(prog->scop->domain);
4069 sc = isl_schedule_constraints_on_domain(domain);
4070 sc = isl_schedule_constraints_set_context(sc,
4071 isl_set_copy(prog->scop->context));
4072 if (prog->scop->options->live_range_reordering) {
4073 sc = isl_schedule_constraints_set_conditional_validity(sc,
4074 isl_union_map_copy(prog->scop->tagged_dep_flow),
4075 isl_union_map_copy(prog->scop->tagged_dep_order));
4076 proximity = isl_union_map_copy(prog->scop->dep_flow);
4077 validity = isl_union_map_copy(proximity);
4078 validity = isl_union_map_union(validity,
4079 isl_union_map_copy(prog->scop->dep_forced));
4080 proximity = isl_union_map_union(proximity,
4081 isl_union_map_copy(prog->scop->dep_false));
4082 coincidence = isl_union_map_copy(validity);
4083 coincidence = isl_union_map_subtract(coincidence,
4084 isl_union_map_copy(prog->scop->independence));
4085 coincidence = isl_union_map_union(coincidence,
4086 isl_union_map_copy(prog->array_order));
4087 } else {
4088 dep_raw = isl_union_map_copy(prog->scop->dep_flow);
4089 dep = isl_union_map_copy(prog->scop->dep_false);
4090 dep = isl_union_map_union(dep, dep_raw);
4091 dep = isl_union_map_coalesce(dep);
4092 proximity = isl_union_map_copy(dep);
4093 coincidence = isl_union_map_copy(dep);
4094 validity = dep;
4095 }
4096 sc = isl_schedule_constraints_set_validity(sc, validity);
4097 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4098 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4099
4100 if (prog->scop->options->debug->dump_schedule_constraints)
4101 isl_schedule_constraints_dump(sc);
4102 return sc;
4103}
4104
4105/* Compute an appropriate schedule based on the accesses in
4106 * gen->read and gen->write.
4107 *
4108 * We derive schedule constraints from the dependences in gen->prog->scop
4109 * and then use isl to compute a schedule that has a parallel loop
4110 * in each tilable band.
4111 */
4112static __isl_give isl_schedule *compute_schedule(struct gpu_gen *gen)
4113{
4114 isl_schedule_constraints *sc;
4115 isl_schedule *schedule;
4116
4117 sc = construct_schedule_constraints(gen->prog);
4118 schedule = isl_schedule_constraints_compute_schedule(sc);
4119
4120 return schedule;
4121}
4122
4123/* If the band node "node" has exactly one member then mark it permutable.
4124 */
4125static __isl_give isl_schedule_node *band_set_permutable(
4126 __isl_take isl_schedule_node *node,
4127 __isl_keep isl_schedule_constraints *sc)
4128{
4129 if (isl_schedule_node_band_n_member(node) == 1)
4130 node = isl_schedule_node_band_set_permutable(node, 1);
4131
4132 return node;
4133}
4134
4135/* Return the coincidence constraints between pairs of instances
4136 * that are scheduled together by the ancestors of "node".
4137 * That is, select those coincidence constraints that relate
4138 * pairs of instances that have the same value for the prefix schedule.
4139 * If the schedule depth is zero, then the prefix schedule does not
4140 * contain any information, so we intersect domain and range
4141 * of the schedule constraints with the reaching domain elements instead.
4142 */
4143static __isl_give isl_union_map *get_local_coincidence(
4144 __isl_keep isl_schedule_node *node,
4145 __isl_keep isl_schedule_constraints *sc)
4146{
4147 isl_union_map *coincidence;
4148 isl_multi_union_pw_aff *prefix;
4149 isl_union_pw_multi_aff *contraction;
4150
4151 coincidence = isl_schedule_constraints_get_coincidence(sc);
4152 contraction = isl_schedule_node_get_subtree_contraction(node);
4153 if (isl_schedule_node_get_schedule_depth(node) == 0) {
4154 isl_union_set *domain;
4155
4156 domain = isl_schedule_node_get_domain(node);
4157 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4158 contraction);
4159 coincidence = isl_union_map_intersect_domain(coincidence,
4160 isl_union_set_copy(domain));
4161 coincidence = isl_union_map_intersect_range(coincidence,
4162 domain);
4163 return coincidence;
4164 }
4165
4166 prefix = isl_schedule_node_get_prefix_schedule_multi_union_pw_aff(node);
4167 prefix = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(prefix,
4168 contraction);
4169 return isl_union_map_eq_at_multi_union_pw_aff(coincidence, prefix);
4170}
4171
4172/* For each member in the band node "node", determine whether
4173 * it is coincident with respect to the outer nodes and mark
4174 * it accordingly.
4175 *
4176 * That is, for each coincidence constraint between pairs
4177 * of instances that are scheduled together by the outer nodes,
4178 * check that domain and range are assigned the same value
4179 * by the band member. This test is performed by checking
4180 * that imposing the same value for the band member does not
4181 * remove any elements from the set of coincidence constraints.
4182 */
4183static __isl_give isl_schedule_node *band_set_coincident(
4184 __isl_take isl_schedule_node *node,
4185 __isl_keep isl_schedule_constraints *sc)
4186{
4187 isl_union_map *coincidence;
4188 isl_union_pw_multi_aff *contraction;
4189 isl_multi_union_pw_aff *partial;
4190 int i, n;
4191
4192 coincidence = get_local_coincidence(node, sc);
4193
4194 partial = isl_schedule_node_band_get_partial_schedule(node);
4195 contraction = isl_schedule_node_get_subtree_contraction(node);
4196 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4197 contraction);
4198 n = isl_schedule_node_band_n_member(node);
4199 for (i = 0; i < n; ++i) {
4200 isl_union_map *coincidence_i;
4201 isl_union_pw_aff *upa;
4202 isl_multi_union_pw_aff *partial_i;
4203 int subset;
4204
4205 upa = isl_multi_union_pw_aff_get_union_pw_aff(partial, i);
4206 partial_i = isl_multi_union_pw_aff_from_union_pw_aff(upa);
4207 coincidence_i = isl_union_map_copy(coincidence);
4208 coincidence_i = isl_union_map_eq_at_multi_union_pw_aff(
4209 coincidence_i, partial_i);
4210 subset = isl_union_map_is_subset(coincidence, coincidence_i);
4211 isl_union_map_free(coincidence_i);
4212
4213 if (subset < 0)
4214 break;
4215 node = isl_schedule_node_band_member_set_coincident(node, i,
4216 subset);
4217 }
4218 if (i < n)
4219 node = isl_schedule_node_free(node);
4220 isl_multi_union_pw_aff_free(partial);
4221 isl_union_map_free(coincidence);
4222
4223 return node;
4224}
4225
4226/* If "node" is a band, then set its properties.
4227 *
4228 * In particular, if the band has exactly one member, then mark it permutable.
4229 * Mark the band member coincident based on the coincidence constraints
4230 * of "sc".
4231 */
4232static __isl_give isl_schedule_node *set_band_properties(
4233 __isl_take isl_schedule_node *node, void *user)
4234{
4235 isl_schedule_constraints *sc = user;
4236
4237 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
4238 return node;
4239 if (isl_schedule_node_band_n_member(node) == 0)
4240 return node;
4241
4242 node = band_set_permutable(node, sc);
4243 node = band_set_coincident(node, sc);
4244
4245 return node;
4246}
4247
4248/* Return the original schedule with all bands marked permutable and
4249 * all band members marked coincident based on the coincidence constraints.
4250 * The bands are explicitly marked permutable so that they will be considered
4251 * by mark_outer_permutable.
4252 */
4253static __isl_give isl_schedule *determine_properties_original_schedule(
4254 struct gpu_gen *gen)
4255{
4256 isl_schedule *schedule;
4257 isl_schedule_constraints *sc;
4258
4259 schedule = isl_schedule_copy(gen->prog->scop->schedule);
4260 sc = construct_schedule_constraints(gen->prog);
4261 schedule = isl_schedule_map_schedule_node_bottom_up(schedule,
4262 &set_band_properties, sc);
4263 isl_schedule_constraints_free(sc);
4264
4265 return schedule;
4266}
4267
4268/* Obtain a schedule for the scop, by reading it from
4269 * a file, by computing one or by determining the properties
4270 * of the original schedule.
4271 */
4272__isl_give isl_schedule *get_schedule(struct gpu_gen *gen)
4273{
4274 isl_schedule *schedule;
4275
4276 if (gen->options->load_schedule_file) {
4277 schedule = load_schedule(gen->ctx,
4278 gen->options->load_schedule_file);
4279 } else {
4280 if (gen->options->reschedule)
4281 schedule = compute_schedule(gen);
4282 else
4283 schedule = determine_properties_original_schedule(gen);
4284 if (gen->options->save_schedule_file)
4285 save_schedule(schedule,
4286 gen->options->save_schedule_file);
4287 }
4288 if (gen->options->debug->dump_schedule)
4289 isl_schedule_dump(schedule);
4290
4291 return schedule;
4292}
4293
4294/* Construct the string "<a>_<b>".
4295 */
4296static char *concat(isl_ctx *ctx, const char *a, const char *b)
4297{
4298 isl_printer *p;
4299 char *s;
4300
4301 p = isl_printer_to_str(ctx);
4302 p = isl_printer_print_str(p, a);
4303 p = isl_printer_print_str(p, "_");
4304 p = isl_printer_print_str(p, b);
4305 s = isl_printer_get_str(p);
4306 isl_printer_free(p);
4307
4308 return s;
4309}
4310
4311/* For each array in "prog" of which an element appears in "accessed" and
4312 * that is not a read only scalar, create a zero-dimensional universe set
4313 * of which the tuple id has name "<prefix>_<name of array>" and a user
4314 * pointer pointing to the array (gpu_array_info).
4315 *
4316 * If the array is local to "prog", then make sure it will be declared
4317 * in the host code.
4318 *
4319 * Return the list of these universe sets.
4320 */
4321static __isl_give isl_union_set_list *create_copy_filters(struct gpu_prog *prog,
4322 const char *prefix, __isl_take isl_union_set *accessed)
4323{
4324 int i;
4325 isl_ctx *ctx;
4326 isl_union_set_list *filters;
4327
4328 ctx = prog->ctx;
4329 filters = isl_union_set_list_alloc(ctx, 0);
4330 for (i = 0; i < prog->n_array; ++i) {
4331 struct gpu_array_info *array = &prog->array[i];
4332 isl_space *space;
4333 isl_set *accessed_i;
4334 int empty;
4335 char *name;
4336 isl_id *id;
4337 isl_union_set *uset;
4338
4339 if (gpu_array_is_read_only_scalar(array))
4340 continue;
4341
4342 space = isl_space_copy(array->space);
4343 accessed_i = isl_union_set_extract_set(accessed, space);
4344 empty = isl_set_plain_is_empty(accessed_i);
4345 isl_set_free(accessed_i);
4346 if (empty < 0) {
4347 filters = isl_union_set_list_free(filters);
4348 break;
4349 }
4350 if (empty)
4351 continue;
4352
4353 array->global = 1;
4354 if (array->local)
4355 array->declare_local = 1;
4356
4357 name = concat(ctx, prefix, array->name);
4358 id = name ? isl_id_alloc(ctx, name, array) : NULL((void*)0);
4359 free(name);
4360 space = isl_space_set_alloc(ctx, 0, 0);
4361 space = isl_space_set_tuple_id(space, isl_dim_set, id);
4362 uset = isl_union_set_from_set(isl_set_universe(space));
4363
4364 filters = isl_union_set_list_add(filters, uset);
4365 }
4366 isl_union_set_free(accessed);
4367
4368 return filters;
4369}
4370
4371/* Make sure that code for the statements in "filters" that
4372 * copy arrays to or from the device is only generated when
4373 * the size of the corresponding array is positive.
4374 * That is, add a set node underneath "graft" with "filters" as children
4375 * and for each child add a guard that the selects the parameter
4376 * values for which the corresponding array has a positive size.
4377 * The array is available in the user pointer of the statement identifier.
4378 * "depth" is the schedule depth of the position where "graft"
4379 * will be added.
4380 */
4381static __isl_give isl_schedule_node *insert_positive_size_guards(
4382 __isl_take isl_schedule_node *graft,
4383 __isl_take isl_union_set_list *filters, int depth)
4384{
4385 int i, n;
4386
4387 graft = isl_schedule_node_child(graft, 0);
4388 graft = isl_schedule_node_insert_set(graft, filters);
4389 n = isl_schedule_node_n_children(graft);
4390 for (i = 0; i < n; ++i) {
4391 isl_union_set *filter;
4392 isl_set *domain, *guard;
4393 isl_id *id;
4394 struct gpu_array_info *array;
4395
4396 graft = isl_schedule_node_child(graft, i);
4397 filter = isl_schedule_node_filter_get_filter(graft);
4398 domain = isl_set_from_union_set(filter);
4399 id = isl_set_get_tuple_id(domain);
4400 array = isl_id_get_user(id);
4401 isl_id_free(id);
4402 isl_set_free(domain);
4403 guard = gpu_array_positive_size_guard(array);
4404 guard = isl_set_from_params(guard);
4405 guard = isl_set_add_dims(guard, isl_dim_set, depth);
4406 graft = isl_schedule_node_child(graft, 0);
4407 graft = isl_schedule_node_insert_guard(graft, guard);
4408 graft = isl_schedule_node_parent(graft);
4409 graft = isl_schedule_node_parent(graft);
4410 }
4411 graft = isl_schedule_node_parent(graft);
4412
4413 return graft;
4414}
4415
4416/* Create a graft for copying arrays to or from the device,
4417 * whenever the size of the array is strictly positive.
4418 * Each statement is called "<prefix>_<name of array>" and
4419 * the identifier has a user pointer pointing to the array.
4420 * The graft will be added at the position specified by "node".
4421 * "copy" contains the array elements that need to be copied.
4422 * Only arrays of which some elements need to be copied
4423 * will have a corresponding statement in the graph.
4424 * Note though that each such statement will copy the entire array.
4425 */
4426static __isl_give isl_schedule_node *create_copy_device(struct gpu_prog *prog,
4427 __isl_keep isl_schedule_node *node, const char *prefix,
4428 __isl_take isl_union_set *copy)
4429{
4430 int depth;
4431 isl_ctx *ctx;
4432 isl_space *space;
4433 isl_union_set *all, *domain;
4434 isl_union_set_list *filters;
4435 isl_union_map *extension;
4436 isl_schedule_node *graft;
4437
4438 ctx = prog->ctx;
4439 depth = isl_schedule_node_get_schedule_depth(node);
4440 filters = create_copy_filters(prog, prefix, copy);
4441 all = isl_union_set_list_union(isl_union_set_list_copy(filters));
4442
4443 space = depth < 0 ? NULL((void*)0) : isl_space_set_alloc(ctx, 0, depth);
4444 domain = isl_union_set_from_set(isl_set_universe(space));
4445 extension = isl_union_map_from_domain_and_range(domain, all);
4446 graft = isl_schedule_node_from_extension(extension);
4447
4448 if (!filters)
4449 return isl_schedule_node_free(graft);
4450 if (isl_union_set_list_n_union_set(filters) == 0) {
4451 isl_union_set_list_free(filters);
4452 return graft;
4453 }
4454
4455 return insert_positive_size_guards(graft, filters, depth);
4456}
4457
4458/* Return (the universe spaces of) the arrays that are declared
4459 * inside the scop corresponding to "prog" and for which all
4460 * potential writes inside the scop form a subset of "domain".
4461 */
4462static __isl_give isl_union_set *extract_local_accesses(struct gpu_prog *prog,
4463 __isl_keep isl_union_set *domain)
4464{
4465 int i;
4466 isl_union_set *local;
4467
4468 local = isl_union_set_empty(isl_union_set_get_space(domain));
4469
4470 for (i = 0; i < prog->n_array; ++i) {
4471 isl_set *set;
4472 isl_union_map *to_outer;
4473 isl_union_map *may_write;
4474 isl_union_set *write_domain;
4475 isl_union_set *fields;
4476 int subset;
4477
4478 if (!prog->array[i].local)
4479 continue;
4480
4481 set = isl_set_universe(isl_space_copy(prog->array[i].space));
4482 to_outer = isl_union_map_copy(prog->to_outer);
4483 to_outer = isl_union_map_intersect_range(to_outer,
4484 isl_union_set_from_set(isl_set_copy(set)));
4485 fields = isl_union_map_domain(to_outer);
4486 may_write = isl_union_map_copy(prog->may_write);
4487 may_write = isl_union_map_intersect_range(may_write, fields);
4488 write_domain = isl_union_map_domain(may_write);
4489 subset = isl_union_set_is_subset(write_domain, domain);
4490 isl_union_set_free(write_domain);
4491
4492 if (subset < 0) {
4493 isl_set_free(set);
4494 return isl_union_set_free(local);
4495 } else if (subset) {
4496 local = isl_union_set_add_set(local, set);
4497 } else {
4498 isl_set_free(set);
4499 }
4500 }
4501
4502 return local;
4503}
4504
4505/* Internal data structure for node_may_persist.
4506 *
4507 * "tagger" maps tagged iteration domains to the corresponding untagged
4508 * iteration domain.
4509 *
4510 * "may_persist_flow" is the set of all tagged dataflow dependences
4511 * with those dependences removed that either precede or follow
4512 * the kernel launch in a sequence.
4513 * "inner_band_flow" is the set of all tagged dataflow dependences
4514 * that are local to a given iteration of the outer band nodes
4515 * with respect to the current node.
4516 * "local_flow" is equal to "inner_band_flow", except that the domain
4517 * and the range have been intersected with intermediate filters
4518 * on children of sets or sequences.
4519 */
4520struct ppcg_may_persist_data {
4521 isl_union_pw_multi_aff *tagger;
4522
4523 isl_union_map *local_flow;
4524 isl_union_map *inner_band_flow;
4525 isl_union_map *may_persist_flow;
4526};
4527
4528/* Update the information in "data" based on the band ancestor "node".
4529 *
4530 * In particular, we restrict the dependences in data->local_flow
4531 * to those dependence where the source and the sink occur in
4532 * the same iteration of the given band node.
4533 * We also update data->inner_band_flow to the new value of
4534 * data->local_flow.
4535 */
4536static int update_may_persist_at_band(__isl_keep isl_schedule_node *node,
4537 struct ppcg_may_persist_data *data)
4538{
4539 isl_multi_union_pw_aff *partial;
4540 isl_union_pw_multi_aff *contraction;
4541 isl_union_map *flow;
4542
4543 if (isl_schedule_node_band_n_member(node) == 0)
4544 return 0;
4545
4546 partial = isl_schedule_node_band_get_partial_schedule(node);
4547 contraction = isl_schedule_node_get_subtree_contraction(node);
4548 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4549 contraction);
4550 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4551 isl_union_pw_multi_aff_copy(data->tagger));
4552
4553 flow = data->local_flow;
4554 flow = isl_union_map_eq_at_multi_union_pw_aff(flow, partial);
4555 data->local_flow = flow;
4556
4557 isl_union_map_free(data->inner_band_flow);
4558 data->inner_band_flow = isl_union_map_copy(data->local_flow);
4559
4560 return 0;
4561}
4562
4563/* Given a set of local reaching domain elements "domain",
4564 * expand them to the corresponding leaf domain elements using "contraction"
4565 * and insert the array references tags using data->tagger.
4566 */
4567static __isl_give isl_union_set *expand_and_tag(
4568 __isl_take isl_union_set *domain,
4569 __isl_take isl_union_pw_multi_aff *contraction,
4570 struct ppcg_may_persist_data *data)
4571{
4572 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4573 contraction);
4574 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4575 isl_union_pw_multi_aff_copy(data->tagger));
4576 return domain;
4577}
4578
4579/* Given a filter node that is the child of a set or sequence node,
4580 * restrict data->local_flow to refer only to those elements
4581 * in the filter of the node.
4582 * "contraction" maps the leaf domain elements of the schedule tree
4583 * to the corresponding domain elements at (the parent of) "node".
4584 */
4585static int filter_flow(__isl_keep isl_schedule_node *node,
4586 struct ppcg_may_persist_data *data,
4587 __isl_take isl_union_pw_multi_aff *contraction)
4588{
4589 isl_union_set *filter;
4590 isl_union_map *flow;
4591
4592 flow = data->local_flow;
4593 filter = isl_schedule_node_filter_get_filter(node);
4594 filter = expand_and_tag(filter, contraction, data);
4595 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(filter));
4596 flow = isl_union_map_intersect_range(flow, filter);
4597 data->local_flow = flow;
4598
4599 return 0;
4600}
4601
4602/* Given a filter node "node", collect the filters on all preceding siblings
4603 * (which are also filter nodes), add them to "filters" and return the result.
4604 */
4605static __isl_give isl_union_set *add_previous_filters(
4606 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4607{
4608 isl_schedule_node *sibling;
4609
4610 sibling = isl_schedule_node_copy(node);
4611 while (sibling && isl_schedule_node_has_previous_sibling(sibling)) {
4612 isl_union_set *filter;
4613
4614 sibling = isl_schedule_node_previous_sibling(sibling);
4615 filter = isl_schedule_node_filter_get_filter(sibling);
4616 filters = isl_union_set_union(filters, filter);
4617 }
4618 isl_schedule_node_free(sibling);
4619 if (!sibling)
4620 return isl_union_set_free(filters);
4621
4622 return filters;
4623}
4624
4625/* Given a filter node "node", collect the filters on all following siblings
4626 * (which are also filter nodes), add them to "filters" and return the result.
4627 */
4628static __isl_give isl_union_set *add_next_filters(
4629 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4630{
4631 isl_schedule_node *sibling;
4632
4633 sibling = isl_schedule_node_copy(node);
4634 while (sibling && isl_schedule_node_has_next_sibling(sibling)) {
4635 isl_union_set *filter;
4636
4637 sibling = isl_schedule_node_next_sibling(sibling);
4638 filter = isl_schedule_node_filter_get_filter(sibling);
4639 filters = isl_union_set_union(filters, filter);
4640 }
4641 isl_schedule_node_free(sibling);
4642 if (!sibling)
4643 return isl_union_set_free(filters);
4644
4645 return filters;
4646}
4647
4648/* Remove those flow dependences from data->may_persist_flow
4649 * that flow between elements of "domain" within the same iteration
4650 * of all outer band nodes.
4651 * "contraction" maps the leaf domain elements of the schedule tree
4652 * to the corresponding elements "domain".
4653 */
4654static void remove_external_flow(struct ppcg_may_persist_data *data,
4655 __isl_take isl_union_set *domain,
4656 __isl_keep isl_union_pw_multi_aff *contraction)
4657{
4658 isl_union_map *flow;
4659
4660 contraction = isl_union_pw_multi_aff_copy(contraction);
4661 domain = expand_and_tag(domain, contraction, data);
4662 flow = isl_union_map_copy(data->local_flow);
4663 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(domain));
4664 flow = isl_union_map_intersect_range(flow, domain);
4665
4666 data->may_persist_flow = isl_union_map_subtract(data->may_persist_flow,
4667 flow);
4668}
4669
4670/* Update the information in "data" based on the filter ancestor "node".
4671 * We only need to modify anything if the filter is the child
4672 * of a set or sequence node.
4673 *
4674 * In the case of a sequence, we remove the dependences between
4675 * statement instances that are both executed either before or
4676 * after the subtree that will be mapped to a kernel, within
4677 * the same iteration of outer bands.
4678 *
4679 * In both cases, we restrict data->local_flow to the current child.
4680 */
4681static int update_may_persist_at_filter(__isl_keep isl_schedule_node *node,
4682 struct ppcg_may_persist_data *data)
4683{
4684 enum isl_schedule_node_type type;
4685 isl_schedule_node *parent;
4686 isl_space *space;
4687 isl_union_pw_multi_aff *contraction;
4688 isl_union_set *before, *after, *filter;
4689 isl_union_map *flow;
4690
4691 type = isl_schedule_node_get_parent_type(node);
4692 if (type != isl_schedule_node_sequence && type != isl_schedule_node_set)
4693 return 0;
4694
4695 parent = isl_schedule_node_copy(node);
4696 parent = isl_schedule_node_parent(parent);
4697 contraction = isl_schedule_node_get_subtree_contraction(parent);
4698 isl_schedule_node_free(parent);
4699
4700 if (type == isl_schedule_node_set)
4701 return filter_flow(node, data, contraction);
4702
4703 filter = isl_schedule_node_filter_get_filter(node);
4704 space = isl_union_set_get_space(filter);
4705 isl_union_set_free(filter);
4706 before = isl_union_set_empty(space);
4707 after = isl_union_set_copy(before);
4708 before = add_previous_filters(before, node);
4709 after = add_next_filters(after, node);
4710
4711 remove_external_flow(data, before, contraction);
4712 remove_external_flow(data, after, contraction);
4713
4714 return filter_flow(node, data, contraction);
4715}
4716
4717/* Update the information in "data" based on the ancestor "node".
4718 */
4719static isl_stat update_may_persist_at(__isl_keep isl_schedule_node *node,
4720 void *user)
4721{
4722 struct ppcg_may_persist_data *data = user;
4723
4724 switch (isl_schedule_node_get_type(node)) {
4725 case isl_schedule_node_error:
4726 return isl_stat_error;
4727 case isl_schedule_node_context:
4728 case isl_schedule_node_domain:
4729 case isl_schedule_node_expansion:
4730 case isl_schedule_node_extension:
4731 case isl_schedule_node_guard:
4732 case isl_schedule_node_leaf:
4733 case isl_schedule_node_mark:
4734 case isl_schedule_node_sequence:
4735 case isl_schedule_node_set:
4736 break;
4737 case isl_schedule_node_band:
4738 if (update_may_persist_at_band(node, data) < 0)
4739 return isl_stat_error;
4740 break;
4741 case isl_schedule_node_filter:
4742 if (update_may_persist_at_filter(node, data) < 0)
4743 return isl_stat_error;
4744 break;
4745 }
4746
4747 return isl_stat_ok;
4748}
4749
4750/* Determine the set of array elements that may need to be perserved
4751 * by a kernel constructed from the subtree at "node".
4752 * This includes the set of array elements that may need to be preserved
4753 * by the entire scop (prog->may_persist) and the elements for which
4754 * there is a potential flow dependence that may cross a kernel launch.
4755 *
4756 * To determine the second set, we start from all flow dependences.
4757 * From this set of dependences, we remove those that cannot possibly
4758 * require data to be preserved by a kernel launch.
4759 * In particular, we consider the following sets of dependences.
4760 * - dependences of which the write occurs inside the kernel.
4761 * If the data is needed outside the kernel, then it will
4762 * be copied out immediately after the kernel launch, so there
4763 * is no need for any special care.
4764 * - dependences of which the read occurs inside the kernel and the
4765 * corresponding write occurs inside the same iteration of the
4766 * outer band nodes. This means that the data is needed in
4767 * the first kernel launch after the write, which is already
4768 * taken care of by the standard copy-in. That is, the data
4769 * do not need to be preserved by any intermediate call to
4770 * the same kernel.
4771 * - dependences of which the write and the read either both occur
4772 * before the kernel launch or both occur after the kernel launch,
4773 * within the same iteration of the outer band nodes with respect
4774 * to the sequence that determines the ordering of the dependence
4775 * and the kernel launch. Such flow dependences cannot cross
4776 * any kernel launch.
4777 *
4778 * For the remaining (tagged) dependences, we take the domain
4779 * (i.e., the tagged writes) and apply the tagged access relation
4780 * to obtain the accessed data elements.
4781 * These are then combined with the elements that may need to be
4782 * preserved by the entire scop.
4783 */
4784static __isl_give isl_union_set *node_may_persist(
4785 __isl_keep isl_schedule_node *node, struct gpu_prog *prog)
4786{
4787 struct ppcg_may_persist_data data;
4788 isl_schedule_node *root;
4789 isl_union_pw_multi_aff *contraction;
4790 isl_union_set *domain;
4791 isl_union_set *persist;
4792 isl_union_map *flow, *local_flow;
4793
4794 data.tagger = prog->scop->tagger;
4795
4796 flow = isl_union_map_copy(prog->scop->tagged_dep_flow);
4797 data.local_flow = isl_union_map_copy(flow);
4798 data.inner_band_flow = isl_union_map_copy(flow);
4799 data.may_persist_flow = flow;
4800 if (isl_schedule_node_foreach_ancestor_top_down(node,
4801 &update_may_persist_at, &data) < 0)
4802 data.may_persist_flow =
4803 isl_union_map_free(data.may_persist_flow);
4804 flow = data.may_persist_flow;
4805 isl_union_map_free(data.local_flow);
4806
4807 domain = isl_schedule_node_get_domain(node);
4808 contraction = isl_schedule_node_get_subtree_contraction(node);
4809 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4810 contraction);
4811 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4812 isl_union_pw_multi_aff_copy(data.tagger));
4813 flow = isl_union_map_subtract_domain(flow, isl_union_set_copy(domain));
4814 local_flow = data.inner_band_flow;
4815 local_flow = isl_union_map_intersect_range(local_flow, domain);
4816 flow = isl_union_map_subtract(flow, local_flow);
4817
4818 persist = isl_union_map_domain(flow);
4819 persist = isl_union_set_apply(persist,
4820 isl_union_map_copy(prog->scop->tagged_may_writes));
4821 persist = isl_union_set_union(persist,
4822 isl_union_set_copy(prog->may_persist));
4823
4824 return persist;
4825}
4826
4827/* Add nodes for copying outer arrays in and out of the device
4828 * before and after the subtree "node", which contains one or more kernels.
4829 * "domain" contains the original reaching domain elements before
4830 * the kernels were created, i.e., before the contraction that
4831 * may have been performed in creating the kernels has been applied.
4832 * "prefix" contains the prefix schedule at that point, in terms
4833 * of the same original reaching domain elements.
4834 *
4835 * We first compute the sets of outer array elements that need
4836 * to be copied in and out and then graft in the nodes for
4837 * performing this copying.
4838 *
4839 * In particular, for each array that is possibly written anywhere in
4840 * the subtree "node" and that may be used after "node"
4841 * or that may be visible outside the corresponding scop,
4842 * we copy out its entire extent.
4843 *
4844 * Any array elements that is read without first being written inside
4845 * the subtree "node" needs to be copied in.
4846 * Furthermore, if there are any array elements that
4847 * are copied out, but that may not be written inside "node, then
4848 * they also need to be copied in to ensure that the value after execution
4849 * is the same as the value before execution, at least for those array
4850 * elements that may have their values preserved by the scop or that
4851 * may be written before "node" and read after "node".
4852 * In case the array elements are structures, we need to take into
4853 * account that all members of the structures need to be written
4854 * by "node" before we can avoid copying the data structure in.
4855 *
4856 * Note that the may_write relation is intersected with the domain,
4857 * which has been intersected with the context.
4858 * This helps in those cases where the arrays are declared with a fixed size,
4859 * while the accesses are parametric and the context assigns a fixed value
4860 * to the parameters.
4861 *
4862 * If an element from a local array is read without first being written,
4863 * then there is no point in copying it in since it cannot have been
4864 * written prior to the scop. Warn about the uninitialized read instead.
4865 */
4866static __isl_give isl_schedule_node *add_to_from_device(
4867 __isl_take isl_schedule_node *node, __isl_take isl_union_set *domain,
4868 __isl_take isl_union_map *prefix, struct gpu_prog *prog)
4869{
4870 isl_union_set *local;
4871 isl_union_set *to_device, *from_device, *may_persist;
4872 isl_union_map *may_write, *must_write, *copy_out, *not_written;
4873 isl_union_map *read, *copy_in;
4874 isl_union_map *tagged;
4875 isl_union_map *local_uninitialized;
4876 isl_schedule_node *graft;
4877
4878 tagged = isl_union_map_copy(prog->scop->tagged_reads);
4879 tagged = isl_union_map_union(tagged,
4880 isl_union_map_copy(prog->scop->tagged_may_writes));
4881
4882 may_write = isl_union_map_copy(prog->may_write);
4883 may_write = isl_union_map_intersect_domain(may_write,
4884 isl_union_set_copy(domain));
4885 may_write = remove_local_accesses(prog,
4886 isl_union_map_copy(tagged), may_write,
4887 isl_union_map_copy(prefix), 0);
4888 may_write = isl_union_map_apply_range(may_write,
4889 isl_union_map_copy(prog->to_outer));
4890 may_write = isl_union_map_apply_domain(may_write,
4891 isl_union_map_copy(prefix));
4892 may_write = approximate_copy_out(may_write, prog);
4893 copy_out = isl_union_map_copy(may_write);
4894 may_write = isl_union_map_apply_range(may_write,
4895 isl_union_map_copy(prog->to_inner));
4896 must_write = isl_union_map_copy(prog->must_write);
4897 must_write = isl_union_map_apply_domain(must_write,
4898 isl_union_map_copy(prefix));
4899 may_persist = node_may_persist(node, prog);
4900 may_write = isl_union_map_intersect_range(may_write, may_persist);
4901 not_written = isl_union_map_subtract(may_write, must_write);
4902
4903 local = extract_local_accesses(prog, domain);
4904 read = isl_union_map_copy(prog->read);
4905 read = isl_union_map_intersect_domain(read, domain);
4906 read = remove_local_accesses(prog, tagged, read,
4907 isl_union_map_copy(prefix), 1);
4908 local = isl_union_set_apply(local, isl_union_map_copy(prog->to_inner));
4909 local_uninitialized = isl_union_map_copy(prog->scop->live_in);
4910 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4911 local);
4912 local_uninitialized = isl_union_map_intersect(local_uninitialized,
4913 isl_union_map_copy(read));
4914 if (!isl_union_map_is_empty(local_uninitialized)) {
4915 fprintf(stderrstderr,
4916 "possibly uninitialized reads (not copied in):\n");
4917 isl_union_map_dump(local_uninitialized);
4918 }
4919 read = isl_union_map_subtract(read, local_uninitialized);
4920 read = isl_union_map_apply_domain(read, prefix);
4921 copy_in = isl_union_map_union(read, not_written);
4922 copy_in = isl_union_map_apply_range(copy_in,
4923 isl_union_map_copy(prog->to_outer));
4924
4925 graft = create_copy_device(prog, node, "to_device",
4926 isl_union_map_range(copy_in));
4927 node = isl_schedule_node_graft_before(node, graft);
4928 graft = create_copy_device(prog, node, "from_device",
4929 isl_union_map_range(copy_out));
4930 node = isl_schedule_node_graft_after(node, graft);
4931
4932 return node;
4933}
4934
4935/* Update "schedule" for mapping to a GPU device.
4936 *
4937 * In particular, insert a context node, create kernels for
4938 * each outermost tilable band and introduce node for copying array
4939 * in and out of the device.
4940 * If the child of the initial root points to a set node,
4941 * then children of this node that do not contain any tilable bands
4942 * are separated from the other children and are not mapped to
4943 * the device.
4944 */
4945__isl_give isl_schedule *map_to_device(struct gpu_gen *gen,
4946 __isl_take isl_schedule *schedule)
4947{
4948 isl_schedule_node *node;
4949 isl_set *context;
4950 isl_union_set *domain;
4951 isl_union_map *prefix;
4952
4953 context = isl_set_copy(gen->prog->context);
4954 context = isl_set_from_params(context);
4955 schedule = isl_schedule_insert_context(schedule, context);
4956
4957 node = isl_schedule_get_root(schedule);
4958 isl_schedule_free(schedule);
4959 node = isl_schedule_node_child(node, 0);
4960 if (isl_schedule_node_get_type(node) == isl_schedule_node_context)
4961 node = isl_schedule_node_child(node, 0);
4962 node = isolate_permutable_subtrees(node, gen->prog);
4963 domain = isl_schedule_node_get_domain(node);
4964 prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
4965 node = mark_kernels(gen, node);
4966 node = add_to_from_device(node, domain, prefix, gen->prog);
4967 schedule = isl_schedule_node_get_schedule(node);
4968 isl_schedule_node_free(node);
4969
4970 return schedule;
4971}
4972
4973/* Internal data structure for extract_access.
4974 * "next_access" points to the end of a linked list that is extended
4975 * by extract_access.
4976 * "single_expression" is set if the access expressions belong to
4977 * an expression statement (i.e., a statement without internal control).
4978 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4979 */
4980struct ppcg_extract_access_data {
4981 struct gpu_stmt_access **next_access;
4982 int single_expression;
4983 isl_union_map *any_to_outer;
4984};
4985
4986/* Given a tagged access relation to a single array "tagged", extract it
4987 * as a map, taking into account that the input may be empty.
4988 * If the access relation is empty, then it does not contain
4989 * any space information, so we try to recover it from the index
4990 * expression.
4991 * The space of the index expression is of the form I -> A,
4992 * with I the statement instances and A the array, or [I -> F] -> A,
4993 * with F the filters corresponding to arguments.
4994 * We first drop F, if present, obtaining I -> A.
4995 * Then we construct I -> R, with R the reference tag,
4996 * combine the two into I -> [R -> A] and uncurry to obtain
4997 * the final result [I -> R] -> A.
4998 * Note that the index expression may have a lower dimension
4999 * than that of the array, but this dimension is not used
5000 * if the access relation is empty.
5001 */
5002static __isl_give isl_map *extract_single_tagged_access(
5003 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
5004{
5005 int empty;
5006 isl_id *id;
5007 isl_space *space, *space2;
5008 isl_multi_pw_aff *index;
5009
5010 empty = isl_union_map_is_empty(tagged);
5011 if (empty < 0)
5012 goto error;
5013 if (!empty)
5014 return isl_map_from_union_map(tagged);
5015 isl_union_map_free(tagged);
5016
5017 index = pet_expr_access_get_index(expr);
5018 space = isl_multi_pw_aff_get_space(index);
5019 isl_multi_pw_aff_free(index);
5020 if (isl_space_domain_is_wrapping(space))
5021 space = isl_space_domain_factor_domain(space);
5022 space2 = isl_space_copy(space);
Value stored to 'space2' is never read
5023 space2 = isl_space_from_domain(isl_space_domain(space));
5024 id = pet_expr_access_get_ref_id(expr);
5025 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
5026 space = isl_space_range_product(space2, space);
5027 space = isl_space_uncurry(space);
5028
5029 return isl_map_empty(space);
5030error:
5031 isl_union_map_free(tagged);
5032 return NULL((void*)0);
5033}
5034
5035/* Extract a gpu_stmt_access from "expr", append it to the list
5036 * that ends in *data->next_access and update the end of the list.
5037 * If the access expression performs a write, then it is considered
5038 * exact only if it appears in a single expression statement and
5039 * if its may access relation is equal to its must access relation.
5040 *
5041 * The combined set of may accesses may be union if member accesses
5042 * are involved, but the entire set is derived from a single reference and
5043 * therefore from a single index expression. These accesses therefore
5044 * all map to the same outer array.
5045 */
5046static int extract_access(__isl_keep pet_expr *expr, void *user)
5047{
5048 struct ppcg_extract_access_data *data = user;
5049 isl_union_map *tagged;
5050 struct gpu_stmt_access *access;
5051 isl_ctx *ctx = pet_expr_get_ctx(expr);
5052 isl_multi_pw_aff *index;
5053
5054 access = isl_alloc_type(ctx, struct gpu_stmt_access)((struct gpu_stmt_access *)isl_malloc_or_die(ctx, sizeof(struct
gpu_stmt_access)))
;
5055 assert(access)((access) ? (void) (0) : __assert_fail ("access", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/polly/lib/External/ppcg/gpu.c"
, 5055, __PRETTY_FUNCTION__))
;
5056 access->next = NULL((void*)0);
5057 access->read = pet_expr_access_is_read(expr);
5058 access->write = pet_expr_access_is_write(expr);
5059 tagged = pet_expr_access_get_tagged_may_read(expr);
5060 tagged = isl_union_map_union(tagged,
5061 pet_expr_access_get_tagged_may_write(expr));
5062 tagged = isl_union_map_apply_range(tagged,
5063 isl_union_map_copy(data->any_to_outer));
5064 if (!access->write) {
5065 access->exact_write = 1;
5066 } else if (!data->single_expression) {
5067 access->exact_write = 0;
5068 } else {
5069 isl_union_map *must, *may;
5070 may = isl_union_map_copy(tagged);
5071 may = isl_union_map_domain_factor_domain(may);
5072 must = pet_expr_access_get_must_write(expr);
5073 access->exact_write = isl_union_map_is_equal(must, may);
5074 isl_union_map_free(must);
5075 isl_union_map_free(may);
5076 }
5077 index = pet_expr_access_get_index(expr);
5078 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5079 isl_multi_pw_aff_free(index);
5080 access->ref_id = pet_expr_access_get_ref_id(expr);
5081 access->tagged_access = extract_single_tagged_access(tagged, expr);
5082 access->access = isl_map_copy(access->tagged_access);
5083 access->access = isl_map_domain_factor_domain(access->access);
5084
5085 *data->next_access = access;
5086 data->next_access = &(*data->next_access)->next;
5087
5088 if (!access->access)
5089 return -1;
5090
5091 return 0;
5092}
5093
5094/* Construct a linked list of gpu_stmt_access objects,
5095 * one for each access expression in the statement body.
5096 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5097 */
5098static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5099 __isl_keep isl_union_map *any_to_outer)
5100{
5101 struct ppcg_extract_access_data data;
5102
5103 stmt->accesses = NULL((void*)0);
5104 data.next_access = &stmt->accesses;
5105 data.single_expression =
5106 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5107 data.any_to_outer = any_to_outer;
5108 return pet_tree_foreach_access_expr(stmt->stmt->body,
5109 &extract_access, &data);
5110}
5111
5112/* Return an array of gpu_stmt representing the statements in "scop".
5113 */
5114static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5115 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
5116{
5117 int i;
5118 struct gpu_stmt *stmts;
5119
5120 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt)((struct gpu_stmt *)isl_calloc_or_die(ctx, scop->pet->n_stmt
, sizeof(struct gpu_stmt)))
;
5121 if (!stmts)
5122 return NULL((void*)0);
5123
5124 for (i = 0; i < scop->pet->n_stmt; ++i) {
5125 struct gpu_stmt *s = &stmts[i];
5126
5127 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5128 s->stmt = scop->pet->stmts[i];
5129 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
5130 return free_stmts(stmts, i + 1);
5131 }
5132
5133 return stmts;
5134}
5135
5136/* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5137 */
5138static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5139{
5140 struct gpu_gen *gen = user;
5141
5142 return gen->print(p, gen->prog, gen->tree, &gen->types,
5143 gen->print_user);
5144}
5145
5146/* Generate CUDA code for "scop" and print it to "p".
5147 * After generating an AST for the transformed scop as explained below,
5148 * we call "gen->print" to print the AST in the desired output format
5149 * to "p".
5150 *
5151 * If it turns out that it does not make sense to generate GPU code,
5152 * then we generate CPU code instead.
5153 *
5154 * The GPU code is generated in a context where at least one
5155 * statement instance is executed. The corresponding guard (if any) is printed
5156 * around the entire generated GPU code, except for the declaration
5157 * of the arrays that are visible outside of the scop and that therefore
5158 * cannot be declared inside the body of any possible guard.
5159 *
5160 * We first compute a schedule that respects the dependences
5161 * of the original program and select the outermost bands
5162 * of tilable dimensions that have at least one parallel loop.
5163 * If the --load-schedule is specified, then the loaded schedule
5164 * is used instead of a computed schedule.
5165 *
5166 * Each of these bands B is then tiled according to "tile" sizes, resulting
5167 * in two nested bands, with a kernel marker on top
5168 *
5169 * K
5170 * |
5171 * T
5172 * |
5173 * P
5174 *
5175 * We then split off at most 2 parallel dimensions from the T band and
5176 * at most 3 parallel dimension from the P band
5177 *
5178 * K
5179 * |
5180 * T
5181 * T1
5182 * |
5183 * T2
5184 * |
5185 * P1
5186 * |
5187 * P2
5188 *
5189 * A filter is introduced in front of T1 that maps the domain instances
5190 * to block identifiers. Similarly, a filter is introduced in front of P1
5191 * that maps the domain instances to thread identifiers.
5192 *
5193 * For each iteration of the T2 band and for each array, we compute
5194 * the array elements accessed by that iteration, construct a rectangular
5195 * box around it and shift it to the origin. The result is used
5196 * as shared memory for the array.
5197 *
5198 * Copying and synchronization statements are added to this schedule tree.
5199 * In principle, these are added in front of the P1 band, but some of
5200 * them may get hoisted up to higher levels.
5201 *
5202 * The entire AST is then generated from the single resulting schedule tree.
5203 * During the generation the subtrees at kernel nodes (K) are saved
5204 * aside and replaced by kernel calls. The result is printed as host code
5205 * while the saved subtrees are printed as device code.
5206 */
5207static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5208 struct gpu_gen *gen, struct ppcg_scop *scop,
5209 struct ppcg_options *options)
5210{
5211 struct gpu_prog *prog;
5212 isl_ctx *ctx;
5213 isl_set *context, *guard;
5214 isl_schedule *schedule;
5215 int any_permutable;
5216
5217 if (!scop)
5218 return isl_printer_free(p);
5219
5220 ctx = isl_printer_get_ctx(p);
5221 prog = gpu_prog_alloc(ctx, scop);
5222 if (!prog)
5223 return isl_printer_free(p);
5224
5225 context = isl_set_copy(prog->context);
5226 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5227 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5228
5229 gen->prog = prog;
5230 schedule = get_schedule(gen);
5231
5232 any_permutable = has_any_permutable_node(schedule);
5233 if (any_permutable < 0 || !any_permutable) {
5234 isl_set_free(context);
5235 isl_set_free(guard);
5236 if (any_permutable < 0)
5237 p = isl_printer_free(p);
5238 else
5239 p = print_cpu(p, scop, options);
5240 isl_schedule_free(schedule);
5241 } else {
5242 schedule = map_to_device(gen, schedule);
5243 gen->tree = generate_code(gen, schedule);
5244 p = isl_ast_op_type_print_macro(isl_ast_op_fdiv_q, p);
5245 p = ppcg_print_exposed_declarations(p, prog->scop);
5246 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5247 isl_ast_node_free(gen->tree);
5248 }
5249
5250 gpu_prog_free(prog);
5251
5252 return p;
5253}
5254
5255/* Wrapper around generate for use as a ppcg_transform callback.
5256 */
5257static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5258 struct ppcg_scop *scop, void *user)
5259{
5260 struct gpu_gen *gen = user;
5261
5262 return generate(p, gen, scop, gen->options);
5263}
5264
5265/* Transform the code in the file called "input" by replacing
5266 * all scops by corresponding GPU code and write the results to "out".
5267 */
5268int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5269 struct ppcg_options *options,
5270 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5271 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5272 struct gpu_types *types, void *user), void *user)
5273{
5274 struct gpu_gen gen;
5275 int r;
5276 int i;
5277
5278 gen.ctx = ctx;
5279 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5280 gen.options = options;
5281 gen.kernel_id = 0;
5282 gen.print = print;
5283 gen.print_user = user;
5284 gen.types.n = 0;
5285 gen.types.name = NULL((void*)0);
5286
5287 if (options->debug->dump_sizes) {
5288 isl_space *space = isl_space_params_alloc(ctx, 0);
5289 gen.used_sizes = isl_union_map_empty(space);
5290 }
5291
5292 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5293
5294 if (options->debug->dump_sizes) {
5295 isl_union_map_dump(gen.used_sizes);
5296 isl_union_map_free(gen.used_sizes);
5297 }
5298
5299 isl_union_map_free(gen.sizes);
5300 for (i = 0; i < gen.types.n; ++i)
5301 free(gen.types.name[i]);
5302 free(gen.types.name);
5303
5304 return r;
5305}
5306
5307/* Compute the set of inner array elements that may have their values
5308 * preserved by "prog". In particular, collect the array elements of
5309 * arrays that are not local to "prog" and remove those elements that
5310 * are definitely killed or definitely written by "prog".
5311 */
5312__isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5313{
5314 int i;
5315 isl_union_set *may_persist, *killed;
5316 isl_union_map *must_kill;
5317
5318 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5319 for (i = 0; i < prog->n_array; ++i) {
5320 isl_set *extent;
5321
5322 if (prog->array[i].local)
5323 continue;
5324
5325 extent = isl_set_copy(prog->array[i].extent);
5326 may_persist = isl_union_set_add_set(may_persist, extent);
5327 }
5328
5329 may_persist = isl_union_set_intersect_params(may_persist,
5330 isl_set_copy(prog->context));
5331 may_persist = isl_union_set_apply(may_persist,
5332 isl_union_map_copy(prog->to_inner));
5333 must_kill = isl_union_map_copy(prog->tagged_must_kill);
5334 killed = isl_union_map_range(must_kill);
5335 must_kill = isl_union_map_copy(prog->must_write);
5336 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
5337
5338 may_persist = isl_union_set_subtract(may_persist, killed);
5339 return may_persist;
5340}
5341
5342struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5343{
5344 struct gpu_prog *prog;
5345 isl_space *space;
5346 isl_map *id;
5347
5348 if (!scop)
5349 return NULL((void*)0);
5350
5351 prog = isl_calloc_type(ctx, struct gpu_prog)((struct gpu_prog *)isl_calloc_or_die(ctx, 1, sizeof(struct gpu_prog
)))
;
5352 assert(prog)((prog) ? (void) (0) : __assert_fail ("prog", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/polly/lib/External/ppcg/gpu.c"
, 5352, __PRETTY_FUNCTION__))
;
5353
5354 prog->ctx = ctx;
5355 prog->scop = scop;
5356 prog->context = isl_set_copy(scop->context);
5357 prog->n_stmts = scop->pet->n_stmt;
5358 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5359 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5360 space = isl_union_map_get_space(prog->any_to_outer);
5361 space = isl_space_set_from_params(space);
5362 space = isl_space_add_dims(space, isl_dim_set, 1);
5363 space = isl_space_map_from_set(space);
5364 id = isl_map_identity(space);
5365 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
5366 prog->stmts = extract_stmts(ctx, scop,
5367 prog->context, prog->any_to_outer);
5368 prog->read = isl_union_map_copy(scop->reads);
5369 prog->may_write = isl_union_map_copy(scop->may_writes);
5370 prog->must_write = isl_union_map_copy(scop->must_writes);
5371 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
5372 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
5373 prog->to_outer = isl_union_map_copy(prog->to_inner);
5374 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5375
5376 if (!prog->stmts)
5377 return gpu_prog_free(prog);
5378
5379 if (collect_array_info(prog) < 0)
5380 return gpu_prog_free(prog);
5381 prog->may_persist = compute_may_persist(prog);
5382
5383 return prog;
5384}
5385
5386void *gpu_prog_free(struct gpu_prog *prog)
5387{
5388 if (!prog)
5389 return NULL((void*)0);
5390 free_array_info(prog);
5391 free_stmts(prog->stmts, prog->n_stmts);
5392 isl_union_map_free(prog->any_to_outer);
5393 isl_union_map_free(prog->to_outer);
5394 isl_union_map_free(prog->to_inner);
5395 isl_union_map_free(prog->read);
5396 isl_union_map_free(prog->may_write);
5397 isl_union_map_free(prog->must_write);
5398 isl_union_map_free(prog->tagged_must_kill);
5399 isl_union_map_free(prog->array_order);
5400 isl_union_set_free(prog->may_persist);
5401 isl_set_free(prog->context);
5402 free(prog);
5403 return NULL((void*)0);
5404}