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