2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[WorkWrap]{Worker/wrapper-generating back-end of strictness analyser}
7 module WorkWrap ( wwTopBinds, mkWrapper ) where
9 #include "HsVersions.h"
12 import CoreUnfold ( certainlyWillInline )
13 import CoreUtils ( exprType, exprIsHNF, exprArity )
15 import Id ( Id, idType, isOneShotLambda,
16 setIdNewStrictness, mkWorkerId,
17 setIdWorkerInfo, setInlinePragma,
19 import MkId ( lazyIdKey, lazyIdUnfolding )
22 import NewDemand ( Demand(..), StrictSig(..), DmdType(..), DmdResult(..),
23 Demands(..), mkTopDmdType, isBotRes, returnsCPR, topSig, isAbsent
26 import Unique ( hasKey )
27 import BasicTypes ( RecFlag(..), isNonRec, isNeverActive )
28 import VarEnv ( isEmptyVarEnv )
29 import Maybes ( orElse )
31 import Util ( lengthIs, notNull )
36 We take Core bindings whose binders have:
40 \item Strictness attached (by the front-end of the strictness
43 \item Constructed Product Result information attached by the CPR
48 and we return some ``plain'' bindings which have been
49 worker/wrapper-ified, meaning:
53 \item Functions have been split into workers and wrappers where
54 appropriate. If a function has both strictness and CPR properties
55 then only one worker/wrapper doing both transformations is produced;
57 \item Binders' @IdInfos@ have been updated to reflect the existence of
58 these workers/wrappers (this is where we get STRICTNESS and CPR pragma
59 info for exported values).
63 wwTopBinds :: UniqSupply -> [CoreBind] -> [CoreBind]
65 wwTopBinds us top_binds
67 top_binds' <- mapM wwBind top_binds
68 return (concat top_binds')
71 %************************************************************************
73 \subsection[wwBind-wwExpr]{@wwBind@ and @wwExpr@}
75 %************************************************************************
77 @wwBind@ works on a binding, trying each \tr{(binder, expr)} pair in
78 turn. Non-recursive case first, then recursive...
82 -> UniqSM [CoreBind] -- returns a WwBinding intermediate form;
83 -- the caller will convert to Expr/Binding,
86 wwBind (NonRec binder rhs) = do
88 new_pairs <- tryWW NonRecursive binder new_rhs
89 return [NonRec b e | (b,e) <- new_pairs]
90 -- Generated bindings must be non-recursive
91 -- because the original binding was.
94 = return . Rec <$> concatMapM do_one pairs
96 do_one (binder, rhs) = do new_rhs <- wwExpr rhs
97 tryWW Recursive binder new_rhs
100 @wwExpr@ basically just walks the tree, looking for appropriate
101 annotations that can be used. Remember it is @wwBind@ that does the
102 matching by looking for strict arguments of the correct type.
103 @wwExpr@ is a version that just returns the ``Plain'' Tree.
106 wwExpr :: CoreExpr -> UniqSM CoreExpr
108 wwExpr e@(Type _) = return e
109 wwExpr e@(Lit _) = return e
110 wwExpr e@(Note InlineMe _) = return e
111 -- Don't w/w inside InlineMe's
114 | v `hasKey` lazyIdKey = return lazyIdUnfolding
115 | otherwise = return e
116 -- HACK alert: Inline 'lazy' after strictness analysis
117 -- (but not inside InlineMe's)
119 wwExpr (Lam binder expr)
120 = Lam binder <$> wwExpr expr
123 = App <$> wwExpr f <*> wwExpr a
125 wwExpr (Note note expr)
126 = Note note <$> wwExpr expr
128 wwExpr (Cast expr co) = do
129 new_expr <- wwExpr expr
130 return (Cast new_expr co)
132 wwExpr (Let bind expr)
133 = mkLets <$> wwBind bind <*> wwExpr expr
135 wwExpr (Case expr binder ty alts) = do
136 new_expr <- wwExpr expr
137 new_alts <- mapM ww_alt alts
138 return (Case new_expr binder ty new_alts)
140 ww_alt (con, binders, rhs) = do
141 new_rhs <- wwExpr rhs
142 return (con, binders, new_rhs)
145 %************************************************************************
147 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
149 %************************************************************************
151 @tryWW@ just accumulates arguments, converts strictness info from the
152 front-end into the proper form, then calls @mkWwBodies@ to do
155 We have to BE CAREFUL that we don't worker-wrapperize an Id that has
156 already been w-w'd! (You can end up with several liked-named Ids
157 bouncing around at the same time---absolute mischief.) So the
158 criterion we use is: if an Id already has an unfolding (for whatever
159 reason), then we don't w-w it.
161 The only reason this is monadised is for the unique supply.
163 Note [Don't w/w inline things]
164 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
165 It's very important to refrain from w/w-ing an INLINE function
166 If we do so by mistake we transform
167 f = __inline (\x -> E)
169 f = __inline (\x -> case x of (a,b) -> fw E)
170 fw = \ab -> (__inline (\x -> E)) (a,b)
171 and the original __inline now vanishes, so E is no longer
172 inside its __inline wrapper. Death! Disaster!
174 Furthermore, if the programmer has marked something as INLINE,
175 we may lose by w/w'ing it.
177 If the strictness analyser is run twice, this test also prevents
178 wrappers (which are INLINEd) from being re-done.
180 Notice that we refrain from w/w'ing an INLINE function even if it is
181 in a recursive group. It might not be the loop breaker. (We could
182 test for loop-breaker-hood, but I'm not sure that ever matters.)
186 -> Id -- The fn binder
187 -> CoreExpr -- The bound rhs; its innards
189 -> UniqSM [(Id, CoreExpr)] -- either *one* or *two* pairs;
190 -- if one, then no worker (only
191 -- the orig "wrapper" lives on);
192 -- if two, then a worker and a
194 tryWW is_rec fn_id rhs
195 | -- isNonRec is_rec && -- Now omitted: see Note [Don't w/w inline things]
196 certainlyWillInline unfolding
198 || isNeverActive inline_prag
199 -- No point in worker/wrappering if the thing is never inlined!
200 -- Because the no-inline prag will prevent the wrapper ever
201 -- being inlined at a call site.
202 = return [ (new_fn_id, rhs) ]
204 | is_thunk && worthSplittingThunk maybe_fn_dmd res_info
205 = ASSERT2( isNonRec is_rec, ppr new_fn_id ) -- The thunk must be non-recursive
206 splitThunk new_fn_id rhs
208 | is_fun && worthSplittingFun wrap_dmds res_info
209 = splitFun new_fn_id fn_info wrap_dmds res_info inline_prag rhs
212 = return [ (new_fn_id, rhs) ]
215 fn_info = idInfo fn_id
216 maybe_fn_dmd = newDemandInfo fn_info
217 unfolding = unfoldingInfo fn_info
218 inline_prag = inlinePragInfo fn_info
220 -- In practice it always will have a strictness
221 -- signature, even if it's a uninformative one
222 strict_sig = newStrictnessInfo fn_info `orElse` topSig
223 StrictSig (DmdType env wrap_dmds res_info) = strict_sig
225 -- new_fn_id has the DmdEnv zapped.
226 -- (a) it is never used again
227 -- (b) it wastes space
228 -- (c) it becomes incorrect as things are cloned, because
229 -- we don't push the substitution into it
230 new_fn_id | isEmptyVarEnv env = fn_id
231 | otherwise = fn_id `setIdNewStrictness`
232 StrictSig (mkTopDmdType wrap_dmds res_info)
234 is_fun = notNull wrap_dmds
235 is_thunk = not is_fun && not (exprIsHNF rhs)
237 ---------------------
238 splitFun :: Id -> IdInfo -> [Demand] -> DmdResult -> InlinePragInfo -> Expr Var
239 -> UniqSM [(Id, CoreExpr)]
240 splitFun fn_id fn_info wrap_dmds res_info inline_prag rhs
241 = WARN( not (wrap_dmds `lengthIs` arity), ppr fn_id <+> (ppr arity $$ ppr wrap_dmds $$ ppr res_info) )
243 -- The arity should match the signature
244 (work_demands, wrap_fn, work_fn) <- mkWwBodies fun_ty wrap_dmds res_info one_shots
245 ; work_uniq <- getUniqueM
247 work_rhs = work_fn rhs
248 work_id = mkWorkerId work_uniq fn_id (exprType work_rhs)
249 `setInlinePragma` inline_prag
250 -- Any inline pragma (which sets when inlining is active)
251 -- on the original function is duplicated on the worker and wrapper
252 -- It *matters* that the pragma stays on the wrapper
253 -- It seems sensible to have it on the worker too, although we
254 -- can't think of a compelling reason. (In ptic, INLINE things are
256 `setIdNewStrictness` StrictSig (mkTopDmdType work_demands work_res_info)
257 -- Even though we may not be at top level,
258 -- it's ok to give it an empty DmdEnv
259 `setIdArity` (exprArity work_rhs)
260 -- Set the arity so that the Core Lint check that the
261 -- arity is consistent with the demand type goes through
263 wrap_rhs = wrap_fn work_id
264 wrap_id = fn_id `setIdWorkerInfo` HasWorker work_id arity
266 ; return ([(work_id, work_rhs), (wrap_id, wrap_rhs)]) })
267 -- Worker first, because wrapper mentions it
268 -- mkWwBodies has already built a wrap_rhs with an INLINE pragma wrapped around it
270 fun_ty = idType fn_id
272 arity = arityInfo fn_info -- The arity is set by the simplifier using exprEtaExpandArity
273 -- So it may be more than the number of top-level-visible lambdas
275 work_res_info | isBotRes res_info = BotRes -- Cpr stuff done by wrapper
278 one_shots = get_one_shots rhs
280 -- If the original function has one-shot arguments, it is important to
281 -- make the wrapper and worker have corresponding one-shot arguments too.
282 -- Otherwise we spuriously float stuff out of case-expression join points,
283 -- which is very annoying.
284 get_one_shots :: Expr Var -> [Bool]
285 get_one_shots (Lam b e)
286 | isIdVar b = isOneShotLambda b : get_one_shots e
287 | otherwise = get_one_shots e
288 get_one_shots (Note _ e) = get_one_shots e
289 get_one_shots _ = noOneShotInfo
294 Suppose x is used strictly (never mind whether it has the CPR
301 splitThunk transforms like this:
304 x* = case x-rhs of { I# a -> I# a }
307 Now simplifier will transform to
310 I# a -> let x* = I# a
313 which is what we want. Now suppose x-rhs is itself a case:
315 x-rhs = case e of { T -> I# a; F -> I# b }
317 The join point will abstract over a, rather than over (which is
318 what would have happened before) which is fine.
320 Notice that x certainly has the CPR property now!
322 In fact, splitThunk uses the function argument w/w splitting
323 function, so that if x's demand is deeper (say U(U(L,L),L))
324 then the splitting will go deeper too.
327 -- splitThunk converts the *non-recursive* binding
332 -- I# y -> let x = I# y in x }
333 -- See comments above. Is it not beautifully short?
335 splitThunk :: Var -> Expr Var -> UniqSM [(Var, Expr Var)]
336 splitThunk fn_id rhs = do
337 (_, wrap_fn, work_fn) <- mkWWstr [fn_id]
338 return [ (fn_id, Let (NonRec fn_id rhs) (wrap_fn (work_fn (Var fn_id)))) ]
342 %************************************************************************
344 \subsection{Functions over Demands}
346 %************************************************************************
349 worthSplittingFun :: [Demand] -> DmdResult -> Bool
350 -- True <=> the wrapper would not be an identity function
351 worthSplittingFun ds res
352 = any worth_it ds || returnsCPR res
353 -- worthSplitting returns False for an empty list of demands,
354 -- and hence do_strict_ww is False if arity is zero and there is no CPR
355 -- See Note [Worker-wrapper for bottoming functions]
357 worth_it Abs = True -- Absent arg
358 worth_it (Eval (Prod _)) = True -- Product arg to evaluate
361 worthSplittingThunk :: Maybe Demand -- Demand on the thunk
362 -> DmdResult -- CPR info for the thunk
364 worthSplittingThunk maybe_dmd res
365 = worth_it maybe_dmd || returnsCPR res
367 -- Split if the thing is unpacked
368 worth_it (Just (Eval (Prod ds))) = not (all isAbsent ds)
372 Note [Worker-wrapper for bottoming functions]
373 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
374 We used not to split if the result is bottom.
375 [Justification: there's no efficiency to be gained.]
377 But it's sometimes bad not to make a wrapper. Consider
378 fw = \x# -> let x = I# x# in case e of
382 The re-boxing code won't go away unless error_fn gets a wrapper too.
383 [We don't do reboxing now, but in general it's better to pass an
384 unboxed thing to f, and have it reboxed in the error cases....]
387 %************************************************************************
389 \subsection{The worker wrapper core}
391 %************************************************************************
393 @mkWrapper@ is called when importing a function. We have the type of
394 the function and the name of its worker, and we want to make its body (the wrapper).
397 mkWrapper :: Type -- Wrapper type
398 -> StrictSig -- Wrapper strictness info
399 -> UniqSM (Id -> CoreExpr) -- Wrapper body, missing worker Id
401 mkWrapper fun_ty (StrictSig (DmdType _ demands res_info)) = do
402 (_, wrap_fn, _) <- mkWwBodies fun_ty demands res_info noOneShotInfo
405 noOneShotInfo :: [Bool]
406 noOneShotInfo = repeat False