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