basicblock: using arrows
[mate.git] / Mate / BasicBlocks.hs
index d4cd2b18bb8cae87ec40ce09d41cc18ae59d5df6..e81282022ceb9ba2b7f423bb54ea7934f0d5017e 100644 (file)
@@ -1,25 +1,23 @@
-{-# LANGUAGE CPP #-}
 {-# LANGUAGE OverloadedStrings #-}
-#include "debug.h"
 module Mate.BasicBlocks(
   BlockID,
   BasicBlock,
   BBEnd,
   MapBB,
   Method,
-#ifdef DBG_BB
   printMapBB,
-#endif
   parseMethod,
   testCFG -- added by hs to perform benches from outside
   )where
 
-import Data.Binary
+import Data.Binary hiding (get)
 import Data.Int
-import Data.List
 import qualified Data.Map as M
 import qualified Data.ByteString.Lazy as B
 import Data.Maybe
+import Control.Monad.State
+import Control.Applicative
+import Control.Arrow
 
 import JVM.ClassFile
 import JVM.Converter
@@ -29,49 +27,43 @@ import Mate.Types
 import Mate.Debug
 import Mate.Utilities
 
-#ifdef DEBUG
-import Text.Printf
-#endif
+-- (offset in bytecode, offset to jump target, ins)
+type OffIns = (Int, Maybe BBEnd, Instruction)
 
--- for immediate representation to determine BBs
-type Offset = (Int, Maybe BBEnd) -- (offset in bytecode, offset to jump target)
-type OffIns = (Offset, Instruction)
+type Targets = [BlockID]
+type BBState = Targets
+type AnalyseState = State BBState [OffIns]
 
 
-#ifdef DBG_BB
 printMapBB :: MapBB -> IO ()
 printMapBB hmap = do
-  putStr "BlockIDs: "
+  printfBb "BlockIDs: "
   let keys = M.keys hmap
-  mapM_ (putStr . (flip (++)) ", " . show) keys
-  putStrLn "\n\nBasicBlocks:"
+  mapM_ (printfBb . flip (++) ", " . show) keys
+  printfBb "\n\nBasicBlocks:\n"
   printMapBB' keys hmap
     where
       printMapBB' :: [BlockID] -> MapBB -> IO ()
       printMapBB' [] _ = return ()
       printMapBB' (i:is) hmap' = case M.lookup i hmap' of
         Just bb -> do
-          putStrLn $ "Block " ++ (show i)
-          mapM_ putStrLn (map ((++) "\t" . show) $ code bb)
-          case successor bb of
-            Return -> putStrLn ""
-            FallThrough t1 -> putStrLn $ "Sucessor: " ++ (show t1) ++ "\n"
-            OneTarget t1 -> putStrLn $ "Sucessor: " ++ (show t1) ++ "\n"
-            TwoTarget t1 t2 -> putStrLn $ "Sucessor: " ++ (show t1) ++ ", " ++ (show t2) ++ "\n"
+          printfBb $ "Block " ++ show i ++ "\n"
+          mapM_ (printfBb . flip (++) "\n" . (++) "\t" . show) $ code bb
+          printfBb $ case successor bb of
+            Return -> ""
+            FallThrough t1 -> "Sucessor: " ++ show t1 ++ "\n"
+            OneTarget t1 -> "Sucessor: " ++ show t1 ++ "\n"
+            TwoTarget t1 t2 -> "Sucessor: " ++ show t1 ++ ", " ++ show t2 ++ "\n"
           printMapBB' is hmap
         Nothing -> error $ "BlockID " ++ show i ++ " not found."
-#endif
 
-#if 0
-#ifdef DBG_BB
+{-
 testInstance :: String -> B.ByteString -> MethodSignature -> IO ()
 testInstance cf method sig = do
   cls <- parseClassFile cf
   hmap <- parseMethod cls method sig
   printMapBB hmap
-#endif
 
-#ifdef DBG_BB
 test_main :: IO ()
 test_main = do
   test_01
@@ -84,8 +76,7 @@ test_01 = testInstance "./tests/Fib.class" "fib"
 test_02 = testInstance "./tests/While.class" "f"
 test_03 = testInstance "./tests/While.class" "g"
 test_04 = testInstance "./tests/Fac.class" "fac"
-#endif
-#endif
+-}
 
 
 parseMethod :: Class Direct -> B.ByteString -> MethodSignature -> IO RawMethod
@@ -100,28 +91,25 @@ parseMethod cls methodname sig = do
   let mapbb = testCFG decoded
   let locals = fromIntegral (codeMaxLocals decoded)
   let stacks = fromIntegral (codeStackSize decoded)
+  let codelen = fromIntegral (codeLength decoded)
   let methoddirect = methodInfoToMethod (MethodInfo methodname "" sig) cls
   let isStatic = methodIsStatic methoddirect
   let nametype = methodNameType methoddirect
   let argscount = methodGetArgsCount nametype + (if isStatic then 0 else 1)
 
-  let msig = methodSignature $ classMethods cls !! 1
-  printfBb "BB: analysing \"%s\"\n" $ toString (methodname `B.append` ": " `B.append` encode msig)
-#ifdef DBG_BB
-  case maybe_bb of
-    Just m -> printMapBB $ rawMapBB m
-    Nothing -> return ()
-#endif
+  let msig = methodSignature method
+  printfBb $ printf "BB: analysing \"%s\"\n" $ toString (methodname `B.append` ": " `B.append` encode msig)
+  printMapBB mapbb
   -- small example how to get information about
   -- exceptions of a method
   -- TODO: remove ;-)
   let (Just m) = lookupMethodSig methodname sig cls
   case attrByName m "Code" of
     Nothing ->
-      printfBb "exception: no handler for this method\n"
+      printfBb $ printf "exception: no handler for this method\n"
     Just exceptionstream ->
-      printfBb "exception: \"%s\"\n" (show $ codeExceptions $ decodeMethod exceptionstream)
-  return $ RawMethod mapbb locals stacks argscount
+      printfBb $ printf "exception: \"%s\"\n" (show $ codeExceptions $ decodeMethod exceptionstream)
+  return $ RawMethod mapbb locals stacks argscount codelen
 
 
 testCFG :: Code -> MapBB
@@ -131,32 +119,31 @@ buildCFG :: [Instruction] -> MapBB
 buildCFG xs = buildCFG' M.empty xs' xs'
   where
   xs' :: [OffIns]
-  xs' = markBackwardTargets $ calculateInstructionOffset xs
+  xs' = evalState (calculateInstructionOffset xs >>= markBackwardTargets) []
 
 -- get already calculated jmp-targets and mark the predecessor of the
 -- target-instruction as "FallThrough". we just care about backwards
 -- jumps here (forward jumps are handled in buildCFG')
-markBackwardTargets :: [OffIns] -> [OffIns]
-markBackwardTargets [] = []
-markBackwardTargets (x:[]) = [x]
-markBackwardTargets insns@(x@((x_off,x_bbend),x_ins):y@((y_off,_),_):xs) =
-  x_new:markBackwardTargets (y:xs)
-    where
-      x_new = if isTarget then checkX y_off else x
-      checkX w16 = case x_bbend of
+markBackwardTargets :: [OffIns] -> AnalyseState
+markBackwardTargets [] = return []
+markBackwardTargets (x:[]) = return [x]
+markBackwardTargets (x@(x_off,x_bbend,x_ins):y@(y_off,_,_):xs) = do
+  rest <- markBackwardTargets (y:xs)
+  targets <- get
+  let isTarget = y_off `elem` targets
+      x_new = case x_bbend of
         Just _ -> x -- already marked, don't change
-        Nothing -> ((x_off, Just $ FallThrough w16), x_ins) -- mark previous insn
+        Nothing -> if isTarget then checkX y_off else x
+      checkX w16 = case x_bbend of
+        Nothing -> (x_off, Just $ FallThrough w16, x_ins) -- mark previous insn
+        _ -> error "basicblock: something is wrong"
+  return $ x_new:rest
 
-      -- look through all remaining insns in the stream if there is a jmp to `y'
-      isTarget = case find cmpOffset insns of Just _ -> True; Nothing -> False
-      cmpOffset ((_,Just (OneTarget w16)),_) = w16 == y_off
-      cmpOffset ((_,Just (TwoTarget _ w16)),_) = w16 == y_off
-      cmpOffset _ = False
 
 
 buildCFG' :: MapBB -> [OffIns] -> [OffIns] -> MapBB
 buildCFG' hmap [] _ = hmap
-buildCFG' hmap (((off, entry), _):xs) insns = buildCFG' (insertlist entryi hmap) xs insns
+buildCFG' hmap ((off, entry, _):xs) insns = buildCFG' (insertlist entryi hmap) xs insns
   where
     insertlist :: [BlockID] -> MapBB -> MapBB
     insertlist [] hmap' = hmap'
@@ -178,35 +165,37 @@ buildCFG' hmap (((off, entry), _):xs) insns = buildCFG' (insertlist entryi hmap)
 parseBasicBlock :: Int -> [OffIns] -> BasicBlock
 parseBasicBlock i insns = BasicBlock insonly endblock
   where
-    startlist = dropWhile (\((x,_),_) -> x < i) insns
-    (Just ((_, Just endblock),_), is) = takeWhilePlusOne validins startlist
-    insonly = snd $ unzip is
+    (lastblock, is) = takeWhilePlusOne validins omitins insns
+    (_, _, insonly) = unzip3 is
+    (_, Just endblock, _) = fromJust lastblock
 
     -- also take last (non-matched) element and return it
-    takeWhilePlusOne :: (a -> Bool) -> [a] -> (Maybe a,[a])
-    takeWhilePlusOne _ [] = (Nothing,[])
-    takeWhilePlusOne p (x:xs)
-      | p x       =  let (lastins, list) = takeWhilePlusOne p xs in (lastins, x:list)
-      | otherwise =  (Just x,[x])
+    takeWhilePlusOne :: (a -> Bool) -> (a -> Bool) -> [a] -> (Maybe a, [a])
+    takeWhilePlusOne _ _ [] = (Nothing, [])
+    takeWhilePlusOne p omit (x:xs)
+      | omit x    = next
+      | p x       = second (x:) next
+      | otherwise = (Just x, [x])
+      where
+        next = takeWhilePlusOne p omit xs
 
-    validins :: ((Int, Maybe BBEnd), Instruction) -> Bool
-    validins ((_,x),_) = case x of Just _ -> False; Nothing -> True
+    validins :: OffIns -> Bool
+    validins (_, x, _) = isNothing x
 
+    omitins :: OffIns -> Bool
+    omitins (off, _, _) = off < i
 
-calculateInstructionOffset :: [Instruction] -> [OffIns]
-calculateInstructionOffset = cio' (0, Nothing)
-  where
-    newoffset :: Instruction -> Int -> Offset
-    newoffset x off = (off + fromIntegral (B.length $ encodeInstructions [x]), Nothing)
 
+calculateInstructionOffset :: [Instruction] -> AnalyseState
+calculateInstructionOffset = cio' (0, Nothing, NOP)
+  where
     addW16Signed :: Int -> Word16 -> Int
     addW16Signed i w16 = i + fromIntegral s16
       where s16 = fromIntegral w16 :: Int16
 
-    cio' :: Offset -> [Instruction] -> [OffIns]
-    cio' _ [] = []
-    -- TODO(bernhard): add more instruction with offset (IF_ACMP, JSR, ...)
-    cio' (off,_) (x:xs) = case x of
+    cio' :: OffIns -> [Instruction] -> AnalyseState
+    cio' _ [] = return $ []
+    cio' (off,_,_) (x:xs) = case x of
         IF _ w16 -> twotargets w16
         IF_ICMP _ w16 -> twotargets w16
         IF_ACMP _ w16 -> twotargets w16
@@ -216,9 +205,23 @@ calculateInstructionOffset = cio' (0, Nothing)
         IRETURN -> notarget
         ARETURN -> notarget
         RETURN -> notarget
-        _ -> ((off, Nothing), x):next
+        _ -> ((off, Nothing, x):) <$> next
       where
-        notarget = ((off, Just Return), x):next
-        onetarget w16 = ((off, Just $ OneTarget (off `addW16Signed` w16)), x):next
-        twotargets w16 = ((off, Just $ TwoTarget (off + 3) (off `addW16Signed` w16)), x):next
-        next = cio' (newoffset x off) xs
+        notarget = ((off, Just Return, x):) <$> next
+        onetarget w16 = do
+          let jump = off `addW16Signed` w16
+          modify (jump:)
+          ((off, Just $ OneTarget jump, x):) <$> next
+        twotargets w16 = do
+          let nojump = off + 3
+          modify (nojump:)
+          let jump = off `addW16Signed` w16
+          modify (jump:)
+          ((off, Just $ TwoTarget nojump jump, x):) <$> next
+        next = cio' newoffset xs
+        newoffset = (off + insnLength x, Nothing, NOP)
+
+-- TODO(bernhard): does GHC memomize results? i.e. does it calculate the size
+--                 of `NOP' only once?
+insnLength :: Num a => Instruction -> a
+insnLength = fromIntegral . B.length . encodeInstructions . (:[])