Make absent-arg wrappers work for unlifted types (fix Trac #4306)
[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, idDemandInfo, setIdDemandInfo,
14                           isOneShotLambda, setOneShotLambda, setIdUnfolding,
15                           setIdInfo
16                         )
17 import IdInfo           ( vanillaIdInfo )
18 import DataCon
19 import Demand           ( Demand(..), DmdResult(..), Demands(..) ) 
20 import MkCore           ( mkRuntimeErrorApp, aBSENT_ERROR_ID )
21 import MkId             ( realWorldPrimId, voidArgId, 
22                           mkUnpackCase, mkProductBox )
23 import TysWiredIn       ( tupleCon )
24 import Type
25 import Coercion         ( mkSymCoercion, splitNewTypeRepCo_maybe )
26 import BasicTypes       ( Boxity(..) )
27 import Var              ( Var )
28 import UniqSupply
29 import Unique
30 import Util             ( zipWithEqual )
31 import Outputable
32 import FastString
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   = do  { let arg_info = demands `zip` (one_shots ++ repeat False)
125         ; (wrap_args, wrap_fn_args, work_fn_args, res_ty) <- mkWWargs emptyTvSubst fun_ty arg_info
126         ; (work_args, wrap_fn_str,  work_fn_str) <- mkWWstr wrap_args
127
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         ; (wrap_fn_cpr, work_fn_cpr,  _cpr_res_ty)
131                <- if any isId work_args then
132                      mkWWcpr res_ty res_info
133                   else
134                      return (id, id, res_ty)
135
136         ; let (work_lam_args, work_call_args) = mkWorkerArgs work_args res_ty
137         ; return ([idDemandInfo v | v <- work_call_args, isId v],
138                   wrap_fn_args . wrap_fn_cpr . wrap_fn_str . applyToVars work_call_args . Var,
139                   mkLams work_lam_args. work_fn_str . work_fn_cpr . work_fn_args) }
140         -- We use an INLINE unconditionally, even if the wrapper turns out to be
141         -- something trivial like
142         --      fw = ...
143         --      f = __inline__ (coerce T fw)
144         -- The point is to propagate the coerce to f's call sites, so even though
145         -- f's RHS is now trivial (size 1) we still want the __inline__ to prevent
146         -- fw from being inlined into f's RHS
147 \end{code}
148
149
150 %************************************************************************
151 %*                                                                      *
152 \subsection{Making wrapper args}
153 %*                                                                      *
154 %************************************************************************
155
156 During worker-wrapper stuff we may end up with an unlifted thing
157 which we want to let-bind without losing laziness.  So we
158 add a void argument.  E.g.
159
160         f = /\a -> \x y z -> E::Int#    -- E does not mention x,y,z
161 ==>
162         fw = /\ a -> \void -> E
163         f  = /\ a -> \x y z -> fw realworld
164
165 We use the state-token type which generates no code.
166
167 \begin{code}
168 mkWorkerArgs :: [Var]
169              -> Type    -- Type of body
170              -> ([Var], -- Lambda bound args
171                  [Var]) -- Args at call site
172 mkWorkerArgs args res_ty
173     | any isId args || not (isUnLiftedType res_ty)
174     = (args, args)
175     | otherwise 
176     = (args ++ [voidArgId], args ++ [realWorldPrimId])
177 \end{code}
178
179
180 %************************************************************************
181 %*                                                                      *
182 \subsection{Coercion stuff}
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 just does eta expansion
213 -- is driven off the function type and arity.
214 -- It chomps bites off foralls, arrows, newtypes
215 -- and keeps repeating that until it's satisfied the supplied arity
216
217 mkWWargs :: TvSubst             -- Freshening substitution to apply to the type
218                                 --   See Note [Freshen type variables]
219          -> Type                -- The type of the function
220          -> [(Demand,Bool)]     -- Demands and one-shot info for value arguments
221          -> UniqSM  ([Var],             -- Wrapper args
222                      CoreExpr -> CoreExpr,      -- Wrapper fn
223                      CoreExpr -> CoreExpr,      -- Worker fn
224                      Type)                      -- Type of wrapper body
225
226 mkWWargs subst fun_ty arg_info
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         --
239         -- Note (Sept 08): This case applies even if demands is empty.
240         --                 I'm not quite sure why; perhaps it makes it
241         --                 easier for CPR
242   = do { (wrap_args, wrap_fn_args, work_fn_args, res_ty)
243             <-  mkWWargs subst rep_ty arg_info
244         ; return (wrap_args,
245                   \e -> Cast (wrap_fn_args e) (mkSymCoercion co),
246                   \e -> work_fn_args (Cast e co),
247                   res_ty) } 
248
249   | null arg_info
250   = return ([], id, id, substTy subst fun_ty)
251
252   | Just (tv, fun_ty') <- splitForAllTy_maybe fun_ty
253   = do  { let (subst', tv') = substTyVarBndr subst tv
254                 -- This substTyVarBndr clones the type variable when necy
255                 -- See Note [Freshen type variables]
256         ; (wrap_args, wrap_fn_args, work_fn_args, res_ty)
257              <- mkWWargs subst' fun_ty' arg_info
258         ; return (tv' : wrap_args,
259                   Lam tv' . wrap_fn_args,
260                   work_fn_args . (`App` Type (mkTyVarTy tv')),
261                   res_ty) }
262
263   | ((dmd,one_shot):arg_info') <- arg_info
264   , Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty
265   = do  { uniq <- getUniqueM
266         ; let arg_ty' = substTy subst arg_ty
267               id = mk_wrap_arg uniq arg_ty' dmd one_shot
268         ; (wrap_args, wrap_fn_args, work_fn_args, res_ty)
269               <- mkWWargs subst fun_ty' arg_info'
270         ; return (id : wrap_args,
271                   Lam id . wrap_fn_args,
272                   work_fn_args . (`App` Var id),
273                   res_ty) }
274
275   | otherwise
276   = WARN( True, ppr fun_ty )                    -- Should not happen: if there is a demand
277     return ([], id, id, substTy subst fun_ty)   -- then there should be a function arrow
278
279 applyToVars :: [Var] -> CoreExpr -> CoreExpr
280 applyToVars vars fn = mkVarApps fn vars
281
282 mk_wrap_arg :: Unique -> Type -> Demand -> Bool -> Id
283 mk_wrap_arg uniq ty dmd one_shot 
284   = set_one_shot one_shot (setIdDemandInfo (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 Note [Freshen type variables]
291 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
292 mkWWargs may be given a type like  (a~b) => <blah>
293 Which really means                 forall (co:a~b). <blah>
294 Because the name of the coercion variable, 'co', isn't mentioned in <blah>,
295 nested coercion foralls may all use the same variable; and sometimes do
296 see Var.mkWildCoVar.
297
298 However, when we do a worker/wrapper split, we must not use shadowed names,
299 else we'll get
300    f = /\ co /\co. fw co co
301 which is obviously wrong.  Actually, the same is true of type variables, which
302 can in principle shadow, within a type (e.g. forall a. a -> forall a. a->a).
303 But type variables *are* mentioned in <blah>, so we must substitute.
304
305 That's why we carry the TvSubst through mkWWargs
306         
307 %************************************************************************
308 %*                                                                      *
309 \subsection{Strictness stuff}
310 %*                                                                      *
311 %************************************************************************
312
313 \begin{code}
314 mkWWstr :: [Var]                                -- Wrapper args; have their demand info on them
315                                                 --  *Includes type variables*
316         -> UniqSM ([Var],                       -- Worker args
317                    CoreExpr -> CoreExpr,        -- Wrapper body, lacking the worker call
318                                                 -- and without its lambdas 
319                                                 -- This fn adds the unboxing
320                                 
321                    CoreExpr -> CoreExpr)        -- Worker body, lacking the original body of the function,
322                                                 -- and lacking its lambdas.
323                                                 -- This fn does the reboxing
324 mkWWstr []
325   = return ([], nop_fn, nop_fn)
326
327 mkWWstr (arg : args) = do
328     (args1, wrap_fn1, work_fn1) <- mkWWstr_one arg
329     (args2, wrap_fn2, work_fn2) <- mkWWstr args
330     return (args1 ++ args2, wrap_fn1 . wrap_fn2, work_fn1 . work_fn2)
331
332 ----------------------
333 -- mkWWstr_one wrap_arg = (work_args, wrap_fn, work_fn)
334 --   *  wrap_fn assumes wrap_arg is in scope,
335 --        brings into scope work_args (via cases)
336 --   * work_fn assumes work_args are in scope, a
337 --        brings into scope wrap_arg (via lets)
338 mkWWstr_one :: Var -> UniqSM ([Var], CoreExpr -> CoreExpr, CoreExpr -> CoreExpr)
339 mkWWstr_one arg
340   | isTyCoVar arg
341   = return ([arg],  nop_fn, nop_fn)
342
343   | otherwise
344   = case idDemandInfo arg of
345
346         -- Absent case.  We don't deal with absence for unlifted types,
347         -- though, because it's not so easy to manufacture a placeholder
348         -- We'll see if this turns out to be a problem
349       Abs -> return ([], nop_fn, mk_absent_let arg) 
350
351         -- Unpack case
352       Eval (Prod cs)
353         | Just (_arg_tycon, _tycon_arg_tys, data_con, inst_con_arg_tys) 
354                 <- deepSplitProductType_maybe (idType arg)
355         -> do uniqs <- getUniquesM
356               let
357                 unpk_args      = zipWith mk_ww_local uniqs inst_con_arg_tys
358                 unpk_args_w_ds = zipWithEqual "mkWWstr" set_worker_arg_info unpk_args cs
359                 unbox_fn       = mkUnpackCase (sanitiseCaseBndr arg) (Var arg) unpk_args data_con
360                 rebox_fn       = Let (NonRec arg con_app) 
361                 con_app        = mkProductBox unpk_args (idType arg)
362               (worker_args, wrap_fn, work_fn) <- mkWWstr unpk_args_w_ds
363               return (worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn) 
364                            -- Don't pass the arg, rebox instead
365
366         -- `seq` demand; evaluate in wrapper in the hope
367         -- of dropping seqs in the worker
368       Eval (Poly Abs)
369         -> let
370                 arg_w_unf = arg `setIdUnfolding` evaldUnfolding
371                 -- Tell the worker arg that it's sure to be evaluated
372                 -- so that internal seqs can be dropped
373            in
374            return ([arg_w_unf], mk_seq_case arg, nop_fn)
375                 -- Pass the arg, anyway, even if it is in theory discarded
376                 -- Consider
377                 --      f x y = x `seq` y
378                 -- x gets a (Eval (Poly Abs)) demand, but if we fail to pass it to the worker
379                 -- we ABSOLUTELY MUST record that x is evaluated in the wrapper.
380                 -- Something like:
381                 --      f x y = x `seq` fw y
382                 --      fw y = let x{Evald} = error "oops" in (x `seq` y)
383                 -- If we don't pin on the "Evald" flag, the seq doesn't disappear, and
384                 -- we end up evaluating the absent thunk.
385                 -- But the Evald flag is pretty weird, and I worry that it might disappear
386                 -- during simplification, so for now I've just nuked this whole case
387                         
388         -- Other cases
389       _other_demand -> return ([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 (setIdDemandInfo worker_arg demand)
396
397     set_one_shot | isOneShotLambda arg = setOneShotLambda
398                  | otherwise           = \x -> x
399
400 ----------------------
401 nop_fn :: CoreExpr -> CoreExpr
402 nop_fn body = body
403 \end{code}
404
405
406 %************************************************************************
407 %*                                                                      *
408 \subsection{CPR stuff}
409 %*                                                                      *
410 %************************************************************************
411
412
413 @mkWWcpr@ takes the worker/wrapper pair produced from the strictness
414 info and adds in the CPR transformation.  The worker returns an
415 unboxed tuple containing non-CPR components.  The wrapper takes this
416 tuple and re-produces the correct structured output.
417
418 The non-CPR results appear ordered in the unboxed tuple as if by a
419 left-to-right traversal of the result structure.
420
421
422 \begin{code}
423 mkWWcpr :: Type                              -- function body type
424         -> DmdResult                         -- CPR analysis results
425         -> UniqSM (CoreExpr -> CoreExpr,             -- New wrapper 
426                    CoreExpr -> CoreExpr,             -- New worker
427                    Type)                        -- Type of worker's body 
428
429 mkWWcpr body_ty RetCPR
430     | not (isClosedAlgType body_ty)
431     = WARN( True, 
432             text "mkWWcpr: non-algebraic or open body type" <+> ppr body_ty )
433       return (id, id, body_ty)
434
435     | n_con_args == 1 && isUnLiftedType con_arg_ty1 = do
436         -- Special case when there is a single result of unlifted type
437         --
438         -- Wrapper:     case (..call worker..) of x -> C x
439         -- Worker:      case (   ..body..    ) of C x -> x
440       (work_uniq : arg_uniq : _) <- getUniquesM
441       let
442         work_wild = mk_ww_local work_uniq body_ty
443         arg       = mk_ww_local arg_uniq  con_arg_ty1
444         con_app   = mkProductBox [arg] body_ty
445
446       return (\ wkr_call -> Case wkr_call (arg) (exprType con_app) [(DEFAULT, [], con_app)],
447                 \ body     -> workerCase (work_wild) body [arg] data_con (Var arg),
448                 con_arg_ty1)
449
450     | otherwise = do    -- The general case
451         -- Wrapper: case (..call worker..) of (# a, b #) -> C a b
452         -- Worker:  case (   ...body...  ) of C a b -> (# a, b #)     
453       uniqs <- getUniquesM
454       let
455         (wrap_wild : work_wild : args) = zipWith mk_ww_local uniqs (ubx_tup_ty : body_ty : con_arg_tys)
456         arg_vars                       = map Var args
457         ubx_tup_con                    = tupleCon Unboxed n_con_args
458         ubx_tup_ty                     = exprType ubx_tup_app
459         ubx_tup_app                    = mkConApp ubx_tup_con (map Type con_arg_tys   ++ arg_vars)
460         con_app                        = mkProductBox args body_ty
461
462       return (\ wkr_call -> Case wkr_call (wrap_wild) (exprType con_app)  [(DataAlt ubx_tup_con, args, con_app)],
463                 \ body     -> workerCase (work_wild) body args data_con ubx_tup_app,
464                 ubx_tup_ty)
465     where
466       (_arg_tycon, _tycon_arg_tys, data_con, con_arg_tys) = deepSplitProductType "mkWWcpr" body_ty
467       n_con_args  = length con_arg_tys
468       con_arg_ty1 = head con_arg_tys
469
470 mkWWcpr body_ty _other          -- No CPR info
471     = return (id, id, body_ty)
472
473 -- If the original function looked like
474 --      f = \ x -> _scc_ "foo" E
475 --
476 -- then we want the CPR'd worker to look like
477 --      \ x -> _scc_ "foo" (case E of I# x -> x)
478 -- and definitely not
479 --      \ x -> case (_scc_ "foo" E) of I# x -> x)
480 --
481 -- This transform doesn't move work or allocation
482 -- from one cost centre to another
483 workerCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
484 workerCase bndr (Note (SCC cc) e) args con body = Note (SCC cc) (mkUnpackCase bndr e args con body)
485 workerCase bndr e args con body = mkUnpackCase bndr e args con body
486 \end{code}
487
488
489 %************************************************************************
490 %*                                                                      *
491 \subsection{Utilities}
492 %*                                                                      *
493 %************************************************************************
494
495
496 Note [Absent error Id]
497 ~~~~~~~~~~~~~~~~~~~~~~
498 We make a new binding for Ids that are marked absent, thus
499    let x = absentError "x :: Int"
500 The idea is that this binding will never be used; but if it 
501 buggily is used we'll get a runtime error message.
502
503 We do this even for *unlifted* types (e.g. Int#).  We define
504 absentError to *not* be a bottoming Id, and we treat it as
505 "ok for speculation" (see CoreUtils.okForSpeculation). That
506 means that the let won't get turned into a case, and will
507 be discarded if (as we fully expect) x turns out to be dead.
508 Coping with absence for unlifted types is important; see, for
509 example, Trac #4306.
510
511 \begin{code}
512 mk_absent_let :: Id -> CoreExpr -> CoreExpr
513 mk_absent_let arg body
514   = Let (NonRec arg abs_rhs) body
515   where
516     arg_ty  = idType arg
517     abs_rhs = mkRuntimeErrorApp aBSENT_ERROR_ID arg_ty msg
518     msg     = showSDocDebug (ppr arg <+> ppr (idType arg))
519
520 mk_seq_case :: Id -> CoreExpr -> CoreExpr
521 mk_seq_case arg body = Case (Var arg) (sanitiseCaseBndr arg) (exprType body) [(DEFAULT, [], body)]
522
523 sanitiseCaseBndr :: Id -> Id
524 -- The argument we are scrutinising has the right type to be
525 -- a case binder, so it's convenient to re-use it for that purpose.
526 -- But we *must* throw away all its IdInfo.  In particular, the argument
527 -- will have demand info on it, and that demand info may be incorrect for
528 -- the case binder.  e.g.       case ww_arg of ww_arg { I# x -> ... }
529 -- Quite likely ww_arg isn't used in '...'.  The case may get discarded
530 -- if the case binder says "I'm demanded".  This happened in a situation 
531 -- like         (x+y) `seq` ....
532 sanitiseCaseBndr id = id `setIdInfo` vanillaIdInfo
533
534 mk_ww_local :: Unique -> Type -> Id
535 mk_ww_local uniq ty = mkSysLocal (fsLit "ww") uniq ty
536 \end{code}