Generating an OpenCL kernel by Textual Substitution

The simplest approach to generating code is to simply substitute snippets of text into an existing code "template". This can be done using the C preprocessor, simple string-based search and replace, or other string-value interpolation functionality present in the language. The example below demonstrates the latter case:

In [1]:
kernel = r"""
    __kernel void {name}({arguments})
    {{
      int lid = get_local_id(0);
      int gsize = get_global_size(0);
      int work_group_start = get_local_size(0)*get_group_id(0);
      long i;

      for (i = work_group_start + lid; i < n; i += gsize)
      {{
        {operation};
      }}
    }}
"""

One slightly unfortunate fact that plays into using Python's .format() facility for this purpose is that opening and closing braces must be escaped by doubling them.

In [2]:
print(kernel.format(
    name="scale",
    arguments="float *y, float a, float *x",
    operation="y[i] = a*x[i]"
))
    __kernel void scale(float *y, float a, float *x)
    {
      int lid = get_local_id(0);
      int gsize = get_global_size(0);
      int work_group_start = get_local_size(0)*get_group_id(0);
      long i;

      for (i = work_group_start + lid; i < n; i += gsize)
      {
        y[i] = a*x[i];
      }
    }

In [ ]: