[project @ 2000-10-03 08:43:00 by simonpj]
[ghc-hetmet.git] / ghc / compiler / profiling / SCCfinal.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[SCCfinal]{Modify and collect code generation for final STG program}
5
6 This is now a sort-of-normal STG-to-STG pass (WDP 94/06), run by stg2stg.
7
8 * Traverses the STG program collecting the cost centres. These are
9   required to declare the cost centres at the start of code
10   generation.
11
12   Note: because of cross-module unfolding, some of these cost centres
13   may be from other modules.  But will still have to give them
14   "extern" declarations.
15
16 * Puts on CAF cost-centres if the user has asked for individual CAF
17   cost-centres.
18
19 * Ditto for individual DICT cost-centres.
20
21 * Boxes top-level inherited functions passed as arguments.
22
23 * "Distributes" given cost-centres to all as-yet-unmarked RHSs.
24
25 \begin{code}
26 module SCCfinal ( stgMassageForProfiling ) where
27
28 #include "HsVersions.h"
29
30 import StgSyn
31
32 import CmdLineOpts      ( opt_AutoSccsOnIndividualCafs )
33 import CostCentre       -- lots of things
34 import Id               ( Id )
35 import Module           ( Module )
36 import UniqSupply       ( uniqFromSupply, splitUniqSupply, UniqSupply )
37 import Unique           ( Unique )
38 import VarSet
39 import ListSetOps       ( removeDups )
40 import Outputable       
41
42 infixr 9 `thenMM`, `thenMM_`
43 \end{code}
44
45 \begin{code}
46 type CollectedCCs = ([CostCentre],      -- locally defined ones
47                      [CostCentre],      -- ones needing "extern" decls
48                      [CostCentreStack]) -- singleton stacks (for CAFs)
49
50 stgMassageForProfiling
51         :: Module                       -- module name
52         -> UniqSupply                   -- unique supply
53         -> [StgBinding]                 -- input
54         -> (CollectedCCs, [StgBinding])
55
56 stgMassageForProfiling mod_name us stg_binds
57   = let
58         ((local_ccs, extern_ccs, cc_stacks),
59          stg_binds2)
60           = initMM mod_name us (do_top_bindings stg_binds)
61
62         (fixed_ccs, fixed_cc_stacks)
63           = if opt_AutoSccsOnIndividualCafs
64             then ([],[])  -- don't need "all CAFs" CC 
65                           -- (for Prelude, we use PreludeCC)
66             else ([all_cafs_cc], [all_cafs_ccs])
67
68         local_ccs_no_dups  = fst (removeDups cmpCostCentre local_ccs)
69         extern_ccs_no_dups = fst (removeDups cmpCostCentre extern_ccs)
70     in
71     ((fixed_ccs ++ local_ccs_no_dups, 
72       extern_ccs_no_dups, 
73       fixed_cc_stacks ++ cc_stacks), stg_binds2)
74   where
75
76     all_cafs_cc  = mkAllCafsCC mod_name
77     all_cafs_ccs = mkSingletonCCS all_cafs_cc
78
79     ----------
80     do_top_bindings :: [StgBinding] -> MassageM [StgBinding]
81
82     do_top_bindings [] = returnMM []
83
84     do_top_bindings (StgNonRec b rhs : bs) 
85       = do_top_rhs b rhs                `thenMM` \ rhs' ->
86         addTopLevelIshId b (
87            do_top_bindings bs `thenMM` \bs' ->
88            returnMM (StgNonRec b rhs' : bs')
89         )
90
91     do_top_bindings (StgRec pairs : bs)
92       = addTopLevelIshIds binders (
93            mapMM do_pair pairs          `thenMM` \ pairs2 ->
94            do_top_bindings bs `thenMM` \ bs' ->
95            returnMM (StgRec pairs2 : bs')
96         )
97       where
98         binders = map fst pairs
99         do_pair (b, rhs) 
100            = do_top_rhs b rhs   `thenMM` \ rhs2 ->
101              returnMM (b, rhs2)
102
103     ----------
104     do_top_rhs :: Id -> StgRhs -> MassageM StgRhs
105
106     do_top_rhs binder (StgRhsClosure _ bi srt fv u [] (StgSCC cc (StgConApp con args)))
107       | not (isSccCountCostCentre cc) && not (isDllConApp con args)
108         -- Trivial _scc_ around nothing but static data
109         -- Eliminate _scc_ ... and turn into StgRhsCon
110
111         -- isDllConApp checks for LitLit args too
112       = returnMM (StgRhsCon dontCareCCS con args)
113
114 {- Can't do this one with cost-centre stacks:  --SDM
115     do_top_rhs binder (StgRhsClosure no_cc bi srt fv u [] (StgSCC ty cc expr))
116       | (noCCSAttached no_cc || currentOrSubsumedCCS no_cc)
117         && not (isSccCountCostCentre cc)
118         -- Top level CAF without a cost centre attached
119         -- Attach and collect cc of trivial _scc_ in body
120       = collectCC cc                                    `thenMM_`
121         set_prevailing_cc cc (do_expr expr)             `thenMM`  \ expr' ->
122         returnMM (StgRhsClosure cc bi srt fv u [] expr')
123 -}
124
125     do_top_rhs binder (StgRhsClosure no_cc bi srt fv u [] body)
126       | noCCSAttached no_cc || currentOrSubsumedCCS no_cc
127         -- Top level CAF without a cost centre attached
128         -- Attach CAF cc (collect if individual CAF ccs)
129       = (if opt_AutoSccsOnIndividualCafs 
130                 then let cc = mkAutoCC binder mod_name CafCC
131                          ccs = mkSingletonCCS cc
132                      in
133                      collectCC  cc  `thenMM_`
134                      collectCCS ccs `thenMM_`
135                      returnMM ccs
136                 else 
137                      returnMM all_cafs_ccs)             `thenMM`  \ caf_ccs ->
138            set_prevailing_cc caf_ccs (do_expr body)     `thenMM`  \ body' ->
139            returnMM (StgRhsClosure caf_ccs bi srt fv u [] body')
140
141     do_top_rhs binder (StgRhsClosure cc bi srt fv u [] body)
142         -- Top level CAF with cost centre attached
143         -- Should this be a CAF cc ??? Does this ever occur ???
144       = pprPanic "SCCfinal: CAF with cc:" (ppr cc)
145
146 {- can't do this with cost-centre stacks:  --SDM
147     do_top_rhs binder (StgRhsClosure _ bi srt fv u args (StgSCC cc expr))
148       | not (isSccCountCostCentre cc)
149         -- Top level function with trivial _scc_ in body
150         -- Attach and collect cc of trivial _scc_
151       = collectCC cc                                    `thenMM_`
152         set_prevailing_cc cc (do_expr expr)             `thenMM` \ expr' ->
153         returnMM (StgRhsClosure cc bi srt fv u args expr')
154 -}
155
156     do_top_rhs binder (StgRhsClosure no_ccs bi srt fv u args body)
157         -- Top level function, probably subsumed
158       | noCCSAttached no_ccs
159       = set_lambda_cc (do_expr body)    `thenMM` \ body' ->
160         returnMM (StgRhsClosure subsumedCCS bi srt fv u args body')
161
162       | otherwise
163       = pprPanic "SCCfinal: CAF with cc:" (ppr no_ccs)
164
165     do_top_rhs binder (StgRhsCon ccs con args)
166         -- Top-level (static) data is not counted in heap
167         -- profiles; nor do we set CCCS from it; so we
168         -- just slam in dontCareCostCentre
169       = returnMM (StgRhsCon dontCareCCS con args)
170
171     ------
172     do_expr :: StgExpr -> MassageM StgExpr
173
174     do_expr (StgLit l) = returnMM (StgLit l)
175
176     do_expr (StgApp fn args)
177       = boxHigherOrderArgs (StgApp fn) args
178
179     do_expr (StgConApp con args)
180       = boxHigherOrderArgs (\args -> StgConApp con args) args
181
182     do_expr (StgPrimApp con args res_ty)
183       = boxHigherOrderArgs (\args -> StgPrimApp con args res_ty) args
184
185     do_expr (StgSCC cc expr)    -- Ha, we found a cost centre!
186       = collectCC cc            `thenMM_`
187         do_expr expr            `thenMM` \ expr' ->
188         returnMM (StgSCC cc expr')
189
190     do_expr (StgCase expr fv1 fv2 bndr srt alts)
191       = do_expr expr            `thenMM` \ expr' ->
192         do_alts alts            `thenMM` \ alts' ->
193         returnMM (StgCase expr' fv1 fv2 bndr srt alts')
194       where
195         do_alts (StgAlgAlts ty alts def) 
196           = mapMM do_alt alts   `thenMM` \ alts' ->
197             do_deflt def        `thenMM` \ def' ->
198             returnMM (StgAlgAlts ty alts' def')
199           where
200             do_alt (id, bs, use_mask, e)
201               = do_expr e `thenMM` \ e' ->
202                 returnMM (id, bs, use_mask, e')
203
204         do_alts (StgPrimAlts ty alts def) 
205           = mapMM do_alt alts   `thenMM` \ alts' ->
206             do_deflt def        `thenMM` \ def' ->
207             returnMM (StgPrimAlts ty alts' def')
208           where
209             do_alt (l,e)
210               = do_expr e `thenMM` \ e' ->
211                 returnMM (l,e')
212
213         do_deflt StgNoDefault = returnMM StgNoDefault
214         do_deflt (StgBindDefault e) 
215           = do_expr e                   `thenMM` \ e' ->
216             returnMM (StgBindDefault e')
217
218     do_expr (StgLet b e)
219         = do_let b e `thenMM` \ (b,e) ->
220           returnMM (StgLet b e)
221
222     do_expr (StgLetNoEscape lvs1 lvs2 b e)
223         = do_let b e `thenMM` \ (b,e) ->
224           returnMM (StgLetNoEscape lvs1 lvs2 b e)
225
226     ----------------------------------
227
228     do_let (StgNonRec b rhs) e
229       = do_rhs rhs                      `thenMM` \ rhs' ->
230         addTopLevelIshId b (
231           do_expr e                     `thenMM` \ e' ->
232           returnMM (StgNonRec b rhs',e')
233         )
234
235     do_let (StgRec pairs) e
236       = addTopLevelIshIds binders (
237            mapMM do_pair pairs          `thenMM` \ pairs' ->
238            do_expr e                    `thenMM` \ e' ->
239            returnMM (StgRec pairs', e')
240         )
241       where
242         binders = map fst pairs
243         do_pair (b, rhs) 
244            = do_rhs rhs                 `thenMM` \ rhs2 ->
245              returnMM (b, rhs2)
246
247     ----------------------------------
248     do_rhs :: StgRhs -> MassageM StgRhs
249         -- We play much the same game as we did in do_top_rhs above;
250         -- but we don't have to worry about cafs etc.
251
252 {-
253     do_rhs (StgRhsClosure closure_cc bi srt fv u [] (StgSCC ty cc (StgCon (DataCon con) args _)))
254       | not (isSccCountCostCentre cc)
255       = collectCC cc `thenMM_`
256         returnMM (StgRhsCon cc con args)
257 -}
258
259 {-
260     do_rhs (StgRhsClosure _ bi srt fv u args (StgSCC ty cc expr))
261       | not (isSccCountCostCentre cc)
262       = collectCC cc                            `thenMM_`
263         set_prevailing_cc cc (do_expr expr)     `thenMM` \ expr' ->
264         returnMM (StgRhsClosure cc bi srt fv u args expr')
265 -}
266
267     do_rhs (StgRhsClosure cc bi srt fv u [] body)
268       = do_expr body                            `thenMM` \ body' ->
269         returnMM (StgRhsClosure currentCCS bi srt fv u [] body')
270
271     do_rhs (StgRhsClosure cc bi srt fv u args body)
272       = set_lambda_cc (do_expr body)            `thenMM` \ body' ->
273         get_prevailing_cc                       `thenMM` \ prev_ccs ->
274         returnMM (StgRhsClosure currentCCS bi srt fv u args body')
275
276     do_rhs (StgRhsCon cc con args)
277       = returnMM (StgRhsCon currentCCS con args)
278 \end{code}
279
280 %************************************************************************
281 %*                                                                      *
282 \subsection{Boxing higher-order args}
283 %*                                                                      *
284 %************************************************************************
285
286 Boxing is *turned off* at the moment, until we can figure out how to
287 do it properly in general.
288
289 \begin{code}
290 boxHigherOrderArgs
291     :: ([StgArg] -> StgExpr)
292                         -- An application lacking its arguments
293     -> [StgArg]         -- arguments which we might box
294     -> MassageM StgExpr
295
296 #ifndef PROF_DO_BOXING
297 boxHigherOrderArgs almost_expr args
298    = returnMM (almost_expr args)
299 #else
300 boxHigherOrderArgs almost_expr args
301   = getTopLevelIshIds           `thenMM` \ ids ->
302     mapAccumMM (do_arg ids) [] args     `thenMM` \ (let_bindings, new_args) ->
303     returnMM (foldr (mk_stg_let currentCCS) (almost_expr new_args) let_bindings)
304   where
305     ---------------
306
307     do_arg ids bindings arg@(StgVarArg old_var)
308         |  (not (isLocallyDefined old_var) || elemVarSet old_var ids)
309         && isFunType var_type
310       =     -- make a trivial let-binding for the top-level function
311         getUniqueMM             `thenMM` \ uniq ->
312         let
313             new_var = mkSysLocal SLIT("sf") uniq var_type
314         in
315         returnMM ( (new_var, old_var) : bindings, StgVarArg new_var )
316       where
317         var_type = idType old_var
318
319     do_arg ids bindings arg = returnMM (bindings, arg)
320
321     ---------------
322     mk_stg_let :: CostCentreStack -> (Id, Id) -> StgExpr -> StgExpr
323
324     mk_stg_let cc (new_var, old_var) body
325       = let
326             rhs_body    = StgApp old_var [{-args-}]
327             rhs_closure = StgRhsClosure cc stgArgOcc NoSRT [{-fvs-}] ReEntrant [{-args-}] rhs_body
328         in
329         StgLet (StgNonRec new_var rhs_closure) body
330       where
331         bOGUS_LVs = emptyUniqSet -- easier to print than: panic "mk_stg_let: LVs"
332
333 isFunType var_type 
334   = case splitForAllTys var_type of
335         (_, ty) -> case splitTyConApp_maybe ty of
336                         Just (tycon,_) | isFunTyCon tycon -> True
337                         _ -> False
338 #endif
339 \end{code}
340
341 %************************************************************************
342 %*                                                                      *
343 \subsection{Boring monad stuff for this}
344 %*                                                                      *
345 %************************************************************************
346
347 \begin{code}
348 type MassageM result
349   =  Module             -- module name
350   -> CostCentreStack    -- prevailing CostCentre
351                         -- if none, subsumedCosts at top-level
352                         -- useCurrentCostCentre at nested levels
353   -> UniqSupply
354   -> VarSet             -- toplevel-ish Ids for boxing
355   -> CollectedCCs
356   -> (CollectedCCs, result)
357
358 -- the initMM function also returns the final CollectedCCs
359
360 initMM :: Module        -- module name, which we may consult
361        -> UniqSupply
362        -> MassageM a
363        -> (CollectedCCs, a)
364
365 initMM mod_name init_us m = m mod_name noCCS init_us emptyVarSet ([],[],[])
366
367 thenMM  :: MassageM a -> (a -> MassageM b) -> MassageM b
368 thenMM_ :: MassageM a -> (MassageM b) -> MassageM b
369
370 thenMM expr cont mod scope_cc us ids ccs
371   = case splitUniqSupply us     of { (s1, s2) ->
372     case (expr mod scope_cc s1 ids ccs) of { (ccs2, result) ->
373     cont result mod scope_cc s2 ids ccs2 }}
374
375 thenMM_ expr cont mod scope_cc us ids ccs
376   = case splitUniqSupply us     of { (s1, s2) ->
377     case (expr mod scope_cc s1 ids ccs) of { (ccs2, _) ->
378     cont mod scope_cc s2 ids ccs2 }}
379
380 returnMM :: a -> MassageM a
381 returnMM result mod scope_cc us ids ccs = (ccs, result)
382
383 nopMM :: MassageM ()
384 nopMM mod scope_cc us ids ccs = (ccs, ())
385
386 mapMM :: (a -> MassageM b) -> [a] -> MassageM [b]
387 mapMM f [] = returnMM []
388 mapMM f (m:ms)
389   = f m         `thenMM` \ r  ->
390     mapMM f ms  `thenMM` \ rs ->
391     returnMM (r:rs)
392
393 mapAccumMM :: (acc -> x -> MassageM (acc, y)) -> acc -> [x] -> MassageM (acc, [y])
394 mapAccumMM f b [] = returnMM (b, [])
395 mapAccumMM f b (m:ms)
396   = f b m               `thenMM` \ (b2, r)  ->
397     mapAccumMM f b2 ms  `thenMM` \ (b3, rs) ->
398     returnMM (b3, r:rs)
399
400 getUniqueMM :: MassageM Unique
401 getUniqueMM mod scope_cc us ids ccs = (ccs, uniqFromSupply us)
402
403 addTopLevelIshId :: Id -> MassageM a -> MassageM a
404 addTopLevelIshId id scope mod scope_cc us ids ccs
405   | isCurrentCCS scope_cc = scope mod scope_cc us ids ccs
406   | otherwise             = scope mod scope_cc us (extendVarSet ids id) ccs
407
408 addTopLevelIshIds :: [Id] -> MassageM a -> MassageM a
409 addTopLevelIshIds [] cont = cont
410 addTopLevelIshIds (id:ids) cont 
411   = addTopLevelIshId id (addTopLevelIshIds ids cont)
412
413 getTopLevelIshIds :: MassageM VarSet
414 getTopLevelIshIds mod scope_cc us ids ccs = (ccs, ids)
415 \end{code}
416
417 The prevailing CCS is used to tell whether we're in a top-levelish
418 position, where top-levelish is defined as "not inside a lambda".
419 Prevailing CCs used to be used for something much more complicated,
420 I'm sure --SDM
421
422 \begin{code}
423 set_lambda_cc :: MassageM a -> MassageM a
424 set_lambda_cc action mod scope_cc us ids ccs
425   = action mod currentCCS us ids ccs
426
427 set_prevailing_cc :: CostCentreStack -> MassageM a -> MassageM a
428 set_prevailing_cc cc_to_set_to action mod scope_cc us ids ccs
429   = action mod cc_to_set_to us ids ccs
430
431 get_prevailing_cc :: MassageM CostCentreStack
432 get_prevailing_cc mod scope_cc us ids ccs = (ccs, scope_cc)
433 \end{code}
434
435 \begin{code}
436 collectCC :: CostCentre -> MassageM ()
437
438 collectCC cc mod_name scope_cc us ids (local_ccs, extern_ccs, ccss)
439   = ASSERT(not (noCCAttached cc))
440     if (cc `ccFromThisModule` mod_name) then
441         ((cc : local_ccs, extern_ccs, ccss), ())
442     else -- must declare it "extern"
443         ((local_ccs, cc : extern_ccs, ccss), ())
444
445 collectCCS :: CostCentreStack -> MassageM ()
446
447 collectCCS ccs mod_name scope_cc us ids (local_ccs, extern_ccs, ccss)
448   = ASSERT(not (noCCSAttached ccs))
449     ((local_ccs, extern_ccs, ccs : ccss), ())
450 \end{code}