Clone wiki

LLVM.NET / Home

Welcome

Welcome to LLVM .NET binding project. The project's aim is to provide full-featured easily-available binding to the Low-Level Virtual Machine native project for .NET based languages such as C#, Visual Basic, F#, etc

The code has moved to https://github.com/lostmsu/LLVM.NET

Getting Started

Installation

We've published pre-release of binding to NuGet package gallery. In most cases you would simply need 2 packages to install:

  1. LLVM - this package provides fully managed class library wrapper for LLVM. Note that it is in its early stage: only JIT is supported, and native memory allocated by LLVM is never freed.
  2. LLVM.NativeLibrary - this package is a class library, which contains native LLVM dlls for 32 and 64 bit Windows, and allows you to load them via single call to LLVMDLL.Load. This function will automatically unpack and load an appropriate DLL into your application.

Calling LLVM's JIT

using System;

using LLVM;
using LLVM.Interop;
using LLVM.NativeLibrary;

class Random
{
	// we need to declare delegate type for our sample function
	delegate int IntFunc();

	static void Main()
	{
		// Loads native LLVM library. Without this call you must manually provide an appropriate
		// (32- or 64-bit)version of LLVM library in %PATH% or in application's directory.
		// For the current version of wrapper, file must be named "LLVM-3.1" without quotes.
		// Note: file must have no ".dll" extension!
		LLVMDLL.Load();
		// this call instructs LLVM to prepare itself to generate native code for
		// current processor architecture
		Target.InitializeNative();

		var context = Context.Global;
		// LLVM needs a module to contain code even if we use JIT
		var container = new Module("mymodule", context);
		// create an instance of JIT engine
		var jit = new ExecutionEngine(container);

		var i32 = IntegerType.GetInt32(context);
		var functionType = new FunctionType(i32);
		var function = container.CreateFunction("myrandom", functionType);
		function.CallingConvention = CallingConvention.Fast;

		// function consists of blocks
		var codeBlock = new Block("codeBlock", context, function);
		// LLVM IR is generated in block by this class instance
		var gen = new InstructionBuilder(context, codeBlock);
		// generate a return instruction
		gen.Return(i32.Constant(42, true));

		// ClrInterop provides interoperability for the code, generated by LLVM
		var interop = new ClrInterop(jit);
		// This line builds managed to native function wrapper. It deals with calling conventions.
		var managedDelegate = interop.GetDelegate<IntFunc>(function, container);
		var randomValue = managedDelegate.Invoke();
		Console.WriteLine(randomValue);
	}
}

If everything is OK, this should output "42" to console!

Have fun!

Project

If you have any further questions, or want to join the project, contact me via an email: lostfreeman@gmail.com

Updated