[project @ 2000-12-06 13:03:28 by simonmar]
[ghc-hetmet.git] / ghc / 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 CoreLint         ( showPass, endPass )
14 import CoreUtils        ( exprType )
15 import MkId             ( mkWorkerId )
16 import Id               ( Id, idType, idStrictness, idArity, isOneShotLambda,
17                           setIdStrictness, idInlinePragma, 
18                           setIdWorkerInfo, idCprInfo, setInlinePragma )
19 import Type             ( Type, isNewType, splitForAllTys, splitFunTys )
20 import IdInfo           ( mkStrictnessInfo, noStrictnessInfo, StrictnessInfo(..),
21                           CprInfo(..), InlinePragInfo(..), isNeverInlinePrag,
22                           WorkerInfo(..)
23                         )
24 import Demand           ( Demand )
25 import UniqSupply       ( UniqSupply, initUs_, returnUs, thenUs, mapUs, getUniqueUs, UniqSM )
26 import CmdLineOpts
27 import WwLib
28 import Outputable
29 \end{code}
30
31 We take Core bindings whose binders have:
32
33 \begin{enumerate}
34
35 \item Strictness attached (by the front-end of the strictness
36 analyser), and / or
37
38 \item Constructed Product Result information attached by the CPR
39 analysis pass.
40
41 \end{enumerate}
42
43 and we return some ``plain'' bindings which have been
44 worker/wrapper-ified, meaning: 
45
46 \begin{enumerate} 
47
48 \item Functions have been split into workers and wrappers where
49 appropriate.  If a function has both strictness and CPR properties
50 then only one worker/wrapper doing both transformations is produced;
51
52 \item Binders' @IdInfos@ have been updated to reflect the existence of
53 these workers/wrappers (this is where we get STRICTNESS and CPR pragma
54 info for exported values).
55 \end{enumerate}
56
57 \begin{code}
58
59 wwTopBinds :: DynFlags 
60            -> UniqSupply
61            -> [CoreBind]
62            -> IO [CoreBind]
63
64 wwTopBinds dflags us binds
65   = do {
66         showPass dflags "Worker Wrapper binds";
67
68         -- Create worker/wrappers, and mark binders with their
69         -- "strictness info" [which encodes their worker/wrapper-ness]
70         let { binds' = workersAndWrappers us binds };
71
72         endPass dflags "Worker Wrapper binds" 
73                 Opt_D_dump_worker_wrapper binds'
74     }
75 \end{code}
76
77
78 \begin{code}
79 workersAndWrappers :: UniqSupply -> [CoreBind] -> [CoreBind]
80
81 workersAndWrappers us top_binds
82   = initUs_ us $
83     mapUs wwBind top_binds `thenUs` \ top_binds' ->
84     returnUs (concat top_binds')
85 \end{code}
86
87 %************************************************************************
88 %*                                                                      *
89 \subsection[wwBind-wwExpr]{@wwBind@ and @wwExpr@}
90 %*                                                                      *
91 %************************************************************************
92
93 @wwBind@ works on a binding, trying each \tr{(binder, expr)} pair in
94 turn.  Non-recursive case first, then recursive...
95
96 \begin{code}
97 wwBind  :: CoreBind
98         -> UniqSM [CoreBind]    -- returns a WwBinding intermediate form;
99                                 -- the caller will convert to Expr/Binding,
100                                 -- as appropriate.
101
102 wwBind (NonRec binder rhs)
103   = wwExpr rhs                                          `thenUs` \ new_rhs ->
104     tryWW True {- non-recursive -} binder new_rhs       `thenUs` \ new_pairs ->
105     returnUs [NonRec b e | (b,e) <- new_pairs]
106       -- Generated bindings must be non-recursive
107       -- because the original binding was.
108
109 ------------------------------
110
111 wwBind (Rec pairs)
112   = mapUs do_one pairs          `thenUs` \ new_pairs ->
113     returnUs [Rec (concat new_pairs)]
114   where
115     do_one (binder, rhs) = wwExpr rhs   `thenUs` \ new_rhs ->
116                            tryWW False {- recursive -} binder new_rhs
117 \end{code}
118
119 @wwExpr@ basically just walks the tree, looking for appropriate
120 annotations that can be used. Remember it is @wwBind@ that does the
121 matching by looking for strict arguments of the correct type.
122 @wwExpr@ is a version that just returns the ``Plain'' Tree.
123
124 \begin{code}
125 wwExpr :: CoreExpr -> UniqSM CoreExpr
126
127 wwExpr e@(Type _)   = returnUs e
128 wwExpr e@(Var _)    = returnUs e
129 wwExpr e@(Lit _)    = returnUs e
130
131 wwExpr (Lam binder expr)
132   = wwExpr expr                 `thenUs` \ new_expr ->
133     returnUs (Lam binder new_expr)
134
135 wwExpr (App f a)
136   = wwExpr f                    `thenUs` \ new_f ->
137     wwExpr a                    `thenUs` \ new_a ->
138     returnUs (App new_f new_a)
139
140 wwExpr (Note note expr)
141   = wwExpr expr                 `thenUs` \ new_expr ->
142     returnUs (Note note new_expr)
143
144 wwExpr (Let bind expr)
145   = wwBind bind                 `thenUs` \ intermediate_bind ->
146     wwExpr expr                 `thenUs` \ new_expr ->
147     returnUs (mkLets intermediate_bind new_expr)
148
149 wwExpr (Case expr binder alts)
150   = wwExpr expr                         `thenUs` \ new_expr ->
151     mapUs ww_alt alts                   `thenUs` \ new_alts ->
152     returnUs (Case new_expr binder new_alts)
153   where
154     ww_alt (con, binders, rhs)
155       = wwExpr rhs                      `thenUs` \ new_rhs ->
156         returnUs (con, binders, new_rhs)
157 \end{code}
158
159 %************************************************************************
160 %*                                                                      *
161 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
162 %*                                                                      *
163 %************************************************************************
164
165 @tryWW@ just accumulates arguments, converts strictness info from the
166 front-end into the proper form, then calls @mkWwBodies@ to do
167 the business.
168
169 We have to BE CAREFUL that we don't worker-wrapperize an Id that has
170 already been w-w'd!  (You can end up with several liked-named Ids
171 bouncing around at the same time---absolute mischief.)  So the
172 criterion we use is: if an Id already has an unfolding (for whatever
173 reason), then we don't w-w it.
174
175 The only reason this is monadised is for the unique supply.
176
177 \begin{code}
178 tryWW   :: Bool                         -- True <=> a non-recursive binding
179         -> Id                           -- The fn binder
180         -> CoreExpr                     -- The bound rhs; its innards
181                                         --   are already ww'd
182         -> UniqSM [(Id, CoreExpr)]      -- either *one* or *two* pairs;
183                                         -- if one, then no worker (only
184                                         -- the orig "wrapper" lives on);
185                                         -- if two, then a worker and a
186                                         -- wrapper.
187 tryWW non_rec fn_id rhs
188   | isNeverInlinePrag inline_prag || arity == 0
189   =     -- Don't split things that will never be inlined
190     returnUs [ (fn_id, rhs) ]
191
192   | non_rec && not do_coerce_ww && certainlyWillInline fn_id
193         -- No point in worker/wrappering a function that is going to be
194         -- INLINEd wholesale anyway.  If the strictness analyser is run
195         -- twice, this test also prevents wrappers (which are INLINEd)
196         -- from being re-done.
197         --
198         -- The do_coerce_ww test is so that
199         -- a function with a coerce should w/w to get rid
200         -- of the coerces, which can significantly improve its arity.
201         -- Example:  f []     = return [] :: IO [Int]
202         --           f (x:xs) = return (x:xs)
203         -- If we aren't careful we end up with
204         --      f = \ x -> case x of {
205         --                   x:xs -> __coerce (IO [Int]) (\ s -> (# s, x:xs #)
206         --                   []   -> lvl_sJ8
207         --
208         --
209         -- OUT OF DATE NOTE, kept for info:
210         -- It's out of date because now wrappers look very cheap 
211         -- even when they are inlined.
212         --   In this case we add an INLINE pragma to the RHS.  Why?
213         --   Because consider
214         --        f = \x -> g x x
215         --        g = \yz -> ...                -- And g is strict
216         --   Then f is small, so we don't w/w it.  But g is big, and we do, so
217         --   g's wrapper will get inlined in f's RHS, which makes f look big now.
218         --   So f doesn't get inlined, but it is strict and we have failed to w/w it.
219   = returnUs [ (fn_id, rhs) ]
220
221   | not (do_strict_ww || do_cpr_ww || do_coerce_ww)
222   = returnUs [ (fn_id, rhs) ]
223
224   | otherwise           -- Do w/w split
225   = mkWwBodies fun_ty arity wrap_dmds result_bot one_shots cpr_info     `thenUs` \ (work_demands, wrap_fn, work_fn) ->
226     getUniqueUs                                                         `thenUs` \ work_uniq ->
227     let
228         work_rhs      = work_fn rhs
229         proto_work_id = mkWorkerId work_uniq fn_id (exprType work_rhs) 
230                         `setInlinePragma` inline_prag
231
232         work_id | has_strictness = proto_work_id `setIdStrictness` mkStrictnessInfo (work_demands, result_bot)
233                 | otherwise      = proto_work_id
234
235         wrap_rhs = wrap_fn work_id
236         wrap_id  = fn_id `setIdStrictness`      wrapper_strictness
237                          `setIdWorkerInfo`      HasWorker work_id arity
238                          `setInlinePragma`      NoInlinePragInfo        -- Put it on the worker instead
239                 -- Add info to the wrapper:
240                 --      (a) we want to set its arity
241                 --      (b) we want to pin on its revised strictness info
242                 --      (c) we pin on its worker id 
243     in
244     returnUs ([(work_id, work_rhs), (wrap_id, wrap_rhs)])
245         -- Worker first, because wrapper mentions it
246         -- mkWwBodies has already built a wrap_rhs with an INLINE pragma wrapped around it
247   where
248     fun_ty = idType fn_id
249     arity  = idArity fn_id      -- The arity is set by the simplifier using exprEtaExpandArity
250                                 -- So it may be more than the number of top-level-visible lambdas
251
252     inline_prag  = idInlinePragma fn_id
253
254     strictness_info           = idStrictness fn_id
255     has_strictness            = case strictness_info of
256                                         StrictnessInfo _ _ -> True
257                                         NoStrictnessInfo   -> False
258     (arg_demands, result_bot) = case strictness_info of
259                                         StrictnessInfo d r -> (d,  r)
260                                         NoStrictnessInfo   -> ([], False)
261
262     wrap_dmds = setUnpackStrategy arg_demands
263     do_strict_ww = WARN( has_strictness && not result_bot && arity < length arg_demands && worthSplitting wrap_dmds result_bot, 
264                          text "Insufficient arity" <+> ppr fn_id <+> ppr arity <+> ppr arg_demands )
265                     (result_bot || arity >= length arg_demands) -- Only if there's enough visible arity
266                  &&                                             -- (else strictness info isn't valid)
267                                                                 -- 
268                     worthSplitting wrap_dmds result_bot         -- And it's useful
269         -- worthSplitting returns False for an empty list of demands,
270         -- and hence do_strict_ww is False if arity is zero
271         -- Also it's false if there is no strictness (arg_demands is [])
272
273     wrapper_strictness | has_strictness = mkStrictnessInfo (wrap_dmds, result_bot)
274                        | otherwise      = noStrictnessInfo
275
276         -------------------------------------------------------------
277     cpr_info  = idCprInfo fn_id
278     do_cpr_ww = arity > 0 &&
279                 case cpr_info of
280                         ReturnsCPR -> True
281                         other      -> False
282
283         -------------------------------------------------------------
284     do_coerce_ww = check_for_coerce arity fun_ty
285         -- We are willing to do a w/w even if the arity is zero.
286         --      x = coerce t E
287         -- ==>
288         --      x' = E
289         --      x  = coerce t x'
290
291         -------------------------------------------------------------
292     one_shots = get_one_shots rhs
293
294 -- See if there's a Coerce before we run out of arity;
295 -- if so, it's worth trying a w/w split.  Reason: we find
296 -- functions like       f = coerce (\s -> e)
297 --           and        g = \x -> coerce (\s -> e)
298 -- and they may have no useful strictness or cpr info, but if we
299 -- do the w/w thing we get rid of the coerces.  
300
301 check_for_coerce arity ty
302   = length arg_tys <= arity && isNewType res_ty
303         -- Don't look further than arity args, 
304         -- but if there are arity or fewer, see if there's
305         -- a newtype in the corner
306   where
307     (_, tau)          = splitForAllTys ty
308     (arg_tys, res_ty) = splitFunTys tau
309
310 -- If the original function has one-shot arguments, it is important to
311 -- make the wrapper and worker have corresponding one-shot arguments too.
312 -- Otherwise we spuriously float stuff out of case-expression join points,
313 -- which is very annoying.
314 get_one_shots (Lam b e)
315   | isId b    = isOneShotLambda b : get_one_shots e
316   | otherwise = get_one_shots e
317 get_one_shots (Note _ e) = get_one_shots e
318 get_one_shots other      = noOneShotInfo
319 \end{code}
320
321
322
323 %************************************************************************
324 %*                                                                      *
325 \subsection{The worker wrapper core}
326 %*                                                                      *
327 %************************************************************************
328
329 @mkWrapper@ is called when importing a function.  We have the type of 
330 the function and the name of its worker, and we want to make its body (the wrapper).
331
332 \begin{code}
333 mkWrapper :: Type               -- Wrapper type
334           -> Int                -- Arity
335           -> [Demand]           -- Wrapper strictness info
336           -> Bool               -- Function returns bottom
337           -> CprInfo            -- Wrapper cpr info
338           -> UniqSM (Id -> CoreExpr)    -- Wrapper body, missing worker Id
339
340 mkWrapper fun_ty arity demands res_bot cpr_info
341   = mkWwBodies fun_ty arity demands res_bot noOneShotInfo cpr_info      `thenUs` \ (_, wrap_fn, _) ->
342     returnUs wrap_fn
343
344 noOneShotInfo = repeat False
345 \end{code}
346
347