debug: get rid of #ifdef guards
[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 #ifdef DBG_BB
10   printMapBB,
11   test_main,
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.Utilities
28 import Mate.Types
29 import Mate.Debug
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 :: Maybe MapBB -> IO ()
42 printMapBB Nothing = putStrLn "No BasicBlock"
43 printMapBB (Just hmap) = do
44                      putStr "BlockIDs: "
45                      let keys = fst $ unzip $ M.toList hmap
46                      mapM_ (putStr . (flip (++)) ", " . show) keys
47                      putStrLn "\n\nBasicBlocks:"
48                      printMapBB' keys hmap
49   where
50   printMapBB' :: [BlockID] -> MapBB -> IO ()
51   printMapBB' [] _ = return ()
52   printMapBB' (i:is) hmap' = case M.lookup i hmap' of
53                   Just bb -> do
54                              putStrLn $ "Block " ++ (show i)
55                              mapM_ putStrLn (map ((++) "\t" . show) $ code bb)
56                              case successor bb of
57                                Return -> putStrLn ""
58                                FallThrough t1 -> putStrLn $ "Sucessor: " ++ (show t1) ++ "\n"
59                                OneTarget t1 -> putStrLn $ "Sucessor: " ++ (show t1) ++ "\n"
60                                TwoTarget t1 t2 -> putStrLn $ "Sucessor: " ++ (show t1) ++ ", " ++ (show t2) ++ "\n"
61                              printMapBB' is hmap
62                   Nothing -> error $ "BlockID " ++ show i ++ " not found."
63 #endif
64
65 #ifdef DBG_BB
66 testInstance :: String -> B.ByteString -> IO ()
67 testInstance cf method = do
68                       cls <- parseClassFile cf
69                       hmap <- parseMethod cls method
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
88
89 parseMethod :: Class Resolved -> B.ByteString -> IO (Maybe MapBB)
90 parseMethod cls method = do
91                      let maybe_bb = testCFG $ lookupMethod method cls
92                      let msig = methodSignature $ (classMethods cls) !! 1
93                      printf_bb "BB: analysing \"%s\"\n" $ toString (method `B.append` ": " `B.append` (encode msig))
94 #ifdef DBG_BB
95                      printMapBB maybe_bb
96 #endif
97                      -- small example how to get information about
98                      -- exceptions of a method
99                      -- TODO: remove ;-)
100                      let (Just m) = lookupMethod method cls
101                      case attrByName m "Code" of
102                       Nothing -> printf_bb "exception: no handler for this method\n"
103                       Just exceptionstream -> printf_bb "exception: \"%s\"\n" (show $ codeExceptions $ decodeMethod exceptionstream)
104                      return maybe_bb
105
106
107 testCFG :: Maybe (Method Resolved) -> Maybe MapBB
108 testCFG (Just m) = case attrByName m "Code" of
109        Nothing -> Nothing
110        Just bytecode -> Just $ buildCFG $ codeInstructions $ decodeMethod bytecode
111 testCFG _ = Nothing
112
113
114 buildCFG :: [Instruction] -> MapBB
115 buildCFG xs = buildCFG' M.empty xs' xs'
116   where
117   xs' :: [OffIns]
118   xs' = markBackwardTargets $ calculateInstructionOffset xs
119
120 -- get already calculated jmp-targets and mark the predecessor of the
121 -- target-instruction as "FallThrough". we just care about backwards
122 -- jumps here (forward jumps are handled in buildCFG')
123 markBackwardTargets :: [OffIns] -> [OffIns]
124 markBackwardTargets [] = []
125 markBackwardTargets (x:[]) = [x]
126 markBackwardTargets insns@(x@((x_off,x_bbend),x_ins):y@((y_off,_),_):xs) =
127   (x_new):(markBackwardTargets (y:xs))
128   where
129   x_new = if isTarget then checkX y_off else x
130   checkX w16 = case x_bbend of
131     Just _ -> x -- already marked, don't change
132     Nothing -> ((x_off, Just $ FallThrough w16), x_ins) -- mark previous insn
133
134   -- look through all remaining insns in the stream if there is a jmp to `y'
135   isTarget = case find cmpOffset insns of Just _ -> True; Nothing -> False
136   cmpOffset ((_,(Just (OneTarget w16))),_) = w16 == y_off
137   cmpOffset ((_,(Just (TwoTarget _ w16))),_) = w16 == y_off
138   cmpOffset _ = False
139
140
141 buildCFG' :: MapBB -> [OffIns] -> [OffIns] -> MapBB
142 buildCFG' hmap [] _ = hmap
143 buildCFG' hmap (((off, entry), _):xs) insns = buildCFG' (insertlist entryi hmap) xs insns
144   where
145   insertlist :: [BlockID] -> MapBB -> MapBB
146   insertlist [] hmap' = hmap'
147   insertlist (y:ys) hmap' = insertlist ys newhmap
148     where
149     newhmap = if M.member y hmap' then hmap' else M.insert y value hmap'
150     value = parseBasicBlock y insns
151
152   entryi :: [BlockID]
153   entryi = (if off == 0 then [0] else []) ++ -- also consider the entrypoint
154         case entry of
155         Just (TwoTarget t1 t2) -> [t1, t2]
156         Just (OneTarget t) -> [t]
157         Just (FallThrough t) -> [t]
158         Just (Return) -> []
159         Nothing -> []
160
161
162 parseBasicBlock :: Int -> [OffIns] -> BasicBlock
163 parseBasicBlock i insns = BasicBlock insonly endblock
164   where
165   startlist = dropWhile (\((x,_),_) -> x < i) insns
166   (Just ((_,(Just endblock)),_), is) = takeWhilePlusOne validins startlist
167   insonly = snd $ unzip is
168
169   -- also take last (non-matched) element and return it
170   takeWhilePlusOne :: (a -> Bool) -> [a] -> (Maybe a,[a])
171   takeWhilePlusOne _ [] = (Nothing,[])
172   takeWhilePlusOne p (x:xs)
173     | p x       =  let (lastins, list) = takeWhilePlusOne p xs in (lastins, (x:list))
174     | otherwise =  (Just x,[x])
175
176   validins :: ((Int, Maybe BBEnd), Instruction) -> Bool
177   validins ((_,x),_) = case x of Just _ -> False; Nothing -> True
178
179
180 calculateInstructionOffset :: [Instruction] -> [OffIns]
181 calculateInstructionOffset = cio' (0, Nothing)
182   where
183   newoffset :: Instruction -> Int -> Offset
184   newoffset x off = (off + (fromIntegral $ B.length $ encodeInstructions [x]), Nothing)
185
186   addW16Signed :: Int -> Word16 -> Int
187   addW16Signed i w16 = i + (fromIntegral s16)
188     where s16 = (fromIntegral w16) :: Int16
189
190   cio' :: Offset -> [Instruction] -> [OffIns]
191   cio' _ [] = []
192   -- TODO(bernhard): add more instruction with offset (IF_ACMP, JSR, ...)
193   cio' (off,_) (x:xs) = case x of
194       IF _ w16 -> twotargets w16
195       IF_ICMP _ w16 -> twotargets w16
196       IF_ACMP _ w16 -> twotargets w16
197       GOTO w16 -> onetarget w16
198       IRETURN -> notarget
199       ARETURN -> notarget
200       RETURN -> notarget
201       _ -> ((off, Nothing), x):next
202     where
203     notarget = ((off, Just Return), x):next
204     onetarget w16 = ((off, Just $ OneTarget $ (off `addW16Signed` w16)), x):next
205     twotargets w16 = ((off, Just $ TwoTarget (off + 3) (off `addW16Signed` w16)), x):next
206     next = cio' (newoffset x off) xs