Global constant propagation

C Rodrigues red5_2 at hotmail.com
Sun Jan 20 22:18:15 CET 2013


I'm curious about global constant propagation in GHC.  It's a fairly basic optimization in the CFG-based compiler domain, and it's similar to constructor specialization, but it doesn't seem to be in GHC's repertoire.  Perhaps it's usually subsumed by other optimizations or it's more complicated than I am thinking.  Is this optimization worth implementing?

This optimization can help when a case expression returns a product, some fields of which are the same in all branches.  The following program is a minimal example of an optimizable situation that GHC doesn't exploit.


{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}


data D = D !Int !Int


foo n = if n > 0

        then D 0 0

        else D 0 n


main =

  case foo $ read "7"

  of D x y -> if x == 0 then return () else print y >> putStrLn "A"


After inlining and case-of-case transformation, GHC produces


main = let n = read "7"

           k x y = case x of {0 -> return (); _ -> print y >> putStrLn "A"}

       in if n > 0

          then k 0 0

          else k 0 n


If the simplifier could discover that x is always 0, it could eliminate one parameter of 'k' and the case expression.

 		 	   		  


More information about the Glasgow-haskell-users mailing list