Adding JIT support

A wide variety of tools can be applied to LLVM IR. For example, as demonstrated in Chapter 1, LLVM Design and Use, the IR can be dumped into bitcode or into an assembly. An optimization tool called opt can be run on IR. IR acts as the common platform—an abstract layer for all of these tools.

JIT support can also be added. It immediately evaluates the top-level expressions typed in. For example, 1 + 2;, as soon as it is typed in, evaluates the code and prints the value as 3.

How to do it...

Do the following steps:

  1. Define a static global variable for the execution engine in the toy.cpp file:
    static ExecutionEngine *TheExecutionEngine;
  2. In the toy.cpp file's main() function, write the code for JIT:
    int main() {
    …
    …
    init_precedence();
    TheExecutionEngine = EngineBuilder(TheModule).create();
    …
    …
    }
  3. Modify the top-level expression parser in the toy.cpp file:
    static void HandleTopExpression() {
    
    if (FunctionDefAST *F = expression_parser())
       if (Function *LF = F->Codegen()) {
            LF -> dump();
           void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
          int (*Int)() = (int (*)())(intptr_t)FPtr;
    
        printf("Evaluated to %d
    ", Int());
    }
       else
    next_token();
    }

How it works…

Do the following steps:

  1. Compile the toy.cpp program:
    $ g++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native` -O3 -o toy
    
  2. Open an example file:
    $ vi example
    
  3. Write the following TOY code in the example file:
    …
    4+5;
  4. Finally, run the TOY compiler on the example file:
    $ ./toy example
    The output will be
    define i32 @0() {
    entry:
      ret i32 9
    }
    

The LLVM JIT compiler matches the native platform ABI, casts the result pointer into a function pointer of that type, and calls it directly. There is no difference between JIT-compiled code and native machine code that is statically linked to the application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.96.94