From: Luke Lau Date: Sun, 10 Mar 2019 01:56:37 +0000 (+0000) Subject: Add basic JIT X-Git-Url: https://git.lukelau.me/?p=kaleidoscope-hs-old.git;a=commitdiff_plain;h=4dc076eed8f88df110e2682bb24e208d19816790 Add basic JIT --- diff --git a/Main.hs b/Main.hs index 7a26601..37c6cbc 100644 --- a/Main.hs +++ b/Main.hs @@ -4,6 +4,11 @@ module Main where import qualified AST import qualified Data.Text.Lazy.IO as Text +import Foreign.Ptr +import LLVM.Context +import LLVM.CodeModel +import LLVM.ExecutionEngine +import LLVM.Module import LLVM.IRBuilder import LLVM.AST.Constant import LLVM.AST.Float @@ -11,14 +16,21 @@ import LLVM.AST.Operand import LLVM.AST.Type import LLVM.Pretty +foreign import ccall "dynamic" exprFun :: FunPtr (IO Float) -> IO Float + main :: IO () main = do ast <- read <$> getContents let mdl = buildModule "main" $ - function "expr" [] float $ \_ -> do - build ast - return () + function "expr" [] float $ \_ -> build ast >>= ret Text.putStrLn (ppllvm mdl) + withContext $ \ctx -> + withMCJIT ctx Nothing Nothing Nothing Nothing $ \mcjit -> + withModuleFromAST ctx mdl $ \mdl' -> + withModuleInEngine mcjit mdl' $ \emdl -> do + Just f <- getFunction emdl "expr" + let f' = castFunPtr f :: FunPtr (IO Float) + exprFun f' >>= print build :: AST.Expr -> IRBuilderT ModuleBuilder Operand build (AST.Num a) = pure $ ConstantOperand (Float (Single a))