2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[WorkWrap]{Worker/wrapper-generating back-end of strictness analyser}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 module WorkWrap ( wwTopBinds, mkWrapper ) where
16 #include "HsVersions.h"
19 import CoreUnfold ( certainlyWillInline, mkWwInlineRule )
20 import CoreLint ( showPass, endPass )
21 import CoreUtils ( exprType, exprIsHNF, exprArity )
22 import Id ( Id, idType, isOneShotLambda,
23 setIdNewStrictness, mkWorkerId,
24 setInlinePragma, setIdUnfolding, setIdArity, idInfo )
25 import MkId ( lazyIdKey, lazyIdUnfolding )
27 import IdInfo ( arityInfo, newDemandInfo, newStrictnessInfo,
28 unfoldingInfo, inlinePragInfo )
29 import NewDemand ( Demand(..), StrictSig(..), DmdType(..), DmdResult(..),
30 Demands(..), mkTopDmdType, isBotRes, returnsCPR, topSig, isAbsent
33 import Unique ( hasKey )
34 import BasicTypes ( RecFlag(..), isNonRec, isNeverActive )
35 import VarEnv ( isEmptyVarEnv )
36 import Maybes ( orElse )
38 import Util ( lengthIs, notNull )
43 We take Core bindings whose binders have:
47 \item Strictness attached (by the front-end of the strictness
50 \item Constructed Product Result information attached by the CPR
55 and we return some ``plain'' bindings which have been
56 worker/wrapper-ified, meaning:
60 \item Functions have been split into workers and wrappers where
61 appropriate. If a function has both strictness and CPR properties
62 then only one worker/wrapper doing both transformations is produced;
64 \item Binders' @IdInfos@ have been updated to reflect the existence of
65 these workers/wrappers (this is where we get STRICTNESS and CPR pragma
66 info for exported values).
70 wwTopBinds :: UniqSupply -> [CoreBind] -> [CoreBind]
72 wwTopBinds us top_binds
74 top_binds' <- mapM wwBind top_binds
75 return (concat top_binds')
78 %************************************************************************
80 \subsection[wwBind-wwExpr]{@wwBind@ and @wwExpr@}
82 %************************************************************************
84 @wwBind@ works on a binding, trying each \tr{(binder, expr)} pair in
85 turn. Non-recursive case first, then recursive...
89 -> UniqSM [CoreBind] -- returns a WwBinding intermediate form;
90 -- the caller will convert to Expr/Binding,
93 wwBind (NonRec binder rhs) = do
95 new_pairs <- tryWW NonRecursive binder new_rhs
96 return [NonRec b e | (b,e) <- new_pairs]
97 -- Generated bindings must be non-recursive
98 -- because the original binding was.
101 = return . Rec <$> concatMapM do_one pairs
103 do_one (binder, rhs) = do new_rhs <- wwExpr rhs
104 tryWW Recursive binder new_rhs
107 @wwExpr@ basically just walks the tree, looking for appropriate
108 annotations that can be used. Remember it is @wwBind@ that does the
109 matching by looking for strict arguments of the correct type.
110 @wwExpr@ is a version that just returns the ``Plain'' Tree.
113 wwExpr :: CoreExpr -> UniqSM CoreExpr
115 wwExpr e@(Type _) = return e
116 wwExpr e@(Lit _) = return e
118 | v `hasKey` lazyIdKey = return lazyIdUnfolding
119 | otherwise = return e
120 -- HACK alert: Inline 'lazy' after strictness analysis
122 wwExpr (Lam binder expr)
123 = Lam binder <$> wwExpr expr
126 = App <$> wwExpr f <*> wwExpr a
128 wwExpr (Note note expr)
129 = Note note <$> wwExpr expr
131 wwExpr (Cast expr co) = do
132 new_expr <- wwExpr expr
133 return (Cast new_expr co)
135 wwExpr (Let bind expr)
136 = mkLets <$> wwBind bind <*> wwExpr expr
138 wwExpr (Case expr binder ty alts) = do
139 new_expr <- wwExpr expr
140 new_alts <- mapM ww_alt alts
141 return (Case new_expr binder ty new_alts)
143 ww_alt (con, binders, rhs) = do
144 new_rhs <- wwExpr rhs
145 return (con, binders, new_rhs)
148 %************************************************************************
150 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
152 %************************************************************************
154 @tryWW@ just accumulates arguments, converts strictness info from the
155 front-end into the proper form, then calls @mkWwBodies@ to do
158 We have to BE CAREFUL that we don't worker-wrapperize an Id that has
159 already been w-w'd! (You can end up with several liked-named Ids
160 bouncing around at the same time---absolute mischief.) So the
161 criterion we use is: if an Id already has an unfolding (for whatever
162 reason), then we don't w-w it.
164 The only reason this is monadised is for the unique supply.
166 Note [Don't w/w inline things]
167 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
168 It's very important to refrain from w/w-ing an INLINE function
169 because the wrapepr will then overwrite the InlineRule unfolding.
171 It was wrong with the old InlineMe Note too: if we do so by mistake
173 f = __inline (\x -> E)
175 f = __inline (\x -> case x of (a,b) -> fw E)
176 fw = \ab -> (__inline (\x -> E)) (a,b)
177 and the original __inline now vanishes, so E is no longer
178 inside its __inline wrapper. Death! Disaster!
180 Furthermore, if the programmer has marked something as INLINE,
181 we may lose by w/w'ing it.
183 If the strictness analyser is run twice, this test also prevents
184 wrappers (which are INLINEd) from being re-done.
186 Notice that we refrain from w/w'ing an INLINE function even if it is
187 in a recursive group. It might not be the loop breaker. (We could
188 test for loop-breaker-hood, but I'm not sure that ever matters.)
192 -> Id -- The fn binder
193 -> CoreExpr -- The bound rhs; its innards
195 -> UniqSM [(Id, CoreExpr)] -- either *one* or *two* pairs;
196 -- if one, then no worker (only
197 -- the orig "wrapper" lives on);
198 -- if two, then a worker and a
200 tryWW is_rec fn_id rhs
201 | -- isNonRec is_rec && -- Now omitted: see Note [Don't w/w inline things]
202 certainlyWillInline unfolding
204 || isNeverActive inline_prag
205 -- No point in worker/wrappering if the thing is never inlined!
206 -- Because the no-inline prag will prevent the wrapper ever
207 -- being inlined at a call site.
208 = return [ (new_fn_id, rhs) ]
210 | is_thunk && worthSplittingThunk maybe_fn_dmd res_info
211 = ASSERT2( isNonRec is_rec, ppr new_fn_id ) -- The thunk must be non-recursive
212 splitThunk new_fn_id rhs
214 | is_fun && worthSplittingFun wrap_dmds res_info
215 = splitFun new_fn_id fn_info wrap_dmds res_info inline_prag rhs
218 = return [ (new_fn_id, rhs) ]
221 fn_info = idInfo fn_id
222 maybe_fn_dmd = newDemandInfo fn_info
223 unfolding = unfoldingInfo fn_info
224 inline_prag = inlinePragInfo fn_info
226 -- In practice it always will have a strictness
227 -- signature, even if it's a uninformative one
228 strict_sig = newStrictnessInfo fn_info `orElse` topSig
229 StrictSig (DmdType env wrap_dmds res_info) = strict_sig
231 -- new_fn_id has the DmdEnv zapped.
232 -- (a) it is never used again
233 -- (b) it wastes space
234 -- (c) it becomes incorrect as things are cloned, because
235 -- we don't push the substitution into it
236 new_fn_id | isEmptyVarEnv env = fn_id
237 | otherwise = fn_id `setIdNewStrictness`
238 StrictSig (mkTopDmdType wrap_dmds res_info)
240 is_fun = notNull wrap_dmds
241 is_thunk = not is_fun && not (exprIsHNF rhs)
243 ---------------------
244 splitFun fn_id fn_info wrap_dmds res_info inline_prag rhs
245 = WARN( not (wrap_dmds `lengthIs` arity), ppr fn_id <+> (ppr arity $$ ppr wrap_dmds $$ ppr res_info) )
247 -- The arity should match the signature
248 (work_demands, wrap_fn, work_fn) <- mkWwBodies fun_ty wrap_dmds res_info one_shots
249 ; work_uniq <- getUniqueM
251 work_rhs = work_fn rhs
252 work_id = mkWorkerId work_uniq fn_id (exprType work_rhs)
253 `setInlinePragma` inline_prag
254 -- Any inline pragma (which sets when inlining is active)
255 -- on the original function is duplicated on the worker and wrapper
256 -- It *matters* that the pragma stays on the wrapper
257 -- It seems sensible to have it on the worker too, although we
258 -- can't think of a compelling reason. (In ptic, INLINE things are
260 `setIdNewStrictness` StrictSig (mkTopDmdType work_demands work_res_info)
261 -- Even though we may not be at top level,
262 -- it's ok to give it an empty DmdEnv
263 `setIdArity` (exprArity work_rhs)
264 -- Set the arity so that the Core Lint check that the
265 -- arity is consistent with the demand type goes through
267 wrap_rhs = wrap_fn work_id
268 wrap_id = fn_id `setIdUnfolding` mkWwInlineRule wrap_rhs arity work_id
270 ; return ([(work_id, work_rhs), (wrap_id, wrap_rhs)]) })
271 -- Worker first, because wrapper mentions it
272 -- mkWwBodies has already built a wrap_rhs with an INLINE pragma wrapped around it
274 fun_ty = idType fn_id
276 arity = arityInfo fn_info -- The arity is set by the simplifier using exprEtaExpandArity
277 -- So it may be more than the number of top-level-visible lambdas
279 work_res_info | isBotRes res_info = BotRes -- Cpr stuff done by wrapper
282 one_shots = get_one_shots rhs
284 -- If the original function has one-shot arguments, it is important to
285 -- make the wrapper and worker have corresponding one-shot arguments too.
286 -- Otherwise we spuriously float stuff out of case-expression join points,
287 -- which is very annoying.
288 get_one_shots (Lam b e)
289 | isIdVar b = isOneShotLambda b : get_one_shots e
290 | otherwise = get_one_shots e
291 get_one_shots (Note _ e) = get_one_shots e
292 get_one_shots other = noOneShotInfo
297 Suppose x is used strictly (never mind whether it has the CPR
304 splitThunk transforms like this:
307 x* = case x-rhs of { I# a -> I# a }
310 Now simplifier will transform to
313 I# a -> let x* = I# a
316 which is what we want. Now suppose x-rhs is itself a case:
318 x-rhs = case e of { T -> I# a; F -> I# b }
320 The join point will abstract over a, rather than over (which is
321 what would have happened before) which is fine.
323 Notice that x certainly has the CPR property now!
325 In fact, splitThunk uses the function argument w/w splitting
326 function, so that if x's demand is deeper (say U(U(L,L),L))
327 then the splitting will go deeper too.
330 -- splitThunk converts the *non-recursive* binding
335 -- I# y -> let x = I# y in x }
336 -- See comments above. Is it not beautifully short?
338 splitThunk fn_id rhs = do
339 (_, wrap_fn, work_fn) <- mkWWstr [fn_id]
340 return [ (fn_id, Let (NonRec fn_id rhs) (wrap_fn (work_fn (Var fn_id)))) ]
344 %************************************************************************
346 \subsection{Functions over Demands}
348 %************************************************************************
351 worthSplittingFun :: [Demand] -> DmdResult -> Bool
352 -- True <=> the wrapper would not be an identity function
353 worthSplittingFun ds res
354 = any worth_it ds || returnsCPR res
355 -- worthSplitting returns False for an empty list of demands,
356 -- and hence do_strict_ww is False if arity is zero and there is no CPR
357 -- See Note [Worker-wrapper for bottoming functions]
359 worth_it Abs = True -- Absent arg
360 worth_it (Eval (Prod ds)) = True -- Product arg to evaluate
361 worth_it other = False
363 worthSplittingThunk :: Maybe Demand -- Demand on the thunk
364 -> DmdResult -- CPR info for the thunk
366 worthSplittingThunk maybe_dmd res
367 = worth_it maybe_dmd || returnsCPR res
369 -- Split if the thing is unpacked
370 worth_it (Just (Eval (Prod ds))) = not (all isAbsent ds)
371 worth_it other = False
374 Note [Worker-wrapper for bottoming functions]
375 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
376 We used not to split if the result is bottom.
377 [Justification: there's no efficiency to be gained.]
379 But it's sometimes bad not to make a wrapper. Consider
380 fw = \x# -> let x = I# x# in case e of
384 The re-boxing code won't go away unless error_fn gets a wrapper too.
385 [We don't do reboxing now, but in general it's better to pass an
386 unboxed thing to f, and have it reboxed in the error cases....]
389 %************************************************************************
391 \subsection{The worker wrapper core}
393 %************************************************************************
395 @mkWrapper@ is called when importing a function. We have the type of
396 the function and the name of its worker, and we want to make its body (the wrapper).
399 mkWrapper :: Type -- Wrapper type
400 -> StrictSig -- Wrapper strictness info
401 -> UniqSM (Id -> CoreExpr) -- Wrapper body, missing worker Id
403 mkWrapper fun_ty (StrictSig (DmdType _ demands res_info)) = do
404 (_, wrap_fn, _) <- mkWwBodies fun_ty demands res_info noOneShotInfo
407 noOneShotInfo = repeat False