internal EmittingContext(LLVMModuleRef pModule, LLVMPassManagerRef pPass, bool pEmitDebug) { CurrentModule = pModule; _passManager = pPass; _context = LLVM.GetGlobalContext(); _deferredStatements = new Stack <List <Syntax.SyntaxNode> >(); Builder = LLVM.CreateBuilder(); _emitDebug = pEmitDebug; Locals = new ScopeCache <LocalDefinition>(); AccessStack = new AccessStack <MemberAccess>(); BreakLocations = new AccessStack <LLVMValueRef>(1); if (_emitDebug) { _debugLocations = new Stack <LLVMMetadataRef>(); _debugInfo = Utils.LlvmPInvokes.LLVMCreateDIBuilder(CurrentModule); _debugFile = Utils.LlvmPInvokes.LLVMDIBuilderCreateFile(_debugInfo, "debug", 5, ".", 1); //Set debug version var version = LLVM.MDNode(new LLVMValueRef[] { GetInt(1), //Error on mismatch LLVM.MDString("Debug Info Version", 18), //Constant string. Cannot change. GetInt(3) }); //Debug version LLVM.AddNamedMetadataOperand(CurrentModule, "llvm.module.flags", version); } }
public LLVMModuleRef Generate(SyntaxTree tree) { m_VariablePointers = new Dictionary <VariableSymbol, LLVMValueRef>(); m_FunctionPointers = new Dictionary <FunctionSymbol, LLVMValueRef>(); m_Types = new Dictionary <TypeSymbol, LLVMTypeRef>(); m_BreakableStatementSuccessor = new Dictionary <Statement, LLVMBasicBlockRef>(); m_Module = LLVM.ModuleCreateWithName("test"); m_Builder = LLVM.CreateBuilder(); m_Tree = tree; LoadTypes(m_Tree.GlobalSymbols); foreach (var stmt in m_Tree.Root) { VisitStmt(stmt); } LLVM.DisposeBuilder(m_Builder); LLVMPassManagerRef pm = LLVM.CreatePassManager(); LLVM.AddPromoteMemoryToRegisterPass(pm); LLVM.AddInstructionCombiningPass(pm); LLVM.AddReassociatePass(pm); LLVM.AddGVNPass(pm); LLVM.AddCFGSimplificationPass(pm); LLVM.RunPassManager(pm, m_Module); return(m_Module); }
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 CodeGenParserListener( LLVMExecutionEngineRef ee, LLVMPassManagerRef passManager, CodeGenVisitor visitor) { _visitor = visitor; _ee = ee; _passManager = passManager; }
public static void AddRewriteStatepointsForGCPass(LLVMPassManagerRef passManagerRef) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { AddRewriteStatepointsForGCPass_Win(passManagerRef); } else { AddRewriteStatepointsForGCPass_Nix(passManagerRef); } }
public override CompilerResult VisitFile([NotNull] LangParser.FileContext context) { module = LLVM.ModuleCreateWithName("Lang"); contexts = new Stack <Context>(); LLVMPassManagerRef passManager = LLVM.CreateFunctionPassManagerForModule(module); // Set up the optimizer pipeline. Start with registering info about how the // target lays out data structures. // LLVM.DisposeTargetData(LLVM.GetExecutionEngineTargetData(engine)); // Provide basic AliasAnalysis support for GVN. LLVM.AddBasicAliasAnalysisPass(passManager); // Promote allocas to registers. LLVM.AddPromoteMemoryToRegisterPass(passManager); // 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); this.passManager = passManager; base.VisitFile(context); LLVM.VerifyModule(module, LLVMVerifierFailureAction.LLVMPrintMessageAction, out string str); LLVM.DumpModule(module); LLVM.WriteBitcodeToFile(module, @"C:\Users\superblaubeere27\Desktop\compilerTest\Compiler\Compiler\code\compiled.bc"); LLVM.DisposePassManager(passManager); LLVM.DisposeModule(module); return(NullCompilerResult.INSTANCE); }
private void OptimizeAll(LLVMPassManagerRef pass, Namespace ns) { foreach (var overloads in ns.Functions.Values) { foreach (var function in overloads.Functions) { if (function.IsCompiled) { pass.RunFunctionPassManager(function.LlvmValue); } } } foreach (var child in ns.Children.Values) { OptimizeAll(pass, child); } }
protected override void Dispose(bool disposing) { if (OptimizeModulePassManager.Pointer != IntPtr.Zero) { DisposePassManager(OptimizeModulePassManager); OptimizeModulePassManager = default(LLVMPassManagerRef); } if (KernelModulePassManager.Pointer != IntPtr.Zero) { DisposePassManager(KernelModulePassManager); KernelModulePassManager = default(LLVMPassManagerRef); } if (LLVMContext.Pointer != IntPtr.Zero) { ContextDispose(LLVMContext); LLVMContext = default(LLVMContextRef); } Dispose(ref debugInformationManager); }
public static extern void AddIndVarSimplifyPass(LLVMPassManagerRef* PM);
public static extern void AddCFGSimplificationPass(LLVMPassManagerRef* PM);
public static extern void PassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef* PMB, LLVMPassManagerRef* PM, bool Internalize, bool RunInliner);
public static extern void AddCorrelatedValuePropagationPass(LLVMPassManagerRef* PM);
public static extern void AddTailCallEliminationPass(LLVMPassManagerRef* PM);
public static extern void AddSCCPPass(LLVMPassManagerRef* PM);
public static extern void AddLoopUnrollPass(LLVMPassManagerRef* PM);
private static extern void LLVMAddScopedNoAliasAAPass(LLVMPassManagerRef @PM);
private static extern void LLVMAddLowerExpectIntrinsicPass(LLVMPassManagerRef @PM);
private static extern void LLVMAddEarlyCSEMemSSAPass(LLVMPassManagerRef @PM);
private static extern void LLVMAddCorrelatedValuePropagationPass(LLVMPassManagerRef @PM);
private static extern void LLVMAddVerifierPass(LLVMPassManagerRef @PM);
private static extern void LLVMAddDemoteMemoryToRegisterPass(LLVMPassManagerRef @PM);
public static extern void AddJumpThreadingPass(LLVMPassManagerRef* PM);
public static extern void AddLoopIdiomPass(LLVMPassManagerRef* PM);
private static extern void LLVMAddBasicAliasAnalysisPass(LLVMPassManagerRef @PM);
public static extern void AddMemCpyOptPass(LLVMPassManagerRef* PM);
private static extern void LLVMAddSLPVectorizePass(LLVMPassManagerRef @PM);
public static extern void AddScalarReplAggregatesPassWithThreshold(LLVMPassManagerRef* PM, int Threshold);
private static extern void AddRewriteStatepointsForGCPass_Nix(LLVMPassManagerRef passManagerRef);
public static extern void AddDemoteMemoryToRegisterPass(LLVMPassManagerRef* PM);
private static extern void LLVMAddSimplifyLibCallsPass(LLVMPassManagerRef @PM);
private static extern void LLVMAddConstantPropagationPass(LLVMPassManagerRef @PM);
private static extern void LLVMAddScalarReplAggregatesPassWithThreshold(LLVMPassManagerRef @PM, int @Threshold);
public static extern void AddAggressiveDCEPass(LLVMPassManagerRef* PM);
private static void Main(string[] args) { // Make the module, which holds all the code. LLVMModuleRef module = LLVM.ModuleCreateWithName("my cool jit"); LLVMBuilderRef builder = LLVM.CreateBuilder(); LLVM.LinkInJIT(); LLVM.InitializeX86TargetInfo(); LLVM.InitializeX86Target(); LLVM.InitializeX86TargetMC(); LLVMExecutionEngineRef engine; IntPtr errorMessage; if (LLVM.CreateExecutionEngineForModule(out engine, module, out errorMessage).Value == 1) { Console.WriteLine(Marshal.PtrToStringAnsi(errorMessage)); LLVM.DisposeMessage(errorMessage); return; } // 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); // Provide basic AliasAnalysis support for GVN. LLVM.AddBasicAliasAnalysisPass(passManager); // Promote allocas to registers. LLVM.AddPromoteMemoryToRegisterPass(passManager); // 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); var codeGenlistener = new CodeGenParserListener(engine, passManager, new CodeGenVisitor(module, builder)); // Install standard binary operators. // 1 is lowest precedence. var binopPrecedence = new Dictionary <char, int>(); binopPrecedence['<'] = 10; binopPrecedence['+'] = 20; binopPrecedence['-'] = 20; binopPrecedence['*'] = 40; // highest. var scanner = new Lexer(Console.In, binopPrecedence); var parser = new Parser(scanner, codeGenlistener); // Prime the first token. Console.Write("ready> "); scanner.GetNextToken(); // Run the main "interpreter loop" now. MainLoop(scanner, parser); // Print out all of the generated code. LLVM.DumpModule(module); }
public static extern void AddDeadStoreEliminationPass(LLVMPassManagerRef* PM);
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(); }
public static extern void AddInstructionCombiningPass(LLVMPassManagerRef* PM);
private static extern void LLVMAddScalarReplAggregatesPassSSA(LLVMPassManagerRef @PM);
public static extern void AddLoopDeletionPass(LLVMPassManagerRef* PM);
internal PassManager(LLVMPassManagerRef handle) { Handle = handle; }
public static extern void AddLoopRotatePass(LLVMPassManagerRef* PM);
private static extern void LLVMAddSCCPPass(LLVMPassManagerRef @PM);
public static extern void AddLoopUnswitchPass(LLVMPassManagerRef* PM);
public void main(IList <CompilationUnit> trees) { if (trees.Count == 0) { return; } LLVMPassManagerRef passManager = LLVM.CreatePassManager(); LLVM.AddStripDeadPrototypesPass(passManager); LLVM.AddPromoteMemoryToRegisterPass(passManager); CompilerNative.AddRewriteStatepointsForGCPass(passManager); LLVM.AddEarlyCSEPass(passManager); LLVM.AddCFGSimplificationPass(passManager); LLVM.AddNewGVNPass(passManager); LLVM.AddLateCFGSimplificationPass(passManager); context = LLVM.GetGlobalContext(); module = LLVM.ModuleCreateWithNameInContext("TheProgram", context); builder = context.CreateBuilderInContext(); foreach ((Type type, ArrayType arrayType) in symtab.arrayTypes) { if (type.IsPrimitive) { declareLLVMStructType(arrayType); createArrayMetadataRecord(arrayType); } } declareBuiltins(); declareRuntimeHelpers(); variableAllocator = new VariableAllocator(builder, typeResolver); build(trees); if (options.DumpIR) { dumpIR(); } LLVMBool success = new LLVMBool(0); if (LLVM.VerifyModule(module, LLVMVerifierFailureAction.LLVMPrintMessageAction, out var error) != success) { Console.WriteLine($"Verfy Error: {error}"); return; } LLVM.RunPassManager(passManager, module); if (options.DumpIR) { dumpIR(); } if (options.Execute) { mcJit(); } else { makeObjectFile(); } LLVM.DisposePassManager(passManager); }
public static extern void AddReassociatePass(LLVMPassManagerRef* PM);
private static extern void LLVMAddReassociatePass(LLVMPassManagerRef @PM);
public static extern void AddScalarReplAggregatesPassSSA(LLVMPassManagerRef* PM);
internal PassManager(LLVMPassManagerRef passManagerRef) { this._instance = passManagerRef; }
public static extern void AddSimplifyLibCallsPass(LLVMPassManagerRef* PM);
public static extern void AddLowerExpectIntrinsicPass(LLVMPassManagerRef* PM);
public static extern void AddConstantPropagationPass(LLVMPassManagerRef* PM);
public static extern void AddBasicAliasAnalysisPass(LLVMPassManagerRef* PM);
public static extern void AddVerifierPass(LLVMPassManagerRef* PM);
public static extern void PassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef* PMB, LLVMPassManagerRef* PM);
public static extern void AddEarlyCSEPass(LLVMPassManagerRef* PM);
private static extern void LLVMAddTailCallEliminationPass(LLVMPassManagerRef @PM);
public static extern void AddTypeBasedAliasAnalysisPass(LLVMPassManagerRef* PM);
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); }
public static extern void AddBBVectorizePass(LLVMPassManagerRef* PM);
public static extern void PassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef* PMB, LLVMPassManagerRef* PM);