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