2 % (c) The University of Glasgow, 1994-2006
5 Core pass to saturate constructors and PrimOps
9 corePrepPgm, corePrepExpr
12 #include "HsVersions.h"
14 import PrelNames ( lazyIdKey, hasKey )
18 import CoreMonad ( endPass, CoreToDo(..) )
44 -- ---------------------------------------------------------------------------
46 -- ---------------------------------------------------------------------------
48 The goal of this pass is to prepare for code generation.
50 1. Saturate constructor and primop applications.
52 2. Convert to A-normal form; that is, function arguments
55 * Use case for strict arguments:
56 f E ==> case E of x -> f x
59 * Use let for non-trivial lazy arguments
60 f E ==> let x = E in f x
61 (were f is lazy and x is non-trivial)
63 3. Similarly, convert any unboxed lets into cases.
64 [I'm experimenting with leaving 'ok-for-speculation'
65 rhss in let-form right up to this point.]
67 4. Ensure that *value* lambdas only occur as the RHS of a binding
68 (The code generator can't deal with anything else.)
69 Type lambdas are ok, however, because the code gen discards them.
71 5. [Not any more; nuked Jun 2002] Do the seq/par munging.
73 6. Clone all local Ids.
74 This means that all such Ids are unique, rather than the
75 weaker guarantee of no clashes which the simplifier provides.
76 And that is what the code generator needs.
78 We don't clone TyVars. The code gen doesn't need that,
79 and doing so would be tiresome because then we'd need
80 to substitute in types.
83 7. Give each dynamic CCall occurrence a fresh unique; this is
84 rather like the cloning step above.
86 8. Inject bindings for the "implicit" Ids:
87 * Constructor wrappers
89 We want curried definitions for all of these in case they
90 aren't inlined by some caller.
92 9. Replace (lazy e) by e. See Note [lazyId magic] in MkId.lhs
94 This is all done modulo type applications and abstractions, so that
95 when type erasure is done for conversion to STG, we don't end up with
96 any trivial or useless bindings.
101 Here is the syntax of the Core produced by CorePrep:
104 triv ::= lit | var | triv ty | /\a. triv | triv |> co
107 app ::= lit | var | app triv | app ty | app |> co
111 | let(rec) x = rhs in body -- Boxed only
112 | case body of pat -> body
116 Right hand sides (only place where lambdas can occur)
117 rhs ::= /\a.rhs | \x.rhs | body
119 We define a synonym for each of these non-terminals. Functions
120 with the corresponding name produce a result in that syntax.
123 type CpeTriv = CoreExpr -- Non-terminal 'triv'
124 type CpeApp = CoreExpr -- Non-terminal 'app'
125 type CpeBody = CoreExpr -- Non-terminal 'body'
126 type CpeRhs = CoreExpr -- Non-terminal 'rhs'
129 %************************************************************************
133 %************************************************************************
136 corePrepPgm :: DynFlags -> [CoreBind] -> [TyCon] -> IO [CoreBind]
137 corePrepPgm dflags binds data_tycons = do
138 showPass dflags "CorePrep"
139 us <- mkSplitUniqSupply 's'
141 let implicit_binds = mkDataConWorkers data_tycons
142 -- NB: we must feed mkImplicitBinds through corePrep too
143 -- so that they are suitably cloned and eta-expanded
145 binds_out = initUs_ us $ do
146 floats1 <- corePrepTopBinds binds
147 floats2 <- corePrepTopBinds implicit_binds
148 return (deFloatTop (floats1 `appendFloats` floats2))
150 endPass dflags CorePrep binds_out []
153 corePrepExpr :: DynFlags -> CoreExpr -> IO CoreExpr
154 corePrepExpr dflags expr = do
155 showPass dflags "CorePrep"
156 us <- mkSplitUniqSupply 's'
157 let new_expr = initUs_ us (cpeBodyNF emptyCorePrepEnv expr)
158 dumpIfSet_dyn dflags Opt_D_dump_prep "CorePrep" (ppr new_expr)
161 corePrepTopBinds :: [CoreBind] -> UniqSM Floats
162 -- Note [Floating out of top level bindings]
163 corePrepTopBinds binds
164 = go emptyCorePrepEnv binds
166 go _ [] = return emptyFloats
167 go env (bind : binds) = do (env', bind') <- cpeBind TopLevel env bind
168 binds' <- go env' binds
169 return (bind' `appendFloats` binds')
171 mkDataConWorkers :: [TyCon] -> [CoreBind]
172 -- See Note [Data constructor workers]
173 mkDataConWorkers data_tycons
174 = [ NonRec id (Var id) -- The ice is thin here, but it works
175 | tycon <- data_tycons, -- CorePrep will eta-expand it
176 data_con <- tyConDataCons tycon,
177 let id = dataConWorkId data_con ]
180 Note [Floating out of top level bindings]
181 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
182 NB: we do need to float out of top-level bindings
183 Consider x = length [True,False]
189 We return a *list* of bindings, because we may start with
191 where x is demanded, in which case we want to finish with
194 And then x will actually end up case-bound
196 Note [CafInfo and floating]
197 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
198 What happens to the CafInfo on the floated bindings? By default, all
199 the CafInfos will be set to MayHaveCafRefs, which is safe.
201 This might be pessimistic, because the floated binding might not refer
202 to any CAFs and the GC will end up doing more traversal than is
203 necessary, but it's still better than not floating the bindings at
204 all, because then the GC would have to traverse the structure in the
205 heap instead. Given this, we decided not to try to get the CafInfo on
206 the floated bindings correct, because it looks difficult.
208 But that means we can't float anything out of a NoCafRefs binding.
210 If f is NoCafRefs, we don't want to convert to
213 where sat conservatively says HasCafRefs, because now f's info
214 is wrong. I don't think this is common, so we simply switch off
215 floating in this case.
217 Note [Data constructor workers]
218 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
219 Create any necessary "implicit" bindings for data con workers. We
220 create the rather strange (non-recursive!) binding
222 $wC = \x y -> $wC x y
224 i.e. a curried constructor that allocates. This means that we can
225 treat the worker for a constructor like any other function in the rest
226 of the compiler. The point here is that CoreToStg will generate a
227 StgConApp for the RHS, rather than a call to the worker (which would
228 give a loop). As Lennart says: the ice is thin here, but it works.
230 Hmm. Should we create bindings for dictionary constructors? They are
231 always fully applied, and the bindings are just there to support
232 partial applications. But it's easier to let them through.
235 %************************************************************************
239 %************************************************************************
242 cpeBind :: TopLevelFlag
243 -> CorePrepEnv -> CoreBind
244 -> UniqSM (CorePrepEnv, Floats)
245 cpeBind top_lvl env (NonRec bndr rhs)
246 = do { (_, bndr1) <- cloneBndr env bndr
247 ; let is_strict = isStrictDmd (idDemandInfo bndr)
248 is_unlifted = isUnLiftedType (idType bndr)
249 ; (floats, bndr2, rhs2) <- cpePair top_lvl NonRecursive
250 (is_strict || is_unlifted)
252 ; let new_float = mkFloat is_strict is_unlifted bndr2 rhs2
254 -- We want bndr'' in the envt, because it records
255 -- the evaluated-ness of the binder
256 ; return (extendCorePrepEnv env bndr bndr2,
257 addFloat floats new_float) }
259 cpeBind top_lvl env (Rec pairs)
260 = do { let (bndrs,rhss) = unzip pairs
261 ; (env', bndrs1) <- cloneBndrs env (map fst pairs)
262 ; stuff <- zipWithM (cpePair top_lvl Recursive False env') bndrs1 rhss
264 ; let (floats_s, bndrs2, rhss2) = unzip3 stuff
265 all_pairs = foldrOL add_float (bndrs1 `zip` rhss2)
266 (concatFloats floats_s)
267 ; return (extendCorePrepEnvList env (bndrs `zip` bndrs2),
268 unitFloat (FloatLet (Rec all_pairs))) }
270 -- Flatten all the floats, and the currrent
271 -- group into a single giant Rec
272 add_float (FloatLet (NonRec b r)) prs2 = (b,r) : prs2
273 add_float (FloatLet (Rec prs1)) prs2 = prs1 ++ prs2
274 add_float b _ = pprPanic "cpeBind" (ppr b)
277 cpePair :: TopLevelFlag -> RecFlag -> RhsDemand
278 -> CorePrepEnv -> Id -> CoreExpr
279 -> UniqSM (Floats, Id, CpeRhs)
280 -- Used for all bindings
281 cpePair top_lvl is_rec is_strict_or_unlifted env bndr rhs
282 = do { (floats1, rhs1) <- cpeRhsE env rhs
285 <- if manifestArity rhs1 <= arity
286 then return (floats1, cpeEtaExpand arity rhs1)
287 else WARN(True, text "CorePrep: silly extra arguments:" <+> ppr bndr)
288 -- Note [Silly extra arguments]
289 (do { v <- newVar (idType bndr)
290 ; let float = mkFloat False False v rhs1
291 ; return (addFloat floats1 float, cpeEtaExpand arity (Var v)) })
294 <- if want_float floats2 rhs2
295 then return (floats2, rhs2)
296 else -- Non-empty floats will wrap rhs1
297 -- But: rhs1 might have lambdas, and we can't
298 -- put them inside a wrapBinds
299 do { body2 <- rhsToBodyNF rhs2
300 ; return (emptyFloats, wrapBinds floats2 body2) }
302 -- Record if the binder is evaluated
303 ; let bndr' | exprIsHNF rhs' = bndr `setIdUnfolding` evaldUnfolding
306 ; return (floats3, bndr', rhs') }
308 arity = idArity bndr -- We must match this arity
309 want_float floats rhs
310 | isTopLevel top_lvl = wantFloatTop bndr floats
311 | otherwise = wantFloatNested is_rec is_strict_or_unlifted floats rhs
313 {- Note [Silly extra arguments]
314 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
317 We *must* match the arity on the Id, so we have to generate
321 It's a bizarre case: why is the arity on the Id wrong? Reason
322 (in the days of __inline_me__):
323 f{arity=0} = __inline_me__ (let v = expensive in \xy. e)
324 When InlineMe notes go away this won't happen any more. But
325 it seems good for CorePrep to be robust.
328 -- ---------------------------------------------------------------------------
329 -- CpeRhs: produces a result satisfying CpeRhs
330 -- ---------------------------------------------------------------------------
332 cpeRhsE :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
336 -- e = let bs in e' (semantically, that is!)
339 -- f (g x) ===> ([v = g x], f v)
341 cpeRhsE _env expr@(Type _) = return (emptyFloats, expr)
342 cpeRhsE _env expr@(Lit _) = return (emptyFloats, expr)
343 cpeRhsE env expr@(Var {}) = cpeApp env expr
345 cpeRhsE env (Var f `App` _ `App` arg)
346 | f `hasKey` lazyIdKey -- Replace (lazy a) by a
347 = cpeRhsE env arg -- See Note [lazyId magic] in MkId
349 cpeRhsE env expr@(App {}) = cpeApp env expr
351 cpeRhsE env (Let bind expr)
352 = do { (env', new_binds) <- cpeBind NotTopLevel env bind
353 ; (floats, body) <- cpeRhsE env' expr
354 ; return (new_binds `appendFloats` floats, body) }
356 cpeRhsE env (Note note expr)
359 | otherwise -- Just SCCs actually
360 = do { body <- cpeBodyNF env expr
361 ; return (emptyFloats, Note note body) }
363 cpeRhsE env (Cast expr co)
364 = do { (floats, expr') <- cpeRhsE env expr
365 ; return (floats, Cast expr' co) }
367 cpeRhsE env expr@(Lam {})
368 = do { let (bndrs,body) = collectBinders expr
369 ; (env', bndrs') <- cloneBndrs env bndrs
370 ; body' <- cpeBodyNF env' body
371 ; return (emptyFloats, mkLams bndrs' body') }
373 cpeRhsE env (Case (Var id) bndr ty [(DEFAULT,[],expr)])
374 | Just (TickBox {}) <- isTickBoxOp_maybe id
375 = do { body <- cpeBodyNF env expr
376 ; return (emptyFloats, Case (Var id) bndr ty [(DEFAULT,[],body)]) }
378 cpeRhsE env (Case scrut bndr ty alts)
379 = do { (floats, scrut') <- cpeBody env scrut
380 ; let bndr1 = bndr `setIdUnfolding` evaldUnfolding
381 -- Record that the case binder is evaluated in the alternatives
382 ; (env', bndr2) <- cloneBndr env bndr1
383 ; alts' <- mapM (sat_alt env') alts
384 ; return (floats, Case scrut' bndr2 ty alts') }
386 sat_alt env (con, bs, rhs)
387 = do { (env2, bs') <- cloneBndrs env bs
388 ; rhs' <- cpeBodyNF env2 rhs
389 ; return (con, bs', rhs') }
391 -- ---------------------------------------------------------------------------
392 -- CpeBody: produces a result satisfying CpeBody
393 -- ---------------------------------------------------------------------------
395 cpeBodyNF :: CorePrepEnv -> CoreExpr -> UniqSM CpeBody
397 = do { (floats, body) <- cpeBody env expr
398 ; return (wrapBinds floats body) }
401 cpeBody :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeBody)
403 = do { (floats1, rhs) <- cpeRhsE env expr
404 ; (floats2, body) <- rhsToBody rhs
405 ; return (floats1 `appendFloats` floats2, body) }
408 rhsToBodyNF :: CpeRhs -> UniqSM CpeBody
409 rhsToBodyNF rhs = do { (floats,body) <- rhsToBody rhs
410 ; return (wrapBinds floats body) }
413 rhsToBody :: CpeRhs -> UniqSM (Floats, CpeBody)
414 -- Remove top level lambdas by let-binding
416 rhsToBody (Note n expr)
417 -- You can get things like
418 -- case e of { p -> coerce t (\s -> ...) }
419 = do { (floats, expr') <- rhsToBody expr
420 ; return (floats, Note n expr') }
422 rhsToBody (Cast e co)
423 = do { (floats, e') <- rhsToBody e
424 ; return (floats, Cast e' co) }
426 rhsToBody expr@(Lam {})
427 | Just no_lam_result <- tryEtaReduce bndrs body
428 = return (emptyFloats, no_lam_result)
429 | all isTyVar bndrs -- Type lambdas are ok
430 = return (emptyFloats, expr)
431 | otherwise -- Some value lambdas
432 = do { fn <- newVar (exprType expr)
433 ; let rhs = cpeEtaExpand (exprArity expr) expr
434 float = FloatLet (NonRec fn rhs)
435 ; return (unitFloat float, Var fn) }
437 (bndrs,body) = collectBinders expr
439 rhsToBody expr = return (emptyFloats, expr)
443 -- ---------------------------------------------------------------------------
444 -- CpeApp: produces a result satisfying CpeApp
445 -- ---------------------------------------------------------------------------
447 cpeApp :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
448 -- May return a CpeRhs because of saturating primops
450 = do { (app, (head,depth), _, floats, ss) <- collect_args expr 0
451 ; MASSERT(null ss) -- make sure we used all the strictness info
453 -- Now deal with the function
455 Var fn_id -> do { sat_app <- maybeSaturate fn_id app depth
456 ; return (floats, sat_app) }
457 _other -> return (floats, app) }
460 -- Deconstruct and rebuild the application, floating any non-atomic
461 -- arguments to the outside. We collect the type of the expression,
462 -- the head of the application, and the number of actual value arguments,
463 -- all of which are used to possibly saturate this application if it
464 -- has a constructor or primop at the head.
468 -> Int -- Current app depth
469 -> UniqSM (CpeApp, -- The rebuilt expression
470 (CoreExpr,Int), -- The head of the application,
471 -- and no. of args it was applied to
472 Type, -- Type of the whole expr
473 Floats, -- Any floats we pulled out
474 [Demand]) -- Remaining argument demands
476 collect_args (App fun arg@(Type arg_ty)) depth
477 = do { (fun',hd,fun_ty,floats,ss) <- collect_args fun depth
478 ; return (App fun' arg, hd, applyTy fun_ty arg_ty, floats, ss) }
480 collect_args (App fun arg) depth
481 = do { (fun',hd,fun_ty,floats,ss) <- collect_args fun (depth+1)
483 (ss1, ss_rest) = case ss of
484 (ss1:ss_rest) -> (ss1, ss_rest)
486 (arg_ty, res_ty) = expectJust "cpeBody:collect_args" $
487 splitFunTy_maybe fun_ty
489 ; (fs, arg') <- cpeArg env (isStrictDmd ss1) arg arg_ty
490 ; return (App fun' arg', hd, res_ty, fs `appendFloats` floats, ss_rest) }
492 collect_args (Var v) depth
493 = do { v1 <- fiddleCCall v
494 ; let v2 = lookupCorePrepEnv env v1
495 ; return (Var v2, (Var v2, depth), idType v2, emptyFloats, stricts) }
497 stricts = case idStrictness v of
498 StrictSig (DmdType _ demands _)
499 | listLengthCmp demands depth /= GT -> demands
500 -- length demands <= depth
502 -- If depth < length demands, then we have too few args to
503 -- satisfy strictness info so we have to ignore all the
504 -- strictness info, e.g. + (error "urk")
505 -- Here, we can't evaluate the arg strictly, because this
506 -- partial application might be seq'd
508 collect_args (Cast fun co) depth
509 = do { let (_ty1,ty2) = coercionKind co
510 ; (fun', hd, _, floats, ss) <- collect_args fun depth
511 ; return (Cast fun' co, hd, ty2, floats, ss) }
513 collect_args (Note note fun) depth
514 | ignoreNote note -- Drop these notes altogether
515 = collect_args fun depth -- They aren't used by the code generator
517 -- N-variable fun, better let-bind it
518 collect_args fun depth
519 = do { (fun_floats, fun') <- cpeArg env True fun ty
520 -- The True says that it's sure to be evaluated,
521 -- so we'll end up case-binding it
522 ; return (fun', (fun', depth), ty, fun_floats, []) }
526 -- ---------------------------------------------------------------------------
527 -- CpeArg: produces a result satisfying CpeArg
528 -- ---------------------------------------------------------------------------
530 -- This is where we arrange that a non-trivial argument is let-bound
531 cpeArg :: CorePrepEnv -> RhsDemand -> CoreArg -> Type
532 -> UniqSM (Floats, CpeTriv)
533 cpeArg env is_strict arg arg_ty
534 | cpe_ExprIsTrivial arg -- Do not eta expand etc a trivial argument
535 = cpeBody env arg -- Must still do substitution though
537 = do { (floats1, arg1) <- cpeRhsE env arg -- arg1 can be a lambda
538 ; (floats2, arg2) <- if want_float floats1 arg1
539 then return (floats1, arg1)
540 else do { body1 <- rhsToBodyNF arg1
541 ; return (emptyFloats, wrapBinds floats1 body1) }
542 -- Else case: arg1 might have lambdas, and we can't
543 -- put them inside a wrapBinds
546 ; let arg3 = cpeEtaExpand (exprArity arg2) arg2
547 arg_float = mkFloat is_strict is_unlifted v arg3
548 ; return (addFloat floats2 arg_float, Var v) }
550 is_unlifted = isUnLiftedType arg_ty
551 want_float = wantFloatNested NonRecursive (is_strict || is_unlifted)
554 Note [Floating unlifted arguments]
555 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
556 Consider C (let v* = expensive in v)
558 where the "*" indicates "will be demanded". Usually v will have been
559 inlined by now, but let's suppose it hasn't (see Trac #2756). Then we
562 let v* = expensive in C v
564 because that has different strictness. Hence the use of 'allLazy'.
565 (NB: the let v* turns into a FloatCase, in mkLocalNonRec.)
568 ------------------------------------------------------------------------------
569 -- Building the saturated syntax
570 -- ---------------------------------------------------------------------------
572 maybeSaturate deals with saturating primops and constructors
573 The type is the type of the entire application
576 maybeSaturate :: Id -> CpeApp -> Int -> UniqSM CpeRhs
577 maybeSaturate fn expr n_args
578 | Just DataToTagOp <- isPrimOpId_maybe fn -- DataToTag must have an evaluated arg
579 -- A gruesome special case
580 = saturateDataToTag sat_expr
582 | hasNoBinding fn -- There's no binding
588 fn_arity = idArity fn
589 excess_arity = fn_arity - n_args
590 sat_expr = cpeEtaExpand excess_arity expr
593 saturateDataToTag :: CpeApp -> UniqSM CpeApp
594 -- Horrid: ensure that the arg of data2TagOp is evaluated
595 -- (data2tag x) --> (case x of y -> data2tag y)
596 -- (yuk yuk) take into account the lambdas we've now introduced
597 saturateDataToTag sat_expr
598 = do { let (eta_bndrs, eta_body) = collectBinders sat_expr
599 ; eta_body' <- eval_data2tag_arg eta_body
600 ; return (mkLams eta_bndrs eta_body') }
602 eval_data2tag_arg :: CpeApp -> UniqSM CpeBody
603 eval_data2tag_arg app@(fun `App` arg)
604 | exprIsHNF arg -- Includes nullary constructors
605 = return app -- The arg is evaluated
606 | otherwise -- Arg not evaluated, so evaluate it
607 = do { arg_id <- newVar (exprType arg)
608 ; let arg_id1 = setIdUnfolding arg_id evaldUnfolding
609 ; return (Case arg arg_id1 (exprType app)
610 [(DEFAULT, [], fun `App` Var arg_id1)]) }
612 eval_data2tag_arg (Note note app) -- Scc notes can appear
613 = do { app' <- eval_data2tag_arg app
614 ; return (Note note app') }
616 eval_data2tag_arg other -- Should not happen
617 = pprPanic "eval_data2tag" (ppr other)
623 %************************************************************************
625 Simple CoreSyn operations
627 %************************************************************************
630 -- We don't ignore SCCs, since they require some code generation
631 ignoreNote :: Note -> Bool
632 -- Tells which notes to drop altogether; they are ignored by code generation
633 -- Do not ignore SCCs!
634 -- It's important that we do drop InlineMe notes; for example
635 -- unzip = __inline_me__ (/\ab. foldr (..) (..))
636 -- Here unzip gets arity 1 so we'll eta-expand it. But we don't
638 -- unzip = /\ab \xs. (__inline_me__ ...) a b xs
639 ignoreNote (CoreNote _) = True
640 ignoreNote _other = False
643 cpe_ExprIsTrivial :: CoreExpr -> Bool
644 -- Version that doesn't consider an scc annotation to be trivial.
645 cpe_ExprIsTrivial (Var _) = True
646 cpe_ExprIsTrivial (Type _) = True
647 cpe_ExprIsTrivial (Lit _) = True
648 cpe_ExprIsTrivial (App e arg) = isTypeArg arg && cpe_ExprIsTrivial e
649 cpe_ExprIsTrivial (Note (SCC _) _) = False
650 cpe_ExprIsTrivial (Note _ e) = cpe_ExprIsTrivial e
651 cpe_ExprIsTrivial (Cast e _) = cpe_ExprIsTrivial e
652 cpe_ExprIsTrivial (Lam b body) | isTyVar b = cpe_ExprIsTrivial body
653 cpe_ExprIsTrivial _ = False
656 -- -----------------------------------------------------------------------------
658 -- -----------------------------------------------------------------------------
661 ~~~~~~~~~~~~~~~~~~~~~
662 Eta expand to match the arity claimed by the binder Remember,
663 CorePrep must not change arity
665 Eta expansion might not have happened already, because it is done by
666 the simplifier only when there at least one lambda already.
668 NB1:we could refrain when the RHS is trivial (which can happen
669 for exported things). This would reduce the amount of code
670 generated (a little) and make things a little words for
671 code compiled without -O. The case in point is data constructor
674 NB2: we have to be careful that the result of etaExpand doesn't
675 invalidate any of the assumptions that CorePrep is attempting
676 to establish. One possible cause is eta expanding inside of
677 an SCC note - we're now careful in etaExpand to make sure the
678 SCC is pushed inside any new lambdas that are generated.
680 Note [Eta expansion and the CorePrep invariants]
681 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
682 It turns out to be much much easier to do eta expansion
683 *after* the main CorePrep stuff. But that places constraints
684 on the eta expander: given a CpeRhs, it must return a CpeRhs.
686 For example here is what we do not want:
687 f = /\a -> g (h 3) -- h has arity 2
689 f = /\a -> let s = h 3 in g s
690 and now we do NOT want eta expansion to give
691 f = /\a -> \ y -> (let s = h 3 in g s) y
693 Instead CoreArity.etaExpand gives
694 f = /\a -> \y -> let s = h 3 in g s y
697 cpeEtaExpand :: Arity -> CpeRhs -> CpeRhs
698 cpeEtaExpand arity expr
700 | otherwise = etaExpand arity expr
703 -- -----------------------------------------------------------------------------
705 -- -----------------------------------------------------------------------------
707 Why try eta reduction? Hasn't the simplifier already done eta?
708 But the simplifier only eta reduces if that leaves something
709 trivial (like f, or f Int). But for deLam it would be enough to
710 get to a partial application:
711 case x of { p -> \xs. map f xs }
712 ==> case x of { p -> map f }
715 tryEtaReduce :: [CoreBndr] -> CoreExpr -> Maybe CoreExpr
716 tryEtaReduce bndrs expr@(App _ _)
717 | ok_to_eta_reduce f &&
719 and (zipWith ok bndrs last_args) &&
720 not (any (`elemVarSet` fvs_remaining) bndrs)
721 = Just remaining_expr
723 (f, args) = collectArgs expr
724 remaining_expr = mkApps f remaining_args
725 fvs_remaining = exprFreeVars remaining_expr
726 (remaining_args, last_args) = splitAt n_remaining args
727 n_remaining = length args - length bndrs
729 ok bndr (Var arg) = bndr == arg
732 -- we can't eta reduce something which must be saturated.
733 ok_to_eta_reduce (Var f) = not (hasNoBinding f)
734 ok_to_eta_reduce _ = False --safe. ToDo: generalise
736 tryEtaReduce bndrs (Let bind@(NonRec _ r) body)
737 | not (any (`elemVarSet` fvs) bndrs)
738 = case tryEtaReduce bndrs body of
739 Just e -> Just (Let bind e)
744 tryEtaReduce _ _ = Nothing
748 -- -----------------------------------------------------------------------------
750 -- -----------------------------------------------------------------------------
753 type RhsDemand = Bool -- True => used strictly; hence not top-level, non-recursive
756 %************************************************************************
760 %************************************************************************
764 = FloatLet CoreBind -- Rhs of bindings are CpeRhss
765 | FloatCase Id CpeBody Bool -- The bool indicates "ok-for-speculation"
767 data Floats = Floats OkToSpec (OrdList FloatingBind)
769 -- Can we float these binds out of the rhs of a let? We cache this decision
770 -- to avoid having to recompute it in a non-linear way when there are
771 -- deeply nested lets.
773 = NotOkToSpec -- definitely not
775 | IfUnboxedOk -- only if floating an unboxed binding is ok
777 mkFloat :: Bool -> Bool -> Id -> CpeRhs -> FloatingBind
778 mkFloat is_strict is_unlifted bndr rhs
779 | use_case = FloatCase bndr rhs (exprOkForSpeculation rhs)
780 | otherwise = FloatLet (NonRec bndr rhs)
782 use_case = is_unlifted || is_strict && not (exprIsHNF rhs)
783 -- Don't make a case for a value binding,
784 -- even if it's strict. Otherwise we get
785 -- case (\x -> e) of ...!
787 emptyFloats :: Floats
788 emptyFloats = Floats OkToSpec nilOL
790 isEmptyFloats :: Floats -> Bool
791 isEmptyFloats (Floats _ bs) = isNilOL bs
793 wrapBinds :: Floats -> CpeBody -> CpeBody
794 wrapBinds (Floats _ binds) body
795 = foldrOL mk_bind body binds
797 mk_bind (FloatCase bndr rhs _) body = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
798 mk_bind (FloatLet bind) body = Let bind body
800 addFloat :: Floats -> FloatingBind -> Floats
801 addFloat (Floats ok_to_spec floats) new_float
802 = Floats (combine ok_to_spec (check new_float)) (floats `snocOL` new_float)
804 check (FloatLet _) = OkToSpec
805 check (FloatCase _ _ ok_for_spec)
806 | ok_for_spec = IfUnboxedOk
807 | otherwise = NotOkToSpec
808 -- The ok-for-speculation flag says that it's safe to
809 -- float this Case out of a let, and thereby do it more eagerly
810 -- We need the top-level flag because it's never ok to float
811 -- an unboxed binding to the top level
813 unitFloat :: FloatingBind -> Floats
814 unitFloat = addFloat emptyFloats
816 appendFloats :: Floats -> Floats -> Floats
817 appendFloats (Floats spec1 floats1) (Floats spec2 floats2)
818 = Floats (combine spec1 spec2) (floats1 `appOL` floats2)
820 concatFloats :: [Floats] -> OrdList FloatingBind
821 concatFloats = foldr (\ (Floats _ bs1) bs2 -> appOL bs1 bs2) nilOL
823 combine :: OkToSpec -> OkToSpec -> OkToSpec
824 combine NotOkToSpec _ = NotOkToSpec
825 combine _ NotOkToSpec = NotOkToSpec
826 combine IfUnboxedOk _ = IfUnboxedOk
827 combine _ IfUnboxedOk = IfUnboxedOk
828 combine _ _ = OkToSpec
830 instance Outputable FloatingBind where
831 ppr (FloatLet bind) = text "FloatLet" <+> ppr bind
832 ppr (FloatCase b rhs spec) = text "FloatCase" <+> ppr b <+> ppr spec <+> equals <+> ppr rhs
834 deFloatTop :: Floats -> [CoreBind]
835 -- For top level only; we don't expect any FloatCases
836 deFloatTop (Floats _ floats)
837 = foldrOL get [] floats
839 get (FloatLet b) bs = b:bs
840 get b _ = pprPanic "corePrepPgm" (ppr b)
842 -------------------------------------------
843 wantFloatTop :: Id -> Floats -> Bool
844 -- Note [CafInfo and floating]
845 wantFloatTop bndr floats = isEmptyFloats floats
846 || (mayHaveCafRefs (idCafInfo bndr)
847 && allLazyTop floats)
849 wantFloatNested :: RecFlag -> Bool -> Floats -> CpeRhs -> Bool
850 wantFloatNested is_rec strict_or_unlifted floats rhs
851 = isEmptyFloats floats
852 || strict_or_unlifted
853 || (allLazyNested is_rec floats && exprIsHNF rhs)
854 -- Why the test for allLazyNested?
855 -- v = f (x `divInt#` y)
856 -- we don't want to float the case, even if f has arity 2,
857 -- because floating the case would make it evaluated too early
859 allLazyTop :: Floats -> Bool
860 allLazyTop (Floats OkToSpec _) = True
863 allLazyNested :: RecFlag -> Floats -> Bool
864 allLazyNested _ (Floats OkToSpec _) = True
865 allLazyNested _ (Floats NotOkToSpec _) = False
866 allLazyNested is_rec (Floats IfUnboxedOk _) = isNonRec is_rec
870 %************************************************************************
874 %************************************************************************
877 -- ---------------------------------------------------------------------------
879 -- ---------------------------------------------------------------------------
881 data CorePrepEnv = CPE (IdEnv Id) -- Clone local Ids
883 emptyCorePrepEnv :: CorePrepEnv
884 emptyCorePrepEnv = CPE emptyVarEnv
886 extendCorePrepEnv :: CorePrepEnv -> Id -> Id -> CorePrepEnv
887 extendCorePrepEnv (CPE env) id id' = CPE (extendVarEnv env id id')
889 extendCorePrepEnvList :: CorePrepEnv -> [(Id,Id)] -> CorePrepEnv
890 extendCorePrepEnvList (CPE env) prs = CPE (extendVarEnvList env prs)
892 lookupCorePrepEnv :: CorePrepEnv -> Id -> Id
893 lookupCorePrepEnv (CPE env) id
894 = case lookupVarEnv env id of
898 ------------------------------------------------------------------------------
900 -- ---------------------------------------------------------------------------
902 cloneBndrs :: CorePrepEnv -> [Var] -> UniqSM (CorePrepEnv, [Var])
903 cloneBndrs env bs = mapAccumLM cloneBndr env bs
905 cloneBndr :: CorePrepEnv -> Var -> UniqSM (CorePrepEnv, Var)
908 = do bndr' <- setVarUnique bndr <$> getUniqueM
909 return (extendCorePrepEnv env bndr bndr', bndr')
911 | otherwise -- Top level things, which we don't want
912 -- to clone, have become GlobalIds by now
913 -- And we don't clone tyvars
917 ------------------------------------------------------------------------------
918 -- Cloning ccall Ids; each must have a unique name,
919 -- to give the code generator a handle to hang it on
920 -- ---------------------------------------------------------------------------
922 fiddleCCall :: Id -> UniqSM Id
924 | isFCallId id = (id `setVarUnique`) <$> getUniqueM
925 | otherwise = return id
927 ------------------------------------------------------------------------------
928 -- Generating new binders
929 -- ---------------------------------------------------------------------------
931 newVar :: Type -> UniqSM Id
933 = seqType ty `seq` do
935 return (mkSysLocal (fsLit "sat") uniq ty)