1 {-# LANGUAGE OverloadedStrings #-}
2 module Mate.BasicBlocks(
15 import qualified Data.Map as M
16 import qualified Data.ByteString.Lazy as B
26 -- Represents a CFG node
27 data BasicBlock = BasicBlock {
28 -- inputs :: [Variable],
29 -- outputs :: [Variable],
30 code :: [Instruction],
33 -- describes (leaving) edges of a CFG node
34 data BBEnd = Return | FallThrough BlockID | OneTarget BlockID | TwoTarget BlockID BlockID deriving Show
36 type MapBB = M.Map BlockID BasicBlock
38 -- for immediate representation for determine BBs
39 type Offset = (Int, Maybe BBEnd) -- (offset in bytecode, offset to jump target)
40 type OffIns = (Offset, Instruction)
43 printMapBB :: Maybe MapBB -> IO ()
44 printMapBB Nothing = putStrLn "No BasicBlock"
45 printMapBB (Just hmap) = do
47 let keys = fst $ unzip $ M.toList hmap
48 mapM_ (putStr . (flip (++)) ", " . show) keys
49 putStrLn "\n\nBasicBlocks:"
52 printMapBB' :: [BlockID] -> MapBB -> IO ()
53 printMapBB' [] _ = return ()
54 printMapBB' (i:is) hmap' = case M.lookup i hmap' of
56 putStrLn $ "Block " ++ (show i)
57 mapM_ putStrLn (map ((++) "\t" . show) $ code bb)
60 FallThrough t1 -> putStrLn $ "Sucessor: " ++ (show t1) ++ "\n"
61 OneTarget t1 -> putStrLn $ "Sucessor: " ++ (show t1) ++ "\n"
62 TwoTarget t1 t2 -> putStrLn $ "Sucessor: " ++ (show t1) ++ ", " ++ (show t2) ++ "\n"
64 Nothing -> error $ "BlockID " ++ show i ++ " not found."
66 testInstance :: String -> B.ByteString -> IO ()
67 testInstance cf method = do
68 cls <- parseClassFile cf
69 hmap <- parseMethod cls method
79 test_01, test_02, test_03, test_04 :: IO ()
80 test_01 = testInstance "./tests/Fib.class" "fib"
81 test_02 = testInstance "./tests/While.class" "f"
82 test_03 = testInstance "./tests/While.class" "g"
83 test_04 = testInstance "./tests/Fac.class" "fac"
86 parseMethod :: Class Resolved -> B.ByteString -> IO (Maybe MapBB)
87 parseMethod cls method = do
88 putStr "BB: analysing: "
89 let msig = methodSignature $ (classMethods cls) !! 1
90 B.putStrLn (method `B.append` ": " `B.append` (encode msig))
91 return $ testCFG $ lookupMethod method cls
94 testCFG :: Maybe (Method Resolved) -> Maybe MapBB
95 testCFG (Just m) = case attrByName m "Code" of
97 Just bytecode -> Just $ buildCFG $ codeInstructions $ decodeMethod bytecode
101 buildCFG :: [Instruction] -> MapBB
102 buildCFG xs = buildCFG' M.empty xs' xs'
105 xs' = markBackwardTargets $ calculateInstructionOffset xs
107 -- get already calculated jmp-targets and mark the predecessor of the
108 -- target-instruction as "FallThrough". we just care about backwards
109 -- jumps here (forward jumps are handled in buildCFG')
110 markBackwardTargets :: [OffIns] -> [OffIns]
111 markBackwardTargets [] = []
112 markBackwardTargets (x:[]) = [x]
113 markBackwardTargets insns@(x@((x_off,x_bbend),x_ins):y@((y_off,_),_):xs) =
114 (x_new):(markBackwardTargets (y:xs))
116 x_new = if isTarget then checkX y_off else x
117 checkX w16 = case x_bbend of
118 Just _ -> x -- already marked, don't change
119 Nothing -> ((x_off, Just $ FallThrough w16), x_ins) -- mark previous insn
121 -- look through all remaining insns in the stream if there is a jmp to `y'
122 isTarget = case find cmpOffset insns of Just _ -> True; Nothing -> False
123 cmpOffset ((_,(Just (OneTarget w16))),_) = w16 == y_off
124 cmpOffset ((_,(Just (TwoTarget _ w16))),_) = w16 == y_off
128 buildCFG' :: MapBB -> [OffIns] -> [OffIns] -> MapBB
129 buildCFG' hmap [] _ = hmap
130 buildCFG' hmap (((off, entry), _):xs) insns = buildCFG' (insertlist entryi hmap) xs insns
132 insertlist :: [BlockID] -> MapBB -> MapBB
133 insertlist [] hmap' = hmap'
134 insertlist (y:ys) hmap' = insertlist ys newhmap
136 newhmap = if M.member y hmap' then hmap' else M.insert y value hmap'
137 value = parseBasicBlock y insns
140 entryi = (if off == 0 then [0] else []) ++ -- also consider the entrypoint
142 Just (TwoTarget t1 t2) -> [t1, t2]
143 Just (OneTarget t) -> [t]
144 Just (FallThrough t) -> [t]
149 parseBasicBlock :: Int -> [OffIns] -> BasicBlock
150 parseBasicBlock i insns = BasicBlock insonly endblock
152 startlist = dropWhile (\((x,_),_) -> x < i) insns
153 (Just ((_,(Just endblock)),_), is) = takeWhilePlusOne validins startlist
154 insonly = snd $ unzip is
156 -- also take last (non-matched) element and return it
157 takeWhilePlusOne :: (a -> Bool) -> [a] -> (Maybe a,[a])
158 takeWhilePlusOne _ [] = (Nothing,[])
159 takeWhilePlusOne p (x:xs)
160 | p x = let (lastins, list) = takeWhilePlusOne p xs in (lastins, (x:list))
161 | otherwise = (Just x,[x])
163 validins :: ((Int, Maybe BBEnd), Instruction) -> Bool
164 validins ((_,x),_) = case x of Just _ -> False; Nothing -> True
167 calculateInstructionOffset :: [Instruction] -> [OffIns]
168 calculateInstructionOffset = cio' (0, Nothing)
170 newoffset :: Instruction -> Int -> Offset
171 newoffset x off = (off + (fromIntegral $ B.length $ encodeInstructions [x]), Nothing)
173 addW16Signed :: Int -> Word16 -> Int
174 addW16Signed i w16 = i + (fromIntegral s16)
175 where s16 = (fromIntegral w16) :: Int16
177 cio' :: Offset -> [Instruction] -> [OffIns]
179 -- TODO(bernhard): add more instruction with offset (IF_ACMP, JSR, ...)
180 cio' (off,_) (x:xs) = case x of
181 IF _ w16 -> twotargets w16
182 IF_ICMP _ w16 -> twotargets w16
183 GOTO w16 -> onetarget w16
186 _ -> ((off, Nothing), x):next
188 notarget = ((off, Just Return), x):next
189 onetarget w16 = ((off, Just $ OneTarget $ (off `addW16Signed` w16)), x):next
190 twotargets w16 = ((off, Just $ TwoTarget (off + 3) (off `addW16Signed` w16)), x):next
191 next = cio' (newoffset x off) xs