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 CmdLineOpts ( SimplifierSwitch(..), DynFlags, DynFlag(..), dopt,
36 opt_PprStyle_Debug, opt_HistorySize,
38 import OccName ( EncodedFS )
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 GLAEXTS ( indexArray# )
48 #if __GLASGOW_HASKELL__ < 503
49 import PrelArr ( Array(..) )
51 import GHC.Arr ( Array(..) )
54 import Array ( array, (//) )
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 :: DynFlags -- We thread the unique supply because
71 -> UniqSupply -- constantly splitting it is rather expensive
73 -> (result, UniqSupply, SimplCount)}
78 -> UniqSupply -- No init count; set to 0
83 = case unSM m dflags us (zeroSimplCount dflags) of
84 (result, _, count) -> (result, count)
87 {-# INLINE thenSmpl #-}
88 {-# INLINE thenSmpl_ #-}
89 {-# INLINE returnSmpl #-}
91 instance Monad SimplM where
96 returnSmpl :: a -> SimplM a
97 returnSmpl e = SM (\ dflags us sc -> (e, us, sc))
99 thenSmpl :: SimplM a -> (a -> SimplM b) -> SimplM b
100 thenSmpl_ :: SimplM a -> SimplM b -> SimplM b
103 = SM (\ dflags us0 sc0 ->
104 case (unSM m dflags us0 sc0) of
105 (m_result, us1, sc1) -> unSM (k m_result) dflags us1 sc1 )
108 = SM (\dflags us0 sc0 ->
109 case (unSM m dflags us0 sc0) of
110 (_, us1, sc1) -> unSM k dflags us1 sc1)
115 mapSmpl :: (a -> SimplM b) -> [a] -> SimplM [b]
116 mapAndUnzipSmpl :: (a -> SimplM (b, c)) -> [a] -> SimplM ([b],[c])
118 mapSmpl f [] = returnSmpl []
120 = f x `thenSmpl` \ x' ->
121 mapSmpl f xs `thenSmpl` \ xs' ->
124 mapAndUnzipSmpl f [] = returnSmpl ([],[])
125 mapAndUnzipSmpl f (x:xs)
126 = f x `thenSmpl` \ (r1, r2) ->
127 mapAndUnzipSmpl f xs `thenSmpl` \ (rs1, rs2) ->
128 returnSmpl (r1:rs1, r2:rs2)
130 mapAccumLSmpl :: (acc -> b -> SimplM (acc,c)) -> acc -> [b] -> SimplM (acc, [c])
131 mapAccumLSmpl f acc [] = returnSmpl (acc, [])
132 mapAccumLSmpl f acc (x:xs) = f acc x `thenSmpl` \ (acc', x') ->
133 mapAccumLSmpl f acc' xs `thenSmpl` \ (acc'', xs') ->
134 returnSmpl (acc'', x':xs')
138 %************************************************************************
140 \subsection{The unique supply}
142 %************************************************************************
145 getUniqSupplySmpl :: SimplM UniqSupply
147 = SM (\dflags us sc -> case splitUniqSupply us of
148 (us1, us2) -> (us1, us2, sc))
150 getUniqueSmpl :: SimplM Unique
152 = SM (\dflags us sc -> case splitUniqSupply us of
153 (us1, us2) -> (uniqFromSupply us1, us2, sc))
155 getUniquesSmpl :: SimplM [Unique]
157 = SM (\dflags us sc -> case splitUniqSupply us of
158 (us1, us2) -> (uniqsFromSupply us1, us2, sc))
160 getDOptsSmpl :: SimplM DynFlags
162 = SM (\dflags us sc -> (dflags, us, sc))
164 newId :: EncodedFS -> Type -> SimplM Id
165 newId fs ty = getUniqueSmpl `thenSmpl` \ uniq ->
166 returnSmpl (mkSysLocal fs uniq ty)
170 %************************************************************************
172 \subsection{Counting up what we've done}
174 %************************************************************************
177 getSimplCount :: SimplM SimplCount
178 getSimplCount = SM (\dflags us sc -> (sc, us, sc))
180 tick :: Tick -> SimplM ()
182 = SM (\dflags us sc -> let sc' = doTick t sc
183 in sc' `seq` ((), us, sc'))
185 freeTick :: Tick -> SimplM ()
186 -- Record a tick, but don't add to the total tick count, which is
187 -- used to decide when nothing further has happened
189 = SM (\dflags us sc -> let sc' = doFreeTick t sc
190 in sc' `seq` ((), us, sc'))
194 verboseSimplStats = opt_PprStyle_Debug -- For now, anyway
196 zeroSimplCount :: DynFlags -> SimplCount
197 isZeroSimplCount :: SimplCount -> Bool
198 pprSimplCount :: SimplCount -> SDoc
199 doTick, doFreeTick :: Tick -> SimplCount -> SimplCount
200 plusSimplCount :: SimplCount -> SimplCount -> SimplCount
204 data SimplCount = VerySimplZero -- These two are used when
205 | VerySimplNonZero -- we are only interested in
209 ticks :: !Int, -- Total ticks
210 details :: !TickCounts, -- How many of each type
212 log1 :: [Tick], -- Last N events; <= opt_HistorySize
213 log2 :: [Tick] -- Last opt_HistorySize events before that
216 type TickCounts = FiniteMap Tick Int
218 zeroSimplCount dflags
219 -- This is where we decide whether to do
220 -- the VerySimpl version or the full-stats version
221 | dopt Opt_D_dump_simpl_stats dflags
222 = SimplCount {ticks = 0, details = emptyFM,
223 n_log = 0, log1 = [], log2 = []}
227 isZeroSimplCount VerySimplZero = True
228 isZeroSimplCount (SimplCount { ticks = 0 }) = True
229 isZeroSimplCount other = False
231 doFreeTick tick sc@SimplCount { details = dts }
232 = dts' `seqFM` sc { details = dts' }
234 dts' = dts `addTick` tick
235 doFreeTick tick sc = sc
237 -- Gross hack to persuade GHC 3.03 to do this important seq
238 seqFM fm x | isEmptyFM fm = x
241 doTick tick sc@SimplCount { ticks = tks, details = dts, n_log = nl, log1 = l1, log2 = l2 }
242 | nl >= opt_HistorySize = sc1 { n_log = 1, log1 = [tick], log2 = l1 }
243 | otherwise = sc1 { n_log = nl+1, log1 = tick : l1 }
245 sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
247 doTick tick sc = VerySimplNonZero -- The very simple case
250 -- Don't use plusFM_C because that's lazy, and we want to
251 -- be pretty strict here!
252 addTick :: TickCounts -> Tick -> TickCounts
253 addTick fm tick = case lookupFM fm tick of
254 Nothing -> addToFM fm tick 1
255 Just n -> n1 `seq` addToFM fm tick n1
260 plusSimplCount sc1@(SimplCount { ticks = tks1, details = dts1 })
261 sc2@(SimplCount { ticks = tks2, details = dts2 })
262 = log_base { ticks = tks1 + tks2, details = plusFM_C (+) dts1 dts2 }
264 -- A hackish way of getting recent log info
265 log_base | null (log1 sc2) = sc1 -- Nothing at all in sc2
266 | null (log2 sc2) = sc2 { log2 = log1 sc1 }
269 plusSimplCount VerySimplZero VerySimplZero = VerySimplZero
270 plusSimplCount sc1 sc2 = VerySimplNonZero
272 pprSimplCount VerySimplZero = ptext SLIT("Total ticks: ZERO!")
273 pprSimplCount VerySimplNonZero = ptext SLIT("Total ticks: NON-ZERO!")
274 pprSimplCount (SimplCount { ticks = tks, details = dts, log1 = l1, log2 = l2 })
275 = vcat [ptext SLIT("Total ticks: ") <+> int tks,
277 pprTickCounts (fmToList dts),
278 if verboseSimplStats then
280 ptext SLIT("Log (most recent first)"),
281 nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
285 pprTickCounts :: [(Tick,Int)] -> SDoc
286 pprTickCounts [] = empty
287 pprTickCounts ((tick1,n1):ticks)
288 = vcat [int tot_n <+> text (tickString tick1),
289 pprTCDetails real_these,
293 tick1_tag = tickToTag tick1
294 (these, others) = span same_tick ticks
295 real_these = (tick1,n1):these
296 same_tick (tick2,_) = tickToTag tick2 == tick1_tag
297 tot_n = sum [n | (_,n) <- real_these]
299 pprTCDetails ticks@((tick,_):_)
300 | verboseSimplStats || isRuleFired tick
301 = nest 4 (vcat [int n <+> pprTickCts tick | (tick,n) <- ticks])
306 %************************************************************************
310 %************************************************************************
314 = PreInlineUnconditionally Id
315 | PostInlineUnconditionally Id
318 | RuleFired FastString -- Rule name
321 | EtaExpansion Id -- LHS binder
322 | EtaReduction Id -- Binder on outer lambda
323 | BetaReduction Id -- Lambda binder
326 | CaseOfCase Id -- Bndr on *inner* case
327 | KnownBranch Id -- Case binder
328 | CaseMerge Id -- Binder on outer case
329 | AltMerge Id -- Case binder
330 | CaseElim Id -- Case binder
331 | CaseIdentity Id -- Case binder
332 | FillInCaseDefault Id -- Case binder
335 | SimplifierDone -- Ticked at each iteration of the simplifier
337 isRuleFired (RuleFired _) = True
338 isRuleFired other = False
340 instance Outputable Tick where
341 ppr tick = text (tickString tick) <+> pprTickCts tick
343 instance Eq Tick where
344 a == b = case a `cmpTick` b of { EQ -> True; other -> False }
346 instance Ord Tick where
349 tickToTag :: Tick -> Int
350 tickToTag (PreInlineUnconditionally _) = 0
351 tickToTag (PostInlineUnconditionally _) = 1
352 tickToTag (UnfoldingDone _) = 2
353 tickToTag (RuleFired _) = 3
354 tickToTag LetFloatFromLet = 4
355 tickToTag (EtaExpansion _) = 5
356 tickToTag (EtaReduction _) = 6
357 tickToTag (BetaReduction _) = 7
358 tickToTag (CaseOfCase _) = 8
359 tickToTag (KnownBranch _) = 9
360 tickToTag (CaseMerge _) = 10
361 tickToTag (CaseElim _) = 11
362 tickToTag (CaseIdentity _) = 12
363 tickToTag (FillInCaseDefault _) = 13
364 tickToTag BottomFound = 14
365 tickToTag SimplifierDone = 16
366 tickToTag (AltMerge _) = 17
368 tickString :: Tick -> String
369 tickString (PreInlineUnconditionally _) = "PreInlineUnconditionally"
370 tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
371 tickString (UnfoldingDone _) = "UnfoldingDone"
372 tickString (RuleFired _) = "RuleFired"
373 tickString LetFloatFromLet = "LetFloatFromLet"
374 tickString (EtaExpansion _) = "EtaExpansion"
375 tickString (EtaReduction _) = "EtaReduction"
376 tickString (BetaReduction _) = "BetaReduction"
377 tickString (CaseOfCase _) = "CaseOfCase"
378 tickString (KnownBranch _) = "KnownBranch"
379 tickString (CaseMerge _) = "CaseMerge"
380 tickString (AltMerge _) = "AltMerge"
381 tickString (CaseElim _) = "CaseElim"
382 tickString (CaseIdentity _) = "CaseIdentity"
383 tickString (FillInCaseDefault _) = "FillInCaseDefault"
384 tickString BottomFound = "BottomFound"
385 tickString SimplifierDone = "SimplifierDone"
387 pprTickCts :: Tick -> SDoc
388 pprTickCts (PreInlineUnconditionally v) = ppr v
389 pprTickCts (PostInlineUnconditionally v)= ppr v
390 pprTickCts (UnfoldingDone v) = ppr v
391 pprTickCts (RuleFired v) = ppr v
392 pprTickCts LetFloatFromLet = empty
393 pprTickCts (EtaExpansion v) = ppr v
394 pprTickCts (EtaReduction v) = ppr v
395 pprTickCts (BetaReduction v) = ppr v
396 pprTickCts (CaseOfCase v) = ppr v
397 pprTickCts (KnownBranch v) = ppr v
398 pprTickCts (CaseMerge v) = ppr v
399 pprTickCts (AltMerge v) = ppr v
400 pprTickCts (CaseElim v) = ppr v
401 pprTickCts (CaseIdentity v) = ppr v
402 pprTickCts (FillInCaseDefault v) = ppr v
403 pprTickCts other = empty
405 cmpTick :: Tick -> Tick -> Ordering
406 cmpTick a b = case (tickToTag a `compare` tickToTag b) of
408 EQ | isRuleFired a || verboseSimplStats -> cmpEqTick a b
411 -- Always distinguish RuleFired, so that the stats
412 -- can report them even in non-verbose mode
414 cmpEqTick :: Tick -> Tick -> Ordering
415 cmpEqTick (PreInlineUnconditionally a) (PreInlineUnconditionally b) = a `compare` b
416 cmpEqTick (PostInlineUnconditionally a) (PostInlineUnconditionally b) = a `compare` b
417 cmpEqTick (UnfoldingDone a) (UnfoldingDone b) = a `compare` b
418 cmpEqTick (RuleFired a) (RuleFired b) = a `compare` b
419 cmpEqTick (EtaExpansion a) (EtaExpansion b) = a `compare` b
420 cmpEqTick (EtaReduction a) (EtaReduction b) = a `compare` b
421 cmpEqTick (BetaReduction a) (BetaReduction b) = a `compare` b
422 cmpEqTick (CaseOfCase a) (CaseOfCase b) = a `compare` b
423 cmpEqTick (KnownBranch a) (KnownBranch b) = a `compare` b
424 cmpEqTick (CaseMerge a) (CaseMerge b) = a `compare` b
425 cmpEqTick (AltMerge a) (AltMerge b) = a `compare` b
426 cmpEqTick (CaseElim a) (CaseElim b) = a `compare` b
427 cmpEqTick (CaseIdentity a) (CaseIdentity b) = a `compare` b
428 cmpEqTick (FillInCaseDefault a) (FillInCaseDefault b) = a `compare` b
429 cmpEqTick other1 other2 = EQ
433 %************************************************************************
435 \subsubsection{Command-line switches}
437 %************************************************************************
440 type SwitchChecker = SimplifierSwitch -> SwitchResult
443 = SwBool Bool -- on/off
444 | SwString FastString -- nothing or a String
445 | SwInt Int -- nothing or an Int
447 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
448 isAmongSimpl on_switches -- Switches mentioned later occur *earlier*
449 -- in the list; defaults right at the end.
451 tidied_on_switches = foldl rm_dups [] on_switches
452 -- The fold*l* ensures that we keep the latest switches;
453 -- ie the ones that occur earliest in the list.
455 sw_tbl :: Array Int SwitchResult
456 sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
460 all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
462 defined_elems = map mk_assoc_elem tidied_on_switches
464 -- (avoid some unboxing, bounds checking, and other horrible things:)
465 case sw_tbl of { Array _ _ stuff ->
467 case (indexArray# stuff (tagOf_SimplSwitch switch)) of
471 mk_assoc_elem k@(MaxSimplifierIterations lvl)
472 = (iBox (tagOf_SimplSwitch k), SwInt lvl)
474 = (iBox (tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
476 -- cannot have duplicates if we are going to use the array thing
477 rm_dups switches_so_far switch
478 = if switch `is_elem` switches_so_far
480 else switch : switches_so_far
482 sw `is_elem` [] = False
483 sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) ==# (tagOf_SimplSwitch s)
488 getSimplIntSwitch :: SwitchChecker -> (Int-> SimplifierSwitch) -> Int
489 getSimplIntSwitch chkr switch
490 = expectJust "getSimplIntSwitch" (intSwitchSet chkr switch)
492 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
494 switchIsOn lookup_fn switch
495 = case (lookup_fn switch) of
496 SwBool False -> False
499 intSwitchSet :: (switch -> SwitchResult)
503 intSwitchSet lookup_fn switch
504 = case (lookup_fn (switch (panic "intSwitchSet"))) of
505 SwInt int -> Just int
510 These things behave just like enumeration types.
513 instance Eq SimplifierSwitch where
514 a == b = tagOf_SimplSwitch a ==# tagOf_SimplSwitch b
516 instance Ord SimplifierSwitch where
517 a < b = tagOf_SimplSwitch a <# tagOf_SimplSwitch b
518 a <= b = tagOf_SimplSwitch a <=# tagOf_SimplSwitch b
521 tagOf_SimplSwitch (MaxSimplifierIterations _) = _ILIT(1)
522 tagOf_SimplSwitch NoCaseOfCase = _ILIT(2)
524 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
526 lAST_SIMPL_SWITCH_TAG = 2