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