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