public Main Compile(LLVMModuleRef module) { string error = null; if (LLVM.VerifyModule(module, LLVMVerifierFailureAction.LLVMPrintMessageAction, out error)) { throw new LLVMJITterException(error); } LLVM.LinkInMCJIT(); LLVM.InitializeX86TargetMC(); LLVM.InitializeX86Target(); LLVM.InitializeX86TargetInfo(); LLVM.InitializeX86AsmParser(); LLVM.InitializeX86AsmPrinter(); LLVMMCJITCompilerOptions options = new LLVMMCJITCompilerOptions() { OptLevel = (int)LLVMCodeGenOptLevel.LLVMCodeGenLevelAggressive }; LLVM.InitializeMCJITCompilerOptions(options); if (LLVM.CreateMCJITCompilerForModule(out var ee, module, options, out error)) { throw new LLVMJITterException(error); } var fp = LLVM.GetPointerToGlobal(ee, LLVM.GetNamedFunction(module, "main")); var main = (Main)Marshal.GetDelegateForFunctionPointer(fp, typeof(Main)); return(main); }
private void RunJit() { LLVMExecutionEngineRef engine; LLVM.LinkInMCJIT(); LLVM.InitializeX86Target(); LLVM.InitializeX86TargetInfo(); LLVM.InitializeX86TargetMC(); LLVM.InitializeX86AsmPrinter(); var options = new LLVMMCJITCompilerOptions(); var optionsSize = (4 * sizeof(int)) + IntPtr.Size; // LLVMMCJITCompilerOptions has 4 ints and a pointer IntPtr error; LLVM.VerifyModule(_module, LLVMVerifierFailureAction.LLVMAbortProcessAction, out error); LLVM.DisposeMessage(error); LLVM.SetTarget(_module, Marshal.PtrToStringAnsi(LLVM.GetDefaultTargetTriple()) + "-elf"); LLVM.CreateMCJITCompilerForModule(out engine, _module, out options, optionsSize, out error); //LLVM.DumpModule(_module); var main = (program)Marshal.GetDelegateForFunctionPointer(LLVM.GetPointerToGlobal(engine, _currentFunction), typeof(program)); main(); }
public override CompilerResult VisitProgram(DesignScriptParser.ProgramContext context) { var success = new LLVMBool(0); module = LLVM.ModuleCreateWithName("DesignScript"); builder = LLVM.CreateBuilder(); LLVM.LinkInMCJIT(); LLVM.InitializeX86TargetInfo(); LLVM.InitializeX86Target(); LLVM.InitializeX86TargetMC(); LLVM.InitializeX86AsmParser(); LLVM.InitializeX86AsmPrinter(); LLVMMCJITCompilerOptions options = new LLVMMCJITCompilerOptions { NoFramePointerElim = 1 }; LLVM.InitializeMCJITCompilerOptions(options); if (LLVM.CreateExecutionEngineForModule(out engine, module, out var errorMessage).Value == 1) { Console.WriteLine(errorMessage); return(new NullCompilerResult()); } #region Add optimization passes // Create a function pass manager for this engine passManager = LLVM.CreateFunctionPassManagerForModule(module); // Do simple "peephole" optimizations and bit-twiddling optzns. LLVM.AddInstructionCombiningPass(passManager); // Reassociate expressions. LLVM.AddReassociatePass(passManager); // Eliminate Common SubExpressions. LLVM.AddGVNPass(passManager); // Simplify the control flow graph (deleting unreachable blocks, etc). LLVM.AddCFGSimplificationPass(passManager); LLVM.InitializeFunctionPassManager(passManager); #endregion base.VisitProgram(context); if (LLVM.VerifyModule(module, LLVMVerifierFailureAction.LLVMPrintMessageAction, out var error) != success) { Console.WriteLine($"Error: {error}"); } LLVM.DumpModule(module); LLVM.DisposeBuilder(builder); LLVM.DisposeExecutionEngine(engine); return(new NullCompilerResult()); }
public void Run(string pPath) { try { if (LLVM.CreateMemoryBufferWithContentsOfFile(pPath, out LLVMMemoryBufferRef mem, out string message).Value != 0) { Console.WriteLine(message); return; } if (LLVM.ParseBitcode(mem, out LLVMModuleRef m, out message).Value != 0) { Console.WriteLine(message); return; } LLVM.LinkInMCJIT(); LLVM.InitializeX86TargetMC(); LLVM.InitializeX86Target(); LLVM.InitializeX86TargetInfo(); LLVM.InitializeX86AsmParser(); LLVM.InitializeX86AsmPrinter(); LLVMMCJITCompilerOptions options = new LLVMMCJITCompilerOptions { NoFramePointerElim = 1 }; LLVM.InitializeMCJITCompilerOptions(options); if (LLVM.CreateMCJITCompilerForModule(out _engine, m, options, out message).Value != 0) { Console.WriteLine($"Error: {message}"); } SetupReversePinvokeCalls(m); IntPtr i = (IntPtr)LLVM.GetGlobalValueAddress(_engine, "_main"); var main = (MainMethod)Marshal.GetDelegateForFunctionPointer(i, typeof(MainMethod)); GC.TryStartNoGCRegion(100000); main(); GC.EndNoGCRegion(); } catch (Exception e) { Console.WriteLine(e.Message); } }
public void TestMethod1() { LLVM.LinkInMCJIT(); LLVM.InitializeX86TargetMC(); LLVM.InitializeX86Target(); LLVM.InitializeX86TargetInfo(); LLVM.InitializeX86AsmParser(); LLVM.InitializeX86AsmPrinter(); var mod = LLVMModuleRef.CreateWithName("Test1"); var options = LLVMMCJITCompilerOptions.Create(); options.NoFramePointerElim = 1; var engine = mod.CreateMCJITCompiler(ref options); LLVMTypeRef[] paramsType = { LLVMTypeRef.Int32 }; var funcType = LLVMTypeRef.CreateFunction(LLVMTypeRef.Int32, paramsType, false); var acc = mod.AddFunction("acc", funcType); var gs = mod.AddGlobal(LLVMTypeRef.Int32, "gs"); var entry = acc.AppendBasicBlock("entry"); var builder = mod.Context.CreateBuilder(); builder.PositionAtEnd(entry); var tmp = builder.BuildLoad(gs); var tmp2 = builder.BuildMul(tmp, acc.GetParam(0), "".AsSpan()); builder.BuildStore(tmp2, gs); builder.BuildRet(tmp2); if (!mod.TryVerify(LLVMVerifierFailureAction.LLVMPrintMessageAction, out var error)) { Trace.WriteLine(error); } builder.Dispose(); object gsActual = 1; var handle = GCHandle.Alloc(gsActual, GCHandleType.Pinned); engine.AddGlobalMapping(gs, handle.AddrOfPinnedObject()); var accMethod = engine.GetPointerToGlobal <Add>(acc); var gsAddr = engine.GetPointerToGlobal(gs); Assert.AreEqual(2, accMethod(2)); Assert.AreEqual(8, accMethod(4)); Assert.AreEqual(8, gsActual); Trace.WriteLine(mod.PrintToString()); engine.Dispose(); handle.Free(); }
///<summary>Runs the LLVM IR by compiling it and using the given function pointers</summary> public void Run(IReadOnlyDictionary <string, IntPtr> env) { LLVM.BuildRetVoid(Generator.Builder); if (LLVM.VerifyModule(Generator.Module, LLVMVerifierFailureAction.LLVMPrintMessageAction, out var error) != new LLVMBool(0)) { Console.WriteLine($"Error in State.Module: {error}"); } LLVM.LinkInMCJIT(); LLVM.InitializeX86TargetMC(); LLVM.InitializeX86Target(); LLVM.InitializeX86TargetInfo(); LLVM.InitializeX86AsmParser(); LLVM.InitializeX86AsmPrinter(); var options = new LLVMMCJITCompilerOptions { NoFramePointerElim = 1 }; LLVM.InitializeMCJITCompilerOptions(options); if (LLVM.CreateMCJITCompilerForModule(out var engine, Generator.Module, options, out error) != new LLVMBool(0)) { Console.WriteLine($"JIT init error: {error}"); } foreach (var fn in env) { LLVM.AddGlobalMapping(engine, Generator.KnownFunctions[fn.Key], fn.Value); } var jitty = (JitEntryPoint)Marshal.GetDelegateForFunctionPointer(LLVM.GetPointerToGlobal(engine, Generator.EntryPoint), typeof(JitEntryPoint)); //LLVM.DumpModule(Generator.Module); var s = Stopwatch.StartNew(); Console.WriteLine("Call into JITted code..."); jitty(); var t = s.ElapsedMilliseconds; Console.WriteLine("Returned after {0} ms", t); LLVM.DisposeBuilder(Generator.Builder); LLVM.DisposeExecutionEngine(engine); }
static LLVMExtensions() { _moduleInstanceFieldInfo = typeof(Module).GetField( "instance", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); LLVMSharp.LLVM.LinkInMCJIT(); LLVMSharp.LLVM.InitializeX86TargetMC(); LLVMSharp.LLVM.InitializeX86Target(); LLVMSharp.LLVM.InitializeX86TargetInfo(); LLVMSharp.LLVM.InitializeX86AsmParser(); LLVMSharp.LLVM.InitializeX86AsmPrinter(); _mcJITCompilerOptions = new LLVMMCJITCompilerOptions { NoFramePointerElim = 1, // TODO: comment about why this is necessary CodeModel = LLVMCodeModel.LLVMCodeModelLarge, }; LLVMSharp.LLVM.InitializeMCJITCompilerOptions(_mcJITCompilerOptions); }
public static LLVMExecutionEngineRef CompilerForModule(LLVMModuleRef mod) { IntPtr error; LLVMExecutionEngineRef engine; LLVM.LinkInMCJIT(); LLVM.InitializeX86AsmPrinter(); LLVM.InitializeX86Target(); LLVM.InitializeX86TargetMC(); LLVM.InitializeX86TargetInfo(); LLVM.InitializeX86Disassembler(); var options = new LLVMMCJITCompilerOptions(); options.OptLevel = 3; options.CodeModel = LLVMCodeModel.LLVMCodeModelJITDefault; var optionsSize = (4 * sizeof(int)) + IntPtr.Size; // LLVMMCJITCompilerOptions has 4 ints and a pointer LLVM.InitializeMCJITCompilerOptions(out options, (ulong)optionsSize); LLVM.CreateMCJITCompilerForModule(out engine, mod, out options, (ulong)optionsSize, out error); Console.WriteLine(StringifyMessage(error)); return(engine); }
static ExecutionContext() { LLVMSharp.LLVM.LinkInMCJIT(); LLVMSharp.LLVM.InitializeX86TargetMC(); LLVMSharp.LLVM.InitializeX86Target(); LLVMSharp.LLVM.InitializeX86TargetInfo(); LLVMSharp.LLVM.InitializeX86AsmParser(); LLVMSharp.LLVM.InitializeX86AsmPrinter(); _options = new LLVMMCJITCompilerOptions { NoFramePointerElim = 1, // TODO: comment about why this is necessary CodeModel = LLVMCodeModel.LLVMCodeModelLarge, }; LLVMSharp.LLVM.InitializeMCJITCompilerOptions(_options); AddSymbolForDelegate("output_bool", _outputBool); AddSymbolForDelegate("output_int8", _outputInt8); AddSymbolForDelegate("output_uint8", _outputUInt8); AddSymbolForDelegate("output_int16", _outputInt16); AddSymbolForDelegate("output_uint16", _outputUInt16); AddSymbolForDelegate("output_int32", _outputInt32); AddSymbolForDelegate("output_uint32", _outputUInt32); AddSymbolForDelegate("output_int64", _outputInt64); AddSymbolForDelegate("output_uint64", _outputUInt64); AddSymbolForDelegate("output_string", _outputString); IntPtr kernel32Instance = LoadLibrary("kernel32.dll"); LLVMSharp.LLVM.AddSymbol("CopyMemory", GetProcAddress(kernel32Instance, "RtlCopyMemory")); LLVMSharp.LLVM.AddSymbol("CloseHandle", GetProcAddress(kernel32Instance, "CloseHandle")); LLVMSharp.LLVM.AddSymbol("CreateFileA", GetProcAddress(kernel32Instance, "CreateFileA")); LLVMSharp.LLVM.AddSymbol("ReadFile", GetProcAddress(kernel32Instance, "ReadFile")); LLVMSharp.LLVM.AddSymbol("WriteFile", GetProcAddress(kernel32Instance, "WriteFile")); }
public static int Process(JIT args) { if (!System.IO.File.Exists(args.File)) { Console.WriteLine($"File does not exists: { args.File }"); return(1); } /* LLVM */ LLVM.LinkInMCJIT(); LLVM.InitializeX86TargetInfo(); LLVM.InitializeX86Target(); LLVM.InitializeX86TargetMC(); LLVM.InitializeX86AsmParser(); LLVM.InitializeX86AsmPrinter(); LLVMMCJITCompilerOptions options = new LLVMMCJITCompilerOptions() { NoFramePointerElim = 1 }; return(0); }
private static InitData Initialize(SyntaxTree tree) { LLVMModuleRef module = LLVM.ModuleCreateWithName("test jit"); LLVMBuilderRef builder = LLVM.CreateBuilder(); LLVM.LinkInMCJIT(); LLVM.InitializeX86TargetInfo(); LLVM.InitializeX86Target(); LLVM.InitializeX86TargetMC(); LLVM.InitializeX86AsmPrinter(); LLVMExecutionEngineRef engine; IntPtr errorMessage; if (LLVM.CreateExecutionEngineForModule(out engine, module, out errorMessage).Value == 1) { Console.WriteLine(Marshal.PtrToStringAnsi(errorMessage)); LLVM.DisposeMessage(errorMessage); throw new Exception("Dispose error"); } var platform = Environment.OSVersion.Platform; if (platform == PlatformID.Win32NT) // On Windows, LLVM currently (3.6) does not support PE/COFF { LLVM.SetTarget(module, string.Concat(Marshal.PtrToStringAnsi(LLVM.GetDefaultTargetTriple()), "-elf")); } var options = new LLVMMCJITCompilerOptions(); var optionsSize = (4 * sizeof(int)) + IntPtr.Size; // LLVMMCJITCompilerOptions has 4 ints and a pointer LLVM.InitializeMCJITCompilerOptions(out options, optionsSize); IntPtr error; LLVM.CreateMCJITCompilerForModule(out engine, module, out options, optionsSize, out error); // Create a function pass manager for this engine LLVMPassManagerRef passManager = LLVM.CreateFunctionPassManagerForModule(module); // Set up the optimizer pipeline. Start with registering info about how the // target lays out data structures. LLVM.AddTargetData(LLVM.GetExecutionEngineTargetData(engine), passManager); LLVM.AddGVNPass(passManager); LLVMBool f = LLVM.InitializeFunctionPassManager(passManager); var s = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); var compilation = CSharpCompilation.Create("MyCompilation", new[] { tree }, new[] { s }); var model = compilation.GetSemanticModel(tree); var initData = new InitData(); initData.builder = builder; initData.engine = engine; initData.model = model; initData.module = module; return(initData); }
private static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); // Make the module, which holds all the code. LLVMModuleRef module = LLVM.ModuleCreateWithName("my cool jit"); LLVMBuilderRef builder = LLVM.CreateBuilder(); LLVM.LinkInMCJIT(); LLVM.InitializeX86TargetInfo(); LLVM.InitializeX86Target(); LLVM.InitializeX86TargetMC(); LLVM.InitializeX86AsmPrinter(); LLVMExecutionEngineRef engine; IntPtr errorMessage; if (LLVM.CreateExecutionEngineForModule(out engine, module, out errorMessage).Value == 1) { Console.WriteLine(Marshal.PtrToStringAnsi(errorMessage)); LLVM.DisposeMessage(errorMessage); return; } var platform = System.Environment.OSVersion.Platform; if (platform == PlatformID.Win32NT) // On Windows, LLVM currently (3.6) does not support PE/COFF { //LLVM.SetTarget(module, string.Concat(Marshal.PtrToStringAnsi(LLVM.GetDefaultTargetTriple()), "-elf")); } var options = new LLVMMCJITCompilerOptions(); var optionsSize = (4 * sizeof(int)) + IntPtr.Size; // LLVMMCJITCompilerOptions has 4 ints and a pointer LLVM.InitializeMCJITCompilerOptions(out options, optionsSize); IntPtr error; LLVM.CreateMCJITCompilerForModule(out engine, module, out options, optionsSize, out error); // Create a function pass manager for this engine LLVMPassManagerRef passManager = LLVM.CreateFunctionPassManagerForModule(module); // Set up the optimizer pipeline. Start with registering info about how the // target lays out data structures. LLVM.AddTargetData(LLVM.GetExecutionEngineTargetData(engine), passManager); LLVMLinkInGC(); sw.Stop(); Console.WriteLine("LLVM Init: " + sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); var tree = CSharpSyntaxTree.ParseText(@" class C { static double F() { float a = 10.0F; int b = (int)a; int c = 10 + b; return (float)c; } }"); var tree2 = CSharpSyntaxTree.ParseText(@" using System; using System.Collections; public enum MiniSharpSimpleType : ushort { Integral, FloatingPoint, Pointer } public class Program2 { public static int Prop { get; set; } } class C { public int Prop {get; set;} int Fjj(int x) { foobar: int aaaw2a = 10; int sdjkdjs = 10; ushort s = 5; switch (s) { case 1: break; case 2: goto case 1; } int aaaa = 10; switch(aaaa) { case 0: goto case 1; case 1: goto default; default: int ssss = 1; break; } if (x >= 0) goto x; x = -x; x: return x; } public object xfoo() { int[] h = new int[10]; ++h[0]; ++Program2.Prop; var c = new C(); ++c.Prop; uint q = 10; var ffffff = -q; float jf = -10.0; int jff = (int)-10.0; var ddddd = !true; int z = +10; int l = ~10; int ff = -10; var k = -10.0F; Hashtable h = new Hashtable(); h[1] = 2; int[] arr = new int[10]; arr[1] = 10; object x = default(int); return new {a = 10}; } static short bar() { return 2; } static short foo(Type t) { var a = 10; return a; } static int Main() { var d = bar() + bar(); foo(typeof(string)); object x = null; object aa = x ?? 0; var ac = 10 as object; short a = 10; short b = 10; var c = a + b; return 0; } } "); sw.Stop(); Console.WriteLine("CSharp Parse Time: " + sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); var sm = tree.GetRoot(); var s = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); var s2 = MetadataReference.CreateFromFile(typeof(Hashtable).Assembly.Location); var compilation = CSharpCompilation.Create("MyCompilation", new[] { tree }, new[] { s }); var model = compilation.GetSemanticModel(tree, ignoreAccessibility: false); sw.Stop(); Console.WriteLine("Semantic Analysis: " + sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); var d = model.Compilation.GetDiagnostics(); var symbolVisitor = new VariableDeclarationVisitor(model, builder); symbolVisitor.Visit(sm); for (int i = 0; i < 100000; ++i) { var stack = new Stack <LLVMValueRef>(); var v = new LLVMIRGenerationVisitor(model, module, builder, stack); v.Visit(sm); LLVM.GetPointerToGlobal(engine, v.Function); } /* * var stack = new Stack<LLVMValueRef>(); * var v = new LLVMIRGenerationVisitor(model, module, builder, stack); * * LLVMTypeRef[] gcrootArgs = new LLVMTypeRef[2]; * gcrootArgs[0] = LLVM.PointerType(LLVM.PointerType(LLVM.Int8Type(), 0), 0); * gcrootArgs[1] = LLVM.PointerType(LLVM.Int8Type(), 0); * * * var gcRootFuncType = LLVM.FunctionType(LLVM.VoidType(), out gcrootArgs[0], 2, new LLVMBool(0)); * * var ff = LLVM.AddFunction(module, "llvm.gcroot", gcRootFuncType); * var argsxx = new LLVMValueRef[2]; * argsxx[0] = LLVM.BuildBitCast(builder, LLVM.ConstNull(LLVM.PointerType(LLVM.Int8Type(), 0)), LLVM.PointerType(LLVM.PointerType(LLVM.Int8Type(), 0), 0), "gc"); * argsxx[1] = LLVM.ConstNull(LLVM.PointerType(LLVM.Int8Type(), 0)); * LLVM.BuildCall(builder, ff, out argsxx[0], 2, ""); */ //var v = new Visitor(model); sw.Stop(); Console.WriteLine("IR Generation: " + sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); // LLVM.SetGC(v.Function, "shadow-stack"); LLVM.DumpModule(module); // LLVM.VerifyFunction(v.Function, LLVMVerifierFailureAction.LLVMAbortProcessAction); //int ddd = f(); LLVM.AddCFGSimplificationPass(passManager); LLVM.AddInstructionCombiningPass(passManager); LLVM.AddBasicAliasAnalysisPass(passManager); LLVM.AddGVNPass(passManager); LLVM.AddPromoteMemoryToRegisterPass(passManager); //LLVM.RunFunctionPassManager(passManager, v.Function); LLVM.DumpModule(module); LLVM.WriteBitcodeToFile(module, @"C:\users\mukul\desktop\h.bc"); sw.Stop(); Console.WriteLine("Dumping + Bitcode Write: " + sw.ElapsedMilliseconds); Console.ReadKey(); // var addMethod = (Add)Marshal.GetDelegateForFunctionPointer(LLVM.GetPointerToGlobal(engine, v.Function), typeof(Add)); // var x = addMethod(); }
private void ExecuteCode() { var globals = new Dictionary <string, GCHandle>(); LLVMModuleRef mod; LLVMExecutionEngineRef engine = null; try { SymbolTable.IsReadOnly = true; mod = LLVMModuleRef.CreateWithName("main"); var options = LLVMMCJITCompilerOptions.Create(); engine = mod.CreateMCJITCompiler(ref options); var builder = mod.Context.CreateBuilder(); var globalSource = SymbolTable.ItemsSource as ICollection <SymbolEntry>; var globalStore = new Dictionary <string, object>(); foreach (var k in globalSource) { globalStore.Add(k.Name, k.Value); } foreach (var kv in globalStore) { globals.Add(kv.Key, GCHandle.Alloc(kv.Value, GCHandleType.Pinned)); } var fpm = mod.CreateFunctionPassManager(); fpm.AddPromoteMemoryToRegisterPass(); fpm.AddInstructionCombiningPass(); fpm.AddReassociatePass(); fpm.AddGVNPass(); fpm.AddCFGSimplificationPass(); fpm.InitializeFunctionPassManager(); var symT = ProcessGlobals(mod, engine, globals); var lexicals = new List <LexicalElement>(); try { using (var ms = new MemoryStream()) { var writer = new StreamWriter(ms); writer.Write(Editor.Document.CurrentSnapshot.GetText(LineTerminator.Newline)); writer.Flush(); ms.Seek(0L, SeekOrigin.Begin); var reader = new StreamReader(ms); var l = new LexerStateMachine(reader); l.AdvanceChar(); LexicalElement t; while ((t = l.NextToken()) != null) { if (t is LineFeedElement) { continue; } lexicals.Add(t); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "词法错误", MessageBoxButton.OK, MessageBoxImage.Error); return; } var exceptions = new List <SyntaxException>(); SyntaxNode treeRoot; try { treeRoot = slr1Driver.Parse(new Queue <LexicalElement>(lexicals), CommonUtils.Closure( new HashSet <Item>() { new Item() { ProductionRule = PascalDefinition.ProductionRules[0], Cursor = 0 } }, generator.ProductionDict), typeof(SNode), null, exceptions); if (exceptions.Count > 0) { StringBuilder sb = new StringBuilder(); sb.Append($"语法分析器共检测到{exceptions.Count}个错误\n\n"); foreach (var exception in exceptions) { sb.Append(exception.Message); sb.Append('\n'); } MessageBox.Show(sb.ToString(), "错误", MessageBoxButton.OK, MessageBoxImage.Error); return; } } catch (SyntaxException ex) { StringBuilder sb = new StringBuilder(); sb.Append($"语法分析器共检测到{exceptions.Count}个错误,无法恢复\n\n"); foreach (var exception in exceptions) { sb.Append(exception.Message); sb.Append('\n'); } MessageBox.Show(sb.ToString(), $"语法分析错误", MessageBoxButton.OK, MessageBoxImage.Error); return; } var translator = new LLVMTranslator.LLVMTranslator(mod, engine, builder, symT); translator.Visit(treeRoot); fpm.RunFunctionPassManager(translator.func); IrBox.Text = mod.PrintToString(); PM main = engine.GetPointerToGlobal <PM>(translator.func); main(); foreach (var symbolEntry in globalSource) { symbolEntry.Value = (int)globalStore[symbolEntry.Name]; } } catch (Exception e) { MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } finally { SymbolTable.IsReadOnly = false; if (engine != null) { engine.Dispose(); } foreach (var kv in globals) { kv.Value.Free(); } } }
public void LLVMTest2() { LLVM.LinkInMCJIT(); LLVM.InitializeX86TargetMC(); LLVM.InitializeX86Target(); LLVM.InitializeX86TargetInfo(); LLVM.InitializeX86AsmParser(); LLVM.InitializeX86AsmPrinter(); var mod = LLVMModuleRef.CreateWithName("Test1"); var options = LLVMMCJITCompilerOptions.Create(); options.NoFramePointerElim = 1; var engine = mod.CreateMCJITCompiler(ref options); var builder = mod.Context.CreateBuilder(); var lexicals = new List <LexicalElement>(); var globals = new LLVMSymbolTable(null); globals.Add("z", mod.AddGlobal(LLVMTypeRef.Int32, "z")); object z = 0; var handle = GCHandle.Alloc(z, GCHandleType.Pinned); engine.AddGlobalMapping(globals["z"], handle.AddrOfPinnedObject()); using (var fs = new FileStream("D:\\Repos\\PascalCompiler\\SyntaxAnalyzerTest\\test_source2.txt", FileMode.Open)) { using (var ss = new StreamReader(fs)) { var l = new LexerStateMachine(ss); l.AdvanceChar(); LexicalElement t; while ((t = l.NextToken()) != null) { if (t is LineFeedElement) { continue; } lexicals.Add(t); } } } var history = new List <ParserConfiguration>(); var exceptions = new List <SyntaxException>(); SyntaxNode treeRoot; var generator = new Generator(PascalDefinition.ProductionRules); var slr1Table = generator.Generate(PascalDefinition.NonTerminalKey.Start); slr1Table.AllowedErrorRecoveryKey.Add(PascalDefinition.NonTerminalKey.Statement, () => new StatementNode(new SyntaxNode[0])); var slr1Driver = new Slr1Driver(slr1Table); treeRoot = slr1Driver.Parse(new Queue <LexicalElement>(lexicals), CommonUtils.Closure( new HashSet <Item>() { new Item() { ProductionRule = PascalDefinition.ProductionRules[0], Cursor = 0 } }, generator.ProductionDict), typeof(SNode), history, exceptions); var translator = new LLVMTranslator.LLVMTranslator(mod, engine, builder, globals); translator.Visit(treeRoot); if (!mod.TryVerify(LLVMVerifierFailureAction.LLVMPrintMessageAction, out var error)) { Trace.WriteLine(error); } Trace.WriteLine(mod.PrintToString()); PM a = engine.GetPointerToGlobal <PM>(translator.func); a(); builder.Dispose(); engine.Dispose(); handle.Free(); }