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