2 % (c) The University of Glasgow, 1994-2000
4 \section{Core pass to saturate constructors and PrimOps}
8 corePrepPgm, corePrepExpr
11 #include "HsVersions.h"
13 import CoreUtils( exprType, exprIsValue, etaExpand, exprArity, exprOkForSpeculation )
14 import CoreFVs ( exprFreeVars )
15 import CoreLint ( endPass )
17 import Type ( Type, applyTy, splitFunTy_maybe,
18 isUnLiftedType, isUnboxedTupleType, seqType )
19 import TcType ( TyThing( AnId ) )
20 import NewDemand ( Demand, isStrictDmd, lazyDmd, StrictSig(..), DmdType(..) )
21 import Var ( Var, Id, setVarUnique )
24 import Id ( mkSysLocal, idType, idNewDemandInfo, idArity,
25 isFCallId, isGlobalId, isImplicitId,
26 isLocalId, hasNoBinding, idNewStrictness,
27 idUnfolding, isDataConWorkId_maybe
29 import HscTypes ( TypeEnv, typeEnvElts )
30 import BasicTypes ( TopLevelFlag(..), isTopLevel, isNotTopLevel,
38 import Util ( listLengthCmp )
42 -- ---------------------------------------------------------------------------
44 -- ---------------------------------------------------------------------------
46 The goal of this pass is to prepare for code generation.
48 1. Saturate constructor and primop applications.
50 2. Convert to A-normal form:
52 * Use case for strict arguments:
53 f E ==> case E of x -> f x
56 * Use let for non-trivial lazy arguments
57 f E ==> let x = E in f x
58 (were f is lazy and x is non-trivial)
60 3. Similarly, convert any unboxed lets into cases.
61 [I'm experimenting with leaving 'ok-for-speculation'
62 rhss in let-form right up to this point.]
64 4. Ensure that lambdas only occur as the RHS of a binding
65 (The code generator can't deal with anything else.)
67 5. [Not any more; nuked Jun 2002] Do the seq/par munging.
69 6. Clone all local Ids.
70 This means that all such Ids are unique, rather than the
71 weaker guarantee of no clashes which the simplifier provides.
72 And that is what the code generator needs.
74 We don't clone TyVars. The code gen doesn't need that,
75 and doing so would be tiresome because then we'd need
76 to substitute in types.
79 7. Give each dynamic CCall occurrence a fresh unique; this is
80 rather like the cloning step above.
82 8. Inject bindings for the "implicit" Ids:
83 * Constructor wrappers
86 We want curried definitions for all of these in case they
87 aren't inlined by some caller.
89 This is all done modulo type applications and abstractions, so that
90 when type erasure is done for conversion to STG, we don't end up with
91 any trivial or useless bindings.
95 -- -----------------------------------------------------------------------------
97 -- -----------------------------------------------------------------------------
100 corePrepPgm :: DynFlags -> [CoreBind] -> TypeEnv -> IO [CoreBind]
101 corePrepPgm dflags binds types
102 = do showPass dflags "CorePrep"
103 us <- mkSplitUniqSupply 's'
105 let implicit_binds = mkImplicitBinds types
106 -- NB: we must feed mkImplicitBinds through corePrep too
107 -- so that they are suitably cloned and eta-expanded
109 binds_out = initUs_ us (
110 corePrepTopBinds binds `thenUs` \ floats1 ->
111 corePrepTopBinds implicit_binds `thenUs` \ floats2 ->
112 returnUs (deFloatTop (floats1 `appendFloats` floats2))
115 endPass dflags "CorePrep" Opt_D_dump_prep binds_out
118 corePrepExpr :: DynFlags -> CoreExpr -> IO CoreExpr
119 corePrepExpr dflags expr
120 = do showPass dflags "CorePrep"
121 us <- mkSplitUniqSupply 's'
122 let new_expr = initUs_ us (corePrepAnExpr emptyVarEnv expr)
123 dumpIfSet_dyn dflags Opt_D_dump_prep "CorePrep"
128 -- -----------------------------------------------------------------------------
130 -- -----------------------------------------------------------------------------
132 Create any necessary "implicit" bindings (data constructors etc).
134 * Constructor workers
135 * Constructor wrappers
136 * Data type record selectors
139 In the latter three cases, the Id contains the unfolding to use for
140 the binding. In the case of data con workers we create the rather
141 strange (non-recursive!) binding
143 $wC = \x y -> $wC x y
145 i.e. a curried constructor that allocates. This means that we can
146 treat the worker for a constructor like any other function in the rest
147 of the compiler. The point here is that CoreToStg will generate a
148 StgConApp for the RHS, rather than a call to the worker (which would
149 give a loop). As Lennart says: the ice is thin here, but it works.
151 Hmm. Should we create bindings for dictionary constructors? They are
152 always fully applied, and the bindings are just there to support
153 partial applications. But it's easier to let them through.
156 mkImplicitBinds type_env
157 = [ NonRec id (get_unfolding id)
158 | AnId id <- typeEnvElts type_env, isImplicitId id ]
159 -- The type environment already contains all the implicit Ids,
160 -- so we just filter them out
162 -- The etaExpand is so that the manifest arity of the
163 -- binding matches its claimed arity, which is an
164 -- invariant of top level bindings going into the code gen
166 get_unfolding id -- See notes above
167 | Just data_con <- isDataConWorkId_maybe id = Var id -- The ice is thin here, but it works
168 -- CorePrep will eta-expand it
169 | otherwise = unfoldingTemplate (idUnfolding id)
174 -- ---------------------------------------------------------------------------
175 -- Dealing with bindings
176 -- ---------------------------------------------------------------------------
178 data FloatingBind = FloatLet CoreBind
179 | FloatCase Id CoreExpr Bool
180 -- The bool indicates "ok-for-speculation"
182 data Floats = Floats OkToSpec (OrdList FloatingBind)
184 -- Can we float these binds out of the rhs of a let? We cache this decision
185 -- to avoid having to recompute it in a non-linear way when there are
186 -- deeply nested lets.
188 = NotOkToSpec -- definitely not
190 | IfUnboxedOk -- only if floating an unboxed binding is ok
192 emptyFloats :: Floats
193 emptyFloats = Floats OkToSpec nilOL
195 addFloat :: Floats -> FloatingBind -> Floats
196 addFloat (Floats ok_to_spec floats) new_float
197 = Floats (combine ok_to_spec (check new_float)) (floats `snocOL` new_float)
199 check (FloatLet _) = OkToSpec
200 check (FloatCase _ _ ok_for_spec)
201 | ok_for_spec = IfUnboxedOk
202 | otherwise = NotOkToSpec
203 -- The ok-for-speculation flag says that it's safe to
204 -- float this Case out of a let, and thereby do it more eagerly
205 -- We need the top-level flag because it's never ok to float
206 -- an unboxed binding to the top level
208 unitFloat :: FloatingBind -> Floats
209 unitFloat = addFloat emptyFloats
211 appendFloats :: Floats -> Floats -> Floats
212 appendFloats (Floats spec1 floats1) (Floats spec2 floats2)
213 = Floats (combine spec1 spec2) (floats1 `appOL` floats2)
215 concatFloats :: [Floats] -> Floats
216 concatFloats = foldr appendFloats emptyFloats
218 combine NotOkToSpec _ = NotOkToSpec
219 combine _ NotOkToSpec = NotOkToSpec
220 combine IfUnboxedOk _ = IfUnboxedOk
221 combine _ IfUnboxedOk = IfUnboxedOk
222 combine _ _ = OkToSpec
224 instance Outputable FloatingBind where
225 ppr (FloatLet bind) = text "FloatLet" <+> ppr bind
226 ppr (FloatCase b rhs spec) = text "FloatCase" <+> ppr b <+> ppr spec <+> equals <+> ppr rhs
228 type CloneEnv = IdEnv Id -- Clone local Ids
230 deFloatTop :: Floats -> [CoreBind]
231 -- For top level only; we don't expect any FloatCases
232 deFloatTop (Floats _ floats)
233 = foldrOL get [] floats
235 get (FloatLet b) bs = b:bs
236 get b bs = pprPanic "corePrepPgm" (ppr b)
238 allLazy :: TopLevelFlag -> RecFlag -> Floats -> Bool
239 allLazy top_lvl is_rec (Floats ok_to_spec _)
243 IfUnboxedOk -> isNotTopLevel top_lvl && isNonRec is_rec
245 -- ---------------------------------------------------------------------------
247 -- ---------------------------------------------------------------------------
249 corePrepTopBinds :: [CoreBind] -> UniqSM Floats
250 corePrepTopBinds binds
251 = go emptyVarEnv binds
253 go env [] = returnUs emptyFloats
254 go env (bind : binds) = corePrepTopBind env bind `thenUs` \ (env', bind') ->
255 go env' binds `thenUs` \ binds' ->
256 returnUs (bind' `appendFloats` binds')
258 -- NB: we do need to float out of top-level bindings
259 -- Consider x = length [True,False]
265 -- We return a *list* of bindings, because we may start with
267 -- where x is demanded, in which case we want to finish with
270 -- And then x will actually end up case-bound
272 -- What happens to the CafInfo on the floated bindings? By
273 -- default, all the CafInfos will be set to MayHaveCafRefs,
276 -- This might be pessimistic, because eg. s1 & s2
277 -- might not refer to any CAFs and the GC will end up doing
278 -- more traversal than is necessary, but it's still better
279 -- than not floating the bindings at all, because then
280 -- the GC would have to traverse the structure in the heap
281 -- instead. Given this, we decided not to try to get
282 -- the CafInfo on the floated bindings correct, because
283 -- it looks difficult.
285 --------------------------------
286 corePrepTopBind :: CloneEnv -> CoreBind -> UniqSM (CloneEnv, Floats)
287 corePrepTopBind env (NonRec bndr rhs)
288 = cloneBndr env bndr `thenUs` \ (env', bndr') ->
289 corePrepRhs TopLevel NonRecursive env (bndr, rhs) `thenUs` \ (floats, rhs') ->
290 returnUs (env', addFloat floats (FloatLet (NonRec bndr' rhs')))
292 corePrepTopBind env (Rec pairs) = corePrepRecPairs TopLevel env pairs
294 --------------------------------
295 corePrepBind :: CloneEnv -> CoreBind -> UniqSM (CloneEnv, Floats)
296 -- This one is used for *local* bindings
297 corePrepBind env (NonRec bndr rhs)
298 = etaExpandRhs bndr rhs `thenUs` \ rhs1 ->
299 corePrepExprFloat env rhs1 `thenUs` \ (floats, rhs2) ->
300 cloneBndr env bndr `thenUs` \ (env', bndr') ->
301 mkLocalNonRec bndr' (bdrDem bndr') floats rhs2 `thenUs` \ floats' ->
302 returnUs (env', floats')
304 corePrepBind env (Rec pairs) = corePrepRecPairs NotTopLevel env pairs
306 --------------------------------
307 corePrepRecPairs :: TopLevelFlag -> CloneEnv
308 -> [(Id,CoreExpr)] -- Recursive bindings
309 -> UniqSM (CloneEnv, Floats)
310 -- Used for all recursive bindings, top level and otherwise
311 corePrepRecPairs lvl env pairs
312 = cloneBndrs env (map fst pairs) `thenUs` \ (env', bndrs') ->
313 mapAndUnzipUs (corePrepRhs lvl Recursive env') pairs `thenUs` \ (floats_s, rhss') ->
314 returnUs (env', unitFloat (FloatLet (Rec (flatten (concatFloats floats_s) bndrs' rhss'))))
316 -- Flatten all the floats, and the currrent
317 -- group into a single giant Rec
318 flatten (Floats _ floats) bndrs rhss = foldrOL get (bndrs `zip` rhss) floats
320 get (FloatLet (NonRec b r)) prs2 = (b,r) : prs2
321 get (FloatLet (Rec prs1)) prs2 = prs1 ++ prs2
323 --------------------------------
324 corePrepRhs :: TopLevelFlag -> RecFlag
325 -> CloneEnv -> (Id, CoreExpr)
326 -> UniqSM (Floats, CoreExpr)
327 -- Used for top-level bindings, and local recursive bindings
328 corePrepRhs top_lvl is_rec env (bndr, rhs)
329 = etaExpandRhs bndr rhs `thenUs` \ rhs' ->
330 corePrepExprFloat env rhs' `thenUs` \ floats_w_rhs ->
331 floatRhs top_lvl is_rec bndr floats_w_rhs
334 -- ---------------------------------------------------------------------------
335 -- Making arguments atomic (function args & constructor args)
336 -- ---------------------------------------------------------------------------
338 -- This is where we arrange that a non-trivial argument is let-bound
339 corePrepArg :: CloneEnv -> CoreArg -> RhsDemand
340 -> UniqSM (Floats, CoreArg)
341 corePrepArg env arg dem
342 = corePrepExprFloat env arg `thenUs` \ (floats, arg') ->
343 if exprIsTrivial arg'
344 then returnUs (floats, arg')
345 else newVar (exprType arg') `thenUs` \ v ->
346 mkLocalNonRec v dem floats arg' `thenUs` \ floats' ->
347 returnUs (floats', Var v)
349 -- version that doesn't consider an scc annotation to be trivial.
350 exprIsTrivial (Var v) = True
351 exprIsTrivial (Type _) = True
352 exprIsTrivial (Lit lit) = True
353 exprIsTrivial (App e arg) = isTypeArg arg && exprIsTrivial e
354 exprIsTrivial (Note (SCC _) e) = False
355 exprIsTrivial (Note _ e) = exprIsTrivial e
356 exprIsTrivial (Lam b body) | isTyVar b = exprIsTrivial body
357 exprIsTrivial other = False
359 -- ---------------------------------------------------------------------------
360 -- Dealing with expressions
361 -- ---------------------------------------------------------------------------
363 corePrepAnExpr :: CloneEnv -> CoreExpr -> UniqSM CoreExpr
364 corePrepAnExpr env expr
365 = corePrepExprFloat env expr `thenUs` \ (floats, expr) ->
369 corePrepExprFloat :: CloneEnv -> CoreExpr -> UniqSM (Floats, CoreExpr)
373 -- e = let bs in e' (semantically, that is!)
376 -- f (g x) ===> ([v = g x], f v)
378 corePrepExprFloat env (Var v)
379 = fiddleCCall v `thenUs` \ v1 ->
380 let v2 = lookupVarEnv env v1 `orElse` v1 in
381 maybeSaturate v2 (Var v2) 0 (idType v2) `thenUs` \ app ->
382 returnUs (emptyFloats, app)
384 corePrepExprFloat env expr@(Type _)
385 = returnUs (emptyFloats, expr)
387 corePrepExprFloat env expr@(Lit lit)
388 = returnUs (emptyFloats, expr)
390 corePrepExprFloat env (Let bind body)
391 = corePrepBind env bind `thenUs` \ (env', new_binds) ->
392 corePrepExprFloat env' body `thenUs` \ (floats, new_body) ->
393 returnUs (new_binds `appendFloats` floats, new_body)
395 corePrepExprFloat env (Note n@(SCC _) expr)
396 = corePrepAnExpr env expr `thenUs` \ expr1 ->
397 deLamFloat expr1 `thenUs` \ (floats, expr2) ->
398 returnUs (floats, Note n expr2)
400 corePrepExprFloat env (Note other_note expr)
401 = corePrepExprFloat env expr `thenUs` \ (floats, expr') ->
402 returnUs (floats, Note other_note expr')
404 corePrepExprFloat env expr@(Lam _ _)
405 = cloneBndrs env bndrs `thenUs` \ (env', bndrs') ->
406 corePrepAnExpr env' body `thenUs` \ body' ->
407 returnUs (emptyFloats, mkLams bndrs' body')
409 (bndrs,body) = collectBinders expr
411 corePrepExprFloat env (Case scrut bndr alts)
412 = corePrepExprFloat env scrut `thenUs` \ (floats1, scrut1) ->
413 deLamFloat scrut1 `thenUs` \ (floats2, scrut2) ->
414 cloneBndr env bndr `thenUs` \ (env', bndr') ->
415 mapUs (sat_alt env') alts `thenUs` \ alts' ->
416 returnUs (floats1 `appendFloats` floats2 , Case scrut2 bndr' alts')
418 sat_alt env (con, bs, rhs)
419 = cloneBndrs env bs `thenUs` \ (env', bs') ->
420 corePrepAnExpr env' rhs `thenUs` \ rhs1 ->
421 deLam rhs1 `thenUs` \ rhs2 ->
422 returnUs (con, bs', rhs2)
424 corePrepExprFloat env expr@(App _ _)
425 = collect_args expr 0 `thenUs` \ (app, (head,depth), ty, floats, ss) ->
426 ASSERT(null ss) -- make sure we used all the strictness info
428 -- Now deal with the function
430 Var fn_id -> maybeSaturate fn_id app depth ty `thenUs` \ app' ->
431 returnUs (floats, app')
433 _other -> returnUs (floats, app)
437 -- Deconstruct and rebuild the application, floating any non-atomic
438 -- arguments to the outside. We collect the type of the expression,
439 -- the head of the application, and the number of actual value arguments,
440 -- all of which are used to possibly saturate this application if it
441 -- has a constructor or primop at the head.
445 -> Int -- current app depth
446 -> UniqSM (CoreExpr, -- the rebuilt expression
447 (CoreExpr,Int), -- the head of the application,
448 -- and no. of args it was applied to
449 Type, -- type of the whole expr
450 Floats, -- any floats we pulled out
451 [Demand]) -- remaining argument demands
453 collect_args (App fun arg@(Type arg_ty)) depth
454 = collect_args fun depth `thenUs` \ (fun',hd,fun_ty,floats,ss) ->
455 returnUs (App fun' arg, hd, applyTy fun_ty arg_ty, floats, ss)
457 collect_args (App fun arg) depth
458 = collect_args fun (depth+1) `thenUs` \ (fun',hd,fun_ty,floats,ss) ->
460 (ss1, ss_rest) = case ss of
461 (ss1:ss_rest) -> (ss1, ss_rest)
463 (arg_ty, res_ty) = expectJust "corePrepExprFloat:collect_args" $
464 splitFunTy_maybe fun_ty
466 corePrepArg env arg (mkDemTy ss1 arg_ty) `thenUs` \ (fs, arg') ->
467 returnUs (App fun' arg', hd, res_ty, fs `appendFloats` floats, ss_rest)
469 collect_args (Var v) depth
470 = fiddleCCall v `thenUs` \ v1 ->
471 let v2 = lookupVarEnv env v1 `orElse` v1 in
472 returnUs (Var v2, (Var v2, depth), idType v2, emptyFloats, stricts)
474 stricts = case idNewStrictness v of
475 StrictSig (DmdType _ demands _)
476 | listLengthCmp demands depth /= GT -> demands
477 -- length demands <= depth
479 -- If depth < length demands, then we have too few args to
480 -- satisfy strictness info so we have to ignore all the
481 -- strictness info, e.g. + (error "urk")
482 -- Here, we can't evaluate the arg strictly, because this
483 -- partial application might be seq'd
486 collect_args (Note (Coerce ty1 ty2) fun) depth
487 = collect_args fun depth `thenUs` \ (fun', hd, fun_ty, floats, ss) ->
488 returnUs (Note (Coerce ty1 ty2) fun', hd, ty1, floats, ss)
490 collect_args (Note note fun) depth
492 = collect_args fun depth `thenUs` \ (fun', hd, fun_ty, floats, ss) ->
493 returnUs (Note note fun', hd, fun_ty, floats, ss)
495 -- non-variable fun, better let-bind it
496 -- ToDo: perhaps we can case-bind rather than let-bind this closure,
497 -- since it is sure to be evaluated.
498 collect_args fun depth
499 = corePrepExprFloat env fun `thenUs` \ (fun_floats, fun') ->
500 newVar ty `thenUs` \ fn_id ->
501 mkLocalNonRec fn_id onceDem fun_floats fun' `thenUs` \ floats ->
502 returnUs (Var fn_id, (Var fn_id, depth), ty, floats, [])
506 ignore_note (CoreNote _) = True
507 ignore_note InlineCall = True
508 ignore_note InlineMe = True
509 ignore_note _other = False
510 -- We don't ignore SCCs, since they require some code generation
512 ------------------------------------------------------------------------------
513 -- Building the saturated syntax
514 -- ---------------------------------------------------------------------------
516 -- maybeSaturate deals with saturating primops and constructors
517 -- The type is the type of the entire application
518 maybeSaturate :: Id -> CoreExpr -> Int -> Type -> UniqSM CoreExpr
519 maybeSaturate fn expr n_args ty
520 | hasNoBinding fn = saturate_it
521 | otherwise = returnUs expr
523 fn_arity = idArity fn
524 excess_arity = fn_arity - n_args
525 saturate_it = getUniquesUs `thenUs` \ us ->
526 returnUs (etaExpand excess_arity us expr ty)
528 -- ---------------------------------------------------------------------------
529 -- Precipitating the floating bindings
530 -- ---------------------------------------------------------------------------
532 floatRhs :: TopLevelFlag -> RecFlag
534 -> (Floats, CoreExpr) -- Rhs: let binds in body
535 -> UniqSM (Floats, -- Floats out of this bind
536 CoreExpr) -- Final Rhs
538 floatRhs top_lvl is_rec bndr (floats, rhs)
539 | isTopLevel top_lvl || exprIsValue rhs, -- Float to expose value or
540 allLazy top_lvl is_rec floats -- at top level
541 = -- Why the test for allLazy?
542 -- v = f (x `divInt#` y)
543 -- we don't want to float the case, even if f has arity 2,
544 -- because floating the case would make it evaluated too early
546 -- Finally, eta-expand the RHS, for the benefit of the code gen
547 returnUs (floats, rhs)
550 -- Don't float; the RHS isn't a value
551 = mkBinds floats rhs `thenUs` \ rhs' ->
552 returnUs (emptyFloats, rhs')
554 -- mkLocalNonRec is used only for *nested*, *non-recursive* bindings
555 mkLocalNonRec :: Id -> RhsDemand -- Lhs: id with demand
556 -> Floats -> CoreExpr -- Rhs: let binds in body
559 mkLocalNonRec bndr dem floats rhs
560 | isUnLiftedType (idType bndr)
561 -- If this is an unlifted binding, we always make a case for it.
562 = ASSERT( not (isUnboxedTupleType (idType bndr)) )
564 float = FloatCase bndr rhs (exprOkForSpeculation rhs)
566 returnUs (addFloat floats float)
569 -- It's a strict let so we definitely float all the bindings
570 = let -- Don't make a case for a value binding,
571 -- even if it's strict. Otherwise we get
572 -- case (\x -> e) of ...!
573 float | exprIsValue rhs = FloatLet (NonRec bndr rhs)
574 | otherwise = FloatCase bndr rhs (exprOkForSpeculation rhs)
576 returnUs (addFloat floats float)
579 = floatRhs NotTopLevel NonRecursive bndr (floats, rhs) `thenUs` \ (floats', rhs') ->
580 returnUs (addFloat floats' (FloatLet (NonRec bndr rhs')))
583 bndr_ty = idType bndr
586 mkBinds :: Floats -> CoreExpr -> UniqSM CoreExpr
587 mkBinds (Floats _ binds) body
588 | isNilOL binds = returnUs body
589 | otherwise = deLam body `thenUs` \ body' ->
590 returnUs (foldrOL mk_bind body' binds)
592 mk_bind (FloatCase bndr rhs _) body = Case rhs bndr [(DEFAULT, [], body)]
593 mk_bind (FloatLet bind) body = Let bind body
595 etaExpandRhs bndr rhs
596 = -- Eta expand to match the arity claimed by the binder
597 -- Remember, after CorePrep we must not change arity
599 -- Eta expansion might not have happened already,
600 -- because it is done by the simplifier only when
601 -- there at least one lambda already.
603 -- NB1:we could refrain when the RHS is trivial (which can happen
604 -- for exported things). This would reduce the amount of code
605 -- generated (a little) and make things a little words for
606 -- code compiled without -O. The case in point is data constructor
609 -- NB2: we have to be careful that the result of etaExpand doesn't
610 -- invalidate any of the assumptions that CorePrep is attempting
611 -- to establish. One possible cause is eta expanding inside of
612 -- an SCC note - we're now careful in etaExpand to make sure the
613 -- SCC is pushed inside any new lambdas that are generated.
615 -- NB3: It's important to do eta expansion, and *then* ANF-ising
616 -- f = /\a -> g (h 3) -- h has arity 2
617 -- If we ANF first we get
618 -- f = /\a -> let s = h 3 in g s
619 -- and now eta expansion gives
620 -- f = /\a -> \ y -> (let s = h 3 in g s) y
621 -- which is horrible.
622 -- Eta expanding first gives
623 -- f = /\a -> \y -> let s = h 3 in g s y
625 getUniquesUs `thenUs` \ us ->
626 returnUs (etaExpand arity us rhs (idType bndr))
628 -- For a GlobalId, take the Arity from the Id.
629 -- It was set in CoreTidy and must not change
630 -- For all others, just expand at will
631 arity | isGlobalId bndr = idArity bndr
632 | otherwise = exprArity rhs
634 -- ---------------------------------------------------------------------------
635 -- Eliminate Lam as a non-rhs (STG doesn't have such a thing)
636 -- We arrange that they only show up as the RHS of a let(rec)
637 -- ---------------------------------------------------------------------------
639 deLam :: CoreExpr -> UniqSM CoreExpr
641 deLamFloat expr `thenUs` \ (floats, expr) ->
645 deLamFloat :: CoreExpr -> UniqSM (Floats, CoreExpr)
646 -- Remove top level lambdas by let-bindinig
648 deLamFloat (Note n expr)
649 = -- You can get things like
650 -- case e of { p -> coerce t (\s -> ...) }
651 deLamFloat expr `thenUs` \ (floats, expr') ->
652 returnUs (floats, Note n expr')
655 | null bndrs = returnUs (emptyFloats, expr)
657 = case tryEta bndrs body of
658 Just no_lam_result -> returnUs (emptyFloats, no_lam_result)
659 Nothing -> newVar (exprType expr) `thenUs` \ fn ->
660 returnUs (unitFloat (FloatLet (NonRec fn expr)),
663 (bndrs,body) = collectBinders expr
665 -- Why try eta reduction? Hasn't the simplifier already done eta?
666 -- But the simplifier only eta reduces if that leaves something
667 -- trivial (like f, or f Int). But for deLam it would be enough to
668 -- get to a partial application, like (map f).
670 tryEta bndrs expr@(App _ _)
671 | ok_to_eta_reduce f &&
673 and (zipWith ok bndrs last_args) &&
674 not (any (`elemVarSet` fvs_remaining) bndrs)
675 = Just remaining_expr
677 (f, args) = collectArgs expr
678 remaining_expr = mkApps f remaining_args
679 fvs_remaining = exprFreeVars remaining_expr
680 (remaining_args, last_args) = splitAt n_remaining args
681 n_remaining = length args - length bndrs
683 ok bndr (Var arg) = bndr == arg
684 ok bndr other = False
686 -- we can't eta reduce something which must be saturated.
687 ok_to_eta_reduce (Var f) = not (hasNoBinding f)
688 ok_to_eta_reduce _ = False --safe. ToDo: generalise
690 tryEta bndrs (Let bind@(NonRec b r) body)
691 | not (any (`elemVarSet` fvs) bndrs)
692 = case tryEta bndrs body of
693 Just e -> Just (Let bind e)
698 tryEta bndrs _ = Nothing
702 -- -----------------------------------------------------------------------------
704 -- -----------------------------------------------------------------------------
708 = RhsDemand { isStrict :: Bool, -- True => used at least once
709 isOnceDem :: Bool -- True => used at most once
712 mkDem :: Demand -> Bool -> RhsDemand
713 mkDem strict once = RhsDemand (isStrictDmd strict) once
715 mkDemTy :: Demand -> Type -> RhsDemand
716 mkDemTy strict ty = RhsDemand (isStrictDmd strict)
719 bdrDem :: Id -> RhsDemand
720 bdrDem id = mkDem (idNewDemandInfo id)
723 -- safeDem :: RhsDemand
724 -- safeDem = RhsDemand False False -- always safe to use this
727 onceDem = RhsDemand False True -- used at most once
733 %************************************************************************
737 %************************************************************************
740 ------------------------------------------------------------------------------
742 -- ---------------------------------------------------------------------------
744 cloneBndrs :: CloneEnv -> [Var] -> UniqSM (CloneEnv, [Var])
745 cloneBndrs env bs = mapAccumLUs cloneBndr env bs
747 cloneBndr :: CloneEnv -> Var -> UniqSM (CloneEnv, Var)
750 = getUniqueUs `thenUs` \ uniq ->
752 bndr' = setVarUnique bndr uniq
754 returnUs (extendVarEnv env bndr bndr', bndr')
756 | otherwise -- Top level things, which we don't want
757 -- to clone, have become GlobalIds by now
758 -- And we don't clone tyvars
759 = returnUs (env, bndr)
762 ------------------------------------------------------------------------------
763 -- Cloning ccall Ids; each must have a unique name,
764 -- to give the code generator a handle to hang it on
765 -- ---------------------------------------------------------------------------
767 fiddleCCall :: Id -> UniqSM Id
769 | isFCallId id = getUniqueUs `thenUs` \ uniq ->
770 returnUs (id `setVarUnique` uniq)
771 | otherwise = returnUs id
773 ------------------------------------------------------------------------------
774 -- Generating new binders
775 -- ---------------------------------------------------------------------------
777 newVar :: Type -> UniqSM Id
780 getUniqueUs `thenUs` \ uniq ->
781 returnUs (mkSysLocal FSLIT("sat") uniq ty)