From: Luke Lau Date: Sun, 2 Jun 2019 18:33:35 +0000 (+0100) Subject: Find our JIT'ed function and run it X-Git-Url: http://git.lukelau.me/?p=kaleidoscope-hs.git;a=commitdiff_plain;h=bc95ec9770ea2b19dd773dd4cec05d61b4684e95 Find our JIT'ed function and run it Here is where the magic happens. We first mangle the symbol before passing it to findSymbolIn: The compilation then happens here. It will spit back a FFI pointer, which we then need to invoke ourselves. In order to do this we have to specify the Haskell type of the function that we're pointing to, which resides in C-land, hence the ccall attribute in our foreign declaration. Try it out! --- diff --git a/Main.hs b/Main.hs index bc7c307..468573d 100644 --- a/Main.hs +++ b/Main.hs @@ -9,6 +9,7 @@ import Control.Monad.IO.Class import Data.String import qualified Data.Map as Map import qualified Data.Text.Lazy.IO as Text +import Foreign.Ptr import LLVM.AST.AddrSpace import LLVM.AST.Constant import LLVM.AST.Float @@ -27,6 +28,8 @@ import System.IO import System.IO.Error import Text.Read (readMaybe) +foreign import ccall "dynamic" mkFun :: FunPtr (IO Double) -> IO Double + data JITEnv = JITEnv { jitEnvContext :: Context , jitEnvCompileLayer :: IRCompileLayer ObjectLinkingLayer @@ -83,8 +86,10 @@ repl = do jit :: JITEnv -> Module -> IO Double jit JITEnv{jitEnvCompileLayer=compLayer, jitEnvModuleKey=mdlKey} mdl = - withModule compLayer mdlKey mdl $ - return 0 + withModule compLayer mdlKey mdl $ do + mangled <- mangleSymbol compLayer "__anon_expr" + Right (JITSymbol fPtr _) <- findSymbolIn compLayer mdlKey mangled False + mkFun (castPtrToFunPtr (wordPtrToPtr fPtr)) type Binds = Map.Map String Operand