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. For value lambda's, also clone before
69 beta (App (Lam x expr) arg) | CoreSyn.isTyVar x = setChanged >> substitute x arg expr
70 | otherwise = setChanged >> substitute_clone x arg expr
71 -- Propagate the application into the let
72 beta (App (Let binds expr) arg) = change $ Let binds (App expr arg)
73 -- Propagate the application into each of the alternatives
74 beta (App (Case scrut b ty alts) arg) = change $ Case scrut b ty' alts'
76 alts' = map (\(con, bndrs, expr) -> (con, bndrs, (App expr arg))) alts
77 ty' = CoreUtils.applyTypeToArg ty arg
78 -- Leave all other expressions unchanged
79 beta expr = return expr
80 -- Perform this transform everywhere
81 betatop = everywhere ("beta", beta)
83 --------------------------------
85 --------------------------------
86 -- Try to move casts as much downward as possible.
87 castprop, castproptop :: Transform
88 castprop (Cast (Let binds expr) ty) = change $ Let binds (Cast expr ty)
89 castprop expr@(Cast (Case scrut b _ alts) ty) = change (Case scrut b ty alts')
91 alts' = map (\(con, bndrs, expr) -> (con, bndrs, (Cast expr ty))) alts
92 -- Leave all other expressions unchanged
93 castprop expr = return expr
94 -- Perform this transform everywhere
95 castproptop = everywhere ("castprop", castprop)
97 --------------------------------
98 -- Cast simplification. Mostly useful for state packing and unpacking, but
99 -- perhaps for others as well.
100 --------------------------------
101 castsimpl, castsimpltop :: Transform
102 castsimpl expr@(Cast val ty) = do
103 -- Don't extract values that are already simpl
104 local_var <- Trans.lift $ is_local_var val
105 -- Don't extract values that are not representable, to prevent loops with
108 if (not local_var) && repr
110 -- Generate a binder for the expression
111 id <- Trans.lift $ mkBinderFor val "castval"
112 -- Extract the expression
113 change $ Let (NonRec id val) (Cast (Var id) ty)
116 -- Leave all other expressions unchanged
117 castsimpl expr = return expr
118 -- Perform this transform everywhere
119 castsimpltop = everywhere ("castsimpl", castsimpl)
122 --------------------------------
123 -- Lambda simplication
124 --------------------------------
125 -- Ensure that a lambda always evaluates to a let expressions or a simple
126 -- variable reference.
127 lambdasimpl, lambdasimpltop :: Transform
128 -- Don't simplify a lambda that evaluates to let, since this is already
129 -- normal form (and would cause infinite loops).
130 lambdasimpl expr@(Lam _ (Let _ _)) = return expr
131 -- Put the of a lambda in its own binding, but not when the expression is
132 -- already a local variable, or not representable (to prevent loops with
134 lambdasimpl expr@(Lam bndr res) = do
136 local_var <- Trans.lift $ is_local_var res
137 if not local_var && repr
139 id <- Trans.lift $ mkBinderFor res "res"
140 change $ Lam bndr (Let (NonRec id res) (Var id))
142 -- If the result is already a local var or not representable, don't
146 -- Leave all other expressions unchanged
147 lambdasimpl expr = return expr
148 -- Perform this transform everywhere
149 lambdasimpltop = everywhere ("lambdasimpl", lambdasimpl)
151 --------------------------------
152 -- let derecursification
153 --------------------------------
154 letderec, letderectop :: Transform
155 letderec expr@(Let (Rec binds) res) = case liftable of
156 -- Nothing is liftable, just return
158 -- Something can be lifted, generate a new let expression
159 _ -> change $ mkNonRecLets liftable (Let (Rec nonliftable) res)
161 -- Make a list of all the binders bound in this recursive let
162 bndrs = map fst binds
163 -- See which bindings are liftable
164 (liftable, nonliftable) = List.partition canlift binds
165 -- Any expression that does not use any of the binders in this recursive let
166 -- can be lifted into a nonrec let. It can't use its own binder either,
167 -- since that would mean the binding is self-recursive and should be in a
168 -- single bind recursive let.
169 canlift (bndr, e) = not $ expr_uses_binders bndrs e
170 -- Leave all other expressions unchanged
171 letderec expr = return expr
172 -- Perform this transform everywhere
173 letderectop = everywhere ("letderec", letderec)
175 --------------------------------
176 -- let simplification
177 --------------------------------
178 letsimpl, letsimpltop :: Transform
179 -- Don't simplify a let that evaluates to another let, since this is already
180 -- normal form (and would cause infinite loops with letflat below).
181 letsimpl expr@(Let _ (Let _ _)) = return expr
182 -- Put the "in ..." value of a let in its own binding, but not when the
183 -- expression is already a local variable, or not representable (to prevent loops with inlinenonrep).
184 letsimpl expr@(Let binds res) = do
186 local_var <- Trans.lift $ is_local_var res
187 if not local_var && repr
189 -- If the result is not a local var already (to prevent loops with
190 -- ourselves), extract it.
191 id <- Trans.lift $ mkBinderFor res "foo"
192 change $ Let binds (Let (NonRec id res) (Var id))
194 -- If the result is already a local var, don't extract it.
197 -- Leave all other expressions unchanged
198 letsimpl expr = return expr
199 -- Perform this transform everywhere
200 letsimpltop = everywhere ("letsimpl", letsimpl)
202 --------------------------------
204 --------------------------------
205 -- Takes a let that binds another let, and turns that into two nested lets.
207 -- let b = (let b' = expr' in res') in res
209 -- let b' = expr' in (let b = res' in res)
210 letflat, letflattop :: Transform
211 -- Turn a nonrec let that binds a let into two nested lets.
212 letflat (Let (NonRec b (Let binds res')) res) =
213 change $ Let binds (Let (NonRec b res') res)
214 letflat (Let (Rec binds) expr) = do
215 -- Flatten each binding.
216 binds' <- Utils.concatM $ Monad.mapM flatbind binds
217 -- Return the new let. We don't use change here, since possibly nothing has
218 -- changed. If anything has changed, flatbind has already flagged that
220 return $ Let (Rec binds') expr
222 -- Turns a binding of a let into a multiple bindings, or any other binding
223 -- into a list with just that binding
224 flatbind :: (CoreBndr, CoreExpr) -> TransformMonad [(CoreBndr, CoreExpr)]
225 flatbind (b, Let (Rec binds) expr) = change ((b, expr):binds)
226 flatbind (b, Let (NonRec b' expr') expr) = change [(b, expr), (b', expr')]
227 flatbind (b, expr) = return [(b, expr)]
228 -- Leave all other expressions unchanged
229 letflat expr = return expr
230 -- Perform this transform everywhere
231 letflattop = everywhere ("letflat", letflat)
233 --------------------------------
235 --------------------------------
236 -- Remove empty (recursive) lets
237 letremove, letremovetop :: Transform
238 letremove (Let (Rec []) res) = change $ res
239 -- Leave all other expressions unchanged
240 letremove expr = return expr
241 -- Perform this transform everywhere
242 letremovetop = everywhere ("letremove", letremove)
244 --------------------------------
245 -- Simple let binding removal
246 --------------------------------
247 -- Remove a = b bindings from let expressions everywhere
248 letremovesimpletop :: Transform
249 letremovesimpletop = everywhere ("letremovesimple", inlinebind (\(b, e) -> Trans.lift $ is_local_var e))
251 --------------------------------
252 -- Unused let binding removal
253 --------------------------------
254 letremoveunused, letremoveunusedtop :: Transform
255 letremoveunused expr@(Let (NonRec b bound) res) = do
256 let used = expr_uses_binders [b] res
260 letremoveunused expr@(Let (Rec binds) res) = do
261 -- Filter out all unused binds.
262 let binds' = filter dobind binds
263 -- Only set the changed flag if binds got removed
264 changeif (length binds' /= length binds) (Let (Rec binds') res)
266 bound_exprs = map snd binds
267 -- For each bind check if the bind is used by res or any of the bound
269 dobind (bndr, _) = any (expr_uses_binders [bndr]) (res:bound_exprs)
270 -- Leave all other expressions unchanged
271 letremoveunused expr = return expr
272 letremoveunusedtop = everywhere ("letremoveunused", letremoveunused)
275 --------------------------------
276 -- Identical let binding merging
277 --------------------------------
278 -- Merge two bindings in a let if they are identical
279 -- TODO: We would very much like to use GHC's CSE module for this, but that
280 -- doesn't track if something changed or not, so we can't use it properly.
281 letmerge, letmergetop :: Transform
282 letmerge expr@(Let _ _) = do
283 let (binds, res) = flattenLets expr
284 binds' <- domerge binds
285 return $ mkNonRecLets binds' res
287 domerge :: [(CoreBndr, CoreExpr)] -> TransformMonad [(CoreBndr, CoreExpr)]
288 domerge [] = return []
290 es' <- mapM (mergebinds e) es
294 -- Uses the second bind to simplify the second bind, if applicable.
295 mergebinds :: (CoreBndr, CoreExpr) -> (CoreBndr, CoreExpr) -> TransformMonad (CoreBndr, CoreExpr)
296 mergebinds (b1, e1) (b2, e2)
297 -- Identical expressions? Replace the second binding with a reference to
299 | CoreUtils.cheapEqExpr e1 e2 = change $ (b2, Var b1)
300 -- Different expressions? Don't change
301 | otherwise = return (b2, e2)
302 -- Leave all other expressions unchanged
303 letmerge expr = return expr
304 letmergetop = everywhere ("letmerge", letmerge)
307 --------------------------------
309 --------------------------------
310 -- Remove a = B bindings, with B :: a -> b, or B :: forall x . T, from let
311 -- expressions everywhere. This means that any value that still needs to be
312 -- applied to something else (polymorphic values need to be applied to a
313 -- Type) will be inlined, and will eventually be applied to all their
316 -- This is a tricky function, which is prone to create loops in the
317 -- transformations. To fix this, we make sure that no transformation will
318 -- create a new let binding with a function type. These other transformations
319 -- will just not work on those function-typed values at first, but the other
320 -- transformations (in particular β-reduction) should make sure that the type
321 -- of those values eventually becomes primitive.
322 inlinenonreptop :: Transform
323 inlinenonreptop = everywhere ("inlinenonrep", inlinebind ((Monad.liftM not) . isRepr . snd))
325 inlinetoplevel, inlinetopleveltop :: Transform
326 -- Any system name is candidate for inlining. Never inline user-defined
327 -- functions, to preserve structure.
328 inlinetoplevel expr@(Var f) | not $ isUserDefined f = do
329 norm <- isNormalizeable f
330 -- See if this is a top level binding for which we have a body
331 body_maybe <- Trans.lift $ getGlobalBind f
332 if norm && Maybe.isJust body_maybe
334 -- Get the normalized version
335 norm <- Trans.lift $ getNormalized f
338 -- Regenerate all uniques in the to-be-inlined expression
339 norm_uniqued <- Trans.lift $ genUniques norm
344 -- No body or not normalizeable.
346 -- Leave all other expressions unchanged
347 inlinetoplevel expr = return expr
348 inlinetopleveltop = everywhere ("inlinetoplevel", inlinetoplevel)
350 needsInline :: CoreExpr -> Bool
351 needsInline expr = case splitNormalized expr of
352 -- Inline any function that only has a single definition, it is probably
353 -- simple enough. This might inline some stuff that it shouldn't though it
354 -- will never inline user-defined functions (inlinetoplevel only tries
355 -- system names) and inlining should never break things.
356 (args, [bind], res) -> True
359 --------------------------------
360 -- Scrutinee simplification
361 --------------------------------
362 scrutsimpl,scrutsimpltop :: Transform
363 -- Don't touch scrutinees that are already simple
364 scrutsimpl expr@(Case (Var _) _ _ _) = return expr
365 -- Replace all other cases with a let that binds the scrutinee and a new
366 -- simple scrutinee, but only when the scrutinee is representable (to prevent
367 -- loops with inlinenonrep, though I don't think a non-representable scrutinee
368 -- will be supported anyway...)
369 scrutsimpl expr@(Case scrut b ty alts) = do
373 id <- Trans.lift $ mkBinderFor scrut "scrut"
374 change $ Let (NonRec id scrut) (Case (Var id) b ty alts)
377 -- Leave all other expressions unchanged
378 scrutsimpl expr = return expr
379 -- Perform this transform everywhere
380 scrutsimpltop = everywhere ("scrutsimpl", scrutsimpl)
382 --------------------------------
383 -- Case binder wildening
384 --------------------------------
385 casesimpl, casesimpltop :: Transform
386 -- This is already a selector case (or, if x does not appear in bndrs, a very
387 -- simple case statement that will be removed by caseremove below). Just leave
389 casesimpl expr@(Case scrut b ty [(con, bndrs, Var x)]) = return expr
390 -- Make sure that all case alternatives have only wild binders and simple
392 -- This is done by creating a new let binding for each non-wild binder, which
393 -- is bound to a new simple selector case statement and for each complex
394 -- expression. We do this only for representable types, to prevent loops with
396 casesimpl expr@(Case scrut b ty alts) = do
397 (bindingss, alts') <- (Monad.liftM unzip) $ mapM doalt alts
398 let bindings = concat bindingss
399 -- Replace the case with a let with bindings and a case
400 let newlet = mkNonRecLets bindings (Case scrut b ty alts')
401 -- If there are no non-wild binders, or this case is already a simple
402 -- selector (i.e., a single alt with exactly one binding), already a simple
403 -- selector altan no bindings (i.e., no wild binders in the original case),
404 -- don't change anything, otherwise, replace the case.
405 if null bindings then return expr else change newlet
407 -- Generate a single wild binder, since they are all the same
408 wild = MkCore.mkWildBinder
409 -- Wilden the binders of one alt, producing a list of bindings as a
411 doalt :: CoreAlt -> TransformMonad ([(CoreBndr, CoreExpr)], CoreAlt)
412 doalt (con, bndrs, expr) = do
413 -- Make each binder wild, if possible
414 bndrs_res <- Monad.zipWithM dobndr bndrs [0..]
415 let (newbndrs, bindings_maybe) = unzip bndrs_res
416 -- Extract a complex expression, if possible. For this we check if any of
417 -- the new list of bndrs are used by expr. We can't use free_vars here,
418 -- since that looks at the old bndrs.
419 let uses_bndrs = not $ VarSet.isEmptyVarSet $ CoreFVs.exprSomeFreeVars (`elem` newbndrs) $ expr
420 (exprbinding_maybe, expr') <- doexpr expr uses_bndrs
421 -- Create a new alternative
422 let newalt = (con, newbndrs, expr')
423 let bindings = Maybe.catMaybes (bindings_maybe ++ [exprbinding_maybe])
424 return (bindings, newalt)
426 -- Make wild alternatives for each binder
427 wildbndrs = map (\bndr -> MkCore.mkWildBinder (Id.idType bndr)) bndrs
428 -- A set of all the binders that are used by the expression
429 free_vars = CoreFVs.exprSomeFreeVars (`elem` bndrs) expr
430 -- Look at the ith binder in the case alternative. Return a new binder
431 -- for it (either the same one, or a wild one) and optionally a let
432 -- binding containing a case expression.
433 dobndr :: CoreBndr -> Int -> TransformMonad (CoreBndr, Maybe (CoreBndr, CoreExpr))
436 -- Is b wild (e.g., not a free var of expr. Since b is only in scope
437 -- in expr, this means that b is unused if expr does not use it.)
438 let wild = not (VarSet.elemVarSet b free_vars)
439 -- Create a new binding for any representable binder that is not
440 -- already wild and is representable (to prevent loops with
442 if (not wild) && repr
444 -- Create on new binder that will actually capture a value in this
445 -- case statement, and return it.
446 let bty = (Id.idType b)
447 id <- Trans.lift $ mkInternalVar "sel" bty
448 let binders = take i wildbndrs ++ [id] ++ drop (i+1) wildbndrs
449 let caseexpr = Case scrut b bty [(con, binders, Var id)]
450 return (wildbndrs!!i, Just (b, caseexpr))
452 -- Just leave the original binder in place, and don't generate an
453 -- extra selector case.
455 -- Process the expression of a case alternative. Accepts an expression
456 -- and whether this expression uses any of the binders in the
457 -- alternative. Returns an optional new binding and a new expression.
458 doexpr :: CoreExpr -> Bool -> TransformMonad (Maybe (CoreBndr, CoreExpr), CoreExpr)
459 doexpr expr uses_bndrs = do
460 local_var <- Trans.lift $ is_local_var expr
462 -- Extract any expressions that do not use any binders from this
463 -- alternative, is not a local var already and is representable (to
464 -- prevent loops with inlinenonrep).
465 if (not uses_bndrs) && (not local_var) && repr
467 id <- Trans.lift $ mkBinderFor expr "caseval"
468 -- We don't flag a change here, since casevalsimpl will do that above
469 -- based on Just we return here.
470 return $ (Just (id, expr), Var id)
472 -- Don't simplify anything else
473 return (Nothing, expr)
474 -- Leave all other expressions unchanged
475 casesimpl expr = return expr
476 -- Perform this transform everywhere
477 casesimpltop = everywhere ("casesimpl", casesimpl)
479 --------------------------------
481 --------------------------------
482 -- Remove case statements that have only a single alternative and only wild
484 caseremove, caseremovetop :: Transform
485 -- Replace a useless case by the value of its single alternative
486 caseremove (Case scrut b ty [(con, bndrs, expr)]) | not usesvars = change expr
487 -- Find if any of the binders are used by expr
488 where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` bndrs))) expr
489 -- Leave all other expressions unchanged
490 caseremove expr = return expr
491 -- Perform this transform everywhere
492 caseremovetop = everywhere ("caseremove", caseremove)
494 --------------------------------
495 -- Argument extraction
496 --------------------------------
497 -- Make sure that all arguments of a representable type are simple variables.
498 appsimpl, appsimpltop :: Transform
499 -- Simplify all representable arguments. Do this by introducing a new Let
500 -- that binds the argument and passing the new binder in the application.
501 appsimpl expr@(App f arg) = do
502 -- Check runtime representability
504 local_var <- Trans.lift $ is_local_var arg
505 if repr && not local_var
506 then do -- Extract representable arguments
507 id <- Trans.lift $ mkBinderFor arg "arg"
508 change $ Let (NonRec id arg) (App f (Var id))
509 else -- Leave non-representable arguments unchanged
511 -- Leave all other expressions unchanged
512 appsimpl expr = return expr
513 -- Perform this transform everywhere
514 appsimpltop = everywhere ("appsimpl", appsimpl)
516 --------------------------------
517 -- Function-typed argument propagation
518 --------------------------------
519 -- Remove all applications to function-typed arguments, by duplication the
520 -- function called with the function-typed parameter replaced by the free
521 -- variables of the argument passed in.
522 argprop, argproptop :: Transform
523 -- Transform any application of a named function (i.e., skip applications of
524 -- lambda's). Also skip applications that have arguments with free type
525 -- variables, since we can't inline those.
526 argprop expr@(App _ _) | is_var fexpr = do
527 -- Find the body of the function called
528 body_maybe <- Trans.lift $ getGlobalBind f
531 -- Process each of the arguments in turn
532 (args', changed) <- Writer.listen $ mapM doarg args
533 -- See if any of the arguments changed
534 case Monoid.getAny changed of
536 let (newargs', newparams', oldargs) = unzip3 args'
537 let newargs = concat newargs'
538 let newparams = concat newparams'
539 -- Create a new body that consists of a lambda for all new arguments and
540 -- the old body applied to some arguments.
541 let newbody = MkCore.mkCoreLams newparams (MkCore.mkCoreApps body oldargs)
542 -- Create a new function with the same name but a new body
543 newf <- Trans.lift $ mkFunction f newbody
544 -- Replace the original application with one of the new function to the
546 change $ MkCore.mkCoreApps (Var newf) newargs
548 -- Don't change the expression if none of the arguments changed
551 -- If we don't have a body for the function called, leave it unchanged (it
552 -- should be a primitive function then).
553 Nothing -> return expr
555 -- Find the function called and the arguments
556 (fexpr, args) = collectArgs expr
559 -- Process a single argument and return (args, bndrs, arg), where args are
560 -- the arguments to replace the given argument in the original
561 -- application, bndrs are the binders to include in the top-level lambda
562 -- in the new function body, and arg is the argument to apply to the old
564 doarg :: CoreExpr -> TransformMonad ([CoreExpr], [CoreBndr], CoreExpr)
567 bndrs <- Trans.lift getGlobalBinders
568 let interesting var = Var.isLocalVar var && (not $ var `elem` bndrs)
569 if not repr && not (is_var arg && interesting (exprToVar arg)) && not (has_free_tyvars arg)
571 -- Propagate all complex arguments that are not representable, but not
572 -- arguments with free type variables (since those would require types
573 -- not known yet, which will always be known eventually).
574 -- Find interesting free variables, each of which should be passed to
575 -- the new function instead of the original function argument.
577 -- Interesting vars are those that are local, but not available from the
578 -- top level scope (functions from this module are defined as local, but
579 -- they're not local to this function, so we can freely move references
580 -- to them into another function).
581 let free_vars = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars interesting arg
582 -- Mark the current expression as changed
584 return (map Var free_vars, free_vars, arg)
586 -- Representable types will not be propagated, and arguments with free
587 -- type variables will be propagated later.
588 -- TODO: preserve original naming?
589 id <- Trans.lift $ mkBinderFor arg "param"
590 -- Just pass the original argument to the new function, which binds it
591 -- to a new id and just pass that new id to the old function body.
592 return ([arg], [id], mkReferenceTo id)
593 -- Leave all other expressions unchanged
594 argprop expr = return expr
595 -- Perform this transform everywhere
596 argproptop = everywhere ("argprop", argprop)
598 --------------------------------
599 -- Function-typed argument extraction
600 --------------------------------
601 -- This transform takes any function-typed argument that cannot be propagated
602 -- (because the function that is applied to it is a builtin function), and
603 -- puts it in a brand new top level binder. This allows us to for example
604 -- apply map to a lambda expression This will not conflict with inlinenonrep,
605 -- since that only inlines local let bindings, not top level bindings.
606 funextract, funextracttop :: Transform
607 funextract expr@(App _ _) | is_var fexpr = do
608 body_maybe <- Trans.lift $ getGlobalBind f
610 -- We don't have a function body for f, so we can perform this transform.
612 -- Find the new arguments
613 args' <- mapM doarg args
614 -- And update the arguments. We use return instead of changed, so the
615 -- changed flag doesn't get set if none of the args got changed.
616 return $ MkCore.mkCoreApps fexpr args'
617 -- We have a function body for f, leave this application to funprop
618 Just _ -> return expr
620 -- Find the function called and the arguments
621 (fexpr, args) = collectArgs expr
623 -- Change any arguments that have a function type, but are not simple yet
624 -- (ie, a variable or application). This means to create a new function
625 -- for map (\f -> ...) b, but not for map (foo a) b.
627 -- We could use is_applicable here instead of is_fun, but I think
628 -- arguments to functions could only have forall typing when existential
629 -- typing is enabled. Not sure, though.
630 doarg arg | not (is_simple arg) && is_fun arg = do
631 -- Create a new top level binding that binds the argument. Its body will
632 -- be extended with lambda expressions, to take any free variables used
633 -- by the argument expression.
634 let free_vars = VarSet.varSetElems $ CoreFVs.exprFreeVars arg
635 let body = MkCore.mkCoreLams free_vars arg
636 id <- Trans.lift $ mkBinderFor body "fun"
637 Trans.lift $ addGlobalBind id body
638 -- Replace the argument with a reference to the new function, applied to
640 change $ MkCore.mkCoreApps (Var id) (map Var free_vars)
641 -- Leave all other arguments untouched
642 doarg arg = return arg
644 -- Leave all other expressions unchanged
645 funextract expr = return expr
646 -- Perform this transform everywhere
647 funextracttop = everywhere ("funextract", funextract)
649 --------------------------------
650 -- Ensure that a function that just returns another function (or rather,
651 -- another top-level binder) is still properly normalized. This is a temporary
652 -- solution, we should probably integrate this pass with lambdasimpl and
654 --------------------------------
655 simplrestop expr@(Lam _ _) = return expr
656 simplrestop expr@(Let _ _) = return expr
657 simplrestop expr = do
658 local_var <- Trans.lift $ is_local_var expr
659 -- Don't extract values that are not representable, to prevent loops with
662 if local_var || not repr
666 id <- Trans.lift $ mkBinderFor expr "res"
667 change $ Let (NonRec id expr) (Var id)
668 --------------------------------
669 -- End of transformations
670 --------------------------------
675 -- What transforms to run?
676 transforms = [inlinetopleveltop, argproptop, funextracttop, etatop, betatop, castproptop, letremovesimpletop, letderectop, letremovetop, letsimpltop, letflattop, scrutsimpltop, casesimpltop, caseremovetop, inlinenonreptop, appsimpltop, letremoveunusedtop, castsimpltop, lambdasimpltop, simplrestop]
678 -- | Returns the normalized version of the given function.
680 CoreBndr -- ^ The function to get
681 -> TranslatorSession CoreExpr -- The normalized function body
683 getNormalized bndr = Utils.makeCached bndr tsNormalized $ do
684 if is_poly (Var bndr)
686 -- This should really only happen at the top level... TODO: Give
687 -- a different error if this happens down in the recursion.
688 error $ "\nNormalize.normalizeBind: Function " ++ show bndr ++ " is polymorphic, can't normalize"
690 expr <- getBinding bndr
691 normalizeExpr (show bndr) expr
693 -- | Normalize an expression
695 String -- ^ What are we normalizing? For debug output only.
696 -> CoreSyn.CoreExpr -- ^ The expression to normalize
697 -> TranslatorSession CoreSyn.CoreExpr -- ^ The normalized expression
699 normalizeExpr what expr = do
700 expr_uniqued <- genUniques expr
701 -- Normalize this expression
702 trace (what ++ " before normalization:\n\n" ++ showSDoc ( ppr expr_uniqued ) ++ "\n") $ return ()
703 expr' <- dotransforms transforms expr_uniqued
704 trace ("\n" ++ what ++ " after normalization:\n\n" ++ showSDoc ( ppr expr')) $ return ()
707 -- | Get the value that is bound to the given binder at top level. Fails when
708 -- there is no such binding.
710 CoreBndr -- ^ The binder to get the expression for
711 -> TranslatorSession CoreExpr -- ^ The value bound to the binder
713 getBinding bndr = Utils.makeCached bndr tsBindings $ do
714 -- If the binding isn't in the "cache" (bindings map), then we can't create
715 -- it out of thin air, so return an error.
716 error $ "Normalize.getBinding: Unknown function requested: " ++ show bndr
718 -- | Split a normalized expression into the argument binders, top level
719 -- bindings and the result binder.
721 CoreExpr -- ^ The normalized expression
722 -> ([CoreBndr], [Binding], CoreBndr)
723 splitNormalized expr = (args, binds, res)
725 (args, letexpr) = CoreSyn.collectBinders expr
726 (binds, resexpr) = flattenLets letexpr
727 res = case resexpr of
729 _ -> error $ "Normalize.splitNormalized: Not in normal form: " ++ pprString expr ++ "\n"