LLVM jit and native

zaharpopov picture zaharpopov · Aug 18, 2010 · Viewed 16.4k times · Source

I don't understand how LLVM JIT relates to normal no JIT compilation and the documentation isn't good.

For example suppose I use the clang front end:

  1. Case 1: I compile C file to native with clang/llvm. This flow I understand is like gcc flow - I get my x86 executable and that runs.
  2. Case 2: I compile into some kind of LLVM IR that runs on LLVM JIT. In this case the executable contains the LLVM runtime to execute the IR on JIT, or how does it work?

What is the difference between these two and are they correct? Does LLVM flow include support for both JIT and non JIT? When do I want to use JIT - does it make sense at all for a language like C?

Answer

ebo picture ebo · Aug 18, 2010

You have to understand that LLVM is a library that helps you build compilers. Clang is merely a frontend for this library.

Clang translates C/C++ code into LLVM IR and hands it over to LLVM, which compiles it into native code.

LLVM is also able to generate native code directly in memory, which then can be called as a normal function. So case 1. and 2. share LLVM's optimization and code generation.

So how does one use LLVM as a JIT compiler? You build an application which generates some LLVM IR (in memory), then use the LLVM library to generate native code (still in memory). LLVM hands you back a pointer which you can call afterwards. No clang involved.

You can, however, use clang to translate some C code into LLVM IR and load this into your JIT context to use the functions.

Real World examples:

There is also the Kaleidoscope tutorial which shows how to implement a simple language with JIT compiler.