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 getUniqueSmpl, getUniquesSmpl, getUniqSupplySmpl, 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 )
41 import UniqSupply ( uniqsFromSupply, uniqFromSupply, splitUniqSupply,
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 )
54 import Data.Array.Base (unsafeAt)
56 infixr 0 `thenSmpl`, `thenSmpl_`
59 %************************************************************************
61 \subsection{Monad plumbing}
63 %************************************************************************
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.)
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
74 -> (result, UniqSupply, SimplCount)}
76 data SimplTopEnv = STE { st_flags :: DynFlags
77 , st_rules :: RuleBase
78 , st_fams :: (FamInstEnv, FamInstEnv) }
82 initSmpl :: DynFlags -> RuleBase -> (FamInstEnv, FamInstEnv)
83 -> UniqSupply -- No init count; set to 0
87 initSmpl dflags rules fam_envs us m
88 = case unSM m env us (zeroSimplCount dflags) of
89 (result, _, count) -> (result, count)
91 env = STE { st_flags = dflags, st_rules = rules, st_fams = fam_envs }
93 {-# INLINE thenSmpl #-}
94 {-# INLINE thenSmpl_ #-}
95 {-# INLINE returnSmpl #-}
97 instance Monad SimplM where
102 returnSmpl :: a -> SimplM a
103 returnSmpl e = SM (\ st_env us sc -> (e, us, sc))
105 thenSmpl :: SimplM a -> (a -> SimplM b) -> SimplM b
106 thenSmpl_ :: SimplM a -> SimplM b -> SimplM b
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 )
114 = SM (\st_env us0 sc0 ->
115 case (unSM m st_env us0 sc0) of
116 (_, us1, sc1) -> unSM k st_env us1 sc1)
121 mapSmpl :: (a -> SimplM b) -> [a] -> SimplM [b]
122 mapAndUnzipSmpl :: (a -> SimplM (b, c)) -> [a] -> SimplM ([b],[c])
124 mapSmpl f [] = returnSmpl []
126 = f x `thenSmpl` \ x' ->
127 mapSmpl f xs `thenSmpl` \ xs' ->
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)
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')
144 %************************************************************************
146 \subsection{The unique supply}
148 %************************************************************************
151 getUniqSupplySmpl :: SimplM UniqSupply
153 = SM (\st_env us sc -> case splitUniqSupply us of
154 (us1, us2) -> (us1, us2, sc))
156 getUniqueSmpl :: SimplM Unique
158 = SM (\st_env us sc -> case splitUniqSupply us of
159 (us1, us2) -> (uniqFromSupply us1, us2, sc))
161 getUniquesSmpl :: SimplM [Unique]
163 = SM (\st_env us sc -> case splitUniqSupply us of
164 (us1, us2) -> (uniqsFromSupply us1, us2, sc))
166 getDOptsSmpl :: SimplM DynFlags
167 getDOptsSmpl = SM (\st_env us sc -> (st_flags st_env, us, sc))
169 getRules :: SimplM RuleBase
170 getRules = SM (\st_env us sc -> (st_rules st_env, us, sc))
172 getFamEnvs :: SimplM (FamInstEnv, FamInstEnv)
173 getFamEnvs = SM (\st_env us sc -> (st_fams st_env, us, sc))
175 newId :: FastString -> Type -> SimplM Id
176 newId fs ty = getUniqueSmpl `thenSmpl` \ uniq ->
177 returnSmpl (mkSysLocal fs uniq ty)
181 %************************************************************************
183 \subsection{Counting up what we've done}
185 %************************************************************************
188 getSimplCount :: SimplM SimplCount
189 getSimplCount = SM (\st_env us sc -> (sc, us, sc))
191 tick :: Tick -> SimplM ()
193 = SM (\st_env us sc -> let sc' = doTick t sc
194 in sc' `seq` ((), us, sc'))
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
200 = SM (\st_env us sc -> let sc' = doFreeTick t sc
201 in sc' `seq` ((), us, sc'))
205 verboseSimplStats = opt_PprStyle_Debug -- For now, anyway
207 zeroSimplCount :: DynFlags -> SimplCount
208 isZeroSimplCount :: SimplCount -> Bool
209 pprSimplCount :: SimplCount -> SDoc
210 doTick, doFreeTick :: Tick -> SimplCount -> SimplCount
211 plusSimplCount :: SimplCount -> SimplCount -> SimplCount
215 data SimplCount = VerySimplZero -- These two are used when
216 | VerySimplNonZero -- we are only interested in
220 ticks :: !Int, -- Total ticks
221 details :: !TickCounts, -- How many of each type
223 log1 :: [Tick], -- Last N events; <= opt_HistorySize
224 log2 :: [Tick] -- Last opt_HistorySize events before that
227 type TickCounts = FiniteMap Tick Int
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 = []}
238 isZeroSimplCount VerySimplZero = True
239 isZeroSimplCount (SimplCount { ticks = 0 }) = True
240 isZeroSimplCount other = False
242 doFreeTick tick sc@SimplCount { details = dts }
243 = dts' `seqFM` sc { details = dts' }
245 dts' = dts `addTick` tick
246 doFreeTick tick sc = sc
248 -- Gross hack to persuade GHC 3.03 to do this important seq
249 seqFM fm x | isEmptyFM fm = x
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 }
256 sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
258 doTick tick sc = VerySimplNonZero -- The very simple case
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
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 }
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 }
280 plusSimplCount VerySimplZero VerySimplZero = VerySimplZero
281 plusSimplCount sc1 sc2 = VerySimplNonZero
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,
288 pprTickCounts (fmToList dts),
289 if verboseSimplStats then
291 ptext SLIT("Log (most recent first)"),
292 nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
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,
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]
310 pprTCDetails ticks@((tick,_):_)
311 | verboseSimplStats || isRuleFired tick
312 = nest 4 (vcat [int n <+> pprTickCts tick | (tick,n) <- ticks])
317 %************************************************************************
321 %************************************************************************
325 = PreInlineUnconditionally Id
326 | PostInlineUnconditionally Id
329 | RuleFired FastString -- Rule name
332 | EtaExpansion Id -- LHS binder
333 | EtaReduction Id -- Binder on outer lambda
334 | BetaReduction Id -- Lambda binder
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
346 | SimplifierDone -- Ticked at each iteration of the simplifier
348 isRuleFired (RuleFired _) = True
349 isRuleFired other = False
351 instance Outputable Tick where
352 ppr tick = text (tickString tick) <+> pprTickCts tick
354 instance Eq Tick where
355 a == b = case a `cmpTick` b of { EQ -> True; other -> False }
357 instance Ord Tick where
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
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"
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
416 cmpTick :: Tick -> Tick -> Ordering
417 cmpTick a b = case (tickToTag a `compare` tickToTag b) of
419 EQ | isRuleFired a || verboseSimplStats -> cmpEqTick a b
422 -- Always distinguish RuleFired, so that the stats
423 -- can report them even in non-verbose mode
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
444 %************************************************************************
446 \subsubsection{Command-line switches}
448 %************************************************************************
451 type SwitchChecker = SimplifierSwitch -> SwitchResult
454 = SwBool Bool -- on/off
455 | SwString FastString -- nothing or a String
456 | SwInt Int -- nothing or an Int
458 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
459 isAmongSimpl on_switches -- Switches mentioned later occur *earlier*
460 -- in the list; defaults right at the end.
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.
466 sw_tbl :: Array Int SwitchResult
467 sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
471 all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
473 defined_elems = map mk_assoc_elem tidied_on_switches
475 -- (avoid some unboxing, bounds checking, and other horrible things:)
476 \ switch -> unsafeAt sw_tbl $ iBox (tagOf_SimplSwitch switch)
478 mk_assoc_elem k@(MaxSimplifierIterations lvl)
479 = (iBox (tagOf_SimplSwitch k), SwInt lvl)
481 = (iBox (tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
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
487 else switch : switches_so_far
489 sw `is_elem` [] = False
490 sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) ==# (tagOf_SimplSwitch s)
495 getSimplIntSwitch :: SwitchChecker -> (Int-> SimplifierSwitch) -> Int
496 getSimplIntSwitch chkr switch
497 = expectJust "getSimplIntSwitch" (intSwitchSet chkr switch)
499 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
501 switchIsOn lookup_fn switch
502 = case (lookup_fn switch) of
503 SwBool False -> False
506 intSwitchSet :: (switch -> SwitchResult)
510 intSwitchSet lookup_fn switch
511 = case (lookup_fn (switch (panic "intSwitchSet"))) of
512 SwInt int -> Just int
517 These things behave just like enumeration types.
520 instance Eq SimplifierSwitch where
521 a == b = tagOf_SimplSwitch a ==# tagOf_SimplSwitch b
523 instance Ord SimplifierSwitch where
524 a < b = tagOf_SimplSwitch a <# tagOf_SimplSwitch b
525 a <= b = tagOf_SimplSwitch a <=# tagOf_SimplSwitch b
528 tagOf_SimplSwitch (MaxSimplifierIterations _) = _ILIT(1)
529 tagOf_SimplSwitch NoCaseOfCase = _ILIT(2)
531 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
533 lAST_SIMPL_SWITCH_TAG = 2