-- GHC API
import CoreSyn
import qualified CoreUtils
+import qualified BasicTypes
import qualified Type
+import qualified TysWiredIn
import qualified Id
import qualified Var
import qualified Name
-- it has a function type. Eventually this will result in a function
-- body consisting of a bunch of nested lambdas containing a
-- non-function value (e.g., a complete application).
-eta, etatop :: Transform
+eta :: Transform
eta c expr | is_fun expr && not (is_lam expr) && all (== LambdaBody) c = do
let arg_ty = (fst . Type.splitFunTy . CoreUtils.exprType) expr
id <- Trans.lift $ mkInternalVar "param" arg_ty
change (Lam id (App expr (Var id)))
-- Leave all other expressions unchanged
eta c e = return e
-etatop = everywhere ("eta", eta)
--------------------------------
-- β-reduction
--------------------------------
-beta, betatop :: Transform
+beta :: Transform
-- Substitute arg for x in expr. For value lambda's, also clone before
-- substitution.
beta c (App (Lam x expr) arg) | CoreSyn.isTyVar x = setChanged >> substitute x arg c expr
| otherwise = setChanged >> substitute_clone x arg c expr
+-- Leave all other expressions unchanged
+beta c expr = return expr
+
+--------------------------------
+-- Application propagation
+--------------------------------
+appprop :: Transform
-- Propagate the application into the let
-beta c (App (Let binds expr) arg) = change $ Let binds (App expr arg)
+appprop c (App (Let binds expr) arg) = change $ Let binds (App expr arg)
-- Propagate the application into each of the alternatives
-beta c (App (Case scrut b ty alts) arg) = change $ Case scrut b ty' alts'
+appprop c (App (Case scrut b ty alts) arg) = change $ Case scrut b ty' alts'
where
alts' = map (\(con, bndrs, expr) -> (con, bndrs, (App expr arg))) alts
ty' = CoreUtils.applyTypeToArg ty arg
-- Leave all other expressions unchanged
-beta c expr = return expr
--- Perform this transform everywhere
-betatop = everywhere ("beta", beta)
+appprop c expr = return expr
--------------------------------
-- Case of known constructor simplification
-- alternative bound to the corresponding argument of the datacon. We do
-- this instead of substituting the binders, to prevent duplication of
-- work and preserve sharing wherever appropriate.
-knowncase, knowncasetop :: Transform
+knowncase :: Transform
knowncase context expr@(Case scrut@(App _ _) bndr ty alts) | not bndr_used = do
case collectArgs scrut of
(Var f, args) -> case Id.isDataConId_maybe f of
-- Leave all other expressions unchanged
knowncase c expr = return expr
--- Perform this transform everywhere
-knowncasetop = everywhere ("knowncase", knowncase)
--------------------------------
-- Cast propagation
--------------------------------
-- Try to move casts as much downward as possible.
-castprop, castproptop :: Transform
+castprop :: Transform
castprop c (Cast (Let binds expr) ty) = change $ Let binds (Cast expr ty)
castprop c expr@(Cast (Case scrut b _ alts) ty) = change (Case scrut b ty alts')
where
alts' = map (\(con, bndrs, expr) -> (con, bndrs, (Cast expr ty))) alts
-- Leave all other expressions unchanged
castprop c expr = return expr
--- Perform this transform everywhere
-castproptop = everywhere ("castprop", castprop)
--------------------------------
-- Cast simplification. Mostly useful for state packing and unpacking, but
-- perhaps for others as well.
--------------------------------
-castsimpl, castsimpltop :: Transform
+castsimpl :: Transform
castsimpl c expr@(Cast val ty) = do
-- Don't extract values that are already simpl
local_var <- Trans.lift $ is_local_var val
return expr
-- Leave all other expressions unchanged
castsimpl c expr = return expr
--- Perform this transform everywhere
-castsimpltop = everywhere ("castsimpl", castsimpl)
--------------------------------
-- Return value simplification
-- Leave all other expressions unchanged
retvalsimpl c expr = return expr
--- Perform this transform everywhere
-retvalsimpltop = everywhere ("retvalsimpl", retvalsimpl)
--------------------------------
-- let derecursification
--------------------------------
-letrec, letrectop :: Transform
+letrec :: Transform
letrec c expr@(Let (NonRec bndr val) res) =
change $ Let (Rec [(bndr, val)]) res
-- Leave all other expressions unchanged
letrec c expr = return expr
--- Perform this transform everywhere
-letrectop = everywhere ("letrec", letrec)
--------------------------------
-- let flattening
-- let b = (let b' = expr' in res') in res
-- to:
-- let b' = expr' in (let b = res' in res)
-letflat, letflattop :: Transform
+letflat :: Transform
-- Turn a nonrec let that binds a let into two nested lets.
letflat c (Let (NonRec b (Let binds res')) res) =
change $ Let binds (Let (NonRec b res') res)
flatbind (b, expr) = return [(b, expr)]
-- Leave all other expressions unchanged
letflat c expr = return expr
--- Perform this transform everywhere
-letflattop = everywhere ("letflat", letflat)
--------------------------------
-- empty let removal
--------------------------------
-- Remove empty (recursive) lets
-letremove, letremovetop :: Transform
+letremove :: Transform
letremove c (Let (Rec []) res) = change res
-- Leave all other expressions unchanged
letremove c expr = return expr
--- Perform this transform everywhere
-letremovetop = everywhere ("letremove", letremove)
--------------------------------
-- Simple let binding removal
--------------------------------
-- Remove a = b bindings from let expressions everywhere
-letremovesimpletop :: Transform
-letremovesimpletop = everywhere ("letremovesimple", inlinebind (\(b, e) -> Trans.lift $ is_local_var e))
+letremovesimple :: Transform
+letremovesimple = inlinebind (\(b, e) -> Trans.lift $ is_local_var e)
--------------------------------
-- Unused let binding removal
--------------------------------
-letremoveunused, letremoveunusedtop :: Transform
+letremoveunused :: Transform
letremoveunused c expr@(Let (NonRec b bound) res) = do
let used = expr_uses_binders [b] res
if used
dobind (bndr, _) = any (expr_uses_binders [bndr]) (res:bound_exprs)
-- Leave all other expressions unchanged
letremoveunused c expr = return expr
-letremoveunusedtop = everywhere ("letremoveunused", letremoveunused)
{-
--------------------------------
-- Merge two bindings in a let if they are identical
-- TODO: We would very much like to use GHC's CSE module for this, but that
-- doesn't track if something changed or not, so we can't use it properly.
-letmerge, letmergetop :: Transform
+letmerge :: Transform
letmerge c expr@(Let _ _) = do
let (binds, res) = flattenLets expr
binds' <- domerge binds
| otherwise = return (b2, e2)
-- Leave all other expressions unchanged
letmerge c expr = return expr
-letmergetop = everywhere ("letmerge", letmerge)
-}
--------------------------------
-- transformations will just not work on those function-typed values at first,
-- but the other transformations (in particular β-reduction) should make sure
-- that the type of those values eventually becomes representable.
-inlinenonreptop :: Transform
-inlinenonreptop = everywhere ("inlinenonrep", inlinebind ((Monad.liftM not) . isRepr . snd))
+inlinenonrep :: Transform
+inlinenonrep = inlinebind ((Monad.liftM not) . isRepr . snd)
--------------------------------
-- Top level function inlining
-- that will eventually generate instantiations of trivial components.
-- By not inlining any other reference, we also prevent looping problems
-- with funextract and inlinedict.
-inlinetoplevel, inlinetopleveltop :: Transform
+inlinetoplevel :: Transform
inlinetoplevel (LetBinding:_) expr | not (is_fun expr) =
case collectArgs expr of
(Var f, args) -> do
-- Leave all other expressions unchanged
inlinetoplevel c expr = return expr
-inlinetopleveltop = everywhere ("inlinetoplevel", inlinetoplevel)
-
+
-- | Does the given binder need to be inlined? If so, return the body to
-- be used for inlining.
needsInline :: CoreBndr -> TransformMonad (Maybe CoreExpr)
(args, [bind], Var res) -> return $ Just norm
-- More complicated function, don't inline
_ -> return Nothing
-
+
--------------------------------
-- Dictionary inlining
--------------------------------
-- Leave all other expressions unchanged
inlinedict c expr = return expr
-inlinedicttop = everywhere ("inlinedict", inlinedict)
--------------------------------
-- ClassOp resolution
-- translateable. For example, when deriving ==, GHC generates code
-- using $con2tag functions to translate a datacon to an int and compare
-- that with GHC.Prim.==# . Better to avoid that for now.
-classopresolution, classopresolutiontop :: Transform
+classopresolution :: Transform
classopresolution c expr@(App (App (Var sel) ty) dict) | not is_builtin =
case Id.isClassOpId_maybe sel of
-- Not a class op selector
-- Leave all other expressions unchanged
classopresolution c expr = return expr
--- Perform this transform everywhere
-classopresolutiontop = everywhere ("classopresolution", classopresolution)
--------------------------------
-- Scrutinee simplification
--------------------------------
-scrutsimpl,scrutsimpltop :: Transform
+scrutsimpl :: Transform
-- Don't touch scrutinees that are already simple
scrutsimpl c expr@(Case (Var _) _ _ _) = return expr
-- Replace all other cases with a let that binds the scrutinee and a new
return expr
-- Leave all other expressions unchanged
scrutsimpl c expr = return expr
--- Perform this transform everywhere
-scrutsimpltop = everywhere ("scrutsimpl", scrutsimpl)
--------------------------------
-- Scrutinee binder removal
-- arguments. Since strictness does not matter for us (rather, everything is
-- sort of strict), this binder is ignored when generating VHDL, and must thus
-- be wild in the normal form.
-scrutbndrremove, scrutbndrremovetop :: Transform
+scrutbndrremove :: Transform
-- If the scrutinee is already simple, and the bndr is not wild yet, replace
-- all occurences of the binder with the scrutinee variable.
scrutbndrremove c (Case (Var scrut) bndr ty alts) | bndr_used = do
wild = MkCore.mkWildBinder (Id.idType bndr)
-- Leave all other expressions unchanged
scrutbndrremove c expr = return expr
-scrutbndrremovetop = everywhere ("scrutbndrremove", scrutbndrremove)
--------------------------------
-- Case binder wildening
--------------------------------
-casesimpl, casesimpltop :: Transform
+casesimpl :: Transform
-- This is already a selector case (or, if x does not appear in bndrs, a very
-- simple case statement that will be removed by caseremove below). Just leave
-- it be.
return (Nothing, expr)
-- Leave all other expressions unchanged
casesimpl c expr = return expr
--- Perform this transform everywhere
-casesimpltop = everywhere ("casesimpl", casesimpl)
--------------------------------
-- Case removal
--------------------------------
-- Remove case statements that have only a single alternative and only wild
-- binders.
-caseremove, caseremovetop :: Transform
+caseremove :: Transform
-- Replace a useless case by the value of its single alternative
caseremove c (Case scrut b ty [(con, bndrs, expr)]) | not usesvars = change expr
-- Find if any of the binders are used by expr
where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` b:bndrs))) expr
-- Leave all other expressions unchanged
caseremove c expr = return expr
--- Perform this transform everywhere
-caseremovetop = everywhere ("caseremove", caseremove)
--------------------------------
-- Argument extraction
--------------------------------
-- Make sure that all arguments of a representable type are simple variables.
-appsimpl, appsimpltop :: Transform
+appsimpl :: Transform
-- Simplify all representable arguments. Do this by introducing a new Let
-- that binds the argument and passing the new binder in the application.
appsimpl c expr@(App f arg) = do
return expr
-- Leave all other expressions unchanged
appsimpl c expr = return expr
--- Perform this transform everywhere
-appsimpltop = everywhere ("appsimpl", appsimpl)
--------------------------------
-- Function-typed argument propagation
-- Remove all applications to function-typed arguments, by duplication the
-- function called with the function-typed parameter replaced by the free
-- variables of the argument passed in.
-argprop, argproptop :: Transform
+argprop :: Transform
-- Transform any application of a named function (i.e., skip applications of
-- lambda's). Also skip applications that have arguments with free type
-- variables, since we can't inline those.
return ([arg], [id], mkReferenceTo id)
-- Leave all other expressions unchanged
argprop c expr = return expr
--- Perform this transform everywhere
-argproptop = everywhere ("argprop", argprop)
+
+--------------------------------
+-- Non-representable result inlining
+--------------------------------
+-- This transformation takes a function (top level binding) that has a
+-- non-representable result (e.g., a tuple containing a function, or an
+-- Integer. The latter can occur in some cases as the result of the
+-- fromIntegerT function) and inlines enough of the function to make the
+-- result representable again.
+--
+-- This is done by first normalizing the function and then "inlining"
+-- the result. Since no unrepresentable let bindings are allowed in
+-- normal form, we can be sure that all free variables of the result
+-- expression will be representable (Note that we probably can't
+-- guarantee that all representable parts of the expression will be free
+-- variables, so we might inline more than strictly needed).
+--
+-- The new function result will be a tuple containing all free variables
+-- of the old result, so the old result can be rebuild at the caller.
+--
+-- We take care not to inline dictionary id's, which are top level
+-- bindings with a non-representable result type as well, since those
+-- will never become VHDL signals directly. There is a separate
+-- transformation (inlinedict) that specifically inlines dictionaries
+-- only when it is useful.
+inlinenonrepresult :: Transform
+
+-- Apply to any (application of) a reference to a top level function
+-- that is fully applied (i.e., dos not have a function type) but is not
+-- representable. We apply in any context, since non-representable
+-- expressions are generally left alone and can occur anywhere.
+inlinenonrepresult context expr | not (is_fun expr) =
+ case collectArgs expr of
+ (Var f, args) | not (Id.isDictId f) -> do
+ repr <- isRepr expr
+ if not repr
+ then do
+ body_maybe <- Trans.lift $ getNormalized_maybe True f
+ case body_maybe of
+ Just body -> do
+ let (bndrs, binds, res) = splitNormalizedNonRep body
+ if has_free_tyvars res
+ then
+ -- Don't touch anything with free type variables, since
+ -- we can't return those. We'll wait until argprop
+ -- removed those variables.
+ return expr
+ else do
+ -- Get the free local variables of res
+ global_bndrs <- Trans.lift getGlobalBinders
+ let interesting var = Var.isLocalVar var && (var `notElem` global_bndrs)
+ let free_vars = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars interesting res
+ let free_var_types = map Id.idType free_vars
+ let n_free_vars = length free_vars
+ -- Get a tuple datacon to wrap around the free variables
+ let fvs_datacon = TysWiredIn.tupleCon BasicTypes.Boxed n_free_vars
+ let fvs_datacon_id = DataCon.dataConWorkId fvs_datacon
+ -- Let the function now return a tuple with references to
+ -- all free variables of the old return value. First pass
+ -- all the types of the variables, since tuple
+ -- constructors are polymorphic.
+ let newres = mkApps (Var fvs_datacon_id) (map Type free_var_types ++ map Var free_vars)
+ -- Recreate the function body with the changed return value
+ let newbody = mkLams bndrs (Let (Rec binds) newres)
+ -- Create the new function
+ f' <- Trans.lift $ mkFunction f newbody
+
+ -- Call the new function
+ let newapp = mkApps (Var f') args
+ res_bndr <- Trans.lift $ mkBinderFor newapp "res"
+ -- Create extractor case expressions to extract each of the
+ -- free variables from the tuple.
+ sel_cases <- Trans.lift $ mapM (mkSelCase (Var res_bndr)) [0..n_free_vars-1]
+
+ -- Bind the res_bndr to the result of the new application
+ -- and each of the free variables to the corresponding
+ -- selector case. Replace the let body with the original
+ -- body of the called function (which can still access all
+ -- of its free variables, from the let).
+ let binds = (res_bndr, newapp):(zip free_vars sel_cases)
+ let letexpr = Let (Rec binds) res
+
+ -- Finally, regenarate all uniques in the new expression,
+ -- since the free variables could otherwise become
+ -- duplicated. It is not strictly necessary to regenerate
+ -- res, since we're moving that expression, but it won't
+ -- hurt.
+ letexpr_uniqued <- Trans.lift $ genUniques letexpr
+ change letexpr_uniqued
+ Nothing -> return expr
+ else
+ -- Don't touch representable expressions or (applications of)
+ -- dictionary ids.
+ return expr
+ -- Not a reference to or application of a top level function
+ _ -> return expr
+-- Leave all other expressions unchanged
+inlinenonrepresult c expr = return expr
+
--------------------------------
-- Function-typed argument extraction
-- puts it in a brand new top level binder. This allows us to for example
-- apply map to a lambda expression This will not conflict with inlinenonrep,
-- since that only inlines local let bindings, not top level bindings.
-funextract, funextracttop :: Transform
+funextract :: Transform
funextract c expr@(App _ _) | is_var fexpr = do
body_maybe <- Trans.lift $ getGlobalBind f
case body_maybe of
-- Leave all other expressions unchanged
funextract c expr = return expr
--- Perform this transform everywhere
-funextracttop = everywhere ("funextract", funextract)
--------------------------------
-- End of transformations
-- What transforms to run?
-transforms = [inlinedicttop, inlinetopleveltop, knowncasetop, classopresolutiontop, argproptop, funextracttop, etatop, betatop, castproptop, letremovesimpletop, letrectop, letremovetop, retvalsimpltop, letflattop, scrutsimpltop, scrutbndrremovetop, casesimpltop, caseremovetop, inlinenonreptop, appsimpltop, letremoveunusedtop, castsimpltop]
+transforms = [ ("inlinedict", inlinedict)
+ , ("inlinetoplevel", inlinetoplevel)
+ , ("inlinenonrepresult", inlinenonrepresult)
+ , ("knowncase", knowncase)
+ , ("classopresolution", classopresolution)
+ , ("argprop", argprop)
+ , ("funextract", funextract)
+ , ("eta", eta)
+ , ("beta", beta)
+ , ("appprop", appprop)
+ , ("castprop", castprop)
+ , ("letremovesimple", letremovesimple)
+ , ("letrec", letrec)
+ , ("letremove", letremove)
+ , ("retvalsimpl", retvalsimpl)
+ , ("letflat", letflat)
+ , ("scrutsimpl", scrutsimpl)
+ , ("scrutbndrremove", scrutbndrremove)
+ , ("casesimpl", casesimpl)
+ , ("caseremove", caseremove)
+ , ("inlinenonrep", inlinenonrep)
+ , ("appsimpl", appsimpl)
+ , ("letremoveunused", letremoveunused)
+ , ("castsimpl", castsimpl)
+ ]
-- | Returns the normalized version of the given function, or an error
-- if it is not a known global binder.
normalizeExpr what expr = do
startcount <- MonadState.get tsTransformCounter
expr_uniqued <- genUniques expr
+ -- Do a debug print, if requested
+ let expr_uniqued' = Utils.traceIf (normalize_debug >= NormDbgFinal) (what ++ " before normalization:\n\n" ++ showSDoc ( ppr expr_uniqued ) ++ "\n") expr_uniqued
-- Normalize this expression
- trace (what ++ " before normalization:\n\n" ++ showSDoc ( ppr expr_uniqued ) ++ "\n") $ return ()
- expr' <- dotransforms transforms expr_uniqued
+ expr' <- dotransforms transforms expr_uniqued'
endcount <- MonadState.get tsTransformCounter
- trace ("\n" ++ what ++ " after normalization:\n\n" ++ showSDoc ( ppr expr')
- ++ "\nNeeded " ++ show (endcount - startcount) ++ " transformations to normalize " ++ what) $
- return expr'
+ -- Do a debug print, if requested
+ Utils.traceIf (normalize_debug >= NormDbgFinal) (what ++ " after normalization:\n\n" ++ showSDoc ( ppr expr') ++ "\nNeeded " ++ show (endcount - startcount) ++ " transformations to normalize " ++ what) $
+ return expr'
-- | Split a normalized expression into the argument binders, top level
-- bindings and the result binder. This function returns an error if