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