extract out shared gpu_array_requires_device_allocation
[ppcg.git] / opencl.c
blob299b652ea40130b32f41441e6c826366a436f764
1 /*
2 * Copyright 2013 Ecole Normale Superieure
4 * Use of this software is governed by the MIT license
6 * Written by Sven Verdoolaege and Riyadh Baghdadi,
7 * Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
8 */
10 #include <ctype.h>
11 #include <limits.h>
12 #include <string.h>
14 #include <isl/aff.h>
15 #include <isl/ast.h>
17 #include "opencl.h"
18 #include "gpu_print.h"
19 #include "gpu.h"
20 #include "ppcg.h"
21 #include "print.h"
22 #include "schedule.h"
23 #include "util.h"
25 #define min(a, b) (((a) < (b)) ? (a) : (b))
26 #define max(a, b) (((a) > (b)) ? (a) : (b))
28 /* options are the global options passed to generate_opencl.
29 * input is the name of the input file.
30 * output is the user-specified output file name and may be NULL
31 * if not specified by the user.
32 * kernel_c_name is the name of the kernel_c file.
33 * kprinter is an isl_printer for the kernel file.
34 * host_c is the generated source file for the host code. kernel_c is
35 * the generated source file for the kernel.
37 struct opencl_info {
38 struct ppcg_options *options;
39 const char *input;
40 const char *output;
41 char kernel_c_name[PATH_MAX];
43 isl_printer *kprinter;
45 FILE *host_c;
46 FILE *kernel_c;
49 /* Open the file called "name" for writing or print an error message.
51 static FILE *open_or_croak(const char *name)
53 FILE *file;
55 file = fopen(name, "w");
56 if (!file)
57 fprintf(stderr, "Failed to open \"%s\" for writing\n", name);
58 return file;
61 /* Open the host .c file and the kernel .h and .cl files for writing.
62 * Their names are derived from info->output (or info->input if
63 * the user did not specify an output file name).
64 * Add the necessary includes to these files, including those specified
65 * by the user.
67 * Return 0 on success and -1 on failure.
69 static int opencl_open_files(struct opencl_info *info)
71 char name[PATH_MAX];
72 int i;
73 int len;
75 if (info->output) {
76 const char *ext;
78 ext = strrchr(info->output, '.');
79 len = ext ? ext - info->output : strlen(info->output);
80 memcpy(name, info->output, len);
82 info->host_c = open_or_croak(info->output);
83 } else {
84 len = ppcg_extract_base_name(name, info->input);
86 strcpy(name + len, "_host.c");
87 info->host_c = open_or_croak(name);
90 memcpy(info->kernel_c_name, name, len);
91 strcpy(info->kernel_c_name + len, "_kernel.cl");
92 info->kernel_c = open_or_croak(info->kernel_c_name);
94 if (!info->host_c || !info->kernel_c)
95 return -1;
97 fprintf(info->host_c, "#include <assert.h>\n");
98 fprintf(info->host_c, "#include <stdio.h>\n");
99 fprintf(info->host_c, "#include \"ocl_utilities.h\"\n");
100 if (info->options->opencl_embed_kernel_code) {
101 fprintf(info->host_c, "#include \"%s\"\n\n",
102 info->kernel_c_name);
105 for (i = 0; i < info->options->opencl_n_include_file; ++i) {
106 info->kprinter = isl_printer_print_str(info->kprinter,
107 "#include <");
108 info->kprinter = isl_printer_print_str(info->kprinter,
109 info->options->opencl_include_files[i]);
110 info->kprinter = isl_printer_print_str(info->kprinter, ">\n");
113 return 0;
116 /* Write text to a file and escape some special characters that would break a
117 * C string.
119 static void opencl_print_escaped(const char *str, const char *end, FILE *file)
121 const char *prev = str;
123 while ((str = strpbrk(prev, "\"\\")) && str < end) {
124 fwrite(prev, 1, str - prev, file);
125 fprintf(file, "\\%c", *str);
126 prev = str + 1;
129 if (*prev)
130 fwrite(prev, 1, end - prev, file);
133 /* Write text to a file as a C string literal.
135 * This function also prints any characters after the last newline, although
136 * normally the input string should end with a newline.
138 static void opencl_print_as_c_string(const char *str, FILE *file)
140 const char *prev = str;
142 while ((str = strchr(prev, '\n'))) {
143 fprintf(file, "\n\"");
144 opencl_print_escaped(prev, str, file);
145 fprintf(file, "\\n\"");
147 prev = str + 1;
150 if (*prev) {
151 fprintf(file, "\n\"");
152 opencl_print_escaped(prev, prev + strlen(prev), file);
153 fprintf(file, "\"");
157 /* Write the code that we have accumulated in the kernel isl_printer to the
158 * kernel.cl file. If the opencl_embed_kernel_code option has been set, print
159 * the code as a C string literal. Start that string literal with an empty
160 * line, such that line numbers reported by the OpenCL C compiler match those
161 * of the kernel file.
163 * Return 0 on success and -1 on failure.
165 static int opencl_write_kernel_file(struct opencl_info *opencl)
167 char *raw = isl_printer_get_str(opencl->kprinter);
169 if (!raw)
170 return -1;
172 if (opencl->options->opencl_embed_kernel_code) {
173 fprintf(opencl->kernel_c,
174 "static const char kernel_code[] = \"\\n\"");
175 opencl_print_as_c_string(raw, opencl->kernel_c);
176 fprintf(opencl->kernel_c, ";\n");
177 } else
178 fprintf(opencl->kernel_c, "%s", raw);
180 free(raw);
182 return 0;
185 /* Close all output files. Write the kernel contents to the kernel file before
186 * closing it.
188 * Return 0 on success and -1 on failure.
190 static int opencl_close_files(struct opencl_info *info)
192 int r = 0;
194 if (info->kernel_c) {
195 r = opencl_write_kernel_file(info);
196 fclose(info->kernel_c);
198 if (info->host_c)
199 fclose(info->host_c);
201 return r;
204 static __isl_give isl_printer *opencl_print_host_macros(
205 __isl_take isl_printer *p)
207 const char *macros =
208 "#define openclCheckReturn(ret) \\\n"
209 " if (ret != CL_SUCCESS) {\\\n"
210 " fprintf(stderr, \"OpenCL error: %s\\n\", "
211 "opencl_error_string(ret)); \\\n"
212 " fflush(stderr); \\\n"
213 " assert(ret == CL_SUCCESS);\\\n }\n";
215 p = isl_printer_start_line(p);
216 p = isl_printer_print_str(p, macros);
217 p = isl_printer_end_line(p);
219 p = isl_ast_op_type_print_macro(isl_ast_op_max, p);
221 return p;
224 static __isl_give isl_printer *opencl_declare_device_arrays(
225 __isl_take isl_printer *p, struct gpu_prog *prog)
227 int i;
229 for (i = 0; i < prog->n_array; ++i) {
230 if (!gpu_array_requires_device_allocation(&prog->array[i]))
231 continue;
232 p = isl_printer_start_line(p);
233 p = isl_printer_print_str(p, "cl_mem dev_");
234 p = isl_printer_print_str(p, prog->array[i].name);
235 p = isl_printer_print_str(p, ";");
236 p = isl_printer_end_line(p);
238 p = isl_printer_start_line(p);
239 p = isl_printer_end_line(p);
240 return p;
243 /* Given an array, check whether its positive size guard expression is
244 * trivial.
246 static int is_array_positive_size_guard_trivial(struct gpu_array_info *array)
248 isl_set *guard;
249 int is_trivial;
251 guard = gpu_array_positive_size_guard(array);
252 is_trivial = isl_set_plain_is_universe(guard);
253 isl_set_free(guard);
254 return is_trivial;
257 /* Allocate a device array for "array'.
259 * Emit a max-expression to ensure the device array can contain at least one
260 * element if the array's positive size guard expression is not trivial.
262 static __isl_give isl_printer *allocate_device_array(__isl_take isl_printer *p,
263 struct gpu_array_info *array)
265 int need_lower_bound;
267 p = ppcg_start_block(p);
269 p = isl_printer_start_line(p);
270 p = isl_printer_print_str(p, "dev_");
271 p = isl_printer_print_str(p, array->name);
272 p = isl_printer_print_str(p, " = clCreateBuffer(context, ");
273 p = isl_printer_print_str(p, "CL_MEM_READ_WRITE, ");
275 need_lower_bound = !is_array_positive_size_guard_trivial(array);
276 if (need_lower_bound) {
277 p = isl_printer_print_str(p, "max(sizeof(");
278 p = isl_printer_print_str(p, array->type);
279 p = isl_printer_print_str(p, "), ");
281 p = gpu_array_info_print_size(p, array);
282 if (need_lower_bound)
283 p = isl_printer_print_str(p, ")");
285 p = isl_printer_print_str(p, ", NULL, &err);");
286 p = isl_printer_end_line(p);
287 p = isl_printer_start_line(p);
288 p = isl_printer_print_str(p, "openclCheckReturn(err);");
289 p = isl_printer_end_line(p);
291 p = ppcg_end_block(p);
293 return p;
296 /* Allocate accessed device arrays.
298 static __isl_give isl_printer *opencl_allocate_device_arrays(
299 __isl_take isl_printer *p, struct gpu_prog *prog)
301 int i;
303 for (i = 0; i < prog->n_array; ++i) {
304 struct gpu_array_info *array = &prog->array[i];
306 if (!gpu_array_requires_device_allocation(array))
307 continue;
309 p = allocate_device_array(p, array);
311 p = isl_printer_start_line(p);
312 p = isl_printer_end_line(p);
313 return p;
316 /* Print a call to the OpenCL clSetKernelArg() function which sets
317 * the arguments of the kernel. arg_name and arg_index are the name and the
318 * index of the kernel argument. The index of the leftmost argument of
319 * the kernel is 0 whereas the index of the rightmost argument of the kernel
320 * is n - 1, where n is the total number of the kernel arguments.
321 * read_only_scalar is a boolean that indicates whether the argument is a read
322 * only scalar.
324 static __isl_give isl_printer *opencl_set_kernel_argument(
325 __isl_take isl_printer *p, int kernel_id,
326 const char *arg_name, int arg_index, int read_only_scalar)
328 p = isl_printer_start_line(p);
329 p = isl_printer_print_str(p,
330 "openclCheckReturn(clSetKernelArg(kernel");
331 p = isl_printer_print_int(p, kernel_id);
332 p = isl_printer_print_str(p, ", ");
333 p = isl_printer_print_int(p, arg_index);
334 p = isl_printer_print_str(p, ", sizeof(");
336 if (read_only_scalar) {
337 p = isl_printer_print_str(p, arg_name);
338 p = isl_printer_print_str(p, "), &");
339 } else
340 p = isl_printer_print_str(p, "cl_mem), (void *) &dev_");
342 p = isl_printer_print_str(p, arg_name);
343 p = isl_printer_print_str(p, "));");
344 p = isl_printer_end_line(p);
346 return p;
349 /* Print the block sizes as a list of the sizes in each
350 * dimension.
352 static __isl_give isl_printer *opencl_print_block_sizes(
353 __isl_take isl_printer *p, struct ppcg_kernel *kernel)
355 int i;
357 if (kernel->n_block > 0)
358 for (i = 0; i < kernel->n_block; ++i) {
359 if (i)
360 p = isl_printer_print_str(p, ", ");
361 p = isl_printer_print_int(p, kernel->block_dim[i]);
363 else
364 p = isl_printer_print_str(p, "1");
366 return p;
369 /* Set the arguments of the OpenCL kernel by printing a call to the OpenCL
370 * clSetKernelArg() function for each kernel argument.
372 static __isl_give isl_printer *opencl_set_kernel_arguments(
373 __isl_take isl_printer *p, struct gpu_prog *prog,
374 struct ppcg_kernel *kernel)
376 int i, n, ro;
377 unsigned nparam;
378 isl_space *space;
379 int arg_index = 0;
381 for (i = 0; i < prog->n_array; ++i) {
382 int required;
384 required = ppcg_kernel_requires_array_argument(kernel, i);
385 if (required < 0)
386 return isl_printer_free(p);
387 if (!required)
388 continue;
389 ro = gpu_array_is_read_only_scalar(&prog->array[i]);
390 opencl_set_kernel_argument(p, kernel->id, prog->array[i].name,
391 arg_index, ro);
392 arg_index++;
395 space = isl_union_set_get_space(kernel->arrays);
396 nparam = isl_space_dim(space, isl_dim_param);
397 for (i = 0; i < nparam; ++i) {
398 const char *name;
400 name = isl_space_get_dim_name(space, isl_dim_param, i);
401 opencl_set_kernel_argument(p, kernel->id, name, arg_index, 1);
402 arg_index++;
404 isl_space_free(space);
406 n = isl_space_dim(kernel->space, isl_dim_set);
407 for (i = 0; i < n; ++i) {
408 const char *name;
410 name = isl_space_get_dim_name(kernel->space, isl_dim_set, i);
411 opencl_set_kernel_argument(p, kernel->id, name, arg_index, 1);
412 arg_index++;
415 return p;
418 /* Print the arguments to a kernel declaration or call. If "types" is set,
419 * then print a declaration (including the types of the arguments).
421 * The arguments are printed in the following order
422 * - the arrays accessed by the kernel
423 * - the parameters
424 * - the host loop iterators
426 static __isl_give isl_printer *opencl_print_kernel_arguments(
427 __isl_take isl_printer *p, struct gpu_prog *prog,
428 struct ppcg_kernel *kernel, int types)
430 int i, n;
431 int first = 1;
432 unsigned nparam;
433 isl_space *space;
434 const char *type;
436 for (i = 0; i < prog->n_array; ++i) {
437 int required;
439 required = ppcg_kernel_requires_array_argument(kernel, i);
440 if (required < 0)
441 return isl_printer_free(p);
442 if (!required)
443 continue;
445 if (!first)
446 p = isl_printer_print_str(p, ", ");
448 if (types)
449 p = gpu_array_info_print_declaration_argument(p,
450 &prog->array[i], "__global");
451 else
452 p = gpu_array_info_print_call_argument(p,
453 &prog->array[i]);
455 first = 0;
458 space = isl_union_set_get_space(kernel->arrays);
459 nparam = isl_space_dim(space, isl_dim_param);
460 for (i = 0; i < nparam; ++i) {
461 const char *name;
463 name = isl_space_get_dim_name(space, isl_dim_param, i);
465 if (!first)
466 p = isl_printer_print_str(p, ", ");
467 if (types)
468 p = isl_printer_print_str(p, "int ");
469 p = isl_printer_print_str(p, name);
471 first = 0;
473 isl_space_free(space);
475 n = isl_space_dim(kernel->space, isl_dim_set);
476 type = isl_options_get_ast_iterator_type(prog->ctx);
477 for (i = 0; i < n; ++i) {
478 const char *name;
480 if (!first)
481 p = isl_printer_print_str(p, ", ");
482 name = isl_space_get_dim_name(kernel->space, isl_dim_set, i);
483 if (types) {
484 p = isl_printer_print_str(p, type);
485 p = isl_printer_print_str(p, " ");
487 p = isl_printer_print_str(p, name);
489 first = 0;
492 return p;
495 /* Print the header of the given kernel.
497 static __isl_give isl_printer *opencl_print_kernel_header(
498 __isl_take isl_printer *p, struct gpu_prog *prog,
499 struct ppcg_kernel *kernel)
501 p = isl_printer_start_line(p);
502 p = isl_printer_print_str(p, "__kernel void kernel");
503 p = isl_printer_print_int(p, kernel->id);
504 p = isl_printer_print_str(p, "(");
505 p = opencl_print_kernel_arguments(p, prog, kernel, 1);
506 p = isl_printer_print_str(p, ")");
507 p = isl_printer_end_line(p);
509 return p;
512 /* Print a list of iterators of type "type" with names "ids" to "p".
513 * Each iterator is assigned the corresponding opencl identifier returned
514 * by the function "opencl_id".
515 * Unlike the equivalent function in the CUDA backend which prints iterators
516 * in reverse order to promote coalescing, this function does not print
517 * iterators in reverse order. The OpenCL backend currently does not take
518 * into account any coalescing considerations.
520 static __isl_give isl_printer *print_iterators(__isl_take isl_printer *p,
521 const char *type, __isl_keep isl_id_list *ids, const char *opencl_id)
523 int i, n;
525 n = isl_id_list_n_id(ids);
526 if (n <= 0)
527 return p;
528 p = isl_printer_start_line(p);
529 p = isl_printer_print_str(p, type);
530 p = isl_printer_print_str(p, " ");
531 for (i = 0; i < n; ++i) {
532 isl_id *id;
534 if (i)
535 p = isl_printer_print_str(p, ", ");
536 id = isl_id_list_get_id(ids, i);
537 p = isl_printer_print_id(p, id);
538 isl_id_free(id);
539 p = isl_printer_print_str(p, " = ");
540 p = isl_printer_print_str(p, opencl_id);
541 p = isl_printer_print_str(p, "(");
542 p = isl_printer_print_int(p, i);
543 p = isl_printer_print_str(p, ")");
545 p = isl_printer_print_str(p, ";");
546 p = isl_printer_end_line(p);
548 return p;
551 static __isl_give isl_printer *opencl_print_kernel_iterators(
552 __isl_take isl_printer *p, struct ppcg_kernel *kernel)
554 isl_ctx *ctx = isl_ast_node_get_ctx(kernel->tree);
555 const char *type;
557 type = isl_options_get_ast_iterator_type(ctx);
559 p = print_iterators(p, type, kernel->block_ids, "get_group_id");
560 p = print_iterators(p, type, kernel->thread_ids, "get_local_id");
562 return p;
565 static __isl_give isl_printer *opencl_print_kernel_var(
566 __isl_take isl_printer *p, struct ppcg_kernel_var *var)
568 int j;
569 isl_val *v;
571 p = isl_printer_start_line(p);
572 if (var->type == ppcg_access_shared)
573 p = isl_printer_print_str(p, "__local ");
574 p = isl_printer_print_str(p, var->array->type);
575 p = isl_printer_print_str(p, " ");
576 p = isl_printer_print_str(p, var->name);
577 for (j = 0; j < var->array->n_index; ++j) {
578 p = isl_printer_print_str(p, "[");
579 v = isl_vec_get_element_val(var->size, j);
580 p = isl_printer_print_val(p, v);
581 p = isl_printer_print_str(p, "]");
582 isl_val_free(v);
584 p = isl_printer_print_str(p, ";");
585 p = isl_printer_end_line(p);
587 return p;
590 static __isl_give isl_printer *opencl_print_kernel_vars(
591 __isl_take isl_printer *p, struct ppcg_kernel *kernel)
593 int i;
595 for (i = 0; i < kernel->n_var; ++i)
596 p = opencl_print_kernel_var(p, &kernel->var[i]);
598 return p;
601 /* Print a call to barrier() which is a sync statement.
602 * All work-items in a work-group executing the kernel on a processor must
603 * execute the barrier() function before any are allowed to continue execution
604 * beyond the barrier.
605 * The flag CLK_LOCAL_MEM_FENCE makes the barrier function either flush any
606 * variables stored in local memory or queue a memory fence to ensure correct
607 * ordering of memory operations to local memory.
608 * The flag CLK_GLOBAL_MEM_FENCE makes the barrier function queue a memory
609 * fence to ensure correct ordering of memory operations to global memory.
611 static __isl_give isl_printer *opencl_print_sync(__isl_take isl_printer *p,
612 struct ppcg_kernel_stmt *stmt)
614 p = isl_printer_start_line(p);
615 p = isl_printer_print_str(p,
616 "barrier(CLK_LOCAL_MEM_FENCE | CLK_GLOBAL_MEM_FENCE);");
617 p = isl_printer_end_line(p);
619 return p;
622 /* Data structure containing function names for which the calls
623 * should be changed from
625 * name(arg)
627 * to
629 * opencl_name((type) (arg))
631 static struct ppcg_opencl_fn {
632 const char *name;
633 const char *opencl_name;
634 const char *type;
635 } opencl_fn[] = {
636 { "expf", "exp", "float" },
637 { "powf", "pow", "float" },
638 { "sqrtf", "sqrt", "float" },
641 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
643 /* If the name of function called by "expr" matches any of those
644 * in ppcg_opencl_fn, then replace the call by a cast to the corresponding
645 * type in ppcg_opencl_fn and a call to corresponding OpenCL function.
647 static __isl_give pet_expr *map_opencl_call(__isl_take pet_expr *expr,
648 void *user)
650 const char *name;
651 int i;
653 name = pet_expr_call_get_name(expr);
654 for (i = 0; i < ARRAY_SIZE(opencl_fn); ++i) {
655 pet_expr *arg;
657 if (strcmp(name, opencl_fn[i].name))
658 continue;
659 expr = pet_expr_call_set_name(expr, opencl_fn[i].opencl_name);
660 arg = pet_expr_get_arg(expr, 0);
661 arg = pet_expr_new_cast(opencl_fn[i].type, arg);
662 expr = pet_expr_set_arg(expr, 0, arg);
664 return expr;
667 /* Print the body of a statement from the input program,
668 * for use in OpenCL code.
670 * Before calling ppcg_kernel_print_domain to print the actual statement body,
671 * we first modify this body to take into account that the output code
672 * is OpenCL code. In particular, if the statement calls any function
673 * with a "f" suffix, then it needs to be replaced by a call to
674 * the corresponding function without suffix after casting the argument
675 * to a float.
677 static __isl_give isl_printer *print_opencl_kernel_domain(
678 __isl_take isl_printer *p, struct ppcg_kernel_stmt *stmt)
680 struct pet_stmt *ps;
681 pet_tree *tree;
683 ps = stmt->u.d.stmt->stmt;
684 tree = pet_tree_copy(ps->body);
685 ps->body = pet_tree_map_call_expr(ps->body, &map_opencl_call, NULL);
686 p = ppcg_kernel_print_domain(p, stmt);
687 pet_tree_free(ps->body);
688 ps->body = tree;
690 return p;
693 /* This function is called for each user statement in the AST,
694 * i.e., for each kernel body statement, copy statement or sync statement.
696 static __isl_give isl_printer *opencl_print_kernel_stmt(
697 __isl_take isl_printer *p,
698 __isl_take isl_ast_print_options *print_options,
699 __isl_keep isl_ast_node *node, void *user)
701 isl_id *id;
702 struct ppcg_kernel_stmt *stmt;
704 id = isl_ast_node_get_annotation(node);
705 stmt = isl_id_get_user(id);
706 isl_id_free(id);
708 isl_ast_print_options_free(print_options);
710 switch (stmt->type) {
711 case ppcg_kernel_copy:
712 return ppcg_kernel_print_copy(p, stmt);
713 case ppcg_kernel_sync:
714 return opencl_print_sync(p, stmt);
715 case ppcg_kernel_domain:
716 return print_opencl_kernel_domain(p, stmt);
719 return p;
722 /* Return true if there is a double array in prog->array or
723 * if any of the types in prog->scop involve any doubles.
724 * To check the latter condition, we simply search for the string "double"
725 * in the type definitions, which may result in false positives.
727 static __isl_give int any_double_elements(struct gpu_prog *prog)
729 int i;
731 for (i = 0; i < prog->n_array; ++i)
732 if (strcmp(prog->array[i].type, "double") == 0)
733 return 1;
735 for (i = 0; i < prog->scop->pet->n_type; ++i) {
736 struct pet_type *type = prog->scop->pet->types[i];
738 if (strstr(type->definition, "double"))
739 return 1;
742 return 0;
745 /* Prints a #pragma to enable support for double floating-point
746 * precision. OpenCL 1.0 adds support for double precision floating-point as
747 * an optional extension. An application that wants to use double will need to
748 * include the #pragma OPENCL EXTENSION cl_khr_fp64 : enable directive before
749 * any double precision data type is declared in the kernel code.
751 static __isl_give isl_printer *opencl_enable_double_support(
752 __isl_take isl_printer *p)
754 p = isl_printer_start_line(p);
755 p = isl_printer_print_str(p, "#pragma OPENCL EXTENSION cl_khr_fp64 :"
756 " enable");
757 p = isl_printer_end_line(p);
758 p = isl_printer_start_line(p);
759 p = isl_printer_end_line(p);
761 return p;
764 static __isl_give isl_printer *opencl_print_kernel(struct gpu_prog *prog,
765 struct ppcg_kernel *kernel, __isl_take isl_printer *p)
767 isl_ctx *ctx = isl_ast_node_get_ctx(kernel->tree);
768 isl_ast_print_options *print_options;
770 print_options = isl_ast_print_options_alloc(ctx);
771 print_options = isl_ast_print_options_set_print_user(print_options,
772 &opencl_print_kernel_stmt, NULL);
774 p = isl_printer_set_output_format(p, ISL_FORMAT_C);
775 p = opencl_print_kernel_header(p, prog, kernel);
776 p = isl_printer_print_str(p, "{");
777 p = isl_printer_end_line(p);
778 p = isl_printer_indent(p, 4);
779 p = opencl_print_kernel_iterators(p, kernel);
780 p = opencl_print_kernel_vars(p, kernel);
781 p = isl_printer_end_line(p);
782 p = gpu_print_macros(p, kernel->tree);
783 p = isl_ast_node_print(kernel->tree, p, print_options);
784 p = isl_printer_indent(p, -4);
785 p = isl_printer_start_line(p);
786 p = isl_printer_print_str(p, "}");
787 p = isl_printer_end_line(p);
789 return p;
792 struct print_host_user_data_opencl {
793 struct opencl_info *opencl;
794 struct gpu_prog *prog;
797 /* This function prints the i'th block size multiplied by the i'th grid size,
798 * where i (a parameter to this function) is one of the possible dimensions of
799 * grid sizes and block sizes.
800 * If the dimension of block sizes is not equal to the dimension of grid sizes
801 * the output is calculated as follows:
803 * Suppose that:
804 * block_sizes[dim1] is the list of blocks sizes and it contains dim1 elements.
805 * grid_sizes[dim2] is the list of grid sizes and it contains dim2 elements.
807 * The output is:
808 * If (i > dim2) then the output is block_sizes[i]
809 * If (i > dim1) then the output is grid_sizes[i]
811 static __isl_give isl_printer *opencl_print_total_number_of_work_items_for_dim(
812 __isl_take isl_printer *p, struct ppcg_kernel *kernel, int i)
814 int grid_dim, block_dim;
815 isl_pw_aff *bound_grid;
817 grid_dim = isl_multi_pw_aff_dim(kernel->grid_size, isl_dim_set);
818 block_dim = kernel->n_block;
820 if (i < min(grid_dim, block_dim)) {
821 bound_grid = isl_multi_pw_aff_get_pw_aff(kernel->grid_size, i);
822 p = isl_printer_print_str(p, "(");
823 p = isl_printer_print_pw_aff(p, bound_grid);
824 p = isl_printer_print_str(p, ") * ");
825 p = isl_printer_print_int(p, kernel->block_dim[i]);
826 isl_pw_aff_free(bound_grid);
827 } else if (i >= grid_dim)
828 p = isl_printer_print_int(p, kernel->block_dim[i]);
829 else {
830 bound_grid = isl_multi_pw_aff_get_pw_aff(kernel->grid_size, i);
831 p = isl_printer_print_pw_aff(p, bound_grid);
832 isl_pw_aff_free(bound_grid);
835 return p;
838 /* Print a list that represents the total number of work items. The list is
839 * constructed by performing an element-wise multiplication of the block sizes
840 * and the grid sizes. To explain how the list is constructed, suppose that:
841 * block_sizes[dim1] is the list of blocks sizes and it contains dim1 elements.
842 * grid_sizes[dim2] is the list of grid sizes and it contains dim2 elements.
844 * The output of this function is constructed as follows:
845 * If (dim1 > dim2) then the output is the following list:
846 * grid_sizes[0]*block_sizes[0], ..., grid_sizes[dim2-1]*block_sizes[dim2-1],
847 * block_sizes[dim2], ..., block_sizes[dim1-2], block_sizes[dim1-1].
849 * If (dim2 > dim1) then the output is the following list:
850 * grid_sizes[0]*block_sizes[0], ..., grid_sizes[dim1-1] * block_sizes[dim1-1],
851 * grid_sizes[dim1], grid_sizes[dim2-2], grid_sizes[dim2-1].
853 * To calculate the total number of work items out of the list constructed by
854 * this function, the user should multiply the elements of the list.
856 static __isl_give isl_printer *opencl_print_total_number_of_work_items_as_list(
857 __isl_take isl_printer *p, struct ppcg_kernel *kernel)
859 int i;
860 int grid_dim, block_dim;
862 grid_dim = isl_multi_pw_aff_dim(kernel->grid_size, isl_dim_set);
863 block_dim = kernel->n_block;
865 if ((grid_dim <= 0) || (block_dim <= 0)) {
866 p = isl_printer_print_str(p, "1");
867 return p;
870 for (i = 0; i <= max(grid_dim, block_dim) - 1; i++) {
871 if (i > 0)
872 p = isl_printer_print_str(p, ", ");
874 p = opencl_print_total_number_of_work_items_for_dim(p,
875 kernel, i);
878 return p;
881 /* Copy "array" from the host to the device (to_host = 0) or
882 * back from the device to the host (to_host = 1).
884 static __isl_give isl_printer *copy_array(__isl_take isl_printer *p,
885 struct gpu_array_info *array, int to_host)
887 p = isl_printer_start_line(p);
888 p = isl_printer_print_str(p, "openclCheckReturn(");
889 if (to_host)
890 p = isl_printer_print_str(p, "clEnqueueReadBuffer");
891 else
892 p = isl_printer_print_str(p, "clEnqueueWriteBuffer");
893 p = isl_printer_print_str(p, "(queue, dev_");
894 p = isl_printer_print_str(p, array->name);
895 p = isl_printer_print_str(p, ", CL_TRUE, 0, ");
896 p = gpu_array_info_print_size(p, array);
898 if (gpu_array_is_scalar(array))
899 p = isl_printer_print_str(p, ", &");
900 else
901 p = isl_printer_print_str(p, ", ");
902 p = isl_printer_print_str(p, array->name);
903 p = isl_printer_print_str(p, ", 0, NULL, NULL));");
904 p = isl_printer_end_line(p);
906 return p;
909 /* Print a statement for copying an array to or from the device.
910 * The statement identifier is called "to_device_<array name>" or
911 * "from_device_<array name>" and its user pointer points
912 * to the gpu_array_info of the array that needs to be copied.
914 * Extract the array from the identifier and call
915 * copy_array_to_device or copy_array_from_device.
917 static __isl_give isl_printer *print_to_from_device(__isl_take isl_printer *p,
918 __isl_keep isl_ast_node *node, struct gpu_prog *prog)
920 isl_ast_expr *expr, *arg;
921 isl_id *id;
922 const char *name;
923 struct gpu_array_info *array;
925 expr = isl_ast_node_user_get_expr(node);
926 arg = isl_ast_expr_get_op_arg(expr, 0);
927 id = isl_ast_expr_get_id(arg);
928 name = isl_id_get_name(id);
929 array = isl_id_get_user(id);
930 isl_id_free(id);
931 isl_ast_expr_free(arg);
932 isl_ast_expr_free(expr);
934 if (!name)
935 array = NULL;
936 if (!array)
937 return isl_printer_free(p);
939 if (!prefixcmp(name, "to_device"))
940 return copy_array(p, array, 0);
941 else
942 return copy_array(p, array, 1);
945 /* Print the user statement of the host code to "p".
947 * The host code may contain original user statements, kernel launches and
948 * statements that copy data to/from the device.
949 * The original user statements and the kernel launches have
950 * an associated annotation, while the data copy statements do not.
951 * The latter are handled by print_to_from_device.
952 * The annotation on the user statements is called "user".
954 * In case of a kernel launch, print a block of statements that
955 * defines the grid and the work group and then launches the kernel.
957 * A grid is composed of many work groups (blocks), each work group holds
958 * many work-items (threads).
960 * global_work_size[kernel->n_block] represents the total number of work
961 * items. It points to an array of kernel->n_block unsigned
962 * values that describe the total number of work-items that will execute
963 * the kernel. The total number of work-items is computed as:
964 * global_work_size[0] *...* global_work_size[kernel->n_block - 1].
966 * The size of each work group (i.e. the number of work-items in each work
967 * group) is described using block_size[kernel->n_block]. The total
968 * number of work-items in a block (work-group) is computed as:
969 * block_size[0] *... * block_size[kernel->n_block - 1].
971 * For more information check:
972 * http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/clEnqueueNDRangeKernel.html
974 static __isl_give isl_printer *opencl_print_host_user(
975 __isl_take isl_printer *p,
976 __isl_take isl_ast_print_options *print_options,
977 __isl_keep isl_ast_node *node, void *user)
979 isl_id *id;
980 int is_user;
981 struct ppcg_kernel *kernel;
982 struct ppcg_kernel_stmt *stmt;
983 struct print_host_user_data_opencl *data;
985 isl_ast_print_options_free(print_options);
987 data = (struct print_host_user_data_opencl *) user;
989 id = isl_ast_node_get_annotation(node);
990 if (!id)
991 return print_to_from_device(p, node, data->prog);
993 is_user = !strcmp(isl_id_get_name(id), "user");
994 kernel = is_user ? NULL : isl_id_get_user(id);
995 stmt = is_user ? isl_id_get_user(id) : NULL;
996 isl_id_free(id);
998 if (is_user)
999 return ppcg_kernel_print_domain(p, stmt);
1001 p = isl_printer_start_line(p);
1002 p = isl_printer_print_str(p, "{");
1003 p = isl_printer_end_line(p);
1004 p = isl_printer_indent(p, 2);
1006 p = isl_printer_start_line(p);
1007 p = isl_printer_print_str(p, "size_t global_work_size[");
1009 if (kernel->n_block > 0)
1010 p = isl_printer_print_int(p, kernel->n_block);
1011 else
1012 p = isl_printer_print_int(p, 1);
1014 p = isl_printer_print_str(p, "] = {");
1015 p = opencl_print_total_number_of_work_items_as_list(p, kernel);
1016 p = isl_printer_print_str(p, "};");
1017 p = isl_printer_end_line(p);
1019 p = isl_printer_start_line(p);
1020 p = isl_printer_print_str(p, "size_t block_size[");
1022 if (kernel->n_block > 0)
1023 p = isl_printer_print_int(p, kernel->n_block);
1024 else
1025 p = isl_printer_print_int(p, 1);
1027 p = isl_printer_print_str(p, "] = {");
1028 p = opencl_print_block_sizes(p, kernel);
1029 p = isl_printer_print_str(p, "};");
1030 p = isl_printer_end_line(p);
1032 p = isl_printer_start_line(p);
1033 p = isl_printer_print_str(p, "cl_kernel kernel");
1034 p = isl_printer_print_int(p, kernel->id);
1035 p = isl_printer_print_str(p, " = clCreateKernel(program, \"kernel");
1036 p = isl_printer_print_int(p, kernel->id);
1037 p = isl_printer_print_str(p, "\", &err);");
1038 p = isl_printer_end_line(p);
1039 p = isl_printer_start_line(p);
1040 p = isl_printer_print_str(p, "openclCheckReturn(err);");
1041 p = isl_printer_end_line(p);
1043 opencl_set_kernel_arguments(p, data->prog, kernel);
1045 p = isl_printer_start_line(p);
1046 p = isl_printer_print_str(p, "openclCheckReturn(clEnqueueNDRangeKernel"
1047 "(queue, kernel");
1048 p = isl_printer_print_int(p, kernel->id);
1049 p = isl_printer_print_str(p, ", ");
1050 if (kernel->n_block > 0)
1051 p = isl_printer_print_int(p, kernel->n_block);
1052 else
1053 p = isl_printer_print_int(p, 1);
1055 p = isl_printer_print_str(p, ", NULL, global_work_size, "
1056 "block_size, "
1057 "0, NULL, NULL));");
1058 p = isl_printer_end_line(p);
1059 p = isl_printer_start_line(p);
1060 p = isl_printer_print_str(p, "openclCheckReturn("
1061 "clReleaseKernel(kernel");
1062 p = isl_printer_print_int(p, kernel->id);
1063 p = isl_printer_print_str(p, "));");
1064 p = isl_printer_end_line(p);
1065 p = isl_printer_start_line(p);
1066 p = isl_printer_print_str(p, "clFinish(queue);");
1067 p = isl_printer_end_line(p);
1068 p = isl_printer_indent(p, -2);
1069 p = isl_printer_start_line(p);
1070 p = isl_printer_print_str(p, "}");
1071 p = isl_printer_end_line(p);
1073 p = isl_printer_start_line(p);
1074 p = isl_printer_end_line(p);
1076 data->opencl->kprinter = opencl_print_kernel(data->prog, kernel,
1077 data->opencl->kprinter);
1079 return p;
1082 static __isl_give isl_printer *opencl_print_host_code(
1083 __isl_take isl_printer *p, struct gpu_prog *prog,
1084 __isl_keep isl_ast_node *tree, struct opencl_info *opencl)
1086 isl_ast_print_options *print_options;
1087 isl_ctx *ctx = isl_ast_node_get_ctx(tree);
1088 struct print_host_user_data_opencl data = { opencl, prog };
1090 print_options = isl_ast_print_options_alloc(ctx);
1091 print_options = isl_ast_print_options_set_print_user(print_options,
1092 &opencl_print_host_user, &data);
1094 p = gpu_print_macros(p, tree);
1095 p = isl_ast_node_print(tree, p, print_options);
1097 return p;
1100 /* Create an OpenCL device, context, command queue and build the kernel.
1101 * input is the name of the input file provided to ppcg.
1103 static __isl_give isl_printer *opencl_setup(__isl_take isl_printer *p,
1104 const char *input, struct opencl_info *info)
1106 p = isl_printer_start_line(p);
1107 p = isl_printer_print_str(p, "cl_device_id device;");
1108 p = isl_printer_end_line(p);
1109 p = isl_printer_start_line(p);
1110 p = isl_printer_print_str(p, "cl_context context;");
1111 p = isl_printer_end_line(p);
1112 p = isl_printer_start_line(p);
1113 p = isl_printer_print_str(p, "cl_program program;");
1114 p = isl_printer_end_line(p);
1115 p = isl_printer_start_line(p);
1116 p = isl_printer_print_str(p, "cl_command_queue queue;");
1117 p = isl_printer_end_line(p);
1118 p = isl_printer_start_line(p);
1119 p = isl_printer_print_str(p, "cl_int err;");
1120 p = isl_printer_end_line(p);
1121 p = isl_printer_start_line(p);
1122 p = isl_printer_print_str(p, "device = opencl_create_device(");
1123 p = isl_printer_print_int(p, info->options->opencl_use_gpu);
1124 p = isl_printer_print_str(p, ");");
1125 p = isl_printer_end_line(p);
1126 p = isl_printer_start_line(p);
1127 p = isl_printer_print_str(p, "context = clCreateContext(NULL, 1, "
1128 "&device, NULL, NULL, &err);");
1129 p = isl_printer_end_line(p);
1130 p = isl_printer_start_line(p);
1131 p = isl_printer_print_str(p, "openclCheckReturn(err);");
1132 p = isl_printer_end_line(p);
1133 p = isl_printer_start_line(p);
1134 p = isl_printer_print_str(p, "queue = clCreateCommandQueue"
1135 "(context, device, 0, &err);");
1136 p = isl_printer_end_line(p);
1137 p = isl_printer_start_line(p);
1138 p = isl_printer_print_str(p, "openclCheckReturn(err);");
1139 p = isl_printer_end_line(p);
1141 p = isl_printer_start_line(p);
1142 p = isl_printer_print_str(p, "program = ");
1144 if (info->options->opencl_embed_kernel_code) {
1145 p = isl_printer_print_str(p, "opencl_build_program_from_string("
1146 "context, device, kernel_code, "
1147 "sizeof(kernel_code), \"");
1148 } else {
1149 p = isl_printer_print_str(p, "opencl_build_program_from_file("
1150 "context, device, \"");
1151 p = isl_printer_print_str(p, info->kernel_c_name);
1152 p = isl_printer_print_str(p, "\", \"");
1155 if (info->options->opencl_compiler_options)
1156 p = isl_printer_print_str(p,
1157 info->options->opencl_compiler_options);
1159 p = isl_printer_print_str(p, "\");");
1160 p = isl_printer_end_line(p);
1161 p = isl_printer_start_line(p);
1162 p = isl_printer_end_line(p);
1164 return p;
1167 static __isl_give isl_printer *opencl_release_cl_objects(
1168 __isl_take isl_printer *p, struct opencl_info *info)
1170 p = isl_printer_start_line(p);
1171 p = isl_printer_print_str(p, "openclCheckReturn(clReleaseCommandQueue"
1172 "(queue));");
1173 p = isl_printer_end_line(p);
1174 p = isl_printer_start_line(p);
1175 p = isl_printer_print_str(p, "openclCheckReturn(clReleaseProgram"
1176 "(program));");
1177 p = isl_printer_end_line(p);
1178 p = isl_printer_start_line(p);
1179 p = isl_printer_print_str(p, "openclCheckReturn(clReleaseContext"
1180 "(context));");
1181 p = isl_printer_end_line(p);
1183 return p;
1186 /* Free the device array corresponding to "array"
1188 static __isl_give isl_printer *release_device_array(__isl_take isl_printer *p,
1189 struct gpu_array_info *array)
1191 p = isl_printer_start_line(p);
1192 p = isl_printer_print_str(p, "openclCheckReturn("
1193 "clReleaseMemObject(dev_");
1194 p = isl_printer_print_str(p, array->name);
1195 p = isl_printer_print_str(p, "));");
1196 p = isl_printer_end_line(p);
1198 return p;
1201 /* Free the accessed device arrays.
1203 static __isl_give isl_printer *opencl_release_device_arrays(
1204 __isl_take isl_printer *p, struct gpu_prog *prog)
1206 int i;
1208 for (i = 0; i < prog->n_array; ++i) {
1209 struct gpu_array_info *array = &prog->array[i];
1210 if (!gpu_array_requires_device_allocation(array))
1211 continue;
1213 p = release_device_array(p, array);
1215 return p;
1218 /* Given a gpu_prog "prog" and the corresponding transformed AST
1219 * "tree", print the entire OpenCL code to "p".
1221 static __isl_give isl_printer *print_opencl(__isl_take isl_printer *p,
1222 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
1223 struct gpu_types *types, void *user)
1225 struct opencl_info *opencl = user;
1227 opencl->kprinter = isl_printer_set_output_format(opencl->kprinter,
1228 ISL_FORMAT_C);
1229 if (any_double_elements(prog))
1230 opencl->kprinter = opencl_enable_double_support(
1231 opencl->kprinter);
1232 if (opencl->options->opencl_print_kernel_types)
1233 opencl->kprinter = gpu_print_types(opencl->kprinter, types,
1234 prog);
1236 if (!opencl->kprinter)
1237 return isl_printer_free(p);
1239 p = ppcg_start_block(p);
1241 p = opencl_print_host_macros(p);
1243 p = gpu_print_local_declarations(p, prog);
1244 p = opencl_declare_device_arrays(p, prog);
1245 p = opencl_setup(p, opencl->input, opencl);
1246 p = opencl_allocate_device_arrays(p, prog);
1248 p = opencl_print_host_code(p, prog, tree, opencl);
1250 p = opencl_release_device_arrays(p, prog);
1251 p = opencl_release_cl_objects(p, opencl);
1253 p = ppcg_end_block(p);
1255 return p;
1258 /* Transform the code in the file called "input" by replacing
1259 * all scops by corresponding OpenCL code.
1260 * The host code is written to "output" or a name derived from
1261 * "input" if "output" is NULL.
1262 * The kernel code is placed in separate files with names
1263 * derived from "output" or "input".
1265 * We let generate_gpu do all the hard work and then let it call
1266 * us back for printing the AST in print_opencl.
1268 * To prepare for this printing, we first open the output files
1269 * and we close them after generate_gpu has finished.
1271 int generate_opencl(isl_ctx *ctx, struct ppcg_options *options,
1272 const char *input, const char *output)
1274 struct opencl_info opencl = { options, input, output };
1275 int r;
1277 opencl.kprinter = isl_printer_to_str(ctx);
1278 r = opencl_open_files(&opencl);
1280 if (r >= 0)
1281 r = generate_gpu(ctx, input, opencl.host_c, options,
1282 &print_opencl, &opencl);
1284 if (opencl_close_files(&opencl) < 0)
1285 r = -1;
1286 isl_printer_free(opencl.kprinter);
1288 return r;