SimplMonad.lhs 22.2 KB
Newer Older
1
%
2
% (c) The AQUA Project, Glasgow University, 1993-1998
3 4 5 6 7
%
\section[SimplMonad]{The simplifier Monad}

\begin{code}
module SimplMonad (
8 9
	InId, InBind, InExpr, InAlt, InArg, InType, InBinder,
	OutId, OutBind, OutExpr, OutAlt, OutArg, OutType, OutBinder,
10
	OutExprStuff, OutStuff,
11 12 13

	-- The monad
	SimplM,
14
	initSmpl, returnSmpl, thenSmpl, thenSmpl_,
15 16
	mapSmpl, mapAndUnzipSmpl, mapAccumLSmpl,

17 18 19
	-- The inlining black-list
	getBlackList,

20 21
        -- Unique supply
        getUniqueSmpl, getUniquesSmpl,
22
	newId, newIds,
23

24
	-- Counting
25
	SimplCount, Tick(..),
26
	tick, freeTick,
27 28 29 30 31 32 33 34 35 36
	getSimplCount, zeroSimplCount, pprSimplCount, 
	plusSimplCount, isZeroSimplCount,

	-- Switch checker
	SwitchChecker, getSwitchChecker, getSimplIntSwitch,

	-- Cost centres
	getEnclosingCC, setEnclosingCC,

	-- Environments
37
	getEnv, setAllExceptInScope,
38 39
	getSubst, setSubst,
	getSubstEnv, extendSubst, extendSubstList,
40
	getInScope, setInScope, extendInScope, extendInScopes, modifyInScope,
41
	setSubstEnv, zapSubstEnv,
42 43
	getSimplBinderStuff, setSimplBinderStuff,
	switchOffInlining
44 45
    ) where

46
#include "HsVersions.h"
47

48
import Id		( Id, mkSysLocal, idUnfolding, isDataConWrapId )
49
import CoreSyn
50
import CoreUnfold	( isCompulsoryUnfolding )
51
import PprCore		()	-- Instances
52
import CostCentre	( CostCentreStack, subsumedCCS )
53
import Name		( isLocallyDefined )
54
import OccName		( UserFS )
55 56
import VarEnv
import VarSet
57
import qualified Subst
58
import Subst		( Subst, mkSubst, substEnv, 
59
			  InScopeSet, substInScope, isInScope
60
			)
61
import Type             ( Type )
62
import UniqSupply	( uniqsFromSupply, uniqFromSupply, splitUniqSupply,
63 64
			  UniqSupply
			)
65 66
import FiniteMap
import CmdLineOpts	( SimplifierSwitch(..), SwitchResult(..),
67
			  opt_PprStyle_Debug, opt_HistorySize, opt_D_dump_simpl_stats,
68 69
			  intSwitchSet
			)
70
import Unique		( Unique )
71 72
import Maybes		( expectJust )
import Util		( zipWithEqual )
73
import Outputable
74

75
infixr 0  `thenSmpl`, `thenSmpl_`
76 77
\end{code}

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
%************************************************************************
%*									*
\subsection[Simplify-types]{Type declarations}
%*									*
%************************************************************************

\begin{code}
type InBinder  = CoreBndr
type InId      = Id			-- Not yet cloned
type InType    = Type			-- Ditto
type InBind    = CoreBind
type InExpr    = CoreExpr
type InAlt     = CoreAlt
type InArg     = CoreArg

type OutBinder  = CoreBndr
type OutId	= Id			-- Cloned
type OutType	= Type			-- Cloned
type OutBind	= CoreBind
type OutExpr	= CoreExpr
type OutAlt	= CoreAlt
type OutArg	= CoreArg

type SwitchChecker = SimplifierSwitch -> SwitchResult

103
type OutExprStuff = OutStuff (InScopeSet, OutExpr)
104 105 106 107
type OutStuff a   = ([OutBind], a)
	-- We return something equivalent to (let b in e), but
	-- in pieces to avoid the quadratic blowup when floating 
	-- incrementally.  Comments just before simplExprB in Simplify.lhs
108 109 110
\end{code}


111 112
%************************************************************************
%*									*
113
\subsection{Monad plumbing}
114 115 116 117 118 119 120
%*									*
%************************************************************************

For the simplifier monad, we want to {\em thread} a unique supply and a counter.
(Command-line switches move around through the explicitly-passed SimplEnv.)

\begin{code}
121 122 123 124 125 126 127 128
type SimplM result		-- We thread the unique supply because
  =  SimplEnv			-- constantly splitting it is rather expensive
  -> UniqSupply
  -> SimplCount 
  -> (result, UniqSupply, SimplCount)

data SimplEnv
  = SimplEnv {
129 130 131 132
	seChkr      :: SwitchChecker,
	seCC        :: CostCentreStack,	-- The enclosing CCS (when profiling)
	seBlackList :: Id -> Bool,	-- True =>  don't inline this Id
	seSubst     :: Subst		-- The current substitution
133
    }
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
	-- The range of the substitution is OutType and OutExpr resp
	-- 
	-- The substitution is idempotent
	-- It *must* be applied; things in its domain simply aren't
	-- bound in the result.
	--
	-- The substitution usually maps an Id to its clone,
	-- but if the orig defn is a let-binding, and
	-- the RHS of the let simplifies to an atom,
	-- we just add the binding to the substitution and elide the let.

	-- The in-scope part of Subst includes *all* in-scope TyVars and Ids
	-- The elements of the set may have better IdInfo than the
	-- occurrences of in-scope Ids, and (more important) they will
	-- have a correctly-substituted type.  So we use a lookup in this
	-- set to replace occurrences
150 151 152
\end{code}

\begin{code}
153 154
initSmpl :: SwitchChecker
	 -> UniqSupply		-- No init count; set to 0
155 156
	 -> VarSet		-- In scope (usually empty, but useful for nested calls)
	 -> (Id -> Bool)	-- Black-list function
157 158 159
	 -> SimplM a
	 -> (a, SimplCount)

160 161 162
initSmpl chkr us in_scope black_list m
  = case m (emptySimplEnv chkr in_scope black_list) us zeroSimplCount of 
	(result, _, count) -> (result, count)
163 164 165 166 167 168


{-# INLINE thenSmpl #-}
{-# INLINE thenSmpl_ #-}
{-# INLINE returnSmpl #-}

169 170
returnSmpl :: a -> SimplM a
returnSmpl e env us sc = (e, us, sc)
171

172 173
thenSmpl  :: SimplM a -> (a -> SimplM b) -> SimplM b
thenSmpl_ :: SimplM a -> SimplM b -> SimplM b
174

175 176 177
thenSmpl m k env us0 sc0
  = case (m env us0 sc0) of 
	(m_result, us1, sc1) -> k m_result env us1 sc1
178

179 180 181 182
thenSmpl_ m k env us0 sc0
  = case (m env us0 sc0) of 
	(_, us1, sc1) -> k env us1 sc1
\end{code}
183

184 185 186 187

\begin{code}
mapSmpl	    	:: (a -> SimplM b) -> [a] -> SimplM [b]
mapAndUnzipSmpl :: (a -> SimplM (b, c)) -> [a] -> SimplM ([b],[c])
188 189 190 191 192 193 194 195 196 197 198 199

mapSmpl f [] = returnSmpl []
mapSmpl f (x:xs)
  = f x		    `thenSmpl` \ x'  ->
    mapSmpl f xs    `thenSmpl` \ xs' ->
    returnSmpl (x':xs')

mapAndUnzipSmpl f [] = returnSmpl ([],[])
mapAndUnzipSmpl f (x:xs)
  = f x			    `thenSmpl` \ (r1,  r2)  ->
    mapAndUnzipSmpl f xs    `thenSmpl` \ (rs1, rs2) ->
    returnSmpl (r1:rs1, r2:rs2)
200 201 202 203 204

mapAccumLSmpl f acc []     = returnSmpl (acc, [])
mapAccumLSmpl f acc (x:xs) = f acc x	`thenSmpl` \ (acc', x') ->
			     mapAccumLSmpl f acc' xs	`thenSmpl` \ (acc'', xs') ->
			     returnSmpl (acc'', x':xs')
205
\end{code}
206 207


208 209 210 211 212 213 214 215 216 217 218 219 220 221
%************************************************************************
%*									*
\subsection{The unique supply}
%*									*
%************************************************************************

\begin{code}
getUniqueSmpl :: SimplM Unique
getUniqueSmpl env us sc = case splitUniqSupply us of
				(us1, us2) -> (uniqFromSupply us1, us2, sc)

getUniquesSmpl :: Int -> SimplM [Unique]
getUniquesSmpl n env us sc = case splitUniqSupply us of
				(us1, us2) -> (uniqsFromSupply n us1, us2, sc)
222 223 224 225 226
\end{code}


%************************************************************************
%*									*
227
\subsection{Counting up what we've done}
228 229 230
%*									*
%************************************************************************

231 232 233 234
\begin{code}
getSimplCount :: SimplM SimplCount
getSimplCount env us sc = (sc, us, sc)

235 236 237 238 239 240 241 242 243 244 245 246
tick :: Tick -> SimplM ()
tick t env us sc = sc' `seq` ((), us, sc')
		 where
		   sc' = doTick t sc

freeTick :: Tick -> SimplM ()
-- Record a tick, but don't add to the total tick count, which is
-- used to decide when nothing further has happened
freeTick t env us sc = sc' `seq` ((), us, sc')
		 where
		   sc' = doFreeTick t sc
\end{code}
247

248 249 250 251 252 253 254 255 256
\begin{code}
verboseSimplStats = opt_PprStyle_Debug		-- For now, anyway

zeroSimplCount	   :: SimplCount
isZeroSimplCount   :: SimplCount -> Bool
pprSimplCount	   :: SimplCount -> SDoc
doTick, doFreeTick :: Tick -> SimplCount -> SimplCount
plusSimplCount     :: SimplCount -> SimplCount -> SimplCount
\end{code}
257 258

\begin{code}
259 260 261
data SimplCount = VerySimplZero		-- These two are used when 
		| VerySimplNonZero	-- we are only interested in 
					-- termination info
262

263
		| SimplCount	{
264 265 266 267 268 269
			ticks   :: !Int,		-- Total ticks
			details :: !TickCounts,		-- How many of each type
			n_log	:: !Int,		-- N
			log1	:: [Tick],		-- Last N events; <= opt_HistorySize
			log2	:: [Tick]		-- Last opt_HistorySize events before that
		  }
270

271 272
type TickCounts = FiniteMap Tick Int

273 274 275 276 277
zeroSimplCount	-- This is where we decide whether to do
		-- the VerySimpl version or the full-stats version
  | opt_D_dump_simpl_stats = SimplCount {ticks = 0, details = emptyFM,
			   		 n_log = 0, log1 = [], log2 = []}
  | otherwise		   = VerySimplZero
278

279 280 281
isZeroSimplCount VerySimplZero    	    = True
isZeroSimplCount (SimplCount { ticks = 0 }) = True
isZeroSimplCount other			    = False
282 283 284 285 286

doFreeTick tick sc@SimplCount { details = dts } 
  = dts' `seqFM` sc { details = dts' }
  where
    dts' = dts `addTick` tick 
287
doFreeTick tick sc = sc 
288 289 290 291 292 293 294 295 296 297 298

-- Gross hack to persuade GHC 3.03 to do this important seq
seqFM fm x | isEmptyFM fm = x
	   | otherwise    = x

doTick tick sc@SimplCount { ticks = tks, details = dts, n_log = nl, log1 = l1, log2 = l2 }
  | nl >= opt_HistorySize = sc1 { n_log = 1, log1 = [tick], log2 = l1 }
  | otherwise		  = sc1 { n_log = nl+1, log1 = tick : l1 }
  where
    sc1 = sc { ticks = tks+1, details = dts `addTick` tick }

299 300 301
doTick tick sc = VerySimplNonZero	-- The very simple case


302 303 304 305 306 307 308 309 310
-- Don't use plusFM_C because that's lazy, and we want to 
-- be pretty strict here!
addTick :: TickCounts -> Tick -> TickCounts
addTick fm tick = case lookupFM fm tick of
			Nothing -> addToFM fm tick 1
			Just n  -> n1 `seq` addToFM fm tick n1
				where
				   n1 = n+1

311

312 313 314
plusSimplCount sc1@(SimplCount { ticks = tks1, details = dts1 })
	       sc2@(SimplCount { ticks = tks2, details = dts2 })
  = log_base { ticks = tks1 + tks2, details = plusFM_C (+) dts1 dts2 }
315
  where
316 317 318 319 320
	-- A hackish way of getting recent log info
    log_base | null (log1 sc2) = sc1	-- Nothing at all in sc2
	     | null (log2 sc2) = sc2 { log2 = log1 sc1 }
	     | otherwise       = sc2

321 322
plusSimplCount VerySimplZero VerySimplZero = VerySimplZero
plusSimplCount sc1	     sc2	   = VerySimplNonZero
323

324 325
pprSimplCount VerySimplZero    = ptext SLIT("Total ticks: ZERO!")
pprSimplCount VerySimplNonZero = ptext SLIT("Total ticks: NON-ZERO!")
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
pprSimplCount (SimplCount { ticks = tks, details = dts, log1 = l1, log2 = l2 })
  = vcat [ptext SLIT("Total ticks:    ") <+> int tks,
	  text "",
	  pprTickCounts (fmToList dts),
	  if verboseSimplStats then
		vcat [text "",
		      ptext SLIT("Log (most recent first)"),
		      nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
	  else empty
    ]

pprTickCounts :: [(Tick,Int)] -> SDoc
pprTickCounts [] = empty
pprTickCounts ((tick1,n1):ticks)
  = vcat [int tot_n <+> text (tickString tick1),
	  pprTCDetails real_these,
	  pprTickCounts others
    ]
  where
    tick1_tag		= tickToTag tick1
    (these, others)	= span same_tick ticks
    real_these		= (tick1,n1):these
    same_tick (tick2,_) = tickToTag tick2 == tick1_tag
    tot_n		= sum [n | (_,n) <- real_these]

pprTCDetails ticks@((tick,_):_)
  | verboseSimplStats || isRuleFired tick
  = nest 4 (vcat [int n <+> pprTickCts tick | (tick,n) <- ticks])
  | otherwise
  = empty
\end{code}

%************************************************************************
%*									*
\subsection{Ticks}
%*									*
%************************************************************************

\begin{code}
data Tick
  = PreInlineUnconditionally	Id
  | PostInlineUnconditionally	Id

  | UnfoldingDone    		Id
  | RuleFired			FAST_STRING	-- Rule name

  | LetFloatFromLet		Id	-- Thing floated out
  | EtaExpansion		Id	-- LHS binder
  | EtaReduction		Id	-- Binder on outer lambda
  | BetaReduction		Id	-- Lambda binder


  | CaseOfCase			Id	-- Bndr on *inner* case
  | KnownBranch			Id	-- Case binder
  | CaseMerge			Id	-- Binder on outer case
  | CaseElim			Id	-- Case binder
  | CaseIdentity		Id	-- Case binder
  | FillInCaseDefault		Id	-- Case binder

  | BottomFound		
  | SimplifierDone		-- Ticked at each iteration of the simplifier

isRuleFired (RuleFired _) = True
isRuleFired other	  = False

instance Outputable Tick where
  ppr tick = text (tickString tick) <+> pprTickCts tick

instance Eq Tick where
  a == b = case a `cmpTick` b of { EQ -> True; other -> False }

instance Ord Tick where
  compare = cmpTick

tickToTag :: Tick -> Int
tickToTag (PreInlineUnconditionally _)	= 0
tickToTag (PostInlineUnconditionally _)	= 1
tickToTag (UnfoldingDone _)		= 2
tickToTag (RuleFired _)			= 3
tickToTag (LetFloatFromLet _)		= 4
tickToTag (EtaExpansion _)		= 5
tickToTag (EtaReduction _)		= 6
tickToTag (BetaReduction _)		= 7
tickToTag (CaseOfCase _)		= 8
tickToTag (KnownBranch _)		= 9
tickToTag (CaseMerge _)			= 10
tickToTag (CaseElim _)			= 11
tickToTag (CaseIdentity _)		= 12
tickToTag (FillInCaseDefault _)		= 13
tickToTag BottomFound			= 14
tickToTag SimplifierDone		= 16

tickString :: Tick -> String
tickString (PreInlineUnconditionally _)	= "PreInlineUnconditionally"
tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
tickString (UnfoldingDone _)		= "UnfoldingDone"
tickString (RuleFired _)		= "RuleFired"
tickString (LetFloatFromLet _)		= "LetFloatFromLet"
tickString (EtaExpansion _)		= "EtaExpansion"
tickString (EtaReduction _)		= "EtaReduction"
tickString (BetaReduction _)		= "BetaReduction"
tickString (CaseOfCase _)		= "CaseOfCase"
tickString (KnownBranch _)		= "KnownBranch"
tickString (CaseMerge _)		= "CaseMerge"
tickString (CaseElim _)			= "CaseElim"
tickString (CaseIdentity _)		= "CaseIdentity"
tickString (FillInCaseDefault _)	= "FillInCaseDefault"
tickString BottomFound			= "BottomFound"
tickString SimplifierDone		= "SimplifierDone"

pprTickCts :: Tick -> SDoc
pprTickCts (PreInlineUnconditionally v)	= ppr v
pprTickCts (PostInlineUnconditionally v)= ppr v
pprTickCts (UnfoldingDone v)		= ppr v
pprTickCts (RuleFired v)		= ppr v
pprTickCts (LetFloatFromLet v)		= ppr v
pprTickCts (EtaExpansion v)		= ppr v
pprTickCts (EtaReduction v)		= ppr v
pprTickCts (BetaReduction v)		= ppr v
pprTickCts (CaseOfCase v)		= ppr v
pprTickCts (KnownBranch v)		= ppr v
pprTickCts (CaseMerge v)		= ppr v
pprTickCts (CaseElim v)			= ppr v
pprTickCts (CaseIdentity v)		= ppr v
pprTickCts (FillInCaseDefault v)	= ppr v
pprTickCts other			= empty

cmpTick :: Tick -> Tick -> Ordering
cmpTick a b = case (tickToTag a `compare` tickToTag b) of
		GT -> GT
		EQ | isRuleFired a || verboseSimplStats -> cmpEqTick a b
		   | otherwise				-> EQ
		LT -> LT
	-- Always distinguish RuleFired, so that the stats
	-- can report them even in non-verbose mode

cmpEqTick :: Tick -> Tick -> Ordering
cmpEqTick (PreInlineUnconditionally a)	(PreInlineUnconditionally b)	= a `compare` b
cmpEqTick (PostInlineUnconditionally a)	(PostInlineUnconditionally b)	= a `compare` b
cmpEqTick (UnfoldingDone a)		(UnfoldingDone b)		= a `compare` b
cmpEqTick (RuleFired a)			(RuleFired b)			= a `compare` b
cmpEqTick (LetFloatFromLet a)		(LetFloatFromLet b)		= a `compare` b
cmpEqTick (EtaExpansion a)		(EtaExpansion b)		= a `compare` b
cmpEqTick (EtaReduction a)		(EtaReduction b)		= a `compare` b
cmpEqTick (BetaReduction a)		(BetaReduction b)		= a `compare` b
cmpEqTick (CaseOfCase a)		(CaseOfCase b)			= a `compare` b
cmpEqTick (KnownBranch a)		(KnownBranch b)			= a `compare` b
cmpEqTick (CaseMerge a)			(CaseMerge b)			= a `compare` b
cmpEqTick (CaseElim a)			(CaseElim b)			= a `compare` b
cmpEqTick (CaseIdentity a)		(CaseIdentity b)		= a `compare` b
cmpEqTick (FillInCaseDefault a)		(FillInCaseDefault b)		= a `compare` b
cmpEqTick other1			other2				= EQ
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
\end{code}


%************************************************************************
%*									*
\subsubsection{Command-line switches}
%*									*
%************************************************************************

\begin{code}
getSwitchChecker :: SimplM SwitchChecker
getSwitchChecker env us sc = (seChkr env, us, sc)

getSimplIntSwitch :: SwitchChecker -> (Int-> SimplifierSwitch) -> Int
getSimplIntSwitch chkr switch
  = expectJust "getSimplIntSwitch" (intSwitchSet chkr switch)
\end{code}


@switchOffInlining@ is used to prepare the environment for simplifying
the RHS of an Id that's marked with an INLINE pragma.  It is going to
be inlined wherever they are used, and then all the inlining will take
effect.  Meanwhile, there isn't much point in doing anything to the
as-yet-un-INLINEd rhs.  Furthremore, it's very important to switch off
inlining!  because
	(a) not doing so will inline a worker straight back into its wrapper!

and 	(b) Consider the following example 
	     	let f = \pq -> BIG
	     	in
	     	let g = \y -> f y y
		    {-# INLINE g #-}
	     	in ...g...g...g...g...g...

	Now, if that's the ONLY occurrence of f, it will be inlined inside g,
	and thence copied multiple times when g is inlined.

	Andy disagrees! Example:
		all xs = foldr (&&) True xs
		any p = all . map p  {-# INLINE any #-}
	
	Problem: any won't get deforested, and so if it's exported and
	the importer doesn't use the inlining, (eg passes it as an arg)
	then we won't get deforestation at all.
	We havn't solved this problem yet!

We prepare the envt by simply modifying the in_scope_env, which has all the
unfolding info. At one point we did it by modifying the chkr so that
it said "EssentialUnfoldingsOnly", but that prevented legitmate, and
important, simplifications happening in the body of the RHS.

6/98 update: 

We *don't* prevent inlining from happening for identifiers
that are marked as IMustBeINLINEd. An example of where
doing this is crucial is:
  
   class Bar a => Foo a where
     ...g....
   {-# INLINE f #-}
   f :: Foo a => a -> b
   f x = ....Foo_sc1...
   
If `f' needs to peer inside Foo's superclass, Bar, it refers
to the appropriate super class selector, which is marked as
must-inlineable. We don't generate any code for a superclass
selector, so failing to inline it in the RHS of `f' will
leave a reference to a non-existent id, with bad consequences.

ALSO NOTE that we do all this by modifing the inline-pragma,
not by zapping the unfolding.  The latter may still be useful for
knowing when something is evaluated.

June 98 update: I've gone back to dealing with this by adding
the EssentialUnfoldingsOnly switch.  That doesn't stop essential
unfoldings, nor inlineUnconditionally stuff; and the thing's going
to be inlined at every call site anyway.  Running over the whole
environment seems like wild overkill.

\begin{code}
switchOffInlining :: SimplM a -> SimplM a
559
switchOffInlining m env us sc
560 561
  = m (env { seBlackList = \v -> not (isCompulsoryUnfolding (idUnfolding v)) &&
				 not (isDataConWrapId v) &&
562
				 ((v `isInScope` subst) || not (isLocallyDefined v))
563
	   }) us sc
564 565 566 567 568 569
	
	-- Inside inlinings, black list anything that is in scope or imported.
	-- except for things that must be unfolded (Compulsory)
	-- and data con wrappers.  The latter is a hack, like the one in
	-- SimplCore.simplRules, to make wrappers inline in rule LHSs.  We
	-- may as well do the same here.
570 571 572
  where
    subst	   = seSubst env
    old_black_list = seBlackList env
573
\end{code}
sof's avatar
sof committed
574 575


576 577 578 579 580
%************************************************************************
%*									*
\subsubsection{The ``enclosing cost-centre''}
%*									*
%************************************************************************
sof's avatar
sof committed
581

582 583 584
\begin{code}
getEnclosingCC :: SimplM CostCentreStack
getEnclosingCC env us sc = (seCC env, us, sc)
sof's avatar
sof committed
585

586 587 588
setEnclosingCC :: CostCentreStack -> SimplM a -> SimplM a
setEnclosingCC cc m env us sc = m (env { seCC = cc }) us sc
\end{code}
sof's avatar
sof committed
589

590

591 592 593 594 595
%************************************************************************
%*									*
\subsubsection{The @SimplEnv@ type}
%*									*
%************************************************************************
sof's avatar
sof committed
596 597


598
\begin{code}
599
emptySimplEnv :: SwitchChecker -> InScopeSet -> (Id -> Bool) -> SimplEnv
600

601
emptySimplEnv sw_chkr in_scope black_list
602
  = SimplEnv { seChkr = sw_chkr, seCC = subsumedCCS,
603 604
	       seBlackList = black_list,
	       seSubst = mkSubst in_scope emptySubstEnv }
605
	-- The top level "enclosing CC" is "SUBSUMED".
606

607 608 609 610 611 612 613 614
getEnv :: SimplM SimplEnv
getEnv env us sc = (env, us, sc)

setAllExceptInScope :: SimplEnv -> SimplM a -> SimplM a
setAllExceptInScope new_env@(SimplEnv {seSubst = new_subst}) m 
		    	    (SimplEnv {seSubst = old_subst}) us sc 
  = m (new_env {seSubst = Subst.setInScope new_subst (substInScope old_subst)}) us sc

615 616
getSubst :: SimplM Subst
getSubst env us sc = (seSubst env, us, sc)
617

618 619
getBlackList :: SimplM (Id -> Bool)
getBlackList env us sc = (seBlackList env, us, sc)
620

621 622
setSubst :: Subst -> SimplM a -> SimplM a
setSubst subst m env us sc = m (env {seSubst = subst}) us sc
623

624 625
getSubstEnv :: SimplM SubstEnv
getSubstEnv env us sc = (substEnv (seSubst env), us, sc)
626 627

extendInScope :: CoreBndr -> SimplM a -> SimplM a
628 629
extendInScope v m env@(SimplEnv {seSubst = subst}) us sc
  = m (env {seSubst = Subst.extendInScope subst v}) us sc
630 631

extendInScopes :: [CoreBndr] -> SimplM a -> SimplM a
632 633 634 635 636 637 638 639 640
extendInScopes vs m env@(SimplEnv {seSubst = subst}) us sc
  = m (env {seSubst = Subst.extendInScopes subst vs}) us sc

getInScope :: SimplM InScopeSet
getInScope env us sc = (substInScope (seSubst env), us, sc)

setInScope :: InScopeSet -> SimplM a -> SimplM a
setInScope in_scope m env@(SimplEnv {seSubst = subst}) us sc
  = m (env {seSubst = Subst.setInScope subst in_scope}) us sc
641

642 643 644
modifyInScope :: CoreBndr -> CoreBndr -> SimplM a -> SimplM a
modifyInScope v v' m env@(SimplEnv {seSubst = subst}) us sc 
  = m (env {seSubst = Subst.modifyInScope subst v v'}) us sc
645

646 647 648
extendSubst :: CoreBndr -> SubstResult -> SimplM a -> SimplM a
extendSubst var res m env@(SimplEnv {seSubst = subst}) us sc
  = m (env { seSubst = Subst.extendSubst subst var res  }) us sc
649

650 651 652
extendSubstList :: [CoreBndr] -> [SubstResult] -> SimplM a -> SimplM a
extendSubstList vars ress m env@(SimplEnv {seSubst = subst}) us sc
  = m (env { seSubst = Subst.extendSubstList subst vars ress  }) us sc
653

654 655 656
setSubstEnv :: SubstEnv -> SimplM a -> SimplM a
setSubstEnv senv m env@(SimplEnv {seSubst = subst}) us sc
  = m (env {seSubst = Subst.setSubstEnv subst senv}) us sc
657 658

zapSubstEnv :: SimplM a -> SimplM a
659 660
zapSubstEnv m env@(SimplEnv {seSubst = subst}) us sc
  = m (env {seSubst = Subst.zapSubstEnv subst}) us sc
661

662 663 664
getSimplBinderStuff :: SimplM (Subst, UniqSupply)
getSimplBinderStuff (SimplEnv {seSubst = subst}) us sc
  = ((subst, us), us, sc)
665

666 667 668
setSimplBinderStuff :: (Subst, UniqSupply) -> SimplM a -> SimplM a
setSimplBinderStuff (subst, us) m env _ sc
  = m (env {seSubst = subst}) us sc
669 670 671 672
\end{code}


\begin{code}
673
newId :: UserFS -> Type -> (Id -> SimplM a) -> SimplM a
674
	-- Extends the in-scope-env too
675
newId fs ty m env@(SimplEnv {seSubst = subst}) us sc
676
  =  case splitUniqSupply us of
677
	(us1, us2) -> m v (env {seSubst = Subst.extendInScope subst v}) us2 sc
678
		   where
679
		      v = mkSysLocal fs (uniqFromSupply us1) ty
680

681 682
newIds :: UserFS -> [Type] -> ([Id] -> SimplM a) -> SimplM a
newIds fs tys m env@(SimplEnv {seSubst = subst}) us sc
683
  =  case splitUniqSupply us of
684
	(us1, us2) -> m vs (env {seSubst = Subst.extendInScopes subst vs}) us2 sc
685
		   where
686
		      vs = zipWithEqual "newIds" (mkSysLocal fs) 
687
					(uniqsFromSupply (length tys) us1) tys
688
\end{code}