59e30521b5b33937262059169ea653d5b12dfd43
[mate.git] / Mate / BasicBlocks.hs
1 {-# LANGUAGE OverloadedStrings #-}
2 module Mate.BasicBlocks(
3   BlockID,
4   BasicBlock (..),
5   BBEnd (..),
6   MapBB,
7   printMapBB,
8   parseMethod,
9   test_main,
10   testCFG -- added by hs to perform benches from outside
11   )where
12
13 import Data.Binary
14 import Data.Int
15 import Data.List
16 import qualified Data.Map as M
17 import qualified Data.ByteString.Lazy as B
18
19 import JVM.ClassFile
20 import JVM.Converter
21 import JVM.Assembler
22
23 import Mate.Utilities
24
25
26 type BlockID = Int
27 -- Represents a CFG node
28 data BasicBlock = BasicBlock {
29                      -- inputs  :: [Variable],
30                      -- outputs :: [Variable],
31                      code    :: [Instruction],
32                      successor :: BBEnd }
33
34 -- describes (leaving) edges of a CFG node
35 data BBEnd = Return | FallThrough BlockID | OneTarget BlockID | TwoTarget BlockID BlockID deriving Show
36
37 type MapBB = M.Map BlockID BasicBlock
38
39 -- for immediate representation for determine BBs
40 type Offset = (Int, Maybe BBEnd) -- (offset in bytecode, offset to jump target)
41 type OffIns = (Offset, Instruction)
42
43
44 printMapBB :: Maybe MapBB -> IO ()
45 printMapBB Nothing = putStrLn "No BasicBlock"
46 printMapBB (Just hmap) = do
47                      putStr "BlockIDs: "
48                      let keys = fst $ unzip $ M.toList hmap
49                      mapM_ (putStr . (flip (++)) ", " . show) keys
50                      putStrLn "\n\nBasicBlocks:"
51                      printMapBB' keys hmap
52   where
53   printMapBB' :: [BlockID] -> MapBB -> IO ()
54   printMapBB' [] _ = return ()
55   printMapBB' (i:is) hmap' = case M.lookup i hmap' of
56                   Just bb -> do
57                              putStrLn $ "Block " ++ (show i)
58                              mapM_ putStrLn (map ((++) "\t" . show) $ code bb)
59                              case successor bb of
60                                Return -> putStrLn ""
61                                FallThrough t1 -> putStrLn $ "Sucessor: " ++ (show t1) ++ "\n"
62                                OneTarget t1 -> putStrLn $ "Sucessor: " ++ (show t1) ++ "\n"
63                                TwoTarget t1 t2 -> putStrLn $ "Sucessor: " ++ (show t1) ++ ", " ++ (show t2) ++ "\n"
64                              printMapBB' is hmap
65                   Nothing -> error $ "BlockID " ++ show i ++ " not found."
66
67 testInstance :: String -> B.ByteString -> IO ()
68 testInstance cf method = do
69                       cls <- parseClassFile cf
70                       hmap <- parseMethod cls method
71                       printMapBB hmap
72
73 test_main :: IO ()
74 test_main = do
75   test_01
76   test_02
77   test_03
78   test_04
79
80 test_01, test_02, test_03, test_04 :: IO ()
81 test_01 = testInstance "./tests/Fib.class" "fib"
82 test_02 = testInstance "./tests/While.class" "f"
83 test_03 = testInstance "./tests/While.class" "g"
84 test_04 = testInstance "./tests/Fac.class" "fac"
85
86
87 parseMethod :: Class Resolved -> B.ByteString -> IO (Maybe MapBB)
88 parseMethod cls method = do
89                      putStr "BB: analysing: "
90                      let msig = methodSignature $ (classMethods cls) !! 1
91                      B.putStrLn (method `B.append` ": " `B.append` (encode msig))
92                      return $ testCFG $ lookupMethod method cls
93
94
95 testCFG :: Maybe (Method Resolved) -> Maybe MapBB
96 testCFG (Just m) = case attrByName m "Code" of
97        Nothing -> Nothing
98        Just bytecode -> Just $ buildCFG $ codeInstructions $ decodeMethod bytecode
99 testCFG _ = Nothing
100
101
102 buildCFG :: [Instruction] -> MapBB
103 buildCFG xs = buildCFG' M.empty xs' xs'
104   where
105   xs' :: [OffIns]
106   xs' = markBackwardTargets $ calculateInstructionOffset xs
107
108 -- get already calculated jmp-targets and mark the predecessor of the
109 -- target-instruction as "FallThrough". we just care about backwards
110 -- jumps here (forward jumps are handled in buildCFG')
111 markBackwardTargets :: [OffIns] -> [OffIns]
112 markBackwardTargets [] = []
113 markBackwardTargets (x:[]) = [x]
114 markBackwardTargets insns@(x@((x_off,x_bbend),x_ins):y@((y_off,_),_):xs) =
115   (x_new):(markBackwardTargets (y:xs))
116   where
117   x_new = if isTarget then checkX y_off else x
118   checkX w16 = case x_bbend of
119     Just _ -> x -- already marked, don't change
120     Nothing -> ((x_off, Just $ FallThrough w16), x_ins) -- mark previous insn
121
122   -- look through all remaining insns in the stream if there is a jmp to `y'
123   isTarget = case find cmpOffset insns of Just _ -> True; Nothing -> False
124   cmpOffset ((_,(Just (OneTarget w16))),_) = w16 == y_off
125   cmpOffset ((_,(Just (TwoTarget _ w16))),_) = w16 == y_off
126   cmpOffset _ = False
127
128
129 buildCFG' :: MapBB -> [OffIns] -> [OffIns] -> MapBB
130 buildCFG' hmap [] _ = hmap
131 buildCFG' hmap (((off, entry), _):xs) insns = buildCFG' (insertlist entryi hmap) xs insns
132   where
133   insertlist :: [BlockID] -> MapBB -> MapBB
134   insertlist [] hmap' = hmap'
135   insertlist (y:ys) hmap' = insertlist ys newhmap
136     where
137     newhmap = if M.member y hmap' then hmap' else M.insert y value hmap'
138     value = parseBasicBlock y insns
139
140   entryi :: [BlockID]
141   entryi = (if off == 0 then [0] else []) ++ -- also consider the entrypoint
142         case entry of
143         Just (TwoTarget t1 t2) -> [t1, t2]
144         Just (OneTarget t) -> [t]
145         Just (FallThrough t) -> [t]
146         Just (Return) -> []
147         Nothing -> []
148
149
150 parseBasicBlock :: Int -> [OffIns] -> BasicBlock
151 parseBasicBlock i insns = BasicBlock insonly endblock
152   where
153   startlist = dropWhile (\((x,_),_) -> x < i) insns
154   (Just ((_,(Just endblock)),_), is) = takeWhilePlusOne validins startlist
155   insonly = snd $ unzip is
156
157   -- also take last (non-matched) element and return it
158   takeWhilePlusOne :: (a -> Bool) -> [a] -> (Maybe a,[a])
159   takeWhilePlusOne _ [] = (Nothing,[])
160   takeWhilePlusOne p (x:xs)
161     | p x       =  let (lastins, list) = takeWhilePlusOne p xs in (lastins, (x:list))
162     | otherwise =  (Just x,[x])
163
164   validins :: ((Int, Maybe BBEnd), Instruction) -> Bool
165   validins ((_,x),_) = case x of Just _ -> False; Nothing -> True
166
167
168 calculateInstructionOffset :: [Instruction] -> [OffIns]
169 calculateInstructionOffset = cio' (0, Nothing)
170   where
171   newoffset :: Instruction -> Int -> Offset
172   newoffset x off = (off + (fromIntegral $ B.length $ encodeInstructions [x]), Nothing)
173
174   addW16Signed :: Int -> Word16 -> Int
175   addW16Signed i w16 = i + (fromIntegral s16)
176     where s16 = (fromIntegral w16) :: Int16
177
178   cio' :: Offset -> [Instruction] -> [OffIns]
179   cio' _ [] = []
180   -- TODO(bernhard): add more instruction with offset (IF_ACMP, JSR, ...)
181   cio' (off,_) (x:xs) = case x of
182       IF _ w16 -> twotargets w16
183       IF_ICMP _ w16 -> twotargets w16
184       GOTO w16 -> onetarget w16
185       IRETURN -> notarget
186       RETURN -> notarget
187       _ -> ((off, Nothing), x):next
188     where
189     notarget = ((off, Just Return), x):next
190     onetarget w16 = ((off, Just $ OneTarget $ (off `addW16Signed` w16)), x):next
191     twotargets w16 = ((off, Just $ TwoTarget (off + 3) (off `addW16Signed` w16)), x):next
192     next = cio' (newoffset x off) xs