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