Exemplo n.º 1
0
 /// <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);
Exemplo n.º 2
0
 public static extern int RunPassManager(LLVMPassManagerRef* PM, LLVMModuleRef* M);
Exemplo n.º 3
0
 public static extern LLVMContextRef* GetModuleContext(LLVMModuleRef* M);
Exemplo n.º 4
0
 public static extern void AddNamedMetadataOperand(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string name, LLVMValueRef* Val);
Exemplo n.º 5
0
 public static extern int WriteBitcodeToFD(LLVMModuleRef* M, int FD, int ShouldClose, int Unbuffered);
Exemplo n.º 6
0
 public static extern System.IntPtr GetTarget(LLVMModuleRef* M);
Exemplo n.º 7
0
 public CodeGenVisitor(LLVMModuleRef module, LLVMBuilderRef builder)
 {
     this.module  = module;
     this.builder = builder;
 }
Exemplo n.º 8
0
 public static extern int VerifyModule(LLVMModuleRef* M, LLVMVerifierFailureAction Action, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder OutMessage);
Exemplo n.º 9
0
 public static void VerifyModule(LLVMModuleRef mod)
 {
     VerifyModule(mod, LLVMVerifierFailureAction.LLVMAbortProcessAction);
 }
Exemplo n.º 10
0
 public static void EmitModule(LLVMExecutionEngineRef ee, LLVMModuleRef mod, string filename)
 {
     EmitModule(ee, mod, LLVMCodeGenFileType.LLVMObjectFile, filename);
 }
Exemplo n.º 11
0
 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;
 }
Exemplo n.º 12
0
 internal void Release()
 {
     DiBuilder.Dispose();
     _module = new LLVMModuleRef();
     _parent.DecrementModule();
 }
Exemplo n.º 13
0
 public Module(LLVMModuleRef source)
 {
     Source = source;
 }
Exemplo n.º 14
0
 public static extern int CreateJITCompilerForModule(ref LLVMExecutionEngineRef * OutJIT, LLVMModuleRef* M, uint OptLevel, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder OutError);
Exemplo n.º 15
0
        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();
        }
Exemplo n.º 16
0
 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;
 }
Exemplo n.º 18
0
 public static extern int GetBitcodeModule(LLVMMemoryBufferRef* MemBuf, ref LLVMModuleRef * OutM, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder OutMessage);
Exemplo n.º 19
0
 public static LLVMValueRef Func(this LLVMModuleRef module, LLVMTypeRef ret, String name,
                                 params LLVMTypeRef[] args)
 {
     return(LLVM.AddFunction(module, name, LLVMUtils.FUNC_TYPE(ret, args)));
 }
Exemplo n.º 20
0
 public static extern void DisposeModule(LLVMModuleRef* M);
Exemplo n.º 21
0
        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];
        }
Exemplo n.º 22
0
 public static extern void DumpModule(LLVMModuleRef* M);
Exemplo n.º 23
0
 private static LLVMValueRef DeclareCxaEndCatch(
     LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule)
 {
     return(DeclareFromSignature(CxaEndCatchSignature, ModuleBuilder, LLVMModule));
 }
Exemplo n.º 24
0
 public static extern uint GetNamedMetadataNumOperands(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string name);
Exemplo n.º 25
0
 /// <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));
 }
Exemplo n.º 26
0
 public static extern LLVMValueRef* GetNamedFunction(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Name);
Exemplo n.º 27
0
 private static LLVMValueRef DeclareCxaAllocateException(
     LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule)
 {
     return(DeclareFromSignature(CxaAllocateExceptionSignature, ModuleBuilder, LLVMModule));
 }
Exemplo n.º 28
0
 public static extern LLVMPassManagerRef* CreateFunctionPassManagerForModule(LLVMModuleRef* M);
Exemplo n.º 29
0
 private static LLVMValueRef DeclareCxaRethrow(
     LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule)
 {
     return(DeclareFromSignature(CxaRethrowSignature, ModuleBuilder, LLVMModule));
 }
Exemplo n.º 30
0
 public static extern int CreateInterpreterForModule(ref LLVMExecutionEngineRef * OutInterp, LLVMModuleRef* M, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder OutError);
Exemplo n.º 31
0
        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);
        }
Exemplo n.º 32
0
 public static extern void AddModule(LLVMExecutionEngineRef* EE, LLVMModuleRef* M);
Exemplo n.º 33
0
 public static extern LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M);
Exemplo n.º 34
0
 public static extern int TargetMachineEmitToFile(LLVMTargetMachineRef* T, LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Filename, LLVMCodeGenFileType codegen, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder ErrorMessage);
Exemplo n.º 35
0
 public StaticFieldLookup(LLVMModuleRef moduleRef, TypeLookup typeLookup)
 {
     this.moduleRef  = moduleRef;
     this.typeLookup = typeLookup;
 }
Exemplo n.º 36
0
 public static extern int ParseBitcodeInContext(LLVMContextRef* ContextRef, LLVMMemoryBufferRef* MemBuf, ref LLVMModuleRef * OutModule, [MarshalAs(UnmanagedType.LPStr)] ref StringBuilder OutMessage);
Exemplo n.º 37
0
 public static LlvmModule Wrap(this LLVMModuleRef reference)
 {
     return(new LlvmModule(reference));
 }
Exemplo n.º 38
0
 public static extern int WriteBitcodeToFile(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Path);
Exemplo n.º 39
0
 private BitcodeModule(LLVMModuleRef handle)
 {
     this.moduleHandle = handle;
     this.Context      = ContextCache.GetContextFor(handle.Context);
 }
Exemplo n.º 40
0
 public static extern int WriteBitcodeToFileHandle(LLVMModuleRef* M, int Handle);
Exemplo n.º 41
0
        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();
                }
            }
        }
Exemplo n.º 42
0
 public static extern System.IntPtr GetDataLayout(LLVMModuleRef* M);
Exemplo n.º 43
0
        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);
        }
Exemplo n.º 44
0
 public static extern void SetTarget(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Triple);
Exemplo n.º 45
0
        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);
        }
Exemplo n.º 46
0
 public static extern void SetModuleInlineAsm(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Asm);
Exemplo n.º 47
0
 public WebAssemblyObjectWriter(string objectFilePath, NodeFactory factory, WebAssemblyCodegenCompilation compilation)
 {
     _nodeFactory    = factory;
     _objectFilePath = objectFilePath;
     Module          = compilation.Module;
 }
Exemplo n.º 48
0
 public static extern LLVMTypeRef* GetTypeByName(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Name);
Exemplo n.º 49
0
 public static extern LLVMValueRef* GetLastGlobal(LLVMModuleRef* M);
Exemplo n.º 50
0
 public static extern void GetNamedMetadataOperands(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string name, System.IntPtr[] Dest);
Exemplo n.º 51
0
 public static extern LLVMValueRef* AddAlias(LLVMModuleRef* M, LLVMTypeRef* Ty, LLVMValueRef* Aliasee, [In][MarshalAs(UnmanagedType.LPStr)] string Name);
Exemplo n.º 52
0
 public static extern LLVMValueRef* AddFunction(LLVMModuleRef* M, [In][MarshalAs(UnmanagedType.LPStr)] string Name, LLVMTypeRef* FunctionTy);
Exemplo n.º 53
0
 public static extern LLVMModuleProviderRef* CreateModuleProviderForExistingModule(LLVMModuleRef* M);
Exemplo n.º 54
0
 public static extern LLVMValueRef* GetLastFunction(LLVMModuleRef* M);
Exemplo n.º 55
0
        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);
        }