1 {-# LANGUAGE PackageImports #-}
3 -- Functions to bring a Core expression in normal form. This module provides a
4 -- top level function "normalize", and defines the actual transformation passes that
7 module CLasH.Normalize (getNormalized, normalizeExpr, splitNormalized) where
11 import qualified Maybe
13 import qualified "transformers" Control.Monad.Trans as Trans
14 import qualified Control.Monad as Monad
15 import qualified Control.Monad.Trans.Writer as Writer
16 import qualified Data.Map as Map
17 import qualified Data.Monoid as Monoid
22 import qualified UniqSupply
23 import qualified CoreUtils
25 import qualified TcType
29 import qualified VarSet
30 import qualified NameSet
31 import qualified CoreFVs
32 import qualified CoreUtils
33 import qualified MkCore
34 import qualified HscTypes
35 import Outputable ( showSDoc, ppr, nest )
38 import CLasH.Normalize.NormalizeTypes
39 import CLasH.Translator.TranslatorTypes
40 import CLasH.Normalize.NormalizeTools
41 import CLasH.VHDL.VHDLTypes
42 import qualified CLasH.Utils as Utils
43 import CLasH.Utils.Core.CoreTools
44 import CLasH.Utils.Core.BinderTools
45 import CLasH.Utils.Pretty
47 --------------------------------
48 -- Start of transformations
49 --------------------------------
51 --------------------------------
53 --------------------------------
54 eta, etatop :: Transform
55 eta expr | is_fun expr && not (is_lam expr) = do
56 let arg_ty = (fst . Type.splitFunTy . CoreUtils.exprType) expr
57 id <- Trans.lift $ mkInternalVar "param" arg_ty
58 change (Lam id (App expr (Var id)))
59 -- Leave all other expressions unchanged
61 etatop = notappargs ("eta", eta)
63 --------------------------------
65 --------------------------------
66 beta, betatop :: Transform
67 -- Substitute arg for x in expr
68 beta (App (Lam x expr) arg) = change $ substitute [(x, arg)] expr
69 -- Propagate the application into the let
70 beta (App (Let binds expr) arg) = change $ Let binds (App expr arg)
71 -- Propagate the application into each of the alternatives
72 beta (App (Case scrut b ty alts) arg) = change $ Case scrut b ty' alts'
74 alts' = map (\(con, bndrs, expr) -> (con, bndrs, (App expr arg))) alts
75 ty' = CoreUtils.applyTypeToArg ty arg
76 -- Leave all other expressions unchanged
77 beta expr = return expr
78 -- Perform this transform everywhere
79 betatop = everywhere ("beta", beta)
81 --------------------------------
83 --------------------------------
84 -- Try to move casts as much downward as possible.
85 castprop, castproptop :: Transform
86 castprop (Cast (Let binds expr) ty) = change $ Let binds (Cast expr ty)
87 castprop expr@(Cast (Case scrut b _ alts) ty) = change (Case scrut b ty alts')
89 alts' = map (\(con, bndrs, expr) -> (con, bndrs, (Cast expr ty))) alts
90 -- Leave all other expressions unchanged
91 castprop expr = return expr
92 -- Perform this transform everywhere
93 castproptop = everywhere ("castprop", castprop)
95 --------------------------------
96 -- Cast simplification. Mostly useful for state packing and unpacking, but
97 -- perhaps for others as well.
98 --------------------------------
99 castsimpl, castsimpltop :: Transform
100 castsimpl expr@(Cast val ty) = do
101 -- Don't extract values that are already simpl
102 local_var <- Trans.lift $ is_local_var val
103 -- Don't extract values that are not representable, to prevent loops with
106 if (not local_var) && repr
108 -- Generate a binder for the expression
109 id <- Trans.lift $ mkBinderFor val "castval"
110 -- Extract the expression
111 change $ Let (NonRec id val) (Cast (Var id) ty)
114 -- Leave all other expressions unchanged
115 castsimpl expr = return expr
116 -- Perform this transform everywhere
117 castsimpltop = everywhere ("castsimpl", castsimpl)
120 --------------------------------
121 -- Lambda simplication
122 --------------------------------
123 -- Ensure that a lambda always evaluates to a let expressions or a simple
124 -- variable reference.
125 lambdasimpl, lambdasimpltop :: Transform
126 -- Don't simplify a lambda that evaluates to let, since this is already
127 -- normal form (and would cause infinite loops).
128 lambdasimpl expr@(Lam _ (Let _ _)) = return expr
129 -- Put the of a lambda in its own binding, but not when the expression is
130 -- already a local variable, or not representable (to prevent loops with
132 lambdasimpl expr@(Lam bndr res) = do
134 local_var <- Trans.lift $ is_local_var res
135 if not local_var && repr
137 id <- Trans.lift $ mkBinderFor res "res"
138 change $ Lam bndr (Let (NonRec id res) (Var id))
140 -- If the result is already a local var or not representable, don't
144 -- Leave all other expressions unchanged
145 lambdasimpl expr = return expr
146 -- Perform this transform everywhere
147 lambdasimpltop = everywhere ("lambdasimpl", lambdasimpl)
149 --------------------------------
150 -- let derecursification
151 --------------------------------
152 letderec, letderectop :: Transform
153 letderec expr@(Let (Rec binds) res) = case liftable of
154 -- Nothing is liftable, just return
156 -- Something can be lifted, generate a new let expression
157 _ -> change $ mkNonRecLets liftable (Let (Rec nonliftable) res)
159 -- Make a list of all the binders bound in this recursive let
160 bndrs = map fst binds
161 -- See which bindings are liftable
162 (liftable, nonliftable) = List.partition canlift binds
163 -- Any expression that does not use any of the binders in this recursive let
164 -- can be lifted into a nonrec let. It can't use its own binder either,
165 -- since that would mean the binding is self-recursive and should be in a
166 -- single bind recursive let.
167 canlift (bndr, e) = not $ expr_uses_binders bndrs e
168 -- Leave all other expressions unchanged
169 letderec expr = return expr
170 -- Perform this transform everywhere
171 letderectop = everywhere ("letderec", letderec)
173 --------------------------------
174 -- let simplification
175 --------------------------------
176 letsimpl, letsimpltop :: Transform
177 -- Don't simplify a let that evaluates to another let, since this is already
178 -- normal form (and would cause infinite loops with letflat below).
179 letsimpl expr@(Let _ (Let _ _)) = return expr
180 -- Put the "in ..." value of a let in its own binding, but not when the
181 -- expression is already a local variable, or not representable (to prevent loops with inlinenonrep).
182 letsimpl expr@(Let binds res) = do
184 local_var <- Trans.lift $ is_local_var res
185 if not local_var && repr
187 -- If the result is not a local var already (to prevent loops with
188 -- ourselves), extract it.
189 id <- Trans.lift $ mkBinderFor res "foo"
190 change $ Let binds (Let (NonRec id res) (Var id))
192 -- If the result is already a local var, don't extract it.
195 -- Leave all other expressions unchanged
196 letsimpl expr = return expr
197 -- Perform this transform everywhere
198 letsimpltop = everywhere ("letsimpl", letsimpl)
200 --------------------------------
202 --------------------------------
203 -- Takes a let that binds another let, and turns that into two nested lets.
205 -- let b = (let b' = expr' in res') in res
207 -- let b' = expr' in (let b = res' in res)
208 letflat, letflattop :: Transform
209 -- Turn a nonrec let that binds a let into two nested lets.
210 letflat (Let (NonRec b (Let binds res')) res) =
211 change $ Let binds (Let (NonRec b res') res)
212 letflat (Let (Rec binds) expr) = do
213 -- Flatten each binding.
214 binds' <- Utils.concatM $ Monad.mapM flatbind binds
215 -- Return the new let. We don't use change here, since possibly nothing has
216 -- changed. If anything has changed, flatbind has already flagged that
218 return $ Let (Rec binds') expr
220 -- Turns a binding of a let into a multiple bindings, or any other binding
221 -- into a list with just that binding
222 flatbind :: (CoreBndr, CoreExpr) -> TransformMonad [(CoreBndr, CoreExpr)]
223 flatbind (b, Let (Rec binds) expr) = change ((b, expr):binds)
224 flatbind (b, Let (NonRec b' expr') expr) = change [(b, expr), (b', expr')]
225 flatbind (b, expr) = return [(b, expr)]
226 -- Leave all other expressions unchanged
227 letflat expr = return expr
228 -- Perform this transform everywhere
229 letflattop = everywhere ("letflat", letflat)
231 --------------------------------
233 --------------------------------
234 -- Remove empty (recursive) lets
235 letremove, letremovetop :: Transform
236 letremove (Let (Rec []) res) = change $ res
237 -- Leave all other expressions unchanged
238 letremove expr = return expr
239 -- Perform this transform everywhere
240 letremovetop = everywhere ("letremove", letremove)
242 --------------------------------
243 -- Simple let binding removal
244 --------------------------------
245 -- Remove a = b bindings from let expressions everywhere
246 letremovesimpletop :: Transform
247 letremovesimpletop = everywhere ("letremovesimple", inlinebind (\(b, e) -> Trans.lift $ is_local_var e))
249 --------------------------------
250 -- Unused let binding removal
251 --------------------------------
252 letremoveunused, letremoveunusedtop :: Transform
253 letremoveunused expr@(Let (NonRec b bound) res) = do
254 let used = expr_uses_binders [b] res
258 letremoveunused expr@(Let (Rec binds) res) = do
259 -- Filter out all unused binds.
260 let binds' = filter dobind binds
261 -- Only set the changed flag if binds got removed
262 changeif (length binds' /= length binds) (Let (Rec binds') res)
264 bound_exprs = map snd binds
265 -- For each bind check if the bind is used by res or any of the bound
267 dobind (bndr, _) = any (expr_uses_binders [bndr]) (res:bound_exprs)
268 -- Leave all other expressions unchanged
269 letremoveunused expr = return expr
270 letremoveunusedtop = everywhere ("letremoveunused", letremoveunused)
273 --------------------------------
274 -- Identical let binding merging
275 --------------------------------
276 -- Merge two bindings in a let if they are identical
277 -- TODO: We would very much like to use GHC's CSE module for this, but that
278 -- doesn't track if something changed or not, so we can't use it properly.
279 letmerge, letmergetop :: Transform
280 letmerge expr@(Let _ _) = do
281 let (binds, res) = flattenLets expr
282 binds' <- domerge binds
283 return $ mkNonRecLets binds' res
285 domerge :: [(CoreBndr, CoreExpr)] -> TransformMonad [(CoreBndr, CoreExpr)]
286 domerge [] = return []
288 es' <- mapM (mergebinds e) es
292 -- Uses the second bind to simplify the second bind, if applicable.
293 mergebinds :: (CoreBndr, CoreExpr) -> (CoreBndr, CoreExpr) -> TransformMonad (CoreBndr, CoreExpr)
294 mergebinds (b1, e1) (b2, e2)
295 -- Identical expressions? Replace the second binding with a reference to
297 | CoreUtils.cheapEqExpr e1 e2 = change $ (b2, Var b1)
298 -- Different expressions? Don't change
299 | otherwise = return (b2, e2)
300 -- Leave all other expressions unchanged
301 letmerge expr = return expr
302 letmergetop = everywhere ("letmerge", letmerge)
305 --------------------------------
307 --------------------------------
308 -- Remove a = B bindings, with B :: a -> b, or B :: forall x . T, from let
309 -- expressions everywhere. This means that any value that still needs to be
310 -- applied to something else (polymorphic values need to be applied to a
311 -- Type) will be inlined, and will eventually be applied to all their
314 -- This is a tricky function, which is prone to create loops in the
315 -- transformations. To fix this, we make sure that no transformation will
316 -- create a new let binding with a function type. These other transformations
317 -- will just not work on those function-typed values at first, but the other
318 -- transformations (in particular β-reduction) should make sure that the type
319 -- of those values eventually becomes primitive.
320 inlinenonreptop :: Transform
321 inlinenonreptop = everywhere ("inlinenonrep", inlinebind ((Monad.liftM not) . isRepr . snd))
323 inlinetoplevel, inlinetopleveltop :: Transform
324 -- Any system name is candidate for inlining. Never inline user-defined
325 -- functions, to preserver structure.
326 inlinetoplevel expr@(Var f) | (Name.isSystemName . Id.idName) f = do
327 -- See if this is a top level binding for which we have a body
328 body_maybe <- Trans.lift $ getGlobalBind f
331 -- Get the normalized version
332 norm <- Trans.lift $ getNormalized f
338 -- No body, this is probably a local variable or builtin or external
340 Nothing -> return expr
341 -- Leave all other expressions unchanged
342 inlinetoplevel expr = return expr
343 inlinetopleveltop = everywhere ("inlinetoplevel", inlinetoplevel)
345 needsInline :: CoreExpr -> Bool
346 -- Any function that just evaluates to another function, can be inlined
347 --needsInline (Var f) = True
348 needsInline _ = False
350 --------------------------------
351 -- Scrutinee simplification
352 --------------------------------
353 scrutsimpl,scrutsimpltop :: Transform
354 -- Don't touch scrutinees that are already simple
355 scrutsimpl expr@(Case (Var _) _ _ _) = return expr
356 -- Replace all other cases with a let that binds the scrutinee and a new
357 -- simple scrutinee, but only when the scrutinee is representable (to prevent
358 -- loops with inlinenonrep, though I don't think a non-representable scrutinee
359 -- will be supported anyway...)
360 scrutsimpl expr@(Case scrut b ty alts) = do
364 id <- Trans.lift $ mkBinderFor scrut "scrut"
365 change $ Let (NonRec id scrut) (Case (Var id) b ty alts)
368 -- Leave all other expressions unchanged
369 scrutsimpl expr = return expr
370 -- Perform this transform everywhere
371 scrutsimpltop = everywhere ("scrutsimpl", scrutsimpl)
373 --------------------------------
374 -- Case binder wildening
375 --------------------------------
376 casesimpl, casesimpltop :: Transform
377 -- This is already a selector case (or, if x does not appear in bndrs, a very
378 -- simple case statement that will be removed by caseremove below). Just leave
380 casesimpl expr@(Case scrut b ty [(con, bndrs, Var x)]) = return expr
381 -- Make sure that all case alternatives have only wild binders and simple
383 -- This is done by creating a new let binding for each non-wild binder, which
384 -- is bound to a new simple selector case statement and for each complex
385 -- expression. We do this only for representable types, to prevent loops with
387 casesimpl expr@(Case scrut b ty alts) = do
388 (bindingss, alts') <- (Monad.liftM unzip) $ mapM doalt alts
389 let bindings = concat bindingss
390 -- Replace the case with a let with bindings and a case
391 let newlet = mkNonRecLets bindings (Case scrut b ty alts')
392 -- If there are no non-wild binders, or this case is already a simple
393 -- selector (i.e., a single alt with exactly one binding), already a simple
394 -- selector altan no bindings (i.e., no wild binders in the original case),
395 -- don't change anything, otherwise, replace the case.
396 if null bindings then return expr else change newlet
398 -- Generate a single wild binder, since they are all the same
399 wild = MkCore.mkWildBinder
400 -- Wilden the binders of one alt, producing a list of bindings as a
402 doalt :: CoreAlt -> TransformMonad ([(CoreBndr, CoreExpr)], CoreAlt)
403 doalt (con, bndrs, expr) = do
404 -- Make each binder wild, if possible
405 bndrs_res <- Monad.zipWithM dobndr bndrs [0..]
406 let (newbndrs, bindings_maybe) = unzip bndrs_res
407 -- Extract a complex expression, if possible. For this we check if any of
408 -- the new list of bndrs are used by expr. We can't use free_vars here,
409 -- since that looks at the old bndrs.
410 let uses_bndrs = not $ VarSet.isEmptyVarSet $ CoreFVs.exprSomeFreeVars (`elem` newbndrs) $ expr
411 (exprbinding_maybe, expr') <- doexpr expr uses_bndrs
412 -- Create a new alternative
413 let newalt = (con, newbndrs, expr')
414 let bindings = Maybe.catMaybes (bindings_maybe ++ [exprbinding_maybe])
415 return (bindings, newalt)
417 -- Make wild alternatives for each binder
418 wildbndrs = map (\bndr -> MkCore.mkWildBinder (Id.idType bndr)) bndrs
419 -- A set of all the binders that are used by the expression
420 free_vars = CoreFVs.exprSomeFreeVars (`elem` bndrs) expr
421 -- Look at the ith binder in the case alternative. Return a new binder
422 -- for it (either the same one, or a wild one) and optionally a let
423 -- binding containing a case expression.
424 dobndr :: CoreBndr -> Int -> TransformMonad (CoreBndr, Maybe (CoreBndr, CoreExpr))
426 repr <- isRepr (Var b)
427 -- Is b wild (e.g., not a free var of expr. Since b is only in scope
428 -- in expr, this means that b is unused if expr does not use it.)
429 let wild = not (VarSet.elemVarSet b free_vars)
430 -- Create a new binding for any representable binder that is not
431 -- already wild and is representable (to prevent loops with
433 if (not wild) && repr
435 -- Create on new binder that will actually capture a value in this
436 -- case statement, and return it.
437 let bty = (Id.idType b)
438 id <- Trans.lift $ mkInternalVar "sel" bty
439 let binders = take i wildbndrs ++ [id] ++ drop (i+1) wildbndrs
440 let caseexpr = Case scrut b bty [(con, binders, Var id)]
441 return (wildbndrs!!i, Just (b, caseexpr))
443 -- Just leave the original binder in place, and don't generate an
444 -- extra selector case.
446 -- Process the expression of a case alternative. Accepts an expression
447 -- and whether this expression uses any of the binders in the
448 -- alternative. Returns an optional new binding and a new expression.
449 doexpr :: CoreExpr -> Bool -> TransformMonad (Maybe (CoreBndr, CoreExpr), CoreExpr)
450 doexpr expr uses_bndrs = do
451 local_var <- Trans.lift $ is_local_var expr
453 -- Extract any expressions that do not use any binders from this
454 -- alternative, is not a local var already and is representable (to
455 -- prevent loops with inlinenonrep).
456 if (not uses_bndrs) && (not local_var) && repr
458 id <- Trans.lift $ mkBinderFor expr "caseval"
459 -- We don't flag a change here, since casevalsimpl will do that above
460 -- based on Just we return here.
461 return $ (Just (id, expr), Var id)
463 -- Don't simplify anything else
464 return (Nothing, expr)
465 -- Leave all other expressions unchanged
466 casesimpl expr = return expr
467 -- Perform this transform everywhere
468 casesimpltop = everywhere ("casesimpl", casesimpl)
470 --------------------------------
472 --------------------------------
473 -- Remove case statements that have only a single alternative and only wild
475 caseremove, caseremovetop :: Transform
476 -- Replace a useless case by the value of its single alternative
477 caseremove (Case scrut b ty [(con, bndrs, expr)]) | not usesvars = change expr
478 -- Find if any of the binders are used by expr
479 where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` bndrs))) expr
480 -- Leave all other expressions unchanged
481 caseremove expr = return expr
482 -- Perform this transform everywhere
483 caseremovetop = everywhere ("caseremove", caseremove)
485 --------------------------------
486 -- Argument extraction
487 --------------------------------
488 -- Make sure that all arguments of a representable type are simple variables.
489 appsimpl, appsimpltop :: Transform
490 -- Simplify all representable arguments. Do this by introducing a new Let
491 -- that binds the argument and passing the new binder in the application.
492 appsimpl expr@(App f arg) = do
493 -- Check runtime representability
495 local_var <- Trans.lift $ is_local_var arg
496 if repr && not local_var
497 then do -- Extract representable arguments
498 id <- Trans.lift $ mkBinderFor arg "arg"
499 change $ Let (NonRec id arg) (App f (Var id))
500 else -- Leave non-representable arguments unchanged
502 -- Leave all other expressions unchanged
503 appsimpl expr = return expr
504 -- Perform this transform everywhere
505 appsimpltop = everywhere ("appsimpl", appsimpl)
507 --------------------------------
508 -- Function-typed argument propagation
509 --------------------------------
510 -- Remove all applications to function-typed arguments, by duplication the
511 -- function called with the function-typed parameter replaced by the free
512 -- variables of the argument passed in.
513 argprop, argproptop :: Transform
514 -- Transform any application of a named function (i.e., skip applications of
515 -- lambda's). Also skip applications that have arguments with free type
516 -- variables, since we can't inline those.
517 argprop expr@(App _ _) | is_var fexpr = do
518 -- Find the body of the function called
519 body_maybe <- Trans.lift $ getGlobalBind f
522 -- Process each of the arguments in turn
523 (args', changed) <- Writer.listen $ mapM doarg args
524 -- See if any of the arguments changed
525 case Monoid.getAny changed of
527 let (newargs', newparams', oldargs) = unzip3 args'
528 let newargs = concat newargs'
529 let newparams = concat newparams'
530 -- Create a new body that consists of a lambda for all new arguments and
531 -- the old body applied to some arguments.
532 let newbody = MkCore.mkCoreLams newparams (MkCore.mkCoreApps body oldargs)
533 -- Create a new function with the same name but a new body
534 newf <- Trans.lift $ mkFunction f newbody
535 -- Replace the original application with one of the new function to the
537 change $ MkCore.mkCoreApps (Var newf) newargs
539 -- Don't change the expression if none of the arguments changed
542 -- If we don't have a body for the function called, leave it unchanged (it
543 -- should be a primitive function then).
544 Nothing -> return expr
546 -- Find the function called and the arguments
547 (fexpr, args) = collectArgs expr
550 -- Process a single argument and return (args, bndrs, arg), where args are
551 -- the arguments to replace the given argument in the original
552 -- application, bndrs are the binders to include in the top-level lambda
553 -- in the new function body, and arg is the argument to apply to the old
555 doarg :: CoreExpr -> TransformMonad ([CoreExpr], [CoreBndr], CoreExpr)
558 bndrs <- Trans.lift getGlobalBinders
559 let interesting var = Var.isLocalVar var && (not $ var `elem` bndrs)
560 if not repr && not (is_var arg && interesting (exprToVar arg)) && not (has_free_tyvars arg)
562 -- Propagate all complex arguments that are not representable, but not
563 -- arguments with free type variables (since those would require types
564 -- not known yet, which will always be known eventually).
565 -- Find interesting free variables, each of which should be passed to
566 -- the new function instead of the original function argument.
568 -- Interesting vars are those that are local, but not available from the
569 -- top level scope (functions from this module are defined as local, but
570 -- they're not local to this function, so we can freely move references
571 -- to them into another function).
572 let free_vars = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars interesting arg
573 -- Mark the current expression as changed
575 return (map Var free_vars, free_vars, arg)
577 -- Representable types will not be propagated, and arguments with free
578 -- type variables will be propagated later.
579 -- TODO: preserve original naming?
580 id <- Trans.lift $ mkBinderFor arg "param"
581 -- Just pass the original argument to the new function, which binds it
582 -- to a new id and just pass that new id to the old function body.
583 return ([arg], [id], mkReferenceTo id)
584 -- Leave all other expressions unchanged
585 argprop expr = return expr
586 -- Perform this transform everywhere
587 argproptop = everywhere ("argprop", argprop)
589 --------------------------------
590 -- Function-typed argument extraction
591 --------------------------------
592 -- This transform takes any function-typed argument that cannot be propagated
593 -- (because the function that is applied to it is a builtin function), and
594 -- puts it in a brand new top level binder. This allows us to for example
595 -- apply map to a lambda expression This will not conflict with inlinenonrep,
596 -- since that only inlines local let bindings, not top level bindings.
597 funextract, funextracttop :: Transform
598 funextract expr@(App _ _) | is_var fexpr = do
599 body_maybe <- Trans.lift $ getGlobalBind f
601 -- We don't have a function body for f, so we can perform this transform.
603 -- Find the new arguments
604 args' <- mapM doarg args
605 -- And update the arguments. We use return instead of changed, so the
606 -- changed flag doesn't get set if none of the args got changed.
607 return $ MkCore.mkCoreApps fexpr args'
608 -- We have a function body for f, leave this application to funprop
609 Just _ -> return expr
611 -- Find the function called and the arguments
612 (fexpr, args) = collectArgs expr
614 -- Change any arguments that have a function type, but are not simple yet
615 -- (ie, a variable or application). This means to create a new function
616 -- for map (\f -> ...) b, but not for map (foo a) b.
618 -- We could use is_applicable here instead of is_fun, but I think
619 -- arguments to functions could only have forall typing when existential
620 -- typing is enabled. Not sure, though.
621 doarg arg | not (is_simple arg) && is_fun arg = do
622 -- Create a new top level binding that binds the argument. Its body will
623 -- be extended with lambda expressions, to take any free variables used
624 -- by the argument expression.
625 let free_vars = VarSet.varSetElems $ CoreFVs.exprFreeVars arg
626 let body = MkCore.mkCoreLams free_vars arg
627 id <- Trans.lift $ mkBinderFor body "fun"
628 Trans.lift $ addGlobalBind id body
629 -- Replace the argument with a reference to the new function, applied to
631 change $ MkCore.mkCoreApps (Var id) (map Var free_vars)
632 -- Leave all other arguments untouched
633 doarg arg = return arg
635 -- Leave all other expressions unchanged
636 funextract expr = return expr
637 -- Perform this transform everywhere
638 funextracttop = everywhere ("funextract", funextract)
640 --------------------------------
641 -- Ensure that a function that just returns another function (or rather,
642 -- another top-level binder) is still properly normalized. This is a temporary
643 -- solution, we should probably integrate this pass with lambdasimpl and
645 --------------------------------
646 simplrestop expr@(Lam _ _) = return expr
647 simplrestop expr@(Let _ _) = return expr
648 simplrestop expr = do
649 local_var <- Trans.lift $ is_local_var expr
654 id <- Trans.lift $ mkBinderFor expr "res"
655 change $ Let (NonRec id expr) (Var id)
656 --------------------------------
657 -- End of transformations
658 --------------------------------
663 -- What transforms to run?
664 transforms = [inlinetopleveltop, argproptop, funextracttop, etatop, betatop, castproptop, letremovesimpletop, letderectop, letremovetop, letsimpltop, letflattop, scrutsimpltop, casesimpltop, caseremovetop, inlinenonreptop, appsimpltop, letremoveunusedtop, castsimpltop, lambdasimpltop, simplrestop]
666 -- | Returns the normalized version of the given function.
668 CoreBndr -- ^ The function to get
669 -> TranslatorSession CoreExpr -- The normalized function body
671 getNormalized bndr = Utils.makeCached bndr tsNormalized $ do
672 if is_poly (Var bndr)
674 -- This should really only happen at the top level... TODO: Give
675 -- a different error if this happens down in the recursion.
676 error $ "\nNormalize.normalizeBind: Function " ++ show bndr ++ " is polymorphic, can't normalize"
678 expr <- getBinding bndr
679 normalizeExpr (show bndr) expr
681 -- | Normalize an expression
683 String -- ^ What are we normalizing? For debug output only.
684 -> CoreSyn.CoreExpr -- ^ The expression to normalize
685 -> TranslatorSession CoreSyn.CoreExpr -- ^ The normalized expression
687 normalizeExpr what expr = do
688 -- Normalize this expression
689 trace (what ++ " before normalization:\n\n" ++ showSDoc ( ppr expr ) ++ "\n") $ return ()
690 expr' <- dotransforms transforms expr
691 trace ("\n" ++ what ++ " after normalization:\n\n" ++ showSDoc ( ppr expr')) $ return ()
694 -- | Get the value that is bound to the given binder at top level. Fails when
695 -- there is no such binding.
697 CoreBndr -- ^ The binder to get the expression for
698 -> TranslatorSession CoreExpr -- ^ The value bound to the binder
700 getBinding bndr = Utils.makeCached bndr tsBindings $ do
701 -- If the binding isn't in the "cache" (bindings map), then we can't create
702 -- it out of thin air, so return an error.
703 error $ "Normalize.getBinding: Unknown function requested: " ++ show bndr
705 -- | Split a normalized expression into the argument binders, top level
706 -- bindings and the result binder.
708 CoreExpr -- ^ The normalized expression
709 -> ([CoreBndr], [Binding], CoreBndr)
710 splitNormalized expr = (args, binds, res)
712 (args, letexpr) = CoreSyn.collectBinders expr
713 (binds, resexpr) = flattenLets letexpr
714 res = case resexpr of
716 _ -> error $ "Normalize.splitNormalized: Not in normal form: " ++ pprString expr ++ "\n"