[project @ 2001-06-25 14:36:04 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 )
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 && 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         -- It's very important to refrain from w/w-ing an INLINE function
198         -- If we do so by mistake we transform
199         --      f = __inline (\x -> E)
200         -- into
201         --      f = __inline (\x -> case x of (a,b) -> fw E)
202         --      fw = \ab -> (__inline (\x -> E)) (a,b)
203         -- and the original __inline now vanishes, so E is no longer
204         -- inside its __inline wrapper.  Death!  Disaster!
205         --
206         -- OUT OF DATE NOTE:
207         --      [Out of date because the size calculation in CoreUnfold now
208         --       makes wrappers look very cheap even when they are inlined.]
209         --   In this case we add an INLINE pragma to the RHS.  Why?
210         --   Because consider
211         --        f = \x -> g x x
212         --        g = \yz -> ...                -- And g is strict
213         --   Then f is small, so we don't w/w it.  But g is big, and we do, so
214         --   g's wrapper will get inlined in f's RHS, which makes f look big now.
215         --   So f doesn't get inlined, but it is strict and we have failed to w/w it.
216   = returnUs [ (fn_id, rhs) ]
217
218   | not (do_strict_ww || do_cpr_ww)
219   = returnUs [ (fn_id, rhs) ]
220
221   | otherwise           -- Do w/w split
222   = mkWwBodies fun_ty arity wrap_dmds result_bot one_shots cpr_info     `thenUs` \ (work_demands, wrap_fn, work_fn) ->
223     getUniqueUs                                                         `thenUs` \ work_uniq ->
224     let
225         work_rhs      = work_fn rhs
226         proto_work_id = mkWorkerId work_uniq fn_id (exprType work_rhs) 
227                         `setInlinePragma` inline_prag
228
229         work_id | has_strictness = proto_work_id `setIdStrictness` mkStrictnessInfo (work_demands, result_bot)
230                 | otherwise      = proto_work_id
231
232         wrap_rhs = wrap_fn work_id
233         wrap_id  = fn_id `setIdStrictness`      wrapper_strictness
234                          `setIdWorkerInfo`      HasWorker work_id arity
235                          `setInlinePragma`      NoInlinePragInfo        -- Put it on the worker instead
236                 -- Add info to the wrapper:
237                 --      (a) we want to set its arity
238                 --      (b) we want to pin on its revised strictness info
239                 --      (c) we pin on its worker id 
240     in
241     returnUs ([(work_id, work_rhs), (wrap_id, wrap_rhs)])
242         -- Worker first, because wrapper mentions it
243         -- mkWwBodies has already built a wrap_rhs with an INLINE pragma wrapped around it
244   where
245     fun_ty = idType fn_id
246     arity  = idArity fn_id      -- The arity is set by the simplifier using exprEtaExpandArity
247                                 -- So it may be more than the number of top-level-visible lambdas
248
249     inline_prag  = idInlinePragma fn_id
250
251     strictness_info           = idStrictness fn_id
252     has_strictness            = case strictness_info of
253                                         StrictnessInfo _ _ -> True
254                                         NoStrictnessInfo   -> False
255     (arg_demands, result_bot) = case strictness_info of
256                                         StrictnessInfo d r -> (d,  r)
257                                         NoStrictnessInfo   -> ([], False)
258
259     wrap_dmds = setUnpackStrategy arg_demands
260     do_strict_ww = WARN( has_strictness && not result_bot && arity < length arg_demands && worthSplitting wrap_dmds result_bot, 
261                          text "Insufficient arity" <+> ppr fn_id <+> ppr arity <+> ppr arg_demands )
262                     (result_bot || arity >= length arg_demands) -- Only if there's enough visible arity
263                  &&                                             -- (else strictness info isn't valid)
264                                                                 -- 
265                     worthSplitting wrap_dmds result_bot         -- And it's useful
266         -- worthSplitting returns False for an empty list of demands,
267         -- and hence do_strict_ww is False if arity is zero
268         -- Also it's false if there is no strictness (arg_demands is [])
269
270     wrapper_strictness | has_strictness = mkStrictnessInfo (wrap_dmds, result_bot)
271                        | otherwise      = noStrictnessInfo
272
273         -------------------------------------------------------------
274     cpr_info  = idCprInfo fn_id
275     do_cpr_ww = arity > 0 &&
276                 case cpr_info of
277                         ReturnsCPR -> True
278                         other      -> False
279
280         -------------------------------------------------------------
281     one_shots = get_one_shots rhs
282
283 -- If the original function has one-shot arguments, it is important to
284 -- make the wrapper and worker have corresponding one-shot arguments too.
285 -- Otherwise we spuriously float stuff out of case-expression join points,
286 -- which is very annoying.
287 get_one_shots (Lam b e)
288   | isId b    = isOneShotLambda b : get_one_shots e
289   | otherwise = get_one_shots e
290 get_one_shots (Note _ e) = get_one_shots e
291 get_one_shots other      = noOneShotInfo
292 \end{code}
293
294
295
296 %************************************************************************
297 %*                                                                      *
298 \subsection{The worker wrapper core}
299 %*                                                                      *
300 %************************************************************************
301
302 @mkWrapper@ is called when importing a function.  We have the type of 
303 the function and the name of its worker, and we want to make its body (the wrapper).
304
305 \begin{code}
306 mkWrapper :: Type               -- Wrapper type
307           -> Int                -- Arity
308           -> [Demand]           -- Wrapper strictness info
309           -> Bool               -- Function returns bottom
310           -> CprInfo            -- Wrapper cpr info
311           -> UniqSM (Id -> CoreExpr)    -- Wrapper body, missing worker Id
312
313 mkWrapper fun_ty arity demands res_bot cpr_info
314   = mkWwBodies fun_ty arity demands res_bot noOneShotInfo cpr_info      `thenUs` \ (_, wrap_fn, _) ->
315     returnUs wrap_fn
316
317 noOneShotInfo = repeat False
318 \end{code}
319
320