public void ComparesGreaterThan([Range(0, 10)] int op1, [Range(0, 10)] int op2) { using (var module = LLVMModuleRef.CreateWithName("test_greaterthan")) { var def = module.AddFunction( LLVMTypeRef.Int1, "greaterthan", new[] { LLVMTypeRef.Int32, LLVMTypeRef.Int32 }, (f, b) => { var p1 = f.Params[0]; var p2 = f.Params[1]; var cmp = b.BuildICmp(LLVMIntPredicate.LLVMIntSGT, p1, p2); var r = b.BuildBitCast(cmp, f.TypeOf.ReturnType.ReturnType); var ret = b.BuildRet(r); }); module.Verify(LLVMVerifierFailureAction.LLVMPrintMessageAction); LLVM.InitializeNativeTarget(); LLVM.InitializeNativeAsmParser(); LLVM.InitializeNativeAsmPrinter(); var engine = module.CreateMCJITCompiler(); var func = engine.GetPointerToGlobal <Int32Int32Int8Delegate>(def); var result = op1 > op2 ? 1 : 0; Assert.AreEqual(result, func(op1, op2)); } }
public void AddsSigned() { var op1 = 0; var op2 = 0; using (var module = LLVMModuleRef.CreateWithName("test_add")) { var def = module.AddFunction( LLVMTypeRef.Int32, "add", new[] { LLVMTypeRef.Int32, LLVMTypeRef.Int32 }, (f, b) => { var p1 = f.Params[0]; var p2 = f.Params[1]; var add = b.BuildAdd(p1, p2); var ret = b.BuildRet(add); }); module.Verify(LLVMVerifierFailureAction.LLVMPrintMessageAction); LLVM.InitializeNativeTarget(); LLVM.InitializeNativeAsmParser(); LLVM.InitializeNativeAsmPrinter(); var engine = module.CreateMCJITCompiler(); var func = engine.GetPointerToGlobal <Int32Int32Int32Delegate>(def); var result = op1 + op2; Assert.AreEqual(result, func(op1, op2)); } }
public unsafe CompilationUnit(CompilerConfiguration compilerConfiguration, string name) { CompilerConfiguration = compilerConfiguration; Name = name; Module = LLVMModuleRef.CreateWithName(name); }
public GamaGlobalContext(string name) { ModuleName = $"{ name }.mod"; ErrorList = new GamaErrorCollection(); Module = LLVMModuleRef.CreateWithName(ModuleName); Context = Module.Context; Root = new GamaNamespace("[root]", this); Namespaces = new List <GamaNamespace>(); ImportedFiles = new List <string>(); // I know this is 'unsafe', but these methods are not implemeted to their OOP counterparts yet // So I am stuck with this for now unsafe { LLVM.SetDataLayout(Module, "e-m:w-i64:64-f80:128-n8:16:32:64-S128".GetSbytePtr()); if (Environment.OSVersion.Platform == PlatformID.Unix) { LLVM.SetTarget(Module, "x86_64-pc-linux-gnu".GetSbytePtr()); } else { LLVM.SetTarget(Module, "x86_64-pc-windows".GetSbytePtr()); } } }
public void Intro() { using var module = LLVMModuleRef.CreateWithName("LLVMSharpIntro"); var def = module.AddFunction( LLVMTypeRef.Int32, "sum", new[] { LLVMTypeRef.Int32, LLVMTypeRef.Int32 }, (f, b) => { var p1 = f.Params[0]; var p2 = f.Params[1]; var add = b.BuildAdd(p1, p2); var ret = b.BuildRet(add); }); module.Verify(LLVMVerifierFailureAction.LLVMPrintMessageAction); LLVM.InitializeNativeTarget(); LLVM.InitializeNativeAsmParser(); LLVM.InitializeNativeAsmPrinter(); var engine = module.CreateMCJITCompiler(); var function = engine.GetPointerToGlobal <BinaryInt32Operation>(def); var result = function(2, 2); Assert.AreEqual(4, result); }
public void ShiftsRight([Range(0, 256)] int op1, [Range(0, 8)] int op2) { using var module = LLVMModuleRef.CreateWithName("test_lshift"); var def = module.AddFunction( LLVMTypeRef.Int32, "lshift", new[] { LLVMTypeRef.Int32, LLVMTypeRef.Int32 }, (f, b) => { var p1 = f.Params[0]; var p2 = f.Params[1]; var shift = b.BuildLShr(p1, p2); var ret = b.BuildRet(shift); }); module.Verify(LLVMVerifierFailureAction.LLVMPrintMessageAction); LLVM.InitializeNativeTarget(); LLVM.InitializeNativeAsmParser(); LLVM.InitializeNativeAsmPrinter(); var engine = module.CreateMCJITCompiler(); var func = engine.GetPointerToGlobal <Int32Int32Int32Delegate>(def); var result = op1 >> op2; Assert.AreEqual(result, func(op1, op2)); }
public void CallsFunction([Range(0, 10)] int op1, [Range(0, 10)] int op2) { using (var module = LLVMModuleRef.CreateWithName("test_call")) { var defAdd = module.AddFunction( LLVMTypeRef.Int32, "add", new[] { LLVMTypeRef.Int32, LLVMTypeRef.Int32 }, (f, b) => { var p1 = f.Params[0]; var p2 = f.Params[1]; var add = b.BuildAdd(p1, p2); var ret = b.BuildRet(add); }); var defEntry = module.AddFunction( LLVMTypeRef.Int32, "entry", new[] { LLVMTypeRef.Int32, LLVMTypeRef.Int32 }, (f, b) => { var p1 = f.Params[0]; var p2 = f.Params[1]; var call = b.BuildCall(defAdd, new[] { p1, p2 }); var ret = b.BuildRet(call); }); module.Verify(LLVMVerifierFailureAction.LLVMPrintMessageAction); LLVM.InitializeNativeTarget(); LLVM.InitializeNativeAsmParser(); LLVM.InitializeNativeAsmPrinter(); var engine = module.CreateMCJITCompiler(); var func = engine.GetPointerToGlobal <Int32Int32Int32Delegate>(defEntry); var result = op1 + op2; Assert.AreEqual(result, func(op1, op2)); } }
internal WebAssemblyCodegenCompilation( DependencyAnalyzerBase <NodeFactory> dependencyGraph, WebAssemblyCodegenNodeFactory nodeFactory, IEnumerable <ICompilationRootProvider> roots, ILProvider ilProvider, DebugInformationProvider debugInformationProvider, Logger logger, WebAssemblyCodegenConfigProvider options) : base(dependencyGraph, nodeFactory, GetCompilationRoots(roots, nodeFactory), ilProvider, debugInformationProvider, null, logger) { NodeFactory = nodeFactory; LLVMModuleRef m = LLVMModuleRef.CreateWithName("netscripten"); m.Target = "wasm32-unknown-unknown-wasm"; // https://llvm.org/docs/LangRef.html#langref-datalayout // e litte endian, mangled names // m:e ELF mangling // p:32:32 pointer size 32, abi 32 // i64:64 64 ints aligned 64 // n:32:64 native widths // S128 natural alignment of stack m.DataLayout = "e-m:e-p:32:32-i64:64-n32:64-S128"; Module = m; Options = options; DIBuilder = Module.CreateDIBuilder(); DebugMetadataMap = new Dictionary <string, DebugMetadata>(); }
public void CreateDebugLocation() { string fileName = Path.GetFileName("DIBuilder.c"); string directory = Path.GetDirectoryName("."); LLVMModuleRef module = LLVMModuleRef.CreateWithName("netscripten"); module.Target = "asmjs-unknown-emscripten"; var dIBuilder = module.CreateDIBuilder(); var builder = module.Context.CreateBuilder(); LLVMMetadataRef fileMetadata = dIBuilder.CreateFile(fileName, directory); LLVMMetadataRef compileUnitMetadata = dIBuilder.CreateCompileUnit( LLVMDWARFSourceLanguage.LLVMDWARFSourceLanguageC, fileMetadata, "ILC", 0 /* Optimized */, String.Empty, 1, String.Empty, LLVMDWARFEmissionKind.LLVMDWARFEmissionFull, 0, 0, 0); module.AddNamedMetadataOperand("llvm.dbg.cu", compileUnitMetadata); LLVMMetadataRef functionMetaType = dIBuilder.CreateSubroutineType(fileMetadata, ReadOnlySpan <LLVMMetadataRef> .Empty, LLVMDIFlags.LLVMDIFlagZero); uint lineNumber = 1; var debugFunction = dIBuilder.CreateFunction(fileMetadata, "CreateDebugLocation", "CreateDebugLocation", fileMetadata, lineNumber, functionMetaType, 1, 1, lineNumber, 0, 0); LLVMMetadataRef currentLine = module.Context.CreateDebugLocation(lineNumber, 0, debugFunction, default(LLVMMetadataRef)); LLVMTypeRef[] FooParamTys = { LLVMTypeRef.Int64, LLVMTypeRef.Int64, }; LLVMTypeRef FooFuncTy = LLVMTypeRef.CreateFunction(LLVMTypeRef.Int64, FooParamTys); LLVMValueRef FooFunction = module.AddFunction("foo", FooFuncTy); var funcBlock = module.Context.AppendBasicBlock(FooFunction, "foo"); builder.PositionAtEnd(funcBlock); builder.BuildRet(LLVMValueRef.CreateConstInt(LLVMTypeRef.Int64, 0)); builder.CurrentDebugLocation = module.Context.MetadataAsValue(currentLine); var dwarfVersion = LLVMValueRef.CreateMDNode(new[] { LLVMValueRef.CreateConstInt(LLVMTypeRef.Int32, 2), module.Context.GetMDString("Dwarf Version", 13), LLVMValueRef.CreateConstInt(LLVMTypeRef.Int32, 4) }); var dwarfSchemaVersion = LLVMValueRef.CreateMDNode(new[] { LLVMValueRef.CreateConstInt(LLVMTypeRef.Int32, 2), module.Context.GetMDString("Debug Info Version", 18), LLVMValueRef.CreateConstInt(LLVMTypeRef.Int32, 3) }); module.AddNamedMetadataOperand("llvm.module.flags", dwarfVersion); module.AddNamedMetadataOperand("llvm.module.flags", dwarfSchemaVersion); dIBuilder.DIBuilderFinalize(); module.TryVerify(LLVMVerifierFailureAction.LLVMPrintMessageAction, out string message); Assert.AreEqual("", message); }
public void SetsAndGetsDataLayout() { var module = LLVMModuleRef.CreateWithName("test"); { const string ExampleDataLayout = "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128"; module.DataLayout = ExampleDataLayout; Assert.AreEqual(ExampleDataLayout, module.DataLayout); } module.Dispose(); }
public void SetsAndGetsTarget() { var module = LLVMModuleRef.CreateWithName("test"); { const string ExampleTarget = "x86_64-pc-windows-msvc"; module.Target = ExampleTarget; Assert.AreEqual(ExampleTarget, module.Target); } module.Dispose(); }
public Module(string name, DirectoryInfo rootDirectory, GlobalCompilationContext context) { Name = name; Context = context; LlvmModule = LLVMModuleRef.CreateWithName(name); StrConstants = new Dictionary <string, Value>(); Constants = new Dictionary <LLVMValueRef, Value>(); RootNamespace = new Namespace(this, rootDirectory); _foreignFunctions = new Dictionary <Function, Function>(); }
public void SizeTest() { LLVMModuleRef m = LLVMModuleRef.CreateWithName("netscripten"); LLVMExecutionEngineRef engineRef = m.CreateExecutionEngine(); LLVMTargetDataRef target = engineRef.TargetData; LLVMTypeRef testStruct = LLVMTypeRef.CreateStruct( new[] { LLVMTypeRef.Int16, LLVMTypeRef.Int32 }, true); Assert.AreEqual(48, target.SizeOfTypeInBits(testStruct)); Assert.AreEqual(6, target.StoreSizeOfType(testStruct)); Assert.AreEqual(6, target.ABISizeOfType(testStruct)); }
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(); }
public void OffsetTest() { LLVMModuleRef m = LLVMModuleRef.CreateWithName("netscripten"); LLVMExecutionEngineRef engineRef = m.CreateExecutionEngine(); LLVMTargetDataRef target = engineRef.TargetData; LLVMTypeRef testStruct = LLVMTypeRef.CreateStruct( new[] { LLVMTypeRef.Int16, LLVMTypeRef.Int32 }, true); Assert.AreEqual(0, target.OffsetOfElement(testStruct, 0)); Assert.AreEqual(2, target.OffsetOfElement(testStruct, 1)); Assert.AreEqual(target.ElementAtOffset(testStruct, 0), 0); Assert.AreEqual(target.ElementAtOffset(testStruct, 2), 1); }
public void ReturnsSizeOf() { using (var module = LLVMModuleRef.CreateWithName("test_sizeof")) { var str = LLVMTypeRef.CreateStruct(new[] { LLVMTypeRef.Int32, LLVMTypeRef.Int32 }, true); var def = module.AddFunction( LLVMTypeRef.Int32, "structure", Array.Empty <LLVMTypeRef>(), (f, b) => { var sz = str.SizeOf; var sz32 = b.BuildBitCast(sz, LLVMTypeRef.Int32); var ret = b.BuildRet(sz32); }); module.Verify(LLVMVerifierFailureAction.LLVMPrintMessageAction); LLVM.InitializeNativeTarget(); LLVM.InitializeNativeAsmParser(); LLVM.InitializeNativeAsmPrinter(); var engine = module.CreateMCJITCompiler(); var func = engine.GetPointerToGlobal <Int32Delegate>(def); Assert.AreEqual(8, func()); } }
public void AlignmentTest() { LLVMModuleRef m = LLVMModuleRef.CreateWithName("netscripten"); m.Target = "wasm32-unknown-unknown-wasm"; m.DataLayout = "e-m:e-p:32:32-i64:64-n32:64-S128"; LLVMExecutionEngineRef engineRef = m.CreateExecutionEngine(); LLVMTargetDataRef target = engineRef.TargetData; LLVMTypeRef testStruct = LLVMTypeRef.CreateStruct( new[] { LLVMTypeRef.Int16, LLVMTypeRef.Int32 }, true); Assert.AreEqual(1, target.ABIAlignmentOfType(testStruct)); Assert.AreEqual(1, target.CallFrameAlignmentOfType(testStruct)); Assert.AreEqual(8, target.PreferredAlignmentOfType(testStruct)); LLVMValueRef global = m.AddGlobal(LLVMTypeRef.CreatePointer(LLVMTypeRef.Int8, 0), "someGlobal"); Assert.AreEqual(4, target.PreferredAlignmentOfGlobal(global)); }
public void ReturnsConstant([Range(0, 10)] int input) { var uInput = (uint)input; using (var module = LLVMModuleRef.CreateWithName("test_constant")) { var def = module.AddFunction( LLVMTypeRef.Int32, "constant", Array.Empty <LLVMTypeRef>(), (f, b) => { var value = LLVMValueRef.CreateConstInt(LLVMTypeRef.Int32, uInput); var ret = b.BuildRet(value); }); module.Verify(LLVMVerifierFailureAction.LLVMPrintMessageAction); LLVM.InitializeNativeTarget(); LLVM.InitializeNativeAsmParser(); LLVM.InitializeNativeAsmPrinter(); var engine = module.CreateMCJITCompiler(); var func = engine.GetPointerToGlobal <Int32Delegate>(def); Assert.AreEqual(input, func()); } }
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(); }