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