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