Saturday, May 30, 2009

LLVM for Beginners (Windows)

Low Level Virtual Machine (LLVM) is, officially, "Compiler Infrastructure". In my own words, it's a platform independent optimizing assembler. That is, you write high level assembly code for a virtual machine, and then LLVM goes through it, optimizes it, and pumps out the native assembly for your target platform (e.g. x86). The best part is that it can do it Just-In-Time (JIT) too!

LLVM and Clang (the llvm c compiler frontend) first gained my interest when I was looking into OpenCL, and heard Apple's technology of choice was LLVM. After that, LLVM replaced GCC for compiling FreeBSD, and more recently, Rapidmind have sung LLVM's praise. Could LLVM be the future for high performance languages? (Goodbye CUDA/Open64?)

So, how do you get started? First, download LLVM, I just grabbed the MinGW builds for Windows. Now, we need a compiler (LLVM is just the 'assembler', Clang is the C front end). LLVM provide an online compiler. Copy past your code in there, for example:

#include
int main() {
printf("hello world\n");
return 0;
}

The online compiler will then spit out the human readable LLVM assembly code, or 'll' code. Copy and paste this to a file, e.g. "hello.ll".
Now we can turn this into a binary bytecode representation using the LLVM assembler, llvm-as:
llvm-as hello.ll
This will generate hello.bc, the byte code version of the file.

We can either run this JIT with lli, (just type lli hello.bc) or create an assembly file with llc the LLVM static compiler. If you wish to compile the program for windows, you need to change the target provided by the online compiler to a windows compatible compiler. Do this by replacing the 'target triple = "i386-pc-linux-gnu"' line in your ll file to 'target triple = "i586-mingw32msvc"'. (Thanks Eli!) Re-run the assmber, Now your ready to compile:
llc hello.bc
Which generates hello.s

At this point, you need to use your platforms compiler, for example MinGW's gcc:
C:\MinGW\bin>gcc hello.s

C:\MinGW\bin>a.exe

hello world


Cool! The LLVM community is very open and friendly so I'm looking foward to trying some nifty things with LLVM!

2 comments:

kalyan said...
This comment has been removed by the author.
Unknown said...

Good article! Quick note: check out your `#include` line. The browser seems to think it's HTML and so is not rendering correctly.