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( exprIsAtom, exprType, exprIsValue, etaExpand, exprArity, exprOkForSpeculation )
14 import CoreFVs ( exprFreeVars )
15 import CoreLint ( endPass )
17 import Type ( Type, applyTy, splitFunTy_maybe, isTyVarTy,
18 isUnLiftedType, isUnboxedTupleType, repType,
19 uaUTy, usOnce, usMany, eqUsage, seqType )
20 import NewDemand ( Demand, isStrictDmd, lazyDmd, StrictSig(..), DmdType(..) )
21 import PrimOp ( PrimOp(..) )
22 import Var ( Var, Id, setVarUnique )
25 import Id ( mkSysLocal, idType, idNewDemandInfo, idArity,
26 setIdType, isPrimOpId_maybe, isFCallId, isLocalId,
27 hasNoBinding, idNewStrictness
29 import HscTypes ( ModDetails(..) )
38 -- ---------------------------------------------------------------------------
40 -- ---------------------------------------------------------------------------
42 The goal of this pass is to prepare for code generation.
44 1. Saturate constructor and primop applications.
46 2. Convert to A-normal form:
48 * Use case for strict arguments:
49 f E ==> case E of x -> f x
52 * Use let for non-trivial lazy arguments
53 f E ==> let x = E in f x
54 (were f is lazy and x is non-trivial)
56 3. Similarly, convert any unboxed lets into cases.
57 [I'm experimenting with leaving 'ok-for-speculation'
58 rhss in let-form right up to this point.]
60 4. Ensure that lambdas only occur as the RHS of a binding
61 (The code generator can't deal with anything else.)
63 5. Do the seq/par munging. See notes with mkCase below.
65 6. Clone all local Ids. This means that Tidy Core has the property
66 that all Ids are unique, rather than the weaker guarantee of
67 no clashes which the simplifier provides.
69 7. Give each dynamic CCall occurrence a fresh unique; this is
70 rather like the cloning step above.
72 This is all done modulo type applications and abstractions, so that
73 when type erasure is done for conversion to STG, we don't end up with
74 any trivial or useless bindings.
79 -- -----------------------------------------------------------------------------
81 -- -----------------------------------------------------------------------------
84 corePrepPgm :: DynFlags -> ModDetails -> IO ModDetails
85 corePrepPgm dflags mod_details
86 = do showPass dflags "CorePrep"
87 us <- mkSplitUniqSupply 's'
88 let new_binds = initUs_ us (corePrepTopBinds emptyVarEnv (md_binds mod_details))
89 endPass dflags "CorePrep" Opt_D_dump_sat new_binds
90 return (mod_details { md_binds = new_binds })
92 corePrepExpr :: DynFlags -> CoreExpr -> IO CoreExpr
93 corePrepExpr dflags expr
94 = do showPass dflags "CorePrep"
95 us <- mkSplitUniqSupply 's'
96 let new_expr = initUs_ us (corePrepAnExpr emptyVarEnv expr)
97 dumpIfSet_dyn dflags Opt_D_dump_sat "CorePrep"
101 -- ---------------------------------------------------------------------------
102 -- Dealing with bindings
103 -- ---------------------------------------------------------------------------
105 data FloatingBind = FloatLet CoreBind
106 | FloatCase Id CoreExpr Bool
107 -- The bool indicates "ok-for-speculation"
109 instance Outputable FloatingBind where
110 ppr (FloatLet bind) = text "FloatLet" <+> ppr bind
111 ppr (FloatCase b rhs spec) = text "FloatCase" <+> ppr b <+> ppr spec <+> equals <+> ppr rhs
113 type CloneEnv = IdEnv Id -- Clone local Ids
115 allLazy :: OrdList FloatingBind -> Bool
117 = foldrOL check True floats
119 check (FloatLet _) y = y
120 check (FloatCase _ _ ok_for_spec) y = ok_for_spec && y
121 -- The ok-for-speculation flag says that it's safe to
122 -- float this Case out of a let, and thereby do it more eagerly
123 -- We need the top-level flag because it's never ok to float
124 -- an unboxed binding to the top level
126 -- ---------------------------------------------------------------------------
128 -- ---------------------------------------------------------------------------
130 corePrepTopBinds :: CloneEnv -> [CoreBind] -> UniqSM [CoreBind]
131 corePrepTopBinds env [] = returnUs []
133 corePrepTopBinds env (bind : binds)
134 = corePrepTopBind env bind `thenUs` \ (env', bind') ->
135 corePrepTopBinds env' binds `thenUs` \ binds' ->
136 returnUs (bind' : binds')
138 -- From top level bindings we don't get any floats
139 -- (a) it isn't necessary because the mkAtomicArgs in Simplify
140 -- has already done all the floating necessary
141 -- (b) floating would give rise to top-level LocaIds, generated
142 -- by CorePrep.newVar. That breaks the invariant that
143 -- after CorePrep all top-level vars are GlobalIds
145 corePrepTopBind :: CloneEnv -> CoreBind -> UniqSM (CloneEnv, CoreBind)
146 corePrepTopBind env (NonRec bndr rhs)
147 = corePrepRhs env (bndr, rhs) `thenUs` \ rhs' ->
148 cloneBndr env bndr `thenUs` \ (env', bndr') ->
149 returnUs (env', NonRec bndr' rhs')
151 corePrepTopBind env (Rec pairs)
152 = corePrepRecPairs env pairs `thenUs` \ (env', pairs') ->
153 returnUs (env, Rec pairs')
155 corePrepRecPairs env pairs
156 = cloneBndrs env bndrs `thenUs` \ (env', bndrs') ->
157 mapUs (corePrepRhs env') pairs `thenUs` \ rhss' ->
158 returnUs (env', bndrs' `zip` rhss')
160 bndrs = map fst pairs
162 corePrepRhs :: CloneEnv -> (Id, CoreExpr) -> UniqSM CoreExpr
163 corePrepRhs env (bndr, rhs)
164 -- Prepare the RHS and eta expand it.
165 -- No nonsense about floating
166 = corePrepAnExpr env rhs `thenUs` \ rhs' ->
167 getUniquesUs `thenUs` \ us ->
168 returnUs (etaExpand (exprArity rhs') us rhs' (idType bndr))
171 corePrepBind :: CloneEnv -> CoreBind -> UniqSM (CloneEnv, OrdList FloatingBind)
172 -- This one is used for *local* bindings
173 -- We return a *list* of bindings, because we may start with
175 -- where x is demanded, in which case we want to finish with
178 -- And then x will actually end up case-bound
180 corePrepBind env (NonRec bndr rhs)
181 = corePrepExprFloat env rhs `thenUs` \ (floats, rhs') ->
182 cloneBndr env bndr `thenUs` \ (env', bndr') ->
183 mkLocalNonRec bndr' (bdrDem bndr') floats rhs' `thenUs` \ floats' ->
184 returnUs (env', floats')
186 corePrepBind env (Rec pairs)
187 -- Don't bother to try to float bindings out of RHSs
188 -- (compare mkNonRec, which does try)
189 = corePrepRecPairs env pairs `thenUs` \ (env', pairs') ->
190 returnUs (env', unitOL (FloatLet (Rec pairs')))
192 -- ---------------------------------------------------------------------------
193 -- Making arguments atomic (function args & constructor args)
194 -- ---------------------------------------------------------------------------
196 -- This is where we arrange that a non-trivial argument is let-bound
197 corePrepArg :: CloneEnv -> CoreArg -> RhsDemand
198 -> UniqSM (OrdList FloatingBind, CoreArg)
199 corePrepArg env arg dem
200 = corePrepExprFloat env arg `thenUs` \ (floats, arg') ->
201 if needs_binding arg'
202 then returnUs (floats, arg')
203 else newVar (exprType arg') `thenUs` \ v ->
204 mkLocalNonRec v dem floats arg' `thenUs` \ floats' ->
205 returnUs (floats', Var v)
207 needs_binding | opt_RuntimeTypes = exprIsAtom
208 | otherwise = exprIsTrivial
210 -- version that doesn't consider an scc annotation to be trivial.
211 exprIsTrivial (Var v)
212 | hasNoBinding v = idArity v == 0
214 exprIsTrivial (Type _) = True
215 exprIsTrivial (Lit lit) = True
216 exprIsTrivial (App e arg) = isTypeArg arg && exprIsTrivial e
217 exprIsTrivial (Note (SCC _) e) = False
218 exprIsTrivial (Note _ e) = exprIsTrivial e
219 exprIsTrivial (Lam b body) | isTyVar b = exprIsTrivial body
220 exprIsTrivial other = False
222 -- ---------------------------------------------------------------------------
223 -- Dealing with expressions
224 -- ---------------------------------------------------------------------------
226 corePrepAnExpr :: CloneEnv -> CoreExpr -> UniqSM CoreExpr
227 corePrepAnExpr env expr
228 = corePrepExprFloat env expr `thenUs` \ (floats, expr) ->
232 corePrepExprFloat :: CloneEnv -> CoreExpr -> UniqSM (OrdList FloatingBind, CoreExpr)
236 -- e = let bs in e' (semantically, that is!)
239 -- f (g x) ===> ([v = g x], f v)
241 corePrepExprFloat env (Var v)
242 = fiddleCCall v `thenUs` \ v1 ->
243 let v2 = lookupVarEnv env v1 `orElse` v1 in
244 maybeSaturate v2 (Var v2) 0 (idType v2) `thenUs` \ app ->
245 returnUs (nilOL, app)
247 corePrepExprFloat env expr@(Type _)
248 = returnUs (nilOL, expr)
250 corePrepExprFloat env expr@(Lit lit)
251 = returnUs (nilOL, expr)
253 corePrepExprFloat env (Let bind body)
254 = corePrepBind env bind `thenUs` \ (env', new_binds) ->
255 corePrepExprFloat env' body `thenUs` \ (floats, new_body) ->
256 returnUs (new_binds `appOL` floats, new_body)
258 corePrepExprFloat env (Note n@(SCC _) expr)
259 = corePrepAnExpr env expr `thenUs` \ expr1 ->
260 deLam expr1 `thenUs` \ expr2 ->
261 returnUs (nilOL, Note n expr2)
263 corePrepExprFloat env (Note other_note expr)
264 = corePrepExprFloat env expr `thenUs` \ (floats, expr') ->
265 returnUs (floats, Note other_note expr')
267 corePrepExprFloat env expr@(Lam _ _)
268 = corePrepAnExpr env body `thenUs` \ body' ->
269 returnUs (nilOL, mkLams bndrs body')
271 (bndrs,body) = collectBinders expr
273 corePrepExprFloat env (Case scrut bndr alts)
274 = corePrepExprFloat env scrut `thenUs` \ (floats, scrut') ->
275 cloneBndr env bndr `thenUs` \ (env', bndr') ->
276 mapUs (sat_alt env') alts `thenUs` \ alts' ->
277 returnUs (floats, mkCase scrut' bndr' alts')
279 sat_alt env (con, bs, rhs)
280 = cloneBndrs env bs `thenUs` \ (env', bs') ->
281 corePrepAnExpr env' rhs `thenUs` \ rhs1 ->
282 deLam rhs1 `thenUs` \ rhs2 ->
283 returnUs (con, bs', rhs2)
285 corePrepExprFloat env expr@(App _ _)
286 = collect_args expr 0 `thenUs` \ (app, (head,depth), ty, floats, ss) ->
287 ASSERT(null ss) -- make sure we used all the strictness info
289 -- Now deal with the function
291 Var fn_id -> maybeSaturate fn_id app depth ty `thenUs` \ app' ->
292 returnUs (floats, app')
294 _other -> returnUs (floats, app)
298 -- Deconstruct and rebuild the application, floating any non-atomic
299 -- arguments to the outside. We collect the type of the expression,
300 -- the head of the application, and the number of actual value arguments,
301 -- all of which are used to possibly saturate this application if it
302 -- has a constructor or primop at the head.
306 -> Int -- current app depth
307 -> UniqSM (CoreExpr, -- the rebuilt expression
308 (CoreExpr,Int), -- the head of the application,
309 -- and no. of args it was applied to
310 Type, -- type of the whole expr
311 OrdList FloatingBind, -- any floats we pulled out
312 [Demand]) -- remaining argument demands
314 collect_args (App fun arg@(Type arg_ty)) depth
315 = collect_args fun depth `thenUs` \ (fun',hd,fun_ty,floats,ss) ->
316 returnUs (App fun' arg, hd, applyTy fun_ty arg_ty, floats, ss)
318 collect_args (App fun arg) depth
319 = collect_args fun (depth+1) `thenUs` \ (fun',hd,fun_ty,floats,ss) ->
321 (ss1, ss_rest) = case ss of
322 (ss1:ss_rest) -> (ss1, ss_rest)
324 (arg_ty, res_ty) = expectJust "corePrepExprFloat:collect_args" $
325 splitFunTy_maybe fun_ty
327 corePrepArg env arg (mkDemTy ss1 arg_ty) `thenUs` \ (fs, arg') ->
328 returnUs (App fun' arg', hd, res_ty, fs `appOL` floats, ss_rest)
330 collect_args (Var v) depth
331 = fiddleCCall v `thenUs` \ v1 ->
332 let v2 = lookupVarEnv env v1 `orElse` v1 in
333 returnUs (Var v2, (Var v2, depth), idType v2, nilOL, stricts)
335 stricts = case idNewStrictness v of
336 StrictSig (DmdType _ demands _)
337 | depth >= length demands -> demands
339 -- If depth < length demands, then we have too few args to
340 -- satisfy strictness info so we have to ignore all the
341 -- strictness info, e.g. + (error "urk")
342 -- Here, we can't evaluate the arg strictly, because this
343 -- partial application might be seq'd
346 collect_args (Note (Coerce ty1 ty2) fun) depth
347 = collect_args fun depth `thenUs` \ (fun', hd, fun_ty, floats, ss) ->
348 returnUs (Note (Coerce ty1 ty2) fun', hd, ty1, floats, ss)
350 collect_args (Note note fun) depth
352 = collect_args fun depth `thenUs` \ (fun', hd, fun_ty, floats, ss) ->
353 returnUs (Note note fun', hd, fun_ty, floats, ss)
355 -- non-variable fun, better let-bind it
356 collect_args fun depth
357 = corePrepExprFloat env fun `thenUs` \ (fun_floats, fun) ->
358 newVar ty `thenUs` \ fn_id ->
359 mkLocalNonRec fn_id onceDem fun_floats fun `thenUs` \ floats ->
360 returnUs (Var fn_id, (Var fn_id, depth), ty, floats, [])
364 ignore_note InlineCall = True
365 ignore_note InlineMe = True
366 ignore_note _other = False
367 -- we don't ignore SCCs, since they require some code generation
369 ------------------------------------------------------------------------------
370 -- Building the saturated syntax
371 -- ---------------------------------------------------------------------------
373 -- maybeSaturate deals with saturating primops and constructors
374 -- The type is the type of the entire application
375 maybeSaturate :: Id -> CoreExpr -> Int -> Type -> UniqSM CoreExpr
376 maybeSaturate fn expr n_args ty
377 | hasNoBinding fn = saturate_it
378 | otherwise = returnUs expr
380 fn_arity = idArity fn
381 excess_arity = fn_arity - n_args
382 saturate_it = getUniquesUs `thenUs` \ us ->
383 returnUs (etaExpand excess_arity us expr ty)
385 -- ---------------------------------------------------------------------------
386 -- Precipitating the floating bindings
387 -- ---------------------------------------------------------------------------
389 -- mkLocalNonRec is used only for local bindings
390 mkLocalNonRec :: Id -> RhsDemand -- Lhs: id with demand
391 -> OrdList FloatingBind -> CoreExpr -- Rhs: let binds in body
392 -> UniqSM (OrdList FloatingBind)
394 mkLocalNonRec bndr dem floats rhs
395 | exprIsValue rhs && allLazy floats -- Notably constructor applications
396 = -- Why the test for allLazy? You might think that the only
397 -- floats we can get out of a value are eta expansions
398 -- e.g. C $wJust ==> let s = \x -> $wJust x in C s
399 -- Here we want to float the s binding.
401 -- But if the programmer writes this:
402 -- f x = case x of { (a,b) -> \y -> a }
403 -- then the strictness analyser may say that f has strictness "S"
404 -- Later the eta expander will transform to
405 -- f x y = case x of { (a,b) -> a }
406 -- So now f has arity 2. Now CorePrep may see
408 -- so the E argument will turn into a FloatCase.
409 -- Indeed we should end up with
410 -- v = case E of { r -> f r }
411 -- That is, we should not float, even though (f r) is a value
414 -- v = f (x `divInt#` y)
415 -- we don't want to float the case, even if f has arity 2,
416 -- because floating the case would make it evaluated too early
418 -- Finally, eta-expand the RHS, for the benefit of the code gen
419 -- NB: we could refrain when the RHS is trivial (which can happen
420 -- for exported things. This would reduce the amount of code
421 -- generated (a little) and make things a little words for
422 -- code compiled without -O. The case in point is data constructor
425 getUniquesUs `thenUs` \ us ->
427 rhs' = etaExpand (exprArity rhs) us rhs bndr_ty
429 returnUs (floats `snocOL` FloatLet (NonRec bndr rhs'))
431 | isUnLiftedType bndr_rep_ty || isStrict dem
432 -- It's a strict let, or the binder is unlifted,
433 -- so we definitely float all the bindings
434 = ASSERT( not (isUnboxedTupleType bndr_rep_ty) )
435 returnUs (floats `snocOL` FloatCase bndr rhs (exprOkForSpeculation rhs))
438 -- Don't float; the RHS isn't a value
439 = mkBinds floats rhs `thenUs` \ rhs' ->
440 returnUs (unitOL (FloatLet (NonRec bndr rhs')))
443 bndr_ty = idType bndr
444 bndr_rep_ty = repType bndr_ty
446 mkBinds :: OrdList FloatingBind -> CoreExpr -> UniqSM CoreExpr
448 | isNilOL binds = returnUs body
449 | otherwise = deLam body `thenUs` \ body' ->
450 returnUs (foldrOL mk_bind body' binds)
452 mk_bind (FloatCase bndr rhs _) body = mkCase rhs bndr [(DEFAULT, [], body)]
453 mk_bind (FloatLet bind) body = Let bind body
455 -- ---------------------------------------------------------------------------
456 -- Eliminate Lam as a non-rhs (STG doesn't have such a thing)
457 -- We arrange that they only show up as the RHS of a let(rec)
458 -- ---------------------------------------------------------------------------
460 deLam :: CoreExpr -> UniqSM CoreExpr
461 -- Remove top level lambdas by let-bindinig
464 = -- You can get things like
465 -- case e of { p -> coerce t (\s -> ...) }
466 deLam expr `thenUs` \ expr' ->
467 returnUs (Note n expr')
470 | null bndrs = returnUs expr
471 | otherwise = case tryEta bndrs body of
472 Just no_lam_result -> returnUs no_lam_result
473 Nothing -> newVar (exprType expr) `thenUs` \ fn ->
474 returnUs (Let (NonRec fn expr) (Var fn))
476 (bndrs,body) = collectBinders expr
478 -- Why try eta reduction? Hasn't the simplifier already done eta?
479 -- But the simplifier only eta reduces if that leaves something
480 -- trivial (like f, or f Int). But for deLam it would be enough to
481 -- get to a partial application, like (map f).
483 tryEta bndrs expr@(App _ _)
484 | ok_to_eta_reduce f &&
486 and (zipWith ok bndrs last_args) &&
487 not (any (`elemVarSet` fvs_remaining) bndrs)
488 = Just remaining_expr
490 (f, args) = collectArgs expr
491 remaining_expr = mkApps f remaining_args
492 fvs_remaining = exprFreeVars remaining_expr
493 (remaining_args, last_args) = splitAt n_remaining args
494 n_remaining = length args - length bndrs
496 ok bndr (Var arg) = bndr == arg
497 ok bndr other = False
499 -- we can't eta reduce something which must be saturated.
500 ok_to_eta_reduce (Var f) = not (hasNoBinding f)
501 ok_to_eta_reduce _ = False --safe. ToDo: generalise
503 tryEta bndrs (Let bind@(NonRec b r) body)
504 | not (any (`elemVarSet` fvs) bndrs)
505 = case tryEta bndrs body of
506 Just e -> Just (Let bind e)
511 tryEta bndrs _ = Nothing
515 -- -----------------------------------------------------------------------------
516 -- Do the seq and par transformation
517 -- -----------------------------------------------------------------------------
519 Here we do two pre-codegen transformations:
525 case a of { DEFAULT -> rhs }
535 NB: seq# :: a -> Int# -- Evaluate value and return anything
536 par# :: a -> Int# -- Spark value and return anything
538 These transformations can't be done earlier, or else we might
539 think that the expression was strict in the variables in which
540 rhs is strict --- but that would defeat the purpose of seq and par.
544 mkCase scrut@(Var fn `App` Type ty `App` arg) bndr alts@(deflt_alt@(DEFAULT,_,rhs) : con_alts)
545 -- DEFAULT alt is always first
546 = case isPrimOpId_maybe fn of
547 Just ParOp -> Case scrut bndr [deflt_alt]
548 Just SeqOp -> Case arg new_bndr [deflt_alt]
549 other -> Case scrut bndr alts
551 -- The binder shouldn't be used in the expression!
552 new_bndr = ASSERT2( not (bndr `elemVarSet` exprFreeVars rhs), ppr bndr )
553 setIdType bndr (exprType arg)
554 -- NB: SeqOp :: forall a. a -> Int#
555 -- So bndr has type Int#
556 -- But now we are going to scrutinise the SeqOp's argument directly,
557 -- so we must change the type of the case binder to match that
558 -- of the argument expression e.
560 mkCase scrut bndr alts = Case scrut bndr alts
564 -- -----------------------------------------------------------------------------
566 -- -----------------------------------------------------------------------------
570 = RhsDemand { isStrict :: Bool, -- True => used at least once
571 isOnceDem :: Bool -- True => used at most once
574 mkDem :: Demand -> Bool -> RhsDemand
575 mkDem strict once = RhsDemand (isStrictDmd strict) once
577 mkDemTy :: Demand -> Type -> RhsDemand
578 mkDemTy strict ty = RhsDemand (isStrictDmd strict) (isOnceTy ty)
580 isOnceTy :: Type -> Bool
584 opt_UsageSPOn && -- can't expect annotations if -fusagesp is off
589 once | u `eqUsage` usOnce = True
590 | u `eqUsage` usMany = False
591 | isTyVarTy u = False -- if unknown at compile-time, is Top ie usMany
593 bdrDem :: Id -> RhsDemand
594 bdrDem id = mkDem (idNewDemandInfo id) (isOnceTy (idType id))
596 safeDem, onceDem :: RhsDemand
597 safeDem = RhsDemand False False -- always safe to use this
598 onceDem = RhsDemand False True -- used at most once
604 %************************************************************************
608 %************************************************************************
611 ------------------------------------------------------------------------------
613 -- ---------------------------------------------------------------------------
615 cloneBndrs :: CloneEnv -> [Var] -> UniqSM (CloneEnv, [Var])
616 cloneBndrs env bs = mapAccumLUs cloneBndr env bs
618 cloneBndr :: CloneEnv -> Var -> UniqSM (CloneEnv, Var)
620 | isId bndr && isLocalId bndr -- Top level things, which we don't want
621 -- to clone, have become GlobalIds by now
622 = getUniqueUs `thenUs` \ uniq ->
624 bndr' = setVarUnique bndr uniq
626 returnUs (extendVarEnv env bndr bndr', bndr')
628 | otherwise = returnUs (env, bndr)
630 ------------------------------------------------------------------------------
631 -- Cloning ccall Ids; each must have a unique name,
632 -- to give the code generator a handle to hang it on
633 -- ---------------------------------------------------------------------------
635 fiddleCCall :: Id -> UniqSM Id
637 | isFCallId id = getUniqueUs `thenUs` \ uniq ->
638 returnUs (id `setVarUnique` uniq)
639 | otherwise = returnUs id
641 ------------------------------------------------------------------------------
642 -- Generating new binders
643 -- ---------------------------------------------------------------------------
645 newVar :: Type -> UniqSM Id
647 = getUniqueUs `thenUs` \ uniq ->
649 returnUs (mkSysLocal SLIT("sat") uniq ty)