1 {-# LANGUAGE PackageImports #-}
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
7 module CLasH.Normalize (getNormalized, normalizeExpr) where
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
21 import qualified UniqSupply
22 import qualified CoreUtils
24 import qualified TcType
27 import qualified VarSet
28 import qualified NameSet
29 import qualified CoreFVs
30 import qualified CoreUtils
31 import qualified MkCore
32 import qualified HscTypes
33 import Outputable ( showSDoc, ppr, nest )
36 import CLasH.Normalize.NormalizeTypes
37 import CLasH.Translator.TranslatorTypes
38 import CLasH.Normalize.NormalizeTools
39 import CLasH.VHDL.VHDLTypes
40 import qualified CLasH.Utils as Utils
41 import CLasH.Utils.Core.CoreTools
42 import CLasH.Utils.Core.BinderTools
43 import CLasH.Utils.Pretty
45 --------------------------------
46 -- Start of transformations
47 --------------------------------
49 --------------------------------
51 --------------------------------
52 eta, etatop :: Transform
53 eta expr | is_fun expr && not (is_lam expr) = do
54 let arg_ty = (fst . Type.splitFunTy . CoreUtils.exprType) expr
55 id <- Trans.lift $ mkInternalVar "param" arg_ty
56 change (Lam id (App expr (Var id)))
57 -- Leave all other expressions unchanged
59 etatop = notappargs ("eta", eta)
61 --------------------------------
63 --------------------------------
64 beta, betatop :: Transform
65 -- Substitute arg for x in expr
66 beta (App (Lam x expr) arg) = change $ substitute [(x, arg)] expr
67 -- Propagate the application into the let
68 beta (App (Let binds expr) arg) = change $ Let binds (App expr arg)
69 -- Propagate the application into each of the alternatives
70 beta (App (Case scrut b ty alts) arg) = change $ Case scrut b ty' alts'
72 alts' = map (\(con, bndrs, expr) -> (con, bndrs, (App expr arg))) alts
73 ty' = CoreUtils.applyTypeToArg ty arg
74 -- Leave all other expressions unchanged
75 beta expr = return expr
76 -- Perform this transform everywhere
77 betatop = everywhere ("beta", beta)
79 --------------------------------
81 --------------------------------
82 -- Try to move casts as much downward as possible.
83 castprop, castproptop :: Transform
84 castprop (Cast (Let binds expr) ty) = change $ Let binds (Cast expr ty)
85 castprop expr@(Cast (Case scrut b _ alts) ty) = change (Case scrut b ty alts')
87 alts' = map (\(con, bndrs, expr) -> (con, bndrs, (Cast expr ty))) alts
88 -- Leave all other expressions unchanged
89 castprop expr = return expr
90 -- Perform this transform everywhere
91 castproptop = everywhere ("castprop", castprop)
93 --------------------------------
94 -- let recursification
95 --------------------------------
96 letrec, letrectop :: Transform
97 letrec (Let (NonRec b expr) res) = change $ Let (Rec [(b, expr)]) res
98 -- Leave all other expressions unchanged
99 letrec expr = return expr
100 -- Perform this transform everywhere
101 letrectop = everywhere ("letrec", letrec)
103 --------------------------------
104 -- let simplification
105 --------------------------------
106 letsimpl, letsimpltop :: Transform
107 -- Put the "in ..." value of a let in its own binding, but not when the
108 -- expression is already a local variable, or not representable (to prevent loops with inlinenonrep).
109 letsimpl expr@(Let (Rec binds) res) = do
111 local_var <- Trans.lift $ is_local_var res
112 if not local_var && repr
114 -- If the result is not a local var already (to prevent loops with
115 -- ourselves), extract it.
116 id <- Trans.lift $ mkInternalVar "foo" (CoreUtils.exprType res)
118 change $ Let (Rec (bind:binds)) (Var id)
120 -- If the result is already a local var, don't extract it.
123 -- Leave all other expressions unchanged
124 letsimpl expr = return expr
125 -- Perform this transform everywhere
126 letsimpltop = everywhere ("letsimpl", letsimpl)
128 --------------------------------
130 --------------------------------
131 letflat, letflattop :: Transform
132 letflat (Let (Rec binds) expr) = do
133 -- Turn each binding into a list of bindings (possibly containing just one
134 -- element, of course)
135 bindss <- Monad.mapM flatbind binds
136 -- Concat all the bindings
137 let binds' = concat bindss
138 -- Return the new let. We don't use change here, since possibly nothing has
139 -- changed. If anything has changed, flatbind has already flagged that
141 return $ Let (Rec binds') expr
143 -- Turns a binding of a let into a multiple bindings, or any other binding
144 -- into a list with just that binding
145 flatbind :: (CoreBndr, CoreExpr) -> TransformMonad [(CoreBndr, CoreExpr)]
146 flatbind (b, Let (Rec binds) expr) = change ((b, expr):binds)
147 flatbind (b, expr) = return [(b, expr)]
148 -- Leave all other expressions unchanged
149 letflat expr = return expr
150 -- Perform this transform everywhere
151 letflattop = everywhere ("letflat", letflat)
153 --------------------------------
154 -- Simple let binding removal
155 --------------------------------
156 -- Remove a = b bindings from let expressions everywhere
157 letremovetop :: Transform
158 letremovetop = everywhere ("letremove", inlinebind (\(b, e) -> Trans.lift $ is_local_var e))
160 --------------------------------
162 --------------------------------
163 -- Remove a = B bindings, with B :: a -> b, or B :: forall x . T, from let
164 -- expressions everywhere. This means that any value that still needs to be
165 -- applied to something else (polymorphic values need to be applied to a
166 -- Type) will be inlined, and will eventually be applied to all their
169 -- This is a tricky function, which is prone to create loops in the
170 -- transformations. To fix this, we make sure that no transformation will
171 -- create a new let binding with a function type. These other transformations
172 -- will just not work on those function-typed values at first, but the other
173 -- transformations (in particular β-reduction) should make sure that the type
174 -- of those values eventually becomes primitive.
175 inlinenonreptop :: Transform
176 inlinenonreptop = everywhere ("inlinenonrep", inlinebind ((Monad.liftM not) . isRepr . snd))
178 --------------------------------
179 -- Scrutinee simplification
180 --------------------------------
181 scrutsimpl,scrutsimpltop :: Transform
182 -- Don't touch scrutinees that are already simple
183 scrutsimpl expr@(Case (Var _) _ _ _) = return expr
184 -- Replace all other cases with a let that binds the scrutinee and a new
185 -- simple scrutinee, but only when the scrutinee is representable (to prevent
186 -- loops with inlinenonrep, though I don't think a non-representable scrutinee
187 -- will be supported anyway...)
188 scrutsimpl expr@(Case scrut b ty alts) = do
192 id <- Trans.lift $ mkInternalVar "scrut" (CoreUtils.exprType scrut)
193 change $ Let (Rec [(id, scrut)]) (Case (Var id) b ty alts)
196 -- Leave all other expressions unchanged
197 scrutsimpl expr = return expr
198 -- Perform this transform everywhere
199 scrutsimpltop = everywhere ("scrutsimpl", scrutsimpl)
201 --------------------------------
202 -- Case binder wildening
203 --------------------------------
204 casesimpl, casesimpltop :: Transform
205 -- This is already a selector case (or, if x does not appear in bndrs, a very
206 -- simple case statement that will be removed by caseremove below). Just leave
208 casesimpl expr@(Case scrut b ty [(con, bndrs, Var x)]) = return expr
209 -- Make sure that all case alternatives have only wild binders and simple
211 -- This is done by creating a new let binding for each non-wild binder, which
212 -- is bound to a new simple selector case statement and for each complex
213 -- expression. We do this only for representable types, to prevent loops with
215 casesimpl expr@(Case scrut b ty alts) = do
216 (bindingss, alts') <- (Monad.liftM unzip) $ mapM doalt alts
217 let bindings = concat bindingss
218 -- Replace the case with a let with bindings and a case
219 let newlet = (Let (Rec bindings) (Case scrut b ty alts'))
220 -- If there are no non-wild binders, or this case is already a simple
221 -- selector (i.e., a single alt with exactly one binding), already a simple
222 -- selector altan no bindings (i.e., no wild binders in the original case),
223 -- don't change anything, otherwise, replace the case.
224 if null bindings then return expr else change newlet
226 -- Generate a single wild binder, since they are all the same
227 wild = MkCore.mkWildBinder
228 -- Wilden the binders of one alt, producing a list of bindings as a
230 doalt :: CoreAlt -> TransformMonad ([(CoreBndr, CoreExpr)], CoreAlt)
231 doalt (con, bndrs, expr) = do
232 -- Make each binder wild, if possible
233 bndrs_res <- Monad.zipWithM dobndr bndrs [0..]
234 let (newbndrs, bindings_maybe) = unzip bndrs_res
235 -- Extract a complex expression, if possible. For this we check if any of
236 -- the new list of bndrs are used by expr. We can't use free_vars here,
237 -- since that looks at the old bndrs.
238 let uses_bndrs = not $ VarSet.isEmptyVarSet $ CoreFVs.exprSomeFreeVars (`elem` newbndrs) $ expr
239 (exprbinding_maybe, expr') <- doexpr expr uses_bndrs
240 -- Create a new alternative
241 let newalt = (con, newbndrs, expr')
242 let bindings = Maybe.catMaybes (exprbinding_maybe : bindings_maybe)
243 return (bindings, newalt)
245 -- Make wild alternatives for each binder
246 wildbndrs = map (\bndr -> MkCore.mkWildBinder (Id.idType bndr)) bndrs
247 -- A set of all the binders that are used by the expression
248 free_vars = CoreFVs.exprSomeFreeVars (`elem` bndrs) expr
249 -- Look at the ith binder in the case alternative. Return a new binder
250 -- for it (either the same one, or a wild one) and optionally a let
251 -- binding containing a case expression.
252 dobndr :: CoreBndr -> Int -> TransformMonad (CoreBndr, Maybe (CoreBndr, CoreExpr))
254 repr <- isRepr (Var b)
255 -- Is b wild (e.g., not a free var of expr. Since b is only in scope
256 -- in expr, this means that b is unused if expr does not use it.)
257 let wild = not (VarSet.elemVarSet b free_vars)
258 -- Create a new binding for any representable binder that is not
259 -- already wild and is representable (to prevent loops with
261 if (not wild) && repr
263 -- Create on new binder that will actually capture a value in this
264 -- case statement, and return it.
265 let bty = (Id.idType b)
266 id <- Trans.lift $ mkInternalVar "sel" bty
267 let binders = take i wildbndrs ++ [id] ++ drop (i+1) wildbndrs
268 let caseexpr = Case scrut b bty [(con, binders, Var id)]
269 return (wildbndrs!!i, Just (b, caseexpr))
271 -- Just leave the original binder in place, and don't generate an
272 -- extra selector case.
274 -- Process the expression of a case alternative. Accepts an expression
275 -- and whether this expression uses any of the binders in the
276 -- alternative. Returns an optional new binding and a new expression.
277 doexpr :: CoreExpr -> Bool -> TransformMonad (Maybe (CoreBndr, CoreExpr), CoreExpr)
278 doexpr expr uses_bndrs = do
279 local_var <- Trans.lift $ is_local_var expr
281 -- Extract any expressions that do not use any binders from this
282 -- alternative, is not a local var already and is representable (to
283 -- prevent loops with inlinenonrep).
284 if (not uses_bndrs) && (not local_var) && repr
286 id <- Trans.lift $ mkInternalVar "caseval" (CoreUtils.exprType expr)
287 -- We don't flag a change here, since casevalsimpl will do that above
288 -- based on Just we return here.
289 return $ (Just (id, expr), Var id)
291 -- Don't simplify anything else
292 return (Nothing, expr)
293 -- Leave all other expressions unchanged
294 casesimpl expr = return expr
295 -- Perform this transform everywhere
296 casesimpltop = everywhere ("casesimpl", casesimpl)
298 --------------------------------
300 --------------------------------
301 -- Remove case statements that have only a single alternative and only wild
303 caseremove, caseremovetop :: Transform
304 -- Replace a useless case by the value of its single alternative
305 caseremove (Case scrut b ty [(con, bndrs, expr)]) | not usesvars = change expr
306 -- Find if any of the binders are used by expr
307 where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` bndrs))) expr
308 -- Leave all other expressions unchanged
309 caseremove expr = return expr
310 -- Perform this transform everywhere
311 caseremovetop = everywhere ("caseremove", caseremove)
313 --------------------------------
314 -- Argument extraction
315 --------------------------------
316 -- Make sure that all arguments of a representable type are simple variables.
317 appsimpl, appsimpltop :: Transform
318 -- Simplify all representable arguments. Do this by introducing a new Let
319 -- that binds the argument and passing the new binder in the application.
320 appsimpl expr@(App f arg) = do
321 -- Check runtime representability
323 local_var <- Trans.lift $ is_local_var arg
324 if repr && not local_var
325 then do -- Extract representable arguments
326 id <- Trans.lift $ mkInternalVar "arg" (CoreUtils.exprType arg)
327 change $ Let (Rec [(id, arg)]) (App f (Var id))
328 else -- Leave non-representable arguments unchanged
330 -- Leave all other expressions unchanged
331 appsimpl expr = return expr
332 -- Perform this transform everywhere
333 appsimpltop = everywhere ("appsimpl", appsimpl)
335 --------------------------------
336 -- Function-typed argument propagation
337 --------------------------------
338 -- Remove all applications to function-typed arguments, by duplication the
339 -- function called with the function-typed parameter replaced by the free
340 -- variables of the argument passed in.
341 argprop, argproptop :: Transform
342 -- Transform any application of a named function (i.e., skip applications of
343 -- lambda's). Also skip applications that have arguments with free type
344 -- variables, since we can't inline those.
345 argprop expr@(App _ _) | is_var fexpr = do
346 -- Find the body of the function called
347 body_maybe <- Trans.lift $ getGlobalBind f
350 -- Process each of the arguments in turn
351 (args', changed) <- Writer.listen $ mapM doarg args
352 -- See if any of the arguments changed
353 case Monoid.getAny changed of
355 let (newargs', newparams', oldargs) = unzip3 args'
356 let newargs = concat newargs'
357 let newparams = concat newparams'
358 -- Create a new body that consists of a lambda for all new arguments and
359 -- the old body applied to some arguments.
360 let newbody = MkCore.mkCoreLams newparams (MkCore.mkCoreApps body oldargs)
361 -- Create a new function with the same name but a new body
362 newf <- Trans.lift $ mkFunction f newbody
363 -- Replace the original application with one of the new function to the
365 change $ MkCore.mkCoreApps (Var newf) newargs
367 -- Don't change the expression if none of the arguments changed
370 -- If we don't have a body for the function called, leave it unchanged (it
371 -- should be a primitive function then).
372 Nothing -> return expr
374 -- Find the function called and the arguments
375 (fexpr, args) = collectArgs expr
378 -- Process a single argument and return (args, bndrs, arg), where args are
379 -- the arguments to replace the given argument in the original
380 -- application, bndrs are the binders to include in the top-level lambda
381 -- in the new function body, and arg is the argument to apply to the old
383 doarg :: CoreExpr -> TransformMonad ([CoreExpr], [CoreBndr], CoreExpr)
386 bndrs <- Trans.lift getGlobalBinders
387 let interesting var = Var.isLocalVar var && (not $ var `elem` bndrs)
388 if not repr && not (is_var arg && interesting (exprToVar arg)) && not (has_free_tyvars arg)
390 -- Propagate all complex arguments that are not representable, but not
391 -- arguments with free type variables (since those would require types
392 -- not known yet, which will always be known eventually).
393 -- Find interesting free variables, each of which should be passed to
394 -- the new function instead of the original function argument.
396 -- Interesting vars are those that are local, but not available from the
397 -- top level scope (functions from this module are defined as local, but
398 -- they're not local to this function, so we can freely move references
399 -- to them into another function).
400 let free_vars = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars interesting arg
401 -- Mark the current expression as changed
403 return (map Var free_vars, free_vars, arg)
405 -- Representable types will not be propagated, and arguments with free
406 -- type variables will be propagated later.
407 -- TODO: preserve original naming?
408 id <- Trans.lift $ mkBinderFor arg "param"
409 -- Just pass the original argument to the new function, which binds it
410 -- to a new id and just pass that new id to the old function body.
411 return ([arg], [id], mkReferenceTo id)
412 -- Leave all other expressions unchanged
413 argprop expr = return expr
414 -- Perform this transform everywhere
415 argproptop = everywhere ("argprop", argprop)
417 --------------------------------
418 -- Function-typed argument extraction
419 --------------------------------
420 -- This transform takes any function-typed argument that cannot be propagated
421 -- (because the function that is applied to it is a builtin function), and
422 -- puts it in a brand new top level binder. This allows us to for example
423 -- apply map to a lambda expression This will not conflict with inlinenonrep,
424 -- since that only inlines local let bindings, not top level bindings.
425 funextract, funextracttop :: Transform
426 funextract expr@(App _ _) | is_var fexpr = do
427 body_maybe <- Trans.lift $ getGlobalBind f
429 -- We don't have a function body for f, so we can perform this transform.
431 -- Find the new arguments
432 args' <- mapM doarg args
433 -- And update the arguments. We use return instead of changed, so the
434 -- changed flag doesn't get set if none of the args got changed.
435 return $ MkCore.mkCoreApps fexpr args'
436 -- We have a function body for f, leave this application to funprop
437 Just _ -> return expr
439 -- Find the function called and the arguments
440 (fexpr, args) = collectArgs expr
442 -- Change any arguments that have a function type, but are not simple yet
443 -- (ie, a variable or application). This means to create a new function
444 -- for map (\f -> ...) b, but not for map (foo a) b.
446 -- We could use is_applicable here instead of is_fun, but I think
447 -- arguments to functions could only have forall typing when existential
448 -- typing is enabled. Not sure, though.
449 doarg arg | not (is_simple arg) && is_fun arg = do
450 -- Create a new top level binding that binds the argument. Its body will
451 -- be extended with lambda expressions, to take any free variables used
452 -- by the argument expression.
453 let free_vars = VarSet.varSetElems $ CoreFVs.exprFreeVars arg
454 let body = MkCore.mkCoreLams free_vars arg
455 id <- Trans.lift $ mkBinderFor body "fun"
456 Trans.lift $ addGlobalBind id body
457 -- Replace the argument with a reference to the new function, applied to
459 change $ MkCore.mkCoreApps (Var id) (map Var free_vars)
460 -- Leave all other arguments untouched
461 doarg arg = return arg
463 -- Leave all other expressions unchanged
464 funextract expr = return expr
465 -- Perform this transform everywhere
466 funextracttop = everywhere ("funextract", funextract)
468 --------------------------------
469 -- End of transformations
470 --------------------------------
475 -- What transforms to run?
476 transforms = [argproptop, funextracttop, etatop, betatop, castproptop, letremovetop, letrectop, letsimpltop, letflattop, scrutsimpltop, casesimpltop, caseremovetop, inlinenonreptop, appsimpltop]
478 -- | Returns the normalized version of the given function.
480 CoreBndr -- ^ The function to get
481 -> TranslatorSession CoreExpr -- The normalized function body
483 getNormalized bndr = Utils.makeCached bndr tsNormalized $ do
484 if is_poly (Var bndr)
486 -- This should really only happen at the top level... TODO: Give
487 -- a different error if this happens down in the recursion.
488 error $ "\nNormalize.normalizeBind: Function " ++ show bndr ++ " is polymorphic, can't normalize"
490 expr <- getBinding bndr
491 normalizeExpr (show bndr) expr
493 -- | Normalize an expression
495 String -- ^ What are we normalizing? For debug output only.
496 -> CoreSyn.CoreExpr -- ^ The expression to normalize
497 -> TranslatorSession CoreSyn.CoreExpr -- ^ The normalized expression
499 normalizeExpr what expr = do
500 -- Introduce an empty Let at the top level, so there will always be
501 -- a let in the expression (none of the transformations will remove
503 let expr' = Let (Rec []) expr
504 -- Normalize this expression
505 trace ("Transforming " ++ what ++ "\nBefore:\n\n" ++ showSDoc ( ppr expr' ) ++ "\n") $ return ()
506 expr'' <- dotransforms transforms expr'
507 trace ("\nAfter:\n\n" ++ showSDoc ( ppr expr')) $ return ()
510 -- | Get the value that is bound to the given binder at top level. Fails when
511 -- there is no such binding.
513 CoreBndr -- ^ The binder to get the expression for
514 -> TranslatorSession CoreExpr -- ^ The value bound to the binder
516 getBinding bndr = Utils.makeCached bndr tsBindings $ do
517 -- If the binding isn't in the "cache" (bindings map), then we can't create
518 -- it out of thin air, so return an error.
519 error $ "Normalize.getBinding: Unknown function requested: " ++ show bndr