-- GRIN-like backend for Yhc Core. -- Optimization of case expressions. module Yhc.Core.GRIN.OptCases where import Yhc.Core.GRIN.Type import Yhc.Core.GRIN.FindType import Yhc.Core.GRIN.HeapPointsTo import Yhc.Core.GRIN.SubstVars import Data.List import qualified Data.Set as S import qualified Data.Map as M -- Optimize case expressions such as if there is only one pattern -- then replace it with the only branch. Heap map is not needed. -- Since case may be only last elment of a block, look at it, -- and if there is a case with only one pattern, append the pattern's -- block to the enclosing block, otherwise leave as is. optCases :: GRIN -> GRIN optCases gr = gr {gFuncs = map f (gFuncs gr)} where f gf = gf {gFuncBody = filter (/= GNop) (ff (gFuncBody gf))} ff [] = [] ff (GBind (GInline ib) bv : bs) = let ib' = (ff . gg) ib b' = GBind (GInline ib') bv in b' : (ff . gg) bs ff (GCase cv cbrs : bs) = let pats = map fst cbrs blks = map snd cbrs blks' = map (ff . gg) blks b' = GCase cv (zip pats blks') in b' : ff bs ff (b:bs) = b : (ff . gg) bs gg [] = [] gg blk = let e:b = reverse blk in case e of GCase _ [cbr] -> reverse b ++ snd cbr _ -> blk