Add scrutinee binder removal transformation.
[matthijs/master-project/cλash.git] / cλash / CLasH / Normalize.hs
1 {-# LANGUAGE PackageImports #-}
2 --
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
5 -- are performed.
6 --
7 module CLasH.Normalize (getNormalized, normalizeExpr, splitNormalized) where
8
9 -- Standard modules
10 import Debug.Trace
11 import qualified Maybe
12 import qualified List
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
18 import Data.Accessor
19
20 -- GHC API
21 import CoreSyn
22 import qualified UniqSupply
23 import qualified CoreUtils
24 import qualified Type
25 import qualified TcType
26 import qualified Name
27 import qualified Id
28 import qualified Var
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 )
36
37 -- Local imports
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
46
47 --------------------------------
48 -- Start of transformations
49 --------------------------------
50
51 --------------------------------
52 -- η abstraction
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
60 eta e = return e
61 etatop = notappargs ("eta", eta)
62
63 --------------------------------
64 -- β-reduction
65 --------------------------------
66 beta, betatop :: Transform
67 -- Substitute arg for x in expr. For value lambda's, also clone before
68 -- substitution.
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'
75   where 
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)
82
83 --------------------------------
84 -- Cast propagation
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')
90   where
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)
96
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
106   -- inlinenonrep
107   repr <- isRepr val
108   if (not local_var) && repr
109     then do
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)
114     else
115       return expr
116 -- Leave all other expressions unchanged
117 castsimpl expr = return expr
118 -- Perform this transform everywhere
119 castsimpltop = everywhere ("castsimpl", castsimpl)
120
121
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
133 -- inlinenonrep).
134 lambdasimpl expr@(Lam bndr res) = do
135   repr <- isRepr res
136   local_var <- Trans.lift $ is_local_var res
137   if not local_var && repr
138     then do
139       id <- Trans.lift $ mkBinderFor res "res"
140       change $ Lam bndr (Let (NonRec id res) (Var id))
141     else
142       -- If the result is already a local var or not representable, don't
143       -- extract it.
144       return expr
145
146 -- Leave all other expressions unchanged
147 lambdasimpl expr = return expr
148 -- Perform this transform everywhere
149 lambdasimpltop = everywhere ("lambdasimpl", lambdasimpl)
150
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
157   [] -> return expr
158   -- Something can be lifted, generate a new let expression
159   _ -> change $ mkNonRecLets liftable (Let (Rec nonliftable) res)
160   where
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)
174
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
185   repr <- isRepr res
186   local_var <- Trans.lift $ is_local_var res
187   if not local_var && repr
188     then do
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))
193     else
194       -- If the result is already a local var, don't extract it.
195       return expr
196
197 -- Leave all other expressions unchanged
198 letsimpl expr = return expr
199 -- Perform this transform everywhere
200 letsimpltop = everywhere ("letsimpl", letsimpl)
201
202 --------------------------------
203 -- let flattening
204 --------------------------------
205 -- Takes a let that binds another let, and turns that into two nested lets.
206 -- e.g., from:
207 -- let b = (let b' = expr' in res') in res
208 -- to:
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
219   -- change.
220   return $ Let (Rec binds') expr
221   where
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)
232
233 --------------------------------
234 -- empty let removal
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)
243
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))
250
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
257   if used
258     then return expr
259     else change 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)
265     where
266       bound_exprs = map snd binds
267       -- For each bind check if the bind is used by res or any of the bound
268       -- expressions
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)
273
274 {-
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
286   where
287     domerge :: [(CoreBndr, CoreExpr)] -> TransformMonad [(CoreBndr, CoreExpr)]
288     domerge [] = return []
289     domerge (e:es) = do 
290       es' <- mapM (mergebinds e) es
291       es'' <- domerge es'
292       return (e:es'')
293
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
298       -- the first binder.
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)
305 -}
306
307 --------------------------------
308 -- Non-representable binding inlining
309 --------------------------------
310 -- Remove a = B bindings, with B of a non-representable type, from let
311 -- expressions everywhere. This means that any value that we can't generate a
312 -- signal for, will be inlined and hopefully turned into something we can
313 -- represent.
314 --
315 -- This is a tricky function, which is prone to create loops in the
316 -- transformations. To fix this, we make sure that no transformation will
317 -- create a new let binding with a non-representable type. These other
318 -- transformations will just not work on those function-typed values at first,
319 -- but the other transformations (in particular β-reduction) should make sure
320 -- that the type of those values eventually becomes representable.
321 inlinenonreptop :: Transform
322 inlinenonreptop = everywhere ("inlinenonrep", inlinebind ((Monad.liftM not) . isRepr . snd))
323
324 --------------------------------
325 -- Top level function inlining
326 --------------------------------
327 -- This transformation inlines top level bindings that have been generated by
328 -- the compiler and are really simple. Really simple currently means that the
329 -- normalized form only contains a single binding, which catches most of the
330 -- cases where a top level function is created that simply calls a type class
331 -- method with a type and dictionary argument, e.g.
332 --   fromInteger = GHC.Num.fromInteger (SizedWord D8) $dNum
333 -- which is later called using simply
334 --   fromInteger (smallInteger 10)
335 -- By inlining such calls to simple, compiler generated functions, we prevent
336 -- huge amounts of trivial components in the VHDL output, which the user never
337 -- wanted. We never inline user-defined functions, since we want to preserve
338 -- all structure defined by the user. Currently this includes all functions
339 -- that were created by funextract, since we would get loops otherwise.
340 --
341 -- Note that "defined by the compiler" isn't completely watertight, since GHC
342 -- doesn't seem to set all those names as "system names", we apply some
343 -- guessing here.
344 inlinetoplevel, inlinetopleveltop :: Transform
345 -- Any system name is candidate for inlining. Never inline user-defined
346 -- functions, to preserve structure.
347 inlinetoplevel expr@(Var f) | not $ isUserDefined f = do
348   norm <- isNormalizeable f
349   -- See if this is a top level binding for which we have a body
350   body_maybe <- Trans.lift $ getGlobalBind f
351   if norm && Maybe.isJust body_maybe
352     then do
353       -- Get the normalized version
354       norm <- Trans.lift $ getNormalized f
355       if needsInline norm 
356         then do
357           -- Regenerate all uniques in the to-be-inlined expression
358           norm_uniqued <- Trans.lift $ genUniques norm
359           change norm_uniqued
360         else
361           return expr
362     else
363       -- No body or not normalizeable.
364       return expr
365 -- Leave all other expressions unchanged
366 inlinetoplevel expr = return expr
367 inlinetopleveltop = everywhere ("inlinetoplevel", inlinetoplevel)
368
369 needsInline :: CoreExpr -> Bool
370 needsInline expr = case splitNormalized expr of
371   -- Inline any function that only has a single definition, it is probably
372   -- simple enough. This might inline some stuff that it shouldn't though it
373   -- will never inline user-defined functions (inlinetoplevel only tries
374   -- system names) and inlining should never break things.
375   (args, [bind], res) -> True
376   _ -> False
377
378 --------------------------------
379 -- Scrutinee simplification
380 --------------------------------
381 scrutsimpl,scrutsimpltop :: Transform
382 -- Don't touch scrutinees that are already simple
383 scrutsimpl expr@(Case (Var _) _ _ _) = return expr
384 -- Replace all other cases with a let that binds the scrutinee and a new
385 -- simple scrutinee, but only when the scrutinee is representable (to prevent
386 -- loops with inlinenonrep, though I don't think a non-representable scrutinee
387 -- will be supported anyway...) 
388 scrutsimpl expr@(Case scrut b ty alts) = do
389   repr <- isRepr scrut
390   if repr
391     then do
392       id <- Trans.lift $ mkBinderFor scrut "scrut"
393       change $ Let (NonRec id scrut) (Case (Var id) b ty alts)
394     else
395       return expr
396 -- Leave all other expressions unchanged
397 scrutsimpl expr = return expr
398 -- Perform this transform everywhere
399 scrutsimpltop = everywhere ("scrutsimpl", scrutsimpl)
400
401 --------------------------------
402 -- Scrutinee binder removal
403 --------------------------------
404 -- A case expression can have an extra binder, to which the scrutinee is bound
405 -- after bringing it to WHNF. This is used for forcing evaluation of strict
406 -- arguments. Since strictness does not matter for us (rather, everything is
407 -- sort of strict), this binder is ignored when generating VHDL, and must thus
408 -- be wild in the normal form.
409 scrutbndrremove, scrutbndrremovetop :: Transform
410 -- If the scrutinee is already simple, and the bndr is not wild yet, replace
411 -- all occurences of the binder with the scrutinee variable.
412 scrutbndrremove (Case (Var scrut) bndr ty alts) | bndr_used = do
413     alts' <- mapM subs_bndr alts
414     return $ Case (Var scrut) wild ty alts'
415   where
416     is_used (_, _, expr) = expr_uses_binders [bndr] expr
417     bndr_used = or $ map is_used alts
418     subs_bndr (con, bndrs, expr) = do
419       expr' <- substitute bndr (Var scrut) expr
420       return (con, bndrs, expr')
421     wild = MkCore.mkWildBinder (Id.idType bndr)
422 scrutbndrremovetop = everywhere ("scrutbndrremove", scrutbndrremove)
423
424 --------------------------------
425 -- Case binder wildening
426 --------------------------------
427 casesimpl, casesimpltop :: Transform
428 -- This is already a selector case (or, if x does not appear in bndrs, a very
429 -- simple case statement that will be removed by caseremove below). Just leave
430 -- it be.
431 casesimpl expr@(Case scrut b ty [(con, bndrs, Var x)]) = return expr
432 -- Make sure that all case alternatives have only wild binders and simple
433 -- expressions.
434 -- This is done by creating a new let binding for each non-wild binder, which
435 -- is bound to a new simple selector case statement and for each complex
436 -- expression. We do this only for representable types, to prevent loops with
437 -- inlinenonrep.
438 casesimpl expr@(Case scrut b ty alts) = do
439   (bindingss, alts') <- (Monad.liftM unzip) $ mapM doalt alts
440   let bindings = concat bindingss
441   -- Replace the case with a let with bindings and a case
442   let newlet = mkNonRecLets bindings (Case scrut b ty alts')
443   -- If there are no non-wild binders, or this case is already a simple
444   -- selector (i.e., a single alt with exactly one binding), already a simple
445   -- selector altan no bindings (i.e., no wild binders in the original case),
446   -- don't change anything, otherwise, replace the case.
447   if null bindings then return expr else change newlet 
448   where
449   -- Generate a single wild binder, since they are all the same
450   wild = MkCore.mkWildBinder
451   -- Wilden the binders of one alt, producing a list of bindings as a
452   -- sideeffect.
453   doalt :: CoreAlt -> TransformMonad ([(CoreBndr, CoreExpr)], CoreAlt)
454   doalt (con, bndrs, expr) = do
455     -- Make each binder wild, if possible
456     bndrs_res <- Monad.zipWithM dobndr bndrs [0..]
457     let (newbndrs, bindings_maybe) = unzip bndrs_res
458     -- Extract a complex expression, if possible. For this we check if any of
459     -- the new list of bndrs are used by expr. We can't use free_vars here,
460     -- since that looks at the old bndrs.
461     let uses_bndrs = not $ VarSet.isEmptyVarSet $ CoreFVs.exprSomeFreeVars (`elem` newbndrs) $ expr
462     (exprbinding_maybe, expr') <- doexpr expr uses_bndrs
463     -- Create a new alternative
464     let newalt = (con, newbndrs, expr')
465     let bindings = Maybe.catMaybes (bindings_maybe ++ [exprbinding_maybe])
466     return (bindings, newalt)
467     where
468       -- Make wild alternatives for each binder
469       wildbndrs = map (\bndr -> MkCore.mkWildBinder (Id.idType bndr)) bndrs
470       -- A set of all the binders that are used by the expression
471       free_vars = CoreFVs.exprSomeFreeVars (`elem` bndrs) expr
472       -- Look at the ith binder in the case alternative. Return a new binder
473       -- for it (either the same one, or a wild one) and optionally a let
474       -- binding containing a case expression.
475       dobndr :: CoreBndr -> Int -> TransformMonad (CoreBndr, Maybe (CoreBndr, CoreExpr))
476       dobndr b i = do
477         repr <- isRepr b
478         -- Is b wild (e.g., not a free var of expr. Since b is only in scope
479         -- in expr, this means that b is unused if expr does not use it.)
480         let wild = not (VarSet.elemVarSet b free_vars)
481         -- Create a new binding for any representable binder that is not
482         -- already wild and is representable (to prevent loops with
483         -- inlinenonrep).
484         if (not wild) && repr
485           then do
486             -- Create on new binder that will actually capture a value in this
487             -- case statement, and return it.
488             let bty = (Id.idType b)
489             id <- Trans.lift $ mkInternalVar "sel" bty
490             let binders = take i wildbndrs ++ [id] ++ drop (i+1) wildbndrs
491             let caseexpr = Case scrut b bty [(con, binders, Var id)]
492             return (wildbndrs!!i, Just (b, caseexpr))
493           else 
494             -- Just leave the original binder in place, and don't generate an
495             -- extra selector case.
496             return (b, Nothing)
497       -- Process the expression of a case alternative. Accepts an expression
498       -- and whether this expression uses any of the binders in the
499       -- alternative. Returns an optional new binding and a new expression.
500       doexpr :: CoreExpr -> Bool -> TransformMonad (Maybe (CoreBndr, CoreExpr), CoreExpr)
501       doexpr expr uses_bndrs = do
502         local_var <- Trans.lift $ is_local_var expr
503         repr <- isRepr expr
504         -- Extract any expressions that do not use any binders from this
505         -- alternative, is not a local var already and is representable (to
506         -- prevent loops with inlinenonrep).
507         if (not uses_bndrs) && (not local_var) && repr
508           then do
509             id <- Trans.lift $ mkBinderFor expr "caseval"
510             -- We don't flag a change here, since casevalsimpl will do that above
511             -- based on Just we return here.
512             return $ (Just (id, expr), Var id)
513           else
514             -- Don't simplify anything else
515             return (Nothing, expr)
516 -- Leave all other expressions unchanged
517 casesimpl expr = return expr
518 -- Perform this transform everywhere
519 casesimpltop = everywhere ("casesimpl", casesimpl)
520
521 --------------------------------
522 -- Case removal
523 --------------------------------
524 -- Remove case statements that have only a single alternative and only wild
525 -- binders.
526 caseremove, caseremovetop :: Transform
527 -- Replace a useless case by the value of its single alternative
528 caseremove (Case scrut b ty [(con, bndrs, expr)]) | not usesvars = change expr
529     -- Find if any of the binders are used by expr
530     where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` bndrs))) expr
531 -- Leave all other expressions unchanged
532 caseremove expr = return expr
533 -- Perform this transform everywhere
534 caseremovetop = everywhere ("caseremove", caseremove)
535
536 --------------------------------
537 -- Argument extraction
538 --------------------------------
539 -- Make sure that all arguments of a representable type are simple variables.
540 appsimpl, appsimpltop :: Transform
541 -- Simplify all representable arguments. Do this by introducing a new Let
542 -- that binds the argument and passing the new binder in the application.
543 appsimpl expr@(App f arg) = do
544   -- Check runtime representability
545   repr <- isRepr arg
546   local_var <- Trans.lift $ is_local_var arg
547   if repr && not local_var
548     then do -- Extract representable arguments
549       id <- Trans.lift $ mkBinderFor arg "arg"
550       change $ Let (NonRec id arg) (App f (Var id))
551     else -- Leave non-representable arguments unchanged
552       return expr
553 -- Leave all other expressions unchanged
554 appsimpl expr = return expr
555 -- Perform this transform everywhere
556 appsimpltop = everywhere ("appsimpl", appsimpl)
557
558 --------------------------------
559 -- Function-typed argument propagation
560 --------------------------------
561 -- Remove all applications to function-typed arguments, by duplication the
562 -- function called with the function-typed parameter replaced by the free
563 -- variables of the argument passed in.
564 argprop, argproptop :: Transform
565 -- Transform any application of a named function (i.e., skip applications of
566 -- lambda's). Also skip applications that have arguments with free type
567 -- variables, since we can't inline those.
568 argprop expr@(App _ _) | is_var fexpr = do
569   -- Find the body of the function called
570   body_maybe <- Trans.lift $ getGlobalBind f
571   case body_maybe of
572     Just body -> do
573       -- Process each of the arguments in turn
574       (args', changed) <- Writer.listen $ mapM doarg args
575       -- See if any of the arguments changed
576       case Monoid.getAny changed of
577         True -> do
578           let (newargs', newparams', oldargs) = unzip3 args'
579           let newargs = concat newargs'
580           let newparams = concat newparams'
581           -- Create a new body that consists of a lambda for all new arguments and
582           -- the old body applied to some arguments.
583           let newbody = MkCore.mkCoreLams newparams (MkCore.mkCoreApps body oldargs)
584           -- Create a new function with the same name but a new body
585           newf <- Trans.lift $ mkFunction f newbody
586           -- Replace the original application with one of the new function to the
587           -- new arguments.
588           change $ MkCore.mkCoreApps (Var newf) newargs
589         False ->
590           -- Don't change the expression if none of the arguments changed
591           return expr
592       
593     -- If we don't have a body for the function called, leave it unchanged (it
594     -- should be a primitive function then).
595     Nothing -> return expr
596   where
597     -- Find the function called and the arguments
598     (fexpr, args) = collectArgs expr
599     Var f = fexpr
600
601     -- Process a single argument and return (args, bndrs, arg), where args are
602     -- the arguments to replace the given argument in the original
603     -- application, bndrs are the binders to include in the top-level lambda
604     -- in the new function body, and arg is the argument to apply to the old
605     -- function body.
606     doarg :: CoreExpr -> TransformMonad ([CoreExpr], [CoreBndr], CoreExpr)
607     doarg arg = do
608       repr <- isRepr arg
609       bndrs <- Trans.lift getGlobalBinders
610       let interesting var = Var.isLocalVar var && (not $ var `elem` bndrs)
611       if not repr && not (is_var arg && interesting (exprToVar arg)) && not (has_free_tyvars arg) 
612         then do
613           -- Propagate all complex arguments that are not representable, but not
614           -- arguments with free type variables (since those would require types
615           -- not known yet, which will always be known eventually).
616           -- Find interesting free variables, each of which should be passed to
617           -- the new function instead of the original function argument.
618           -- 
619           -- Interesting vars are those that are local, but not available from the
620           -- top level scope (functions from this module are defined as local, but
621           -- they're not local to this function, so we can freely move references
622           -- to them into another function).
623           let free_vars = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars interesting arg
624           -- Mark the current expression as changed
625           setChanged
626           return (map Var free_vars, free_vars, arg)
627         else do
628           -- Representable types will not be propagated, and arguments with free
629           -- type variables will be propagated later.
630           -- TODO: preserve original naming?
631           id <- Trans.lift $ mkBinderFor arg "param"
632           -- Just pass the original argument to the new function, which binds it
633           -- to a new id and just pass that new id to the old function body.
634           return ([arg], [id], mkReferenceTo id) 
635 -- Leave all other expressions unchanged
636 argprop expr = return expr
637 -- Perform this transform everywhere
638 argproptop = everywhere ("argprop", argprop)
639
640 --------------------------------
641 -- Function-typed argument extraction
642 --------------------------------
643 -- This transform takes any function-typed argument that cannot be propagated
644 -- (because the function that is applied to it is a builtin function), and
645 -- puts it in a brand new top level binder. This allows us to for example
646 -- apply map to a lambda expression This will not conflict with inlinenonrep,
647 -- since that only inlines local let bindings, not top level bindings.
648 funextract, funextracttop :: Transform
649 funextract expr@(App _ _) | is_var fexpr = do
650   body_maybe <- Trans.lift $ getGlobalBind f
651   case body_maybe of
652     -- We don't have a function body for f, so we can perform this transform.
653     Nothing -> do
654       -- Find the new arguments
655       args' <- mapM doarg args
656       -- And update the arguments. We use return instead of changed, so the
657       -- changed flag doesn't get set if none of the args got changed.
658       return $ MkCore.mkCoreApps fexpr args'
659     -- We have a function body for f, leave this application to funprop
660     Just _ -> return expr
661   where
662     -- Find the function called and the arguments
663     (fexpr, args) = collectArgs expr
664     Var f = fexpr
665     -- Change any arguments that have a function type, but are not simple yet
666     -- (ie, a variable or application). This means to create a new function
667     -- for map (\f -> ...) b, but not for map (foo a) b.
668     --
669     -- We could use is_applicable here instead of is_fun, but I think
670     -- arguments to functions could only have forall typing when existential
671     -- typing is enabled. Not sure, though.
672     doarg arg | not (is_simple arg) && is_fun arg = do
673       -- Create a new top level binding that binds the argument. Its body will
674       -- be extended with lambda expressions, to take any free variables used
675       -- by the argument expression.
676       let free_vars = VarSet.varSetElems $ CoreFVs.exprFreeVars arg
677       let body = MkCore.mkCoreLams free_vars arg
678       id <- Trans.lift $ mkBinderFor body "fun"
679       Trans.lift $ addGlobalBind id body
680       -- Replace the argument with a reference to the new function, applied to
681       -- all vars it uses.
682       change $ MkCore.mkCoreApps (Var id) (map Var free_vars)
683     -- Leave all other arguments untouched
684     doarg arg = return arg
685
686 -- Leave all other expressions unchanged
687 funextract expr = return expr
688 -- Perform this transform everywhere
689 funextracttop = everywhere ("funextract", funextract)
690
691 --------------------------------
692 -- Ensure that a function that just returns another function (or rather,
693 -- another top-level binder) is still properly normalized. This is a temporary
694 -- solution, we should probably integrate this pass with lambdasimpl and
695 -- letsimpl instead.
696 --------------------------------
697 simplrestop expr@(Lam _ _) = return expr
698 simplrestop expr@(Let _ _) = return expr
699 simplrestop expr = do
700   local_var <- Trans.lift $ is_local_var expr
701   -- Don't extract values that are not representable, to prevent loops with
702   -- inlinenonrep
703   repr <- isRepr expr
704   if local_var || not repr
705     then
706       return expr
707     else do
708       id <- Trans.lift $ mkBinderFor expr "res" 
709       change $ Let (NonRec id expr) (Var id)
710 --------------------------------
711 -- End of transformations
712 --------------------------------
713
714
715
716
717 -- What transforms to run?
718 transforms = [inlinetopleveltop, argproptop, funextracttop, etatop, betatop, castproptop, letremovesimpletop, letderectop, letremovetop, letsimpltop, letflattop, scrutsimpltop, scrutbndrremovetop, casesimpltop, caseremovetop, inlinenonreptop, appsimpltop, letremoveunusedtop, castsimpltop, lambdasimpltop, simplrestop]
719
720 -- | Returns the normalized version of the given function.
721 getNormalized ::
722   CoreBndr -- ^ The function to get
723   -> TranslatorSession CoreExpr -- The normalized function body
724
725 getNormalized bndr = Utils.makeCached bndr tsNormalized $ do
726   if is_poly (Var bndr)
727     then
728       -- This should really only happen at the top level... TODO: Give
729       -- a different error if this happens down in the recursion.
730       error $ "\nNormalize.normalizeBind: Function " ++ show bndr ++ " is polymorphic, can't normalize"
731     else do
732       expr <- getBinding bndr
733       normalizeExpr (show bndr) expr
734
735 -- | Normalize an expression
736 normalizeExpr ::
737   String -- ^ What are we normalizing? For debug output only.
738   -> CoreSyn.CoreExpr -- ^ The expression to normalize 
739   -> TranslatorSession CoreSyn.CoreExpr -- ^ The normalized expression
740
741 normalizeExpr what expr = do
742       expr_uniqued <- genUniques expr
743       -- Normalize this expression
744       trace (what ++ " before normalization:\n\n" ++ showSDoc ( ppr expr_uniqued ) ++ "\n") $ return ()
745       expr' <- dotransforms transforms expr_uniqued
746       trace ("\n" ++ what ++ " after normalization:\n\n" ++ showSDoc ( ppr expr')) $ return ()
747       return expr'
748
749 -- | Get the value that is bound to the given binder at top level. Fails when
750 --   there is no such binding.
751 getBinding ::
752   CoreBndr -- ^ The binder to get the expression for
753   -> TranslatorSession CoreExpr -- ^ The value bound to the binder
754
755 getBinding bndr = Utils.makeCached bndr tsBindings $ do
756   -- If the binding isn't in the "cache" (bindings map), then we can't create
757   -- it out of thin air, so return an error.
758   error $ "Normalize.getBinding: Unknown function requested: " ++ show bndr
759
760 -- | Split a normalized expression into the argument binders, top level
761 --   bindings and the result binder.
762 splitNormalized ::
763   CoreExpr -- ^ The normalized expression
764   -> ([CoreBndr], [Binding], CoreBndr)
765 splitNormalized expr = (args, binds, res)
766   where
767     (args, letexpr) = CoreSyn.collectBinders expr
768     (binds, resexpr) = flattenLets letexpr
769     res = case resexpr of 
770       (Var x) -> x
771       _ -> error $ "Normalize.splitNormalized: Not in normal form: " ++ pprString expr ++ "\n"