[project @ 2001-09-26 15:12:33 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, idNewStrictness, idArity, isOneShotLambda,
16                           setIdNewStrictness, zapIdNewStrictness, idInlinePragma, mkWorkerId,
17                           setIdWorkerInfo, setInlinePragma )
18 import Type             ( Type )
19 import IdInfo           ( WorkerInfo(..) )
20 import NewDemand        ( Demand(..), StrictSig(..), DmdType(..), DmdResult(..), 
21                           mkTopDmdType, isBotRes, returnsCPR
22                         )
23 import UniqSupply       ( UniqSupply, initUs_, returnUs, thenUs, mapUs, getUniqueUs, UniqSM )
24 import BasicTypes       ( RecFlag(..), isNonRec, Activation(..), isNeverActive )
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 NonRecursive 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 wwBind (Rec pairs)
109   = mapUs do_one pairs          `thenUs` \ new_pairs ->
110     returnUs [Rec (concat new_pairs)]
111   where
112     do_one (binder, rhs) = wwExpr rhs   `thenUs` \ new_rhs ->
113                            tryWW Recursive binder new_rhs
114 \end{code}
115
116 @wwExpr@ basically just walks the tree, looking for appropriate
117 annotations that can be used. Remember it is @wwBind@ that does the
118 matching by looking for strict arguments of the correct type.
119 @wwExpr@ is a version that just returns the ``Plain'' Tree.
120
121 \begin{code}
122 wwExpr :: CoreExpr -> UniqSM CoreExpr
123
124 wwExpr e@(Type _)   = returnUs e
125 wwExpr e@(Var _)    = returnUs e
126 wwExpr e@(Lit _)    = returnUs e
127
128 wwExpr (Lam binder expr)
129   = wwExpr expr                 `thenUs` \ new_expr ->
130     returnUs (Lam binder new_expr)
131
132 wwExpr (App f a)
133   = wwExpr f                    `thenUs` \ new_f ->
134     wwExpr a                    `thenUs` \ new_a ->
135     returnUs (App new_f new_a)
136
137 wwExpr (Note note expr)
138   = wwExpr expr                 `thenUs` \ new_expr ->
139     returnUs (Note note new_expr)
140
141 wwExpr (Let bind expr)
142   = wwBind bind                 `thenUs` \ intermediate_bind ->
143     wwExpr expr                 `thenUs` \ new_expr ->
144     returnUs (mkLets intermediate_bind new_expr)
145
146 wwExpr (Case expr binder alts)
147   = wwExpr expr                         `thenUs` \ new_expr ->
148     mapUs ww_alt alts                   `thenUs` \ new_alts ->
149     returnUs (Case new_expr binder new_alts)
150   where
151     ww_alt (con, binders, rhs)
152       = wwExpr rhs                      `thenUs` \ new_rhs ->
153         returnUs (con, binders, new_rhs)
154 \end{code}
155
156 %************************************************************************
157 %*                                                                      *
158 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
159 %*                                                                      *
160 %************************************************************************
161
162 @tryWW@ just accumulates arguments, converts strictness info from the
163 front-end into the proper form, then calls @mkWwBodies@ to do
164 the business.
165
166 We have to BE CAREFUL that we don't worker-wrapperize an Id that has
167 already been w-w'd!  (You can end up with several liked-named Ids
168 bouncing around at the same time---absolute mischief.)  So the
169 criterion we use is: if an Id already has an unfolding (for whatever
170 reason), then we don't w-w it.
171
172 The only reason this is monadised is for the unique supply.
173
174 \begin{code}
175 tryWW   :: RecFlag
176         -> Id                           -- The fn binder
177         -> CoreExpr                     -- The bound rhs; its innards
178                                         --   are already ww'd
179         -> UniqSM [(Id, CoreExpr)]      -- either *one* or *two* pairs;
180                                         -- if one, then no worker (only
181                                         -- the orig "wrapper" lives on);
182                                         -- if two, then a worker and a
183                                         -- wrapper.
184 tryWW is_rec fn_id rhs
185   | isNeverActive inline_prag
186         -- Don't split NOINLINE things, because they will never be inlined
187         -- Furthermore, zap the strictess info in the Id.  Why?  Because
188         -- the NOINLINE says "don't expose any of the inner workings at the call 
189         -- site" and the strictness is certainly an inner working.
190         --
191         -- More concretely, the demand analyser discovers the following strictness
192         -- for unsafePerformIO:  C(U(AV))
193         -- But then consider
194         --      unsafePerformIO (\s -> let r = f x in 
195         --                             case writeIORef v r s of (# s1, _ #) ->
196         --                             (# s1, r #)
197         -- The strictness analyser will find that the binding for r is strict,
198         -- (becuase of uPIO's strictness sig), and so it'll evaluate it before 
199         -- doing the writeIORef.  This actually makes tests/lib/should_run/memo002
200         -- get a deadlock!  
201         --
202         -- Solution: don't expose the strictness of unsafePerformIO.
203   = returnUs [ (zapIdNewStrictness fn_id, rhs) ]
204
205   |  arity == 0
206         -- Don't worker-wrapper thunks
207   || isNonRec is_rec && certainlyWillInline fn_id
208         -- No point in worker/wrappering a function that is going to be
209         -- INLINEd wholesale anyway.  If the strictness analyser is run
210         -- twice, this test also prevents wrappers (which are INLINEd)
211         -- from being re-done.
212         --      
213         -- It's very important to refrain from w/w-ing an INLINE function
214         -- If we do so by mistake we transform
215         --      f = __inline (\x -> E)
216         -- into
217         --      f = __inline (\x -> case x of (a,b) -> fw E)
218         --      fw = \ab -> (__inline (\x -> E)) (a,b)
219         -- and the original __inline now vanishes, so E is no longer
220         -- inside its __inline wrapper.  Death!  Disaster!
221   || not (worthSplitting strict_sig)
222         -- Strictness info suggests not to w/w
223   = returnUs [ (fn_id, rhs) ]
224
225   | otherwise           -- Do w/w split!
226   = WARN( arity /= length wrap_dmds, ppr fn_id <+> (ppr arity $$ ppr strict_sig) )
227         -- The arity should match the signature
228     mkWwBodies fun_ty wrap_dmds res_info one_shots      `thenUs` \ (work_demands, wrap_fn, work_fn) ->
229     getUniqueUs                                         `thenUs` \ work_uniq ->
230     let
231         work_rhs = work_fn rhs
232         work_id  = mkWorkerId work_uniq fn_id (exprType work_rhs) 
233                         `setInlinePragma` inline_prag
234                         `setIdNewStrictness` StrictSig (mkTopDmdType work_demands work_res_info)
235                                 -- Even though we may not be at top level, 
236                                 -- it's ok to give it an empty DmdEnv
237
238         wrap_rhs = wrap_fn work_id
239         wrap_id  = fn_id `setIdWorkerInfo`      HasWorker work_id arity
240                          `setInlinePragma`      AlwaysActive    -- Zap any inline pragma;
241                                                                 -- Put it on the worker instead
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     strict_sig  = idNewStrictness fn_id
253
254     StrictSig (DmdType _ wrap_dmds res_info) = strict_sig
255     work_res_info | isBotRes res_info = BotRes  -- Cpr stuff done by wrapper
256                   | otherwise         = TopRes
257
258     one_shots = get_one_shots rhs
259
260 -- If the original function has one-shot arguments, it is important to
261 -- make the wrapper and worker have corresponding one-shot arguments too.
262 -- Otherwise we spuriously float stuff out of case-expression join points,
263 -- which is very annoying.
264 get_one_shots (Lam b e)
265   | isId b    = isOneShotLambda b : get_one_shots e
266   | otherwise = get_one_shots e
267 get_one_shots (Note _ e) = get_one_shots e
268 get_one_shots other      = noOneShotInfo
269 \end{code}
270
271
272 %************************************************************************
273 %*                                                                      *
274 \subsection{Functions over Demands}
275 %*                                                                      *
276 %************************************************************************
277
278 \begin{code}
279 worthSplitting :: StrictSig -> Bool
280                 -- True <=> the wrapper would not be an identity function
281 worthSplitting (StrictSig (DmdType _ ds res))
282   = any worth_it ds || returnsCPR res
283         -- worthSplitting returns False for an empty list of demands,
284         -- and hence do_strict_ww is False if arity is zero
285
286         -- We used not to split if the result is bottom.
287         -- [Justification:  there's no efficiency to be gained.]
288         -- But it's sometimes bad not to make a wrapper.  Consider
289         --      fw = \x# -> let x = I# x# in case e of
290         --                                      p1 -> error_fn x
291         --                                      p2 -> error_fn x
292         --                                      p3 -> the real stuff
293         -- The re-boxing code won't go away unless error_fn gets a wrapper too.
294         -- [We don't do reboxing now, but in general it's better to pass 
295         --  an unboxed thing to f, and have it reboxed in the error cases....]
296   where
297     worth_it Abs        = True  -- Absent arg
298     worth_it (Seq _ ds) = True  -- Arg to evaluate
299     worth_it other      = False
300 \end{code}
301
302
303
304 %************************************************************************
305 %*                                                                      *
306 \subsection{The worker wrapper core}
307 %*                                                                      *
308 %************************************************************************
309
310 @mkWrapper@ is called when importing a function.  We have the type of 
311 the function and the name of its worker, and we want to make its body (the wrapper).
312
313 \begin{code}
314 mkWrapper :: Type               -- Wrapper type
315           -> StrictSig          -- Wrapper strictness info
316           -> UniqSM (Id -> CoreExpr)    -- Wrapper body, missing worker Id
317
318 mkWrapper fun_ty (StrictSig (DmdType _ demands res_info))
319   = mkWwBodies fun_ty demands res_info noOneShotInfo    `thenUs` \ (_, wrap_fn, _) ->
320     returnUs wrap_fn
321
322 noOneShotInfo = repeat False
323 \end{code}