1 {-# LANGUAGE OverloadedStrings #-}
2 module Mate.BasicBlocks(
10 testCFG -- added by hs to perform benches from outside
13 import Data.Binary hiding (get)
15 import qualified Data.Map as M
16 import qualified Data.ByteString.Lazy as B
18 import Control.Monad.State
19 import Control.Applicative
30 -- (offset in bytecode, offset to jump target, ins)
31 type OffIns = (Int, Maybe BBEnd, Instruction)
33 type Targets = [BlockID]
34 type BBState = Targets
35 type AnalyseState = State BBState [OffIns]
38 printMapBB :: MapBB -> IO ()
41 let keys = M.keys hmap
42 mapM_ (printfBb . flip (++) ", " . show) keys
43 printfBb "\n\nBasicBlocks:\n"
46 printMapBB' :: [BlockID] -> MapBB -> IO ()
47 printMapBB' [] _ = return ()
48 printMapBB' (i:is) hmap' = case M.lookup i hmap' of
50 printfBb $ "Block " ++ show i ++ "\n"
51 mapM_ (printfBb . flip (++) "\n" . (++) "\t" . show) $ code bb
52 printfBb $ case successor bb of
54 FallThrough t1 -> "Sucessor: " ++ show t1 ++ "\n"
55 OneTarget t1 -> "Sucessor: " ++ show t1 ++ "\n"
56 TwoTarget t1 t2 -> "Sucessor: " ++ show t1 ++ ", " ++ show t2 ++ "\n"
58 Nothing -> error $ "BlockID " ++ show i ++ " not found."
61 testInstance :: String -> B.ByteString -> MethodSignature -> IO ()
62 testInstance cf method sig = do
63 cls <- parseClassFile cf
64 hmap <- parseMethod cls method sig
74 test_01, test_02, test_03, test_04 :: IO ()
75 test_01 = testInstance "./tests/Fib.class" "fib"
76 test_02 = testInstance "./tests/While.class" "f"
77 test_03 = testInstance "./tests/While.class" "g"
78 test_04 = testInstance "./tests/Fac.class" "fac"
82 parseMethod :: Class Direct -> B.ByteString -> MethodSignature -> IO RawMethod
83 parseMethod cls methodname sig = do
84 let method = fromMaybe
85 (error $ "method " ++ (show . toString) methodname ++ " not found")
86 (lookupMethodSig methodname sig cls)
87 let codeseg = fromMaybe
88 (error $ "codeseg " ++ (show . toString) methodname ++ " not found")
89 (attrByName method "Code")
90 let decoded = decodeMethod codeseg
91 let mapbb = testCFG decoded
92 let locals = fromIntegral (codeMaxLocals decoded)
93 let stacks = fromIntegral (codeStackSize decoded)
94 let codelen = fromIntegral (codeLength decoded)
95 let methoddirect = methodInfoToMethod (MethodInfo methodname "" sig) cls
96 let isStatic = methodIsStatic methoddirect
97 let nametype = methodNameType methoddirect
98 let argscount = methodGetArgsCount nametype + (if isStatic then 0 else 1)
100 let msig = methodSignature method
101 printfBb $ printf "BB: analysing \"%s\"\n" $ toString (methodname `B.append` ": " `B.append` encode msig)
103 -- small example how to get information about
104 -- exceptions of a method
106 let (Just m) = lookupMethodSig methodname sig cls
107 case attrByName m "Code" of
109 printfBb $ printf "exception: no handler for this method\n"
110 Just exceptionstream ->
111 printfBb $ printf "exception: \"%s\"\n" (show $ codeExceptions $ decodeMethod exceptionstream)
112 return $ RawMethod mapbb locals stacks argscount codelen
115 testCFG :: Code -> MapBB
116 testCFG = buildCFG . codeInstructions
118 buildCFG :: [Instruction] -> MapBB
119 buildCFG xs = buildCFG' M.empty xs' xs'
122 xs' = evalState (calculateInstructionOffset xs >>= markBackwardTargets) []
124 -- get already calculated jmp-targets and mark the predecessor of the
125 -- target-instruction as "FallThrough". we just care about backwards
126 -- jumps here (forward jumps are handled in buildCFG')
127 markBackwardTargets :: [OffIns] -> AnalyseState
128 markBackwardTargets [] = return []
129 markBackwardTargets (x:[]) = return [x]
130 markBackwardTargets (x@(x_off,x_bbend,x_ins):y@(y_off,_,_):xs) = do
131 rest <- markBackwardTargets (y:xs)
133 let isTarget = y_off `elem` targets
134 x_new = case x_bbend of
135 Just _ -> x -- already marked, don't change
136 Nothing -> if isTarget then checkX y_off else x
137 checkX w16 = case x_bbend of
138 Nothing -> (x_off, Just $ FallThrough w16, x_ins) -- mark previous insn
139 _ -> error "basicblock: something is wrong"
144 buildCFG' :: MapBB -> [OffIns] -> [OffIns] -> MapBB
145 buildCFG' hmap [] _ = hmap
146 buildCFG' hmap ((off, entry, _):xs) insns = buildCFG' (insertlist entryi hmap) xs insns
148 insertlist :: [BlockID] -> MapBB -> MapBB
149 insertlist [] hmap' = hmap'
150 insertlist (y:ys) hmap' = insertlist ys newhmap
152 newhmap = if M.member y hmap' then hmap' else M.insert y value hmap'
153 value = parseBasicBlock y insns
155 entryi = if off == 0 then 0:ys else ys -- also consider the entrypoint
158 Just (TwoTarget t1 t2) -> [t1, t2]
159 Just (OneTarget t) -> [t]
160 Just (FallThrough t) -> [t]
165 parseBasicBlock :: Int -> [OffIns] -> BasicBlock
166 parseBasicBlock i insns = BasicBlock insonly endblock
168 (lastblock, is) = takeWhilePlusOne validins omitins insns
169 (_, _, insonly) = unzip3 is
170 (_, Just endblock, _) = fromJust lastblock
172 -- also take last (non-matched) element and return it
173 takeWhilePlusOne :: (a -> Bool) -> (a -> Bool) -> [a] -> (Maybe a, [a])
174 takeWhilePlusOne _ _ [] = (Nothing, [])
175 takeWhilePlusOne p omit (x:xs)
177 | p x = second (x:) next
178 | otherwise = (Just x, [x])
180 next = takeWhilePlusOne p omit xs
182 validins :: OffIns -> Bool
183 validins (_, x, _) = isNothing x
185 omitins :: OffIns -> Bool
186 omitins (off, _, _) = off < i
189 calculateInstructionOffset :: [Instruction] -> AnalyseState
190 calculateInstructionOffset = cio' (0, Nothing, NOP)
192 addW16Signed :: Int -> Word16 -> Int
193 addW16Signed i w16 = i + fromIntegral s16
194 where s16 = fromIntegral w16 :: Int16
196 cio' :: OffIns -> [Instruction] -> AnalyseState
197 cio' _ [] = return $ []
198 cio' (off,_,_) (x:xs) = case x of
199 IF _ w16 -> twotargets w16
200 IF_ICMP _ w16 -> twotargets w16
201 IF_ACMP _ w16 -> twotargets w16
202 IFNONNULL w16 -> twotargets w16
203 IFNULL w16 -> twotargets w16
204 GOTO w16 -> onetarget w16
208 _ -> ((off, Nothing, x):) <$> next
210 notarget = ((off, Just Return, x):) <$> next
212 let jump = off `addW16Signed` w16
214 ((off, Just $ OneTarget jump, x):) <$> next
218 let jump = off `addW16Signed` w16
220 ((off, Just $ TwoTarget nojump jump, x):) <$> next
221 next = cio' newoffset xs
222 newoffset = (off + insnLength x, Nothing, NOP)
224 -- TODO(bernhard): does GHC memomize results? i.e. does it calculate the size
225 -- of `NOP' only once?
226 insnLength :: Num a => Instruction -> a
227 insnLength = fromIntegral . B.length . encodeInstructions . (:[])