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