Completely new treatment of INLINE pragmas (big patch)
[ghc-hetmet.git] / compiler / stranal / WorkWrap.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[WorkWrap]{Worker/wrapper-generating back-end of strictness analyser}
5
6 \begin{code}
7 {-# OPTIONS -w #-}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
12 -- for details
13
14 module WorkWrap ( wwTopBinds, mkWrapper ) where
15
16 #include "HsVersions.h"
17
18 import CoreSyn
19 import CoreUnfold       ( certainlyWillInline, mkWwInlineRule )
20 import CoreLint         ( showPass, endPass )
21 import CoreUtils        ( exprType, exprIsHNF, exprArity )
22 import Id               ( Id, idType, isOneShotLambda, 
23                           setIdNewStrictness, mkWorkerId,
24                           setInlinePragma, setIdUnfolding, setIdArity, idInfo )
25 import MkId             ( lazyIdKey, lazyIdUnfolding )
26 import Type             ( Type )
27 import IdInfo           ( arityInfo, newDemandInfo, newStrictnessInfo, 
28                           unfoldingInfo, inlinePragInfo )
29 import NewDemand        ( Demand(..), StrictSig(..), DmdType(..), DmdResult(..), 
30                           Demands(..), mkTopDmdType, isBotRes, returnsCPR, topSig, isAbsent
31                         )
32 import UniqSupply
33 import Unique           ( hasKey )
34 import BasicTypes       ( RecFlag(..), isNonRec, isNeverActive )
35 import VarEnv           ( isEmptyVarEnv )
36 import Maybes           ( orElse )
37 import WwLib
38 import Util             ( lengthIs, notNull )
39 import Outputable
40 import MonadUtils
41 \end{code}
42
43 We take Core bindings whose binders have:
44
45 \begin{enumerate}
46
47 \item Strictness attached (by the front-end of the strictness
48 analyser), and / or
49
50 \item Constructed Product Result information attached by the CPR
51 analysis pass.
52
53 \end{enumerate}
54
55 and we return some ``plain'' bindings which have been
56 worker/wrapper-ified, meaning: 
57
58 \begin{enumerate} 
59
60 \item Functions have been split into workers and wrappers where
61 appropriate.  If a function has both strictness and CPR properties
62 then only one worker/wrapper doing both transformations is produced;
63
64 \item Binders' @IdInfos@ have been updated to reflect the existence of
65 these workers/wrappers (this is where we get STRICTNESS and CPR pragma
66 info for exported values).
67 \end{enumerate}
68
69 \begin{code}
70 wwTopBinds :: UniqSupply -> [CoreBind] -> [CoreBind]
71
72 wwTopBinds us top_binds
73   = initUs_ us $ do
74     top_binds' <- mapM wwBind top_binds
75     return (concat top_binds')
76 \end{code}
77
78 %************************************************************************
79 %*                                                                      *
80 \subsection[wwBind-wwExpr]{@wwBind@ and @wwExpr@}
81 %*                                                                      *
82 %************************************************************************
83
84 @wwBind@ works on a binding, trying each \tr{(binder, expr)} pair in
85 turn.  Non-recursive case first, then recursive...
86
87 \begin{code}
88 wwBind  :: CoreBind
89         -> UniqSM [CoreBind]    -- returns a WwBinding intermediate form;
90                                 -- the caller will convert to Expr/Binding,
91                                 -- as appropriate.
92
93 wwBind (NonRec binder rhs) = do
94     new_rhs <- wwExpr rhs
95     new_pairs <- tryWW NonRecursive binder new_rhs
96     return [NonRec b e | (b,e) <- new_pairs]
97       -- Generated bindings must be non-recursive
98       -- because the original binding was.
99
100 wwBind (Rec pairs)
101   = return . Rec <$> concatMapM do_one pairs
102   where
103     do_one (binder, rhs) = do new_rhs <- wwExpr rhs
104                               tryWW Recursive binder new_rhs
105 \end{code}
106
107 @wwExpr@ basically just walks the tree, looking for appropriate
108 annotations that can be used. Remember it is @wwBind@ that does the
109 matching by looking for strict arguments of the correct type.
110 @wwExpr@ is a version that just returns the ``Plain'' Tree.
111
112 \begin{code}
113 wwExpr :: CoreExpr -> UniqSM CoreExpr
114
115 wwExpr e@(Type _) = return e
116 wwExpr e@(Lit _)  = return e
117 wwExpr e@(Var v)
118   | v `hasKey` lazyIdKey = return lazyIdUnfolding
119   | otherwise            = return e
120         -- HACK alert: Inline 'lazy' after strictness analysis
121
122 wwExpr (Lam binder expr)
123   = Lam binder <$> wwExpr expr
124
125 wwExpr (App f a)
126   = App <$> wwExpr f <*> wwExpr a
127
128 wwExpr (Note note expr)
129   = Note note <$> wwExpr expr
130
131 wwExpr (Cast expr co) = do
132     new_expr <- wwExpr expr
133     return (Cast new_expr co)
134
135 wwExpr (Let bind expr)
136   = mkLets <$> wwBind bind <*> wwExpr expr
137
138 wwExpr (Case expr binder ty alts) = do
139     new_expr <- wwExpr expr
140     new_alts <- mapM ww_alt alts
141     return (Case new_expr binder ty new_alts)
142   where
143     ww_alt (con, binders, rhs) = do
144         new_rhs <- wwExpr rhs
145         return (con, binders, new_rhs)
146 \end{code}
147
148 %************************************************************************
149 %*                                                                      *
150 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
151 %*                                                                      *
152 %************************************************************************
153
154 @tryWW@ just accumulates arguments, converts strictness info from the
155 front-end into the proper form, then calls @mkWwBodies@ to do
156 the business.
157
158 We have to BE CAREFUL that we don't worker-wrapperize an Id that has
159 already been w-w'd!  (You can end up with several liked-named Ids
160 bouncing around at the same time---absolute mischief.)  So the
161 criterion we use is: if an Id already has an unfolding (for whatever
162 reason), then we don't w-w it.
163
164 The only reason this is monadised is for the unique supply.
165
166 Note [Don't w/w inline things]
167 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
168 It's very important to refrain from w/w-ing an INLINE function
169 because the wrapepr will then overwrite the InlineRule unfolding.
170
171 It was wrong with the old InlineMe Note too: if we do so by mistake 
172 we transform
173         f = __inline (\x -> E)
174 into
175         f = __inline (\x -> case x of (a,b) -> fw E)
176         fw = \ab -> (__inline (\x -> E)) (a,b)
177 and the original __inline now vanishes, so E is no longer
178 inside its __inline wrapper.  Death!  Disaster!
179
180 Furthermore, if the programmer has marked something as INLINE, 
181 we may lose by w/w'ing it.
182
183 If the strictness analyser is run twice, this test also prevents
184 wrappers (which are INLINEd) from being re-done.
185
186 Notice that we refrain from w/w'ing an INLINE function even if it is
187 in a recursive group.  It might not be the loop breaker.  (We could
188 test for loop-breaker-hood, but I'm not sure that ever matters.)
189
190 \begin{code}
191 tryWW   :: RecFlag
192         -> Id                           -- The fn binder
193         -> CoreExpr                     -- The bound rhs; its innards
194                                         --   are already ww'd
195         -> UniqSM [(Id, CoreExpr)]      -- either *one* or *two* pairs;
196                                         -- if one, then no worker (only
197                                         -- the orig "wrapper" lives on);
198                                         -- if two, then a worker and a
199                                         -- wrapper.
200 tryWW is_rec fn_id rhs
201   |  -- isNonRec is_rec &&      -- Now omitted: see Note [Don't w/w inline things]
202      certainlyWillInline unfolding
203
204   || isNeverActive inline_prag
205         -- No point in worker/wrappering if the thing is never inlined!
206         -- Because the no-inline prag will prevent the wrapper ever
207         -- being inlined at a call site. 
208   = return [ (new_fn_id, rhs) ]
209
210   | is_thunk && worthSplittingThunk maybe_fn_dmd res_info
211   = ASSERT2( isNonRec is_rec, ppr new_fn_id )   -- The thunk must be non-recursive
212     splitThunk new_fn_id rhs
213
214   | is_fun && worthSplittingFun wrap_dmds res_info
215   = splitFun new_fn_id fn_info wrap_dmds res_info inline_prag rhs
216
217   | otherwise
218   = return [ (new_fn_id, rhs) ]
219
220   where
221     fn_info      = idInfo fn_id
222     maybe_fn_dmd = newDemandInfo fn_info
223     unfolding    = unfoldingInfo fn_info
224     inline_prag  = inlinePragInfo fn_info
225
226         -- In practice it always will have a strictness 
227         -- signature, even if it's a uninformative one
228     strict_sig  = newStrictnessInfo fn_info `orElse` topSig
229     StrictSig (DmdType env wrap_dmds res_info) = strict_sig
230
231         -- new_fn_id has the DmdEnv zapped.  
232         --      (a) it is never used again
233         --      (b) it wastes space
234         --      (c) it becomes incorrect as things are cloned, because
235         --          we don't push the substitution into it
236     new_fn_id | isEmptyVarEnv env = fn_id
237               | otherwise         = fn_id `setIdNewStrictness` 
238                                      StrictSig (mkTopDmdType wrap_dmds res_info)
239
240     is_fun    = notNull wrap_dmds
241     is_thunk  = not is_fun && not (exprIsHNF rhs)
242
243 ---------------------
244 splitFun fn_id fn_info wrap_dmds res_info inline_prag rhs
245   = WARN( not (wrap_dmds `lengthIs` arity), ppr fn_id <+> (ppr arity $$ ppr wrap_dmds $$ ppr res_info) ) 
246     (do {
247         -- The arity should match the signature
248       (work_demands, wrap_fn, work_fn) <- mkWwBodies fun_ty wrap_dmds res_info one_shots
249     ; work_uniq <- getUniqueM
250     ; let
251         work_rhs = work_fn rhs
252         work_id  = mkWorkerId work_uniq fn_id (exprType work_rhs) 
253                         `setInlinePragma` inline_prag
254                                 -- Any inline pragma (which sets when inlining is active) 
255                                 -- on the original function is duplicated on the worker and wrapper
256                                 -- It *matters* that the pragma stays on the wrapper
257                                 -- It seems sensible to have it on the worker too, although we
258                                 -- can't think of a compelling reason. (In ptic, INLINE things are 
259                                 -- not w/wd)
260                         `setIdNewStrictness` StrictSig (mkTopDmdType work_demands work_res_info)
261                                 -- Even though we may not be at top level, 
262                                 -- it's ok to give it an empty DmdEnv
263                         `setIdArity` (exprArity work_rhs)
264                                 -- Set the arity so that the Core Lint check that the 
265                                 -- arity is consistent with the demand type goes through
266
267         wrap_rhs = wrap_fn work_id
268         wrap_id  = fn_id `setIdUnfolding` mkWwInlineRule wrap_rhs arity work_id
269
270     ; return ([(work_id, work_rhs), (wrap_id, wrap_rhs)]) })
271         -- Worker first, because wrapper mentions it
272         -- mkWwBodies has already built a wrap_rhs with an INLINE pragma wrapped around it
273   where
274     fun_ty = idType fn_id
275
276     arity  = arityInfo fn_info  -- The arity is set by the simplifier using exprEtaExpandArity
277                                 -- So it may be more than the number of top-level-visible lambdas
278
279     work_res_info | isBotRes res_info = BotRes  -- Cpr stuff done by wrapper
280                   | otherwise         = TopRes
281
282     one_shots = get_one_shots rhs
283
284 -- If the original function has one-shot arguments, it is important to
285 -- make the wrapper and worker have corresponding one-shot arguments too.
286 -- Otherwise we spuriously float stuff out of case-expression join points,
287 -- which is very annoying.
288 get_one_shots (Lam b e)
289   | isIdVar b = isOneShotLambda b : get_one_shots e
290   | otherwise = get_one_shots e
291 get_one_shots (Note _ e) = get_one_shots e
292 get_one_shots other      = noOneShotInfo
293 \end{code}
294
295 Thunk splitting
296 ~~~~~~~~~~~~~~~
297 Suppose x is used strictly (never mind whether it has the CPR
298 property).  
299
300       let
301         x* = x-rhs
302       in body
303
304 splitThunk transforms like this:
305
306       let
307         x* = case x-rhs of { I# a -> I# a }
308       in body
309
310 Now simplifier will transform to
311
312       case x-rhs of 
313         I# a -> let x* = I# a 
314                 in body
315
316 which is what we want. Now suppose x-rhs is itself a case:
317
318         x-rhs = case e of { T -> I# a; F -> I# b }
319
320 The join point will abstract over a, rather than over (which is
321 what would have happened before) which is fine.
322
323 Notice that x certainly has the CPR property now!
324
325 In fact, splitThunk uses the function argument w/w splitting 
326 function, so that if x's demand is deeper (say U(U(L,L),L))
327 then the splitting will go deeper too.
328
329 \begin{code}
330 -- splitThunk converts the *non-recursive* binding
331 --      x = e
332 -- into
333 --      x = let x = e
334 --          in case x of 
335 --               I# y -> let x = I# y in x }
336 -- See comments above. Is it not beautifully short?
337
338 splitThunk fn_id rhs = do
339     (_, wrap_fn, work_fn) <- mkWWstr [fn_id]
340     return [ (fn_id, Let (NonRec fn_id rhs) (wrap_fn (work_fn (Var fn_id)))) ]
341 \end{code}
342
343
344 %************************************************************************
345 %*                                                                      *
346 \subsection{Functions over Demands}
347 %*                                                                      *
348 %************************************************************************
349
350 \begin{code}
351 worthSplittingFun :: [Demand] -> DmdResult -> Bool
352                 -- True <=> the wrapper would not be an identity function
353 worthSplittingFun ds res
354   = any worth_it ds || returnsCPR res
355         -- worthSplitting returns False for an empty list of demands,
356         -- and hence do_strict_ww is False if arity is zero and there is no CPR
357   -- See Note [Worker-wrapper for bottoming functions]
358   where
359     worth_it Abs              = True    -- Absent arg
360     worth_it (Eval (Prod ds)) = True    -- Product arg to evaluate
361     worth_it other            = False
362
363 worthSplittingThunk :: Maybe Demand     -- Demand on the thunk
364                     -> DmdResult        -- CPR info for the thunk
365                     -> Bool
366 worthSplittingThunk maybe_dmd res
367   = worth_it maybe_dmd || returnsCPR res
368   where
369         -- Split if the thing is unpacked
370     worth_it (Just (Eval (Prod ds))) = not (all isAbsent ds)
371     worth_it other                   = False
372 \end{code}
373
374 Note [Worker-wrapper for bottoming functions]
375 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
376 We used not to split if the result is bottom.
377 [Justification:  there's no efficiency to be gained.]
378
379 But it's sometimes bad not to make a wrapper.  Consider
380         fw = \x# -> let x = I# x# in case e of
381                                         p1 -> error_fn x
382                                         p2 -> error_fn x
383                                         p3 -> the real stuff
384 The re-boxing code won't go away unless error_fn gets a wrapper too.
385 [We don't do reboxing now, but in general it's better to pass an
386 unboxed thing to f, and have it reboxed in the error cases....]
387
388
389 %************************************************************************
390 %*                                                                      *
391 \subsection{The worker wrapper core}
392 %*                                                                      *
393 %************************************************************************
394
395 @mkWrapper@ is called when importing a function.  We have the type of 
396 the function and the name of its worker, and we want to make its body (the wrapper).
397
398 \begin{code}
399 mkWrapper :: Type               -- Wrapper type
400           -> StrictSig          -- Wrapper strictness info
401           -> UniqSM (Id -> CoreExpr)    -- Wrapper body, missing worker Id
402
403 mkWrapper fun_ty (StrictSig (DmdType _ demands res_info)) = do
404     (_, wrap_fn, _) <- mkWwBodies fun_ty demands res_info noOneShotInfo
405     return wrap_fn
406
407 noOneShotInfo = repeat False
408 \end{code}