[project @ 2001-07-31 10:06:25 by sewardj]
[ghc-hetmet.git] / ghc / compiler / stranal / WwLib.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[WwLib]{A library for the ``worker/wrapper'' back-end to the strictness analyser}
5
6 \begin{code}
7 module WwLib ( mkWwBodies ) where
8
9 #include "HsVersions.h"
10
11 import CoreSyn
12 import CoreUtils        ( exprType )
13 import Id               ( Id, idType, mkSysLocal, idNewDemandInfo, setIdNewDemandInfo,
14                           isOneShotLambda, setOneShotLambda,
15                           setIdInfo
16                         )
17 import IdInfo           ( vanillaIdInfo )
18 import DataCon          ( splitProductType_maybe, splitProductType )
19 import NewDemand        ( Demand(..), Keepity(..), DmdResult(..) ) 
20 import PrelInfo         ( realWorldPrimId, aBSENT_ERROR_ID, eRROR_CSTRING_ID )
21 import TysPrim          ( realWorldStatePrimTy )
22 import TysWiredIn       ( tupleCon )
23 import Type             ( Type, isUnLiftedType, mkFunTys,
24                           splitForAllTys, splitFunTys, splitNewType_maybe, isAlgType
25                         )
26 import Literal          ( Literal(MachStr) )
27 import BasicTypes       ( Arity, Boxity(..) )
28 import Var              ( Var, isId )
29 import UniqSupply       ( returnUs, thenUs, getUniqueUs, getUniquesUs, UniqSM )
30 import Util             ( zipWithEqual )
31 import Outputable
32 import List             ( zipWith4 )
33 \end{code}
34
35
36 %************************************************************************
37 %*                                                                      *
38 \subsection[mkWrapperAndWorker]{@mkWrapperAndWorker@}
39 %*                                                                      *
40 %************************************************************************
41
42 Here's an example.  The original function is:
43
44 \begin{verbatim}
45 g :: forall a . Int -> [a] -> a
46
47 g = /\ a -> \ x ys ->
48         case x of
49           0 -> head ys
50           _ -> head (tail ys)
51 \end{verbatim}
52
53 From this, we want to produce:
54 \begin{verbatim}
55 -- wrapper (an unfolding)
56 g :: forall a . Int -> [a] -> a
57
58 g = /\ a -> \ x ys ->
59         case x of
60           I# x# -> $wg a x# ys
61             -- call the worker; don't forget the type args!
62
63 -- worker
64 $wg :: forall a . Int# -> [a] -> a
65
66 $wg = /\ a -> \ x# ys ->
67         let
68             x = I# x#
69         in
70             case x of               -- note: body of g moved intact
71               0 -> head ys
72               _ -> head (tail ys)
73 \end{verbatim}
74
75 Something we have to be careful about:  Here's an example:
76
77 \begin{verbatim}
78 -- "f" strictness: U(P)U(P)
79 f (I# a) (I# b) = a +# b
80
81 g = f   -- "g" strictness same as "f"
82 \end{verbatim}
83
84 \tr{f} will get a worker all nice and friendly-like; that's good.
85 {\em But we don't want a worker for \tr{g}}, even though it has the
86 same strictness as \tr{f}.  Doing so could break laziness, at best.
87
88 Consequently, we insist that the number of strictness-info items is
89 exactly the same as the number of lambda-bound arguments.  (This is
90 probably slightly paranoid, but OK in practice.)  If it isn't the
91 same, we ``revise'' the strictness info, so that we won't propagate
92 the unusable strictness-info into the interfaces.
93
94
95 %************************************************************************
96 %*                                                                      *
97 \subsection{The worker wrapper core}
98 %*                                                                      *
99 %************************************************************************
100
101 @mkWwBodies@ is called when doing the worker/wrapper split inside a module.
102
103 \begin{code}
104 mkWwBodies :: Type                              -- Type of original function
105            -> [Demand]                          -- Strictness of original function
106            -> DmdResult                         -- Info about function result
107            -> [Bool]                            -- One-shot-ness of the function
108            -> UniqSM ([Demand],                 -- Demands for worker (value) args
109                       Id -> CoreExpr,           -- Wrapper body, lacking only the worker Id
110                       CoreExpr -> CoreExpr)     -- Worker body, lacking the original function rhs
111
112 -- wrap_fn_args E       = \x y -> E
113 -- work_fn_args E       = E x y
114
115 -- wrap_fn_str E        = case x of { (a,b) -> 
116 --                        case a of { (a1,a2) ->
117 --                        E a1 a2 b y }}
118 -- work_fn_str E        = \a2 a2 b y ->
119 --                        let a = (a1,a2) in
120 --                        let x = (a,b) in
121 --                        E
122
123 mkWwBodies fun_ty demands res_info one_shots
124   = mkWWargs fun_ty demands one_shots'  `thenUs` \ (wrap_args,   wrap_fn_args, work_fn_args, res_ty) ->
125     mkWWcpr res_ty res_info             `thenUs` \ (wrap_fn_cpr, work_fn_cpr,  cpr_res_ty) ->
126     mkWWstr cpr_res_ty wrap_args        `thenUs` \ (work_dmds,   wrap_fn_str,  work_fn_str) ->
127
128     returnUs (work_dmds,
129               Note InlineMe . wrap_fn_args . wrap_fn_cpr . wrap_fn_str . Var,
130               work_fn_str . work_fn_cpr . work_fn_args)
131         -- We use an INLINE unconditionally, even if the wrapper turns out to be
132         -- something trivial like
133         --      fw = ...
134         --      f = __inline__ (coerce T fw)
135         -- The point is to propagate the coerce to f's call sites, so even though
136         -- f's RHS is now trivial (size 1) we still want the __inline__ to prevent
137         -- fw from being inlined into f's RHS
138   where
139     one_shots' = one_shots ++ repeat False
140 \end{code}
141
142
143 %************************************************************************
144 %*                                                                      *
145 \subsection{Coercion stuff}
146 %*                                                                      *
147 %************************************************************************
148
149
150 We really want to "look through" coerces.
151 Reason: I've seen this situation:
152
153         let f = coerce T (\s -> E)
154         in \x -> case x of
155                     p -> coerce T' f
156                     q -> \s -> E2
157                     r -> coerce T' f
158
159 If only we w/w'd f, we'd get
160         let f = coerce T (\s -> fw s)
161             fw = \s -> E
162         in ...
163
164 Now we'll inline f to get
165
166         let fw = \s -> E
167         in \x -> case x of
168                     p -> fw
169                     q -> \s -> E2
170                     r -> fw
171
172 Now we'll see that fw has arity 1, and will arity expand
173 the \x to get what we want.
174
175 \begin{code}
176 -- mkWWargs is driven off the function type and arity.
177 -- It chomps bites off foralls, arrows, newtypes
178 -- and keeps repeating that until it's satisfied the supplied arity
179
180 mkWWargs :: Type
181          -> [Demand]
182          -> [Bool]                      -- True for a one-shot arg; ** may be infinite **
183          -> UniqSM  ([Var],             -- Wrapper args
184                      CoreExpr -> CoreExpr,      -- Wrapper fn
185                      CoreExpr -> CoreExpr,      -- Worker fn
186                      Type)                      -- Type of wrapper body
187
188 mkWWargs fun_ty demands one_shots
189   | Just rep_ty <- splitNewType_maybe fun_ty
190         -- The newtype case is for when the function has
191         -- a recursive newtype after the arrow (rare)
192         -- We check for arity >= 0 to avoid looping in the case
193         -- of a function whose type is, in effect, infinite
194         -- [Arity is driven by looking at the term, not just the type.]
195         --
196         -- It's also important when we have a function returning (say) a pair
197         -- wrapped in a recursive newtype, at least if CPR analysis can look 
198         -- through such newtypes, which it probably can since they are 
199         -- simply coerces.
200   = mkWWargs rep_ty demands one_shots   `thenUs` \ (wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
201     returnUs (wrap_args,
202               Note (Coerce fun_ty rep_ty) . wrap_fn_args,
203               work_fn_args . Note (Coerce rep_ty fun_ty),
204               res_ty)
205
206   | not (null demands)
207   = getUniquesUs                `thenUs` \ wrap_uniqs ->
208     let
209       (tyvars, tau)             = splitForAllTys fun_ty
210       (arg_tys, body_ty)        = splitFunTys tau
211
212       n_demands = length demands
213       n_arg_tys = length arg_tys
214       n_args    = n_demands `min` n_arg_tys
215
216       new_fun_ty    = mkFunTys (drop n_demands arg_tys) body_ty
217       new_demands   = drop n_arg_tys demands
218       new_one_shots = drop n_args one_shots
219
220       val_args  = zipWith4 mk_wrap_arg wrap_uniqs arg_tys demands one_shots
221       wrap_args = tyvars ++ val_args
222     in
223 {-     ASSERT( not (null tyvars) || not (null arg_tys) ) -}
224     if (null tyvars) && (null arg_tys) then
225         pprTrace "mkWWargs" (ppr fun_ty $$ ppr demands) 
226                 returnUs ([], id, id, fun_ty)
227         else
228
229     mkWWargs new_fun_ty
230              new_demands
231              new_one_shots      `thenUs` \ (more_wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
232
233     returnUs (wrap_args ++ more_wrap_args,
234               mkLams wrap_args . wrap_fn_args,
235               work_fn_args . applyToVars wrap_args,
236               res_ty)
237
238   | otherwise
239   = returnUs ([], id, id, fun_ty)
240
241
242 applyToVars :: [Var] -> CoreExpr -> CoreExpr
243 applyToVars vars fn = mkVarApps fn vars
244
245 mk_wrap_arg uniq ty dmd one_shot 
246   = set_one_shot one_shot (setIdNewDemandInfo (mkSysLocal SLIT("w") uniq ty) dmd)
247   where
248     set_one_shot True  id = setOneShotLambda id
249     set_one_shot False id = id
250 \end{code}
251
252
253 %************************************************************************
254 %*                                                                      *
255 \subsection{Strictness stuff}
256 %*                                                                      *
257 %************************************************************************
258
259 \begin{code}
260 mkWWstr :: Type                                 -- Result type
261         -> [Var]                                -- Wrapper args; have their demand info on them
262                                                 -- *Includes type variables*
263         -> UniqSM ([Demand],                    -- Demand on worker (value) args
264                    CoreExpr -> CoreExpr,        -- Wrapper body, lacking the worker call
265                                                 -- and without its lambdas 
266                                                 -- This fn adds the unboxing, and makes the
267                                                 -- call passing the unboxed things
268                                 
269                    CoreExpr -> CoreExpr)        -- Worker body, lacking the original body of the function,
270                                                 -- but *with* lambdas
271
272 mkWWstr res_ty wrap_args
273   = mk_ww_str wrap_args         `thenUs` \ (work_args, take_apart, put_together) ->
274     let
275         work_dmds = [idNewDemandInfo v | v <- work_args, isId v]
276         apply_to args fn = mkVarApps fn args
277     in
278     if not (null work_dmds && isUnLiftedType res_ty) then
279         returnUs ( work_dmds, 
280                    take_apart . applyToVars work_args,
281                    mkLams work_args . put_together)
282     else
283         -- Horrid special case.  If the worker would have no arguments, and the
284         -- function returns a primitive type value, that would make the worker into
285         -- an unboxed value.  We box it by passing a dummy void argument, thus:
286         --
287         --      f = /\abc. \xyz. fw abc void
288         --      fw = /\abc. \v. body
289         --
290         -- We use the state-token type which generates no code
291     getUniqueUs                 `thenUs` \ void_arg_uniq ->
292     let
293         void_arg = mk_ww_local void_arg_uniq realWorldStatePrimTy
294     in
295     returnUs ([Lazy],           
296               take_apart . applyToVars [realWorldPrimId] . apply_to work_args,
297               mkLams work_args . Lam void_arg . put_together)
298
299         -- Empty case
300 mk_ww_str []
301   = returnUs ([],
302               \ wrapper_body -> wrapper_body,
303               \ worker_body  -> worker_body)
304
305
306 mk_ww_str (arg : ds)
307   | isTyVar arg
308   = mk_ww_str ds                `thenUs` \ (worker_args, wrap_fn, work_fn) ->
309     returnUs (arg : worker_args, wrap_fn, work_fn)
310
311   | otherwise
312   = case idNewDemandInfo arg of
313
314         -- Absent case.  We don't deal with absence for unlifted types,
315         -- though, because it's not so easy to manufacture a placeholder
316         -- We'll see if this turns out to be a problem
317       Abs | not (isUnLiftedType (idType arg)) ->
318         mk_ww_str ds            `thenUs` \ (worker_args, wrap_fn, work_fn) ->
319         returnUs (worker_args, wrap_fn, mk_absent_let arg . work_fn)
320
321         -- Seq and keep
322       Seq Keep _ [] ->  mk_ww_str ds            `thenUs` \ (worker_args, wrap_fn, work_fn) ->
323                         returnUs (arg : worker_args, mk_seq_case arg . wrap_fn, work_fn)
324                            -- Pass the arg, no need to rebox
325
326         -- Seq and discard
327       Seq Drop _ [] ->  mk_ww_str ds            `thenUs` \ (worker_args, wrap_fn, work_fn) ->
328                         returnUs (worker_args,  mk_seq_case arg . wrap_fn, mk_absent_let arg . work_fn)
329                            -- Don't pass the arg, build absent arg 
330
331         -- Unpack case
332       Seq keep _ cs 
333         | Just (arg_tycon, tycon_arg_tys, data_con, inst_con_arg_tys) 
334                 <- splitProductType_maybe (idType arg)
335         -> getUniquesUs                 `thenUs` \ uniqs ->
336            let
337              unpk_args      = zipWith mk_ww_local uniqs inst_con_arg_tys
338              unpk_args_w_ds = zipWithEqual "mk_ww_str" set_worker_arg_info unpk_args cs
339              unbox_fn       = mk_unpk_case arg unpk_args data_con arg_tycon
340              rebox_fn       = mk_pk_let arg data_con tycon_arg_tys unpk_args
341            in
342            mk_ww_str (unpk_args_w_ds ++ ds)             `thenUs` \ (worker_args, wrap_fn, work_fn) ->
343            case keep of
344              Keep -> returnUs (arg : worker_args, unbox_fn . wrap_fn, work_fn)
345                            -- Pass the arg, no need to rebox
346              Drop -> returnUs (worker_args,       unbox_fn . wrap_fn, work_fn . rebox_fn)
347                            -- Don't pass the arg, rebox instead
348
349         | otherwise -> 
350            WARN( True, ppr arg )
351            mk_ww_str ds         `thenUs` \ (worker_args, wrap_fn, work_fn) ->
352            returnUs (arg : worker_args, wrap_fn, work_fn)
353
354         -- Other cases
355       other_demand ->
356         mk_ww_str ds            `thenUs` \ (worker_args, wrap_fn, work_fn) ->
357         returnUs (arg : worker_args, wrap_fn, work_fn)
358   where
359         -- If the wrapper argument is a one-shot lambda, then
360         -- so should (all) the corresponding worker arguments be
361         -- This bites when we do w/w on a case join point
362     set_worker_arg_info worker_arg demand = set_one_shot (setIdNewDemandInfo worker_arg demand)
363
364     set_one_shot | isOneShotLambda arg = setOneShotLambda
365                  | otherwise           = \x -> x
366 \end{code}
367
368
369 %************************************************************************
370 %*                                                                      *
371 \subsection{CPR stuff}
372 %*                                                                      *
373 %************************************************************************
374
375
376 @mkWWcpr@ takes the worker/wrapper pair produced from the strictness
377 info and adds in the CPR transformation.  The worker returns an
378 unboxed tuple containing non-CPR components.  The wrapper takes this
379 tuple and re-produces the correct structured output.
380
381 The non-CPR results appear ordered in the unboxed tuple as if by a
382 left-to-right traversal of the result structure.
383
384
385 \begin{code}
386 mkWWcpr :: Type                              -- function body type
387         -> DmdResult                         -- CPR analysis results
388         -> UniqSM (CoreExpr -> CoreExpr,             -- New wrapper 
389                    CoreExpr -> CoreExpr,             -- New worker
390                    Type)                        -- Type of worker's body 
391
392 mkWWcpr body_ty RetCPR
393     | not (isAlgType body_ty)
394     = WARN( True, text "mkWWcpr: non-algebraic body type" <+> ppr body_ty )
395       returnUs (id, id, body_ty)
396
397     | n_con_args == 1 && isUnLiftedType con_arg_ty1
398         -- Special case when there is a single result of unlifted type
399     = getUniquesUs                      `thenUs` \ (work_uniq : arg_uniq : _) ->
400       let
401         work_wild = mk_ww_local work_uniq body_ty
402         arg       = mk_ww_local arg_uniq  con_arg_ty1
403       in
404       returnUs (\ wkr_call -> Case wkr_call arg [(DEFAULT, [], mkConApp data_con (map Type tycon_arg_tys ++ [Var arg]))],
405                 \ body     -> workerCase body work_wild [(DataAlt data_con, [arg], Var arg)],
406                 con_arg_ty1)
407
408     | otherwise         -- The general case
409     = getUniquesUs              `thenUs` \ uniqs ->
410       let
411         (wrap_wild : work_wild : args) = zipWith mk_ww_local uniqs (ubx_tup_ty : body_ty : con_arg_tys)
412         arg_vars                       = map Var args
413         ubx_tup_con                    = tupleCon Unboxed n_con_args
414         ubx_tup_ty                     = exprType ubx_tup_app
415         ubx_tup_app                    = mkConApp ubx_tup_con (map Type con_arg_tys   ++ arg_vars)
416         con_app                        = mkConApp data_con    (map Type tycon_arg_tys ++ arg_vars)
417       in
418       returnUs (\ wkr_call -> Case wkr_call wrap_wild [(DataAlt ubx_tup_con, args, con_app)],
419                 \ body     -> workerCase body work_wild [(DataAlt data_con,    args, ubx_tup_app)],
420                 ubx_tup_ty)
421     where
422       (_, tycon_arg_tys, data_con, con_arg_tys) = splitProductType "mkWWcpr" body_ty
423       n_con_args  = length con_arg_tys
424       con_arg_ty1 = head con_arg_tys
425
426 mkWWcpr body_ty other           -- No CPR info
427     = returnUs (id, id, body_ty)
428
429 -- If the original function looked like
430 --      f = \ x -> _scc_ "foo" E
431 --
432 -- then we want the CPR'd worker to look like
433 --      \ x -> _scc_ "foo" (case E of I# x -> x)
434 -- and definitely not
435 --      \ x -> case (_scc_ "foo" E) of I# x -> x)
436 --
437 -- This transform doesn't move work or allocation
438 -- from one cost centre to another
439
440 workerCase (Note (SCC cc) e) arg alts = Note (SCC cc) (Case e arg alts)
441 workerCase e                 arg alts = Case e arg alts
442 \end{code}
443
444
445 %************************************************************************
446 %*                                                                      *
447 \subsection{Utilities}
448 %*                                                                      *
449 %************************************************************************
450
451
452 \begin{code}
453 mk_absent_let arg body
454   | not (isUnLiftedType arg_ty)
455   = Let (NonRec arg abs_rhs) body
456   | otherwise
457   = panic "WwLib: haven't done mk_absent_let for primitives yet"
458   where
459     arg_ty = idType arg
460 --    abs_rhs = mkTyApps (Var aBSENT_ERROR_ID) [arg_ty]
461     abs_rhs = mkApps (Var eRROR_CSTRING_ID) [Type arg_ty, Lit (MachStr (_PK_ msg))] 
462     msg     = "Oops!  Entered absent arg " ++ showSDocDebug (ppr arg <+> ppr (idType arg))
463
464 mk_unpk_case arg unpk_args boxing_con boxing_tycon body
465         -- A data type
466   = Case (Var arg) 
467          (sanitiseCaseBndr arg)
468          [(DataAlt boxing_con, unpk_args, body)]
469
470 mk_seq_case arg body = Case (Var arg) (sanitiseCaseBndr arg) [(DEFAULT, [], body)]
471
472 sanitiseCaseBndr :: Id -> Id
473 -- The argument we are scrutinising has the right type to be
474 -- a case binder, so it's convenient to re-use it for that purpose.
475 -- But we *must* throw away all its IdInfo.  In particular, the argument
476 -- will have demand info on it, and that demand info may be incorrect for
477 -- the case binder.  e.g.       case ww_arg of ww_arg { I# x -> ... }
478 -- Quite likely ww_arg isn't used in '...'.  The case may get discarded
479 -- if the case binder says "I'm demanded".  This happened in a situation 
480 -- like         (x+y) `seq` ....
481 sanitiseCaseBndr id = id `setIdInfo` vanillaIdInfo
482
483 mk_pk_let arg boxing_con con_tys unpk_args body
484   = Let (NonRec arg (mkConApp boxing_con con_args)) body
485   where
486     con_args = map Type con_tys ++ map Var unpk_args
487
488 mk_ww_local uniq ty = mkSysLocal SLIT("ww") uniq ty
489 \end{code}