2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplMonad]{The simplifier Monad}
10 initSmpl, returnSmpl, thenSmpl, thenSmpl_,
11 mapSmpl, mapAndUnzipSmpl, mapAccumLSmpl,
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 UniqSupply ( uniqsFromSupply, uniqFromSupply, splitUniqSupply,
35 import DynFlags ( SimplifierSwitch(..), DynFlags, DynFlag(..), dopt )
36 import StaticFlags ( opt_PprStyle_Debug, opt_HistorySize )
37 import Unique ( Unique )
38 import Maybes ( expectJust )
39 import FiniteMap ( FiniteMap, emptyFM, isEmptyFM, lookupFM, addToFM, plusFM_C, fmToList )
40 import FastString ( FastString )
44 import GHC.Exts ( indexArray# )
46 #if __GLASGOW_HASKELL__ < 503
47 import PrelArr ( Array(..) )
49 import GHC.Arr ( Array(..) )
52 import Array ( array, (//) )
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 :: DynFlags -- We thread the unique supply because
69 -> UniqSupply -- constantly splitting it is rather expensive
71 -> (result, UniqSupply, SimplCount)}
76 -> UniqSupply -- No init count; set to 0
81 = case unSM m dflags us (zeroSimplCount dflags) of
82 (result, _, count) -> (result, count)
85 {-# INLINE thenSmpl #-}
86 {-# INLINE thenSmpl_ #-}
87 {-# INLINE returnSmpl #-}
89 instance Monad SimplM where
94 returnSmpl :: a -> SimplM a
95 returnSmpl e = SM (\ dflags us sc -> (e, us, sc))
97 thenSmpl :: SimplM a -> (a -> SimplM b) -> SimplM b
98 thenSmpl_ :: SimplM a -> SimplM b -> SimplM b
101 = SM (\ dflags us0 sc0 ->
102 case (unSM m dflags us0 sc0) of
103 (m_result, us1, sc1) -> unSM (k m_result) dflags us1 sc1 )
106 = SM (\dflags us0 sc0 ->
107 case (unSM m dflags us0 sc0) of
108 (_, us1, sc1) -> unSM k dflags us1 sc1)
113 mapSmpl :: (a -> SimplM b) -> [a] -> SimplM [b]
114 mapAndUnzipSmpl :: (a -> SimplM (b, c)) -> [a] -> SimplM ([b],[c])
116 mapSmpl f [] = returnSmpl []
118 = f x `thenSmpl` \ x' ->
119 mapSmpl f xs `thenSmpl` \ xs' ->
122 mapAndUnzipSmpl f [] = returnSmpl ([],[])
123 mapAndUnzipSmpl f (x:xs)
124 = f x `thenSmpl` \ (r1, r2) ->
125 mapAndUnzipSmpl f xs `thenSmpl` \ (rs1, rs2) ->
126 returnSmpl (r1:rs1, r2:rs2)
128 mapAccumLSmpl :: (acc -> b -> SimplM (acc,c)) -> acc -> [b] -> SimplM (acc, [c])
129 mapAccumLSmpl f acc [] = returnSmpl (acc, [])
130 mapAccumLSmpl f acc (x:xs) = f acc x `thenSmpl` \ (acc', x') ->
131 mapAccumLSmpl f acc' xs `thenSmpl` \ (acc'', xs') ->
132 returnSmpl (acc'', x':xs')
136 %************************************************************************
138 \subsection{The unique supply}
140 %************************************************************************
143 getUniqSupplySmpl :: SimplM UniqSupply
145 = SM (\dflags us sc -> case splitUniqSupply us of
146 (us1, us2) -> (us1, us2, sc))
148 getUniqueSmpl :: SimplM Unique
150 = SM (\dflags us sc -> case splitUniqSupply us of
151 (us1, us2) -> (uniqFromSupply us1, us2, sc))
153 getUniquesSmpl :: SimplM [Unique]
155 = SM (\dflags us sc -> case splitUniqSupply us of
156 (us1, us2) -> (uniqsFromSupply us1, us2, sc))
158 getDOptsSmpl :: SimplM DynFlags
160 = SM (\dflags us sc -> (dflags, us, sc))
162 newId :: FastString -> Type -> SimplM Id
163 newId fs ty = getUniqueSmpl `thenSmpl` \ uniq ->
164 returnSmpl (mkSysLocal fs uniq ty)
168 %************************************************************************
170 \subsection{Counting up what we've done}
172 %************************************************************************
175 getSimplCount :: SimplM SimplCount
176 getSimplCount = SM (\dflags us sc -> (sc, us, sc))
178 tick :: Tick -> SimplM ()
180 = SM (\dflags us sc -> let sc' = doTick t sc
181 in sc' `seq` ((), us, sc'))
183 freeTick :: Tick -> SimplM ()
184 -- Record a tick, but don't add to the total tick count, which is
185 -- used to decide when nothing further has happened
187 = SM (\dflags us sc -> let sc' = doFreeTick t sc
188 in sc' `seq` ((), us, sc'))
192 verboseSimplStats = opt_PprStyle_Debug -- For now, anyway
194 zeroSimplCount :: DynFlags -> SimplCount
195 isZeroSimplCount :: SimplCount -> Bool
196 pprSimplCount :: SimplCount -> SDoc
197 doTick, doFreeTick :: Tick -> SimplCount -> SimplCount
198 plusSimplCount :: SimplCount -> SimplCount -> SimplCount
202 data SimplCount = VerySimplZero -- These two are used when
203 | VerySimplNonZero -- we are only interested in
207 ticks :: !Int, -- Total ticks
208 details :: !TickCounts, -- How many of each type
210 log1 :: [Tick], -- Last N events; <= opt_HistorySize
211 log2 :: [Tick] -- Last opt_HistorySize events before that
214 type TickCounts = FiniteMap Tick Int
216 zeroSimplCount dflags
217 -- This is where we decide whether to do
218 -- the VerySimpl version or the full-stats version
219 | dopt Opt_D_dump_simpl_stats dflags
220 = SimplCount {ticks = 0, details = emptyFM,
221 n_log = 0, log1 = [], log2 = []}
225 isZeroSimplCount VerySimplZero = True
226 isZeroSimplCount (SimplCount { ticks = 0 }) = True
227 isZeroSimplCount other = False
229 doFreeTick tick sc@SimplCount { details = dts }
230 = dts' `seqFM` sc { details = dts' }
232 dts' = dts `addTick` tick
233 doFreeTick tick sc = sc
235 -- Gross hack to persuade GHC 3.03 to do this important seq
236 seqFM fm x | isEmptyFM fm = x
239 doTick tick sc@SimplCount { ticks = tks, details = dts, n_log = nl, log1 = l1, log2 = l2 }
240 | nl >= opt_HistorySize = sc1 { n_log = 1, log1 = [tick], log2 = l1 }
241 | otherwise = sc1 { n_log = nl+1, log1 = tick : l1 }
243 sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
245 doTick tick sc = VerySimplNonZero -- The very simple case
248 -- Don't use plusFM_C because that's lazy, and we want to
249 -- be pretty strict here!
250 addTick :: TickCounts -> Tick -> TickCounts
251 addTick fm tick = case lookupFM fm tick of
252 Nothing -> addToFM fm tick 1
253 Just n -> n1 `seq` addToFM fm tick n1
258 plusSimplCount sc1@(SimplCount { ticks = tks1, details = dts1 })
259 sc2@(SimplCount { ticks = tks2, details = dts2 })
260 = log_base { ticks = tks1 + tks2, details = plusFM_C (+) dts1 dts2 }
262 -- A hackish way of getting recent log info
263 log_base | null (log1 sc2) = sc1 -- Nothing at all in sc2
264 | null (log2 sc2) = sc2 { log2 = log1 sc1 }
267 plusSimplCount VerySimplZero VerySimplZero = VerySimplZero
268 plusSimplCount sc1 sc2 = VerySimplNonZero
270 pprSimplCount VerySimplZero = ptext SLIT("Total ticks: ZERO!")
271 pprSimplCount VerySimplNonZero = ptext SLIT("Total ticks: NON-ZERO!")
272 pprSimplCount (SimplCount { ticks = tks, details = dts, log1 = l1, log2 = l2 })
273 = vcat [ptext SLIT("Total ticks: ") <+> int tks,
275 pprTickCounts (fmToList dts),
276 if verboseSimplStats then
278 ptext SLIT("Log (most recent first)"),
279 nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
283 pprTickCounts :: [(Tick,Int)] -> SDoc
284 pprTickCounts [] = empty
285 pprTickCounts ((tick1,n1):ticks)
286 = vcat [int tot_n <+> text (tickString tick1),
287 pprTCDetails real_these,
291 tick1_tag = tickToTag tick1
292 (these, others) = span same_tick ticks
293 real_these = (tick1,n1):these
294 same_tick (tick2,_) = tickToTag tick2 == tick1_tag
295 tot_n = sum [n | (_,n) <- real_these]
297 pprTCDetails ticks@((tick,_):_)
298 | verboseSimplStats || isRuleFired tick
299 = nest 4 (vcat [int n <+> pprTickCts tick | (tick,n) <- ticks])
304 %************************************************************************
308 %************************************************************************
312 = PreInlineUnconditionally Id
313 | PostInlineUnconditionally Id
316 | RuleFired FastString -- Rule name
319 | EtaExpansion Id -- LHS binder
320 | EtaReduction Id -- Binder on outer lambda
321 | BetaReduction Id -- Lambda binder
324 | CaseOfCase Id -- Bndr on *inner* case
325 | KnownBranch Id -- Case binder
326 | CaseMerge Id -- Binder on outer case
327 | AltMerge Id -- Case binder
328 | CaseElim Id -- Case binder
329 | CaseIdentity Id -- Case binder
330 | FillInCaseDefault Id -- Case binder
333 | SimplifierDone -- Ticked at each iteration of the simplifier
335 isRuleFired (RuleFired _) = True
336 isRuleFired other = False
338 instance Outputable Tick where
339 ppr tick = text (tickString tick) <+> pprTickCts tick
341 instance Eq Tick where
342 a == b = case a `cmpTick` b of { EQ -> True; other -> False }
344 instance Ord Tick where
347 tickToTag :: Tick -> Int
348 tickToTag (PreInlineUnconditionally _) = 0
349 tickToTag (PostInlineUnconditionally _) = 1
350 tickToTag (UnfoldingDone _) = 2
351 tickToTag (RuleFired _) = 3
352 tickToTag LetFloatFromLet = 4
353 tickToTag (EtaExpansion _) = 5
354 tickToTag (EtaReduction _) = 6
355 tickToTag (BetaReduction _) = 7
356 tickToTag (CaseOfCase _) = 8
357 tickToTag (KnownBranch _) = 9
358 tickToTag (CaseMerge _) = 10
359 tickToTag (CaseElim _) = 11
360 tickToTag (CaseIdentity _) = 12
361 tickToTag (FillInCaseDefault _) = 13
362 tickToTag BottomFound = 14
363 tickToTag SimplifierDone = 16
364 tickToTag (AltMerge _) = 17
366 tickString :: Tick -> String
367 tickString (PreInlineUnconditionally _) = "PreInlineUnconditionally"
368 tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
369 tickString (UnfoldingDone _) = "UnfoldingDone"
370 tickString (RuleFired _) = "RuleFired"
371 tickString LetFloatFromLet = "LetFloatFromLet"
372 tickString (EtaExpansion _) = "EtaExpansion"
373 tickString (EtaReduction _) = "EtaReduction"
374 tickString (BetaReduction _) = "BetaReduction"
375 tickString (CaseOfCase _) = "CaseOfCase"
376 tickString (KnownBranch _) = "KnownBranch"
377 tickString (CaseMerge _) = "CaseMerge"
378 tickString (AltMerge _) = "AltMerge"
379 tickString (CaseElim _) = "CaseElim"
380 tickString (CaseIdentity _) = "CaseIdentity"
381 tickString (FillInCaseDefault _) = "FillInCaseDefault"
382 tickString BottomFound = "BottomFound"
383 tickString SimplifierDone = "SimplifierDone"
385 pprTickCts :: Tick -> SDoc
386 pprTickCts (PreInlineUnconditionally v) = ppr v
387 pprTickCts (PostInlineUnconditionally v)= ppr v
388 pprTickCts (UnfoldingDone v) = ppr v
389 pprTickCts (RuleFired v) = ppr v
390 pprTickCts LetFloatFromLet = empty
391 pprTickCts (EtaExpansion v) = ppr v
392 pprTickCts (EtaReduction v) = ppr v
393 pprTickCts (BetaReduction v) = ppr v
394 pprTickCts (CaseOfCase v) = ppr v
395 pprTickCts (KnownBranch v) = ppr v
396 pprTickCts (CaseMerge v) = ppr v
397 pprTickCts (AltMerge v) = ppr v
398 pprTickCts (CaseElim v) = ppr v
399 pprTickCts (CaseIdentity v) = ppr v
400 pprTickCts (FillInCaseDefault v) = ppr v
401 pprTickCts other = empty
403 cmpTick :: Tick -> Tick -> Ordering
404 cmpTick a b = case (tickToTag a `compare` tickToTag b) of
406 EQ | isRuleFired a || verboseSimplStats -> cmpEqTick a b
409 -- Always distinguish RuleFired, so that the stats
410 -- can report them even in non-verbose mode
412 cmpEqTick :: Tick -> Tick -> Ordering
413 cmpEqTick (PreInlineUnconditionally a) (PreInlineUnconditionally b) = a `compare` b
414 cmpEqTick (PostInlineUnconditionally a) (PostInlineUnconditionally b) = a `compare` b
415 cmpEqTick (UnfoldingDone a) (UnfoldingDone b) = a `compare` b
416 cmpEqTick (RuleFired a) (RuleFired b) = a `compare` b
417 cmpEqTick (EtaExpansion a) (EtaExpansion b) = a `compare` b
418 cmpEqTick (EtaReduction a) (EtaReduction b) = a `compare` b
419 cmpEqTick (BetaReduction a) (BetaReduction b) = a `compare` b
420 cmpEqTick (CaseOfCase a) (CaseOfCase b) = a `compare` b
421 cmpEqTick (KnownBranch a) (KnownBranch b) = a `compare` b
422 cmpEqTick (CaseMerge a) (CaseMerge b) = a `compare` b
423 cmpEqTick (AltMerge a) (AltMerge b) = a `compare` b
424 cmpEqTick (CaseElim a) (CaseElim b) = a `compare` b
425 cmpEqTick (CaseIdentity a) (CaseIdentity b) = a `compare` b
426 cmpEqTick (FillInCaseDefault a) (FillInCaseDefault b) = a `compare` b
427 cmpEqTick other1 other2 = EQ
431 %************************************************************************
433 \subsubsection{Command-line switches}
435 %************************************************************************
438 type SwitchChecker = SimplifierSwitch -> SwitchResult
441 = SwBool Bool -- on/off
442 | SwString FastString -- nothing or a String
443 | SwInt Int -- nothing or an Int
445 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
446 isAmongSimpl on_switches -- Switches mentioned later occur *earlier*
447 -- in the list; defaults right at the end.
449 tidied_on_switches = foldl rm_dups [] on_switches
450 -- The fold*l* ensures that we keep the latest switches;
451 -- ie the ones that occur earliest in the list.
453 sw_tbl :: Array Int SwitchResult
454 sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
458 all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
460 defined_elems = map mk_assoc_elem tidied_on_switches
462 -- (avoid some unboxing, bounds checking, and other horrible things:)
463 case sw_tbl of { Array _ _ stuff ->
465 case (indexArray# stuff (tagOf_SimplSwitch switch)) of
469 mk_assoc_elem k@(MaxSimplifierIterations lvl)
470 = (iBox (tagOf_SimplSwitch k), SwInt lvl)
472 = (iBox (tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
474 -- cannot have duplicates if we are going to use the array thing
475 rm_dups switches_so_far switch
476 = if switch `is_elem` switches_so_far
478 else switch : switches_so_far
480 sw `is_elem` [] = False
481 sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) ==# (tagOf_SimplSwitch s)
486 getSimplIntSwitch :: SwitchChecker -> (Int-> SimplifierSwitch) -> Int
487 getSimplIntSwitch chkr switch
488 = expectJust "getSimplIntSwitch" (intSwitchSet chkr switch)
490 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
492 switchIsOn lookup_fn switch
493 = case (lookup_fn switch) of
494 SwBool False -> False
497 intSwitchSet :: (switch -> SwitchResult)
501 intSwitchSet lookup_fn switch
502 = case (lookup_fn (switch (panic "intSwitchSet"))) of
503 SwInt int -> Just int
508 These things behave just like enumeration types.
511 instance Eq SimplifierSwitch where
512 a == b = tagOf_SimplSwitch a ==# tagOf_SimplSwitch b
514 instance Ord SimplifierSwitch where
515 a < b = tagOf_SimplSwitch a <# tagOf_SimplSwitch b
516 a <= b = tagOf_SimplSwitch a <=# tagOf_SimplSwitch b
519 tagOf_SimplSwitch (MaxSimplifierIterations _) = _ILIT(1)
520 tagOf_SimplSwitch NoCaseOfCase = _ILIT(2)
522 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
524 lAST_SIMPL_SWITCH_TAG = 2