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