Make genMap support mapping applications.
[matthijs/master-project/cλash.git] / 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 Normalize (normalizeModule) where
8
9 -- Standard modules
10 import Debug.Trace
11 import qualified Maybe
12 import qualified "transformers" Control.Monad.Trans as Trans
13 import qualified Control.Monad as Monad
14 import qualified Control.Monad.Trans.Writer as Writer
15 import qualified Data.Map as Map
16 import qualified Data.Monoid as Monoid
17 import Data.Accessor
18
19 -- GHC API
20 import CoreSyn
21 import qualified UniqSupply
22 import qualified CoreUtils
23 import qualified Type
24 import qualified Id
25 import qualified Var
26 import qualified VarSet
27 import qualified CoreFVs
28 import qualified CoreUtils
29 import qualified MkCore
30 import Outputable ( showSDoc, ppr, nest )
31
32 -- Local imports
33 import NormalizeTypes
34 import NormalizeTools
35 import CoreTools
36 import Pretty
37
38 --------------------------------
39 -- Start of transformations
40 --------------------------------
41
42 --------------------------------
43 -- η abstraction
44 --------------------------------
45 eta, etatop :: Transform
46 eta expr | is_fun expr && not (is_lam expr) = do
47   let arg_ty = (fst . Type.splitFunTy . CoreUtils.exprType) expr
48   id <- mkInternalVar "param" arg_ty
49   change (Lam id (App expr (Var id)))
50 -- Leave all other expressions unchanged
51 eta e = return e
52 etatop = notappargs ("eta", eta)
53
54 --------------------------------
55 -- β-reduction
56 --------------------------------
57 beta, betatop :: Transform
58 -- Substitute arg for x in expr
59 beta (App (Lam x expr) arg) = change $ substitute [(x, arg)] expr
60 -- Propagate the application into the let
61 beta (App (Let binds expr) arg) = change $ Let binds (App expr arg)
62 -- Propagate the application into each of the alternatives
63 beta (App (Case scrut b ty alts) arg) = change $ Case scrut b ty' alts'
64   where 
65     alts' = map (\(con, bndrs, expr) -> (con, bndrs, (App expr arg))) alts
66     ty' = CoreUtils.applyTypeToArg ty arg
67 -- Leave all other expressions unchanged
68 beta expr = return expr
69 -- Perform this transform everywhere
70 betatop = everywhere ("beta", beta)
71
72 --------------------------------
73 -- Cast propagation
74 --------------------------------
75 -- Try to move casts as much downward as possible.
76 castprop, castproptop :: Transform
77 castprop (Cast (Let binds expr) ty) = change $ Let binds (Cast expr ty)
78 castprop expr@(Cast (Case scrut b _ alts) ty) = change (Case scrut b ty alts')
79   where
80     alts' = map (\(con, bndrs, expr) -> (con, bndrs, (Cast expr ty))) alts
81 -- Leave all other expressions unchanged
82 castprop expr = return expr
83 -- Perform this transform everywhere
84 castproptop = everywhere ("castprop", castprop)
85
86 --------------------------------
87 -- let recursification
88 --------------------------------
89 letrec, letrectop :: Transform
90 letrec (Let (NonRec b expr) res) = change $ Let (Rec [(b, expr)]) res
91 -- Leave all other expressions unchanged
92 letrec expr = return expr
93 -- Perform this transform everywhere
94 letrectop = everywhere ("letrec", letrec)
95
96 --------------------------------
97 -- let simplification
98 --------------------------------
99 letsimpl, letsimpltop :: Transform
100 -- Don't simplifiy lets that are already simple
101 letsimpl expr@(Let _ (Var _)) = return expr
102 -- Put the "in ..." value of a let in its own binding, but not when the
103 -- expression is applicable (to prevent loops with inlinefun).
104 letsimpl (Let (Rec binds) expr) | not $ is_applicable expr = do
105   id <- mkInternalVar "foo" (CoreUtils.exprType expr)
106   let bind = (id, expr)
107   change $ Let (Rec (bind:binds)) (Var id)
108 -- Leave all other expressions unchanged
109 letsimpl expr = return expr
110 -- Perform this transform everywhere
111 letsimpltop = everywhere ("letsimpl", letsimpl)
112
113 --------------------------------
114 -- let flattening
115 --------------------------------
116 letflat, letflattop :: Transform
117 letflat (Let (Rec binds) expr) = do
118   -- Turn each binding into a list of bindings (possibly containing just one
119   -- element, of course)
120   bindss <- Monad.mapM flatbind binds
121   -- Concat all the bindings
122   let binds' = concat bindss
123   -- Return the new let. We don't use change here, since possibly nothing has
124   -- changed. If anything has changed, flatbind has already flagged that
125   -- change.
126   return $ Let (Rec binds') expr
127   where
128     -- Turns a binding of a let into a multiple bindings, or any other binding
129     -- into a list with just that binding
130     flatbind :: (CoreBndr, CoreExpr) -> TransformMonad [(CoreBndr, CoreExpr)]
131     flatbind (b, Let (Rec binds) expr) = change ((b, expr):binds)
132     flatbind (b, expr) = return [(b, expr)]
133 -- Leave all other expressions unchanged
134 letflat expr = return expr
135 -- Perform this transform everywhere
136 letflattop = everywhere ("letflat", letflat)
137
138 --------------------------------
139 -- Simple let binding removal
140 --------------------------------
141 -- Remove a = b bindings from let expressions everywhere
142 letremovetop :: Transform
143 letremovetop = everywhere ("letremove", inlinebind (\(b, e) -> case e of (Var v) | not $ Id.isDataConWorkId v -> True; otherwise -> False))
144
145 --------------------------------
146 -- Function inlining
147 --------------------------------
148 -- Remove a = B bindings, with B :: a -> b, or B :: forall x . T, from let
149 -- expressions everywhere. This means that any value that still needs to be
150 -- applied to something else (polymorphic values need to be applied to a
151 -- Type) will be inlined, and will eventually be applied to all their
152 -- arguments.
153 --
154 -- This is a tricky function, which is prone to create loops in the
155 -- transformations. To fix this, we make sure that no transformation will
156 -- create a new let binding with a function type. These other transformations
157 -- will just not work on those function-typed values at first, but the other
158 -- transformations (in particular β-reduction) should make sure that the type
159 -- of those values eventually becomes primitive.
160 inlinefuntop :: Transform
161 inlinefuntop = everywhere ("inlinefun", inlinebind (is_applicable . snd))
162
163 --------------------------------
164 -- Scrutinee simplification
165 --------------------------------
166 scrutsimpl,scrutsimpltop :: Transform
167 -- Don't touch scrutinees that are already simple
168 scrutsimpl expr@(Case (Var _) _ _ _) = return expr
169 -- Replace all other cases with a let that binds the scrutinee and a new
170 -- simple scrutinee, but not when the scrutinee is applicable (to prevent
171 -- loops with inlinefun, though I don't think a scrutinee can be
172 -- applicable...)
173 scrutsimpl (Case scrut b ty alts) | not $ is_applicable scrut = do
174   id <- mkInternalVar "scrut" (CoreUtils.exprType scrut)
175   change $ Let (Rec [(id, scrut)]) (Case (Var id) b ty alts)
176 -- Leave all other expressions unchanged
177 scrutsimpl expr = return expr
178 -- Perform this transform everywhere
179 scrutsimpltop = everywhere ("scrutsimpl", scrutsimpl)
180
181 --------------------------------
182 -- Case binder wildening
183 --------------------------------
184 casewild, casewildtop :: Transform
185 casewild expr@(Case scrut b ty alts) = do
186   (bindingss, alts') <- (Monad.liftM unzip) $ mapM doalt alts
187   let bindings = concat bindingss
188   -- Replace the case with a let with bindings and a case
189   let newlet = (Let (Rec bindings) (Case scrut b ty alts'))
190   -- If there are no non-wild binders, or this case is already a simple
191   -- selector (i.e., a single alt with exactly one binding), already a simple
192   -- selector altan no bindings (i.e., no wild binders in the original case),
193   -- don't change anything, otherwise, replace the case.
194   if null bindings || length alts == 1 && length bindings == 1 then return expr else change newlet 
195   where
196   -- Generate a single wild binder, since they are all the same
197   wild = Id.mkWildId
198   -- Wilden the binders of one alt, producing a list of bindings as a
199   -- sideeffect.
200   doalt :: CoreAlt -> TransformMonad ([(CoreBndr, CoreExpr)], CoreAlt)
201   doalt (con, bndrs, expr) = do
202     bindings_maybe <- Monad.zipWithM mkextracts bndrs [0..]
203     let bindings = Maybe.catMaybes bindings_maybe
204     -- We replace the binders with wild binders only. We can leave expr
205     -- unchanged, since the new bindings bind the same vars as the original
206     -- did.
207     let newalt = (con, wildbndrs, expr)
208     return (bindings, newalt)
209     where
210       -- Make all binders wild
211       wildbndrs = map (\bndr -> Id.mkWildId (Id.idType bndr)) bndrs
212       -- Creates a case statement to retrieve the ith element from the scrutinee
213       -- and binds that to b.
214       mkextracts :: CoreBndr -> Int -> TransformMonad (Maybe (CoreBndr, CoreExpr))
215       mkextracts b i =
216         if is_wild b || Type.isFunTy (Id.idType b) 
217           -- Don't create extra bindings for binders that are already wild, or
218           -- for binders that bind function types (to prevent loops with
219           -- inlinefun).
220           then return Nothing
221           else do
222             -- Create on new binder that will actually capture a value in this
223             -- case statement, and return it
224             let bty = (Id.idType b)
225             id <- mkInternalVar "sel" bty
226             let binders = take i wildbndrs ++ [id] ++ drop (i+1) wildbndrs
227             return $ Just (b, Case scrut b bty [(con, binders, Var id)])
228 -- Leave all other expressions unchanged
229 casewild expr = return expr
230 -- Perform this transform everywhere
231 casewildtop = everywhere ("casewild", casewild)
232
233 --------------------------------
234 -- Case value simplification
235 --------------------------------
236 casevalsimpl, casevalsimpltop :: Transform
237 casevalsimpl expr@(Case scrut b ty alts) = do
238   -- Try to simplify each alternative, resulting in an optional binding and a
239   -- new alternative.
240   (bindings_maybe, alts') <- (Monad.liftM unzip) $ mapM doalt alts
241   let bindings = Maybe.catMaybes bindings_maybe
242   -- Create a new let around the case, that binds of the cases values.
243   let newlet = Let (Rec bindings) (Case scrut b ty alts')
244   -- If there were no values that needed and allowed simplification, don't
245   -- change the case.
246   if null bindings then return expr else change newlet 
247   where
248     doalt :: CoreAlt -> TransformMonad (Maybe (CoreBndr, CoreExpr), CoreAlt)
249     -- Don't simplify values that are already simple
250     doalt alt@(con, bndrs, Var _) = return (Nothing, alt)
251     -- Simplify each alt by creating a new id, binding the case value to it and
252     -- replacing the case value with that id. Only do this when the case value
253     -- does not use any of the binders bound by this alternative, for that would
254     -- cause those binders to become unbound when moving the value outside of
255     -- the case statement. Also, don't create a binding for applicable
256     -- expressions, to prevent loops with inlinefun.
257     doalt (con, bndrs, expr) | (not usesvars) && (not $ is_applicable expr) = do
258       id <- mkInternalVar "caseval" (CoreUtils.exprType expr)
259       -- We don't flag a change here, since casevalsimpl will do that above
260       -- based on Just we return here.
261       return $ (Just (id, expr), (con, bndrs, Var id))
262       -- Find if any of the binders are used by expr
263       where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` bndrs))) expr
264     -- Don't simplify anything else
265     doalt alt = return (Nothing, alt)
266 -- Leave all other expressions unchanged
267 casevalsimpl expr = return expr
268 -- Perform this transform everywhere
269 casevalsimpltop = everywhere ("casevalsimpl", casevalsimpl)
270
271 --------------------------------
272 -- Case removal
273 --------------------------------
274 -- Remove case statements that have only a single alternative and only wild
275 -- binders.
276 caseremove, caseremovetop :: Transform
277 -- Replace a useless case by the value of its single alternative
278 caseremove (Case scrut b ty [(con, bndrs, expr)]) | not usesvars = change expr
279     -- Find if any of the binders are used by expr
280     where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` bndrs))) expr
281 -- Leave all other expressions unchanged
282 caseremove expr = return expr
283 -- Perform this transform everywhere
284 caseremovetop = everywhere ("caseremove", caseremove)
285
286 --------------------------------
287 -- Application simplification
288 --------------------------------
289 -- Make sure that all arguments in an application are simple variables.
290 appsimpl, appsimpltop :: Transform
291 -- Don't simplify arguments that are already simple. Do simplify datacons,
292 -- however, since we can't portmap literals.
293 appsimpl expr@(App f (Var v)) | not $ Id.isDataConWorkId v = return expr
294 -- Simplify all non-applicable (to prevent loops with inlinefun) arguments,
295 -- except for type arguments (since a let can't bind type vars, only a lambda
296 -- can). Do this by introducing a new Let that binds the argument and passing
297 -- the new binder in the application.
298 appsimpl (App f expr) | (not $ is_applicable expr) && (not $ CoreSyn.isTypeArg expr) = do
299   id <- mkInternalVar "arg" (CoreUtils.exprType expr)
300   change $ Let (Rec [(id, expr)]) (App f (Var id))
301 -- Leave all other expressions unchanged
302 appsimpl expr = return expr
303 -- Perform this transform everywhere
304 appsimpltop = everywhere ("appsimpl", appsimpl)
305
306
307 --------------------------------
308 -- Type argument propagation
309 --------------------------------
310 -- Remove all applications to type arguments, by duplicating the function
311 -- called with the type application in its new definition. We leave
312 -- dictionaries that might be associated with the type untouched, the funprop
313 -- transform should propagate these later on.
314 typeprop, typeproptop :: Transform
315 -- Transform any function that is applied to a type argument. Since type
316 -- arguments are always the first ones to apply and we'll remove all type
317 -- arguments, we can simply do them one by one. We only propagate type
318 -- arguments without any free tyvars, since tyvars those wouldn't be in scope
319 -- in the new function.
320 typeprop expr@(App (Var f) arg@(Type ty)) | not $ has_free_tyvars arg = do
321   body_maybe <- Trans.lift $ getGlobalBind f
322   case body_maybe of
323     Just body -> do
324       let newbody = App body (Type ty)
325       -- Create a new function with the same name but a new body
326       newf <- mkFunction f newbody
327       -- Replace the application with this new function
328       change (Var newf)
329     -- If we don't have a body for the function called, leave it unchanged (it
330     -- should be a primitive function then).
331     Nothing -> return expr
332 -- Leave all other expressions unchanged
333 typeprop expr = return expr
334 -- Perform this transform everywhere
335 typeproptop = everywhere ("typeprop", typeprop)
336
337
338 --------------------------------
339 -- Function-typed argument propagation
340 --------------------------------
341 -- Remove all applications to function-typed arguments, by duplication the
342 -- function called with the function-typed parameter replaced by the free
343 -- variables of the argument passed in.
344 funprop, funproptop :: Transform
345 -- Transform any application of a named function (i.e., skip applications of
346 -- lambda's). Also skip applications that have arguments with free type
347 -- variables, since we can't inline those.
348 funprop expr@(App _ _) | is_var fexpr && not (any has_free_tyvars args) = do
349   -- Find the body of the function called
350   body_maybe <- Trans.lift $ getGlobalBind f
351   case body_maybe of
352     Just body -> do
353       -- Process each of the arguments in turn
354       (args', changed) <- Writer.listen $ mapM doarg args
355       -- See if any of the arguments changed
356       case Monoid.getAny changed of
357         True -> do
358           let (newargs', newparams', oldargs) = unzip3 args'
359           let newargs = concat newargs'
360           let newparams = concat newparams'
361           -- Create a new body that consists of a lambda for all new arguments and
362           -- the old body applied to some arguments.
363           let newbody = MkCore.mkCoreLams newparams (MkCore.mkCoreApps body oldargs)
364           -- Create a new function with the same name but a new body
365           newf <- mkFunction f newbody
366           -- Replace the original application with one of the new function to the
367           -- new arguments.
368           change $ MkCore.mkCoreApps (Var newf) newargs
369         False ->
370           -- Don't change the expression if none of the arguments changed
371           return expr
372       
373     -- If we don't have a body for the function called, leave it unchanged (it
374     -- should be a primitive function then).
375     Nothing -> return expr
376   where
377     -- Find the function called and the arguments
378     (fexpr, args) = collectArgs expr
379     Var f = fexpr
380
381     -- Process a single argument and return (args, bndrs, arg), where args are
382     -- the arguments to replace the given argument in the original
383     -- application, bndrs are the binders to include in the top-level lambda
384     -- in the new function body, and arg is the argument to apply to the old
385     -- function body.
386     doarg :: CoreExpr -> TransformMonad ([CoreExpr], [CoreBndr], CoreExpr)
387     doarg arg | is_fun arg = do
388       bndrs <- Trans.lift getGlobalBinders
389       -- Find interesting free variables, each of which should be passed to
390       -- the new function instead of the original function argument.
391       -- 
392       -- Interesting vars are those that are local, but not available from the
393       -- top level scope (functions from this module are defined as local, but
394       -- they're not local to this function, so we can freely move references
395       -- to them into another function).
396       let interesting var = Var.isLocalVar var && (not $ var `elem` bndrs)
397       let free_vars = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars interesting arg
398       -- Mark the current expression as changed
399       setChanged
400       return (map Var free_vars, free_vars, arg)
401     -- Non-functiontyped arguments can be unchanged. Note that this handles
402     -- both values and types.
403     doarg arg = do
404       -- TODO: preserve original naming?
405       id <- mkBinderFor arg "param"
406       -- Just pass the original argument to the new function, which binds it
407       -- to a new id and just pass that new id to the old function body.
408       return ([arg], [id], mkReferenceTo id) 
409 -- Leave all other expressions unchanged
410 funprop expr = return expr
411 -- Perform this transform everywhere
412 funproptop = everywhere ("funprop", funprop)
413
414 --------------------------------
415 -- Function-typed argument extraction
416 --------------------------------
417 -- This transform takes any function-typed argument that cannot be propagated
418 -- (because the function that is applied to it is a builtin function), and
419 -- puts it in a brand new top level binder. This allows us to for example
420 -- apply map to a lambda expression This will not conflict with inlinefun,
421 -- since that only inlines local let bindings, not top level bindings.
422 funextract, funextracttop :: Transform
423 funextract expr@(App _ _) | is_var fexpr = do
424   body_maybe <- Trans.lift $ getGlobalBind f
425   case body_maybe of
426     -- We don't have a function body for f, so we can perform this transform.
427     Nothing -> do
428       -- Find the new arguments
429       args' <- mapM doarg args
430       -- And update the arguments. We use return instead of changed, so the
431       -- changed flag doesn't get set if none of the args got changed.
432       return $ MkCore.mkCoreApps fexpr args'
433     -- We have a function body for f, leave this application to funprop
434     Just _ -> return expr
435   where
436     -- Find the function called and the arguments
437     (fexpr, args) = collectArgs expr
438     Var f = fexpr
439     -- Change any arguments that have a function type, but are not simple yet
440     -- (ie, a variable or application). This means to create a new function
441     -- for map (\f -> ...) b, but not for map (foo a) b.
442     --
443     -- We could use is_applicable here instead of is_fun, but I think
444     -- arguments to functions could only have forall typing when existential
445     -- typing is enabled. Not sure, though.
446     doarg arg | not (is_simple arg) && is_fun arg = do
447       -- Create a new top level binding that binds the argument. Its body will
448       -- be extended with lambda expressions, to take any free variables used
449       -- by the argument expression.
450       let free_vars = VarSet.varSetElems $ CoreFVs.exprFreeVars arg
451       let body = MkCore.mkCoreLams free_vars arg
452       id <- mkBinderFor body "fun"
453       Trans.lift $ addGlobalBind id body
454       -- Replace the argument with a reference to the new function, applied to
455       -- all vars it uses.
456       change $ MkCore.mkCoreApps (Var id) (map Var free_vars)
457     -- Leave all other arguments untouched
458     doarg arg = return arg
459
460 -- Leave all other expressions unchanged
461 funextract expr = return expr
462 -- Perform this transform everywhere
463 funextracttop = everywhere ("funextract", funextract)
464
465 --------------------------------
466 -- End of transformations
467 --------------------------------
468
469
470
471
472 -- What transforms to run?
473 transforms = [typeproptop, funproptop, funextracttop, etatop, betatop, castproptop, letremovetop, letrectop, letsimpltop, letflattop, casewildtop, scrutsimpltop, casevalsimpltop, caseremovetop, inlinefuntop, appsimpltop]
474
475 -- Turns the given bind into VHDL
476 normalizeModule :: 
477   UniqSupply.UniqSupply -- ^ A UniqSupply we can use
478   -> [(CoreBndr, CoreExpr)]  -- ^ All bindings we know (i.e., in the current module)
479   -> [CoreBndr]  -- ^ The bindings to generate VHDL for (i.e., the top level bindings)
480   -> [Bool] -- ^ For each of the bindings to generate VHDL for, if it is stateful
481   -> [(CoreBndr, CoreExpr)] -- ^ The resulting VHDL
482
483 normalizeModule uniqsupply bindings generate_for statefuls = runTransformSession uniqsupply $ do
484   -- Put all the bindings in this module in the tsBindings map
485   putA tsBindings (Map.fromList bindings)
486   -- (Recursively) normalize each of the requested bindings
487   mapM normalizeBind generate_for
488   -- Get all initial bindings and the ones we produced
489   bindings_map <- getA tsBindings
490   let bindings = Map.assocs bindings_map
491   normalized_bindings <- getA tsNormalized
492   -- But return only the normalized bindings
493   return $ filter ((flip VarSet.elemVarSet normalized_bindings) . fst) bindings
494
495 normalizeBind :: CoreBndr -> TransformSession ()
496 normalizeBind bndr =
497   -- Don't normalize global variables, these should be either builtin
498   -- functions or data constructors.
499   Monad.when (Var.isLocalIdVar bndr) $ do
500     -- Skip binders that have a polymorphic type, since it's impossible to
501     -- create polymorphic hardware.
502     if is_poly (Var bndr)
503       then
504         -- This should really only happen at the top level... TODO: Give
505         -- a different error if this happens down in the recursion.
506         error $ "Function " ++ show bndr ++ " is polymorphic, can't normalize"
507       else do
508         normalized_funcs <- getA tsNormalized
509         -- See if this function was normalized already
510         if VarSet.elemVarSet bndr normalized_funcs
511           then
512             -- Yup, don't do it again
513             return ()
514           else do
515             -- Nope, note that it has been and do it.
516             modA tsNormalized (flip VarSet.extendVarSet bndr)
517             expr_maybe <- getGlobalBind bndr
518             case expr_maybe of 
519               Just expr -> do
520                 -- Introduce an empty Let at the top level, so there will always be
521                 -- a let in the expression (none of the transformations will remove
522                 -- the last let).
523                 let expr' = Let (Rec []) expr
524                 -- Normalize this expression
525                 trace ("Transforming " ++ (show bndr) ++ "\nBefore:\n\n" ++ showSDoc ( ppr expr' ) ++ "\n") $ return ()
526                 expr' <- dotransforms transforms expr'
527                 trace ("\nAfter:\n\n" ++ showSDoc ( ppr expr')) $ return ()
528                 -- And store the normalized version in the session
529                 modA tsBindings (Map.insert bndr expr')
530                 -- Find all vars used with a function type. All of these should be global
531                 -- binders (i.e., functions used), since any local binders with a function
532                 -- type should have been inlined already.
533                 let used_funcs_set = CoreFVs.exprSomeFreeVars (\v -> (Type.isFunTy . snd . Type.splitForAllTys . Id.idType) v) expr'
534                 let used_funcs = VarSet.varSetElems used_funcs_set
535                 -- Process each of the used functions recursively
536                 mapM normalizeBind used_funcs
537                 return ()
538               -- We don't have a value for this binder. This really shouldn't
539               -- happen for local id's...
540               Nothing -> error $ "No value found for binder " ++ pprString bndr ++ "? This should not happen!"