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 )
20 import CoreLint ( showPass, endPass )
21 import CoreUtils ( exprType, exprIsHNF, exprArity )
22 import Id ( Id, idType, isOneShotLambda,
23 setIdNewStrictness, mkWorkerId,
24 setIdWorkerInfo, setInlinePragma,
26 import MkId ( lazyIdKey, lazyIdUnfolding )
28 import IdInfo ( WorkerInfo(..), arityInfo,
29 newDemandInfo, newStrictnessInfo, unfoldingInfo, inlinePragInfo
31 import NewDemand ( Demand(..), StrictSig(..), DmdType(..), DmdResult(..),
32 Demands(..), mkTopDmdType, isBotRes, returnsCPR, topSig, isAbsent
35 import Unique ( hasKey )
36 import BasicTypes ( RecFlag(..), isNonRec, isNeverActive )
37 import VarEnv ( isEmptyVarEnv )
38 import Maybes ( orElse )
40 import Util ( lengthIs, notNull )
45 We take Core bindings whose binders have:
49 \item Strictness attached (by the front-end of the strictness
52 \item Constructed Product Result information attached by the CPR
57 and we return some ``plain'' bindings which have been
58 worker/wrapper-ified, meaning:
62 \item Functions have been split into workers and wrappers where
63 appropriate. If a function has both strictness and CPR properties
64 then only one worker/wrapper doing both transformations is produced;
66 \item Binders' @IdInfos@ have been updated to reflect the existence of
67 these workers/wrappers (this is where we get STRICTNESS and CPR pragma
68 info for exported values).
72 wwTopBinds :: UniqSupply -> [CoreBind] -> [CoreBind]
74 wwTopBinds us top_binds
76 top_binds' <- mapM wwBind top_binds
77 return (concat top_binds')
80 %************************************************************************
82 \subsection[wwBind-wwExpr]{@wwBind@ and @wwExpr@}
84 %************************************************************************
86 @wwBind@ works on a binding, trying each \tr{(binder, expr)} pair in
87 turn. Non-recursive case first, then recursive...
91 -> UniqSM [CoreBind] -- returns a WwBinding intermediate form;
92 -- the caller will convert to Expr/Binding,
95 wwBind (NonRec binder rhs) = do
97 new_pairs <- tryWW NonRecursive binder new_rhs
98 return [NonRec b e | (b,e) <- new_pairs]
99 -- Generated bindings must be non-recursive
100 -- because the original binding was.
103 = return . Rec <$> concatMapM do_one pairs
105 do_one (binder, rhs) = do new_rhs <- wwExpr rhs
106 tryWW Recursive binder new_rhs
109 @wwExpr@ basically just walks the tree, looking for appropriate
110 annotations that can be used. Remember it is @wwBind@ that does the
111 matching by looking for strict arguments of the correct type.
112 @wwExpr@ is a version that just returns the ``Plain'' Tree.
115 wwExpr :: CoreExpr -> UniqSM CoreExpr
117 wwExpr e@(Type _) = return e
118 wwExpr e@(Lit _) = return e
119 wwExpr e@(Note InlineMe expr) = return e
120 -- Don't w/w inside InlineMe's
123 | v `hasKey` lazyIdKey = return lazyIdUnfolding
124 | otherwise = return e
125 -- HACK alert: Inline 'lazy' after strictness analysis
126 -- (but not inside InlineMe's)
128 wwExpr (Lam binder expr)
129 = Lam binder <$> wwExpr expr
132 = App <$> wwExpr f <*> wwExpr a
134 wwExpr (Note note expr)
135 = Note note <$> wwExpr expr
137 wwExpr (Cast expr co) = do
138 new_expr <- wwExpr expr
139 return (Cast new_expr co)
141 wwExpr (Let bind expr)
142 = mkLets <$> wwBind bind <*> wwExpr expr
144 wwExpr (Case expr binder ty alts) = do
145 new_expr <- wwExpr expr
146 new_alts <- mapM ww_alt alts
147 return (Case new_expr binder ty new_alts)
149 ww_alt (con, binders, rhs) = do
150 new_rhs <- wwExpr rhs
151 return (con, binders, new_rhs)
154 %************************************************************************
156 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
158 %************************************************************************
160 @tryWW@ just accumulates arguments, converts strictness info from the
161 front-end into the proper form, then calls @mkWwBodies@ to do
164 We have to BE CAREFUL that we don't worker-wrapperize an Id that has
165 already been w-w'd! (You can end up with several liked-named Ids
166 bouncing around at the same time---absolute mischief.) So the
167 criterion we use is: if an Id already has an unfolding (for whatever
168 reason), then we don't w-w it.
170 The only reason this is monadised is for the unique supply.
172 Note [Don't w/w inline things]
173 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
174 It's very important to refrain from w/w-ing an INLINE function
175 If we do so by mistake we transform
176 f = __inline (\x -> E)
178 f = __inline (\x -> case x of (a,b) -> fw E)
179 fw = \ab -> (__inline (\x -> E)) (a,b)
180 and the original __inline now vanishes, so E is no longer
181 inside its __inline wrapper. Death! Disaster!
183 Furthermore, if the programmer has marked something as INLINE,
184 we may lose by w/w'ing it.
186 If the strictness analyser is run twice, this test also prevents
187 wrappers (which are INLINEd) from being re-done.
189 Notice that we refrain from w/w'ing an INLINE function even if it is
190 in a recursive group. It might not be the loop breaker. (We could
191 test for loop-breaker-hood, but I'm not sure that ever matters.)
195 -> Id -- The fn binder
196 -> CoreExpr -- The bound rhs; its innards
198 -> UniqSM [(Id, CoreExpr)] -- either *one* or *two* pairs;
199 -- if one, then no worker (only
200 -- the orig "wrapper" lives on);
201 -- if two, then a worker and a
203 tryWW is_rec fn_id rhs
204 | -- isNonRec is_rec && -- Now omitted: see Note [Don't w/w inline things]
205 certainlyWillInline unfolding
207 || isNeverActive inline_prag
208 -- No point in worker/wrappering if the thing is never inlined!
209 -- Because the no-inline prag will prevent the wrapper ever
210 -- being inlined at a call site.
211 = return [ (new_fn_id, rhs) ]
213 | is_thunk && worthSplittingThunk maybe_fn_dmd res_info
214 = ASSERT2( isNonRec is_rec, ppr new_fn_id ) -- The thunk must be non-recursive
215 splitThunk new_fn_id rhs
217 | is_fun && worthSplittingFun wrap_dmds res_info
218 = splitFun new_fn_id fn_info wrap_dmds res_info inline_prag rhs
221 = return [ (new_fn_id, rhs) ]
224 fn_info = idInfo fn_id
225 maybe_fn_dmd = newDemandInfo fn_info
226 unfolding = unfoldingInfo fn_info
227 inline_prag = inlinePragInfo fn_info
229 -- In practice it always will have a strictness
230 -- signature, even if it's a uninformative one
231 strict_sig = newStrictnessInfo fn_info `orElse` topSig
232 StrictSig (DmdType env wrap_dmds res_info) = strict_sig
234 -- new_fn_id has the DmdEnv zapped.
235 -- (a) it is never used again
236 -- (b) it wastes space
237 -- (c) it becomes incorrect as things are cloned, because
238 -- we don't push the substitution into it
239 new_fn_id | isEmptyVarEnv env = fn_id
240 | otherwise = fn_id `setIdNewStrictness`
241 StrictSig (mkTopDmdType wrap_dmds res_info)
243 is_fun = notNull wrap_dmds
244 is_thunk = not is_fun && not (exprIsHNF rhs)
246 ---------------------
247 splitFun fn_id fn_info wrap_dmds res_info inline_prag rhs
248 = WARN( not (wrap_dmds `lengthIs` arity), ppr fn_id <+> (ppr arity $$ ppr wrap_dmds $$ ppr res_info) )
250 -- The arity should match the signature
251 (work_demands, wrap_fn, work_fn) <- mkWwBodies fun_ty wrap_dmds res_info one_shots
252 ; work_uniq <- getUniqueM
254 work_rhs = work_fn rhs
255 work_id = mkWorkerId work_uniq fn_id (exprType work_rhs)
256 `setInlinePragma` inline_prag
257 -- Any inline pragma (which sets when inlining is active)
258 -- on the original function is duplicated on the worker and wrapper
259 -- It *matters* that the pragma stays on the wrapper
260 -- It seems sensible to have it on the worker too, although we
261 -- can't think of a compelling reason. (In ptic, INLINE things are
263 `setIdNewStrictness` StrictSig (mkTopDmdType work_demands work_res_info)
264 -- Even though we may not be at top level,
265 -- it's ok to give it an empty DmdEnv
266 `setIdArity` (exprArity work_rhs)
267 -- Set the arity so that the Core Lint check that the
268 -- arity is consistent with the demand type goes through
270 wrap_rhs = wrap_fn work_id
271 wrap_id = fn_id `setIdWorkerInfo` HasWorker work_id arity
273 ; return ([(work_id, work_rhs), (wrap_id, wrap_rhs)]) })
274 -- Worker first, because wrapper mentions it
275 -- mkWwBodies has already built a wrap_rhs with an INLINE pragma wrapped around it
277 fun_ty = idType fn_id
279 arity = arityInfo fn_info -- The arity is set by the simplifier using exprEtaExpandArity
280 -- So it may be more than the number of top-level-visible lambdas
282 work_res_info | isBotRes res_info = BotRes -- Cpr stuff done by wrapper
285 one_shots = get_one_shots rhs
287 -- If the original function has one-shot arguments, it is important to
288 -- make the wrapper and worker have corresponding one-shot arguments too.
289 -- Otherwise we spuriously float stuff out of case-expression join points,
290 -- which is very annoying.
291 get_one_shots (Lam b e)
292 | isIdVar b = isOneShotLambda b : get_one_shots e
293 | otherwise = get_one_shots e
294 get_one_shots (Note _ e) = get_one_shots e
295 get_one_shots other = noOneShotInfo
300 Suppose x is used strictly (never mind whether it has the CPR
307 splitThunk transforms like this:
310 x* = case x-rhs of { I# a -> I# a }
313 Now simplifier will transform to
316 I# a -> let x* = I# a
319 which is what we want. Now suppose x-rhs is itself a case:
321 x-rhs = case e of { T -> I# a; F -> I# b }
323 The join point will abstract over a, rather than over (which is
324 what would have happened before) which is fine.
326 Notice that x certainly has the CPR property now!
328 In fact, splitThunk uses the function argument w/w splitting
329 function, so that if x's demand is deeper (say U(U(L,L),L))
330 then the splitting will go deeper too.
333 -- splitThunk converts the *non-recursive* binding
338 -- I# y -> let x = I# y in x }
339 -- See comments above. Is it not beautifully short?
341 splitThunk fn_id rhs = do
342 (_, wrap_fn, work_fn) <- mkWWstr [fn_id]
343 return [ (fn_id, Let (NonRec fn_id rhs) (wrap_fn (work_fn (Var fn_id)))) ]
347 %************************************************************************
349 \subsection{Functions over Demands}
351 %************************************************************************
354 worthSplittingFun :: [Demand] -> DmdResult -> Bool
355 -- True <=> the wrapper would not be an identity function
356 worthSplittingFun ds res
357 = any worth_it ds || returnsCPR res
358 -- worthSplitting returns False for an empty list of demands,
359 -- and hence do_strict_ww is False if arity is zero and there is no CPR
360 -- See Note [Worker-wrapper for bottoming functions]
362 worth_it Abs = True -- Absent arg
363 worth_it (Eval (Prod ds)) = True -- Product arg to evaluate
364 worth_it other = False
366 worthSplittingThunk :: Maybe Demand -- Demand on the thunk
367 -> DmdResult -- CPR info for the thunk
369 worthSplittingThunk maybe_dmd res
370 = worth_it maybe_dmd || returnsCPR res
372 -- Split if the thing is unpacked
373 worth_it (Just (Eval (Prod ds))) = not (all isAbsent ds)
374 worth_it other = False
377 Note [Worker-wrapper for bottoming functions]
378 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
379 We used not to split if the result is bottom.
380 [Justification: there's no efficiency to be gained.]
382 But it's sometimes bad not to make a wrapper. Consider
383 fw = \x# -> let x = I# x# in case e of
387 The re-boxing code won't go away unless error_fn gets a wrapper too.
388 [We don't do reboxing now, but in general it's better to pass an
389 unboxed thing to f, and have it reboxed in the error cases....]
392 %************************************************************************
394 \subsection{The worker wrapper core}
396 %************************************************************************
398 @mkWrapper@ is called when importing a function. We have the type of
399 the function and the name of its worker, and we want to make its body (the wrapper).
402 mkWrapper :: Type -- Wrapper type
403 -> StrictSig -- Wrapper strictness info
404 -> UniqSM (Id -> CoreExpr) -- Wrapper body, missing worker Id
406 mkWrapper fun_ty (StrictSig (DmdType _ demands res_info)) = do
407 (_, wrap_fn, _) <- mkWwBodies fun_ty demands res_info noOneShotInfo
410 noOneShotInfo = repeat False