[project @ 2005-03-10 14:03:28 by simonmar]
[ghc-hetmet.git] / ghc / compiler / simplCore / SimplMonad.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[SimplMonad]{The simplifier Monad}
5
6 \begin{code}
7 module SimplMonad (
8         -- The monad
9         SimplM,
10         initSmpl, returnSmpl, thenSmpl, thenSmpl_,
11         mapSmpl, mapAndUnzipSmpl, mapAccumLSmpl,
12         getDOptsSmpl,
13
14         -- Unique supply
15         getUniqueSmpl, getUniquesSmpl, getUniqSupplySmpl, newId,
16
17         -- Counting
18         SimplCount, Tick(..),
19         tick, freeTick,
20         getSimplCount, zeroSimplCount, pprSimplCount, 
21         plusSimplCount, isZeroSimplCount,
22
23         -- Switch checker
24         SwitchChecker, SwitchResult(..), getSimplIntSwitch,
25         isAmongSimpl, intSwitchSet, switchIsOn
26     ) where
27
28 #include "HsVersions.h"
29
30 import Id               ( Id, mkSysLocal )
31 import Type             ( Type )
32 import UniqSupply       ( uniqsFromSupply, uniqFromSupply, splitUniqSupply,
33                           UniqSupply
34                         )
35 import CmdLineOpts      ( SimplifierSwitch(..), DynFlags, DynFlag(..), dopt, 
36                           opt_PprStyle_Debug, opt_HistorySize, 
37                         )
38 import OccName          ( EncodedFS )
39 import Unique           ( Unique )
40 import Maybes           ( expectJust )
41 import FiniteMap        ( FiniteMap, emptyFM, isEmptyFM, lookupFM, addToFM, plusFM_C, fmToList )
42 import FastString       ( FastString )
43 import Outputable
44 import FastTypes
45
46 import GLAEXTS          ( indexArray# )
47
48 #if __GLASGOW_HASKELL__ < 503
49 import PrelArr  ( Array(..) )
50 #else
51 import GHC.Arr  ( Array(..) )
52 #endif
53
54 import Array            ( array, (//) )
55
56 infixr 0  `thenSmpl`, `thenSmpl_`
57 \end{code}
58
59 %************************************************************************
60 %*                                                                      *
61 \subsection{Monad plumbing}
62 %*                                                                      *
63 %************************************************************************
64
65 For the simplifier monad, we want to {\em thread} a unique supply and a counter.
66 (Command-line switches move around through the explicitly-passed SimplEnv.)
67
68 \begin{code}
69 newtype SimplM result
70   =  SM  { unSM :: DynFlags             -- We thread the unique supply because
71                    -> UniqSupply        -- constantly splitting it is rather expensive
72                    -> SimplCount 
73                    -> (result, UniqSupply, SimplCount)}
74 \end{code}
75
76 \begin{code}
77 initSmpl :: DynFlags
78          -> UniqSupply          -- No init count; set to 0
79          -> SimplM a
80          -> (a, SimplCount)
81
82 initSmpl dflags us m
83   = case unSM m dflags us (zeroSimplCount dflags) of 
84         (result, _, count) -> (result, count)
85
86
87 {-# INLINE thenSmpl #-}
88 {-# INLINE thenSmpl_ #-}
89 {-# INLINE returnSmpl #-}
90
91 instance Monad SimplM where
92    (>>)   = thenSmpl_
93    (>>=)  = thenSmpl
94    return = returnSmpl
95
96 returnSmpl :: a -> SimplM a
97 returnSmpl e = SM (\ dflags us sc -> (e, us, sc))
98
99 thenSmpl  :: SimplM a -> (a -> SimplM b) -> SimplM b
100 thenSmpl_ :: SimplM a -> SimplM b -> SimplM b
101
102 thenSmpl m k 
103   = SM (\ dflags us0 sc0 ->
104           case (unSM m dflags us0 sc0) of 
105                 (m_result, us1, sc1) -> unSM (k m_result) dflags us1 sc1 )
106
107 thenSmpl_ m k 
108   = SM (\dflags us0 sc0 ->
109          case (unSM m dflags us0 sc0) of 
110                 (_, us1, sc1) -> unSM k dflags us1 sc1)
111 \end{code}
112
113
114 \begin{code}
115 mapSmpl         :: (a -> SimplM b) -> [a] -> SimplM [b]
116 mapAndUnzipSmpl :: (a -> SimplM (b, c)) -> [a] -> SimplM ([b],[c])
117
118 mapSmpl f [] = returnSmpl []
119 mapSmpl f (x:xs)
120   = f x             `thenSmpl` \ x'  ->
121     mapSmpl f xs    `thenSmpl` \ xs' ->
122     returnSmpl (x':xs')
123
124 mapAndUnzipSmpl f [] = returnSmpl ([],[])
125 mapAndUnzipSmpl f (x:xs)
126   = f x                     `thenSmpl` \ (r1,  r2)  ->
127     mapAndUnzipSmpl f xs    `thenSmpl` \ (rs1, rs2) ->
128     returnSmpl (r1:rs1, r2:rs2)
129
130 mapAccumLSmpl :: (acc -> b -> SimplM (acc,c)) -> acc -> [b] -> SimplM (acc, [c])
131 mapAccumLSmpl f acc []     = returnSmpl (acc, [])
132 mapAccumLSmpl f acc (x:xs) = f acc x    `thenSmpl` \ (acc', x') ->
133                              mapAccumLSmpl f acc' xs    `thenSmpl` \ (acc'', xs') ->
134                              returnSmpl (acc'', x':xs')
135 \end{code}
136
137
138 %************************************************************************
139 %*                                                                      *
140 \subsection{The unique supply}
141 %*                                                                      *
142 %************************************************************************
143
144 \begin{code}
145 getUniqSupplySmpl :: SimplM UniqSupply
146 getUniqSupplySmpl 
147    = SM (\dflags us sc -> case splitUniqSupply us of
148                                 (us1, us2) -> (us1, us2, sc))
149
150 getUniqueSmpl :: SimplM Unique
151 getUniqueSmpl 
152    = SM (\dflags us sc -> case splitUniqSupply us of
153                                 (us1, us2) -> (uniqFromSupply us1, us2, sc))
154
155 getUniquesSmpl :: SimplM [Unique]
156 getUniquesSmpl 
157    = SM (\dflags us sc -> case splitUniqSupply us of
158                                 (us1, us2) -> (uniqsFromSupply us1, us2, sc))
159
160 getDOptsSmpl :: SimplM DynFlags
161 getDOptsSmpl 
162    = SM (\dflags us sc -> (dflags, us, sc))
163
164 newId :: EncodedFS -> Type -> SimplM Id
165 newId fs ty = getUniqueSmpl     `thenSmpl` \ uniq ->
166               returnSmpl (mkSysLocal fs uniq ty)
167 \end{code}
168
169
170 %************************************************************************
171 %*                                                                      *
172 \subsection{Counting up what we've done}
173 %*                                                                      *
174 %************************************************************************
175
176 \begin{code}
177 getSimplCount :: SimplM SimplCount
178 getSimplCount = SM (\dflags us sc -> (sc, us, sc))
179
180 tick :: Tick -> SimplM ()
181 tick t 
182    = SM (\dflags us sc -> let sc' = doTick t sc 
183                           in sc' `seq` ((), us, sc'))
184
185 freeTick :: Tick -> SimplM ()
186 -- Record a tick, but don't add to the total tick count, which is
187 -- used to decide when nothing further has happened
188 freeTick t 
189    = SM (\dflags us sc -> let sc' = doFreeTick t sc
190                           in sc' `seq` ((), us, sc'))
191 \end{code}
192
193 \begin{code}
194 verboseSimplStats = opt_PprStyle_Debug          -- For now, anyway
195
196 zeroSimplCount     :: DynFlags -> SimplCount
197 isZeroSimplCount   :: SimplCount -> Bool
198 pprSimplCount      :: SimplCount -> SDoc
199 doTick, doFreeTick :: Tick -> SimplCount -> SimplCount
200 plusSimplCount     :: SimplCount -> SimplCount -> SimplCount
201 \end{code}
202
203 \begin{code}
204 data SimplCount = VerySimplZero         -- These two are used when 
205                 | VerySimplNonZero      -- we are only interested in 
206                                         -- termination info
207
208                 | SimplCount    {
209                         ticks   :: !Int,                -- Total ticks
210                         details :: !TickCounts,         -- How many of each type
211                         n_log   :: !Int,                -- N
212                         log1    :: [Tick],              -- Last N events; <= opt_HistorySize
213                         log2    :: [Tick]               -- Last opt_HistorySize events before that
214                   }
215
216 type TickCounts = FiniteMap Tick Int
217
218 zeroSimplCount dflags
219                 -- This is where we decide whether to do
220                 -- the VerySimpl version or the full-stats version
221   | dopt Opt_D_dump_simpl_stats dflags
222   = SimplCount {ticks = 0, details = emptyFM,
223                 n_log = 0, log1 = [], log2 = []}
224   | otherwise
225   = VerySimplZero
226
227 isZeroSimplCount VerySimplZero              = True
228 isZeroSimplCount (SimplCount { ticks = 0 }) = True
229 isZeroSimplCount other                      = False
230
231 doFreeTick tick sc@SimplCount { details = dts } 
232   = dts' `seqFM` sc { details = dts' }
233   where
234     dts' = dts `addTick` tick 
235 doFreeTick tick sc = sc 
236
237 -- Gross hack to persuade GHC 3.03 to do this important seq
238 seqFM fm x | isEmptyFM fm = x
239            | otherwise    = x
240
241 doTick tick sc@SimplCount { ticks = tks, details = dts, n_log = nl, log1 = l1, log2 = l2 }
242   | nl >= opt_HistorySize = sc1 { n_log = 1, log1 = [tick], log2 = l1 }
243   | otherwise             = sc1 { n_log = nl+1, log1 = tick : l1 }
244   where
245     sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
246
247 doTick tick sc = VerySimplNonZero       -- The very simple case
248
249
250 -- Don't use plusFM_C because that's lazy, and we want to 
251 -- be pretty strict here!
252 addTick :: TickCounts -> Tick -> TickCounts
253 addTick fm tick = case lookupFM fm tick of
254                         Nothing -> addToFM fm tick 1
255                         Just n  -> n1 `seq` addToFM fm tick n1
256                                 where
257                                    n1 = n+1
258
259
260 plusSimplCount sc1@(SimplCount { ticks = tks1, details = dts1 })
261                sc2@(SimplCount { ticks = tks2, details = dts2 })
262   = log_base { ticks = tks1 + tks2, details = plusFM_C (+) dts1 dts2 }
263   where
264         -- A hackish way of getting recent log info
265     log_base | null (log1 sc2) = sc1    -- Nothing at all in sc2
266              | null (log2 sc2) = sc2 { log2 = log1 sc1 }
267              | otherwise       = sc2
268
269 plusSimplCount VerySimplZero VerySimplZero = VerySimplZero
270 plusSimplCount sc1           sc2           = VerySimplNonZero
271
272 pprSimplCount VerySimplZero    = ptext SLIT("Total ticks: ZERO!")
273 pprSimplCount VerySimplNonZero = ptext SLIT("Total ticks: NON-ZERO!")
274 pprSimplCount (SimplCount { ticks = tks, details = dts, log1 = l1, log2 = l2 })
275   = vcat [ptext SLIT("Total ticks:    ") <+> int tks,
276           text "",
277           pprTickCounts (fmToList dts),
278           if verboseSimplStats then
279                 vcat [text "",
280                       ptext SLIT("Log (most recent first)"),
281                       nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
282           else empty
283     ]
284
285 pprTickCounts :: [(Tick,Int)] -> SDoc
286 pprTickCounts [] = empty
287 pprTickCounts ((tick1,n1):ticks)
288   = vcat [int tot_n <+> text (tickString tick1),
289           pprTCDetails real_these,
290           pprTickCounts others
291     ]
292   where
293     tick1_tag           = tickToTag tick1
294     (these, others)     = span same_tick ticks
295     real_these          = (tick1,n1):these
296     same_tick (tick2,_) = tickToTag tick2 == tick1_tag
297     tot_n               = sum [n | (_,n) <- real_these]
298
299 pprTCDetails ticks@((tick,_):_)
300   | verboseSimplStats || isRuleFired tick
301   = nest 4 (vcat [int n <+> pprTickCts tick | (tick,n) <- ticks])
302   | otherwise
303   = empty
304 \end{code}
305
306 %************************************************************************
307 %*                                                                      *
308 \subsection{Ticks}
309 %*                                                                      *
310 %************************************************************************
311
312 \begin{code}
313 data Tick
314   = PreInlineUnconditionally    Id
315   | PostInlineUnconditionally   Id
316
317   | UnfoldingDone               Id
318   | RuleFired                   FastString      -- Rule name
319
320   | LetFloatFromLet
321   | EtaExpansion                Id      -- LHS binder
322   | EtaReduction                Id      -- Binder on outer lambda
323   | BetaReduction               Id      -- Lambda binder
324
325
326   | CaseOfCase                  Id      -- Bndr on *inner* case
327   | KnownBranch                 Id      -- Case binder
328   | CaseMerge                   Id      -- Binder on outer case
329   | AltMerge                    Id      -- Case binder
330   | CaseElim                    Id      -- Case binder
331   | CaseIdentity                Id      -- Case binder
332   | FillInCaseDefault           Id      -- Case binder
333
334   | BottomFound         
335   | SimplifierDone              -- Ticked at each iteration of the simplifier
336
337 isRuleFired (RuleFired _) = True
338 isRuleFired other         = False
339
340 instance Outputable Tick where
341   ppr tick = text (tickString tick) <+> pprTickCts tick
342
343 instance Eq Tick where
344   a == b = case a `cmpTick` b of { EQ -> True; other -> False }
345
346 instance Ord Tick where
347   compare = cmpTick
348
349 tickToTag :: Tick -> Int
350 tickToTag (PreInlineUnconditionally _)  = 0
351 tickToTag (PostInlineUnconditionally _) = 1
352 tickToTag (UnfoldingDone _)             = 2
353 tickToTag (RuleFired _)                 = 3
354 tickToTag LetFloatFromLet               = 4
355 tickToTag (EtaExpansion _)              = 5
356 tickToTag (EtaReduction _)              = 6
357 tickToTag (BetaReduction _)             = 7
358 tickToTag (CaseOfCase _)                = 8
359 tickToTag (KnownBranch _)               = 9
360 tickToTag (CaseMerge _)                 = 10
361 tickToTag (CaseElim _)                  = 11
362 tickToTag (CaseIdentity _)              = 12
363 tickToTag (FillInCaseDefault _)         = 13
364 tickToTag BottomFound                   = 14
365 tickToTag SimplifierDone                = 16
366 tickToTag (AltMerge _)                  = 17
367
368 tickString :: Tick -> String
369 tickString (PreInlineUnconditionally _) = "PreInlineUnconditionally"
370 tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
371 tickString (UnfoldingDone _)            = "UnfoldingDone"
372 tickString (RuleFired _)                = "RuleFired"
373 tickString LetFloatFromLet              = "LetFloatFromLet"
374 tickString (EtaExpansion _)             = "EtaExpansion"
375 tickString (EtaReduction _)             = "EtaReduction"
376 tickString (BetaReduction _)            = "BetaReduction"
377 tickString (CaseOfCase _)               = "CaseOfCase"
378 tickString (KnownBranch _)              = "KnownBranch"
379 tickString (CaseMerge _)                = "CaseMerge"
380 tickString (AltMerge _)                 = "AltMerge"
381 tickString (CaseElim _)                 = "CaseElim"
382 tickString (CaseIdentity _)             = "CaseIdentity"
383 tickString (FillInCaseDefault _)        = "FillInCaseDefault"
384 tickString BottomFound                  = "BottomFound"
385 tickString SimplifierDone               = "SimplifierDone"
386
387 pprTickCts :: Tick -> SDoc
388 pprTickCts (PreInlineUnconditionally v) = ppr v
389 pprTickCts (PostInlineUnconditionally v)= ppr v
390 pprTickCts (UnfoldingDone v)            = ppr v
391 pprTickCts (RuleFired v)                = ppr v
392 pprTickCts LetFloatFromLet              = empty
393 pprTickCts (EtaExpansion v)             = ppr v
394 pprTickCts (EtaReduction v)             = ppr v
395 pprTickCts (BetaReduction v)            = ppr v
396 pprTickCts (CaseOfCase v)               = ppr v
397 pprTickCts (KnownBranch v)              = ppr v
398 pprTickCts (CaseMerge v)                = ppr v
399 pprTickCts (AltMerge v)                 = ppr v
400 pprTickCts (CaseElim v)                 = ppr v
401 pprTickCts (CaseIdentity v)             = ppr v
402 pprTickCts (FillInCaseDefault v)        = ppr v
403 pprTickCts other                        = empty
404
405 cmpTick :: Tick -> Tick -> Ordering
406 cmpTick a b = case (tickToTag a `compare` tickToTag b) of
407                 GT -> GT
408                 EQ | isRuleFired a || verboseSimplStats -> cmpEqTick a b
409                    | otherwise                          -> EQ
410                 LT -> LT
411         -- Always distinguish RuleFired, so that the stats
412         -- can report them even in non-verbose mode
413
414 cmpEqTick :: Tick -> Tick -> Ordering
415 cmpEqTick (PreInlineUnconditionally a)  (PreInlineUnconditionally b)    = a `compare` b
416 cmpEqTick (PostInlineUnconditionally a) (PostInlineUnconditionally b)   = a `compare` b
417 cmpEqTick (UnfoldingDone a)             (UnfoldingDone b)               = a `compare` b
418 cmpEqTick (RuleFired a)                 (RuleFired b)                   = a `compare` b
419 cmpEqTick (EtaExpansion a)              (EtaExpansion b)                = a `compare` b
420 cmpEqTick (EtaReduction a)              (EtaReduction b)                = a `compare` b
421 cmpEqTick (BetaReduction a)             (BetaReduction b)               = a `compare` b
422 cmpEqTick (CaseOfCase a)                (CaseOfCase b)                  = a `compare` b
423 cmpEqTick (KnownBranch a)               (KnownBranch b)                 = a `compare` b
424 cmpEqTick (CaseMerge a)                 (CaseMerge b)                   = a `compare` b
425 cmpEqTick (AltMerge a)                  (AltMerge b)                    = a `compare` b
426 cmpEqTick (CaseElim a)                  (CaseElim b)                    = a `compare` b
427 cmpEqTick (CaseIdentity a)              (CaseIdentity b)                = a `compare` b
428 cmpEqTick (FillInCaseDefault a)         (FillInCaseDefault b)           = a `compare` b
429 cmpEqTick other1                        other2                          = EQ
430 \end{code}
431
432
433 %************************************************************************
434 %*                                                                      *
435 \subsubsection{Command-line switches}
436 %*                                                                      *
437 %************************************************************************
438
439 \begin{code}
440 type SwitchChecker = SimplifierSwitch -> SwitchResult
441
442 data SwitchResult
443   = SwBool      Bool            -- on/off
444   | SwString    FastString      -- nothing or a String
445   | SwInt       Int             -- nothing or an Int
446
447 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
448 isAmongSimpl on_switches                -- Switches mentioned later occur *earlier*
449                                         -- in the list; defaults right at the end.
450   = let
451         tidied_on_switches = foldl rm_dups [] on_switches
452                 -- The fold*l* ensures that we keep the latest switches;
453                 -- ie the ones that occur earliest in the list.
454
455         sw_tbl :: Array Int SwitchResult
456         sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
457                         all_undefined)
458                  // defined_elems
459
460         all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
461
462         defined_elems = map mk_assoc_elem tidied_on_switches
463     in
464     -- (avoid some unboxing, bounds checking, and other horrible things:)
465     case sw_tbl of { Array _ _ stuff ->
466     \ switch ->
467         case (indexArray# stuff (tagOf_SimplSwitch switch)) of
468           (# v #) -> v
469     }
470   where
471     mk_assoc_elem k@(MaxSimplifierIterations lvl)
472         = (iBox (tagOf_SimplSwitch k), SwInt lvl)
473     mk_assoc_elem k
474         = (iBox (tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
475
476     -- cannot have duplicates if we are going to use the array thing
477     rm_dups switches_so_far switch
478       = if switch `is_elem` switches_so_far
479         then switches_so_far
480         else switch : switches_so_far
481       where
482         sw `is_elem` []     = False
483         sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) ==# (tagOf_SimplSwitch s)
484                             || sw `is_elem` ss
485 \end{code}
486
487 \begin{code}
488 getSimplIntSwitch :: SwitchChecker -> (Int-> SimplifierSwitch) -> Int
489 getSimplIntSwitch chkr switch
490   = expectJust "getSimplIntSwitch" (intSwitchSet chkr switch)
491
492 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
493
494 switchIsOn lookup_fn switch
495   = case (lookup_fn switch) of
496       SwBool False -> False
497       _            -> True
498
499 intSwitchSet :: (switch -> SwitchResult)
500              -> (Int -> switch)
501              -> Maybe Int
502
503 intSwitchSet lookup_fn switch
504   = case (lookup_fn (switch (panic "intSwitchSet"))) of
505       SwInt int -> Just int
506       _         -> Nothing
507 \end{code}
508
509
510 These things behave just like enumeration types.
511
512 \begin{code}
513 instance Eq SimplifierSwitch where
514     a == b = tagOf_SimplSwitch a ==# tagOf_SimplSwitch b
515
516 instance Ord SimplifierSwitch where
517     a <  b  = tagOf_SimplSwitch a <# tagOf_SimplSwitch b
518     a <= b  = tagOf_SimplSwitch a <=# tagOf_SimplSwitch b
519
520
521 tagOf_SimplSwitch (MaxSimplifierIterations _)   = _ILIT(1)
522 tagOf_SimplSwitch NoCaseOfCase                  = _ILIT(2)
523
524 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
525
526 lAST_SIMPL_SWITCH_TAG = 2
527 \end{code}
528