2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplMonad]{The simplifier Monad}
10 initSmpl, returnSmpl, thenSmpl, thenSmpl_,
11 mapSmpl, mapAndUnzipSmpl, mapAccumLSmpl,
12 getDOptsSmpl, getRules, getFamEnvs,
15 getUniqueSmpl, getUniquesSmpl, getUniqSupplySmpl, newId,
20 getSimplCount, zeroSimplCount, pprSimplCount,
21 plusSimplCount, isZeroSimplCount,
24 SwitchChecker, SwitchResult(..), getSimplIntSwitch,
25 isAmongSimpl, intSwitchSet, switchIsOn
28 #include "HsVersions.h"
30 import Id ( Id, mkSysLocal )
32 import FamInstEnv ( FamInstEnv )
33 import Rules ( RuleBase )
34 import UniqSupply ( uniqsFromSupply, uniqFromSupply, splitUniqSupply,
37 import DynFlags ( SimplifierSwitch(..), DynFlags, DynFlag(..), dopt )
38 import StaticFlags ( opt_PprStyle_Debug, opt_HistorySize )
39 import Unique ( Unique )
40 import Maybes ( expectJust )
41 import FiniteMap ( FiniteMap, emptyFM, isEmptyFM, lookupFM, addToFM, plusFM_C, fmToList )
42 import FastString ( FastString )
46 import GHC.Exts ( indexArray# )
48 import GHC.Arr ( Array(..) )
50 import Array ( array, (//) )
52 infixr 0 `thenSmpl`, `thenSmpl_`
55 %************************************************************************
57 \subsection{Monad plumbing}
59 %************************************************************************
61 For the simplifier monad, we want to {\em thread} a unique supply and a counter.
62 (Command-line switches move around through the explicitly-passed SimplEnv.)
66 = SM { unSM :: SimplTopEnv -- Envt that does not change much
67 -> UniqSupply -- We thread the unique supply because
68 -- constantly splitting it is rather expensive
70 -> (result, UniqSupply, SimplCount)}
72 data SimplTopEnv = STE { st_flags :: DynFlags
73 , st_rules :: RuleBase
74 , st_fams :: (FamInstEnv, FamInstEnv) }
78 initSmpl :: DynFlags -> RuleBase -> (FamInstEnv, FamInstEnv)
79 -> UniqSupply -- No init count; set to 0
83 initSmpl dflags rules fam_envs us m
84 = case unSM m env us (zeroSimplCount dflags) of
85 (result, _, count) -> (result, count)
87 env = STE { st_flags = dflags, st_rules = rules, st_fams = fam_envs }
89 {-# INLINE thenSmpl #-}
90 {-# INLINE thenSmpl_ #-}
91 {-# INLINE returnSmpl #-}
93 instance Monad SimplM where
98 returnSmpl :: a -> SimplM a
99 returnSmpl e = SM (\ st_env us sc -> (e, us, sc))
101 thenSmpl :: SimplM a -> (a -> SimplM b) -> SimplM b
102 thenSmpl_ :: SimplM a -> SimplM b -> SimplM b
105 = SM (\ st_env us0 sc0 ->
106 case (unSM m st_env us0 sc0) of
107 (m_result, us1, sc1) -> unSM (k m_result) st_env us1 sc1 )
110 = SM (\st_env us0 sc0 ->
111 case (unSM m st_env us0 sc0) of
112 (_, us1, sc1) -> unSM k st_env us1 sc1)
117 mapSmpl :: (a -> SimplM b) -> [a] -> SimplM [b]
118 mapAndUnzipSmpl :: (a -> SimplM (b, c)) -> [a] -> SimplM ([b],[c])
120 mapSmpl f [] = returnSmpl []
122 = f x `thenSmpl` \ x' ->
123 mapSmpl f xs `thenSmpl` \ xs' ->
126 mapAndUnzipSmpl f [] = returnSmpl ([],[])
127 mapAndUnzipSmpl f (x:xs)
128 = f x `thenSmpl` \ (r1, r2) ->
129 mapAndUnzipSmpl f xs `thenSmpl` \ (rs1, rs2) ->
130 returnSmpl (r1:rs1, r2:rs2)
132 mapAccumLSmpl :: (acc -> b -> SimplM (acc,c)) -> acc -> [b] -> SimplM (acc, [c])
133 mapAccumLSmpl f acc [] = returnSmpl (acc, [])
134 mapAccumLSmpl f acc (x:xs) = f acc x `thenSmpl` \ (acc', x') ->
135 mapAccumLSmpl f acc' xs `thenSmpl` \ (acc'', xs') ->
136 returnSmpl (acc'', x':xs')
140 %************************************************************************
142 \subsection{The unique supply}
144 %************************************************************************
147 getUniqSupplySmpl :: SimplM UniqSupply
149 = SM (\st_env us sc -> case splitUniqSupply us of
150 (us1, us2) -> (us1, us2, sc))
152 getUniqueSmpl :: SimplM Unique
154 = SM (\st_env us sc -> case splitUniqSupply us of
155 (us1, us2) -> (uniqFromSupply us1, us2, sc))
157 getUniquesSmpl :: SimplM [Unique]
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 = getUniqueSmpl `thenSmpl` \ uniq ->
173 returnSmpl (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 case sw_tbl of { Array _ _ stuff ->
474 case (indexArray# stuff (tagOf_SimplSwitch switch)) of
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