[project @ 1998-02-05 12:23:33 by simonm]
[ghc-hetmet.git] / ghc / compiler / stranal / WorkWrap.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1996
3 %
4 \section[WorkWrap]{Worker/wrapper-generating back-end of strictness analyser}
5
6 \begin{code}
7 module WorkWrap ( workersAndWrappers, getWorkerIdAndCons ) where
8
9 #include "HsVersions.h"
10
11 import CoreSyn
12 import CoreUnfold       ( Unfolding, certainlySmallEnoughToInline, calcUnfoldingGuidance )
13 import CmdLineOpts      ( opt_UnfoldingCreationThreshold )
14
15 import CoreUtils        ( coreExprType )
16 import Id               ( getInlinePragma, getIdStrictness, mkWorkerId,
17                           addIdStrictness, addInlinePragma,
18                           IdSet, emptyIdSet, addOneToIdSet,
19                           GenId, Id
20                         )
21 import IdInfo           ( noIdInfo, addUnfoldInfo,  
22                           mkStrictnessInfo, addStrictnessInfo, StrictnessInfo(..)
23                         )
24 import SaLib
25 import UniqSupply       ( returnUs, thenUs, mapUs, getUnique, UniqSM )
26 import WwLib
27 import Outputable
28 \end{code}
29
30 We take Core bindings whose binders have their strictness attached (by
31 the front-end of the strictness analyser), and we return some
32 ``plain'' bindings which have been worker/wrapper-ified, meaning:
33 \begin{enumerate}
34 \item
35 Functions have been split into workers and wrappers where appropriate;
36 \item
37 Binders' @IdInfos@ have been updated to reflect the existence
38 of these workers/wrappers (this is where we get STRICTNESS pragma
39 info for exported values).
40 \end{enumerate}
41
42 \begin{code}
43 workersAndWrappers :: [CoreBinding] -> UniqSM [CoreBinding]
44
45 workersAndWrappers top_binds
46   = mapUs (wwBind True{-top-level-}) top_binds `thenUs` \ top_binds2 ->
47     let
48         top_binds3 = map make_top_binding top_binds2
49     in
50     returnUs (concat top_binds3)
51   where
52     make_top_binding :: WwBinding -> [CoreBinding]
53
54     make_top_binding (WwLet binds) = binds
55 \end{code}
56
57 %************************************************************************
58 %*                                                                      *
59 \subsection[wwBind-wwExpr]{@wwBind@ and @wwExpr@}
60 %*                                                                      *
61 %************************************************************************
62
63 @wwBind@ works on a binding, trying each \tr{(binder, expr)} pair in
64 turn.  Non-recursive case first, then recursive...
65
66 \begin{code}
67 wwBind  :: Bool                 -- True <=> top-level binding
68         -> CoreBinding
69         -> UniqSM WwBinding     -- returns a WwBinding intermediate form;
70                                 -- the caller will convert to Expr/Binding,
71                                 -- as appropriate.
72
73 wwBind top_level (NonRec binder rhs)
74   = wwExpr rhs                  `thenUs` \ new_rhs ->
75     tryWW binder new_rhs        `thenUs` \ new_pairs ->
76     returnUs (WwLet [NonRec b e | (b,e) <- new_pairs])
77       -- Generated bindings must be non-recursive
78       -- because the original binding was.
79
80 ------------------------------
81
82 wwBind top_level (Rec pairs)
83   = mapUs do_one pairs          `thenUs` \ new_pairs ->
84     returnUs (WwLet [Rec (concat new_pairs)])
85   where
86     do_one (binder, rhs) = wwExpr rhs   `thenUs` \ new_rhs ->
87                            tryWW binder new_rhs
88 \end{code}
89
90 @wwExpr@ basically just walks the tree, looking for appropriate
91 annotations that can be used. Remember it is @wwBind@ that does the
92 matching by looking for strict arguments of the correct type.
93 @wwExpr@ is a version that just returns the ``Plain'' Tree.
94 ???????????????? ToDo
95
96 \begin{code}
97 wwExpr :: CoreExpr -> UniqSM CoreExpr
98
99 wwExpr e@(Var _)    = returnUs e
100 wwExpr e@(Lit _)    = returnUs e
101 wwExpr e@(Con  _ _) = returnUs e
102 wwExpr e@(Prim _ _) = returnUs e
103
104 wwExpr (Lam binder expr)
105   = wwExpr expr                 `thenUs` \ new_expr ->
106     returnUs (Lam binder new_expr)
107
108 wwExpr (App f a)
109   = wwExpr f                    `thenUs` \ new_f ->
110     returnUs (App new_f a)
111
112 wwExpr (SCC cc expr)
113   = wwExpr expr                 `thenUs` \ new_expr ->
114     returnUs (SCC cc new_expr)
115
116 wwExpr (Coerce c ty expr)
117   = wwExpr expr                 `thenUs` \ new_expr ->
118     returnUs (Coerce c ty new_expr)
119
120 wwExpr (Let bind expr)
121   = wwBind False{-not top-level-} bind  `thenUs` \ intermediate_bind ->
122     wwExpr expr                         `thenUs` \ new_expr ->
123     returnUs (mash_ww_bind intermediate_bind new_expr)
124   where
125     mash_ww_bind (WwLet  binds)   body = mkCoLetsNoUnboxed binds body
126     mash_ww_bind (WwCase case_fn) body = case_fn body
127
128 wwExpr (Case expr alts)
129   = wwExpr expr                         `thenUs` \ new_expr ->
130     ww_alts alts                        `thenUs` \ new_alts ->
131     returnUs (Case new_expr new_alts)
132   where
133     ww_alts (AlgAlts alts deflt)
134       = mapUs ww_alg_alt alts           `thenUs` \ new_alts ->
135         ww_deflt deflt                  `thenUs` \ new_deflt ->
136         returnUs (AlgAlts new_alts new_deflt)
137
138     ww_alts (PrimAlts alts deflt)
139       = mapUs ww_prim_alt alts          `thenUs` \ new_alts ->
140         ww_deflt deflt                  `thenUs` \ new_deflt ->
141         returnUs (PrimAlts new_alts new_deflt)
142
143     ww_alg_alt (con, binders, rhs)
144       = wwExpr rhs                      `thenUs` \ new_rhs ->
145         returnUs (con, binders, new_rhs)
146
147     ww_prim_alt (lit, rhs)
148       = wwExpr rhs                      `thenUs` \ new_rhs ->
149         returnUs (lit, new_rhs)
150
151     ww_deflt NoDefault
152       = returnUs NoDefault
153
154     ww_deflt (BindDefault binder rhs)
155       = wwExpr rhs                      `thenUs` \ new_rhs ->
156         returnUs (BindDefault binder new_rhs)
157 \end{code}
158
159 %************************************************************************
160 %*                                                                      *
161 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
162 %*                                                                      *
163 %************************************************************************
164
165 @tryWW@ just accumulates arguments, converts strictness info from the
166 front-end into the proper form, then calls @mkWwBodies@ to do
167 the business.
168
169 We have to BE CAREFUL that we don't worker-wrapperize an Id that has
170 already been w-w'd!  (You can end up with several liked-named Ids
171 bouncing around at the same time---absolute mischief.)  So the
172 criterion we use is: if an Id already has an unfolding (for whatever
173 reason), then we don't w-w it.
174
175 The only reason this is monadised is for the unique supply.
176
177 \begin{code}
178 tryWW   :: Id                           -- The fn binder
179         -> CoreExpr                     -- The bound rhs; its innards
180                                         --   are already ww'd
181         -> UniqSM [(Id, CoreExpr)]      -- either *one* or *two* pairs;
182                                         -- if one, then no worker (only
183                                         -- the orig "wrapper" lives on);
184                                         -- if two, then a worker and a
185                                         -- wrapper.
186 tryWW fn_id rhs
187   | (certainlySmallEnoughToInline $
188      calcUnfoldingGuidance (getInlinePragma fn_id) 
189                           opt_UnfoldingCreationThreshold
190                           rhs
191     )
192             -- No point in worker/wrappering something that is going to be
193             -- INLINEd wholesale anyway.  If the strictness analyser is run
194             -- twice, this test also prevents wrappers (which are INLINEd)
195             -- from being re-done.
196
197   || not has_strictness_info
198   || not (worthSplitting revised_wrap_args_info)
199   = returnUs [ (fn_id, rhs) ]
200
201   | otherwise           -- Do w/w split
202   = let
203         (tyvars, wrap_args, body) = collectBinders rhs
204     in
205     mkWwBodies tyvars wrap_args 
206                (coreExprType body)
207                revised_wrap_args_info           `thenUs` \ (wrap_fn, work_fn, work_demands) ->
208     getUnique                                   `thenUs` \ work_uniq ->
209     let
210         work_rhs  = work_fn body
211         work_id   = mkWorkerId work_uniq fn_id (coreExprType work_rhs) work_info
212         work_info = noIdInfo `addStrictnessInfo` mkStrictnessInfo work_demands False
213
214         wrap_rhs = wrap_fn work_id
215         wrap_id  = addInlinePragma (fn_id `addIdStrictness`
216                                     mkStrictnessInfo revised_wrap_args_info True)
217                 -- Add info to the wrapper:
218                 --      (a) we want to inline it everywhere
219                 --      (b) we want to pin on its revised stricteness info
220                 --      (c) we pin on its worker id and the list of constructors mentioned in the wrapper
221     in
222     returnUs ([(work_id, work_rhs), (wrap_id, wrap_rhs)])
223         -- Worker first, because wrapper mentions it
224   where
225     strictness_info     = getIdStrictness fn_id
226     has_strictness_info = case strictness_info of
227                                 StrictnessInfo _ _ -> True
228                                 other              -> False
229
230     wrap_args_info = case strictness_info of
231                         StrictnessInfo args_info _ -> args_info
232     revised_wrap_args_info = setUnpackStrategy wrap_args_info
233
234 -- This rather (nay! extremely!) crude function looks at a wrapper function, and
235 -- snaffles out (a) the worker Id and (b) constructors needed to 
236 -- make the wrapper.
237 -- These are needed when we write an interface file.
238 getWorkerIdAndCons wrap_id wrapper_fn
239   = go wrapper_fn
240   where
241     go (Lam _ body)                       = go body
242     go (Case _ (AlgAlts [(con,_,rhs)] _)) = let (wrap_id, cons) = go rhs
243                                             in  (wrap_id, cons `addOneToIdSet` con)
244     go (Let (NonRec _ (Coerce (CoerceOut con) _ _)) body) 
245                                           = let (wrap_id, cons) = go body
246                                             in  (wrap_id, cons `addOneToIdSet` con)
247     go other                              = (get_work_id other, emptyIdSet)
248
249     get_work_id (App fn _)    = get_work_id fn
250     get_work_id (Var work_id) = work_id
251     get_work_id other         = pprPanic "getWorkerIdAndCons" (ppr wrap_id)
252 \end{code}