opencl.c: fix minor style issue
[ppcg.git] / opencl.c
blob097a0834a01cc1cbd0eed0fe936efce0f78520e4
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, ppcg_max);
278 p = isl_printer_print_str(p, "(sizeof(");
279 p = isl_printer_print_str(p, array->type);
280 p = isl_printer_print_str(p, "), ");
282 p = gpu_array_info_print_size(p, array);
283 if (need_lower_bound)
284 p = isl_printer_print_str(p, ")");
286 p = isl_printer_print_str(p, ", NULL, &err);");
287 p = isl_printer_end_line(p);
288 p = isl_printer_start_line(p);
289 p = isl_printer_print_str(p, "openclCheckReturn(err);");
290 p = isl_printer_end_line(p);
292 p = ppcg_end_block(p);
294 return p;
297 /* Allocate accessed device arrays.
299 static __isl_give isl_printer *opencl_allocate_device_arrays(
300 __isl_take isl_printer *p, struct gpu_prog *prog)
302 int i;
304 for (i = 0; i < prog->n_array; ++i) {
305 struct gpu_array_info *array = &prog->array[i];
307 if (!gpu_array_requires_device_allocation(array))
308 continue;
310 p = allocate_device_array(p, array);
312 p = isl_printer_start_line(p);
313 p = isl_printer_end_line(p);
314 return p;
317 /* Free the device array corresponding to "array"
319 static __isl_give isl_printer *release_device_array(__isl_take isl_printer *p,
320 struct gpu_array_info *array)
322 p = isl_printer_start_line(p);
323 p = isl_printer_print_str(p, "openclCheckReturn("
324 "clReleaseMemObject(dev_");
325 p = isl_printer_print_str(p, array->name);
326 p = isl_printer_print_str(p, "));");
327 p = isl_printer_end_line(p);
329 return p;
332 /* Free the accessed device arrays.
334 static __isl_give isl_printer *opencl_release_device_arrays(
335 __isl_take isl_printer *p, struct gpu_prog *prog)
337 int i;
339 for (i = 0; i < prog->n_array; ++i) {
340 struct gpu_array_info *array = &prog->array[i];
341 if (!gpu_array_requires_device_allocation(array))
342 continue;
344 p = release_device_array(p, array);
346 return p;
349 /* Create an OpenCL device, context, command queue and build the kernel.
350 * input is the name of the input file provided to ppcg.
352 static __isl_give isl_printer *opencl_setup(__isl_take isl_printer *p,
353 const char *input, struct opencl_info *info)
355 p = isl_printer_start_line(p);
356 p = isl_printer_print_str(p, "cl_device_id device;");
357 p = isl_printer_end_line(p);
358 p = isl_printer_start_line(p);
359 p = isl_printer_print_str(p, "cl_context context;");
360 p = isl_printer_end_line(p);
361 p = isl_printer_start_line(p);
362 p = isl_printer_print_str(p, "cl_program program;");
363 p = isl_printer_end_line(p);
364 p = isl_printer_start_line(p);
365 p = isl_printer_print_str(p, "cl_command_queue queue;");
366 p = isl_printer_end_line(p);
367 p = isl_printer_start_line(p);
368 p = isl_printer_print_str(p, "cl_int err;");
369 p = isl_printer_end_line(p);
370 p = isl_printer_start_line(p);
371 p = isl_printer_print_str(p, "device = opencl_create_device(");
372 p = isl_printer_print_int(p, info->options->opencl_use_gpu);
373 p = isl_printer_print_str(p, ");");
374 p = isl_printer_end_line(p);
375 p = isl_printer_start_line(p);
376 p = isl_printer_print_str(p, "context = clCreateContext(NULL, 1, "
377 "&device, NULL, NULL, &err);");
378 p = isl_printer_end_line(p);
379 p = isl_printer_start_line(p);
380 p = isl_printer_print_str(p, "openclCheckReturn(err);");
381 p = isl_printer_end_line(p);
382 p = isl_printer_start_line(p);
383 p = isl_printer_print_str(p, "queue = clCreateCommandQueue"
384 "(context, device, 0, &err);");
385 p = isl_printer_end_line(p);
386 p = isl_printer_start_line(p);
387 p = isl_printer_print_str(p, "openclCheckReturn(err);");
388 p = isl_printer_end_line(p);
390 p = isl_printer_start_line(p);
391 p = isl_printer_print_str(p, "program = ");
393 if (info->options->opencl_embed_kernel_code) {
394 p = isl_printer_print_str(p, "opencl_build_program_from_string("
395 "context, device, kernel_code, "
396 "sizeof(kernel_code), \"");
397 } else {
398 p = isl_printer_print_str(p, "opencl_build_program_from_file("
399 "context, device, \"");
400 p = isl_printer_print_str(p, info->kernel_c_name);
401 p = isl_printer_print_str(p, "\", \"");
404 if (info->options->opencl_compiler_options)
405 p = isl_printer_print_str(p,
406 info->options->opencl_compiler_options);
408 p = isl_printer_print_str(p, "\");");
409 p = isl_printer_end_line(p);
410 p = isl_printer_start_line(p);
411 p = isl_printer_end_line(p);
413 return p;
416 static __isl_give isl_printer *opencl_release_cl_objects(
417 __isl_take isl_printer *p, struct opencl_info *info)
419 p = isl_printer_start_line(p);
420 p = isl_printer_print_str(p, "openclCheckReturn(clReleaseCommandQueue"
421 "(queue));");
422 p = isl_printer_end_line(p);
423 p = isl_printer_start_line(p);
424 p = isl_printer_print_str(p, "openclCheckReturn(clReleaseProgram"
425 "(program));");
426 p = isl_printer_end_line(p);
427 p = isl_printer_start_line(p);
428 p = isl_printer_print_str(p, "openclCheckReturn(clReleaseContext"
429 "(context));");
430 p = isl_printer_end_line(p);
432 return p;
435 /* Print a call to the OpenCL clSetKernelArg() function which sets
436 * the arguments of the kernel. arg_name and arg_index are the name and the
437 * index of the kernel argument. The index of the leftmost argument of
438 * the kernel is 0 whereas the index of the rightmost argument of the kernel
439 * is n - 1, where n is the total number of the kernel arguments.
440 * read_only_scalar is a boolean that indicates whether the argument is a read
441 * only scalar.
443 static __isl_give isl_printer *opencl_set_kernel_argument(
444 __isl_take isl_printer *p, int kernel_id,
445 const char *arg_name, int arg_index, int read_only_scalar)
447 p = isl_printer_start_line(p);
448 p = isl_printer_print_str(p,
449 "openclCheckReturn(clSetKernelArg(kernel");
450 p = isl_printer_print_int(p, kernel_id);
451 p = isl_printer_print_str(p, ", ");
452 p = isl_printer_print_int(p, arg_index);
453 p = isl_printer_print_str(p, ", sizeof(");
455 if (read_only_scalar) {
456 p = isl_printer_print_str(p, arg_name);
457 p = isl_printer_print_str(p, "), &");
458 } else
459 p = isl_printer_print_str(p, "cl_mem), (void *) &dev_");
461 p = isl_printer_print_str(p, arg_name);
462 p = isl_printer_print_str(p, "));");
463 p = isl_printer_end_line(p);
465 return p;
468 /* Print the block sizes as a list of the sizes in each
469 * dimension.
471 static __isl_give isl_printer *opencl_print_block_sizes(
472 __isl_take isl_printer *p, struct ppcg_kernel *kernel)
474 int i;
476 if (kernel->n_block > 0)
477 for (i = 0; i < kernel->n_block; ++i) {
478 if (i)
479 p = isl_printer_print_str(p, ", ");
480 p = isl_printer_print_int(p, kernel->block_dim[i]);
482 else
483 p = isl_printer_print_str(p, "1");
485 return p;
488 /* Set the arguments of the OpenCL kernel by printing a call to the OpenCL
489 * clSetKernelArg() function for each kernel argument.
491 static __isl_give isl_printer *opencl_set_kernel_arguments(
492 __isl_take isl_printer *p, struct gpu_prog *prog,
493 struct ppcg_kernel *kernel)
495 int i, n, ro;
496 unsigned nparam;
497 isl_space *space;
498 int arg_index = 0;
500 for (i = 0; i < prog->n_array; ++i) {
501 int required;
503 required = ppcg_kernel_requires_array_argument(kernel, i);
504 if (required < 0)
505 return isl_printer_free(p);
506 if (!required)
507 continue;
508 ro = gpu_array_is_read_only_scalar(&prog->array[i]);
509 opencl_set_kernel_argument(p, kernel->id, prog->array[i].name,
510 arg_index, ro);
511 arg_index++;
514 space = isl_union_set_get_space(kernel->arrays);
515 nparam = isl_space_dim(space, isl_dim_param);
516 for (i = 0; i < nparam; ++i) {
517 const char *name;
519 name = isl_space_get_dim_name(space, isl_dim_param, i);
520 opencl_set_kernel_argument(p, kernel->id, name, arg_index, 1);
521 arg_index++;
523 isl_space_free(space);
525 n = isl_space_dim(kernel->space, isl_dim_set);
526 for (i = 0; i < n; ++i) {
527 const char *name;
529 name = isl_space_get_dim_name(kernel->space, isl_dim_set, i);
530 opencl_set_kernel_argument(p, kernel->id, name, arg_index, 1);
531 arg_index++;
534 return p;
537 /* Print the arguments to a kernel declaration or call. If "types" is set,
538 * then print a declaration (including the types of the arguments).
540 * The arguments are printed in the following order
541 * - the arrays accessed by the kernel
542 * - the parameters
543 * - the host loop iterators
545 static __isl_give isl_printer *opencl_print_kernel_arguments(
546 __isl_take isl_printer *p, struct gpu_prog *prog,
547 struct ppcg_kernel *kernel, int types)
549 int i, n;
550 int first = 1;
551 unsigned nparam;
552 isl_space *space;
553 const char *type;
555 for (i = 0; i < prog->n_array; ++i) {
556 int required;
558 required = ppcg_kernel_requires_array_argument(kernel, i);
559 if (required < 0)
560 return isl_printer_free(p);
561 if (!required)
562 continue;
564 if (!first)
565 p = isl_printer_print_str(p, ", ");
567 if (types)
568 p = gpu_array_info_print_declaration_argument(p,
569 &prog->array[i], "__global");
570 else
571 p = gpu_array_info_print_call_argument(p,
572 &prog->array[i]);
574 first = 0;
577 space = isl_union_set_get_space(kernel->arrays);
578 nparam = isl_space_dim(space, isl_dim_param);
579 for (i = 0; i < nparam; ++i) {
580 const char *name;
582 name = isl_space_get_dim_name(space, isl_dim_param, i);
584 if (!first)
585 p = isl_printer_print_str(p, ", ");
586 if (types)
587 p = isl_printer_print_str(p, "int ");
588 p = isl_printer_print_str(p, name);
590 first = 0;
592 isl_space_free(space);
594 n = isl_space_dim(kernel->space, isl_dim_set);
595 type = isl_options_get_ast_iterator_type(prog->ctx);
596 for (i = 0; i < n; ++i) {
597 const char *name;
599 if (!first)
600 p = isl_printer_print_str(p, ", ");
601 name = isl_space_get_dim_name(kernel->space, isl_dim_set, i);
602 if (types) {
603 p = isl_printer_print_str(p, type);
604 p = isl_printer_print_str(p, " ");
606 p = isl_printer_print_str(p, name);
608 first = 0;
611 return p;
614 /* Print the header of the given kernel.
616 static __isl_give isl_printer *opencl_print_kernel_header(
617 __isl_take isl_printer *p, struct gpu_prog *prog,
618 struct ppcg_kernel *kernel)
620 p = isl_printer_start_line(p);
621 p = isl_printer_print_str(p, "__kernel void kernel");
622 p = isl_printer_print_int(p, kernel->id);
623 p = isl_printer_print_str(p, "(");
624 p = opencl_print_kernel_arguments(p, prog, kernel, 1);
625 p = isl_printer_print_str(p, ")");
626 p = isl_printer_end_line(p);
628 return p;
631 /* Print a list of iterators of type "type" with names "ids" to "p".
632 * Each iterator is assigned the corresponding opencl identifier returned
633 * by the function "opencl_id".
634 * Unlike the equivalent function in the CUDA backend which prints iterators
635 * in reverse order to promote coalescing, this function does not print
636 * iterators in reverse order. The OpenCL backend currently does not take
637 * into account any coalescing considerations.
639 static __isl_give isl_printer *print_iterators(__isl_take isl_printer *p,
640 const char *type, __isl_keep isl_id_list *ids, const char *opencl_id)
642 int i, n;
644 n = isl_id_list_n_id(ids);
645 if (n <= 0)
646 return p;
647 p = isl_printer_start_line(p);
648 p = isl_printer_print_str(p, type);
649 p = isl_printer_print_str(p, " ");
650 for (i = 0; i < n; ++i) {
651 isl_id *id;
653 if (i)
654 p = isl_printer_print_str(p, ", ");
655 id = isl_id_list_get_id(ids, i);
656 p = isl_printer_print_id(p, id);
657 isl_id_free(id);
658 p = isl_printer_print_str(p, " = ");
659 p = isl_printer_print_str(p, opencl_id);
660 p = isl_printer_print_str(p, "(");
661 p = isl_printer_print_int(p, i);
662 p = isl_printer_print_str(p, ")");
664 p = isl_printer_print_str(p, ";");
665 p = isl_printer_end_line(p);
667 return p;
670 static __isl_give isl_printer *opencl_print_kernel_iterators(
671 __isl_take isl_printer *p, struct ppcg_kernel *kernel)
673 isl_ctx *ctx = isl_ast_node_get_ctx(kernel->tree);
674 const char *type;
676 type = isl_options_get_ast_iterator_type(ctx);
678 p = print_iterators(p, type, kernel->block_ids, "get_group_id");
679 p = print_iterators(p, type, kernel->thread_ids, "get_local_id");
681 return p;
684 static __isl_give isl_printer *opencl_print_kernel_var(
685 __isl_take isl_printer *p, struct ppcg_kernel_var *var)
687 int j;
688 isl_val *v;
690 p = isl_printer_start_line(p);
691 if (var->type == ppcg_access_shared)
692 p = isl_printer_print_str(p, "__local ");
693 p = isl_printer_print_str(p, var->array->type);
694 p = isl_printer_print_str(p, " ");
695 p = isl_printer_print_str(p, var->name);
696 for (j = 0; j < var->array->n_index; ++j) {
697 p = isl_printer_print_str(p, "[");
698 v = isl_vec_get_element_val(var->size, j);
699 p = isl_printer_print_val(p, v);
700 p = isl_printer_print_str(p, "]");
701 isl_val_free(v);
703 p = isl_printer_print_str(p, ";");
704 p = isl_printer_end_line(p);
706 return p;
709 static __isl_give isl_printer *opencl_print_kernel_vars(
710 __isl_take isl_printer *p, struct ppcg_kernel *kernel)
712 int i;
714 for (i = 0; i < kernel->n_var; ++i)
715 p = opencl_print_kernel_var(p, &kernel->var[i]);
717 return p;
720 /* Print a call to barrier() which is a sync statement.
721 * All work-items in a work-group executing the kernel on a processor must
722 * execute the barrier() function before any are allowed to continue execution
723 * beyond the barrier.
724 * The flag CLK_LOCAL_MEM_FENCE makes the barrier function either flush any
725 * variables stored in local memory or queue a memory fence to ensure correct
726 * ordering of memory operations to local memory.
727 * The flag CLK_GLOBAL_MEM_FENCE makes the barrier function queue a memory
728 * fence to ensure correct ordering of memory operations to global memory.
730 static __isl_give isl_printer *opencl_print_sync(__isl_take isl_printer *p,
731 struct ppcg_kernel_stmt *stmt)
733 p = isl_printer_start_line(p);
734 p = isl_printer_print_str(p,
735 "barrier(CLK_LOCAL_MEM_FENCE | CLK_GLOBAL_MEM_FENCE);");
736 p = isl_printer_end_line(p);
738 return p;
741 /* Data structure containing function names for which the calls
742 * should be changed from
744 * name(arg)
746 * to
748 * opencl_name((type) (arg))
750 static struct ppcg_opencl_fn {
751 const char *name;
752 const char *opencl_name;
753 const char *type;
754 } opencl_fn[] = {
755 { "expf", "exp", "float" },
756 { "powf", "pow", "float" },
757 { "sqrtf", "sqrt", "float" },
760 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
762 /* If the name of function called by "expr" matches any of those
763 * in ppcg_opencl_fn, then replace the call by a cast to the corresponding
764 * type in ppcg_opencl_fn and a call to corresponding OpenCL function.
766 static __isl_give pet_expr *map_opencl_call(__isl_take pet_expr *expr,
767 void *user)
769 const char *name;
770 int i;
772 name = pet_expr_call_get_name(expr);
773 for (i = 0; i < ARRAY_SIZE(opencl_fn); ++i) {
774 pet_expr *arg;
776 if (strcmp(name, opencl_fn[i].name))
777 continue;
778 expr = pet_expr_call_set_name(expr, opencl_fn[i].opencl_name);
779 arg = pet_expr_get_arg(expr, 0);
780 arg = pet_expr_new_cast(opencl_fn[i].type, arg);
781 expr = pet_expr_set_arg(expr, 0, arg);
783 return expr;
786 /* Print the body of a statement from the input program,
787 * for use in OpenCL code.
789 * Before calling ppcg_kernel_print_domain to print the actual statement body,
790 * we first modify this body to take into account that the output code
791 * is OpenCL code. In particular, if the statement calls any function
792 * with a "f" suffix, then it needs to be replaced by a call to
793 * the corresponding function without suffix after casting the argument
794 * to a float.
796 static __isl_give isl_printer *print_opencl_kernel_domain(
797 __isl_take isl_printer *p, struct ppcg_kernel_stmt *stmt)
799 struct pet_stmt *ps;
800 pet_tree *tree;
802 ps = stmt->u.d.stmt->stmt;
803 tree = pet_tree_copy(ps->body);
804 ps->body = pet_tree_map_call_expr(ps->body, &map_opencl_call, NULL);
805 p = ppcg_kernel_print_domain(p, stmt);
806 pet_tree_free(ps->body);
807 ps->body = tree;
809 return p;
812 /* This function is called for each user statement in the AST,
813 * i.e., for each kernel body statement, copy statement or sync statement.
815 static __isl_give isl_printer *opencl_print_kernel_stmt(
816 __isl_take isl_printer *p,
817 __isl_take isl_ast_print_options *print_options,
818 __isl_keep isl_ast_node *node, void *user)
820 isl_id *id;
821 struct ppcg_kernel_stmt *stmt;
823 id = isl_ast_node_get_annotation(node);
824 stmt = isl_id_get_user(id);
825 isl_id_free(id);
827 isl_ast_print_options_free(print_options);
829 switch (stmt->type) {
830 case ppcg_kernel_copy:
831 return ppcg_kernel_print_copy(p, stmt);
832 case ppcg_kernel_sync:
833 return opencl_print_sync(p, stmt);
834 case ppcg_kernel_domain:
835 return print_opencl_kernel_domain(p, stmt);
838 return p;
841 /* Return true if there is a double array in prog->array or
842 * if any of the types in prog->scop involve any doubles.
843 * To check the latter condition, we simply search for the string "double"
844 * in the type definitions, which may result in false positives.
846 static __isl_give int any_double_elements(struct gpu_prog *prog)
848 int i;
850 for (i = 0; i < prog->n_array; ++i)
851 if (strcmp(prog->array[i].type, "double") == 0)
852 return 1;
854 for (i = 0; i < prog->scop->pet->n_type; ++i) {
855 struct pet_type *type = prog->scop->pet->types[i];
857 if (strstr(type->definition, "double"))
858 return 1;
861 return 0;
864 /* Prints a #pragma to enable support for double floating-point
865 * precision. OpenCL 1.0 adds support for double precision floating-point as
866 * an optional extension. An application that wants to use double will need to
867 * include the #pragma OPENCL EXTENSION cl_khr_fp64 : enable directive before
868 * any double precision data type is declared in the kernel code.
870 static __isl_give isl_printer *opencl_enable_double_support(
871 __isl_take isl_printer *p)
873 p = isl_printer_start_line(p);
874 p = isl_printer_print_str(p, "#pragma OPENCL EXTENSION cl_khr_fp64 :"
875 " enable");
876 p = isl_printer_end_line(p);
877 p = isl_printer_start_line(p);
878 p = isl_printer_end_line(p);
880 return p;
883 static __isl_give isl_printer *opencl_print_kernel(struct gpu_prog *prog,
884 struct ppcg_kernel *kernel, __isl_take isl_printer *p)
886 isl_ctx *ctx = isl_ast_node_get_ctx(kernel->tree);
887 isl_ast_print_options *print_options;
889 print_options = isl_ast_print_options_alloc(ctx);
890 print_options = isl_ast_print_options_set_print_user(print_options,
891 &opencl_print_kernel_stmt, NULL);
893 p = isl_printer_set_output_format(p, ISL_FORMAT_C);
894 p = opencl_print_kernel_header(p, prog, kernel);
895 p = isl_printer_print_str(p, "{");
896 p = isl_printer_end_line(p);
897 p = isl_printer_indent(p, 4);
898 p = opencl_print_kernel_iterators(p, kernel);
899 p = opencl_print_kernel_vars(p, kernel);
900 p = isl_printer_end_line(p);
901 p = ppcg_set_macro_names(p);
902 p = isl_ast_op_type_print_macro(isl_ast_op_fdiv_q, p);
903 p = ppcg_print_macros(p, kernel->tree);
904 p = isl_ast_node_print(kernel->tree, p, print_options);
905 p = isl_printer_indent(p, -4);
906 p = isl_printer_start_line(p);
907 p = isl_printer_print_str(p, "}");
908 p = isl_printer_end_line(p);
910 return p;
913 struct print_host_user_data_opencl {
914 struct opencl_info *opencl;
915 struct gpu_prog *prog;
918 /* This function prints the i'th block size multiplied by the i'th grid size,
919 * where i (a parameter to this function) is one of the possible dimensions of
920 * grid sizes and block sizes.
921 * If the dimension of block sizes is not equal to the dimension of grid sizes
922 * the output is calculated as follows:
924 * Suppose that:
925 * block_sizes[dim1] is the list of blocks sizes and it contains dim1 elements.
926 * grid_sizes[dim2] is the list of grid sizes and it contains dim2 elements.
928 * The output is:
929 * If (i > dim2) then the output is block_sizes[i]
930 * If (i > dim1) then the output is grid_sizes[i]
932 static __isl_give isl_printer *opencl_print_total_number_of_work_items_for_dim(
933 __isl_take isl_printer *p, struct ppcg_kernel *kernel, int i)
935 int grid_dim, block_dim;
936 isl_pw_aff *bound_grid;
938 grid_dim = isl_multi_pw_aff_dim(kernel->grid_size, isl_dim_set);
939 block_dim = kernel->n_block;
941 if (i < min(grid_dim, block_dim)) {
942 bound_grid = isl_multi_pw_aff_get_pw_aff(kernel->grid_size, i);
943 p = isl_printer_print_str(p, "(");
944 p = isl_printer_print_pw_aff(p, bound_grid);
945 p = isl_printer_print_str(p, ") * ");
946 p = isl_printer_print_int(p, kernel->block_dim[i]);
947 isl_pw_aff_free(bound_grid);
948 } else if (i >= grid_dim) {
949 p = isl_printer_print_int(p, kernel->block_dim[i]);
950 } else {
951 bound_grid = isl_multi_pw_aff_get_pw_aff(kernel->grid_size, i);
952 p = isl_printer_print_pw_aff(p, bound_grid);
953 isl_pw_aff_free(bound_grid);
956 return p;
959 /* Print a list that represents the total number of work items. The list is
960 * constructed by performing an element-wise multiplication of the block sizes
961 * and the grid sizes. To explain how the list is constructed, suppose that:
962 * block_sizes[dim1] is the list of blocks sizes and it contains dim1 elements.
963 * grid_sizes[dim2] is the list of grid sizes and it contains dim2 elements.
965 * The output of this function is constructed as follows:
966 * If (dim1 > dim2) then the output is the following list:
967 * grid_sizes[0]*block_sizes[0], ..., grid_sizes[dim2-1]*block_sizes[dim2-1],
968 * block_sizes[dim2], ..., block_sizes[dim1-2], block_sizes[dim1-1].
970 * If (dim2 > dim1) then the output is the following list:
971 * grid_sizes[0]*block_sizes[0], ..., grid_sizes[dim1-1] * block_sizes[dim1-1],
972 * grid_sizes[dim1], grid_sizes[dim2-2], grid_sizes[dim2-1].
974 * To calculate the total number of work items out of the list constructed by
975 * this function, the user should multiply the elements of the list.
977 static __isl_give isl_printer *opencl_print_total_number_of_work_items_as_list(
978 __isl_take isl_printer *p, struct ppcg_kernel *kernel)
980 int i;
981 int grid_dim, block_dim;
983 grid_dim = isl_multi_pw_aff_dim(kernel->grid_size, isl_dim_set);
984 block_dim = kernel->n_block;
986 if ((grid_dim <= 0) || (block_dim <= 0)) {
987 p = isl_printer_print_str(p, "1");
988 return p;
991 for (i = 0; i <= max(grid_dim, block_dim) - 1; i++) {
992 if (i > 0)
993 p = isl_printer_print_str(p, ", ");
995 p = opencl_print_total_number_of_work_items_for_dim(p,
996 kernel, i);
999 return p;
1002 /* Copy "array" from the host to the device (to_host = 0) or
1003 * back from the device to the host (to_host = 1).
1005 static __isl_give isl_printer *copy_array(__isl_take isl_printer *p,
1006 struct gpu_array_info *array, int to_host)
1008 p = isl_printer_start_line(p);
1009 p = isl_printer_print_str(p, "openclCheckReturn(");
1010 if (to_host)
1011 p = isl_printer_print_str(p, "clEnqueueReadBuffer");
1012 else
1013 p = isl_printer_print_str(p, "clEnqueueWriteBuffer");
1014 p = isl_printer_print_str(p, "(queue, dev_");
1015 p = isl_printer_print_str(p, array->name);
1016 p = isl_printer_print_str(p, ", CL_TRUE, 0, ");
1017 p = gpu_array_info_print_size(p, array);
1019 if (gpu_array_is_scalar(array))
1020 p = isl_printer_print_str(p, ", &");
1021 else
1022 p = isl_printer_print_str(p, ", ");
1023 p = isl_printer_print_str(p, array->name);
1024 p = isl_printer_print_str(p, ", 0, NULL, NULL));");
1025 p = isl_printer_end_line(p);
1027 return p;
1030 /* Print code for initializing the device for execution of the transformed
1031 * code. This includes declaring locally defined variables as well as
1032 * declaring and allocating the required copies of arrays on the device.
1034 static __isl_give isl_printer *init_device(__isl_take isl_printer *p,
1035 struct gpu_prog *prog, struct opencl_info *opencl)
1037 p = opencl_print_host_macros(p);
1039 p = gpu_print_local_declarations(p, prog);
1040 p = opencl_declare_device_arrays(p, prog);
1041 p = opencl_setup(p, opencl->input, opencl);
1042 p = opencl_allocate_device_arrays(p, prog);
1044 return p;
1047 /* Print code for clearing the device after execution of the transformed code.
1048 * In particular, free the memory that was allocated on the device.
1050 static __isl_give isl_printer *clear_device(__isl_take isl_printer *p,
1051 struct gpu_prog *prog, struct opencl_info *opencl)
1053 p = opencl_release_device_arrays(p, prog);
1054 p = opencl_release_cl_objects(p, opencl);
1056 return p;
1059 /* Print a statement for copying an array to or from the device,
1060 * or for initializing or clearing the device.
1061 * The statement identifier of a copying node is called
1062 * "to_device_<array name>" or "from_device_<array name>" and
1063 * its user pointer points to the gpu_array_info of the array
1064 * that needs to be copied.
1065 * The node for initializing the device is called "init_device".
1066 * The node for clearing the device is called "clear_device".
1068 * Extract the array (if any) from the identifier and call
1069 * init_device, clear_device, copy_array_to_device or copy_array_from_device.
1071 static __isl_give isl_printer *print_device_node(__isl_take isl_printer *p,
1072 __isl_keep isl_ast_node *node, struct gpu_prog *prog,
1073 struct opencl_info *opencl)
1075 isl_ast_expr *expr, *arg;
1076 isl_id *id;
1077 const char *name;
1078 struct gpu_array_info *array;
1080 expr = isl_ast_node_user_get_expr(node);
1081 arg = isl_ast_expr_get_op_arg(expr, 0);
1082 id = isl_ast_expr_get_id(arg);
1083 name = isl_id_get_name(id);
1084 array = isl_id_get_user(id);
1085 isl_id_free(id);
1086 isl_ast_expr_free(arg);
1087 isl_ast_expr_free(expr);
1089 if (!name)
1090 return isl_printer_free(p);
1091 if (!strcmp(name, "init_device"))
1092 return init_device(p, prog, opencl);
1093 if (!strcmp(name, "clear_device"))
1094 return clear_device(p, prog, opencl);
1095 if (!array)
1096 return isl_printer_free(p);
1098 if (!prefixcmp(name, "to_device"))
1099 return copy_array(p, array, 0);
1100 else
1101 return copy_array(p, array, 1);
1104 /* Print the user statement of the host code to "p".
1106 * The host code may contain original user statements, kernel launches,
1107 * statements that copy data to/from the device and statements
1108 * the initialize or clear the device.
1109 * The original user statements and the kernel launches have
1110 * an associated annotation, while the other statements do not.
1111 * The latter are handled by print_device_node.
1112 * The annotation on the user statements is called "user".
1114 * In case of a kernel launch, print a block of statements that
1115 * defines the grid and the work group and then launches the kernel.
1117 * A grid is composed of many work groups (blocks), each work group holds
1118 * many work-items (threads).
1120 * global_work_size[kernel->n_block] represents the total number of work
1121 * items. It points to an array of kernel->n_block unsigned
1122 * values that describe the total number of work-items that will execute
1123 * the kernel. The total number of work-items is computed as:
1124 * global_work_size[0] *...* global_work_size[kernel->n_block - 1].
1126 * The size of each work group (i.e. the number of work-items in each work
1127 * group) is described using block_size[kernel->n_block]. The total
1128 * number of work-items in a block (work-group) is computed as:
1129 * block_size[0] *... * block_size[kernel->n_block - 1].
1131 * For more information check:
1132 * http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/clEnqueueNDRangeKernel.html
1134 static __isl_give isl_printer *opencl_print_host_user(
1135 __isl_take isl_printer *p,
1136 __isl_take isl_ast_print_options *print_options,
1137 __isl_keep isl_ast_node *node, void *user)
1139 isl_id *id;
1140 int is_user;
1141 struct ppcg_kernel *kernel;
1142 struct ppcg_kernel_stmt *stmt;
1143 struct print_host_user_data_opencl *data;
1145 isl_ast_print_options_free(print_options);
1147 data = (struct print_host_user_data_opencl *) user;
1149 id = isl_ast_node_get_annotation(node);
1150 if (!id)
1151 return print_device_node(p, node, data->prog, data->opencl);
1153 is_user = !strcmp(isl_id_get_name(id), "user");
1154 kernel = is_user ? NULL : isl_id_get_user(id);
1155 stmt = is_user ? isl_id_get_user(id) : NULL;
1156 isl_id_free(id);
1158 if (is_user)
1159 return ppcg_kernel_print_domain(p, stmt);
1161 p = isl_printer_start_line(p);
1162 p = isl_printer_print_str(p, "{");
1163 p = isl_printer_end_line(p);
1164 p = isl_printer_indent(p, 2);
1166 p = isl_printer_start_line(p);
1167 p = isl_printer_print_str(p, "size_t global_work_size[");
1169 if (kernel->n_block > 0)
1170 p = isl_printer_print_int(p, kernel->n_block);
1171 else
1172 p = isl_printer_print_int(p, 1);
1174 p = isl_printer_print_str(p, "] = {");
1175 p = opencl_print_total_number_of_work_items_as_list(p, kernel);
1176 p = isl_printer_print_str(p, "};");
1177 p = isl_printer_end_line(p);
1179 p = isl_printer_start_line(p);
1180 p = isl_printer_print_str(p, "size_t block_size[");
1182 if (kernel->n_block > 0)
1183 p = isl_printer_print_int(p, kernel->n_block);
1184 else
1185 p = isl_printer_print_int(p, 1);
1187 p = isl_printer_print_str(p, "] = {");
1188 p = opencl_print_block_sizes(p, kernel);
1189 p = isl_printer_print_str(p, "};");
1190 p = isl_printer_end_line(p);
1192 p = isl_printer_start_line(p);
1193 p = isl_printer_print_str(p, "cl_kernel kernel");
1194 p = isl_printer_print_int(p, kernel->id);
1195 p = isl_printer_print_str(p, " = clCreateKernel(program, \"kernel");
1196 p = isl_printer_print_int(p, kernel->id);
1197 p = isl_printer_print_str(p, "\", &err);");
1198 p = isl_printer_end_line(p);
1199 p = isl_printer_start_line(p);
1200 p = isl_printer_print_str(p, "openclCheckReturn(err);");
1201 p = isl_printer_end_line(p);
1203 opencl_set_kernel_arguments(p, data->prog, kernel);
1205 p = isl_printer_start_line(p);
1206 p = isl_printer_print_str(p, "openclCheckReturn(clEnqueueNDRangeKernel"
1207 "(queue, kernel");
1208 p = isl_printer_print_int(p, kernel->id);
1209 p = isl_printer_print_str(p, ", ");
1210 if (kernel->n_block > 0)
1211 p = isl_printer_print_int(p, kernel->n_block);
1212 else
1213 p = isl_printer_print_int(p, 1);
1215 p = isl_printer_print_str(p, ", NULL, global_work_size, "
1216 "block_size, "
1217 "0, NULL, NULL));");
1218 p = isl_printer_end_line(p);
1219 p = isl_printer_start_line(p);
1220 p = isl_printer_print_str(p, "openclCheckReturn("
1221 "clReleaseKernel(kernel");
1222 p = isl_printer_print_int(p, kernel->id);
1223 p = isl_printer_print_str(p, "));");
1224 p = isl_printer_end_line(p);
1225 p = isl_printer_start_line(p);
1226 p = isl_printer_print_str(p, "clFinish(queue);");
1227 p = isl_printer_end_line(p);
1228 p = isl_printer_indent(p, -2);
1229 p = isl_printer_start_line(p);
1230 p = isl_printer_print_str(p, "}");
1231 p = isl_printer_end_line(p);
1233 p = isl_printer_start_line(p);
1234 p = isl_printer_end_line(p);
1236 data->opencl->kprinter = opencl_print_kernel(data->prog, kernel,
1237 data->opencl->kprinter);
1239 return p;
1242 static __isl_give isl_printer *opencl_print_host_code(
1243 __isl_take isl_printer *p, struct gpu_prog *prog,
1244 __isl_keep isl_ast_node *tree, struct opencl_info *opencl)
1246 isl_ast_print_options *print_options;
1247 isl_ctx *ctx = isl_ast_node_get_ctx(tree);
1248 struct print_host_user_data_opencl data = { opencl, prog };
1250 print_options = isl_ast_print_options_alloc(ctx);
1251 print_options = isl_ast_print_options_set_print_user(print_options,
1252 &opencl_print_host_user, &data);
1254 p = ppcg_print_macros(p, tree);
1255 p = isl_ast_node_print(tree, p, print_options);
1257 return p;
1260 /* Given a gpu_prog "prog" and the corresponding transformed AST
1261 * "tree", print the entire OpenCL code to "p".
1263 static __isl_give isl_printer *print_opencl(__isl_take isl_printer *p,
1264 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
1265 struct gpu_types *types, void *user)
1267 struct opencl_info *opencl = user;
1269 opencl->kprinter = isl_printer_set_output_format(opencl->kprinter,
1270 ISL_FORMAT_C);
1271 if (any_double_elements(prog))
1272 opencl->kprinter = opencl_enable_double_support(
1273 opencl->kprinter);
1274 if (opencl->options->opencl_print_kernel_types)
1275 opencl->kprinter = gpu_print_types(opencl->kprinter, types,
1276 prog);
1278 if (!opencl->kprinter)
1279 return isl_printer_free(p);
1281 p = opencl_print_host_code(p, prog, tree, opencl);
1283 return p;
1286 /* Transform the code in the file called "input" by replacing
1287 * all scops by corresponding OpenCL code.
1288 * The host code is written to "output" or a name derived from
1289 * "input" if "output" is NULL.
1290 * The kernel code is placed in separate files with names
1291 * derived from "output" or "input".
1293 * We let generate_gpu do all the hard work and then let it call
1294 * us back for printing the AST in print_opencl.
1296 * To prepare for this printing, we first open the output files
1297 * and we close them after generate_gpu has finished.
1299 int generate_opencl(isl_ctx *ctx, struct ppcg_options *options,
1300 const char *input, const char *output)
1302 struct opencl_info opencl = { options, input, output };
1303 int r;
1305 opencl.kprinter = isl_printer_to_str(ctx);
1306 r = opencl_open_files(&opencl);
1308 if (r >= 0)
1309 r = generate_gpu(ctx, input, opencl.host_c, options,
1310 &print_opencl, &opencl);
1312 if (opencl_close_files(&opencl) < 0)
1313 r = -1;
1314 isl_printer_free(opencl.kprinter);
1316 return r;