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