2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplMonad]{The simplifier Monad}
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
17 initSmpl, returnSmpl, thenSmpl, thenSmpl_,
18 mapSmpl, mapAndUnzipSmpl, mapAccumLSmpl,
19 getDOptsSmpl, getRules, getFamEnvs,
22 MonadUnique(..), newId,
27 getSimplCount, zeroSimplCount, pprSimplCount,
28 plusSimplCount, isZeroSimplCount,
31 SwitchChecker, SwitchResult(..), getSimplIntSwitch,
32 isAmongSimpl, intSwitchSet, switchIsOn
35 #include "HsVersions.h"
37 import Id ( Id, mkSysLocal )
39 import FamInstEnv ( FamInstEnv )
40 import Rules ( RuleBase )
42 import DynFlags ( SimplifierSwitch(..), DynFlags, DynFlag(..), dopt )
43 import StaticFlags ( opt_PprStyle_Debug, opt_HistorySize )
44 import Unique ( Unique )
45 import Maybes ( expectJust )
46 import FiniteMap ( FiniteMap, emptyFM, isEmptyFM, lookupFM, addToFM, plusFM_C, fmToList )
47 import FastString ( FastString )
52 import Data.Array.Base (unsafeAt)
54 infixr 0 `thenSmpl`, `thenSmpl_`
57 %************************************************************************
59 \subsection{Monad plumbing}
61 %************************************************************************
63 For the simplifier monad, we want to {\em thread} a unique supply and a counter.
64 (Command-line switches move around through the explicitly-passed SimplEnv.)
68 = SM { unSM :: SimplTopEnv -- Envt that does not change much
69 -> UniqSupply -- We thread the unique supply because
70 -- constantly splitting it is rather expensive
72 -> (result, UniqSupply, SimplCount)}
74 data SimplTopEnv = STE { st_flags :: DynFlags
75 , st_rules :: RuleBase
76 , st_fams :: (FamInstEnv, FamInstEnv) }
80 initSmpl :: DynFlags -> RuleBase -> (FamInstEnv, FamInstEnv)
81 -> UniqSupply -- No init count; set to 0
85 initSmpl dflags rules fam_envs us m
86 = case unSM m env us (zeroSimplCount dflags) of
87 (result, _, count) -> (result, count)
89 env = STE { st_flags = dflags, st_rules = rules, st_fams = fam_envs }
91 {-# INLINE thenSmpl #-}
92 {-# INLINE thenSmpl_ #-}
93 {-# INLINE returnSmpl #-}
95 instance Monad SimplM where
100 returnSmpl :: a -> SimplM a
101 returnSmpl e = SM (\ st_env us sc -> (e, us, sc))
103 thenSmpl :: SimplM a -> (a -> SimplM b) -> SimplM b
104 thenSmpl_ :: SimplM a -> SimplM b -> SimplM b
107 = SM (\ st_env us0 sc0 ->
108 case (unSM m st_env us0 sc0) of
109 (m_result, us1, sc1) -> unSM (k m_result) st_env us1 sc1 )
112 = SM (\st_env us0 sc0 ->
113 case (unSM m st_env us0 sc0) of
114 (_, us1, sc1) -> unSM k st_env us1 sc1)
119 mapSmpl :: (a -> SimplM b) -> [a] -> SimplM [b]
120 mapAndUnzipSmpl :: (a -> SimplM (b, c)) -> [a] -> SimplM ([b],[c])
122 mapSmpl f [] = returnSmpl []
124 = f x `thenSmpl` \ x' ->
125 mapSmpl f xs `thenSmpl` \ xs' ->
128 mapAndUnzipSmpl f [] = returnSmpl ([],[])
129 mapAndUnzipSmpl f (x:xs)
130 = f x `thenSmpl` \ (r1, r2) ->
131 mapAndUnzipSmpl f xs `thenSmpl` \ (rs1, rs2) ->
132 returnSmpl (r1:rs1, r2:rs2)
134 mapAccumLSmpl :: (acc -> b -> SimplM (acc,c)) -> acc -> [b] -> SimplM (acc, [c])
135 mapAccumLSmpl f acc [] = returnSmpl (acc, [])
136 mapAccumLSmpl f acc (x:xs) = f acc x `thenSmpl` \ (acc', x') ->
137 mapAccumLSmpl f acc' xs `thenSmpl` \ (acc'', xs') ->
138 returnSmpl (acc'', x':xs')
142 %************************************************************************
144 \subsection{The unique supply}
146 %************************************************************************
149 instance MonadUnique SimplM where
151 = SM (\st_env us sc -> case splitUniqSupply us of
152 (us1, us2) -> (us1, us2, sc))
155 = SM (\st_env us sc -> case splitUniqSupply us of
156 (us1, us2) -> (uniqFromSupply us1, us2, sc))
159 = SM (\st_env us sc -> case splitUniqSupply us of
160 (us1, us2) -> (uniqsFromSupply us1, us2, sc))
162 getDOptsSmpl :: SimplM DynFlags
163 getDOptsSmpl = SM (\st_env us sc -> (st_flags st_env, us, sc))
165 getRules :: SimplM RuleBase
166 getRules = SM (\st_env us sc -> (st_rules st_env, us, sc))
168 getFamEnvs :: SimplM (FamInstEnv, FamInstEnv)
169 getFamEnvs = SM (\st_env us sc -> (st_fams st_env, us, sc))
171 newId :: FastString -> Type -> SimplM Id
172 newId fs ty = do uniq <- getUniqueM
173 return (mkSysLocal fs uniq ty)
177 %************************************************************************
179 \subsection{Counting up what we've done}
181 %************************************************************************
184 getSimplCount :: SimplM SimplCount
185 getSimplCount = SM (\st_env us sc -> (sc, us, sc))
187 tick :: Tick -> SimplM ()
189 = SM (\st_env us sc -> let sc' = doTick t sc
190 in sc' `seq` ((), us, sc'))
192 freeTick :: Tick -> SimplM ()
193 -- Record a tick, but don't add to the total tick count, which is
194 -- used to decide when nothing further has happened
196 = SM (\st_env us sc -> let sc' = doFreeTick t sc
197 in sc' `seq` ((), us, sc'))
201 verboseSimplStats = opt_PprStyle_Debug -- For now, anyway
203 zeroSimplCount :: DynFlags -> SimplCount
204 isZeroSimplCount :: SimplCount -> Bool
205 pprSimplCount :: SimplCount -> SDoc
206 doTick, doFreeTick :: Tick -> SimplCount -> SimplCount
207 plusSimplCount :: SimplCount -> SimplCount -> SimplCount
211 data SimplCount = VerySimplZero -- These two are used when
212 | VerySimplNonZero -- we are only interested in
216 ticks :: !Int, -- Total ticks
217 details :: !TickCounts, -- How many of each type
219 log1 :: [Tick], -- Last N events; <= opt_HistorySize
220 log2 :: [Tick] -- Last opt_HistorySize events before that
223 type TickCounts = FiniteMap Tick Int
225 zeroSimplCount dflags
226 -- This is where we decide whether to do
227 -- the VerySimpl version or the full-stats version
228 | dopt Opt_D_dump_simpl_stats dflags
229 = SimplCount {ticks = 0, details = emptyFM,
230 n_log = 0, log1 = [], log2 = []}
234 isZeroSimplCount VerySimplZero = True
235 isZeroSimplCount (SimplCount { ticks = 0 }) = True
236 isZeroSimplCount other = False
238 doFreeTick tick sc@SimplCount { details = dts }
239 = dts' `seqFM` sc { details = dts' }
241 dts' = dts `addTick` tick
242 doFreeTick tick sc = sc
244 -- Gross hack to persuade GHC 3.03 to do this important seq
245 seqFM fm x | isEmptyFM fm = x
248 doTick tick sc@SimplCount { ticks = tks, details = dts, n_log = nl, log1 = l1, log2 = l2 }
249 | nl >= opt_HistorySize = sc1 { n_log = 1, log1 = [tick], log2 = l1 }
250 | otherwise = sc1 { n_log = nl+1, log1 = tick : l1 }
252 sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
254 doTick tick sc = VerySimplNonZero -- The very simple case
257 -- Don't use plusFM_C because that's lazy, and we want to
258 -- be pretty strict here!
259 addTick :: TickCounts -> Tick -> TickCounts
260 addTick fm tick = case lookupFM fm tick of
261 Nothing -> addToFM fm tick 1
262 Just n -> n1 `seq` addToFM fm tick n1
267 plusSimplCount sc1@(SimplCount { ticks = tks1, details = dts1 })
268 sc2@(SimplCount { ticks = tks2, details = dts2 })
269 = log_base { ticks = tks1 + tks2, details = plusFM_C (+) dts1 dts2 }
271 -- A hackish way of getting recent log info
272 log_base | null (log1 sc2) = sc1 -- Nothing at all in sc2
273 | null (log2 sc2) = sc2 { log2 = log1 sc1 }
276 plusSimplCount VerySimplZero VerySimplZero = VerySimplZero
277 plusSimplCount sc1 sc2 = VerySimplNonZero
279 pprSimplCount VerySimplZero = ptext SLIT("Total ticks: ZERO!")
280 pprSimplCount VerySimplNonZero = ptext SLIT("Total ticks: NON-ZERO!")
281 pprSimplCount (SimplCount { ticks = tks, details = dts, log1 = l1, log2 = l2 })
282 = vcat [ptext SLIT("Total ticks: ") <+> int tks,
284 pprTickCounts (fmToList dts),
285 if verboseSimplStats then
287 ptext SLIT("Log (most recent first)"),
288 nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
292 pprTickCounts :: [(Tick,Int)] -> SDoc
293 pprTickCounts [] = empty
294 pprTickCounts ((tick1,n1):ticks)
295 = vcat [int tot_n <+> text (tickString tick1),
296 pprTCDetails real_these,
300 tick1_tag = tickToTag tick1
301 (these, others) = span same_tick ticks
302 real_these = (tick1,n1):these
303 same_tick (tick2,_) = tickToTag tick2 == tick1_tag
304 tot_n = sum [n | (_,n) <- real_these]
306 pprTCDetails ticks@((tick,_):_)
307 | verboseSimplStats || isRuleFired tick
308 = nest 4 (vcat [int n <+> pprTickCts tick | (tick,n) <- ticks])
313 %************************************************************************
317 %************************************************************************
321 = PreInlineUnconditionally Id
322 | PostInlineUnconditionally Id
325 | RuleFired FastString -- Rule name
328 | EtaExpansion Id -- LHS binder
329 | EtaReduction Id -- Binder on outer lambda
330 | BetaReduction Id -- Lambda binder
333 | CaseOfCase Id -- Bndr on *inner* case
334 | KnownBranch Id -- Case binder
335 | CaseMerge Id -- Binder on outer case
336 | AltMerge Id -- Case binder
337 | CaseElim Id -- Case binder
338 | CaseIdentity Id -- Case binder
339 | FillInCaseDefault Id -- Case binder
342 | SimplifierDone -- Ticked at each iteration of the simplifier
344 isRuleFired (RuleFired _) = True
345 isRuleFired other = False
347 instance Outputable Tick where
348 ppr tick = text (tickString tick) <+> pprTickCts tick
350 instance Eq Tick where
351 a == b = case a `cmpTick` b of { EQ -> True; other -> False }
353 instance Ord Tick where
356 tickToTag :: Tick -> Int
357 tickToTag (PreInlineUnconditionally _) = 0
358 tickToTag (PostInlineUnconditionally _) = 1
359 tickToTag (UnfoldingDone _) = 2
360 tickToTag (RuleFired _) = 3
361 tickToTag LetFloatFromLet = 4
362 tickToTag (EtaExpansion _) = 5
363 tickToTag (EtaReduction _) = 6
364 tickToTag (BetaReduction _) = 7
365 tickToTag (CaseOfCase _) = 8
366 tickToTag (KnownBranch _) = 9
367 tickToTag (CaseMerge _) = 10
368 tickToTag (CaseElim _) = 11
369 tickToTag (CaseIdentity _) = 12
370 tickToTag (FillInCaseDefault _) = 13
371 tickToTag BottomFound = 14
372 tickToTag SimplifierDone = 16
373 tickToTag (AltMerge _) = 17
375 tickString :: Tick -> String
376 tickString (PreInlineUnconditionally _) = "PreInlineUnconditionally"
377 tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
378 tickString (UnfoldingDone _) = "UnfoldingDone"
379 tickString (RuleFired _) = "RuleFired"
380 tickString LetFloatFromLet = "LetFloatFromLet"
381 tickString (EtaExpansion _) = "EtaExpansion"
382 tickString (EtaReduction _) = "EtaReduction"
383 tickString (BetaReduction _) = "BetaReduction"
384 tickString (CaseOfCase _) = "CaseOfCase"
385 tickString (KnownBranch _) = "KnownBranch"
386 tickString (CaseMerge _) = "CaseMerge"
387 tickString (AltMerge _) = "AltMerge"
388 tickString (CaseElim _) = "CaseElim"
389 tickString (CaseIdentity _) = "CaseIdentity"
390 tickString (FillInCaseDefault _) = "FillInCaseDefault"
391 tickString BottomFound = "BottomFound"
392 tickString SimplifierDone = "SimplifierDone"
394 pprTickCts :: Tick -> SDoc
395 pprTickCts (PreInlineUnconditionally v) = ppr v
396 pprTickCts (PostInlineUnconditionally v)= ppr v
397 pprTickCts (UnfoldingDone v) = ppr v
398 pprTickCts (RuleFired v) = ppr v
399 pprTickCts LetFloatFromLet = empty
400 pprTickCts (EtaExpansion v) = ppr v
401 pprTickCts (EtaReduction v) = ppr v
402 pprTickCts (BetaReduction v) = ppr v
403 pprTickCts (CaseOfCase v) = ppr v
404 pprTickCts (KnownBranch v) = ppr v
405 pprTickCts (CaseMerge v) = ppr v
406 pprTickCts (AltMerge v) = ppr v
407 pprTickCts (CaseElim v) = ppr v
408 pprTickCts (CaseIdentity v) = ppr v
409 pprTickCts (FillInCaseDefault v) = ppr v
410 pprTickCts other = empty
412 cmpTick :: Tick -> Tick -> Ordering
413 cmpTick a b = case (tickToTag a `compare` tickToTag b) of
415 EQ | isRuleFired a || verboseSimplStats -> cmpEqTick a b
418 -- Always distinguish RuleFired, so that the stats
419 -- can report them even in non-verbose mode
421 cmpEqTick :: Tick -> Tick -> Ordering
422 cmpEqTick (PreInlineUnconditionally a) (PreInlineUnconditionally b) = a `compare` b
423 cmpEqTick (PostInlineUnconditionally a) (PostInlineUnconditionally b) = a `compare` b
424 cmpEqTick (UnfoldingDone a) (UnfoldingDone b) = a `compare` b
425 cmpEqTick (RuleFired a) (RuleFired b) = a `compare` b
426 cmpEqTick (EtaExpansion a) (EtaExpansion b) = a `compare` b
427 cmpEqTick (EtaReduction a) (EtaReduction b) = a `compare` b
428 cmpEqTick (BetaReduction a) (BetaReduction b) = a `compare` b
429 cmpEqTick (CaseOfCase a) (CaseOfCase b) = a `compare` b
430 cmpEqTick (KnownBranch a) (KnownBranch b) = a `compare` b
431 cmpEqTick (CaseMerge a) (CaseMerge b) = a `compare` b
432 cmpEqTick (AltMerge a) (AltMerge b) = a `compare` b
433 cmpEqTick (CaseElim a) (CaseElim b) = a `compare` b
434 cmpEqTick (CaseIdentity a) (CaseIdentity b) = a `compare` b
435 cmpEqTick (FillInCaseDefault a) (FillInCaseDefault b) = a `compare` b
436 cmpEqTick other1 other2 = EQ
440 %************************************************************************
442 \subsubsection{Command-line switches}
444 %************************************************************************
447 type SwitchChecker = SimplifierSwitch -> SwitchResult
450 = SwBool Bool -- on/off
451 | SwString FastString -- nothing or a String
452 | SwInt Int -- nothing or an Int
454 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
455 isAmongSimpl on_switches -- Switches mentioned later occur *earlier*
456 -- in the list; defaults right at the end.
458 tidied_on_switches = foldl rm_dups [] on_switches
459 -- The fold*l* ensures that we keep the latest switches;
460 -- ie the ones that occur earliest in the list.
462 sw_tbl :: Array Int SwitchResult
463 sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
467 all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
469 defined_elems = map mk_assoc_elem tidied_on_switches
471 -- (avoid some unboxing, bounds checking, and other horrible things:)
472 \ switch -> unsafeAt sw_tbl $ iBox (tagOf_SimplSwitch switch)
474 mk_assoc_elem k@(MaxSimplifierIterations lvl)
475 = (iBox (tagOf_SimplSwitch k), SwInt lvl)
477 = (iBox (tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
479 -- cannot have duplicates if we are going to use the array thing
480 rm_dups switches_so_far switch
481 = if switch `is_elem` switches_so_far
483 else switch : switches_so_far
485 sw `is_elem` [] = False
486 sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) ==# (tagOf_SimplSwitch s)
491 getSimplIntSwitch :: SwitchChecker -> (Int-> SimplifierSwitch) -> Int
492 getSimplIntSwitch chkr switch
493 = expectJust "getSimplIntSwitch" (intSwitchSet chkr switch)
495 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
497 switchIsOn lookup_fn switch
498 = case (lookup_fn switch) of
499 SwBool False -> False
502 intSwitchSet :: (switch -> SwitchResult)
506 intSwitchSet lookup_fn switch
507 = case (lookup_fn (switch (panic "intSwitchSet"))) of
508 SwInt int -> Just int
513 These things behave just like enumeration types.
516 instance Eq SimplifierSwitch where
517 a == b = tagOf_SimplSwitch a ==# tagOf_SimplSwitch b
519 instance Ord SimplifierSwitch where
520 a < b = tagOf_SimplSwitch a <# tagOf_SimplSwitch b
521 a <= b = tagOf_SimplSwitch a <=# tagOf_SimplSwitch b
524 tagOf_SimplSwitch (MaxSimplifierIterations _) = _ILIT(1)
525 tagOf_SimplSwitch NoCaseOfCase = _ILIT(2)
527 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
529 lAST_SIMPL_SWITCH_TAG = 2