Skip to content
richardxia edited this page Sep 14, 2011 · 13 revisions

Tutorials

Templating and the ArrayDoubler Specializer

This section will explain the ArrayDoubler example specializer, which comes packaged with Asp in the specializers/array_doubler/ directory. The ArrayDoubler specializer is meant to introduce developers to the templating features of Asp. ArrayDoubler itself simply takes an input list of numbers and returns the result of multiplying each of the elements by 2. If you look at tests/arraydoubler_test.py, you can see how an ArrayDoubler object is instantiated and how its pure Python implementation and its more efficient C implementation are called.

In array_doubler.py, you will see two methods for ArrayDoubler: double(), which is the pure Python implementation, and double_using_template(), which uses a template to output C code. Asp uses Mako as its templating engine. The template file is located at templates/double_template.mako, but since this is a trivial example, the only specialization used here is to set the upper bound of the for loop. Back in double_using_template(), the template is rendered as a string containing the code and is passed into an instance of ASPModule with the add_function() method, which handles the dynamic compilation and linking.

(Talk more about writing templates, using the C Python API, etc.)

Generating C code using templates is the fastest way of writing a specializer for Asp, but it is limited in power compared to using tree transformations.

Tree Transformations and the Stencil Specializer

To make more complicated specializers, a specializer writer should take advantage of the tree transformation capabilities of Asp. The general workflow begins with AST of a Python method. The specializer writer can write code to walk the AST, performing transformations on the individual nodes of the tree. Here Python code can be transformed into a semantic model that the specializer writer defines which more gives a richer representation of the important aspects of the domain-specific problem. From here, the code is converted into a C/C++ AST using another tree-walking class written by the specializer writer.

Here is a brief list of the files used in the Stencil Specializer (also bundled with the Asp code):

  • stencil_kernel.py - The main driver of Stencil which calls each of the phases described above
  • stencil_python_front_end.py - Converts the initial Python AST into a special semantic model named StencilModel
  • stencil_model.py - Defines the new nodes used in StencilModel
  • stencil_unroll_neighbor_iter.py - Performs a couple optimizations on the StencilModel
  • stencil_convert.py - Converts a StencilModel into a C++ AST
  • stencil_optimize_cpp.py - Performs a couple optimizations on the C++ AST
Clone this wiki locally