Skip to content

Minimal AOT compiled example

ShawnLess edited this page May 26, 2017 · 4 revisions

For ahead-of-time (AOT) compiled programs, there are two source files involved. The first, "halide_generate.cpp", defines and builds a Halide pipeline, then compiles it into an object file. The second, "halide_run.cpp", will use this object file to run the pipeline.

halide_generate.cpp:

#include <Halide.h>
#include <stdio.h>

int main(int argc, char **argv) {
  // Define a gradient function.
  Halide::Func f;
  Halide::Var x, y;
  f(x, y) = x + y;
 
  std::vector<Halide::Argument> args(0);
  // Compile it to an object file and header.
  f.compile_to_file("gradient", args);

  return 0;
}

Compile and run it. On linux, that looks like:

% g++ halide_generate.cpp -I Halide/include -L Halide/lib -lHalide -o halide_generate
% LD_LIBRARY_PATH=Halide/lib ./halide_generate
% ls gradient.*
gradient.h gradient.o

(where Halide/include is the folder containing Halide.h, and Halide/lib is the folder containing libHalide.so.)

halide_run.cpp:

// Compiling and running halide_generate.cpp produced the following header:
#include "gradient.h"

// Note we don't include Halide.h. This program doesn't depend on libHalide.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    // This pipeline has no inputs. We still need to make a buffer_t
    // to hold the output.
    halide_buffer_t  output = {0};

    int result[32*32];

   // // Request the gradient function over a 32x32 box.
   output.host          = (uint8_t *) result        ; 

   output.type.code     = halide_type_int           ;
   output.type.bits     = sizeof(int32_t)*8         ;
   output.type.lanes    = 1                         ;


   //setup the dimension info
   output.dimensions    = 2                         ;
   halide_dimension_t  dim[2];
   
   dim[0].extent        = 32 ;// Width
   dim[0].stride        = 1  ;
   dim[1].extent        = 32 ;// Heigth
   dim[1].stride        = 32 ;
   output.dim           = dim;
   
    // Run the pipeline
    //f_old_buffer_t(&output);
    f(&output);

    // Print the result.
    for (int y = 0; y < 32; y++) {
        for (int x = 0; x < 32; x++) {
            printf("%3d ", result[y * 32 + x]);
        }
        printf("\n");
    }

    return 0;
}

Compile and run it:


% g++ halide_run.cpp gradient.o -o halide_run
% ./halide_run
  0   1   2   3 ....

For a more complete example of AOT compilation, see tutorial lesson 10. For more complex examples, browse the static tests, and the apps in the repository.