/// <summary> /// Prepares the given native module for code generation. /// This step can generate required meta information or attributes, for instance. /// </summary> /// <param name="unit">The target unit.</param> /// <param name="module">The final module for code generation.</param> /// <param name="entryPoint">The entry point.</param> /// <param name="generatedEntryPoint">The generated entry point.</param> internal abstract void PrepareModule( CompileUnit unit, LLVMModuleRef module, EntryPoint entryPoint, LLVMValueRef generatedEntryPoint);
public static extern int RunPassManager(LLVMPassManagerRef* PM, LLVMModuleRef* M);
public static extern LLVMContextRef* GetModuleContext(LLVMModuleRef* M);
public static extern void AddNamedMetadataOperand(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string name, LLVMValueRef* Val);
public static extern int WriteBitcodeToFD(LLVMModuleRef* M, int FD, int ShouldClose, int Unbuffered);
public static extern System.IntPtr GetTarget(LLVMModuleRef* M);
public CodeGenVisitor(LLVMModuleRef module, LLVMBuilderRef builder) { this.module = module; this.builder = builder; }
public static extern int VerifyModule(LLVMModuleRef* M, LLVMVerifierFailureAction Action, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder OutMessage);
public static void VerifyModule(LLVMModuleRef mod) { VerifyModule(mod, LLVMVerifierFailureAction.LLVMAbortProcessAction); }
public static void EmitModule(LLVMExecutionEngineRef ee, LLVMModuleRef mod, string filename) { EmitModule(ee, mod, LLVMCodeGenFileType.LLVMObjectFile, filename); }
public ClepsMemberGeneratorParser(ClassManager classManager, CompileStatus status, LLVMContextRef context, LLVMModuleRef module, LLVMBuilderRef builder, ClepsLLVMTypeConvertor clepsLLVMTypeConvertor) { ClassManager = classManager; Status = status; Context = context; Module = module; Builder = builder; ClepsLLVMTypeConvertorInst = clepsLLVMTypeConvertor; }
internal void Release() { DiBuilder.Dispose(); _module = new LLVMModuleRef(); _parent.DecrementModule(); }
public Module(LLVMModuleRef source) { Source = source; }
public static extern int CreateJITCompilerForModule(ref LLVMExecutionEngineRef * OutJIT, LLVMModuleRef* M, uint OptLevel, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder OutError);
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(); }
public static extern int RemoveModuleProvider(LLVMExecutionEngineRef* EE, LLVMModuleProviderRef* MP, ref LLVMModuleRef * OutMod, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder OutError);
public ClepsClassNamesGeneratorParser(ClassManager classManager, CompileStatus status, LLVMContextRef context, LLVMModuleRef module, LLVMBuilderRef builder, out Dictionary <string, LLVMTypeRef> classSkeletons) { ClassManager = classManager; Status = status; Context = context; Module = module; Builder = builder; classSkeletons = new Dictionary <string, LLVMTypeRef>(); ClassSkeletons = classSkeletons; }
public static extern int GetBitcodeModule(LLVMMemoryBufferRef* MemBuf, ref LLVMModuleRef * OutM, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder OutMessage);
public static LLVMValueRef Func(this LLVMModuleRef module, LLVMTypeRef ret, String name, params LLVMTypeRef[] args) { return(LLVM.AddFunction(module, name, LLVMUtils.FUNC_TYPE(ret, args))); }
public static extern void DisposeModule(LLVMModuleRef* M);
public ILImporter(LLVMBuilderRef builder, WebAssemblyCodegenCompilation compilation, LLVMModuleRef module, LLVMValueRef helperFunc, MethodDesc delegateCtor) { this._builder = builder; this._compilation = compilation; this.Module = module; this._currentFunclet = helperFunc; _locals = new LocalVariableDefinition[0]; if (delegateCtor == null) { _signature = new MethodSignature(MethodSignatureFlags.None, 0, GetWellKnownType(WellKnownType.Void), new TypeDesc[0]); } else { _signature = delegateCtor.Signature; _argSlots = new LLVMValueRef[_signature.Length]; int signatureIndex = 2; // past hidden param int thisOffset = 0; if (!_signature.IsStatic) { thisOffset = 1; } for (int i = 0; i < _signature.Length; i++) { if (CanStoreTypeOnStack(_signature[i])) { LLVMValueRef storageAddr; LLVMValueRef argValue = helperFunc.GetParam((uint)signatureIndex); // The caller will always pass the argument on the stack. If this function doesn't have // EH, we can put it in an alloca for efficiency and better debugging. Otherwise, // copy it to the shadow stack so funclets can find it int argOffset = i + thisOffset; string argName = $"arg{argOffset}_"; storageAddr = _builder.BuildAlloca(GetLLVMTypeForTypeDesc(_signature[i]), argName); _argSlots[i] = storageAddr; _builder.BuildStore(argValue, storageAddr); signatureIndex++; } } } _thisType = GetWellKnownType(WellKnownType.Void); _pointerSize = compilation.NodeFactory.Target.PointerSize; _exceptionRegions = new ExceptionRegion[0]; }
public static extern void DumpModule(LLVMModuleRef* M);
private static LLVMValueRef DeclareCxaEndCatch( LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule) { return(DeclareFromSignature(CxaEndCatchSignature, ModuleBuilder, LLVMModule)); }
public static extern uint GetNamedMetadataNumOperands(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string name);
/// <summary> /// Declares this intrinsic in the given module. /// </summary> /// <param name="ModuleBuilder">The module builder for the module to declare the intrinsic in.</param> /// <param name="LLVMModule">The module to declare the intrinsic in.</param> /// <returns>The intrinsic's declaration.</returns> public LLVMValueRef Declare(LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule) { return(declareIntrinsic(ModuleBuilder, LLVMModule)); }
public static extern LLVMValueRef* GetNamedFunction(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Name);
private static LLVMValueRef DeclareCxaAllocateException( LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule) { return(DeclareFromSignature(CxaAllocateExceptionSignature, ModuleBuilder, LLVMModule)); }
public static extern LLVMPassManagerRef* CreateFunctionPassManagerForModule(LLVMModuleRef* M);
private static LLVMValueRef DeclareCxaRethrow( LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule) { return(DeclareFromSignature(CxaRethrowSignature, ModuleBuilder, LLVMModule)); }
public static extern int CreateInterpreterForModule(ref LLVMExecutionEngineRef * OutInterp, LLVMModuleRef* M, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder OutError);
private void AddEntryPoint(ClassManager classManager, CompileStatus status, LLVMContextRef context, LLVMModuleRef module, LLVMBuilderRef builder) { LLVMTypeRef functionType = LLVM.FunctionType(LLVM.Int32TypeInContext(context), new LLVMTypeRef[] { }, false); LLVMValueRef functionValue = LLVM.AddFunction(module, "main", functionType); LLVMBasicBlockRef blockValue = LLVM.AppendBasicBlockInContext(context, functionValue, "entry"); LLVM.PositionBuilderAtEnd(builder, blockValue); LLVMValueRef intRet = LLVM.ConstInt(LLVM.Int32Type(), 0, false); if (classManager.MainFunctionFullNames.Count < 1) { status.AddError(new CompilerError("", 0, 0, "No main functions found in the program")); } else if (classManager.MainFunctionFullNames.Count > 1) { status.AddError(new CompilerError("", 0, 0, "Multiple main functions found in the program: " + String.Join(",", classManager.MainFunctionFullNames))); } else { LLVMValueRef functionToCall = LLVM.GetNamedFunction(module, classManager.MainFunctionFullNames.First()); LLVMValueRef intOrIntMappedTypeRet = LLVM.BuildCall(builder, functionToCall, new LLVMValueRef[0], "entryPointCall"); LLVMTypeRef returnType = LLVM.TypeOf(intOrIntMappedTypeRet); if (returnType.TypeKind == LLVMTypeKind.LLVMIntegerTypeKind && returnType.GetIntTypeWidth() == 32) { intRet = intOrIntMappedTypeRet; } else { LLVMValueRef intMappedTypeRetPtr = LLVM.BuildAlloca(builder, LLVM.TypeOf(intOrIntMappedTypeRet), "intMappedType"); LLVM.BuildStore(builder, intOrIntMappedTypeRet, intMappedTypeRetPtr); //Extract the first field to get the int value from the mapped type //See rawtypemap for more details LLVMValueRef fieldPtr = LLVM.BuildStructGEP(builder, intMappedTypeRetPtr, 0, "returnIntFieldPtr"); intRet = LLVM.BuildLoad(builder, fieldPtr, "returnValue"); } } LLVM.BuildRet(builder, intRet); }
public static extern void AddModule(LLVMExecutionEngineRef* EE, LLVMModuleRef* M);
public static extern LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M);
public static extern int TargetMachineEmitToFile(LLVMTargetMachineRef* T, LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Filename, LLVMCodeGenFileType codegen, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder ErrorMessage);
public StaticFieldLookup(LLVMModuleRef moduleRef, TypeLookup typeLookup) { this.moduleRef = moduleRef; this.typeLookup = typeLookup; }
public static extern int ParseBitcodeInContext(LLVMContextRef* ContextRef, LLVMMemoryBufferRef* MemBuf, ref LLVMModuleRef * OutModule, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder OutMessage);
public static LlvmModule Wrap(this LLVMModuleRef reference) { return(new LlvmModule(reference)); }
public static extern int WriteBitcodeToFile(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Path);
private BitcodeModule(LLVMModuleRef handle) { this.moduleHandle = handle; this.Context = ContextCache.GetContextFor(handle.Context); }
public static extern int WriteBitcodeToFileHandle(LLVMModuleRef* M, int Handle);
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 static extern System.IntPtr GetDataLayout(LLVMModuleRef* M);
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.LinkInMCJIT(); LLVM.InitializeX86TargetInfo(); LLVM.InitializeX86Target(); LLVM.InitializeX86TargetMC(); if (LLVM.CreateExecutionEngineForModule(out var engine, module, out var errorMessage).Value == 1) { Console.WriteLine(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.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); var codeGenlistener = new CodeGenParserListener(engine, passManager, new CodeGenVisitor(module, builder)); // Install standard binary operators. // 1 is lowest precedence. var binopPrecedence = new Dictionary <char, int> { ['<'] = 10, ['+'] = 20, ['-'] = 20, ['*'] = 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); LLVM.DisposeModule(module); LLVM.DisposePassManager(passManager); }
public static extern void SetTarget(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Triple);
public static LLVMPassManagerRef CreatePassManager(LLVMModuleRef module, OptFlags flags) { var pass = module.CreateFunctionPassManager(); if ((flags & OptFlags.Reassociate) != 0) { pass.AddReassociatePass(); } if ((flags & OptFlags.Vectorize) != 0) { pass.AddLoopVectorizePass(); } if ((flags & OptFlags.CombineInstructions) != 0) { pass.AddInstructionCombiningPass(); } if ((flags & OptFlags.RotateLoops) != 0) { pass.AddLoopRotatePass(); } if ((flags & OptFlags.UnrollLoops) != 0) { pass.AddLoopUnrollPass(); } if ((flags & OptFlags.UnswitchLoops) != 0) { pass.AddLoopUnswitchPass(); } if ((flags & OptFlags.CanonicalizeInductionVariables) != 0) { pass.AddIndVarSimplifyPass(); } if ((flags & OptFlags.DeleteUnusedLoops) != 0) { pass.AddLoopDeletionPass(); } if ((flags & OptFlags.GlobalValueNumbering) != 0) { pass.AddNewGVNPass(); } if ((flags & OptFlags.OptimizeMemCpy) != 0) { pass.AddMemCpyOptPass(); } if ((flags & OptFlags.SimplifyControlFlowGraph) != 0) { pass.AddCFGSimplificationPass(); } pass.InitializeFunctionPassManager(); return(pass); }
public static extern void SetModuleInlineAsm(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Asm);
public WebAssemblyObjectWriter(string objectFilePath, NodeFactory factory, WebAssemblyCodegenCompilation compilation) { _nodeFactory = factory; _objectFilePath = objectFilePath; Module = compilation.Module; }
public static extern LLVMTypeRef* GetTypeByName(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Name);
public static extern LLVMValueRef* GetLastGlobal(LLVMModuleRef* M);
public static extern void GetNamedMetadataOperands(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string name, System.IntPtr[] Dest);
public static extern LLVMValueRef* AddAlias(LLVMModuleRef* M, LLVMTypeRef* Ty, LLVMValueRef* Aliasee, [In][MarshalAs(UnmanagedType.LPStr)] string Name);
public static extern LLVMValueRef* AddFunction(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Name, LLVMTypeRef* FunctionTy);
public static extern LLVMModuleProviderRef* CreateModuleProviderForExistingModule(LLVMModuleRef* M);
public static extern LLVMValueRef* GetLastFunction(LLVMModuleRef* M);
public bool Compile(CompilerOptions pOptions, out LLVMModuleRef?pModule) { double totalTime = 0; var sw = new System.Diagnostics.Stopwatch(); sw.Start(); //Read source files pModule = null; string source = string.IsNullOrEmpty(pOptions.SourceFile) ? pOptions.Source : ReadSourceFile(pOptions.SourceFile); if (source == null) { return(false); } var lexer = new SmallerLexer(); var stream = lexer.StartTokenStream(source, pOptions.SourceFile); var parser = new SmallerParser(stream); //Create AST var tree = parser.Parse(); if (CompilerErrors.ErrorOccurred) { return(false); } totalTime += RecordPerfData(sw, "Parsed in: "); //Type inference, type checking, AST transformations var compilationModule = ModuleBuilder.Build(tree); if (compilationModule == null) { return(false); } totalTime += RecordPerfData(sw, "Type checked in: "); LLVMModuleRef module = LLVM.ModuleCreateWithName(tree.Name); LLVMPassManagerRef passManager = LLVM.CreateFunctionPassManagerForModule(module); if (pOptions.Optimizations) { LLVM.AddConstantPropagationPass(passManager); //Promote allocas to registers LLVM.AddPromoteMemoryToRegisterPass(passManager); //Do simple peephole optimizations LLVM.AddInstructionCombiningPass(passManager); //Re-associate expressions LLVM.AddReassociatePass(passManager); //Eliminate common subexpressions LLVM.AddGVNPass(passManager); //Simplify control flow graph LLVM.AddCFGSimplificationPass(passManager); } LLVM.InitializeFunctionPassManager(passManager); //Emitting LLVM bytecode using (var c = new EmittingContext(module, passManager, pOptions.Debug)) { compilationModule.Emit(c); if (LLVM.VerifyModule(module, LLVMVerifierFailureAction.LLVMPrintMessageAction, out string message).Value != 0) { LLVM.DumpModule(module); LLVM.DisposePassManager(passManager); pModule = null; return(false); } } pModule = module; LLVM.DisposePassManager(passManager); totalTime += RecordPerfData(sw, "Emitted bytecode in: "); Console.WriteLine("Total time: " + totalTime + "s"); return(true); }