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