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