on 4e6adeb help sign in
Idris-dev/src/IRTS/Compiler.hs
409 lines 17 kB history raw
1{-# LANGUAGE PatternGuards, TypeSynonymInstances, CPP #-}
3module IRTS.Compiler where
5import IRTS.Lang
6import IRTS.Defunctionalise
7import IRTS.Simplified
8import IRTS.CodegenCommon
9import IRTS.CodegenC
10import IRTS.CodegenJava
11import IRTS.DumpBC
12import IRTS.CodegenJavaScript
13#ifdef IDRIS_LLVM
14import IRTS.CodegenLLVM
15#else
16import Util.LLVMStubs
17#endif
18import IRTS.Inliner
20import Idris.AbsSyntax
21import Idris.UnusedArgs
22import Idris.Error
24import Idris.Core.TT
25import Idris.Core.Evaluate
26import Idris.Core.CaseTree
28import Control.Monad.State
29import Data.List
30import System.Process
31import System.IO
32import System.Directory
33import System.Environment
34import System.FilePath ((</>), addTrailingPathSeparator)
36import Paths_idris
38compile :: Codegen -> FilePath -> Term -> Idris ()
39compile codegen f tm
40 = do checkMVs
41 let tmnames = namesUsed (STerm tm)
42 usedIn <- mapM (allNames []) tmnames
43 let used = [UN "prim__subBigInt", UN "prim__addBigInt"] : usedIn
44 defsIn <- mkDecls tm (concat used)
45 findUnusedArgs (concat used)
46 maindef <- irMain tm
47 objs <- getObjectFiles codegen
48 libs <- getLibs codegen
49 flags <- getFlags codegen
50 hdrs <- getHdrs codegen
51 impdirs <- allImportDirs
52 let defs = defsIn ++ [(MN 0 "runMain", maindef)]
53 -- iputStrLn $ showSep "\n" (map show defs)
54 let (nexttag, tagged) = addTags 65536 (liftAll defs)
55 let ctxtIn = addAlist tagged emptyContext
56 iLOG "Defunctionalising"
57 let defuns_in = defunctionalise nexttag ctxtIn
58 logLvl 5 $ show defuns_in
59 iLOG "Inlining"
60 let defuns = inline defuns_in
61 logLvl 5 $ show defuns
62 iLOG "Resolving variables for CG"
63 -- iputStrLn $ showSep "\n" (map show (toAlist defuns))
64 let checked = checkDefs defuns (toAlist defuns)
65 outty <- outputTy
66 dumpCases <- getDumpCases
67 dumpDefun <- getDumpDefun
68 case dumpCases of
69 Nothing -> return ()
70 Just f -> runIO $ writeFile f (showCaseTrees defs)
71 case dumpDefun of
72 Nothing -> return ()
73 Just f -> runIO $ writeFile f (dumpDefuns defuns)
74 triple <- targetTriple
75 cpu <- targetCPU
76 optimize <- optLevel
77 iLOG "Building output"
78 case checked of
79 OK c -> runIO $ case codegen of
80 ViaC ->
81 codegenC c f outty hdrs
82 (concatMap mkObj objs)
83 (concatMap mkLib libs)
84 (concatMap mkFlag flags ++
85 concatMap incdir impdirs) NONE
86 ViaJava ->
87 codegenJava [] c f hdrs libs outty
88 ViaJavaScript ->
89 codegenJavaScript JavaScript c f outty
90 ViaNode ->
91 codegenJavaScript Node c f outty
92 ViaLLVM -> codegenLLVM c triple cpu optimize f outty
93 Bytecode -> dumpBC c f
94 Error e -> ierror e
95 where checkMVs = do i <- getIState
96 case map fst (idris_metavars i) \\ primDefs of
97 [] -> return ()
98 ms -> ifail $ "There are undefined metavariables: " ++ show ms
99 inDir d h = do let f = d </> h
100 ex <- doesFileExist f
101 if ex then return f else return h
102 mkObj f = f ++ " "
103 mkLib l = "-l" ++ l ++ " "
104 mkFlag l = l ++ " "
106 incdir i = "-I" ++ i ++ " "
109irMain :: TT Name -> Idris LDecl
110irMain tm = do i <- ir tm
111 return $ LFun [] (MN 0 "runMain") [] (LForce i)
113mkDecls :: Term -> [Name] -> Idris [(Name, LDecl)]
114mkDecls t used
115 = do i <- getIState
116 let ds = filter (\ (n, d) -> n `elem` used || isCon d) $ ctxtAlist (tt_ctxt i)
117 mapM traceUnused used
118 decls <- mapM build ds
119 return decls
121showCaseTrees :: [(Name, LDecl)] -> String
122showCaseTrees ds = showSep "\n\n" (map showCT ds)
123 where
124 showCT (n, LFun _ f args lexp)
125 = show n ++ " " ++ showSep " " (map show args) ++ " =\n\t "
126 ++ show lexp
127 showCT (n, LConstructor c t a) = "data " ++ show n ++ " " ++ show a
129isCon (TyDecl _ _) = True
130isCon _ = False
132class ToIR a where
133 ir :: a -> Idris LExp
135build :: (Name, Def) -> Idris (Name, LDecl)
136build (n, d)
137 = do i <- getIState
138 case lookup n (idris_scprims i) of
139 Just (ar, op) ->
140 let args = map (\x -> MN x "op") [0..] in
141 return (n, (LFun [] n (take ar args)
142 (LOp op (map (LV . Glob) (take ar args)))))
143 _ -> do def <- mkLDecl n d
144 logLvl 3 $ "Compiled " ++ show n ++ " =\n\t" ++ show def
145 return (n, def)
147getPrim :: IState -> Name -> [LExp] -> Maybe LExp
148getPrim i n args = case lookup n (idris_scprims i) of
149 Just (ar, op) ->
150 if (ar == length args)
151 then return (LOp op args)
152 else Nothing
153 _ -> Nothing
155declArgs args inl n (LLam xs x) = declArgs (args ++ xs) inl n x
156declArgs args inl n x = LFun (if inl then [Inline] else []) n args x
158mkLDecl n (Function tm _) = do e <- ir tm
159 return (declArgs [] True n e)
160mkLDecl n (CaseOp ci _ _ _ pats cd)
161 = let (args, sc) = cases_runtime cd in
162 do e <- ir (args, sc)
163 return (declArgs [] (case_inlinable ci) n e)
164mkLDecl n (TyDecl (DCon t a) _) = return $ LConstructor n t a
165mkLDecl n (TyDecl (TCon t a) _) = return $ LConstructor n (-1) a
166mkLDecl n _ = return (LFun [] n [] (LError ("Impossible declaration " ++ show n)))
168instance ToIR (TT Name) where
169 ir tm = ir' [] tm where
170 ir' env tm@(App f a)
171 | (P _ (UN "mkForeignPrim") _, args) <- unApply tm
172 = doForeign env args
173 | (P _ (UN "unsafePerformPrimIO") _, [_, arg]) <- unApply tm
174 = ir' env arg
175 -- TMP HACK - until we get inlining.
176 | (P _ (UN "replace") _, [_, _, _, _, _, arg]) <- unApply tm
177 = ir' env arg
178 | (P _ (UN "lazy") _, [_, arg]) <- unApply tm
179 = do arg' <- ir' env arg
180 return $ LLazyExp arg'
181 | (P _ (UN "assert_smaller") _, [_, _, _, arg]) <- unApply tm
182 = ir' env arg
183 | (P _ (UN "par") _, [_, arg]) <- unApply tm
184 = do arg' <- ir' env arg
185 return $ LOp LPar [LLazyExp arg']
186 | (P _ (UN "prim_fork") _, [arg]) <- unApply tm
187 = do arg' <- ir' env arg
188 return $ LOp LFork [LLazyExp arg']
189-- | (P _ (UN "prim__IO") _, [v]) <- unApply tm
190-- = do v' <- ir' env v
191-- return v'
192-- | (P _ (UN "prim_io_bind") _, [_,_,v,Bind n (Lam _) sc]) <- unApply tm
193-- = do v' <- ir' env v
194-- sc' <- ir' (n:env) sc
195-- return (LLet n (LForce v') sc')
196-- | (P _ (UN "prim_io_bind") _, [_,_,v,k]) <- unApply tm
197-- = do v' <- ir' env v
198-- k' <- ir' env k
199-- return (LApp False k' [LForce v'])
200 | (P _ (UN "malloc") _, [_,size,t]) <- unApply tm
201 = do size' <- ir' env size
202 t' <- ir' env t
203 return t' -- TODO $ malloc_ size' t'
204 | (P _ (UN "trace_malloc") _, [_,t]) <- unApply tm
205 = do t' <- ir' env t
206 return t' -- TODO
207-- | (P _ (NS (UN "S") ["Nat", "Prelude"]) _, [k]) <- unApply tm
208-- = do k' <- ir' env k
209-- return (LOp LBPlus [k', LConst (BI 1)])
210 | (P (DCon t a) n _, args) <- unApply tm
211 = irCon env t a n args
212 | (P (TCon t a) n _, args) <- unApply tm
213 = return LNothing
214 | (P _ n _, args) <- unApply tm
215 = do i <- getIState
216 args' <- mapM (ir' env) args
217 case getPrim i n args' of
218 Just tm -> return tm
219 _ -> do
220 let collapse
221 = case lookupCtxtExact n
222 (idris_optimisation i) of
223 [oi] -> collapsible oi
224 _ -> False
225 let unused
226 = case lookupCtxtExact n
227 (idris_callgraph i) of
228 [CGInfo _ _ _ _ unusedpos] ->
229 unusedpos
230 _ -> []
231 if collapse
232 then return LNothing
233 else return (LApp False (LV (Glob n))
234 (mkUnused unused 0 args'))
235 | (f, args) <- unApply tm
236 = do f' <- ir' env f
237 args' <- mapM (ir' env) args
238 return (LApp False f' args')
239 where mkUnused u i [] = []
240 mkUnused u i (x : xs) | i `elem` u = LNothing : mkUnused u (i + 1) xs
241 | otherwise = x : mkUnused u (i + 1) xs
242-- ir' env (P _ (NS (UN "Z") ["Nat", "Prelude"]) _)
243-- = return $ LConst (BI 0)
244 ir' env (P _ n _) = return $ LV (Glob n)
245 ir' env (V i) | i >= 0 && i < length env = return $ LV (Glob (env!!i))
246 | otherwise = ifail $ "IR fail " ++ show i ++ " " ++ show tm
247 ir' env (Bind n (Lam _) sc)
248 = do let n' = uniqueName n env
249 sc' <- ir' (n' : env) sc
250 return $ LLam [n'] sc'
251 ir' env (Bind n (Let _ v) sc)
252 = do sc' <- ir' (n : env) sc
253 v' <- ir' env v
254 return $ LLet n v' sc'
255 ir' env (Bind _ _ _) = return $ LNothing
256 ir' env (Proj t i) | i == -1
257 = do t' <- ir' env t
258 return $ LOp (LMinus (ATInt ITBig))
259 [t', LConst (BI 1)]
260 ir' env (Proj t i) = do t' <- ir' env t
261 return $ LProj t' i
262 ir' env (Constant c) = return $ LConst c
263 ir' env (TType _) = return $ LNothing
264 ir' env Erased = return $ LNothing
265 ir' env Impossible = return $ LNothing
266-- ir' env _ = return $ LError "Impossible"
268 irCon env t arity n args
269 | length args == arity = buildApp env (LV (Glob n)) args
270 | otherwise = let extra = satArgs (arity - length args) in
271 do sc' <- irCon env t arity n
272 (args ++ map (\n -> P Bound n undefined) extra)
273 return $ LLam extra sc'
275 satArgs n = map (\i -> MN i "sat") [1..n]
277 buildApp env e [] = return e
278 buildApp env e xs = do xs' <- mapM (ir' env) xs
279 return $ LApp False e xs'
281 doForeign :: [Name] -> [TT Name] -> Idris LExp
282 doForeign env (_ : fgn : args)
283 | (_, (Constant (Str fgnName) : fgnArgTys : ret : [])) <- unApply fgn
284 = let maybeTys = getFTypes fgnArgTys
285 rty = mkIty' ret in
286 case maybeTys of
287 Nothing -> ifail $ "Foreign type specification is not a constant list: " ++ show (fgn:args)
288 Just tys -> do
289 args' <- mapM (ir' env) (init args)
290 -- wrap it in a prim__IO
291 -- return $ con_ 0 @@ impossible @@
292 return $ -- LLazyExp $
293 LForeign LANG_C rty fgnName (zip tys args')
294 | otherwise = ifail "Badly formed foreign function call"
296getFTypes :: TT Name -> Maybe [FType]
297getFTypes tm = case unApply tm of
298 (nil, []) -> Just []
299 (cons, [ty, xs]) ->
300 fmap (mkIty' ty :) (getFTypes xs)
301 _ -> Nothing
303mkIty' (P _ (UN ty) _) = mkIty ty
304mkIty' (App (P _ (UN "FIntT") _) (P _ (UN intTy) _)) = mkIntIty intTy
305mkIty' (App (App (P _ (UN "FFunction") _) _) (App (P _ (UN "FAny") _) (App (P _ (UN "IO") _) _))) = FFunctionIO
306mkIty' (App (App (P _ (UN "FFunction") _) _) _) = FFunction
307mkIty' _ = FAny
309-- would be better if these FInt types were evaluated at compile time
310-- TODO: add %eval directive for such things
312mkIty "FFloat" = FArith ATFloat
313mkIty "FInt" = mkIntIty "ITNative"
314mkIty "FChar" = mkIntIty "ITChar"
315mkIty "FByte" = mkIntIty "IT8"
316mkIty "FShort" = mkIntIty "IT16"
317mkIty "FLong" = mkIntIty "IT64"
318mkIty "FBits8" = mkIntIty "IT8"
319mkIty "FBits16" = mkIntIty "IT16"
320mkIty "FBits32" = mkIntIty "IT32"
321mkIty "FBits64" = mkIntIty "IT64"
322mkIty "FString" = FString
323mkIty "FPtr" = FPtr
324mkIty "FUnit" = FUnit
325mkIty "FFunction" = FFunction
326mkIty "FFunctionIO" = FFunctionIO
327mkIty "FBits8x16" = FArith (ATInt (ITVec IT8 16))
328mkIty "FBits16x8" = FArith (ATInt (ITVec IT16 8))
329mkIty "FBits32x4" = FArith (ATInt (ITVec IT32 4))
330mkIty "FBits64x2" = FArith (ATInt (ITVec IT64 2))
331mkIty x = error $ "Unknown type " ++ x
333mkIntIty "ITNative" = FArith (ATInt ITNative)
334mkIntIty "ITChar" = FArith (ATInt ITChar)
335mkIntIty "IT8" = FArith (ATInt (ITFixed IT8))
336mkIntIty "IT16" = FArith (ATInt (ITFixed IT16))
337mkIntIty "IT32" = FArith (ATInt (ITFixed IT32))
338mkIntIty "IT64" = FArith (ATInt (ITFixed IT64))
340zname = NS (UN "Z") ["Nat","Prelude"]
341sname = NS (UN "S") ["Nat","Prelude"]
343instance ToIR ([Name], SC) where
344 ir (args, tree) = do logLvl 3 $ "Compiling " ++ show args ++ "\n" ++ show tree
345 tree' <- ir tree
346 return $ LLam args tree'
348instance ToIR SC where
349 ir t = ir' t where
351 ir' (STerm t) = ir t
352 ir' (UnmatchedCase str) = return $ LError str
353 ir' (ProjCase tm alts) = do tm' <- ir tm
354 alts' <- mapM (mkIRAlt tm') alts
355 return $ LCase tm' alts'
356 ir' (Case n alts) = do alts' <- mapM (mkIRAlt (LV (Glob n))) alts
357 return $ LCase (LV (Glob n)) alts'
358 ir' ImpossibleCase = return LNothing
360 -- special cases for Z and S
361 -- Needs rethink: projections make this fail
362-- mkIRAlt n (ConCase z _ [] rhs) | z == zname
363-- = mkIRAlt n (ConstCase (BI 0) rhs)
364-- mkIRAlt n (ConCase s _ [arg] rhs) | s == sname
365-- = do n' <- ir n
366-- rhs' <- ir rhs
367-- return $ LDefaultCase
368-- (LLet arg (LOp LBMinus [n', LConst (BI 1)])
369-- rhs')
370 mkIRAlt _ (ConCase n t args rhs)
371 = do rhs' <- ir rhs
372 return $ LConCase (-1) n args rhs'
373 mkIRAlt _ (ConstCase x rhs)
374 | matchable x
375 = do rhs' <- ir rhs
376 return $ LConstCase x rhs'
377 | matchableTy x
378 = do rhs' <- ir rhs
379 return $ LDefaultCase rhs'
380 mkIRAlt tm (SucCase n rhs)
381 = do rhs' <- ir rhs
382 return $ LDefaultCase (LLet n (LOp (LMinus (ATInt ITBig))
383 [tm,
384 LConst (BI 1)]) rhs')
385-- return $ LSucCase n rhs'
386 mkIRAlt _ (ConstCase c rhs)
387 = ifail $ "Can't match on (" ++ show c ++ ")"
388 mkIRAlt _ (DefaultCase rhs)
389 = do rhs' <- ir rhs
390 return $ LDefaultCase rhs'
392 matchable (I _) = True
393 matchable (BI _) = True
394 matchable (Ch _) = True
395 matchable (Str _) = True
396 matchable _ = False
398 matchableTy (AType (ATInt ITNative)) = True
399 matchableTy (AType (ATInt ITBig)) = True
400 matchableTy (AType (ATInt ITChar)) = True
401 matchableTy StrType = True
403 matchableTy (AType (ATInt (ITFixed IT8))) = True
404 matchableTy (AType (ATInt (ITFixed IT16))) = True
405 matchableTy (AType (ATInt (ITFixed IT32))) = True
406 matchableTy (AType (ATInt (ITFixed IT64))) = True
408 matchableTy _ = False