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.Accessor.Monad.Trans.State as MonadState
17 import qualified Data.Monoid as Monoid
18 import qualified Data.Map as Map
22 import qualified CoreUtils
26 import qualified VarSet
27 import qualified CoreFVs
28 import qualified MkCore
29 import Outputable ( showSDoc, ppr, nest )
32 import CLasH.Normalize.NormalizeTypes
33 import CLasH.Translator.TranslatorTypes
34 import CLasH.Normalize.NormalizeTools
35 import qualified CLasH.Utils as Utils
36 import CLasH.Utils.Core.CoreTools
37 import CLasH.Utils.Core.BinderTools
38 import CLasH.Utils.Pretty
40 --------------------------------
41 -- Start of transformations
42 --------------------------------
44 --------------------------------
46 --------------------------------
47 eta, etatop :: Transform
48 eta expr | is_fun expr && not (is_lam expr) = do
49 let arg_ty = (fst . Type.splitFunTy . CoreUtils.exprType) expr
50 id <- Trans.lift $ mkInternalVar "param" arg_ty
51 change (Lam id (App expr (Var id)))
52 -- Leave all other expressions unchanged
54 etatop = notappargs ("eta", eta)
56 --------------------------------
58 --------------------------------
59 beta, betatop :: Transform
60 -- Substitute arg for x in expr. For value lambda's, also clone before
62 beta (App (Lam x expr) arg) | CoreSyn.isTyVar x = setChanged >> substitute x arg expr
63 | otherwise = setChanged >> substitute_clone x arg expr
64 -- Propagate the application into the let
65 beta (App (Let binds expr) arg) = change $ Let binds (App expr arg)
66 -- Propagate the application into each of the alternatives
67 beta (App (Case scrut b ty alts) arg) = change $ Case scrut b ty' alts'
69 alts' = map (\(con, bndrs, expr) -> (con, bndrs, (App expr arg))) alts
70 ty' = CoreUtils.applyTypeToArg ty arg
71 -- Leave all other expressions unchanged
72 beta expr = return expr
73 -- Perform this transform everywhere
74 betatop = everywhere ("beta", beta)
76 --------------------------------
78 --------------------------------
79 -- Try to move casts as much downward as possible.
80 castprop, castproptop :: Transform
81 castprop (Cast (Let binds expr) ty) = change $ Let binds (Cast expr ty)
82 castprop expr@(Cast (Case scrut b _ alts) ty) = change (Case scrut b ty alts')
84 alts' = map (\(con, bndrs, expr) -> (con, bndrs, (Cast expr ty))) alts
85 -- Leave all other expressions unchanged
86 castprop expr = return expr
87 -- Perform this transform everywhere
88 castproptop = everywhere ("castprop", castprop)
90 --------------------------------
91 -- Cast simplification. Mostly useful for state packing and unpacking, but
92 -- perhaps for others as well.
93 --------------------------------
94 castsimpl, castsimpltop :: Transform
95 castsimpl expr@(Cast val ty) = do
96 -- Don't extract values that are already simpl
97 local_var <- Trans.lift $ is_local_var val
98 -- Don't extract values that are not representable, to prevent loops with
101 if (not local_var) && repr
103 -- Generate a binder for the expression
104 id <- Trans.lift $ mkBinderFor val "castval"
105 -- Extract the expression
106 change $ Let (NonRec id val) (Cast (Var id) ty)
109 -- Leave all other expressions unchanged
110 castsimpl expr = return expr
111 -- Perform this transform everywhere
112 castsimpltop = everywhere ("castsimpl", castsimpl)
115 --------------------------------
116 -- Lambda simplication
117 --------------------------------
118 -- Ensure that a lambda always evaluates to a let expressions or a simple
119 -- variable reference.
120 lambdasimpl, lambdasimpltop :: Transform
121 -- Don't simplify a lambda that evaluates to let, since this is already
122 -- normal form (and would cause infinite loops).
123 lambdasimpl expr@(Lam _ (Let _ _)) = return expr
124 -- Put the of a lambda in its own binding, but not when the expression is
125 -- already a local variable, or not representable (to prevent loops with
127 lambdasimpl expr@(Lam bndr res) = do
129 local_var <- Trans.lift $ is_local_var res
130 if not local_var && repr
132 id <- Trans.lift $ mkBinderFor res "res"
133 change $ Lam bndr (Let (NonRec id res) (Var id))
135 -- If the result is already a local var or not representable, don't
139 -- Leave all other expressions unchanged
140 lambdasimpl expr = return expr
141 -- Perform this transform everywhere
142 lambdasimpltop = everywhere ("lambdasimpl", lambdasimpl)
144 --------------------------------
145 -- let derecursification
146 --------------------------------
147 letderec, letderectop :: Transform
148 letderec expr@(Let (Rec binds) res) = case liftable of
149 -- Nothing is liftable, just return
151 -- Something can be lifted, generate a new let expression
152 _ -> change $ mkNonRecLets liftable (Let (Rec nonliftable) res)
154 -- Make a list of all the binders bound in this recursive let
155 bndrs = map fst binds
156 -- See which bindings are liftable
157 (liftable, nonliftable) = List.partition canlift binds
158 -- Any expression that does not use any of the binders in this recursive let
159 -- can be lifted into a nonrec let. It can't use its own binder either,
160 -- since that would mean the binding is self-recursive and should be in a
161 -- single bind recursive let.
162 canlift (bndr, e) = not $ expr_uses_binders bndrs e
163 -- Leave all other expressions unchanged
164 letderec expr = return expr
165 -- Perform this transform everywhere
166 letderectop = everywhere ("letderec", letderec)
168 --------------------------------
169 -- let simplification
170 --------------------------------
171 letsimpl, letsimpltop :: Transform
172 -- Don't simplify a let that evaluates to another let, since this is already
173 -- normal form (and would cause infinite loops with letflat below).
174 letsimpl expr@(Let _ (Let _ _)) = return expr
175 -- Put the "in ..." value of a let in its own binding, but not when the
176 -- expression is already a local variable, or not representable (to prevent loops with inlinenonrep).
177 letsimpl expr@(Let binds res) = do
179 local_var <- Trans.lift $ is_local_var res
180 if not local_var && repr
182 -- If the result is not a local var already (to prevent loops with
183 -- ourselves), extract it.
184 id <- Trans.lift $ mkBinderFor res "foo"
185 change $ Let binds (Let (NonRec id res) (Var id))
187 -- If the result is already a local var, don't extract it.
190 -- Leave all other expressions unchanged
191 letsimpl expr = return expr
192 -- Perform this transform everywhere
193 letsimpltop = everywhere ("letsimpl", letsimpl)
195 --------------------------------
197 --------------------------------
198 -- Takes a let that binds another let, and turns that into two nested lets.
200 -- let b = (let b' = expr' in res') in res
202 -- let b' = expr' in (let b = res' in res)
203 letflat, letflattop :: Transform
204 -- Turn a nonrec let that binds a let into two nested lets.
205 letflat (Let (NonRec b (Let binds res')) res) =
206 change $ Let binds (Let (NonRec b res') res)
207 letflat (Let (Rec binds) expr) = do
208 -- Flatten each binding.
209 binds' <- Utils.concatM $ Monad.mapM flatbind binds
210 -- Return the new let. We don't use change here, since possibly nothing has
211 -- changed. If anything has changed, flatbind has already flagged that
213 return $ Let (Rec binds') expr
215 -- Turns a binding of a let into a multiple bindings, or any other binding
216 -- into a list with just that binding
217 flatbind :: (CoreBndr, CoreExpr) -> TransformMonad [(CoreBndr, CoreExpr)]
218 flatbind (b, Let (Rec binds) expr) = change ((b, expr):binds)
219 flatbind (b, Let (NonRec b' expr') expr) = change [(b, expr), (b', expr')]
220 flatbind (b, expr) = return [(b, expr)]
221 -- Leave all other expressions unchanged
222 letflat expr = return expr
223 -- Perform this transform everywhere
224 letflattop = everywhere ("letflat", letflat)
226 --------------------------------
228 --------------------------------
229 -- Remove empty (recursive) lets
230 letremove, letremovetop :: Transform
231 letremove (Let (Rec []) res) = change res
232 -- Leave all other expressions unchanged
233 letremove expr = return expr
234 -- Perform this transform everywhere
235 letremovetop = everywhere ("letremove", letremove)
237 --------------------------------
238 -- Simple let binding removal
239 --------------------------------
240 -- Remove a = b bindings from let expressions everywhere
241 letremovesimpletop :: Transform
242 letremovesimpletop = everywhere ("letremovesimple", inlinebind (\(b, e) -> Trans.lift $ is_local_var e))
244 --------------------------------
245 -- Unused let binding removal
246 --------------------------------
247 letremoveunused, letremoveunusedtop :: Transform
248 letremoveunused expr@(Let (NonRec b bound) res) = do
249 let used = expr_uses_binders [b] res
253 letremoveunused expr@(Let (Rec binds) res) = do
254 -- Filter out all unused binds.
255 let binds' = filter dobind binds
256 -- Only set the changed flag if binds got removed
257 changeif (length binds' /= length binds) (Let (Rec binds') res)
259 bound_exprs = map snd binds
260 -- For each bind check if the bind is used by res or any of the bound
262 dobind (bndr, _) = any (expr_uses_binders [bndr]) (res:bound_exprs)
263 -- Leave all other expressions unchanged
264 letremoveunused expr = return expr
265 letremoveunusedtop = everywhere ("letremoveunused", letremoveunused)
268 --------------------------------
269 -- Identical let binding merging
270 --------------------------------
271 -- Merge two bindings in a let if they are identical
272 -- TODO: We would very much like to use GHC's CSE module for this, but that
273 -- doesn't track if something changed or not, so we can't use it properly.
274 letmerge, letmergetop :: Transform
275 letmerge expr@(Let _ _) = do
276 let (binds, res) = flattenLets expr
277 binds' <- domerge binds
278 return $ mkNonRecLets binds' res
280 domerge :: [(CoreBndr, CoreExpr)] -> TransformMonad [(CoreBndr, CoreExpr)]
281 domerge [] = return []
283 es' <- mapM (mergebinds e) es
287 -- Uses the second bind to simplify the second bind, if applicable.
288 mergebinds :: (CoreBndr, CoreExpr) -> (CoreBndr, CoreExpr) -> TransformMonad (CoreBndr, CoreExpr)
289 mergebinds (b1, e1) (b2, e2)
290 -- Identical expressions? Replace the second binding with a reference to
292 | CoreUtils.cheapEqExpr e1 e2 = change $ (b2, Var b1)
293 -- Different expressions? Don't change
294 | otherwise = return (b2, e2)
295 -- Leave all other expressions unchanged
296 letmerge expr = return expr
297 letmergetop = everywhere ("letmerge", letmerge)
300 --------------------------------
301 -- Non-representable binding inlining
302 --------------------------------
303 -- Remove a = B bindings, with B of a non-representable type, from let
304 -- expressions everywhere. This means that any value that we can't generate a
305 -- signal for, will be inlined and hopefully turned into something we can
308 -- This is a tricky function, which is prone to create loops in the
309 -- transformations. To fix this, we make sure that no transformation will
310 -- create a new let binding with a non-representable type. These other
311 -- transformations will just not work on those function-typed values at first,
312 -- but the other transformations (in particular β-reduction) should make sure
313 -- that the type of those values eventually becomes representable.
314 inlinenonreptop :: Transform
315 inlinenonreptop = everywhere ("inlinenonrep", inlinebind ((Monad.liftM not) . isRepr . snd))
317 --------------------------------
318 -- Top level function inlining
319 --------------------------------
320 -- This transformation inlines top level bindings that have been generated by
321 -- the compiler and are really simple. Really simple currently means that the
322 -- normalized form only contains a single binding, which catches most of the
323 -- cases where a top level function is created that simply calls a type class
324 -- method with a type and dictionary argument, e.g.
325 -- fromInteger = GHC.Num.fromInteger (SizedWord D8) $dNum
326 -- which is later called using simply
327 -- fromInteger (smallInteger 10)
328 -- By inlining such calls to simple, compiler generated functions, we prevent
329 -- huge amounts of trivial components in the VHDL output, which the user never
330 -- wanted. We never inline user-defined functions, since we want to preserve
331 -- all structure defined by the user. Currently this includes all functions
332 -- that were created by funextract, since we would get loops otherwise.
334 -- Note that "defined by the compiler" isn't completely watertight, since GHC
335 -- doesn't seem to set all those names as "system names", we apply some
337 inlinetoplevel, inlinetopleveltop :: Transform
338 -- Any system name is candidate for inlining. Never inline user-defined
339 -- functions, to preserve structure.
340 inlinetoplevel expr@(Var f) | not $ isUserDefined f = do
341 norm_maybe <- Trans.lift $ getNormalized_maybe f
343 -- No body or not normalizeable.
344 Nothing -> return expr
345 Just norm -> if needsInline norm then do
346 -- Regenerate all uniques in the to-be-inlined expression
347 norm_uniqued <- Trans.lift $ genUniques norm
348 -- And replace the variable reference with the unique'd body.
354 -- Leave all other expressions unchanged
355 inlinetoplevel expr = return expr
356 inlinetopleveltop = everywhere ("inlinetoplevel", inlinetoplevel)
358 needsInline :: CoreExpr -> Bool
359 needsInline expr = case splitNormalized expr of
360 -- Inline any function that only has a single definition, it is probably
361 -- simple enough. This might inline some stuff that it shouldn't though it
362 -- will never inline user-defined functions (inlinetoplevel only tries
363 -- system names) and inlining should never break things.
364 (args, [bind], res) -> True
367 --------------------------------
368 -- Scrutinee simplification
369 --------------------------------
370 scrutsimpl,scrutsimpltop :: Transform
371 -- Don't touch scrutinees that are already simple
372 scrutsimpl expr@(Case (Var _) _ _ _) = return expr
373 -- Replace all other cases with a let that binds the scrutinee and a new
374 -- simple scrutinee, but only when the scrutinee is representable (to prevent
375 -- loops with inlinenonrep, though I don't think a non-representable scrutinee
376 -- will be supported anyway...)
377 scrutsimpl expr@(Case scrut b ty alts) = do
381 id <- Trans.lift $ mkBinderFor scrut "scrut"
382 change $ Let (NonRec id scrut) (Case (Var id) b ty alts)
385 -- Leave all other expressions unchanged
386 scrutsimpl expr = return expr
387 -- Perform this transform everywhere
388 scrutsimpltop = everywhere ("scrutsimpl", scrutsimpl)
390 --------------------------------
391 -- Scrutinee binder removal
392 --------------------------------
393 -- A case expression can have an extra binder, to which the scrutinee is bound
394 -- after bringing it to WHNF. This is used for forcing evaluation of strict
395 -- arguments. Since strictness does not matter for us (rather, everything is
396 -- sort of strict), this binder is ignored when generating VHDL, and must thus
397 -- be wild in the normal form.
398 scrutbndrremove, scrutbndrremovetop :: Transform
399 -- If the scrutinee is already simple, and the bndr is not wild yet, replace
400 -- all occurences of the binder with the scrutinee variable.
401 scrutbndrremove (Case (Var scrut) bndr ty alts) | bndr_used = do
402 alts' <- mapM subs_bndr alts
403 change $ Case (Var scrut) wild ty alts'
405 is_used (_, _, expr) = expr_uses_binders [bndr] expr
406 bndr_used = or $ map is_used alts
407 subs_bndr (con, bndrs, expr) = do
408 expr' <- substitute bndr (Var scrut) expr
409 return (con, bndrs, expr')
410 wild = MkCore.mkWildBinder (Id.idType bndr)
411 -- Leave all other expressions unchanged
412 scrutbndrremove expr = return expr
413 scrutbndrremovetop = everywhere ("scrutbndrremove", scrutbndrremove)
415 --------------------------------
416 -- Case binder wildening
417 --------------------------------
418 casesimpl, casesimpltop :: Transform
419 -- This is already a selector case (or, if x does not appear in bndrs, a very
420 -- simple case statement that will be removed by caseremove below). Just leave
422 casesimpl expr@(Case scrut b ty [(con, bndrs, Var x)]) = return expr
423 -- Make sure that all case alternatives have only wild binders and simple
425 -- This is done by creating a new let binding for each non-wild binder, which
426 -- is bound to a new simple selector case statement and for each complex
427 -- expression. We do this only for representable types, to prevent loops with
429 casesimpl expr@(Case scrut b ty alts) = do
430 (bindingss, alts') <- (Monad.liftM unzip) $ mapM doalt alts
431 let bindings = concat bindingss
432 -- Replace the case with a let with bindings and a case
433 let newlet = mkNonRecLets bindings (Case scrut b ty alts')
434 -- If there are no non-wild binders, or this case is already a simple
435 -- selector (i.e., a single alt with exactly one binding), already a simple
436 -- selector altan no bindings (i.e., no wild binders in the original case),
437 -- don't change anything, otherwise, replace the case.
438 if null bindings then return expr else change newlet
440 -- Generate a single wild binder, since they are all the same
441 wild = MkCore.mkWildBinder
442 -- Wilden the binders of one alt, producing a list of bindings as a
444 doalt :: CoreAlt -> TransformMonad ([(CoreBndr, CoreExpr)], CoreAlt)
445 doalt (con, bndrs, expr) = do
446 -- Make each binder wild, if possible
447 bndrs_res <- Monad.zipWithM dobndr bndrs [0..]
448 let (newbndrs, bindings_maybe) = unzip bndrs_res
449 -- Extract a complex expression, if possible. For this we check if any of
450 -- the new list of bndrs are used by expr. We can't use free_vars here,
451 -- since that looks at the old bndrs.
452 let uses_bndrs = not $ VarSet.isEmptyVarSet $ CoreFVs.exprSomeFreeVars (`elem` newbndrs) expr
453 (exprbinding_maybe, expr') <- doexpr expr uses_bndrs
454 -- Create a new alternative
455 let newalt = (con, newbndrs, expr')
456 let bindings = Maybe.catMaybes (bindings_maybe ++ [exprbinding_maybe])
457 return (bindings, newalt)
459 -- Make wild alternatives for each binder
460 wildbndrs = map (\bndr -> MkCore.mkWildBinder (Id.idType bndr)) bndrs
461 -- A set of all the binders that are used by the expression
462 free_vars = CoreFVs.exprSomeFreeVars (`elem` bndrs) expr
463 -- Look at the ith binder in the case alternative. Return a new binder
464 -- for it (either the same one, or a wild one) and optionally a let
465 -- binding containing a case expression.
466 dobndr :: CoreBndr -> Int -> TransformMonad (CoreBndr, Maybe (CoreBndr, CoreExpr))
469 -- Is b wild (e.g., not a free var of expr. Since b is only in scope
470 -- in expr, this means that b is unused if expr does not use it.)
471 let wild = not (VarSet.elemVarSet b free_vars)
472 -- Create a new binding for any representable binder that is not
473 -- already wild and is representable (to prevent loops with
475 if (not wild) && repr
477 -- Create on new binder that will actually capture a value in this
478 -- case statement, and return it.
479 let bty = (Id.idType b)
480 id <- Trans.lift $ mkInternalVar "sel" bty
481 let binders = take i wildbndrs ++ [id] ++ drop (i+1) wildbndrs
482 let caseexpr = Case scrut b bty [(con, binders, Var id)]
483 return (wildbndrs!!i, Just (b, caseexpr))
485 -- Just leave the original binder in place, and don't generate an
486 -- extra selector case.
488 -- Process the expression of a case alternative. Accepts an expression
489 -- and whether this expression uses any of the binders in the
490 -- alternative. Returns an optional new binding and a new expression.
491 doexpr :: CoreExpr -> Bool -> TransformMonad (Maybe (CoreBndr, CoreExpr), CoreExpr)
492 doexpr expr uses_bndrs = do
493 local_var <- Trans.lift $ is_local_var expr
495 -- Extract any expressions that do not use any binders from this
496 -- alternative, is not a local var already and is representable (to
497 -- prevent loops with inlinenonrep).
498 if (not uses_bndrs) && (not local_var) && repr
500 id <- Trans.lift $ mkBinderFor expr "caseval"
501 -- We don't flag a change here, since casevalsimpl will do that above
502 -- based on Just we return here.
503 return (Just (id, expr), Var id)
505 -- Don't simplify anything else
506 return (Nothing, expr)
507 -- Leave all other expressions unchanged
508 casesimpl expr = return expr
509 -- Perform this transform everywhere
510 casesimpltop = everywhere ("casesimpl", casesimpl)
512 --------------------------------
514 --------------------------------
515 -- Remove case statements that have only a single alternative and only wild
517 caseremove, caseremovetop :: Transform
518 -- Replace a useless case by the value of its single alternative
519 caseremove (Case scrut b ty [(con, bndrs, expr)]) | not usesvars = change expr
520 -- Find if any of the binders are used by expr
521 where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` bndrs))) expr
522 -- Leave all other expressions unchanged
523 caseremove expr = return expr
524 -- Perform this transform everywhere
525 caseremovetop = everywhere ("caseremove", caseremove)
527 --------------------------------
528 -- Argument extraction
529 --------------------------------
530 -- Make sure that all arguments of a representable type are simple variables.
531 appsimpl, appsimpltop :: Transform
532 -- Simplify all representable arguments. Do this by introducing a new Let
533 -- that binds the argument and passing the new binder in the application.
534 appsimpl expr@(App f arg) = do
535 -- Check runtime representability
537 local_var <- Trans.lift $ is_local_var arg
538 if repr && not local_var
539 then do -- Extract representable arguments
540 id <- Trans.lift $ mkBinderFor arg "arg"
541 change $ Let (NonRec id arg) (App f (Var id))
542 else -- Leave non-representable arguments unchanged
544 -- Leave all other expressions unchanged
545 appsimpl expr = return expr
546 -- Perform this transform everywhere
547 appsimpltop = everywhere ("appsimpl", appsimpl)
549 --------------------------------
550 -- Function-typed argument propagation
551 --------------------------------
552 -- Remove all applications to function-typed arguments, by duplication the
553 -- function called with the function-typed parameter replaced by the free
554 -- variables of the argument passed in.
555 argprop, argproptop :: Transform
556 -- Transform any application of a named function (i.e., skip applications of
557 -- lambda's). Also skip applications that have arguments with free type
558 -- variables, since we can't inline those.
559 argprop expr@(App _ _) | is_var fexpr = do
560 -- Find the body of the function called
561 body_maybe <- Trans.lift $ getGlobalBind f
564 -- Process each of the arguments in turn
565 (args', changed) <- Writer.listen $ mapM doarg args
566 -- See if any of the arguments changed
567 case Monoid.getAny changed of
569 let (newargs', newparams', oldargs) = unzip3 args'
570 let newargs = concat newargs'
571 let newparams = concat newparams'
572 -- Create a new body that consists of a lambda for all new arguments and
573 -- the old body applied to some arguments.
574 let newbody = MkCore.mkCoreLams newparams (MkCore.mkCoreApps body oldargs)
575 -- Create a new function with the same name but a new body
576 newf <- Trans.lift $ mkFunction f newbody
578 Trans.lift $ MonadState.modify tsInitStates (\ismap ->
579 let init_state_maybe = Map.lookup f ismap in
580 case init_state_maybe of
582 Just init_state -> Map.insert newf init_state ismap)
583 -- Replace the original application with one of the new function to the
585 change $ MkCore.mkCoreApps (Var newf) newargs
587 -- Don't change the expression if none of the arguments changed
590 -- If we don't have a body for the function called, leave it unchanged (it
591 -- should be a primitive function then).
592 Nothing -> return expr
594 -- Find the function called and the arguments
595 (fexpr, args) = collectArgs expr
598 -- Process a single argument and return (args, bndrs, arg), where args are
599 -- the arguments to replace the given argument in the original
600 -- application, bndrs are the binders to include in the top-level lambda
601 -- in the new function body, and arg is the argument to apply to the old
603 doarg :: CoreExpr -> TransformMonad ([CoreExpr], [CoreBndr], CoreExpr)
606 bndrs <- Trans.lift getGlobalBinders
607 let interesting var = Var.isLocalVar var && (var `notElem` bndrs)
608 if not repr && not (is_var arg && interesting (exprToVar arg)) && not (has_free_tyvars arg)
610 -- Propagate all complex arguments that are not representable, but not
611 -- arguments with free type variables (since those would require types
612 -- not known yet, which will always be known eventually).
613 -- Find interesting free variables, each of which should be passed to
614 -- the new function instead of the original function argument.
616 -- Interesting vars are those that are local, but not available from the
617 -- top level scope (functions from this module are defined as local, but
618 -- they're not local to this function, so we can freely move references
619 -- to them into another function).
620 let free_vars = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars interesting arg
621 -- Mark the current expression as changed
623 -- TODO: Clone the free_vars (and update references in arg), since
624 -- this might cause conflicts if two arguments that are propagated
625 -- share a free variable. Also, we are now introducing new variables
626 -- into a function that are not fresh, which violates the binder
627 -- uniqueness invariant.
628 return (map Var free_vars, free_vars, arg)
630 -- Representable types will not be propagated, and arguments with free
631 -- type variables will be propagated later.
632 -- Note that we implicitly remove any type variables in the type of
633 -- the original argument by using the type of the actual argument
634 -- for the new formal parameter.
635 -- TODO: preserve original naming?
636 id <- Trans.lift $ mkBinderFor arg "param"
637 -- Just pass the original argument to the new function, which binds it
638 -- to a new id and just pass that new id to the old function body.
639 return ([arg], [id], mkReferenceTo id)
640 -- Leave all other expressions unchanged
641 argprop expr = return expr
642 -- Perform this transform everywhere
643 argproptop = everywhere ("argprop", argprop)
645 --------------------------------
646 -- Function-typed argument extraction
647 --------------------------------
648 -- This transform takes any function-typed argument that cannot be propagated
649 -- (because the function that is applied to it is a builtin function), and
650 -- puts it in a brand new top level binder. This allows us to for example
651 -- apply map to a lambda expression This will not conflict with inlinenonrep,
652 -- since that only inlines local let bindings, not top level bindings.
653 funextract, funextracttop :: Transform
654 funextract expr@(App _ _) | is_var fexpr = do
655 body_maybe <- Trans.lift $ getGlobalBind f
657 -- We don't have a function body for f, so we can perform this transform.
659 -- Find the new arguments
660 args' <- mapM doarg args
661 -- And update the arguments. We use return instead of changed, so the
662 -- changed flag doesn't get set if none of the args got changed.
663 return $ MkCore.mkCoreApps fexpr args'
664 -- We have a function body for f, leave this application to funprop
665 Just _ -> return expr
667 -- Find the function called and the arguments
668 (fexpr, args) = collectArgs expr
670 -- Change any arguments that have a function type, but are not simple yet
671 -- (ie, a variable or application). This means to create a new function
672 -- for map (\f -> ...) b, but not for map (foo a) b.
674 -- We could use is_applicable here instead of is_fun, but I think
675 -- arguments to functions could only have forall typing when existential
676 -- typing is enabled. Not sure, though.
677 doarg arg | not (is_simple arg) && is_fun arg = do
678 -- Create a new top level binding that binds the argument. Its body will
679 -- be extended with lambda expressions, to take any free variables used
680 -- by the argument expression.
681 let free_vars = VarSet.varSetElems $ CoreFVs.exprFreeVars arg
682 let body = MkCore.mkCoreLams free_vars arg
683 id <- Trans.lift $ mkBinderFor body "fun"
684 Trans.lift $ addGlobalBind id body
685 -- Replace the argument with a reference to the new function, applied to
687 change $ MkCore.mkCoreApps (Var id) (map Var free_vars)
688 -- Leave all other arguments untouched
689 doarg arg = return arg
691 -- Leave all other expressions unchanged
692 funextract expr = return expr
693 -- Perform this transform everywhere
694 funextracttop = everywhere ("funextract", funextract)
696 --------------------------------
697 -- Ensure that a function that just returns another function (or rather,
698 -- another top-level binder) is still properly normalized. This is a temporary
699 -- solution, we should probably integrate this pass with lambdasimpl and
701 --------------------------------
702 simplrestop expr@(Lam _ _) = return expr
703 simplrestop expr@(Let _ _) = return expr
704 simplrestop expr = do
705 local_var <- Trans.lift $ is_local_var expr
706 -- Don't extract values that are not representable, to prevent loops with
709 if local_var || not repr
713 id <- Trans.lift $ mkBinderFor expr "res"
714 change $ Let (NonRec id expr) (Var id)
715 --------------------------------
716 -- End of transformations
717 --------------------------------
722 -- What transforms to run?
723 transforms = [inlinetopleveltop, argproptop, funextracttop, etatop, betatop, castproptop, letremovesimpletop, letderectop, letremovetop, letsimpltop, letflattop, scrutsimpltop, scrutbndrremovetop, casesimpltop, caseremovetop, inlinenonreptop, appsimpltop, letremoveunusedtop, castsimpltop, lambdasimpltop, simplrestop]
725 -- | Returns the normalized version of the given function, or an error
726 -- if it is not a known global binder.
728 CoreBndr -- ^ The function to get
729 -> TranslatorSession CoreExpr -- The normalized function body
730 getNormalized bndr = do
731 norm <- getNormalized_maybe bndr
732 return $ Maybe.fromMaybe
733 (error $ "Normalize.getNormalized: Unknown or non-representable function requested: " ++ show bndr)
736 -- | Returns the normalized version of the given function, or Nothing
737 -- when the binder is not a known global binder or is not normalizeable.
738 getNormalized_maybe ::
739 CoreBndr -- ^ The function to get
740 -> TranslatorSession (Maybe CoreExpr) -- The normalized function body
742 getNormalized_maybe bndr = do
743 expr_maybe <- getGlobalBind bndr
744 normalizeable <- isNormalizeable' bndr
745 if not normalizeable || Maybe.isNothing expr_maybe
747 -- Binder not normalizeable or not found
749 else if is_poly (Var bndr)
751 -- This should really only happen at the top level... TODO: Give
752 -- a different error if this happens down in the recursion.
753 error $ "\nNormalize.normalizeBind: Function " ++ show bndr ++ " is polymorphic, can't normalize"
755 -- Binder found and is monomorphic. Normalize the expression
756 -- and cache the result.
757 normalized <- Utils.makeCached bndr tsNormalized $
758 normalizeExpr (show bndr) (Maybe.fromJust expr_maybe)
759 return (Just normalized)
761 -- | Normalize an expression
763 String -- ^ What are we normalizing? For debug output only.
764 -> CoreSyn.CoreExpr -- ^ The expression to normalize
765 -> TranslatorSession CoreSyn.CoreExpr -- ^ The normalized expression
767 normalizeExpr what expr = do
768 expr_uniqued <- genUniques expr
769 -- Normalize this expression
770 trace (what ++ " before normalization:\n\n" ++ showSDoc ( ppr expr_uniqued ) ++ "\n") $ return ()
771 expr' <- dotransforms transforms expr_uniqued
772 trace ("\n" ++ what ++ " after normalization:\n\n" ++ showSDoc ( ppr expr')) $ return ()
775 -- | Split a normalized expression into the argument binders, top level
776 -- bindings and the result binder.
778 CoreExpr -- ^ The normalized expression
779 -> ([CoreBndr], [Binding], CoreBndr)
780 splitNormalized expr = (args, binds, res)
782 (args, letexpr) = CoreSyn.collectBinders expr
783 (binds, resexpr) = flattenLets letexpr
784 res = case resexpr of
786 _ -> error $ "Normalize.splitNormalized: Not in normal form: " ++ pprString expr ++ "\n"