static void Main(string[] args) { var context = new LLVMContext(); var module = new Module("NoName", context); var builder = new IRBuilder(context); var t = builder.getInt32Ty(); var funcType = FunctionType.get(t, false); var main = Function.Create(funcType, GlobalValue.LinkageTypes.ExternalLinkage, "main", module); var entry = BasicBlock.Create(context, "entrypoint", main); builder.SetInsertPoint(entry); var hello = builder.CreateGlobalStringPtr("Hello, World!"); var putsType = FunctionType.get(builder.getInt32Ty(), new[] { builder.getInt8Ty().getPointerTo(0) }, false); var putsFunc = module.getOrInsertFunction("puts", putsType); builder.CreateCall(putsFunc, hello); var variable = builder.CreateAlloca(t); var val = ConstantInt.get(t, 127); builder.CreateStore(val, variable); builder.CreateRetVoid(); var pm = new PassManager(); var os = new raw_fd_ostream("code.ll"); pm.add(Passes.createPrintModulePass(os)); pm.run(module); os.close(); Console.ReadKey(); }
static void Main() { LLVM.Module module = new LLVM.Module("test_type"); module.AddTypeName("int1", LLVM.Type.GetInt1()); module.AddTypeName("int8", LLVM.Type.GetInt8()); module.AddTypeName("int16", LLVM.Type.GetInt16()); module.AddTypeName("int32", LLVM.Type.GetInt32()); module.AddTypeName("int64", LLVM.Type.GetInt64()); module.AddTypeName("int24", LLVM.Type.GetIntN(24)); module.AddTypeName("int48", LLVM.IntegerType.Get(48)); LLVM.Type[] arr = new LLVM.Type[] {LLVM.Type.GetInt8(), LLVM.Type.GetInt8(), LLVM.Type.GetInt32()}; module.AddTypeName("structtype", LLVM.StructType.Get(arr)); module.AddTypeName("arraytype", LLVM.ArrayType.Get(LLVM.Type.GetInt8(), 10)); module.AddTypeName("pointertype", LLVM.PointerType.Get(LLVM.Type.GetInt8(), 0)); module.AddTypeName("opaquetype", LLVM.OpaqueType.Get()); LLVM.OpaqueType o = LLVM.OpaqueType.Get(); LLVM.TypeHandle th = new LLVM.TypeHandle(o); LLVM.StructType st = LLVM.StructType.Get(new LLVM.Type[] {LLVM.Type.GetInt32(), o}); o.RefineAbstractTypeTo(st); module.AddTypeName("refinedtype", th.Resolve()); module.Dump(); }
static void Main() { LLVM.Module module = new LLVM.Module("test_type"); module.AddTypeName("int1", LLVM.Type.GetInt1()); module.AddTypeName("int8", LLVM.Type.GetInt8()); module.AddTypeName("int16", LLVM.Type.GetInt16()); module.AddTypeName("int32", LLVM.Type.GetInt32()); module.AddTypeName("int64", LLVM.Type.GetInt64()); module.AddTypeName("int24", LLVM.Type.GetIntN(24)); module.AddTypeName("int48", LLVM.IntegerType.Get(48)); LLVM.Type[] arr = new LLVM.Type[] { LLVM.Type.GetInt8(), LLVM.Type.GetInt8(), LLVM.Type.GetInt32() }; module.AddTypeName("structtype", LLVM.StructType.Get(arr)); module.AddTypeName("arraytype", LLVM.ArrayType.Get(LLVM.Type.GetInt8(), 10)); module.AddTypeName("pointertype", LLVM.PointerType.Get(LLVM.Type.GetInt8(), 0)); module.AddTypeName("opaquetype", LLVM.OpaqueType.Get()); LLVM.OpaqueType o = LLVM.OpaqueType.Get(); LLVM.TypeHandle th = new LLVM.TypeHandle(o); LLVM.StructType st = LLVM.StructType.Get(new LLVM.Type[] { LLVM.Type.GetInt32(), o }); o.RefineAbstractTypeTo(st); module.AddTypeName("refinedtype", th.Resolve()); module.Dump(); }
private static Function EmitFunction(Module module, MethodBase method) { var methodInfo = method as MethodInfo; var methodConstructor = method as ConstructorInfo; var declaringType = method.DeclaringType; if (methodInfo == null && methodConstructor == null) throw new CudaSharpException("Unknown MethodBase type " + method.GetType().FullName); if (declaringType == null) throw new CudaSharpException("Could not find the declaring type of " + method.Name.StripNameToValidPtx()); var parameters = method.GetParameters().Select(p => p.ParameterType); if (methodConstructor != null) parameters = new[] { declaringType.MakeByRefType() }.Concat(parameters); if (methodInfo != null && methodInfo.IsStatic == false) { if (declaringType.IsValueType == false) throw new CudaSharpException("Cannot compile object instance methods (did you forget to mark the method as static?)"); parameters = new[] { declaringType.MakeByRefType() }.Concat(parameters); } var llvmParameters = parameters.Select(t => ConvertType(module, t)).ToArray(); var funcType = new FunctionType(ConvertType(module, methodInfo == null ? typeof(void) : methodInfo.ReturnType), llvmParameters); var intrinsic = method.GetCustomAttribute<Gpu.BuiltinAttribute>(); if (intrinsic != null) { var name = intrinsic.Intrinsic; var preExisting = module.GetFunction(name); if (preExisting != null) return preExisting; return module.CreateFunction(name, funcType); } var function = module.CreateFunction(methodConstructor == null ? method.Name.StripNameToValidPtx() : declaringType.Name.StripNameToValidPtx() + "_ctor", funcType); var block = new Block("entry", module.Context, function); var writer = new InstructionBuilder(module.Context, block); var opcodes = method.Disassemble().ToList(); FindBranchTargets(opcodes, module.Context, function); var body = method.GetMethodBody(); var efo = new EmitFuncObj(module, function, body, writer, null, new Stack<Value>(), body == null ? null : new Value[body.LocalVariables.Count], new Value[llvmParameters.Length]); PrintHeader(efo); foreach (var opcode in opcodes) { if (EmitFunctions.ContainsKey(opcode.Opcode) == false) throw new CudaSharpException("Unsupported CIL instruction " + opcode.Opcode); var func = EmitFunctions[opcode.Opcode]; efo.Argument = opcode.Parameter; func(efo); } return function; }
public static StructType GetTypeByName(this Module module, string name) { var intPtr = LLVMGetTypeByName(module, name); if (intPtr == IntPtr.Zero) { return(null); } return((StructType)StructTypeConstructor.Invoke(new object[] { intPtr })); }
/// <summary> /// Create a function with arguments and a return type. /// </summary> /// <param name="module"></param> /// <param name="name"></param> /// <param name="returnType"></param> /// <param name="paramTypes"></param> public Function(Module module, string name, TypeRef returnType, TypeRef[] paramTypes) { m_name = name; m_returnType = returnType; m_paramTypes = paramTypes; IntPtr[] paramArray = LLVMHelper.MarshallPointerArray(paramTypes); m_funcType = Native.FunctionType(returnType.Handle, paramArray, (uint)paramArray.Length, 0); m_handle = Native.AddFunction(module.Handle, name, m_funcType); }
public EmitFuncObj(Module module, Function function, MethodBody cilMethod, InstructionBuilder instructionBuilder, object argument, Stack <Value> stack, Value[] locals, Value[] parameters) { Module = module; Function = function; CilMethod = cilMethod; Builder = instructionBuilder; Argument = argument; Stack = stack; Locals = locals; Parameters = parameters; }
private static void Translate(Module module, MethodBase method) { var function = EmitFunction(module, method); if (method.IsStatic == false) throw new CudaSharpException("Cannot translate instance methods to GPU code"); var metadataArgs = new[] { function, PInvoke.LLVMMDStringInContext(module.Context, "kernel"), IntegerType.GetInt32(module.Context).Constant(1, true) }; var metadata = module.Context.MetadataNodeInContext(metadataArgs); module.AddNamedMetadataOperand("nvvm.annotations", metadata); }
private static void Translate(Module module, MethodBase method) { var function = EmitFunction(module, method); if (method.IsStatic == false) { throw new CudaSharpException("Cannot translate instance methods to GPU code"); } var metadataArgs = new[] { function, PInvoke.LLVMMDStringInContext(module.Context, "kernel"), IntegerType.GetInt32(module.Context).Constant(1, true) }; var metadata = module.Context.MetadataNodeInContext(metadataArgs); module.AddNamedMetadataOperand("nvvm.annotations", metadata); }
public static Module Translate(Context context, params MethodInfo[] methods) { var module = new Module("Module", context); if (Environment.Is64BitOperatingSystem) { PInvoke.LLVMSetTarget(module, "nvptx64-nvidia-cuda"); PInvoke.LLVMSetDataLayout(module, "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64"); } else { PInvoke.LLVMSetTarget(module, "nvptx-nvidia-cuda"); PInvoke.LLVMSetDataLayout(module, "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64"); } foreach (var method in methods) Translate(context, module, method); return module; }
public static byte[] EmitInMemory(Module module, string targetCpu) { if (!_initialized) { _initialized = true; PInvoke.LLVMInitializeNVPTXTarget(); PInvoke.LLVMInitializeNVPTXTargetMC(); PInvoke.LLVMInitializeNVPTXTargetInfo(); PInvoke.LLVMInitializeNVPTXAsmPrinter(); } var triple = Marshal.PtrToStringAnsi(PInvoke.LLVMGetTarget(module)); IntPtr errorMessage; IntPtr target; if (PInvoke.LLVMGetTargetFromTriple(triple, out target, out errorMessage)) { throw new CudaSharpException(Marshal.PtrToStringAnsi(errorMessage)); } var targetMachine = PInvoke.LLVMCreateTargetMachine(target, triple, targetCpu, "", PInvoke.LlvmCodeGenOptLevel.LlvmCodeGenLevelDefault, PInvoke.LlvmRelocMode.LlvmRelocDefault, PInvoke.LlvmCodeModel.LlvmCodeModelDefault); IntPtr memoryBuffer; PInvoke.LLVMTargetMachineEmitToMemoryBuffer(targetMachine, module, PInvoke.LlvmCodeGenFileType.LlvmAssemblyFile, out errorMessage, out memoryBuffer); if (errorMessage != IntPtr.Zero) { var errorMessageStr = Marshal.PtrToStringAnsi(errorMessage); if (string.IsNullOrWhiteSpace(errorMessageStr) == false) { throw new CudaSharpException(errorMessageStr); } } var bufferStart = PInvoke.LLVMGetBufferStart(memoryBuffer); var bufferLength = PInvoke.LLVMGetBufferSize(memoryBuffer); var buffer = new byte[bufferLength.ToInt32()]; Marshal.Copy(bufferStart, buffer, 0, buffer.Length); PInvoke.LLVMDisposeMemoryBuffer(memoryBuffer); return(buffer); }
private static Function EmitFunction(Module module, MethodBase method) { var methodInfo = method as MethodInfo; var methodConstructor = method as ConstructorInfo; var declaringType = method.DeclaringType; if (methodInfo == null && methodConstructor == null) { throw new CudaSharpException("Unknown MethodBase type " + method.GetType().FullName); } if (declaringType == null) { throw new CudaSharpException("Could not find the declaring type of " + method.Name.StripNameToValidPtx()); } var parameters = method.GetParameters().Select(p => p.ParameterType); if (methodConstructor != null) { parameters = new[] { declaringType.MakeByRefType() } }
public static Module Translate(Context context, params MethodInfo[] methods) { var module = new Module("Module", context); if (Environment.Is64BitOperatingSystem) { module.SetTarget("nvptx64-nvidia-cuda"); module.SetDataLayout("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64"); } else { module.SetTarget("nvptx-nvidia-cuda"); module.SetDataLayout("e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64"); } foreach (var method in methods) { Translate(module, method); } return(module); }
/// <summary> /// Create a void function that takes no arguments /// </summary> /// <param name="module"></param> /// <param name="name"></param> /// <param name="returnType"></param> public Function(Module module, string name) : this(module, name, TypeRef.CreateVoid(), new TypeRef[0]) { }
public static byte[] EmitInMemory(Module module, string targetCpu) { if (!_initialized) { _initialized = true; PInvoke.LLVMInitializeNVPTXTarget(); PInvoke.LLVMInitializeNVPTXTargetMC(); PInvoke.LLVMInitializeNVPTXTargetInfo(); PInvoke.LLVMInitializeNVPTXAsmPrinter(); } var triple = Marshal.PtrToStringAnsi(PInvoke.LLVMGetTarget(module)); IntPtr errorMessage; IntPtr target; if (PInvoke.LLVMGetTargetFromTriple(triple, out target, out errorMessage)) throw new CudaSharpException(Marshal.PtrToStringAnsi(errorMessage)); var targetMachine = PInvoke.LLVMCreateTargetMachine(target, triple, targetCpu, "", PInvoke.LlvmCodeGenOptLevel.LlvmCodeGenLevelDefault, PInvoke.LlvmRelocMode.LlvmRelocDefault, PInvoke.LlvmCodeModel.LlvmCodeModelDefault); IntPtr memoryBuffer; PInvoke.LLVMTargetMachineEmitToMemoryBuffer(targetMachine, module, PInvoke.LlvmCodeGenFileType.LlvmAssemblyFile, out errorMessage, out memoryBuffer); if (errorMessage != IntPtr.Zero) { var errorMessageStr = Marshal.PtrToStringAnsi(errorMessage); if (string.IsNullOrWhiteSpace(errorMessageStr) == false) throw new CudaSharpException(errorMessageStr); } var bufferStart = PInvoke.LLVMGetBufferStart(memoryBuffer); var bufferLength = PInvoke.LLVMGetBufferSize(memoryBuffer); var buffer = new byte[bufferLength.ToInt32()]; Marshal.Copy(bufferStart, buffer, 0, buffer.Length); PInvoke.LLVMDisposeMemoryBuffer(memoryBuffer); return buffer; }
public Value AddGlobal(Module module, TypeRef type, String name) { return new Value(Native.AddGlobal(module.Handle, type.Handle, name)); }
public static void SetDataLayout(this Module module, string triple) { LLVMSetDataLayout(module, triple); }
public static void SetTarget(this Module module, string triple) { LLVMSetTarget(module, triple); }
public ExecutionEngine(Module module) { StringBuilder sb = new StringBuilder(1024); if(Native.CreateExecutionEngineForModule(ref m_handle, module.Handle, ref sb) == 0) Console.Error.WriteLine(sb.ToString()); }
public Function(Module mod, string name, FunctionType fnTy) : base(LLVM.AddFunction(mod, name, fnTy)) { _type = fnTy; }
public static void Translate(Context context, Module module, MethodInfo method) { var function = EmitFunction(context, module, method); var metadataArgs = new[] { function, PInvoke.LLVMMDStringInContext(context, method.Name), IntegerType.GetInt32(context).Constant(1, true) }; var metadata = PInvoke.LLVMMDNodeInContext(context, metadataArgs); PInvoke.LLVMAddNamedMetadataOperand(module, "nvvm.annotations", metadata); }
public static void AddNamedMetadataOperand(this Module module, string name, IntPtr value) { LLVMAddNamedMetadataOperand(module, name, value); }
public PassManager(Module module) { Guard.ArgumentNull(module, "module"); m_handle = Native.CreateFunctionPassManagerForModule(module.Handle); m_module = module.Handle; }
private static Function EmitFunction(Context context, Module module, MethodInfo method) { var funcType = new FunctionType(ConvertType(context, method.ReturnType), AnalyzeArguments(context, method.GetParameters())); var intrinsic = method.GetCustomAttribute<Gpu.BuiltinAttribute>(); if (intrinsic != null) { var name = intrinsic.Intrinsic; var preExisting = module.GetFunction(name); if (preExisting != null) return preExisting; return module.CreateFunction(name, funcType); } var function = module.CreateFunction(method.Name, funcType); var block = new Block("entry", context, function); var writer = new InstructionBuilder(context, block); var opcodes = method.Decompile().ToList(); FindBranchTargets(opcodes, context, function); var body = method.GetMethodBody(); var efo = new EmitFuncObj(context, module, function, writer, null, new Stack<Value>(), body == null ? null : new Value[body.LocalVariables.Count], new Value[method.GetParameters().Length]); foreach (var opcode in opcodes) { if (EmitFunctions.ContainsKey(opcode.Opcode) == false) throw new Exception("Unsupported CIL instruction " + opcode.Opcode); var func = EmitFunctions[opcode.Opcode]; efo.Argument = opcode.Parameter; func(efo); } return function; }
static void Main() { LLVM.Module module = new LLVM.Module("test_module"); module.Dump(); }
private static Type ConvertType(Module module, System.Type type) { if (type == typeof(void)) return Type.GetVoid(module.Context); if (type == typeof(bool)) return IntegerType.Get(module.Context, 1); if (type == typeof(byte)) return IntegerType.Get(module.Context, 8); if (type == typeof(short)) return IntegerType.Get(module.Context, 16); if (type == typeof(int)) return IntegerType.GetInt32(module.Context); if (type == typeof(long)) return IntegerType.Get(module.Context, 64); if (type == typeof(float)) return FloatType.Get(module.Context, 32); if (type == typeof(double)) return FloatType.Get(module.Context, 64); if (type.IsArray) return PointerType.Get(ConvertType(module, type.GetElementType()), 1); if (type.IsByRef) return PointerType.Get(ConvertType(module, type.GetElementType())); if (type.IsValueType) { var name = type.Name.StripNameToValidPtx(); var preExisting = module.GetTypeByName(name); if (preExisting != null) return preExisting; return new StructType(module.Context, name, AllFields(type).Select(t => ConvertType(module, t.FieldType))); } throw new CudaSharpException("Type cannot be translated to CUDA: " + type.FullName); }
public EmitFuncObj(Module module, Function function, MethodBody cilMethod, InstructionBuilder instructionBuilder, object argument, Stack<Value> stack, Value[] locals, Value[] parameters) { Module = module; Function = function; CilMethod = cilMethod; Builder = instructionBuilder; Argument = argument; Stack = stack; Locals = locals; Parameters = parameters; }
/// <summary> /// Create a function that takes no arguments /// </summary> /// <param name="module"></param> /// <param name="name"></param> /// <param name="returnType"></param> public Function(Module module, string name, TypeRef returnType) : this(module, name, returnType, new TypeRef[0]) { }
public EmitFuncObj(Context context, Module module, Function function, InstructionBuilder instructionBuilder, object argument, Stack<Value> stack, Value[] locals, Value[] parameters) { Context = context; Module = module; Function = function; Builder = instructionBuilder; Argument = argument; Stack = stack; Locals = locals; Parameters = parameters; }
public static void Initialize(LLVM.Module module) { TargetData tgt = new TargetData("e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-a0:0:64-f80:32:32-n8:16:32"); // TargetData tgt = new TargetData(module.DataLayout); Void = LLVM.Type.GetVoid(); //module.AddTypeName("type System.Void", Void); Bool = LLVM.Type.GetInt8(); //module.AddTypeName("type System.Bool", Bool); Char = LLVM.Type.GetInt8(); //module.AddTypeName("type System.Char", Char); Int8 = LLVM.Type.GetInt8(); //module.AddTypeName("type System.Int8", Int8); Int16 = LLVM.Type.GetInt16(); //module.AddTypeName("type System.Int16", Int16); Int32 = LLVM.Type.GetInt32(); //module.AddTypeName("type System.Int32", Int32); Int64 = LLVM.Type.GetInt64(); //module.AddTypeName("type System.Int64", Int64); Native = tgt.GetIntPtrType(); //module.AddTypeName("type System.Native", Native); Ptr = Native.GetPointerTo(0); //module.AddTypeName("type System.Ptr", Ptr); Object = LLVM.StructType.Get(module.Context, "type System.Object", new LLVM.Type[2] { Int32, Int32 }, false); //module.AddTypeName("type System.Object", Object); String = LLVM.Type.GetInt8(); // FIXME, TODO //module.AddTypeName("type System.String", String); // Initialize constants // Const_0 = GetConstant(0); Const_1 = GetConstant(1); Const_2 = GetConstant(2); Const_3 = GetConstant(3); Const_4 = GetConstant(4); Const_5 = GetConstant(5); Const_6 = GetConstant(6); Const_7 = GetConstant(7); Const_8 = GetConstant(8); Const_m1 = GetConstant(-1); LLVM.FunctionType ft = LLVM.FunctionType.Get(Object.GetPointerTo(0), new LLVM.Type[1] { Native }, false); Newobj = new LLVM.Function(module, "newobj", ft); ft = LLVM.FunctionType.Get(String.GetPointerTo(0), new LLVM.Type[1] { Int8.GetPointerTo(0) }, false); Newstr = new LLVM.Function(module, "newstring", ft); ft = LLVM.FunctionType.Get(Object.GetPointerTo(0), new LLVM.Type[2] { Native, Native }, false); Newarr = new LLVM.Function(module, "newarr", ft); }
/// <summary> /// Generates the BrainF runtime environment. /// </summary> private void GenerateHeader() { this.module = new Module(this.context, "BrainF"); // === Function prototypes ========================================= Function memsetFunction = Intrinsic.GetDecleration(this.module, IntrinsicType.memset, Type.GetInteger8PointerType(this.context), Type.GetInteger32Type(this.context)); // declare i32 @getchar() this.getcharFunction = (Function)this.module.GetOrInsertFunction("getchar", new FunctionType(Type.GetInteger32Type(this.context))); // declare i32 @putchar(i32) this.putcharFunction = (Function)this.module.GetOrInsertFunction("putchar", new FunctionType(Type.GetInteger32Type(this.context), Type.GetInteger32Type(this.context))); // === Function header ============================================= // define void @brainf() this.brainfFunction = (Function)this.module.GetOrInsertFunction("brainf", new FunctionType(Type.GetVoidType(this.context))); this.builder = new IRBuilder(new BasicBlock( this.context, this.brainfFunction, "brainf")); // %arr = malloc i8, i32 %d Constant valMemory = new Constant(this.context, 32, this.totalMemory); BasicBlock bb = this.builder.GetInsertBlock(); Type intType = Type.GetInteger32Type(this.context); Type byteType = Type.GetInteger8Type(this.context); Constant allocsize = new Constant(byteType); allocsize.TruncOrBitCast(intType); Instruction pointerArray = CallInstruction.CreateMalloc(bb, intType, byteType, allocsize, valMemory, "arr"); bb.PushBack(pointerArray); // call void @llvm.memset. CallInstruction memsetCall = this.builder.CreateCall( memsetFunction, pointerArray, new Constant(this.context, 8, 0), valMemory, new Constant(this.context, 32, 1), new Constant(this.context, 1, 0)); memsetCall.TailCall = false; // this.currentHead = this.builder.CreateGEP( pointerArray, new Constant(this.context, 32, this.totalMemory / 2), "head"); // Footer this.endBlock = new BasicBlock(this.context, this.brainfFunction, "brainf"); this.endBlock.PushBack(CallInstruction.CreateFree(pointerArray, this.endBlock)); ReturnInstruction.Create(this.context, this.endBlock); }
public GlobalVariable(Module mod, Type ty, string name) : base(LLVM.AddGlobal(mod, ty, name)) { }