codegen: handle exceptions of a method
[mate.git] / Mate / BasicBlocks.hs
index 7fd2e4830eca4c7699fafde8030da559f11b4fb5..2f96a40fe66ee6ce5b86b644141b3e3cf269b964 100644 (file)
@@ -13,6 +13,7 @@ module Mate.BasicBlocks(
 import Data.Binary hiding (get)
 import Data.Int
 import qualified Data.Map as M
+import qualified Data.Set as S
 import qualified Data.ByteString.Lazy as B
 import Data.Maybe
 import Control.Monad.State
@@ -30,18 +31,15 @@ import Mate.Utilities
 -- (offset in bytecode, offset to jump target, ins)
 type OffIns = (Int, Maybe BBEnd, Instruction)
 
-type Targets = [BlockID]
-type BBState = Targets
+type Target = BlockID
+type BBState = S.Set Target
 type AnalyseState = State BBState [OffIns]
 
 
-noException :: B.ByteString
-noException = B.empty
-
 emptyBasicBlock :: BasicBlock
 emptyBasicBlock = BasicBlock
                     { code = []
-                    , exception = noException
+                    , bblength = 0
                     , successor = Return }
 
 printMapBB :: MapBB -> IO ()
@@ -56,7 +54,7 @@ printMapBB hmap = do
       printMapBB' [] _ = return ()
       printMapBB' (i:is) hmap' = case M.lookup i hmap' of
         Just bb -> do
-          printfBb $ "Block " ++ show i ++ "\n"
+          printfBb $ "Block " ++ show i ++ ". len: " ++ (show $ bblength bb) ++ "\n"
           mapM_ (printfBb . flip (++) "\n" . (++) "\t" . show) $ code bb
           printfBb $ case successor bb of
             Return -> ""
@@ -106,58 +104,52 @@ parseMethod cls methodname sig = do
   let nametype = methodNameType methoddirect
   let argscount = methodGetArgsCount nametype + (if isStatic then 0 else 1)
 
+  let exceptionMap :: ExceptionMap
+      exceptionMap = foldl f M.empty $ codeExceptions decoded
+        where
+          f emap ce =
+            if M.member key emap
+              then M.adjust (value:) key emap
+              else M.insert key [value] emap
+              where
+                key = (&&&) eStartPC eEndPC ce
+                value = (&&&) g eHandlerPC ce
+                  where
+                    g ce' = case eCatchType ce' of
+                        0 -> B.empty
+                        x -> buildClassID cls x
+
   let msig = methodSignature method
   printfBb $ printf "BB: analysing \"%s\"\n" $ toString (methodname `B.append` ": " `B.append` encode msig)
   printMapBB mapbb
-  -- small example how to get information about
-  -- exceptions of a method
-  -- TODO: remove ;-)
-  let (Just m) = lookupMethodSig methodname sig cls
-  case attrByName m "Code" of
-    Nothing ->
-      printfBb $ printf "exception: no handler for this method\n"
-    Just exceptionstream ->
-      printfBb $ printf "exception: \"%s\"\n" (show $ codeExceptions $ decodeMethod exceptionstream)
-  return $ RawMethod mapbb locals stacks argscount codelen
+  return $ RawMethod mapbb exceptionMap locals stacks argscount codelen
 
 
 testCFG :: Code -> MapBB
-testCFG = buildCFG . codeInstructions
-
-buildCFG :: [Instruction] -> MapBB
-buildCFG xs = buildCFG' M.empty xs' xs'
+testCFG c = buildCFG (codeInstructions c) (codeExceptions c)
   where
-  xs' :: [OffIns]
-  xs' = evalState (calculateInstructionOffset xs) []
-
-
-buildCFG' :: MapBB -> [OffIns] -> [OffIns] -> MapBB
-buildCFG' hmap [] _ = hmap
-buildCFG' hmap ((off, entry, _):xs) insns = buildCFG' (insertlist entryi hmap) xs insns
-  where
-    insertlist :: [BlockID] -> MapBB -> MapBB
-    insertlist [] hmap' = hmap'
-    insertlist (y:ys) hmap' = insertlist ys newhmap
-      where
-        newhmap = if M.member y hmap' then hmap' else M.insert y value hmap'
-        value = parseBasicBlock y insns
-    entryi :: [BlockID]
-    entryi = if off == 0 then 0:ys else ys -- also consider the entrypoint
+    buildCFG :: [Instruction] -> [CodeException] -> MapBB
+    buildCFG xs excps = execState (mapM buildCFG' $ alltargets ++ handlerEntries) M.empty
       where
-        ys = case entry of
-          Just (TwoTarget t1 t2) -> [t1, t2]
-          Just (OneTarget t) -> [t]
-          Just (FallThrough t) -> [t]
-          Just Return -> []
-          Nothing -> []
+      (offins, targets) = runState (calculateInstructionOffset tryBlocks xs) S.empty
+      alltargets = S.toList $ S.insert 0 targets
+      tryBlocks = map (fromIntegral . eStartPC) excps
+      handlerEntries = map (fromIntegral . eHandlerPC) excps
 
+      buildCFG' :: Int -> State MapBB ()
+      buildCFG' off = do
+        let value = parseBasicBlock off offins
+        modify (M.insert off value)
 
 parseBasicBlock :: Int -> [OffIns] -> BasicBlock
-parseBasicBlock i insns = emptyBasicBlock { code = insonly, successor = endblock }
+parseBasicBlock i insns = emptyBasicBlock
+          { code = zip offsets insonly
+          , bblength = lastoff - i + (insnLength lastins)
+          , successor = endblock }
   where
     (lastblock, is) = takeWhilePlusOne validins omitins insns
-    (_, _, insonly) = unzip3 is
-    (_, Just endblock, _) = fromJust lastblock
+    (offsets, _, insonly) = unzip3 is
+    (lastoff, Just endblock, lastins) = fromJust lastblock
 
     -- also take last (non-matched) element and return it
     takeWhilePlusOne :: (a -> Bool) -> (a -> Bool) -> [a] -> (Maybe a, [a])
@@ -176,30 +168,34 @@ parseBasicBlock i insns = emptyBasicBlock { code = insonly, successor = endblock
     omitins (off, _, _) = off < i
 
 
-calculateInstructionOffset :: [Instruction] -> AnalyseState
-calculateInstructionOffset = cio' (0, Nothing, NOP)
+calculateInstructionOffset :: [BlockID] -> [Instruction] -> AnalyseState
+calculateInstructionOffset exstarts = cio' 0
   where
-    addW16Signed :: Int -> Word16 -> Int
     addW16Signed i w16 = i + fromIntegral s16
       where s16 = fromIntegral w16 :: Int16
 
-    cio' :: OffIns -> [Instruction] -> AnalyseState
+    cio' :: Int -> [Instruction] -> AnalyseState
     cio' _ [] = return $ []
-    cio' (off,_,_) (x:xs) = case x of
+    cio' off (x:xs) = case x of
         IF _ w16 -> twotargets w16
         IF_ICMP _ w16 -> twotargets w16
         IF_ACMP _ w16 -> twotargets w16
         IFNONNULL w16 -> twotargets w16
         IFNULL w16 -> twotargets w16
         GOTO w16 -> onetarget w16
+        ATHROW -> notarget
         IRETURN -> notarget
         ARETURN -> notarget
         RETURN -> notarget
-        _ -> normalins
+        _ -> if newoffset `elem` exstarts
+              then do
+                modify (S.insert newoffset)
+                ((off, Just $ OneTarget newoffset, x):) <$> next
+              else normalins
       where
         normalins = do
           tailinsns <- next -- eval remaining instructions
-          isNextInsATarget <- (elem newoffset) <$> get
+          isNextInsATarget <- (S.member newoffset) <$> get
           let bbtyp = if isNextInsATarget
                 then Just $ FallThrough newoffset
                 else Nothing
@@ -207,17 +203,17 @@ calculateInstructionOffset = cio' (0, Nothing, NOP)
         notarget = ((off, Just Return, x):) <$> next
         onetarget w16 = do
           let jump = off `addW16Signed` w16
-          modify (jump:)
+          modify (S.insert jump)
           ((off, Just $ OneTarget jump, x):) <$> next
         twotargets w16 = do
           let nojump = off + 3
-          modify (nojump:)
+          modify (S.insert nojump)
           let jump = off `addW16Signed` w16
-          modify (jump:)
+          modify (S.insert jump)
           ((off, Just $ TwoTarget nojump jump, x):) <$> next
-        next = cio' nextins xs
-        nextins = (newoffset, Nothing, NOP)
-        newoffset = off + insnLength x
+        next = cio' newoffset xs
+        newoffset = off + insLen
+        insLen = insnLength x
 
 -- TODO(bernhard): does GHC memomize results? i.e. does it calculate the size
 --                 of `NOP' only once?