9f19dc35b199e2e6078cd1d38544e713e9f0aa2f
[ghc-hetmet.git] / compiler / stranal / WorkWrap.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[WorkWrap]{Worker/wrapper-generating back-end of strictness analyser}
5
6 \begin{code}
7 module WorkWrap ( wwTopBinds, mkWrapper ) where
8
9 #include "HsVersions.h"
10
11 import CoreSyn
12 import CoreUnfold       ( certainlyWillInline )
13 import CoreUtils        ( exprType, exprIsHNF, exprArity )
14 import Var
15 import Id               ( Id, idType, isOneShotLambda, 
16                           setIdNewStrictness, mkWorkerId,
17                           setIdWorkerInfo, setInlinePragma,
18                           setIdArity, idInfo )
19 import MkId             ( lazyIdKey, lazyIdUnfolding )
20 import Type             ( Type )
21 import IdInfo
22 import NewDemand        ( Demand(..), StrictSig(..), DmdType(..), DmdResult(..), 
23                           Demands(..), mkTopDmdType, isBotRes, returnsCPR, topSig, isAbsent
24                         )
25 import UniqSupply
26 import Unique           ( hasKey )
27 import BasicTypes       ( RecFlag(..), isNonRec, isNeverActive )
28 import VarEnv           ( isEmptyVarEnv )
29 import Maybes           ( orElse )
30 import WwLib
31 import Util             ( lengthIs, notNull )
32 import Outputable
33 import MonadUtils
34 \end{code}
35
36 We take Core bindings whose binders have:
37
38 \begin{enumerate}
39
40 \item Strictness attached (by the front-end of the strictness
41 analyser), and / or
42
43 \item Constructed Product Result information attached by the CPR
44 analysis pass.
45
46 \end{enumerate}
47
48 and we return some ``plain'' bindings which have been
49 worker/wrapper-ified, meaning: 
50
51 \begin{enumerate} 
52
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;
56
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).
60 \end{enumerate}
61
62 \begin{code}
63 wwTopBinds :: UniqSupply -> [CoreBind] -> [CoreBind]
64
65 wwTopBinds us top_binds
66   = initUs_ us $ do
67     top_binds' <- mapM wwBind top_binds
68     return (concat top_binds')
69 \end{code}
70
71 %************************************************************************
72 %*                                                                      *
73 \subsection[wwBind-wwExpr]{@wwBind@ and @wwExpr@}
74 %*                                                                      *
75 %************************************************************************
76
77 @wwBind@ works on a binding, trying each \tr{(binder, expr)} pair in
78 turn.  Non-recursive case first, then recursive...
79
80 \begin{code}
81 wwBind  :: CoreBind
82         -> UniqSM [CoreBind]    -- returns a WwBinding intermediate form;
83                                 -- the caller will convert to Expr/Binding,
84                                 -- as appropriate.
85
86 wwBind (NonRec binder rhs) = do
87     new_rhs <- wwExpr rhs
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.
92
93 wwBind (Rec pairs)
94   = return . Rec <$> concatMapM do_one pairs
95   where
96     do_one (binder, rhs) = do new_rhs <- wwExpr rhs
97                               tryWW Recursive binder new_rhs
98 \end{code}
99
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.
104
105 \begin{code}
106 wwExpr :: CoreExpr -> UniqSM CoreExpr
107
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
112
113 wwExpr e@(Var v)
114   | v `hasKey` lazyIdKey = return lazyIdUnfolding
115   | otherwise            = return e
116         -- HACK alert: Inline 'lazy' after strictness analysis
117         -- (but not inside InlineMe's)
118
119 wwExpr (Lam binder expr)
120   = Lam binder <$> wwExpr expr
121
122 wwExpr (App f a)
123   = App <$> wwExpr f <*> wwExpr a
124
125 wwExpr (Note note expr)
126   = Note note <$> wwExpr expr
127
128 wwExpr (Cast expr co) = do
129     new_expr <- wwExpr expr
130     return (Cast new_expr co)
131
132 wwExpr (Let bind expr)
133   = mkLets <$> wwBind bind <*> wwExpr expr
134
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)
139   where
140     ww_alt (con, binders, rhs) = do
141         new_rhs <- wwExpr rhs
142         return (con, binders, new_rhs)
143 \end{code}
144
145 %************************************************************************
146 %*                                                                      *
147 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
148 %*                                                                      *
149 %************************************************************************
150
151 @tryWW@ just accumulates arguments, converts strictness info from the
152 front-end into the proper form, then calls @mkWwBodies@ to do
153 the business.
154
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.
160
161 The only reason this is monadised is for the unique supply.
162
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)
168 into
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!
173
174 Furthermore, if the programmer has marked something as INLINE, 
175 we may lose by w/w'ing it.
176
177 If the strictness analyser is run twice, this test also prevents
178 wrappers (which are INLINEd) from being re-done.
179
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.)
183
184 \begin{code}
185 tryWW   :: RecFlag
186         -> Id                           -- The fn binder
187         -> CoreExpr                     -- The bound rhs; its innards
188                                         --   are already ww'd
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
193                                         -- wrapper.
194 tryWW is_rec fn_id rhs
195   |  -- isNonRec is_rec &&      -- Now omitted: see Note [Don't w/w inline things]
196      certainlyWillInline unfolding
197
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) ]
203
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
207
208   | is_fun && worthSplittingFun wrap_dmds res_info
209   = splitFun new_fn_id fn_info wrap_dmds res_info inline_prag rhs
210
211   | otherwise
212   = return [ (new_fn_id, rhs) ]
213
214   where
215     fn_info      = idInfo fn_id
216     maybe_fn_dmd = newDemandInfo fn_info
217     unfolding    = unfoldingInfo fn_info
218     inline_prag  = inlinePragInfo fn_info
219
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
224
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)
233
234     is_fun    = notNull wrap_dmds
235     is_thunk  = not is_fun && not (exprIsHNF rhs)
236
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) ) 
242     (do {
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
246     ; let
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 
255                                 -- not w/wd)
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
262
263         wrap_rhs = wrap_fn work_id
264         wrap_id  = fn_id `setIdWorkerInfo` HasWorker work_id arity
265
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
269   where
270     fun_ty = idType fn_id
271
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
274
275     work_res_info | isBotRes res_info = BotRes  -- Cpr stuff done by wrapper
276                   | otherwise         = TopRes
277
278     one_shots = get_one_shots rhs
279
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   | isId 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
290 \end{code}
291
292 Thunk splitting
293 ~~~~~~~~~~~~~~~
294 Suppose x is used strictly (never mind whether it has the CPR
295 property).  
296
297       let
298         x* = x-rhs
299       in body
300
301 splitThunk transforms like this:
302
303       let
304         x* = case x-rhs of { I# a -> I# a }
305       in body
306
307 Now simplifier will transform to
308
309       case x-rhs of 
310         I# a -> let x* = I# a 
311                 in body
312
313 which is what we want. Now suppose x-rhs is itself a case:
314
315         x-rhs = case e of { T -> I# a; F -> I# b }
316
317 The join point will abstract over a, rather than over (which is
318 what would have happened before) which is fine.
319
320 Notice that x certainly has the CPR property now!
321
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.
325
326 \begin{code}
327 -- splitThunk converts the *non-recursive* binding
328 --      x = e
329 -- into
330 --      x = let x = e
331 --          in case x of 
332 --               I# y -> let x = I# y in x }
333 -- See comments above. Is it not beautifully short?
334
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)))) ]
339 \end{code}
340
341
342 %************************************************************************
343 %*                                                                      *
344 \subsection{Functions over Demands}
345 %*                                                                      *
346 %************************************************************************
347
348 \begin{code}
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]
356   where
357     worth_it Abs              = True    -- Absent arg
358     worth_it (Eval (Prod _)) = True     -- Product arg to evaluate
359     worth_it _                = False
360
361 worthSplittingThunk :: Maybe Demand     -- Demand on the thunk
362                     -> DmdResult        -- CPR info for the thunk
363                     -> Bool
364 worthSplittingThunk maybe_dmd res
365   = worth_it maybe_dmd || returnsCPR res
366   where
367         -- Split if the thing is unpacked
368     worth_it (Just (Eval (Prod ds))) = not (all isAbsent ds)
369     worth_it _                       = False
370 \end{code}
371
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.]
376
377 But it's sometimes bad not to make a wrapper.  Consider
378         fw = \x# -> let x = I# x# in case e of
379                                         p1 -> error_fn x
380                                         p2 -> error_fn x
381                                         p3 -> the real stuff
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....]
385
386
387 %************************************************************************
388 %*                                                                      *
389 \subsection{The worker wrapper core}
390 %*                                                                      *
391 %************************************************************************
392
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).
395
396 \begin{code}
397 mkWrapper :: Type               -- Wrapper type
398           -> StrictSig          -- Wrapper strictness info
399           -> UniqSM (Id -> CoreExpr)    -- Wrapper body, missing worker Id
400
401 mkWrapper fun_ty (StrictSig (DmdType _ demands res_info)) = do
402     (_, wrap_fn, _) <- mkWwBodies fun_ty demands res_info noOneShotInfo
403     return wrap_fn
404
405 noOneShotInfo :: [Bool]
406 noOneShotInfo = repeat False
407 \end{code}